make romdir saving not GP2X specific
[gpsp.git] / main.c
1 /* gameplaySP
2  *
3  * Copyright (C) 2006 Exophase <exophase@gmail.com>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of
8  * the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19
20 #include "common.h"
21
22 #ifdef PSP_BUILD
23
24 //PSP_MODULE_INFO("gpSP", 0x1000, 0, 6);
25 //PSP_MAIN_THREAD_ATTR(THREAD_ATTR_USER);
26
27 void vblank_interrupt_handler(u32 sub, u32 *parg);
28
29 #endif
30
31 timer_type timer[4];
32
33 //debug_state current_debug_state = COUNTDOWN_BREAKPOINT;
34 //debug_state current_debug_state = PC_BREAKPOINT;
35 u32 breakpoint_value = 0x7c5000;
36 debug_state current_debug_state = RUN;
37 //debug_state current_debug_state = STEP_RUN;
38
39 //u32 breakpoint_value = 0;
40
41 frameskip_type current_frameskip_type = auto_frameskip;
42 u32 global_cycles_per_instruction = 1;
43 u32 random_skip = 0;
44 u32 fps_debug = 0;
45
46 u32 frameskip_value = 2;
47
48 u64 last_frame_interval_timestamp;
49
50 u32 skip_next_frame = 0;
51
52 u32 frameskip_counter = 0;
53
54 u32 cpu_ticks = 0;
55 u32 frame_ticks = 0;
56
57 u32 execute_cycles = 960;
58 s32 video_count = 960;
59 u32 ticks;
60
61 u32 arm_frame = 0;
62 u32 thumb_frame = 0;
63 u32 last_frame = 0;
64
65 u32 cycle_memory_access = 0;
66 u32 cycle_pc_relative_access = 0;
67 u32 cycle_sp_relative_access = 0;
68 u32 cycle_block_memory_access = 0;
69 u32 cycle_block_memory_sp_access = 0;
70 u32 cycle_block_memory_words = 0;
71 u32 cycle_dma16_words = 0;
72 u32 cycle_dma32_words = 0;
73 u32 flush_ram_count = 0;
74 u32 gbc_update_count = 0;
75 u32 oam_update_count = 0;
76
77 u32 synchronize_flag = 1;
78
79 u32 update_backup_flag = 1;
80 #ifdef GP2X_BUILD
81 u32 clock_speed = 200;
82 #else
83 u32 clock_speed = 333;
84 #endif
85 char main_path[512];
86
87 void trigger_ext_event();
88
89 #define check_count(count_var)                                                \
90   if(count_var < execute_cycles)                                              \
91     execute_cycles = count_var;                                               \
92
93 #define check_timer(timer_number)                                             \
94   if(timer[timer_number].status == TIMER_PRESCALE)                            \
95     check_count(timer[timer_number].count);                                   \
96
97 #define update_timer(timer_number)                                            \
98   if(timer[timer_number].status != TIMER_INACTIVE)                            \
99   {                                                                           \
100     if(timer[timer_number].status != TIMER_CASCADE)                           \
101     {                                                                         \
102       timer[timer_number].count -= execute_cycles;                            \
103       io_registers[REG_TM##timer_number##D] =                                 \
104        -(timer[timer_number].count >> timer[timer_number].prescale);          \
105     }                                                                         \
106                                                                               \
107     if(timer[timer_number].count <= 0)                                        \
108     {                                                                         \
109       if(timer[timer_number].irq == TIMER_TRIGGER_IRQ)                        \
110         irq_raised |= IRQ_TIMER##timer_number;                                \
111                                                                               \
112       if((timer_number != 3) &&                                               \
113        (timer[timer_number + 1].status == TIMER_CASCADE))                     \
114       {                                                                       \
115         timer[timer_number + 1].count--;                                      \
116         io_registers[REG_TM0D + (timer_number + 1) * 2] =                     \
117          -(timer[timer_number + 1].count);                                    \
118       }                                                                       \
119                                                                               \
120       if(timer_number < 2)                                                    \
121       {                                                                       \
122         if(timer[timer_number].direct_sound_channels & 0x01)                  \
123           sound_timer(timer[timer_number].frequency_step, 0);                 \
124                                                                               \
125         if(timer[timer_number].direct_sound_channels & 0x02)                  \
126           sound_timer(timer[timer_number].frequency_step, 1);                 \
127       }                                                                       \
128                                                                               \
129       timer[timer_number].count +=                                            \
130        (timer[timer_number].reload << timer[timer_number].prescale);          \
131     }                                                                         \
132   }                                                                           \
133
134 static const char *file_ext[] = { ".gba", ".bin", ".zip", NULL };
135
136 #ifdef PSP_BUILD
137 static void ChangeWorkingDirectory(char *exe)
138 {
139 #ifndef _WIN32_WCE
140   char *s = strrchr(exe, '/');
141   if (s != NULL) {
142     *s = '\0';
143     chdir(exe);
144     *s = '/';
145   }
146 #endif
147 }
148
149 static void switch_to_romdir(void)
150 {
151   char buff[256];
152   int r;
153   
154   file_open(romdir_file, "romdir.txt", read);
155
156   if(file_check_valid(romdir_file))
157   {
158     r = file_read(romdir_file, buff, sizeof(buff) - 1);
159     if (r > 0)
160     {
161       buff[r] = 0;
162       while (r > 0 && isspace(buff[r-1]))
163         buff[--r] = 0;
164       chdir(buff);
165     }
166     file_close(romdir_file);
167   }
168 }
169
170 static void save_romdir(void)
171 {
172   char buff[512];
173   int r = -1;
174
175   snprintf(buff, sizeof(buff), "%s" PATH_SEPARATOR "romdir.txt", main_path);
176   file_open(romdir_file, buff, write);
177
178   if(file_check_valid(romdir_file))
179   {
180     if (getcwd(buff, sizeof(buff)))
181     {
182       file_write(romdir_file, buff, strlen(buff));
183     }
184     file_close(romdir_file);
185   }
186 }
187 #else
188 void ChangeWorkingDirectory(char *exe) {}
189 static void switch_to_romdir(void) {}
190 static void save_romdir(void) {}
191 #endif
192
193 void init_main()
194 {
195   u32 i;
196
197   skip_next_frame = 0;
198
199   for(i = 0; i < 4; i++)
200   {
201     dma[i].start_type = DMA_INACTIVE;
202     dma[i].direct_sound_channel = DMA_NO_DIRECT_SOUND;
203     timer[i].status = TIMER_INACTIVE;
204     timer[i].reload = 0x10000;
205     timer[i].stop_cpu_ticks = 0;
206   }
207
208   timer[0].direct_sound_channels = TIMER_DS_CHANNEL_BOTH;
209   timer[1].direct_sound_channels = TIMER_DS_CHANNEL_NONE;
210
211   cpu_ticks = 0;
212   frame_ticks = 0;
213
214   execute_cycles = 960;
215   video_count = 960;
216
217   flush_translation_cache_rom();
218   flush_translation_cache_ram();
219   flush_translation_cache_bios();
220 }
221
222 int main(int argc, char *argv[])
223 {
224   char bios_filename[512];
225   int ret;
226
227 #ifdef PSP_BUILD
228   sceKernelRegisterSubIntrHandler(PSP_VBLANK_INT, 0,
229    vblank_interrupt_handler, NULL);
230   sceKernelEnableSubIntr(PSP_VBLANK_INT, 0);
231 #endif
232
233   init_gamepak_buffer();
234
235   // Copy the directory path of the executable into main_path
236
237   // ChangeWorkingDirectory will null out the filename out of the path
238   ChangeWorkingDirectory(argv[0]);
239
240   getcwd(main_path, 512);
241
242 #ifdef PSP_BUILD
243   delay_us(2500000);
244 #endif
245
246 #ifndef PC_BUILD
247   gpsp_plat_init();
248 #endif
249   load_config_file();
250
251   gamepak_filename[0] = 0;
252
253   init_video();
254
255   sprintf(bios_filename, "%s" PATH_SEPARATOR "%s", main_path, "gba_bios.bin");
256   ret = load_bios(bios_filename);
257   if (ret != 0)
258     ret = load_bios("gba_bios.bin");
259   if (ret != 0)
260   {
261     gui_action_type gui_action = CURSOR_NONE;
262
263     debug_screen_start();
264     debug_screen_printl("Sorry, but gpSP requires a Gameboy Advance BIOS   ");
265     debug_screen_printl("image to run correctly. Make sure to get an       ");
266     debug_screen_printl("authentic one, it'll be exactly 16384 bytes large ");
267     debug_screen_printl("and should have the following md5sum value:       ");
268     debug_screen_printl("                                                  ");
269     debug_screen_printl("a860e8c0b6d573d191e4ec7db1b1e4f6                  ");
270     debug_screen_printl("                                                  ");
271     debug_screen_printl("When you do get it name it gba_bios.bin and put it");
272 #ifdef PND_BUILD
273     debug_screen_printl("in <CD card>/pandora/appdata/gpsp/ .              ");
274 #else
275     debug_screen_printl("in the same directory as gpSP.                    ");
276 #endif
277     debug_screen_printl("                                                  ");
278     debug_screen_printl("Press any button to exit.                         ");
279
280     debug_screen_update();
281
282     while(gui_action == CURSOR_NONE)
283     {
284       gui_action = get_gui_input();
285       delay_us(15000);
286     }
287
288     debug_screen_end();
289
290     quit();
291   }
292
293   if(bios_rom[0] != 0x18)
294   {
295     gui_action_type gui_action = CURSOR_NONE;
296
297     debug_screen_start();
298     debug_screen_printl("You have an incorrect BIOS image.                 ");
299     debug_screen_printl("While many games will work fine, some will not. It");
300     debug_screen_printl("is strongly recommended that you obtain the       ");
301     debug_screen_printl("correct BIOS file. Do NOT report any bugs if you  ");
302     debug_screen_printl("are seeing this message.                          ");
303     debug_screen_printl("                                                  ");
304     debug_screen_printl("Press any button to resume, at your own risk.     ");
305
306     debug_screen_update();
307
308     while(gui_action == CURSOR_NONE)
309     {
310       gui_action = get_gui_input();
311       delay_us(15000);
312     }
313
314     debug_screen_end();
315   }
316
317   init_main();
318   init_sound();
319
320   init_input();
321
322   video_resolution_large();
323
324   if(argc > 1)
325   {
326     switch_to_romdir();
327     if(load_gamepak(argv[1]) == -1)
328     {
329 #ifndef PSP_BUILD
330       printf("Failed to load gamepak %s, exiting.\n", argv[1]);
331 #endif
332       exit(-1);
333     }
334
335     set_gba_resolution(screen_scale);
336     video_resolution_small();
337
338     init_cpu();
339     init_memory();
340   }
341   else
342   {
343     char load_filename[512];
344     if(load_file(file_ext, load_filename) == -1)
345     {
346       menu(copy_screen());
347     }
348     else
349     {
350       if(load_gamepak(load_filename) == -1)
351       {
352 #ifndef PSP_BUILD
353         printf("Failed to load gamepak %s, exiting.\n", load_filename);
354 #endif
355         exit(-1);
356       }
357
358       set_clock_speed();
359       set_gba_resolution(screen_scale);
360       video_resolution_small();
361
362       init_cpu();
363       init_memory();
364     }
365   }
366
367   last_frame = 0;
368
369   // We'll never actually return from here.
370
371 #ifdef PSP_BUILD
372   execute_arm_translate(execute_cycles);
373 #else
374
375 /*  u8 current_savestate_filename[512];
376   get_savestate_filename_noshot(savestate_slot,
377    current_savestate_filename);
378   load_state(current_savestate_filename); */
379
380 //  debug_on();
381
382   if(argc > 2)
383   {
384     current_debug_state = COUNTDOWN_BREAKPOINT;
385     breakpoint_value = strtol(argv[2], NULL, 16);
386   }
387
388   trigger_ext_event();
389
390   execute_arm_translate(execute_cycles);
391   execute_arm(execute_cycles);
392 #endif
393   return 0;
394 }
395
396 void print_memory_stats(u32 *counter, u32 *region_stats, char *stats_str)
397 {
398   u32 other_region_counter = region_stats[0x1] + region_stats[0xE] +
399    region_stats[0xF];
400   u32 rom_region_counter = region_stats[0x8] + region_stats[0x9] +
401    region_stats[0xA] + region_stats[0xB] + region_stats[0xC] +
402    region_stats[0xD];
403   u32 _counter = *counter;
404
405   printf("memory access stats: %s (out of %d)\n", stats_str, _counter);
406   printf("bios: %f%%\tiwram: %f%%\tewram: %f%%\tvram: %f\n",
407    region_stats[0x0] * 100.0 / _counter, region_stats[0x3] * 100.0 /
408    _counter,
409    region_stats[0x2] * 100.0 / _counter, region_stats[0x6] * 100.0 /
410    _counter);
411
412   printf("oam: %f%%\tpalette: %f%%\trom: %f%%\tother: %f%%\n",
413    region_stats[0x7] * 100.0 / _counter, region_stats[0x5] * 100.0 /
414    _counter,
415    rom_region_counter * 100.0 / _counter, other_region_counter * 100.0 /
416    _counter);
417
418   *counter = 0;
419   memset(region_stats, 0, sizeof(u32) * 16);
420 }
421
422 u32 event_cycles = 0;
423 const u32 event_cycles_trigger = 60 * 5;
424 u32 no_alpha = 0;
425
426 void trigger_ext_event()
427 {
428   static u32 event_number = 0;
429   static u64 benchmark_ticks[16];
430   u64 new_ticks;
431   char current_savestate_filename[512];
432
433   return;
434
435   if(event_number)
436   {
437     get_ticks_us(&new_ticks);
438     benchmark_ticks[event_number - 1] =
439      new_ticks - benchmark_ticks[event_number - 1];
440   }
441
442   current_frameskip_type = no_frameskip;
443   no_alpha = 0;
444   synchronize_flag = 0;
445
446   get_savestate_filename_noshot(savestate_slot,
447    current_savestate_filename);
448   load_state(current_savestate_filename);
449
450   switch(event_number)
451   {
452     case 0:
453       // Full benchmark, run normally
454       break;
455
456     case 1:
457       // No alpha blending
458       no_alpha = 1;
459       break;
460
461     case 2:
462       // No video benchmark
463       // Set frameskip really high + manual
464       current_frameskip_type = manual_frameskip;
465       frameskip_value = 1000000;
466       break;
467
468     case 3:
469       // No CPU benchmark
470       // Put CPU in halt mode, put it in IRQ mode with interrupts off
471       reg[CPU_HALT_STATE] = CPU_HALT;
472       reg[REG_CPSR] = 0xD2;
473       break;
474
475     case 4:
476       // No CPU or video benchmark
477       reg[CPU_HALT_STATE] = CPU_HALT;
478       reg[REG_CPSR] = 0xD2;
479       current_frameskip_type = manual_frameskip;
480       frameskip_value = 1000000;
481       break;
482
483     case 5:
484     {
485       // Done
486       char *print_strings[] =
487       {
488         "Full test   ",
489         "No blending ",
490         "No video    ",
491         "No CPU      ",
492         "No CPU/video",
493         "CPU speed   ",
494         "Video speed ",
495         "Alpha cost  "
496       };
497       u32 i;
498
499       benchmark_ticks[6] = benchmark_ticks[0] - benchmark_ticks[2];
500       benchmark_ticks[5] = benchmark_ticks[0] - benchmark_ticks[4] -
501        benchmark_ticks[6];
502       benchmark_ticks[7] = benchmark_ticks[0] - benchmark_ticks[1];
503
504       printf("Benchmark results (%d frames): \n", event_cycles_trigger);
505       for(i = 0; i < 8; i++)
506       {
507         printf("   %s: %d ms (%f ms per frame)\n",
508          print_strings[i], (u32)benchmark_ticks[i] / 1000,
509          (float)(benchmark_ticks[i] / (1000.0 * event_cycles_trigger)));
510         if(i == 4)
511           printf("\n");
512       }
513       quit();
514     }
515   }
516
517   event_cycles = 0;
518
519   get_ticks_us(benchmark_ticks + event_number);
520   event_number++;
521 }
522
523 static u32 fps = 60;
524 static u32 frames_drawn = 60;
525
526 u32 update_gba()
527 {
528   irq_type irq_raised = IRQ_NONE;
529
530   do
531   {
532     cpu_ticks += execute_cycles;
533
534     reg[CHANGED_PC_STATUS] = 0;
535
536     if(gbc_sound_update)
537     {
538       gbc_update_count++;
539       update_gbc_sound(cpu_ticks);
540       gbc_sound_update = 0;
541     }
542
543     update_timer(0);
544     update_timer(1);
545     update_timer(2);
546     update_timer(3);
547
548     video_count -= execute_cycles;
549
550     if(video_count <= 0)
551     {
552       u32 vcount = io_registers[REG_VCOUNT];
553       u32 dispstat = io_registers[REG_DISPSTAT];
554
555       if((dispstat & 0x02) == 0)
556       {
557         // Transition from hrefresh to hblank
558         video_count += (272);
559         dispstat |= 0x02;
560
561         if((dispstat & 0x01) == 0)
562         {
563           u32 i;
564           if(oam_update)
565             oam_update_count++;
566
567           if(no_alpha)
568             io_registers[REG_BLDCNT] = 0;
569           update_scanline();
570
571           // If in visible area also fire HDMA
572           for(i = 0; i < 4; i++)
573           {
574             if(dma[i].start_type == DMA_START_HBLANK)
575               dma_transfer(dma + i);
576           }
577         }
578
579         if(dispstat & 0x10)
580           irq_raised |= IRQ_HBLANK;
581       }
582       else
583       {
584         // Transition from hblank to next line
585         video_count += 960;
586         dispstat &= ~0x02;
587
588         vcount++;
589
590         if(vcount == 160)
591         {
592           // Transition from vrefresh to vblank
593           u32 i;
594
595           dispstat |= 0x01;
596           if(dispstat & 0x8)
597           {
598             irq_raised |= IRQ_VBLANK;
599           }
600
601           affine_reference_x[0] =
602            (s32)(address32(io_registers, 0x28) << 4) >> 4;
603           affine_reference_y[0] =
604            (s32)(address32(io_registers, 0x2C) << 4) >> 4;
605           affine_reference_x[1] =
606            (s32)(address32(io_registers, 0x38) << 4) >> 4;
607           affine_reference_y[1] =
608            (s32)(address32(io_registers, 0x3C) << 4) >> 4;
609
610           for(i = 0; i < 4; i++)
611           {
612             if(dma[i].start_type == DMA_START_VBLANK)
613               dma_transfer(dma + i);
614           }
615         }
616         else
617
618         if(vcount == 228)
619         {
620           // Transition from vblank to next screen
621           dispstat &= ~0x01;
622           frame_ticks++;
623
624   #ifdef PC_BUILD
625 /*        printf("frame update (%x), %d instructions total, %d RAM flushes\n",
626            reg[REG_PC], instruction_count - last_frame, flush_ram_count);
627           last_frame = instruction_count;
628 */
629 /*          printf("%d gbc audio updates\n", gbc_update_count);
630           printf("%d oam updates\n", oam_update_count); */
631           gbc_update_count = 0;
632           oam_update_count = 0;
633           flush_ram_count = 0;
634   #endif
635
636           if(update_input())
637             continue;
638
639           update_gbc_sound(cpu_ticks);
640
641           if(fps_debug)
642           {
643             char print_buffer[32];
644             sprintf(print_buffer, "%2d (%2d)", fps, frames_drawn);
645             print_string(print_buffer, 0xFFFF, 0x000, 0, 0);
646           }
647           if(!synchronize_flag)
648             print_string("-FF-", 0xFFFF, 0x000, 216, 0);
649
650           update_screen();
651
652           synchronize();
653
654           if(update_backup_flag)
655             update_backup();
656
657           process_cheats();
658
659           event_cycles++;
660           if(event_cycles == event_cycles_trigger)
661           {
662             trigger_ext_event();
663             continue;
664           }
665
666           vcount = 0;
667         }
668
669         if(vcount == (dispstat >> 8))
670         {
671           // vcount trigger
672           dispstat |= 0x04;
673           if(dispstat & 0x20)
674           {
675             irq_raised |= IRQ_VCOUNT;
676           }
677         }
678         else
679         {
680           dispstat &= ~0x04;
681         }
682
683         io_registers[REG_VCOUNT] = vcount;
684       }
685       io_registers[REG_DISPSTAT] = dispstat;
686     }
687
688     if(irq_raised)
689       raise_interrupt(irq_raised);
690
691     execute_cycles = video_count;
692
693     check_timer(0);
694     check_timer(1);
695     check_timer(2);
696     check_timer(3);
697   } while(reg[CPU_HALT_STATE] != CPU_ACTIVE);
698
699   return execute_cycles;
700 }
701
702 #ifdef PSP_BUILD
703
704 u32 real_frame_count = 0;
705 u32 virtual_frame_count = 0;
706 u32 num_skipped_frames = 0;
707
708 void vblank_interrupt_handler(u32 sub, u32 *parg)
709 {
710   real_frame_count++;
711 }
712
713 void synchronize()
714 {
715   char char_buffer[64];
716   u64 new_ticks, time_delta;
717   s32 used_frameskip = frameskip_value;
718
719   if(!synchronize_flag)
720   {
721     used_frameskip = 4;
722     virtual_frame_count = real_frame_count - 1;
723   }
724
725   skip_next_frame = 0;
726
727   virtual_frame_count++;
728
729   if(real_frame_count >= virtual_frame_count)
730   {
731     if((real_frame_count > virtual_frame_count) &&
732      (current_frameskip_type == auto_frameskip) &&
733      (num_skipped_frames < frameskip_value))
734     {
735       skip_next_frame = 1;
736       num_skipped_frames++;
737     }
738     else
739     {
740       virtual_frame_count = real_frame_count;
741       num_skipped_frames = 0;
742     }
743
744     // Here so that the home button return will eventually work.
745     // If it's not running fullspeed anyway this won't really hurt
746     // it much more.
747
748     delay_us(1);
749   }
750   else
751   {
752     if(synchronize_flag)
753       sceDisplayWaitVblankStart();
754   }
755
756   if(current_frameskip_type == manual_frameskip)
757   {
758     frameskip_counter = (frameskip_counter + 1) %
759      (used_frameskip + 1);
760     if(random_skip)
761     {
762       if(frameskip_counter != (rand() % (used_frameskip + 1)))
763         skip_next_frame = 1;
764     }
765     else
766     {
767       if(frameskip_counter)
768         skip_next_frame = 1;
769     }
770   }
771
772 /*  sprintf(char_buffer, "%08d %08d %d %d %d\n",
773    real_frame_count, virtual_frame_count, num_skipped_frames,
774    real_frame_count - virtual_frame_count, skip_next_frame);
775   print_string(char_buffer, 0xFFFF, 0x0000, 0, 10); */
776
777 /*
778     sprintf(char_buffer, "%02d %02d %06d %07d", frameskip, (u32)ms_needed,
779      ram_translation_ptr - ram_translation_cache, rom_translation_ptr -
780      rom_translation_cache);
781     print_string(char_buffer, 0xFFFF, 0x0000, 0, 0);
782 */
783 }
784
785 #else
786
787 u32 real_frame_count = 0;
788 u32 virtual_frame_count = 0;
789 u32 num_skipped_frames = 0;
790 u32 interval_skipped_frames;
791 u32 frames;
792
793 const u32 frame_interval = 60;
794
795 void synchronize()
796 {
797   u64 new_ticks;
798   u64 time_delta;
799
800   get_ticks_us(&new_ticks);
801
802   skip_next_frame = 0;
803   virtual_frame_count++;
804
805   real_frame_count = (new_ticks * 3) / 50000;
806
807   if(real_frame_count >= virtual_frame_count)
808   {
809     if((real_frame_count > virtual_frame_count) &&
810      (current_frameskip_type == auto_frameskip) &&
811      (num_skipped_frames < frameskip_value))
812     {
813       skip_next_frame = 1;
814       num_skipped_frames++;
815     }
816     else
817     {
818       virtual_frame_count = real_frame_count;
819       num_skipped_frames = 0;
820     }
821   }
822   else if (synchronize_flag)
823   {
824 #if defined(PND_BUILD)
825     fb_wait_vsync();
826 #elif !defined(GP2X_BUILD) // sleeping on GP2X is a bad idea
827     delay_us((u64)virtual_frame_count * 50000 / 3 - new_ticks + 2);
828 #endif
829   }
830
831   frames++;
832
833   if(frames == frame_interval)
834   {
835     u32 new_fps;
836     u32 new_frames_drawn;
837
838     time_delta = new_ticks - last_frame_interval_timestamp;
839     new_fps = (u64)((u64)1000000 * (u64)frame_interval) / time_delta;
840     new_frames_drawn =
841      (frame_interval - interval_skipped_frames) * (60 / frame_interval);
842
843     // Left open for rolling averages
844     fps = new_fps;
845     frames_drawn = new_frames_drawn;
846
847     last_frame_interval_timestamp = new_ticks;
848     interval_skipped_frames = 0;
849     frames = 0;
850   }
851
852   if(current_frameskip_type == manual_frameskip)
853   {
854     frameskip_counter = (frameskip_counter + 1) %
855      (frameskip_value + 1);
856     if(random_skip)
857     {
858       if(frameskip_counter != (rand() % (frameskip_value + 1)))
859         skip_next_frame = 1;
860     }
861     else
862     {
863       if(frameskip_counter)
864         skip_next_frame = 1;
865     }
866   }
867
868   interval_skipped_frames += skip_next_frame;
869
870 #if !defined(GP2X_BUILD) && !defined(PND_BUILD)
871   char char_buffer[64];
872   sprintf(char_buffer, "gpSP: %2d (%2d) fps", fps, frames_drawn);
873   SDL_WM_SetCaption(char_buffer, "gpSP");
874 #endif
875 }
876
877 #endif
878
879 void quit()
880 {
881   save_romdir();
882
883   if(!update_backup_flag)
884     update_backup_force();
885
886   sound_exit();
887
888 #ifdef REGISTER_USAGE_ANALYZE
889   print_register_usage();
890 #endif
891
892 #ifdef PSP_BUILD
893   sceKernelExitGame();
894 #else
895   SDL_Quit();
896
897 #ifndef PC_BUILD
898   gpsp_plat_quit();
899 #endif
900
901   exit(0);
902 #endif
903 }
904
905 void reset_gba()
906 {
907   init_main();
908   init_memory();
909   init_cpu();
910   reset_sound();
911 }
912
913 #ifdef PSP_BUILD
914
915 u32 file_length(char *filename, s32 dummy)
916 {
917   SceIoStat stats;
918   sceIoGetstat(filename, &stats);
919   return stats.st_size;
920 }
921
922 void delay_us(u32 us_count)
923 {
924   sceKernelDelayThread(us_count);
925 }
926
927 void get_ticks_us(u64 *tick_return)
928 {
929   u64 ticks;
930   sceRtcGetCurrentTick(&ticks);
931
932   *tick_return = (ticks * 1000000) / sceRtcGetTickResolution();
933 }
934
935 #else
936
937 u32 file_length(char *dummy, FILE *fp)
938 {
939   u32 length;
940
941   fseek(fp, 0, SEEK_END);
942   length = ftell(fp);
943   fseek(fp, 0, SEEK_SET);
944
945   return length;
946 }
947
948 #ifdef PC_BUILD
949
950 void delay_us(u32 us_count)
951 {
952   SDL_Delay(us_count / 1000);
953 }
954
955 void get_ticks_us(u64 *ticks_return)
956 {
957   *ticks_return = (u64)SDL_GetTicks() * 1000;
958 }
959
960 #else
961
962 void delay_us(u32 us_count)
963 {
964   //usleep(us_count);
965   SDL_Delay(us_count / 1000);
966 }
967
968 void get_ticks_us(u64 *ticks_return)
969 {
970   struct timeval current_time;
971   gettimeofday(&current_time, NULL);
972
973   *ticks_return =
974    (u64)current_time.tv_sec * 1000000 + current_time.tv_usec;
975 }
976
977 #endif
978
979 #endif
980
981 void change_ext(const char *src, char *buffer, const char *extension)
982 {
983   char *dot_position;
984   strcpy(buffer, src);
985   dot_position = strrchr(buffer, '.');
986
987   if(dot_position)
988     strcpy(dot_position, extension);
989 }
990
991 // make path: <main_path>/<romname>.<ext>
992 void make_rpath(char *buff, size_t size, const char *ext)
993 {
994   char *p;
995   p = strrchr(gamepak_filename, PATH_SEPARATOR_CHAR);
996   if (p == NULL)
997     p = gamepak_filename;
998
999   snprintf(buff, size, "%s/%s", main_path, p);
1000   p = strrchr(buff, '.');
1001   if (p != NULL)
1002     strcpy(p, ext);
1003 }
1004
1005 #define main_savestate_builder(type)                                          \
1006 void main_##type##_savestate(file_tag_type savestate_file)                    \
1007 {                                                                             \
1008   file_##type##_variable(savestate_file, cpu_ticks);                          \
1009   file_##type##_variable(savestate_file, execute_cycles);                     \
1010   file_##type##_variable(savestate_file, video_count);                        \
1011   file_##type##_array(savestate_file, timer);                                 \
1012 }                                                                             \
1013
1014 main_savestate_builder(read);
1015 main_savestate_builder(write_mem);
1016
1017
1018 void printout(void *str, u32 val)
1019 {
1020   printf(str, val);
1021 }
1022
1023 void set_clock_speed()
1024 {
1025   static u32 clock_speed_old = default_clock_speed;
1026   if (clock_speed != clock_speed_old)
1027   {
1028     printf("about to set CPU clock to %iMHz\n", clock_speed);
1029   #ifdef PSP_BUILD
1030     scePowerSetClockFrequency(clock_speed, clock_speed, clock_speed / 2);
1031   #elif defined(GP2X_BUILD)
1032     set_FCLK(clock_speed);
1033   #endif
1034     clock_speed_old = clock_speed;
1035   }
1036 }
1037