4 #include <sys/stat.h> // mkdir
7 #include "kgsdk/Framework.h"
8 #include "kgsdk/Framework2D.h"
9 #include "kgsdk/FrameworkAudio.h"
10 #include "../common/emu.h"
11 #include "../common/lprintf.h"
12 #include "../common/arm_utils.h"
16 #include "asm_utils.h"
18 #include <Pico/PicoInt.h>
26 // main 300K gfx-related buffer. Used by menu and renderers.
27 unsigned char gfx_buffer[321*240*2*2];
28 char romFileName[MAX_PATH];
31 unsigned char *PicoDraw2FB = gfx_buffer; // temporary buffer for alt renderer ( (8+320)*(8+240+8) )
34 static int combo_keys = 0, combo_acts = 0; // keys and actions which need button combos
35 static DWORD noticeMsgTime = 0;
36 static short *snd_cbuff = NULL;
37 static int snd_cbuf_samples = 0, snd_all_samples = 0;
40 static void blit(const char *fps, const char *notice);
41 static void clearArea(int full);
43 void emu_noticeMsgUpdated(void)
45 noticeMsgTime = GetTickCount();
48 void emu_getMainDir(char *dst, int len)
50 if (len > 0) *dst = 0;
53 static void emu_msg_cb(const char *msg)
55 if (giz_screen == NULL)
56 giz_screen = Framework2D_LockBuffer();
58 memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
59 emu_textOut16(4, 232, msg);
60 noticeMsgTime = GetTickCount() - 2000;
62 /* assumption: emu_msg_cb gets called only when something slow is about to happen */
66 static void emu_state_cb(const char *str)
68 if (giz_screen == NULL)
69 giz_screen = Framework2D_LockBuffer();
74 Framework2D_UnlockBuffer();
77 Sleep(0); /* yield the CPU, the system may need it */
80 static void emu_msg_tray_open(void)
82 strcpy(noticeMsg, "CD tray opened");
83 noticeMsgTime = GetTickCount();
89 // make dirs for saves, cfgs, etc.
96 PicoMessage = emu_msg_cb;
97 PicoMCDopenTray = emu_msg_tray_open;
98 PicoMCDcloseTray = menu_loop_tray;
101 void emu_Deinit(void)
104 if((currentConfig.EmuOpt & 1) && SRam.changed) {
105 emu_SaveLoadGame(0, 1);
109 if (!(currentConfig.EmuOpt & 0x20)) {
110 FILE *f = fopen(PicoConfigFile, "r+b");
111 if (!f) emu_WriteConfig(0);
113 // if we already have config, reload it, except last ROM
114 fseek(f, sizeof(currentConfig.lastRomFile), SEEK_SET);
115 fread(¤tConfig.EmuOpt, 1, sizeof(currentConfig) - sizeof(currentConfig.lastRomFile), f);
116 fseek(f, 0, SEEK_SET);
117 fwrite(¤tConfig, 1, sizeof(currentConfig), f);
126 void emu_setDefaultConfig(void)
128 memset(¤tConfig, 0, sizeof(currentConfig));
129 currentConfig.lastRomFile[0] = 0;
130 currentConfig.EmuOpt = 0x1f | 0x680; // | confirm_save, cd_leds, 16bit rend
131 currentConfig.PicoOpt = 0x07 | 0xc00; // | cd_pcm, cd_cdda
132 currentConfig.PsndRate = 22050;
133 currentConfig.PicoRegion = 0; // auto
134 currentConfig.PicoAutoRgnOrder = 0x184; // US, EU, JP
135 currentConfig.Frameskip = -1; // auto
136 currentConfig.volume = 50;
137 currentConfig.KeyBinds[ 2] = 1<<0; // SACB RLDU
138 currentConfig.KeyBinds[ 3] = 1<<1;
139 currentConfig.KeyBinds[ 0] = 1<<2;
140 currentConfig.KeyBinds[ 1] = 1<<3;
141 currentConfig.KeyBinds[ 5] = 1<<4;
142 currentConfig.KeyBinds[ 6] = 1<<5;
143 currentConfig.KeyBinds[ 7] = 1<<6;
144 currentConfig.KeyBinds[ 4] = 1<<7;
145 currentConfig.KeyBinds[13] = 1<<26; // switch rend
146 currentConfig.KeyBinds[ 8] = 1<<27; // save state
147 currentConfig.KeyBinds[ 9] = 1<<28; // load state
148 currentConfig.KeyBinds[12] = 1<<29; // vol up
149 currentConfig.KeyBinds[11] = 1<<30; // vol down
150 currentConfig.PicoCDBuffers = 0;
151 currentConfig.scaling = 0;
155 static int EmuScan16(unsigned int num, void *sdata)
157 if (!(Pico.video.reg[1]&8)) num += 8;
158 DrawLineDest = (unsigned short *) giz_screen + 321*(num+1);
160 if ((currentConfig.EmuOpt&0x4000) && (num&1) == (Pico.m.frame_count&1))
161 return 1; // skip next line
166 static int EmuScan8(unsigned int num, void *sdata)
168 // draw like the fast renderer
169 if (!(Pico.video.reg[1]&8)) num += 8;
170 HighCol = gfx_buffer + 328*(num+1);
175 static void osd_text(int x, int y, const char *text)
177 int len = strlen(text) * 8 / 2;
179 for (h = 0; h < 8; h++) {
180 p = (int *) ((unsigned short *) giz_screen+x+321*(y+h));
181 p = (int *) ((int)p & ~3); // align
184 emu_textOut16(x, y, text);
188 void log1(void *p1, void *p2)
190 lprintf("%p %p %p\n", p1, p2, DrawLineDest);
194 static void cd_leds(void)
196 static int old_reg = 0;
197 unsigned int col_g, col_r, *p;
199 if (!((Pico_mcd->s68k_regs[0] ^ old_reg) & 3)) return; // no change
200 old_reg = Pico_mcd->s68k_regs[0];
202 p = (unsigned int *)((short *)giz_screen + 321*2+4+2);
203 col_g = (old_reg & 2) ? 0x06000600 : 0;
204 col_r = (old_reg & 1) ? 0xc000c000 : 0;
205 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 321/2 - 12/2 + 1;
206 *p++ = col_g; p+=3; *p++ = col_r; p += 321/2 - 10/2;
207 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r;
211 static short localPal[0x100];
213 static void blit(const char *fps, const char *notice)
215 int emu_opt = currentConfig.EmuOpt;
219 int lines_flags = 224;
220 // 8bit fast renderer
221 if (Pico.m.dirtyPal) {
223 vidConvCpyRGB565(localPal, Pico.cram, 0x40);
225 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
226 if (currentConfig.EmuOpt&0x4000)
227 lines_flags|=(Pico.m.frame_count&1)?0x20000:0x40000;
228 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
230 else if (!(emu_opt&0x80))
233 // 8bit accurate renderer
234 if (Pico.m.dirtyPal) {
236 vidConvCpyRGB565(localPal, Pico.cram, 0x40);
237 if (Pico.video.reg[0xC]&8) { // shadow/hilight mode
238 //vidConvCpyRGB32sh(localPal+0x40, Pico.cram, 0x40);
239 //vidConvCpyRGB32hi(localPal+0x80, Pico.cram, 0x40); // TODO?
240 blockcpy(localPal+0xc0, localPal+0x40, 0x40*2);
241 localPal[0xc0] = 0x0600;
242 localPal[0xd0] = 0xc000;
243 localPal[0xe0] = 0x0000; // reserved pixels for OSD
244 localPal[0xf0] = 0xffff;
247 else if (rendstatus & 0x20) { // mid-frame palette changes
248 vidConvCpyRGB565(localPal+0x40, HighPal, 0x40);
249 vidConvCpyRGB565(localPal+0x80, HighPal+0x40, 0x40);
252 lines_flags = (Pico.video.reg[1]&8) ? 240 : 224;
253 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
254 if (currentConfig.EmuOpt&0x4000)
255 lines_flags|=(Pico.m.frame_count&1)?0x20000:0x40000;
256 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
259 if (notice || (emu_opt & 2)) {
261 if (notice) osd_text(4, h, notice);
262 if (emu_opt & 2) osd_text(OSD_FPS_X, h, fps);
265 if ((emu_opt & 0x400) && (PicoMCD & 1))
269 // clears whole screen or just the notice area (in all buffers)
270 static void clearArea(int full)
272 if (giz_screen == NULL)
273 giz_screen = Framework2D_LockBuffer();
274 if (full) memset32(giz_screen, 0, 320*240*2/4);
275 else memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
278 static void vidResetMode(void)
280 giz_screen = Framework2D_LockBuffer();
283 } else if (currentConfig.EmuOpt&0x80) {
284 PicoDrawSetColorFormat(1);
285 PicoScan = EmuScan16;
287 PicoDrawSetColorFormat(-1);
290 if ((PicoOpt&0x10) || !(currentConfig.EmuOpt&0x80)) {
291 // setup pal for 8-bit modes
292 localPal[0xc0] = 0x0600;
293 localPal[0xd0] = 0xc000;
294 localPal[0xe0] = 0x0000; // reserved pixels for OSD
295 localPal[0xf0] = 0xffff;
299 memset32(giz_screen, 0, 321*240*2/4);
300 Framework2D_UnlockBuffer();
306 static void stdbg(const char *fmt, ...)
311 sprintf(noticeMsg, "%x ", cnt++);
313 vsnprintf(noticeMsg+strlen(noticeMsg), sizeof(noticeMsg)-strlen(noticeMsg), fmt, vl);
316 noticeMsgTime = GetTickCount();
320 static void updateSound(int len)
322 if (PicoOpt&8) len<<=1;
324 snd_all_samples += len;
326 if (PsndOut - snd_cbuff >= snd_cbuf_samples)
328 //if (PsndOut - snd_cbuff != snd_cbuf_samples)
329 // stdbg("snd diff is %i, not %i", PsndOut - snd_cbuff, snd_cbuf_samples);
335 static void SkipFrame(void)
342 void emu_forcedFrame(void)
344 int po_old = PicoOpt;
345 int eo_old = currentConfig.EmuOpt;
348 PicoOpt |= 0x4080; // soft_scale | acc_sprites
349 currentConfig.EmuOpt |= 0x80;
351 if (giz_screen == NULL)
352 giz_screen = Framework2D_LockBuffer();
354 PicoDrawSetColorFormat(1);
355 PicoScan = EmuScan16;
356 PicoScan((unsigned) -1, NULL);
360 Framework2D_UnlockBuffer();
364 currentConfig.EmuOpt = eo_old;
368 static void RunEvents(unsigned int which)
370 if (which & 0x1800) // save or load (but not both)
375 FrameworkAudio_SetPause(1);
376 if (giz_screen == NULL)
377 giz_screen = Framework2D_LockBuffer();
378 if ( emu_checkSaveFile(state_slot) &&
379 (( (which & 0x1000) && (currentConfig.EmuOpt & 0x800)) || // load
380 (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200))) ) // save
383 blit("", (which & 0x1000) ? "LOAD STATE? (PLAY=yes, STOP=no)" : "OVERWRITE SAVE? (PLAY=yes, STOP=no)");
384 while( !((keys = Framework_PollGetButtons()) & (BTN_PLAY|BTN_STOP)) )
386 if (keys & BTN_STOP) do_it = 0;
387 while( ((keys = Framework_PollGetButtons()) & (BTN_PLAY|BTN_STOP)) ) // wait for release
394 osd_text(4, 232, (which & 0x1000) ? "LOADING GAME" : "SAVING GAME");
395 PicoStateProgressCB = emu_state_cb;
396 emu_SaveLoadGame((which & 0x1000) >> 12, 0);
397 PicoStateProgressCB = NULL;
402 FrameworkAudio_SetPause(0);
405 if (which & 0x0400) // switch renderer
407 if (PicoOpt&0x10) { PicoOpt&=~0x10; currentConfig.EmuOpt |= 0x80; }
408 else { PicoOpt|= 0x10; currentConfig.EmuOpt &= ~0x80; }
413 strcpy(noticeMsg, " 8bit fast renderer");
414 } else if (currentConfig.EmuOpt&0x80) {
415 strcpy(noticeMsg, "16bit accurate renderer");
417 strcpy(noticeMsg, " 8bit accurate renderer");
420 noticeMsgTime = GetTickCount();
426 if(state_slot < 0) state_slot = 9;
429 if(state_slot > 9) state_slot = 0;
431 sprintf(noticeMsg, "SAVE SLOT %i [%s]", state_slot, emu_checkSaveFile(state_slot) ? "USED" : "FREE");
432 noticeMsgTime = GetTickCount();
436 static void updateKeys(void)
438 unsigned int keys, allActions[2] = { 0, 0 }, events;
439 static unsigned int prevEvents = 0;
442 keys = Framework_PollGetButtons();
444 engineState = PGS_Menu;
446 keys &= CONFIGURABLE_KEYS;
448 for (i = 0; i < 32; i++)
452 int pl, acts = currentConfig.KeyBinds[i];
454 pl = (acts >> 16) & 1;
455 if (combo_keys & (1 << i))
457 int u = i+1, acts_c = acts & combo_acts;
458 // let's try to find the other one
461 if ( (currentConfig.KeyBinds[u] & acts_c) && (keys & (1 << u)) ) {
462 allActions[pl] |= acts_c;
463 keys &= ~((1 << i) | (1 << u));
466 // add non-combo actions if combo ones were not found
467 if (!acts_c || u == 32)
468 allActions[pl] |= acts & ~combo_acts;
470 allActions[pl] |= acts;
475 PicoPad[0] = (unsigned short) allActions[0];
476 PicoPad[1] = (unsigned short) allActions[1];
478 events = (allActions[0] | allActions[1]) >> 16;
480 // volume is treated in special way and triggered every frame
481 if ((events & 0x6000) && PsndOut != NULL)
483 int vol = currentConfig.volume;
484 if (events & 0x2000) {
485 if (vol < 100) vol++;
489 FrameworkAudio_SetVolume(vol, vol);
490 sprintf(noticeMsg, "VOL: %02i", vol);
491 noticeMsgTime = GetTickCount();
492 currentConfig.volume = vol;
495 events &= ~prevEvents;
496 if (events) RunEvents(events);
497 if (movie_data) emu_updateMovie();
499 prevEvents = (allActions[0] | allActions[1]) >> 16;
502 static void find_combos(void)
506 // find out which keys and actions are combos
507 combo_keys = combo_acts = 0;
508 for (act = 0; act < 32; act++)
511 if (act == 16 || act == 17) continue; // player2 flag
512 for (u = 0; u < 32; u++)
514 if (currentConfig.KeyBinds[u] & (1 << act)) keyc++;
518 // loop again and mark those keys and actions as combo
519 for (u = 0; u < 32; u++)
521 if (currentConfig.KeyBinds[u] & (1 << act)) {
522 combo_keys |= 1 << u;
523 combo_acts |= 1 << act;
531 static void simpleWait(DWORD until)
536 tval = GetTickCount();
537 diff = (int)until - (int)tval;
541 while ((tval = GetTickCount()) < until && until - tval < 512) // some simple overflow detection
542 spend_cycles(1024*2);
547 static int PsndRate_old = 0, PicoOpt_old = 0, pal_old = 0;
548 char fpsbuff[24]; // fps count c string
549 DWORD tval, tval_prev = 0, tval_thissec = 0; // timing
550 int frames_done = 0, frames_shown = 0, oldmodes = 0, sec_ms = 1000;
551 int target_fps, target_frametime, lim_time, tval_diff, i;
554 lprintf("entered emu_Loop()\n");
558 // make sure we are in correct mode
560 if (currentConfig.scaling) PicoOpt|=0x4000;
561 else PicoOpt&=~0x4000;
563 oldmodes = ((Pico.video.reg[12]&1)<<2) ^ 0xc;
566 // pal/ntsc might have changed, reset related stuff
567 target_fps = Pico.m.pal ? 50 : 60;
568 target_frametime = Pico.m.pal ? (1000<<8)/50 : (1000<<8)/60+1;
572 if (PicoMCD & 1) PicoCDBufferInit();
574 // prepare sound stuff
576 if (currentConfig.EmuOpt & 4)
578 int ret, snd_excess_add, stereo;
579 if (PsndRate != PsndRate_old || (PicoOpt&0x0b) != (PicoOpt_old&0x0b) || Pico.m.pal != pal_old) {
580 sound_rerate(Pico.m.frame_count ? 1 : 0);
582 stereo=(PicoOpt&8)>>3;
583 snd_excess_add = ((PsndRate - PsndLen*target_fps)<<16) / target_fps;
584 snd_cbuf_samples = (PsndRate<<stereo) * 16 / target_fps;
585 lprintf("starting audio: %i len: %i (ex: %04x) stereo: %i, pal: %i\n",
586 PsndRate, PsndLen, snd_excess_add, stereo, Pico.m.pal);
587 ret = FrameworkAudio_Init(PsndRate, snd_cbuf_samples, stereo);
589 lprintf("FrameworkAudio_Init() failed: %i\n", ret);
590 sprintf(noticeMsg, "sound init failed (%i), snd disabled", ret);
591 noticeMsgTime = GetTickCount();
592 currentConfig.EmuOpt &= ~4;
594 FrameworkAudio_SetVolume(currentConfig.volume, currentConfig.volume);
595 PicoWriteSound = updateSound;
596 snd_cbuff = FrameworkAudio_56448Buffer();
597 PsndOut = snd_cbuff + snd_cbuf_samples / 2; // start writing at the middle
599 PsndRate_old = PsndRate;
600 PicoOpt_old = PicoOpt;
601 pal_old = Pico.m.pal;
606 while (engineState == PGS_Running)
610 tval = GetTickCount();
611 if (reset_timing || tval < tval_prev) {
612 //stdbg("timing reset");
615 frames_shown = frames_done = 0;
618 // show notice message?
620 static int noticeMsgSum;
621 if (tval - noticeMsgTime > 2000) { // > 2.0 sec
626 int sum = noticeMsg[0]+noticeMsg[1]+noticeMsg[2];
627 if (sum != noticeMsgSum) { clearArea(0); noticeMsgSum = sum; }
632 // check for mode changes
633 modes = ((Pico.video.reg[12]&1)<<2)|(Pico.video.reg[1]&8);
634 if (modes != oldmodes) {
640 if (tval - tval_thissec >= sec_ms)
643 static int bench = 0, bench_fps = 0, bench_fps_s = 0, bfp = 0, bf[4];
646 bench_fps_s = bench_fps;
647 bf[bfp++ & 3] = bench_fps;
650 bench_fps += frames_shown;
651 sprintf(fpsbuff, "%02i/%02i/%02i", frames_shown, bench_fps_s, (bf[0]+bf[1]+bf[2]+bf[3])>>2);
653 if(currentConfig.EmuOpt & 2)
654 sprintf(fpsbuff, "%02i/%02i", frames_shown, frames_done);
656 //tval_thissec += 1000;
657 tval_thissec += sec_ms;
661 /* some code which tries to sync things to audio clock, the dirty way */
662 static int audio_skew_prev = 0;
663 int audio_skew, adj, co = 9, shift = 7;
664 audio_skew = snd_all_samples*2 - FrameworkAudio_BufferPos();
665 if (PsndRate == 22050) co = 10;
666 if (PsndRate > 22050) co = 11;
667 if (PicoOpt&8) shift++;
668 if (audio_skew < 0) {
669 adj = -((-audio_skew) >> shift);
670 if (audio_skew > -(6<<co)) adj>>=1;
671 if (audio_skew > -(4<<co)) adj>>=1;
672 if (audio_skew > -(2<<co)) adj>>=1;
673 if (audio_skew > audio_skew_prev) adj>>=2; // going up already
675 adj = audio_skew >> shift;
676 if (audio_skew < (6<<co)) adj>>=1;
677 if (audio_skew < (4<<co)) adj>>=1;
678 if (audio_skew < (2<<co)) adj>>=1;
679 if (audio_skew < audio_skew_prev) adj>>=2;
681 audio_skew_prev = audio_skew;
682 target_frametime += adj;
683 sec_ms = (target_frametime * target_fps) >> 8;
684 //stdbg("%i %i %i", audio_skew, adj, sec_ms);
685 frames_done = frames_shown = 0;
687 else if (currentConfig.Frameskip < 0) {
688 frames_done -= target_fps; if (frames_done < 0) frames_done = 0;
689 frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;
690 if (frames_shown > frames_done) frames_shown = frames_done;
692 frames_done = frames_shown = 0;
696 sprintf(fpsbuff, "%i", Pico.m.frame_count);
700 lim_time = (frames_done+1) * target_frametime;
701 if (currentConfig.Frameskip >= 0) // frameskip enabled
703 for (i = 0; i < currentConfig.Frameskip; i++) {
705 SkipFrame(); frames_done++;
706 if (PsndOut) { // do framelimitting if sound is enabled
708 tval = GetTickCount();
709 tval_diff = (int)(tval - tval_thissec) << 8;
710 if (tval_diff < lim_time) // we are too fast
711 simpleWait(tval + ((lim_time - tval_diff)>>8));
713 lim_time += target_frametime;
716 else // auto frameskip
719 tval = GetTickCount();
720 tval_diff = (int)(tval - tval_thissec) << 8;
721 if (tval_diff > lim_time)
723 // no time left for this frame - skip
724 if (tval_diff - lim_time >= (300<<8)) {
725 /* something caused a slowdown for us (disk access? cache flush?)
726 * try to recover by resetting timing... */
731 SkipFrame(); frames_done++;
738 if (giz_screen == NULL && (currentConfig.EmuOpt&0x80))
739 giz_screen = Framework2D_LockBuffer();
741 PicoScan((unsigned) -1, NULL);
745 if (currentConfig.EmuOpt&0x2000)
746 Framework2D_WaitVSync();
748 if (giz_screen == NULL)
749 giz_screen = Framework2D_LockBuffer();
751 blit(fpsbuff, notice);
753 if (giz_screen != NULL) {
754 Framework2D_UnlockBuffer();
759 tval = GetTickCount();
760 tval_diff = (int)(tval - tval_thissec) << 8;
762 if (currentConfig.Frameskip < 0 && tval_diff - lim_time >= (300<<8)) // slowdown detection
764 else if (PsndOut != NULL || currentConfig.Frameskip < 0)
766 // sleep if we are still too fast
767 if (tval_diff < lim_time)
770 simpleWait(tval + ((lim_time - tval_diff) >> 8));
774 frames_done++; frames_shown++;
778 if (PicoMCD & 1) PicoCDBufferFree();
780 if (PsndOut != NULL) {
781 PsndOut = snd_cbuff = NULL;
782 FrameworkAudio_Close();
786 if ((currentConfig.EmuOpt & 1) && SRam.changed) {
787 emu_state_cb("Writing SRAM/BRAM..");
788 emu_SaveLoadGame(0, 1);
794 void emu_ResetGame(void)