{-
   TeaAmbient.hs (adapted from teaambient.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 renders three lighted, shaded teapots, with
   different ambient values.
-}

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 0.0 0.0 0.0) ]

   lightModel (LightModelAmbient (Color4 0.75 0.75 0.75 1.0))

   frontFace Cw
   enable Lighting
   enable (Light 0)
   enable AutoNormal
   enable Normalize
   depthFunc GL.Less
   enable DepthTest

display :: DisplayCallback
display = do
   clear [ ColorBufferBit, DepthBufferBit ]

   -- material has small ambient reflection
   material Front (MaterialColor Ambient (Color4 0.1 0.1 0.1 1.0))
   material Front (Shininess 40.0)
   pushMatrix
   translate (Vector3 0.0 2.0 (0.0 :: GLfloat))
   renderObject Solid (Teapot 1.0)
   popMatrix

   -- material has moderate ambient reflection
   material Front (MaterialColor Ambient (Color4 0.4 0.4 0.4 1.0))
   pushMatrix
   translate (Vector3 0.0 0.0 (0.0 :: GLfloat))
   renderObject Solid (Teapot 1.0)
   popMatrix

   -- material has large ambient reflection
   material Front (MaterialColor Ambient (Color4 1.0 1.0 1.0 1.0))
   pushMatrix
   translate (Vector3 0.0 (-2.0) (0.0 :: GLfloat))
   renderObject Solid (Teapot 1.0)
   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 (-4.0) 4.0 (-4.0*hf/wf) (4.0*hf/wf) (-10.0) 10.0
      else ortho (-4.0*wf/hf) (4.0*wf/hf) (-4.0) 4.0 (-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
