/*
	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:   IntroScreen
// Purpose:      Draws the star wars style introduction screen. Last minute bit of fun :)
//
//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################

#include "IntroScreen.h"

//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------

// The number of background stars:

const unsigned IntroScreen::NUM_STARS = 1024;

//------------------------------------------------------------------------------
// Static variable intialisation
//------------------------------------------------------------------------------

// Timer which times the frame rate

Timer * IntroScreen::frameTimer = 0;

// Continue running the intro screen ?

bool IntroScreen::continueRunning = true;

// Settings:

const char *    IntroScreen::titleText     = 0;        // title text
const char *    IntroScreen::mainText      = 0;        // main  text
float           IntroScreen::titleTextTime = 0;        // time the title is up for
float           IntroScreen::mainTextTime  = 0;        // time the main text is up for
float           IntroScreen::mainTextSpeed = 0;        // speed at which the main text scrolls

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

Name:     IntroScreen::exit()
Purpose:  Exits the intro screen
Params:   none
Returns:  none

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

void IntroScreen::exit(){ continueRunning = false; }

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

Name:     IntroScreen::run()
Purpose:  Runs the intro screen
Params:   As commented.
Returns:  none

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

void IntroScreen::run
(
    const char * titleText  ,   // The title text
    const char * mainText   ,   // The main text to show
    float titleTextTime     ,   // Time the title text is on the screen for
    float mainTextTime      ,   // Time the main text is on the screen for
    float mainTextSpeed         // Speed at which the main text scrolls
)
{
    //--------------------------------------------------------------------------
    // Validate all the settings
    //--------------------------------------------------------------------------

    if ( titleText == 0 ) return;
    if ( mainText  == 0 ) return;

    if ( titleTextTime <= 0 ) return;
    if ( mainTextTime  <= 0 ) return;
    if ( mainTextSpeed <  0 ) return;

    //--------------------------------------------------------------------------
    // Play the intro tune:
    //--------------------------------------------------------------------------

    MusicSystem::playFile("mus\\intro\\intro.mid");

    //--------------------------------------------------------------------------
    // Save all settings
    //--------------------------------------------------------------------------

    IntroScreen::titleText      = titleText;
    IntroScreen::mainText       = mainText;
    IntroScreen::titleTextTime  = titleTextTime;
    IntroScreen::mainTextTime   = mainTextTime;
    IntroScreen::mainTextSpeed  = mainTextSpeed;

    //--------------------------------------------------------------------------
    // Create the frame timer:
    //--------------------------------------------------------------------------

    frameTimer = new Timer();

    //--------------------------------------------------------------------------
    // Window state saving
    //--------------------------------------------------------------------------

    // Save the current window event listener:

    GLWindowEventListener * currentListener = GLWindow::getEventListener();

    // Create an intro screen event listener to catch keypresses and assign to the window

    IntroScreenEventListener listener;

    GLWindow::setEventListener(&listener);

    //--------------------------------------------------------------------------
    // Run the window: draw the title part of the intro screen
    //--------------------------------------------------------------------------

    // Set the screen to run initially

    continueRunning = true;

    // Set the time left in the first part of the intro screen

    float timeLeft = titleTextTime;

    // Now run the window

    while ( GLWindow::exists() && timeLeft > 0 && continueRunning )
    {
        // Process the window messages

        GLWindow::requestRepaint();
        GLWindow::run();

        // Draw the title text part of the intro screen

        drawTitleText(timeLeft);

        // Update the frame timer

        frameTimer->update();

        // Subtract the time the last frame took from the frame time

        timeLeft -= frameTimer->getSeconds();
    }

    //--------------------------------------------------------------------------
    // Run the window: draw the main text part of the intro screen
    //--------------------------------------------------------------------------

    // Set the time left in the second part of the intro screen

    timeLeft = mainTextTime;

    // Now run the window

    while ( GLWindow::exists() && timeLeft > 0 && continueRunning )
    {
        // Process the window messages

        GLWindow::requestRepaint();
        GLWindow::run();

        // Draw the main text part of the intro screen

        drawMainText(timeLeft);

        // Update the frame timer

        frameTimer->update();

        // Subtract the time the last frame took from the frame time

        timeLeft -= frameTimer->getSeconds();
    }

    //--------------------------------------------------------------------------
    // Fade out the screen: if the window still exists
    //--------------------------------------------------------------------------

    if ( GLWindow::exists() )
    {
        // Make sure all drawing is done:

        glFlush();

        // Swap the buffer

        GLWindow::swapBuffers();

        // Fade out the screen

        GLWindow::fadeScreen(1.0f);
    }

    //--------------------------------------------------------------------------
    // Cleanup
    //--------------------------------------------------------------------------

    // Restore the last window event listener

    GLWindow::setEventListener(currentListener);

    // Delete the frame timer

    delete frameTimer; frameTimer = 0;

    // Stop the intro tune:

    MusicSystem::stopMusic();
}

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

Name:     IntroScreen::drawTitleText()
Purpose:  Draws the title text part of the intro screen
Params:   Time left in the title text part
Returns:  none

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

void IntroScreen::drawTitleText( float timeLeft )
{
    //--------------------------------------------------------------------------
    // Switch into 2D
    //--------------------------------------------------------------------------

    GLWindow::glBeginDraw2d();

    //---------------------------------------------------------------------------
    // Draw the background part of the screen
    //---------------------------------------------------------------------------

    drawBackground();

    //--------------------------------------------------------------------------
    // Figure out the size of the text from the time left:
    //--------------------------------------------------------------------------

    float size;

    if ( timeLeft < titleTextTime / 2.0f )
    {
        size = 32;
    }
    else
    {
        size = ( 0.5f - ( ( timeLeft - titleTextTime * 0.5f ) / titleTextTime ) ) * 64.0f;
    }

    //--------------------------------------------------------------------------
    // Figure out what brightness to make the text from the time left:
    //--------------------------------------------------------------------------

    float brightness;

    if ( timeLeft >= titleTextTime / 2.0f )
    {
        brightness = 1.0f;
    }
    else
    {
        brightness  = timeLeft / titleTextTime;
        brightness *= 2.0f;
    }

    //--------------------------------------------------------------------------
    // Draw the title
    //--------------------------------------------------------------------------

    GLFont * font = GLFontManager::getFont_big();

    font->drawStringCentered
    (
        titleText,								// string to draw
        0.0f,									// box position: x
        0.0f,									// box position: y
        float( GLWindow::getClientWidth()	),  // box width
        float( GLWindow::getClientHeight()	),  // box height
        size,									// text size
        brightness,								// text color: r
        brightness,								// text color: g
        brightness								// text color: b
    );

    //--------------------------------------------------------------------------
    // Swap the back buffer onto the front buffer:
    //--------------------------------------------------------------------------

    GLWindow::swapBuffers();
}

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

Name:     IntroScreen::drawMainText()
Purpose:  Draws the main text part of the intro screen
Params:   Time left in the main text part
Returns:  none

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

void IntroScreen::drawMainText( float timeLeft )
{
    //--------------------------------------------------------------------------
    // Switch into 2D
    //--------------------------------------------------------------------------

    GLWindow::glBeginDraw2d();

    //--------------------------------------------------------------------------
    // Draw the background part of the screen
    //--------------------------------------------------------------------------

    drawBackground();

    //--------------------------------------------------------------------------
    // Switch into 3D mode for drawing the text:
    //--------------------------------------------------------------------------

    GLWindow::glBeginDraw3d(90,1,1000);

    //--------------------------------------------------------------------------
    // Turn the view around to face the text
    //--------------------------------------------------------------------------

    glRotatef( 180 , 0 , 1 , 0 );
    glRotatef( 180 , 0 , 0 , 1 );
    glRotatef( -20 , 1 , 0 , 0 );

    //--------------------------------------------------------------------------
    // Translate the text into its 3D position:
    //--------------------------------------------------------------------------

    glTranslatef
    (
        float( - GLWindow::getClientWidth()		) / 2.0f ,
        float( + GLWindow::getClientHeight()	) / 4.0f ,
        float( + GLWindow::getClientHeight()	) / 2.0f
    );

    // Translate the text along the screen as time passes:

    glTranslatef
    (
        0,
        - ( mainTextTime - timeLeft ) * mainTextSpeed,
        0
    );

    //--------------------------------------------------------------------------
    // Draw the scrolling text
    //--------------------------------------------------------------------------

    drawText();

    //--------------------------------------------------------------------------
    // Swap the back buffer onto the front buffer:
    //--------------------------------------------------------------------------

    GLWindow::swapBuffers();
}

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

Name:     IntroScreen::drawBackground()
Purpose:  Draws the background part of the intro screen
Params:   none
Returns:  none

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

void IntroScreen::drawBackground()
{
    // Clear the screen to black:

    GLWindow::clearScreen(0,0,0);

    // Seed the random number generator:

    mlRandomSeed(24242);

    // Save the current transformation matrices and opengl state

    glMatrixMode( GL_MODELVIEW  ); glPushMatrix();
    glMatrixMode( GL_PROJECTION ); glPushMatrix();

    glPushAttrib( GL_ENABLE_BIT );

    // Draw a load of points:

    glDisable( GL_TEXTURE_2D );
    glDisable( GL_LIGHTING   );
    glDisable( GL_CULL_FACE  );
    glDisable( GL_BLEND      );

    // Go into 2D mode

    GLWindow::glBeginDraw2d();

    // Draw the stars:

    glBegin( GL_POINTS );

    for ( unsigned i = NUM_STARS ; i ; i-- )
    {
        // Decide on the star position:

        float pos_x = mlRandomFloat() * GLWindow::getClientWidth();
        float pos_y = mlRandomFloat() * GLWindow::getClientHeight();

        // Decide on star brightness

        float brightness = mlRandomFloat();

        // Draw the point

        glColor3f
        (
            brightness,
            brightness,
            brightness
        );

        glVertex2f(pos_x,pos_y);
    }

    glEnd();

    // Restore the previous opengl state

    glPopAttrib(); glPopMatrix(); glMatrixMode( GL_MODELVIEW ); glPopMatrix();
}

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

Name:     IntroScreen::drawText()
Purpose:  Draws the text part of the intro screen
Params:   none
Returns:  none

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

void IntroScreen::drawText()
{
    //--------------------------------------------------------------------------
    // Pointer to the start of the current line of text
    //--------------------------------------------------------------------------

    const char * linePointer = mainText;

    //--------------------------------------------------------------------------
    // Get the big font
    //--------------------------------------------------------------------------

    GLFont * font = GLFontManager::getFont_big();

    //--------------------------------------------------------------------------
    // Draw each line
    //--------------------------------------------------------------------------

    unsigned lineNum = 0;

    while ( * linePointer )
    {
        // Figure out how characters there are until the end of the line:

        const char * t = linePointer; unsigned numChars = 0;

        while ( ( * t != 0 ) && ( * t != '\n' ) )
        {
            numChars++; t++;
        }

        // Make a copy of this line of text

        char * lineText = new char[ numChars + 1 ];

        for ( unsigned i = 0 ; i < numChars; i++ )
        {
            lineText[i] = linePointer[i];
        }

        // Null terminate the copy of the line

        lineText[ numChars ] = 0;

        // Draw this line of text:

        font->drawStringCentered
        (
            lineText							,
            0.0f								,
            float(lineNum) * 24.0f				,
            float(GLWindow::getClientWidth())	,
            24.0f	,
            16.0f	,
            1.0f	,
            1.0f	,
            0.0f
        );

        // Move onto the next line of text

        linePointer += numChars;

        // If still stuck on a carriage return then move on:

        if ( * linePointer == '\n' ) linePointer++;

        // Increment the number of lines that have been drawn]

        lineNum++;

        // Delete the line text

        delete lineText;

    }   // end while ( * line )
}


