bugfixes, r171 release
[fceu.git] / drivers / gp2x / main.c
1 /* FCE Ultra - NES/Famicom Emulator
2  *
3  * This program is free software; you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation; either version 2 of the License, or
6  * (at your option) any later version.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program; if not, write to the Free Software
15  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16  */
17
18
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <signal.h>
22 #include <sys/time.h>
23 #include <sys/stat.h>
24 #include <string.h>
25 #include <strings.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29
30 #include "main.h"
31 #include "minimal.h"
32 #include "throttle.h"
33 #include "menu.h"
34 #include "gp2x.h"
35
36 #include "../common/config.h"
37 #include "../common/args.h"
38 #include "../common/unixdsp.h"
39 #include "../common/cheat.h"
40
41 #include "../../fce.h"
42 #include "../../cart.h"
43
44 #include "dface.h"
45
46
47 void CleanSurface(void);
48
49 // internals
50 extern char lastLoadedGameName[2048];
51 extern uint8 Exit; // exit emu loop flag
52 extern int FSkip;
53 void CloseGame(void);
54
55 FCEUGI *fceugi = NULL;
56 int ntsccol=0,ntschue=-1,ntsctint=-1;
57 int soundvol=70;
58 int inited=0;
59
60 int srendlinev[2]={8,0};
61 int erendlinev[2]={231,239};
62 int srendline,erendline;
63
64
65 static char BaseDirectory[2048];
66
67 int eoptions=0;
68
69 static void DriverKill(void);
70 static int DriverInitialize(void);
71
72 static int gametype;
73 #include "input.c"
74
75 static void ParseGI(FCEUGI *gi)
76 {
77  gametype=gi->type;
78
79  InputType[0]=UsrInputType[0];
80  InputType[1]=UsrInputType[1];
81  InputTypeFC=UsrInputTypeFC;
82
83  if(gi->input[0]>=0)
84   InputType[0]=gi->input[0];
85  if(gi->input[1]>=0)
86   InputType[1]=gi->input[1];
87  if(gi->inputfc>=0)
88   InputTypeFC=gi->inputfc;
89 }
90
91 void FCEUD_PrintError(char *s)
92 {
93  puts(s);
94 }
95
96 char *cpalette=0;
97 void LoadCPalette(void)
98 {
99  char tmpp[192];
100  FILE *fp;
101
102  if(!(fp=fopen(cpalette,"rb")))
103  {
104   printf(" Error loading custom palette from file: %s\n",cpalette);
105   free(cpalette);
106   cpalette=0;
107   return;
108  }
109  fread(tmpp,1,192,fp);
110  FCEUI_SetPaletteArray((uint8 *)tmpp);
111  fclose(fp);
112 }
113
114 static CFGSTRUCT fceuconfig[]={
115         AC(soundvol),
116         ACS(cpalette),
117         AC(ntsctint),
118         AC(ntschue),
119         AC(ntsccol),
120         AC(UsrInputTypeFC),
121         ACA(UsrInputType),
122         AC(powerpadside),
123         AC(powerpadsc),
124         AC(eoptions),
125         ACA(srendlinev),
126         ACA(erendlinev),
127         ADDCFGSTRUCT(DriverConfig),
128         ENDCFGSTRUCT
129 };
130
131 static const char *skip_path(const char *path)
132 {
133         const char *p;
134         if (path == NULL) return NULL;
135         for (p = path+strlen(path)-1; p > path && *p != '/'; p--);
136         if (*p == '/') p++;
137         return p;
138 }
139
140 int SaveConfig(const char *llgn_path)
141 {
142         const char *name = skip_path(llgn_path);
143         char tdir[2048];
144         int ret;
145         if (name)
146              sprintf(tdir,"%s"PSS"cfg"PSS"%s.cfg",BaseDirectory,name);
147         else sprintf(tdir,"%s"PSS"fceu2.cfg",BaseDirectory);
148         printf("saving cfg to %s ... ", tdir); fflush(stdout);
149         FCEUI_GetNTSCTH(&ntsctint, &ntschue);
150         ret=SaveFCEUConfig(tdir,fceuconfig);
151         printf(ret == 0 ? "done\n" : "failed\n");
152         return ret;
153 }
154
155 static int LoadConfig(const char *llgn_path)
156 {
157         const char *name = skip_path(llgn_path);
158         char tdir[2048];
159         int ret;
160         if (name)
161              sprintf(tdir,"%s"PSS"cfg"PSS"%s.cfg",BaseDirectory,name);
162         else sprintf(tdir,"%s"PSS"fceu2.cfg",BaseDirectory);
163         printf("loading cfg from %s ... ", tdir); fflush(stdout);
164         FCEUI_GetNTSCTH(&ntsctint, &ntschue); /* Get default settings for if no config file exists. */
165         ret=LoadFCEUConfig(tdir,fceuconfig);
166         FCEUI_SetNTSCTH(ntsccol, ntsctint, ntschue);
167         printf(ret == 0 ? "done\n" : "failed\n");
168         return ret;
169 }
170
171 static void LoadLLGN(void)
172 {
173  char tdir[2048];
174  FILE *f;
175  int len;
176  sprintf(tdir,"%s"PSS"last_rom.txt",BaseDirectory);
177  f=fopen(tdir, "r");
178  if(f)
179  {
180   len = fread(lastLoadedGameName, 1, sizeof(lastLoadedGameName)-1, f);
181   lastLoadedGameName[len] = 0;
182   fclose(f);
183  }
184 }
185
186 static void SaveLLGN(void)
187 {
188  // save last loaded game name
189  if (lastLoadedGameName[0] && !(eoptions&EO_NOAUTOWRITE))
190  {
191   char tdir[2048];
192   FILE *f;
193   sprintf(tdir,"%s"PSS"last_rom.txt",BaseDirectory);
194   f=fopen(tdir, "w");
195   if(f)
196   {
197    fwrite(lastLoadedGameName, 1, strlen(lastLoadedGameName), f);
198    fclose(f);
199    sync();
200   }
201  }
202 }
203
204
205 static void CreateDirs(void)
206 {
207  char *subs[]={"fcs","snaps","gameinfo","sav","cheats","cfg","pal"};
208  char tdir[2048];
209  int x;
210
211  mkdir(BaseDirectory,S_IRWXU);
212  for(x=0;x<sizeof(subs)/sizeof(subs[0]);x++)
213  {
214   sprintf(tdir,"%s"PSS"%s",BaseDirectory,subs[x]);
215   mkdir(tdir,S_IRWXU);
216  }
217 }
218
219 static void SetSignals(void (*t)(int))
220 {
221   int sigs[11]={SIGINT,SIGTERM,SIGHUP,SIGPIPE,SIGSEGV,SIGFPE,SIGKILL,SIGALRM,SIGABRT,SIGUSR1,SIGUSR2};
222   int x;
223   for(x=0;x<11;x++)
224    signal(sigs[x],t);
225 }
226
227 static void CloseStuff(int signum)
228 {
229         DriverKill();
230         printf("\nSignal %d has been caught and dealt with...\n",signum);
231         switch(signum)
232         {
233          case SIGINT:printf("How DARE you interrupt me!\n");break;
234          case SIGTERM:printf("MUST TERMINATE ALL HUMANS\n");break;
235          case SIGHUP:printf("Reach out and hang-up on someone.\n");break;
236          case SIGPIPE:printf("The pipe has broken!  Better watch out for floods...\n");break;
237          case SIGSEGV:printf("Iyeeeeeeeee!!!  A segmentation fault has occurred.  Have a fluffy day.\n");break;
238          #if(SIGBUS!=SIGSEGV)
239          case SIGBUS:printf("I told you to be nice to the driver.\n");break;
240          #endif
241          case SIGFPE:printf("Those darn floating points.  Ne'er know when they'll bite!\n");break;
242          case SIGALRM:printf("Don't throw your clock at the meowing cats!\n");break;
243          case SIGABRT:printf("Abort, Retry, Ignore, Fail?\n");break;
244          case SIGUSR1:
245          case SIGUSR2:printf("Killing your processes is not nice.\n");break;
246         }
247         exit(1);
248 }
249
250 static int DoArgs(int argc, char *argv[])
251 {
252         static char *cortab[5]={"none","gamepad","zapper","powerpad","arkanoid"};
253         static int cortabi[5]={SI_NONE,SI_GAMEPAD,
254                                SI_ZAPPER,SI_POWERPADA,SI_ARKANOID};
255         static char *fccortab[5]={"none","arkanoid","shadow","4player","fkb"};
256         static int fccortabi[5]={SIFC_NONE,SIFC_ARKANOID,SIFC_SHADOW,
257                                  SIFC_4PLAYER,SIFC_FKB};
258
259         int x, ret;
260         static char *inputa[2]={0,0};
261         static char *fcexp=0;
262         static int docheckie[4];
263
264         static ARGPSTRUCT FCEUArgs[]={
265          {"-soundvol",0,&soundvol,0},
266          {"-cpalette",0,&cpalette,0x4001},
267
268          {"-ntsccol",0,&ntsccol,0},
269          {"-pal",&docheckie[0],0,0},
270          {"-input1",0,&inputa[0],0x4001},{"-input2",0,&inputa[1],0x4001},
271          {"-fcexp",0,&fcexp,0x4001},
272
273          {"-gg",0,&eoptions,0x8000|EO_GG},
274          {"-no8lim",0,&eoptions,0x8000|EO_NO8LIM},
275          {"-snapname",0,&eoptions,0x8000|EO_SNAPNAME},
276          {"-nofs",0,&eoptions,0x8000|EO_NOFOURSCORE},
277          {"-clipsides",0,&eoptions,0x8000|EO_CLIPSIDES},
278          {"-nothrottle",0,&eoptions,0x8000|EO_NOTHROTTLE},
279          {"-noautowrite",0,&eoptions,0x8000|EO_NOAUTOWRITE},
280          {"-slstart",0,&srendlinev[0],0},{"-slend",0,&erendlinev[0],0},
281          {"-slstartp",0,&srendlinev[1],0},{"-slendp",0,&erendlinev[1],0},
282          {0,(void *)DriverArgs,0,0},
283          {0,0,0,0}
284         };
285
286         memset(docheckie,0,sizeof(docheckie));
287         ret=ParseArguments(argc, argv, FCEUArgs);
288         if(cpalette)
289         {
290          if(cpalette[0]=='0')
291           if(cpalette[1]==0)
292           {
293            free(cpalette);
294            cpalette=0;
295           }
296         }
297         if(docheckie[0])
298          Settings.region_force=2;
299         FCEUI_SetGameGenie(eoptions&EO_GG);
300         FCEUI_DisableSpriteLimitation(eoptions&EO_NO8LIM);
301         FCEUI_SetSnapName(eoptions&EO_SNAPNAME);
302
303         for(x=0;x<2;x++)
304         {
305          if(srendlinev[x]<0 || srendlinev[x]>239) srendlinev[x]=0;
306          if(erendlinev[x]<srendlinev[x] || erendlinev[x]>239) erendlinev[x]=239;
307         }
308
309         FCEUI_SetRenderedLines(srendlinev[0],erendlinev[0],srendlinev[1],erendlinev[1]);
310         FCEUI_SetSoundVolume(80);
311         DoDriverArgs();
312
313         if(fcexp)
314         {
315          int y;
316          for(y=0;y<5;y++)
317          {
318           if(!strncmp(fccortab[y],fcexp,8))
319           {
320            UsrInputTypeFC=fccortabi[y];
321            break;
322           }
323          }
324          free(fcexp);
325         }
326         for(x=0;x<2;x++)
327         {
328          int y;
329
330          if(!inputa[x])
331           continue;
332
333          for(y=0;y<5;y++)
334          {
335           if(!strncmp(cortab[y],inputa[x],8))
336           {
337            UsrInputType[x]=cortabi[y];
338            if(y==3)
339            {
340             powerpadside&=~(1<<x);
341             powerpadside|=((((inputa[x][8])-'a')&1)^1)<<x;
342            }
343            free(inputa[x]);
344           }
345          }
346         }
347         return ret;
348 }
349
350
351 #include "usage.h"
352
353 int CLImain(int argc, char *argv[])
354 {
355         int last_arg_parsed, ret;
356         /* TODO if(argc<=1)
357         {
358          ShowUsage(argv[0]);
359          return 1;
360         }*/
361
362         if(!DriverInitialize())
363         {
364          return 1;
365         }
366
367         if(!FCEUI_Initialize())
368          return(1);
369         GetBaseDirectory(BaseDirectory);
370         FCEUI_SetBaseDirectory(BaseDirectory);
371         lastLoadedGameName[0] = 0;
372
373         CreateDirs();
374         LoadConfig(NULL);
375         last_arg_parsed=DoArgs(argc-1,&argv[1]);
376         gp2x_opt_setup();
377         LoadLLGN();
378         FCEUI_SetNTSCTH(ntsccol, ntsctint, ntschue);
379         if(cpalette)
380          LoadCPalette();
381         if(InitSound())
382          inited|=1;
383
384         if (argc > 1 && !last_arg_parsed)
385         {
386          strncpy(lastLoadedGameName, argv[argc-1], sizeof(lastLoadedGameName));
387          lastLoadedGameName[sizeof(lastLoadedGameName)-1] = 0;
388          Exit = 0;
389         }
390         else
391         {
392          Exit = 1;
393         }
394
395         while (1)
396         {
397          if(!Exit)
398          {
399           if (fceugi)
400            CloseGame();
401           ret=LoadConfig(lastLoadedGameName);
402           if (ret != 0)
403           {
404            LoadConfig(NULL);
405           }
406           FCEUI_SetEmuMode(Settings.accurate_mode);
407           fceugi=FCEUI_LoadGame(lastLoadedGameName);
408           if (fceugi)
409           {
410            char infostring[32];
411            if (Settings.region_force)
412             FCEUI_SetVidSystem(Settings.region_force - 1);
413            ParseGI(fceugi);
414            InitOtherInput();
415
416            if ((eoptions&EO_GG) && geniestage == 0) {
417             strcpy(infostring, "gg.rom is missing, GG disabled");
418             eoptions&=~EO_GG;
419             FCEUI_SetGameGenie(0);
420            } else
421             GameInterface(GI_INFOSTRING, infostring);
422            FCEU_DispMessage("%s", infostring);
423           }
424           else
425           {
426            switch(LoadGameLastError) {
427             default: strcpy(menuErrorMsg, "failed to load ROM"); break;
428             case  2: strcpy(menuErrorMsg, "Can't find a ROM for ips/movie"); break;
429             case 10: strcpy(menuErrorMsg, "FDS BIOS ROM is missing, read docs"); break;
430             case 11: strcpy(menuErrorMsg, "Error reading auxillary FDS file"); break;
431            }
432           }
433          }
434          if(Exit || !fceugi)
435          {
436           int ret;
437           ret = gp2x_menu_do();
438           if (ret == 1) break;          // exit emu
439           if (ret == 2) {               // reload ROM
440            Exit = 0;
441            continue;
442           }
443          }
444
445          gp2x_opt_update();
446          PrepareOtherInput();
447          FCEUI_GetCurrentVidSystem(&srendline,&erendline);
448          gp2x_video_changemode(Settings.scaling == 3 ? 15 : 8);
449          switch (Settings.scaling & 3) {
450                  case 0: gp2x_video_set_offs(0);  gp2x_video_RGB_setscaling(320, 240); break;
451                  case 1: gp2x_video_set_offs(32); gp2x_video_RGB_setscaling(256, 240); break;
452                  case 2: gp2x_video_set_offs(32+srendline*320); gp2x_video_RGB_setscaling(256, erendline-srendline); break;
453                  case 3: gp2x_video_set_offs(32); gp2x_video_RGB_setscaling(320, 240); break;
454          }
455          CleanSurface();
456          gp2x_start_sound(Settings.sound_rate, 16, 0);
457          RefreshThrottleFPS();
458          FCEUI_Emulate();
459         }
460
461         if (fceugi)
462          CloseGame();
463
464         SaveLLGN();
465         FCEUI_Kill();
466         DriverKill();
467         return 0;
468 }
469
470 static int DriverInitialize(void)
471 {
472    SetSignals((void *)CloseStuff);
473
474    if(!InitVideo()) return 0;
475    inited|=4;
476    return 1;
477 }
478
479 static void DriverKill(void)
480 {
481  // SaveConfig(NULL); // done explicitly in menu now
482  SetSignals(SIG_DFL);
483
484  if(cpalette) free(cpalette);
485  cpalette=0;
486
487  if(inited&4)
488   KillVideo();
489  if(inited&1)
490   KillSound();
491  inited=0;
492 }
493
494 void FCEUD_Update(uint8 *xbuf, int16 *Buffer, int Count)
495 {
496  FCEUD_UpdateInput();   // must update input before blitting because of save confirmation stuff
497  BlitPrepare(xbuf == NULL);
498  if(!(eoptions&EO_NOTHROTTLE))
499  {
500   if(Count)
501    WriteSound(Buffer,Count);
502   SpeedThrottle();
503  }
504  BlitScreen(xbuf == NULL);
505  // make sure last frame won't get skipped, because we need it for menu bg
506  if (Exit) FSkip=0;
507 }
508