{-
   SceneFlat.hs (adapted from sceneflat.c which is (c) Mark J. Kilgard)
   This file is part of HOpenGL - a binding of OpenGL and GLUT for Haskell.
   Copyright (C) 2000  Sven Panne <Sven.Panne@informatik.uni-muenchen.de>

   This program draws lighted objects with flat shading.
-}

import System.Exit ( exitWith, ExitCode(ExitSuccess) )

import GL
import Graphics.UI.GLUT

-- Initialize material property and light source.
myInit :: IO ()
myInit = do
   mapM_ (light (Light 0)) [
      LightColor Ambient  (Color4 0.0 0.0 0.0 1.0),
      LightColor Diffuse  (Color4 1.0 1.0 1.0 1.0),
      LightColor Specular (Color4 1.0 1.0 1.0 1.0),
      Position (Vertex4 1.0 1.0 1.0 0.0) ]

   enable Lighting
   enable (Light 0)
   depthFunc GL.Less
   enable DepthTest
   shadeModel Flat

display :: DisplayCallback
display = do
   clear [ ColorBufferBit, DepthBufferBit ]
   pushMatrix
   rotate (20 :: GLfloat) (Vector3 1 0 0)

   pushMatrix
   translate (Vector3 (-0.75) 0.5 (0.0 :: GLfloat))
   rotate (90 :: GLfloat) (Vector3 1 0 0)
   renderObject Solid (Torus 0.275 0.85 15 15)
   popMatrix

   pushMatrix
   translate (Vector3 (-0.75) (-0.5) (0.0 :: GLfloat))
   rotate (270 :: GLfloat) (Vector3 1 0 0)
   renderObject Solid (Cone 1.0 2.0 15 15)
   popMatrix

   pushMatrix
   translate (Vector3 0.75 0.0 (-1.0 :: GLfloat))
   renderObject Solid (Sphere 1.0 15 15)
   popMatrix

   popMatrix
   flush

myReshape :: ReshapeCallback
myReshape (WindowSize w h) = do
   viewport (0, 0) (fromIntegral w, fromIntegral h)
   matrixMode Projection
   loadIdentity
   let wf = fromIntegral w
       hf = fromIntegral h
   if (w <= h)
      then ortho (-2.5) 2.5 (-2.5*hf/wf) (2.5*hf/wf) (-10.0) 10.0
      else ortho (-2.5*wf/hf) (2.5*wf/hf) (-2.5) 2.5 (-10.0) 10.0
   matrixMode Modelview

key :: KeyboardMouseCallback
key (Char '\27') Down _ _ = exitWith ExitSuccess
key _            _    _ _ = return ()

-- Main Loop
-- Open window with initial window size, title bar,
-- RGBA display mode, and handle input events.
main :: IO ()
main = do
   (progName, _args) <- getArgsAndInitialize
   setInitialDisplayMode [ Single, RGB, Graphics.UI.GLUT.Depth ]
   setInitialWindowSize (WindowSize 500 500)
   createWindow progName
   myInit
   setReshapeCallback (Just myReshape)
   setDisplayCallback display
   setKeyboardMouseCallback (Just key)
   mainLoop
