53e52b87d9f0ac05e8f8062d23a270d2662d6899
[picodrive.git] / platform / common / menu_pico.c
1 /*
2  * PicoDrive
3  * (C) notaz, 2010,2011
4  * (C) irixxxx, 2023,2024
5  *
6  * This work is licensed under the terms of MAME license.
7  * See COPYING file in the top-level directory.
8  */
9 #include <stdio.h>
10 #include <string.h>
11 #include <time.h>
12
13 #include "emu.h"
14 #include "menu_pico.h"
15 #include "input_pico.h"
16 #include "version.h"
17
18 #include "../libpicofe/plat.h"
19
20 #include <pico/pico_int.h>
21 #include <pico/patch.h>
22
23 #if defined(PANDORA) || defined(__PS2__)
24 #define MENU_X2 1
25 #else
26 #define MENU_X2 0
27 #endif
28
29 #define COL_ROM PXMAKE(0xbf, 0xbf, 0xff)
30 #define COL_OTH PXMAKE(0xaf, 0xff, 0xaf)
31
32 // FIXME
33 #ifndef REVISION
34 #define REVISION "0"
35 #endif
36
37 static const char *rom_exts[] = {
38         "zip", "bin",
39         "pco", "smd", "gen", "md",
40         "iso", "cso", "cue", "chd",
41         "32x",
42         "sms", "gg",  "sg", "sc",
43         NULL
44 };
45
46 // rrrr rggg gggb bbbb
47 static unsigned short fname2color(const char *fname)
48 {
49         static const char *other_exts[] = { "gmv", "pat" };
50         const char *ext;
51         int i;
52
53         ext = strrchr(fname, '.');
54         if (ext++ == NULL) {
55                 ext = fname + strlen(fname) - 3;
56                 if (ext < fname) ext = fname;
57         }
58
59         for (i = 0; rom_exts[i] != NULL; i++)
60                 if (strcasecmp(ext, rom_exts[i]) == 0) return COL_ROM;
61         for (i = 0; i < array_size(other_exts); i++)
62                 if (strcasecmp(ext, other_exts[i]) == 0) return COL_OTH;
63         return PXMAKE(0xff, 0xff, 0xff);
64 }
65
66 #include <platform/libpicofe/menu.c>
67
68 static const char *men_dummy[] = { NULL };
69 static int menu_w, menu_h;
70
71 /* platform specific options and handlers */
72 #if   defined(__GP2X__)
73 #include <platform/gp2x/menu.c>
74 #elif defined(__PSP__)
75 #include <platform/psp/menu.c>
76 #elif defined(__PS2__)
77 #include <platform/ps2/menu.c>
78 #elif defined(PANDORA)
79 #include <platform/pandora/menu.c>
80 #else
81 #include <platform/linux/menu.c>
82 #endif
83
84 static void make_bg(int no_scale, int from_screen)
85 {
86         unsigned short *src = (void *)g_menubg_src_ptr;
87         int w = g_menubg_src_w ? g_menubg_src_w : g_screen_width;
88         int h = g_menubg_src_h ? g_menubg_src_h : g_screen_height;
89         int pp = g_menubg_src_pp ? g_menubg_src_pp : g_screen_ppitch;
90         short *dst;
91         int x, y;
92
93         if (from_screen) {
94                 src = g_screen_ptr;
95                 w = g_screen_width;
96                 h = g_screen_height;
97                 pp = g_screen_ppitch;
98         }
99
100         memset(g_menubg_ptr, 0, g_menuscreen_w * g_menuscreen_h * 2);
101         if (src == NULL)
102                 return;
103
104         if (!no_scale && g_menuscreen_w / w >= 2 && g_menuscreen_h / h >= 2)
105         {
106                 u32 t, *d = g_menubg_ptr;
107                 d += (g_menuscreen_h / 2 - h * 2 / 2)
108                         * g_menuscreen_w / 2;
109                 d += (g_menuscreen_w / 2 - w * 2 / 2) / 2;
110                 for (y = 0; y < h; y++, src += pp, d += g_menuscreen_w*2/2) {
111                         for (x = 0; x < w; x++) {
112                                 t = src[x];
113                                 t = (PXMASKH(t,1)>>1) - (PXMASKH(t,3)>>3);
114                                 t |= t << 16;
115                                 d[x] = d[x + g_menuscreen_w / 2] = t;
116                         }
117                 }
118                 return;
119         }
120
121         if (w > g_menuscreen_w)
122                 w = g_menuscreen_w;
123         if (h > g_menuscreen_h)
124                 h = g_menuscreen_h;
125         dst = (short *)g_menubg_ptr +
126                 (g_menuscreen_h / 2 - h / 2) * g_menuscreen_w +
127                 (g_menuscreen_w / 2 - w / 2);
128
129         // darken the active framebuffer
130         for (; h > 0; dst += g_menuscreen_w, src += pp, h--)
131                 menu_darken_bg(dst, src, w, 1);
132 }
133
134 static void copy_bg(int dir)
135 {
136         unsigned short *bg = (void *)g_menubg_ptr;
137         unsigned short *sc = (void *)g_menuscreen_ptr;
138         int h = g_menuscreen_h;
139
140         for (; h > 0; sc += g_menuscreen_pp, bg += g_menuscreen_w, h--) {
141                 if (dir)
142                         memcpy(bg, sc, g_menuscreen_w * 2);
143                 else
144                         memcpy(sc, bg, g_menuscreen_w * 2);
145         }
146 }
147
148 static void menu_draw_prep(void)
149 {
150         if (menu_w == g_menuscreen_w && menu_h == g_menuscreen_h)
151                 return;
152         menu_w = g_menuscreen_w, menu_h = g_menuscreen_h;
153
154         if (PicoGameLoaded)
155         {
156                 make_bg(0, 0);
157         }
158         else
159         {
160                 int pos;
161                 char buff[256];
162                 pos = plat_get_skin_dir(buff, 256);
163                 strcpy(buff + pos, "background.png");
164
165                 // should really only happen once, on startup..
166                 memset(g_menubg_ptr, 0, g_menuscreen_w * g_menuscreen_h * 2);
167                 if (readpng(g_menubg_ptr, buff, READPNG_BG,
168                                                 g_menuscreen_w, g_menuscreen_h) < 0)
169                         memset(g_menubg_ptr, 0, g_menuscreen_w * g_menuscreen_h * 2);
170         }
171 }
172
173 static void draw_savestate_bg(int slot)
174 {
175         const char *fname;
176         void *tmp_state;
177
178         fname = emu_get_save_fname(1, 0, slot, NULL);
179         if (!fname)
180                 return;
181
182         tmp_state = PicoTmpStateSave();
183
184         PicoStateLoadGfx(fname);
185
186         /* do a frame and fetch menu bg */
187         pemu_forced_frame(0, 0);
188
189         make_bg(0, 1);
190
191         PicoTmpStateRestore(tmp_state);
192 }
193
194 static void menu_enter(int is_rom_loaded)
195 {
196         plat_video_menu_enter(is_rom_loaded);
197         menu_w = menu_h = 0;
198         menu_draw_prep();
199 }
200
201 // --------- loading ROM screen ----------
202
203 static int cdload_called = 0;
204
205 static void load_progress_cb(int percent)
206 {
207         int ln, len = percent * g_menuscreen_w / 100;
208         unsigned short *dst;
209
210         if (len > g_menuscreen_w)
211                 len = g_menuscreen_w;
212
213         menu_draw_begin(0, 1);
214         copy_bg(0);
215         dst = (unsigned short *)g_menuscreen_ptr + g_menuscreen_pp * me_sfont_h * 2;
216         for (ln = me_sfont_h - 2; ln > 0; ln--, dst += g_menuscreen_pp)
217                 memset(dst, 0xff, len * 2);
218         menu_draw_end();
219 }
220
221 static void cdload_progress_cb(const char *fname, int percent)
222 {
223         int ln, len = percent * g_menuscreen_w / 100;
224         unsigned short *dst;
225
226         menu_draw_begin(0, 1);
227         dst = (unsigned short *)g_menuscreen_ptr + g_menuscreen_pp * me_sfont_h * 2;
228
229         copy_bg(0);
230         menuscreen_memset_lines(dst, 0xff, me_sfont_h - 2);
231
232         smalltext_out16(1, 3 * me_sfont_h, "Processing CD image / MP3s", PXMAKE(0xff, 0xff, 0xff));
233         smalltext_out16(1, 4 * me_sfont_h, fname, PXMAKE(0xff, 0xff, 0xff));
234         dst += g_menuscreen_pp * me_sfont_h * 3;
235
236         if (len > g_menuscreen_w)
237                 len = g_menuscreen_w;
238
239         for (ln = (me_sfont_h - 2); ln > 0; ln--, dst += g_menuscreen_pp)
240                 memset(dst, 0xff, len * 2);
241         menu_draw_end();
242
243         cdload_called = 1;
244 }
245
246 void menu_romload_prepare(const char *rom_name)
247 {
248         const char *p = rom_name + strlen(rom_name);
249
250         while (p > rom_name && *p != '/')
251                 p--;
252
253         menu_draw_begin(1, 1);
254         smalltext_out16(1, 1, "Loading", PXMAKE(0xff, 0xff, 0xff));
255         smalltext_out16(1, me_sfont_h, p, PXMAKE(0xff, 0xff, 0xff));
256         /* copy menu to bg for callbacks. OK since we are not in menu_loop here */
257         copy_bg(1);
258         menu_draw_end();
259
260         PicoCartLoadProgressCB = load_progress_cb;
261         PicoCDLoadProgressCB = cdload_progress_cb;
262         cdload_called = 0;
263 }
264
265 void menu_romload_end(void)
266 {
267         PicoCartLoadProgressCB = NULL;
268         PicoCDLoadProgressCB = NULL;
269
270         menu_draw_begin(0, 1);
271         copy_bg(0);
272         smalltext_out16(1, (cdload_called ? 6 : 3) * me_sfont_h,
273                 "Starting emulation...", PXMAKE(0xff, 0xff, 0xff));
274         menu_draw_end();
275 }
276
277 // ------------ patch/gg menu ------------
278
279 static void draw_patchlist(int sel)
280 {
281         int max_cnt, start, i, pos, active;
282
283         max_cnt = g_menuscreen_h / me_sfont_h;
284         start = max_cnt / 2 - sel;
285
286         menu_draw_begin(1, 0);
287
288         for (i = 0; i < PicoPatchCount; i++) {
289                 pos = start + i;
290                 if (pos < 0) continue;
291                 if (pos >= max_cnt) break;
292                 active = PicoPatches[i].active;
293                 smalltext_out16(14,                pos * me_sfont_h, active ? "ON " : "OFF", PXMAKE(0xff, 0xff, active ? 0xff : 0xb0));
294                 smalltext_out16(14 + me_sfont_w*4, pos * me_sfont_h, PicoPatches[i].name,    PXMAKE(0xff, 0xff, active ? 0xff : 0xb0));
295         }
296         pos = start + i;
297         if (pos < max_cnt)
298                 smalltext_out16(14, pos * me_sfont_h, "done", PXMAKE(0xff, 0xff, 0xff));
299
300         text_out16(5, max_cnt / 2 * me_sfont_h, ">");
301         menu_draw_end();
302 }
303
304 static void menu_loop_patches(void)
305 {
306         static int menu_sel = 0;
307         int inp;
308
309         for (;;)
310         {
311                 draw_patchlist(menu_sel);
312                 inp = in_menu_wait(PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT|PBTN_L|PBTN_R
313                                 |PBTN_MOK|PBTN_MBACK, NULL, 33);
314                 if (inp & PBTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = PicoPatchCount; }
315                 if (inp & PBTN_DOWN) { menu_sel++; if (menu_sel > PicoPatchCount) menu_sel = 0; }
316                 if (inp &(PBTN_LEFT|PBTN_L))  { menu_sel-=10; if (menu_sel < 0) menu_sel = 0; }
317                 if (inp &(PBTN_RIGHT|PBTN_R)) { menu_sel+=10; if (menu_sel > PicoPatchCount) menu_sel = PicoPatchCount; }
318                 if (inp & PBTN_MOK) { // action
319                         if (menu_sel < PicoPatchCount)
320                                 PicoPatches[menu_sel].active = !PicoPatches[menu_sel].active;
321                         else    break;
322                 }
323                 if (inp & PBTN_MBACK)
324                         break;
325         }
326 }
327
328 // -------------- key config --------------
329
330 // PicoIn.pad[] format: MXYZ SACB RLDU
331 me_bind_action me_ctrl_actions[] =
332 {
333         { "UP     ", 0x0001 },
334         { "DOWN   ", 0x0002 },
335         { "LEFT   ", 0x0004 },
336         { "RIGHT  ", 0x0008 },
337         { "A      ", 0x0040 },
338         { "B      ", 0x0010 },
339         { "C      ", 0x0020 },
340         { "A turbo", 0x4000 },
341         { "B turbo", 0x1000 },
342         { "C turbo", 0x2000 },
343         { "START  ", 0x0080 },
344         { "MODE   ", 0x0800 },
345         { "X      ", 0x0400 },
346         { "Y      ", 0x0200 },
347         { "Z      ", 0x0100 },
348         { NULL,      0 },
349 };
350
351 me_bind_action emuctrl_actions[] =
352 {
353         { "Load State     ", PEV_STATE_LOAD },
354         { "Save State     ", PEV_STATE_SAVE },
355         { "Prev Save Slot ", PEV_SSLOT_PREV },
356         { "Next Save Slot ", PEV_SSLOT_NEXT },
357         { "Switch Renderer", PEV_SWITCH_RND },
358         { "Volume Down    ", PEV_VOL_DOWN },
359         { "Volume Up      ", PEV_VOL_UP },
360         { "Fast forward   ", PEV_FF },
361         { "Reset Game     ", PEV_RESET },
362         { "Enter Menu     ", PEV_MENU },
363         { "Pico Next page ", PEV_PICO_PNEXT },
364         { "Pico Prev page ", PEV_PICO_PPREV },
365         { "Pico Storyware ", PEV_PICO_STORY },
366         { "Pico Pad       ", PEV_PICO_PAD },
367         { "Pico Pen state ", PEV_PICO_PENST },
368         { NULL,                0 }
369 };
370
371 static int key_config_loop_wrap(int id, int keys)
372 {
373         switch (id) {
374                 case MA_CTRL_PLAYER1:
375                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 0);
376                         break;
377                 case MA_CTRL_PLAYER2:
378                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 1);
379                         break;
380                 case MA_CTRL_PLAYER3:
381                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 2);
382                         break;
383                 case MA_CTRL_PLAYER4:
384                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 3);
385                         break;
386                 case MA_CTRL_EMU:
387                         key_config_loop(emuctrl_actions, array_size(emuctrl_actions) - 1, -1);
388                         break;
389                 default:
390                         break;
391         }
392         return 0;
393 }
394
395 static const char *mgn_dev_name(int id, int *offs)
396 {
397         const char *name = NULL;
398         static int it = 0;
399
400         if (id == MA_CTRL_DEV_FIRST)
401                 it = 0;
402
403         for (; it < IN_MAX_DEVS; it++) {
404                 name = in_get_dev_name(it, 1, 1);
405                 if (name != NULL)
406                         break;
407         }
408
409         it++;
410         return name;
411 }
412
413 const char *indev0_names[] = { "none", "3 button pad", "6 button pad", "Team player", "4 way play", NULL };
414 const char *indev1_names[] = { "none", "3 button pad", "6 button pad", NULL };
415
416 static char h_play34[] = "Works only for Mega Drive/CD/32X games having\n"
417                                 "support for Team player or 4 way play";
418
419 static menu_entry e_menu_keyconfig[] =
420 {
421         mee_handler_id("Player 1",          MA_CTRL_PLAYER1,    key_config_loop_wrap),
422         mee_handler_id("Player 2",          MA_CTRL_PLAYER2,    key_config_loop_wrap),
423         mee_handler_id_h("Player 3",        MA_CTRL_PLAYER3,    key_config_loop_wrap, h_play34),
424         mee_handler_id_h("Player 4",        MA_CTRL_PLAYER4,    key_config_loop_wrap, h_play34),
425         mee_handler_id("Emulator hotkeys",  MA_CTRL_EMU,        key_config_loop_wrap),
426         mee_enum      ("Input device 1",    MA_OPT_INPUT_DEV0,  currentConfig.input_dev0, indev0_names),
427         mee_enum      ("Input device 2",    MA_OPT_INPUT_DEV1,  currentConfig.input_dev1, indev1_names),
428         mee_range     ("Turbo rate",        MA_CTRL_TURBO_RATE, currentConfig.turbo_rate, 1, 30),
429         mee_range     ("Analog deadzone",   MA_CTRL_DEADZONE,   currentConfig.analog_deadzone, 1, 99),
430         mee_label     (""),
431         mee_label     ("Input devices:"),
432         mee_label_mk  (MA_CTRL_DEV_FIRST, mgn_dev_name),
433         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
434         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
435         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
436         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
437         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
438         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
439         mee_end,
440 };
441
442 static int menu_loop_keyconfig(int id, int keys)
443 {
444         static int sel = 0;
445         int it = 0, x = me_id2offset(e_menu_keyconfig, MA_CTRL_DEV_FIRST);
446
447         while (in_get_dev_name(it, 1, 1))
448                 it++;
449         for (it += x; x && e_menu_keyconfig[x].name; x++)
450                 e_menu_keyconfig[x].enabled = x < it;
451
452         me_loop_d(e_menu_keyconfig, &sel, menu_draw_prep, NULL);
453
454         PicoSetInputDevice(0, currentConfig.input_dev0);
455         PicoSetInputDevice(1, currentConfig.input_dev1);
456
457         return 0;
458 }
459
460 // ------------ MD options menu ------------
461
462 static const char h_renderer[] = "16bit is more accurate, 8bit is faster";
463 static const char h_fmsound[]  = "Disabling improves performance, but breaks sound";
464 static const char h_dacnoise[] = "FM chips in the 1st Mega Drive model have DAC noise,\n"
465                                 "newer models used different chips without this";
466 static const char h_fmfilter[] = "Improves sound accuracy but is noticeably slower,\n"
467                                 "best quality if native rate isn't working";
468 static const char h_picopen[]  = "Enabling resets Pico display and d-pad input back to\n"
469                                 "screen if the Pico pen button is pressed";
470
471 static menu_entry e_menu_md_options[] =
472 {
473         mee_enum_h    ("Renderer",                  MA_OPT_RENDERER, currentConfig.renderer, renderer_names, h_renderer),
474         mee_onoff_h   ("FM audio",                  MA_OPT2_ENABLE_YM2612, PicoIn.opt, POPT_EN_FM, h_fmsound),
475         mee_onoff_h   ("FM filter",                 MA_OPT_FM_FILTER, PicoIn.opt, POPT_EN_FM_FILTER, h_fmfilter),
476         mee_onoff_h   ("FM DAC noise",              MA_OPT2_ENABLE_YM_DAC, PicoIn.opt, POPT_EN_FM_DAC, h_dacnoise),
477         mee_onoff_h   ("Pen button shows screen",   MA_OPT_PICO_PEN, currentConfig.EmuOpt, EOPT_PICO_PEN, h_picopen),
478         mee_end,
479 };
480
481 static int menu_loop_md_options(int id, int keys)
482 {
483         static int sel = 0;
484         if (renderer_names[0] == NULL)
485                 me_enable(e_menu_md_options, MA_OPT_RENDERER, 0);
486         me_loop_d(e_menu_md_options, &sel, menu_draw_prep, NULL);
487
488         return 0;
489 }
490
491 // ------------ SCD options menu ------------
492
493 static const char h_cdleds[] = "Show power/CD LEDs of emulated console";
494 static const char h_cdda[]   = "Play audio tracks from mp3s/wavs/bins";
495 static const char h_cdpcm[]  = "Emulate PCM audio chip for effects/voices/music";
496 static const char h_srcart[] = "Emulate the save RAM cartridge accessory\n"
497                                 "most games don't need this";
498
499 static menu_entry e_menu_cd_options[] =
500 {
501         mee_onoff_h("SaveRAM cart",         MA_CDOPT_SAVERAM,       PicoIn.opt, POPT_EN_MCD_RAMCART, h_srcart),
502         mee_onoff_h("CD LEDs",              MA_CDOPT_LEDS,          currentConfig.EmuOpt, EOPT_EN_CD_LEDS, h_cdleds),
503         mee_onoff_h("CDDA audio",           MA_CDOPT_CDDA,          PicoIn.opt, POPT_EN_MCD_CDDA, h_cdda),
504         mee_onoff_h("PCM audio",            MA_CDOPT_PCM,           PicoIn.opt, POPT_EN_MCD_PCM, h_cdpcm),
505         mee_end,
506 };
507
508 static int menu_loop_cd_options(int id, int keys)
509 {
510         static int sel = 0;
511         me_loop_d(e_menu_cd_options, &sel, menu_draw_prep, NULL);
512         return 0;
513 }
514
515 // ------------ 32X options menu ------------
516
517 #ifndef NO_32X
518
519 // convert from multiplier of VClk
520 static int mh_opt_sh2cycles(int id, int keys)
521 {
522         int *khz = (id == MA_32XOPT_MSH2_CYCLES) ?
523                 &currentConfig.msh2_khz : &currentConfig.ssh2_khz;
524
525         if (keys & (PBTN_LEFT|PBTN_RIGHT))
526                 *khz += (keys & PBTN_LEFT) ? -50 : 50;
527         if (keys & (PBTN_L|PBTN_R))
528                 *khz += (keys & PBTN_L) ? -500 : 500;
529
530         if (*khz < 1)
531                 *khz = 1;
532         else if (*khz > 0x7fffffff / 1000)
533                 *khz = 0x7fffffff / 1000;
534
535         return 0;
536 }
537
538 static const char *mgn_opt_sh2cycles(int id, int *offs)
539 {
540         int khz = (id == MA_32XOPT_MSH2_CYCLES) ?
541                 currentConfig.msh2_khz : currentConfig.ssh2_khz;
542
543         sprintf(static_buff, "%d", khz);
544         return static_buff;
545 }
546
547 static const char h_pwm[]        = "Disabling may improve performance, but break sound";
548 static const char h_pwmopt[]     = "Enabling may improve performance, but break sound";
549
550 static menu_entry e_menu_32x_options[] =
551 {
552         mee_enum      ("32X renderer",      MA_32XOPT_RENDERER,    currentConfig.renderer32x, renderer_names32x),
553         mee_onoff_h   ("PWM audio",         MA_32XOPT_PWM,         PicoIn.opt, POPT_EN_PWM, h_pwm),
554         mee_onoff_h   ("PWM IRQ optimization", MA_OPT2_PWM_IRQ_OPT, PicoIn.opt, POPT_PWM_IRQ_OPT, h_pwmopt),
555         mee_end,
556 };
557
558 static int menu_loop_32x_options(int id, int keys)
559 {
560         static int sel = 0;
561
562         if (renderer_names32x[0] == NULL)
563                 me_enable(e_menu_32x_options, MA_32XOPT_RENDERER, 0);
564         me_loop_d(e_menu_32x_options, &sel, menu_draw_prep, NULL);
565
566         Pico32xSetClocks(currentConfig.msh2_khz * 1000, currentConfig.msh2_khz * 1000);
567
568         return 0;
569 }
570
571 #endif
572
573 // ------------ SMS options menu ------------
574
575 #ifndef NO_SMS
576
577 static const char *sms_hardwares[] = { "auto", "Game Gear", "Master System", "SG-1000", "SC-3000", NULL };
578 static const char *gg_ghosting_opts[] = { "OFF", "weak", "normal", NULL };
579 static const char *sms_mappers[] = { "auto", "Sega", "Codemasters", "Korea", "Korea MSX", "Korea X-in-1", "Korea 4-Pak", "Korea Janggun", "Korea Nemesis", "Taiwan 8K RAM", "Korea XOR", "Sega 32K RAM", NULL };
580 static const char *sms_tmspalette[] = { "SMS", "SG-1000", NULL };
581
582 static const char h_smsfm[] = "FM sound is only supported by few games,\n"
583                                 "some games may crash with FM enabled";
584 static const char h_ghost[] = "Simulate the inertia of the GG LCD display";
585 static const char h_smspal[] = "Selects the color palette used for SMS games\n"
586                                 "using the original TMS9918 graphics modes";
587
588 static menu_entry e_menu_sms_options[] =
589 {
590         mee_enum      ("System",            MA_SMSOPT_HARDWARE, PicoIn.hwSelect, sms_hardwares),
591         mee_enum      ("Cartridge mapping", MA_SMSOPT_MAPPER, PicoIn.mapper, sms_mappers),
592         mee_enum_h    ("Game Gear LCD ghosting", MA_SMSOPT_GHOSTING, currentConfig.ghosting, gg_ghosting_opts, h_ghost),
593         mee_onoff_h   ("FM Sound Unit",     MA_OPT2_ENABLE_YM2413, PicoIn.opt, POPT_EN_YM2413, h_smsfm),
594         mee_enum_h    ("SMS palette in TMS mode", MA_SMSOPT_TMSPALETTE, PicoIn.tmsPalette, sms_tmspalette, h_smspal),
595         mee_end,
596 };
597
598 static int menu_loop_sms_options(int id, int keys)
599 {
600         static int sel = 0;
601
602         me_loop_d(e_menu_sms_options, &sel, menu_draw_prep, NULL);
603
604         return 0;
605 }
606
607 #endif
608
609 // ------------ adv options menu ------------
610
611 static const char h_gglcd[] = "Show full VDP image with borders if disabled";
612 static const char h_ovrclk[] = "Will break some games, keep at 0";
613 static const char h_dynarec[] = "Disabling dynarecs massively slows down 32X";
614 static const char h_sh2cycles[]  = "Cycles/millisecond (similar to DOSBox)\n"
615                                    "lower values speed up emulation but break games\n"
616                                    "at least 11000 recommended for compatibility";
617
618 static menu_entry e_menu_adv_options[] =
619 {
620         mee_onoff     ("Disable frame limiter",    MA_OPT2_NO_FRAME_LIMIT,currentConfig.EmuOpt, EOPT_NO_FRMLIMIT),
621         mee_onoff     ("Disable sprite limit",     MA_OPT2_NO_SPRITE_LIM, PicoIn.opt, POPT_DIS_SPRITE_LIM),
622         mee_onoff     ("Disable idle loop patching",MA_OPT2_NO_IDLE_LOOPS,PicoIn.opt, POPT_DIS_IDLE_DET),
623         mee_onoff_h   ("Emulate Game Gear LCD",    MA_OPT2_ENABLE_GGLCD  ,PicoIn.opt, POPT_EN_GG_LCD, h_gglcd),
624         mee_range_h   ("Overclock M68k (%)",       MA_OPT2_OVERCLOCK_M68K,currentConfig.overclock_68k, 0, 1000, h_ovrclk),
625         mee_onoff_h   ("Enable dynarecs",          MA_OPT2_DYNARECS,      PicoIn.opt, POPT_EN_DRC, h_dynarec),
626         mee_cust_h    ("Master SH2 cycles",        MA_32XOPT_MSH2_CYCLES, mh_opt_sh2cycles, mgn_opt_sh2cycles, h_sh2cycles),
627         mee_cust_h    ("Slave SH2 cycles",         MA_32XOPT_SSH2_CYCLES, mh_opt_sh2cycles, mgn_opt_sh2cycles, h_sh2cycles),
628         MENU_OPTIONS_ADV
629         mee_end,
630 };
631
632 static int menu_loop_adv_options(int id, int keys)
633 {
634         static int sel = 0;
635
636         me_loop_d(e_menu_adv_options, &sel, menu_draw_prep, NULL);
637         PicoIn.overclockM68k = currentConfig.overclock_68k; // int vs short
638
639         return 0;
640 }
641
642 // ------------ sound options menu ------------
643
644 static int sndrate_prevnext(int rate, int dir)
645 {
646         const int *rates = plat_target.sound_rates;
647         int rate_count;
648         int i;
649
650         for (rate_count = 0; rates[rate_count] != -1; rate_count++)
651                 ;
652         for (i = 0; i < rate_count; i++)
653                 if (rates[i] == rate) break;
654
655         i += dir ? 1 : -1;
656         if (i >= rate_count) {
657                 if (!(PicoIn.opt & POPT_EN_STEREO)) {
658                         PicoIn.opt |= POPT_EN_STEREO;
659                         return rates[0];
660                 }
661                 return rates[rate_count-1];
662         }
663         if (i < 0) {
664                 if (PicoIn.opt & POPT_EN_STEREO) {
665                         PicoIn.opt &= ~POPT_EN_STEREO;
666                         return rates[rate_count-1];
667                 }
668                 return rates[0];
669         }
670         return rates[i];
671 }
672
673 static int mh_opt_snd(int id, int keys)
674 {
675         PicoIn.sndRate = sndrate_prevnext(PicoIn.sndRate, keys & PBTN_RIGHT);
676         return 0;
677 }
678
679 static const char *mgn_opt_sound(int id, int *offs)
680 {
681         const char *str2;
682         *offs = -8;
683         str2 = (PicoIn.opt & POPT_EN_STEREO) ? "stereo" : "mono";
684         if (PicoIn.sndRate > 52000 && PicoIn.sndRate < 54000)
685                 sprintf(static_buff, "native  %s", str2);
686         else    sprintf(static_buff, "%5iHz %s", PicoIn.sndRate, str2);
687         return static_buff;
688 }
689
690 static int mh_opt_alpha(int id, int keys)
691 {
692         int val = (PicoIn.sndFilterAlpha * 100 + 0x08000) / 0x10000;
693         if (keys & PBTN_LEFT)   val--;
694         if (keys & PBTN_RIGHT)  val++;
695         if (val <  1)           val = 1;
696         if (val > 99)           val = 99;
697         PicoIn.sndFilterAlpha = val * 0x10000 / 100;
698         return 0;
699 }
700
701 static const char *mgn_opt_alpha(int id, int *offs)
702 {
703         int val = (PicoIn.sndFilterAlpha * 100 + 0x08000) / 0x10000;
704         sprintf(static_buff, "0.%02d", val);
705         return static_buff;
706 }
707
708 static const char h_ensound[] = "Disabling turns off sound output, however all\n"
709                                 "enabled sound components are still emulated";
710 static const char h_quality[] = "native: Mega Drive FM hardware rate (~53000Hz),\n"
711                                 "best quality, but may not work on some devices";
712 static const char h_lowpass[] = "Low pass filter for sound closer to real hardware";
713 static const char h_lpalpha[] = "Higher values have more impact";
714
715 static menu_entry e_menu_snd_options[] =
716 {
717         mee_onoff_h   ("Enable sound",    MA_OPT_ENABLE_SOUND,  currentConfig.EmuOpt, EOPT_EN_SOUND, h_ensound),
718         mee_cust_h    ("Sound quality",   MA_OPT_SOUND_QUALITY, mh_opt_snd, mgn_opt_sound, h_quality),
719         mee_onoff_h   ("Sound filter",    MA_OPT_SOUND_FILTER,  PicoIn.opt, POPT_EN_SNDFILTER, h_lowpass),
720         mee_cust_h    ("Filter strength", MA_OPT_SOUND_ALPHA,   mh_opt_alpha, mgn_opt_alpha, h_lpalpha),
721         mee_end,
722 };
723
724 static int menu_loop_snd_options(int id, int keys)
725 {
726         static int sel = 0;
727
728         if (PicoIn.sndRate > 52000 && PicoIn.sndRate < 54000)
729                 PicoIn.sndRate = 53000;
730         me_loop_d(e_menu_snd_options, &sel, menu_draw_prep, NULL);
731
732         return 0;
733 }
734
735 // ------------ gfx options menu ------------
736
737 static const char h_gamma[] = "Gamma/brightness adjustment (default 1.00)";
738
739 static const char *mgn_opt_fskip(int id, int *offs)
740 {
741         if (currentConfig.Frameskip < 0)
742                 return "Auto";
743         sprintf(static_buff, "%d", currentConfig.Frameskip);
744         return static_buff;
745 }
746
747 static const char *mgn_aopt_gamma(int id, int *offs)
748 {
749         sprintf(static_buff, "%i.%02i", currentConfig.gamma / 100, currentConfig.gamma % 100);
750         return static_buff;
751 }
752
753 static menu_entry e_menu_gfx_options[] =
754 {
755         mee_enum      ("Video output mode", MA_OPT_VOUT_MODE, plat_target.vout_method, men_dummy),
756         mee_range_cust("Frameskip",         MA_OPT_FRAMESKIP, currentConfig.Frameskip, -1, 16, mgn_opt_fskip),
757         mee_range     ("Max auto frameskip",MA_OPT2_MAX_FRAMESKIP, currentConfig.max_skip, 1, 10),
758         mee_enum      ("Filter",            MA_OPT3_FILTERING, currentConfig.filter, men_dummy),
759         mee_range_cust_h("Gamma correction",MA_OPT2_GAMMA, currentConfig.gamma, 1, 300, mgn_aopt_gamma, h_gamma),
760         MENU_OPTIONS_GFX
761         mee_end,
762 };
763
764 static int menu_loop_gfx_options(int id, int keys)
765 {
766         static int sel = 0;
767
768         me_loop_d(e_menu_gfx_options, &sel, menu_draw_prep, NULL);
769
770         return 0;
771 }
772
773 // ------------ UI options menu ------------
774
775 static const char *men_confirm_save[] = { "OFF", "writes", "loads", "both", NULL };
776 static const char h_confirm_save[]    = "Ask for confirmation when overwriting save,\n"
777                                         "loading state or both";
778
779 static menu_entry e_menu_ui_options[] =
780 {
781         mee_onoff     ("Show FPS",                 MA_OPT_SHOW_FPS,       currentConfig.EmuOpt, EOPT_SHOW_FPS),
782         mee_enum_h    ("Confirm save/load",        MA_OPT_CONFIRM_STATES, currentConfig.confirm_save, men_confirm_save, h_confirm_save),
783         mee_onoff     ("Don't save last used game", MA_OPT2_NO_LAST_ROM,  currentConfig.EmuOpt, EOPT_NO_AUTOSVCFG),
784         mee_end,
785 };
786
787 static int menu_loop_ui_options(int id, int keys)
788 {
789         static int sel = 0;
790
791         me_loop_d(e_menu_ui_options, &sel, menu_draw_prep, NULL);
792
793         return 0;
794 }
795
796 // ------------ options menu ------------
797
798 static int find_renderer(const char *names[], const char *which)
799 {
800         int i = 0;
801         for (i = 0; *names; names++, i++)
802                 if (strstr(*names, which)) return i;
803         return 0;
804 }
805
806 static int mh_profile(int id, int keys) {
807         switch (id) {
808         case MA_PROFILE_ACCURATE:
809                 currentConfig.renderer = find_renderer(renderer_names, "16bit");
810                 currentConfig.renderer32x = find_renderer(renderer_names32x, "accurate");
811                 PicoIn.sndRate = 44100;
812                 PicoIn.opt |= POPT_EN_FM_FILTER | POPT_EN_FM | POPT_EN_MCD_CDDA;
813                 PicoIn.opt &= ~POPT_PWM_IRQ_OPT;
814                 break;
815         case MA_PROFILE_BALANCED:
816                 currentConfig.renderer = find_renderer(renderer_names, "8bit");
817                 currentConfig.renderer32x = find_renderer(renderer_names32x, "fast");
818                 PicoIn.sndRate = 44100;
819                 PicoIn.opt |= POPT_EN_FM | POPT_EN_MCD_CDDA;
820                 PicoIn.opt &= ~(POPT_PWM_IRQ_OPT | POPT_EN_FM_FILTER);
821                 break;
822         case MA_PROFILE_FAST:
823                 currentConfig.renderer = find_renderer(renderer_names, "fast");
824                 currentConfig.renderer32x = find_renderer(renderer_names32x, "fastest");
825                 PicoIn.sndRate = 22050;
826                 PicoIn.opt |= POPT_PWM_IRQ_OPT | POPT_EN_FM | POPT_EN_MCD_CDDA;
827                 PicoIn.opt &= ~POPT_EN_FM_FILTER;
828                 break;
829         case MA_PROFILE_BREAKING:
830                 currentConfig.renderer = find_renderer(renderer_names, "fast");
831                 currentConfig.renderer32x = find_renderer(renderer_names32x, "fastest");
832                 PicoIn.sndRate = 16000;
833                 PicoIn.opt |= POPT_PWM_IRQ_OPT;
834                 PicoIn.opt &= ~(POPT_EN_FM_FILTER | POPT_EN_FM | POPT_EN_MCD_CDDA);
835                 break;
836         }
837         return 1;
838 }
839
840 static menu_entry e_menu_profile[] =
841 {
842         mee_label     ("Select option profile and press OK:"),
843         mee_handler_id("accurate", MA_PROFILE_ACCURATE, mh_profile),
844         mee_handler_id("balanced", MA_PROFILE_BALANCED, mh_profile),
845         mee_handler_id("fast",     MA_PROFILE_FAST,     mh_profile),
846         mee_handler_id("breaking", MA_PROFILE_BREAKING, mh_profile),
847         mee_label     (""),
848         mee_label     ("Options changed by Option profiles:"),
849         mee_label     (""),
850         mee_label     ("Sound: Sound quality"),
851         mee_label     ("MD:    Renderer, FM audio, FM filter"),
852         mee_label     ("32X:   Renderer, PWM IRQ optimization"),
853         mee_label     ("CD:    CDDA audio"),
854         mee_end,
855 };
856
857 static int menu_loop_profile_options(int id, int keys)
858 {
859         static int sel = 0;
860
861         me_loop_d(e_menu_profile, &sel, menu_draw_prep, NULL);
862
863         return 0;
864 }
865
866 static void region_prevnext(int right)
867 {
868         // jp_ntsc=1, jp_pal=2, usa=4, eu=8
869         static const int rgn_orders[] = { 0x148, 0x184, 0x814, 0x418, 0x841, 0x481 };
870         int i;
871
872         if (right) {
873                 if (!PicoIn.regionOverride) {
874                         for (i = 0; i < 6; i++)
875                                 if (rgn_orders[i] == PicoIn.autoRgnOrder) break;
876                         if (i < 5) PicoIn.autoRgnOrder = rgn_orders[i+1];
877                         else PicoIn.regionOverride=1;
878                 }
879                 else
880                         PicoIn.regionOverride <<= 1;
881                 if (PicoIn.regionOverride > 8)
882                         PicoIn.regionOverride = 8;
883         } else {
884                 if (!PicoIn.regionOverride) {
885                         for (i = 0; i < 6; i++)
886                                 if (rgn_orders[i] == PicoIn.autoRgnOrder) break;
887                         if (i > 0) PicoIn.autoRgnOrder = rgn_orders[i-1];
888                 }
889                 else
890                         PicoIn.regionOverride >>= 1;
891         }
892 }
893
894 static int mh_opt_misc(int id, int keys)
895 {
896         switch (id) {
897         case MA_OPT_REGION:
898                 region_prevnext(keys & PBTN_RIGHT);
899                 break;
900         default:
901                 break;
902         }
903         return 0;
904 }
905
906 static int mh_restore_defaults(int id, int keys)
907 {
908         emu_set_defconfig();
909         menu_update_msg("defaults restored");
910         return 1;
911 }
912
913 static const char *mgn_opt_region(int id, int *offs)
914 {
915         static const char *names[] = { "Auto", "      Japan NTSC", "      Japan PAL", "      USA", "      Europe" };
916         static const char *names_short[] = { "", " JP", " JP", " US", " EU" };
917         int code = PicoIn.regionOverride;
918         int u, i = 0;
919
920         *offs = -6;
921         if (code) {
922                 code <<= 1;
923                 while ((code >>= 1)) i++;
924                 if (i > 4)
925                         return "unknown";
926                 return names[i];
927         } else {
928                 strcpy(static_buff, "Auto:");
929                 for (u = 0; u < 3; u++) {
930                         code = (PicoIn.autoRgnOrder >> u*4) & 0xf;
931                         for (i = 0; code; code >>= 1, i++)
932                                 ;
933                         strcat(static_buff, names_short[i]);
934                 }
935                 return static_buff;
936         }
937 }
938
939 static const char h_hotkeysvld[] = "Slot used for save/load by emulator hotkey";
940
941 static menu_entry e_menu_options[] =
942 {
943         mee_cust      ("Region",                   MA_OPT_REGION,        mh_opt_misc, mgn_opt_region),
944         mee_range     ("",                         MA_OPT_CPU_CLOCKS,    currentConfig.CPUclock, 20, 3200),
945         mee_range_h   ("Hotkey save/load slot",    MA_OPT_SAVE_SLOT,     state_slot, 0, 9, h_hotkeysvld),
946         mee_handler   ("Configure controls",       menu_loop_keyconfig),
947         mee_label     (""),
948         mee_handler   ("Option profiles",          menu_loop_profile_options),
949         mee_handler   ("Interface options",        menu_loop_ui_options),
950         mee_handler   ("Display options",          menu_loop_gfx_options),
951         mee_handler   ("Sound options",            menu_loop_snd_options),
952         mee_handler   ("MD/Genesis/Pico options",  menu_loop_md_options),
953         mee_handler   ("  Sega/Mega CD add-on",    menu_loop_cd_options),
954 #ifndef NO_32X
955         mee_handler   ("  32X add-on",             menu_loop_32x_options),
956 #endif
957 #ifndef NO_SMS
958         mee_handler   ("SG/SMS/GG options",        menu_loop_sms_options),
959 #endif
960         mee_handler   ("Advanced options",         menu_loop_adv_options),
961
962         mee_handler   ("Restore defaults",         mh_restore_defaults),
963         mee_end,
964 };
965
966 static int menu_loop_options(int id, int keys)
967 {
968         static int sel = 0;
969
970         me_loop_d(e_menu_options, &sel, menu_draw_prep, NULL);
971
972         return 0;
973 }
974
975 // ------------ debug menu ------------
976
977 #include <pico/debug.h>
978
979 extern void SekStepM68k(void);
980
981 static void mplayer_loop(void)
982 {
983         pemu_sound_start();
984
985         while (1)
986         {
987                 PDebugZ80Frame();
988                 if (in_menu_wait_any(NULL, 0) & PBTN_MA3)
989                         break;
990                 emu_sound_wait();
991         }
992
993         emu_sound_stop();
994 }
995
996 static void draw_text_debug(const char *str, int skip, int from)
997 {
998         const char *p;
999         int line;
1000
1001         p = str;
1002         while (skip-- > 0)
1003         {
1004                 while (*p && *p != '\n')
1005                         p++;
1006                 if (*p == 0 || p[1] == 0)
1007                         return;
1008                 p++;
1009         }
1010
1011         str = p;
1012         for (line = from; line < g_menuscreen_h / me_sfont_h; line++)
1013         {
1014                 smalltext_out16(1, line * me_sfont_h, str, PXMAKE(0xff, 0xff, 0xff));
1015                 while (*p && *p != '\n')
1016                         p++;
1017                 if (*p == 0)
1018                         break;
1019                 p++; str = p;
1020         }
1021 }
1022
1023 #ifdef __GNUC__
1024 #define COMPILER "gcc " __VERSION__
1025 #else
1026 #define COMPILER
1027 #endif
1028
1029 static void draw_frame_debug(void)
1030 {
1031         char layer_str[48] = "layers:                   ";
1032         struct PicoVideo *pv = &Pico.video;
1033
1034         if (!(pv->debug_p & PVD_KILL_B))    memcpy(layer_str +  8, "B", 1);
1035         if (!(pv->debug_p & PVD_KILL_A))    memcpy(layer_str + 10, "A", 1);
1036         if (!(pv->debug_p & PVD_KILL_S_LO)) memcpy(layer_str + 12, "spr_lo", 6);
1037         if (!(pv->debug_p & PVD_KILL_S_HI)) memcpy(layer_str + 19, "spr_hi", 6);
1038         if (!(pv->debug_p & PVD_KILL_32X))  memcpy(layer_str + 26, "32x", 4);
1039
1040         pemu_forced_frame(1, 0);
1041         make_bg(1, 1);
1042
1043         smalltext_out16(4, 1, "build: r" REVISION "  "__DATE__ " " __TIME__ " " COMPILER, PXMAKE(0xff, 0xff, 0xff));
1044         smalltext_out16(4, g_menuscreen_h - me_sfont_h, layer_str, PXMAKE(0xff, 0xff, 0xff));
1045 }
1046
1047 static void debug_menu_loop(void)
1048 {
1049         struct PicoVideo *pv = &Pico.video;
1050         int inp, mode = 0;
1051         int spr_offs = 0, dumped = 0;
1052         char *tmp;
1053
1054         while (1)
1055         {
1056                 menu_draw_begin(1, 0);
1057                 g_screen_ptr = g_menuscreen_ptr;
1058                 g_screen_width = g_menuscreen_w;
1059                 g_screen_height = g_menuscreen_h;
1060                 g_screen_ppitch = g_menuscreen_pp;
1061                 switch (mode)
1062                 {
1063                         case 0: tmp = PDebugMain();
1064                                 plat_debug_cat(tmp);
1065                                 draw_text_debug(tmp, 0, 0);
1066                                 if (dumped) {
1067                                         smalltext_out16(g_menuscreen_w - 6 * me_sfont_h,
1068                                                 g_menuscreen_h - me_mfont_h, "dumped", PXMAKE(0xff, 0xff, 0xff));
1069                                         dumped = 0;
1070                                 }
1071                                 break;
1072                         case 1: draw_frame_debug();
1073                                 break;
1074                         case 2: pemu_forced_frame(1, 0);
1075                                 make_bg(1, 1);
1076                                 PDebugShowSpriteStats((unsigned short *)g_menuscreen_ptr
1077                                         + (g_menuscreen_h/2 - 240/2) * g_menuscreen_pp
1078                                         + g_menuscreen_w/2 - 320/2, g_menuscreen_pp);
1079                                 break;
1080                         case 3: menuscreen_memset_lines(g_menuscreen_ptr, 0, g_menuscreen_h);
1081                                 PDebugShowPalette(g_menuscreen_ptr, g_menuscreen_pp);
1082                                 PDebugShowSprite((unsigned short *)g_menuscreen_ptr
1083                                         + g_menuscreen_pp * 120 + g_menuscreen_w / 2 + 16,
1084                                         g_menuscreen_pp, spr_offs);
1085                                 draw_text_debug(PDebugSpriteList(), spr_offs, 6);
1086                                 break;
1087                         case 4: tmp = PDebug32x();
1088                                 draw_text_debug(tmp, 0, 0);
1089                                 break;
1090                 }
1091                 menu_draw_end();
1092
1093                 inp = in_menu_wait(PBTN_MOK|PBTN_MBACK|PBTN_MA2|PBTN_MA3|PBTN_L|PBTN_R |
1094                                         PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT, NULL, 70);
1095                 if (inp & PBTN_MBACK) return;
1096                 if (inp & PBTN_L) { mode--; if (mode < 0) mode = 4; }
1097                 if (inp & PBTN_R) { mode++; if (mode > 4) mode = 0; }
1098                 switch (mode)
1099                 {
1100                         case 0:
1101                                 if (inp & PBTN_MOK)
1102                                         PDebugCPUStep();
1103                                 if (inp & PBTN_MA3) {
1104                                         while (inp & PBTN_MA3)
1105                                                 inp = in_menu_wait_any(NULL, -1);
1106                                         mplayer_loop();
1107                                 }
1108                                 if ((inp & (PBTN_MA2|PBTN_LEFT)) == (PBTN_MA2|PBTN_LEFT)) {
1109                                         mkdir("dumps", 0777);
1110                                         PDebugDumpMem();
1111                                         while (inp & PBTN_MA2) inp = in_menu_wait_any(NULL, -1);
1112                                         dumped = 1;
1113                                 }
1114                                 break;
1115                         case 1:
1116                                 if (inp & PBTN_LEFT)  pv->debug_p ^= PVD_KILL_B;
1117                                 if (inp & PBTN_RIGHT) pv->debug_p ^= PVD_KILL_A;
1118                                 if (inp & PBTN_DOWN)  pv->debug_p ^= PVD_KILL_S_LO;
1119                                 if (inp & PBTN_UP)    pv->debug_p ^= PVD_KILL_S_HI;
1120                                 if (inp & PBTN_MA2)   pv->debug_p ^= PVD_KILL_32X;
1121                                 if (inp & PBTN_MOK) {
1122                                         PicoIn.sndOut = NULL; // just in case
1123                                         PicoIn.skipFrame = 1;
1124                                         PicoFrame();
1125                                         PicoIn.skipFrame = 0;
1126                                         while (inp & PBTN_MOK) inp = in_menu_wait_any(NULL, -1);
1127                                 }
1128                                 break;
1129                         case 3:
1130                                 if (inp & PBTN_DOWN)  spr_offs++;
1131                                 if (inp & PBTN_UP)    spr_offs--;
1132                                 if (spr_offs < 0) spr_offs = 0;
1133                                 break;
1134                 }
1135         }
1136 }
1137
1138 // ------------ main menu ------------
1139
1140 static void draw_frame_credits(void)
1141 {
1142         smalltext_out16(4, 1, "build: " __DATE__ " " __TIME__, PXMAKE(0xe0, 0xff, 0xe0));
1143 }
1144
1145 static const char credits[] =
1146         "PicoDrive v" VERSION "\n"
1147         "(c) notaz, 2006-2013; irixxxx, 2018-2024\n\n"
1148         "Credits:\n"
1149         "fDave: initial code\n"
1150 #ifdef EMU_C68K
1151         "      Cyclone 68000 core\n"
1152 #else
1153         "Stef, Chui: FAME/C 68k core\n"
1154 #endif
1155 #ifdef _USE_DRZ80
1156         "Reesy & FluBBa: DrZ80 core\n"
1157 #else
1158         "Stef, NJ: CZ80 core\n"
1159 #endif
1160         "MAME devs: SH2, YM2612 and SN76496 cores\n"
1161         "Eke, Stef: some Sega CD code\n"
1162         "Inder, ketchupgun: graphics\n"
1163 #ifdef __GP2X__
1164         "Squidge: mmuhack\n"
1165         "Dzz: ARM940 sample\n"
1166 #endif
1167         "\n"
1168         "special thanks (for docs, ideas):\n"
1169         " Charles MacDonald, Haze,\n"
1170         " Stephane Dallongeville,\n"
1171         " Lordus, Exophase, Rokas,\n"
1172         " Eke, Nemesis, Tasco Deluxe";
1173
1174 static void menu_main_draw_status(void)
1175 {
1176         static time_t last_bat_read = 0;
1177         static int last_bat_val = -1;
1178         unsigned short *bp = g_menuscreen_ptr;
1179         int bat_h = me_mfont_h * 2 / 3;
1180         int i, u, w, wfill, batt_val;
1181         struct tm *tmp;
1182         time_t ltime;
1183         char time_s[16];
1184
1185         if (!(currentConfig.EmuOpt & EOPT_SHOW_RTC))
1186                 return;
1187
1188         ltime = time(NULL);
1189         tmp = gmtime(&ltime);
1190         strftime(time_s, sizeof(time_s), "%H:%M", tmp);
1191
1192         text_out16(g_menuscreen_w - me_mfont_w * 6, me_mfont_h + 2, time_s);
1193
1194         if (ltime - last_bat_read > 10) {
1195                 last_bat_read = ltime;
1196                 last_bat_val = batt_val = plat_target_bat_capacity_get();
1197         }
1198         else
1199                 batt_val = last_bat_val;
1200
1201         if (batt_val < 0 || batt_val > 100)
1202                 return;
1203
1204         /* battery info */
1205         bp += (me_mfont_h * 2 + 2) * g_menuscreen_pp + g_menuscreen_w - me_mfont_w * 3 - 3;
1206         for (i = 0; i < me_mfont_w * 2; i++)
1207                 bp[i] = menu_text_color;
1208         for (i = 0; i < me_mfont_w * 2; i++)
1209                 bp[i + g_menuscreen_pp * bat_h] = menu_text_color;
1210         for (i = 0; i <= bat_h; i++)
1211                 bp[i * g_menuscreen_pp] =
1212                 bp[i * g_menuscreen_pp + me_mfont_w * 2] = menu_text_color;
1213         for (i = 2; i < bat_h - 1; i++)
1214                 bp[i * g_menuscreen_pp - 1] =
1215                 bp[i * g_menuscreen_pp - 2] = menu_text_color;
1216
1217         w = me_mfont_w * 2 - 1;
1218         wfill = batt_val * w / 100;
1219         for (u = 1; u < bat_h; u++)
1220                 for (i = 0; i < wfill; i++)
1221                         bp[(w - i) + g_menuscreen_pp * u] = menu_text_color;
1222 }
1223
1224 static menu_entry e_menu_main[];
1225
1226 static int main_menu_handler(int id, int keys)
1227 {
1228         const char *ret_name;
1229
1230         switch (id)
1231         {
1232         case MA_MAIN_RESUME_GAME:
1233                 if (PicoGameLoaded)
1234                         return 1;
1235                 break;
1236         case MA_MAIN_SAVE_STATE:
1237                 if (PicoGameLoaded)
1238                         return menu_loop_savestate(0);
1239                 break;
1240         case MA_MAIN_LOAD_STATE:
1241                 if (PicoGameLoaded)
1242                         return menu_loop_savestate(1);
1243                 break;
1244         case MA_MAIN_RESET_GAME:
1245                 if (PicoGameLoaded) {
1246                         emu_reset_game();
1247                         return 1;
1248                 }
1249                 break;
1250         case MA_MAIN_LOAD_ROM:
1251                 rom_fname_reload = NULL;
1252                 ret_name = menu_loop_romsel_d(rom_fname_loaded,
1253                         sizeof(rom_fname_loaded), rom_exts, NULL, menu_draw_prep);
1254                 if (ret_name != NULL) {
1255                         lprintf("selected file: %s\n", ret_name);
1256                         rom_fname_reload = ret_name;
1257                         engineState = PGS_ReloadRom;
1258                         return 1;
1259                 }
1260                 break;
1261         case MA_MAIN_CHANGE_CD:
1262                 if (PicoIn.AHW & PAHW_MCD) {
1263                         // if cd is loaded, cdd_unload() triggers eject and
1264                         // returns 1, else we'll select and load new CD here
1265                         if (!cdd_unload())
1266                                 menu_loop_tray();
1267                         return 1;
1268                 }
1269                 break;
1270         case MA_MAIN_CREDITS:
1271                 draw_menu_message(credits, draw_frame_credits);
1272                 in_menu_wait(PBTN_MOK|PBTN_MBACK, NULL, 70);
1273                 break;
1274         case MA_MAIN_EXIT:
1275                 engineState = PGS_Quit;
1276                 return 1;
1277         case MA_MAIN_PATCHES:
1278                 if (PicoGameLoaded && PicoPatches) {
1279                         menu_loop_patches();
1280                         PicoPatchApply();
1281                         menu_update_msg("Patches applied");
1282                 }
1283                 break;
1284         default:
1285                 lprintf("%s: something unknown selected\n", __FUNCTION__);
1286                 break;
1287         }
1288
1289         return 0;
1290 }
1291
1292 static const char *mgn_picopage(int id, int *offs)
1293 {
1294         strcpy(static_buff, "   ");
1295         sprintf(static_buff, "%i", PicoPicohw.page);
1296         return static_buff;
1297 }
1298
1299 static int mh_picopage(int id, int keys)
1300 {
1301         if (keys & (PBTN_LEFT|PBTN_RIGHT)) { // multi choice
1302                 PicoPicohw.page += (keys & PBTN_LEFT) ? -1 : 1;
1303                 if (PicoPicohw.page < 0) PicoPicohw.page = 6;
1304                 else if (PicoPicohw.page > 6) PicoPicohw.page = 0;
1305                 return 0;
1306         }
1307         return 1;
1308 }
1309
1310 static const char *mgn_saveloadcfg(int id, int *offs)
1311 {
1312         strcpy(static_buff, "   ");
1313         if (config_slot != 0)
1314                 sprintf(static_buff, "[%i]", config_slot);
1315         return static_buff;
1316 }
1317
1318 static int mh_saveloadcfg(int id, int keys)
1319 {
1320         int ret;
1321
1322         if (keys & (PBTN_LEFT|PBTN_RIGHT)) { // multi choice
1323                 config_slot += (keys & PBTN_LEFT) ? -1 : 1;
1324                 if (config_slot < 0) config_slot = 9;
1325                 else if (config_slot > 9) config_slot = 0;
1326                 me_enable(e_menu_main, MA_OPT_LOADCFG, PicoGameLoaded && config_slot != config_slot_current);
1327                 return 0;
1328         }
1329
1330         switch (id) {
1331         case MA_OPT_SAVECFG:
1332         case MA_OPT_SAVECFG_GAME:
1333                 if (emu_write_config(id == MA_OPT_SAVECFG_GAME ? 1 : 0))
1334                         menu_update_msg("config saved");
1335                 else
1336                         menu_update_msg("failed to write config");
1337                 break;
1338         case MA_OPT_LOADCFG:
1339                 ret = emu_read_config(rom_fname_loaded, 1);
1340                 if (!ret) ret = emu_read_config(NULL, 1);
1341                 if (ret)  menu_update_msg("config loaded");
1342                 else      menu_update_msg("failed to load config");
1343                 break;
1344         default:
1345                 return 0;
1346         }
1347
1348         return 1;
1349 }
1350
1351 static const char h_saveload[] = "Game options are overloading global options";
1352
1353 static menu_entry e_menu_main[] =
1354 {
1355         mee_label     ("PicoDrive " VERSION),
1356         mee_label     (""),
1357         mee_label     (""),
1358         mee_handler_id("Resume game",        MA_MAIN_RESUME_GAME, main_menu_handler),
1359         mee_handler_id("Save state",         MA_MAIN_SAVE_STATE,  main_menu_handler),
1360         mee_handler_id("Load state",         MA_MAIN_LOAD_STATE,  main_menu_handler),
1361         mee_handler_id("Reset game",         MA_MAIN_RESET_GAME,  main_menu_handler),
1362         mee_handler_id("Change CD",          MA_MAIN_CHANGE_CD,   main_menu_handler),
1363         mee_cust_s_h  ("Storyware page",     MA_MAIN_PICO_PAGE, 0,mh_picopage, mgn_picopage, NULL),
1364         mee_handler_id("Patches / GameGenie",MA_MAIN_PATCHES,     main_menu_handler),
1365         mee_handler_id("Load new game",      MA_MAIN_LOAD_ROM,    main_menu_handler),
1366         mee_handler   ("Change options",                          menu_loop_options),
1367         mee_cust_s_h  ("Save global options",MA_OPT_SAVECFG, 0,   mh_saveloadcfg, mgn_saveloadcfg, NULL),
1368         mee_cust_s_h  ("Save game options",  MA_OPT_SAVECFG_GAME, 0, mh_saveloadcfg, mgn_saveloadcfg, h_saveload),
1369         mee_cust_s_h  ("Load game options",  MA_OPT_LOADCFG, 0,   mh_saveloadcfg, mgn_saveloadcfg, h_saveload),
1370         mee_handler_id("Credits",            MA_MAIN_CREDITS,     main_menu_handler),
1371         mee_handler_id("Exit",               MA_MAIN_EXIT,        main_menu_handler),
1372         mee_end,
1373 };
1374
1375 void menu_loop(void)
1376 {
1377         static int sel = 0;
1378
1379         me_enable(e_menu_main, MA_MAIN_RESUME_GAME, PicoGameLoaded);
1380         me_enable(e_menu_main, MA_MAIN_SAVE_STATE,  PicoGameLoaded);
1381         me_enable(e_menu_main, MA_MAIN_LOAD_STATE,  PicoGameLoaded);
1382         me_enable(e_menu_main, MA_MAIN_RESET_GAME,  PicoGameLoaded);
1383         me_enable(e_menu_main, MA_MAIN_CHANGE_CD,   PicoIn.AHW & PAHW_MCD);
1384         me_enable(e_menu_main, MA_MAIN_PICO_PAGE,   PicoIn.AHW & PAHW_PICO);
1385         me_enable(e_menu_main, MA_MAIN_PATCHES,     PicoPatches != NULL);
1386         me_enable(e_menu_main, MA_OPT_SAVECFG_GAME, PicoGameLoaded);
1387         me_enable(e_menu_main, MA_OPT_LOADCFG,      PicoGameLoaded && config_slot != config_slot_current);
1388
1389         menu_enter(PicoGameLoaded);
1390         in_set_config_int(0, IN_CFG_BLOCKING, 1);
1391         me_loop_d(e_menu_main, &sel, menu_draw_prep, menu_main_draw_status);
1392
1393         if (PicoGameLoaded) {
1394                 if (engineState == PGS_Menu)
1395                         engineState = PGS_Running;
1396                 /* wait until menu, ok, back is released */
1397                 while (in_menu_wait_any(NULL, 50) & (PBTN_MENU|PBTN_MOK|PBTN_MBACK))
1398                         ;
1399         }
1400
1401         in_set_config_int(0, IN_CFG_BLOCKING, 0);
1402         plat_video_menu_leave();
1403 }
1404
1405 // --------- CD tray close menu ----------
1406
1407 static int mh_tray_load_cd(int id, int keys)
1408 {
1409         const char *ret_name;
1410
1411         rom_fname_reload = NULL;
1412         ret_name = menu_loop_romsel_d(rom_fname_loaded,
1413                         sizeof(rom_fname_loaded), rom_exts, NULL, menu_draw_prep);
1414         if (ret_name == NULL)
1415                 return 0;
1416
1417         rom_fname_reload = ret_name;
1418         engineState = PGS_RestartRun;
1419         return emu_swap_cd(ret_name);
1420 }
1421
1422 static int mh_tray_nothing(int id, int keys)
1423 {
1424         return 1;
1425 }
1426
1427 static menu_entry e_menu_tray[] =
1428 {
1429         mee_label  ("The CD tray has opened."),
1430         mee_label  (""),
1431         mee_label  (""),
1432         mee_handler("Load CD image",  mh_tray_load_cd),
1433         mee_handler("Insert nothing", mh_tray_nothing),
1434         mee_end,
1435 };
1436
1437 int menu_loop_tray(void)
1438 {
1439         int ret = 1, sel = 0;
1440
1441         menu_enter(PicoGameLoaded);
1442
1443         in_set_config_int(0, IN_CFG_BLOCKING, 1);
1444         me_loop_d(e_menu_tray, &sel, menu_draw_prep, NULL);
1445
1446         if (engineState != PGS_RestartRun) {
1447                 engineState = PGS_RestartRun;
1448                 ret = 0; /* no CD inserted */
1449         }
1450
1451         while (in_menu_wait_any(NULL, 50) & (PBTN_MENU|PBTN_MOK|PBTN_MBACK))
1452                 ;
1453         in_set_config_int(0, IN_CFG_BLOCKING, 0);
1454         plat_video_menu_leave();
1455
1456         return ret;
1457 }
1458
1459 void menu_update_msg(const char *msg)
1460 {
1461         strncpy(menu_error_msg, msg, sizeof(menu_error_msg));
1462         menu_error_msg[sizeof(menu_error_msg) - 1] = 0;
1463
1464         menu_error_time = plat_get_ticks_ms();
1465         lprintf("msg: %s\n", menu_error_msg);
1466 }
1467
1468 // ------------ util ------------
1469
1470 /* hidden options for config engine only */
1471 static menu_entry e_menu_hidden[] =
1472 {
1473         mee_onoff("Accurate sprites",         MA_OPT_ACC_SPRITES,    PicoIn.opt, POPT_ACC_SPRITES),
1474 //      mee_range("Save slot",                MA_OPT_SAVE_SLOT,      state_slot, 0, 9),
1475
1476 //      mee_enum ("Confirm savestate",        MA_OPT_CONFIRM_STATES, currentConfig.confirm_save, men_confirm_save),
1477         mee_onoff("autoload savestates",      MA_OPT_AUTOLOAD_SAVE,  g_autostateld_opt, 1),
1478         mee_onoff("SDL fullscreen mode",      MA_OPT_VOUT_FULL,      plat_target.vout_fullscreen, 1),
1479         mee_onoff("Emulate Z80",              MA_OPT2_ENABLE_Z80,    PicoIn.opt, POPT_EN_Z80),
1480         mee_onoff("Emulate YM2612 (FM)",      MA_OPT2_ENABLE_YM2612, PicoIn.opt, POPT_EN_FM),
1481         mee_onoff("Disable YM2612 SSG-EG",    MA_OPT2_DISABLE_YM_SSG,PicoIn.opt, POPT_DIS_FM_SSGEG),
1482         mee_onoff("Enable YM2612 DAC noise",  MA_OPT2_ENABLE_YM_DAC, PicoIn.opt, POPT_EN_FM_DAC),
1483         mee_onoff("Emulate SN76496 (PSG)",    MA_OPT2_ENABLE_SN76496,PicoIn.opt, POPT_EN_PSG),
1484         mee_onoff("Scale/Rot. fx",            MA_CDOPT_SCALEROT_CHIP,PicoIn.opt, POPT_EN_MCD_GFX),
1485         mee_onoff("32X enabled",              MA_32XOPT_ENABLE_32X,  PicoIn.opt, POPT_EN_32X),
1486         mee_end,
1487 };
1488
1489 static menu_entry *e_menu_table[] =
1490 {
1491         e_menu_options,
1492         e_menu_ui_options,
1493         e_menu_snd_options,
1494         e_menu_gfx_options,
1495         e_menu_adv_options,
1496         e_menu_md_options,
1497         e_menu_cd_options,
1498 #ifndef NO_32X
1499         e_menu_32x_options,
1500 #endif
1501 #ifndef NO_SMS
1502         e_menu_sms_options,
1503 #endif
1504         e_menu_keyconfig,
1505         e_menu_hidden,
1506 };
1507
1508 static menu_entry *me_list_table = NULL;
1509 static menu_entry *me_list_i = NULL;
1510
1511 menu_entry *me_list_get_first(void)
1512 {
1513         me_list_table = me_list_i = e_menu_table[0];
1514         return me_list_i;
1515 }
1516
1517 menu_entry *me_list_get_next(void)
1518 {
1519         int i;
1520
1521         me_list_i++;
1522         if (me_list_i->name != NULL)
1523                 return me_list_i;
1524
1525         for (i = 0; i < array_size(e_menu_table); i++)
1526                 if (me_list_table == e_menu_table[i])
1527                         break;
1528
1529         if (i + 1 < array_size(e_menu_table))
1530                 me_list_table = me_list_i = e_menu_table[i + 1];
1531         else
1532                 me_list_table = me_list_i = NULL;
1533
1534         return me_list_i;
1535 }
1536
1537 void menu_init(void)
1538 {
1539         int i;
1540
1541         menu_init_base();
1542
1543         i = 0;
1544 #if defined(_SVP_DRC) || defined(DRC_SH2)
1545         i = 1;
1546 #endif
1547         me_enable(e_menu_adv_options, MA_OPT2_DYNARECS, i);
1548
1549         i = me_id2offset(e_menu_gfx_options, MA_OPT_VOUT_MODE);
1550         e_menu_gfx_options[i].data = plat_target.vout_methods;
1551         me_enable(e_menu_gfx_options, MA_OPT_VOUT_MODE,
1552                 plat_target.vout_methods != NULL);
1553
1554         i = me_id2offset(e_menu_gfx_options, MA_OPT3_FILTERING);
1555         e_menu_gfx_options[i].data = plat_target.hwfilters;
1556         me_enable(e_menu_gfx_options, MA_OPT3_FILTERING,
1557                 plat_target.hwfilters != NULL);
1558
1559         me_enable(e_menu_gfx_options, MA_OPT2_GAMMA,
1560                 plat_target.gamma_set != NULL);
1561
1562         i = me_id2offset(e_menu_options, MA_OPT_CPU_CLOCKS);
1563         e_menu_options[i].enabled = 0;
1564         if (plat_target.cpu_clock_set != NULL) {
1565                 e_menu_options[i].name = "CPU clock";
1566                 e_menu_options[i].enabled = 1;
1567         }
1568 }