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