/*
	Rogue Trader.
	Copyright (c) 2007, Darragh Coy.
	All rights reserved.
	Original work(s), source code & author(s) details available at: http://www.darraghcoy.com

	Redistribution and use in source and binary forms, with or without modification, are permitted 
	provided that the following conditions are met:

		* 	Redistributions of source code must retain the above copyright notice, this list of 
			conditions and the following disclaimer.
		* 	Redistributions in binary form must reproduce the above copyright notice, this list of 
			conditions and the following disclaimer in the documentation.
		* 	Neither the name of the author nor the names of contributors may be used to endorse or 
			promote products derived from this software without specific prior written permission.
		* 	The use of any third party libraries, modules or data files provided with the source 
			form of the program must follow and respect the individual licensing terms of these 
			components. You do not have permission to modify or circumvent the licensing terms for 
			provided third party components unless the third party licenses specifically allow this. 
			If you do not agree to the terms of provided third party components then you do not have 
			permission to use them in your derived work(s).
		* 	The terms of this license do not apply to separate (but related) distributions if supplied 
			by the author(s), only to the contents of this source distribution, derived works, and the 
			binaries produced by either modified or unmodified versions of the source code. The terms 
			of this license do not also apply to any third party libraries or components provided with 
			the source distribution. Such third party elements are licensed under their own separate 
			agreements.

	THIS SOFTWARE IS PROVIDED BY DARRAGH COY ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
	ARE DISCLAIMED. IN NO EVENT SHALL DARRAGH COY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
	OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
	OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
	IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################
//
//
// Class Name:   GuiMeshViewer
// Purpose:      Widget which can display a view of a 3d mesh to the screen.
//
//
//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################

#include "GuiMeshViewer.h"
#include "Game.h"

//------------------------------------------------------------------------------
// Constant initialisation
//------------------------------------------------------------------------------

// Speed of model rotation: radians per second

const float GuiMeshViewer::ROTATE_SPEED = 1.0;

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     GuiMeshViewer::GuiMeshViewer()
Purpose:  Constructor. Initialises the widget.
Params:   none.
Returns:  n/a

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

GuiMeshViewer::GuiMeshViewer()
{
    // Set the mesh shown by the widget to null:

    modelMesh = 0;

    // Set the yaw, pitch and zoom for the model view to the defaults:

    modelYaw   = 0;
    modelPitch = 0;
    modelZoom  = 1;

    // Automatically rotate the model as default:

    autoRotateYaw   = true;
    autoRotatePitch = true;
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     GuiMeshViewer::windowRedrawing()
Purpose:  Draw event for the mesh viewer. Draws the mesh if it is there.
Params:   none
Returns:  none

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

void GuiMeshViewer::windowRedrawing()
{
    // Abort if there is no mesh:

    if ( modelMesh == 0 ) return;
    
    //--------------------------------------------------------------------------
	// Get the dimensions of the mesh viewer, scaled by the GUI scaling factor
	//--------------------------------------------------------------------------
	
	float guiScalingFactor = Game::getGuiScaleFactor();
	float scaledSizeX = (float) this->size_x * guiScalingFactor;
	float scaledSizeY = (float) this->size_y * guiScalingFactor;

    //--------------------------------------------------------------------------
    // Autorotate the model if enabled:
    //--------------------------------------------------------------------------

    // Update the framerate timer:

    frameTimer.update();

    if ( autoRotateYaw )
    {
        // Rotate the model:

        modelYaw   += frameTimer.getSeconds() * ROTATE_SPEED;

        // Clamp angle to 0-2PI Range:

        fmod( modelYaw   , PI2 );
    }

    if ( autoRotatePitch )
    {
        // Rotate the model:

        modelPitch += frameTimer.getSeconds() * ROTATE_SPEED;

        // Clamp angle to 0-2PI Range:

        fmod( modelPitch , PI2 );
    }

    //--------------------------------------------------------------------------
    // Get the curent modelview and projection matrices from opengl:
    //--------------------------------------------------------------------------

    float mMatrix[16]; glGetFloatv( GL_MODELVIEW_MATRIX     , mMatrix );
    float pMatrix[16]; glGetFloatv( GL_PROJECTION_MATRIX    , pMatrix );

    //--------------------------------------------------------------------------
    // Transform the position of the mesh viewer to see where it actually lies
    // in screen coordinates. The position of the widget on the screen might not
    // neccessarily be the same as its x and y coordinates given because it can
    // be affected by parent widget transforms - such as those with panels.
    //--------------------------------------------------------------------------

    float screenPos[4] =
    {
        (float) this->position_x,		// Note: these have already been scaled by UI scaling. Hence not using scaled coords.
        (float) this->position_y,		// Note: these have already been scaled by UI scaling. Hence not using scaled coords.
        0.0f,
        1.0f
    };

    mlTransform4d( screenPos , mMatrix );   // transform by modelview matrix
    mlTransform4d( screenPos , pMatrix );   // transform by projection matrix

    // Do perspective divide by the w coordinate:

    screenPos[0] /= screenPos[3];
    screenPos[1] /= screenPos[3];

    // Now in normalised device coordinates, un-normalise to get an actual screen coordinate:

    screenPos[0] +=  1.0f;											// bring x coordinate in 0 - 2 range
    screenPos[1] +=  1.0f;											// bring y coordinate in 0 - 2 range
    screenPos[0] *=  float( GLWindow::getClientWidth()	) * 0.5f;	// scale coordinates to screen size
    screenPos[1] *=  float( GLWindow::getClientHeight() ) * 0.5f;	// scale coordinates to screen size

    //--------------------------------------------------------------------------
    // Save the current opengl state:
    //--------------------------------------------------------------------------

    // Save the modelview matrix:

    glMatrixMode( GL_MODELVIEW ); glPushMatrix();

    // Save the projection matrix:

    glMatrixMode( GL_PROJECTION );

    glPushMatrix();

    glMatrixMode( GL_MODELVIEW );

    // Save all enables:

    glPushAttrib( GL_ENABLE_BIT );

    //--------------------------------------------------------------------------
    // Setup opengl state for drawing the model:
    //--------------------------------------------------------------------------

    // Enables

    glEnable( GL_TEXTURE_2D );
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_CULL_FACE  );
    glEnable( GL_LIGHTING   );

    // Culling setup

    glCullFace( GL_BACK );

    // Depth testing setup

    glDepthFunc( GL_LEQUAL );
    glClear( GL_DEPTH_BUFFER_BIT );
    glDepthMask( GL_TRUE );

    // Disables

    glDisable( GL_BLEND         );
    glDisable( GL_ALPHA_TEST    );
    glDisable( GL_STENCIL_TEST  );
    glDisable( GL_CLIP_PLANE0   );
    glDisable( GL_CLIP_PLANE1   );
    glDisable( GL_CLIP_PLANE2   );
    glDisable( GL_CLIP_PLANE3   );
    glDisable( GL_CLIP_PLANE4   );
    glDisable( GL_CLIP_PLANE5   );

    // Setup the view port:

    glViewport
    (
        int(screenPos[0]),						// x coordinate of viewport
        int(screenPos[1]) - (int) scaledSizeY,	// y coordinate of viewport
        (int) scaledSizeX,						// width of viewport
        (int) scaledSizeY						// height of viewport
    );

    // Calculate the aspect ratio:

    float aspect = scaledSizeX / scaledSizeY;

    // Use the glu helper function to the set the perspective mode

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    gluPerspective
    (
        90.0,       // feeling of view angle
        aspect,     // aspect ratio
        0.001,      // near plane distance
        10000.0     // far plane distance
    );

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // Enable vertex, normal and texture coordinate arrays but disable color arrays

    glDisableClientState( GL_COLOR_ARRAY  );
    glEnableClientState ( GL_VERTEX_ARRAY );
    glEnableClientState ( GL_NORMAL_ARRAY );
    glEnableClientState ( GL_TEXTURE_COORD_ARRAY );

    //--------------------------------------------------------------------------
    // Setup transforms for viewing the model: part 1
    //--------------------------------------------------------------------------

    // Setup a default identity matrix for the ships orientation

    float orientation[9] =
    {
        1 , 0 , 0,
        0 , 1 , 0,
        0 , 0 , 1
    };

    // Set the color to white:

    glColor4f(1,1,1,1);

    // Figure out the distance to place the camera from the model based on the zoom and bounding sphere radius

    float distance = ( modelMesh->getSphereRadius() * 1.0f ) * modelZoom;

    // Translate by the view distance

    glTranslatef(0,0, -distance - 1);

    //--------------------------------------------------------------------------
    // Setup transforms for viewing the model
    //--------------------------------------------------------------------------

    // Get the maximum number of lights:

    unsigned maxLights = 0;

    glGetIntegerv( GL_MAX_LIGHTS , (GLint*)(&maxLights) );

    // Disable all lights except the first one:

    glEnable(GL_LIGHT0);

    for ( unsigned i = 1 ; i < maxLights ; i++ )
    {
        glDisable(GL_LIGHT0 + i );
    }

    // The color vectors for black and white

    float black[4] = { 0 , 0 , 0 , 1 };
    float white[4] = { 1 , 1 , 1 , 1 };

    // Setup the material properties

    glMaterialfv( GL_FRONT_AND_BACK , GL_AMBIENT    , white     );
    glMaterialfv( GL_FRONT_AND_BACK , GL_DIFFUSE    , white     );
    glMaterialfv( GL_FRONT_AND_BACK , GL_EMISSION   , black     );
    glMaterialfv( GL_FRONT_AND_BACK , GL_SPECULAR   , black     );
    glMaterialf ( GL_FRONT_AND_BACK , GL_SHININESS  , 0         );

    // Set the ambient light color

    float ambientColor[4] = { 0.2f , 0.2f , 0.2f , 1.0f };

    glLightModelfv( GL_LIGHT_MODEL_AMBIENT , ambientColor );

    // Enable two sided lighting

    glLightModeli( GL_LIGHT_MODEL_TWO_SIDE , GL_TRUE );

    // Setup the light itself

        // Light position: directional light

        float lightPos[4] = { 0 , 0 , 1 , 0 };

    glLightfv( GL_LIGHT0 , GL_POSITION , lightPos       );      // set light position
    glLightfv( GL_LIGHT0 , GL_DIFFUSE  , white          );      // set light diffuse  color
    glLightfv( GL_LIGHT0 , GL_SPECULAR , white          );      // set light specular color
    glLightfv( GL_LIGHT0 , GL_EMISSION , white          );      // set light emission color
    glLightfv( GL_LIGHT0 , GL_AMBIENT  , black          );      // set light ambient color: no ambient
    glLightf ( GL_LIGHT0 , GL_SPOT_CUTOFF , 180         );      // no spot lighting. full 180 degree apex on light cone.
    glLightf ( GL_LIGHT0 , GL_CONSTANT_ATTENUATION  , 1 );      // constant attentuation factor
    glLightf ( GL_LIGHT0 , GL_QUADRATIC_ATTENUATION , 0 );      // quadratic attentuation factor: no quadratic attenuation
    glLightf ( GL_LIGHT0 , GL_LINEAR_ATTENUATION    , 0 );      // Linear attentuation

    //--------------------------------------------------------------------------
    // Setup transforms for viewing the model: part 2
    //--------------------------------------------------------------------------

    // Rotate by model pitch and yaw:

    glRotatef( modelPitch * TO_DEGREES , 1 , 0 , 0 );
    glRotatef( modelYaw   * TO_DEGREES , 0 , 1 , 0 );

    //--------------------------------------------------------------------------
    // Actually draw the model:
    //--------------------------------------------------------------------------

    // Draw the mesh in the default position and orientation

    modelMesh->draw(0,0,0,orientation);

    //--------------------------------------------------------------------------
    // Restore the opengl state
    //--------------------------------------------------------------------------

    // Restore the projection matrix:

    glMatrixMode( GL_PROJECTION ); glPopMatrix();

    // Restore the modelview matrix:

    glMatrixMode( GL_MODELVIEW ); glPopMatrix();

    // Disable backface culling

    glDisable(GL_CULL_FACE);

    // Restore all enables:

    glPopAttrib();

    // Restore the viewport to window size:

    glViewport( 0 , 0 , GLWindow::getClientWidth() , GLWindow::getClientHeight() );
}
