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