psp bugfixes, refactoring, stuff
[picodrive.git] / platform / gp2x / emu.c
1 // (c) Copyright 2006-2007 notaz, All rights reserved.\r
2 // Free for non-commercial use.\r
3 \r
4 // For commercial use, separate licencing terms must be obtained.\r
5 \r
6 #include <stdio.h>\r
7 #include <stdlib.h>\r
8 #include <sys/time.h>\r
9 #include <sys/stat.h>\r
10 #include <sys/types.h>\r
11 #include <linux/limits.h>\r
12 #include <ctype.h>\r
13 #include <unistd.h>\r
14 \r
15 #include <stdarg.h>\r
16 \r
17 #include "emu.h"\r
18 #include "gp2x.h"\r
19 #include "usbjoy.h"\r
20 #include "menu.h"\r
21 #include "../common/arm_utils.h"\r
22 #include "../common/fonts.h"\r
23 #include "../common/emu.h"\r
24 #include "cpuctrl.h"\r
25 \r
26 #include <Pico/PicoInt.h>\r
27 #include <Pico/Patch.h>\r
28 #include <zlib/zlib.h>\r
29 \r
30 //#define PFRAMES\r
31 \r
32 #ifdef BENCHMARK\r
33 #define OSD_FPS_X 220\r
34 #else\r
35 #define OSD_FPS_X 260\r
36 #endif\r
37 \r
38 \r
39 int engineState;\r
40 int select_exits = 0;\r
41 \r
42 char romFileName[PATH_MAX];\r
43 \r
44 extern int crashed_940;\r
45 \r
46 static short sndBuffer[2*44100/50];\r
47 static struct timeval noticeMsgTime = { 0, 0 }; // when started showing\r
48 static int osd_fps_x;\r
49 static int combo_keys = 0, combo_acts = 0;      // keys and actions which need button combos\r
50 static int gp2x_old_gamma = 100;\r
51 char noticeMsg[64];                     // notice msg to draw\r
52 unsigned char *PicoDraw2FB = NULL;  // temporary buffer for alt renderer\r
53 int reset_timing = 0;\r
54 \r
55 static void emu_msg_cb(const char *msg);\r
56 static void emu_msg_tray_open(void);\r
57 \r
58 \r
59 void emu_noticeMsgUpdated(void)\r
60 {\r
61         gettimeofday(&noticeMsgTime, 0);\r
62 }\r
63 \r
64 void emu_getMainDir(char *dst, int len)\r
65 {\r
66         extern char **g_argv;\r
67         int j;\r
68 \r
69         strncpy(dst, g_argv[0], len);\r
70         len -= 32; // reserve\r
71         if (len < 0) len = 0;\r
72         dst[len] = 0;\r
73         for (j = strlen(dst); j > 0; j--)\r
74                 if (dst[j] == '/') { dst[j+1] = 0; break; }\r
75 }\r
76 \r
77 void emu_Init(void)\r
78 {\r
79         // make temp buffer for alt renderer\r
80         PicoDraw2FB = malloc((8+320)*(8+240+8));\r
81         if (!PicoDraw2FB)\r
82         {\r
83                 printf("PicoDraw2FB == 0\n");\r
84         }\r
85 \r
86         // make dirs for saves, cfgs, etc.\r
87         mkdir("mds", 0777);\r
88         mkdir("srm", 0777);\r
89         mkdir("brm", 0777);\r
90         mkdir("cfg", 0777);\r
91 \r
92         PicoInit();\r
93         PicoMessage = emu_msg_cb;\r
94         PicoMCDopenTray = emu_msg_tray_open;\r
95         PicoMCDcloseTray = menu_loop_tray;\r
96 }\r
97 \r
98 \r
99 static void find_combos(void)\r
100 {\r
101         int act, u;\r
102 \r
103         // find out which keys and actions are combos\r
104         combo_keys = combo_acts = 0;\r
105         for (act = 0; act < 32; act++)\r
106         {\r
107                 int keyc = 0;\r
108                 if (act == 16 || act == 17) continue; // player2 flag\r
109                 for (u = 0; u < 32; u++)\r
110                 {\r
111                         if (currentConfig.KeyBinds[u] & (1 << act)) keyc++;\r
112                 }\r
113                 if (keyc > 1)\r
114                 {\r
115                         // loop again and mark those keys and actions as combo\r
116                         for (u = 0; u < 32; u++)\r
117                         {\r
118                                 if (currentConfig.KeyBinds[u] & (1 << act)) {\r
119                                         combo_keys |= 1 << u;\r
120                                         combo_acts |= 1 << act;\r
121                                 }\r
122                         }\r
123                 }\r
124         }\r
125         // printf("combo keys/acts: %08x %08x\n", combo_keys, combo_acts);\r
126 }\r
127 \r
128 \r
129 static void scaling_update(void)\r
130 {\r
131         PicoOpt &= ~0x4100;\r
132         switch (currentConfig.scaling) {\r
133                 default: break; // off\r
134                 case 1:  // hw hor\r
135                 case 2:  PicoOpt |=  0x0100; break; // hw hor+vert\r
136                 case 3:  PicoOpt |=  0x4000; break; // sw hor\r
137         }\r
138 }\r
139 \r
140 \r
141 void emu_Deinit(void)\r
142 {\r
143         // save SRAM\r
144         if((currentConfig.EmuOpt & 1) && SRam.changed) {\r
145                 emu_SaveLoadGame(0, 1);\r
146                 SRam.changed = 0;\r
147         }\r
148 \r
149         if (!(currentConfig.EmuOpt & 0x20)) {\r
150                 FILE *f = fopen(PicoConfigFile, "r+b");\r
151                 if (!f) emu_WriteConfig(0);\r
152                 else {\r
153                         // if we already have config, reload it, except last ROM\r
154                         fseek(f, sizeof(currentConfig.lastRomFile), SEEK_SET);\r
155                         fread(&currentConfig.EmuOpt, 1, sizeof(currentConfig) - sizeof(currentConfig.lastRomFile), f);\r
156                         fseek(f, 0, SEEK_SET);\r
157                         fwrite(&currentConfig, 1, sizeof(currentConfig), f);\r
158                         fflush(f);\r
159                         fclose(f);\r
160 #ifndef NO_SYNC\r
161                         sync();\r
162 #endif\r
163                 }\r
164         }\r
165 \r
166         free(PicoDraw2FB);\r
167 \r
168         PicoExit();\r
169 \r
170         // restore gamma\r
171         if (gp2x_old_gamma != 100)\r
172                 set_gamma(100, 0);\r
173 }\r
174 \r
175 void emu_setDefaultConfig(void)\r
176 {\r
177         memset(&currentConfig, 0, sizeof(currentConfig));\r
178         currentConfig.lastRomFile[0] = 0;\r
179         currentConfig.EmuOpt  = 0x1f | 0x600; // | confirm_save, cd_leds\r
180         currentConfig.PicoOpt = 0x0f | 0xe00; // | use_940, cd_pcm, cd_cdda\r
181         currentConfig.PsndRate = 22050; // 44100;\r
182         currentConfig.PicoRegion = 0; // auto\r
183         currentConfig.PicoAutoRgnOrder = 0x184; // US, EU, JP\r
184         currentConfig.Frameskip = -1; // auto\r
185         currentConfig.CPUclock = 200;\r
186         currentConfig.volume = 50;\r
187         currentConfig.KeyBinds[ 0] = 1<<0; // SACB RLDU\r
188         currentConfig.KeyBinds[ 4] = 1<<1;\r
189         currentConfig.KeyBinds[ 2] = 1<<2;\r
190         currentConfig.KeyBinds[ 6] = 1<<3;\r
191         currentConfig.KeyBinds[14] = 1<<4;\r
192         currentConfig.KeyBinds[13] = 1<<5;\r
193         currentConfig.KeyBinds[12] = 1<<6;\r
194         currentConfig.KeyBinds[ 8] = 1<<7;\r
195         currentConfig.KeyBinds[15] = 1<<26; // switch rend\r
196         currentConfig.KeyBinds[10] = 1<<27; // save state\r
197         currentConfig.KeyBinds[11] = 1<<28; // load state\r
198         currentConfig.KeyBinds[23] = 1<<29; // vol up\r
199         currentConfig.KeyBinds[22] = 1<<30; // vol down\r
200         currentConfig.gamma = 100;\r
201         currentConfig.PicoCDBuffers = 64;\r
202         currentConfig.scaling = 0;\r
203 }\r
204 \r
205 void osd_text(int x, int y, const char *text)\r
206 {\r
207         int len = strlen(text)*8;\r
208 \r
209         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
210                 int *p, i, h;\r
211                 x &= ~3; // align x\r
212                 len = (len+3) >> 2;\r
213                 for (h = 0; h < 8; h++) {\r
214                         p = (int *) ((unsigned char *) gp2x_screen+x+320*(y+h));\r
215                         for (i = len; i; i--, p++) *p = 0xe0e0e0e0;\r
216                 }\r
217                 emu_textOut8(x, y, text);\r
218         } else {\r
219                 int *p, i, h;\r
220                 x &= ~1; // align x\r
221                 len = (len+1) >> 1;\r
222                 for (h = 0; h < 8; h++) {\r
223                         p = (int *) ((unsigned short *) gp2x_screen+x+320*(y+h));\r
224                         for (i = len; i; i--, p++) *p = (*p>>2)&0x39e7;\r
225                 }\r
226                 emu_textOut16(x, y, text);\r
227         }\r
228 }\r
229 \r
230 static void cd_leds(void)\r
231 {\r
232 //      static\r
233         int old_reg;\r
234 //      if (!((Pico_mcd->s68k_regs[0] ^ old_reg) & 3)) return; // no change // mmu hack problems?\r
235         old_reg = Pico_mcd->s68k_regs[0];\r
236 \r
237         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
238                 // 8-bit modes\r
239                 unsigned int col_g = (old_reg & 2) ? 0xc0c0c0c0 : 0xe0e0e0e0;\r
240                 unsigned int col_r = (old_reg & 1) ? 0xd0d0d0d0 : 0xe0e0e0e0;\r
241                 *(unsigned int *)((char *)gp2x_screen + 320*2+ 4) =\r
242                 *(unsigned int *)((char *)gp2x_screen + 320*3+ 4) =\r
243                 *(unsigned int *)((char *)gp2x_screen + 320*4+ 4) = col_g;\r
244                 *(unsigned int *)((char *)gp2x_screen + 320*2+12) =\r
245                 *(unsigned int *)((char *)gp2x_screen + 320*3+12) =\r
246                 *(unsigned int *)((char *)gp2x_screen + 320*4+12) = col_r;\r
247         } else {\r
248                 // 16-bit modes\r
249                 unsigned int *p = (unsigned int *)((short *)gp2x_screen + 320*2+4);\r
250                 unsigned int col_g = (old_reg & 2) ? 0x06000600 : 0;\r
251                 unsigned int col_r = (old_reg & 1) ? 0xc000c000 : 0;\r
252                 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 320/2 - 12/2;\r
253                 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 320/2 - 12/2;\r
254                 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r;\r
255         }\r
256 }\r
257 \r
258 static int EmuScan16(unsigned int num, void *sdata)\r
259 {\r
260         if (!(Pico.video.reg[1]&8)) num += 8;\r
261         DrawLineDest = (unsigned short *) gp2x_screen + 320*(num+1);\r
262 \r
263         return 0;\r
264 }\r
265 \r
266 static int EmuScan8(unsigned int num, void *sdata)\r
267 {\r
268         if (!(Pico.video.reg[1]&8)) num += 8;\r
269         DrawLineDest = (unsigned char *)  gp2x_screen + 320*(num+1);\r
270 \r
271         return 0;\r
272 }\r
273 \r
274 int localPal[0x100];\r
275 static void (*vidCpyM2)(void *dest, void *src) = NULL;\r
276 \r
277 static void blit(const char *fps, const char *notice)\r
278 {\r
279         int emu_opt = currentConfig.EmuOpt;\r
280 \r
281         if (PicoOpt&0x10) {\r
282                 // 8bit fast renderer\r
283                 if (Pico.m.dirtyPal) {\r
284                         Pico.m.dirtyPal = 0;\r
285                         vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
286                         // feed new palette to our device\r
287                         gp2x_video_setpalette(localPal, 0x40);\r
288                 }\r
289                 vidCpyM2((unsigned char *)gp2x_screen+320*8, PicoDraw2FB+328*8);\r
290         } else if (!(emu_opt&0x80)) {\r
291                 // 8bit accurate renderer\r
292                 if (Pico.m.dirtyPal) {\r
293                         Pico.m.dirtyPal = 0;\r
294                         if(Pico.video.reg[0xC]&8) { // shadow/hilight mode\r
295                                 vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
296                                 vidConvCpyRGB32sh(localPal+0x40, Pico.cram, 0x40);\r
297                                 vidConvCpyRGB32hi(localPal+0x80, Pico.cram, 0x40);\r
298                                 blockcpy(localPal+0xc0, localPal+0x40, 0x40*4);\r
299                                 localPal[0xc0] = 0x0000c000;\r
300                                 localPal[0xd0] = 0x00c00000;\r
301                                 localPal[0xe0] = 0x00000000; // reserved pixels for OSD\r
302                                 localPal[0xf0] = 0x00ffffff;\r
303                                 gp2x_video_setpalette(localPal, 0x100);\r
304                         } else if (rendstatus & 0x20) { // mid-frame palette changes\r
305                                 vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
306                                 vidConvCpyRGB32(localPal+0x40, HighPal, 0x40);\r
307                                 vidConvCpyRGB32(localPal+0x80, HighPal+0x40, 0x40);\r
308                                 gp2x_video_setpalette(localPal, 0xc0);\r
309                         } else {\r
310                                 vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
311                                 gp2x_video_setpalette(localPal, 0x40);\r
312                         }\r
313                 }\r
314         }\r
315 \r
316         if (notice || (emu_opt & 2)) {\r
317                 int h = 232;\r
318                 if (currentConfig.scaling == 2 && !(Pico.video.reg[1]&8)) h -= 8;\r
319                 if (notice) osd_text(4, h, notice);\r
320                 if (emu_opt & 2)\r
321                         osd_text(osd_fps_x, h, fps);\r
322         }\r
323         if ((emu_opt & 0x400) && (PicoMCD & 1))\r
324                 cd_leds();\r
325 \r
326         //gp2x_video_wait_vsync();\r
327         gp2x_video_flip();\r
328 \r
329         if (!(PicoOpt&0x10)) {\r
330                 if (!(Pico.video.reg[1]&8)) {\r
331                         if (currentConfig.EmuOpt&0x80) {\r
332                                 DrawLineDest = (unsigned short *) gp2x_screen + 320*8;\r
333                         } else {\r
334                                 DrawLineDest = (unsigned char  *) gp2x_screen + 320*8;\r
335                         }\r
336                 } else {\r
337                         DrawLineDest = gp2x_screen;\r
338                 }\r
339         }\r
340 }\r
341 \r
342 \r
343 // clears whole screen or just the notice area (in all buffers)\r
344 static void clearArea(int full)\r
345 {\r
346         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
347                 // 8-bit renderers\r
348                 if (full) gp2x_memset_all_buffers(0, 0xe0, 320*240);\r
349                 else      gp2x_memset_all_buffers(320*232, 0xe0, 320*8);\r
350         } else {\r
351                 // 16bit accurate renderer\r
352                 if (full) gp2x_memset_all_buffers(0, 0, 320*240*2);\r
353                 else      gp2x_memset_all_buffers(320*232*2, 0, 320*8*2);\r
354         }\r
355 }\r
356 \r
357 \r
358 static void vidResetMode(void)\r
359 {\r
360         if (PicoOpt&0x10) {\r
361                 gp2x_video_changemode(8);\r
362         } else if (currentConfig.EmuOpt&0x80) {\r
363                 gp2x_video_changemode(16);\r
364                 PicoDrawSetColorFormat(1);\r
365                 PicoScan = EmuScan16;\r
366                 PicoScan(0, 0);\r
367         } else {\r
368                 gp2x_video_changemode(8);\r
369                 PicoDrawSetColorFormat(2);\r
370                 PicoScan = EmuScan8;\r
371                 PicoScan(0, 0);\r
372         }\r
373         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
374                 // setup pal for 8-bit modes\r
375                 localPal[0xc0] = 0x0000c000; // MCD LEDs\r
376                 localPal[0xd0] = 0x00c00000;\r
377                 localPal[0xe0] = 0x00000000; // reserved pixels for OSD\r
378                 localPal[0xf0] = 0x00ffffff;\r
379                 gp2x_video_setpalette(localPal, 0x100);\r
380                 gp2x_memset_all_buffers(0, 0xe0, 320*240);\r
381                 gp2x_video_flip();\r
382         }\r
383         Pico.m.dirtyPal = 1;\r
384         // reset scaling\r
385         if (currentConfig.scaling == 2 && !(Pico.video.reg[1]&8))\r
386              gp2x_video_RGB_setscaling(8, (PicoOpt&0x100)&&!(Pico.video.reg[12]&1) ? 256 : 320, 224);\r
387         else gp2x_video_RGB_setscaling(0, (PicoOpt&0x100)&&!(Pico.video.reg[12]&1) ? 256 : 320, 240);\r
388 }\r
389 \r
390 \r
391 static void emu_msg_cb(const char *msg)\r
392 {\r
393         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
394                 // 8-bit renderers\r
395                 gp2x_memset_all_buffers(320*232, 0xe0, 320*8);\r
396                 osd_text(4, 232, msg);\r
397                 gp2x_memcpy_all_buffers((char *)gp2x_screen+320*232, 320*232, 320*8);\r
398         } else {\r
399                 // 16bit accurate renderer\r
400                 gp2x_memset_all_buffers(320*232*2, 0, 320*8*2);\r
401                 osd_text(4, 232, msg);\r
402                 gp2x_memcpy_all_buffers((char *)gp2x_screen+320*232*2, 320*232*2, 320*8*2);\r
403         }\r
404         gettimeofday(&noticeMsgTime, 0);\r
405         noticeMsgTime.tv_sec -= 2;\r
406 \r
407         /* assumption: emu_msg_cb gets called only when something slow is about to happen */\r
408         reset_timing = 1;\r
409 }\r
410 \r
411 static void emu_state_cb(const char *str)\r
412 {\r
413         clearArea(0);\r
414         blit("", str);\r
415 }\r
416 \r
417 static void emu_msg_tray_open(void)\r
418 {\r
419         strcpy(noticeMsg, "CD tray opened");\r
420         gettimeofday(&noticeMsgTime, 0);\r
421 }\r
422 \r
423 static void RunEvents(unsigned int which)\r
424 {\r
425         if(which & 0x1800) { // save or load (but not both)\r
426                 int do_it = 1;\r
427                 if ( emu_checkSaveFile(state_slot) &&\r
428                                 (( (which & 0x1000) && (currentConfig.EmuOpt & 0x800)) ||   // load\r
429                                  (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200))) ) { // save\r
430                         unsigned long keys;\r
431                         blit("", (which & 0x1000) ? "LOAD STATE? (Y=yes, X=no)" : "OVERWRITE SAVE? (Y=yes, X=no)");\r
432                         while( !((keys = gp2x_joystick_read(1)) & (GP2X_X|GP2X_Y)) )\r
433                                 usleep(50*1024);\r
434                         if (keys & GP2X_X) do_it = 0;\r
435                         clearArea(0);\r
436                 }\r
437                 if (do_it) {\r
438                         osd_text(4, 232, (which & 0x1000) ? "LOADING GAME" : "SAVING GAME");\r
439                         PicoStateProgressCB = emu_state_cb;\r
440                         gp2x_memcpy_all_buffers(gp2x_screen, 0, 320*240*2);\r
441                         emu_SaveLoadGame((which & 0x1000) >> 12, 0);\r
442                         PicoStateProgressCB = NULL;\r
443                 }\r
444 \r
445                 reset_timing = 1;\r
446         }\r
447         if(which & 0x0400) { // switch renderer\r
448                 if      (  PicoOpt&0x10)             { PicoOpt&=~0x10; currentConfig.EmuOpt |= 0x80; }\r
449                 else if (!(currentConfig.EmuOpt&0x80)) PicoOpt|= 0x10;\r
450                 else   currentConfig.EmuOpt &= ~0x80;\r
451 \r
452                 vidResetMode();\r
453 \r
454                 if (PicoOpt&0x10) {\r
455                         strcpy(noticeMsg, " 8bit fast renderer");\r
456                 } else if (currentConfig.EmuOpt&0x80) {\r
457                         strcpy(noticeMsg, "16bit accurate renderer");\r
458                 } else {\r
459                         strcpy(noticeMsg, " 8bit accurate renderer");\r
460                 }\r
461 \r
462                 gettimeofday(&noticeMsgTime, 0);\r
463         }\r
464         if(which & 0x0300) {\r
465                 if(which&0x0200) {\r
466                         state_slot -= 1;\r
467                         if(state_slot < 0) state_slot = 9;\r
468                 } else {\r
469                         state_slot += 1;\r
470                         if(state_slot > 9) state_slot = 0;\r
471                 }\r
472                 sprintf(noticeMsg, "SAVE SLOT %i [%s]", state_slot, emu_checkSaveFile(state_slot) ? "USED" : "FREE");\r
473                 gettimeofday(&noticeMsgTime, 0);\r
474         }\r
475         if(which & 0x0080) {\r
476                 engineState = PGS_Menu;\r
477         }\r
478 }\r
479 \r
480 \r
481 static void updateKeys(void)\r
482 {\r
483         unsigned long keys, allActions[2] = { 0, 0 }, events;\r
484         static unsigned long prevEvents = 0;\r
485         int joy, i;\r
486 \r
487         keys = gp2x_joystick_read(0);\r
488         if (keys & GP2X_SELECT) {\r
489                 engineState = select_exits ? PGS_Quit : PGS_Menu;\r
490                 // wait until select is released, so menu would not resume game\r
491                 while (gp2x_joystick_read(1) & GP2X_SELECT) usleep(50*1000);\r
492         }\r
493 \r
494         keys &= CONFIGURABLE_KEYS;\r
495 \r
496         for (i = 0; i < 32; i++)\r
497         {\r
498                 if (keys & (1 << i)) {\r
499                         int pl, acts = currentConfig.KeyBinds[i];\r
500                         if (!acts) continue;\r
501                         pl = (acts >> 16) & 1;\r
502                         if (combo_keys & (1 << i)) {\r
503                                 int u = i+1, acts_c = acts & combo_acts;\r
504                                 // let's try to find the other one\r
505                                 if (acts_c)\r
506                                         for (; u < 32; u++)\r
507                                                 if ( (currentConfig.KeyBinds[u] & acts_c) && (keys & (1 << u)) ) {\r
508                                                         allActions[pl] |= acts_c;\r
509                                                         keys &= ~((1 << i) | (1 << u));\r
510                                                         break;\r
511                                                 }\r
512                                 // add non-combo actions if combo ones were not found\r
513                                 if (!acts_c || u == 32)\r
514                                         allActions[pl] |= acts & ~combo_acts;\r
515                         } else {\r
516                                 allActions[pl] |= acts;\r
517                         }\r
518                 }\r
519         }\r
520 \r
521         // add joy inputs\r
522         if (num_of_joys > 0)\r
523         {\r
524                 gp2x_usbjoy_update();\r
525                 for (joy = 0; joy < num_of_joys; joy++) {\r
526                         int keys = gp2x_usbjoy_check2(joy);\r
527                         for (i = 0; i < 32; i++) {\r
528                                 if (keys & (1 << i)) {\r
529                                         int acts = currentConfig.JoyBinds[joy][i];\r
530                                         int pl = (acts >> 16) & 1;\r
531                                         allActions[pl] |= acts;\r
532                                 }\r
533                         }\r
534                 }\r
535         }\r
536 \r
537         PicoPad[0] = (unsigned short) allActions[0];\r
538         PicoPad[1] = (unsigned short) allActions[1];\r
539 \r
540         events = (allActions[0] | allActions[1]) >> 16;\r
541 \r
542         // volume is treated in special way and triggered every frame\r
543         if(events & 0x6000) {\r
544                 int vol = currentConfig.volume;\r
545                 if (events & 0x2000) {\r
546                         if (vol < 99) vol++;\r
547                 } else {\r
548                         if (vol >  0) vol--;\r
549                 }\r
550                 gp2x_sound_volume(vol, vol);\r
551                 sprintf(noticeMsg, "VOL: %02i", vol);\r
552                 gettimeofday(&noticeMsgTime, 0);\r
553                 currentConfig.volume = vol;\r
554         }\r
555 \r
556         events &= ~prevEvents;\r
557         if (events) RunEvents(events);\r
558         if (movie_data) emu_updateMovie();\r
559 \r
560         prevEvents = (allActions[0] | allActions[1]) >> 16;\r
561 }\r
562 \r
563 \r
564 static void updateSound(int len)\r
565 {\r
566         if (PicoOpt&8) len<<=1;\r
567 \r
568         /* avoid writing audio when lagging behind to prevent audio lag */\r
569         if (PicoSkipFrame != 2)\r
570                 gp2x_sound_write(PsndOut, len<<1);\r
571 }\r
572 \r
573 \r
574 static void SkipFrame(int do_audio)\r
575 {\r
576         PicoSkipFrame=do_audio ? 1 : 2;\r
577         PicoFrame();\r
578         PicoSkipFrame=0;\r
579 }\r
580 \r
581 \r
582 void emu_forcedFrame(void)\r
583 {\r
584         int po_old = PicoOpt;\r
585         int eo_old = currentConfig.EmuOpt;\r
586 \r
587         PicoOpt &= ~0x0010;\r
588         PicoOpt |=  0x4080; // soft_scale | acc_sprites\r
589         currentConfig.EmuOpt |= 0x80;\r
590 \r
591         //vidResetMode();\r
592         PicoDrawSetColorFormat(1);\r
593         PicoScan = EmuScan16;\r
594         PicoScan(0, 0);\r
595         Pico.m.dirtyPal = 1;\r
596         PicoFrameDrawOnly();\r
597 \r
598 /*\r
599         if (!(Pico.video.reg[12]&1)) {\r
600                 vidCpyM2 = vidCpyM2_32col;\r
601                 clearArea(1);\r
602         } else  vidCpyM2 = vidCpyM2_40col;\r
603 \r
604         vidCpyM2((unsigned char *)gp2x_screen+320*8, PicoDraw2FB+328*8);\r
605         vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
606         gp2x_video_setpalette(localPal, 0x40);\r
607 */\r
608         PicoOpt = po_old;\r
609         currentConfig.EmuOpt = eo_old;\r
610 }\r
611 \r
612 static void simpleWait(int thissec, int lim_time)\r
613 {\r
614         struct timeval tval;\r
615 \r
616         spend_cycles(1024);\r
617         gettimeofday(&tval, 0);\r
618         if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
619 \r
620         while(tval.tv_usec < lim_time)\r
621         {\r
622                 spend_cycles(1024);\r
623                 gettimeofday(&tval, 0);\r
624                 if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
625         }\r
626 }\r
627 \r
628 \r
629 void emu_Loop(void)\r
630 {\r
631         static int gp2x_old_clock = 200;\r
632         static int PsndRate_old = 0, PicoOpt_old = 0, EmuOpt_old = 0, pal_old = 0;\r
633         char fpsbuff[24]; // fps count c string\r
634         struct timeval tval; // timing\r
635         int thissec = 0, frames_done = 0, frames_shown = 0, oldmodes = 0;\r
636         int target_fps, target_frametime, lim_time, vsync_offset, i;\r
637         char *notice = 0;\r
638 \r
639         printf("entered emu_Loop()\n");\r
640 \r
641         if (gp2x_old_clock != currentConfig.CPUclock) {\r
642                 printf("changing clock to %i...", currentConfig.CPUclock); fflush(stdout);\r
643                 set_FCLK(currentConfig.CPUclock);\r
644                 gp2x_old_clock = currentConfig.CPUclock;\r
645                 printf(" done\n");\r
646         }\r
647 \r
648         if (gp2x_old_gamma != currentConfig.gamma || (EmuOpt_old&0x1000) != (currentConfig.EmuOpt&0x1000)) {\r
649                 set_gamma(currentConfig.gamma, !!(currentConfig.EmuOpt&0x1000));\r
650                 gp2x_old_gamma = currentConfig.gamma;\r
651                 printf("updated gamma to %i, A_SN's curve: %i\n", currentConfig.gamma, !!(currentConfig.EmuOpt&0x1000));\r
652         }\r
653 \r
654         if ((EmuOpt_old&0x2000) != (currentConfig.EmuOpt&0x2000)) {\r
655                 if (currentConfig.EmuOpt&0x2000)\r
656                      set_LCD_custom_rate(Pico.m.pal ? LCDR_100 : LCDR_120);\r
657                 else unset_LCD_custom_rate();\r
658         }\r
659 \r
660         EmuOpt_old = currentConfig.EmuOpt;\r
661         fpsbuff[0] = 0;\r
662 \r
663         // make sure we are in correct mode\r
664         vidResetMode();\r
665         scaling_update();\r
666         Pico.m.dirtyPal = 1;\r
667         oldmodes = ((Pico.video.reg[12]&1)<<2) ^ 0xc;\r
668         find_combos();\r
669 \r
670         // pal/ntsc might have changed, reset related stuff\r
671         target_fps = Pico.m.pal ? 50 : 60;\r
672         target_frametime = 1000000/target_fps;\r
673         reset_timing = 1;\r
674 \r
675         // prepare sound stuff\r
676         if(currentConfig.EmuOpt & 4) {\r
677                 int snd_excess_add;\r
678                 if (PsndRate != PsndRate_old || (PicoOpt&0x20b) != (PicoOpt_old&0x20b) || Pico.m.pal != pal_old ||\r
679                                 ((PicoOpt&0x200) && crashed_940)) {\r
680                         /* if 940 is turned off, we need it to be put back to sleep */\r
681                         if (!(PicoOpt&0x200) && ((PicoOpt^PicoOpt_old)&0x200)) {\r
682                                 Reset940(1, 2);\r
683                                 Pause940(1);\r
684                         }\r
685                         PsndRerate(Pico.m.frame_count ? 1 : 0);\r
686                 }\r
687                 snd_excess_add = ((PsndRate - PsndLen*target_fps)<<16) / target_fps;\r
688                 printf("starting audio: %i len: %i (ex: %04x) stereo: %i, pal: %i\n",\r
689                         PsndRate, PsndLen, snd_excess_add, (PicoOpt&8)>>3, Pico.m.pal);\r
690                 gp2x_start_sound(PsndRate, 16, (PicoOpt&8)>>3);\r
691                 gp2x_sound_volume(currentConfig.volume, currentConfig.volume);\r
692                 PicoWriteSound = updateSound;\r
693                 memset(sndBuffer, 0, sizeof(sndBuffer));\r
694                 PsndOut = sndBuffer;\r
695                 PsndRate_old = PsndRate;\r
696                 PicoOpt_old  = PicoOpt;\r
697                 pal_old = Pico.m.pal;\r
698         } else {\r
699                 PsndOut = 0;\r
700         }\r
701 \r
702         // prepare CD buffer\r
703         if (PicoMCD & 1) PicoCDBufferInit();\r
704 \r
705         // calc vsync offset to sync timing code with vsync\r
706         if (currentConfig.EmuOpt&0x2000) {\r
707                 gettimeofday(&tval, 0);\r
708                 gp2x_video_wait_vsync();\r
709                 gettimeofday(&tval, 0);\r
710                 vsync_offset = tval.tv_usec;\r
711                 while (vsync_offset >= target_frametime)\r
712                         vsync_offset -= target_frametime;\r
713                 if (!vsync_offset) vsync_offset++;\r
714                 printf("vsync_offset: %i\n", vsync_offset);\r
715         } else\r
716                 vsync_offset = 0;\r
717 \r
718         // loop?\r
719         while (engineState == PGS_Running)\r
720         {\r
721                 int modes;\r
722 \r
723                 gettimeofday(&tval, 0);\r
724                 if(reset_timing) {\r
725                         reset_timing = 0;\r
726                         thissec = tval.tv_sec;\r
727                         frames_shown = frames_done = tval.tv_usec/target_frametime;\r
728                 }\r
729 \r
730                 // show notice message?\r
731                 if(noticeMsgTime.tv_sec) {\r
732                         static int noticeMsgSum;\r
733                         if((tval.tv_sec*1000000+tval.tv_usec) - (noticeMsgTime.tv_sec*1000000+noticeMsgTime.tv_usec) > 2000000) { // > 2.0 sec\r
734                                 noticeMsgTime.tv_sec = noticeMsgTime.tv_usec = 0;\r
735                                 clearArea(0);\r
736                                 notice = 0;\r
737                         } else {\r
738                                 int sum = noticeMsg[0]+noticeMsg[1]+noticeMsg[2];\r
739                                 if (sum != noticeMsgSum) { clearArea(0); noticeMsgSum = sum; }\r
740                                 notice = noticeMsg;\r
741                         }\r
742                 }\r
743 \r
744                 // check for mode changes\r
745                 modes = ((Pico.video.reg[12]&1)<<2)|(Pico.video.reg[1]&8);\r
746                 if (modes != oldmodes) {\r
747                         int scalex = 320;\r
748                         osd_fps_x = OSD_FPS_X;\r
749                         if (modes & 4) {\r
750                                 vidCpyM2 = vidCpyM2_40col;\r
751                         } else {\r
752                                 if (PicoOpt & 0x100) {\r
753                                         vidCpyM2 = vidCpyM2_32col_nobord;\r
754                                         scalex = 256;\r
755                                         osd_fps_x = OSD_FPS_X - 64;\r
756                                 } else {\r
757                                         vidCpyM2 = vidCpyM2_32col;\r
758                                 }\r
759                         }\r
760                         if (currentConfig.scaling == 2 && !(modes&8)) // want vertical scaling and game is not in 240 line mode\r
761                              gp2x_video_RGB_setscaling(8, scalex, 224);\r
762                         else gp2x_video_RGB_setscaling(0, scalex, 240);\r
763                         oldmodes = modes;\r
764                         clearArea(1);\r
765                 }\r
766 \r
767                 // second changed?\r
768                 if(thissec != tval.tv_sec) {\r
769 #ifdef BENCHMARK\r
770                         static int bench = 0, bench_fps = 0, bench_fps_s = 0, bfp = 0, bf[4];\r
771                         if(++bench == 10) {\r
772                                 bench = 0;\r
773                                 bench_fps_s = bench_fps;\r
774                                 bf[bfp++ & 3] = bench_fps;\r
775                                 bench_fps = 0;\r
776                         }\r
777                         bench_fps += frames_shown;\r
778                         sprintf(fpsbuff, "%02i/%02i/%02i", frames_shown, bench_fps_s, (bf[0]+bf[1]+bf[2]+bf[3])>>2);\r
779 #else\r
780                         if(currentConfig.EmuOpt & 2)\r
781                                 sprintf(fpsbuff, "%02i/%02i", frames_shown, frames_done);\r
782 #endif\r
783                         thissec = tval.tv_sec;\r
784 \r
785                         if(PsndOut == 0 && currentConfig.Frameskip >= 0) {\r
786                                 frames_done = frames_shown = 0;\r
787                         } else {\r
788                                 // it is quite common for this implementation to leave 1 fame unfinished\r
789                                 // when second changes, but we don't want buffer to starve.\r
790                                 if(PsndOut && frames_done < target_fps && frames_done > target_fps-5) {\r
791                                         updateKeys();\r
792                                         SkipFrame(1); frames_done++;\r
793                                 }\r
794 \r
795                                 frames_done  -= target_fps; if (frames_done  < 0) frames_done  = 0;\r
796                                 frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;\r
797                                 if (frames_shown > frames_done) frames_shown = frames_done;\r
798                         }\r
799                 }\r
800 #ifdef PFRAMES\r
801                 sprintf(fpsbuff, "%i", Pico.m.frame_count);\r
802 #endif\r
803 \r
804                 lim_time = (frames_done+1) * target_frametime + vsync_offset;\r
805                 if(currentConfig.Frameskip >= 0) { // frameskip enabled\r
806                         for(i = 0; i < currentConfig.Frameskip; i++) {\r
807                                 updateKeys();\r
808                                 SkipFrame(1); frames_done++;\r
809                                 if (PsndOut) { // do framelimitting if sound is enabled\r
810                                         gettimeofday(&tval, 0);\r
811                                         if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
812                                         if(tval.tv_usec < lim_time) { // we are too fast\r
813                                                 simpleWait(thissec, lim_time);\r
814                                         }\r
815                                 }\r
816                                 lim_time += target_frametime;\r
817                         }\r
818                 } else if(tval.tv_usec > lim_time) { // auto frameskip\r
819                         // no time left for this frame - skip\r
820                         if (tval.tv_usec - lim_time >= 300000) {\r
821                                 /* something caused a slowdown for us (disk access? cache flush?)\r
822                                  * try to recover by resetting timing... */\r
823                                 reset_timing = 1;\r
824                                 continue;\r
825                         }\r
826                         updateKeys();\r
827                         SkipFrame(tval.tv_usec < lim_time+target_frametime*2); frames_done++;\r
828                         continue;\r
829                 }\r
830 \r
831                 updateKeys();\r
832                 PicoFrame();\r
833 \r
834 #if 0\r
835 if (Pico.m.frame_count == 31563) {\r
836         FILE *f;\r
837         f = fopen("ram_p.bin", "wb");\r
838         if (!f) { printf("!f\n"); exit(1); }\r
839         fwrite(Pico.ram, 1, 0x10000, f);\r
840         fclose(f);\r
841         exit(0);\r
842 }\r
843 #endif\r
844 #if 0\r
845                 // debug\r
846                 {\r
847                         #define BYTE unsigned char\r
848                         #define WORD unsigned short\r
849                         struct\r
850                         {\r
851                                 BYTE IDLength;        /* 00h  Size of Image ID field */\r
852                                 BYTE ColorMapType;    /* 01h  Color map type */\r
853                                 BYTE ImageType;       /* 02h  Image type code */\r
854                                 WORD CMapStart;       /* 03h  Color map origin */\r
855                                 WORD CMapLength;      /* 05h  Color map length */\r
856                                 BYTE CMapDepth;       /* 07h  Depth of color map entries */\r
857                                 WORD XOffset;         /* 08h  X origin of image */\r
858                                 WORD YOffset;         /* 0Ah  Y origin of image */\r
859                                 WORD Width;           /* 0Ch  Width of image */\r
860                                 WORD Height;          /* 0Eh  Height of image */\r
861                                 BYTE PixelDepth;      /* 10h  Image pixel size */\r
862                                 BYTE ImageDescriptor; /* 11h  Image descriptor byte */\r
863                         } __attribute__((packed)) TGAHEAD;\r
864                         static unsigned short oldscr[320*240];\r
865                         FILE *f; char name[128]; int i;\r
866 \r
867                         memset(&TGAHEAD, 0, sizeof(TGAHEAD));\r
868                         TGAHEAD.ImageType = 2;\r
869                         TGAHEAD.Width = 320;\r
870                         TGAHEAD.Height = 240;\r
871                         TGAHEAD.PixelDepth = 16;\r
872                         TGAHEAD.ImageDescriptor = 2<<4; // image starts at top-left\r
873 \r
874                         #define CONV(X) (((X>>1)&0x7fe0)|(X&0x1f)) // 555?\r
875 \r
876                         for (i = 0; i < 320*240; i++)\r
877                                 if(oldscr[i] != CONV(((unsigned short *)gp2x_screen)[i])) break;\r
878                         if (i < 320*240)\r
879                         {\r
880                                 for (i = 0; i < 320*240; i++)\r
881                                         oldscr[i] = CONV(((unsigned short *)gp2x_screen)[i]);\r
882                                 sprintf(name, "%05i.tga", Pico.m.frame_count);\r
883                                 f = fopen(name, "wb");\r
884                                 if (!f) { printf("!f\n"); exit(1); }\r
885                                 fwrite(&TGAHEAD, 1, sizeof(TGAHEAD), f);\r
886                                 fwrite(oldscr, 1, 320*240*2, f);\r
887                                 fclose(f);\r
888                         }\r
889                 }\r
890 #endif\r
891 \r
892                 // check time\r
893                 gettimeofday(&tval, 0);\r
894                 if (thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
895 \r
896                 if (currentConfig.Frameskip < 0 && tval.tv_usec - lim_time >= 300000) // slowdown detection\r
897                         reset_timing = 1;\r
898                 else if (PsndOut != NULL || currentConfig.Frameskip < 0)\r
899                 {\r
900                         // sleep or vsync if we are still too fast\r
901                         // usleep sleeps for ~20ms minimum, so it is not a solution here\r
902                         if(tval.tv_usec < lim_time)\r
903                         {\r
904                                 // we are too fast\r
905                                 if (vsync_offset) {\r
906                                         if (lim_time - tval.tv_usec > target_frametime/2)\r
907                                                 simpleWait(thissec, lim_time - target_frametime/4);\r
908                                         gp2x_video_wait_vsync();\r
909                                 } else {\r
910                                         simpleWait(thissec, lim_time);\r
911                                 }\r
912                         }\r
913                 }\r
914 \r
915                 blit(fpsbuff, notice);\r
916 \r
917                 frames_done++; frames_shown++;\r
918         }\r
919 \r
920 \r
921         if (PicoMCD & 1) PicoCDBufferFree();\r
922 \r
923         // save SRAM\r
924         if((currentConfig.EmuOpt & 1) && SRam.changed) {\r
925                 emu_state_cb("Writing SRAM/BRAM..");\r
926                 emu_SaveLoadGame(0, 1);\r
927                 SRam.changed = 0;\r
928         }\r
929 \r
930         // if in 8bit mode, generate 16bit image for menu background\r
931         if ((PicoOpt&0x10) || !(currentConfig.EmuOpt&0x80))\r
932                 emu_forcedFrame();\r
933 }\r
934 \r
935 \r
936 void emu_ResetGame(void)\r
937 {\r
938         PicoReset(0);\r
939         reset_timing = 1;\r
940 }\r
941 \r
942 \r