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