Render game graphics using OpenGL
[mercenary-reloaded.git] / src / mercenary / main.c
1 /* main routine
2  *
3  * (C) 2018 by Andreas Eversberg <jolly@eversberg.eu>
4  * All Rights Reserved
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <stdio.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include "../libsdl/sdl.h"
26 #include "../libsdl/opengl.h"
27 #include "../libsdl/print.h"
28 #include "../libcpu/m68k.h"
29 #include "../libcpu/execute.h"
30 #include "../libvideo/video.h"
31 #include "../libsound/sound.h"
32 #include "../libjoystick/joystick.h"
33 #include "../libkeyboard/keyboard.h"
34 #include "../libdisk/disk.h"
35 #include "mercenary.h"
36 #include "render.h"
37
38 #define FOV_MIN         10.0
39 #define FOV_NOVAGEN     64.0
40 #define FOV_JOLLY       80.0
41 #define FOV_MAX         170.0
42
43 static int config_ctrl_c = 0;
44 static int config_amiga_speed = 1;
45 static const char *config_gamesave_dir = ".mercenary";
46 static int config_video_filter = 1;
47 static int config_audio_filter = 1;
48 static int config_render = 0;
49 static int config_skip_intro = 0;
50 static int config_multisampling = 16;
51 static double config_fov = FOV_NOVAGEN;
52 static double config_benson_size = 1.0;
53 static int config_debug_transparent = 0;
54 static int config_debug_opengl = 0;
55 /* render improvements */
56 static int config_improve_extend_roads = 0;     /* set to 1 to extend roads */
57
58 #define CPU_SPEED       7093790.0;
59
60 #define SOUND_SAMPLERATE 48000
61 /* - game IRQ rate
62  * - must be used for sound rendering chunk
63  */
64 #define IRQ_RATE        50
65 /* numbe of buffer chunks to dejitter:
66  * - SDL render interval
67  * - sound rendering interval
68  * - sound card interval
69  * 4 should be minimum, if video rate is >=50 Hz
70  */
71 #define SOUND_CHUNKS    4
72
73 /* test sound to check if buffer does not overflow / underrun */
74 //#define DEBUG_SOUND_BUFFERING
75
76 #define IOSIZE          0x1000 /* bytes in io space */
77 #define MEMORY_SIZE     0x80000
78 static uint8_t *memory = NULL;
79 static uint8_t *stop_event = NULL;
80 static uint8_t *image = NULL;
81 #define SCREEN_WIDTH    320
82 #define SCREEN_HEIGHT   200
83 #define IMAGE_WIDTH     320
84 #define IMAGE_HEIGHT    200
85 #define BENSON_AT_LINE  136
86 #define IMAGE_DIWSTART  0x2c
87 static uint16_t *chipreg = NULL;
88 static stereo_t *sound_buffer = NULL; /* sound buffer memory */
89 static int sound_buffer_size; /* buffer sample size */
90 static int sound_buffer_writep; /* write pointer at buffer */
91 static int sound_buffer_readp; /* read pointer at buffer */
92 static int double_pixel_size = 1; /* render in double size, so each pixle is 2*2 pixles wide */
93 static double benson_size; /* render size of benson */
94 static int render_legacy = 0; /* render original amiga screen, if set */
95 static int render_improved = 0; /* render improved image, if set */
96 static int debug_opengl = 0; /* render both, amiga screen and  improved image, if set */
97
98 static const char *home_dir;
99
100 static int quit = 0;
101
102 int parse_args(int argc, char *argv[])
103 {
104         int i = 1;
105
106         while (argc > i) {
107                 if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
108                         print_info("Usage: %s\n", argv[0]);
109                         print_info(" -s --amiga-speed original | full\n");
110                         print_info("        Set speed of rendering to original Amiga or full speed.\n");
111                         print_info(" -v --video-filter on | off\n");
112                         print_info("        Set video filter.\n");
113                         print_info(" -a --audio-filter on | off\n");
114                         print_info("        Set audio filter.\n");
115                         print_info(" -r --render original | opegl\n");
116                         print_info("        Set speed of rendering to original Amiga or full speed.\n");
117                         print_info(" -b --benson normal | half\n");
118                         print_info("        Size of 'Benson' (control panel).\n");
119                         print_info(" -m --multisampling <samples>\n");
120                         print_info("        Use multisampling (default = %d) to render the scene.\n", config_multisampling);
121                         print_info(" -f --fov <%.0f..%.0f..%.0f>\n", FOV_MIN, FOV_NOVAGEN, FOV_MAX);
122                         print_info("        Set field-of-view. Default is %.0f.\n", FOV_NOVAGEN);
123                         print_info(" -i --skip-intro\n");
124                         print_info("        Skip intro sequence approaching to Eris space port.\n");
125                         print_info("Debug options:\n");
126                         print_info(" -o --debug-opengl\n");
127                         print_info("        Use split screen to display both Amiga and OpenGL rendering.\n");
128                         print_info("    --debug-transparent\n");
129                         print_info("        Draw all things half transparent.\n");
130                         print_info("    --ctrl-c\n");
131                         print_info("        Use CTRL+C to exit game (used for development)\n");
132                         return -1;
133                 } else
134                 if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--amiga-speed")) {
135                         i++;
136                         if (argc == i) {
137 missing_parameter:
138                                 print_info("Missing parameter, use '--help'!\n");
139                                 return -1;
140                         }
141                         if (!strcmp(argv[i], "original"))
142                                 config_amiga_speed = 1;
143                         else
144                         if (!strcmp(argv[i], "full"))
145                                 config_amiga_speed = 0;
146                         else {
147 illegal_parameter:
148                                 print_info("Illegal parameter, use '--help'!\n");
149                                 return -1;
150                         }
151                 } else
152                 if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--video-filter")) {
153                         i++;
154                         if (argc == i)
155                                 goto missing_parameter;
156                         if (!strcmp(argv[i], "on"))
157                                 config_video_filter = 1;
158                         else
159                         if (!strcmp(argv[i], "off"))
160                                 config_video_filter = 0;
161                         else
162                                 goto illegal_parameter;
163                 } else
164                 if (!strcmp(argv[i], "-a") || !strcmp(argv[i], "--audio-filter")) {
165                         i++;
166                         if (argc == i)
167                                 goto missing_parameter;
168                         if (!strcmp(argv[i], "on"))
169                                 config_audio_filter = 1;
170                         else
171                         if (!strcmp(argv[i], "off"))
172                                 config_audio_filter = 0;
173                         else
174                                 goto illegal_parameter;
175                 } else
176                 if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--render")) {
177                         i++;
178                         if (argc == i)
179                                 goto missing_parameter;
180                         if (!strcmp(argv[i], "original"))
181                                 config_render = 0;
182                         else
183                         if (!strcmp(argv[i], "opengl"))
184                                 config_render = 1;
185                         else
186                                 goto illegal_parameter;
187                 } else
188                 if (!strcmp(argv[i], "-b") || !strcmp(argv[i], "--benson")) {
189                         i++;
190                         if (argc == i)
191                                 goto missing_parameter;
192                         if (!strcmp(argv[i], "normal"))
193                                 config_benson_size = 1.0;
194                         else
195                         if (!strcmp(argv[i], "half")) {
196                                 config_benson_size = 0.5;
197                                 if (config_fov == FOV_NOVAGEN)
198                                         config_fov = FOV_JOLLY;
199                         } else
200                                 goto illegal_parameter;
201                 } else
202                 if (!strcmp(argv[i], "-m") || !strcmp(argv[i], "--multisampling")) {
203                         i++;
204                         if (argc == i)
205                                 goto missing_parameter;
206                         config_multisampling = atoi(argv[i]);
207                 } else
208                 if (!strcmp(argv[i], "-f") || !strcmp(argv[i], "--fov")) {
209                         i++;
210                         if (argc == i)
211                                 goto missing_parameter;
212                         config_fov = atof(argv[i]);
213                         if (config_fov < 1.0 || config_fov > 179.0)
214                                 goto illegal_parameter;
215                 } else
216                 if (!strcmp(argv[i], "-i") || !strcmp(argv[i], "--skip-intro")) {
217                         config_skip_intro = 1;
218                 } else
219                 if (!strcmp(argv[i], "-o") || !strcmp(argv[i], "--debug-opengl")) {
220                         config_debug_opengl = 1;
221                 } else
222                 if (!strcmp(argv[i], "--debug-transparent")) {
223                         config_debug_transparent = 1;
224                 } else
225                 if (!strcmp(argv[i], "--ctrl-c")) {
226                         config_ctrl_c = 1;
227                 } else {
228                         print_info("Illegal option '%s', use '--help'!\n", argv[i]);
229                         return -1;
230                 }
231                 i++;
232         }
233
234         return 0;
235 }
236
237 static void special_event(int event)
238 {
239         if (render_improved)
240                 render_improved_event(event);
241 }
242
243 static void main_loop(void)
244 {
245         int had_first_irq = 0;
246         static uint32_t current_time, last_time = 0, diff;
247         int i, rc;
248         int space, length;
249         int cycle_count, event;
250         double render_delay = 0.0;
251         uint32_t palette_address;
252         uint16_t palette[16];
253
254         last_time = SDL_GetTicks();
255
256         /* render result on window */
257         while (!quit) {
258                 /* handle SDL events */
259                 rc = event_sdl();
260                 if (rc)
261                         break;
262
263                 /* clear screen */
264                 opengl_clear();
265
266                 /* initialize rendering */
267                 debug_opengl = config_debug_opengl;
268                 benson_size = config_benson_size;
269                 render_legacy = (!config_render) || debug_opengl;
270                 render_improved = config_render || debug_opengl;
271                 if (render_improved) {
272                         opengl_viewport_improved(debug_opengl, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, benson_size);
273                         opengl_copy_last();
274                 }
275                 /* STEP 1: let the CPU render/process the game, also improve rendering via OpenGL, if enabled */
276                 /* don't render if we still delay */
277                 if (!render_delay) {
278                         /* start rendering for improved graphics */
279                         if (render_improved)
280                                 render_start(config_fov, config_improve_extend_roads, config_debug_transparent);
281
282                         /* execute until the rendered image is ready (wait for VBL) */
283                         cycle_count = 0;
284                         do {
285                                 cycle_count += execute_cpu(0, &event);
286                                 /* handle special events */
287                                 if (event != STOP_AT_WAIT_VBL)
288                                         special_event(event);
289                         } while (event != STOP_AT_WAIT_VBL);
290                         /* copy palette */
291                         palette_address = mercenary_palette_view();
292                         for (i = 0; i < 16; i++)
293                                 palette[i] = m68k_read_memory_16(palette_address + i*2);
294                         /* for amiga speed: set delay by the number of cycles */
295                         if (config_amiga_speed)
296                                 render_delay = (double)cycle_count / CPU_SPEED;
297                 }
298
299                 /* STEP 2: transfer legacy image (or just benson) in memory to OpenGL texture */
300                 if (had_first_irq) {
301                         /* render game view without benson
302                          * because benson is not updated before VBL IRQ, we don't want old image from double buffer
303                          */
304                         if (render_legacy)
305                                 emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, 0, BENSON_AT_LINE, double_pixel_size);
306                 }
307                 /* render benson on improved rendering, if enabled */
308                 if (render_improved) {
309                         render_finish();
310                         opengl_blit_benson(image, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, benson_size, (double_pixel_size) ? 2 : 1);
311                 }
312                 /* setup viewport for legacy image and render image, if enabled */
313                 if (render_legacy) {
314                         opengl_viewport_legacy(debug_opengl);
315                         opengl_blit_legacy(image, config_video_filter);
316                 }
317                 swap_sdl();
318
319                 /* STEP 3: execute interrupt at rate of 50Hz, render sound */
320                 current_time = SDL_GetTicks();
321                 diff = current_time - last_time;
322                 /* in case of timer glitch, execute IRQ only by maximum number of SOUND_CHUNKS */
323                 if (diff > 1000 * SOUND_CHUNKS / IRQ_RATE) {
324                         diff = 1000 * SOUND_CHUNKS / IRQ_RATE;
325                         last_time = current_time - 1000 * SOUND_CHUNKS / IRQ_RATE;
326                 }
327                 while (diff > 1000 / IRQ_RATE) {
328                         execute_cpu(3, NULL);
329                         execute_cpu(4, NULL);
330                         had_first_irq = 1;
331                         /* transfer benson without game view
332                          * because we only got benson refreshed during VBL IRQ
333                          */
334                         emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, BENSON_AT_LINE, IMAGE_HEIGHT, double_pixel_size);
335                         /* render sound to sound buffer
336                          * buffer pointer read and write is atomic, so no locking required!
337                          */
338                         space = (sound_buffer_readp - sound_buffer_writep - 1 + sound_buffer_size) % sound_buffer_size;
339                         if (space < SOUND_SAMPLERATE / IRQ_RATE) {
340 #ifdef DEBUG_SOUND_BUFFERING
341                                 fprintf(stderr, "sound buffer overflow\n");
342 #endif
343                                 length = space;
344                         } else
345                                 length = SOUND_SAMPLERATE / IRQ_RATE;
346 #ifdef DEBUG_SOUND_BUFFERING
347                         printf("can write %d, write %d\n", space, length);
348                         static int cnt = 0;
349                         int s;
350                         for (s = 0; s < length; s++) {
351                                 sound_buffer[(sound_buffer_writep + s) % sound_buffer_size].left =
352                                 sound_buffer[(sound_buffer_writep + s) % sound_buffer_size].right
353                                         = sin(2 * M_PI * 999 * cnt / SOUND_SAMPLERATE)
354                                         * sin(2 * M_PI * 21 * cnt / SOUND_SAMPLERATE)
355                                         * sin(2 * M_PI * 0.5 * cnt / SOUND_SAMPLERATE);
356                                  cnt++;
357                         }
358 #else
359                         render_sound(memory, sound_buffer, sound_buffer_size, sound_buffer_writep, length, config_audio_filter);
360 #endif
361                         sound_buffer_writep = (sound_buffer_writep + length) % sound_buffer_size;
362                         diff -= 1000 / IRQ_RATE;
363                         last_time += 1000 / IRQ_RATE;
364
365                         /* count down render delay */
366                         if (render_delay) {
367                                 render_delay -= 1.0 / (double)IRQ_RATE;
368                                 if (render_delay < 0.0)
369                                         render_delay = 0.0;
370                         }
371                 }
372         }
373 }
374
375 static uint16_t io_read(uint32_t address)
376 {
377         uint16_t value = 0xffff;
378
379         /* joystick and fire button */
380         if (address == 0xbfe000 || address == 0xdff00c)
381                 value &= emulate_joystick_read(address);
382         /* keyboard */
383         if (address == 0xbfec00 || address == 0xbfed00 || address == 0xbfee00)
384                 value &= emulate_keyboard_read(address);
385         /* diskette */
386         if (address == 0xbfd100 || address == 0xbfe000 || address == 0xdff01a || address == 0xdff01e)
387                 value &= emulate_disk_read(address);
388
389         return value;
390 }
391
392 static void io_write(uint32_t address, uint16_t value)
393 {
394         /* dmacon and sound registers */
395         if (address == 0xdff096 || (address >= 0xdff0a0 && address <= 0xdff0df))
396                 emulate_sound_write(address, value, SOUND_SAMPLERATE);
397         if (address == 0xbfd100 || (address >= 0xdff020 && address <= 0xdff024))
398                 emulate_disk_write(address, value);
399 }
400
401 /* two tracks with 0x1820 words of length */
402 static uint8_t game_save[2][0x1820 << 1];
403 static int last_track = 0;
404
405 /* game reads track with saved game */
406 static void disk_read(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
407 {
408         if (length > sizeof(game_save[0])) {
409                 print_error("loading game state failed, because length exceeds game save data size, please fix!\n");
410                 return;
411         }
412
413         /* if even track is selected, load game */
414         if (!(track & 1)) {
415                 char filename[256];
416                 int gamesave_num = (track - 2) >> 1;
417                 int got;
418                 FILE *fp;
419
420                 memset(game_save, 0, sizeof(game_save)); /* clear so make the game fail, if we fail */
421 #if defined(_WIN32)
422                 filename[0] = '\0';
423 #else
424                 sprintf(filename, "%s/%s/", home_dir, config_gamesave_dir);
425                 mkdir(filename, 0777);
426 #endif
427                 sprintf(filename + strlen(filename), "%d%s", gamesave_num, mercenary_gamesavesuffix);
428                 fp = fopen(filename, "r");
429                 if (!fp) {
430 fail:
431                         print_error("failed to load game from '%s'\n", filename);
432                         goto copy;
433                 }
434                 got = fread(game_save, sizeof(game_save[0]), 2, fp);
435                 fclose(fp);
436                 if (got != 2)
437                         goto fail;
438         }
439
440 copy:
441         /* copy track */
442         memcpy(memory + data, game_save[track & 1], length /* sizeof(game_save[0])*/);
443 }
444
445 /* game writes track with saved game */
446 static void disk_write(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
447 {
448         /* skip sync info that is provided by game and only relevant for a real disk track */
449         data += 0x200;
450         length -= 0x200;
451
452         if (length != sizeof(game_save[0])) {
453                 print_error("saving game state failed, because length of data does not match, please fix!\n");
454                 return;
455         }
456
457         /* don't save if last track is the same, because disk is written on both sides with the same data */
458         if (track == last_track) {
459                 if (memcmp(memory + data, game_save[track & 1], length)) {
460                         print_error("saving game data on other side of the disk is different, please fix!\n");
461                 }
462                 return;
463         }
464         last_track = track;
465
466         /* save game data */
467         memcpy(game_save[track & 1], memory + data, length);
468
469         /* if done with saving */
470         if ((track & 1)) {
471                 char filename[256];
472                 int gamesave_num = (track - 2) >> 1;
473                 int wrote;
474                 FILE *fp;
475
476 #if defined(_WIN32)
477                 filename[0] = '\0';
478 #else
479                 sprintf(filename, "%s/%s/", home_dir, config_gamesave_dir);
480                 mkdir(filename, 0777);
481 #endif
482                 sprintf(filename + strlen(filename), "%d%s", gamesave_num, mercenary_gamesavesuffix);
483                 fp = fopen(filename, "w");
484                 if (!fp) {
485 fail:
486                         print_error("failed to save game to '%s'\n", filename);
487                         return;
488                 }
489                 print_info("Game state saved to '%s'\n", filename);
490                 wrote = fwrite(game_save, sizeof(game_save[0]), 2, fp);
491                 fclose(fp);
492                 if (wrote != 2)
493                         goto fail;
494         }
495 }
496
497 static int shift = 0, ctrl = 0;
498
499 static void keyboard_sdl(int down, SDL_Keycode sym)
500 {
501         switch (sym) {
502         case SDLK_LCTRL:
503         case SDLK_RCTRL:
504                 ctrl = down;
505                 break;
506         }
507
508         if (ctrl) {
509                 switch (sym) {
510                 case SDLK_v:
511                         if (down) {
512                                 config_video_filter ^= 1;
513                                 print_info("video filter: %s\n", (config_video_filter) ? "on" : "off");
514                         }
515                         break;
516                 case SDLK_a:
517                         if (down) {
518                                 config_audio_filter ^= 1;
519                                 print_info("audio filter: %s\n", (config_audio_filter) ? "on" : "off");
520                         }
521                         break;
522                 case SDLK_s:
523                         if (down) {
524                                 config_amiga_speed ^= 1;
525                                 print_info("amiga speed: %s\n", (config_amiga_speed) ? "original" : "full");
526                         }
527                         break;
528                 case SDLK_r:
529                         if (down) {
530                                 config_render ^= 1;
531                                 print_info("render: %s\n", (config_render) ? "opengl" : "original");
532                         }
533                         break;
534                 case SDLK_b:
535                         if (down) {
536                                 if (config_benson_size == 0.5) {
537                                         config_benson_size = 1.0;
538                                         config_fov = FOV_NOVAGEN;
539                                 } else {
540                                         config_benson_size = 0.5;
541                                         config_fov = FOV_JOLLY;
542                                 }
543                                 print_info("benson: %s\n", (config_benson_size == 0.5) ? "half" : "normal");
544                         }
545                         break;
546                 case SDLK_c:
547                         if (down) {
548                                 if (config_ctrl_c)
549                                         quit = 1;
550                         }
551                         break;
552                 case SDLK_KP_PLUS:
553                         if (down) {
554                                 if (config_fov / 1.2 >= FOV_MIN)
555                                         config_fov /= 1.2;
556                                 print_info("FOV: %.2f\n", config_fov);
557                         }
558                         break;
559                 case SDLK_KP_MINUS:
560                         if (down) {
561                                 if (config_fov * 1.2 <= FOV_MAX)
562                                         config_fov *= 1.2;
563                                 print_info("FOV: %.2f\n", config_fov);
564                         }
565                         break;
566                 }
567                 /* do not pass keys to game while holding CTRL */
568                 return;
569         }
570
571         switch (sym) {
572         case SDLK_LSHIFT:
573                 set_key("LSH", down);
574                 shift = down;
575                 break;
576         case SDLK_RSHIFT:
577                 set_key("RSH", down);
578                 shift = down;
579                 break;
580         case SDLK_LEFT:
581                 if (shift && down) {
582                         set_key("LF", down);
583                         set_joystick(-1, -1, -1, -1, -1);
584                         break;
585                 }
586                 set_key("LF", 0);
587                 set_joystick(down, -1, -1, -1, -1);
588                 break;
589         case SDLK_RIGHT:
590                 if (shift && down) {
591                         set_key("RT", down);
592                         set_joystick(-1, -1, -1, -1, -1);
593                         break;
594                 }
595                 set_key("RT", 0);
596                 set_joystick(-1, down, -1, -1, -1);
597                 break;
598         case SDLK_UP:
599                 if (shift && down) {
600                         set_key("UP", down);
601                         set_joystick(-1, -1, -1, -1, -1);
602                         break;
603                 }
604                 set_key("UP", 0);
605                 set_joystick(-1, -1, down, -1, -1);
606                 break;
607         case SDLK_DOWN:
608                 if (shift && down) {
609                         set_key("DN", down);
610                         set_joystick(-1, -1, -1, -1, -1);
611                         break;
612                 }
613                 set_key("DN", 0);
614                 set_joystick(-1, -1, -1, down, -1);
615                 break;
616         case SDLK_END:
617                 set_joystick(-1, -1, -1, -1, down);
618                 break;
619
620         case SDLK_a: set_key("A", down); break;
621         case SDLK_b: set_key("B", down); break;
622         case SDLK_c: set_key("C", down); break;
623         case SDLK_d: set_key("D", down); break;
624         case SDLK_e: set_key("E", down); break;
625         case SDLK_f: set_key("F", down); break;
626         case SDLK_g: set_key("G", down); break;
627         case SDLK_h: set_key("H", down); break;
628         case SDLK_i: set_key("I", down); break;
629         case SDLK_j: set_key("J", down); break;
630         case SDLK_k: set_key("K", down); break;
631         case SDLK_l: set_key("L", down); break;
632         case SDLK_m: set_key("M", down); break;
633         case SDLK_n: set_key("N", down); break;
634         case SDLK_o: set_key("O", down); break;
635         case SDLK_p: set_key("P", down); break;
636         case SDLK_q: set_key("Q", down); break;
637         case SDLK_r: set_key("R", down); break;
638         case SDLK_s: set_key("S", down); break;
639         case SDLK_t: set_key("T", down); break;
640         case SDLK_u: set_key("U", down); break;
641         case SDLK_v: set_key("V", down); break;
642         case SDLK_w: set_key("W", down); break;
643         case SDLK_x: set_key("X", down); break;
644         case SDLK_y: set_key("Y", down); break;
645         case SDLK_z: set_key("Z", down); break;
646
647         case SDLK_0: set_key("0", down); break;
648         case SDLK_1: set_key("1", down); break;
649         case SDLK_2: set_key("2", down); break;
650         case SDLK_3: set_key("3", down); break;
651         case SDLK_4: set_key("4", down); break;
652         case SDLK_5: set_key("5", down); break;
653         case SDLK_6: set_key("6", down); break;
654         case SDLK_7: set_key("7", down); break;
655         case SDLK_8: set_key("8", down); break;
656         case SDLK_9: set_key("9", down); break;
657
658         case SDLK_KP_0: set_key("NP0", down); break;
659         case SDLK_KP_1: set_key("NP1", down); break;
660         case SDLK_KP_2: set_key("NP2", down); break;
661         case SDLK_KP_3: set_key("NP3", down); break;
662         case SDLK_KP_4: set_key("NP4", down); break;
663         case SDLK_KP_5: set_key("NP5", down); break;
664         case SDLK_KP_6: set_key("NP6", down); break;
665         case SDLK_KP_7: set_key("NP7", down); break;
666         case SDLK_KP_8: set_key("NP8", down); break;
667         case SDLK_KP_9: set_key("NP9", down); break;
668         case SDLK_KP_DIVIDE: set_key("NPDIV", down); break;
669         case SDLK_KP_MULTIPLY: set_key("NPMUL", down); break;
670         case SDLK_KP_MINUS: set_key("NPSUB", down); break;
671         case SDLK_KP_PLUS: set_key("NPADD", down); break;
672         case SDLK_KP_PERIOD: set_key("NPDEL", down); break;
673         // NPLPAREN and NPRPAREN are not emulated
674
675         case SDLK_F1: set_key("F1", down); break;
676         case SDLK_F2: set_key("F2", down); break;
677         case SDLK_F3: set_key("F3", down); break;
678         case SDLK_F4: set_key("F4", down); break;
679         case SDLK_F5: set_key("F5", down); break;
680         case SDLK_F6: set_key("F6", down); break;
681         case SDLK_F7: set_key("F7", down); break;
682         case SDLK_F8: set_key("F8", down); break;
683         case SDLK_F9: set_key("F9", down); break;
684         case SDLK_F10: set_key("F10", down); break;
685
686         case SDLK_SPACE: set_key("SPC", down); break;
687         case SDLK_BACKSPACE: set_key("BS", down); break;
688         case SDLK_TAB: set_key("TAB", down); break;
689         case SDLK_KP_ENTER: set_key("ENT", down); break;
690         case SDLK_RETURN: set_key("RET", down); break;
691         case SDLK_ESCAPE: set_key("ESC", down); break;
692         case SDLK_DELETE: set_key("DEL", down); break;
693         case SDLK_INSERT: set_key("HELP", down); break;
694
695         }
696 }
697
698 void audio_sdl(float *data, int length)
699 {
700         int fill, s;
701
702         /* read sound from sound buffer
703          * buffer pointer read and write is atomic, so no locking required!
704          */
705         fill = (sound_buffer_writep - sound_buffer_readp + sound_buffer_size) % sound_buffer_size;
706         if (fill < length) {
707 #ifdef DEBUG_SOUND_BUFFERING
708                 fprintf(stderr, "sound buffer underrun\n");
709 #endif
710                 /* correct read pointer as if the buffer would have 'length' of samples stored inside */
711                 sound_buffer_readp = (sound_buffer_readp + fill - length + sound_buffer_size) % sound_buffer_size;
712         }
713         for (s = 0; s < length; s++) {
714                 *data++ = sound_buffer[(sound_buffer_readp + s) % sound_buffer_size].left;
715                 *data++ = sound_buffer[(sound_buffer_readp + s) % sound_buffer_size].right;
716         }
717 #ifdef DEBUG_SOUND_BUFFERING
718         printf("fill %d = %.4f\n", length, sound_buffer[sound_buffer_readp][0]);
719 #endif
720         sound_buffer_readp =(sound_buffer_readp + length) % sound_buffer_size;
721 }
722
723 int main(int argc, char *argv[])
724 {
725         int rc;
726         int sdl_sound_chunk;
727
728         home_dir = getenv("HOME");
729         if (!home_dir)
730                 home_dir = "";
731
732         rc = parse_args(argc, argv);
733         if (rc)
734                 return 0;
735
736         /* allocate image */
737         image = calloc(IMAGE_WIDTH * IMAGE_HEIGHT * ((double_pixel_size) ? 4 : 1), 3);
738         if (!image) {
739                 print_error("Failed to allocate image buffer\n");
740                 goto done;
741         }
742
743         if ((SOUND_SAMPLERATE % IRQ_RATE)) {
744                 print_error("Sample rate must be a multiple of IRQ rate, please fix!\n");
745                 goto done;
746         }
747         if ((1000 % IRQ_RATE)) {
748                 print_error("1000 (Ticks per second) rate must be a multiple of IRQ rate, please fix!\n");
749                 goto done;
750         }
751
752         /* calculate SDL chunk size for audio
753          * it must be a power of two, but not more than the chunk size for each IRQ!
754          */
755         for (sdl_sound_chunk = 2; sdl_sound_chunk <= (SOUND_SAMPLERATE / IRQ_RATE); sdl_sound_chunk <<= 1)
756                 ;
757         sdl_sound_chunk >>= 1;
758 //      printf("samples per IRQ = %d, samples per SDL audio = %d\n", SOUND_SAMPLERATE / IRQ_RATE, sdl_sound_chunk); exit(0);
759
760         /* allocate sound buffers */
761         sound_buffer_size = SOUND_SAMPLERATE / IRQ_RATE * SOUND_CHUNKS;
762         sound_buffer = calloc(sound_buffer_size, sizeof(*sound_buffer));
763         if (!sound_buffer) {
764                 print_error("Failed to allocate image buffer\n");
765                 goto done;
766         }
767
768         /* allocate memory */
769         memory = calloc(MEMORY_SIZE, 1);
770         if (!memory) {
771                 print_error("Failed to allocate cpu's memory\n");
772                 goto done;
773         }
774         stop_event = calloc(MEMORY_SIZE, 1);
775         if (!stop_event) {
776                 print_error("Failed to allocate cpu's stop_event memory\n");
777                 goto done;
778         }
779         chipreg = calloc(IOSIZE, 1);
780         if (!chipreg) {
781                 print_error("Failed to allocate chip register\n");
782                 goto done;
783         }
784
785         /* init cpu code */
786         execute_init(MEMORY_SIZE, memory, stop_event, chipreg, io_read, io_write, mercenary_stop_at);
787
788         /* init disk emulation */
789         disk_init(disk_read, disk_write);
790
791         /* load binary */
792         mercenary_load();
793
794         /* patch some stuff */
795         mercenary_patch();
796
797         /* init SDL and OpenGL */
798         rc = init_sdl(argv[0], (config_debug_opengl) ? SCREEN_WIDTH * 2 : SCREEN_WIDTH * 3, (config_debug_opengl) ? SCREEN_HEIGHT * 4 : SCREEN_HEIGHT * 3, SOUND_SAMPLERATE, sdl_sound_chunk, keyboard_sdl, audio_sdl, config_multisampling);
799         if (rc < 0)
800                 goto done;
801         rc = init_opengl((double_pixel_size) ? IMAGE_WIDTH * 2 : IMAGE_WIDTH, (double_pixel_size) ? IMAGE_HEIGHT * 2 : IMAGE_HEIGHT);
802         if (rc < 0)
803                 goto done;
804         resize_opengl((config_debug_opengl) ? SCREEN_WIDTH * 2 : SCREEN_WIDTH * 3, (config_debug_opengl) ? SCREEN_HEIGHT * 4 : SCREEN_HEIGHT * 3);
805
806         /* init audio filter */
807         sound_init_filter(SOUND_SAMPLERATE);
808
809         /* start cpu */
810         reset_cpu();
811
812         if (config_skip_intro) {
813                 int event;
814
815                 print_info("*** Skipping intro, fast forwarding... ***\n\n");
816                 do {
817                         execute_cpu(0, &event);
818                 } while (event != STOP_AT_CLEAR_SCREEN1);
819                 do {
820                         execute_cpu(0, &event);
821                 } while (event != STOP_AT_WAIT_VBL);
822         }
823
824         print_info("**********************************\n");
825         print_info("* Welcome to Mercenary Reloaded! *\n");
826         print_info("**********************************\n\n");
827         print_info("Press CTRL + cursor keys to select inventory or pickup/drop item.\n");
828         print_info("Press CTRL + f to toggle full screen.\n");
829         print_info("Press CTRL + s to toggle rendering speed.\n");
830         print_info("Press CTRL + v to toggle video filter.\n");
831         print_info("Press CTRL + a to toggle audio filter.\n");
832         print_info("Press CTRL + r to toggle rendering with opengl or orignal code.\n");
833         print_info("Press CTRL + Keypad Plus to decrement FOV.\n");
834         print_info("Press CTRL + Keypad Minus to increment FOV.\n");
835         print_info("Press CTRL + c to exit game.\n\n");
836         print_info("Use '--help' as command line option for configuration settings.\n\n");
837
838         /* run game */
839         main_loop();
840
841 done:
842         exit_opengl();
843         exit_sdl();
844
845         if (chipreg)
846                 free(chipreg);
847         if (stop_event)
848                 free(stop_event);
849         if (memory)
850                 free(memory);
851         if (sound_buffer)
852                 free(sound_buffer);
853         if (image)
854                 free(image);
855
856         return 0;
857 }
858