move ROM detect code to pico/
[picodrive.git] / platform / common / menu_pico.c
1 /*
2  * PicoDrive
3  * (C) notaz, 2010,2011
4  *
5  * This work is licensed under the terms of MAME license.
6  * See COPYING file in the top-level directory.
7  */
8 #include <stdio.h>
9 #include <string.h>
10
11 #include "emu.h"
12 #include "menu_pico.h"
13 #include "input_pico.h"
14
15 #include <version.h>
16
17 #include <pico/pico.h>
18 #include <pico/patch.h>
19
20 #ifdef PANDORA
21 #define MENU_X2 1
22 #else
23 #define MENU_X2 0
24 #endif
25
26 // FIXME
27 #define REVISION "0"
28
29 static const char *rom_exts[] = {
30         "zip",
31         "bin", "smd", "gen",
32         "iso", "cso", "cue",
33         "32x",
34         "sms",
35         NULL
36 };
37
38 // rrrr rggg gggb bbbb
39 static unsigned short fname2color(const char *fname)
40 {
41         const char *ext = fname + strlen(fname) - 3;
42         static const char *other_exts[] = { "gmv", "pat" };
43         int i;
44
45         if (ext < fname) ext = fname;
46         for (i = 0; rom_exts[i] != NULL; i++)
47                 if (strcasecmp(ext, rom_exts[i]) == 0) return 0xbdff; // FIXME: mk defines
48         for (i = 0; i < array_size(other_exts); i++)
49                 if (strcasecmp(ext, other_exts[i]) == 0) return 0xaff5;
50         return 0xffff;
51 }
52
53 #include "../libpicofe/menu.c"
54
55 static const char *men_dummy[] = { NULL };
56
57 /* platform specific options and handlers */
58 #if   defined(__GP2X__)
59 #include "../gp2x/menu.c"
60 #elif defined(PANDORA)
61 #include "../pandora/menu.c"
62 #else
63 #define MENU_OPTIONS_GFX
64 #define MENU_OPTIONS_ADV
65 #define menu_main_plat_draw NULL
66 #endif
67
68 static void make_bg(int no_scale)
69 {
70         unsigned short *src = (void *)g_menubg_src_ptr;
71         int w = g_screen_width, h = g_screen_height;
72         short *dst;
73         int x, y;
74
75         if (!no_scale && g_menuscreen_w / w >= 2 && g_menuscreen_h / h >= 2)
76         {
77                 unsigned int t, *d = g_menubg_ptr;
78                 d += (g_menuscreen_h / 2 - h * 2 / 2)
79                         * g_menuscreen_w / 2;
80                 d += (g_menuscreen_w / 2 - w * 2 / 2) / 2;
81                 for (y = 0; y < h; y++, src += w, d += g_menuscreen_w*2/2) {
82                         for (x = 0; x < w; x++) {
83                                 t = src[x];
84                                 t = ((t & 0xf79e)>>1) - ((t & 0xc618)>>3);
85                                 t |= t << 16;
86                                 d[x] = d[x + g_menuscreen_w / 2] = t;
87                         }
88                 }
89                 return;
90         }
91
92         if (w > g_menuscreen_w)
93                 w = g_menuscreen_w;
94         if (h > g_menuscreen_h)
95                 h = g_menuscreen_h;
96         dst = (short *)g_menubg_ptr +
97                 (g_menuscreen_h / 2 - h / 2) * g_menuscreen_w +
98                 (g_menuscreen_w / 2 - w / 2);
99
100         // darken the active framebuffer
101         for (; h > 0; dst += g_menuscreen_w, src += g_screen_width, h--)
102                 menu_darken_bg(dst, src, w, 1);
103 }
104
105 static void menu_enter(int is_rom_loaded)
106 {
107         if (is_rom_loaded)
108         {
109                 make_bg(0);
110         }
111         else
112         {
113                 char buff[256];
114
115                 // should really only happen once, on startup..
116                 emu_make_path(buff, "skin/background.png", sizeof(buff));
117                 if (readpng(g_menubg_ptr, buff, READPNG_BG, g_menuscreen_w, g_menuscreen_h) < 0)
118                         memset(g_menubg_ptr, 0, g_menuscreen_w * g_menuscreen_h * 2);
119         }
120
121         plat_video_menu_enter(is_rom_loaded);
122 }
123
124 static void draw_savestate_bg(int slot)
125 {
126         const char *fname;
127         void *tmp_state;
128
129         fname = emu_get_save_fname(1, 0, slot);
130         if (!fname)
131                 return;
132
133         tmp_state = PicoTmpStateSave();
134
135         PicoStateLoadGfx(fname);
136
137         /* do a frame and fetch menu bg */
138         pemu_forced_frame(0, 0);
139
140         make_bg(0);
141
142         PicoTmpStateRestore(tmp_state);
143 }
144
145 // --------- loading ROM screen ----------
146
147 static int cdload_called = 0;
148
149 static void load_progress_cb(int percent)
150 {
151         int ln, len = percent * g_menuscreen_w / 100;
152         unsigned short *dst;
153
154         if (len > g_menuscreen_w)
155                 len = g_menuscreen_w;
156
157         menu_draw_begin(0, 1);
158         dst = (unsigned short *)g_menuscreen_ptr + g_menuscreen_w * me_sfont_h * 2;
159         for (ln = me_sfont_h - 2; ln > 0; ln--, dst += g_menuscreen_w)
160                 memset(dst, 0xff, len * 2);
161         menu_draw_end();
162 }
163
164 static void cdload_progress_cb(const char *fname, int percent)
165 {
166         int ln, len = percent * g_menuscreen_w / 100;
167         unsigned short *dst;
168
169         menu_draw_begin(0, 1);
170         dst = (unsigned short *)g_menuscreen_ptr + g_menuscreen_w * me_sfont_h * 2;
171         memset(dst, 0xff, g_menuscreen_w * (me_sfont_h - 2) * 2);
172
173         smalltext_out16(1, 3 * me_sfont_h, "Processing CD image / MP3s", 0xffff);
174         smalltext_out16(1, 4 * me_sfont_h, fname, 0xffff);
175         dst += g_menuscreen_w * me_sfont_h * 3;
176
177         if (len > g_menuscreen_w)
178                 len = g_menuscreen_w;
179
180         for (ln = (me_sfont_h - 2); ln > 0; ln--, dst += g_menuscreen_w)
181                 memset(dst, 0xff, len * 2);
182         menu_draw_end();
183
184         cdload_called = 1;
185 }
186
187 void menu_romload_prepare(const char *rom_name)
188 {
189         const char *p = rom_name + strlen(rom_name);
190         int i;
191
192         while (p > rom_name && *p != '/')
193                 p--;
194
195         /* fill all buffers, callbacks won't update in full */
196         for (i = 0; i < 3; i++) {
197                 menu_draw_begin(1, 1);
198                 smalltext_out16(1, 1, "Loading", 0xffff);
199                 smalltext_out16(1, me_sfont_h, p, 0xffff);
200                 menu_draw_end();
201         }
202
203         PicoCartLoadProgressCB = load_progress_cb;
204         PicoCDLoadProgressCB = cdload_progress_cb;
205         cdload_called = 0;
206 }
207
208 void menu_romload_end(void)
209 {
210         PicoCartLoadProgressCB = NULL;
211         PicoCDLoadProgressCB = NULL;
212
213         menu_draw_begin(0, 1);
214         smalltext_out16(1, (cdload_called ? 6 : 3) * me_sfont_h,
215                 "Starting emulation...", 0xffff);
216         menu_draw_end();
217 }
218
219 // ------------ patch/gg menu ------------
220
221 static void draw_patchlist(int sel)
222 {
223         int max_cnt, start, i, pos, active;
224
225         max_cnt = g_menuscreen_h / me_sfont_h;
226         start = max_cnt / 2 - sel;
227
228         menu_draw_begin(1, 0);
229
230         for (i = 0; i < PicoPatchCount; i++) {
231                 pos = start + i;
232                 if (pos < 0) continue;
233                 if (pos >= max_cnt) break;
234                 active = PicoPatches[i].active;
235                 smalltext_out16(14,                pos * me_sfont_h, active ? "ON " : "OFF", active ? 0xfff6 : 0xffff);
236                 smalltext_out16(14 + me_sfont_w*4, pos * me_sfont_h, PicoPatches[i].name,    active ? 0xfff6 : 0xffff);
237         }
238         pos = start + i;
239         if (pos < max_cnt)
240                 smalltext_out16(14, pos * me_sfont_h, "done", 0xffff);
241
242         text_out16(5, max_cnt / 2 * me_sfont_h, ">");
243         menu_draw_end();
244 }
245
246 static void menu_loop_patches(void)
247 {
248         static int menu_sel = 0;
249         int inp;
250
251         for (;;)
252         {
253                 draw_patchlist(menu_sel);
254                 inp = in_menu_wait(PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT|PBTN_L|PBTN_R
255                                 |PBTN_MOK|PBTN_MBACK, NULL, 33);
256                 if (inp & PBTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = PicoPatchCount; }
257                 if (inp & PBTN_DOWN) { menu_sel++; if (menu_sel > PicoPatchCount) menu_sel = 0; }
258                 if (inp &(PBTN_LEFT|PBTN_L))  { menu_sel-=10; if (menu_sel < 0) menu_sel = 0; }
259                 if (inp &(PBTN_RIGHT|PBTN_R)) { menu_sel+=10; if (menu_sel > PicoPatchCount) menu_sel = PicoPatchCount; }
260                 if (inp & PBTN_MOK) { // action
261                         if (menu_sel < PicoPatchCount)
262                                 PicoPatches[menu_sel].active = !PicoPatches[menu_sel].active;
263                         else    break;
264                 }
265                 if (inp & PBTN_MBACK)
266                         break;
267         }
268 }
269
270 // -------------- key config --------------
271
272 // PicoPad[] format: MXYZ SACB RLDU
273 me_bind_action me_ctrl_actions[] =
274 {
275         { "UP     ", 0x0001 },
276         { "DOWN   ", 0x0002 },
277         { "LEFT   ", 0x0004 },
278         { "RIGHT  ", 0x0008 },
279         { "A      ", 0x0040 },
280         { "B      ", 0x0010 },
281         { "C      ", 0x0020 },
282         { "A turbo", 0x4000 },
283         { "B turbo", 0x1000 },
284         { "C turbo", 0x2000 },
285         { "START  ", 0x0080 },
286         { "MODE   ", 0x0800 },
287         { "X      ", 0x0400 },
288         { "Y      ", 0x0200 },
289         { "Z      ", 0x0100 },
290         { NULL,      0 },
291 };
292
293 me_bind_action emuctrl_actions[] =
294 {
295         { "Load State       ", PEV_STATE_LOAD },
296         { "Save State       ", PEV_STATE_SAVE },
297         { "Prev Save Slot   ", PEV_SSLOT_PREV },
298         { "Next Save Slot   ", PEV_SSLOT_NEXT },
299         { "Switch Renderer  ", PEV_SWITCH_RND },
300         { "Volume Down      ", PEV_VOL_DOWN },
301         { "Volume Up        ", PEV_VOL_UP },
302         { "Fast forward     ", PEV_FF },
303         { "Enter Menu       ", PEV_MENU },
304         { "Pico Next page   ", PEV_PICO_PNEXT },
305         { "Pico Prev page   ", PEV_PICO_PPREV },
306         { "Pico Switch input", PEV_PICO_SWINP },
307         { NULL,                0 }
308 };
309
310 static int key_config_loop_wrap(int id, int keys)
311 {
312         switch (id) {
313                 case MA_CTRL_PLAYER1:
314                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 0);
315                         break;
316                 case MA_CTRL_PLAYER2:
317                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 1);
318                         break;
319                 case MA_CTRL_EMU:
320                         key_config_loop(emuctrl_actions, array_size(emuctrl_actions) - 1, -1);
321                         break;
322                 default:
323                         break;
324         }
325         return 0;
326 }
327
328 static const char *mgn_dev_name(int id, int *offs)
329 {
330         const char *name = NULL;
331         static int it = 0;
332
333         if (id == MA_CTRL_DEV_FIRST)
334                 it = 0;
335
336         for (; it < IN_MAX_DEVS; it++) {
337                 name = in_get_dev_name(it, 1, 1);
338                 if (name != NULL)
339                         break;
340         }
341
342         it++;
343         return name;
344 }
345
346 static int mh_saveloadcfg(int id, int keys);
347 static const char *mgn_saveloadcfg(int id, int *offs);
348
349 static menu_entry e_menu_keyconfig[] =
350 {
351         mee_handler_id("Player 1",          MA_CTRL_PLAYER1,    key_config_loop_wrap),
352         mee_handler_id("Player 2",          MA_CTRL_PLAYER2,    key_config_loop_wrap),
353         mee_handler_id("Emulator controls", MA_CTRL_EMU,        key_config_loop_wrap),
354         mee_onoff     ("6 button pad",      MA_OPT_6BUTTON_PAD, PicoOpt, POPT_6BTN_PAD),
355         mee_range     ("Turbo rate",        MA_CTRL_TURBO_RATE, currentConfig.turbo_rate, 1, 30),
356         mee_range     ("Analog deadzone",   MA_CTRL_DEADZONE,   currentConfig.analog_deadzone, 1, 99),
357         mee_cust_nosave("Save global config",       MA_OPT_SAVECFG, mh_saveloadcfg, mgn_saveloadcfg),
358         mee_cust_nosave("Save cfg for loaded game", MA_OPT_SAVECFG_GAME, mh_saveloadcfg, mgn_saveloadcfg),
359         mee_label     (""),
360         mee_label     ("Input devices:"),
361         mee_label_mk  (MA_CTRL_DEV_FIRST, mgn_dev_name),
362         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
363         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
364         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
365         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
366         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
367         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
368         mee_end,
369 };
370
371 static int menu_loop_keyconfig(int id, int keys)
372 {
373         static int sel = 0;
374
375         me_enable(e_menu_keyconfig, MA_OPT_SAVECFG_GAME, PicoGameLoaded);
376         me_loop(e_menu_keyconfig, &sel);
377         return 0;
378 }
379
380 // ------------ SCD options menu ------------
381
382 static const char *mgn_cdopt_ra(int id, int *offs)
383 {
384         *offs = -5;
385         if (PicoCDBuffers <= 0)
386                 return "     OFF";
387         sprintf(static_buff, "%5iK", PicoCDBuffers * 2);
388         return static_buff;
389 }
390
391 static int mh_cdopt_ra(int id, int keys)
392 {
393         if (keys & PBTN_LEFT) {
394                 PicoCDBuffers >>= 1;
395                 if (PicoCDBuffers < 2)
396                         PicoCDBuffers = 0;
397         } else {
398                 if (PicoCDBuffers <= 0)
399                         PicoCDBuffers = 1;
400                 PicoCDBuffers <<= 1;
401                 if (PicoCDBuffers > 8*1024)
402                         PicoCDBuffers = 8*1024; // 16M
403         }
404         return 0;
405 }
406
407 static const char h_cdleds[] = "Show power/CD LEDs of emulated console";
408 static const char h_cdda[]   = "Play audio tracks from mp3s/wavs/bins";
409 static const char h_cdpcm[]  = "Emulate PCM audio chip for effects/voices/music";
410 static const char h_srcart[] = "Emulate the save RAM cartridge accessory\n"
411                                 "most games don't need this";
412 static const char h_scfx[]   = "Emulate scale/rotate ASIC chip for graphics effects\n"
413                                 "disable to improve performance";
414 static const char h_bsync[]  = "More accurate mode for CPUs (needed for some games)\n"
415                                 "disable to improve performance";
416
417 static menu_entry e_menu_cd_options[] =
418 {
419         mee_onoff_h("CD LEDs",              MA_CDOPT_LEDS,          currentConfig.EmuOpt, EOPT_EN_CD_LEDS, h_cdleds),
420         mee_onoff_h("CDDA audio",           MA_CDOPT_CDDA,          PicoOpt, POPT_EN_MCD_CDDA, h_cdda),
421         mee_onoff_h("PCM audio",            MA_CDOPT_PCM,           PicoOpt, POPT_EN_MCD_PCM, h_cdpcm),
422         mee_cust   ("ReadAhead buffer",     MA_CDOPT_READAHEAD,     mh_cdopt_ra, mgn_cdopt_ra),
423         mee_onoff_h("SaveRAM cart",         MA_CDOPT_SAVERAM,       PicoOpt, POPT_EN_MCD_RAMCART, h_srcart),
424         mee_onoff_h("Scale/Rot. fx (slow)", MA_CDOPT_SCALEROT_CHIP, PicoOpt, POPT_EN_MCD_GFX, h_scfx),
425         mee_onoff_h("Better sync (slow)",   MA_CDOPT_BETTER_SYNC,   PicoOpt, POPT_EN_MCD_PSYNC, h_bsync),
426         mee_end,
427 };
428
429 static int menu_loop_cd_options(int id, int keys)
430 {
431         static int sel = 0;
432         me_loop(e_menu_cd_options, &sel);
433         return 0;
434 }
435
436 // ------------ 32X options menu ------------
437
438 #ifndef NO_32X
439
440 // convert from multiplier of VClk
441 static int mh_opt_sh2cycles(int id, int keys)
442 {
443         int *mul = (id == MA_32XOPT_MSH2_CYCLES) ? &p32x_msh2_multiplier : &p32x_ssh2_multiplier;
444
445         if (keys & (PBTN_LEFT|PBTN_RIGHT))
446                 *mul += (keys & PBTN_LEFT) ? -10 : 10;
447         if (keys & (PBTN_L|PBTN_R))
448                 *mul += (keys & PBTN_L) ? -100 : 100;
449
450         if (*mul < 1)
451                 *mul = 1;
452         else if (*mul > (10 << SH2_MULTI_SHIFT))
453                 *mul = 10 << SH2_MULTI_SHIFT;
454
455         return 0;
456 }
457
458 static const char *mgn_opt_sh2cycles(int id, int *offs)
459 {
460         int mul = (id == MA_32XOPT_MSH2_CYCLES) ? p32x_msh2_multiplier : p32x_ssh2_multiplier;
461         
462         sprintf(static_buff, "%d", 7670 * mul >> SH2_MULTI_SHIFT);
463         return static_buff;
464 }
465
466 static const char h_32x_enable[] = "Enable emulation of the 32X addon";
467 static const char h_pwm[]        = "Disabling may improve performance, but break sound";
468 static const char h_sh2cycles[]  = "Cycles/millisecond (similar to DOSBox)\n"
469                                    "lower values speed up emulation but break games\n"
470                                    "at least 11000 recommended for compatibility";
471
472 static menu_entry e_menu_32x_options[] =
473 {
474         mee_onoff_h   ("32X enabled",       MA_32XOPT_ENABLE_32X,  PicoOpt, POPT_EN_32X, h_32x_enable),
475         mee_enum      ("32X renderer",      MA_32XOPT_RENDERER,    currentConfig.renderer32x, renderer_names32x),
476         mee_onoff_h   ("PWM sound",         MA_32XOPT_PWM,         PicoOpt, POPT_EN_PWM, h_pwm),
477         mee_cust_h    ("Master SH2 cycles", MA_32XOPT_MSH2_CYCLES, mh_opt_sh2cycles, mgn_opt_sh2cycles, h_sh2cycles),
478         mee_cust_h    ("Slave SH2 cycles",  MA_32XOPT_SSH2_CYCLES, mh_opt_sh2cycles, mgn_opt_sh2cycles, h_sh2cycles),
479         mee_end,
480 };
481
482 static int menu_loop_32x_options(int id, int keys)
483 {
484         static int sel = 0;
485
486         me_enable(e_menu_32x_options, MA_32XOPT_RENDERER, renderer_names32x[0] != NULL);
487         me_loop(e_menu_32x_options, &sel);
488
489         return 0;
490 }
491
492 #endif
493
494 // ------------ adv options menu ------------
495
496 static menu_entry e_menu_adv_options[] =
497 {
498         mee_onoff     ("SRAM/BRAM saves",          MA_OPT_SRAM_STATES,    currentConfig.EmuOpt, EOPT_EN_SRAM),
499         mee_onoff     ("Disable sprite limit",     MA_OPT2_NO_SPRITE_LIM, PicoOpt, POPT_DIS_SPRITE_LIM),
500         mee_onoff     ("Emulate Z80",              MA_OPT2_ENABLE_Z80,    PicoOpt, POPT_EN_Z80),
501         mee_onoff     ("Emulate YM2612 (FM)",      MA_OPT2_ENABLE_YM2612, PicoOpt, POPT_EN_FM),
502         mee_onoff     ("Emulate SN76496 (PSG)",    MA_OPT2_ENABLE_SN76496,PicoOpt, POPT_EN_PSG),
503         mee_onoff     ("gzip savestates",          MA_OPT2_GZIP_STATES,   currentConfig.EmuOpt, EOPT_GZIP_SAVES),
504         mee_onoff     ("Don't save last used ROM", MA_OPT2_NO_LAST_ROM,   currentConfig.EmuOpt, EOPT_NO_AUTOSVCFG),
505         mee_onoff     ("Disable idle loop patching",MA_OPT2_NO_IDLE_LOOPS,PicoOpt, POPT_DIS_IDLE_DET),
506         mee_onoff     ("Disable frame limiter",    MA_OPT2_NO_FRAME_LIMIT,currentConfig.EmuOpt, EOPT_NO_FRMLIMIT),
507         MENU_OPTIONS_ADV
508         mee_end,
509 };
510
511 static int menu_loop_adv_options(int id, int keys)
512 {
513         static int sel = 0;
514         me_loop(e_menu_adv_options, &sel);
515         return 0;
516 }
517
518 // ------------ gfx options menu ------------
519
520 static const char h_gamma[] = "Gamma/brightness adjustment (default 100)";
521
522 static menu_entry e_menu_gfx_options[] =
523 {
524         mee_enum   ("Video output mode", MA_OPT_VOUT_MODE, plat_target.vout_method, men_dummy),
525         mee_enum   ("Renderer",          MA_OPT_RENDERER, currentConfig.renderer, renderer_names),
526         mee_enum   ("Filter",            MA_OPT3_FILTERING, currentConfig.filter, men_dummy),
527         mee_range_h("Gamma adjustment",  MA_OPT3_GAMMA, currentConfig.gamma, 1, 200, h_gamma),
528         MENU_OPTIONS_GFX
529         mee_end,
530 };
531
532 static int menu_loop_gfx_options(int id, int keys)
533 {
534         static int sel = 0;
535
536         me_enable(e_menu_gfx_options, MA_OPT_RENDERER, renderer_names[0] != NULL);
537         me_loop(e_menu_gfx_options, &sel);
538
539         return 0;
540 }
541
542 // ------------ options menu ------------
543
544 static menu_entry e_menu_options[];
545
546 static int sndrate_prevnext(int rate, int dir)
547 {
548         static const int rates[] = { 8000, 11025, 16000, 22050, 44100 };
549         int i;
550
551         for (i = 0; i < 5; i++)
552                 if (rates[i] == rate) break;
553
554         i += dir ? 1 : -1;
555         if (i > 4) {
556                 if (!(PicoOpt & POPT_EN_STEREO)) {
557                         PicoOpt |= POPT_EN_STEREO;
558                         return rates[0];
559                 }
560                 return rates[4];
561         }
562         if (i < 0) {
563                 if (PicoOpt & POPT_EN_STEREO) {
564                         PicoOpt &= ~POPT_EN_STEREO;
565                         return rates[4];
566                 }
567                 return rates[0];
568         }
569         return rates[i];
570 }
571
572 static void region_prevnext(int right)
573 {
574         // jp_ntsc=1, jp_pal=2, usa=4, eu=8
575         static const int rgn_orders[] = { 0x148, 0x184, 0x814, 0x418, 0x841, 0x481 };
576         int i;
577
578         if (right) {
579                 if (!PicoRegionOverride) {
580                         for (i = 0; i < 6; i++)
581                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
582                         if (i < 5) PicoAutoRgnOrder = rgn_orders[i+1];
583                         else PicoRegionOverride=1;
584                 }
585                 else
586                         PicoRegionOverride <<= 1;
587                 if (PicoRegionOverride > 8)
588                         PicoRegionOverride = 8;
589         } else {
590                 if (!PicoRegionOverride) {
591                         for (i = 0; i < 6; i++)
592                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
593                         if (i > 0) PicoAutoRgnOrder = rgn_orders[i-1];
594                 }
595                 else
596                         PicoRegionOverride >>= 1;
597         }
598 }
599
600 static int mh_opt_misc(int id, int keys)
601 {
602         switch (id) {
603         case MA_OPT_SOUND_QUALITY:
604                 PsndRate = sndrate_prevnext(PsndRate, keys & PBTN_RIGHT);
605                 break;
606         case MA_OPT_REGION:
607                 region_prevnext(keys & PBTN_RIGHT);
608                 break;
609         default:
610                 break;
611         }
612         return 0;
613 }
614
615 static int mh_saveloadcfg(int id, int keys)
616 {
617         int ret;
618
619         if (keys & (PBTN_LEFT|PBTN_RIGHT)) { // multi choice
620                 config_slot += (keys & PBTN_LEFT) ? -1 : 1;
621                 if (config_slot < 0) config_slot = 9;
622                 else if (config_slot > 9) config_slot = 0;
623                 me_enable(e_menu_options, MA_OPT_LOADCFG, config_slot != config_slot_current);
624                 return 0;
625         }
626
627         switch (id) {
628         case MA_OPT_SAVECFG:
629         case MA_OPT_SAVECFG_GAME:
630                 if (emu_write_config(id == MA_OPT_SAVECFG_GAME ? 1 : 0))
631                         menu_update_msg("config saved");
632                 else
633                         menu_update_msg("failed to write config");
634                 break;
635         case MA_OPT_LOADCFG:
636                 ret = emu_read_config(rom_fname_loaded, 1);
637                 if (!ret) ret = emu_read_config(NULL, 1);
638                 if (ret)  menu_update_msg("config loaded");
639                 else      menu_update_msg("failed to load config");
640                 break;
641         default:
642                 return 0;
643         }
644
645         return 1;
646 }
647
648 static int mh_restore_defaults(int id, int keys)
649 {
650         emu_set_defconfig();
651         menu_update_msg("defaults restored");
652         return 1;
653 }
654
655 static const char *mgn_opt_fskip(int id, int *offs)
656 {
657         if (currentConfig.Frameskip < 0)
658                 return "Auto";
659         sprintf(static_buff, "%d", currentConfig.Frameskip);
660         return static_buff;
661 }
662
663 static const char *mgn_opt_sound(int id, int *offs)
664 {
665         const char *str2;
666         *offs = -8;
667         str2 = (PicoOpt & POPT_EN_STEREO) ? "stereo" : "mono";
668         sprintf(static_buff, "%5iHz %s", PsndRate, str2);
669         return static_buff;
670 }
671
672 static const char *mgn_opt_region(int id, int *offs)
673 {
674         static const char *names[] = { "Auto", "      Japan NTSC", "      Japan PAL", "      USA", "      Europe" };
675         static const char *names_short[] = { "", " JP", " JP", " US", " EU" };
676         int code = PicoRegionOverride;
677         int u, i = 0;
678
679         *offs = -6;
680         if (code) {
681                 code <<= 1;
682                 while ((code >>= 1)) i++;
683                 if (i > 4)
684                         return "unknown";
685                 return names[i];
686         } else {
687                 strcpy(static_buff, "Auto:");
688                 for (u = 0; u < 3; u++) {
689                         code = (PicoAutoRgnOrder >> u*4) & 0xf;
690                         for (i = 0; code; code >>= 1, i++)
691                                 ;
692                         strcat(static_buff, names_short[i]);
693                 }
694                 return static_buff;
695         }
696 }
697
698 static const char *mgn_saveloadcfg(int id, int *offs)
699 {
700         static_buff[0] = 0;
701         if (config_slot != 0)
702                 sprintf(static_buff, "[%i]", config_slot);
703         return static_buff;
704 }
705
706 static const char *men_confirm_save[] = { "OFF", "writes", "loads", "both", NULL };
707 static const char h_confirm_save[]    = "Ask for confirmation when overwriting save,\n"
708                                         "loading state or both";
709
710 static menu_entry e_menu_options[] =
711 {
712         mee_range     ("Save slot",                MA_OPT_SAVE_SLOT,     state_slot, 0, 9),
713         mee_range_cust("Frameskip",                MA_OPT_FRAMESKIP,     currentConfig.Frameskip, -1, 16, mgn_opt_fskip),
714         mee_cust      ("Region",                   MA_OPT_REGION,        mh_opt_misc, mgn_opt_region),
715         mee_onoff     ("Show FPS",                 MA_OPT_SHOW_FPS,      currentConfig.EmuOpt, EOPT_SHOW_FPS),
716         mee_onoff     ("Enable sound",             MA_OPT_ENABLE_SOUND,  currentConfig.EmuOpt, EOPT_EN_SOUND),
717         mee_cust      ("Sound Quality",            MA_OPT_SOUND_QUALITY, mh_opt_misc, mgn_opt_sound),
718         mee_enum_h    ("Confirm savestate",        MA_OPT_CONFIRM_STATES,currentConfig.confirm_save, men_confirm_save, h_confirm_save),
719         mee_range     ("",                         MA_OPT_CPU_CLOCKS,    currentConfig.CPUclock, 20, 1200),
720         mee_handler   ("[Display options]",        menu_loop_gfx_options),
721         mee_handler   ("[Sega/Mega CD options]",   menu_loop_cd_options),
722 #ifndef NO_32X
723         mee_handler   ("[32X options]",            menu_loop_32x_options),
724 #endif
725         mee_handler   ("[Advanced options]",       menu_loop_adv_options),
726         mee_cust_nosave("Save global config",      MA_OPT_SAVECFG, mh_saveloadcfg, mgn_saveloadcfg),
727         mee_cust_nosave("Save cfg for loaded game",MA_OPT_SAVECFG_GAME, mh_saveloadcfg, mgn_saveloadcfg),
728         mee_cust_nosave("Load cfg from profile",   MA_OPT_LOADCFG, mh_saveloadcfg, mgn_saveloadcfg),
729         mee_handler   ("Restore defaults",         mh_restore_defaults),
730         mee_end,
731 };
732
733 static int menu_loop_options(int id, int keys)
734 {
735         static int sel = 0;
736         int i;
737
738         i = me_id2offset(e_menu_options, MA_OPT_CPU_CLOCKS);
739         e_menu_options[i].enabled = e_menu_options[i].name[0] ? 1 : 0;
740         me_enable(e_menu_options, MA_OPT_SAVECFG_GAME, PicoGameLoaded);
741         me_enable(e_menu_options, MA_OPT_LOADCFG, config_slot != config_slot_current);
742
743         me_loop(e_menu_options, &sel);
744
745         return 0;
746 }
747
748 // ------------ debug menu ------------
749
750 #include <pico/debug.h>
751
752 extern void SekStepM68k(void);
753
754 static void mplayer_loop(void)
755 {
756         pemu_sound_start();
757
758         while (1)
759         {
760                 PDebugZ80Frame();
761                 if (in_menu_wait_any(NULL, 0) & PBTN_MA3)
762                         break;
763                 emu_sound_wait();
764         }
765
766         emu_sound_stop();
767 }
768
769 static void draw_text_debug(const char *str, int skip, int from)
770 {
771         const char *p;
772         int line;
773
774         p = str;
775         while (skip-- > 0)
776         {
777                 while (*p && *p != '\n')
778                         p++;
779                 if (*p == 0 || p[1] == 0)
780                         return;
781                 p++;
782         }
783
784         str = p;
785         for (line = from; line < g_menuscreen_h / me_sfont_h; line++)
786         {
787                 smalltext_out16(1, line * me_sfont_h, str, 0xffff);
788                 while (*p && *p != '\n')
789                         p++;
790                 if (*p == 0)
791                         break;
792                 p++; str = p;
793         }
794 }
795
796 #ifdef __GNUC__
797 #define COMPILER "gcc " __VERSION__
798 #else
799 #define COMPILER
800 #endif
801
802 static void draw_frame_debug(void)
803 {
804         char layer_str[48] = "layers:                   ";
805         if (PicoDrawMask & PDRAW_LAYERB_ON)      memcpy(layer_str +  8, "B", 1);
806         if (PicoDrawMask & PDRAW_LAYERA_ON)      memcpy(layer_str + 10, "A", 1);
807         if (PicoDrawMask & PDRAW_SPRITES_LOW_ON) memcpy(layer_str + 12, "spr_lo", 6);
808         if (PicoDrawMask & PDRAW_SPRITES_HI_ON)  memcpy(layer_str + 19, "spr_hi", 6);
809         if (PicoDrawMask & PDRAW_32X_ON)         memcpy(layer_str + 26, "32x", 4);
810
811         pemu_forced_frame(1, 0);
812         make_bg(1);
813
814         smalltext_out16(4, 1, "build: r" REVISION "  "__DATE__ " " __TIME__ " " COMPILER, 0xffff);
815         smalltext_out16(4, g_menuscreen_h - me_sfont_h, layer_str, 0xffff);
816 }
817
818 static void debug_menu_loop(void)
819 {
820         int inp, mode = 0;
821         int spr_offs = 0, dumped = 0;
822         char *tmp;
823
824         while (1)
825         {
826                 menu_draw_begin(1, 0);
827                 switch (mode)
828                 {
829                         case 0: tmp = PDebugMain();
830                                 plat_debug_cat(tmp);
831                                 draw_text_debug(tmp, 0, 0);
832                                 if (dumped) {
833                                         smalltext_out16(g_menuscreen_w - 6 * me_sfont_h,
834                                                 g_menuscreen_h - me_mfont_h, "dumped", 0xffff);
835                                         dumped = 0;
836                                 }
837                                 break;
838                         case 1: draw_frame_debug();
839                                 break;
840                         case 2: pemu_forced_frame(1, 0);
841                                 make_bg(1);
842                                 PDebugShowSpriteStats((unsigned short *)g_menuscreen_ptr + (g_menuscreen_h/2 - 240/2)*g_menuscreen_w +
843                                         g_menuscreen_w/2 - 320/2, g_menuscreen_w);
844                                 break;
845                         case 3: memset(g_menuscreen_ptr, 0, g_menuscreen_w * g_menuscreen_h * 2);
846                                 PDebugShowPalette(g_menuscreen_ptr, g_menuscreen_w);
847                                 PDebugShowSprite((unsigned short *)g_menuscreen_ptr + g_menuscreen_w*120 + g_menuscreen_w/2 + 16,
848                                         g_menuscreen_w, spr_offs);
849                                 draw_text_debug(PDebugSpriteList(), spr_offs, 6);
850                                 break;
851                         case 4: tmp = PDebug32x();
852                                 draw_text_debug(tmp, 0, 0);
853                                 break;
854                 }
855                 menu_draw_end();
856
857                 inp = in_menu_wait(PBTN_MOK|PBTN_MBACK|PBTN_MA2|PBTN_MA3|PBTN_L|PBTN_R |
858                                         PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT, NULL, 70);
859                 if (inp & PBTN_MBACK) return;
860                 if (inp & PBTN_L) { mode--; if (mode < 0) mode = 4; }
861                 if (inp & PBTN_R) { mode++; if (mode > 4) mode = 0; }
862                 switch (mode)
863                 {
864                         case 0:
865                                 if (inp & PBTN_MOK)
866                                         PDebugCPUStep();
867                                 if (inp & PBTN_MA3) {
868                                         while (inp & PBTN_MA3)
869                                                 inp = in_menu_wait_any(NULL, -1);
870                                         mplayer_loop();
871                                 }
872                                 if ((inp & (PBTN_MA2|PBTN_LEFT)) == (PBTN_MA2|PBTN_LEFT)) {
873                                         mkdir("dumps", 0777);
874                                         PDebugDumpMem();
875                                         while (inp & PBTN_MA2) inp = in_menu_wait_any(NULL, -1);
876                                         dumped = 1;
877                                 }
878                                 break;
879                         case 1:
880                                 if (inp & PBTN_LEFT)  PicoDrawMask ^= PDRAW_LAYERB_ON;
881                                 if (inp & PBTN_RIGHT) PicoDrawMask ^= PDRAW_LAYERA_ON;
882                                 if (inp & PBTN_DOWN)  PicoDrawMask ^= PDRAW_SPRITES_LOW_ON;
883                                 if (inp & PBTN_UP)    PicoDrawMask ^= PDRAW_SPRITES_HI_ON;
884                                 if (inp & PBTN_MA2)   PicoDrawMask ^= PDRAW_32X_ON;
885                                 if (inp & PBTN_MOK) {
886                                         PsndOut = NULL; // just in case
887                                         PicoSkipFrame = 1;
888                                         PicoFrame();
889                                         PicoSkipFrame = 0;
890                                         while (inp & PBTN_MOK) inp = in_menu_wait_any(NULL, -1);
891                                 }
892                                 break;
893                         case 3:
894                                 if (inp & PBTN_DOWN)  spr_offs++;
895                                 if (inp & PBTN_UP)    spr_offs--;
896                                 if (spr_offs < 0) spr_offs = 0;
897                                 break;
898                 }
899         }
900 }
901
902 // ------------ main menu ------------
903
904 static const char credits[] =
905         "PicoDrive v" VERSION " (c) notaz, 2006-2011\n\n\n"
906         "Credits:\n"
907         "fDave: Cyclone 68000 core,\n"
908         "      base code of PicoDrive\n"
909         "Reesy & FluBBa: DrZ80 core\n"
910         "MAME devs: YM2612 and SN76496 cores\n"
911         "Inder, ketchupgun: graphics\n"
912 #ifdef __GP2X__
913         "rlyeh and others: minimal SDK\n"
914         "Squidge: mmuhack\n"
915         "Dzz: ARM940 sample\n"
916 #endif
917         "\n"
918         "special thanks (for docs, ideas):\n"
919         " Charles MacDonald, Haze,\n"
920         " Stephane Dallongeville,\n"
921         " Lordus, Exophase, Rokas,\n"
922         " Nemesis, Tasco Deluxe";
923
924 static int main_menu_handler(int id, int keys)
925 {
926         const char *ret_name;
927
928         switch (id)
929         {
930         case MA_MAIN_RESUME_GAME:
931                 if (PicoGameLoaded)
932                         return 1;
933                 break;
934         case MA_MAIN_SAVE_STATE:
935                 if (PicoGameLoaded)
936                         return menu_loop_savestate(0);
937                 break;
938         case MA_MAIN_LOAD_STATE:
939                 if (PicoGameLoaded)
940                         return menu_loop_savestate(1);
941                 break;
942         case MA_MAIN_RESET_GAME:
943                 if (PicoGameLoaded) {
944                         emu_reset_game();
945                         return 1;
946                 }
947                 break;
948         case MA_MAIN_LOAD_ROM:
949                 rom_fname_reload = NULL;
950                 ret_name = menu_loop_romsel(rom_fname_loaded,
951                         sizeof(rom_fname_loaded), rom_exts, NULL);
952                 if (ret_name != NULL) {
953                         lprintf("selected file: %s\n", ret_name);
954                         rom_fname_reload = ret_name;
955                         engineState = PGS_ReloadRom;
956                         return 1;
957                 }
958                 break;
959         case MA_MAIN_CREDITS:
960                 draw_menu_message(credits, NULL);
961                 in_menu_wait(PBTN_MOK|PBTN_MBACK, NULL, 70);
962                 break;
963         case MA_MAIN_EXIT:
964                 engineState = PGS_Quit;
965                 return 1;
966         case MA_MAIN_PATCHES:
967                 if (PicoGameLoaded && PicoPatches) {
968                         menu_loop_patches();
969                         PicoPatchApply();
970                         menu_update_msg("Patches applied");
971                 }
972                 break;
973         default:
974                 lprintf("%s: something unknown selected\n", __FUNCTION__);
975                 break;
976         }
977
978         return 0;
979 }
980
981 static menu_entry e_menu_main[] =
982 {
983         mee_label     ("PicoDrive " VERSION),
984         mee_label     (""),
985         mee_label     (""),
986         mee_label     (""),
987         mee_handler_id("Resume game",        MA_MAIN_RESUME_GAME, main_menu_handler),
988         mee_handler_id("Save State",         MA_MAIN_SAVE_STATE,  main_menu_handler),
989         mee_handler_id("Load State",         MA_MAIN_LOAD_STATE,  main_menu_handler),
990         mee_handler_id("Reset game",         MA_MAIN_RESET_GAME,  main_menu_handler),
991         mee_handler_id("Load new ROM/ISO",   MA_MAIN_LOAD_ROM,    main_menu_handler),
992         mee_handler   ("Change options",                          menu_loop_options),
993         mee_handler   ("Configure controls",                      menu_loop_keyconfig),
994         mee_handler_id("Credits",            MA_MAIN_CREDITS,     main_menu_handler),
995         mee_handler_id("Patches / GameGenie",MA_MAIN_PATCHES,     main_menu_handler),
996         mee_handler_id("Exit",               MA_MAIN_EXIT,        main_menu_handler),
997         mee_end,
998 };
999
1000 void menu_loop(void)
1001 {
1002         static int sel = 0;
1003
1004         me_enable(e_menu_main, MA_MAIN_RESUME_GAME, PicoGameLoaded);
1005         me_enable(e_menu_main, MA_MAIN_SAVE_STATE,  PicoGameLoaded);
1006         me_enable(e_menu_main, MA_MAIN_LOAD_STATE,  PicoGameLoaded);
1007         me_enable(e_menu_main, MA_MAIN_RESET_GAME,  PicoGameLoaded);
1008         me_enable(e_menu_main, MA_MAIN_PATCHES, PicoPatches != NULL);
1009
1010         menu_enter(PicoGameLoaded);
1011         in_set_config_int(0, IN_CFG_BLOCKING, 1);
1012         me_loop_d(e_menu_main, &sel, NULL, menu_main_plat_draw);
1013
1014         if (PicoGameLoaded) {
1015                 if (engineState == PGS_Menu)
1016                         engineState = PGS_Running;
1017                 /* wait until menu, ok, back is released */
1018                 while (in_menu_wait_any(NULL, 50) & (PBTN_MENU|PBTN_MOK|PBTN_MBACK))
1019                         ;
1020         }
1021
1022         in_set_config_int(0, IN_CFG_BLOCKING, 0);
1023         plat_video_menu_leave();
1024 }
1025
1026 // --------- CD tray close menu ----------
1027
1028 static int mh_tray_load_cd(int id, int keys)
1029 {
1030         const char *ret_name;
1031
1032         rom_fname_reload = NULL;
1033         ret_name = menu_loop_romsel(rom_fname_loaded,
1034                         sizeof(rom_fname_loaded), rom_exts, NULL);
1035         if (ret_name == NULL)
1036                 return 0;
1037
1038         rom_fname_reload = ret_name;
1039         engineState = PGS_RestartRun;
1040         return emu_swap_cd(ret_name);
1041 }
1042
1043 static int mh_tray_nothing(int id, int keys)
1044 {
1045         return 1;
1046 }
1047
1048 static menu_entry e_menu_tray[] =
1049 {
1050         mee_label  ("The CD tray has opened."),
1051         mee_label  (""),
1052         mee_label  (""),
1053         mee_handler("Load CD image",  mh_tray_load_cd),
1054         mee_handler("Insert nothing", mh_tray_nothing),
1055         mee_end,
1056 };
1057
1058 int menu_loop_tray(void)
1059 {
1060         int ret = 1, sel = 0;
1061
1062         menu_enter(PicoGameLoaded);
1063
1064         in_set_config_int(0, IN_CFG_BLOCKING, 1);
1065         me_loop(e_menu_tray, &sel);
1066
1067         if (engineState != PGS_RestartRun) {
1068                 engineState = PGS_RestartRun;
1069                 ret = 0; /* no CD inserted */
1070         }
1071
1072         while (in_menu_wait_any(NULL, 50) & (PBTN_MENU|PBTN_MOK|PBTN_MBACK));
1073         in_set_config_int(0, IN_CFG_BLOCKING, 0);
1074         plat_video_menu_leave();
1075
1076         return ret;
1077 }
1078
1079 void menu_update_msg(const char *msg)
1080 {
1081         strncpy(menu_error_msg, msg, sizeof(menu_error_msg));
1082         menu_error_msg[sizeof(menu_error_msg) - 1] = 0;
1083
1084         menu_error_time = plat_get_ticks_ms();
1085         lprintf("msg: %s\n", menu_error_msg);
1086 }
1087
1088 // ------------ util ------------
1089
1090 /* hidden options for config engine only */
1091 static menu_entry e_menu_hidden[] =
1092 {
1093         mee_onoff("Accurate sprites", MA_OPT_ACC_SPRITES, PicoOpt, 0x080),
1094         mee_end,
1095 };
1096
1097 static menu_entry *e_menu_table[] =
1098 {
1099         e_menu_options,
1100         e_menu_gfx_options,
1101         e_menu_adv_options,
1102         e_menu_cd_options,
1103 #ifndef NO_32X
1104         e_menu_32x_options,
1105 #endif
1106         e_menu_keyconfig,
1107         e_menu_hidden,
1108 };
1109
1110 static menu_entry *me_list_table = NULL;
1111 static menu_entry *me_list_i = NULL;
1112
1113 menu_entry *me_list_get_first(void)
1114 {
1115         me_list_table = me_list_i = e_menu_table[0];
1116         return me_list_i;
1117 }
1118
1119 menu_entry *me_list_get_next(void)
1120 {
1121         int i;
1122
1123         me_list_i++;
1124         if (me_list_i->name != NULL)
1125                 return me_list_i;
1126
1127         for (i = 0; i < array_size(e_menu_table); i++)
1128                 if (me_list_table == e_menu_table[i])
1129                         break;
1130
1131         if (i + 1 < array_size(e_menu_table))
1132                 me_list_table = me_list_i = e_menu_table[i + 1];
1133         else
1134                 me_list_table = me_list_i = NULL;
1135
1136         return me_list_i;
1137 }
1138
1139 void menu_init(void)
1140 {
1141         int i;
1142
1143         menu_init_base();
1144
1145         i = me_id2offset(e_menu_gfx_options, MA_OPT_VOUT_MODE);
1146         e_menu_gfx_options[i].data = plat_target.vout_methods;
1147         me_enable(e_menu_gfx_options, MA_OPT_VOUT_MODE,
1148                 plat_target.vout_methods != NULL);
1149
1150         i = me_id2offset(e_menu_gfx_options, MA_OPT3_FILTERING);
1151         e_menu_gfx_options[i].data = plat_target.hwfilters;
1152         me_enable(e_menu_gfx_options, MA_OPT3_FILTERING,
1153                 plat_target.hwfilters != NULL);
1154
1155         me_enable(e_menu_gfx_options, MA_OPT3_GAMMA,
1156                 plat_target.gamma_set != NULL);
1157 }