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