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