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