// ================================================================
 // Filename: Lighting.cpp
 // Description: Demonstrating use of Lighting and materials
 //
 //              This source corresponds to 32Bits.co.uk DirectX
 //              Basics Series 3 part 5.
 // ================================================================


 #define WIN32_LEAN_AND_MEAN
 #include <windows.h>
 #include <d3d8.h>
 #include <d3dx8.h>
 #include <dxerr8.h>
 #include <mmsystem.h>

 #include "D3DFuncs.h"
 #include "D3DCube.h"

 // Function declarations
 int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow);
 LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam );

 HRESULT GameInit();
 HRESULT GameLoop();
 HRESULT GameShutDown();
 HRESULT Render();


 // Globals
 static char strAppname[]="32Bits Tutorial - Lighting";
 LPDIRECT3D8 g_pD3D;
 LPDIRECT3DDEVICE8 g_pDevice;
 LPDIRECT3DSURFACE8 g_pBackSurface;
 HWND g_hWnd;

 D3DCURRENTSETTINGS g_D3DSettings;

 // Globals specifically for this source
 CD3DCube    g_Cube;

 //-----------------------------------------------------------------------------
 // Name: WinMain()
 // Desc: The application's entry point
 //-----------------------------------------------------------------------------

 int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
 {
     WNDCLASSEX wc;

     ZeroMemory(&wc, sizeof(WNDCLASSEX));
     wc.cbSize=sizeof(WNDCLASSEX);                       // size of the window struct in bytes
     wc.style=CS_HREDRAW | CS_VREDRAW | CS_OWNDC;        // window styles to use
     wc.lpfnWndProc=MsgProc;                             // function name of event handler
     wc.hInstance=hInstance;                             // handle to this apps instance
     wc.hbrBackground=(HBRUSH)GetStockObject(GRAY_BRUSH);// background colour of window
     wc.hIcon= LoadIcon(NULL, IDI_APPLICATION);          // icon for the app window
     wc.hIconSm=LoadIcon(NULL, IDI_APPLICATION);         // icon when minimized to taskbar
     wc.hCursor=LoadCursor(NULL, IDC_ARROW);             // cursor to use for this window
     wc.lpszClassName=strAppname;                        // name for this class

     // Register the window class
     RegisterClassEx( &wc );

     g_D3DSettings.m_nDeviceWidth=800;
     g_D3DSettings.m_nDeviceHeight=600;
     g_D3DSettings.m_fScreenAspect=(float)g_D3DSettings.m_nDeviceWidth / (float)g_D3DSettings.m_nDeviceHeight;

     // Create the application's window
     g_hWnd = CreateWindow(strAppname, strAppname, WS_OVERLAPPEDWINDOW, 10, 10,
                           g_D3DSettings.m_nDeviceWidth, g_D3DSettings.m_nDeviceHeight,
                           NULL, NULL, wc.hInstance, NULL );

     // Show the window
     ShowWindow(g_hWnd, nCmdShow);
     UpdateWindow(g_hWnd);

     if(FAILED(GameInit()))
     {
         UnregisterClass( strAppname, wc.hInstance );
         return -1;
     }

     // Enter the message loop
     MSG msg;
     ZeroMemory( &msg, sizeof(msg) );
     int count=0;
     while( msg.message!=WM_QUIT )
     {
         if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
         {
             TranslateMessage( &msg );
             DispatchMessage( &msg );
         }
         else
         {
             GameLoop();
         }
     }

     GameShutDown();
     UnregisterClass( strAppname, wc.hInstance );
     return 0;
 }


 //-----------------------------------------------------------------------------
 // Name: MsgProc()
 // Desc: The window's message handler
 //-----------------------------------------------------------------------------
 LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
 {
     switch( msg )
     {
     case WM_KEYDOWN:
         {
             switch(wParam)
             {

             case VK_SPACE:
                 {
                     PostQuitMessage( 0 );
                     return 0;
                 }
             }
         }

     case WM_DESTROY:
         {
             PostQuitMessage( 0 );
             return 0;
         }

     default:
         return DefWindowProc( hWnd, msg, wParam, lParam );
     }

 }


 // =====================================================================================
 //  High level functions for initialization, loop and shutdown
 // =====================================================================================

 HRESULT GameInit()
 {
     HRESULT rslt=0;

     g_pD3D=Direct3DCreate8(D3D_SDK_VERSION);
     if(g_pD3D==NULL)
     {
         return D3DError(E_FAIL, __LINE__, __FILE__, "Failed to create a D3D8 object.");
     }


     // Populate our struct with how we want to set up D3D...
     g_D3DSettings.m_bWindowed=TRUE;
     g_D3DSettings.m_bMultiSampling=FALSE;
     g_D3DSettings.m_D3DFormat=D3DFMT_X8R8G8B8;

     // ...and pass it to our function to create the device!
     rslt=InitDirect3DDevice(g_hWnd, g_D3DSettings, g_pD3D, &g_pDevice);
     if(FAILED(rslt))
     {
         return E_FAIL;
     }



     // ===================================================================================
     // Set up our Projection, View and World transformations
     // ===================================================================================

     // Create a matrix to store our Projection transform. Null all the fields.
     D3DXMATRIX matProjection;
     ZeroMemory(&matProjection, sizeof(matProjection));

     // Use D3DX to create a left handed cartesian Field Of View transform
     D3DXMatrixPerspectiveFovLH(&matProjection, D3DX_PI/4, g_D3DSettings.m_fScreenAspect,
                                1.0f, 100.0f);

     // Tell D3D to use our Projection matrix for the projection transformation stage
     rslt=g_pDevice->SetTransform(D3DTS_PROJECTION, &matProjection);
     if(FAILED(rslt)) { return D3DError(rslt, __LINE__, __FILE__, "Failed to set Projection Transform."); }



     // Create a matrix to store our View transform. Null all the fields.
     D3DXMATRIX matView;
     ZeroMemory(&matView, sizeof(matView));

     // Use D3DX to create a Look At matrix from eye, lookat and up vectors.
     D3DXMatrixLookAtLH(&matView, &D3DXVECTOR3(0.0f, 0.0f, -6.0f),
                                  &D3DXVECTOR3(0.0f, 0.0f,  0.0f),
                                  &D3DXVECTOR3(0.0f, 1.0f,  0.0f));

     // Tell D3D to use our View matrix for the view transformation stage
     rslt=g_pDevice->SetTransform(D3DTS_VIEW, &matView);
     if(FAILED(rslt)) { return D3DError(rslt, __LINE__, __FILE__, "Failed to set View Transform."); }




     // Create a matrix to store our World transform
     D3DXMATRIX matWorld;
     // Set the matrix to an identity matrix (one that makes no change)
     D3DXMatrixIdentity(&matWorld);

     // Tell D3D to use our World matrix for the world transformation stage
     rslt=g_pDevice->SetTransform(D3DTS_WORLD, &matWorld);
     if(FAILED(rslt)) { return D3DError(rslt, __LINE__, __FILE__, "Failed to set World Transform."); }



     // ===================================================================================
     // Set up our scene states
     // ===================================================================================

     // Set our culling & lighting renderstates
     g_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
     g_pDevice->SetRenderState(D3DRS_LIGHTING, TRUE);


     // Set up the level of ambient light in the scene
     g_pDevice->SetRenderState( D3DRS_AMBIENT, D3DCOLOR_XRGB(100,100,100));

     // Uncomment this for specular highlights
     // g_pDevice->SetRenderState( D3DRS_SPECULARENABLE, TRUE);


     // Set up our light
     D3DLIGHT8 Light;
     ZeroMemory(&Light, sizeof(D3DLIGHT8));

     // Create a white, single direction light
     Light.Type=D3DLIGHT_DIRECTIONAL;
     Light.Diffuse.r=1.0f;
     Light.Diffuse.g=1.0f;
     Light.Diffuse.b=1.0f;
     Light.Position=D3DXVECTOR3(  3.0f, 2.0f, -3.0f);
     Light.Direction=D3DXVECTOR3(-0.5f,-1.0f,  1.0f);

 /*
     // Uncomment this for specular highlights
     Light.Specular.r = 1.0f;
     Light.Specular.g = 1.0f;
     Light.Specular.b = 1.0f;
     Light.Specular.a = 1.0f;
 */


     // Tell D3D to copy our light properties into the T&L pipeline...
     rslt=g_pDevice->SetLight(0, &Light);
     if(FAILED(rslt)) { return D3DError(rslt, __LINE__, __FILE__, "Could not set light."); }

     // ...and enable the light
     rslt=g_pDevice->LightEnable(0, TRUE);
     if(FAILED(rslt)) { return D3DError(rslt, __LINE__, __FILE__, "Could not enable light."); }


     // Now set up our material

     D3DMATERIAL8 Material;
     ZeroMemory(&Material, sizeof(D3DMATERIAL8));

     // The ambient and diffuse colours for the material directly set the apparent colour of
     // any primitives rendered with this material. They specify what colours this material reflects
     // when light falls on them. For example, a blue light (0.0, 0.0, 1.0) shining on a material with
     // diffuse (0.0, 0.0, 1.0) will make the primitives appear blue, because a blue material will
     // reflect a blue light. However a red light (1.0, 0.0, 0.0) shining on the same material will
     // make the primitive appear black, because there are no blue components in a red light, therefore
     // nothing to reflect.
     // It is normal for your material diffuse and ambient colours to be the same

     // Set the RGBA for diffuse reflection. This colour affects the colour of any faces that DO have
     // light fall on them
     Material.Diffuse.r = 0.0f;
     Material.Diffuse.g = 0.5f;
     Material.Diffuse.b = 1.0f;
     Material.Diffuse.a = 1.0f;

     // Set the RGBA for Ambient reflection. This colour affects the colour of any faces that do NOT
     // have any light fall on them.
     Material.Ambient.r = 0.0f;
     Material.Ambient.g = 0.5f;
     Material.Ambient.b = 1.0f;
     Material.Ambient.a = 1.0f;


 /*
     // Uncomment this for specular highlights
     Material.Specular.r = 1.0f;
     Material.Specular.g = 1.0f;
     Material.Specular.b = 1.0f;
     Material.Specular.a = 1.0f;

     Material.Power=100.0f;
 */


     // Tell D3D to use our material
     rslt=g_pDevice->SetMaterial(&Material);
     if(FAILED(rslt)) { return D3DError(rslt, __LINE__, __FILE__, "Could not set material."); }


     // Initialise our cube
     g_Cube.Initialise(2.0f, 2.0f, 2.0f, -1.0f, -1.0f, -1.0f, g_pDevice);
     g_Cube.SetTexture("roof.bmp", g_pDevice);

     return S_OK;
 }

 HRESULT GameLoop()
 {
     return Render();
 }

 HRESULT GameShutDown()
 {

     if(g_pBackSurface)
         g_pBackSurface->Release();
     if(g_pDevice)
         g_pDevice->Release();
     if(g_pD3D)
         g_pD3D->Release();
     return S_OK;
 }



 // =====================================================================================
 // Main render function to perform D3D drawing
 // =====================================================================================

 HRESULT Render()
 {
     HRESULT rslt=NULL;


     // ====================================================================================
     // - Do all the usual checks to make sure we have the right pointers, etc...
     // ====================================================================================

     // Make sure we have a valid D3D Device
     if(!g_pDevice) { return E_FAIL; }

     // Return if the device is not ready
     rslt=ValidateDevice(g_pDevice, g_pBackSurface, g_D3DSettings);
     if(FAILED(rslt)) { return rslt; }

     // Clear the back buffer
     g_pDevice->Clear(0,0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,55), 1.0f, 0);

     // Get a pointer to the back buffer (remember, page flipping has taken place)
     rslt=g_pDevice->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &g_pBackSurface);
     if(FAILED(rslt)) { return D3DError(rslt, __LINE__, __FILE__, "Failed to get the back buffer."); }



     rslt=g_pDevice->BeginScene();
     if(FAILED(rslt)) { return D3DError(rslt, __LINE__, __FILE__, "BeginScene() failed."); }

     // ====================================================================================
     // - Do our drawing operations
     // ====================================================================================

     // Create a matrix to rotate the cube nicely.
     D3DXMATRIX matWorld;
     // timeGetTime() requires #include <mmsystem.h>, and winmm.lib to be linked
     D3DXMatrixRotationYawPitchRoll(&matWorld, timeGetTime()/1700.0f, timeGetTime()/1500.0f,
                                    timeGetTime()/1600.0f);

     g_pDevice->SetTransform(D3DTS_WORLD, &matWorld);

     g_Cube.Render(g_pDevice, g_pBackSurface);

     // ====================================================================================
     // - Clean up and present the back buffer to be page flipped
     // ====================================================================================

     g_pDevice->EndScene();
     g_pBackSurface->Release();

     // Present the back buffer to the display adapter to be drawn
     g_pDevice->Present(NULL, NULL, NULL, NULL);


     return S_OK;
 }