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