/********************************************************************************/
/* Name     : FIRE																*/
/* Title    : KAMUI test program "FIRE" from VL									*/
/* Author   : VideoLogic Carlos Sarria / NEC Software Takeshi Muto				*/
/* Created  : July 1997 by VideoLogic											*/
/* Modified : Novenber 6. 1997 by Takeshi Muto for KAMUI						*/
/*            May 20, 1998 by Takeshi Muto for SET5								*/
/* Description :																*/
/* Copyright : 1997 by VideoLogic Limited. All rights reserved.					*/
/********************************************************************************/

#if 0
#define		_X86_
/* _X86_ flag for win95 : SET2 */
#endif

#define		_DISPLAY_STRING_
/* if defined then display strings on screen */

#define		_DISP_PERFORMANCE_
/* Display performance : for windows */

/* Set Display Mode */
#define NTSC 1

#define		SPEED			(1.0f)	/* move speed ( 1 to n ) */

#include	<math.h>
#include	<stdio.h>				/* for printf */
#include	<stdlib.h>
#include	<float.h>

#include	<shinobi.h>

#if defined(_X86_)
	#include	<time.h>				/* for time */
	#include	<windows.h>
#endif

#if 0
	#include	<io.h>					/* for _filelength */
	#include	<FCNTL.H>				/* for _open switches */
	#include	<malloc.h>
#endif

#include	"kamui.h"				/* for Kamui Call */
#include	"dispstr.h"				/* for DisplayString */

#define _KM_USE_VERTEX_MACRO_
#define _KM_USE_VERTEX_MACRO_L3_
#include	"kamuix.h"

#if defined(_DISP_PERFORMANCE_)
#if defined(_X86_)
#else
	#include    "QPF.H"                 /* for QueryPerformance */
#endif
#endif

/* Texture */
extern const unsigned char gsFace[];
extern const unsigned char gsFire[];
extern const unsigned char gsFirer[];
extern const unsigned char gsglass[];
extern const unsigned char gsTorso[];

/*#include <ddraw.h> */
/*#include <sgl.h> */

/*#include "frontend.h" */
#include "fire.h"  /* This is the file with 3D data */

#pragma warning (disable : 4244)  /* Disables float to double conversion warning */

/*#define RGBColour(r, g, b) ((sgl_uint32) (((sgl_uint32)(r&0x000000FF)<<16) | ((sgl_uint32)(g&0x000000FF) << 8) | (sgl_uint32)(b&0x000000FF))) */
#define	RGBColour(r, g, b)	((KMUINT32) (((r) << 16) | ((g) << 8) | (b)))
#define	RGBA(r, g, b, a)	((KMUINT32) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b)))

/* Macros for kamui */
#define		GetRED(col)			((KMFLOAT) ( ((col) & 0x00ff0000) >> 16 ) / 256.0f)
#define		GetGREEN(col)		((KMFLOAT) ( ((col) & 0x0000ff00) >>  8 ) / 256.0f)
#define		GetBLUE(col)		((KMFLOAT) ( ((col) & 0x000000ff)       ) / 256.0f)
#define		GetALPHA(col)		((KMFLOAT) ( ((col) & 0xff000000) >> 24 ) / 256.0f)

/* SGLŒÝŠ·TYPE */
typedef	KMUINT32	sgl_uint32;		/* type of sgl_uint32 */
typedef float		sgl_vector[3];	/* type of sgl_vector */
typedef float		sgl_2d_vec[2];	/* type of sgl_2d_vec */
typedef float		sgl_colour[3];	/* type of sgl_colour */
/* --------- */
/* SGLVERTEX */
/* --------- */
/* This structure is currently physically equivalent to Direct3D's D3DTLVERTEX */
/* (so one can be cast to the other), with the exception that Direct3D's u and */
/* v values must be multiplied by the 1/w value.  RAVE vertices already contain */
/* u/w and v/w. */
typedef struct tagSGLVERTEX
{
	/* Projected screen coordinates: */
	float		fX;		/* 0 <= fX < screen width (up to 1024) */
	float		fY;		/* 0 <= fY < screen height (up to 1024) */
	float		fZ;		/* 0.01 <= fZ <= 1, where 1 is infinite distance away */
	/* 1/w for the perspective projection (should be set to 1.0/fZ; fZ is */
	/* actually ignored): */
	float		fInvW;
	KMUINT32	u32Colour;			/* Material colour (D3DCOLOR format): */
	KMUINT32	u32Specular;		/* Specular colour (D3DCOLOR format): */
	float		fUOverW, fVOverW;	/* Texture coordinates: */
} SGLVERTEX, *PSGLVERTEX;

/****************************************************************************/
/**	Valuables for KAMUI *****************************************************/
/****************************************************************************/
	KMSTATUS			status;					/* return status of KAMUI API */
	KMVERSIONINFO		VersionInfo;			/* KAMUI Version information */
	KMSURFACEDESC		PrimarySurfaceDesc;		/* Primary frame buffer */
	KMSURFACEDESC		BackSurfaceDesc;		/* Back-buffer frame buffer */
	KMSURFACEDESC		Texture[10];			/* texture surface */
	KMVERTEXBUFFDESC	VertexBufferDesc;		/* Vertex-buffer */
	KMVERTEXCONTEXT		VertexContext;			/* Vertex context */

	PKMDWORD			BuffTex;				/* Pointer to texture */

	PKMSURFACEDESC			pFB[2];
	KMSYSTEMCONFIGSTRUCT	SystemConfig;
	PKMDWORD				dwDataPtr;


	int			frame;				
	int			frame_2 = 0;		
#if defined(_DISP_PERFORMANCE_)
	int			pcount_f;			/* Hight-resolution counter supported? */
	double		nFPS;				
	double		aFPS;				
	double		MxFPS;				
	double		MnFPS;				
	__int64 	Time3i;				
	__int64		freqi;				
	double		freq;				
	double		Time3;				
	double		maxTime = 0.00001;	
	double		minTime = 99999;	
	double		OldTime3;			
	double		nowTime;			
	double		totalTime	= 0;	
	double		aveTime;			
#if defined(_X86_)
	time_t		start_time;			
#endif
#endif

/*------------------------------- Global Variables -----------------------------------*/

#define PI	3.1416f

/*static int   Device, Init = TRUE; */
/*static int   frame = 0, Texture[100]; */
static float GlassRefect[4], Ligth1[3], Shad[255], CamFocus = 500.0;
static float YAng, XAng;
extern float XAng1 = 0.0 , YAng1 = 0.005f, LH=20.0;

/* SGLCONTEXT SGLContext; */
SGLVERTEX  *TempVert[NUM_MESHES];
SGLVERTEX  Fire[4][4];

void SetupTextures (void);
void SetupContext  (void);
void InitMeshes    (void);
void DrawAll       (void);
void UpdateVertex  (int Num);
void Shading       (int Num);
void CreateFire    (void);
static void ReadMaple (void);


/****************************************************************************/
/**	Check KAMUI function status *********************************************/
/****************************************************************************/
void	Check_Status(KMSTATUS status, char *func)
{
	switch(status) {
	case KMSTATUS_SUCCESS:
		/* No message is displayed when SUCCESS */
		break;
	case KMSTATUS_INVALID_DISPLAY_MODE:
		PRINTOUT(("%s:KMSTATUS_INVALID_DISPLAY_MODE\n",func)); break;
	case KMSTATUS_INVALID_VIDEO_MODE:
		PRINTOUT(("%s:KMSTATUS_INVALID_VIDEO_MODE\n",func)); break;
	case KMSTATUS_NOT_ENOUGH_MEMORY:
		PRINTOUT(("%s:KMSTATUS_NOT_ENOUGH_MEMORY\n",func)); break;
	case KMSTATUS_INVALID_TEXTURE_TYPE:
		PRINTOUT(("%s:KMSTATUS_INVALID_TEXTURE_TYPE\n",func)); break;
	case KMSTATUS_INVALID_MIPMAPED_TEXTURE:
		PRINTOUT(("%s:KMSTATUS_INVALID_MIPMAPED_TEXTURE\n",func)); break;
	case KMSTATUS_CANT_FLIP_SURFACE:
		PRINTOUT(("%s:KMSTATUS_CANT_FLIP_SURFACE\n",func)); break;
	case KMSTATUS_INVALID_ADDRESS:
		PRINTOUT(("%s:KMSTATUS_INVALID_ADDRESS\n",func)); break;
	case KMSTATUS_HARDWARE_NOT_PRESENTED:
		PRINTOUT(("%s:KMSTATUS_HARDWARE_NOT_PRESENTED\n",func)); break;
	case KMSTATUS_INVALID_SETTING:
		PRINTOUT(("%s:KMSTATUS_INVALID_SETTING\n",func)); break;
	case KMSTATUS_INVALID_VERTEX_TYPE:
		PRINTOUT(("%s:KMSTATUS_INVALID_VERTEX_TYPE\n",func)); break;
	case KMSTATUS_NOT_IMPLEMENTED:
		PRINTOUT(("%s:KMSTATUS_NOT_IMPREMENTED\n",func)); break;
	case KMSTATUS_INVALID_PARAMETER:
		PRINTOUT(("%s:KMSTATUS_INVALID_PARAMETER\n",func)); break;
	default:
		PRINTOUT(("%s:???Undefined status : %d\n", func, status));
		break;
	}
}

/****************************************************************************/
/**	Background surface setting **********************************************/
/****************************************************************************/
void	InitBackGround(void)
{
	KMSTATUS			status;
	KMVERTEXCONTEXT		BackVertexContext;		/* Vertex context */
	KMVERTEX_01			BV[3];					/* pointer to Vertex */
	PVOID				pBV[3];					/* pointer to Vertex */

	/* Clear VertexContext */
	memset(&BackVertexContext,0,sizeof(KMVERTEXCONTEXT));

	/* Setup VertexContext */
	BackVertexContext.RenderState	= KM_DEPTHMODE  		| KM_CULLINGMODE				/* ISP/TSP IW */
									| KM_SCREENCOORDINATION	| KM_SHADINGMODE
									| KM_MODIFIER 			| KM_ZWRITEDISABLE				/* TSP CW */
									| KM_SRCBLENDINGMODE
									| KM_SRCSELECT			| KM_DSTSELECT
									| KM_FOGMODE			| KM_USESPECULAR
									| KM_USEALPHA			| KM_IGNORETEXTUREALPHA
									| KM_FLIPUV 			| KM_CLAMPUV 
									| KM_FILTERMODE			| KM_SUPERSAMPLE
									| KM_MIPMAPDADJUST 		| KM_TEXTURESHADINGMODE
									| KM_PARAMTYPE 			| KM_LISTTYPE 					/* Param CW */
									| KM_COLORTYPE			| KM_USESPECULAR
									| KM_UVFORMAT;

	/* for ParameterControlWord  */
	BackVertexContext.ParamType				= KM_POLYGON;
	BackVertexContext.ListType				= KM_OPAQUE_POLYGON;
	BackVertexContext.ColorType				= KM_FLOATINGCOLOR;
	BackVertexContext.bUseSpecular			= FALSE;
	BackVertexContext.UVFormat				= KM_32BITUV;

	/* for ISP/TSP InstructionWord  */
	BackVertexContext.DepthMode				= KM_GREATER;
	BackVertexContext.CullingMode			= KM_NOCULLING;
	BackVertexContext.ScreenCoordination	= KM_SCREEN;
	BackVertexContext.ShadingMode			= KM_NOTEXTUREGOURAUD;
	BackVertexContext.SelectModifier		= KM_NOMODIFIER;
	BackVertexContext.bZWriteDisable		= FALSE;			/* not effective on ARC1 */

	/* for TSP ControlWord  */
	BackVertexContext.SRCBlendingMode		= KM_ONE;
/*	BackVertexContext.DSTBlendingMode		= KM_ZERO;	// must not set this parameter on background plane */
	BackVertexContext.bSRCSel				= FALSE;			/* not effective on ARC1 */
	BackVertexContext.bDSTSel				= FALSE;			/* not effective on ARC1 */
	BackVertexContext.FogMode				= KM_NOFOG;			/* 11 is reserved */
	BackVertexContext.bUseSpecular			= FALSE;
	BackVertexContext.bUseAlpha				= FALSE;
	BackVertexContext.ClampUV				= KM_NOCLAMP;
	BackVertexContext.FilterMode			= KM_POINT_SAMPLE;
	BackVertexContext.bSuperSample			= FALSE;
	BackVertexContext.MipMapAdjust			= 0x00000004;		/* D=1.00 */
	BackVertexContext.TextureShadingMode	= KM_MODULATE;
	
	/* for Texture ControlBit */

	/* No effect on ARC1 */
	BackVertexContext.bColorClamp			= FALSE;
	BackVertexContext.PaletteBank			= 0;

	/* for GlobalColorData */
	BackVertexContext.fFaceColorAlpha		= 1.0f;		/* Face Color Alpha */
	BackVertexContext.fFaceColorRed			= 1.0f;		/* Face Color Red */
	BackVertexContext.fFaceColorGreen		= 1.0f;		/* Face Color Green */
	BackVertexContext.fFaceColorBlue		= 1.0f;		/* Face Color Blue */
	BackVertexContext.fOffsetColorAlpha		= 1.0f;		/* Specular Color Alpha */
	BackVertexContext.fOffsetColorRed		= 1.0f;		/* Specular Color Red */
	BackVertexContext.fOffsetColorGreen		= 1.0f;		/* Specular Color Green */
	BackVertexContext.fOffsetColorBlue		= 1.0f;		/* Specular Color Blue */

	status = kmProcessVertexRenderState(&BackVertexContext);
	Check_Status(status, "kmProcessVertexRenderState");
	status = kmSetBackGroundRenderState(&BackVertexContext);
	Check_Status(status, "kmSetBackGroundRenderState");

	/*----------------------------------------------------------------------------------- */
	/* set VERTEX DATA */

	/* Vertex #1 */
	BV[0].ParamControlWord	= KM_VERTEXPARAM_NORMAL;
	BV[0].fX				=   0.0f;
	BV[0].fY				= 479.0f;
#if defined(_STRICT_UNION_)
	BV[0].u.fZ				=  0.0001f;
#else
	BV[0].fZ				=  0.0001f;
#endif
	BV[0].fBaseAlpha		=   0.0f;
	BV[0].fBaseRed			=   0.0f;
	BV[0].fBaseGreen		=   0.0f;
	BV[0].fBaseBlue			=   0.0f;

	/* Vertex #2 */
	BV[1].ParamControlWord	= KM_VERTEXPARAM_NORMAL;
	BV[1].fX				= 320.0f;
	BV[1].fY				=   0.0f;
#if defined(_STRICT_UNION_)
	BV[1].u.fZ				=  0.0001f;
#else
	BV[1].fZ				=  0.0001f;
#endif
	BV[1].fBaseAlpha		=   0.0f;
	BV[1].fBaseRed			=   0.05f;
	BV[1].fBaseGreen		=   0.05f;
	BV[1].fBaseBlue			=   0.05f;

	/* Vertex #3 */
	BV[2].ParamControlWord	= KM_VERTEXPARAM_ENDOFSTRIP;
	BV[2].fX				= 639.0f;
	BV[2].fY				= 479.0f;
#if defined(_STRICT_UNION_)
	BV[2].u.fZ				=  0.0001f;
#else
	BV[2].fZ				=  0.0001f;
#endif
	BV[2].fBaseAlpha		=   0.0f;
	BV[2].fBaseRed			=   0.0f;
	BV[2].fBaseGreen		=   0.0f;
	BV[2].fBaseBlue			=   0.0f;

	pBV[0] = &BV[0];
	pBV[1] = &BV[1];
	pBV[2] = &BV[2];

	/*----------------------------------------------------------------------------------- */
	/* set VERTEX */
	status = kmSetBackGroundPlane(	pBV,					/* pVertex */
									KM_VERTEXTYPE_01,		/* VertexType */
									sizeof(KMVERTEX_01)		/* StructSize */
									);
	Check_Status(status, "kmSetBackGroundPlane");
}

/****************************************************************************/
/**	kmtri_quads  by T.Hirata ************************************************/
/****************************************************************************/
void 
kmtri_quads (	KMVERTEXBUFFDESC	BufferDesc,
				KMVERTEXCONTEXT		VertexContext,
				int					nNumFaces,
				int					pFaces[][4],
				PSGLVERTEX			pVertices,
				int					bTexture)
{
	KMSTATUS	status;
	int			i;
	PSGLVERTEX	pVert;

	status = kmSetVertexRenderState(&VertexContext);
	Check_Status(status, "kmSetVertexRenderState");
	kmxxGetCurrentPtr(&BufferDesc);

	for(i = 0; i < nNumFaces; i++)
	{
		kmxxStartVertexStrip(&BufferDesc);
		if(bTexture == TRUE) {
			pVert = &pVertices[pFaces[i][0]];
			kmxxSetVertex_3(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->fUOverW,
							pVert->fVOverW,
							pVert->u32Colour,
							pVert->u32Specular
							);

			pVert = &pVertices[pFaces[i][1]];
			kmxxSetVertex_3(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->fUOverW,
							pVert->fVOverW,
							pVert->u32Colour,
							pVert->u32Specular
							);

			pVert = &pVertices[pFaces[i][3]];
			kmxxSetVertex_3(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->fUOverW,
							pVert->fVOverW,
							pVert->u32Colour,
							pVert->u32Specular
							);

			pVert = &pVertices[pFaces[i][2]];
			kmxxSetVertex_3(KM_VERTEXPARAM_ENDOFSTRIP,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->fUOverW,
							pVert->fVOverW,
							pVert->u32Colour,
							pVert->u32Specular
							);
		}
		else {	/* if(bTexture == TRUE) : NO-TEXTURE */
			pVert = &pVertices[pFaces[i][0]];
			kmxxSetVertex_0(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->u32Colour
							);

			pVert = &pVertices[pFaces[i][1]];
			kmxxSetVertex_0(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->u32Colour
							);

			pVert = &pVertices[pFaces[i][3]];
			kmxxSetVertex_0(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->u32Colour
							);

			pVert = &pVertices[pFaces[i][2]];
			kmxxSetVertex_0(KM_VERTEXPARAM_ENDOFSTRIP,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->u32Colour
							);
		} /* end of if(bTexture == TRUE) */
	}
	kmxxReleaseCurrentPtr(&BufferDesc);
}

/****************************************************************************/
/**	kmtri_triangles  by T.Hirata ********************************************/
/****************************************************************************/
void 
kmtri_triangles ( KMVERTEXBUFFDESC		BufferDesc,
				  KMVERTEXCONTEXT		VertexContext,
				  int  					nNumFaces,
				  int  					pFaces[][3],
				  PSGLVERTEX  			pVertices,
				  int					bTexture)
{
	KMSTATUS	status;
	int			i;
	PSGLVERTEX	pVert;

	status = kmSetVertexRenderState(&VertexContext);
	Check_Status(status, "kmSetVertexRenderState");
	kmxxGetCurrentPtr(&BufferDesc);

	for(i = 0; i < nNumFaces; i++)
	{
		kmxxStartVertexStrip(&BufferDesc);
		if(bTexture == TRUE) {
			pVert = &pVertices[pFaces[i][0]];
			kmxxSetVertex_3(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->fUOverW,
							pVert->fVOverW,
							pVert->u32Colour,
							pVert->u32Specular
							);

			pVert = &pVertices[pFaces[i][1]];
			kmxxSetVertex_3(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->fUOverW,
							pVert->fVOverW,
							pVert->u32Colour,
							pVert->u32Specular
							);

			pVert = &pVertices[pFaces[i][2]];
			kmxxSetVertex_3(KM_VERTEXPARAM_ENDOFSTRIP,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->fUOverW,
							pVert->fVOverW,
							pVert->u32Colour,
							pVert->u32Specular
							);
		}
		else {	/* if(bTexture == TRUE) : NO-TEXTURE */
			pVert = &pVertices[pFaces[i][0]];
			kmxxSetVertex_0(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->u32Colour
							);

			pVert = &pVertices[pFaces[i][1]];
			kmxxSetVertex_0(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->u32Colour
							);

			pVert = &pVertices[pFaces[i][2]];
			kmxxSetVertex_0(KM_VERTEXPARAM_ENDOFSTRIP,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							pVert->u32Colour
							);
		} /* end of if(bTexture == TRUE) */
	}
	kmxxReleaseCurrentPtr(&BufferDesc);
}

/****************************************************************************/
/**	Initialize Vertex Context ***********************************************/
/****************************************************************************/
void	InitVertexContext(PKMVERTEXCONTEXT pVertexContext)
{
	
	pVertexContext->RenderState	= KM_DEPTHMODE  		| KM_CULLINGMODE
								| KM_SCREENCOORDINATION	| KM_SHADINGMODE
								| KM_MODIFIER 			| KM_ZWRITEDISABLE
								| KM_SRCBLENDINGMODE	| KM_DSTBLENDINGMODE
								| KM_SRCSELECT			| KM_DSTSELECT
								| KM_FOGMODE			| KM_USESPECULAR
								| KM_USEALPHA			| KM_IGNORETEXTUREALPHA
								| KM_FLIPUV 			| KM_CLAMPUV 
								| KM_FILTERMODE			| KM_SUPERSAMPLE
								| KM_MIPMAPDADJUST 		| KM_TEXTURESHADINGMODE
								| KM_PARAMTYPE 			| KM_LISTTYPE
								| KM_COLORTYPE			| KM_USESPECULAR
								| KM_UVFORMAT;

	/* for ParameterControlWord  */
	pVertexContext->ParamType			= KM_POLYGON;
	pVertexContext->ListType			= KM_OPAQUE_POLYGON;
	pVertexContext->ColorType			= KM_PACKEDCOLOR;
	pVertexContext->bUseSpecular		= FALSE;
	pVertexContext->UVFormat			= KM_32BITUV;

	/* for ISP/TSP InstructionWord  */
	pVertexContext->DepthMode			= KM_GREATER;
/*	pVertexContext->CullingMode			= KM_NOCULLING; */
	pVertexContext->CullingMode			= KM_CULLSMALL;
	pVertexContext->ScreenCoordination	= KM_SCREEN;
	pVertexContext->ShadingMode			= KM_NOTEXTUREGOURAUD;
	pVertexContext->SelectModifier		= KM_NOMODIFIER;
	pVertexContext->bZWriteDisable		= FALSE;			

	/* for TSP ControlWord  */
	pVertexContext->SRCBlendingMode		= KM_ONE;
	pVertexContext->DSTBlendingMode		= KM_ZERO;
	pVertexContext->bSRCSel				= FALSE;			
	pVertexContext->bDSTSel				= FALSE;			
	pVertexContext->FogMode				= KM_NOFOG;			
	pVertexContext->bUseSpecular		= FALSE;
	pVertexContext->bUseAlpha			= FALSE;
	pVertexContext->FlipUV				= KM_NOFLIP;
	pVertexContext->ClampUV				= KM_NOCLAMP;
/*	pVertexContext->FilterMode			= KM_POINT_SAMPLE; */
	pVertexContext->FilterMode			= KM_BILINEAR;
	pVertexContext->bSuperSample		= FALSE;
	pVertexContext->MipMapAdjust		= 0x00000004;		/* D=1.00 */
	pVertexContext->TextureShadingMode	= KM_MODULATE;
/*	pVertexContext->TextureShadingMode	= KM_MODULATE_ALPHA; */
	
	/* for Texture ControlBit */

	/* No effect on ARC1 */
	pVertexContext->bColorClamp		= FALSE;
	pVertexContext->PaletteBank		= 0;

	/* for GlobalColorData */
	pVertexContext->fFaceColorAlpha		= 1.0f;		/* Face Color Alpha */
	pVertexContext->fFaceColorRed		= 1.0f;		/* Face Color Red */
	pVertexContext->fFaceColorGreen		= 1.0f;		/* Face Color Green */
	pVertexContext->fFaceColorBlue		= 1.0f;		/* Face Color Blue */
	pVertexContext->fOffsetColorAlpha	= 1.0f;		/* Specular Color Alpha */
	pVertexContext->fOffsetColorRed		= 1.0f;		/* Specular Color Red */
	pVertexContext->fOffsetColorGreen	= 1.0f;		/* Specular Color Green */
	pVertexContext->fOffsetColorBlue	= 1.0f;		/* Specular Color Blue */

	kmProcessVertexRenderState(pVertexContext);
}

#if 0
/****************************************************************************/
/**	Load texture ************************************************************/
/****************************************************************************/
PKMDWORD LoadTextureFile(char *filename)
{
	int			hFile;
	long		filelen;
	PKMDWORD	pTexture;

	/* Open input file */
	hFile = _open(filename, _O_RDONLY | _O_BINARY);
	if(hFile != -1) {
		filelen = _filelength(hFile);			/* length of texture file */
		pTexture = (PKMDWORD)malloc(filelen);	/* allocate mainmemory */
		_read(hFile, pTexture, filelen);		/* read in texture file */
		_close(hFile);							/* file close */
		printf("LoadTextureFile: Texture file %s load OK.\n",filename);
	}
	else {
		printf("LoadTextureFile: ??ERROR Can not read texture file %s .\n",filename);
	}
	return pTexture;
}
#endif

/*-------------------------------------------------------------------------------------*/
/*  Function Name   :   SetupScene                                                     */
/*  Inputs          :   None                                                           */
/*  Outputs         :   None                                                           */
/*  Returns         :   Error message or 0                                             */
/*  Globals Used    :   Device                                                         */
/*  Description     :   This routine is used to set SGL device and setup some values.  */
/*                      This routine is called from FRONTEND.C                         */
/*-------------------------------------------------------------------------------------*/
int SetupScene (void)
{
/*	Device = sgl_create_screen_device (0, 640, 480, sgl_device_16bit, TRUE); */
/*	if (Device<0) return ERR_CREATE_SCREEN_DEVICE; */

	/*----------------------------------------------------------------------------------- */
	/* Initialize Hardware */

#if NTSC
	sbInitSystem( NJD_RESOLUTION_640x480_NTSCNI, NJD_FRAMEBUFFER_MODE_RGB565, 1 );
#else
	sbInitSystem( NJD_RESOLUTION_VGA, NJD_FRAMEBUFFER_MODE_RGB565, 1 );
#endif

	kmGetVersionInfo(&VersionInfo);
#if 0
	PRINTOUT(("MajorVersion      0x0%08x\n",VersionInfo.kmMajorVersion));
	PRINTOUT(("LocalVersion      0x0%08x\n",VersionInfo.kmLocalVersion));
	PRINTOUT(("kmFrameBufferSize 0x0%08x\n",VersionInfo.kmFrameBufferSize));
#endif

	/*----------------------------------------------------------------------------------- */
	/* Create frame buffer and vertex buffer */

	pFB[0] = &PrimarySurfaceDesc;
	pFB[1] = &BackSurfaceDesc;

	/* VertexBufferPointer(set5) */
	dwDataPtr = (PKMDWORD)0xACB00000;

	SystemConfig.dwSize	=	sizeof(KMSYSTEMCONFIGSTRUCT);
	SystemConfig.flags	=	KM_CONFIGFLAG_ENABLE_CLEAR_FRAMEBUFFER;

	/* for Frame buffer */
	SystemConfig.ppSurfaceDescArray	=	pFB;	/* Array of SurfaceDesc	pointer     */
	SystemConfig.nNumOfFrameBuffer	=	2;		/* Number Of Frame Buffer			*/
	SystemConfig.nWidth				=	0;		/* Width of Frame buffer			*/
	SystemConfig.nHeight			=	0;		/* Height of Frame buffer			*/
	SystemConfig.nBpp				=	0;		/* Bit Per Depth for Frame buffer	*/
	/* for Texture Memory */
	SystemConfig.nTextureMemorySize	=	262144 * 2;	/* Texture Memory size : 1MB * 2 */
	/* for Vertex buffer */
	SystemConfig.pBufferDesc		=	&VertexBufferDesc;	/* pointer to VERTEXBUFFDESC 		*/
	SystemConfig.pVertexBuffer		=	dwDataPtr;			/* pointer to Vertex buffer 		*/
	SystemConfig.nVertexBufferSize	=	262144 * 2;	/* size of Vertex buffer : 1MB * 2 */
	SystemConfig.fBufferSize[0]		=	50.0f;		/* Opaque polygon buffer size        : 35% */
	SystemConfig.fBufferSize[1]		=	 0.0f;		/* Opaque modifier buffer size       :  0% */
	SystemConfig.fBufferSize[2]		=	50.0f;		/* Trans polygon buffer size         : 30% */
	SystemConfig.fBufferSize[3]		=	 0.0f;		/* Trans modifier buffer size        :  0% */
	SystemConfig.fBufferSize[4]		=	 0.0f;		/* Punchthrough polygon buffer size  : 35% */

	SystemConfig.nVbufModel			=	 KM_VERTEXBUFMODEL_NORMAL;	/* VertexBuffer Model		*/
	status = kmSetSystemConfiguration( &SystemConfig );
	Check_Status(status, "kmSetSystemConfiguration");

	/*-----------------------------------------------------------------------------------*/
	/* Initialize DisplayString routine */
	txt_InitDisplayString();

	/*-----------------------------------------------------------------------------------*/
	/* some initializes */
    SetupTextures ();
	SetupContext  ();
    InitMeshes ();

	InitBackGround();		/* Setup background plane */

	/*-----------------------------------------------------------------------------------*/
	/* Set Culling Register */
	status = kmSetCullingRegister(1.0f);
	Check_Status(status, "kmSetCullingRegister");

	/*-----------------------------------------------------------------------------------*/
	

	frame		= 0;

#if defined(_DISP_PERFORMANCE_)
	totalTime	= 0;

	pcount_f = QueryPerformanceFrequency((LARGE_INTEGER*)&freqi);	
	if(pcount_f) {	
		QueryPerformanceCounter((LARGE_INTEGER*)&Time3i);	
		freq = 1000.0f / (double)freqi;						
		OldTime3 = Time3 = (double)Time3i * freq;			
	}
	else {	
		Time3 = (double)timeGetTime();						
	}

	/* Get AP start time ---------------------------------------------*/
#if defined(_X86_)
	 time( &start_time );
#endif
#endif	/* defined(_DISP_PERFORMANCE_) */

	 return 0;
}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   :   NextFrame                                                      */
/*  Inputs          :   None                                                           */
/*  Outputs         :   None                                                           */
/*  Returns         :   None                                                           */
/*  Globals Used    :   SGLContext                                                     */
/*  Description     :   Drawing everything and rendering.                              */
/*                      This routine is called from FRONTEND.C                         */
/*-------------------------------------------------------------------------------------*/
void NextFrame()
{
#if defined(_X86_)
	time_t		ltime;
#endif
/*   sgltri_startofframe (&SGLContext); */
	 DrawAll ();
/*   sgltri_render   (&SGLContext); */

	txt_SetCursor(0,1);
#if defined(_DISP_PERFORMANCE_)
	/* Write Date & Time on screen ---------------------------------------------*/
#if defined(_X86_)
	 time( &ltime );
    PRINTOUT(("START:%s", ctime( &start_time )));
    PRINTOUT(("NOW  :%s", ctime( &ltime )));
#endif
	/* Write FPS on screen -----------------------------------------------------*/
	PRINTOUT(("FRAME:%06d%06d Now:%07.3fFPS, Ave:%07.3fFPS\n",frame_2, frame,nFPS,aFPS));
#else
	PRINTOUT(("FRAME:%06d%06d\n",frame_2, frame));
#endif	/* defined(_DISP_PERFORMANCE_) */

	/*-----------------------------------------------------------------------------------*/
	/* Rendering start */
#if defined(_DISPLAY_STRING_)
	txt_DispScreen(VertexBufferDesc);		/* Display screen */
#endif
	status = kmRender();
	Check_Status(status, "kmRender");

	/*----------------------------------------------------------------------------------- */
	/* Flip screen */
	status = kmFlipFrameBuffer();
	Check_Status(status, "kmFlipFrameBuffer");

	pdExecPeripheralServer();


#if defined(_DISP_PERFORMANCE_)
	
	if(pcount_f) {
		QueryPerformanceCounter((LARGE_INTEGER*)&Time3i);	
		OldTime3 = Time3; Time3 = (double)Time3i * freq;
	}
	else {
		OldTime3 = Time3; Time3 = (double)timeGetTime();	
	}


	nowTime = Time3 - OldTime3;					
	if((nowTime > 1000.0f)||(nowTime < 1.0f)) nowTime = 20.0f;		
	if(nowTime > maxTime) maxTime = nowTime;	
	if(nowTime < minTime) minTime = nowTime;	

	totalTime += nowTime;										
	aveTime = totalTime / ((double)frame + 1.0f);		

	nFPS  = 1000.0f / (double)nowTime;
	aFPS  = 1000.0f / (double)aveTime;
	MxFPS = 1000.0f / (double)minTime;
	MnFPS = 1000.0f / (double)maxTime;
#endif	/* defined(_DISP_PERFORMANCE_) */

	frame++;
	if(frame > 1000000) {	
		frame = 0;
#if defined(_DISP_PERFORMANCE_)
		totalTime = 0;
#endif	/* defined(_DISP_PERFORMANCE_) */
		frame_2++;
	}

}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   :   Finish                                                         */
/*  Inputs          :   None                                                           */
/*  Outputs         :   None                                                           */
/*  Returns         :   None                                                           */
/*  Globals Used    :   Device                                                         */
/*  Description     :   Free textures and close device.                                */
/*                      This routine is called from FRONTEND.C                         */
/*-------------------------------------------------------------------------------------*/
void Finish()
{
/*		FreeAllBMPTextures (); */
/*		sgl_delete_device(Device); */
/*		Init = FALSE; */

	/*----------------------------------------------------------------------------------- */
	/* Free vertex buffer */
	status = kmDiscardVertexBuffer(&VertexBufferDesc);
	Check_Status(status, "kmDiscardVertexBuffer");

	/*----------------------------------------------------------------------------------- */
	/* End display */
	status = kmStopDisplayFrameBuffer();
	Check_Status(status, "kmStopDisplayFrameBuffer");
}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   :  DrawAll                                                         */
/*  Inputs          :  None                                                            */
/*  Outputs         :  None                                                            */
/*  Returns         :  None                                                            */
/*  Globals Used    :  XAng, YAng, XAng1, YAng1, SGLContext                            */
/*  Description     :  Updates and draws all the meshes in the model.                  */
/*  Note            :  The definition of Mesh[i] struct is in logo.h                   */
/*-------------------------------------------------------------------------------------*/
void DrawAll()
{
register i;

     YAng += (YAng1 / SPEED);

    for (i=0; i<NUM_MESHES; i++){

        UpdateVertex (i);   /* Recalculate SGL vertices for the new position */
        Shading      (i);   /* Smooth shading */

		/* Updating texture parameters for each mesh of the model */
/*		SGLContext.nTextureName = Texture[Mesh[i].Material]; */
/*		SGLContext.u32Flags = SGLTT_TEXTURE | SGLTT_GOURAUD | SGLTT_BILINEAR; */
		/* Set shading mode */
		VertexContext.RenderState	|= KM_SHADINGMODE;
		VertexContext.ShadingMode	= KM_TEXTUREGOURAUD;
		/* Set texture surface */
		VertexContext.pTextureSurfaceDesc	= &Texture[Mesh[i].Material];

        if ((i == FIRE) || (i == REFLECTION))  {	/* Texture-trans polygon */
			/* */
			VertexContext.RenderState	|= KM_SRCBLENDINGMODE;
			VertexContext.SRCBlendingMode	= KM_SRCALPHA;
			/* */
			VertexContext.RenderState	|= KM_DSTBLENDINGMODE;
			VertexContext.DSTBlendingMode	= KM_INVSRCALPHA;
			/* */
			VertexContext.RenderState	|= KM_LISTTYPE;
			VertexContext.ListType  = KM_TRANS_POLYGON;
			/* */
			VertexContext.RenderState	|= KM_TEXTURESHADINGMODE;
			VertexContext.TextureShadingMode	= KM_MODULATE;
			/* */
			VertexContext.RenderState	|= KM_USEALPHA;
			VertexContext.bUseAlpha = TRUE;
		}
		else {	/* Opaque polygon */
			/* */
			VertexContext.RenderState	|= KM_SRCBLENDINGMODE;
			VertexContext.SRCBlendingMode	= KM_ONE;
			/* */
			VertexContext.RenderState	|= KM_DSTBLENDINGMODE;
			VertexContext.DSTBlendingMode	= KM_ZERO;
			/* */
			VertexContext.RenderState	|= KM_LISTTYPE;
			VertexContext.ListType  = KM_OPAQUE_POLYGON;
			/* */
			VertexContext.RenderState	|= KM_TEXTURESHADINGMODE;
			VertexContext.TextureShadingMode	= KM_MODULATE;
			/* */
			VertexContext.RenderState	|= KM_USEALPHA;
			VertexContext.bUseAlpha = FALSE;
		}

		/* Process & Set Texture */
		status = kmProcessVertexRenderState(&VertexContext);
		Check_Status(status, "kmProcessVertexRenderState");

		/* Draws everything */
		if (i==FIRE) CreateFire();
/*	    else sgltri_triangles (&SGLContext, Mesh[i].NumFaces, (int(*)[3])Mesh[i].Faces, TempVert[i]); */
		else
		kmtri_triangles (	VertexBufferDesc,			/* KMVERTEXBUFFDESC	BufferDesc, */
							VertexContext,				/* KMVERTEXCONTEXT		VertexContext, */
							Mesh[i].NumFaces,			/* int  nNumFaces, */
							(int(*)[3])Mesh[i].Faces,	/* int  pFaces[][3], */
							TempVert[i],				/* PSGLVERTEX  pVertices */
							TRUE						/* int	bTexture */
							);
    }
}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   : SetupTextures                                                    */
/*  Inputs          : None                                                             */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : NumMaterials, Texture, MatInfo                                   */
/*  Description     : Loads BMP files getting the information from MatInfo struct      */
/*-------------------------------------------------------------------------------------*/
void SetupTextures (void)
{
register i;
	PKMDWORD			pTexture01;				/* Pointer to texture */
	KMTEXTURETYPE		nTextureType;			/* texture type definition */

  for (i=0;i<NumMaterials; i++)
  {
		if (i==MFIRE) { /* Translucent texture */
/*			Texture[i]  = LoadBMPTexture (MatInfo[i].MatFile, TRUE , FALSE, FALSE); */

	/*----------------------------------------------------------------------------------- */
	/* Create texture surface */
	nTextureType = KM_TEXTURE_TWIDDLED | KM_TEXTURE_ARGB4444;	/* Set texture type */
	status = kmCreateTextureSurface(
		&Texture[i],			/* OUT	PKMSURFACEDESC	pSurfaceDesc */
		128,					/*	IN	KMINT32			nWidth  */
		128,					/*	IN	KMINT32			nHeight  */
		nTextureType			/*	IN	KMTEXTURETYPE	nTextureType */
	);
	Check_Status(status, "kmCreateTextureSurface(ARGB)");
	/*----------------------------------------------------------------------------------- */
	/* Load and set texture */
/*--
	pTexture01 =  LoadTextureFile(MatInfo[i].MatFile);
--*/
	pTexture01 = (unsigned long *)&gsFire;
	status = kmLoadTexture(&Texture[i],			/* PKMSURFACEDESC pSurfaceDesc */
							pTexture01 + (16 / sizeof(KMDWORD)),			/* PKMDWORD pTexture */
							FALSE,				/* KMBOOLEAN bAutoMipMap */
							FALSE				/* KMBOOLEAN bDither */
							);
	Check_Status(status, "kmLoadTexture(ARGB)");
/*
	free(pTexture01);
*/
		}
		else { /* Opaque texture */
/*			Texture[i]  = LoadBMPTexture (MatInfo[i].MatFile, FALSE, FALSE, FALSE); */

	/*----------------------------------------------------------------------------------- */
	/* Create texture surface */
	nTextureType = KM_TEXTURE_TWIDDLED | KM_TEXTURE_RGB565;	/* Set texture type */
	status = kmCreateTextureSurface(
		&Texture[i],			/* OUT	PKMSURFACEDESC	pSurfaceDesc */
		128,					/*	IN	KMINT32			nWidth  */
		128,					/*	IN	KMINT32			nHeight  */
		nTextureType			/*	IN	KMTEXTURETYPE	nTextureType */
	);
	Check_Status(status, "kmCreateTextureSurface(RGB)");
	/*----------------------------------------------------------------------------------- */
	/* Load and set texture */
/*--
	pTexture01 =  LoadTextureFile(MatInfo[i].MatFile);
--*/
	switch(i){
	default:
	case 0:	pTexture01 = (unsigned long *)&gsFace; break;
	case 1:	pTexture01 = (unsigned long *)&gsglass; break;
	case 2:	pTexture01 = (unsigned long *)&gsTorso; break;
	case 3:	pTexture01 = (unsigned long *)&gsFirer; break;
	case 4:	pTexture01 = (unsigned long *)&gsFire; break;
	}
	status = kmLoadTexture(&Texture[i],			/* PKMSURFACEDESC pSurfaceDesc */
							pTexture01 + (16 / sizeof(KMDWORD)),			/* PKMDWORD pTexture */
							FALSE,				/* KMBOOLEAN bAutoMipMap */
							FALSE				/* KMBOOLEAN bDither */
							);
	Check_Status(status, "kmLoadTexture(ARGB)");
/*
	free(pTexture01);
*/
		}
  }

}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   : SetupContext                                                     */
/*  Inputs          : None                                                             */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : SGLContext                                                       */
/*  Description     : Sets default values for the render context.                      */
/*-------------------------------------------------------------------------------------*/
void SetupContext (void)
{
/*	SGLContext.bFogOn               = FALSE; */
/*	SGLContext.fFogR                = 0.3f; */
/*	SGLContext.fFogG                = 0.7f; */
/*	SGLContext.fFogB                = 0.7f; */
/*	SGLContext.u32FogDensity        = 5; */
/*	SGLContext.bCullBackfacing      = FALSE; */
/*	SGLContext.u32Flags             = SGLTT_TEXTURE | SGLTT_GOURAUD | SGLTT_BILINEAR; */
/*	SGLContext.nTextureName         = 0; */
/*	SGLContext.bDoClipping          = TRUE; */
/*	SGLContext.cBackgroundColour[0] = 0.0f; */
/*	SGLContext.cBackgroundColour[1] = 0.0f; */
/*	SGLContext.cBackgroundColour[2] = 0.0f; */
/*	SGLContext.eShadowLightVolMode  = NO_SHADOWS_OR_LIGHTVOLS; */
/*	SGLContext.bFlipU               = FALSE; */
/*	SGLContext.bFlipV               = FALSE; */
/*	SGLContext.bDoUVTimesInvW       = TRUE; */
/*	SGLContext.RenderRegions        = 0; */
/*	SGLContext.n32MipmapOffset      = 0; */
/*	SGLContext.u32GlobalTrans       = 255; */
/*	SGLContext.eFilterType          = sgl_tf_bilinear; */

	/*-------------------------------------------------------------------------------- */
	/* Initialize Vertex Context */
	/*-------------------------------------------------------------------------------- */
	memset( &VertexContext, 0, sizeof(VertexContext));	/* Crear Context */
	InitVertexContext(&VertexContext);					/* Initialize context */
}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   : InitMeshes                                                       */
/*  Inputs          : None                                                             */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : Shad, Mesh, TempVert, GlassReflect                               */
/*  Description     : Sets initials values for meshes managing                         */
/*-------------------------------------------------------------------------------------*/
void InitMeshes (void)
{
float Col;
register i,j, k=0;
#if defined(_X86_)
#else
/* SET4/SET5 */
int mptr = 0x0c400000;
#endif

    /* This function is in logo.h and creates an array of structures with 3D data */
    CreateMeshesArray ();

    /* Shad is a 255 values array with information for smooth shading */
    for (i=0; i<120; i++) { Col = (float)(120-i)/4; Shad[k++] = 0;}
    for (i=0; i<100; i++) { Col=(float)(i*255)/100; Shad[k++] = (float) i/100.0;}
    for (i=0; i<35;  i++)                    Shad[k++] = 1.0f;

#if defined(_X86_)
	/* Memory allocation for TempVert and TempNormals */
	for (i=0; i<NUM_MESHES; i++) {
		TempVert[i] = (SGLVERTEX *) malloc (Mesh[i].NumVertex*sizeof(SGLVERTEX));
	}
#else
	for (i=0; i<NUM_MESHES; i++)
	{
		TempVert[i] = (SGLVERTEX *)mptr; mptr += Mesh[i].NumVertex*sizeof(SGLVERTEX);
	}
#endif

	/* Setting UV values for all the meshes*/
    for (j=0; j<NUM_MESHES;j++)
	{
            for (i=0; i<Mesh[j].NumVertex; i++)
			{
               (TempVert[j]+i)->fUOverW    =  (Mesh[j].TexMap) ? *(Mesh[j].UV+i*2+0) : 0;
               (TempVert[j]+i)->fVOverW    =  (Mesh[j].TexMap) ? *(Mesh[j].UV+i*2+1) : 0;
            }

    }

   /* Reference position for glasses reflection */
   for (i=0;i<4;i++) GlassRefect[i] = *(Mesh[REFLECTION].Vertex+i*3+2);
}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   : UpdateVertex                                                     */
/*  Inputs          : Num (the mesh in the model)                                      */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : XAng, YAng                                                       */
/*  Description     : Turns vertices around two axes.                                  */
/*-------------------------------------------------------------------------------------*/
void UpdateVertex (int Num)
{
sgl_vector Temp;
int i, j=0, k=0, l=0;
float x, y, z, CosX, SinX, CosY, SinY, CamZ;

CosX = cos(XAng); SinX = sin(XAng);
CosY = cos(YAng); SinY = sin(YAng);

    for (i=0; i<Mesh[Num].NumVertex; i++){

		 x = *(Mesh[Num].Vertex+k++)-GroupCenter[0];
         y = *(Mesh[Num].Vertex+k++)-GroupCenter[1];
         z = *(Mesh[Num].Vertex+k++)-GroupCenter[2];

		 /* Temp is the outcome vertex after the rotation */
         Temp[0]  = x * CosY - z * SinY;
         Temp[2]  = z * CosY + x * SinY;

         z        = Temp[2];
         Temp[1]  = y * CosX - z * SinX;
         Temp[2]  = z * CosX + y * SinX + 800;

         if (Temp[2] <=0.0) Temp[2] = 0.001f;

		  /* We store the SGL vertex in TempVert */
         CamZ = 1.0/(Temp[2]);
         (TempVert[Num]+i)->fX    =  CamFocus * CamZ * Temp[0] + 320;
         (TempVert[Num]+i)->fY    = -CamFocus * CamZ * Temp[1] + 240;
	     (TempVert[Num]+i)->fInvW =  CamZ;
   }

}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   : Shading                                                          */
/*  Inputs          : Num                                                              */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : Light1, Mesh, TempVert                                           */
/*  Description     : Shades a mesh.                                                   */
/*-------------------------------------------------------------------------------------*/
void Shading (int Num)
{
float TempCo, TCo, Dir;
float Sh, LTemp[3], sl, x,y,z;
register l=0, i;
unsigned k=0;
sgl_uint32 Col;


    /* We move the position for simulating a dinamic light */
    if (Num != FIRER) { Ligth1[0] = 1; Ligth1[2]=0.2 + 0.1*sin(frame/1.5); Ligth1[1] = 0;}
    else              { Ligth1[0] = 0; Ligth1[1]=1; Ligth1[2] = 0;}

    if (Num == FIRE) return;

    /* We just rotate the light vector in the opposite direction instead of rotating all the normals */
    Dir = sqrt (Ligth1[0]*Ligth1[0]+Ligth1[1]*Ligth1[1]+Ligth1[2]*Ligth1[2]);
    LTemp[0] = Ligth1[0]/Dir;
	LTemp[1] = Ligth1[1]/Dir;
	LTemp[2] = Ligth1[2]/Dir;


    k = Mesh[Num].Material;

    sl = LH/60.0;

    TempCo = 255.0 * sl;

    if (Num == REFLECTION){
       if (LH<20) sl = 20.0f/60.0f;
       TempCo = 255.0*sl;
    }

    for (i=0; i<Mesh[Num].NumVertex; i++){

        x = *(Mesh[Num].Normals+l++);
        y = *(Mesh[Num].Normals+l++);
        z = *(Mesh[Num].Normals+l++);

		/* Sh is a value from 0.0 to 1.0 depending on the angle between a normal */
		/* and the light direction.                                              */
        Sh = fabs( LTemp[0] * x + LTemp[1] * y + LTemp[2] * z + 1.0);

        TCo = Shad[(int)(127.0*Sh)];

        Col = (int)(TempCo*TCo);

        /* Setting vertex colour */
        (TempVert[Num]+i)->u32Colour  = RGBColour (Col, Col, Col);
    }

}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   : CreateFire                                                       */
/*  Inputs          : None                                                             */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : TempVert, SGLContext, LH                                         */
/*  Description     : Creates fire poligons and shows the front face always.           */
/*-------------------------------------------------------------------------------------*/
void CreateFire (void)
{
register i,j, k;
float Ax, Ay, Bx, By, Bz, Sh, Ch, h, w;
float UVFire[][2] = {{ 1.000000f, 1.000000f },   { 0.000000f, 1.000000f },
                     { 0.000000f, 0.000000f },   { 1.000000f, 0.000000f } };
int   FFire []    = {0, 1, 2, 3};


    for (k=0; k<1; k++)
	{
        for (j=0; j<4; j++)
		{
            Ax = (TempVert[FIRE]+j+4)->fX;
            Ay = (TempVert[FIRE]+j+4)->fY;

            Bx = (TempVert[FIRE]+j+0)->fX;
            By = (TempVert[FIRE]+j+0)->fY;
            Bz = (TempVert[FIRE]+j+0)->fInvW;

	        /* Growing up and down the flames (LH is the value)*/
            Sh = LH*(By-Ay)/5.0;
            Ch = 200.0*Bz*LH;
            /* Moving vertices a little bit to simulating dinamic light */
            h =  Sh + (Sh/8.0) * sin((j/2+k*2+frame)/1.0);
            w =  Ch + (Ch/4.0) * cos((k*4+frame)/1.0);

	       /* Building 4 poligons (4 flames) */
           for (i=0; i<4; i++)
		   {
               Fire[j][i].fUOverW    =  UVFire[i][0];
               Fire[j][i].fVOverW    =  UVFire[i][1];
               Fire[j][i].u32Colour  =  0xFFFFFF;
               Fire[j][i].fUOverW    =  UVFire[i][0];
               Fire[j][i].fVOverW    =  UVFire[i][1];
               Fire[j][i].fInvW      =  (TempVert[FIRE]+j)->fInvW;
		   }

           Fire[j][0].fX =  Ax - w;
           Fire[j][0].fY =  Ay - h;

           Fire[j][1].fX =  Ax + w;
           Fire[j][1].fY =  Ay - h;

           Fire[j][2].fX =  Bx + w;
           Fire[j][2].fY =  By;

           Fire[j][3].fX =  Bx -w;
           Fire[j][3].fY =  By;

          /* Drawing quads... */
/*		sgltri_quads (&SGLContext, 1, &FFire, Fire[j]); */
kmtri_quads (	VertexBufferDesc,		/* KMVERTEXBUFFDESC	BufferDesc, */
				VertexContext,			/* KMVERTEXCONTEXT		VertexContext, */
				1,						/* int  nNumFaces, */
				&FFire,					/* int  pFaces[][4], */
				Fire[j],				/* PSGLVERTEX  pVertices */
				TRUE					/* bTexture */
				);

		}

	}

	/* Updating the reflection on the glasses */
    for (i=0;i<4;i++)
    {
	  *(Mesh[REFLECTION].Vertex+i*3+2) = GlassRefect[i]-(float)cos((double)YAng)*40.0;
	}

    (TempVert[REFLECTION]+0)->fVOverW = *(Mesh[REFLECTION].UV+0+1)- (LH-30)/550;
    (TempVert[REFLECTION]+1)->fVOverW = *(Mesh[REFLECTION].UV+2+1)- (LH-30)/550;
    (TempVert[REFLECTION]+2)->fVOverW = *(Mesh[REFLECTION].UV+4+1)+ 0.01*sin((j*8.0+frame)/1.5)-(LH-30)/1520;
    (TempVert[REFLECTION]+3)->fVOverW = *(Mesh[REFLECTION].UV+6+1)+ 0.01*sin((j*8.0+frame)/1.5)-(LH-30)/1520;
}
/*--------------------------- End of File --------------------------------*/
/****************************************************************************/
/**	main ********************************************************************/
/****************************************************************************/ 

NJS_PERIPHERAL *per;

int	main(void)
{
	float	LHD = 0.02f;

	txt_ClearScreen();	/* Clear text screen */
	PRINTOUT(("** Gas flame **\n"));
	SetupScene ();	/* Initialize */

	do {
		ReadMaple ();
		NextFrame();	/* Rendering */
		LH += (LHD / SPEED);
		if(LH > 60.0f) { LHD = -LHD; LH = 60.0f; }
		if(LH <  5.0f) { LHD = -LHD; LH =  5.0f; }
	} while(1);

	Finish();		/* End of render */
	PRINTOUT(("** END Gas flame **\n"));
	return 0;
}

/*----------------------------------------------------------------------*/
/*  Function Name   : ReadMaple                                         */
/*  Inputs          :                                                   */
/*  Outputs         :                                                   */
/*  Returns         :                                                   */
/*  Globals Used    : PosZ, BlendSrc, BlendDst, AlphaSource,            */
/*                    BlendModulate                                     */
/*  Description     : Read MAPLE status                                 */
/*----------------------------------------------------------------------*/
void ReadMaple (void)
{
	per = njGetPeripheral(NJD_PORT_A0);

	/* START button */
	if ( per->on & NJD_DGT_ST ){
		YAng1 = 0.0f;
	}

	/* UP cross key */
	if ( per->on & NJD_DGT_KU ){
		LH += 0.5f;
		if(LH > 60.0f) LH = 60.0f;
	}
	/* DOWN cross key */
	if ( per->on & NJD_DGT_KD ){
		LH -= 0.5f;
		if(LH < 5.0f) LH = 5.0f;
	}
	/* Left cross key */
	if ( per->on & NJD_DGT_KL ){
		YAng1 -= 0.001f;
	}
	/* Right cross key */
	if ( per->on & NJD_DGT_KR ){
		YAng1 += 0.001f;
	}

}

/*--------------------------- End of File --------------------------------*/
