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"
13 #include "../common/config.h"
17 #include "asm_utils.h"
19 #include <pico/pico_int.h>
27 // main 300K gfx-related buffer. Used by menu and renderers.
28 unsigned char gfx_buffer[321*240*2*2];
29 char romFileName[MAX_PATH];
32 unsigned char *PicoDraw2FB = gfx_buffer; // temporary buffer for alt renderer ( (8+320)*(8+240+8) )
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 int emu_getMainDir(char *dst, int len)
50 if (len > 0) *dst = 0;
55 static void emu_msg_cb(const char *msg)
57 if (giz_screen != NULL) fb_unlock();
58 giz_screen = fb_lock(1);
60 memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
61 emu_textOut16(4, 232, msg);
62 noticeMsgTime = GetTickCount() - 2000;
64 /* assumption: emu_msg_cb gets called only when something slow is about to happen */
68 giz_screen = fb_lock((currentConfig.EmuOpt&0x8000) ? 0 : 1);
71 void emu_stateCb(const char *str)
73 if (giz_screen != NULL) fb_unlock();
74 giz_screen = fb_lock(1);
82 Sleep(0); /* yield the CPU, the system may need it */
85 static void emu_msg_tray_open(void)
87 strcpy(noticeMsg, "CD tray opened");
88 noticeMsgTime = GetTickCount();
94 // make dirs for saves, cfgs, etc.
101 PicoMessage = emu_msg_cb;
102 PicoMCDopenTray = emu_msg_tray_open;
103 PicoMCDcloseTray = menu_loop_tray;
106 void emu_Deinit(void)
109 if ((currentConfig.EmuOpt & 1) && SRam.changed) {
110 emu_SaveLoadGame(0, 1);
114 if (!(currentConfig.EmuOpt & 0x20))
115 config_writelrom(PicoConfigFile);
120 void emu_prepareDefaultConfig(void)
122 memset(&defaultConfig, 0, sizeof(defaultConfig));
123 defaultConfig.EmuOpt = 0x1d | 0x680; // | confirm_save, cd_leds, 16bit rend
124 defaultConfig.s_PicoOpt = 0x0f | POPT_EN_MCD_PCM|POPT_EN_MCD_CDDA|POPT_EN_SVP_DRC|POPT_ACC_SPRITES;
125 defaultConfig.s_PsndRate = 22050;
126 defaultConfig.s_PicoRegion = 0; // auto
127 defaultConfig.s_PicoAutoRgnOrder = 0x184; // US, EU, JP
128 defaultConfig.s_PicoCDBuffers = 0;
129 defaultConfig.Frameskip = -1; // auto
130 defaultConfig.volume = 50;
131 defaultConfig.KeyBinds[ 2] = 1<<0; // SACB RLDU
132 defaultConfig.KeyBinds[ 3] = 1<<1;
133 defaultConfig.KeyBinds[ 0] = 1<<2;
134 defaultConfig.KeyBinds[ 1] = 1<<3;
135 defaultConfig.KeyBinds[ 5] = 1<<4;
136 defaultConfig.KeyBinds[ 6] = 1<<5;
137 defaultConfig.KeyBinds[ 7] = 1<<6;
138 defaultConfig.KeyBinds[ 4] = 1<<7;
139 defaultConfig.KeyBinds[13] = 1<<26; // switch rend
140 defaultConfig.KeyBinds[ 8] = 1<<27; // save state
141 defaultConfig.KeyBinds[ 9] = 1<<28; // load state
142 defaultConfig.KeyBinds[12] = 1<<29; // vol up
143 defaultConfig.KeyBinds[11] = 1<<30; // vol down
144 defaultConfig.scaling = 0;
145 defaultConfig.turbo_rate = 15;
149 static int EmuScanBegin16(unsigned int num)
151 if (!(Pico.video.reg[1]&8)) num += 8;
152 DrawLineDest = (unsigned short *) giz_screen + 321 * num;
154 if ((currentConfig.EmuOpt&0x4000) && (num&1) == 0) // (Pico.m.frame_count&1))
155 return 1; // skip next line
160 static int EmuScanBegin8(unsigned int num)
162 // draw like the fast renderer
163 if (!(Pico.video.reg[1]&8)) num += 8;
164 HighCol = gfx_buffer + 328 * num;
169 static void osd_text(int x, int y, const char *text)
171 int len = strlen(text) * 8 / 2;
173 for (h = 0; h < 8; h++) {
174 p = (int *) ((unsigned short *) giz_screen+x+321*(y+h));
175 p = (int *) ((int)p & ~3); // align
178 emu_textOut16(x, y, text);
182 void log1(void *p1, void *p2)
184 lprintf("%p %p %p\n", p1, p2, DrawLineDest);
188 static void cd_leds(void)
190 static int old_reg = 0;
191 unsigned int col_g, col_r, *p;
193 if (!((Pico_mcd->s68k_regs[0] ^ old_reg) & 3)) return; // no change
194 old_reg = Pico_mcd->s68k_regs[0];
196 p = (unsigned int *)((short *)giz_screen + 321*2+4+2);
197 col_g = (old_reg & 2) ? 0x06000600 : 0;
198 col_r = (old_reg & 1) ? 0xc000c000 : 0;
199 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 321/2 - 12/2 + 1;
200 *p++ = col_g; p+=3; *p++ = col_r; p += 321/2 - 10/2;
201 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r;
205 static short localPal[0x100];
207 static void blit(const char *fps, const char *notice)
209 int emu_opt = currentConfig.EmuOpt;
213 int lines_flags = 224;
214 // 8bit fast renderer
215 if (Pico.m.dirtyPal) {
217 vidConvCpyRGB565(localPal, Pico.cram, 0x40);
220 if (PicoRead16Hook == PicoSVPRead16)
221 memset32((int *)(PicoDraw2FB+328*8+328*223), 0xe0e0e0e0, 328);
222 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
223 if (currentConfig.EmuOpt&0x4000)
224 lines_flags|=0x40000; // (Pico.m.frame_count&1)?0x20000:0x40000;
225 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
227 else if (!(emu_opt&0x80))
230 // 8bit accurate renderer
231 if (Pico.m.dirtyPal) {
233 vidConvCpyRGB565(localPal, Pico.cram, 0x40);
234 if (Pico.video.reg[0xC]&8) { // shadow/hilight mode
235 //vidConvCpyRGB32sh(localPal+0x40, Pico.cram, 0x40);
236 //vidConvCpyRGB32hi(localPal+0x80, Pico.cram, 0x40); // TODO?
237 memcpy32((void *)(localPal+0xc0), (void *)(localPal+0x40), 0x40*2/4);
238 localPal[0xc0] = 0x0600;
239 localPal[0xd0] = 0xc000;
240 localPal[0xe0] = 0x0000; // reserved pixels for OSD
241 localPal[0xf0] = 0xffff;
244 else if (rendstatus & 0x20) { // mid-frame palette changes
245 vidConvCpyRGB565(localPal+0x40, HighPal, 0x40);
246 vidConvCpyRGB565(localPal+0x80, HighPal+0x40, 0x40);
249 lines_flags = (Pico.video.reg[1]&8) ? 240 : 224;
250 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
251 if (currentConfig.EmuOpt&0x4000)
252 lines_flags|=0x40000; // (Pico.m.frame_count&1)?0x20000:0x40000;
253 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
256 if (notice || (emu_opt & 2)) {
258 if (notice) osd_text(4, h, notice);
259 if (emu_opt & 2) osd_text(OSD_FPS_X, h, fps);
262 if ((emu_opt & 0x400) && (PicoAHW & PAHW_MCD))
266 // clears whole screen or just the notice area (in all buffers)
267 static void clearArea(int full)
269 if (giz_screen == NULL)
270 giz_screen = fb_lock(1);
271 if (full) memset32(giz_screen, 0, 320*240*2/4);
272 else memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
274 if (currentConfig.EmuOpt&0x8000) {
276 giz_screen = fb_lock(0);
277 if (full) memset32(giz_screen, 0, 320*240*2/4);
278 else memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
282 static void vidResetMode(void)
284 giz_screen = fb_lock(1);
287 } else if (currentConfig.EmuOpt&0x80) {
288 PicoDrawSetColorFormat(1);
289 PicoScanBegin = EmuScanBegin16;
291 PicoDrawSetColorFormat(-1);
292 PicoScanBegin = EmuScanBegin8;
294 if ((PicoOpt&0x10) || !(currentConfig.EmuOpt&0x80)) {
295 // setup pal for 8-bit modes
296 localPal[0xc0] = 0x0600;
297 localPal[0xd0] = 0xc000;
298 localPal[0xe0] = 0x0000; // reserved pixels for OSD
299 localPal[0xf0] = 0xffff;
303 memset32(giz_screen, 0, 321*240*2/4);
304 if (currentConfig.EmuOpt&0x8000) {
306 giz_screen = fb_lock(0);
307 memset32(giz_screen, 0, 321*240*2/4);
315 static void stdbg(const char *fmt, ...)
320 sprintf(noticeMsg, "%x ", cnt++);
322 vsnprintf(noticeMsg+strlen(noticeMsg), sizeof(noticeMsg)-strlen(noticeMsg), fmt, vl);
325 noticeMsgTime = GetTickCount();
329 static void updateSound(int len)
331 if (PicoOpt&8) len<<=1;
333 snd_all_samples += len;
335 if (PsndOut - snd_cbuff >= snd_cbuf_samples)
337 //if (PsndOut - snd_cbuff != snd_cbuf_samples)
338 // stdbg("snd diff is %i, not %i", PsndOut - snd_cbuff, snd_cbuf_samples);
344 static void SkipFrame(void)
351 /* forced frame to front buffer */
352 void emu_forcedFrame(int opts)
354 int po_old = PicoOpt;
355 int eo_old = currentConfig.EmuOpt;
358 PicoOpt |= opts|POPT_ACC_SPRITES;
359 currentConfig.EmuOpt |= 0x80;
361 if (giz_screen == NULL)
362 giz_screen = fb_lock(1);
364 PicoDrawSetColorFormat(1);
365 PicoScanBegin = EmuScanBegin16;
373 currentConfig.EmuOpt = eo_old;
377 static void RunEvents(unsigned int which)
379 if (which & 0x1800) // save or load (but not both)
384 FrameworkAudio_SetPause(1);
385 if (giz_screen == NULL)
386 giz_screen = fb_lock(1);
387 if ( emu_checkSaveFile(state_slot) &&
388 (( (which & 0x1000) && (currentConfig.EmuOpt & 0x800)) || // load
389 (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200))) ) // save
392 blit("", (which & 0x1000) ? "LOAD STATE? (PLAY=yes, STOP=no)" : "OVERWRITE SAVE? (PLAY=yes, STOP=no)");
393 while( !((keys = Framework_PollGetButtons()) & (PBTN_PLAY|PBTN_STOP)) )
395 if (keys & PBTN_STOP) do_it = 0;
396 while( ((keys = Framework_PollGetButtons()) & (PBTN_PLAY|PBTN_STOP)) ) // wait for release
403 osd_text(4, 232, (which & 0x1000) ? "LOADING GAME" : "SAVING GAME");
404 PicoStateProgressCB = emu_stateCb;
405 emu_SaveLoadGame((which & 0x1000) >> 12, 0);
406 PicoStateProgressCB = NULL;
411 FrameworkAudio_SetPause(0);
414 if (which & 0x0400) // switch renderer
416 if (PicoOpt&0x10) { PicoOpt&=~0x10; currentConfig.EmuOpt |= 0x80; }
417 else { PicoOpt|= 0x10; currentConfig.EmuOpt &= ~0x80; }
422 strcpy(noticeMsg, " 8bit fast renderer");
423 } else if (currentConfig.EmuOpt&0x80) {
424 strcpy(noticeMsg, "16bit accurate renderer");
426 strcpy(noticeMsg, " 8bit accurate renderer");
429 noticeMsgTime = GetTickCount();
435 if(state_slot < 0) state_slot = 9;
438 if(state_slot > 9) state_slot = 0;
440 sprintf(noticeMsg, "SAVE SLOT %i [%s]", state_slot, emu_checkSaveFile(state_slot) ? "USED" : "FREE");
441 noticeMsgTime = GetTickCount();
445 static void updateKeys(void)
447 unsigned int keys, allActions[2] = { 0, 0 }, events;
448 static unsigned int prevEvents = 0;
451 keys = Framework_PollGetButtons();
452 if (keys & PBTN_HOME)
453 engineState = PGS_Menu;
455 keys &= CONFIGURABLE_KEYS;
457 for (i = 0; i < 32; i++)
461 int pl, acts = currentConfig.KeyBinds[i];
463 pl = (acts >> 16) & 1;
464 if (kb_combo_keys & (1 << i))
466 int u = i+1, acts_c = acts & kb_combo_acts;
467 // let's try to find the other one
470 if ( (keys & (1 << u)) && (currentConfig.KeyBinds[u] & acts_c) ) {
471 allActions[pl] |= acts_c & currentConfig.KeyBinds[u];
472 keys &= ~((1 << i) | (1 << u));
476 // add non-combo actions if combo ones were not found
477 if (!acts_c || u == 32)
478 allActions[pl] |= acts & ~kb_combo_acts;
480 allActions[pl] |= acts;
485 PicoPad[0] = allActions[0] & 0xfff;
486 PicoPad[1] = allActions[1] & 0xfff;
488 if (allActions[0] & 0x7000) emu_DoTurbo(&PicoPad[0], allActions[0]);
489 if (allActions[1] & 0x7000) emu_DoTurbo(&PicoPad[1], allActions[1]);
491 events = (allActions[0] | allActions[1]) >> 16;
493 // volume is treated in special way and triggered every frame
494 if ((events & 0x6000) && PsndOut != NULL)
496 int vol = currentConfig.volume;
497 if (events & 0x2000) {
498 if (vol < 100) vol++;
502 FrameworkAudio_SetVolume(vol, vol);
503 sprintf(noticeMsg, "VOL: %02i ", vol);
504 noticeMsgTime = GetTickCount();
505 currentConfig.volume = vol;
508 events &= ~prevEvents;
509 if (events) RunEvents(events);
510 if (movie_data) emu_updateMovie();
512 prevEvents = (allActions[0] | allActions[1]) >> 16;
515 void emu_platformDebugCat(char *str)
520 static void simpleWait(DWORD until)
525 tval = GetTickCount();
526 diff = (int)until - (int)tval;
530 while ((tval = GetTickCount()) < until && until - tval < 512) // some simple overflow detection
531 spend_cycles(1024*2);
536 static int PsndRate_old = 0, PicoOpt_old = 0, pal_old = 0;
537 char fpsbuff[24]; // fps count c string
538 DWORD tval, tval_prev = 0, tval_thissec = 0; // timing
539 int frames_done = 0, frames_shown = 0, oldmodes = 0, sec_ms = 1000;
540 int target_fps, target_frametime, lim_time, tval_diff, i;
543 lprintf("entered emu_Loop()\n");
547 // make sure we are in correct mode
549 if (currentConfig.scaling) PicoOpt|=0x4000;
550 else PicoOpt&=~0x4000;
552 oldmodes = ((Pico.video.reg[12]&1)<<2) ^ 0xc;
553 emu_findKeyBindCombos();
555 // pal/ntsc might have changed, reset related stuff
556 target_fps = Pico.m.pal ? 50 : 60;
557 target_frametime = Pico.m.pal ? (1000<<8)/50 : (1000<<8)/60+1;
561 if (PicoAHW & PAHW_MCD) PicoCDBufferInit();
563 // prepare sound stuff
565 if (currentConfig.EmuOpt & 4)
567 int ret, snd_excess_add, stereo;
568 if (PsndRate != PsndRate_old || (PicoOpt&0x0b) != (PicoOpt_old&0x0b) || Pico.m.pal != pal_old) {
569 PsndRerate(Pico.m.frame_count ? 1 : 0);
571 stereo=(PicoOpt&8)>>3;
572 snd_excess_add = ((PsndRate - PsndLen*target_fps)<<16) / target_fps;
573 snd_cbuf_samples = (PsndRate<<stereo) * 16 / target_fps;
574 lprintf("starting audio: %i len: %i (ex: %04x) stereo: %i, pal: %i\n",
575 PsndRate, PsndLen, snd_excess_add, stereo, Pico.m.pal);
576 ret = FrameworkAudio_Init(PsndRate, snd_cbuf_samples, stereo);
578 lprintf("FrameworkAudio_Init() failed: %i\n", ret);
579 sprintf(noticeMsg, "sound init failed (%i), snd disabled", ret);
580 noticeMsgTime = GetTickCount();
581 currentConfig.EmuOpt &= ~4;
583 FrameworkAudio_SetVolume(currentConfig.volume, currentConfig.volume);
584 PicoWriteSound = updateSound;
585 snd_cbuff = FrameworkAudio_56448Buffer();
586 PsndOut = snd_cbuff + snd_cbuf_samples / 2; // start writing at the middle
588 PsndRate_old = PsndRate;
589 PicoOpt_old = PicoOpt;
590 pal_old = Pico.m.pal;
595 while (engineState == PGS_Running)
599 tval = GetTickCount();
600 if (reset_timing || tval < tval_prev) {
601 //stdbg("timing reset");
604 frames_shown = frames_done = 0;
607 // show notice message?
609 static int noticeMsgSum;
610 if (tval - noticeMsgTime > 2000) { // > 2.0 sec
615 int sum = noticeMsg[0]+noticeMsg[1]+noticeMsg[2];
616 if (sum != noticeMsgSum) { clearArea(0); noticeMsgSum = sum; }
621 // check for mode changes
622 modes = ((Pico.video.reg[12]&1)<<2)|(Pico.video.reg[1]&8);
623 if (modes != oldmodes) {
629 if (tval - tval_thissec >= sec_ms)
632 static int bench = 0, bench_fps = 0, bench_fps_s = 0, bfp = 0, bf[4];
635 bench_fps_s = bench_fps;
636 bf[bfp++ & 3] = bench_fps;
639 bench_fps += frames_shown;
640 sprintf(fpsbuff, "%02i/%02i/%02i", frames_shown, bench_fps_s, (bf[0]+bf[1]+bf[2]+bf[3])>>2);
642 if(currentConfig.EmuOpt & 2)
643 sprintf(fpsbuff, "%02i/%02i", frames_shown, frames_done);
645 //tval_thissec += 1000;
646 tval_thissec += sec_ms;
650 /* some code which tries to sync things to audio clock, the dirty way */
651 static int audio_skew_prev = 0;
652 int audio_skew, adj, co = 9, shift = 7;
653 audio_skew = snd_all_samples*2 - FrameworkAudio_BufferPos();
654 if (PsndRate == 22050) co = 10;
655 if (PsndRate > 22050) co = 11;
656 if (PicoOpt&8) shift++;
657 if (audio_skew < 0) {
658 adj = -((-audio_skew) >> shift);
659 if (audio_skew > -(6<<co)) adj>>=1;
660 if (audio_skew > -(4<<co)) adj>>=1;
661 if (audio_skew > -(2<<co)) adj>>=1;
662 if (audio_skew > audio_skew_prev) adj>>=2; // going up already
664 adj = audio_skew >> shift;
665 if (audio_skew < (6<<co)) adj>>=1;
666 if (audio_skew < (4<<co)) adj>>=1;
667 if (audio_skew < (2<<co)) adj>>=1;
668 if (audio_skew < audio_skew_prev) adj>>=2;
670 audio_skew_prev = audio_skew;
671 target_frametime += adj;
672 sec_ms = (target_frametime * target_fps) >> 8;
673 //stdbg("%i %i %i", audio_skew, adj, sec_ms);
674 frames_done = frames_shown = 0;
676 else if (currentConfig.Frameskip < 0) {
677 frames_done -= target_fps; if (frames_done < 0) frames_done = 0;
678 frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;
679 if (frames_shown > frames_done) frames_shown = frames_done;
681 frames_done = frames_shown = 0;
685 sprintf(fpsbuff, "%i", Pico.m.frame_count);
689 lim_time = (frames_done+1) * target_frametime;
690 if (currentConfig.Frameskip >= 0) // frameskip enabled
692 for (i = 0; i < currentConfig.Frameskip; i++) {
694 SkipFrame(); frames_done++;
695 if (PsndOut) { // do framelimitting if sound is enabled
697 tval = GetTickCount();
698 tval_diff = (int)(tval - tval_thissec) << 8;
699 if (tval_diff < lim_time) // we are too fast
700 simpleWait(tval + ((lim_time - tval_diff)>>8));
702 lim_time += target_frametime;
705 else // auto frameskip
708 tval = GetTickCount();
709 tval_diff = (int)(tval - tval_thissec) << 8;
710 if (tval_diff > lim_time)
712 // no time left for this frame - skip
713 if (tval_diff - lim_time >= (300<<8)) {
714 /* something caused a slowdown for us (disk access? cache flush?)
715 * try to recover by resetting timing... */
720 SkipFrame(); frames_done++;
727 if (currentConfig.EmuOpt&0x80)
728 /* be sure correct framebuffer is locked */
729 giz_screen = fb_lock((currentConfig.EmuOpt&0x8000) ? 0 : 1);
733 if (giz_screen == NULL)
734 giz_screen = fb_lock((currentConfig.EmuOpt&0x8000) ? 0 : 1);
736 blit(fpsbuff, notice);
738 if (giz_screen != NULL) {
743 if (currentConfig.EmuOpt&0x2000)
744 Framework2D_WaitVSync();
746 if (currentConfig.EmuOpt&0x8000)
750 tval = GetTickCount();
751 tval_diff = (int)(tval - tval_thissec) << 8;
753 if (currentConfig.Frameskip < 0 && tval_diff - lim_time >= (300<<8)) // slowdown detection
755 else if (PsndOut != NULL || currentConfig.Frameskip < 0)
757 // sleep if we are still too fast
758 if (tval_diff < lim_time)
761 simpleWait(tval + ((lim_time - tval_diff) >> 8));
765 frames_done++; frames_shown++;
769 if (PicoAHW & PAHW_MCD) PicoCDBufferFree();
771 if (PsndOut != NULL) {
772 PsndOut = snd_cbuff = NULL;
773 FrameworkAudio_Close();
777 if ((currentConfig.EmuOpt & 1) && SRam.changed) {
778 emu_stateCb("Writing SRAM/BRAM..");
779 emu_SaveLoadGame(0, 1);
785 void emu_ResetGame(void)