Fix rendering buffer handling
[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 "../libtext/text.h"
37 #include "mercenary.h"
38 #include "render.h"
39
40 #define FOV_MIN         10.0
41 #define FOV_NOVAGEN     64.0
42 #define FOV_JOLLY       80.0
43 #define FOV_MAX         170.0
44
45 static int config_ctrl_c = 0;
46 static int config_amiga_speed = 1;
47 #warning fixme: make use of 10 for intro, then be as fast as given
48 static double config_fps = 16.0;
49 static const char *config_gamesave_dir = ".mercenary";
50 static int config_video_filter = 1;
51 static int config_audio_filter = 1;
52 static int config_render = 0;
53 static int config_skip_intro = 0;
54 static int config_multisampling = 16;
55 static double config_fov = FOV_NOVAGEN;
56 static double config_benson_size = 1.0;
57 static int config_debug_transparent = 0;
58 static int config_debug_opengl = 0;
59 /* render improvements */
60 static int config_improve_extend_roads = 1;     /* set to 1 to extend roads */
61
62 #define CPU_SPEED       7093790.0;
63
64 #define SOUND_SAMPLERATE 48000
65 /* - game IRQ rate
66  * - must be used for sound rendering chunk
67  */
68 #define IRQ_RATE        50
69 /* numbe of buffer chunks to dejitter:
70  * - SDL render interval
71  * - sound rendering interval
72  * - sound card interval
73  * 4 should be minimum, if video rate is >=50 Hz
74  */
75 #define SOUND_CHUNKS    4
76
77 /* test sound to check if buffer does not overflow / underrun */
78 //#define DEBUG_SOUND_BUFFERING
79
80 #define IOSIZE          0x1000 /* bytes in io space */
81 #define MEMORY_SIZE     0x80000
82 static uint8_t *memory = NULL;
83 static uint8_t *stop_event = NULL;
84 static uint8_t *image = NULL;
85 static uint8_t *help_osd = NULL;
86 static uint8_t *info_osd = NULL;
87 static int help_view = 1;
88 static int32_t osd_timer = 0;
89 #define SCREEN_WIDTH    320
90 #define SCREEN_HEIGHT   200
91 #define IMAGE_WIDTH     320
92 #define IMAGE_HEIGHT    200
93 #define BENSON_AT_LINE  136
94 #define IMAGE_DIWSTART  0x2c
95 #define HELP_ALPHA      0xd0
96 #define OSD_WIDTH       320
97 #define OSD_HEIGHT      16
98 static uint16_t *chipreg = NULL;
99 static stereo_t *sound_buffer = NULL; /* sound buffer memory */
100 static int sound_buffer_size; /* buffer sample size */
101 static int sound_buffer_writep; /* write pointer at buffer */
102 static int sound_buffer_readp; /* read pointer at buffer */
103 static int double_pixel_size = 1; /* render in double size, so each pixle is 2*2 pixles wide */
104 static double benson_size; /* render size of benson */
105 static int render_legacy = 0; /* render original amiga screen, if set */
106 static int render_improved = 0; /* render improved image, if set */
107 static int debug_opengl = 0; /* render both, amiga screen and  improved image, if set */
108 static int intro_skipped = 0; /* indicated if we already have landed */
109
110 static const char *home_dir;
111
112 static int quit = 0;
113
114 int parse_args(int argc, char *argv[])
115 {
116         int i = 1;
117
118         while (argc > i) {
119                 if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
120                         print_info("Usage: %s\n", argv[0]);
121                         print_info(" -s --render-speed original | fast\n");
122                         print_info("        Set speed of rendering to original Amiga or fast speed.\n");
123                         print_info("    --fps <fps>\n");
124                         print_info("        Set frames per second for fast rate (default = %.1f).\n", config_fps);
125                         print_info(" -v --video-filter on | off\n");
126                         print_info("        Set video filter.\n");
127                         print_info(" -a --audio-filter on | off\n");
128                         print_info("        Set audio filter.\n");
129                         print_info(" -r --render original | opengl\n");
130                         print_info("        Set speed of rendering to original Amiga or OpenGL.\n");
131                         print_info(" -b --benson normal | half\n");
132                         print_info("        Size of 'Benson' (control panel).\n");
133                         print_info(" -m --multisampling <samples>\n");
134                         print_info("        Use multisampling (default = %d) to render the scene.\n", config_multisampling);
135                         print_info(" -f --fov <%.0f..%.0f..%.0f>\n", FOV_MIN, FOV_NOVAGEN, FOV_MAX);
136                         print_info("        Set field-of-view. Default is %.0f.\n", FOV_NOVAGEN);
137                         print_info(" -i --skip-intro\n");
138                         print_info("        Skip intro sequence approaching to Eris space port.\n");
139                         print_info("Debug options:\n");
140                         print_info(" -o --debug-opengl\n");
141                         print_info("        Use split screen to display both Amiga and OpenGL rendering.\n");
142                         print_info("    --debug-transparent\n");
143                         print_info("        Draw all things half transparent.\n");
144                         print_info("    --ctrl-c\n");
145                         print_info("        Use CTRL+C to exit game (used for development)\n");
146                         return -1;
147                 } else
148                 if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--render-speed")) {
149                         i++;
150                         if (argc == i) {
151 missing_parameter:
152                                 print_info("Missing parameter, use '--help'!\n");
153                                 return -1;
154                         }
155                         if (!strcmp(argv[i], "original"))
156                                 config_amiga_speed = 1;
157                         else
158                         if (!strcmp(argv[i], "fast"))
159                                 config_amiga_speed = 0;
160                         else {
161 illegal_parameter:
162                                 print_info("Illegal parameter, use '--help'!\n");
163                                 return -1;
164                         }
165                 } else
166                 if (!strcmp(argv[i], "--fps")) {
167                         i++;
168                         if (argc == i)
169                                 goto missing_parameter;
170                         config_fps = atof(argv[i]);
171                         if (config_fov <= 0.0)
172                                 goto illegal_parameter;
173                 } else
174                 if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--video-filter")) {
175                         i++;
176                         if (argc == i)
177                                 goto missing_parameter;
178                         if (!strcmp(argv[i], "on"))
179                                 config_video_filter = 1;
180                         else
181                         if (!strcmp(argv[i], "off"))
182                                 config_video_filter = 0;
183                         else
184                                 goto illegal_parameter;
185                 } else
186                 if (!strcmp(argv[i], "-a") || !strcmp(argv[i], "--audio-filter")) {
187                         i++;
188                         if (argc == i)
189                                 goto missing_parameter;
190                         if (!strcmp(argv[i], "on"))
191                                 config_audio_filter = 1;
192                         else
193                         if (!strcmp(argv[i], "off"))
194                                 config_audio_filter = 0;
195                         else
196                                 goto illegal_parameter;
197                 } else
198                 if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--render")) {
199                         i++;
200                         if (argc == i)
201                                 goto missing_parameter;
202                         if (!strcmp(argv[i], "original"))
203                                 config_render = 0;
204                         else
205                         if (!strcmp(argv[i], "opengl"))
206                                 config_render = 1;
207                         else
208                                 goto illegal_parameter;
209                 } else
210                 if (!strcmp(argv[i], "-b") || !strcmp(argv[i], "--benson")) {
211                         i++;
212                         if (argc == i)
213                                 goto missing_parameter;
214                         if (!strcmp(argv[i], "normal"))
215                                 config_benson_size = 1.0;
216                         else
217                         if (!strcmp(argv[i], "half")) {
218                                 config_benson_size = 0.5;
219                                 if (config_fov == FOV_NOVAGEN)
220                                         config_fov = FOV_JOLLY;
221                         } else
222                                 goto illegal_parameter;
223                 } else
224                 if (!strcmp(argv[i], "-m") || !strcmp(argv[i], "--multisampling")) {
225                         i++;
226                         if (argc == i)
227                                 goto missing_parameter;
228                         config_multisampling = atoi(argv[i]);
229                 } else
230                 if (!strcmp(argv[i], "-f") || !strcmp(argv[i], "--fov")) {
231                         i++;
232                         if (argc == i)
233                                 goto missing_parameter;
234                         config_fov = atof(argv[i]);
235                         if (config_fov < 1.0 || config_fov > 179.0)
236                                 goto illegal_parameter;
237                 } else
238                 if (!strcmp(argv[i], "-i") || !strcmp(argv[i], "--skip-intro")) {
239                         config_skip_intro = 1;
240                 } else
241                 if (!strcmp(argv[i], "-o") || !strcmp(argv[i], "--debug-opengl")) {
242                         config_debug_opengl = 1;
243                 } else
244                 if (!strcmp(argv[i], "--debug-transparent")) {
245                         config_debug_transparent = 1;
246                 } else
247                 if (!strcmp(argv[i], "--ctrl-c")) {
248                         config_ctrl_c = 1;
249                 } else {
250                         print_info("Illegal option '%s', use '--help'!\n", argv[i]);
251                         return -1;
252                 }
253                 i++;
254         }
255
256         return 0;
257 }
258
259 static void skip_intro(void)
260 {
261         int event;
262         double render_delay = 0.0;
263         double cycle_count;
264
265         if (intro_skipped)
266                 return;
267
268         print_info("*** Skipping intro, fast forwarding... ***\n\n");
269         do {
270                 /* render, if not delayed */
271                 if (render_delay <= 0.0) {
272                         cycle_count = 0;
273                         do {
274                                 cycle_count += execute_cpu(0, &event);
275                         } while (event != STOP_AT_WAIT_VBL && event != STOP_AT_CLEAR_SCREEN1);
276                         render_delay += (double)cycle_count / CPU_SPEED;
277                 }
278                 /* VBL */
279                 execute_cpu(3, NULL);
280                 /* count down render delay */
281                 if (render_delay) {
282                         render_delay -= 1.0 / (double)IRQ_RATE;
283                         if (render_delay < 0.0)
284                                 render_delay = 0.0;
285                 }
286         } while (event != STOP_AT_CLEAR_SCREEN1);
287
288         intro_skipped = 1;
289 }
290
291 static void special_event(int event)
292 {
293         if (render_improved)
294                 render_capture_event(event);
295 }
296
297 static void main_loop(void)
298 {
299         double frame_step, frame_time = 0.0, frame_render = 1;
300         int had_first_irq = 0;
301         int render_improved_rc;
302         static uint32_t current_time, last_time = 0, diff;
303         int i, rc;
304         int space, length;
305         int cycle_count, event = STOP_AT_END;
306         double render_delay = 0.0;
307         uint32_t palette_address;
308         uint16_t palette[16];
309
310         last_time = SDL_GetTicks();
311
312         /* render result on window */
313         while (!quit) {
314 #warning oder ganz anders: bevor landung machen wir amiga-rate als interpolation
315                 /* if we are in interstellar fligt, we use 50 Hz */
316                 /* if we are approaching to Eris Space Port, we use 10 Hz */
317                 /* else we use whatever frame rate the user wants */
318                 if (render_capture_is_interstellar())
319                         frame_step = vbl_duration * 50.0;
320                 else
321                         frame_step = vbl_duration * config_fps;
322                 if (frame_step > 1.0)
323                         frame_step = 1.0;
324                 /* handle SDL events */
325                 rc = event_sdl();
326                 if (rc)
327                         break;
328
329                 /* clear screen */
330                 opengl_clear();
331
332                 /* initialize rendering */
333                 debug_opengl = config_debug_opengl;
334                 benson_size = config_benson_size;
335                 render_legacy = (!config_render) || debug_opengl;
336                 render_improved = config_render || debug_opengl;
337                 if (!render_improved) {
338                         /* be sure to clean all capture history, so we don't get glichtes when turning on improved rendering again */
339                         render_capture_reset();
340                 }
341                 if (render_improved)
342                         opengl_viewport_improved(debug_opengl, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, benson_size);
343                 /* STEP 1: let the CPU render/process the game, also improve rendering via OpenGL, if enabled */
344                 /* amgia speed: don't render if we still delay */
345                 /* non amiga speed: render if we need a new frame */
346                 /* NOTE: at input event we must render after every VBL, so we do this in every loop */
347                 /* in case of help view: stop cpu after first IRQ, regardless of other options */
348                 /* NOTE: We need initial IRQ, so we have out copper list initialized */
349                 if (((frame_render && !config_amiga_speed)
350                   || (config_amiga_speed && render_delay <= 0.0)
351                   || event == STOP_AT_WAIT_INPUT)
352                 && !(had_first_irq && help_view)) {
353                         frame_render = 0;
354                         /* start capturing for improved graphics */
355                         if (render_improved)
356                                 render_capture_start(config_fov, config_improve_extend_roads, config_debug_transparent);
357
358                         /* execute until the rendered image is ready (wait for VBL) */
359                         cycle_count = 0;
360                         do {
361                                 cycle_count += execute_cpu(0, &event);
362                                 /* handle special events */
363                                 special_event(event);
364                                 if (event == STOP_AT_CLEAR_SCREEN1)
365                                         intro_skipped = 1;
366                         } while (event != STOP_AT_WAIT_VBL && event != STOP_AT_WAIT_INPUT);
367                         /* stop capturing for improved graphics */
368                         if (render_improved)
369                                 render_capture_stop();
370                         /* copy palette */
371                         palette_address = mercenary_palette_view();
372                         for (i = 0; i < 16; i++)
373                                 palette[i] = m68k_read_memory_16(palette_address + i*2);
374                         /* for amiga speed: set delay by the number of cycles */
375                         if (config_amiga_speed)
376                                 render_delay += (double)cycle_count / CPU_SPEED;
377                 }
378                 /* render improved graphics, interpolate, if required */
379                 if (render_improved)
380                         render_improved_rc = render_all_items((config_amiga_speed) ? 1.0 : frame_time);
381                 else
382                         render_improved_rc = -1;
383                 /* advance frame time, if we are not in help view  */
384                 if (!(had_first_irq && help_view)) {
385 //printf("frame rate: %.6f, frame-step=%.5f frame-time=%.5f\n", 1.0 / vbl_duration, frame_step,frame_time);
386                         frame_time += frame_step;
387                         if (frame_time >= 1.0) {
388                                 frame_time -= 1.0;
389                                 frame_render = 1;
390                         }
391                 }
392
393                 /* STEP 2: transfer legacy image (or just benson) in memory to OpenGL texture */
394                 if (had_first_irq) {
395                         /* render game view without benson
396                          * because benson is not updated before VBL IRQ, we don't want old image from double buffer
397                          */
398                         if (render_legacy || render_improved_rc)
399                                 emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, 0, BENSON_AT_LINE, double_pixel_size);
400                 }
401                 /* render benson + osd ontop of improved opengl rendering, if enabled */
402                 if (render_improved && render_improved_rc == 0) {
403                         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);
404                         if (help_view)
405                                 opengl_blit_osd(0, help_osd, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, benson_size, 1.0, 1.0, 0.0, 0.0);
406                         if (osd_timer) {
407                                 opengl_blit_osd(1, info_osd, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, benson_size, 0.5, 0.04, 0.5, -0.95);
408                                 if (osd_timer - (int32_t)SDL_GetTicks() < 0)
409                                         osd_timer = 0;
410                         }
411                 }
412                 /* setup viewport for legacy image and render image, if enabled */
413                 /* also render legacy, if render_improved failed due to not (yet) available items */
414                 if (render_legacy || (render_improved && render_improved_rc)) {
415                         opengl_viewport_legacy(debug_opengl);
416                         opengl_blit_legacy(image, config_video_filter);
417                         if (help_view)
418                                 opengl_blit_osd(0, help_osd, config_video_filter, 0, 0.0, 0, 1.0, 1.0, 0.0, 0.0);
419                         if (osd_timer) {
420                                 opengl_blit_osd(1, info_osd, config_video_filter, 0, 0.0, 0, 0.5, 0.04, 0.5, -0.95);
421                                 if (osd_timer - (int32_t)SDL_GetTicks() < 0)
422                                         osd_timer = 0;
423                         }
424                 }
425
426                 /* at this point we are ready with our image, so we display */
427                 swap_sdl();
428                 /* measure frame rate */
429                 framerate_measure();
430
431                 /* STEP 3: execute interrupt at rate of 50Hz, render sound */
432                 /* only do this, if we are not in help view */
433                 /* NOTE: We need initial IRQ, so we have out copper list initialized */
434                 if (!(had_first_irq && help_view)) {
435                         current_time = SDL_GetTicks();
436                         diff = current_time - last_time;
437                         /* in case of timer glitch, execute IRQ only by maximum number of SOUND_CHUNKS */
438                         if (diff > 1000 * SOUND_CHUNKS / IRQ_RATE) {
439                                 diff = 1000 * SOUND_CHUNKS / IRQ_RATE;
440                                 last_time = current_time - 1000 * SOUND_CHUNKS / IRQ_RATE;
441                         }
442                         while (diff > 1000 / IRQ_RATE) {
443                                 /* trigger and execute IRQ 3 = VBL */
444                                 execute_cpu(3, NULL);
445                                 had_first_irq = 1;
446                                 /* transfer benson without game view
447                                  * because we only got benson refreshed during VBL IRQ
448                                  */
449                                 emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, BENSON_AT_LINE, IMAGE_HEIGHT, double_pixel_size);
450                                 /* render sound to sound buffer
451                                  * buffer pointer read and write is atomic, so no locking required!
452                                  */
453                                 space = (sound_buffer_readp - sound_buffer_writep - 1 + sound_buffer_size) % sound_buffer_size;
454                                 if (space < SOUND_SAMPLERATE / IRQ_RATE) {
455 #ifdef DEBUG_SOUND_BUFFERING
456                                         fprintf(stderr, "sound buffer overflow\n");
457 #endif
458                                         length = space;
459                                 } else
460                                         length = SOUND_SAMPLERATE / IRQ_RATE;
461 #ifdef DEBUG_SOUND_BUFFERING
462                                 printf("can write %d, write %d\n", space, length);
463                                 static int cnt = 0;
464                                 int s;
465                                 for (s = 0; s < length; s++) {
466                                         sound_buffer[(sound_buffer_writep + s) % sound_buffer_size].left =
467                                         sound_buffer[(sound_buffer_writep + s) % sound_buffer_size].right
468                                                 = sin(2 * M_PI * 999 * cnt / SOUND_SAMPLERATE)
469                                                 * sin(2 * M_PI * 21 * cnt / SOUND_SAMPLERATE)
470                                                 * sin(2 * M_PI * 0.5 * cnt / SOUND_SAMPLERATE);
471                                          cnt++;
472                                 }
473 #else
474                                 render_sound(memory, sound_buffer, sound_buffer_size, sound_buffer_writep, length, config_audio_filter);
475 #endif
476                                 sound_buffer_writep = (sound_buffer_writep + length) % sound_buffer_size;
477                                 diff -= 1000 / IRQ_RATE;
478                                 last_time += 1000 / IRQ_RATE;
479
480                                 /* count down render delay */
481                                 if (render_delay) {
482                                         render_delay -= 1.0 / (double)IRQ_RATE;
483                                         if (render_delay < 0.0)
484                                                 render_delay = 0.0;
485                                 }
486                         }
487                 }
488         }
489 }
490
491 static uint16_t io_read(uint32_t address)
492 {
493         uint16_t value = 0xffff;
494
495         /* joystick and fire button */
496         if (address == 0xbfe000 || address == 0xdff00c)
497                 value &= emulate_joystick_read(address);
498         /* keyboard */
499         if (address == 0xbfec00 || address == 0xbfed00 || address == 0xbfee00)
500                 value &= emulate_keyboard_read(address);
501         /* diskette */
502         if (address == 0xbfd100 || address == 0xbfe000 || address == 0xdff01a || address == 0xdff01e)
503                 value &= emulate_disk_read(address);
504
505         return value;
506 }
507
508 static void io_write(uint32_t address, uint16_t value)
509 {
510         /* dmacon and sound registers */
511         if (address == 0xdff096 || address == 0xdff09a || (address >= 0xdff0a0 && address <= 0xdff0df))
512                 emulate_sound_write(address, value, SOUND_SAMPLERATE);
513         if (address == 0xbfd100 || (address >= 0xdff020 && address <= 0xdff024))
514                 emulate_disk_write(address, value);
515 }
516
517 /* two tracks with 0x1820 words of length */
518 static uint8_t game_save[2][0x1820 << 1];
519 static int last_track = 0;
520
521 /* game reads track with saved game */
522 static void disk_read(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
523 {
524         if (length > sizeof(game_save[0])) {
525                 print_error("loading game state failed, because length exceeds game save data size, please fix!\n");
526                 return;
527         }
528
529         /* if even track is selected, load game */
530         if (!(track & 1)) {
531                 char filename[256];
532                 int gamesave_num = (track - 2) >> 1;
533                 int got;
534                 FILE *fp;
535
536                 memset(game_save, 0, sizeof(game_save)); /* clear so make the game fail, if we fail */
537 #if defined(_WIN32)
538                 filename[0] = '\0';
539 #else
540                 sprintf(filename, "%s/%s/", home_dir, config_gamesave_dir);
541                 mkdir(filename, 0777);
542 #endif
543                 sprintf(filename + strlen(filename), "%d%s", gamesave_num, mercenary_gamesavesuffix);
544                 fp = fopen(filename, "r");
545                 if (!fp) {
546 fail:
547                         print_error("failed to load game from '%s'\n", filename);
548                         goto copy;
549                 }
550                 got = fread(game_save, sizeof(game_save[0]), 2, fp);
551                 fclose(fp);
552                 if (got != 2)
553                         goto fail;
554         }
555
556 copy:
557         /* copy track */
558         memcpy(memory + data, game_save[track & 1], length /* sizeof(game_save[0])*/);
559 }
560
561 /* game writes track with saved game */
562 static void disk_write(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
563 {
564         /* skip sync info that is provided by game and only relevant for a real disk track */
565         data += 0x200;
566         length -= 0x200;
567
568         if (length != sizeof(game_save[0])) {
569                 print_error("saving game state failed, because length of data does not match, please fix!\n");
570                 return;
571         }
572
573         /* don't save if last track is the same, because disk is written on both sides with the same data */
574         if (track == last_track) {
575                 if (memcmp(memory + data, game_save[track & 1], length)) {
576                         print_error("saving game data on other side of the disk is different, please fix!\n");
577                 }
578                 return;
579         }
580         last_track = track;
581
582         /* save game data */
583         memcpy(game_save[track & 1], memory + data, length);
584
585         /* if done with saving */
586         if ((track & 1)) {
587                 char filename[256];
588                 int gamesave_num = (track - 2) >> 1;
589                 int wrote;
590                 FILE *fp;
591
592 #if defined(_WIN32)
593                 filename[0] = '\0';
594 #else
595                 sprintf(filename, "%s/%s/", home_dir, config_gamesave_dir);
596                 mkdir(filename, 0777);
597 #endif
598                 sprintf(filename + strlen(filename), "%d%s", gamesave_num, mercenary_gamesavesuffix);
599                 fp = fopen(filename, "w");
600                 if (!fp) {
601 fail:
602                         print_error("failed to save game to '%s'\n", filename);
603                         return;
604                 }
605                 print_info("Game state saved to '%s'\n", filename);
606                 wrote = fwrite(game_save, sizeof(game_save[0]), 2, fp);
607                 fclose(fp);
608                 if (wrote != 2)
609                         goto fail;
610         }
611 }
612
613 static void osd_info(const char *param, const char *value)
614 {
615         char line[41] = "                                        ";
616
617         if (param[0]) {
618                 strncpy(line + 21 - strlen(param), param, strlen(param));
619                 line[22] = ':';
620         }
621         if (strlen(value) > 15) {
622                 print_error("string too long\n");
623                 return;
624         }
625         strncpy(line + 25, value, strlen(value));
626         text_render(info_osd, OSD_WIDTH, OSD_HEIGHT, line, 0x00, 4, 0, 0, 1);
627         osd_timer = SDL_GetTicks() + 2500;
628 }
629
630 static int shift = 0, ctrl = 0;
631
632 static void keyboard_sdl(int down, SDL_Keycode sym)
633 {
634         switch (sym) {
635         case SDLK_LCTRL:
636         case SDLK_RCTRL:
637                 ctrl = down;
638                 break;
639         }
640
641         if (ctrl && down) {
642                 switch (sym) {
643                 case SDLK_h:
644                         help_view ^= 1;
645                         break;
646                 case SDLK_v:
647                         config_video_filter ^= 1;
648                         osd_info("video filter", (config_video_filter) ? "on" : "off");
649                         break;
650                 case SDLK_a:
651                         config_audio_filter ^= 1;
652                         osd_info("audio filter", (config_audio_filter) ? "on" : "off");
653                         break;
654                 case SDLK_s:
655                         config_amiga_speed ^= 1;
656                         osd_info("render speed", (config_amiga_speed) ? "original" : "fast");
657                         break;
658                 case SDLK_r:
659                         config_render ^= 1;
660                         osd_info("render mode", (config_render) ? "OpenGL" : "original");
661                         break;
662                 case SDLK_b:
663                         if (!config_render) {
664                                 osd_info("", "not applicable");
665                                 break;
666                         }
667                         if (config_benson_size == 0.5) {
668                                 config_benson_size = 1.0;
669                                 config_fov = FOV_NOVAGEN;
670                         } else {
671                                 config_benson_size = 0.5;
672                                 config_fov = FOV_JOLLY;
673                         }
674                         osd_info("Benson size", (config_benson_size == 0.5) ? "half" : "normal");
675                         break;
676                 case SDLK_i:
677                         if (!intro_skipped)
678                                 skip_intro();
679                         else
680                                 osd_info("", "not applicable");
681                         break;
682                 case SDLK_c:
683                         if (config_ctrl_c)
684                                 quit = 1;
685                         break;
686                 case SDLK_KP_PLUS:
687                         if (config_fov / 1.2 >= FOV_MIN)
688                                 config_fov /= 1.2;
689                         disp_fov:
690                         {
691                                 char text[16];
692                                 sprintf(text, "%.2f", config_fov);
693                                 osd_info("FOV", text);
694                         }
695                         break;
696                 case SDLK_KP_MINUS:
697                         if (config_fov * 1.2 <= FOV_MAX)
698                                 config_fov *= 1.2;
699                         goto disp_fov;
700                 }
701                 /* do not pass keys to game while holding CTRL */
702                 return;
703         }
704
705         if (sym == SDLK_PAUSE && down)
706                 help_view ^= 1;
707
708         /* in help view we don't need to forward keypresses */
709         if (help_view)
710                 return;
711
712         switch (sym) {
713         case SDLK_LSHIFT:
714                 set_key("LSH", down);
715                 shift = down;
716                 break;
717         case SDLK_RSHIFT:
718                 set_key("RSH", down);
719                 shift = down;
720                 break;
721         case SDLK_LEFT:
722                 if (shift && down) {
723                         set_key("LF", down);
724                         set_joystick(-1, -1, -1, -1, -1);
725                         break;
726                 }
727                 set_key("LF", 0);
728                 set_joystick(down, -1, -1, -1, -1);
729                 break;
730         case SDLK_RIGHT:
731                 if (shift && down) {
732                         set_key("RT", down);
733                         set_joystick(-1, -1, -1, -1, -1);
734                         break;
735                 }
736                 set_key("RT", 0);
737                 set_joystick(-1, down, -1, -1, -1);
738                 break;
739         case SDLK_UP:
740                 if (shift && down) {
741                         set_key("UP", down);
742                         set_joystick(-1, -1, -1, -1, -1);
743                         break;
744                 }
745                 set_key("UP", 0);
746                 set_joystick(-1, -1, down, -1, -1);
747                 break;
748         case SDLK_DOWN:
749                 if (shift && down) {
750                         set_key("DN", down);
751                         set_joystick(-1, -1, -1, -1, -1);
752                         break;
753                 }
754                 set_key("DN", 0);
755                 set_joystick(-1, -1, -1, down, -1);
756                 break;
757         case SDLK_END:
758                 set_joystick(-1, -1, -1, -1, down);
759                 break;
760
761         case SDLK_a: set_key("A", down); break;
762         case SDLK_b: set_key("B", down); break;
763         case SDLK_c: set_key("C", down); break;
764         case SDLK_d: set_key("D", down); break;
765         case SDLK_e: set_key("E", down); break;
766         case SDLK_f: set_key("F", down); break;
767         case SDLK_g: set_key("G", down); break;
768         case SDLK_h: set_key("H", down); break;
769         case SDLK_i: set_key("I", down); break;
770         case SDLK_j: set_key("J", down); break;
771         case SDLK_k: set_key("K", down); break;
772         case SDLK_l: set_key("L", down); break;
773         case SDLK_m: set_key("M", down); break;
774         case SDLK_n: set_key("N", down); break;
775         case SDLK_o: set_key("O", down); break;
776         case SDLK_p: set_key("P", down); break;
777         case SDLK_q: set_key("Q", down); break;
778         case SDLK_r: set_key("R", down); break;
779         case SDLK_s: set_key("S", down); break;
780         case SDLK_t: set_key("T", down); break;
781         case SDLK_u: set_key("U", down); break;
782         case SDLK_v: set_key("V", down); break;
783         case SDLK_w: set_key("W", down); break;
784         case SDLK_x: set_key("X", down); break;
785         case SDLK_y: set_key("Y", down); break;
786         case SDLK_z: set_key("Z", down); break;
787
788         case SDLK_0: set_key("0", down); break;
789         case SDLK_1: set_key("1", down); break;
790         case SDLK_2: set_key("2", down); break;
791         case SDLK_3: set_key("3", down); break;
792         case SDLK_4: set_key("4", down); break;
793         case SDLK_5: set_key("5", down); break;
794         case SDLK_6: set_key("6", down); break;
795         case SDLK_7: set_key("7", down); break;
796         case SDLK_8: set_key("8", down); break;
797         case SDLK_9: set_key("9", down); break;
798
799         case SDLK_KP_0: set_key("NP0", down); break;
800         case SDLK_KP_1: set_key("NP1", down); break;
801         case SDLK_KP_2: set_key("NP2", down); break;
802         case SDLK_KP_3: set_key("NP3", down); break;
803         case SDLK_KP_4: set_key("NP4", down); break;
804         case SDLK_KP_5: set_key("NP5", down); break;
805         case SDLK_KP_6: set_key("NP6", down); break;
806         case SDLK_KP_7: set_key("NP7", down); break;
807         case SDLK_KP_8: set_key("NP8", down); break;
808         case SDLK_KP_9: set_key("NP9", down); break;
809         case SDLK_KP_DIVIDE: set_key("NPDIV", down); break;
810         case SDLK_KP_MULTIPLY: set_key("NPMUL", down); break;
811         case SDLK_KP_MINUS: set_key("NPSUB", down); break;
812         case SDLK_KP_PLUS: set_key("NPADD", down); break;
813         case SDLK_KP_PERIOD: set_key("NPDEL", down); break;
814         // NPLPAREN and NPRPAREN are not emulated
815
816         case SDLK_F1: set_key("F1", down); break;
817         case SDLK_F2: set_key("F2", down); break;
818         case SDLK_F3: set_key("F3", down); break;
819         case SDLK_F4: set_key("F4", down); break;
820         case SDLK_F5: set_key("F5", down); break;
821         case SDLK_F6: set_key("F6", down); break;
822         case SDLK_F7: set_key("F7", down); break;
823         case SDLK_F8: set_key("F8", down); break;
824         case SDLK_F9: set_key("F9", down); break;
825         case SDLK_F10: set_key("F10", down); break;
826
827         case SDLK_SPACE: set_key("SPC", down); break;
828         case SDLK_BACKSPACE: set_key("BS", down); break;
829         case SDLK_TAB: set_key("TAB", down); break;
830         case SDLK_KP_ENTER: set_key("ENT", down); break;
831         case SDLK_RETURN: set_key("RET", down); break;
832         case SDLK_ESCAPE: set_key("ESC", down); break;
833         case SDLK_DELETE: set_key("DEL", down); break;
834         case SDLK_INSERT: set_key("HELP", down); break;
835
836         }
837 }
838
839 void audio_sdl(float *data, int length)
840 {
841         int fill, s;
842
843         /* read sound from sound buffer
844          * buffer pointer read and write is atomic, so no locking required!
845          */
846         fill = (sound_buffer_writep - sound_buffer_readp + sound_buffer_size) % sound_buffer_size;
847         if (fill < length) {
848 #ifdef DEBUG_SOUND_BUFFERING
849                 fprintf(stderr, "sound buffer underrun\n");
850 #endif
851                 /* correct read pointer as if the buffer would have 'length' of samples stored inside */
852                 sound_buffer_readp = (sound_buffer_readp + fill - length + sound_buffer_size) % sound_buffer_size;
853         }
854         for (s = 0; s < length; s++) {
855                 *data++ = sound_buffer[(sound_buffer_readp + s) % sound_buffer_size].left;
856                 *data++ = sound_buffer[(sound_buffer_readp + s) % sound_buffer_size].right;
857         }
858 #ifdef DEBUG_SOUND_BUFFERING
859         printf("fill %d = %.4f\n", length, sound_buffer[sound_buffer_readp][0]);
860 #endif
861         sound_buffer_readp =(sound_buffer_readp + length) % sound_buffer_size;
862 }
863
864 void sound_irq(void)
865 {
866         /* trigger and execute IRQ 4 = sound */
867         execute_cpu(4, NULL);
868 }
869
870 int main(int argc, char *argv[])
871 {
872         int rc;
873         int sdl_sound_chunk;
874
875         home_dir = getenv("HOME");
876         if (!home_dir)
877                 home_dir = "";
878
879         rc = parse_args(argc, argv);
880         if (rc)
881                 return 0;
882
883         /* allocate image */
884         image = calloc(IMAGE_WIDTH * IMAGE_HEIGHT * ((double_pixel_size) ? 4 : 1), 3);
885         if (!image) {
886                 print_error("Failed to allocate image buffer\n");
887                 goto done;
888         }
889
890         if ((SOUND_SAMPLERATE % IRQ_RATE)) {
891                 print_error("Sample rate must be a multiple of IRQ rate, please fix!\n");
892                 goto done;
893         }
894         if ((1000 % IRQ_RATE)) {
895                 print_error("1000 (Ticks per second) rate must be a multiple of IRQ rate, please fix!\n");
896                 goto done;
897         }
898
899         /* calculate SDL chunk size for audio
900          * it must be a power of two, but not more than the chunk size for each IRQ!
901          */
902         for (sdl_sound_chunk = 2; sdl_sound_chunk <= (SOUND_SAMPLERATE / IRQ_RATE); sdl_sound_chunk <<= 1)
903                 ;
904         sdl_sound_chunk >>= 1;
905 //      printf("samples per IRQ = %d, samples per SDL audio = %d\n", SOUND_SAMPLERATE / IRQ_RATE, sdl_sound_chunk); exit(0);
906
907         /* allocate sound buffers */
908         sound_buffer_size = SOUND_SAMPLERATE / IRQ_RATE * SOUND_CHUNKS;
909         sound_buffer = calloc(sound_buffer_size, sizeof(*sound_buffer));
910         if (!sound_buffer) {
911                 print_error("Failed to allocate image buffer\n");
912                 goto done;
913         }
914
915         /* allocate memory */
916         memory = calloc(MEMORY_SIZE, 1);
917         if (!memory) {
918                 print_error("Failed to allocate cpu's memory\n");
919                 goto done;
920         }
921         stop_event = calloc(MEMORY_SIZE, 1);
922         if (!stop_event) {
923                 print_error("Failed to allocate cpu's stop_event memory\n");
924                 goto done;
925         }
926         chipreg = calloc(IOSIZE, 1);
927         if (!chipreg) {
928                 print_error("Failed to allocate chip register\n");
929                 goto done;
930         }
931
932         /* init cpu code */
933         execute_init(MEMORY_SIZE, memory, stop_event, chipreg, io_read, io_write, mercenary_stop_at);
934
935         /* init disk emulation */
936         disk_init(disk_read, disk_write);
937
938         /* load binary */
939         mercenary_load();
940
941         /* patch some stuff */
942         mercenary_patch();
943
944         /* init SDL and OpenGL */
945         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);
946         if (rc < 0)
947                 goto done;
948         rc = init_opengl((double_pixel_size) ? IMAGE_WIDTH * 2 : IMAGE_WIDTH, (double_pixel_size) ? IMAGE_HEIGHT * 2 : IMAGE_HEIGHT);
949         if (rc < 0)
950                 goto done;
951         resize_opengl((config_debug_opengl) ? SCREEN_WIDTH * 2 : SCREEN_WIDTH * 3, (config_debug_opengl) ? SCREEN_HEIGHT * 4 : SCREEN_HEIGHT * 3);
952
953         /* init osd */
954         rc = init_osd(0, IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2);
955         if (rc < 0)
956                 goto done;
957         rc = init_osd(1, OSD_WIDTH, OSD_HEIGHT);
958         if (rc < 0)
959                 goto done;
960         help_osd = text_alloc(IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, HELP_ALPHA);
961         if (!help_osd)
962                 goto done;
963         text_render(help_osd, IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, mercenary_name, HELP_ALPHA, 3, (double)(80 - strlen(mercenary_name)) / 2.0, 1, 1);
964         text_render(help_osd, IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2,
965                 "Emulation:\n"
966                 "        Press `PAUSE' to toggle this help screen on or off.\n"
967                 "        Press `CTRL' + `F' to toggle between full screen / window mode.\n"
968                 "        Press `CTRL' + `R' to toggle between original / OpenGL rendering.\n"
969                 "        Press `CTRL' + `S' to toggle between original / fast rendering.\n"
970                 "        Press `CTRL' + `B' to toggle between large / small Benson.\n"
971                 "        Press `CTRL' + `V' to toggle video filter on / off.\n"
972                 "        Press `CTRL' + `A' to toggle audio filter on / off.\n"
973                 "        Press `CTRL' + `+' or `-' to change field-of-view (OpenGL).\n"
974                 "        Press `CTRL' + `I' to skip intro (approaching to Eris).\n"
975                 "\n"
976                 "Answer to a Question:\n"
977                 "        Press `O' (not Zero) for OK and other key for NO.\n"
978                 "\n"
979                 "Walking / Driving / Flying:\n"
980                 "        Use cursor keys as joystick, to move player / craft.\n"
981                 "        Press `R' for running, 'W' for walking speed.\n"
982                 "        Press `B' to board, `L' to leave.\n"
983                 "        Press `1'...`0' to drive / fly (slow...fast), `+' or `-' to adjust.\n"
984                 "        Press `F1'...`F0' to drive / fly backwards (slow...fast).\n"
985                 "        Press `SPACE' to stop craft.\n"
986                 "        Press `ESCAPE' to activate escape sequence on crafts.\n"
987                 "        Press `T' for turbo on certain craft.\n"
988                 "        Press `END' as joystick's fire button.\n"
989                 "\n"
990                 "Elevator:\n"
991                 "        Press `1'...`9' to select floor, 'G' for ground, `B' for basement.\n"
992                 "\n"
993                 "Inside a transporter:\n"
994                 "        Press `1'...`0' to select destination.\n"
995                 "\n"
996                 "Items:\n"
997                 "        Press `SHFIT' + cursor left / right keys to choose item.\n"
998                 "        Press `SHFIT' + cursor up / down keys to pickup / drop item.\n"
999                 "        Press `NUMPAD Enter' to select certain items.\n"
1000                 "        Press `NUMPAD +' / `NUMPAD -' to select entries.\n"
1001                 "        Press `NUMPAD *' to read entry\n"
1002                 "Saving / Loading / Pause:\n"
1003                 "        Press `INSERT' to loading and saving options.\n"
1004                 "        Press `ENTER' to pause game, other key to continue.\n"
1005                 ,HELP_ALPHA, 1, 2, 5, 0);
1006         info_osd = text_alloc(OSD_WIDTH, OSD_HEIGHT, 0x00);
1007         if (!info_osd)
1008                 goto done;
1009
1010         /* init audio */
1011         sound_init(SOUND_SAMPLERATE, sound_irq);
1012
1013         /* start cpu */
1014         reset_cpu();
1015
1016         if (config_skip_intro)
1017                 skip_intro();
1018
1019         /* run game */
1020         main_loop();
1021
1022 done:
1023         exit_opengl();
1024         exit_sdl();
1025
1026         if (chipreg)
1027                 free(chipreg);
1028         if (stop_event)
1029                 free(stop_event);
1030         if (memory)
1031                 free(memory);
1032         if (sound_buffer)
1033                 free(sound_buffer);
1034         if (image)
1035                 free(image);
1036         if (help_osd)
1037                 free(help_osd);
1038         if (info_osd)
1039                 free(info_osd);
1040
1041         return 0;
1042 }
1043