]> Shamusworld >> Repos - virtualjaguar/blob - src/vj.cpp
Changes to support new video subsystem
[virtualjaguar] / src / vj.cpp
1 //
2 // Virtual Jaguar Emulator
3 //
4 // Original codebase by Cal2
5 // GCC/SDL port by Niels Wagenaar (Linux/WIN32) and Caz (BeOS)
6 // Cleanups/fixes/enhancements by James L. Hammons and Adam Green
7 //
8
9 #ifdef __GCCUNIX__
10 #include <unistd.h>
11 #endif
12
13 #include <dirent.h>                                                                     // POSIX, but should compile with linux & mingw...
14 #include <time.h>
15 #include <SDL.h>
16 #include "jaguar.h"
17 #include "crc32.h"
18 #include "zlib.h"
19 #include "unzip.h"
20 #include "video.h"
21 #include "gui.h"
22 #include "sdlemu_opengl.h"                                                      // For testing only... ;-)
23
24 // Uncomment this for speed control
25 //#define SPEED_CONTROL
26
27 // Private function prototypes
28
29 void InitSDL(void);
30 uint32 JaguarLoadROM(uint8 *, char *);
31 void JaguarLoadCart(uint8 *, char *);
32 int gzfilelength(gzFile gd);
33
34 // External variables
35
36 extern uint8 * jaguar_mainRam;
37 extern uint8 * jaguar_bootRom;
38 extern uint8 * jaguar_mainRom;
39
40 // Various paths
41
42 static char * jaguar_bootRom_path = "./bios/jagboot.rom";
43 //static char  *jaguar_bootRom_path="c:/jaguarEmu/newload.img";
44 //static char  *jaguar_bootRom_path="./bios/JagOS.bin";
45 char * jaguar_eeproms_path = "./eeproms/";
46 char jaguar_boot_dir[1024];
47
48 SDL_Surface * surface, * mainSurface;
49 int16 * backbuffer = NULL;
50 SDL_Joystick * joystick;
51 Uint32 mainSurfaceFlags = SDL_SWSURFACE;
52
53 bool finished = false;
54 bool fullscreen = false;
55 bool hardwareTypeNTSC = true;                                           // Set to false for PAL
56
57 bool useJoystick = false;
58 int32 nJoyport = 0;                                                                     // Joystick port
59 bool showGUI = false;
60 //These two should be local!
61 // And now they are! ;-)
62 bool jaguar_use_bios = false;                                           // Default is now to USE the BIOS
63 bool dsp_enabled = false;
64
65 // Keybindings in order of L, R, U, D, C, B, A, Op, Pa, 0-9, #, *
66 uint16 p1KeyBindings[21] = {};
67 uint16 p2KeyBindings[21] = {};
68
69 bool showMessage = false;
70 uint32 showMessageTimeout;
71 char messageBuffer[200];
72
73 bool useOpenGL = true;                                                          // ! ;-)
74
75 //
76 // The main emulator loop (what else?)
77 //
78 //Maybe we should move the video stuff to TOM? Makes more sense to put it there...
79 uint32 totalFrames;//temp, so we can grab this from elsewhere...
80 int main(int argc, char * argv[])
81 {
82         uint32 startTime;//, totalFrames;//, endTime;//, w, h;
83         uint32 nNormalLast = 0;
84         int32 nNormalFrac = 0; 
85     int32 nFrameskip = 0;                                                               // Default: Show every frame
86     int32 nFrame = 0;                                                                   // No. of Frame
87
88         printf("Virtual Jaguar/SDL v1.0.6 (GCC/SDL Port)\n");
89         printf("Based upon Virtual Jaguar core v1.0.0 by cal2 of Potato emulation.\n");
90         printf("Written by Niels Wagenaar (Linux/WIN32) and Caz (BeOS)\n");
91         printf("Portions massaged by James L. Hammons (WIN32)\n");
92         printf("Contact: http://sdlemu.ngemu.com/ | sdlemu@ngemu.com\n");
93
94         // BIOS is now ON by default--use the -nobios switch to turn it off!
95         jaguar_use_bios = true;
96         bool haveCart = false;                                                          // Assume there is no cartridge...!
97
98         // Checking the switches ;)
99
100         for(int i=1; i<argc || argv[i]!=NULL; i++)
101         {
102                 // This would be the most likely place to do the cart loading...
103                 if (argv[i][0] != '-')
104                         haveCart = true;                                                                // It looks like we have a cartridge!
105
106                 if (!strcmp(argv[i], "-fullscreen")) 
107                         fullscreen = true;
108
109 //We *don't* need this option!
110 /*              if (!strcmp(argv[i], "-window")) 
111 //                      console.option("windowed output");
112                         fullscreen = false;*/
113
114                 if (!strcmp(argv[i], "-joystick")) 
115                         useJoystick = true;
116
117                 if (!strcmp(argv[i], "-joyport"))
118                 {
119                         nJoyport = atoi(argv[++i]) + 1;
120                         if (nJoyport > 3)
121                                 nJoyport = 3;
122                 }
123
124                 if (!strcmp(argv[i], "-frameskip"))
125                 {
126                         nFrameskip = atoi(argv[++i]) + 1;
127                         if (nFrameskip > 10)
128                                 nFrameskip = 10;
129 #ifdef SPEED_CONTROL
130                         nFrameskip = 0;
131 #endif
132                 }
133
134                 if (!strcmp(argv[i], "-nobios"))
135                         jaguar_use_bios = false;
136
137                 if (!strcmp(argv[i], "-dspon"))
138                         dsp_enabled = 1;
139
140                 if (!strcmp(argv[i], "-pal"))
141                         hardwareTypeNTSC = false;
142
143                 if (!strcmp(argv[i], "-help") || !strcmp(argv[i], "-?"))
144                 {
145                     printf("Usage: \n\n");
146                         printf("vj [romfile] [switches]\n");
147                         printf("  -? or -help     : Display usage and switches                \n");
148                         printf("  -fullscreen     : Enable fullscreen mode (default: windowed)\n");
149                         printf("  -frameskip 1-10 : Enable frameskip 1 - 10 (default: none)   \n");
150                         printf("  -joystick       : Enable joystick/gamepad                   \n");
151                         printf("  -joyport   0-3  : Select desired joystick port              \n");
152                         printf("  -nobios         : Boot cart without using Jaguar BIOS ROM   \n");
153                         printf("  -dspon          : Force VJ to use the DSP                   \n");
154                         printf("  -pal            : Force VJ to PAL mode (default is NTSC)    \n");
155                         printf("\nInvoking Virtual Jagaur with no ROM file will cause it to boot up\n");
156                         printf("with the Jaguar BIOS.\n");
157                         return 1;
158                 }
159     }
160
161         getcwd(jaguar_boot_dir, 1024);
162         log_init("vj.log");
163         memory_init();
164         version_init();
165         version_display(log_get());
166         jaguar_init();
167
168         // Get the BIOS ROM
169         if (jaguar_use_bios)
170                 JaguarLoadROM(jaguar_bootRom, jaguar_bootRom_path);
171
172         SET32(jaguar_mainRam, 0, 0x00200000);                   // Set top of stack...
173
174 //This is done here, so that we get valid numbers from TOM... !!! FIX !!!
175         jaguar_reset();
176
177         // Set up the backbuffer
178 //      int16 * backbuffer = (int16 *)malloc(845 * 525 * sizeof(int16));
179         backbuffer = (int16 *)malloc(845 * 525 * sizeof(int16));
180         memset(backbuffer, 0x22, tom_getVideoModeWidth() * tom_getVideoModeHeight() * sizeof(int16));
181
182         InitSDL();
183
184         // Get the cartridge ROM (if passed in)
185 //      if (haveCart)
186 //              JaguarLoadCart(jaguar_mainRom, argv[1]);
187         // Now with crunchy GUI goodness!
188         JaguarLoadCart(jaguar_mainRom, (haveCart ? argv[1] : (char *)""));
189
190 //Do this again??? Hmm... This is not very nice.
191 //Maybe it's not necessary??? Seems to be, at least for PD ROMs... !!! FIX !!!
192         jaguar_reset();
193         
194         totalFrames = 0;
195         startTime = clock();
196         nNormalLast = 0;                                                                        // Last value of timeGetTime()
197         nNormalFrac = 0;                                                                        // Extra fraction we did
198         nNormalLast = SDL_GetTicks();                                           //timeGetTime();
199
200         while (!finished)
201         {
202 #ifdef SPEED_CONTROL
203                 nTime = SDL_GetTicks() - nNormalLast;                   // calcule le temps Ã©coulé depuis le dernier affichage
204                                                                                                                 // nTime est en mili-secondes.
205                 // détermine le nombre de trames Ã  passer + 1
206                 nCount = (nTime * 600 - nNormalFrac) / 10000;
207
208                 // si le nombre de trames Ã  passer + 1 est nul ou négatif,
209                 // ne rien faire pendant 2 ms
210                 if (nCount <= 0) 
211                 { 
212                         //Sleep(2); 
213                         //SDL_Delay(1);
214                 } // No need to do anything for a bit
215                 else
216                 {
217                         nNormalFrac += nCount * 10000;                          // 
218                         nNormalLast += nNormalFrac / 600;                       // add the duration of nNormalFrac frames
219                         nNormalFrac %= 600;                                                     // 
220
221                         // Pas plus de 9 (10-1) trames non affichées 
222                         if (nCount > 10)
223                                 nCount = 10;
224                         for(int i=0; i<nCount-1; i++)
225                                 jaguar_exec(backbuffer, false);
226 #endif
227             // Setting up new backbuffer with new pixels and data
228                         JaguarExecute(backbuffer, true);
229                         totalFrames++;
230
231                         // GUI stuff here...
232                         if (showGUI)
233                         {
234                                 extern uint32 gpu_pc, dsp_pc;
235                                 DrawString(backbuffer, 8, 8, false, "GPU PC: %08X", gpu_pc);
236                                 DrawString(backbuffer, 8, 16, false, "DSP PC: %08X", dsp_pc);
237                         }
238
239                         // Simple frameskip
240                         if (nFrame == nFrameskip)
241                         {
242                                 RenderBackbuffer();
243                                 nFrame = 0;
244                         }
245                         else
246                                 nFrame++;
247
248                         joystick_exec();
249
250 #ifdef SPEED_CONTROL
251                 }
252 #endif
253         }
254
255         int elapsedTime = clock() - startTime;
256         int fps = (1000 * totalFrames) / elapsedTime;
257         fprintf(log_get(), "VJ: Ran at an average of %i FPS.\n", fps);
258
259         jaguar_done();
260         version_done();
261         memory_done();
262         log_done();     
263
264         if (useOpenGL)
265                 sdlemu_close_opengl();
266         SDL_JoystickClose(joystick);
267         SDL_FreeSurface(surface);
268         SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO | SDL_INIT_TIMER);
269         SDL_Quit();
270
271     return 0;
272 }
273
274 //
275 // Prime SDL and create surfaces
276 //
277 void InitSDL(void)
278 {
279         // Set up SDL library
280         if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO | SDL_INIT_TIMER | SDL_INIT_NOPARACHUTE) < 0)
281         {
282                 WriteLog("VJ: Could not initialize the SDL library: %s", SDL_GetError());
283                 exit(1);
284         }
285
286         // Get proper info about the platform we're running on...
287         const SDL_VideoInfo * info = SDL_GetVideoInfo();
288
289         if (!info)
290         {
291                 WriteLog("VJ: SDL is unable to get the video info: %s\n", SDL_GetError());
292                 exit(1);
293         }
294
295         if (useOpenGL)
296         {
297                 mainSurfaceFlags = SDL_HWSURFACE | SDL_HWPALETTE | SDL_DOUBLEBUF | SDL_OPENGL;
298                 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
299         }
300         else
301         {
302                 if (info->hw_available)
303                         mainSurfaceFlags = SDL_HWSURFACE | SDL_HWPALETTE | SDL_DOUBLEBUF;
304
305                 if (info->blit_hw)
306                         mainSurfaceFlags |= SDL_HWACCEL;
307         }
308
309         if (fullscreen)
310                 mainSurfaceFlags |= SDL_FULLSCREEN;
311
312 //      mainSurface = SDL_SetVideoMode(tom_getVideoModeWidth(), tom_getVideoModeHeight(), 16, mainSurfaceFlags);
313 //Testing purposes... :-)
314         mainSurface = SDL_SetVideoMode(tom_getVideoModeWidth()*2, tom_getVideoModeHeight()*2, 16, mainSurfaceFlags);
315
316         if (mainSurface == NULL)
317         {
318                 WriteLog("VJ: SDL is unable to set the video mode: %s\n", SDL_GetError());
319                 exit(1);
320         }
321
322         SDL_WM_SetCaption("Virtual Jaguar", "Virtual Jaguar");
323
324         // Create the primary SDL display (16 BPP, 5/5/5 RGB format)
325         surface = SDL_CreateRGBSurface(SDL_SWSURFACE, tom_getVideoModeWidth(),
326                 tom_getVideoModeHeight(), 16, 0x7C00, 0x03E0, 0x001F, 0);
327
328         if (surface == NULL)
329         {
330                 WriteLog("VJ: Could not create primary SDL surface: %s\n", SDL_GetError());
331                 exit(1);
332         }
333
334         if (useOpenGL)
335 //              sdlemu_init_opengl(surface, 1/*method*/, 1/*size*/, 0/*texture type (linear, nearest)*/);
336 //Testing purposes... :-)
337                 sdlemu_init_opengl(surface, 1/*method*/, 2/*size*/, 0/*texture type (linear, nearest)*/);
338
339         // Initialize Joystick support under SDL
340         if (useJoystick)
341         {
342                 if (SDL_NumJoysticks() <= 0)
343                 {
344                         useJoystick = false;
345                         printf("VJ: No joystick(s) or joypad(s) detected on your system. Using keyboard...\n");
346                 }
347                 else
348                 {
349                         if ((joystick = SDL_JoystickOpen(nJoyport)) == 0)
350                         {
351                                 useJoystick = false;
352                                 printf("VJ: Unable to open a Joystick on port: %d\n", (int)nJoyport);
353                         }
354                         else
355                                 printf("VJ: Using: %s\n", SDL_JoystickName(nJoyport));
356                 }
357         }
358 }
359
360 //
361 // Generic ROM loading
362 //
363 uint32 JaguarLoadROM(uint8 * rom, char * path)
364 {
365         uint32 romSize = 0;
366
367         char * ext = strrchr(path, '.');
368         if (ext != NULL)
369         {
370                 WriteLog("VJ: Loading %s...", path);
371
372                 if (stricmp(ext, ".zip") == 0)
373                 {
374                         // Handle ZIP file loading here...
375                         WriteLog("(ZIPped)...");
376
377                         if (load_zipped_file(0, 0, path, NULL, &rom, &romSize) == -1)
378                         {
379                                 WriteLog("Failed!\n");
380                                 return 0;
381                         }
382                 }
383                 else
384                 {
385 /*                      FILE * fp = fopen(path, "rb");
386
387                         if (fp == NULL)
388                         {
389                                 WriteLog("Failed!\n");
390                                 return 0;
391                         }
392
393                         fseek(fp, 0, SEEK_END);
394                         romSize = ftell(fp);
395                         fseek(fp, 0, SEEK_SET);
396                         fread(rom, 1, romSize, fp);
397                         fclose(fp);*/
398
399                         gzFile fp = gzopen(path, "rb");
400
401                         if (fp == NULL)
402                         {
403                                 WriteLog("Failed!\n");
404                                 return 0;
405                         }
406
407                         //fseek(fp, 0, SEEK_END);
408                         romSize = gzfilelength(fp);//ftell(fp);
409                         gzseek(fp, 0, SEEK_SET);
410                         gzread(fp, rom, romSize);
411                         gzclose(fp);
412                 }
413
414                 WriteLog("OK (%i bytes)\n", romSize);
415         }
416
417         return romSize;
418 }
419
420 //
421 // Jaguar cartridge ROM loading
422 //
423 void JaguarLoadCart(uint8 * mem, char * path)
424 {
425         uint32 romSize = JaguarLoadROM(mem, path);
426
427         if (romSize == 0)
428         {
429                 char newPath[2048];
430                 WriteLog("VJ: Trying GUI...\n");
431
432 //This is not *nix friendly for some reason...
433 //              if (!UserSelectFile(path, newPath))
434                 if (!UserSelectFile((path == "" ? (char *)"." : path), newPath))
435                 {
436                         WriteLog("VJ: Could not find valid ROM in directory \"%s\"...\nAborting!\n", path);
437                         log_done();
438                         exit(0);
439                 }
440
441                 romSize = JaguarLoadROM(mem, newPath);
442
443                 if (romSize == 0)
444                 {
445                         WriteLog("VJ: Could not load ROM from file \"%s\"...\nAborting!\n", newPath);
446                         log_done();
447                         exit(0);
448                 }
449         }
450
451         jaguar_mainRom_crc32 = crc32_calcCheckSum(jaguar_mainRom, romSize);
452         WriteLog("CRC: %08X\n", (unsigned int)jaguar_mainRom_crc32);
453         eeprom_init();
454 }
455
456 //
457 // Get the length of a (possibly) gzipped file
458 //
459 int gzfilelength(gzFile gd)
460 {
461    int size = 0, length = 0;
462    unsigned char buffer[0x10000];
463
464    gzrewind(gd);
465
466    do
467    {
468       // Read in chunks until EOF
469       size = gzread(gd, buffer, 0x10000);
470
471       if (size <= 0)
472         break;
473
474       length += size;
475    }
476    while (!gzeof(gd));
477
478    gzrewind(gd);
479    return length;
480 }