OVR: Show mirror of single eye only
[mercenary-reloaded.git] / src / mercenary / main.c
index 0d8d582..45d87e4 100644 (file)
 #include <stdio.h>
 #include <stdint.h>
 #include <stdlib.h>
-#include <endian.h>
+#include <string.h>
+#include <math.h>
 #include <sys/stat.h>
 #include <sys/types.h>
+#include "../../include/keycodes.h"
 #include "../libsdl/sdl.h"
-#include "../libsdl/opengl.h"
+#ifdef HAVE_OVR
+#include "../libovr/ovr.h"
+#include "../libovr/keyboard.h"
+#endif
+#include "../libopengl/opengl.h"
+#include "../libsdl/print.h"
 #include "../libcpu/m68k.h"
 #include "../libcpu/execute.h"
+#include "../libframerate/framerate.h"
 #include "../libvideo/video.h"
 #include "../libsound/sound.h"
 #include "../libjoystick/joystick.h"
 #include "../libkeyboard/keyboard.h"
 #include "../libdisk/disk.h"
+#include "../libtext/text.h"
 #include "mercenary.h"
+#include "render.h"
+
+#define FOV_MIN                10.0
+#define FOV_NOVAGEN    64.0
+#define FOV_JOLLY      80.0
+#define FOV_MAX                170.0
 
-static int config_amiga_speed = 1;
+#define STICK_WALK_THRESHOLD 0.3 /* move the stick until the player moves */
+#define STICK_ROTATE_THRESHOLD 0.3 /* move the stick until the player rotates */
+#define STICK_THRUST_THRESHOLD 0.1 /* move the stick until the craft moves */
+
+static int config_ctrl_c = 0;
+static int config_amiga_speed = 0; /* fast speed */
+static double config_fps = 10.0;
+#if !defined(_WIN32)
 static const char *config_gamesave_dir = ".mercenary";
+#endif
 static int config_video_filter = 1;
 static int config_audio_filter = 1;
+static int config_render = 1; /* opengl render */
+static int config_skip_intro = 0;
+static int config_multisampling = 8;
+static int config_joystick = -1, config_joystick_x = -1, config_joystick_y = -1, config_joystick_fire = -1;
+#ifdef HAVE_OVR
+static double config_benson_size = 0.7;
+static double config_fov = FOV_JOLLY;
+#else
+static double config_benson_size = 1.0;
+static double config_fov = FOV_NOVAGEN;
+#endif
+static double config_monitor_distance = 41.5; /* inch */
+#ifdef HAVE_OVR
+static double config_keyboard_distance = 38.5; /* inch */
+static double config_keyboard_height = -26.0; /* inch */
+#endif
+static int config_debug_transparent = 0;
+static int config_debug_opengl = 0;
+/* render improvements */
+static int config_improve_extend_roads = 1;    /* set to 1 to extend roads */
+static int config_improve_smooth_planets = 1;  /* set to 1 to rotate planets smoothly */
+static int config_improve_stars_rotation = 1;  /* set to 1 to improve star rendering */
+static int config_improve_fix_sky_rotation = 0;        /* set to 1 to fix sky rotation */
+static int config_improve_round_planets = 0;   /* set to 1 to make planets exactly round */
 
 #define CPU_SPEED      7093790.0;
 
@@ -60,19 +107,35 @@ static int config_audio_filter = 1;
 #define IOSIZE         0x1000 /* bytes in io space */
 #define        MEMORY_SIZE     0x80000
 static uint8_t *memory = NULL;
+static uint8_t *stop_event = NULL;
 static uint8_t *image = NULL;
+static uint8_t *help_osd[3] = { NULL, NULL, NULL };
+static uint8_t *info_osd = NULL;
+static int help_view = 1;
+static int help_views = 0;
+static int32_t osd_timer = 0, border_timer = 0;
 #define SCREEN_WIDTH   (320*3)
 #define SCREEN_HEIGHT  (200*3)
 #define IMAGE_WIDTH    320
 #define IMAGE_HEIGHT   200
 #define BENSON_AT_LINE 136
 #define IMAGE_DIWSTART 0x2c
+#define HELP_ALPHA     0xd0
+#define OSD_WIDTH      320
+#define OSD_HEIGHT     16
 static uint16_t *chipreg = NULL;
-static float *sound_buffer = NULL; /* sound buffer memory */
+static stereo_t *sound_buffer = NULL; /* sound buffer memory */
 static int sound_buffer_size; /* buffer sample size */
 static int sound_buffer_writep; /* write pointer at buffer */
 static int sound_buffer_readp; /* read pointer at buffer */
-static int double_size = 1; /* render in double size, so each pixle is 2*2 pixles wide */
+static int double_pixel_size = 1; /* render in double size, so each pixle is 2*2 pixles wide */
+static double benson_size; /* render size of benson */
+static int render_legacy = 0; /* render original amiga screen, if set */
+static int render_improved = 0; /* render improved image, if set */
+static int debug_opengl = 0; /* render both, amiga screen and  improved image, if set */
+static int intro_skipped = 0; /* indicated if we already have landed */
+static int window_width, window_height;
+static int mission_disk = 0;
 
 static const char *home_dir;
 
@@ -84,33 +147,89 @@ int parse_args(int argc, char *argv[])
 
        while (argc > i) {
                if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
-                       printf("Usage: %s\n", argv[0]);
-                       printf(" -s --amiga-speed original | full\n");
-                       printf("        Set speed of rendering to original Amiga or full speed.\n");
-                       printf(" -v --video-filter on | off\n");
-                       printf("        Set video filter.\n");
-                       printf(" -a --audio-filter on | off\n");
-                       printf("        Set audio filter.\n");
+                       /*          |                                                                             | */
+                       print_info("Usage: %s\n", argv[0]);
+                       print_info(" -s --render-speed original | fast\n");
+                       print_info("        Set speed of rendering to original Amiga or fast speed.\n");
+                       print_info("    --fps <fps>\n");
+                       print_info("        Set frames per second for fast rate (default = %.1f).\n", config_fps);
+                       print_info(" -v --video-filter on | off\n");
+                       print_info("        Set video filter.\n");
+                       print_info(" -a --audio-filter on | off\n");
+                       print_info("        Set audio filter.\n");
+                       print_info(" -r --render original | opengl\n");
+                       print_info("        Set speed of rendering to original Amiga or OpenGL.\n");
+                       print_info(" -b --benson normal | half\n");
+                       print_info("        Size of 'Benson' (control panel).\n");
+                       print_info(" -m --multisampling <samples>\n");
+                       print_info("        Use multisampling (default = %d) to render the scene.\n", config_multisampling);
+                       print_info(" -f --fov <%.0f..%.0f..%.0f>\n", FOV_MIN, FOV_NOVAGEN, FOV_MAX);
+                       print_info("        Set field-of-view. Default is %.0f.\n", FOV_NOVAGEN);
+                       print_info(" -i --skip-intro\n");
+                       print_info("        Skip intro sequence approaching to Eris space port.\n");
+                       print_info(" -j --joystick <num> | list\n");
+                       print_info("        Select given joystick number or show list. (default = 0, if available)\n");
+                       print_info("    --joystick-x <axis num>\n");
+                       print_info("    --joystick-y <axis num>\n");
+                       print_info("    --joystick-fire <button num>\n");
+                       print_info("        Specify explicit axis and button of joystick.\n");
+                       print_info("Improvement options:\n");
+                       print_info("    --extend-roads 1 | 0\n");
+                       print_info("        Roads in the distance end in a single point. This was ok for low\n");
+                       print_info("        resolution, but for OpenGL we want equal width all the way.\n");
+                       print_info("        This requires OpenGL rendering. (default = %d)\n", config_improve_extend_roads);
+                       print_info("    --smooth-planets 1 | 0\n");
+                       print_info("        Planet's rotation uses integer value, so they judder in the original\n");
+                       print_info("        game rendering. This option requires OpenGL rendering. (default = %d)\n", config_improve_smooth_planets);
+                       print_info("    --stars-rotation 1 | 0\n");
+                       print_info("        Stars are rendered originally by using a fast routine. Use this option\n");
+                       print_info("        to make them render on a sphere. They also rotate with the sky then.\n");
+                       print_info("        This requires OpenGL rendering and is default with VR. (default = %d)\n", config_improve_stars_rotation);
+                       print_info("    --fix-sky-rotation 1 | 0\n");
+                       print_info("        Sky rotates in the wrong direction, if flying over planet. This is\n");
+                       print_info("        fixed by rotating all sky object by 180 degrees. The original (wrong)\n");
+                       print_info("        rotation is default, because it preserves the game's spirit!\n");
+                       print_info("        This option requires OpenGL rendering. (default = %d)\n", config_improve_fix_sky_rotation);
+                       print_info("    --round-planets 1 | 0\n");
+                       print_info("        The original game renders planets and explosion debris horizontally\n");
+                       print_info("        stretched. This compensates the vertical stretch of NTSC vs PAL video.\n");
+                       print_info("        The original (stretched) sphere makes the game authentic.\n");
+                       print_info("        This option requires OpenGL rendering. (default = %d)\n", config_improve_round_planets);
+                       print_info("Debug options:\n");
+                       print_info(" -o --debug-opengl\n");
+                       print_info("        Use split screen to display both Amiga and OpenGL rendering.\n");
+                       print_info("    --debug-transparent\n");
+                       print_info("        Draw all things half transparent.\n");
+                       print_info("    --ctrl-c\n");
+                       print_info("        Use CTRL+C to exit game (used for development)\n");
                        return -1;
                } else
-               if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--amiga-speed")) {
+               if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--render-speed")) {
                        i++;
                        if (argc == i) {
 missing_parameter:
-                               printf("Missing parameter, use '--help'!\n");
+                               print_info("Missing parameter, use '--help'!\n");
                                return -1;
                        }
                        if (!strcmp(argv[i], "original"))
                                config_amiga_speed = 1;
                        else
-                       if (!strcmp(argv[i], "full"))
+                       if (!strcmp(argv[i], "fast"))
                                config_amiga_speed = 0;
                        else {
 illegal_parameter:
-                               printf("Illegal parameter, use '--help'!\n");
+                               print_info("Illegal parameter, use '--help'!\n");
                                return -1;
                        }
                } else
+               if (!strcmp(argv[i], "--fps")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       config_fps = atof(argv[i]);
+                       if (config_fov <= 0.0)
+                               goto illegal_parameter;
+               } else
                if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--video-filter")) {
                        i++;
                        if (argc == i)
@@ -134,8 +253,118 @@ illegal_parameter:
                                config_audio_filter = 0;
                        else
                                goto illegal_parameter;
+               } else
+               if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--render")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       if (!strcmp(argv[i], "original"))
+                               config_render = 0;
+                       else
+                       if (!strcmp(argv[i], "opengl"))
+                               config_render = 1;
+                       else
+                               goto illegal_parameter;
+               } else
+               if (!strcmp(argv[i], "-b") || !strcmp(argv[i], "--benson")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       if (!strcmp(argv[i], "normal"))
+                               config_benson_size = 1.0;
+                       else
+                       if (!strcmp(argv[i], "half")) {
+                               config_benson_size = 0.5;
+                               if (config_fov == FOV_NOVAGEN)
+                                       config_fov = FOV_JOLLY;
+                       } else
+                               goto illegal_parameter;
+               } else
+               if (!strcmp(argv[i], "-m") || !strcmp(argv[i], "--multisampling")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       config_multisampling = atoi(argv[i]);
+               } else
+               if (!strcmp(argv[i], "-f") || !strcmp(argv[i], "--fov")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       config_fov = atof(argv[i]);
+                       if (config_fov < 1.0 || config_fov > 179.0)
+                               goto illegal_parameter;
+               } else
+               if (!strcmp(argv[i], "-i") || !strcmp(argv[i], "--skip-intro")) {
+                       config_skip_intro = 1;
+               } else
+               if (!strcmp(argv[i], "-j") || !strcmp(argv[i], "--joystick")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       if (!strcmp(argv[i], "list")) {
+                               sdl_list_joysticks();
+                               return 1;
+                       }
+                       config_joystick = atoi(argv[i]);
+               } else
+               if (!strcmp(argv[i], "--joystick-x")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       config_joystick_x = atoi(argv[i]);
+               } else
+               if (!strcmp(argv[i], "--joystick-y")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       config_joystick_y = atoi(argv[i]);
+               } else
+               if (!strcmp(argv[i], "--joystick-fire")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       config_joystick_fire = atoi(argv[i]);
+               } else
+               if (!strcmp(argv[i], "--extend-roads")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       config_improve_extend_roads = atoi(argv[i]);
+               } else
+               if (!strcmp(argv[i], "--smooth-planets")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       config_improve_smooth_planets = atoi(argv[i]);
+               } else
+               if (!strcmp(argv[i], "--stars-rotation")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       config_improve_stars_rotation = atoi(argv[i]);
+               } else
+               if (!strcmp(argv[i], "--fix-sky-rotation")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       config_improve_fix_sky_rotation = atoi(argv[i]);
+               } else
+               if (!strcmp(argv[i], "--round-planets")) {
+                       i++;
+                       if (argc == i)
+                               goto missing_parameter;
+                       config_improve_round_planets = atoi(argv[i]);
+               } else
+               if (!strcmp(argv[i], "-o") || !strcmp(argv[i], "--debug-opengl")) {
+                       config_debug_opengl = 1;
+               } else
+               if (!strcmp(argv[i], "--debug-transparent")) {
+                       config_debug_transparent = 1;
+               } else
+               if (!strcmp(argv[i], "--ctrl-c")) {
+                       config_ctrl_c = 1;
                } else {
-                       printf("Illegal option '%s', use '--help'!\n", argv[i]);
+                       print_info("Illegal option '%s', use '--help'!\n", argv[i]);
                        return -1;
                }
                i++;
@@ -144,515 +373,1276 @@ illegal_parameter:
        return 0;
 }
 
+static void osd_info(const char *param, const char *value)
+{
+       char line[41] = "                                        ";
+
+       if (param[0]) {
+               strncpy(line + 21 - strlen(param), param, strlen(param));
+               line[22] = ':';
+       }
+       if (strlen(value) > 15) {
+               print_error("string too long\n");
+               return;
+       }
+       strncpy(line + 25, value, strlen(value));
+       text_render(info_osd, OSD_WIDTH, OSD_HEIGHT, line, 0x00, 4, 0, 0, 1);
+       osd_timer = ticks_sdl() + 2500;
+}
+
+static void toggle_help(void)
+{
+       if (help_view == 0)
+               help_view = 2;
+       else
+       if (help_view == help_views)
+               help_view = 0;
+       else
+               help_view++;
+}
+
+static void resize_window(int width, int height)
+{
+       window_width = width;
+       window_height = height;
+       border_timer = ticks_sdl() + 1500;
+       osd_info("", "window resized");
+}
+
+#ifdef HAVE_OVR
+static int __attribute__((unused)) button_a_last = 0, button_b_last = 0, button_x_last = 0, button_y_last = 0, button_menu_last = 0, button_left_trigger_last = 0, button_right_trigger_last = 0, button_left_thumb_last = 0, button_right_thumb_last = 0;
+static double __attribute__((unused)) stick_left_x_last = 0.0, stick_left_y_last = 0.0, stick_right_x_last = 0.0, stick_right_y_last = 0.0;
+static int thrust_last = 0;
+static int joystick_set_x_last = 0, joystick_set_y_last = 0;
+static int keyboard_on = 0;
+static enum keycode vr_key_pressed = 0, vr_key = 0;
+static int we_walk = 0, we_rotate = 0;
+static double degrees45 = 45.0 / 180.0 * M_PI;
+
+static void handle_vr_poses(void)
+{
+       int button_a = 0, button_b = 0, button_x = 0, button_y = 0, button_menu = 0, button_left_trigger = 0, button_right_trigger = 0, button_left_thumb = 0, button_right_thumb = 0;
+       double hand_right_x = 0.0, hand_right_y = 0.0, hand_right_z = 0.0;
+       double hand_right_yaw = 0.0, hand_right_pitch = 0.0, hand_right_roll = 0.0;
+       double head_yaw = 0.0, head_pitch = 0.0, head_roll = 0.0;
+       double stick_left_x = 0.0, stick_left_y = 0.0, stick_right_x = 0.0, stick_right_y = 0.0;
+       int thrust = thrust_last;
+       int joystick_set_x = 0, joystick_set_y = 0;
+       static uint32_t current_time, last_time = 0, diff;
+       static double increment, inc_count = 0.0;
+
+       /* handle input */
+       get_poses_ovr(&button_a, &button_b, &button_x, &button_y, &button_menu, &button_left_trigger, &button_right_trigger, &button_left_thumb, &button_right_thumb, &hand_right_x, &hand_right_y, &hand_right_z, &hand_right_yaw, &hand_right_pitch, &hand_right_roll, &stick_left_x, &stick_left_y, &stick_right_x, &stick_right_y, &head_yaw, &head_pitch, &head_roll);
+       if (button_a && !button_a_last) {
+               /* menu toggle */
+               toggle_help();
+       }
+       if (button_b && !button_b_last) {
+               /* reset observer */
+               reset_observer_ovr();
+               osd_info("", "reset observer");
+       }
+       if (button_x && !button_x_last) {
+               /* menu toggle */
+               toggle_help();
+       }
+       if (button_y && !button_y_last) {
+               /* reset observer */
+               reset_observer_ovr();
+               osd_info("", "reset observer");
+       }
+       if (!help_view) {
+               if (button_right_trigger && !button_right_trigger_last) {
+                       /* trigger pressed */
+                       if (keyboard_on) {
+                               if (vr_key) {
+                                       vr_key_pressed = vr_key;
+                                       set_amiga_key(vr_key_pressed, 1);
+                                       /* reset vr thrust */
+                                       thrust = 0;
+                               }
+                       } else {
+                               /* fire button */
+                               set_joystick(-1, -1, -1, -1, 1);
+                       }
+               }
+               if (!button_right_trigger && button_right_trigger_last) {
+                       /* trigger released */
+                       set_joystick(-1, -1, -1, -1, 0);
+                       if (vr_key_pressed) {
+                               set_amiga_key(vr_key_pressed, 0);
+                               vr_key_pressed = 0;
+                       }
+               }
+               /* joystick */
+               /* reset moving state, so the game is not influenced before we want to */
+               mercenary_vr_move(0, NULL, NULL, 256, 256);
+               joystick_set_x = 0;
+               joystick_set_y = 0;
+               if (!mercenary_get_info_walking()) {
+                       /* turn right and left when not walking */
+                       if (stick_right_x > STICK_ROTATE_THRESHOLD) {
+                               set_joystick(0, 1, -1, -1, -1);
+                               joystick_set_x = 1;
+                       } else
+                       if (stick_right_x < -STICK_ROTATE_THRESHOLD) {
+                               set_joystick(1, 0, -1, -1, -1);
+                               joystick_set_x = 1;
+                       }
+                       /* pitch craft */
+                       if (stick_right_y > STICK_WALK_THRESHOLD) {
+                               set_joystick(-1, -1, 1, 0, -1);
+                               joystick_set_y = 1;
+                       } else
+                       if (stick_right_y < -STICK_WALK_THRESHOLD) {
+                               set_joystick(-1, -1, 0, 1, -1);
+                               joystick_set_y = 1;
+                       }
+                       if (joystick_set_x || joystick_set_y) {
+                               mercenary_vr_move(0, NULL, NULL,
+                                       256,
+                                       (int)(256.0 * fabs(stick_right_y) - STICK_WALK_THRESHOLD / (1.0 - STICK_WALK_THRESHOLD) + 0.5));
+                       }
+               } else {
+                       double roll, pitch, yaw;
+                       double tilt, dir, east, north;
+                       int32_t move_east[4], move_north[4];
+
+                       tilt = sqrt(stick_right_x * stick_right_x + stick_right_y * stick_right_y);
+
+                       /* check if we rotate, walk or rest */
+                       if (we_rotate == 0 && we_walk == 0) {
+                               /* we rest */
+                               if (fabs(stick_right_y) > fabs(stick_right_x) && tilt > STICK_WALK_THRESHOLD)
+                                       we_walk = 1;
+                               if (fabs(stick_right_x) > fabs(stick_right_y) && tilt > STICK_ROTATE_THRESHOLD)
+                                       we_rotate = 1;
+                       } else if (we_walk) {
+                               /* we walk */
+                               if (tilt < STICK_WALK_THRESHOLD) {
+                                       we_walk = 0;
+                                       /* we need to stop right here and not continue until next rendering */
+                                       set_joystick(-1, -1, 0, 0, -1); /* stop y */
+                                       reset_joystick(); /* commit stop */
+                               }
+                       } else {
+                               /* we rotate */
+                               if (tilt < STICK_ROTATE_THRESHOLD)
+                                       we_rotate = 0;
+                       }
+
+                       /* if we walk */
+                       if (we_walk) {
+                               /* get stick amplitude (dist) and direction (dir) */
+                               if (tilt > 1.0)
+                                       tilt = 1.0;
+                               tilt = (tilt - STICK_WALK_THRESHOLD) / (1.0 - STICK_WALK_THRESHOLD) * 40.0;
+                               dir = atan2(stick_right_x, stick_right_y);
+#if 0
+                               /* use hand direction to get actual stick direction */
+                               dir = fmod(dir - hand_right_yaw, M_PI * 2.0);
+                               if (dir < -M_PI)
+                                       dir += M_PI * 2.0;
+                               if (dir > M_PI)
+                                       dir -= M_PI * 2.0;
+#endif
+                               /* flip direction, if we walk backwards */
+                               if (dir > M_PI / 2.0 || dir < -M_PI / 2.0) {
+                                       /* go backwards */
+                                       set_joystick(-1, -1, 0, 1, -1);
+                                       joystick_set_y = 1;
+                               } else {
+                                       /* go forward */
+                                       set_joystick(-1, -1, 1, 0, -1);
+                                       joystick_set_y = 1;
+                               }
+                               mercenary_get_orientation(&roll, &pitch, &yaw);
+                               east = sin(yaw - dir + M_PI) * tilt;
+                               north = -cos(yaw - dir + M_PI) * tilt;
+                               /* calculatate the integer positions of 4 steps */
+                               move_east[0] = (int32_t)((east * 0.25) + 0.5);
+                               move_north[0] = (int32_t)((north * 0.25) + 0.5);
+                               move_east[1] = (int32_t)((east * 0.5) + 0.5);
+                               move_north[1] = (int32_t)((north * 0.5) + 0.5);
+                               move_east[2] = (int32_t)((east * 0.75) + 0.5);
+                               move_north[2] = (int32_t)((north * 0.75) + 0.5);
+                               move_east[3] = (int32_t)(east + 0.5);
+                               move_north[3] = (int32_t)(north + 0.5);
+                               /* calculate the delta between each of the 4 step */
+                               move_east[3] -= move_east[2];
+                               move_north[3] -= move_north[2];
+                               move_east[2] -= move_east[1];
+                               move_north[2] -= move_north[1];
+                               move_east[1] -= move_east[0];
+                               move_north[1] -= move_north[0];
+                               /* the game takes 4 steps to move the player */
+                               mercenary_vr_move(1, move_east, move_north, 256, 256);
+                       }
+
+                       /* snap orientation to steps of 45 degrees */
+                       if (we_rotate == 1) {
+                               mercenary_get_orientation(&roll, &pitch, &yaw);
+                               yaw = round(yaw / degrees45) * degrees45;
+                               /* if we rotate: change orientation */
+                               if (stick_right_x > 0)
+                                       yaw -= degrees45;
+                               else
+                                       yaw += degrees45;
+                               /* rotate only once per stick movement */
+                               we_rotate = 2;
+                               mercenary_set_orientation(yaw);
+                       }
+               }
+               if (joystick_set_x_last && !joystick_set_x)
+                       set_joystick(0, 0, -1, -1, -1);
+               if (joystick_set_y_last && !joystick_set_y)
+                       set_joystick(-1, -1, 0, 0, -1);
+               /* thrust */
+               /* button to toggle between stop and escape */
+               if (button_left_thumb && !button_left_thumb_last) {
+                       /* 'escape' pressed */
+                       if (thrust_last != -99)
+                               thrust = -99;
+                       else
+                               thrust = 0;
+               }
+               /* button to stop */
+               if (button_left_trigger && !button_left_trigger_last) {
+                       /* 'stop' pressed */
+                       thrust = 0;
+               }
+               /* get stick to increment or decrement thrust */
+               if (stick_left_y > STICK_THRUST_THRESHOLD)
+                       increment = (stick_left_y - STICK_THRUST_THRESHOLD) / (1.0 - STICK_THRUST_THRESHOLD);
+               else
+               if (stick_left_y < -STICK_THRUST_THRESHOLD)
+                       increment = (stick_left_y + STICK_THRUST_THRESHOLD) / (1.0 - STICK_THRUST_THRESHOLD);
+               else
+                       increment = 0;
+               current_time = ticks_sdl();
+               if (increment) {
+                       diff = current_time - last_time;
+                       inc_count += increment * diff;
+                       /* if we are in 'escape' mode, we stop thrust first */
+                       if (thrust == -99)
+                               thrust = 0;
+                       if (inc_count > 150.0 && thrust >= -10 && thrust < 10) {
+                               thrust++;
+                               inc_count = 0.0;
+                       }
+                       if (inc_count < -150.0 && thrust <= 10 && thrust > -10) {
+                               thrust--;
+                               inc_count = 0.0;
+                       }
+               } else {
+                       inc_count = 0;
+               }
+               last_time = current_time;
+               /* send thrust change as keycodes */
+               if (thrust_last != thrust) {
+                       /* if we were in escape mode, we stop us first and then apply the new code */
+                       if (thrust_last == -99) {
+                               set_amiga_key(KEYCODE_SPACE, 1);
+                               set_amiga_key(KEYCODE_SPACE, 0);
+                       }
+
+                       if (thrust >= 10) {
+                               set_amiga_key(KEYCODE_0, 1);
+                               set_amiga_key(KEYCODE_0, 0);
+                       } else
+                       if (thrust <= -10 && thrust > -99) {
+                               set_amiga_key(KEYCODE_F10, 1);
+                               set_amiga_key(KEYCODE_F10, 0);
+                       } else
+                       if (thrust <= -99) {
+                               set_amiga_key(KEYCODE_ESCAPE, 1);
+                               set_amiga_key(KEYCODE_ESCAPE, 0);
+                       } else
+                       if (thrust > 0) {
+                               set_amiga_key(KEYCODE_1 + thrust - 1, 1);
+                               set_amiga_key(KEYCODE_1 + thrust - 1, 0);
+                       } else
+                       if (thrust < 0) {
+                               set_amiga_key(KEYCODE_F1 - thrust - 1, 1);
+                               set_amiga_key(KEYCODE_F1 - thrust - 1, 0);
+                       } else {
+                               set_amiga_key(KEYCODE_SPACE, 1);
+                               set_amiga_key(KEYCODE_SPACE, 0);
+                       }
+               }
+       }
+       button_a_last = button_a;
+       button_b_last = button_b;
+       button_x_last = button_x;
+       button_y_last = button_y;
+       button_menu_last = button_menu;
+       button_left_trigger_last = button_left_trigger;
+       button_right_trigger_last = button_right_trigger;
+       button_left_thumb_last = button_left_thumb;
+       button_right_thumb_last = button_right_thumb;
+       stick_left_x_last = stick_left_x;
+       stick_left_y_last = stick_left_y;
+       stick_right_x_last = stick_right_x;
+       stick_right_y_last = stick_right_y;
+       thrust_last = thrust;
+       joystick_set_x_last = joystick_set_x;
+       joystick_set_y_last = joystick_set_y;
+
+       /* we must handle keyboard after toggeling keyboard_on,
+        * so that keyboard_on will not change until keyboard is rendered */
+       vr_key = 0;
+       keyboard_on = handle_vr_keyboard(hand_right_x, hand_right_y, hand_right_z, hand_right_yaw, hand_right_pitch, &vr_key);
+}
+#endif
+
+static void skip_intro(void)
+{
+       int event;
+       double render_delay = 0.0;
+       double cycle_count;
+
+       if (intro_skipped)
+               return;
+
+       print_info("*** Skipping intro, fast forwarding... ***\n\n");
+       do {
+               /* render, if not delayed */
+               if (render_delay <= 0.0) {
+                       cycle_count = 0;
+                       do {
+                               cycle_count += execute_cpu(0, &event);
+                       } while (event != STOP_AT_WAIT_VBL && event != STOP_AT_CLEAR_SCREEN1);
+                       render_delay += (double)cycle_count / CPU_SPEED;
+               }
+               /* VBL */
+               execute_cpu(3, NULL);
+               /* count down render delay */
+               if (render_delay) {
+                       render_delay -= 1.0 / (double)IRQ_RATE;
+                       if (render_delay < 0.0)
+                               render_delay = 0.0;
+               }
+       } while (event != STOP_AT_CLEAR_SCREEN1);
+
+       intro_skipped = 1;
+}
+
 static void special_event(int event)
 {
+#ifdef HAVE_OVR
+       /* handle VR events */
+       if (event == STOP_AT_PATCH_VR) {
+               mercenary_patch_vr();
+               return;
+       }
+#endif
+       /* handle events to improve rendering */
+       if (render_improved)
+               render_capture_event(event);
 }
 
 static void main_loop(void)
 {
+       double frame_step, frame_time = 0.0, frame_render = 1;
        int had_first_irq = 0;
        static uint32_t current_time, last_time = 0, diff;
        int i, rc;
        int space, length;
-       int cycle_count, event;
+       int cycle_count, event = STOP_AT_END;
        double render_delay = 0.0;
        uint32_t palette_address;
        uint16_t palette[16];
+       int all_white = 0;
+#ifdef HAVE_OVR
+       int eye;
+       int vr = 1;
+#else
+       int vr = 0;
+#endif
 
-       last_time = SDL_GetTicks();
+       last_time = ticks_sdl();
 
        /* render result on window */
        while (!quit) {
-               /* STEP 1: let the CPU render/process the game */
-               /* don't render if we still delay */
-               if (!render_delay) {
+#ifdef HAVE_OVR
+               /* quit by OVR server */
+               if (should_quit_ovr())
+                       break;
+               /* get vr poses */
+               handle_vr_poses();
+#endif
+               /* if we are in interstellar fligt, we use 50 Hz */
+               /* if we are approaching to Eris Space Port, we use 10 Hz */
+               /* else we use whatever frame rate the user wants */
+               if (render_capture_is_interstellar())
+                       frame_step = vbl_duration * 50.0;
+               else if (!intro_skipped)
+                       frame_step = vbl_duration * 10.0;
+               else
+                       frame_step = vbl_duration * config_fps;
+               if (frame_step > 1.0)
+                       frame_step = 1.0;
+               /* handle SDL events */
+               rc = event_sdl();
+               if (rc)
+                       break;
+
+               /* initialize rendering */
+               debug_opengl = config_debug_opengl;
+               benson_size = config_benson_size;
+               render_legacy = (!config_render) || debug_opengl;
+               render_improved = config_render || debug_opengl;
+               if (!render_improved) {
+                       /* be sure to clean all capture history, so we don't get glichtes when turning on improved rendering again */
+                       render_capture_reset();
+               }
+               /* STEP 1: let the CPU render/process the game, also improve rendering via OpenGL, if enabled */
+               /* amgia speed: don't render if we still delay */
+               /* non amiga speed: render if we need a new frame */
+               /* NOTE: at input event we must render after every VBL, so we do this in every loop */
+               /* in case of help view: stop cpu after first IRQ, regardless of other options */
+               /* NOTE: We need initial IRQ, so we have out copper list initialized */
+               if (((frame_render && !config_amiga_speed)
+                 || (config_amiga_speed && render_delay <= 0.0)
+                 || event == STOP_AT_WAIT_INPUT)
+               && !(had_first_irq && help_view)) {
+                       frame_render = 0;
+                       /* start capturing for improved graphics */
+                       if (render_improved)
+                               render_capture_start(config_fov, config_improve_extend_roads, config_improve_smooth_planets, config_improve_stars_rotation, config_improve_fix_sky_rotation, config_improve_round_planets, config_debug_transparent);
+
                        /* execute until the rendered image is ready (wait for VBL) */
                        cycle_count = 0;
                        do {
-                               cycle_count += execute_cpu(0, mercenary_stop_at, &event);
+                               cycle_count += execute_cpu(0, &event);
                                /* handle special events */
-                               if (event != STOP_AT_WAIT_VBL)
-                                       special_event(event);
-                       } while (event != STOP_AT_WAIT_VBL);
+                               special_event(event);
+                               if (event == STOP_AT_CLEAR_SCREEN1)
+                                       intro_skipped = 1;
+                       } while (event != STOP_AT_WAIT_VBL && event != STOP_AT_WAIT_INPUT);
+                       /* stop capturing for improved graphics */
+                       if (render_improved)
+                               render_capture_stop();
                        /* copy palette */
-                       palette_address = mercenary_palette();
+                       palette_address = mercenary_palette_view();
                        for (i = 0; i < 16; i++)
                                palette[i] = m68k_read_memory_16(palette_address + i*2);
                        /* for amiga speed: set delay by the number of cycles */
                        if (config_amiga_speed)
-                               render_delay = (double)cycle_count / CPU_SPEED;
+                               render_delay += (double)cycle_count / CPU_SPEED;
+                       /* reset joystick after rendering */
+                       reset_joystick();
                }
 
-               /* STEP 2: render image in memory via OpenGL */
-               if (had_first_irq) {
-                       /* render game view without benson
-                        * because benson is not updated before VBL IRQ, we don't want old image from double buffer
-                        */
-                       emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, 0, BENSON_AT_LINE, double_size);
+               /* STEP 2: transfer legacy image (or just benson) in memory to OpenGL texture */
+#ifdef HAVE_OVR
+               begin_render_ovr();
+
+               for (eye = 0; eye < 2; eye++) {
+                       double camera_x, camera_y, camera_z;
+                       /* begin of rendering eye, viewport and frustum is set here */
+                       begin_render_ovr_eye(eye, &camera_x, &camera_y, &camera_z);
+#else
+               {
+#endif
+                       /* clear screen */
+                       opengl_clear(vr);
+                       /* render benson + osd ontop of improved opengl rendering, if enabled */
+                       if (render_improved) {
+#ifndef HAVE_OVR
+                               /* viewport and frustum is set here */
+                               opengl_viewport(window_width, window_height, (debug_opengl) ? 2 : 0, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, benson_size);
+#endif
+                               /* render improved graphics, interpolate, if required,
+                                * if no item list is available, for legacy rendering
+                                */
+                               if (all_white)
+                                       rc = render_all_white(vr);
+                               else
+                                       rc = render_all_items((config_amiga_speed) ? 1.0 : frame_time, vr);
+                               if (rc)
+                                       goto goto_legacy;
+                               opengl_blit_image(image, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, 1, config_fov, config_monitor_distance, benson_size, vr);
+                               if (help_view)
+                                       opengl_blit_osd(0, help_osd[help_view - 1], config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, (vr) ? FOV_NOVAGEN : config_fov, config_monitor_distance, (vr) ? 1.0 : benson_size, 1.0, 1.0, 0.0, 0.0);
+                               if (osd_timer) {
+                                       opengl_blit_osd(1, info_osd, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, (vr) ? FOV_NOVAGEN : config_fov, config_monitor_distance, (vr) ? 1.0 : benson_size, 0.5, 0.04, 0.5, -0.95);
+                                       if (osd_timer - (int32_t)ticks_sdl() < 0)
+                                               osd_timer = 0;
+                               }
+#ifndef HAVE_OVR
+                               /* draw border around legacy render area */
+                               if (border_timer) {
+                                       opengl_render_color(1.0, 0.0, 0.0, 1.0);
+                                       opengl_render_line(160, -68, 256, 160, 68, 256, 0.0);
+                                       opengl_render_line(-160, -68, 256, -160, 68, 256, 0.0);
+                                       opengl_render_line(-160, 68, 256, 160, 68, 256, 0.0);
+                                       opengl_render_line(-160, -68, 256, 160, -68, 256, 0.0);
+                                       if (border_timer - (int32_t)ticks_sdl() < 0)
+                                               border_timer = 0;
+                               }
+#endif
+                       }
+                       /* setup viewport for legacy image and render image, if enabled */
+                       /* also render legacy, if render_improved failed due to not (yet) available items */
+                       if (render_legacy) {
+                               goto_legacy:
+                               /* render game view without benson
+                                * because benson is not updated before VBL IRQ, we don't want old image from double buffer
+                                */
+                               if (had_first_irq)
+                                       emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, 0, BENSON_AT_LINE, double_pixel_size);
+#ifndef HAVE_OVR
+                               /* viewport and frustum is set here */
+                               opengl_viewport(window_width, window_height, (debug_opengl) ? 1 : 0, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, FOV_NOVAGEN, 1.0);
+#endif
+                               opengl_blit_image(image, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, 0, FOV_NOVAGEN, config_monitor_distance, 1.0, 0);
+                               if (help_view)
+                                       opengl_blit_osd(0, help_osd[help_view - 1], config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, FOV_NOVAGEN, config_monitor_distance, 1.0, 1.0, 1.0, 0.0, 0.0);
+                               if (osd_timer) {
+                                       opengl_blit_osd(1, info_osd, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, FOV_NOVAGEN, config_monitor_distance, 1.0, 0.5, 0.04, 0.5, -0.95);
+                                       if (osd_timer - (int32_t)ticks_sdl() < 0)
+                                               osd_timer = 0;
+                               }
+                       }
+#ifdef HAVE_OVR
+                       /* render keyboard */
+                       if (keyboard_on)
+                               render_vr_keyboard(camera_x, camera_y);
+
+                       /* end of rendering eye */
+                       end_render_ovr_eye(eye);
                }
-               rc = event_sdl();
-               if (rc)
-                       break;
-               render_opengl(image, config_video_filter);
+               /* at this point we are ready with our image, so we display */
+               end_render_ovr();
+               render_mirror_ovr(window_width, window_height);
+#else
+               }
+#endif
                swap_sdl();
 
-               /* STEP 3: execute interrupt at rate of 50Hz, render sound */
-               current_time = SDL_GetTicks();
-               diff = current_time - last_time;
-               /* in case of timer glitch, execute IRQ only by maximum number of SOUND_CHUNKS */
-               if (diff > 1000 * SOUND_CHUNKS / IRQ_RATE) {
-                       diff = 1000 * SOUND_CHUNKS / IRQ_RATE;
-                       last_time = current_time - 1000 * SOUND_CHUNKS / IRQ_RATE;
+               /* advance frame time, if we are not in help view  */
+               if (!(had_first_irq && help_view)) {
+                       frame_time += frame_step;
+                       if (frame_time >= 1.0) {
+                               frame_time -= 1.0;
+                               frame_render = 1;
+                       }
                }
-               while (diff > 1000 / IRQ_RATE) {
-                       execute_cpu(3, NULL, NULL);
-                       execute_cpu(4, NULL, NULL);
-                       had_first_irq = 1;
-                       /* render benson without game view
-                        * because we only got benson refreshed during VBL IRQ
-                        */
-                       emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, BENSON_AT_LINE, IMAGE_HEIGHT, double_size);
-                       /* render sound to sound buffer
-                        * buffer pointer read and write is atomic, so no locking required!
-                        */
-                       space = (sound_buffer_readp - sound_buffer_writep - 1 + sound_buffer_size) % sound_buffer_size;
-                       if (space < SOUND_SAMPLERATE / IRQ_RATE) {
+
+               /* measure frame rate */
+               framerate_measure();
+
+               /* STEP 3: execute interrupt at rate of 50Hz, render sound */
+               /* only do this, if we are not in help view */
+               /* NOTE: We need initial IRQ, so we have out copper list initialized */
+               if (!(had_first_irq && help_view)) {
+                       current_time = ticks_sdl();
+                       diff = current_time - last_time;
+                       /* in case of timer glitch, execute IRQ only by maximum number of SOUND_CHUNKS */
+                       if (diff > 1000 * SOUND_CHUNKS / IRQ_RATE) {
+                               diff = 1000 * SOUND_CHUNKS / IRQ_RATE;
+                               last_time = current_time - 1000 * SOUND_CHUNKS / IRQ_RATE;
+                       }
+                       while (diff > 1000 / IRQ_RATE) {
+                               /* trigger and execute IRQ 3 = VBL */
+                               execute_cpu(3, NULL);
+                               had_first_irq = 1;
+                               /* transfer benson without game view
+                                * because we only got benson refreshed during VBL IRQ
+                                */
+                               all_white = emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, BENSON_AT_LINE, IMAGE_HEIGHT, double_pixel_size);
+                               /* render sound to sound buffer
+                                * buffer pointer read and write is atomic, so no locking required!
+                                */
+                               space = (sound_buffer_readp - sound_buffer_writep - 1 + sound_buffer_size) % sound_buffer_size;
+                               if (space < SOUND_SAMPLERATE / IRQ_RATE) {
 #ifdef DEBUG_SOUND_BUFFERING
-                               fprintf(stderr, "sound buffer overflow\n");
+                                       fprintf(stderr, "sound buffer overflow\n");
 #endif
-                               length = space;
-                       } else
-                               length = SOUND_SAMPLERATE / IRQ_RATE;
+                                       length = space;
+                               } else
+                                       length = SOUND_SAMPLERATE / IRQ_RATE;
 #ifdef DEBUG_SOUND_BUFFERING
-                       printf("can write %d, write %d\n", space, length);
-                       static int cnt = 0;
-                       int s;
-                       for (s = 0; s < length; s++) {
-                               sound_buffer[(sound_buffer_writep + s) % sound_buffer_size]
-                                       = sin(2 * M_PI * 999 * cnt / SOUND_SAMPLERATE)
-                                       * sin(2 * M_PI * 21 * cnt / SOUND_SAMPLERATE)
-                                       * sin(2 * M_PI * 0.5 * cnt / SOUND_SAMPLERATE);
-                                cnt++;
-                       }
+                               printf("can write %d, write %d\n", space, length);
+                               static int cnt = 0;
+                               int s;
+                               for (s = 0; s < length; s++) {
+                                       sound_buffer[(sound_buffer_writep + s) % sound_buffer_size].left =
+                                       sound_buffer[(sound_buffer_writep + s) % sound_buffer_size].right
+                                               = sin(2 * M_PI * 999 * cnt / SOUND_SAMPLERATE)
+                                               * sin(2 * M_PI * 21 * cnt / SOUND_SAMPLERATE)
+                                               * sin(2 * M_PI * 0.5 * cnt / SOUND_SAMPLERATE);
+                                        cnt++;
+                               }
 #else
-                       render_sound(memory, sound_buffer, sound_buffer_size, sound_buffer_writep, length, config_audio_filter);
+                               render_sound(memory, sound_buffer, sound_buffer_size, sound_buffer_writep, length, config_audio_filter);
 #endif
-                       sound_buffer_writep = (sound_buffer_writep + length) % sound_buffer_size;
-                       diff -= 1000 / IRQ_RATE;
-                       last_time += 1000 / IRQ_RATE;
-
-                       /* count down render delay */
-                       if (render_delay) {
-                               render_delay -= 1.0 / (double)IRQ_RATE;
-                               if (render_delay < 0.0)
-                                       render_delay = 0.0;
+                               sound_buffer_writep = (sound_buffer_writep + length) % sound_buffer_size;
+                               diff -= 1000 / IRQ_RATE;
+                               last_time += 1000 / IRQ_RATE;
+
+                               /* count down render delay */
+                               if (render_delay) {
+                                       render_delay -= 1.0 / (double)IRQ_RATE;
+                                       if (render_delay < 0.0)
+                                               render_delay = 0.0;
+                               }
                        }
                }
        }
 }
 
-int main(int argc, char *argv[])
+static uint16_t io_read(uint32_t address)
 {
-       int rc;
-       int sdl_sound_chunk;
+       uint16_t value = 0xffff;
 
-       home_dir = getenv("HOME");
-       if (!home_dir)
-               home_dir = "";
+       /* joystick and fire button */
+       if (address == 0xbfe000 || address == 0xdff00c)
+               value &= emulate_joystick_read(address);
+       /* keyboard */
+       if (address == 0xbfec00 || address == 0xbfed00 || address == 0xbfee00)
+               value &= emulate_keyboard_read(address);
+       /* diskette */
+       if (address == 0xbfd100 || address == 0xbfe000 || address == 0xdff01a || address == 0xdff01e)
+               value &= emulate_disk_read(address);
 
-       rc = parse_args(argc, argv);
-       if (rc)
-               return 0;
+       return value;
+}
 
-       /* allocate image */
-       image = calloc(IMAGE_WIDTH * IMAGE_HEIGHT * ((double_size) ? 4 : 1), 3);
-       if (!image) {
-               fprintf(stderr, "Failed to allocate image buffer\n");
-               goto done;
-       }
+static void io_write(uint32_t address, uint16_t value)
+{
+       /* dmacon and sound registers */
+       if (address == 0xdff096 || address == 0xdff09a || (address >= 0xdff0a0 && address <= 0xdff0df))
+               emulate_sound_write(address, value, SOUND_SAMPLERATE);
+       if (address == 0xbfd100 || (address >= 0xdff020 && address <= 0xdff024))
+               emulate_disk_write(address, value);
+}
 
-       if ((SOUND_SAMPLERATE % IRQ_RATE)) {
-               fprintf(stderr, "Sample rate must be a multiple of IRQ rate, please fix!\n");
-               goto done;
-       }
-       if ((1000 % IRQ_RATE)) {
-               fprintf(stderr, "1000 (Ticks per second) rate must be a multiple of IRQ rate, please fix!\n");
-               goto done;
+/* two tracks with 0x1820 words of length */
+static uint8_t game_save[2][0x1820 << 1];
+static int last_track = 0;
+
+/* game reads track with saved game */
+static void disk_read(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
+{
+       if (length > sizeof(game_save[0])) {
+               print_error("loading game state failed, because length exceeds game save data size, please fix!\n");
+               return;
        }
 
-       /* calculate SDL chunk size for audio
-        * it must be a power of two, but not more than the chunk size for each IRQ!
-        */
-       for (sdl_sound_chunk = 2; sdl_sound_chunk <= (SOUND_SAMPLERATE / IRQ_RATE); sdl_sound_chunk <<= 1)
-               ;
-       sdl_sound_chunk >>= 1;
-//     printf("samples per IRQ = %d, samples per SDL audio = %d\n", SOUND_SAMPLERATE / IRQ_RATE, sdl_sound_chunk); exit(0);
+       /* if even track is selected, load game */
+       if (!(track & 1)) {
+               char filename[256];
+               int gamesave_num = (track - 2) >> 1;
 
-       /* allocate sound buffers */
-       sound_buffer_size = SOUND_SAMPLERATE / IRQ_RATE * SOUND_CHUNKS;
-       sound_buffer = calloc(sound_buffer_size, sizeof(*sound_buffer));
-       if (!sound_buffer) {
-               fprintf(stderr, "Failed to allocate image buffer\n");
-               goto done;
+               memset(game_save, 0, sizeof(game_save)); /* clear so make the game fail, if we fail */
+
+               if (mission_disk == 0) {
+                       int got;
+                       FILE *fp;
+
+#if defined(_WIN32)
+                       filename[0] = '\0';
+#else
+                       sprintf(filename, "%s/%s/", home_dir, config_gamesave_dir);
+                       mkdir(filename, 0777);
+#endif
+                       sprintf(filename + strlen(filename), "%d%s", gamesave_num, mercenary_gamesavesuffix);
+                       fp = fopen(filename, "r");
+                       if (!fp) {
+fail:
+                               print_info("failed to load game from '%s'\n", filename);
+                               osd_info("load game", "FAILED!");
+                               goto copy;
+                       }
+                       got = fread(game_save, sizeof(game_save[0]), 2, fp);
+                       fclose(fp);
+                       if (got != 2)
+                               goto fail;
+                       sprintf(filename, "#%d", gamesave_num);
+                       osd_info("loaded game", filename);
+               } else {
+                       const uint8_t *mission_data = get_mission_disk(mission_disk, gamesave_num);
+                       sprintf(filename, "disk %d #%d", mission_disk, gamesave_num);
+                       if (!mission_data) {
+                               print_info("failed to load mission %s\n", filename);
+                               osd_info("load mission", "FAILED!");
+                               goto copy;
+                       }
+                       memcpy(game_save, mission_data, 0x1820 << 2);
+                       osd_info("loaded mission", filename);
+               }
        }
 
-       /* allocate memory */
-       memory = calloc(MEMORY_SIZE, 1);
-       if (!memory) {
-               fprintf(stderr, "Failed to allocate cpu's memory\n");
-               goto done;
-       }
-       chipreg = calloc(IOSIZE, 1);
-       if (!chipreg) {
-               fprintf(stderr, "Failed to allocate chip register\n");
-               goto done;
-       }
-
-       /* init cpu code */
-       execute_init(MEMORY_SIZE, memory, chipreg);
-
-       /* load binary */
-       mercenary_load();
-
-       /* patch some stuff */
-       mercenary_patch();
-
-       /* init SDL and OpenGL */
-       rc = init_sdl(argv[0], SCREEN_WIDTH, SCREEN_HEIGHT, SOUND_SAMPLERATE, sdl_sound_chunk);
-       if (rc < 0)
-               goto done;
-       rc = init_opengl((double_size) ? IMAGE_WIDTH * 2 : IMAGE_WIDTH, (double_size) ? IMAGE_HEIGHT * 2 : IMAGE_HEIGHT);
-       if (rc < 0)
-               goto done;
-       resize_opengl(SCREEN_WIDTH, SCREEN_HEIGHT);
-
-       /* init audio filter */
-       sound_init_filter(SOUND_SAMPLERATE);
-
-       /* start cpu */
-       reset_cpu();
+copy:
+       /* copy track */
+       memcpy(memory + data, game_save[track & 1], length /* sizeof(game_save[0])*/);
+}
 
-       printf("**********************************\n");
-       printf("* Welcome to Mercenary Reloaded! *\n");
-       printf("**********************************\n\n");
-       printf("Press CTRL + cursor keys to select inventory or pickup/drop item.\n");
-       printf("Press CTRL + f to toggle full screen.\n");
-       printf("Press CTRL + s to toggle rendering speed.\n");
-       printf("Press CTRL + v to toggle video filter.\n");
-       printf("Press CTRL + a to toggle audio filter.\n");
-       printf("Press CTRL + c to exit game.\n\n");
-       printf("Use '--help' as command line option for configuration settings.\n\n");
+/* game writes track with saved game */
+static void disk_write(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
+{
+       /* cannot save on mission disk */
+       if (mission_disk) {
+               osd_info("", "not applicable");
+               return;
+       }
 
-       /* run game */
-       main_loop();
+       /* skip sync info that is provided by game and only relevant for a real disk track */
+       data += 0x200;
+       length -= 0x200;
 
-done:
-       exit_opengl();
-       exit_sdl();
+       if (length != sizeof(game_save[0])) {
+               print_error("saving game state failed, because length of data does not match, please fix!\n");
+               return;
+       }
 
-       if (chipreg)
-               free(chipreg);
-       if (memory)
-               free(memory);
-       if (sound_buffer)
-               free(sound_buffer);
-       if (image)
-               free(image);
+       /* don't save if last track is the same, because disk is written on both sides with the same data */
+       if (track == last_track) {
+               if (memcmp(memory + data, game_save[track & 1], length)) {
+                       print_error("saving game data on other side of the disk is different, please fix!\n");
+               }
+               return;
+       }
+       last_track = track;
 
-       return 0;
-}
+       /* save game data */
+       memcpy(game_save[track & 1], memory + data, length);
 
-void audio_sdl(float *data, int length)
-{
-       int fill, s;
+       /* if done with saving */
+       if ((track & 1)) {
+               char filename[256];
+               int gamesave_num = (track - 2) >> 1;
+               int wrote;
+               FILE *fp;
 
-       /* read sound from sound buffer
-        * buffer pointer read and write is atomic, so no locking required!
-        */
-       fill = (sound_buffer_writep - sound_buffer_readp + sound_buffer_size) % sound_buffer_size;
-       if (fill < length) {
-#ifdef DEBUG_SOUND_BUFFERING
-               fprintf(stderr, "sound buffer underrun\n");
+#if defined(_WIN32)
+               filename[0] = '\0';
+#else
+               sprintf(filename, "%s/%s/", home_dir, config_gamesave_dir);
+               mkdir(filename, 0777);
 #endif
-               /* correct read pointer as if the buffer would have 'length' of samples stored inside */
-               sound_buffer_readp = (sound_buffer_readp + fill - length + sound_buffer_size) % sound_buffer_size;
+               sprintf(filename + strlen(filename), "%d%s", gamesave_num, mercenary_gamesavesuffix);
+               fp = fopen(filename, "w");
+               if (!fp) {
+fail:
+                       print_error("failed to save game to '%s'\n", filename);
+                       osd_info("save game", "FAILED!");
+                       return;
+               }
+               print_info("Game state saved to '%s'\n", filename);
+               sprintf(filename, "#%d", gamesave_num);
+               osd_info("saved game", filename);
+               wrote = fwrite(game_save, sizeof(game_save[0]), 2, fp);
+               fclose(fp);
+               if (wrote != 2)
+                       goto fail;
        }
-       for (s = 0; s < length; s++)
-               *data++ = sound_buffer[(sound_buffer_readp + s) % sound_buffer_size];
-#ifdef DEBUG_SOUND_BUFFERING
-       printf("fill %d = %.4f\n", length, sound_buffer[sound_buffer_readp]);
-#endif
-       sound_buffer_readp =(sound_buffer_readp + length) % sound_buffer_size;
 }
 
-static int shift = 0, ctrl = 0;
+static int shift = 0, ctrl = 0, alt = 0;
 
-void keyboard_sdl(int down, SDL_Keycode sym)
+static void keyboard_sdl(int down, enum keycode keycode)
 {
-       switch (sym) {
-       case SDLK_LCTRL:
-       case SDLK_RCTRL:
+       switch (keycode) {
+       case KEYCODE_LCTRL:
+       case KEYCODE_RCTRL:
                ctrl = down;
                break;
-       case SDLK_v:
-               if (down && ctrl) {
+       default: break;
+       }
+
+       if (ctrl && down) {
+               switch (keycode) {
+               case KEYCODE_h:
+                       toggle_help();
+                       break;
+               case KEYCODE_v:
                        config_video_filter ^= 1;
-                       printf("video filter: %s\n", (config_video_filter) ? "on" : "off");
-               }
-               break;
-       case SDLK_a:
-               if (down && ctrl) {
+                       osd_info("video filter", (config_video_filter) ? "on" : "off");
+                       break;
+               case KEYCODE_a:
                        config_audio_filter ^= 1;
-                       printf("audio filter: %s\n", (config_audio_filter) ? "on" : "off");
-               }
-               break;
-       case SDLK_s:
-               if (down && ctrl) {
+                       osd_info("audio filter", (config_audio_filter) ? "on" : "off");
+                       break;
+               case KEYCODE_s:
                        config_amiga_speed ^= 1;
-                       printf("amiga speed: %s\n", (config_amiga_speed) ? "original" : "full");
+                       osd_info("render speed", (config_amiga_speed) ? "original" : "fast");
+                       break;
+               case KEYCODE_r:
+                       config_render ^= 1;
+                       osd_info("render mode", (config_render) ? "OpenGL" : "original");
+                       break;
+               case KEYCODE_b:
+                       if (!config_render && !config_debug_opengl) {
+                               osd_info("", "not applicable");
+                               break;
+                       }
+                       if (config_benson_size == 0.5) {
+                               config_benson_size = 1.0;
+                               config_fov = FOV_NOVAGEN;
+                       } else {
+                               config_benson_size = 0.5;
+                               config_fov = FOV_JOLLY;
+                       }
+                       osd_info("Benson size", (config_benson_size == 0.5) ? "half" : "normal");
+                       border_timer = ticks_sdl() + 1500;
+                       break;
+               case KEYCODE_i:
+                       if (!intro_skipped)
+                               skip_intro();
+                       else
+                               osd_info("", "not applicable");
+                       break;
+               case KEYCODE_1:
+                       if (get_mission_disk(1, 1)) { /* just to check support */
+                               mission_disk = 1;
+                               osd_info("mission disk", "insert 1");
+                       } else
+                               osd_info("", "not applicable");
+                       break;
+               case KEYCODE_2:
+                       if (get_mission_disk(2, 1)) { /* just to check support */
+                               mission_disk = 2;
+                               osd_info("mission disk", "insert 2");
+                       } else
+                               osd_info("", "not applicable");
+                       break;
+               case KEYCODE_0:
+                       if (get_mission_disk(1, 1)) { /* just to check support */
+                               mission_disk = 0;
+                               osd_info("mission disk", "removed");
+                       } else
+                               osd_info("", "not applicable");
+                       break;
+               case KEYCODE_c:
+                       if (config_ctrl_c)
+                               quit = 1;
+                       break;
+               case KEYCODE_o:
+#ifdef HAVE_OVR
+                       reset_observer_ovr();
+                       osd_info("", "reset observer");
+#else
+                       osd_info("", "not applicable");
+#endif
+                       break;
+               case KEYCODE_KP_PLUS:
+#ifdef HAVE_OVR
+                       osd_info("", "not applicable");
+#else
+                       if (config_fov / 1.2 >= FOV_MIN)
+                               config_fov /= 1.2;
+                       disp_fov:
+                       {
+                               char text[16];
+                               if (config_fov < 63.5 || config_fov > 64.5)
+                                       sprintf(text, "%.2f", config_fov);
+                               else
+                                       sprintf(text, "%.2f (default)", config_fov);
+                               osd_info("FOV", text);
+                               border_timer = ticks_sdl() + 1500;
+                       }
+#endif
+                       break;
+               case KEYCODE_KP_MINUS:
+#ifdef HAVE_OVR
+                       osd_info("", "not applicable");
+#else
+                       if (config_fov * 1.2 <= FOV_MAX)
+                               config_fov *= 1.2;
+                       goto disp_fov;
+#endif
+                       break;
+               default: break;
                }
-               break;
-       case SDLK_c:
-               if (down)
-                       quit = 1;
-               break;
+               /* do not pass keys to game while holding CTRL */
+               return;
+       }
+
+       if (help_view == 1 && down) {
+               help_view = 2;
+               return;
        }
 
-       switch (sym) {
-       case SDLK_LSHIFT:
-               set_key("LSH", down);
+       if (keycode == KEYCODE_PAUSE && down) {
+               toggle_help();
+               return;
+       }
+
+       /* in help view we must not forward keypresses */
+       if (help_view)
+               return;
+
+       switch (keycode) {
+       case KEYCODE_LSHIFT:
+               set_amiga_key(keycode, down);
                shift = down;
                break;
-       case SDLK_RSHIFT:
-               set_key("RSH", down);
+       case KEYCODE_RSHIFT:
+               set_amiga_key(keycode, down);
                shift = down;
                break;
-       case SDLK_LEFT:
+       case KEYCODE_LALT:
+               set_amiga_key(keycode, down);
+               alt = down;
+               break;
+       case KEYCODE_RALT:
+               set_amiga_key(keycode, down);
+               alt = down;
+               break;
+       case KEYCODE_LEFT:
                if (shift && down) {
-                       set_key("LF", down);
+                       set_amiga_key(keycode, down);
                        set_joystick(-1, -1, -1, -1, -1);
                        break;
                }
-               set_key("LF", 0);
+               set_amiga_key(keycode, 0);
                set_joystick(down, -1, -1, -1, -1);
                break;
-       case SDLK_RIGHT:
+       case KEYCODE_RIGHT:
                if (shift && down) {
-                       set_key("RT", down);
+                       set_amiga_key(keycode, down);
                        set_joystick(-1, -1, -1, -1, -1);
                        break;
                }
-               set_key("RT", 0);
+               set_amiga_key(keycode, 0);
                set_joystick(-1, down, -1, -1, -1);
                break;
-       case SDLK_UP:
+       case KEYCODE_UP:
                if (shift && down) {
-                       set_key("UP", down);
+                       set_amiga_key(keycode, down);
                        set_joystick(-1, -1, -1, -1, -1);
                        break;
                }
-               set_key("UP", 0);
-               set_joystick(-1, -1, down, -1, -1);
+               set_amiga_key(keycode, 0);
+               if (!alt || down)
+                       set_joystick(-1, -1, down, 0, -1);
                break;
-       case SDLK_DOWN:
+       case KEYCODE_DOWN:
                if (shift && down) {
-                       set_key("DN", down);
+                       set_amiga_key(keycode, down);
                        set_joystick(-1, -1, -1, -1, -1);
                        break;
                }
-               set_key("DN", 0);
-               set_joystick(-1, -1, -1, down, -1);
+               set_amiga_key(keycode, 0);
+               if (!alt || down)
+                       set_joystick(-1, -1, 0, down, -1);
                break;
-       case SDLK_END:
+       case KEYCODE_END:
                set_joystick(-1, -1, -1, -1, down);
                break;
-
-       case SDLK_a: set_key("A", down); break;
-       case SDLK_b: set_key("B", down); break;
-       case SDLK_c: set_key("C", down); break;
-       case SDLK_d: set_key("D", down); break;
-       case SDLK_e: set_key("E", down); break;
-       case SDLK_f: set_key("F", down); break;
-       case SDLK_g: set_key("G", down); break;
-       case SDLK_h: set_key("H", down); break;
-       case SDLK_i: set_key("I", down); break;
-       case SDLK_j: set_key("J", down); break;
-       case SDLK_k: set_key("K", down); break;
-       case SDLK_l: set_key("L", down); break;
-       case SDLK_m: set_key("M", down); break;
-       case SDLK_n: set_key("N", down); break;
-       case SDLK_o: set_key("O", down); break;
-       case SDLK_p: set_key("P", down); break;
-       case SDLK_q: set_key("Q", down); break;
-       case SDLK_r: set_key("R", down); break;
-       case SDLK_s: set_key("S", down); break;
-       case SDLK_t: set_key("T", down); break;
-       case SDLK_u: set_key("U", down); break;
-       case SDLK_v: set_key("V", down); break;
-       case SDLK_w: set_key("W", down); break;
-       case SDLK_x: set_key("X", down); break;
-       case SDLK_y: set_key("Y", down); break;
-       case SDLK_z: set_key("Z", down); break;
-
-       case SDLK_0: set_key("0", down); break;
-       case SDLK_1: set_key("1", down); break;
-       case SDLK_2: set_key("2", down); break;
-       case SDLK_3: set_key("3", down); break;
-       case SDLK_4: set_key("4", down); break;
-       case SDLK_5: set_key("5", down); break;
-       case SDLK_6: set_key("6", down); break;
-       case SDLK_7: set_key("7", down); break;
-       case SDLK_8: set_key("8", down); break;
-       case SDLK_9: set_key("9", down); break;
-
-       case SDLK_KP_0: set_key("NP0", down); break;
-       case SDLK_KP_1: set_key("NP1", down); break;
-       case SDLK_KP_2: set_key("NP2", down); break;
-       case SDLK_KP_3: set_key("NP3", down); break;
-       case SDLK_KP_4: set_key("NP4", down); break;
-       case SDLK_KP_5: set_key("NP5", down); break;
-       case SDLK_KP_6: set_key("NP6", down); break;
-       case SDLK_KP_7: set_key("NP7", down); break;
-       case SDLK_KP_8: set_key("NP8", down); break;
-       case SDLK_KP_9: set_key("NP9", down); break;
-       case SDLK_KP_DIVIDE: set_key("NPDIV", down); break;
-       case SDLK_KP_MULTIPLY: set_key("NPMUL", down); break;
-       case SDLK_KP_MINUS: set_key("NPSUB", down); break;
-       case SDLK_KP_PLUS: set_key("NPADD", down); break;
-       case SDLK_KP_PERIOD: set_key("NPDEL", down); break;
-       // NPLPAREN and NPRPAREN are not emulated
-
-       case SDLK_F1: set_key("F1", down); break;
-       case SDLK_F2: set_key("F2", down); break;
-       case SDLK_F3: set_key("F3", down); break;
-       case SDLK_F4: set_key("F4", down); break;
-       case SDLK_F5: set_key("F5", down); break;
-       case SDLK_F6: set_key("F6", down); break;
-       case SDLK_F7: set_key("F7", down); break;
-       case SDLK_F8: set_key("F8", down); break;
-       case SDLK_F9: set_key("F9", down); break;
-       case SDLK_F10: set_key("F10", down); break;
-
-       case SDLK_SPACE: set_key("SPC", down); break;
-       case SDLK_BACKSPACE: set_key("BS", down); break;
-       case SDLK_TAB: set_key("TAB", down); break;
-       case SDLK_KP_ENTER: set_key("ENT", down); break;
-       case SDLK_RETURN: set_key("RET", down); break;
-       case SDLK_ESCAPE: set_key("ESC", down); break;
-       case SDLK_DELETE: set_key("DEL", down); break;
-       case SDLK_INSERT: set_key("HELP", down); break;
-
+       case KEYCODE_INSERT:
+               set_amiga_key(KEYCODE_HELP, down);
+               break;
+       default:
+               /* reset vr thrust */
+#ifdef HAVE_OVR
+               thrust_last = 0;
+#endif
+               set_amiga_key(keycode, down);
        }
 }
 
-uint16_t emulate_io_read(uint32_t address)
+static double joystick_last_x = 0, joystick_last_y = 0;
+static int joystick_last_fire = 0;
+
+static void joystick_sdl(double x, double y, int fire)
 {
-       uint16_t value = 0xffff;
+       int left = -1, right = -1, up = -1, down = -1;
 
-       /* joystick and fire button */
-       if (address == 0xbfe000 || address == 0xdff00c)
-               value &= emulate_joystick_read(address);
-       /* keyboard */
-       if (address == 0xbfec00 || address == 0xbfed00 || address == 0xbfee00)
-               value &= emulate_keyboard_read(address);
-       /* diskette */
-       if (address == 0xbfd100 || address == 0xbfe000 || address == 0xdff01a || address == 0xdff01e)
-               value &= emulate_disk_read(address);
+       if (x <= -0.5 && joystick_last_x > -0.5)
+               left = 1;
+       if (x > -0.5 && joystick_last_x <= -0.5)
+               left = 0;
+       if (x >= 0.5 && joystick_last_x < 0.5)
+               right = 1;
+       if (x < 0.5 && joystick_last_x >= 0.5)
+               right = 0;
+       if (y <= -0.5 && joystick_last_y > -0.5)
+               up = 1;
+       if (y > -0.5 && joystick_last_y <= -0.5)
+               up = 0;
+       if (y >= 0.5 && joystick_last_y < 0.5)
+               down = 1;
+       if (y < 0.5 && joystick_last_y >= 0.5)
+               down = 0;
+       set_joystick(left, right, up, down, fire);
+       joystick_last_x = x;
+       joystick_last_y = y;
+       joystick_last_fire = fire;
+}
 
-       return value;
+void audio_sdl(float *data, int length)
+{
+       int fill, s;
+
+       /* read sound from sound buffer
+        * buffer pointer read and write is atomic, so no locking required!
+        */
+       fill = (sound_buffer_writep - sound_buffer_readp + sound_buffer_size) % sound_buffer_size;
+       if (fill < length) {
+#ifdef DEBUG_SOUND_BUFFERING
+               fprintf(stderr, "sound buffer underrun\n");
+#endif
+               /* correct read pointer as if the buffer would have 'length' of samples stored inside */
+               sound_buffer_readp = (sound_buffer_readp + fill - length + sound_buffer_size) % sound_buffer_size;
+       }
+       for (s = 0; s < length; s++) {
+               *data++ = sound_buffer[(sound_buffer_readp + s) % sound_buffer_size].left;
+               *data++ = sound_buffer[(sound_buffer_readp + s) % sound_buffer_size].right;
+       }
+#ifdef DEBUG_SOUND_BUFFERING
+       printf("fill %d = %.4f\n", length, sound_buffer[sound_buffer_readp][0]);
+#endif
+       sound_buffer_readp =(sound_buffer_readp + length) % sound_buffer_size;
 }
 
-void emulate_io_write(uint32_t address, uint16_t value)
+/* used for geier counter */
+void sound_irq(void)
 {
-       /* dmacon and sound registers */
-       if (address == 0xdff096 || (address >= 0xdff0a0 && address <= 0xdff0df))
-               emulate_sound_write(address, value, SOUND_SAMPLERATE);
-       if (address == 0xbfd100 || (address >= 0xdff020 && address <= 0xdff024))
-               emulate_disk_write(address, value);
+       /* trigger and execute IRQ 4 = sound */
+       execute_cpu(4, NULL);
 }
 
-/* two tracks with 0x1820 words of length */
-static uint8_t game_save[2][0x1820 << 1];
-static int last_track = 0;
+extern uint8_t mercenary_splash_palette[][3];
+extern char mercenary_splash_pixels[];
 
-/* game reads track with saved game */
-void disk_read(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
+int main(int argc, char *argv[])
 {
-       if (length > sizeof(game_save[0])) {
-               fprintf(stderr, "loading game state failed, because length exceeds game save data size, please fix!\n");
-               return;
-       }
+       int rc;
+       int sdl_sound_chunk;
 
-       /* if even track is selected, load game */
-       if (!(track & 1)) {
-               char filename[256];
-               int gamesave_num = (track - 2) >> 1;
-               int got;
-               FILE *fp;
+       home_dir = getenv("HOME");
+       if (!home_dir)
+               home_dir = "";
 
-               memset(game_save, 0, sizeof(game_save)); /* clear so make the game fail, if we fail */
-               sprintf(filename, "%s/%s/%d.gamesave", home_dir, config_gamesave_dir, gamesave_num);
-               fp = fopen(filename, "r");
-               if (!fp) {
-fail:
-                       fprintf(stderr, "failed to load game from '%s'\n", filename);
-                       goto copy;
-               }
-               got = fread(game_save, sizeof(game_save[0]), 2, fp);
-               fclose(fp);
-               if (got != 2)
-                       goto fail;
+       rc = parse_args(argc, argv);
+       if (rc)
+               return 0;
+
+       /* allocate image */
+       image = calloc(IMAGE_WIDTH * IMAGE_HEIGHT * ((double_pixel_size) ? 4 : 1), 3);
+       if (!image) {
+               print_error("Failed to allocate image buffer\n");
+               goto done;
        }
 
-copy:
-       /* copy track */
-       memcpy(memory + data, game_save[track & 1], length /* sizeof(game_save[0])*/);
-}
+       if ((SOUND_SAMPLERATE % IRQ_RATE)) {
+               print_error("Sample rate must be a multiple of IRQ rate, please fix!\n");
+               goto done;
+       }
+       if ((1000 % IRQ_RATE)) {
+               print_error("1000 (Ticks per second) rate must be a multiple of IRQ rate, please fix!\n");
+               goto done;
+       }
 
-/* game writes track with saved game */
-void disk_write(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
-{
-       /* skip sync info that is provided by game and only relevant for a real disk track */
-       data += 0x200;
-       length -= 0x200;
+       /* calculate SDL chunk size for audio
+        * it must be a power of two, but not more than the chunk size for each IRQ!
+        */
+       for (sdl_sound_chunk = 2; sdl_sound_chunk <= (SOUND_SAMPLERATE / IRQ_RATE); sdl_sound_chunk <<= 1)
+               ;
+       sdl_sound_chunk >>= 1;
+//     printf("samples per IRQ = %d, samples per SDL audio = %d\n", SOUND_SAMPLERATE / IRQ_RATE, sdl_sound_chunk); exit(0);
 
-       if (length != sizeof(game_save[0])) {
-               fprintf(stderr, "saving game state failed, because length of data does not match, please fix!\n");
-               return;
+       /* allocate sound buffers */
+       sound_buffer_size = SOUND_SAMPLERATE / IRQ_RATE * SOUND_CHUNKS;
+       sound_buffer = calloc(sound_buffer_size, sizeof(*sound_buffer));
+       if (!sound_buffer) {
+               print_error("Failed to allocate image buffer\n");
+               goto done;
        }
 
-       /* don't save if last track is the same, because disk is written on both sides with the same data */
-       if (track == last_track) {
-               if (memcmp(memory + data, game_save[track & 1], length)) {
-                       fprintf(stderr, "saving game data on other side of the disk is different, please fix!\n");
-               }
-               return;
+       /* allocate memory */
+       memory = calloc(MEMORY_SIZE, 1);
+       if (!memory) {
+               print_error("Failed to allocate cpu's memory\n");
+               goto done;
+       }
+       stop_event = calloc(MEMORY_SIZE, 1);
+       if (!stop_event) {
+               print_error("Failed to allocate cpu's stop_event memory\n");
+               goto done;
+       }
+       chipreg = calloc(IOSIZE, 1);
+       if (!chipreg) {
+               print_error("Failed to allocate chip register\n");
+               goto done;
        }
-       last_track = track;
 
-       /* save game data */
-       memcpy(game_save[track & 1], memory + data, length);
+       /* init cpu code */
+       execute_init(MEMORY_SIZE, memory, stop_event, chipreg, io_read, io_write, mercenary_stop_at);
 
-       /* if done with saving */
-       if ((track & 1)) {
-               char filename[256];
-               int gamesave_num = (track - 2) >> 1;
-               int wrote;
-               FILE *fp;
+       /* init disk emulation */
+       disk_init(disk_read, disk_write);
 
-               sprintf(filename, "%s/%s", home_dir, config_gamesave_dir);
-               mkdir(filename, 0777);
-               sprintf(filename + strlen(filename), "/%d.gamesave", gamesave_num);
-               fp = fopen(filename, "w");
-               if (!fp) {
-fail:
-                       fprintf(stderr, "failed to save game to '%s'\n", filename);
-                       return;
-               }
-               printf("Game state saved to '%s'\n", filename);
-               wrote = fwrite(game_save, sizeof(game_save[0]), 2, fp);
-               fclose(fp);
-               if (wrote != 2)
-                       goto fail;
+       /* load binary */
+       mercenary_load();
+
+       /* patch some stuff */
+       mercenary_patch();
+
+       /* init SDL and OpenGL */
+#ifdef HAVE_OVR
+       int vbl_sync = 0;
+       int vr = 1;
+       int multisampling = 0;
+       window_width = SCREEN_WIDTH;
+       window_height = SCREEN_HEIGHT;
+#else
+       int vbl_sync = 1;
+       int vr = 0;
+       int multisampling = config_multisampling;
+       window_width = (config_debug_opengl) ? SCREEN_WIDTH / 3 * 2 : SCREEN_WIDTH;
+       window_height = (config_debug_opengl) ? SCREEN_HEIGHT / 3 * 4 : SCREEN_HEIGHT;
+#endif
+       rc = init_sdl(mercenary_name, window_width, window_height, SOUND_SAMPLERATE, sdl_sound_chunk, keyboard_sdl, config_joystick, config_joystick_x, config_joystick_y, config_joystick_fire, joystick_sdl, audio_sdl, resize_window, multisampling, vbl_sync, vr);
+       if (rc < 0)
+               goto done;
+#ifdef HAVE_OVR
+       rc = init_ovr(config_multisampling);
+       if (rc < 0)
+               goto done;
+       rc = init_vr_keyboard(config_keyboard_height, config_keyboard_distance);
+       if (rc < 0)
+               goto done;
+#endif
+       rc = init_opengl_image((double_pixel_size) ? IMAGE_WIDTH * 2 : IMAGE_WIDTH, (double_pixel_size) ? IMAGE_HEIGHT * 2 : IMAGE_HEIGHT);
+       if (rc < 0)
+               goto done;
+
+       /* init osd */
+       rc = init_opengl_osd(0, IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2);
+       if (rc < 0)
+               goto done;
+       rc = init_opengl_osd(1, OSD_WIDTH, OSD_HEIGHT);
+       if (rc < 0)
+               goto done;
+       help_osd[0] = text_alloc(IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, 0x00);
+       if (!help_osd[0])
+               goto done;
+       text_insert_image(help_osd[0], mercenary_splash_palette, mercenary_splash_pixels, 0xff);
+       help_views++;
+       help_osd[1] = text_alloc(IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, HELP_ALPHA);
+       if (!help_osd[1])
+               goto done;
+       text_render(help_osd[1], IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, mercenary_name, HELP_ALPHA, 3, (double)(80 - strlen(mercenary_name)) / 2.0, 1, 1);
+       text_render(help_osd[1], IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2,
+               "Emulation:\n"
+               "        Press `PAUSE' to toggle this help screen on or off.\n"
+               "        Press `CTRL' + `F' to toggle between full screen / window mode.\n"
+               "        Press `CTRL' + `R' to toggle between original / OpenGL rendering.\n"
+               "        Press `CTRL' + `S' to toggle between original / fast rendering.\n"
+               "        Press `CTRL' + `B' to toggle between large / small Benson.\n"
+               "        Press `CTRL' + `V' to toggle video filter on / off.\n"
+               "        Press `CTRL' + `A' to toggle audio filter on / off.\n"
+               "        Press `CTRL' + `+' or `-' to change field-of-view (OpenGL).\n"
+               "        Press `CTRL' + `I' to skip intro (approaching to Eris).\n"
+               "        Press `CTRL' + `1' or `2' to insert or `0' to remove mission disk.\n"
+#ifdef HAVE_OVR
+               "        Press `CTRL' + `O' to reset observer position.\n"
+#endif
+               "\n"
+               "Answer to a Question:\n"
+               "        Press `O' (not Zero) for OK and other key for NO.\n"
+               "\n"
+               "Walking / Driving / Flying:\n"
+               "        Use cursor keys as joystick, to move player / craft.\n"
+               "        Press `R' for running, 'W' for walking speed.\n"
+               "        Press `B' to board, `L' to leave.\n"
+               "        Press `1'...`0' to drive / fly (slow...fast), `+' or `-' to adjust.\n"
+               "        Press `F1'...`F0' to drive / fly backwards (slow...fast).\n"
+               "        Press `SPACE' to stop craft.\n"
+               "        Press `ESCAPE' to activate escape sequence on crafts.\n"
+               "        Press `T' for turbo on certain craft.\n"
+               "        Press `END' as joystick's fire button.\n"
+               "\n"
+               "Elevator:\n"
+               "        Press `1'...`9' to select floor, 'G' for ground, `B' for basement.\n"
+               "\n"
+               "Inside a transporter:\n"
+               "        Press `1'...`0' to select destination.\n"
+               "\n"
+               "Items:\n"
+               "        Press `SHFIT' + cursor left / right keys to choose item.\n"
+               "        Press `SHFIT' + cursor up / down keys to pickup / drop item.\n"
+               "        Press `NUMPAD Enter' to select certain items.\n"
+               "        Press `NUMPAD +' / `NUMPAD -' to select entries.\n"
+               "        Press `NUMPAD *' to read entry\n"
+               "Saving / Loading / Pause:\n"
+               "        Press `INSERT' to loading and saving options.\n"
+               "        Press `ENTER' to pause game, other key to continue.\n"
+               ,HELP_ALPHA, 1, 2, 5, 0);
+               help_views++;
+#ifdef HAVE_OVR
+       help_osd[2] = text_alloc(IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, HELP_ALPHA);
+       if (!help_osd[2])
+               goto done;
+       text_render(help_osd[2], IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, mercenary_name, HELP_ALPHA, 3, (double)(80 - strlen(mercenary_name)) / 2.0, 1, 1);
+       text_render(help_osd[2], IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2,
+               "Emulation using Controller:\n"
+               "        Press `A' or 'X' button to toggle this help screen on or off.\n"
+               "        Press 'B' or 'Y' button to reset observer position. (importaint!)\n"
+               "        To have a virtual keyboard, point right hand below control pannel.\n"
+               "        Point to a key on keyboard. The key will highlight.\n"
+               "        Pull `Trigger' on right controller to enter the highlighted key.\n"
+               "\n"
+               "Walking / Driving / Flying using Controller:\n"
+               "        Use thumb stick on right controller, to move player / craft.\n"
+               "        Move thumb stick forth and back to walk, left and right to rotate.\n"
+               "        Pull `Trigger' on right controller to change orientation.\n"
+               "        Press `X' button to board, `Y' button to leave.\n"
+               "        Move thumb stick on left controller to drive/fly forward or backward.\n"
+               "        Pull `Trigger' on left controller stop craft.\n"
+               "        Press thumb stick on left controller for escape sequence and stop it.\n"
+               "        Pull `Trigger' on right controller to fire.\n"
+               "\n"
+               "For all other game function, use the virtual or real keyboard!\n"
+               ,HELP_ALPHA, 1, 2, 5, 0);
+               help_views++;
+#endif
+       info_osd = text_alloc(OSD_WIDTH, OSD_HEIGHT, 0x00);
+       if (!info_osd)
+               goto done;
+
+       /* init audio */
+       sound_init(SOUND_SAMPLERATE, sound_irq);
+
+       /* start cpu */
+       reset_cpu();
+
+       if (config_skip_intro)
+               skip_intro();
+
+       /* run game */
+       main_loop();
+
+done:
+       exit_opengl();
+#ifdef HAVE_OVR
+       exit_ovr();
+#endif
+       exit_sdl();
+
+       if (chipreg)
+               free(chipreg);
+       if (stop_event)
+               free(stop_event);
+       if (memory)
+               free(memory);
+       if (sound_buffer)
+               free(sound_buffer);
+       if (image)
+               free(image);
+       while (help_views) {
+               help_views--;
+               if (help_osd[help_views])
+                       free(help_osd[help_views]);
        }
+       if (info_osd)
+               free(info_osd);
+
+       return 0;
 }
+