FAMEC idle loops, PSP port sync, minor adjustments
[libpicofe.git] / psp / menu.c
1 // (c) Copyright 2007 notaz, All rights reserved.
2 // Free for non-commercial use.
3
4 // For commercial use, separate licencing terms must be obtained.
5
6 // don't like to use loads of #ifdefs, so duplicating GP2X code
7 // horribly instead
8
9 #include <string.h>
10 #include <stdlib.h>
11 #include <wchar.h>
12 #include <unistd.h>
13 #include <sys/syslimits.h> // PATH_MAX
14
15 #include <pspdisplay.h>
16 #include <pspgu.h>
17 #include <pspiofilemgr.h>
18 #include <psputils.h>
19
20 #include "psp.h"
21 #include "emu.h"
22 #include "menu.h"
23 #include "mp3.h"
24 #include "../common/menu.h"
25 #include "../common/emu.h"
26 #include "../common/readpng.h"
27 #include "../common/lprintf.h"
28 #include "version.h"
29
30 #include <Pico/PicoInt.h>
31 #include <Pico/Patch.h>
32 #include <zlib/zlib.h>
33
34
35 #define pspKeyUnkn "???"
36 const char * const keyNames[] = {
37         "SELECT",   pspKeyUnkn, pspKeyUnkn, "START",    "UP",       "RIGHT",     "DOWN",     "LEFT",
38         "L",        "R",        pspKeyUnkn, pspKeyUnkn, "TRIANGLE", "CIRCLE",    "X",        "SQUARE",
39         "HOME",     "HOLD",     "WLAN_UP",  "REMOTE",   "VOLUP",    "VOLDOWN",   "SCREEN",   "NOTE",
40         pspKeyUnkn, pspKeyUnkn, pspKeyUnkn, pspKeyUnkn, "NUB UP",   "NUB RIGHT", "NUB DOWN", "NUB LEFT" // fake
41 };
42
43 static unsigned short bg_buffer[480*272] __attribute__((aligned(16)));
44 #define menu_screen psp_screen
45
46 static void menu_darken_bg(void *dst, const void *src, int pixels, int darker);
47 static void menu_prepare_bg(int use_game_bg, int use_fg);
48
49
50 static unsigned int inp_prev = 0;
51
52 static unsigned long wait_for_input(unsigned int interesting, int is_key_config)
53 {
54         unsigned int ret;
55         static int repeats = 0, wait = 20;
56         int release = 0, count, i;
57
58         if (!is_key_config)
59                 interesting |= (interesting & 0xf0) << 24; // also use analog
60
61         if      (repeats == 2) wait = 3;
62         else if (repeats == 4) wait = 2;
63         else if (repeats == 6) wait = 1;
64
65         for (i = 0; i < wait && inp_prev == psp_pad_read(1); i++) {
66                 if (i == 0) repeats++;
67                 psp_msleep(30);
68         }
69
70         for (count = 0; !((ret = psp_pad_read(1)) & interesting) && count < 100; count++) {
71                 psp_msleep(50);
72                 release = 1;
73         }
74
75         if (release || ret != inp_prev) {
76                 repeats = 0;
77                 wait = 20;
78         }
79         inp_prev = ret;
80
81         if (!is_key_config)
82                 ret |= (ret & 0xf0000000) >> 24; // use analog as d-pad
83         if (wait > 6 && (ret&(BTN_UP|BTN_LEFT|BTN_DOWN|BTN_RIGHT|BTN_L|BTN_R)))
84                 wait = 6;
85
86         // we don't need diagonals in menus
87         if ((ret&BTN_UP)   && (ret&BTN_LEFT))  ret &= ~BTN_LEFT;
88         if ((ret&BTN_UP)   && (ret&BTN_RIGHT)) ret &= ~BTN_RIGHT;
89         if ((ret&BTN_DOWN) && (ret&BTN_LEFT))  ret &= ~BTN_LEFT;
90         if ((ret&BTN_DOWN) && (ret&BTN_RIGHT)) ret &= ~BTN_RIGHT;
91
92         return ret;
93 }
94
95 static void menu_draw_begin(void)
96 {
97         // short *src = (short *)bg_buffer, *dst = (short *)menu_screen;
98         // int i;
99
100         // for (i = 272; i >= 0; i--, dst += 512, src += 480)
101         //      memcpy32((int *)dst, (int *)src, 480*2/4);
102
103         sceGuSync(0,0); // sync with prev
104         sceGuStart(GU_DIRECT, guCmdList);
105         sceGuCopyImage(GU_PSM_5650, 0, 0, 480, 272, 480, bg_buffer, 0, 0, 512, menu_screen);
106         sceGuFinish();
107         sceGuSync(0,0);
108 }
109
110
111 static void menu_draw_end(void)
112 {
113         psp_video_flip(1);
114 }
115
116
117 // --------- loading ROM screen ----------
118
119 static int lcdr_line = 0;
120
121 static void load_progress_cb(int percent)
122 {
123         int ln, len = percent * 480 / 100;
124         unsigned short *dst;
125
126         //sceDisplayWaitVblankStart();
127
128         dst = (unsigned short *)menu_screen + 512*10*lcdr_line;
129
130         if (len > 480) len = 480;
131         for (ln = 8; ln > 0; ln--, dst += 512)
132                 memset(dst, 0xff, len*2);
133 }
134
135 static void cdload_progress_cb(int percent)
136 {
137         int ln, len = percent * 480 / 100;
138         unsigned short *dst;
139
140         if (lcdr_line <= 2) {
141                 lcdr_line++;
142                 smalltext_out16(1, lcdr_line++ * 10, "Processing CD image / MP3s", 0xffff);
143                 smalltext_out16_lim(1, lcdr_line++ * 10, romFileName, 0xffff, 80);
144         }
145
146         dst = (unsigned short *)menu_screen + 512*10*lcdr_line;
147
148         if (len > 480) len = 480;
149         for (ln = 8; ln > 0; ln--, dst += 512)
150                 memset(dst, 0xff, len*2);
151 }
152
153 void menu_romload_prepare(const char *rom_name)
154 {
155         const char *p = rom_name + strlen(rom_name);
156         while (p > rom_name && *p != '/') p--;
157
158         psp_video_switch_to_single();
159         if (rom_loaded) menu_draw_begin();
160         else memset32_uncached(psp_screen, 0, 512*272*2/4);
161
162         smalltext_out16(1, 1, "Loading", 0xffff);
163         smalltext_out16_lim(1, 10, p, 0xffff, 80);
164         PicoCartLoadProgressCB = load_progress_cb;
165         PicoCDLoadProgressCB = cdload_progress_cb;
166         lcdr_line = 2;
167 }
168
169 void menu_romload_end(void)
170 {
171         PicoCartLoadProgressCB = PicoCDLoadProgressCB = NULL;
172         smalltext_out16(1, ++lcdr_line*10, "Starting emulation...", 0xffff);
173 }
174
175 // -------------- ROM selector --------------
176
177 // SceIoDirent
178 #define DT_DIR FIO_SO_IFDIR
179 #define DT_REG FIO_SO_IFREG
180
181 struct my_dirent
182 {
183         unsigned char d_type;
184         char d_name[255];
185 };
186
187 // bbbb bggg gggr rrrr
188 static unsigned short file2color(const char *fname)
189 {
190         const char *ext = fname + strlen(fname) - 3;
191         static const char *rom_exts[]   = { "zip", "bin", "smd", "gen", "iso", "cso", "cue" };
192         static const char *other_exts[] = { "gmv", "pat" };
193         int i;
194
195         if (ext < fname) ext = fname;
196         for (i = 0; i < sizeof(rom_exts)/sizeof(rom_exts[0]); i++)
197                 if (strcasecmp(ext, rom_exts[i]) == 0) return 0xfdf7;
198         for (i = 0; i < sizeof(other_exts)/sizeof(other_exts[0]); i++)
199                 if (strcasecmp(ext, other_exts[i]) == 0) return 0xaff5;
200         return 0xffff;
201 }
202
203 static void draw_dirlist(char *curdir, struct my_dirent **namelist, int n, int sel)
204 {
205         int start, i, pos;
206
207         start = 13 - sel;
208         n--; // exclude current dir (".")
209
210         menu_draw_begin();
211
212         if (!rom_loaded) {
213 //              menu_darken_bg(menu_screen, menu_screen, 321*240, 0);
214         }
215
216         menu_darken_bg((char *)menu_screen + 512*129*2, (char *)menu_screen + 512*129*2, 512*10, 0);
217
218         if (start - 2 >= 0)
219                 smalltext_out16_lim(14, (start - 2)*10, curdir, 0xffff, 53-2);
220         for (i = 0; i < n; i++) {
221                 pos = start + i;
222                 if (pos < 0)  continue;
223                 if (pos > 26) break;
224                 if (namelist[i+1]->d_type & DT_DIR) {
225                         smalltext_out16_lim(14,   pos*10, "/", 0xd7ff, 1);
226                         smalltext_out16_lim(14+6, pos*10, namelist[i+1]->d_name, 0xd7ff, 80-3);
227                 } else {
228                         unsigned short color = file2color(namelist[i+1]->d_name);
229                         smalltext_out16_lim(14,   pos*10, namelist[i+1]->d_name, color, 80-2);
230                 }
231         }
232         text_out16(5, 130, ">");
233         menu_draw_end();
234 }
235
236 static int scandir_cmp(const void *p1, const void *p2)
237 {
238         struct my_dirent **d1 = (struct my_dirent **)p1, **d2 = (struct my_dirent **)p2;
239         if ((*d1)->d_type == (*d2)->d_type) return strcasecmp((*d1)->d_name, (*d2)->d_name);
240         if ((*d1)->d_type & DT_DIR) return -1; // put before
241         if ((*d2)->d_type & DT_DIR) return  1;
242         return strcasecmp((*d1)->d_name, (*d2)->d_name);
243 }
244
245 static char *filter_exts[] = {
246         ".mp3", ".srm", ".brm", "s.gz", ".mds", "bcfg", ".txt", ".htm", "html",
247         ".jpg", ".pbp"
248 };
249
250 static int scandir_filter(const struct my_dirent *ent)
251 {
252         const char *p;
253         int i;
254
255         if (ent == NULL || ent->d_name == NULL) return 0;
256         if (strlen(ent->d_name) < 5) return 1;
257
258         p = ent->d_name + strlen(ent->d_name) - 4;
259
260         for (i = 0; i < sizeof(filter_exts)/sizeof(filter_exts[0]); i++)
261         {
262                 if (strcasecmp(p, filter_exts[i]) == 0) return 0;
263         }
264
265         return 1;
266 }
267
268 static int my_scandir(const char *dir, struct my_dirent ***namelist_out,
269                 int(*filter)(const struct my_dirent *),
270                 int(*compar)(const void *, const void *))
271 {
272         int ret = -1, dir_uid = -1, name_alloc = 4, name_count = 0;
273         struct my_dirent **namelist = NULL, *ent;
274         SceIoDirent sce_ent;
275
276         namelist = malloc(sizeof(*namelist) * name_alloc);
277         if (namelist == NULL) { lprintf("%s:%i: OOM\n", __FILE__, __LINE__); goto fail; }
278
279         // try to read first..
280         dir_uid = sceIoDopen(dir);
281         if (dir_uid >= 0)
282         {
283                 /* it is very important to clear SceIoDirent to be passed to sceIoDread(), */
284                 /* or else it may crash, probably misinterpreting something in it. */
285                 memset(&sce_ent, 0, sizeof(sce_ent));
286                 ret = sceIoDread(dir_uid, &sce_ent);
287                 if (ret < 0)
288                 {
289                         lprintf("sceIoDread(\"%s\") failed with %i\n", dir, ret);
290                         goto fail;
291                 }
292         }
293         else
294                 lprintf("sceIoDopen(\"%s\") failed with %i\n", dir, dir_uid);
295
296         while (ret > 0)
297         {
298                 ent = malloc(sizeof(*ent));
299                 if (ent == NULL) { lprintf("%s:%i: OOM\n", __FILE__, __LINE__); goto fail; }
300                 ent->d_type = sce_ent.d_stat.st_attr;
301                 strncpy(ent->d_name, sce_ent.d_name, sizeof(ent->d_name));
302                 ent->d_name[sizeof(ent->d_name)-1] = 0;
303                 if (filter == NULL || filter(ent))
304                      namelist[name_count++] = ent;
305                 else free(ent);
306
307                 if (name_count >= name_alloc)
308                 {
309                         void *tmp;
310                         name_alloc *= 2;
311                         tmp = realloc(namelist, sizeof(*namelist) * name_alloc);
312                         if (tmp == NULL) { lprintf("%s:%i: OOM\n", __FILE__, __LINE__); goto fail; }
313                         namelist = tmp;
314                 }
315
316                 memset(&sce_ent, 0, sizeof(sce_ent));
317                 ret = sceIoDread(dir_uid, &sce_ent);
318         }
319
320         // sort
321         if (compar != NULL && name_count > 3) qsort(&namelist[2], name_count - 2, sizeof(namelist[0]), compar);
322
323         // all done.
324         ret = name_count;
325         *namelist_out = namelist;
326         goto end;
327
328 fail:
329         if (namelist != NULL)
330         {
331                 while (name_count--)
332                         free(namelist[name_count]);
333                 free(namelist);
334         }
335 end:
336         if (dir_uid >= 0) sceIoDclose(dir_uid);
337         return ret;
338 }
339
340
341 static SceIoStat cpstat;
342
343 static char *romsel_loop(char *curr_path)
344 {
345         struct my_dirent **namelist;
346         int n, iret, sel = 0;
347         unsigned long inp = 0;
348         char *ret = NULL, *fname = NULL;
349
350         // is this a dir or a full path?
351         memset(&cpstat, 0, sizeof(cpstat));
352         iret = sceIoGetstat(curr_path, &cpstat);
353         if (iret >= 0 && (cpstat.st_attr & FIO_SO_IFREG)) { // file
354                 char *p;
355                 for (p = curr_path + strlen(curr_path) - 1; p > curr_path && *p != '/'; p--);
356                 if (p > curr_path) {
357                         *p = 0;
358                         fname = p+1;
359                 }
360                 else strcpy(curr_path, "ms0:/");
361         }
362         else if (iret >= 0 && (cpstat.st_attr & FIO_SO_IFDIR)); // dir
363         else strcpy(curr_path, "ms0:/"); // something else
364
365         n = my_scandir(curr_path, &namelist, scandir_filter, scandir_cmp);
366         if (n < 0) {
367                 // try root..
368                 n = my_scandir("ms0:/", &namelist, scandir_filter, scandir_cmp);
369                 if (n < 0) {
370                         // oops, we failed
371                         lprintf("scandir failed, dir: "); lprintf(curr_path); lprintf("\n");
372                         return NULL;
373                 }
374         }
375
376         // try to find sel
377         if (fname != NULL) {
378                 int i;
379                 for (i = 1; i < n; i++) {
380                         if (strcmp(namelist[i]->d_name, fname) == 0) {
381                                 sel = i - 1;
382                                 break;
383                         }
384                 }
385         }
386
387         for (;;)
388         {
389                 draw_dirlist(curr_path, namelist, n, sel);
390                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_L|BTN_R|BTN_X|BTN_CIRCLE, 0);
391                 if(inp & BTN_UP  )  { sel--;   if (sel < 0)   sel = n-2; }
392                 if(inp & BTN_DOWN)  { sel++;   if (sel > n-2) sel = 0; }
393                 if(inp & BTN_LEFT)  { sel-=10; if (sel < 0)   sel = 0; }
394                 if(inp & BTN_L)     { sel-=24; if (sel < 0)   sel = 0; }
395                 if(inp & BTN_RIGHT) { sel+=10; if (sel > n-2) sel = n-2; }
396                 if(inp & BTN_R)     { sel+=24; if (sel > n-2) sel = n-2; }
397                 if(inp & BTN_CIRCLE) { // enter dir/select
398                         if (namelist[sel+1]->d_type & DT_REG) {
399                                 strcpy(romFileName, curr_path);
400                                 strcat(romFileName, "/");
401                                 strcat(romFileName, namelist[sel+1]->d_name);
402                                 ret = romFileName;
403                                 break;
404                         } else if (namelist[sel+1]->d_type & DT_DIR) {
405                                 int newlen = strlen(curr_path) + strlen(namelist[sel+1]->d_name) + 2;
406                                 char *p, *newdir = malloc(newlen);
407                                 if (strcmp(namelist[sel+1]->d_name, "..") == 0) {
408                                         char *start = curr_path;
409                                         p = start + strlen(start) - 1;
410                                         while (*p == '/' && p > start) p--;
411                                         while (*p != '/' && *p != ':' && p > start) p--;
412                                         if (p <= start || *p == ':') strcpy(newdir, "ms0:/");
413                                         else { strncpy(newdir, start, p-start); newdir[p-start] = 0; }
414                                 } else {
415                                         strcpy(newdir, curr_path);
416                                         p = newdir + strlen(newdir) - 1;
417                                         while (*p == '/' && p >= newdir) *p-- = 0;
418                                         strcat(newdir, "/");
419                                         strcat(newdir, namelist[sel+1]->d_name);
420                                 }
421                                 ret = romsel_loop(newdir);
422                                 free(newdir);
423                                 break;
424                         }
425                 }
426                 if(inp & BTN_X) break; // cancel
427         }
428
429         if (n > 0) {
430                 while(n--) free(namelist[n]);
431                 free(namelist);
432         }
433
434         return ret;
435 }
436
437 // ------------ debug menu ------------
438
439 char *debugString(void);
440 void PicoDrawShowSpriteStats(unsigned short *screen, int stride);
441 void PicoDrawShowPalette(unsigned short *screen, int stride);
442
443 static void draw_main_debug(void)
444 {
445         char *p, *str = debugString();
446         int len, line;
447
448         menu_draw_begin();
449
450         p = str;
451         for (line = 0; line < 24; line++)
452         {
453                 while (*p && *p != '\n') p++;
454                 len = p - str;
455                 if (len > 55) len = 55;
456                 smalltext_out16_lim(1, line*10, str, 0xffff, len);
457                 if (*p == 0) break;
458                 p++; str = p;
459         }
460 }
461
462 static void draw_frame_debug(void)
463 {
464         char layer_str[48] = "layers:             ";
465         if (PicoDrawMask & PDRAW_LAYERB_ON)      memcpy(layer_str +  8, "B", 1);
466         if (PicoDrawMask & PDRAW_LAYERA_ON)      memcpy(layer_str + 10, "A", 1);
467         if (PicoDrawMask & PDRAW_SPRITES_LOW_ON) memcpy(layer_str + 12, "spr_lo", 6);
468         if (PicoDrawMask & PDRAW_SPRITES_HI_ON)  memcpy(layer_str + 19, "spr_hi", 6);
469
470         memset(psp_screen, 0, 512*272*2);
471         emu_forcedFrame(0);
472         smalltext_out16(4, 264, layer_str, 0xffff);
473 }
474
475 static void debug_menu_loop(void)
476 {
477         int inp, mode = 0;
478
479         while (1)
480         {
481                 switch (mode)
482                 {
483                         case 0: draw_main_debug(); break;
484                         case 1: draw_frame_debug(); break;
485                         case 2: menu_draw_begin();
486                                 PicoDrawShowSpriteStats((unsigned short *)psp_screen+512*16+80, 512); break;
487                         case 3: memset(psp_screen, 0, 512*272*2);
488                                 PicoDrawShowPalette(psp_screen, 512); break;
489                 }
490                 menu_draw_end();
491
492                 inp = wait_for_input(BTN_X|BTN_CIRCLE|BTN_L|BTN_R|BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT, 0);
493                 if (inp & (BTN_X|BTN_CIRCLE)) return;
494                 if (inp & BTN_L) { mode--; if (mode < 0) mode = 3; }
495                 if (inp & BTN_R) { mode++; if (mode > 3) mode = 0; }
496                 if (mode == 1) {
497                         if (inp & BTN_LEFT)  PicoDrawMask ^= PDRAW_LAYERB_ON;
498                         if (inp & BTN_RIGHT) PicoDrawMask ^= PDRAW_LAYERA_ON;
499                         if (inp & BTN_DOWN)  PicoDrawMask ^= PDRAW_SPRITES_LOW_ON;
500                         if (inp & BTN_UP)    PicoDrawMask ^= PDRAW_SPRITES_HI_ON;
501                 }
502         }
503 }
504
505 // ------------ patch/gg menu ------------
506
507 static void draw_patchlist(int sel)
508 {
509         int start, i, pos, active;
510
511         start = 13 - sel;
512
513         menu_draw_begin();
514
515         for (i = 0; i < PicoPatchCount; i++) {
516                 pos = start + i;
517                 if (pos < 0)  continue;
518                 if (pos > 26) break;
519                 active = PicoPatches[i].active;
520                 smalltext_out16_lim(14,     pos*10, active ? "ON " : "OFF", active ? 0xfff6 : 0xffff, 3);
521                 smalltext_out16_lim(14+6*4, pos*10, PicoPatches[i].name, active ? 0xfff6 : 0xffff, 53-6);
522         }
523         pos = start + i;
524         if (pos < 27) smalltext_out16_lim(14, pos*10, "done", 0xffff, 4);
525
526         text_out16(5, 130, ">");
527         menu_draw_end();
528 }
529
530
531 static void patches_menu_loop(void)
532 {
533         int menu_sel = 0;
534         unsigned long inp = 0;
535
536         for(;;)
537         {
538                 draw_patchlist(menu_sel);
539                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_L|BTN_R|BTN_X|BTN_CIRCLE, 0);
540                 if(inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = PicoPatchCount; }
541                 if(inp & BTN_DOWN) { menu_sel++; if (menu_sel > PicoPatchCount) menu_sel = 0; }
542                 if(inp &(BTN_LEFT|BTN_L))  { menu_sel-=10; if (menu_sel < 0) menu_sel = 0; }
543                 if(inp &(BTN_RIGHT|BTN_R)) { menu_sel+=10; if (menu_sel > PicoPatchCount) menu_sel = PicoPatchCount; }
544                 if(inp & BTN_CIRCLE) { // action
545                         if (menu_sel < PicoPatchCount)
546                                 PicoPatches[menu_sel].active = !PicoPatches[menu_sel].active;
547                         else    return;
548                 }
549                 if(inp & BTN_X) return;
550         }
551
552 }
553
554 // ------------ savestate loader ------------
555
556 static int state_slot_flags = 0;
557
558 static void state_check_slots(void)
559 {
560         int slot;
561
562         state_slot_flags = 0;
563
564         for (slot = 0; slot < 10; slot++)
565         {
566                 if (emu_checkSaveFile(slot))
567                 {
568                         state_slot_flags |= 1 << slot;
569                 }
570         }
571 }
572
573 static void *get_oldstate_for_preview(void)
574 {
575         unsigned char *ptr = malloc(sizeof(Pico.vram) + sizeof(Pico.cram) + sizeof(Pico.vsram) + sizeof(Pico.video));
576         if (ptr == NULL) return NULL;
577
578         memcpy(ptr, Pico.vram, sizeof(Pico.vram));
579         memcpy(ptr + sizeof(Pico.vram), Pico.cram, sizeof(Pico.cram));
580         memcpy(ptr + sizeof(Pico.vram) + sizeof(Pico.cram), Pico.vsram, sizeof(Pico.vsram));
581         memcpy(ptr + sizeof(Pico.vram) + sizeof(Pico.cram) + sizeof(Pico.vsram), &Pico.video, sizeof(Pico.video));
582         return ptr;
583 }
584
585 static void restore_oldstate(void *ptrx)
586 {
587         unsigned char *ptr = ptrx;
588         memcpy(Pico.vram,  ptr,  sizeof(Pico.vram));
589         memcpy(Pico.cram,  ptr + sizeof(Pico.vram), sizeof(Pico.cram));
590         memcpy(Pico.vsram, ptr + sizeof(Pico.vram) + sizeof(Pico.cram), sizeof(Pico.vsram));
591         memcpy(&Pico.video,ptr + sizeof(Pico.vram) + sizeof(Pico.cram) + sizeof(Pico.vsram), sizeof(Pico.video));
592         free(ptrx);
593 }
594
595 static void draw_savestate_bg(int slot)
596 {
597         void *file, *oldstate;
598         char *fname;
599
600         fname = emu_GetSaveFName(1, 0, slot);
601         if (!fname) return;
602
603         oldstate = get_oldstate_for_preview();
604         if (oldstate == NULL) return;
605
606         if (strcmp(fname + strlen(fname) - 3, ".gz") == 0) {
607                 file = gzopen(fname, "rb");
608                 emu_setSaveStateCbs(1);
609         } else {
610                 file = fopen(fname, "rb");
611                 emu_setSaveStateCbs(0);
612         }
613
614         if (file) {
615                 if (PicoAHW & PAHW_MCD) {
616                         PicoCdLoadStateGfx(file);
617                 } else {
618                         areaSeek(file, 0x10020, SEEK_SET);  // skip header and RAM in state file
619                         areaRead(Pico.vram, 1, sizeof(Pico.vram), file);
620                         areaSeek(file, 0x2000, SEEK_CUR);
621                         areaRead(Pico.cram, 1, sizeof(Pico.cram), file);
622                         areaRead(Pico.vsram, 1, sizeof(Pico.vsram), file);
623                         areaSeek(file, 0x221a0, SEEK_SET);
624                         areaRead(&Pico.video, 1, sizeof(Pico.video), file);
625                 }
626                 areaClose(file);
627         }
628
629         emu_forcedFrame(0);
630         menu_prepare_bg(1, 0);
631
632         restore_oldstate(oldstate);
633 }
634
635 static void draw_savestate_menu(int menu_sel, int is_loading)
636 {
637         int tl_x = 80+25, tl_y = 16+60, y, i;
638
639         if (state_slot_flags & (1 << menu_sel))
640                 draw_savestate_bg(menu_sel);
641         menu_draw_begin();
642
643         text_out16(tl_x, 16+30, is_loading ? "Load state" : "Save state");
644
645         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 108);
646
647         /* draw all 10 slots */
648         y = tl_y;
649         for (i = 0; i < 10; i++, y+=10)
650         {
651                 text_out16(tl_x, y, "SLOT %i (%s)", i, (state_slot_flags & (1 << i)) ? "USED" : "free");
652         }
653         text_out16(tl_x, y, "back");
654
655         menu_draw_end();
656 }
657
658 static int savestate_menu_loop(int is_loading)
659 {
660         static int menu_sel = 10;
661         int menu_sel_max = 10;
662         unsigned long inp = 0;
663
664         state_check_slots();
665
666         for(;;)
667         {
668                 draw_savestate_menu(menu_sel, is_loading);
669                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X|BTN_CIRCLE, 0);
670                 if(inp & BTN_UP  ) {
671                         do {
672                                 menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max;
673                         } while (!(state_slot_flags & (1 << menu_sel)) && menu_sel != menu_sel_max && is_loading);
674                 }
675                 if(inp & BTN_DOWN) {
676                         do {
677                                 menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0;
678                         } while (!(state_slot_flags & (1 << menu_sel)) && menu_sel != menu_sel_max && is_loading);
679                 }
680                 if(inp & BTN_CIRCLE) { // save/load
681                         if (menu_sel < 10) {
682                                 state_slot = menu_sel;
683                                 PicoStateProgressCB = emu_msg_cb; /* also suitable for menu */
684                                 if (emu_SaveLoadGame(is_loading, 0)) {
685                                         strcpy(menuErrorMsg, is_loading ? "Load failed" : "Save failed");
686                                         return 1;
687                                 }
688                                 return 0;
689                         } else  return 1;
690                 }
691                 if(inp & BTN_X) return 1;
692         }
693 }
694
695 // -------------- key config --------------
696
697 static char *action_binds(int player_idx, int action_mask)
698 {
699         static char strkeys[32*5];
700         int i;
701
702         strkeys[0] = 0;
703         for (i = 0; i < 32; i++) // i is key index
704         {
705                 if (currentConfig.KeyBinds[i] & action_mask)
706                 {
707                         if (player_idx >= 0 && ((currentConfig.KeyBinds[i] >> 16) & 3) != player_idx) continue;
708                         if (strkeys[0]) {
709                                 strcat(strkeys, i >= 28 ? ", " : " + "); // nub "buttons" don't create combos
710                                 strcat(strkeys, keyNames[i]);
711                                 break;
712                         }
713                         else strcpy(strkeys, keyNames[i]);
714                 }
715         }
716
717         return strkeys;
718 }
719
720 static void unbind_action(int action)
721 {
722         int i;
723
724         for (i = 0; i < 32; i++)
725                 currentConfig.KeyBinds[i] &= ~action;
726 }
727
728 static int count_bound_keys(int action, int pl_idx)
729 {
730         int i, keys = 0;
731
732         for (i = 0; i < 32; i++)
733         {
734                 if (pl_idx >= 0 && (currentConfig.KeyBinds[i]&0x30000) != (pl_idx<<16)) continue;
735                 if (currentConfig.KeyBinds[i] & action) keys++;
736         }
737
738         return keys;
739 }
740
741 static void draw_key_config(const me_bind_action *opts, int opt_cnt, int player_idx, int sel)
742 {
743         int x, y, tl_y = 16+40, i;
744
745         menu_draw_begin();
746         if (player_idx >= 0) {
747                 text_out16(80+80, 16+20, "Player %i controls", player_idx + 1);
748                 x = 80+80;
749         } else {
750                 text_out16(80+80, 16+20, "Emulator controls");
751                 x = 80+40;
752         }
753
754         menu_draw_selection(x - 16, tl_y + sel*10, (player_idx >= 0) ? 66 : 130);
755
756         y = tl_y;
757         for (i = 0; i < opt_cnt; i++, y+=10)
758                 text_out16(x, y, "%s : %s", opts[i].name, action_binds(player_idx, opts[i].mask));
759
760         text_out16(x, y, "Done");
761
762         if (sel < opt_cnt) {
763                 text_out16(80+30, 220, "Press a button to bind/unbind");
764                 text_out16(80+30, 230, "Use SELECT to clear");
765                 text_out16(80+30, 240, "To bind UP/DOWN, hold SELECT");
766                 text_out16(80+30, 250, "Select \"Done\" to exit");
767         } else {
768                 text_out16(80+30, 230, "Use Options -> Save cfg");
769                 text_out16(80+30, 240, "to save controls");
770                 text_out16(80+30, 250, "Press X or O to exit");
771         }
772         menu_draw_end();
773 }
774
775 static void key_config_loop(const me_bind_action *opts, int opt_cnt, int player_idx)
776 {
777         int sel = 0, menu_sel_max = opt_cnt, prev_select = 0, i;
778         unsigned long inp = 0;
779
780         for (;;)
781         {
782                 draw_key_config(opts, opt_cnt, player_idx, sel);
783                 inp = wait_for_input(CONFIGURABLE_KEYS|BTN_SELECT, 1);
784                 if (!(inp & BTN_SELECT)) {
785                         prev_select = 0;
786                         if(inp & BTN_UP  ) { sel--; if (sel < 0) sel = menu_sel_max; continue; }
787                         if(inp & BTN_DOWN) { sel++; if (sel > menu_sel_max) sel = 0; continue; }
788                 }
789                 if (sel >= opt_cnt) {
790                         if (inp & (BTN_X|BTN_CIRCLE)) break;
791                         else continue;
792                 }
793                 // if we are here, we want to bind/unbind something
794                 if ((inp & BTN_SELECT) && !prev_select)
795                         unbind_action(opts[sel].mask);
796                 prev_select = inp & BTN_SELECT;
797                 inp &= CONFIGURABLE_KEYS;
798                 inp &= ~BTN_SELECT;
799                 for (i = 0; i < 32; i++)
800                         if (inp & (1 << i)) {
801                                 if (count_bound_keys(opts[sel].mask, player_idx) >= 2)
802                                      currentConfig.KeyBinds[i] &= ~opts[sel].mask; // allow to unbind only
803                                 else currentConfig.KeyBinds[i] ^=  opts[sel].mask;
804                                 if (player_idx >= 0 && (currentConfig.KeyBinds[i] & opts[sel].mask)) {
805                                         currentConfig.KeyBinds[i] &= ~(3 << 16);
806                                         currentConfig.KeyBinds[i] |= player_idx << 16;
807                                 }
808                         }
809         }
810 }
811
812 static void draw_kc_sel(int menu_sel)
813 {
814         int tl_x = 80+25+40, tl_y = 16+60, y;
815
816         y = tl_y;
817         menu_draw_begin();
818         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 138);
819
820         text_out16(tl_x, y,       "Player 1");
821         text_out16(tl_x, (y+=10), "Player 2");
822         text_out16(tl_x, (y+=10), "Emulator controls");
823         text_out16(tl_x, (y+=10), "Done");
824
825         menu_draw_end();
826 }
827
828
829 // player2_flag, ?, ?, ?, ?, ?, ?, menu
830 // "NEXT SAVE SLOT", "PREV SAVE SLOT", "SWITCH RENDERER", "SAVE STATE",
831 // "LOAD STATE", "VOLUME UP", "VOLUME DOWN", "DONE"
832 me_bind_action emuctrl_actions[] =
833 {
834         { "Load State       ", 1<<28 },
835         { "Save State       ", 1<<27 },
836         { "Prev Save Slot   ", 1<<25 },
837         { "Next Save Slot   ", 1<<24 },
838         { "Switch Renderer  ", 1<<26 },
839         { "Fast forward     ", 1<<22 },
840         { "Pico Next page   ", 1<<21 },
841         { "Pico Prev page   ", 1<<20 },
842         { "Pico Switch input", 1<<19 },
843         { NULL,                0     }
844 };
845
846 static void kc_sel_loop(void)
847 {
848         int menu_sel = 3, menu_sel_max = 3;
849         unsigned long inp = 0;
850         int is_6button = PicoOpt & POPT_6BTN_PAD;
851
852         while (1)
853         {
854                 draw_kc_sel(menu_sel);
855                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X|BTN_CIRCLE, 0);
856                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
857                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
858                 if (inp & BTN_CIRCLE) {
859                         switch (menu_sel) {
860                                 case 0: key_config_loop(me_ctrl_actions, is_6button ? 12 : 8, 0); return;
861                                 case 1: key_config_loop(me_ctrl_actions, is_6button ? 12 : 8, 1); return;
862                                 case 2: key_config_loop(emuctrl_actions,
863                                                 sizeof(emuctrl_actions)/sizeof(emuctrl_actions[0]) - 1, -1); return;
864                                 case 3: if (!rom_loaded) emu_WriteConfig(0); return;
865                                 default: return;
866                         }
867                 }
868                 if (inp & BTN_X) return;
869         }
870 }
871
872
873 // --------- sega/mega cd options ----------
874
875 menu_entry cdopt_entries[] =
876 {
877         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_USA, NULL, 0, 0, 0, 1, 0 },
878         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_EUR, NULL, 0, 0, 0, 1, 0 },
879         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_JAP, NULL, 0, 0, 0, 1, 0 },
880         { "CD LEDs",                   MB_ONOFF, MA_CDOPT_LEDS,         &currentConfig.EmuOpt,  0x0400, 0, 0, 1, 1 },
881         { "CDDA audio (using mp3s)",   MB_ONOFF, MA_CDOPT_CDDA,         &PicoOpt, 0x0800, 0, 0, 1, 1 },
882         { "PCM audio",                 MB_ONOFF, MA_CDOPT_PCM,          &PicoOpt, 0x0400, 0, 0, 1, 1 },
883         { NULL,                        MB_NONE,  MA_CDOPT_READAHEAD,    NULL, 0, 0, 0, 1, 1 },
884         { "SaveRAM cart",              MB_ONOFF, MA_CDOPT_SAVERAM,      &PicoOpt, 0x8000, 0, 0, 1, 1 },
885         { "Scale/Rot. fx (slow)",      MB_ONOFF, MA_CDOPT_SCALEROT_CHIP,&PicoOpt, 0x1000, 0, 0, 1, 1 },
886         { "Better sync (slow)",        MB_ONOFF, MA_CDOPT_BETTER_SYNC,  &PicoOpt, 0x2000, 0, 0, 1, 1 },
887         { "done",                      MB_NONE,  MA_CDOPT_DONE,         NULL, 0, 0, 0, 1, 0 },
888 };
889
890 #define CDOPT_ENTRY_COUNT (sizeof(cdopt_entries) / sizeof(cdopt_entries[0]))
891 const int cdopt_entry_count = CDOPT_ENTRY_COUNT;
892
893
894 struct bios_names_t
895 {
896         char us[32], eu[32], jp[32];
897 };
898
899 static void menu_cdopt_cust_draw(const menu_entry *entry, int x, int y, void *param)
900 {
901         struct bios_names_t *bios_names = param;
902         char ra_buff[16];
903
904         switch (entry->id)
905         {
906                 case MA_CDOPT_TESTBIOS_USA: text_out16(x, y, "USA BIOS:     %s", bios_names->us); break;
907                 case MA_CDOPT_TESTBIOS_EUR: text_out16(x, y, "EUR BIOS:     %s", bios_names->eu); break;
908                 case MA_CDOPT_TESTBIOS_JAP: text_out16(x, y, "JAP BIOS:     %s", bios_names->jp); break;
909                 case MA_CDOPT_READAHEAD:
910                         if (PicoCDBuffers > 1) sprintf(ra_buff, "%5iK", PicoCDBuffers * 2);
911                         else strcpy(ra_buff, "     OFF");
912                         text_out16(x, y, "ReadAhead buffer      %s", ra_buff);
913                         break;
914                 default:break;
915         }
916 }
917
918 static void draw_cd_menu_options(int menu_sel, struct bios_names_t *bios_names)
919 {
920         int tl_x = 80+25, tl_y = 16+60;
921         menu_id selected_id;
922         char ra_buff[16];
923
924         if (PicoCDBuffers > 1) sprintf(ra_buff, "%5iK", PicoCDBuffers * 2);
925         else strcpy(ra_buff, "     OFF");
926
927         menu_draw_begin();
928
929         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 246);
930
931         me_draw(cdopt_entries, CDOPT_ENTRY_COUNT, tl_x, tl_y, menu_cdopt_cust_draw, bios_names);
932
933         selected_id = me_index2id(cdopt_entries, CDOPT_ENTRY_COUNT, menu_sel);
934         if ((selected_id == MA_CDOPT_TESTBIOS_USA && strcmp(bios_names->us, "NOT FOUND")) ||
935                 (selected_id == MA_CDOPT_TESTBIOS_EUR && strcmp(bios_names->eu, "NOT FOUND")) ||
936                 (selected_id == MA_CDOPT_TESTBIOS_JAP && strcmp(bios_names->jp, "NOT FOUND")))
937                         text_out16(tl_x, 250, "Press start to test selected BIOS");
938
939         menu_draw_end();
940 }
941
942 static void cd_menu_loop_options(void)
943 {
944         static int menu_sel = 0;
945         int menu_sel_max = 10;
946         unsigned long inp = 0;
947         struct bios_names_t bios_names;
948         menu_id selected_id;
949         char *bios, *p;
950
951         if (emu_findBios(4, &bios)) { // US
952                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--);
953                 if (*p == '/') p++;
954                 strncpy(bios_names.us, p, sizeof(bios_names.us)); bios_names.us[sizeof(bios_names.us)-1] = 0;
955         } else  strcpy(bios_names.us, "NOT FOUND");
956
957         if (emu_findBios(8, &bios)) { // EU
958                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--);
959                 if (*p == '/') p++;
960                 strncpy(bios_names.eu, p, sizeof(bios_names.eu)); bios_names.eu[sizeof(bios_names.eu)-1] = 0;
961         } else  strcpy(bios_names.eu, "NOT FOUND");
962
963         if (emu_findBios(1, &bios)) { // JP
964                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--);
965                 if (*p == '/') p++;
966                 strncpy(bios_names.jp, p, sizeof(bios_names.jp)); bios_names.jp[sizeof(bios_names.jp)-1] = 0;
967         } else  strcpy(bios_names.jp, "NOT FOUND");
968
969         menuErrorMsg[0] = 0;
970
971         for (;;)
972         {
973                 draw_cd_menu_options(menu_sel, &bios_names);
974                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE|BTN_START, 0);
975                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
976                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
977                 selected_id = me_index2id(cdopt_entries, CDOPT_ENTRY_COUNT, menu_sel);
978                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
979                         if (!me_process(cdopt_entries, CDOPT_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0) &&
980                             selected_id == MA_CDOPT_READAHEAD) {
981                                 if (inp & BTN_LEFT) {
982                                         PicoCDBuffers >>= 1;
983                                         if (PicoCDBuffers < 2) PicoCDBuffers = 0;
984                                 } else {
985                                         if (PicoCDBuffers < 2) PicoCDBuffers = 2;
986                                         else PicoCDBuffers <<= 1;
987                                         if (PicoCDBuffers > 8*1024) PicoCDBuffers = 8*1024; // 16M
988                                 }
989                         }
990                 }
991                 if (inp & BTN_CIRCLE) // toggleable options
992                         if (!me_process(cdopt_entries, CDOPT_ENTRY_COUNT, selected_id, 1) &&
993                             selected_id == MA_CDOPT_DONE) {
994                                 return;
995                         }
996                 if (inp & BTN_START) {
997                         switch (selected_id) { // BIOS testers
998                                 case MA_CDOPT_TESTBIOS_USA:
999                                         if (emu_findBios(4, &bios)) { // test US
1000                                                 strcpy(romFileName, bios);
1001                                                 engineState = PGS_ReloadRom;
1002                                                 return;
1003                                         }
1004                                         break;
1005                                 case MA_CDOPT_TESTBIOS_EUR:
1006                                         if (emu_findBios(8, &bios)) { // test EU
1007                                                 strcpy(romFileName, bios);
1008                                                 engineState = PGS_ReloadRom;
1009                                                 return;
1010                                         }
1011                                         break;
1012                                 case MA_CDOPT_TESTBIOS_JAP:
1013                                         if (emu_findBios(1, &bios)) { // test JP
1014                                                 strcpy(romFileName, bios);
1015                                                 engineState = PGS_ReloadRom;
1016                                                 return;
1017                                         }
1018                                         break;
1019                                 default:
1020                                         break;
1021                         }
1022                 }
1023                 if (inp & BTN_X) return;
1024         }
1025 }
1026
1027 // --------- display options ----------
1028
1029 menu_entry opt3_entries[] =
1030 {
1031         { NULL,                        MB_NONE,  MA_OPT3_SCALE,         NULL, 0, 0, 0, 1, 1 },
1032         { NULL,                        MB_NONE,  MA_OPT3_HSCALE32,      NULL, 0, 0, 0, 1, 1 },
1033         { NULL,                        MB_NONE,  MA_OPT3_HSCALE40,      NULL, 0, 0, 0, 1, 1 },
1034         { NULL,                        MB_ONOFF, MA_OPT3_FILTERING,     &currentConfig.scaling, 1,  0,  0, 1, 1 },
1035         { NULL,                        MB_RANGE, MA_OPT3_GAMMAA,        &currentConfig.gamma,   0, -4, 16, 1, 1 },
1036         { NULL,                        MB_RANGE, MA_OPT3_BLACKLVL,      &currentConfig.gamma2,  0,  0,  2, 1, 1 },
1037         { NULL,                        MB_NONE,  MA_OPT3_VSYNC,         NULL, 0, 0, 0, 1, 1 },
1038         { "Set to unscaled centered",  MB_NONE,  MA_OPT3_PRES_NOSCALE,  NULL, 0, 0, 0, 1, 0 },
1039         { "Set to 4:3 scaled",         MB_NONE,  MA_OPT3_PRES_SCALE43,  NULL, 0, 0, 0, 1, 0 },
1040         { "Set to fullscreen",         MB_NONE,  MA_OPT3_PRES_FULLSCR,  NULL, 0, 0, 0, 1, 0 },
1041         { "done",                      MB_NONE,  MA_OPT3_DONE,          NULL, 0, 0, 0, 1, 0 },
1042 };
1043
1044 #define OPT3_ENTRY_COUNT (sizeof(opt3_entries) / sizeof(opt3_entries[0]))
1045 const int opt3_entry_count = OPT3_ENTRY_COUNT;
1046
1047
1048 static void menu_opt3_cust_draw(const menu_entry *entry, int x, int y, void *param)
1049 {
1050         switch (entry->id)
1051         {
1052                 case MA_OPT3_SCALE:
1053                         text_out16(x, y, "Scale factor:                      %.2f", currentConfig.scale);
1054                         break;
1055                 case MA_OPT3_HSCALE32:
1056                         text_out16(x, y, "Hor. scale (for low res. games):   %.2f", currentConfig.hscale32);
1057                         break;
1058                 case MA_OPT3_HSCALE40:
1059                         text_out16(x, y, "Hor. scale (for hi res. games):    %.2f", currentConfig.hscale40);
1060                         break;
1061                 case MA_OPT3_FILTERING:
1062                         text_out16(x, y, "Bilinear filtering                 %s", currentConfig.scaling?"ON":"OFF");
1063                         break;
1064                 case MA_OPT3_GAMMAA:
1065                         text_out16(x, y, "Gamma adjustment                  %2i", currentConfig.gamma);
1066                         break;
1067                 case MA_OPT3_BLACKLVL:
1068                         text_out16(x, y, "Black level                       %2i", currentConfig.gamma2);
1069                         break;
1070                 case MA_OPT3_VSYNC: {
1071                         char *val = "    never";
1072                         if (currentConfig.EmuOpt & 0x2000)
1073                                 val = (currentConfig.EmuOpt & 0x10000) ? "sometimes" : "   always";
1074                         text_out16(x, y, "Wait for vsync (slow)         %s", val);
1075                         break;
1076                 }
1077                 default: break;
1078         }
1079 }
1080
1081 static void menu_opt3_preview(int is_32col)
1082 {
1083         void *oldstate = NULL;
1084
1085         if (!rom_loaded || ((Pico.video.reg[12]&1)^1) != is_32col)
1086         {
1087                 extern char bgdatac32_start[], bgdatac40_start[];
1088                 extern int bgdatac32_size, bgdatac40_size;
1089                 void *bgdata = is_32col ? bgdatac32_start : bgdatac40_start;
1090                 unsigned long insize = is_32col ? bgdatac32_size : bgdatac40_size, outsize = 65856;
1091                 int ret;
1092                 ret = uncompress((Bytef *)bg_buffer, &outsize, bgdata, insize);
1093                 if (ret == 0)
1094                 {
1095                         if (rom_loaded) oldstate = get_oldstate_for_preview();
1096                         memcpy(Pico.vram,  bg_buffer, sizeof(Pico.vram));
1097                         memcpy(Pico.cram,  (char *)bg_buffer + 0x10000, 0x40*2);
1098                         memcpy(Pico.vsram, (char *)bg_buffer + 0x10080, 0x40*2);
1099                         memcpy(&Pico.video,(char *)bg_buffer + 0x10100, 0x40);
1100                 }
1101                 else
1102                         lprintf("uncompress returned %i\n", ret);
1103         }
1104
1105         memset32_uncached(psp_screen, 0, 512*272*2/4);
1106         emu_forcedFrame(0);
1107         menu_prepare_bg(1, 0);
1108
1109         if (oldstate) restore_oldstate(oldstate);
1110 }
1111
1112 static void draw_dispmenu_options(int menu_sel)
1113 {
1114         int tl_x = 80, tl_y = 16+50;
1115
1116         menu_draw_begin();
1117
1118         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 316);
1119
1120         me_draw(opt3_entries, OPT3_ENTRY_COUNT, tl_x, tl_y, menu_opt3_cust_draw, NULL);
1121
1122         menu_draw_end();
1123 }
1124
1125 static void dispmenu_loop_options(void)
1126 {
1127         static int menu_sel = 0;
1128         int menu_sel_max, is_32col = (Pico.video.reg[12]&1)^1;
1129         unsigned long inp = 0;
1130         menu_id selected_id;
1131
1132         menu_sel_max = me_count_enabled(opt3_entries, OPT3_ENTRY_COUNT) - 1;
1133
1134         for (;;)
1135         {
1136                 draw_dispmenu_options(menu_sel);
1137                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE, 0);
1138                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1139                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1140                 selected_id = me_index2id(opt3_entries, OPT3_ENTRY_COUNT, menu_sel);
1141                 if (selected_id == MA_OPT3_HSCALE40 &&  is_32col) { is_32col = 0; menu_opt3_preview(is_32col); }
1142                 if (selected_id == MA_OPT3_HSCALE32 && !is_32col) { is_32col = 1; menu_opt3_preview(is_32col); }
1143
1144                 if (inp & (BTN_LEFT|BTN_RIGHT)) // multi choise
1145                 {
1146                         float *setting = NULL;
1147                         int tmp;
1148                         me_process(opt3_entries, OPT3_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0);
1149                         switch (selected_id) {
1150                                 case MA_OPT3_SCALE:     setting = &currentConfig.scale; break;
1151                                 case MA_OPT3_HSCALE40:  setting = &currentConfig.hscale40; is_32col = 0; break;
1152                                 case MA_OPT3_HSCALE32:  setting = &currentConfig.hscale32; is_32col = 1; break;
1153                                 case MA_OPT3_FILTERING:
1154                                 case MA_OPT3_GAMMAA:
1155                                 case MA_OPT3_BLACKLVL:  menu_opt3_preview(is_32col); break;
1156                                 case MA_OPT3_VSYNC:
1157                                         tmp = ((currentConfig.EmuOpt>>13)&1) | ((currentConfig.EmuOpt>>15)&2);
1158                                         tmp = (inp & BTN_LEFT) ? (tmp>>1) : ((tmp<<1)|1);
1159                                         if (tmp > 3) tmp = 3;
1160                                         currentConfig.EmuOpt &= ~0x12000;
1161                                         currentConfig.EmuOpt |= ((tmp&2)<<15) | ((tmp&1)<<13);
1162                                         break;
1163                                 default: break;
1164                         }
1165                         if (setting != NULL) {
1166                                 while ((inp = psp_pad_read(0)) & (BTN_LEFT|BTN_RIGHT)) {
1167                                         *setting += (inp & BTN_LEFT) ? -0.01 : 0.01;
1168                                         if (*setting <= 0) *setting = 0.01;
1169                                         menu_opt3_preview(is_32col);
1170                                         draw_dispmenu_options(menu_sel); // will wait vsync
1171                                 }
1172                         }
1173                 }
1174                 if (inp & BTN_CIRCLE) { // toggleable options
1175                         me_process(opt3_entries, OPT3_ENTRY_COUNT, selected_id, 1);
1176                         switch (selected_id) {
1177                                 case MA_OPT3_DONE:
1178                                         return;
1179                                 case MA_OPT3_PRES_NOSCALE:
1180                                         currentConfig.scale = currentConfig.hscale40 = currentConfig.hscale32 = 1.0;
1181                                         menu_opt3_preview(is_32col);
1182                                         break;
1183                                 case MA_OPT3_PRES_SCALE43:
1184                                         currentConfig.scale = 1.20;
1185                                         currentConfig.hscale40 = 1.00;
1186                                         currentConfig.hscale32 = 1.25;
1187                                         menu_opt3_preview(is_32col);
1188                                         break;
1189                                 case MA_OPT3_PRES_FULLSCR:
1190                                         currentConfig.scale = 1.20;
1191                                         currentConfig.hscale40 = 1.25;
1192                                         currentConfig.hscale32 = 1.56;
1193                                         menu_opt3_preview(is_32col);
1194                                         break;
1195                                 case MA_OPT3_FILTERING:
1196                                         menu_opt3_preview(is_32col);
1197                                         break;
1198                                 default: break;
1199                         }
1200                 }
1201                 if (inp & BTN_X) return;
1202         }
1203 }
1204
1205
1206 // --------- advanced options ----------
1207
1208 menu_entry opt2_entries[] =
1209 {
1210         { "Disable sprite limit",      MB_ONOFF, MA_OPT2_NO_SPRITE_LIM,  &PicoOpt, 0x40000, 0, 0, 1, 1 },
1211         { "Emulate Z80",               MB_ONOFF, MA_OPT2_ENABLE_Z80,     &PicoOpt, 0x00004, 0, 0, 1, 1 },
1212         { "Emulate YM2612 (FM)",       MB_ONOFF, MA_OPT2_ENABLE_YM2612,  &PicoOpt, 0x00001, 0, 0, 1, 1 },
1213         { "Emulate SN76496 (PSG)",     MB_ONOFF, MA_OPT2_ENABLE_SN76496, &PicoOpt, 0x00002, 0, 0, 1, 1 },
1214         { "gzip savestates",           MB_ONOFF, MA_OPT2_GZIP_STATES,    &currentConfig.EmuOpt, 0x00008, 0, 0, 1, 1 },
1215         { "Don't save last used ROM",  MB_ONOFF, MA_OPT2_NO_LAST_ROM,    &currentConfig.EmuOpt, 0x00020, 0, 0, 1, 1 },
1216         { "Status line in main menu",  MB_ONOFF, MA_OPT2_STATUS_LINE,    &currentConfig.EmuOpt, 0x20000, 0, 0, 1, 1 },
1217         { "Disable frame limiter",     MB_ONOFF, MA_OPT2_NO_FRAME_LIMIT, &currentConfig.EmuOpt, 0x40000, 0, 0, 1, 1 },
1218         { "done",                      MB_NONE,  MA_OPT2_DONE,           NULL, 0, 0, 0, 1, 0 },
1219 };
1220
1221 #define OPT2_ENTRY_COUNT (sizeof(opt2_entries) / sizeof(opt2_entries[0]))
1222 const int opt2_entry_count = OPT2_ENTRY_COUNT;
1223
1224
1225 static void draw_amenu_options(int menu_sel)
1226 {
1227         int tl_x = 80+25, tl_y = 16+50;
1228
1229         menu_draw_begin();
1230
1231         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 252);
1232
1233         me_draw(opt2_entries, OPT2_ENTRY_COUNT, tl_x, tl_y, NULL, NULL);
1234
1235         menu_draw_end();
1236 }
1237
1238 static void amenu_loop_options(void)
1239 {
1240         static int menu_sel = 0;
1241         int menu_sel_max;
1242         unsigned long inp = 0;
1243         menu_id selected_id;
1244
1245         menu_sel_max = me_count_enabled(opt2_entries, OPT2_ENTRY_COUNT) - 1;
1246
1247         for(;;)
1248         {
1249                 draw_amenu_options(menu_sel);
1250                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE, 0);
1251                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1252                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1253                 selected_id = me_index2id(opt2_entries, OPT2_ENTRY_COUNT, menu_sel);
1254                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
1255                         if (!me_process(opt2_entries, OPT2_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0) &&
1256                             selected_id == MA_OPT2_GAMMA) {
1257                                 // TODO?
1258                         }
1259                 }
1260                 if (inp & BTN_CIRCLE) { // toggleable options
1261                         if (!me_process(opt2_entries, OPT2_ENTRY_COUNT, selected_id, 1) &&
1262                             selected_id == MA_OPT2_DONE) {
1263                                 return;
1264                         }
1265                 }
1266                 if (inp & BTN_X) return;
1267         }
1268 }
1269
1270 // -------------- options --------------
1271
1272
1273 menu_entry opt_entries[] =
1274 {
1275         { NULL,                        MB_NONE,  MA_OPT_RENDERER,      NULL, 0, 0, 0, 1, 1 },
1276         { "Accurate sprites",          MB_ONOFF, MA_OPT_ACC_SPRITES,   &PicoOpt, 0x0080, 0, 0, 0, 1 },
1277         { "Show FPS",                  MB_ONOFF, MA_OPT_SHOW_FPS,      &currentConfig.EmuOpt,  0x0002,  0,  0, 1, 1 },
1278         { NULL,                        MB_RANGE, MA_OPT_FRAMESKIP,     &currentConfig.Frameskip,    0, -1, 16, 1, 1 },
1279         { "Enable sound",              MB_ONOFF, MA_OPT_ENABLE_SOUND,  &currentConfig.EmuOpt,  0x0004,  0,  0, 1, 1 },
1280         { NULL,                        MB_NONE,  MA_OPT_SOUND_QUALITY, NULL, 0, 0, 0, 1, 1 },
1281         { "6 button pad",              MB_ONOFF, MA_OPT_6BUTTON_PAD,   &PicoOpt, 0x0020, 0, 0, 1, 1 },
1282         { NULL,                        MB_NONE,  MA_OPT_REGION,        NULL, 0, 0, 0, 1, 1 },
1283         { "Use SRAM/BRAM savestates",  MB_ONOFF, MA_OPT_SRAM_STATES,   &currentConfig.EmuOpt,  0x0001, 0, 0, 1, 1 },
1284         { NULL,                        MB_NONE,  MA_OPT_CONFIRM_STATES,NULL, 0, 0, 0, 1, 1 },
1285         { "Save slot",                 MB_RANGE, MA_OPT_SAVE_SLOT,     &state_slot, 0, 0, 9, 1, 1 },
1286         { NULL,                        MB_NONE,  MA_OPT_CPU_CLOCKS,    NULL, 0, 0, 0, 1, 1 },
1287         { "[Display options]",         MB_NONE,  MA_OPT_DISP_OPTS,     NULL, 0, 0, 0, 1, 0 },
1288         { "[Sega/Mega CD options]",    MB_NONE,  MA_OPT_SCD_OPTS,      NULL, 0, 0, 0, 1, 0 },
1289         { "[Advanced options]",        MB_NONE,  MA_OPT_ADV_OPTS,      NULL, 0, 0, 0, 1, 0 },
1290         { NULL,                        MB_NONE,  MA_OPT_SAVECFG,       NULL, 0, 0, 0, 1, 0 },
1291         { "Save cfg for current game only",MB_NONE,MA_OPT_SAVECFG_GAME,NULL, 0, 0, 0, 1, 0 },
1292         { NULL,                        MB_NONE,  MA_OPT_LOADCFG,       NULL, 0, 0, 0, 1, 0 },
1293 };
1294
1295 #define OPT_ENTRY_COUNT (sizeof(opt_entries) / sizeof(opt_entries[0]))
1296 const int opt_entry_count = OPT_ENTRY_COUNT;
1297
1298
1299 static void menu_opt_cust_draw(const menu_entry *entry, int x, int y, void *param)
1300 {
1301         char *str, str24[24];
1302
1303         switch (entry->id)
1304         {
1305                 case MA_OPT_RENDERER:
1306                         if (PicoOpt & 0x10)
1307                                 str = "fast";
1308                         else if (currentConfig.EmuOpt & 0x80)
1309                                 str = "accurate";
1310                         else
1311                                 str = " 8bit accurate"; // n/a
1312                         text_out16(x, y, "Renderer:                  %s", str);
1313                         break;
1314                 case MA_OPT_FRAMESKIP:
1315                         if (currentConfig.Frameskip < 0)
1316                              strcpy(str24, "Auto");
1317                         else sprintf(str24, "%i", currentConfig.Frameskip);
1318                         text_out16(x, y, "Frameskip                  %s", str24);
1319                         break;
1320                 case MA_OPT_SOUND_QUALITY:
1321                         str = (PicoOpt&0x08)?"stereo":"mono";
1322                         text_out16(x, y, "Sound Quality:     %5iHz %s", PsndRate, str);
1323                         break;
1324                 case MA_OPT_REGION:
1325                         text_out16(x, y, "Region:              %s", me_region_name(PicoRegionOverride, PicoAutoRgnOrder));
1326                         break;
1327                 case MA_OPT_CONFIRM_STATES:
1328                         switch ((currentConfig.EmuOpt >> 9) & 5) {
1329                                 default: str = "OFF";    break;
1330                                 case 1:  str = "writes"; break;
1331                                 case 4:  str = "loads";  break;
1332                                 case 5:  str = "both";   break;
1333                         }
1334                         text_out16(x, y, "Confirm savestate          %s", str);
1335                         break;
1336                 case MA_OPT_CPU_CLOCKS:
1337                         text_out16(x, y, "CPU/bus clock       %3i/%3iMHz", currentConfig.CPUclock, currentConfig.CPUclock/2);
1338                         break;
1339                 case MA_OPT_SAVECFG:
1340                         str24[0] = 0;
1341                         if (config_slot != 0) sprintf(str24, " (profile: %i)", config_slot);
1342                         text_out16(x, y, "Save cfg as default%s", str24);
1343                         break;
1344                 case MA_OPT_LOADCFG:
1345                         text_out16(x, y, "Load cfg from profile %i", config_slot);
1346                         break;
1347                 default:
1348                         lprintf("%s: unimplemented (%i)\n", __FUNCTION__, entry->id);
1349                         break;
1350         }
1351 }
1352
1353
1354 static void draw_menu_options(int menu_sel)
1355 {
1356         int tl_x = 80+25, tl_y = 16+24;
1357
1358         menu_draw_begin();
1359
1360         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 284);
1361
1362         me_draw(opt_entries, OPT_ENTRY_COUNT, tl_x, tl_y, menu_opt_cust_draw, NULL);
1363
1364         menu_draw_end();
1365 }
1366
1367 static int sndrate_prevnext(int rate, int dir)
1368 {
1369         int i, rates[] = { 11025, 22050, 44100 };
1370
1371         for (i = 0; i < 5; i++)
1372                 if (rates[i] == rate) break;
1373
1374         i += dir ? 1 : -1;
1375         if (i > 2) return dir ? 44100 : 22050;
1376         if (i < 0) return dir ? 22050 : 11025;
1377         return rates[i];
1378 }
1379
1380 static void region_prevnext(int right)
1381 {
1382         // jp_ntsc=1, jp_pal=2, usa=4, eu=8
1383         static int rgn_orders[] = { 0x148, 0x184, 0x814, 0x418, 0x841, 0x481 };
1384         int i;
1385         if (right) {
1386                 if (!PicoRegionOverride) {
1387                         for (i = 0; i < 6; i++)
1388                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
1389                         if (i < 5) PicoAutoRgnOrder = rgn_orders[i+1];
1390                         else PicoRegionOverride=1;
1391                 }
1392                 else PicoRegionOverride<<=1;
1393                 if (PicoRegionOverride > 8) PicoRegionOverride = 8;
1394         } else {
1395                 if (!PicoRegionOverride) {
1396                         for (i = 0; i < 6; i++)
1397                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
1398                         if (i > 0) PicoAutoRgnOrder = rgn_orders[i-1];
1399                 }
1400                 else PicoRegionOverride>>=1;
1401         }
1402 }
1403
1404 static void menu_options_save(void)
1405 {
1406         if (PicoRegionOverride) {
1407                 // force setting possibly changed..
1408                 Pico.m.pal = (PicoRegionOverride == 2 || PicoRegionOverride == 8) ? 1 : 0;
1409         }
1410         if (!(PicoOpt & POPT_6BTN_PAD)) {
1411                 // unbind XYZ MODE, just in case
1412                 unbind_action(0xf00);
1413         }
1414 }
1415
1416 static int menu_loop_options(void)
1417 {
1418         static int menu_sel = 0;
1419         int menu_sel_max, ret;
1420         unsigned long inp = 0;
1421         menu_id selected_id;
1422
1423         me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_SAVECFG_GAME, rom_loaded);
1424         me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_LOADCFG, config_slot != config_slot_current);
1425         menu_sel_max = me_count_enabled(opt_entries, OPT_ENTRY_COUNT) - 1;
1426         if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1427
1428         while (1)
1429         {
1430                 draw_menu_options(menu_sel);
1431                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE, 0);
1432                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1433                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1434                 selected_id = me_index2id(opt_entries, OPT_ENTRY_COUNT, menu_sel);
1435                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
1436                         if (!me_process(opt_entries, OPT_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0)) {
1437                                 switch (selected_id) {
1438                                         case MA_OPT_RENDERER:
1439                                                 if ((PicoOpt & 0x10) || !(currentConfig.EmuOpt & 0x80)) {
1440                                                         PicoOpt &= ~0x10;
1441                                                         currentConfig.EmuOpt |=  0x80;
1442                                                 } else {
1443                                                         PicoOpt |=  0x10;
1444                                                         currentConfig.EmuOpt &= ~0x80;
1445                                                 }
1446                                                 break;
1447                                         case MA_OPT_SOUND_QUALITY:
1448                                                 PsndRate = sndrate_prevnext(PsndRate, inp & BTN_RIGHT);
1449                                                 break;
1450                                         case MA_OPT_REGION:
1451                                                 region_prevnext(inp & BTN_RIGHT);
1452                                                 break;
1453                                         case MA_OPT_CONFIRM_STATES: {
1454                                                          int n = ((currentConfig.EmuOpt>>9)&1) | ((currentConfig.EmuOpt>>10)&2);
1455                                                          n += (inp & BTN_LEFT) ? -1 : 1;
1456                                                          if (n < 0) n = 0; else if (n > 3) n = 3;
1457                                                          n |= n << 1; n &= ~2;
1458                                                          currentConfig.EmuOpt &= ~0xa00;
1459                                                          currentConfig.EmuOpt |= n << 9;
1460                                                          break;
1461                                                  }
1462                                         case MA_OPT_SAVE_SLOT:
1463                                                  if (inp & BTN_RIGHT) {
1464                                                          state_slot++; if (state_slot > 9) state_slot = 0;
1465                                                  } else {state_slot--; if (state_slot < 0) state_slot = 9;
1466                                                  }
1467                                                  break;
1468                                         case MA_OPT_CPU_CLOCKS:
1469                                                  while ((inp = psp_pad_read(0)) & (BTN_LEFT|BTN_RIGHT)) {
1470                                                          currentConfig.CPUclock += (inp & BTN_LEFT) ? -1 : 1;
1471                                                          if (currentConfig.CPUclock <  19) currentConfig.CPUclock = 19;
1472                                                          if (currentConfig.CPUclock > 333) currentConfig.CPUclock = 333;
1473                                                          draw_menu_options(menu_sel); // will wait vsync
1474                                                  }
1475                                                  break;
1476                                         case MA_OPT_SAVECFG:
1477                                         case MA_OPT_SAVECFG_GAME:
1478                                         case MA_OPT_LOADCFG:
1479                                                  config_slot += (inp&BTN_RIGHT) ? 1 : -1;
1480                                                  if (config_slot > 9) config_slot = 0;
1481                                                  if (config_slot < 0) config_slot = 9;
1482                                                  me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_LOADCFG, config_slot != config_slot_current);
1483                                                  menu_sel_max = me_count_enabled(opt_entries, OPT_ENTRY_COUNT) - 1;
1484                                                  if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1485                                                  break;
1486                                         default:
1487                                                 //lprintf("%s: something unknown selected (%i)\n", __FUNCTION__, selected_id);
1488                                                 break;
1489                                 }
1490                         }
1491                 }
1492                 if (inp & BTN_CIRCLE) {
1493                         if (!me_process(opt_entries, OPT_ENTRY_COUNT, selected_id, 1))
1494                         {
1495                                 switch (selected_id)
1496                                 {
1497                                         case MA_OPT_DISP_OPTS:
1498                                                 dispmenu_loop_options();
1499                                                 break;
1500                                         case MA_OPT_SCD_OPTS:
1501                                                 cd_menu_loop_options();
1502                                                 if (engineState == PGS_ReloadRom)
1503                                                         return 0; // test BIOS
1504                                                 break;
1505                                         case MA_OPT_ADV_OPTS:
1506                                                 amenu_loop_options();
1507                                                 break;
1508                                         case MA_OPT_SAVECFG: // done (update and write)
1509                                                 menu_options_save();
1510                                                 if (emu_WriteConfig(0)) strcpy(menuErrorMsg, "config saved");
1511                                                 else strcpy(menuErrorMsg, "failed to write config");
1512                                                 return 1;
1513                                         case MA_OPT_SAVECFG_GAME: // done (update and write for current game)
1514                                                 menu_options_save();
1515                                                 if (emu_WriteConfig(1)) strcpy(menuErrorMsg, "config saved");
1516                                                 else strcpy(menuErrorMsg, "failed to write config");
1517                                                 return 1;
1518                                         case MA_OPT_LOADCFG:
1519                                                 ret = emu_ReadConfig(1, 1);
1520                                                 if (!ret) ret = emu_ReadConfig(0, 1);
1521                                                 if (ret)  strcpy(menuErrorMsg, "config loaded");
1522                                                 else      strcpy(menuErrorMsg, "failed to load config");
1523                                                 return 1;
1524                                         default:
1525                                                 //lprintf("%s: something unknown selected (%i)\n", __FUNCTION__, selected_id);
1526                                                 break;
1527                                 }
1528                         }
1529                 }
1530                 if(inp & BTN_X) {
1531                         menu_options_save();
1532                         return 0;  // done (update, no write)
1533                 }
1534         }
1535 }
1536
1537 // -------------- credits --------------
1538
1539 static void draw_menu_credits(void)
1540 {
1541         int tl_x = 80+15, tl_y = 16+64, y;
1542         menu_draw_begin();
1543
1544         text_out16(tl_x, 16+20, "PicoDrive v" VERSION " (c) notaz, 2006-2008");
1545
1546         y = tl_y;
1547         text_out16(tl_x, y, "Credits:");
1548         text_out16(tl_x, (y+=10), "fDave: base code of PicoDrive");
1549         text_out16(tl_x, (y+=10), "Chui: Fame/C");
1550         text_out16(tl_x, (y+=10), "NJ: CZ80");
1551         text_out16(tl_x, (y+=10), "MAME devs: YM2612 and SN76496 cores");
1552         text_out16(tl_x, (y+=10), "ps2dev.org people: PSP SDK/code");
1553         text_out16(tl_x, (y+=10), "ketchupgun: skin design");
1554
1555         text_out16(tl_x, (y+=20), "special thanks (for docs, ideas):");
1556         text_out16(tl_x, (y+=10), " Charles MacDonald, Haze,");
1557         text_out16(tl_x, (y+=10), " Stephane Dallongeville,");
1558         text_out16(tl_x, (y+=10), " Lordus, Exophase, Rokas,");
1559         text_out16(tl_x, (y+=10), " Nemesis, Tasco Deluxe");
1560
1561         menu_draw_end();
1562 }
1563
1564
1565 // -------------- root menu --------------
1566
1567 menu_entry main_entries[] =
1568 {
1569         { "Resume game",        MB_NONE, MA_MAIN_RESUME_GAME, NULL, 0, 0, 0, 0 },
1570         { "Save State",         MB_NONE, MA_MAIN_SAVE_STATE,  NULL, 0, 0, 0, 0 },
1571         { "Load State",         MB_NONE, MA_MAIN_LOAD_STATE,  NULL, 0, 0, 0, 0 },
1572         { "Reset game",         MB_NONE, MA_MAIN_RESET_GAME,  NULL, 0, 0, 0, 0 },
1573         { "Load new ROM/ISO",   MB_NONE, MA_MAIN_LOAD_ROM,    NULL, 0, 0, 0, 1 },
1574         { "Change options",     MB_NONE, MA_MAIN_OPTIONS,     NULL, 0, 0, 0, 1 },
1575         { "Configure controls", MB_NONE, MA_MAIN_CONTROLS,    NULL, 0, 0, 0, 1 },
1576         { "Credits",            MB_NONE, MA_MAIN_CREDITS,     NULL, 0, 0, 0, 1 },
1577         { "Patches / GameGenie",MB_NONE, MA_MAIN_PATCHES,     NULL, 0, 0, 0, 0 },
1578         { "Exit",               MB_NONE, MA_MAIN_EXIT,        NULL, 0, 0, 0, 1 }
1579 };
1580
1581 #define MAIN_ENTRY_COUNT (sizeof(main_entries) / sizeof(main_entries[0]))
1582
1583 static void draw_menu_root(int menu_sel)
1584 {
1585         const int tl_x = 86+70, tl_y = 16+70;
1586         char *stat = NULL;
1587
1588         menu_draw_begin();
1589
1590         if ((currentConfig.EmuOpt&0x20000) && (stat = psp_get_status_line()))
1591                 text_out16(287, 12, "%s", stat);
1592
1593         text_out16(tl_x, 48, "PicoDrive v" VERSION);
1594
1595         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 146);
1596
1597         me_draw(main_entries, MAIN_ENTRY_COUNT, tl_x, tl_y, NULL, NULL);
1598
1599         // error
1600         if (menuErrorMsg[0])
1601                 text_out16(10, 252, menuErrorMsg);
1602         menu_draw_end();
1603 }
1604
1605
1606 static void menu_loop_root(void)
1607 {
1608         static int menu_sel = 0;
1609         int ret, menu_sel_max;
1610         unsigned long inp = 0;
1611
1612         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_RESUME_GAME, rom_loaded);
1613         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_SAVE_STATE,  rom_loaded);
1614         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_LOAD_STATE,  rom_loaded);
1615         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_RESET_GAME,  rom_loaded);
1616         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_PATCHES,     PicoPatches != NULL);
1617
1618         menu_sel_max = me_count_enabled(main_entries, MAIN_ENTRY_COUNT) - 1;
1619         if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1620
1621         // mp3 errors?
1622         if (mp3_last_error != 0) {
1623                 if (mp3_last_error == -1)
1624                      sprintf(menuErrorMsg, "Unsupported mp3 format, use 44kHz stereo");
1625                 else sprintf(menuErrorMsg, "mp3 init failed, code %08x", mp3_last_error);
1626                 mp3_last_error = 0;
1627         }
1628
1629         /* make sure action buttons are not pressed on entering menu */
1630         draw_menu_root(menu_sel);
1631
1632         while (psp_pad_read(1) & (BTN_X|BTN_CIRCLE|BTN_SELECT)) psp_msleep(50);
1633
1634         for (;;)
1635         {
1636                 draw_menu_root(menu_sel);
1637                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X|BTN_CIRCLE|BTN_SELECT|BTN_L|BTN_R, 0);
1638                 if(inp & BTN_UP  )  { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1639                 if(inp & BTN_DOWN)  { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1640                 if((inp & (BTN_L|BTN_R)) == (BTN_L|BTN_R)) debug_menu_loop();
1641                 if( inp & (BTN_SELECT|BTN_X)) {
1642                         if (rom_loaded) {
1643                                 while (psp_pad_read(1) & (BTN_SELECT|BTN_X)) psp_msleep(50); // wait until released
1644                                 engineState = PGS_Running;
1645                                 break;
1646                         }
1647                 }
1648                 if(inp & BTN_CIRCLE)  {
1649                         menuErrorMsg[0] = 0; // clear error msg
1650                         switch (me_index2id(main_entries, MAIN_ENTRY_COUNT, menu_sel))
1651                         {
1652                                 case MA_MAIN_RESUME_GAME:
1653                                         if (rom_loaded) {
1654                                                 while (psp_pad_read(1) & BTN_CIRCLE) psp_msleep(50);
1655                                                 engineState = PGS_Running;
1656                                                 return;
1657                                         }
1658                                         break;
1659                                 case MA_MAIN_SAVE_STATE:
1660                                         if (rom_loaded) {
1661                                                 if(savestate_menu_loop(0))
1662                                                         continue;
1663                                                 engineState = PGS_Running;
1664                                                 return;
1665                                         }
1666                                         break;
1667                                 case MA_MAIN_LOAD_STATE:
1668                                         if (rom_loaded) {
1669                                                 if(savestate_menu_loop(1))
1670                                                         continue;
1671                                                 while (psp_pad_read(1) & BTN_CIRCLE) psp_msleep(50);
1672                                                 engineState = PGS_Running;
1673                                                 return;
1674                                         }
1675                                         break;
1676                                 case MA_MAIN_RESET_GAME:
1677                                         if (rom_loaded) {
1678                                                 emu_ResetGame();
1679                                                 while (psp_pad_read(1) & BTN_CIRCLE) psp_msleep(50);
1680                                                 engineState = PGS_Running;
1681                                                 return;
1682                                         }
1683                                         break;
1684                                 case MA_MAIN_LOAD_ROM:
1685                                 {
1686                                         char curr_path[PATH_MAX], *selfname;
1687                                         FILE *tstf;
1688                                         if ( (tstf = fopen(lastRomFile, "rb")) )
1689                                         {
1690                                                 fclose(tstf);
1691                                                 strcpy(curr_path, lastRomFile);
1692                                         }
1693                                         else
1694                                                 getcwd(curr_path, PATH_MAX);
1695                                         selfname = romsel_loop(curr_path);
1696                                         if (selfname) {
1697                                                 lprintf("selected file: %s\n", selfname);
1698                                                 engineState = PGS_ReloadRom;
1699                                                 return;
1700                                         }
1701                                         break;
1702                                 }
1703                                 case MA_MAIN_OPTIONS:
1704                                         ret = menu_loop_options();
1705                                         if (ret == 1) continue; // status update
1706                                         if (engineState == PGS_ReloadRom)
1707                                                 return; // BIOS test
1708                                         break;
1709                                 case MA_MAIN_CONTROLS:
1710                                         kc_sel_loop();
1711                                         break;
1712                                 case MA_MAIN_CREDITS:
1713                                         draw_menu_credits();
1714                                         psp_msleep(500);
1715                                         inp = 0;
1716                                         while (!(inp & (BTN_X|BTN_CIRCLE)))
1717                                                 inp = wait_for_input(BTN_X|BTN_CIRCLE, 0);
1718                                         break;
1719                                 case MA_MAIN_EXIT:
1720                                         engineState = PGS_Quit;
1721                                         return;
1722                                 case MA_MAIN_PATCHES:
1723                                         if (rom_loaded && PicoPatches) {
1724                                                 patches_menu_loop();
1725                                                 PicoPatchApply();
1726                                                 strcpy(menuErrorMsg, "Patches applied");
1727                                                 continue;
1728                                         }
1729                                         break;
1730                                 default:
1731                                         lprintf("%s: something unknown selected\n", __FUNCTION__);
1732                                         break;
1733                         }
1734                 }
1735         }
1736 }
1737
1738 // warning: alignment
1739 static void menu_darken_bg(void *dst, const void *src, int pixels, int darker)
1740 {
1741         unsigned int *dest = dst;
1742         const unsigned int *srce = src;
1743         pixels /= 2;
1744         if (darker)
1745         {
1746                 while (pixels--)
1747                 {
1748                         unsigned int p = *srce++;
1749                         *dest++ = ((p&0xf79ef79e)>>1) - ((p&0xc618c618)>>3);
1750                 }
1751         }
1752         else
1753         {
1754                 while (pixels--)
1755                 {
1756                         unsigned int p = *srce++;
1757                         *dest++ = (p&0xf79ef79e)>>1;
1758                 }
1759         }
1760 }
1761
1762 static void menu_prepare_bg(int use_game_bg, int use_fg)
1763 {
1764         if (use_game_bg)
1765         {
1766                 // darken the active framebuffer
1767                 unsigned short *dst = bg_buffer;
1768                 unsigned short *src = use_fg ? psp_video_get_active_fb() : psp_screen;
1769                 int i;
1770                 for (i = 272; i > 0; i--, dst += 480, src += 512)
1771                         menu_darken_bg(dst, src, 480, 1);
1772                 //memset32_uncached((int *)(bg_buffer + 480*264), 0, 480*8*2/4);
1773         }
1774         else
1775         {
1776                 // should really only happen once, on startup..
1777                 memset32_uncached((int *)(void *)bg_buffer, 0, sizeof(bg_buffer)/4);
1778                 readpng(bg_buffer, "skin/background.png", READPNG_BG);
1779         }
1780         sceKernelDcacheWritebackAll();
1781 }
1782
1783 static void menu_gfx_prepare(void)
1784 {
1785         menu_prepare_bg(rom_loaded, 1);
1786
1787         menu_draw_begin();
1788         menu_draw_end();
1789 }
1790
1791
1792 void menu_loop(void)
1793 {
1794         menu_gfx_prepare();
1795
1796         menu_loop_root();
1797
1798         menuErrorMsg[0] = 0;
1799 }
1800
1801
1802 // --------- CD tray close menu ----------
1803
1804 static void draw_menu_tray(int menu_sel)
1805 {
1806         int tl_x = 70, tl_y = 90, y;
1807
1808         menu_draw_begin();
1809
1810         text_out16(tl_x, 20, "The unit is about to");
1811         text_out16(tl_x, 30, "close the CD tray.");
1812
1813         y = tl_y;
1814         text_out16(tl_x, y,       "Load new CD image");
1815         text_out16(tl_x, (y+=10), "Insert nothing");
1816
1817         // draw cursor
1818         text_out16(tl_x - 16, tl_y + menu_sel*10, ">");
1819         // error
1820         if (menuErrorMsg[0]) text_out16(5, 226, menuErrorMsg);
1821         menu_draw_end();
1822 }
1823
1824
1825 int menu_loop_tray(void)
1826 {
1827         int menu_sel = 0, menu_sel_max = 1;
1828         unsigned long inp = 0;
1829         char curr_path[PATH_MAX], *selfname;
1830         FILE *tstf;
1831
1832         menu_gfx_prepare();
1833
1834         if ( (tstf = fopen(lastRomFile, "rb")) )
1835         {
1836                 fclose(tstf);
1837                 strcpy(curr_path, lastRomFile);
1838         }
1839         else
1840         {
1841                 getcwd(curr_path, PATH_MAX);
1842         }
1843
1844         /* make sure action buttons are not pressed on entering menu */
1845         draw_menu_tray(menu_sel);
1846         while (psp_pad_read(1) & BTN_CIRCLE) psp_msleep(50);
1847
1848         for (;;)
1849         {
1850                 draw_menu_tray(menu_sel);
1851                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_CIRCLE, 0);
1852                 if(inp & BTN_UP  )  { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1853                 if(inp & BTN_DOWN)  { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1854                 if(inp & BTN_CIRCLE)  {
1855                         switch (menu_sel) {
1856                                 case 0: // select image
1857                                         selfname = romsel_loop(curr_path);
1858                                         if (selfname) {
1859                                                 int ret = -1;
1860                                                 cd_img_type cd_type;
1861                                                 cd_type = emu_cdCheck(NULL);
1862                                                 if (cd_type != CIT_NOT_CD)
1863                                                         ret = Insert_CD(romFileName, cd_type);
1864                                                 if (ret != 0) {
1865                                                         sprintf(menuErrorMsg, "Load failed, invalid CD image?");
1866                                                         lprintf("%s\n", menuErrorMsg);
1867                                                         continue;
1868                                                 }
1869                                                 engineState = PGS_RestartRun;
1870                                                 return 1;
1871                                         }
1872                                         break;
1873                                 case 1: // insert nothing
1874                                         engineState = PGS_RestartRun;
1875                                         return 0;
1876                         }
1877                 }
1878                 menuErrorMsg[0] = 0; // clear error msg
1879         }
1880 }
1881
1882