/********************************************************************************/
/* Name     : VLdemo.c  ( SGL ARC1 demo)										*/
/* Title    : KAMUI test program "SnowHill" from VL								*/
/* Author   : VideoLogic Carlos Sarria / NEC Software Takeshi Muto				*/
/* Created  : Janualy 1998 by VideoLogic										*/
/* Modified : Februaly 4. 1998 by Takeshi Muto for KAMUI						*/
/*																				*/
/* Description :																*/
/* Copyright : 1998 by VideoLogic Limited. All rights reserved.					*/
/********************************************************************************/

/*
#define		_X86_
*/
/* _X86_ flag for win95 : SET2 */

/* Set Display Mode */
#define NTSC 1

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <shinobi.h>

/*--
#include	<io.h>
#include	<FCNTL.H>
#include	<malloc.h>
#include	<memory.h>
#include	<conio.h>
--*/

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

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

#include	"kmtools.h"
#include	"kmtrees.h"	/* This is the file with 3D data */

#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

/* Textures */
extern unsigned char Snow;
extern unsigned char TTree;
extern unsigned char Tree;
extern unsigned char Leaf;

/****************************************************************************/
/**	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 */
	KMVERTEXBUFFDESC	VertexBufferDesc;		/* Vertex-buffer */
	KMVERTEXCONTEXT		VertexContext00;		/* Vertex context Snow */
	KMVERTEXCONTEXT		VertexContext01;		/* Vertex context TTree */
	KMVERTEXCONTEXT		VertexContext02;		/* Vertex context Tree */
	KMVERTEXCONTEXT		VertexContext03;		/* Vertex context Leaf */
	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;				/* 現在の性能(Frame/Second) */
	double		aFPS;				/* 性能の平均値 */
	double		MxFPS;				/* 最高性能 */
	double		MnFPS;				/* 最低性能 */
	__int64 	Time3i;				/* render API 完了時刻 */
	__int64		freqi;				/* カウンタの精度 */
	double		freq;				/* カウンタの精度 */
	double		Time3;				/* render API 完了時刻 */
	double		maxTime = 0.00001;	/* 最高描画時間(msec) */
	double		minTime = 99999;	/* 最低描画時間(msec) */
	double		OldTime3;			/* １フレーム前のrender直後の時間(msec) */
	double		nowTime;			/* 現在の描画時間(msec) */
	double		totalTime	= 0;	/* 累積render時間(msec) */
	double		aveTime;			/* 平均描画時間(msec) */
#if defined(_X86_)
	time_t		start_time;			/* APの開始時間 */
#endif
#endif

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

/*int				Frame = 0; */
/*unsigned			TexSnow, TexTree, TexOpaq, TexLeaf; */
KMSURFACEDESC		TexSnow, TexTree, TexOpaq, TexLeaf;
extern TRANSFORM	T[NUM_MESHES];
static sgl_vector	X_Axle = { 1, 0,0}, Y_Axle = { 0,1, 0}, Z_Axle = { 0,0, 1};
unsigned char		BColor[3];

int					 menu = 0;
#define	MENU_MAX_F	(6.0f)
int					transmode = 2;	/* 0=Opaq. 1=Trans. 2=PunchThrough */

float				Ang, PosZ = 0.0f, PosX=0.0f, High=-100.0f;
float				DAng = 0.01f;
int					nTrees = 150;

int					Translucent = TRUE, IsBark=FALSE, Stopped=FALSE, RandTree = TRUE, Type = 0;
int					TCont[1000];

float				CosA, SinA, TrX, TrY, TrZ, MovX, MovZ;

/* Info Structure */
INFO Info = 
{
	FALSE,		/* OpaqMap       */
	TRUE,       /* Textured      */
	TRUE,		/* Gouraud       */
	FALSE,      /* GlobalTrans   */
	FALSE,      /* VertexAlpha   */
	FALSE,		/* TableFog      */
	FALSE,      /* VertexFog     */
	TRUE,       /* Bilinear      */
	FALSE,      /* Highlight     */
};

/* Prototypes */

static void SetTextures			(void);
static void NextFrame			(void);
static void DisplayInformation	(int menu);
static void ReadMaple (void);

/*extern SGLCONTEXT SGLContext; */

/****************************************************************************/
/**	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.55f;
	BV[0].fBaseGreen		=   0.87f;
	BV[0].fBaseBlue			=   0.96f;

	/* 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.0f;
	BV[1].fBaseGreen		=   0.15f;
	BV[1].fBaseBlue			=   0.73f;

	/* 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.55f;
	BV[2].fBaseGreen		=   0.87f;
	BV[2].fBaseBlue			=   0.96f;

	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_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_1(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							GetALPHA(pVert->u32Colour),
							GetRED  (pVert->u32Colour),
							GetGREEN(pVert->u32Colour),
							GetBLUE (pVert->u32Colour)
							);

			pVert = &pVertices[pFaces[i][1]];
			kmxxSetVertex_1(KM_VERTEXPARAM_NORMAL,
							pVert->fX,
							pVert->fY,
							pVert->fInvW,
							GetALPHA(pVert->u32Colour),
							GetRED  (pVert->u32Colour),
							GetGREEN(pVert->u32Colour),
							GetBLUE (pVert->u32Colour)
							);

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


#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

/*-------------------------------------------------------------------------------------*/
/*                                       MAIN                                          */
/*-------------------------------------------------------------------------------------*/

NJS_PERIPHERAL *per;

int main (void)
{
int			Control = 0;
/*int		Device; */
int			Val = 0, i;

#ifdef __GNUC__
	shinobi_workaround();
#endif
  
/*	Device = sgl_create_screen_device (0, 640, 480, sgl_device_16bit, FALSE); */
/*	if (Device<0) return -1; */

	txt_ClearScreen();	/* Clear text screen */
	PRINTOUT(("** Snow hill **\n"));

	/*----------------------------------------------------------------------------------- */
	/* 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)0xAC880000;

	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 * 1;	/* Texture Memory size : 1MB * 1 */
	/* for Vertex buffer */
	SystemConfig.pBufferDesc		=	&VertexBufferDesc;	/* pointer to VERTEXBUFFDESC 		*/
	SystemConfig.pVertexBuffer		=	dwDataPtr;			/* pointer to Vertex buffer 		*/
	SystemConfig.nVertexBufferSize	=	262144 * 6 + 131072;/* size of Vertex buffer : 1MB * 6 */
	SystemConfig.fBufferSize[0]		=	40.0f;		/* Opaque polygon buffer size        : 35% */
	SystemConfig.fBufferSize[1]		=	 0.0f;		/* Opaque modifier buffer size       :  0% */
	SystemConfig.fBufferSize[2]		=	30.0f;		/* Trans polygon buffer size         : 30% */
	SystemConfig.fBufferSize[3]		=	 0.0f;		/* Trans modifier buffer size        :  0% */
	SystemConfig.fBufferSize[4]		=	30.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 */
	SetTextures ();
	InitContext (&VertexContext00, Info, 0, &TexSnow);
	InitContext (&VertexContext01, Info, transmode, &TexTree);
	InitContext (&VertexContext02, Info, 0, &TexOpaq);
	InitContext (&VertexContext03, Info, 0, &TexLeaf);
	InitBackGround();		/* Setup background plane */
	DisplayInformation (menu);


	/*----------------------------------------------------------------------------------- */
	/* 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がサポートされている */
		QueryPerformanceCounter((LARGE_INTEGER*)&Time3i);	/* ダミー値による初期化 */
		freq = 1000.0f / (double)freqi;						/* msec変換用係数の生成 */
		OldTime3 = Time3 = (double)Time3i * freq;			/* countからmsecへ変換 */
	}
	else {	/* QueryPerformanceCounterがサポートされていない */
		Time3 = (double)timeGetTime();						/* ダミー値による初期化 */
	}

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

	/* This function creates an array of structures with 3D data */
	CreateMeshesArray ();
	InitMeshes (NUM_MESHES, (CASTMESHES *) Mesh);

	for(i=0; i<1000; i++) TCont[i] = rand()%8 + 1;

   	while (TRUE)
	{
	
#if defined(_X86_)
	   while(!kbhit())  NextFrame ();
	   Val = _getch ();
      
	   switch (Val)
	   {
			case K_ESC:
			case K_F12:
				 goto Finish;    

	      	case K_F1 :
			     Info.Bilinear = (Info.Bilinear) ? FALSE:TRUE;
				 DisplayInformation (menu);
				 break;
	
			case K_F2 :
				 Type++; if (Type==3) Type=0;
				 DisplayInformation (menu);
				 break;
			case K_F3 :
				 Info.Textured = (Info.Textured) ? FALSE:TRUE;
				 if (Translucent && !Info.Textured) Info.VertexAlpha =  TRUE;
                 else  Info.VertexAlpha =  FALSE;
				 DisplayInformation (menu);
				 break;

	      
			case K_F4:
				 Translucent = (Translucent) ? FALSE:TRUE;
				 if (Translucent && !Info.Textured) Info.VertexAlpha =  TRUE;
				 else  Info.VertexAlpha =  FALSE;
				 DisplayInformation (menu);
				 break;

			case K_F6:
				 RandTree = (RandTree) ? FALSE:TRUE;
				 if(RandTree) 	for(i=0; i<1000; i++) TCont[i] = (rand()%8) + 1;
				 else 	        for(i=0; i<1000; i++) TCont[i] = 1;

				 DisplayInformation (menu);
				 break;

		 	case K_F7 :
				 if(nTrees > 10) nTrees-=10;
				 	 DisplayInformation (menu);
				 break;
			case K_F8 :
				 if(nTrees < 300) nTrees+=10;
				 	 DisplayInformation (menu);
				 break;

			case K_F9 :
/*				while(!kbhit()) { sgltri_rerender(&SGLContext);Timer(HARD_TIME);} */
/*				 DisplayInformation (menu); */
				break;

			case K_F5:
				 Stopped = (Stopped) ? FALSE:TRUE;
				 DisplayInformation (menu);
				 break;

			
            case K_UP  : PosZ-=2.0f; break;
			case K_DOWN: PosZ+=2.0f; break;
			case K_LEFT:  PosX+=2.0f; break;
			case K_RIGHT: PosX-=2.0f; break;
            
			case 122:  High+=5.0f;break;
			case 97: High-=5.0f;break;
				 
	   }
	   Val = 0;
#else	/* Not X86 */
	ReadMaple ();
	NextFrame ();
#endif
	}

Finish:

    FreeMeshes (NUM_MESHES);
/*	FreeAllBMPTextures (); */
/*	sgl_delete_device(Device); */

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

	/*----------------------------------------------------------------------------------- */
	/* End display */
	status = kmStopDisplayFrameBuffer();
	Check_Status(status, "kmStopDisplayFrameBuffer");

	return 0;
}

/*-------------------------------------------------------------------------------------*/
void SetTextures (void)
{
/*	sgl_intermediate_map TexBuff; */

/*	TexSnow   = LoadBMPTexture ("Snow.bmp", FALSE, FALSE, FALSE);	 */
/*	TexTree  = LoadBMPTexture  ("tree.bmp", TRUE, FALSE, FALSE); */
/*	TexOpaq  = LoadBMPTexture  ("tree.bmp", FALSE, FALSE, FALSE); */
/*	TexLeaf  = LoadBMPTexture  ("leaf.bmp", FALSE, FALSE, FALSE); */

	PKMDWORD			pTexture01;				/* Pointer to texture */
	KMTEXTURETYPE		nTextureType;			/* texture type definition */

	/*----------------------------------------------------------------------------------- */
	/* Create texture surface */
	nTextureType = KM_TEXTURE_TWIDDLED | KM_TEXTURE_RGB565;	/* Set texture type */
	status = kmCreateTextureSurface(
		&TexSnow,				/* OUT	PKMSURFACEDESC	pSurfaceDesc */
		256,					/*	IN	KMINT32			nWidth  */
		256,					/*	IN	KMINT32			nHeight  */
		nTextureType			/*	IN	KMTEXTURETYPE	nTextureType */
	);
	Check_Status(status, "kmCreateTextureSurface(RGB)");
	/*----------------------------------------------------------------------------------- */
	/* Create texture surface */
	nTextureType = KM_TEXTURE_TWIDDLED | KM_TEXTURE_ARGB1555;	/* Set texture type */
	status = kmCreateTextureSurface(
		&TexTree,				/* OUT	PKMSURFACEDESC	pSurfaceDesc */
		256,					/*	IN	KMINT32			nWidth  */
		256,					/*	IN	KMINT32			nHeight  */
		nTextureType			/*	IN	KMTEXTURETYPE	nTextureType */
	);
	Check_Status(status, "kmCreateTextureSurface(RGB)");
	/*----------------------------------------------------------------------------------- */
	/* Create texture surface */
	nTextureType = KM_TEXTURE_TWIDDLED | KM_TEXTURE_RGB565;	/* Set texture type */
	status = kmCreateTextureSurface(
		&TexOpaq,				/* OUT	PKMSURFACEDESC	pSurfaceDesc */
		256,					/*	IN	KMINT32			nWidth  */
		256,					/*	IN	KMINT32			nHeight  */
		nTextureType			/*	IN	KMTEXTURETYPE	nTextureType */
	);
	Check_Status(status, "kmCreateTextureSurface(RGB)");
	/*----------------------------------------------------------------------------------- */
	/* Create texture surface */
	nTextureType = KM_TEXTURE_TWIDDLED | KM_TEXTURE_RGB565;	/* Set texture type */
	status = kmCreateTextureSurface(
		&TexLeaf,				/* OUT	PKMSURFACEDESC	pSurfaceDesc */
		256,					/*	IN	KMINT32			nWidth  */
		256,					/*	IN	KMINT32			nHeight  */
		nTextureType			/*	IN	KMTEXTURETYPE	nTextureType */
	);
	Check_Status(status, "kmCreateTextureSurface(RGB)");
	/*----------------------------------------------------------------------------------- */
	/* Load and set texture */
#if 0
	pTexture01 =  LoadTextureFile("snow.pvr");	/* Load KAMUI texture */
#endif
	pTexture01 = (unsigned long *)&Snow;
	status = kmLoadTexture(&TexSnow,			/* PKMSURFACEDESC pSurfaceDesc */
							pTexture01 + (16 / sizeof(KMDWORD)),			/* PKMDWORD pTexture */
							FALSE,				/* KMBOOLEAN bAutoMipMap */
							FALSE				/* KMBOOLEAN bDither */
							);
	Check_Status(status, "kmLoadTexture(ARGB)");
/*	free(pTexture01);	*/
	/*----------------------------------------------------------------------------------- */
	/* Load and set texture */
#if 0
	pTexture01 =  LoadTextureFile("ttree.pvr");	/* Load KAMUI texture */
#endif
	pTexture01 = (unsigned long *)&TTree;
	status = kmLoadTexture(&TexTree,			/* PKMSURFACEDESC pSurfaceDesc */
							pTexture01 + (16 / sizeof(KMDWORD)),			/* PKMDWORD pTexture */
							FALSE,				/* KMBOOLEAN bAutoMipMap */
							FALSE				/* KMBOOLEAN bDither */
							);
	Check_Status(status, "kmLoadTexture(ARGB)");
/*	free(pTexture01);	*/
	/*----------------------------------------------------------------------------------- */
	/* Load and set texture */
#if 0
	pTexture01 =  LoadTextureFile("tree.pvr");	/* Load KAMUI texture */
#endif
	pTexture01 = (unsigned long *)&Tree;
	status = kmLoadTexture(&TexOpaq,			/* PKMSURFACEDESC pSurfaceDesc */
							pTexture01 + (16 / sizeof(KMDWORD)),			/* PKMDWORD pTexture */
							FALSE,				/* KMBOOLEAN bAutoMipMap */
							FALSE				/* KMBOOLEAN bDither */
							);
	Check_Status(status, "kmLoadTexture(ARGB)");
/*	free(pTexture01);	*/
	/*----------------------------------------------------------------------------------- */
	/* Load and set texture */
#if 0
	pTexture01 =  LoadTextureFile("leaf.pvr");	/* Load KAMUI texture */
#endif
	pTexture01 = (unsigned long *)&Leaf;
	status = kmLoadTexture(&TexLeaf,			/* PKMSURFACEDESC pSurfaceDesc */
							pTexture01 + (16 / sizeof(KMDWORD)),			/* PKMDWORD pTexture */
							FALSE,				/* KMBOOLEAN bAutoMipMap */
							FALSE				/* KMBOOLEAN bDither */
							);
	Check_Status(status, "kmLoadTexture(ARGB)");
/*	free(pTexture01);	*/

}
/*-------------------------------------------------------------------------------------*/
void NextFrame (void)
{

static			Movement = 0;
static float	Sun = 0, HPos ;
register		i;
/*register		j, k; */
float			Xpos[] = { -50.0f,  -50.0f,  50.0f,   50.0f,-15.0f,  -15.0f,  15.0f,   15.0f};
float			Ypos[] = { -50.0f,  50.0f,   -50.0f,  50.0f ,-50.0f,  50.0f,   -50.0f,  50.0f};
/*int				TransTemp; */
int				Cont = 1000;

	if (!Stopped) Ang += DAng;

	CosA = cos (Ang);
	SinA = sin (Ang);

	InitScene ();

	if (Translucent && !Info.Textured) Info.VertexAlpha =  TRUE;

	for (i = 0; i < nTrees; i++) {
		Cont += TCont[i];
		TrX = Vertex_Ground[Cont][0];
		TrY = High + Vertex_Ground[Cont][1] - 1.0f;
		TrZ = Vertex_Ground[Cont][2];

		MovX = PosX;
		MovZ = PosZ;

		/*	SGLContext.bCullBackfacing      = 0; */
		SetVertices (1, (!Translucent)? VertexContext02:VertexContext01, FX_NONE );
		if (Type==1 || Type==2) SetVertices (3, (!Translucent)? VertexContext02:VertexContext01, FX_NONE );
		if (Type==2) SetVertices (2, VertexContext03, FX_NONE );	/* Leaf : Opaq. */
	}

#if 0
  Info.VertexAlpha =  FALSE;
  SetContext (Info);
#endif

	/* GROUND */
	TrX = 0.0f;
	TrY = High;
	TrZ = 0.0f;
	MovX = PosX ;
	MovZ = PosZ;
	/*	SGLContext.bCullBackfacing      = 0; */
	SetVertices (0, VertexContext00, FX_NONE );

	/*  Timer(DISPLAY_TIME); */

	EndScene();

	pdExecPeripheralServer();


/*  Frame++; */
}

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

void DisplayInformation (int menu)
{
char *treeT[] = { "3 TRANS","6 TRANS","6 TRANS + 6 OPAQ" };
char *transT[] = { "Opaque","Translucent","Punchthrough" };
char *Flag[2]   = { "FALSE", "TRUE" };

	txt_SetCursor(0,13);
	if(menu == 0)	txt_SetColor( 1.0f, 0.5f, 0.0f );
	else			txt_SetColor( 1.0f, 1.0f, 1.0f );
	PRINTOUT(( " Bilinear      %s\n",   Flag[Info.Bilinear]));
	if(menu == 1)	txt_SetColor( 1.0f, 0.5f, 0.0f );
	else			txt_SetColor( 1.0f, 1.0f, 1.0f );
	PRINTOUT(( " Gouraud       %s\n",   Flag[Info.Gouraud]));	
	if(menu == 2)	txt_SetColor( 1.0f, 0.5f, 0.0f );
	else			txt_SetColor( 1.0f, 1.0f, 1.0f );
	PRINTOUT(( " Textured      %s\n",   Flag[Info.Textured]));	
	if(menu == 3)	txt_SetColor( 1.0f, 0.5f, 0.0f );
	else			txt_SetColor( 1.0f, 1.0f, 1.0f );
	PRINTOUT(( " Tree type     %s\n",   treeT[Type]));		
	if(menu == 4)	txt_SetColor( 1.0f, 0.5f, 0.0f );
	else			txt_SetColor( 1.0f, 1.0f, 1.0f );
	PRINTOUT(( " Trans. mode   %s\n",   transT[transmode]));
	if(menu == 5)	txt_SetColor( 1.0f, 0.5f, 0.0f );
	else			txt_SetColor( 1.0f, 1.0f, 1.0f );
	PRINTOUT(( " Random        %s\n", Flag[RandTree]));
	if(menu == 6)	txt_SetColor( 1.0f, 0.5f, 0.0f );
	else			txt_SetColor( 1.0f, 1.0f, 1.0f );
	PRINTOUT(( " Num. of trees %d\n", nTrees));
	txt_SetColor( 1.0f, 1.0f, 1.0f );
/*	PRINTOUT(( " F9 : Hardware Time (F10 to normal)\n\n")); */

/*	Timer (RESET_TIME); */
}

/*----------------------------------------------------------------------*/
/*  Function Name   : ReadMaple                                         */
/*  Inputs          :                                                   */
/*  Outputs         :                                                   */
/*  Returns         :                                                   */
/*  Globals Used    : PosZ, BlendSrc, BlendDst, AlphaSource,            */
/*                    BlendModulate                                     */
/*  Description     : Read MAPLE status                                 */
/*----------------------------------------------------------------------*/
void ReadMaple (void)
{
	static	int	swadelay = 0;	/* flag for cancel chattering of A button */
	static	int	swbdelay = 0;	/* flag for cancel chattering of B button */
	static	int	swxdelay = 0;	/* flag for cancel chattering of X button */
	static	int	swydelay = 0;	/* flag for cancel chattering of Y button */
	static	float	menu2 = 0.0f;
	int			i;

	per = njGetPeripheral(NJD_PORT_A0);

		/* START button */
		if ( per->on & NJD_DGT_ST ){
			DAng	=    0.0f;
			nTrees	=  150.0f;
			PosZ	=    0.0f;
			PosX	=    0.0f;
			High	= -100.0f;
			DisplayInformation (menu);
		}

		/* UP cross key */
		if ( per->on & NJD_DGT_KU ){
			menu2 -= 0.2f;
			if(menu2 < 0.0f) menu2 = MENU_MAX_F + 0.9f;
			menu = (int)menu2;
			DisplayInformation (menu);
		}
		/* DOWN cross key */
		if ( per->on & NJD_DGT_KD ){
			menu2 += 0.2f;
			if(menu2 > (MENU_MAX_F + 0.9f)) menu2 = 0.0f;
			menu = (int)menu2;
			DisplayInformation (menu);
		}
		/* Left cross key */
		if ( per->on & NJD_DGT_KL ){
			DAng += 0.001;
		}
		/* Right cross key */
		if ( per->on & NJD_DGT_KR ){
			DAng -= 0.001;
		}

		/* Medama X */
		PosX -= ((float)per->x1) / 100.0f;

		/* Medama Y */
		PosZ += ((float)per->y1) / 100.0f;

		/* Slider Right */
		High += ((float)per->r) / 100.0f;

		/* Slider Left */
		High -= ((float)per->l) / 100.0f;

		/* A button */
		if ( swadelay == 0 ) {
			if ( per->on & NJD_DGT_TA ){
				switch(menu) {
				case 0:
					Info.Bilinear = (Info.Bilinear) ? FALSE:TRUE;
					SetContext (&VertexContext00, Info, 0, &TexSnow);
					SetContext (&VertexContext01, Info, transmode, &TexTree);
					SetContext (&VertexContext02, Info, 0, &TexOpaq);
					SetContext (&VertexContext03, Info, 0, &TexLeaf);
					break;
				case 1:
					Info.Gouraud = (Info.Gouraud) ? FALSE:TRUE;
					SetContext (&VertexContext00, Info, 0, &TexSnow);
					SetContext (&VertexContext01, Info, transmode, &TexTree);
					SetContext (&VertexContext02, Info, 0, &TexOpaq);
					SetContext (&VertexContext03, Info, 0, &TexLeaf);
					break;
				case 2:
					Info.Textured = (Info.Textured) ? FALSE:TRUE;
					SetContext (&VertexContext00, Info, 0, &TexSnow);
					SetContext (&VertexContext01, Info, transmode, &TexTree);
					SetContext (&VertexContext02, Info, 0, &TexOpaq);
					SetContext (&VertexContext03, Info, 0, &TexLeaf);
					break;
				case 3:
					Type++; if (Type == 3) Type = 0;
					break;
				case 4:
					transmode++; if(transmode == 3) transmode = 0;
					if(transmode > 0) {
						Translucent = TRUE;
						SetContext (&VertexContext01, Info, transmode, &TexTree);
					}
					else {
						Translucent = FALSE;
					}
#if 0
					if (Translucent && !Info.Textured) Info.VertexAlpha =  TRUE;
					else  Info.VertexAlpha =  FALSE;
#endif
					DisplayInformation (menu);
					break;
				case 5:
					RandTree = (RandTree) ? FALSE:TRUE;
					if(RandTree) 	for(i=0; i<1000; i++) TCont[i] = (rand()%8) + 1;
					else 	        for(i=0; i<1000; i++) TCont[i] = 1;
					break;
				case 6:
					if(nTrees < 1000) nTrees+=10;
					break;
				default:
					break;
				}
				DisplayInformation (menu);
				swadelay = 1;
			}
		} else {
			if ( per->off & NJD_DGT_TA ){
				swadelay = 0;
			}
		}

		/* B button */
		if ( swbdelay == 0 ) {
			if ( per->on & NJD_DGT_TB ){
				switch(menu) {
				case 6:
					 if(nTrees > 10) nTrees-=10;
					break;
				default:
					break;
				}
				DisplayInformation (menu);
				swbdelay = 1;
			}
		} else {
			if ( per->off & NJD_DGT_TB ){
				swbdelay = 0;
			}
		}

		/* X button */
		if ( swxdelay == 0 ) {
			if ( per->on & NJD_DGT_TX ){
				DAng = 0.0f;
				swxdelay = 1;
			}
		} else {
			if ( per->off & NJD_DGT_TX ){
				swxdelay = 0;
			}
		}

		/* Y button */
		if ( swydelay == 0 ) {
			if ( per->on & NJD_DGT_TY ){
				swydelay = 1;
			}
		} else {
			if ( per->off & NJD_DGT_TY ){
				swydelay = 0;
			}
		}

}

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

