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