/*
	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:   Galaxy
// Purpose:      Class that describes a galaxy full of stars. The galaxy is more
//               or less infinite (well as far as the player is concerned) and
//               generated using predictably random numbers. The galaxy also
//               maintains a stack of recently visited systems and simulates
//               econonmy between those systems.
//
//
//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################

#include "Galaxy.h"

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

const int Galaxy::SECTOR_SIZE = 64;     // size of each sector in the galaxy. only one system may occupy a sector

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

Name:     Galaxy::Galaxy
Purpose:  Galaxy constructor. Saves the random seed for the galaxy.
Params:   random seed for the galaxy
Returns:  n/a

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

Galaxy::Galaxy( unsigned seed )
{
    // Save the random seed:

    this->seed = seed;

    // Initialise all the systems in the star system memory to the default null systems

    for ( unsigned i = 0 ; i < SYSTEM_MEMORY_SIZE ; i++ )
    {
        systemMemory[i] = StarSystem();
    }
}

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

Name:     Galaxy::rememberSystem
Purpose:  Adds the given star system to the memory of recently visited systems
Params:   System to add to the memory
Returns:  none

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

void Galaxy::rememberSystem( StarSystem system )
{
    //--------------------------------------------------------------------------
    // First see if the system is already in the galaxys memory:
    //--------------------------------------------------------------------------

    // Save the index of the system in the memory array here:

    int index = -1;

    // Search for the system in the system memory array

    for ( unsigned i = 0 ; i < SYSTEM_MEMORY_SIZE; i++ )
    {
        // See if this current system matches the system for insertion:

        if ( system == systemMemory[i] )
        {
            // Found the system being inserted already in memory: save index

            index = i;

            // Abort search

            break;
        }
    }

    //--------------------------------------------------------------------------
    // Now insert the new system into memory: move the other systems in the
    // array differently depending on whether this system is already in memory.
    //--------------------------------------------------------------------------

    // See if the system was found in memory:

    if ( index > -1 )
    {
        //----------------------------------------------------------------------
        // System already in memory: shift all systems higher up than it in the
        // array down one place:
        //----------------------------------------------------------------------

        for ( int i = index ; i > 0 ; i-- )
        {
            // Swap the next system up from this index down one place:

            systemMemory[i] = systemMemory[i-1];
        }

        // Now set the head system as the one being inserted

        systemMemory[0] = system;
    }
    else
    {
        //----------------------------------------------------------------------
        // System not in memory: shift all systems down one place except the
        // very last system..
        //----------------------------------------------------------------------

        for ( int i = SYSTEM_MEMORY_SIZE - 1 ; i > 0 ; i-- )
        {
            // Swap the next system up from this index down one place

            systemMemory[i] = systemMemory[i-1];
        }

        // Now set the head system as the one being inserted

        systemMemory[0] = system;
    }
}

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

Name:       Galaxy::getStartSystem
Purpose:    Picks a valid random starting system for the player.
Params:     none
Returns:    Star system that the player can star in.

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

StarSystem Galaxy::getStartSystem()
{
    //--------------------------------------------------------------------------
    // Hold the system here:
    //--------------------------------------------------------------------------

    StarSystem s;

    //--------------------------------------------------------------------------
    // Seed the random number generator by galaxy seed:
    //--------------------------------------------------------------------------

    mlRandomSeed( this->seed );

    //--------------------------------------------------------------------------
    // Now keep trying to pick a system until a valid one is found:
    //--------------------------------------------------------------------------

    while ( s.isNullSystem() )
    {
        // Pick another system at random:

        s = getSystem
        (
            mlRandomInt() / SECTOR_SIZE,
            mlRandomInt() / SECTOR_SIZE
        );
    }

    //--------------------------------------------------------------------------
    // Return the system picked:
    //--------------------------------------------------------------------------

    return s;
}

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

Name:       Galaxy::getSystem
Purpose:    Returns the star system at a given sector. returns a null system with
            no name if there is no system at that sector.
Params:     x coordinate of sector, y coordinate of sector
Returns:    star system at that sector, which may be null and non-existant

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

StarSystem Galaxy::getSystem ( unsigned sectorX , unsigned sectorY ) const
{

    //--------------------------------------------------------------------------
    // Seed the random number generator based on galaxys seed and sector position
    //--------------------------------------------------------------------------

    // Pick a seed based on galaxy seed and sector position:

    unsigned seed = ( sectorX & 0xffff ) + ( sectorY << 16 ) + this->seed;

    // Set this as the current random seed:

    mlRandomSeed( seed );

    //--------------------------------------------------------------------------
    // There is a one in four chance that a star system may be on this sector:
    //--------------------------------------------------------------------------

    if ( ( mlRandomInt() & 0x3 ) == 0 )
    {
        //----------------------------------------------------------------------
        // Star system exists on this sector: create it.
        //----------------------------------------------------------------------

        StarSystem system( seed, sectorX , sectorY );

        //----------------------------------------------------------------------
        // Now see if a modified version of this system exists in memory:
        //----------------------------------------------------------------------

        for ( unsigned i = 0 ; i < SYSTEM_MEMORY_SIZE ; i++ )
        {
            // See if this system matches the one in memory at this index:

            if ( system == systemMemory[i] )
            {
                // Match found. Update the system with the modified version of it:

                system = systemMemory[i];

                // Abort search

                break;
            }
        }

        // Now return the system

        return system;
    }
    else
    {
        //----------------------------------------------------------------------
        // No star system on this sector: return a defaul null star system
        //----------------------------------------------------------------------

        return StarSystem();
    }
}
