/*=========================================================================
* LoadLvl.cpp : This module contain all functions used to load
*               a level.
* This is a part of the Game project.
*
* Version              1.0
* Creation date        28/08/96
* Revision date
*
* That file needs to be compatible for all platforms.
*
* (c) Ubi Studios 1996
*=======================================================================*/
 
#if defined (WIN32)
#include <direct.h>
#endif /* WIN32 */
 
#define D_Dynam_StructureDefine
 
#include "ToolsCPA.h"
 
#include "Main.h"
 
#include "Options/Options.h"
#include "macros.h"
 
#include "Main.h"
 
#include "Actions/AllActs.h"
 
#include "Structur/3DOSLkTb.h"
#include "Structur/GameScpt.h"
#include "Structur/ErrGame.h"
#include "Structur/MemGame.h"
#include "Structur/StdObjSt.h"
#include "Structur/EngMode.h"
#include "Structur/Objects.h"
 
 
#include "PlayAnim/PlayAnim.h"
 
#include "Engine.h"
#include "Always.h"
#include "Basic.h"
#include "DspFix.h"
#include "Family.h"
#include "GameEng.h"
#include "GamSave.h"
#include "ia_dnm.h"
#include "InitEng.h"
#include "LoadAni.h"
#include "LoadFml.h"
#include "LoadLvl.h"
#include "MainChar.h"
#include "micros.h"
#include "ObjInit.h"
#include "ObjType.h"
#include "Zemem.h"
#include "LoadBin.h"
#include "TBLLoad.h"
#include "CHLLoad.h"
#include "Structur/Anim_s.h"
#include "toolmatr.h"
#include "AlwAct.h"
#include "LoadGame.h"
 
#include "options\Specif\SubMapPs.h"
 
extern void SHW_fn_vReInitShadowForMapChange(void);

// FBF N64-format pour coords, et logfile dans x:\exe\geodump.log{
#ifdef U64CONVERTETLOG
extern BOOL				g_bLoadMap;

#endif //U64CONVERTLOG
// } fin N64-format

 
#if defined (ACTIVE_EDITOR)
extern BOOL g_bSectionSoundFoundInLevelDSC;
#endif /*ACTIVE_EDITOR*/
 
#ifndef U64
#include "sna.h"
 
#endif
 
/* ANNECY AV DEMO {*/
#ifndef U64
    #include "Specif/Demos.h"
#endif
/* END ANNECY AV }*/
 
extern HIE_tdxHandleToSuperObject g_hLoadedSuperObjectRoot;
 
/* need for game installations with no sound on hard drive*/
extern int g_iSoundOnHD;
 
#ifdef ACTIVE_EDITOR
extern ACP_tdxBool g_bUseSAIWithEditor;
#endif /* ACTIVE_EDITOR */
 
extern tdstEngineObject *g_AlphabetCharacterPointer;
 
/**************** FabPerez SectorAnalyse  ************/
/*****************************************************/
#if defined(WIN32) && defined(_DEBUG)
	StructInfoSectorTrame	*pt_aStructInfoSectorTrame;
#endif /*WIN32 & _DEBUG*/
/************** Fin FabPerez SectorAnalyse  ***********/
/******************************************************/



/*-----------------------------------------------------------------------------
*  Description :   Init Geometric Object Normals
*-----------------------------------------------------------------------------
*  Input :
*  Output :
*-----------------------------------------------------------------------------
*  Creation date : 05/12/96            Author : CGHT
*-----------------------------------------------------------------------------
*  Modification date :                 Modification Author :
*  Modifications :
*---------------------------------------------------------------------------*/
void fn_vInitCollSet(HIE_tdxHandleToSuperObject p_stSO)
{
 
	HIE_tdxHandleToSuperObject p_stChild;
	GEO_tdstGeometricObject *p_stObject;
	unsigned long i;
 
	i = HIE_fn_ulGetSuperObjectType(p_stSO);
	p_stObject = (GEO_tdstGeometricObject *)HIE_fn_hGetSuperObjectObject(p_stSO);
 
	if(i & (HIE_C_ulEDT_Geometric | HIE_C_ulPO ))
	{
		GEO_xComputeObjectNormals(p_stObject);
	}
 
	HIE_M_ForEachChildOf(p_stSO,p_stChild,i)
	{
		fn_vInitCollSet(p_stChild);
	}
}
 
/* Jourdan 10/02/97*/
/* fonction recursive creation des octrees hierarchique a partir d un super objet */
void TGE_fn_vRecursiveInitOctreeSuperObject ( HIE_tdxHandleToSuperObject _hSprObj )
{
	GEO_tdstGeometricObject *p_stGeomObj;
	ACP_tdxIndex xChildIndex;
	HIE_tdxHandleToSuperObject hChild;
	MTH_tdxReal tdxTmpReal;
	PO_tdxHandleToPhysicalObject _hPhysicalObject;
	register unsigned long		ulType;
 
	ulType = HIE_fn_ulGetSuperObjectType(_hSprObj);
 
	if(ulType == HIE_C_ulEDT_Geometric)
	{
		p_stGeomObj = (GEO_tdstGeometricObject *)HIE_fn_hGetSuperObjectObject ( _hSprObj );
		COL_fn_bCreateOctree ( p_stGeomObj, 10, 5, 4 );
	}
	else if(ulType & (HIE_C_ulIPO | HIE_C_ulIPO_Mirror))
	{
		_hPhysicalObject = IPO_fn_hGetPhysicalObject((IPO_tdxHandleToInstanciatedPhysicalObject)HIE_fn_hGetSuperObjectObject(_hSprObj));
		GLI_vGetVisualSetLOD(PO_fn_hGetVisualSet(_hPhysicalObject), 0, &tdxTmpReal, &p_stGeomObj);
 
		COL_fn_bCreateOctree ( p_stGeomObj, 10, 5, 4 );
	}
 
	else if(ulType != HIE_C_ulActor)
	{
		HIE_M_ForEachChildOf ( _hSprObj, hChild, xChildIndex )
		{
			TGE_fn_vRecursiveInitOctreeSuperObject ( hChild );
		}
	}
}
 
/* creation des octrees hierarchique a partir d un super objet */
void TGE_fn_vInitOctreeSuperObject ( HIE_tdxHandleToSuperObject _hSprObj )
{
	TGE_fn_vRecursiveInitOctreeSuperObject ( _hSprObj );
}
 
/*-----------------------------------------------------------------------------
*  Description :   Load the level.
*-----------------------------------------------------------------------------
*  Input :         Number of level
*  Output :        void
*-----------------------------------------------------------------------------
*  Creation date : 29/08/96            Author : Francois
*-----------------------------------------------------------------------------
*  Modification date :                 Modification Author :
*  Modifications :
*---------------------------------------------------------------------------*/
extern void fn_v_InitInterpol();
 
/* ANNECY MT - 08/09/98 {*/
void fn_vLoadLevel(char *_szLevelName,long _lSubMapNumber)
/* END ANNECY MT }*/
{
	char szLevelFileName[_MAX_PATH];
 
#ifdef ACTIVE_EDITOR
	g_bUseSAIWithEditor=FALSE;
#endif /* ACTIVE_EDITOR */
 
	/* ANNECY MT - 08/09/98 {*/
 	fn_vLoadTheMap(_szLevelName,_lSubMapNumber);
	/* END ANNECY MT }*/
 
#ifdef ACTIVE_EDITOR
	fn_vEditorSetCurrentMap("cave\\edmap.spo");
#endif
 
	fn_vChangeWindowTitle("Chargement du level");
	/* InitArrayOfDynamicalFunctions((tdstPairOfDynamicalFunctions *)g_a_stPairOfDynamicalFunctions);*/
 
	/* BINARISATION YLG*/
	/*  fn_v_InitInterpol();*/
 
	SECT_hFatherSector=HIE_fn_hGetSuperObjectLastChild(gp_stActualWorld);
	HIE_fn_vSetSuperObjectObjectAndType(SECT_hFatherSector,NULL,HIE_C_ulSuperObject);
 
	if ( strlen(_szLevelName) )
	{
 
		/* load always model object*/
		fn_vChangeWindowTitle("Chargement des always");
		sprintf(szLevelFileName,"%s\\%s.%s",_szLevelName,_szLevelName,C_ScriptAlwaysSuffixe);
		if (SCR_fn_c_RdL0_IsSectionExists(szLevelFileName))
		{
			SCR_fnp_st_RdL0_AnalyseSection(szLevelFileName, SCR_CDF_uw_Anl_Normal);
		}
 
/* ANNECY MT - 16/09/98 { load actors before waypoints because of submap loading (waypoints need to know position of actors)*/
		fn_vChangeWindowTitle("Chargement des personnages");
		sprintf(szLevelFileName,"%s\\%s.%s",_szLevelName,_szLevelName,C_ScriptLevelSuffixe);
		if (!SCR_fn_c_RdL0_IsSectionExists(szLevelFileName))
			sprintf(szLevelFileName,"default.%s",C_ScriptLevelSuffixe);
#ifdef ACTIVE_EDITOR
		g_stEngineStructure.h_StdCamCaracter = NULL;
#endif
		SCR_fnp_st_RdL0_AnalyseSection(szLevelFileName, SCR_CDF_uw_Anl_Normal);
#ifdef ACTIVE_EDITOR
		if ( g_stEngineStructure.h_StdCamCaracter == NULL)
			MessageBox(NULL,"Add (StandardCamera) after {InsertCharacter:StdCamer", "Missing information in *.lvl", MB_OK);
		if (LST2_M_DynamicGetNumberOfElements(&g_stEngineStructure.hMainCharacterList) == 0)
			MessageBox(NULL,"Add (PrincipalActor,ActorLauchingSounds) after {InsertCharacter:Rayman", "Error Missing information in *.lvl", MB_OK);
#endif
		/*ANNECY Bart#01 17/02/98 {*/
		fn_vChangeWindowTitle("Chargement des waypoints");
		sprintf(szLevelFileName,"%s\\%s.%s",_szLevelName,_szLevelName,C_ScriptWayPointSuffixe);
		if (SCR_fn_c_RdL0_IsSectionExists(szLevelFileName))
		{
			SCR_fnp_st_RdL0_AnalyseSection(szLevelFileName,SCR_CDF_uw_Anl_Normal);
		}
/* END ANNECY MT }*/
		/*ENDANNECY Bart#01 }*/
	}
 
/* ANNECY AV DEMO {*/
    {
      HIE_tdxHandleToSuperObject  hActor;
      int                         i;
 
      HIE_M_ForEachChildOf (gp_stDynamicWorld , hActor , i)
      {
          DEMO_fn_vPutCharacterInList (hActor);
      }
    }
/* END ANNECY AV }*/
 
	fn_vChangeWindowTitle("Traitement de la Map");
	/*SECT_hFatherSector=HIE_fn_hGetSuperObjectNextBrother(HIE_fn_hGetSuperObjectFirstChild(gp_stActualWorld));*/
	/* ylg SECT_hFatherSector=HIE_fn_hGetSuperObjectLastChild(gp_stActualWorld);*/
 
#if !defined(ACTIVE_EDITOR)
	/*fn_vDeleteAllLevelReUsableSections();*/
#endif /* ACTIVE_EDITOR */
 
	fn_vGeneralCoherenceOfSmoothing(SECT_hFatherSector);
	TGE_fn_vInitOctreeSuperObject(SECT_hFatherSector);
 
	COL_fn_vOctreeGlobalsCompute();
 
	/* For BIN*/
	/* GLI_vEndofGeometricLoad();*/
 
	HIE_fn_vInitMatrixStack();
	HIE_fn_vComputePoAndIpoBoundingVolumes(SECT_hFatherSector);
	HIE_fn_vComputeBoundingVolumeOfSuperObjectBranch(SECT_hFatherSector);
 
#if !defined(ACTIVE_EDITOR) /* {*/
	fn_vRecurUpdateWithMatrixIdentityConst( SECT_hFatherSector );
#endif /* ACTIVE_EDITOR }*/
 
	if ( strlen(_szLevelName) )
	{
		sprintf(szLevelFileName,"%s\\%s.RLI",_szLevelName,_szLevelName);
		if (!SCR_fn_c_RdL0_IsSectionExists(szLevelFileName))
		{
			fn_vSetDisplayFlag(edmDisplayModeUseRLI,0);
			fn_vSetDisplayFlag(edmDisplayModeUseStaticLight,1);
		}
	}
 
/*	fn_vGameTestMemory();*/
 
	fn_vTestAllSectorsListForIncoherences();
	SHW_fn_vReInitShadowForMapChange();
#if defined(ACTIVE_EDITOR)
	fn_vEnableEditorsMainWnd(TRUE);
#endif /* ACTIVE_EDITOR */
}
 
#if !defined(ACTIVE_EDITOR) /* {*/
 
/* fbolefeysot - 31/07/98{*/
extern GEO_tdstGeometricObject *HIE_fn_p_stGetGeometricObjectFromSuperObject( HIE_tdxHandleToSuperObject  h_SuperObject );
/*END fbolefeysot}*/
void fn_vUpdateWithMatrixIdentityConst(HIE_tdxHandleToSuperObject h_SuperObject)
{
	POS_tdxHandleToPosition hMatrix;
 
	if( HIE_fn_bIsSuperObjectValid( h_SuperObject ) )
	{
/* fbolefeysot - 31/07/98{*/
		GEO_tdstGeometricObject *p_stObject;
 
		p_stObject = HIE_fn_p_stGetGeometricObjectFromSuperObject(h_SuperObject);
	    if (!p_stObject || !GEO_bIsLookAt(p_stObject))
		{
/*END fbolefeysot}*/
			/* local matrix*/
			hMatrix = HIE_fn_hGetSuperObjectMatrix( h_SuperObject );
			if( POS_M_xIsIdentity( hMatrix ) )
			{
				/*ANNECY TQ 23/07/98{*/
				/* The matrices are allocated in a bloc of the module GEO and not in POS*/
				/*			POS_fn_vDestroyMatrix( hMatrix );*/
				GEO_fn_vDestroyMatrix( hMatrix );
				/*ENDANNECY TQ}*/
 
				HIE_fn_vSetSuperObjectMatrix( h_SuperObject , POS_fn_hGetMatrixIdentityConst() );
			}
			/* global matrix*/
			hMatrix = HIE_fn_hGetSuperObjectGlobalMatrix( h_SuperObject );
			if( POS_M_xIsIdentity( hMatrix ) )
			{
				/*ANNECY TQ 23/07/98{*/
				/*			POS_fn_vDestroyMatrix( hMatrix );*/
				GEO_fn_vDestroyMatrix( hMatrix );
				/*ENDANNECY TQ}*/
				HIE_M_vSetSuperObjectMember( h_SuperObject , hGlobalMatrix , POS_fn_hGetMatrixIdentityConst() );
				HIE_M_vSetSuperObjectMember( h_SuperObject , lLastComputeFrame, HIE_C_lCounterNotValid);
			}
/* fbolefeysot - 31/07/98{*/
		}
/*END fbolefeysot}*/
 
	}
}
 
void fn_vRecurUpdateWithMatrixIdentityConst(HIE_tdxHandleToSuperObject h_SuperObject)
{
	HIE_tdxHandleToSuperObject hChild;
	long xI;
 
	/* current*/
	fn_vUpdateWithMatrixIdentityConst( h_SuperObject );
	/* children*/
	HIE_M_ForEachChildOf( h_SuperObject , hChild , xI )
	{
		fn_vRecurUpdateWithMatrixIdentityConst( hChild );
	}
}
 
#endif /* ACTIVE_EDITOR }*/
 
/* ANNECY MT - 08/09/98 {*/
void fn_vInitCompleteWorld3DEngine(LPCTSTR szName,long _lSubMapNumber)
/* END ANNECY MT }*/
{
	HIE_tdxHandleToSuperObject	h_SuperObject;

// FBF N64-format pour coords, et logfile dans x:\exe\geodump.log{
#ifdef U64CONVERTETLOG
	g_bLoadMap = TRUE;

#endif //U64CONVERTLOG
// } fin N64-format

/* ANNECY MT - 08/09/98 {*/
    if (_lSubMapNumber == 0)
    {
        h_SuperObject = HIE_fn_hLoadSPOFile(".",(char *) szName);
    }
    else
    {
        h_SuperObject = HIE_fn_hLoadSUBFile(".",(char *) szName,GAM_M_GetSubMap(_lSubMapNumber),GAM_M_GetEntry(_lSubMapNumber));
    }
/* END ANNECY MT }*/
	HIE_fn_vLoadLinkedObject(h_SuperObject);
 
	g_hLoadedSuperObjectRoot = h_SuperObject;
	HIE_fn_vSetSuperObjectObjectAndType(h_SuperObject,HIE_fn_hGetSuperObjectObject(h_SuperObject),HIE_C_ulSuperObject);
	HIE_fn_vSuperObjectAddTail(gp_stActualWorld,h_SuperObject);
	HIE_fn_vSetSuperObjectObjectAndType(gp_stActualWorld,NULL,HIE_C_ulSuperObject);
// FBF N64-format pour coords, et logfile dans x:\exe\geodump.log{
#ifdef U64CONVERTETLOG
	g_bLoadMap = FALSE;

#endif //U64CONVERTLOG
// } fin N64-format

}
 
 
/*-----------------------------------------------------------------------------
*  Description :   verify the coherence of  submap
*-----------------------------------------------------------------------------
*  Input :         void
*  Output :        void
*-----------------------------------------------------------------------------
*  Creation date : 08/09/98            Author : Marc
*-----------------------------------------------------------------------------
*  Modification date :                 Modification Author :
*  Modifications :
*---------------------------------------------------------------------------*/
/* ANNECY MT - 08/09/98 {*/
void fn_vVerifySubMapCoherence(char *_szLevelName,long _lSubMapNumber)
{
    SCR_tdst_Link_Table			*p_stLK;
    SCR_tdst_Link_Value			*p_xLVa = NULL;
    unsigned int				uiPos;
	HIE_tdxHandleToSuperObject	h_SO;
	long						lType;
	long						lNbError;
	FILE						*pFile;
	char						*p_cDelimiter,*p_cText;
 
	pFile		= fopen("SubMap.log","at");
	lNbError	= 0;
 
	if( pFile )
	{
		fprintf( pFile ,"==============================================================================\n");
		fprintf( pFile ,"Map : %s     Submap : %02d\n" , _szLevelName , GAM_M_GetSubMap(_lSubMapNumber) );
		fprintf( pFile ,"==============================================================================\n");
	}
	/**/
	p_stLK		= HIE_fn_p_stGetSuperObjectLinkTable();
    uiPos		= 0;
    SCR_M_DyAr_GetNextElement(SCR_tdst_Link_Value, uiPos, p_xLVa, SCR_M_st_Link_GetDynamicArray(p_stLK));
    while(p_xLVa)
    {
		if( SCR_M_e_Link_GetState( p_xLVa ) == SCR_ELS_Link_Initialized )
		{
			h_SO	= (HIE_tdxHandleToSuperObject)SCR_M_ul_Link_GetValue( p_xLVa );
			lType	= HIE_fn_ulGetSuperObjectType( h_SO );
 
			if( (lType == -3) && (HIE_fn_hGetSuperObjectFather( h_SO ) == NULL) )
			{
				/* error*/
				lNbError++;
				if( pFile )
				{
					p_cText = SCR_M_p_sz_Link_GetKey( p_xLVa );
					p_cDelimiter = strchr( p_cText , ':' );
					fprintf( pFile , "Sector %s loaded but isn't child of root\n" , ++p_cDelimiter);
				}
			}
		}
		/* next*/
        uiPos++;
        SCR_M_DyAr_GetNextElement(SCR_tdst_Link_Value, uiPos, p_xLVa, SCR_M_st_Link_GetDynamicArray(p_stLK));
    }
	/**/
	if( lNbError )
	{
		if( pFile )
		{
			fprintf( pFile ,"==============================================================================\n\n");
			fclose( pFile );
		}
		/* message*/
		M_GameInformationErrorWithString(E_uwGameUnCoherentSubMap,"Uncoherent SubMap");
	}
}
 
/* END ANNECY MT }*/
 
/*-----------------------------------------------------------------------------
*  Description :   Load the map
*-----------------------------------------------------------------------------
*  Input :         Level number
*  Output :        void
*-----------------------------------------------------------------------------
*  Creation date : 05/11/96            Author : Francois
*-----------------------------------------------------------------------------
*  Modification date :                 Modification Author :
*  Modifications :
*---------------------------------------------------------------------------*/
/* ANNECY MT - 08/09/98 {*/
void fn_vLoadTheMap(char *_szLevelName,long _lSubMapNumber)
/* END ANNECY MT }*/
{
	char szLevelFileName[_MAX_PATH];
	POS_tdstCompletePosition * p_stMatrix,stMatrix;
	MTH3D_tdstVector stVector;
 
	GLI_xCreateLight(&gp_stLight , GLI_C_lParallelLight);
	MTH3D_M_vSetVectorElements(&stVector,0,0,1);
	POS_fn_vSetIdentityMatrix(&stMatrix);
	POS_fn_vSetTranslationVector(&stMatrix,&stVector);
	fn_vTurnMatrixX ( &stMatrix,MTH_C_Pi);
	GLI_xSetLightMatrix(gp_stLight ,&stMatrix);
 
#if defined(ACTIVE_EDITOR) /* {*/
	p_stMatrix = GEO_fn_hCreateMatrix();
#else
	p_stMatrix = POS_fn_hGetMatrixIdentityConst();
#endif
	/* The static complet world */
	gp_stActualWorld = HIE_fn_hCreateSuperObject();
	HIE_fn_vSetSuperObjectObjectAndType(gp_stActualWorld,NULL,HIE_C_ulSuperObject);
	HIE_fn_vSetSuperObjectMatrix(gp_stActualWorld,p_stMatrix);
 
	/* The Active dynamic world */
	gp_stDynamicWorld = HIE_fn_hCreateSuperObject();
	HIE_fn_vSetSuperObjectObjectAndType(gp_stDynamicWorld,NULL,HIE_C_ulSuperObject);
	HIE_fn_vSetSuperObjectMatrix(gp_stDynamicWorld,p_stMatrix);
	HIE_fn_vSuperObjectAddTail(gp_stActualWorld,gp_stDynamicWorld);
 
	/* The Inactive dynamic world */
	gp_stInactiveDynamicWorld = HIE_fn_hCreateSuperObject();
	HIE_fn_SO_vSetFlags(gp_stInactiveDynamicWorld , HIE_fn_SO_ulGetFlags(gp_stInactiveDynamicWorld) | HIE_C_Flag_ulNotPickable);
	HIE_fn_vSetSuperObjectObjectAndType(gp_stInactiveDynamicWorld,NULL,HIE_C_ulSuperObject);
	HIE_fn_vSetSuperObjectMatrix(gp_stInactiveDynamicWorld,p_stMatrix);
	HIE_fn_vSuperObjectAddTail(gp_stActualWorld,gp_stInactiveDynamicWorld);
 
	g_hSOCurrentMainSector = NULL;
	g_hSOPreviousMainSector = NULL;
 
	if ( strlen(_szLevelName) )
	{
		/* Loading and linking the map world */
		sprintf(szLevelFileName,"Chargement de la map (%s)",_szLevelName);
		fn_vChangeWindowTitle(szLevelFileName);
/* ANNECY MT - 08/09/98 {*/
		if(_lSubMapNumber == 0)
			sprintf(szLevelFileName,"%s\\%s.%s",_szLevelName,_szLevelName,"spo");
		else
			sprintf(szLevelFileName,"%s\\%s.%s",_szLevelName,_szLevelName,"sub");
/* END ANNECY MT }*/
/*
		if(g_bUseBinaryData==1)
		{
			fn_vBinLoadLevelFromOneFile(szLevelName);
 
			HIE_fn_vSuperObjectAddTail(gp_stActualWorld,g_hLoadedSuperObjectRoot);
			HIE_fn_vSetSuperObjectObjectAndType(gp_stActualWorld,NULL,C_ucSuperObject);
		}
		else
*/
/* ANNECY MT - 08/09/98 {*/
    fn_vInitCompleteWorld3DEngine(szLevelFileName,_lSubMapNumber);
/* END ANNECY MT }*/
 
		/* init the border box of all sectors*/
		SECT_fn_vInitAllBorders(g_hLoadedSuperObjectRoot);
	}
 
/* ANNECY MT - 08/09/98 {*/
	GAM_fn_vInitSubMapPositionList();
	if(_lSubMapNumber != 0)
	{
		fn_vVerifySubMapCoherence(_szLevelName,_lSubMapNumber);
	}
	else
	{
		sprintf(szLevelFileName,"%s\\%s.%s",_szLevelName,_szLevelName,"sub");
		GAM_fn_vLoadSubMapPositions(szLevelFileName);
	}	
/* END ANNECY MT }*/
}
 


/**************** FabPerez SectorAnalyse  ************/
/*****************************************************/
#if defined(WIN32) && defined(_DEBUG)
void fn_InitMapSectorStruct(void)
{
	HIE_tdxHandleToSuperObject		hSuperObjectSector;
	SECT_tdxHandleOfSectorObject	hSectorObject;
	int								iNbSector = 0, i;

	HIE_M_ForEachChildOf(g_hLoadedSuperObjectRoot,hSuperObjectSector,iNbSector)
	{
	};
	pt_aStructInfoSectorTrame = malloc(sizeof(StructInfoSectorTrame)*iNbSector);

	HIE_M_ForEachChildOf(g_hLoadedSuperObjectRoot,hSuperObjectSector,i)
	{
		hSectorObject = HIE_fn_hGetSuperObjectObject(hSuperObjectSector);
		(pt_aStructInfoSectorTrame+i)->i_NbSectorMap = iNbSector;
		(pt_aStructInfoSectorTrame+i)->p_a256_SectorName = hSectorObject->szSectorName;
		(pt_aStructInfoSectorTrame+i)->ul_UneTrame = 0;
		(pt_aStructInfoSectorTrame+i)->ul_DeuxTrames = 0;
		(pt_aStructInfoSectorTrame+i)->ul_TroisTrames = 0;
	}
}
#endif /*WIN32 & _DEBUG*/
/************** Fin FabPerez SectorAnalyse  ***********/
/******************************************************/



/*-----------------------------------------------------------------------------
*  Description :   Callback script function
*-----------------------------------------------------------------------------
*  Input :         ...
*  Output :        void
*-----------------------------------------------------------------------------
*  Creation date : 29/08/96            Author : Francois
*-----------------------------------------------------------------------------
*  Modification date :                 Modification Author :
*  Modifications :
*---------------------------------------------------------------------------*/
SCR_tde_Anl_ReturnValue fn_eScriptCallBackLevelDescription(SCR_tdst_File_Description *_p_stFile,char *_p_szName,char *_ap_szParams[],SCR_tde_Anl_Action	_eAction)
{
	SCR_tdst_Cxt_Values *pScriptContext;
	SND_tduRefEvt stSndThemeEvent;
	SCR_tde_Anl_ReturnValue eReturnValue = SCR_ERV_Anl_NormalReturn;
 
	_p_stFile=_p_stFile;
 
	if (M_IsTitle)
	{
		g_bBeginMapSoundEventFlag = FALSE;
#ifndef RETAIL
        if ( SNA_M_bTestSaveLevelDesc() )
            SNA_fn_vWriteNoParamEntryToCurrentDscFile( SNA_C_ul_LevelDscTitle );
#endif
	}
 
 
	if (M_IsEntry)
	{
		if(M_ActionIs(C_EntryInitNumberOfAlways))
        {
			g_stAlways.ulMaxNumberOfAlways = fn_lAToI(_ap_szParams[0]);
#ifndef RETAIL
			if(SNA_M_bTestSaveLevelDesc())
				SNA_fn_vWriteLongEntryToCurrentDscFile( SNA_C_ul_NumberOfAlways, fn_lAToI(_ap_szParams[0]) );
#endif
        }
/*		else if (M_ActionIs(C_EntryReserveString))
		{
			fn_vReserveSuperimposedText(fn_lAToI(_ap_szParams[0]),FON_fn_hGetTextHandle(_ap_szParams[1]),FON_fn_xGetFont(_ap_szParams[2]),fn_fAToF(_ap_szParams[3]),fn_fAToF(_ap_szParams[4]),-1);
		}*/
#ifdef U64
		else if (M_ActionIs("LoadSoundEvent"))
#else
			else if (M_ActionIs("LoadSoundEvent") && g_iSoundOnHD)
			/* play theme while level loading only if the sound is on the Hard Drive*/
#endif
		{
			/* Load theme event for this level:*/
			pScriptContext=SCR_fnp_st_RdL0_AnalyseSection(_ap_szParams[0], SCR_CDF_uw_Anl_Normal);
			stSndThemeEvent.pstPtr=(SND_tdstBlockEvent *)SCR_M_ul_RdL0_ExtractLongValue(pScriptContext,0);
			SND_fn_lSendRequestSound(/*C_SOUNDOBJECT_MUSIC*/SND_C_OBJET_FANTOME,g_lSoundObjectTypeMusic,stSndThemeEvent,0/*prio*/,NULL/*Proc=NULL*/);
		}
		else if( M_ActionIs("BeginMapSoundEvent") )
		{
			pScriptContext=SCR_fnp_st_RdL0_AnalyseSection(_ap_szParams[0], SCR_CDF_uw_Anl_Normal);
			g_stBeginMapSoundEvent.pstPtr=(SND_tdstBlockEvent *)SCR_M_ul_RdL0_ExtractLongValue(pScriptContext,0);
			g_bBeginMapSoundEventFlag = TRUE;
		}
		else
			M_GameInformationError(E_uwGameScriptCallBackDescriptionUnknownAction);
	}
#ifndef RETAIL
    else if ( M_IsEnd )
        if ( SNA_M_bTestSaveLevelDesc() )
            SNA_fn_vWriteNoParamEntryToCurrentDscFile( SNA_C_ulEndOfDescSection );
#endif
 
	return(eReturnValue);
}
 
/*-----------------------------------------------------------------------------
*  Description :   Callback script function
*-----------------------------------------------------------------------------
*  Input :         ...
*  Output :        void
*-----------------------------------------------------------------------------
*  Creation date : 29/08/96            Author : CB
*-----------------------------------------------------------------------------
*  Modification date :                 Modification Author :
*  Modifications :
*---------------------------------------------------------------------------*/
extern char gc_EraseBackground;
SCR_tde_Anl_ReturnValue fn_eScriptCallBackLevelOptions(SCR_tdst_File_Description *_p_stFile,char *_p_szName,char *_ap_szParams[],SCR_tde_Anl_Action	_eAction)
{
	_p_stFile = _p_stFile;
 
	if (M_IsTitle)
	{
		gc_EraseBackground = 1;
	}
 
 
	if (M_IsEntry)
	{
		if(M_ActionIs("EraseBackground"))
		{
			if(!strcmpi(_ap_szParams[0], "off"))
				gc_EraseBackground = 0;
			else
				gc_EraseBackground = 1;
		}
		else
			M_GameInformationError(E_uwGameScriptCallBackDescriptionUnknownAction);
	}
 
	return(SCR_ERV_Anl_NormalReturn);
}
 
unsigned long fn_ulEmptySizeOf()
{
	return 0;
}
void fn_vEmptyAlloc(struct tdstEngineObject_ *p_stObject)
{
}
void fn_vEmptyFree(struct tdstEngineObject_ *p_stObject)
{
}
void fn_vEmptyInit(struct tdstEngineObject_ *p_stObject,enum tdeObjectTreeInit_ eObjectInit)
{
}
void fn_vEmptyDesinit(struct tdstEngineObject_ *p_stObject,enum tdeObjectTreeInit_ eObjectInit)
{
}
void fn_vEmptyCopyClone(struct tdstEngineObject_ * _p_stObjectDest,struct tdstEngineObject_ * _p_stObjectSrc)
{
}
 
/*END*/
 
 
 
/*-----------------------------------------------------------------------------
*  Description :   Callback script function
*-----------------------------------------------------------------------------
*  Input :         ...
*  Output :        void
*-----------------------------------------------------------------------------
*  Creation date : 29/08/96            Author : Francois
*-----------------------------------------------------------------------------
*  Modification date :                 Modification Author :
*  Modifications :  For loading chars of the fix too (not only level's chars...)
*---------------------------------------------------------------------------*/
SCR_tde_Anl_ReturnValue fn_eScriptCallBackLevelCharacters(SCR_tdst_File_Description *_p_stFile,char *_p_szName,char *_ap_szParams[],SCR_tde_Anl_Action	_eAction)
{
	SCR_tde_Anl_ReturnValue      eReturnValue = SCR_ERV_Anl_NormalReturn;
	HIE_tdxHandleToSuperObject   h_SupObject = NULL;
	static tdstEngineObject     *p_stEngineObject = NULL;
	SCR_tdst_Cxt_Values         *p_stValues = NULL;
 
	static char                  g_szCharacterSection[MAX_PATH];
	static ACP_tdxBool           s_bMainCharacter = FALSE,s_bMainCamera = FALSE;
	
	static ACP_tdxBool           s_bLaunchingSound = FALSE;
/* ANNECY MT - 19/11/98 {*/
	static ACP_tdxBool			 s_bInAllSubMap = FALSE;
/* END ANNECY MT }*/
 
	_p_stFile = _p_stFile;
 
	if (M_IsTitle && !GAM_fn_bIsEngineInFixMode())
	{
		int i = 0;
		char *szParam;
 
		s_bInAllSubMap = s_bLaunchingSound = s_bMainCharacter = s_bMainCamera = FALSE;
 
		/* Scan all parameters and set flags accordingly..*/
		while( (szParam = _ap_szParams[i++]) != NULL )
		{
			if( !s_bMainCharacter )
				if( stricmp(szParam,C_LevelPrincipalCharacter) == 0 )
				{	s_bMainCharacter = TRUE;	continue; }
 
			if( !s_bLaunchingSound )
				if( stricmp(szParam,C_LevelCharacterLauchingSounds) == 0 ||
					stricmp(szParam,C_LevelCharacterLaunchingSounds) == 0 )
				{	s_bLaunchingSound = TRUE;	continue;	}
 
			if( !s_bMainCamera )
				if( stricmp(szParam,C_LevelStandardCamera) == 0 )
					s_bMainCamera = TRUE;
		}
		/* The SuperObject is created later, to avoid double creation for chars in fix.*/
		/* For now, set it to NULL*/
		SCR_M_RdL0_SetSectionLong(C_ThisSection,0,NULL);
 
	}
	else if (M_IsEntry)
	{
		/* For all entries : get SuperObject handle.*/
		/* This handle is NULL before entry C_LevelLinkCharacters and C_LevelCharacterMatrixTranslation*/
		SCR_M_RdL0_GetSectionLong(C_ThisSection,0,HIE_tdxHandleToSuperObject,h_SupObject);
 
 
		if (M_ActionIs(C_LevelLinkCharacters))
		{
			VIG_fn_vAddToProgressBar(1);
			M_CheckScriptParamNumber(1);
 
			strcpy( g_szCharacterSection, _ap_szParams[0]);
 
			/* Chars in the fix are created here (actually only a part of the creation is done).*/
			if( GAM_fn_bIsEngineInFixMode() )
			{
				/* Here is where FIX's chars are created*/
				h_SupObject=HIE_fn_hCreateSuperObject();
/* ANNECY AV DEMO {*/
/*              DEMO_fn_vPutCharacterInList (h_SupObject);*/
/* END ANNECY AV }*/
				/* Rq : it's useless to set the SectionLong with this handle,*/
				/* because the current section is in Game.fix and we need to access*/
				/* the handle at level loading time...*/
 
				/* Parse char scripts and create it's engine object.*/
				p_stValues = SCR_fnp_st_RdL0_AnalyseSection(g_szCharacterSection, SCR_CDF_uw_Anl_Normal);
				assert( p_stValues );  /* Test if we can get character's EngineObject.*/
				p_stEngineObject=(tdstEngineObject *)(p_stValues->a_ulValues[0]);
 
				HIE_fn_vSetSuperObjectObjectAndType(h_SupObject,(void *)p_stEngineObject,HIE_C_ulActor);
				M_SetSuperObject(p_stEngineObject,h_SupObject);
				/* Actors have zoom instead of scale*/
				HIE_fn_SO_vSetFlags (h_SupObject, HIE_fn_SO_ulGetFlags (h_SupObject) | HIE_C_Flag_ulZoomInsteadOfScale);
				HIE_fn_vSetSuperObjectMatrix(h_SupObject,fn_p_st3dDataGetMatrix(M_GetMSHandle(h_SupObject,3dData)));
 
				SNA_g_stFixInfo.a20_stObjects[SNA_g_stFixInfo.ulNbObject]=p_stEngineObject;
				SNA_g_stFixInfo.ulNbObject++;
			}
		}
 
		else if (M_ActionIs(C_LevelCharacterIsInAllSubmap))
		{
			s_bInAllSubMap = TRUE;
		}
		else if (M_ActionIs(C_LevelCharacterMatrixTranslation) && !GAM_fn_bIsEngineInFixMode() )
		{
			MTH3D_tdstVector stTempMatrixTranslation;
			HIE_tdxHandleToSuperObject	h_SOSector;
 
			if( (fn_lGetSubMapNumber()!=0) && g_stEngineStructure.bResurection && (s_bMainCamera || s_bMainCharacter))
			{
				if(s_bMainCamera)
					POS_fn_vGetTranslationVector(&g_stEngineStructure.stMainCameraPosition,&stTempMatrixTranslation);
				else if(s_bMainCharacter)
					POS_fn_vGetTranslationVector(&g_stEngineStructure.stMainCharacterPosition,&stTempMatrixTranslation);
			}
			else
			{
				M_CheckScriptParamNumber(3);
				MTH3D_M_vSetVectorElements(&stTempMatrixTranslation,fn_fAToF(_ap_szParams[0]),fn_fAToF(_ap_szParams[1]),fn_fAToF(_ap_szParams[2]));
			}
 
/* ANNECY MT - 19/11/98 {*/
			if ((fn_lGetSubMapNumber() != 0) && !s_bInAllSubMap)
			{
				h_SOSector=SECT_fn_hResearchInWhatSectorIAm(SECT_hFatherSector,&stTempMatrixTranslation);
 
				if (SECT_fn_bIsThisSectorUniverse(h_SOSector))
				{
					if(SCR_fnp_st_RdL0_GetOpenSection(g_szCharacterSection,0) == NULL)
					{
						/* the .car has not already been analysed, so the actor is not in fix.*/
						/* we can ignore it.*/
						eReturnValue = SCR_ERV_Anl_TerminateCurrentSection;
						return(eReturnValue);
					}
				}
			}
/* END ANNECY MT }*/
 
			p_stValues = SCR_fnp_st_RdL0_AnalyseSection(g_szCharacterSection, SCR_CDF_uw_Anl_Normal);
			assert( p_stValues );
			p_stEngineObject=(tdstEngineObject *)(p_stValues->a_ulValues[0]);
 
			/* Get the SuperObject of the EngineObject.*/
			h_SupObject=M_GetSuperObject(p_stEngineObject);
 
			/* Test if SuperObject has already been created*/
			/* (if so, char is in the fix (good),or is loaded twice in a level(bad!)).*/
			if( ! h_SupObject )
			{
				/* SuperObject does not exists, create it and do the init*/
				/* Here is where LEVEL's chars are created*/
				h_SupObject=HIE_fn_hCreateSuperObject();
/* ANNECY AV DEMO {*/
/*              DEMO_fn_vPutCharacterInList (h_SupObject);*/
/* END ANNECY AV }*/
				HIE_fn_vSetSuperObjectObjectAndType(h_SupObject,(void *)p_stEngineObject,HIE_C_ulActor);
				M_SetSuperObject(p_stEngineObject,h_SupObject);
				/* Actors have zoom instead of scale*/
				HIE_fn_SO_vSetFlags (h_SupObject, HIE_fn_SO_ulGetFlags (h_SupObject) | HIE_C_Flag_ulZoomInsteadOfScale);
 
			}
 
			/* A this point, the SuperObject has been  created, so we can store it.*/
			SCR_M_RdL0_SetSectionLong(C_ThisSection,0,h_SupObject);
 
			if ( fn_ucStandardGameGetPlatFormType(M_GetMSHandle(h_SupObject,StandardGame)) )
			{
					HIE_fn_vSuperObjectAddHead(gp_stDynamicWorld,h_SupObject);
			}
			else
			{
					HIE_fn_vSuperObjectAddTail(gp_stDynamicWorld,h_SupObject);
			}
			HIE_fn_vSetSuperObjectMatrix(h_SupObject,fn_p_st3dDataGetMatrix(M_GetMSHandle(h_SupObject,3dData)));
 
			POS_fn_vSetTranslationVector(fn_p_st3dDataGetMatrix(M_GetMSHandle(h_SupObject,3dData)),&stTempMatrixTranslation);
 
			/* Now take care of its flags defined in the title :*/
			if( s_bMainCharacter )
				MC_fn_vAddCharacterInMainCharacterList(h_SupObject);
			if( s_bLaunchingSound )
				fn_vSectInfoSetCharacterLauchingEvents( h_SupObject );
			if( s_bMainCamera )
				g_stEngineStructure.h_StdCamCaracter = h_SupObject;
 
/* ANNECY MT - 19/11/98 {*/
#if defined(ACTIVE_EDITOR)
			fn_vStdGameSetInAllSubMaps(M_GetMSHandle(h_SupObject,StandardGame),s_bInAllSubMap);
#endif
/* END ANNECY MT }*/
		}
		else if (M_ActionIs(C_LevelCharacterMatrixRotation))
		{
			MTH3D_tdstVector stTempRotationVX,stTempRotationVY,stTempRotationVZ;
 
			if( (fn_lGetSubMapNumber()!=0) && g_stEngineStructure.bResurection && (s_bMainCamera || s_bMainCharacter))
			{
				if(s_bMainCamera)
					POS_fn_vGetRotationMatrix(&g_stEngineStructure.stMainCameraPosition,&stTempRotationVX,&stTempRotationVY,&stTempRotationVZ);
				else if(s_bMainCharacter)
					POS_fn_vGetRotationMatrix(&g_stEngineStructure.stMainCharacterPosition,&stTempRotationVX,&stTempRotationVY,&stTempRotationVZ);
			}
			else
			{
				M_CheckScriptParamNumber(9);
				MTH3D_M_vSetVectorElements(&stTempRotationVX
					,fn_fAToF(_ap_szParams[0])
					,fn_fAToF(_ap_szParams[1])
					,fn_fAToF(_ap_szParams[2]));
				MTH3D_M_vSetVectorElements(&stTempRotationVY
					,fn_fAToF(_ap_szParams[3])
					,fn_fAToF(_ap_szParams[4])
					,fn_fAToF(_ap_szParams[5]));
				MTH3D_M_vSetVectorElements(&stTempRotationVZ
					,fn_fAToF(_ap_szParams[6])
					,fn_fAToF(_ap_szParams[7])
					,fn_fAToF(_ap_szParams[8]));
			}
				POS_fn_vSetRotationMatrix(fn_p_st3dDataGetMatrix(M_GetMSHandle(h_SupObject,3dData)),
					&stTempRotationVX,&stTempRotationVY,&stTempRotationVZ ) ;
			}
			else if (M_ActionIs(C_LevelCharacterMatrixScale) && !GAM_fn_bIsEngineInFixMode())
			{
				MTH3D_tdstVector stTempScaleVX,stTempScaleVY,stTempScaleVZ;
 
			if( (fn_lGetSubMapNumber()!=0) && g_stEngineStructure.bResurection && (s_bMainCamera || s_bMainCharacter))
			{
				if(s_bMainCamera)
					POS_fn_vGetScaleMatrix(&g_stEngineStructure.stMainCameraPosition,&stTempScaleVX,&stTempScaleVY,&stTempScaleVZ);
				else if(s_bMainCharacter)
					POS_fn_vGetScaleMatrix(&g_stEngineStructure.stMainCharacterPosition,&stTempScaleVX,&stTempScaleVY,&stTempScaleVZ);
			}
			else
			{
				M_CheckScriptParamNumber(9);
				MTH3D_M_vSetVectorElements(&stTempScaleVX
					,fn_fAToF(_ap_szParams[0])
					,fn_fAToF(_ap_szParams[1])
					,fn_fAToF(_ap_szParams[2]));
				MTH3D_M_vSetVectorElements(&stTempScaleVY
					,fn_fAToF(_ap_szParams[3])
					,fn_fAToF(_ap_szParams[4])
					,fn_fAToF(_ap_szParams[5]));
				MTH3D_M_vSetVectorElements(&stTempScaleVZ
					,fn_fAToF(_ap_szParams[6])
					,fn_fAToF(_ap_szParams[7])
					,fn_fAToF(_ap_szParams[8]));
			}
			/**/
			POS_fn_vSetScaleMatrix (fn_p_st3dDataGetMatrix(M_GetMSHandle(h_SupObject,3dData)),
				&stTempScaleVX,&stTempScaleVY,&stTempScaleVZ ) ;
		}
		else if (M_ActionIs(C_LevelCharacterInitialState) && !GAM_fn_bIsEngineInFixMode())
		{
			char szCompletFileName[_MAX_PATH];
			SCR_tdst_Link_Value *p_xIndex;
			strcpy(szCompletFileName,fn_szGetFamiliesDataPath());
			strcat(szCompletFileName,"\\");
			strcat(szCompletFileName,_ap_szParams[0]);
			p_xIndex = SCR_fnp_st_Link_SearchKey(&g_st3DOSLinkTable.stState,szCompletFileName);
			if (p_xIndex!=NULL&&p_xIndex->eState==SCR_ELS_Link_Initialized)
				fn_v3dDataSetInitialState(M_GetMSHandle(h_SupObject,3dData),(tdxHandleToState)(p_xIndex->ulValue));
		}
		else if(M_ActionIs(C_LevelCharacterIsAlwaysActive) && !GAM_fn_bIsEngineInFixMode())
		{
			fn_vAddCharacterInAlwaysActiveCharacterList(h_SupObject);
		}
		else if(M_ActionIs(C_LevelCharacterFlags) && !GAM_fn_bIsEngineInFixMode())
		{
			unsigned long ulFlags;
 
			ulFlags = atol(_ap_szParams[0]);
			ulFlags &= ~HIE_C_Flag_ulSuperimposed;
			HIE_fn_SO_vSetFlags(h_SupObject, ulFlags);
			/* Actors have zoom instead of scale*/
			/*			HIE_fn_SO_vSetFlags (h_SupObject, HIE_fn_SO_ulGetFlags (h_SupObject) | HIE_C_Flag_ulZoomInsteadOfScale);*/
		}
 
		else if (M_ActionIs(C_LevelCharacterTransparency) && !GAM_fn_bIsEngineInFixMode())
		{   
            tdstEngineObject *p_stObject;
 
			HIE_fn_vSetSuperObjectTransparenceLevel( h_SupObject, (float) atof( _ap_szParams[0] ) );
            p_stObject = M_GetEngineObject( h_SupObject );
			p_stObject->h_3dData->ucTransparency = (unsigned char)h_SupObject->fTransparenceLevel;
		}
	}
	else if ( M_IsEnd )
	{
		if (  !GAM_fn_bIsEngineInFixMode() )
		{
			SCR_M_RdL0_GetSectionLong(C_ThisSection,0,HIE_tdxHandleToSuperObject,h_SupObject);
			POS_fn_vUpdateMatrixType( fn_p_st3dDataGetMatrix(M_GetMSHandle(h_SupObject,3dData)) );
		}
		/* check that the principal actor has no zoom!*/
		if ( s_bMainCharacter && !POS_fn_ulIsNotScaledMatrix(HIE_fn_hGetSuperObjectMatrix(h_SupObject)) )
		{
			Erm_fn_iMessageBox("The principal actor has zoom or scale in this map\nThis is not allowed.", "Warning!", MB_TOPMOST| MB_ICONEXCLAMATION | MB_OK);
			fn_vForceEditor();
		}
	}
 
	return(eReturnValue);
}
 
 
 
/* For conditional sound bank load test:*/
int gs_iTempMapState=0;
 
/*-----------------------------------------------------------------------------
*  Description :   Callback script function
*-----------------------------------------------------------------------------
*  Input :         ...
*  Output :        void
*-----------------------------------------------------------------------------
*  Creation date : 15/08/97            Author : Frederic decreau
*-----------------------------------------------------------------------------
*  Modification date :                 Modification Author :
*  Modifications :
*---------------------------------------------------------------------------*/
SCR_tde_Anl_ReturnValue fn_eScriptCallBackLevelSoundBank(SCR_tdst_File_Description *_p_stFile,char *_p_szName,char *_ap_szParams[],SCR_tde_Anl_Action	_eAction)
{
 
	SCR_tde_Anl_ReturnValue eReturnValue = SCR_ERV_Anl_NormalReturn;
	char szLevelName[100];
	char szSectionName[150];
	BOOL	bLoadMapParsed;
/*	int iBankId;*/
 
	_p_stFile=_p_stFile;
 
	if (M_IsTitle)
	{
#if defined (ACTIVE_EDITOR)
		g_bSectionSoundFoundInLevelDSC = TRUE;
#endif /*ACTIVE_EDITOR*/
 
/*		SND_fn_bStartLoadBanks();*/
#ifndef RETAIL
		SCR_M_RdL0_SetContextLong(0, 0, FALSE)
        if (SNA_M_bTestSaveGameDesc() || SNA_M_bTestSaveLevelDesc())
		{
			int a500_iArray[500];
			int iSize;
            SNA_fn_vWriteNoParamEntryToCurrentDscFile( SNA_C_ul_LevelDscLevelSoundBanks );

			if (SNA_M_bTestSaveGameDesc())
				SND_fn_vLoadSoundMap("Fix",TRUE);
			else
				SND_fn_vLoadSoundMap(fn_p_szGetLevelName(),TRUE);
	
			iSize = SND_fn_iGetLoadedBankArray(a500_iArray, 500);
			SNA_fn_vWriteIntArrayEntryToCurrentDscFile
			(
				  SNA_C_ul_LevelLoadMap,
				  iSize,
				  a500_iArray
			);
		}
#endif
	}
	else if (M_IsEntry)
	{
		if (M_ActionIs("LoadMap"))
		{
#ifndef RETAIL
			if (!(SNA_M_bTestSaveGameDesc() || SNA_M_bTestSaveLevelDesc()))
			{
				if (SCR_fn_c_RdL0_IsSectionExists(_ap_szParams[0]))
				{
					SND_fn_bStartLoadBanks();
					SCR_fnp_st_RdL0_AnalyseSection(_ap_szParams[0],SCR_CDF_uw_Anl_ForceAnalyse);
					SND_fn_bEndLoadBanks();
					SCR_M_RdL0_SetContextLong(0, 0, TRUE)
				}
			}
#endif
		}
/*		else if (M_ActionIs("LoadSoundBank"))
		{
			iBankId=atoi(_ap_szParams[0]);
	        if ( SNA_M_bTestSaveGameDesc() || SNA_M_bTestSaveLevelDesc() )
			{
				SNA_fn_vWriteLongEntryToCurrentDscFile
				(
				  SNA_C_ul_LevelLoadSoundBank,
				  (long)iBankId
				);
			}
 
			SND_fn_bInitBank(iBankId);
		}

*/	}
#ifndef RETAIL
	else if (M_IsEnd)
	{
		SCR_M_RdL0_GetContextLong(0, 0, long, bLoadMapParsed);
		if (!bLoadMapParsed)
		{
			/* load map from default lcb file */
			strcpy(szLevelName ,fn_p_szGetLevelName());
			strcpy(szSectionName,"Rayman2.lcb^SndMapE:");
			if (!strcmp(szLevelName,""))
				strcat(szSectionName,"Fix");
			else
				strcat(szSectionName,szLevelName);

			if (SCR_fn_c_RdL0_IsSectionExists(szSectionName))
			{
				SND_fn_bStartLoadBanks();
				SCR_fnp_st_RdL0_AnalyseSection(szSectionName,SCR_CDF_uw_Anl_ForceAnalyse);
				SND_fn_bEndLoadBanks();
			}
			
		}

        if ( SNA_M_bTestSaveGameDesc() || SNA_M_bTestSaveLevelDesc() )
			SNA_fn_vWriteNoParamEntryToCurrentDscFile( SNA_C_ulEndOfDescSection );
/*		SND_fn_bEndLoadBanks();*/
	}
#endif
	return(eReturnValue);
}
 
 
SCR_tde_Anl_ReturnValue fn_eScriptCallBackLevelSoundBankBlock(SCR_tdst_File_Description *_p_stFile,char *_p_szName,char *_ap_szParams[],SCR_tde_Anl_Action	_eAction)
{
	SCR_tde_Anl_ReturnValue eReturnValue = SCR_ERV_Anl_NormalReturn;
	int iBlockValue,iBankId;
 
	_p_stFile=_p_stFile;
 
	if (M_IsTitle)
	{
		iBlockValue=atoi(_ap_szParams[0]);
	}
	else if (M_IsEntry)
	{
		if (M_ActionIs("LoadSoundBank"))
		{
			iBankId=atoi(_ap_szParams[0]);
			SND_fn_bInitBank(iBankId);
		}
	}
	else if (M_IsEnd)
	{
	}
 
	return(eReturnValue);
}
 

// Try to find szSubString  in szString.
// Comparaison is case INSENSITIVE.
static const char *stristr( const char *szString, const char *szSubString )
{
	const char *p_szSrcCur;
	const char *p_szToFindCur;
	const char *p_szSrcStartFind;


	p_szSrcStartFind = szString; 
	p_szToFindCur    = szSubString;
	for( p_szSrcCur = szString; *p_szSrcCur && *p_szToFindCur; p_szSrcCur++ )
	{
		if( tolower( *p_szSrcCur ) == tolower( *p_szToFindCur ) )
		{
			if( ! p_szSrcStartFind )
				p_szSrcStartFind = p_szSrcCur;
			p_szToFindCur ++;
		}
		else
		{
			p_szToFindCur    = szSubString;
			p_szSrcStartFind = NULL;
		}
	}

	if( *p_szToFindCur == '\0' )
		return p_szSrcStartFind;

	return NULL;
}

/*-----------------------------------------------------------------------------
*  Description :   Callback script function
*-----------------------------------------------------------------------------
*  Input :         ...
*  Output :        void
*-----------------------------------------------------------------------------
*  Creation date : 29/08/96            Author : Francois
*-----------------------------------------------------------------------------
*  Modification date :                 Modification Author :
*  Modifications : For loading always of the fix too (not only level's always...)
*---------------------------------------------------------------------------*/
#if defined(WIN32) && defined(_DEBUG) /* on PC, and in debug versions */
#ifdef __cplusplus
extern "C"
{
#endif
	ACP_tdxBool g_bIsLoadingAnAlways = FALSE ;
#ifdef __cplusplus
}
#endif
#endif /* WIN32 && _DEBUG */

SCR_tde_Anl_ReturnValue fn_eScriptCallBackLevelAlways(SCR_tdst_File_Description *_p_stFile,char *_p_szName,char *_ap_szParams[],SCR_tde_Anl_Action	_eAction)
{
	SCR_tde_Anl_ReturnValue      eReturnValue = SCR_ERV_Anl_NormalReturn;
	HIE_tdxHandleToSuperObject   h_SupObject;
	static tdstEngineObject     *p_stEngineObject = NULL;
	SCR_tdst_Cxt_Values         *p_stValues ;
 
	_p_stFile=_p_stFile;
 
	if (M_IsTitle)
	{
		h_SupObject=NULL; /**** There's no super object for always character's*/
#if defined(WIN32) && defined(_DEBUG) /* on PC, and in debug versions */
		g_bIsLoadingAnAlways = TRUE ;
#endif /* WIN32 && _DEBUG */
		SCR_M_RdL0_SetSectionLong(C_ThisSection,0,h_SupObject);
	}
	else if (M_IsEntry)
	{
		if (M_ActionIs(C_LevelLinkCharacters))
		{
			VIG_fn_vAddToProgressBar(1);
			p_stValues = SCR_fnp_st_RdL0_AnalyseSection(_ap_szParams[0], SCR_CDF_uw_Anl_Normal);
			if(p_stValues)
				p_stEngineObject=(tdstEngineObject *)(p_stValues->a_ulValues[0]);
 
			/* Add an always model only if it hasn't already been added (for always in the fix)*/
			if( !fn_ucIsAnAlwaysModel( p_stEngineObject ) )
				fn_vAddAnAlwaysModel(p_stEngineObject);
 
			if( GAM_fn_bIsEngineInFixMode() )
			{
				SNA_g_stFixInfo.a20_stObjects[SNA_g_stFixInfo.ulNbObject]=p_stEngineObject;
				SNA_g_stFixInfo.ulNbObject++;
				SNA_g_stFixInfo.h_LastAlwaysInTheFix = LST2_M_DynamicGetLastElement(&(g_stAlways.ALW_h_LstAlwaysModel));
			}

			/* GuS : added this for ago text display. */
			if( ! g_AlphabetCharacterPointer && stristr( _ap_szParams[0], "alphabet" ) )
				g_AlphabetCharacterPointer = p_stEngineObject;

		}
		else if (M_ActionIs(C_LevelCharacterInitialState))
		{
			char szCompletFileName[_MAX_PATH];
			SCR_tdst_Link_Value *p_xIndex;
			SCR_M_RdL0_GetSectionLong(C_ThisSection,0,HIE_tdxHandleToSuperObject,h_SupObject);
 
			strcpy(szCompletFileName,fn_szGetFamiliesDataPath());
			strcat(szCompletFileName,"\\");
			strcat(szCompletFileName,_ap_szParams[0]);
			p_xIndex = SCR_fnp_st_Link_SearchKey(&g_st3DOSLinkTable.stState,szCompletFileName);
			if (p_xIndex!=NULL&&p_xIndex->eState==SCR_ELS_Link_Initialized)
				fn_v3dDataSetInitialState(p_stEngineObject->h_3dData,(tdxHandleToState)(p_xIndex->ulValue));
		}
/* ANNECY MT - 27/11/98 {*/
		else if (M_ActionIs(C_LevelCharacterTransparency))
		{   
			p_stEngineObject -> h_3dData -> ucTransparency = (unsigned char)atof( _ap_szParams[0] );
		}
/* END ANNECY MT }*/
	}
	else if (M_IsEnd)
	{
#if defined(WIN32) && defined(_DEBUG) /* on PC, and in debug versions */
		g_bIsLoadingAnAlways = FALSE ;
#endif /* WIN32 && _DEBUG */
		SCR_M_RdL0_GetSectionLong(C_ThisSection,0,HIE_tdxHandleToSuperObject,h_SupObject);
	}
 
	return(eReturnValue);
}
 
 
/*-----------------------------------------------------------------------------
*  Description :   Callback script function
*-----------------------------------------------------------------------------
*  Input :         ...
*  Output :        void
*-----------------------------------------------------------------------------
*  Creation date : 13/08/98            Author : Jacques Thénoz
*-----------------------------------------------------------------------------
*  Modification date :                 Modification Author :
*  Modifications :
*---------------------------------------------------------------------------*/
SCR_tde_Anl_ReturnValue fn_eScriptCallBackLevelUseSAIWithEditor(SCR_tdst_File_Description *_p_stFile,char *_p_szName,char *_ap_szParams[],SCR_tde_Anl_Action	_eAction)
{
#ifdef ACTIVE_EDITOR
	g_bUseSAIWithEditor = TRUE;
#endif /* ACTIVE_EDITOR */
	return SCR_ERV_Anl_NormalReturn;
}
 
 
 
/**************************************************************************/
void fn_vDeleteAllLevelReUsableSections(void)
{
#ifndef RETAIL
	GAM_PrintAllUsedStaticMemory();
#endif
#if defined(_DEBUG)
	GEO_fn_vPrintMemoryInformation();
	GAM_fn_vPrintMemoryInformation();
	SCR_fn_ul_Mem_GetAllocationSize(0,255);
#endif /* _DEBUG*/
	SCR_fn_v_Mem_DeleteWithMemLevel(GAM_C_LevelScriptPriority,GAM_C_LevelScriptPriority);
	SCR_fn_v_Mem_DeleteWithMemLevel(GAM_C_LevelDynamicScriptPriority,GAM_C_LevelDynamicScriptPriority);
	SCR_fn_v_Mem_ReduceMemory();
}
/**************************************************************************/
