main.c 24.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
/**************************************************************************
 *                                                                        *
 *               Copyright (C) 1995, Silicon Graphics, Inc.               *
 *                                                                        *
 *  These coded instructions, statements, and computer programs  contain  *
 *  unpublished  proprietary  information of Silicon Graphics, Inc., and  *
 *  are protected by Federal copyright  law.  They  may not be disclosed  *
 *  to  third  parties  or copied or duplicated in any form, in whole or  *
 *  in part, without the prior written consent of Silicon Graphics, Inc.  *
 *                                                                        *
 *************************************************************************/

/*---------------------------------------------------------------------*
        Copyright (C) 1998 Nintendo. (Originated by SGI)
        
        $RCSfile: main.c,v $
        $Revision: 1.1.1.1 $
        $Date: 2002/05/02 03:27:26 $
 *---------------------------------------------------------------------*/

/*
 * File:  main.c
 *
 *  Compiler Flags:
 *  o  _DEBUG - compile with rmon thread
 *
 *  The stress application is designed to touch as many different
 *  parts of the software interface as possible.  These include
 *
 *    Graphics      - use many different texture types, shading, lighting,
 *            transparency, copy, fill, etc.
 *
 *    Memory Mgmt.  - use static and dynamic segments, show some simple
 *            animation capability.
 *
 *    Audio     - play a test MIDI sequence
 *
 *    IO Manager    - simultaneous DMA activity from ROM to DRAM for audio
 *          and graphics streams.
 *
 *    VI Manager    - double buffer display, maybe a few video modes
 *
 *    Overloads     - demonstrate techniques for handling graphics overruns,
 *          cpu overruns, task yielding, etc.
 *
 *    Task Swapping     - demonstrate microcode task swapping
 *
 *    Timers        - demonstrate timer functionality
 *
 *    Sprite Library    - demonstrate some simple sprite operations
 *
 *    Controllers   - use serial controller gadgets to toggle some
 *            state within the application.
 *
 *    Because this application is meant to stress the system, it is purposefully
 *    wasteful of system bandwidth in some cases.
 *    
 */

#include <ultra64.h>
#include <ultralog.h>
#include <sched.h>
#include <assert.h>
#include <ramrom.h>

#include "stress.h"
#include "texture.h"
#include "vect.h"
#include "flight_path.h"
#include "audio.h"

#define NUM_PI_MSGS     		8
#define SP_UCODE_SIZE           4096
#define SP_UCODE_DATA_SIZE      2048

#define SCHED_CONTROLLER_MSG    (OS_SC_LAST_MSG+1)

/*
 *  Mode definitions
 */
typedef enum {
	D_MOUNTAINS = 1,
	D_POOL = 2,
	D_ORB = 4,
	D_CLOCK = 8,
	D_ALTIMETER = 16
} DisplayEnable;

typedef enum {
	M_BFCULL = 1,
	M_RGBDITHER = 2,
	M_TEXBILERP = 4,
	M_TEXPERSP = 8
} ModeEnable;

typedef enum {
	STILL, ORBIT, FLY
} FlyMode;

static DisplayEnable   DisplayEn = D_ORB | D_POOL | D_MOUNTAINS;
static ModeEnable      ModeEn = M_BFCULL | M_RGBDITHER | M_TEXBILERP | 
								M_TEXPERSP;
static FlyMode         flymode = ORBIT;
static u32      	   CurView = 0;

/*
 *  Message logging stuff
 */
#define LOG_SCHEDULE_GFX_TASK	101
#define LOG_RDP_DONE		    102
#define LOG_RETRACE		    	103
#define LOG_INTR		    	104
#define LOG_SWAPREQUEST		    105

#define LOG_LEN 				0x2000

OSLog           logger;
OSLog          *log = &logger;
u32             logData[LOG_LEN];


/*
 * Symbol genererated by "makerom" to indicate the end of the code segment
 * in virtual (and physical) memory
 */
extern char     _codeSegmentEnd[];
extern char     _cfbSegmentEnd[];

/*
 * Symbols generated by "makerom" to tell us where the static segment is
 * in ROM.
 */
extern char     _staticSegmentRomStart[],
                _staticSegmentRomEnd[];
extern char     _textureSegmentRomStart[],
                _textureSegmentRomEnd[];

char           *staticSegment;
char           *textureSegment;

/*
 * Stacks for the threads as well as message queues for synchronization
 */
u32		token0 = 0xdead0000;
u64             bootStack[BOOT_STACKSIZE / sizeof(u64)];
u32		token1 = 0xdead0001;
u64             stressloopThreadStack[STRESS_STACKSIZE / sizeof(u64)];
u32		token2 = 0xdead0002;
u64             mainThreadStack[MAIN_STACKSIZE / sizeof(u64)];
u32		token3 = 0xdead0003;
u64             audioStack[AUDIO_STACKSIZE / sizeof(u64)];
u32		token4 = 0xdead0004;

u64             rmonStack[RMON_STACKSIZE / sizeof(u64)];
u32		token5 = 0xdead0005;
u64             scheduleStack[OS_SC_STACKSIZE / sizeof(u64)];
u32		token6 = 0xdead0006;
OSSched         sc;
u32		token7 = 0xdead0007;

static OSThread stressThread;
static OSThread mainThread;
static OSThread rmonThread;

static OSMesg   	PiMessages[NUM_PI_MSGS];
static 	OSMesgQueue PiMessageQ;

OSMesgQueue     dmaMessageQ,
                rdpMessageQ,
                retraceMessageQ,
                rspMessageQ;
OSMesg          dmaMessageBuf,
                taskMessageBuf,
                retraceMessageBuf,
                rspMessageBuf;
OSIoMesg        dmaIOMessageBuf;

OSMesgQueue     gfxFrameMsgQ;
OSMesg          gfxFrameMsgBuf[MAX_MESGS];

/*
 * function prototypes for private functions in this file
 */
static void     main(void *);
static void     parse_args(char *argstring);
static void     stressloop(void *);
static void     initAudio(ALHeap * hp);
static void     create_gfx_tasks(GFXInfo *);
static void     romCopy(char *src, char *dest, int len);
static int      initControllers(void);
static void 	BuildGraphicsTask(OSTask *, Gfx *, u32);
static void		set_user_modes(void);
static void		set_display(Dynamic *);

/*
 *  External functions
 */
void			make_waves(Dynamic *);
void			getflytransform( float mat[4][4] );
void 			get_fp_position( float p,
                   float *vx, float *vy, float *vz,
                   float *ax, float *ay, float *az,
           		   float *ux, float *uy, float *uz);
void			clock_init(void);
void			do_clock(Gfx **);

/*
 *  Controller Data
 */
static OSContStatus statusdata[MAXCONTROLLERS];
static OSContPad controllerdata[MAXCONTROLLERS];

/*
 * XXX header!! public - shared by rmon and users 
 */
extern OSMesgQueue rmonCalloutMQ;

extern void     rmonMain(void *);

/*
 *  Matrix stack for RSP
 */
extern u64      dram_stack[];

/*
 *  rdp command buffer
 */
extern u64      rdp_output[];
extern u64      rdp_output_len;

/*
 *   must be in BSS, not on the stack for this to work:
 */

/*
 *   Double-buffered dynamic segments
 */
static GFXInfo	gInfo[2];
Gfx            *glistp;

/*
 *   global variables for arguments, to control test cases
 */
u32      		Logging;
static u32      Debugflag;
static u32      Verbose;
static u32      Silent;
static u32      Trap;
static u32      GbiDump;

/*
 *  Scheduler stuff
 */
static int      framecount;
static OSMesgQueue *schedqueue;
static GFXMsg   controllermsg;

/*
 *  Controller data
 */
static s8       velocity;
static s8       lastx;
static s8       lasty;
static u16      lastbutton;


/*
 *  Position, Attitude
 */
float           time = 0.0;
float           timeinc = 7.0;
float           Vpx,
                Vpy,
                Vpz;
float           Atx,
                Aty,
                Atz;
float           Upx,
                Upy,
                Upz;
float           ViewAlt[5] = {100.0, 1300.0, 500.0, 500.0, 500.0};
float           ViewXpos[5] = {300.0, 300.0, 200.0, 0.0, -500.0};
float           ViewZpos[5] = {650.0, 2350.0, 800.0, 5000.0, -500.0};

/*
 *  Audio Stuff
 */

ALSeqPlayer    *seqp;
static char    *seqPtr;
static int      seqLen;
static ALSeq   *seq;
static ALSeqMarker seqStart;
static ALSeqMarker seqEnd;
ALHeap          hp;
u8            audioHeap[AUDIO_HEAP_SIZE];



/*
 *  Boot
 */
OSPiHandle	*handler;

boot(char *arg)
{
	int             i;
	char           *ap;
	u32            *argp;
	u32             argbuf[16];

	osInitialize();

	handler = osCartRomInit();

	argp = (u32 *) RAMROM_APP_WRITE_ADDR;
	for (i = 0; i < sizeof(argbuf) / 4; i++, arg++) {
		osEPiReadIo(handler, (u32) argp, &argbuf[i]);	/*
												 * assume no DMA 
												 */
	}

	/*
	 * parse the options 
	 */
	parse_args((char *) argbuf);

	osCreateThread(&mainThread, 1, main, (void *) arg,
				   mainThreadStack + MAIN_STACKSIZE / sizeof(u64), MAIN_PRIORITY);
	osStartThread(&mainThread);

	/*
	 * Never Reached - feel free to use bootStack 
	 */
}

/*
 *      M a i n
 */
void
main(void *arg)
{
	/*
	 * Initialize video
	 */
	osCreateViManager(OS_PRIORITY_VIMGR);
	/* osViSetMode(&osViModeTable[OS_VI_NTSC_LAN1]); */

	/*
	 * Start PI Mgr for access to cartridge
	 */
	osCreatePiManager((OSPri) OS_PRIORITY_PIMGR, &PiMessageQ, PiMessages, 
		NUM_PI_MSGS);

	/*
	 * Start RMON for debugging (make sure to start PI Mgr first
	 */
#ifdef _DEBUG
	osCreateThread(&rmonThread, 4, rmonMain, (void *) 0,
				   rmonStack + RMON_STACKSIZE / sizeof(u64), OS_PRIORITY_RMON);
	osStartThread(&rmonThread);
#endif 

	/*
	 * Create stress thread
	 */
	osCreateThread(&stressThread, 6, stressloop, (void *) 0,
				   stressloopThreadStack + STRESS_STACKSIZE / sizeof(u64), 
				   STRESS_PRIORITY);

	if (!Debugflag)
		osStartThread(&stressThread);

	/*
	 * Become the idle thread
	 */
	osSetThreadPri(0, 0);
	for (;;) ;
}

/*
 *  Main Stress Loop
 */
void
stressloop(void *arg)
{
	char           *i;
	unsigned int    sum;

	int             displaybuffer = 0;
	int             drawbuffer = 0;
	int             bufCnt = 0;
	GFXMsg         *msg;
	OSScClient      client;
	GFXInfo        *gfxp;
	int             controller;
	int             controllervalid = 1;
	OSContPad      *pad;
	s8              roll,
	                pitch;
	if (DisplayEn & D_CLOCK)
		clock_init();

	if (Logging)
		osCreateLog(log, logData, LOG_LEN);

	/*
	 * Initialize the RCP task scheduler 
	 */
	osCreateMesgQueue(&dmaMessageQ, &dmaMessageBuf, MAX_MESGS);
	osCreateScheduler(&sc, 
				(void *) (scheduleStack + OS_SC_STACKSIZE / sizeof(u64)),
				SCHEDULER_PRIORITY, OS_VI_NTSC_LAN1, NUM_FIELDS);

	/*
	 * DMA models and textures
	 */
	staticSegment = _cfbSegmentEnd;
	romCopy(_staticSegmentRomStart, staticSegment,
			_staticSegmentRomEnd - _staticSegmentRomStart);


	textureSegment = (_staticSegmentRomEnd - _staticSegmentRomStart) +
	  _cfbSegmentEnd;


	romCopy(_textureSegmentRomStart, textureSegment,
			_textureSegmentRomEnd - _textureSegmentRomStart);

	osViSetSpecialFeatures(OS_VI_DIVOT_OFF | OS_VI_GAMMA_ON);

	if (ModeEn & M_RGBDITHER) {
		osViSetSpecialFeatures(OS_VI_DITHER_FILTER_ON);
	} else {
		osViSetSpecialFeatures(OS_VI_DITHER_FILTER_OFF);
	}

	/*
	 *  Initialize flying controls
	 */
	/* fly_init(); */

	if (!Silent) {
		initAudio(&hp);
		alSeqpPlay(seqp);
	}

	gInfo[0].msg.gen.type = OS_SC_DONE_MSG;
	gInfo[0].cfb = cfb_16_a;
	gInfo[1].msg.gen.type = OS_SC_DONE_MSG;
	gInfo[1].cfb = cfb_16_b;
	controllermsg.gen.type = SCHED_CONTROLLER_MSG;

	osCreateMesgQueue(&gfxFrameMsgQ, gfxFrameMsgBuf, MAX_MESGS);

	osScAddClient(&sc, &client, &gfxFrameMsgQ);

	if ((controller = initControllers()) < 0)
		controllervalid = 0;
	else
		controllervalid = 1;

	osSetEventMesg(OS_EVENT_SI, &gfxFrameMsgQ, (OSMesg) & controllermsg);


	/*
	 * Main stress loop
	 */
	while (1) {
		(void) osRecvMesg(&gfxFrameMsgQ, (OSMesg *) & msg, OS_MESG_BLOCK);

		switch (msg->gen.type) {
				/*
				 * Received every retrace
				 * Create a new gfx task unless we are overrunning
				 */
			case (OS_SC_RETRACE_MSG):
				if (Logging)
					osLogEvent(log, LOG_RETRACE, 1, bufCnt);

				if (bufCnt < 2) {
					create_gfx_tasks(&gInfo[drawbuffer]);
					bufCnt++;
					drawbuffer ^= 1;
				}
				/*
				 * request latest controller information 
				 */
				if (controllervalid) {
					osContStartReadData(&gfxFrameMsgQ);
					controllervalid = 0;
				}

				break;

			case (OS_SC_DONE_MSG):
				gfxp = &gInfo[displaybuffer];

				if (Logging)
					osLogEvent(log, LOG_RDP_DONE, 3, gfxp->cfb, framecount);

				displaybuffer ^= 1;
				framecount++;
				bufCnt--;
				if (framecount >= 3000) {
					framecount = 0;
					if(Logging)
						osFlushLog(log);
				}
				break;

			case SCHED_CONTROLLER_MSG:

				osContGetReadData(controllerdata);
				controllervalid = 1;
				pad = &controllerdata[controller];

				if (pad->button & CONT_START && !(lastbutton & CONT_START)) {
					if (flymode == FLY)
						flymode = STILL;
					else
						flymode++;
				}
				if ((pad->button & CONT_R) && !(lastbutton & CONT_R))
					timeinc += .3;

				if ((pad->button & CONT_L) && !(lastbutton & CONT_L))
					timeinc -= .3;

				lastx = pad->stick_x;
				lasty = pad->stick_y;
				lastbutton = pad->button;
				break;

            case (OS_SC_PRE_NMI_MSG):
            	bufCnt += 2;
                break;
       

			default:
				PRINTF("gameproc loop unknown intr 0x%x\n", msg->gen.type);
				break;
		}
	}
	alSeqpStop(seqp);
}

/*
 *  Draw loop
 */
static void
create_gfx_tasks(GFXInfo * info)
{
	OSScTask       *t;
	u16             pnorm;
	Dynamic        *dynamicp;
	float           eye_mat[4][4];
	

	/*
	 * pointers to build the display list.
	 */
	dynamicp = &info->dp;
	glistp = dynamicp->glist;

	/*
	 *  Animate texture maps
	 */
	make_waves(dynamicp);

	/*
	 *  Get matrix for eye point position
	 */
/*
	getflytransform(eye_mat);
*/
	myidentity(eye_mat);
	guMtxF2L(eye_mat, &(dynamicp->eye));
	/*
	 *  Calculate Matrices
	 */
	guPerspective(&dynamicp->projection, &pnorm,
				  33, 320.0 / 240.0, 100, 10000, 1.0);

	switch (flymode) {

		case STILL:
			guLookAt(&dynamicp->viewing,
					 ViewXpos[CurView], ViewAlt[CurView], ViewZpos[CurView],
					 125, 0, 110,
					 0, 1, 0);

			if(DisplayEn & D_ORB) {
				/*
			 	* look at lighted sphere, matrix is not used 
			 	*/
				guLookAtHilite(&dynamicp->dummy_mtx,
						   &(dynamicp->lookat[0]),
						   &(dynamicp->hilite[0]),
						   ViewXpos[CurView], 
						   ViewAlt[CurView], 
						   ViewZpos[CurView],
						   0, 100, 0,
						   0, 1, 0,
						   32.0, 64.0, 32.0,	/*
												 * lt0 direction 
												 */
						   1.0, 1.0, 1.0,	/*
											 * not used 
											 */
						   32, 32);		/*
										 * texture width 
										 */
			}
			break;

		case ORBIT:

			if (time > 1000 * 60 * 2.1)
				time = 0.0;

			Atx = sinf(time / 1000 * 2 * M_PI) * 370;
			Aty = cosf(time / 500 * 2 * M_PI) * 125 + 175;
			Atz = cosf(time / 1000 * 2 * M_PI) * 850;
			time += timeinc;

			guLookAt(&dynamicp->viewing,
					 Atx, Aty, Atz,
					 125, 50, 110,
					 0, 1, 0);

			/*
			 * look at lighted sphere, matrix is not used 
			 */
			guLookAtHilite(&dynamicp->dummy_mtx,
						   &(dynamicp->lookat[0]),
						   &(dynamicp->hilite[0]),
						   Atx, Aty, Atz,
						   0, 100, 0,
						   0, 1, 0,
						   32.0, 64.0, 32.0,	/*
												 * lt0 direction 
												 */
						   1.0, 1.0, 1.0,	/*
											 * not used 
											 */
						   32, 32);		/*
										 * texture width 
										 */

			break;

		case FLY:

			if (time > 31.0)
				time = 0.0;

			get_fp_position(time,
							&Vpx, &Vpy, &Vpz,
							&Atx, &Aty, &Atz,
							&Upx, &Upy, &Upz);

			guLookAt(&dynamicp->viewing,
					 Vpx, Vpy, Vpz,
					 Atx, Aty, Atz,
					 Upx, Upy, Upz);

			/*
			 * look at lighted sphere, matrix is not used 
			 */
			guLookAtHilite(&dynamicp->dummy_mtx,
						   &(dynamicp->lookat[0]),
						   &(dynamicp->hilite[0]),
						   Vpx, Vpy, Vpz,
						   Atx, Aty, Atz,
						   Upx, Upy, Upz,
						   32.0, 64.0, 32.0,	/*
												 * lt0 direction 
												 */
						   1.0, 1.0, 1.0,	/*
											 * not used 
											 */
						   32, 32);		/*
										 * texture width 
										 */

			time += (timeinc / 10.0);
			break;
	}
	/*
	 * Set up segment registers
	 */
	gSPSegment(glistp++, DYNAMIC_SEGMENT, 
				(void *) osVirtualToPhysical(dynamicp));
	gSPSegment(glistp++, PHYSICAL_SEGMENT, 0);
	gSPSegment(glistp++, STATIC_SEGMENT,
			   (void *) osVirtualToPhysical(staticSegment));
	gSPSegment(glistp++, TEXTURE_SEGMENT,
			   (void *) osVirtualToPhysical(textureSegment));
	gSPSegment(glistp++, CFB_SEGMENT,
			   (void *) osVirtualToPhysical(info->cfb));

	/*
	 * set pipeline mode, send BOWTIEVAL, set clipping frustrum ratio
	 */
/*
	gDPPipelineMode(glistp++, G_PM_1PRIMITIVE);
	gSPTexture(glistp++, 0, 0, 0, 0, G_OFF);
	gSPClipRatio(glistp++, FRUSTRATIO_2);
*/

	/*
	 *  Scale factor for W, keeps W at about 1.0 through divide
	 */
	gSPPerspNormalize(glistp++, pnorm);

	/*
	 *  Get static gfx commands
	 */
	gSPDisplayList(glistp++, &(gfxinit_dl[0]));

	/*
	 *  Display pieces of the scene
	 */
	set_user_modes();
	set_display(dynamicp);

	/*
	 *  required
	 */
	gDPFullSync(glistp++);
	gSPEndDisplayList(glistp++);

	assert((glistp - dynamicp->glist) < GFXDLSIZE);

	/*
	 *  Only write back dynamic structure, since this is only data
	 *  in display list that changed.
	 */
	osWritebackDCache(&info->dp, (int)glistp - (int)&info->dp);

	/*
	 * build graphics task 
	 */
	t = &info->task;
	BuildGraphicsTask(&t->list, dynamicp->glist,
			(int) (glistp - dynamicp->glist) * sizeof(Gfx));


	/*
	 *  Build scheduler task
	 */
	t->next = 0;
	t->flags = OS_SC_NEEDS_RSP | OS_SC_NEEDS_RDP | OS_SC_LAST_TASK |
			OS_SC_SWAPBUFFER;
	t->msgQ = &gfxFrameMsgQ;
	t->msg = (OSMesg) & info->msg;
	t->framebuffer = (void *) info->cfb;

	osSendMesg(osScGetCmdQ(&sc), (OSMesg) t, OS_MESG_BLOCK);
}

/*
 *  Interpret Command Line options
 */
static void 
parse_args(char *argstring)
{
	int             argc = 1,
	                i;
	char           *arglist[32],
	              **argv = arglist;		/*
										 * max 32 args 
										 */
	char           *c,
	               *ptr;

	if (argstring == NULL || argstring[0] == '\0')
		return;

	/*
	 * re-organize argstring to be like main(argv,argc) 
	 */
	ptr = argstring;
	while (*ptr != '\0') {
		while (*ptr != '\0' && (*ptr == ' ')) {
			*ptr = '\0';
			ptr++;
		}
		if (*ptr != '\0')
			arglist[argc++] = ptr;
		while (*ptr != '\0' && (*ptr != ' ')) {
			ptr++;
		}
	}

	/*
	 * process the arguments: 
	 */
	while ((argc > 1) && (argv[1][0] == '-')) {
		switch (argv[1][1]) {

			case 'd':
				Debugflag = 1;
				break;

			case 'v':
				Verbose = 1;
				break;

			case 's':
				Silent = 1;
				break;

			case 'l':
				Logging = 1;
				break;

			case 'g':
				GbiDump = 1;
				break;

			case 't':
				Trap = 1;
				break;

			default:
				break;
		}
		argc--;
		argv++;
	}
}


/*
 *  Copy data from ROM to DRAM
 */
void 
romCopy(char *src, char *dest, int len)
{
	OSIoMesg        dmaIoMesgBuf;
	OSMesg          dummyMesg;

	osWritebackDCacheAll();

	dmaIoMesgBuf.hdr.pri      = OS_MESG_PRI_NORMAL;
	dmaIoMesgBuf.hdr.retQueue = &dmaMessageQ;
	dmaIoMesgBuf.dramAddr     = dest;
	dmaIoMesgBuf.devAddr      = (u32)src;
	dmaIoMesgBuf.size         = len;

	osEPiStartDma(handler, &dmaIoMesgBuf, OS_READ);
	(void) osRecvMesg(&dmaMessageQ, &dummyMesg, OS_MESG_BLOCK);
}

/*
 *  Initialize Audio
 */
static void 
initAudio(ALHeap * hp)
{
	ALBankFile     *bankPtr;
	int             bankLen;
	ALSynConfig     c;
	ALSeqpConfig    seqc;

	alHeapInit(hp, audioHeap, sizeof(audioHeap));

	/*
	 * Load the bank file from ROM
	 */
	bankLen = _bankSegmentRomEnd - _bankSegmentRomStart;
	bankPtr = alHeapAlloc(hp, 1, bankLen);
	romCopy(_bankSegmentRomStart, (char *) bankPtr, bankLen);

	alBnkfNew(bankPtr, _tableSegmentRomStart);

	/*
	 * Load the sequence file from ROM
	 */
	seqLen = _seqSegmentRomEnd - _seqSegmentRomStart;
	seqPtr = alHeapAlloc(hp, 1, seqLen);
	romCopy(_seqSegmentRomStart, seqPtr, seqLen);

	/*
	 * Create the Audio Manager
	 */
	c.maxVVoices = MAX_VOICES;
	c.maxPVoices = MAX_VOICES;
	c.maxUpdates = MAX_UPDATES;
	c.dmaproc = 0;				/*
								 * audio mgr will fill this in 
								 */
	c.fxType = AL_FX_SMALLROOM;
	c.outputRate = osAiSetFrequency(32000);
	c.heap = hp;

	amCreateAudioMgr(&c, AUDIO_PRIORITY);

	/*
	 * Create the sequence and the sequence player
	 */
	seqc.maxVoices = MAX_VOICES;
	seqc.maxEvents = MAX_EVENTS;
	seqc.maxChannels = 16;
	seqc.heap = hp;
	seqc.initOsc = 0;
	seqc.updateOsc = 0;
	seqc.stopOsc = 0;
#ifdef _DEBUG
	seqc.debugFlags =  NO_SOUND_ERR_MASK;
#endif
	seqp = alHeapAlloc(hp, 1, sizeof(ALSeqPlayer));
	alSeqpNew(seqp, &seqc);

	seq = alHeapAlloc(hp, 1, sizeof(ALSeq));
	alSeqNew(seq, seqPtr, seqLen);
	alSeqNewMarker(seq, &seqStart, 0);
    alSeqNewMarker(seq, &seqEnd, -1);

    alSeqpLoop(seqp, &seqStart, &seqEnd, -1);
	alSeqpSetSeq(seqp, seq);
	alSeqpSetBank(seqp, bankPtr->bankArray[0]);
}



/*
 *
 * Return the lowest number controller connected to system
 */
static int 
initControllers()
{
	OSMesgQueue     tempMsgQ;
	OSMesg          tempMsg;
	int             i;
	u8              pattern;

	osCreateMesgQueue(&tempMsgQ, &tempMsg, 1);
	osSetEventMesg(OS_EVENT_SI, &tempMsgQ, (OSMesg) 1);

	osContInit(&tempMsgQ, &pattern, &statusdata[0]);

	for (i = 0; i < MAXCONTROLLERS; i++) {
		if ((pattern & (1 << i)) &&
			!(statusdata[i].errno & CONT_NO_RESPONSE_ERROR))
			return i;
	}
	return -1;
}


/*
 *  Build 3-D Graphics Task List
 */
static void
BuildGraphicsTask(OSTask * tlistp, Gfx * data_ptr, u32 data_size)
{
	tlistp->t.type = M_GFXTASK;
	tlistp->t.flags = OS_TASK_DP_WAIT;
	tlistp->t.ucode_boot = (u64 *) rspbootTextStart;
	tlistp->t.ucode_boot_size = ((int) rspbootTextEnd -
								 (int) rspbootTextStart);

	/*
	 * SP output over XBUS to DP: 
	 */
	tlistp->t.ucode = (u64 *) gspFast3DTextStart;
	tlistp->t.ucode_data = (u64 *) gspFast3DDataStart;

	if (Trap) {
		tlistp->t.ucode = (u64 *) gspFast3D_dramTextStart;
		tlistp->t.ucode_data = (u64 *) gspFast3D_dramDataStart;
	}
	tlistp->t.ucode_size = SP_UCODE_SIZE;
	tlistp->t.ucode_data_size = SP_UCODE_DATA_SIZE;
	tlistp->t.dram_stack = (u64 *) &(dram_stack[0]);
	tlistp->t.dram_stack_size = SP_DRAM_STACK_SIZE8;

	tlistp->t.output_buff = (u64 *) 0x0;
	tlistp->t.output_buff_size = (u64 *) 0x0;

	if (Trap) {
		tlistp->t.output_buff = (u64 *) rdp_output;
		tlistp->t.output_buff_size = (u64 *) &(rdp_output_len);
	}
	tlistp->t.yield_data_ptr = (u64 *) gfxYieldBuf;
	tlistp->t.yield_data_size = OS_YIELD_DATA_SIZE;

	/*
	 * initial display list: 
	 */
	tlistp->t.data_ptr = (u64 *) data_ptr;
	tlistp->t.data_size = data_size;

    if(GbiDump) {
		guParseGbiDL(tlistp->t.data_ptr, tlistp->t.data_size, 0);
		osExit();
	}

}

/*
 *  Build Line Task List
 */
#ifdef LATER
static void
BuildLineTask(OSTask * tlistp, int draw_buffer)
{
	tlistp->t.type = M_GFXTASK;
	tlistp->t.flags =			/*
								 * OS_TASK_DP_WAIT 
								 */ 0x0;
	tlistp->t.ucode_boot = (unsigned long long *) rspbootTextStart;
	tlistp->t.ucode_boot_size = ((int) rspbootTextEnd -
								 (int) rspbootTextStart);

	tlistp->t.ucode = (unsigned long long *) gspLine3DTextStart;
	tlistp->t.ucode_data = (unsigned long long *) gspLine3DDataStart;

	if (Trap) {
		tlistp->t.ucode = (unsigned long long *) gspLine3D_dramTextStart;
		tlistp->t.ucode_data = (unsigned long long *) gspLine3D_dramDataStart;
	}
	tlistp->t.ucode_size = 4096;
	tlistp->t.ucode_data_size = 2048;
	tlistp->t.dram_stack = (unsigned long long *) &(dram_stack[0]);
	tlistp->t.dram_stack_size = SP_DRAM_STACK_SIZE8;

	tlistp->t.output_buff = (unsigned long long *) 0x0;
	tlistp->t.output_buff_size = (unsigned long long *) 0x0;

	if (Trap) {
		tlistp->t.output_buff = (unsigned long long *) rdp_output;
		tlistp->t.output_buff_size = (unsigned long long *) &(rdp_output_len);
	}
	/*
	 * initial display list: 
	 */
	tlistp->t.data_ptr = (unsigned long long *)
	  dynamicBuffer[draw_buffer].lnlist;
	tlistp->t.data_size = ((int) (lnlistp - dynamicBuffer[draw_buffer].lnlist) *
						   sizeof(Gfx));
}
#endif /* LATER */


/*
 *  Set User-Defined Attributes
 */
static void
set_user_modes(void)
{
	gSPSetGeometryMode(glistp++, G_SHADE | G_ZBUFFER);
	gSPTexture(glistp++, 0x8000, 0x8000, 0, G_TX_RENDERTILE, G_ON);

	if (ModeEn & M_RGBDITHER) {
		gDPSetColorDither(glistp++, G_CD_BAYER);
	} else {
		gDPSetColorDither(glistp++, G_CD_DISABLE);
	}

	if (ModeEn & M_BFCULL) {
		gSPSetGeometryMode(glistp++, G_CULL_BACK);
	} else {
		gSPClearGeometryMode(glistp++, G_CULL_BACK);
	}

	if (ModeEn & M_TEXPERSP) {
		gDPSetTexturePersp(glistp++, G_TP_PERSP);
	} else {
		gDPSetTexturePersp(glistp++, G_TP_NONE);
	}

	if (ModeEn & M_TEXBILERP) {
		gDPSetTextureFilter(glistp++, G_TF_BILERP);
	} else {
		gDPSetTextureFilter(glistp++, G_TF_POINT);
	}
}

/*
 *   Determine what to display
 */
static void
set_display(Dynamic * dynamicp)
{
	if (DisplayEn & D_MOUNTAINS)
		gSPDisplayList(glistp++, &(relax0_dl[0]));

	if (DisplayEn & D_POOL)
		gSPDisplayList(glistp++, &(relax1_dl[0]));

	if (DisplayEn & D_ORB) {
		gSPLookAt(glistp++, &(RSPdynamic.lookat[0]));
		gSPDisplayList(glistp++, ltsphere_att_dl);
		gDPSetHilite1Tile(glistp++, G_TX_RENDERTILE, dynamicp->hilite, 32, 32);
		gSPDisplayList(glistp++, ltsphere_dl);
	}

	if (DisplayEn & D_CLOCK) {
		gDPPipeSync(glistp++);
		gDPSetCycleType(glistp++, G_CYC_1CYCLE);
		gDPSetTexturePersp(glistp++, G_TP_NONE);
		do_clock(&glistp);
	}
}