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