diff --git a/src/config.c b/src/config.c index ee5e291..0e78584 100644 --- a/src/config.c +++ b/src/config.c @@ -31,6 +31,7 @@ #include "varz.h" #include "video.h" #include "video_scale.h" +#include "web.h" #define SAVE_FILES_SIZE (109 * SAVE_FILES_NUM) #define SAVE_FILE_SIZE (SAVE_FILES_SIZE + 100) @@ -50,8 +51,15 @@ const KeySettings defaultKeySettings = SDL_SCANCODE_RIGHT, SDL_SCANCODE_SPACE, SDL_SCANCODE_RETURN, +#ifdef __EMSCRIPTEN__ + // Web: no Ctrl/Alt (they collide with browser shortcuts and the Windows Alt menu); + // X and C are at the same place on QWERTY, QWERTZ and AZERTY. + SDL_SCANCODE_X, + SDL_SCANCODE_C, +#else SDL_SCANCODE_LCTRL, SDL_SCANCODE_LALT, +#endif }; static const char *const keySettingNames[] = @@ -352,6 +360,9 @@ static void saveOpenTyrianConfig(void) logError("Failed to write to '%s': %s", opentyrianConfigFilename, fileGetError(&file)); fileClose(&file); +#ifdef __EMSCRIPTEN__ + webSaved(); +#endif } static void playeritems_to_pitems(JE_PItemsType pItems, PlayerItems *items, JE_byte initial_episode_num) @@ -925,6 +936,9 @@ void saveSaves(void) logError("Failed to write to '%s': %s", tyrianSaveFilename, fileGetError(&file)); fileClose(&file); +#ifdef __EMSCRIPTEN__ + webSaved(); +#endif } } diff --git a/src/game_menu.c b/src/game_menu.c index 6277942..af1f650 100644 --- a/src/game_menu.c +++ b/src/game_menu.c @@ -43,6 +43,7 @@ #include "varz.h" #include "vga256d.h" #include "video.h" +#include "web.h" #include @@ -2686,6 +2687,9 @@ void JE_menuFunction(JE_byte select) colC = 1; bool joyHeld = joydown; +#ifdef __EMSCRIPTEN__ + webKeyCaptureActive = true; // the pressed key itself is wanted, W/A/S/D included +#endif while (true) { joyHeld &= joydown; @@ -2713,6 +2717,9 @@ void JE_menuFunction(JE_byte select) } KeyboardInput keyboardInput; +#ifdef __EMSCRIPTEN__ + webKeyCaptureActive = false; +#endif if (mouseGetInput(INPUT_NO_MOTION, NULL)) { diff --git a/src/joystick.c b/src/joystick.c index 39eccec..a44f897 100644 --- a/src/joystick.c +++ b/src/joystick.c @@ -202,10 +202,57 @@ void poll_joystick(int j) joystick[j].joystick_delay = SDL_GetTicks() + joystick_repeat_delay; } +#ifdef __EMSCRIPTEN__ +#include + +// Web: browsers only report a gamepad after its first button press, i.e. after the game +// started. Open gamepads that appear later (hot-plug). +void web_check_new_joysticks(void) +{ + if (ignore_joystick) + return; + + int n = SDL_NumJoysticks(); + if (n <= joysticks) + return; + + Joystick *grown = realloc(joystick, n * sizeof(*joystick)); + if (grown == NULL) + return; + joystick = grown; + + for (int j = joysticks; j < n; j++) + { + memset(&joystick[j], 0, sizeof(*joystick)); + joystick[j].handle = SDL_JoystickOpen(j); + } + int first = joysticks; + joysticks = n; + for (int j = first; j < n; j++) + { + if (joystick[j].handle == NULL) + continue; + logInfo("Joystick detected: %s (%d axes, %d buttons, %d hats)", + SDL_JoystickName(joystick[j].handle), + SDL_JoystickNumAxes(joystick[j].handle), + SDL_JoystickNumButtons(joystick[j].handle), + SDL_JoystickNumHats(joystick[j].handle)); + if (!load_joystick_assignments(&opentyrian_config, j)) + reset_joystick_assignments(j); + joystick[j].joystick_delay = SDL_GetTicks() + joystick_repeat_delay; + EM_ASM({ if (Module.otGamepadConnected) Module.otGamepadConnected($0); }, j); + } +} +#endif + // updates all joystick states void poll_joysticks(void) { joydown = false; + +#ifdef __EMSCRIPTEN__ + web_check_new_joysticks(); +#endif for (int j = 0; j < joysticks; j++) poll_joystick(j); @@ -355,6 +402,32 @@ void reset_joystick_assignments(int j) joystick[j].analog = false; joystick[j].sensitivity = 5; joystick[j].threshold = 5; + +#ifdef __EMSCRIPTEN__ + // Web: browsers expose gamepads with the "standard" layout (17 buttons, D-pad as + // buttons 12-15, no hats). Defaults: left stick (analog) + D-pad move, A/RT fire, + // B rear-weapon mode (= back in menus), LB/X left sidekick, RB/Y right sidekick, + // Start menu, Back pause. + if (SDL_JoystickNumButtons(joystick[j].handle) >= 16 && SDL_JoystickNumAxes(joystick[j].handle) >= 2) + { + static const int dpad[4] = { 12, 15, 13, 14 }; // up, right, down, left + static const int actions[6][2] = { { 0, 7 }, { 1, -1 }, { 4, 2 }, { 5, 3 }, { 9, -1 }, { 8, -1 } }; + for (uint a = 0; a < 4; a++) + { + joystick[j].assignment[a][1].type = BUTTON; + joystick[j].assignment[a][1].num = dpad[a]; + } + for (uint a = 0; a < 6; a++) + { + for (uint i = 0; i < 2; i++) + { + joystick[j].assignment[4 + a][i].type = actions[a][i] < 0 ? NONE : BUTTON; + joystick[j].assignment[4 + a][i].num = actions[a][i] < 0 ? 0 : actions[a][i]; + } + } + joystick[j].analog = true; + } +#endif } static const char* const assignment_names[] = diff --git a/src/joystick.h b/src/joystick.h index b37f103..fdbbb70 100644 --- a/src/joystick.h +++ b/src/joystick.h @@ -82,6 +82,9 @@ void push_key(SDL_Scancode key); void push_joysticks_as_keyboard(void); void init_joysticks(void); +#ifdef __EMSCRIPTEN__ +void web_check_new_joysticks(void); +#endif void deinit_joysticks(void); void reset_joystick_assignments(int j); diff --git a/src/keyboard.c b/src/keyboard.c index 17bf955..ba5eddd 100644 --- a/src/keyboard.c +++ b/src/keyboard.c @@ -24,6 +24,10 @@ #include "nortsong.h" #include "opentyr.h" #include "video.h" +#include "web.h" +#ifdef __EMSCRIPTEN__ +#include "config.h" +#endif #include "SDL.h" @@ -155,7 +159,12 @@ void mouseClearInput(void) void mouseSetRelative(bool enable) { +#ifdef __EMSCRIPTEN__ + // Web: the page handles pointer lock and touch dragging (see ot_web_mouse_rel). + webSetRelativeMouse(enable); +#else SDL_SetRelativeMouseMode(enable && windowHasFocus); +#endif mouseRelativeEnabled = enable; @@ -165,18 +174,133 @@ void mouseSetRelative(bool enable) void mouseGetRelativePosition(Sint32 *const out_x, Sint32 *const out_y) { +#ifdef __EMSCRIPTEN__ + // Web: relative motion is delivered in game-screen pixels already. + *out_x = mouseWindowXRelative; + *out_y = mouseWindowYRelative; +#else scaleWindowDistanceToScreen(&mouseWindowXRelative, &mouseWindowYRelative); *out_x = mouseWindowXRelative; *out_y = mouseWindowYRelative; +#endif mouseWindowXRelative = 0; mouseWindowYRelative = 0; } +#ifdef __EMSCRIPTEN__ +/* Pointer input from the page (mouse, touch), already in 320x200 game-screen pixels. */ + +EMSCRIPTEN_KEEPALIVE void ot_web_mouse_abs(int x, int y) +{ + if (x != mouseX || y != mouseY) + mouseInactive = false; + mouseX = x; + mouseY = y; + mouseHasMotionInput = true; +} + +EMSCRIPTEN_KEEPALIVE void ot_web_mouse_rel(int dx, int dy) +{ + if (mouseRelativeEnabled) + { + mouseWindowXRelative += dx; + mouseWindowYRelative += dy; + } + if (dx != 0 || dy != 0) + mouseInactive = false; +} + +EMSCRIPTEN_KEEPALIVE void ot_web_mouse_button(int button, int down, int x, int y) +{ + if (down) + { + mouseX = x; + mouseY = y; + if (mouseInputsCount < COUNTOF(mouseInputs)) + { + MouseInput *const input = &mouseInputs[mouseInputsBack]; + input->button = button; + input->x = x; + input->y = y; + mouseInputsBack = mouseInputsBack == COUNTOF(mouseInputs) - 1 ? 0 : mouseInputsBack + 1; + mouseInputsCount += 1; + } + mouseButtonsDown |= SDL_BUTTON(button); + mouseInactive = false; + } + else + { + mouseButtonsDown &= ~SDL_BUTTON(button); + } +} +#endif + +#ifdef __EMSCRIPTEN__ +/* Web: secondary keys for players used to WASD. W/A/S/D move (in addition to the configured + * keys; in menus they act as arrow keys), J/K/L fire and the left/right sidekick for the right + * hand. A secondary key only works while it is not assigned to an action itself, never during + * text input and never while the keyboard setup waits for a new key. */ +bool webKeyCaptureActive = false; +static bool physKeys[SDL_NUM_SCANCODES]; + +static const struct { SDL_Scancode key; int setting; SDL_Scancode menuKey; } webAltKeys[] = +{ + { SDL_SCANCODE_W, KEY_SETTING_UP, SDL_SCANCODE_UP }, + { SDL_SCANCODE_S, KEY_SETTING_DOWN, SDL_SCANCODE_DOWN }, + { SDL_SCANCODE_A, KEY_SETTING_LEFT, SDL_SCANCODE_LEFT }, + { SDL_SCANCODE_D, KEY_SETTING_RIGHT, SDL_SCANCODE_RIGHT }, + { SDL_SCANCODE_J, KEY_SETTING_FIRE, SDL_SCANCODE_UNKNOWN }, + { SDL_SCANCODE_K, KEY_SETTING_LEFT_SIDEKICK, SDL_SCANCODE_UNKNOWN }, + { SDL_SCANCODE_L, KEY_SETTING_RIGHT_SIDEKICK, SDL_SCANCODE_UNKNOWN }, +}; + +static bool webKeyAssigned(SDL_Scancode scancode) +{ + for (size_t i = 0; i < COUNTOF(keySettings); ++i) + if (keySettings[i] == scancode) + return true; + return false; +} + +static bool webAltKeyUsable(size_t i) +{ + return !webTextInputActive() && !webKeyCaptureActive && !webKeyAssigned(webAltKeys[i].key); +} + +// keysactive[configured key] = configured key held || its free secondary key held +static void webUpdateAltKeys(void) +{ + for (size_t i = 0; i < COUNTOF(webAltKeys); ++i) + { + const SDL_Scancode target = keySettings[webAltKeys[i].setting]; + if (target == SDL_SCANCODE_UNKNOWN || target == webAltKeys[i].key) + continue; + keysactive[target] = physKeys[target] || (webAltKeyUsable(i) && physKeys[webAltKeys[i].key]); + } +} + +// Menus read the key queue: W/A/S/D arrive there as arrow keys (the typed letter stays in .sym). +static SDL_Scancode webMenuScancode(SDL_Scancode scancode, Uint16 mod) +{ + if (mod & (KMOD_CTRL | KMOD_ALT | KMOD_GUI)) + return scancode; + for (size_t i = 0; i < COUNTOF(webAltKeys); ++i) + if (webAltKeys[i].key == scancode && webAltKeys[i].menuKey != SDL_SCANCODE_UNKNOWN && webAltKeyUsable(i)) + return webAltKeys[i].menuKey; + return scancode; +} +#endif + void handleSdlEvents(void) { SDL_Event ev; +#ifdef __EMSCRIPTEN__ + webPollGuard(); + web_check_new_joysticks(); // gamepads appear only after their first button press +#endif + while (SDL_PollEvent(&ev)) { switch (ev.type) @@ -212,6 +336,10 @@ void handleSdlEvents(void) if (!ev.key.repeat) keysactive[ev.key.keysym.scancode] = true; +#ifdef __EMSCRIPTEN__ + physKeys[ev.key.keysym.scancode] = true; + webUpdateAltKeys(); +#endif for (size_t i = 0; i < COUNTOF(lordKeySyms); ++i) lordKeySymsDown[i] |= ev.key.keysym.sym == lordKeySyms[i]; @@ -222,6 +350,9 @@ void handleSdlEvents(void) KeyboardInput *const input = &keyboardInputs[keyboardInputsBack]; input->sym = ev.key.keysym.sym; input->scancode = ev.key.keysym.scancode; +#ifdef __EMSCRIPTEN__ + input->scancode = webMenuScancode(ev.key.keysym.scancode, ev.key.keysym.mod); +#endif input->mod = ev.key.keysym.mod; input->ch = 0; keyboardInputsBack = keyboardInputsBack == COUNTOF(keyboardInputs) - 1 ? 0 : keyboardInputsBack + 1; @@ -233,6 +364,10 @@ void handleSdlEvents(void) case SDL_KEYUP: keysactive[ev.key.keysym.scancode] = false; +#ifdef __EMSCRIPTEN__ + physKeys[ev.key.keysym.scancode] = false; + webUpdateAltKeys(); +#endif for (size_t i = 0; i < COUNTOF(lordKeySyms); ++i) lordKeySymsDown[i] &= ev.key.keysym.sym != lordKeySyms[i]; @@ -361,7 +496,9 @@ void handleSdlEvents(void) break; case SDL_QUIT: +#ifndef __EMSCRIPTEN__ exit(0); +#endif break; } } @@ -389,7 +526,11 @@ void waitUntilHasInput(InputFlags flags) if (hasInput(flags)) return; +#ifdef __EMSCRIPTEN__ + webWaitVsync(); +#else SDL_Delay(SDL_POLL_INTERVAL); +#endif } } @@ -405,7 +546,11 @@ void waitUntilGetInput(void) if (getInput()) return; +#ifdef __EMSCRIPTEN__ + webWaitVsync(); +#else SDL_Delay(SDL_POLL_INTERVAL); +#endif } } @@ -418,11 +563,18 @@ void waitUntilElapsed(void) push_joysticks_as_keyboard(); handleSdlEvents(); +#ifdef __EMSCRIPTEN__ + if (frameCountElapsedForVsync()) + return; + + webWaitVsync(); +#else Uint32 delay = getFrameCountTicks(); if (delay == 0) return; SDL_Delay(MIN(delay, SDL_POLL_INTERVAL)); +#endif } } @@ -438,11 +590,18 @@ bool waitUntilHasInputOrElapsed(void) if (hasInput(INPUT_NO_MOTION)) return true; +#ifdef __EMSCRIPTEN__ + if (frameCountElapsedForVsync()) + return false; + + webWaitVsync(); +#else Uint32 delay = getFrameCountTicks(); if (delay == 0) return false; SDL_Delay(MIN(delay, SDL_POLL_INTERVAL)); +#endif } } @@ -458,10 +617,17 @@ bool waitUntilGetInputOrElapsed(void) if (getInput()) return true; +#ifdef __EMSCRIPTEN__ + if (frameCountElapsedForVsync()) + return false; + + webWaitVsync(); +#else Uint32 delay = getFrameCountTicks(); if (delay == 0) return false; SDL_Delay(MIN(delay, SDL_POLL_INTERVAL)); +#endif } } diff --git a/src/loudness.c b/src/loudness.c index 666e143..ef59152 100644 --- a/src/loudness.c +++ b/src/loudness.c @@ -88,6 +88,11 @@ bool init_audio(void) ask.format = AUDIO_S16SYS; ask.channels = 1; ask.samples = 256 * OUTPUT_QUALITY; // ~23 ms +#ifdef __EMSCRIPTEN__ + // Web: the audio callback runs on the browser's main thread (ScriptProcessorNode); + // a larger buffer (~46 ms) avoids crackling on phones when a frame takes longer. + ask.samples = 2048; +#endif ask.callback = audioCallback; if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) diff --git a/src/mainint.c b/src/mainint.c index ab8a94b..fb934d0 100644 --- a/src/mainint.c +++ b/src/mainint.c @@ -51,6 +51,7 @@ #include "varz.h" #include "vga256d.h" #include "video.h" +#include "web.h" #include #include @@ -206,6 +207,12 @@ void JE_helpSystem(JE_byte startTopic) const int yMenuItems = 60; const int dyMenuItems = 20; const int hMenuItem = 13; +#ifdef __EMSCRIPTEN__ + // Web: the clickable area of a menu item covers the gap to its neighbours (touch). + const int hitPadTop = (dyMenuItems - hMenuItem) / 2, hitPadBottom = dyMenuItems - hMenuItem - hitPadTop; +#else + const int hitPadTop = 0, hitPadBottom = 0; +#endif int wMenuItem[COUNTOF(topicName) - 1] = { 0 }; for (; ; ) @@ -281,7 +288,7 @@ void JE_helpSystem(JE_byte startTopic) if (mouseInput.x >= xMenuItem && mouseInput.x < xMenuItem + wMenuItem[i]) { const int yMenuItem = yMenuItems + dyMenuItems * i; - if (mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + if (mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { if (selectedIndex != i) { @@ -292,7 +299,7 @@ void JE_helpSystem(JE_byte startTopic) if (mouseInput.button == SDL_BUTTON_LEFT && mouseInput.x >= xMenuItem && mouseInput.x < xMenuItem + wMenuItem[i] && - mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { action = true; } @@ -636,6 +643,12 @@ bool JE_loadScreen(void) const int yMenuItems = 30; const int dyMenuItems = 13; const int hMenuItem = 8; +#ifdef __EMSCRIPTEN__ + // Web: the clickable area of a menu item covers the gap to its neighbours (touch). + const int hitPadTop = (dyMenuItems - hMenuItem) / 2, hitPadBottom = dyMenuItems - hMenuItem - hitPadTop; +#else + const int hitPadTop = 0, hitPadBottom = 0; +#endif const int xLeftControl = 83; const int xRightControl = 213; const int wControl = 24; @@ -769,7 +782,7 @@ bool JE_loadScreen(void) for (size_t i = 0; i < menuItemsCount; ++i) { const int yMenuItem = yMenuItems + dyMenuItems * i; - if (mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + if (mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { if (selectedIndex != i) { @@ -780,7 +793,7 @@ bool JE_loadScreen(void) if (mouseInput.button == SDL_BUTTON_LEFT && mouseInput.x >= xMenuItem && mouseInput.x < xMenuItem + wMenuItem && - mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { action = true; } @@ -1482,6 +1495,12 @@ JE_boolean JE_inGameSetup(void) const int wMenuItemValue = 90; const int wMenuItem = wMenuItemName + wMenuItemValue; const int hMenuItem = 13; +#ifdef __EMSCRIPTEN__ + // Web: the clickable area of a menu item covers the gap to its neighbours (touch). + const int hitPadTop = (dyMenuItems - hMenuItem) / 2, hitPadBottom = dyMenuItems - hMenuItem - hitPadTop; +#else + const int hitPadTop = 0, hitPadBottom = 0; +#endif for (bool done = false; !done; ) { @@ -1570,7 +1589,7 @@ JE_boolean JE_inGameSetup(void) for (size_t i = 0; i < menuItemsCount; ++i) { const int yMenuItem = yMenuItems + dyMenuItems * i; - if (mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + if (mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { if (selectedIndex != i) { @@ -1581,7 +1600,7 @@ JE_boolean JE_inGameSetup(void) if (mouseInput.button == SDL_BUTTON_LEFT && mouseInput.x >= xMenuItem && mouseInput.x < xMenuItem + wMenuItem && - mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { // Act on menu item via name. if (mouseInput.x >= xMenuItemName && mouseInput.x < xMenuItemName + wMenuItemName) @@ -1985,6 +2004,9 @@ void JE_highScoreCheck(void) JE_barShade(VGAScreen, 65, 55, 255, 155); SDL_StartTextInput(); +#ifdef __EMSCRIPTEN__ + webTextInput(true); +#endif do { @@ -2101,6 +2123,9 @@ void JE_highScoreCheck(void) } while (!quit); SDL_StopTextInput(); +#ifdef __EMSCRIPTEN__ + webTextInput(false); +#endif if (!cancel) { @@ -2736,6 +2761,9 @@ void JE_operation(JE_byte slot) JE_barShade(VGAScreen, 65, 55, 255, 155); SDL_StartTextInput(); +#ifdef __EMSCRIPTEN__ + webTextInput(true); +#endif bool quit = false; while (!quit) @@ -2841,6 +2869,9 @@ void JE_operation(JE_byte slot) } SDL_StopTextInput(); +#ifdef __EMSCRIPTEN__ + webTextInput(false); +#endif } } @@ -3480,6 +3511,23 @@ redo: } } +#ifdef __EMSCRIPTEN__ + /* web touch buttons (page): fire, left/right sidekick, change rear mode */ + if (playerNum_ == 1 && !playDemo) + { + button[0] |= (webTouchButtons & 1) != 0; + button[1] |= (webTouchButtons & 2) != 0; + button[2] |= (webTouchButtons & 4) != 0; + button[3] |= (webTouchButtons & 8) != 0; + + /* touch dragging: fed through the original mouse movement path */ + Sint32 touchXR, touchYR; + webTakeTouchMotion(&touchXR, &touchYR); + mouseXC += touchXR; + mouseYC += touchYR; + } +#endif + /* mouse input */ if ((inputDevice == 0 || inputDevice == 2) && has_mouse) { diff --git a/src/menus.c b/src/menus.c index 9ea634d..fc01f01 100644 --- a/src/menus.c +++ b/src/menus.c @@ -58,6 +58,12 @@ bool gameplaySelect(void) const int yMenuItems = 54; const int dyMenuItems = 24; const int hMenuItem = 13; +#ifdef __EMSCRIPTEN__ + // Web: the clickable area of a menu item covers the gap to its neighbours (touch). + const int hitPadTop = (dyMenuItems - hMenuItem) / 2, hitPadBottom = dyMenuItems - hMenuItem - hitPadTop; +#else + const int hitPadTop = 0, hitPadBottom = 0; +#endif int wMenuItem[COUNTOF(gameplay_name) - 1] = { 0 }; for (; ; ) @@ -123,7 +129,7 @@ bool gameplaySelect(void) if (mouseInput.x >= xMenuItem && mouseInput.x < xMenuItem + wMenuItem[i]) { const int yMenuItem = yMenuItems + dyMenuItems * i; - if (mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + if (mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { if (selectedIndex != i) { @@ -134,7 +140,7 @@ bool gameplaySelect(void) if (mouseInput.button == SDL_BUTTON_LEFT && mouseInput.x >= xMenuItem && mouseInput.x < xMenuItem + wMenuItem[i] && - mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { action = true; } @@ -242,6 +248,12 @@ bool episodeSelect(void) const int yMenuItems = 50; const int dyMenuItems = 30; const int hMenuItem = 13; +#ifdef __EMSCRIPTEN__ + // Web: the clickable area of a menu item covers the gap to its neighbours (touch). + const int hitPadTop = (dyMenuItems - hMenuItem) / 2, hitPadBottom = dyMenuItems - hMenuItem - hitPadTop; +#else + const int hitPadTop = 0, hitPadBottom = 0; +#endif int wMenuItem[EPISODE_AVAILABLE] = { 0 }; for (; ; ) @@ -305,7 +317,7 @@ bool episodeSelect(void) if (mouseInput.x >= xMenuItem && mouseInput.x < xMenuItem + wMenuItem[i]) { const int yMenuItem = yMenuItems + dyMenuItems * i; - if (mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + if (mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { if (selectedIndex != i) { @@ -316,7 +328,7 @@ bool episodeSelect(void) if (mouseInput.button == SDL_BUTTON_LEFT && mouseInput.x >= xMenuItem && mouseInput.x < xMenuItem + wMenuItem[i] && - mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { action = true; } @@ -417,6 +429,12 @@ bool difficultySelect(void) const int yMenuItems = 54; const int dyMenuItems = 24; const int hMenuItem = 13; +#ifdef __EMSCRIPTEN__ + // Web: the clickable area of a menu item covers the gap to its neighbours (touch). + const int hitPadTop = (dyMenuItems - hMenuItem) / 2, hitPadBottom = dyMenuItems - hMenuItem - hitPadTop; +#else + const int hitPadTop = 0, hitPadBottom = 0; +#endif int wMenuItem[COUNTOF(difficulty_name) - 1] = { 0 }; for (; ; ) @@ -481,7 +499,7 @@ bool difficultySelect(void) if (mouseInput.x >= xMenuItem && mouseInput.x < xMenuItem + wMenuItem[i]) { const int yMenuItem = yMenuItems + dyMenuItems * i; - if (mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + if (mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { if (selectedIndex != i) { @@ -492,7 +510,7 @@ bool difficultySelect(void) if (mouseInput.button == SDL_BUTTON_LEFT && mouseInput.x >= xMenuItem && mouseInput.x < xMenuItem + wMenuItem[i] && - mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { action = true; } diff --git a/src/nortsong.c b/src/nortsong.c index 2ec1f37..856f5f6 100644 --- a/src/nortsong.c +++ b/src/nortsong.c @@ -23,6 +23,7 @@ #include "loudness.h" #include "opentyr.h" #include "sndmast.h" +#include "web.h" #include "SDL.h" @@ -52,6 +53,20 @@ static Uint16 framePeriod = ((Uint64)0x4300 << 10) * 1000 * 88 * 3 / 315000000; static Uint32 frameCountEnd = 0; static Uint32 frameCount2End = 0; +// How late a frame may be before the timer phase is dropped. Original: one timer tick +// (like the DOS timer interrupt, a late game simply lost the time). Web: displays may +// show fewer frames per second than the game's ~34.8 Hz (30 Hz screens, iOS low-power +// mode), so short delays are caught up to keep the original game speed; only real stalls +// (tab hidden, pause, long loads) resynchronize. +static Sint32 resyncLimit(void) +{ +#ifdef __EMSCRIPTEN__ + return 100 << 10; +#else + return framePeriod; +#endif +} + void setFrameSpeed(Uint16 speed) // FKA NortSong.speed and NortSong.setTimerInt { frameSpeed = speed; @@ -66,7 +81,7 @@ void setFrameCount(JE_word frameCount) // FKA NortSong.frameCount // Keep the partial timer period that has already elapsed. Uint32 now = SDL_GetTicks() << 10; Sint32 diff = now - frameCountEnd; - if (diff >= framePeriod) + if (diff >= resyncLimit()) frameCountEnd = now - (Uint32)diff % framePeriod; else if (-diff >= framePeriod) frameCountEnd = now + (Uint32)-diff % framePeriod; @@ -79,7 +94,7 @@ void setFrameCount2(JE_word frameCount2) // FKA NortSong.frameCount2 // Keep the partial timer period that has already elapsed. Uint32 now = SDL_GetTicks() << 10; Sint32 diff = now - frameCount2End; - if (diff >= framePeriod) + if (diff >= resyncLimit()) frameCount2End = now - (Uint32)diff % framePeriod; else if (-diff >= framePeriod) frameCount2End = now + (Uint32)-diff % framePeriod; @@ -103,6 +118,25 @@ Uint32 getFrameCount2Ticks(void) return diff >= 0 ? ((Uint32)diff + half) >> 10 : 0; } +#ifdef __EMSCRIPTEN__ +// Web: frames are shown at the display's vsync (requestAnimationFrame). A frame deadline +// that is less than half a refresh period away counts as reached, so every game frame is +// shown at the vsync nearest to its original deadline. The deadlines themselves stay on +// the original fixed timer grid (setFrameCount keeps the phase), so the game speed is +// exactly the original one at any refresh rate. +bool frameCountElapsedForVsync(void) +{ + Uint32 now = SDL_GetTicks() << 10; + Sint32 diff = frameCountEnd - now; + return diff <= (Sint32)webHalfVsyncQ10(); +} + +void delayUntilElapsed(void) +{ + while (!frameCountElapsedForVsync()) + webWaitVsync(); +} +#else void delayUntilElapsed(void) { const Uint32 half = 1 << 9; @@ -111,6 +145,7 @@ void delayUntilElapsed(void) if (diff >= 0) SDL_Delay(((Uint32)diff + half) >> 10); } +#endif static void loadSounds(size_t soundsOffset, size_t soundsCount, const char *filename, bool trim, SDL_AudioCVT *cvt) { diff --git a/src/nortsong.h b/src/nortsong.h index dc9b30f..b46017e 100644 --- a/src/nortsong.h +++ b/src/nortsong.h @@ -38,6 +38,9 @@ void setFrameCount2(JE_word frameCount2); Uint32 getFrameCountTicks(void); Uint32 getFrameCount2Ticks(void); void delayUntilElapsed(void); +#ifdef __EMSCRIPTEN__ +bool frameCountElapsedForVsync(void); +#endif void JE_changeVolume(JE_word *music, int music_delta, JE_word *sample, int sample_delta); diff --git a/src/opentyr.c b/src/opentyr.c index 59b481d..827c190 100644 --- a/src/opentyr.c +++ b/src/opentyr.c @@ -49,6 +49,7 @@ #include "video.h" #include "video_scale.h" #include "xmas.h" +#include "web.h" #include "SDL.h" @@ -143,7 +144,9 @@ void setupMenu(void) [MENU_SETUP] = { .header = "Setup", .items = { +#ifndef __EMSCRIPTEN__ // web: display options are in the page's settings panel { MENU_ITEM_GRAPHICS, "Graphics...", "Change the graphics settings." }, +#endif { MENU_ITEM_SOUND, "Sound...", "Change the sound settings." }, { MENU_ITEM_JUKEBOX, "Jukebox", "Listen to the music of Tyrian." }, // { MENU_ITEM_DESTRUCT, "Destruct", "Play a bonus mini-game." }, @@ -196,6 +199,12 @@ void setupMenu(void) const int yMenuItems = 37; const int dyMenuItems = 21; const int hMenuItem = 13; +#ifdef __EMSCRIPTEN__ + // Web: the clickable area of a menu item covers the gap to its neighbours (touch). + const int hitPadTop = (dyMenuItems - hMenuItem) / 2, hitPadBottom = dyMenuItems - hMenuItem - hitPadTop; +#else + const int hitPadTop = 0, hitPadBottom = 0; +#endif for (; ; ) { @@ -356,7 +365,7 @@ void setupMenu(void) for (size_t i = 0; i < menuItemsCount; ++i) { const int yMenuItem = yMenuItems + dyMenuItems * i; - if (mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + if (mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { if (*selectedMenuItemIndex != i) { @@ -366,7 +375,7 @@ void setupMenu(void) } if (mouseInput.button == SDL_BUTTON_LEFT && - mouseInput.y >= yMenuItem && mouseInput.y < yMenuItem + hMenuItem) + mouseInput.y >= yMenuItem - hitPadTop && mouseInput.y < yMenuItem + hMenuItem + hitPadBottom) { // Act on menu item via name. if (mouseInput.x >= xMenuItemName && mouseInput.x < xMenuItemName + wMenuItemName) @@ -547,7 +556,13 @@ void setupMenu(void) fade_black(10); +#ifdef __EMSCRIPTEN__ + webKeyCaptureActive = true; // the jukebox uses letter keys itself (S = stop, ...) +#endif jukebox(); +#ifdef __EMSCRIPTEN__ + webKeyCaptureActive = false; +#endif restart = true; break; diff --git a/src/tyrian2.c b/src/tyrian2.c index 044fa4c..527cec8 100644 --- a/src/tyrian2.c +++ b/src/tyrian2.c @@ -95,6 +95,12 @@ void JE_starShowVGA(void) setFrameCount(frameCountMax); } +#ifdef __EMSCRIPTEN__ + { + extern unsigned int webGameFrames; + ++webGameFrames; + } +#endif if (starShowVGASpecialCode == 1) { diff --git a/src/video.c b/src/video.c index c95e269..ef9c23f 100644 --- a/src/video.c +++ b/src/video.c @@ -21,6 +21,9 @@ #include "keyboard.h" #include "logging.h" #include "video_scale.h" +#include "web.h" + +#include "palette.h" #include #include @@ -93,6 +96,16 @@ void init_video(void) exit(EXIT_FAILURE); } +#ifdef __EMSCRIPTEN__ + // Web: the page draws the 320x200 frame itself (WebGL, sharp scaling, aspect ratio, + // vsync). The SDL window only exists for keyboard/focus events; no SDL renderer. + // RGBA byte order so the palette entries can be uploaded to WebGL as they are. + main_window_tex_format = SDL_AllocFormat(SDL_PIXELFORMAT_ABGR8888); + scaler_function = NULL; + (void)init_renderer; + (void)init_texture; + SDL_ShowWindow(main_window); +#else reinit_fullscreen(fullscreen_display); init_renderer(); init_texture(); @@ -103,6 +116,7 @@ void init_video(void) SDL_SetRenderDrawColor(main_window_renderer, 0, 0, 0, 255); SDL_RenderClear(main_window_renderer); SDL_RenderPresent(main_window_renderer); +#endif } void deinit_video(void) @@ -192,6 +206,11 @@ static void window_center_in_display(int display_index) void reinit_fullscreen(int new_display) { +#ifdef __EMSCRIPTEN__ + (void)new_display; + fullscreen_display = -1; // the page has its own fullscreen button + return; +#endif fullscreen_display = new_display; if (fullscreen_display >= SDL_GetNumVideoDisplays()) @@ -220,6 +239,9 @@ void reinit_fullscreen(int new_display) void video_on_win_resize(void) { +#ifdef __EMSCRIPTEN__ + return; +#endif int w, h; int scaler_w, scaler_h; @@ -249,6 +271,10 @@ void toggle_fullscreen(void) bool init_scaler(unsigned int new_scaler) { +#ifdef __EMSCRIPTEN__ + scaler = new_scaler; // remembered in the config only; the page does the scaling + return true; +#endif int w = scalers[new_scaler].width, h = scalers[new_scaler].height; int bpp = main_window_tex_format->BitsPerPixel; // TODOSDL2 @@ -378,6 +404,11 @@ static void scale_and_flip(SDL_Surface *src_surface) { assert(src_surface->format->BitsPerPixel == 8); +#ifdef __EMSCRIPTEN__ + webPresent(src_surface, rgb_palette); + return; +#endif + // Do software scaling assert(scaler_function != NULL); scaler_function(src_surface, main_window_texture); diff --git a/src/web.c b/src/web.c new file mode 100644 index 0000000..e805f09 --- /dev/null +++ b/src/web.c @@ -0,0 +1,288 @@ +/* + * OpenTyrian: A modern cross-platform port of Tyrian + * Copyright (C) The OpenTyrian Development Team + * + * Web (Emscripten) port glue – Retro Classics. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ +#ifdef __EMSCRIPTEN__ + +#include "web.h" + +#include "config.h" +#include "keyboard.h" +#include "opentyr.h" +#include "player.h" +#include "varz.h" +#include "video.h" + +#include +#include + +Uint8 webTouchButtons = 0; + +static Uint32 frameRgba[vga_width * vga_height]; + +static Uint32 halfVsyncQ10 = (Uint32)(8.33 * 1024); // until measured: 60 Hz +static unsigned int yieldCount = 0; // increments whenever we gave control to the browser +static unsigned int pollsSinceYield = 0; +static double lastYieldTime = 0; + +static bool relativeMouse = false; +static bool textInput = false; + +// Statistics for automated tests (frame pacing / game speed). +unsigned int webGameFrames = 0; // game logic frames (JE_starShowVGA) +static unsigned int webPresents = 0; // frames handed to the page + +// Resolves on the next requestAnimationFrame; returns the measured refresh period in +// microseconds (0 = unknown). The page may hold the promise while the game is paused. +EM_ASYNC_JS(int, web_js_wait_frame, (void), { + return await Module.otWaitFrame(); +}); + +void webWaitVsync(void) +{ + int periodUs = web_js_wait_frame(); + // Snap window = half a refresh period, but at most 10 ms: setFrameCount() moves the + // timer phase if a frame starts more than one timer tick (14.4 ms) early. + if (periodUs >= 2000 && periodUs <= 70000) + halfVsyncQ10 = (Uint32)((Uint64)MIN(periodUs, 20000) * 1024 / 2000); + + ++yieldCount; + pollsSinceYield = 0; + lastYieldTime = emscripten_get_now(); +} + +Uint32 webHalfVsyncQ10(void) +{ + return halfVsyncQ10; +} + +void webPresent(const SDL_Surface *surface, const Uint32 *palette) +{ + const Uint8 *src = surface->pixels; + Uint32 *dst = frameRgba; + for (int y = 0; y < vga_height; ++y) + { + const Uint8 *s = src + y * surface->pitch; + for (int x = 0; x < vga_width; ++x) + *dst++ = palette[s[x]]; + } + ++webPresents; + EM_ASM({ if (Module.otPresent) Module.otPresent($0); }, frameRgba); +} + +void webPollGuard(void) +{ + // In normal play the game yields once per frame (vsync wait), so it never polls more + // than a couple of times in a row. Loops that poll input without waiting would freeze + // the browser (events can only arrive when we yield), so give control back. + if (++pollsSinceYield < 4) + return; + double now = emscripten_get_now(); + if (now - lastYieldTime < 12.0) + return; + emscripten_sleep(4); + ++yieldCount; + pollsSinceYield = 0; + lastYieldTime = emscripten_get_now(); +} + +void webSetRelativeMouse(bool enable) +{ + if (relativeMouse == enable) + return; + relativeMouse = enable; + EM_ASM({ if (Module.otRelativeMouse) Module.otRelativeMouse($0); }, enable); +} + +void webTextInput(bool active) +{ + textInput = active; + EM_ASM({ if (Module.otTextInput) Module.otTextInput($0); }, active); +} + +bool webTextInputActive(void) +{ + return textInput; +} + +void webSaved(void) +{ + EM_ASM({ if (Module.otSaved) Module.otSaved(); }); +} + +/* --------------------------------------------------------------------------------------- + * Exports for the page (see app/play/opentyrian/index.html) + * ------------------------------------------------------------------------------------- */ + +// Bit 0: in-game (relative mouse / ship control), bit 1: text input active. +EMSCRIPTEN_KEEPALIVE int ot_web_state(void) +{ + return (relativeMouse ? 1 : 0) | (textInput ? 2 : 0); +} + +EMSCRIPTEN_KEEPALIVE void ot_web_touch_buttons(int mask) +{ + webTouchButtons = (Uint8)mask; +} + +// Pushes a key press/release (SDL scancode) into the SDL event queue. +EMSCRIPTEN_KEEPALIVE void ot_web_key(int scancode, int down) +{ + SDL_Event e; + SDL_zero(e); + e.type = down ? SDL_KEYDOWN : SDL_KEYUP; + e.key.state = down ? SDL_PRESSED : SDL_RELEASED; + e.key.keysym.scancode = (SDL_Scancode)scancode; + e.key.keysym.sym = SDL_GetKeyFromScancode((SDL_Scancode)scancode); + e.key.keysym.mod = KMOD_NONE; + SDL_PushEvent(&e); +} + +// Pushes one character of text input (ASCII). +EMSCRIPTEN_KEEPALIVE void ot_web_text(int ch) +{ + SDL_Event e; + SDL_zero(e); + e.type = SDL_TEXTINPUT; + e.text.text[0] = (char)ch; + e.text.text[1] = '\0'; + SDL_PushEvent(&e); +} + +/* Touch dragging ("relative": the ship follows the finger with an offset). + * + * The page reports finger movement in 1/256 game pixels. We keep a target position + * (ship position when the finger touched down + finger movement since) and every game + * frame choose the mouse delta for the ORIGINAL mouse movement code that brings the ship + * to the target fastest without overshooting. The ship physics stay untouched: a mouse + * delta d moves the ship directly by (d +- 3) / 4 pixels (d clamped to +-30) and, above + * a small threshold, accelerates it (velocity max 4, friction every 2nd/3rd frame) - + * exactly what a real mouse does. The controller simulates that model to brake in time. + */ +typedef struct { int pos, vel, ticks; } AxisState; + +static bool touchActive = false; +static Sint32 targetXQ8 = 0, targetYQ8 = 0; + +static int clampi(int v, int lo, int hi) { return v < lo ? lo : v > hi ? hi : v; } + +// One frame of the original movement model (JE_playerMovement) for a mouse delta d. +// axis 0 = x (accel above 3, friction every 2nd frame, 40..256), 1 = y (above 2, every 3rd, 10..160) +static void stepAxis(AxisState *st, int d, int axis) +{ + d = clampi(d, -30, 30); + int direct = d > 0 ? (d + 3) / 4 : d < 0 ? (d - 3) / 4 : 0; + int accel = (d > (axis == 0 ? 3 : 2)) ? 1 : (d < -2 ? -1 : 0); + st->pos += direct; + if (st->ticks > 0) + --st->ticks; + else + { + st->ticks = axis == 0 ? 1 : 2; + if (st->vel < 0) ++st->vel; else if (st->vel > 0) --st->vel; + } + st->vel = clampi(st->vel + accel, -4, 4); + st->pos += st->vel; + st->pos = axis == 0 ? clampi(st->pos, 40, 256) : clampi(st->pos, 10, 160); +} + +static int controlAxis(int pos, int vel, int ticks, int target, int axis) +{ + if (target == pos && vel == 0) + return 0; + const int brakeUp = axis == 0 ? 4 : 3; // smallest delta that accelerates upwards/rightwards + int bestD = 0, bestCost = 1 << 30; + for (int d = -30; d <= 30; ++d) + { + AxisState st = { pos, vel, ticks }; + stepAxis(&st, d, axis); + int pos1 = st.pos; + // then brake as hard as possible until the ship stands still + for (int i = 0; i < 16 && st.vel != 0; ++i) + stepAxis(&st, st.vel > 0 ? -3 : brakeUp, axis); + int cost = 4 * abs(target - st.pos) + abs(target - pos1); + if (cost < bestCost || (cost == bestCost && abs(d) < abs(bestD))) + { + bestCost = cost; + bestD = d; + } + } + return bestD; +} + +EMSCRIPTEN_KEEPALIVE void ot_web_touch_begin(void) +{ + touchActive = true; + targetXQ8 = player[0].x << 8; + targetYQ8 = player[0].y << 8; +} + +EMSCRIPTEN_KEEPALIVE void ot_web_touch_move(int dxQ8, int dyQ8) +{ + if (!touchActive) + ot_web_touch_begin(); + // keep the target reachable: finger movement beyond the edges is dropped, so moving + // back immediately moves the ship back (like a mouse at the screen edge) + targetXQ8 = clampi(targetXQ8 + dxQ8, 40 << 8, 256 << 8); + targetYQ8 = clampi(targetYQ8 + dyQ8, 10 << 8, 160 << 8); +} + +EMSCRIPTEN_KEEPALIVE void ot_web_touch_reset(void) +{ + touchActive = false; +} + +void webTakeTouchMotion(Sint32 *out_x, Sint32 *out_y) +{ + *out_x = *out_y = 0; + if (!touchActive) + return; + const Player *p = &player[0]; + *out_x = controlAxis(p->x, p->x_velocity, (int)p->x_friction_ticks, (targetXQ8 + 128) >> 8, 0); + *out_y = controlAxis(p->y, p->y_velocity, (int)p->y_friction_ticks, (targetYQ8 + 128) >> 8, 1); +} + +// Saves tyrian.cfg / opentyrian.cfg (the game itself only does that when quitting). +EMSCRIPTEN_KEEPALIVE void ot_web_save_config(void) +{ + saveConfiguration(); +} + +// Debug values for automated tests. +EMSCRIPTEN_KEEPALIVE int ot_web_debug(int what) +{ + switch (what) + { + case 0: return (int)webGameFrames; + case 1: return (int)webPresents; + case 2: return (int)yieldCount; + case 3: return (int)halfVsyncQ10; + case 4: return player[0].x; + case 5: return player[0].y; + case 6: return (int)player[0].cash; + case 7: return mouseX; + case 8: return mouseY; + case 9: // keysactive of the 8 configured keys (up, down, left, right, fire, mode, left/right sidekick) + { + int mask = 0; + for (int i = 0; i < 8; ++i) + mask |= keysactive[keySettings[i]] ? 1 << i : 0; + return mask; + } + default: return 0; + } +} + +#endif /* __EMSCRIPTEN__ */ diff --git a/src/web.h b/src/web.h new file mode 100644 index 0000000..cea1488 --- /dev/null +++ b/src/web.h @@ -0,0 +1,54 @@ +/* + * OpenTyrian: A modern cross-platform port of Tyrian + * Copyright (C) The OpenTyrian Development Team + * + * Web (Emscripten) port glue – Retro Classics. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + */ +#ifndef WEB_H +#define WEB_H + +#ifdef __EMSCRIPTEN__ + +#include "SDL.h" + +#include +#include + +// Touch/virtual buttons from the page: bit 0 fire, 1 left sidekick, 2 right sidekick, 3 change rear mode. +extern Uint8 webTouchButtons; + +// Touch dragging (relative): returns this frame's movement for the original mouse path +// (see JE_playerMovement) so the ship follows the finger 1:1 within the game's own speed limit. +void webTakeTouchMotion(Sint32 *out_x, Sint32 *out_y); + +// Waits (ASYNCIFY) for the next requestAnimationFrame of the page. +void webWaitVsync(void); + +// Half of the measured display refresh period in UQ22.10 milliseconds (frame deadlines +// that are closer than this are treated as reached, so frames snap to the nearest vsync). +Uint32 webHalfVsyncQ10(void); + +// Converts the 8-bit screen with the current palette and hands it to the page renderer. +void webPresent(const SDL_Surface *surface, const Uint32 *palette); + +// Busy-wait guard: called whenever the game polls input. Yields to the browser if the +// game polled several times without ever yielding (original "wait until key released" loops). +void webPollGuard(void); + +// Notifications to the page. +void webSetRelativeMouse(bool enable); +void webTextInput(bool active); +void webSaved(void); +bool webTextInputActive(void); + +// True while the keyboard setup waits for a key or the jukebox runs (no secondary-key translation then). +extern bool webKeyCaptureActive; + +#endif /* __EMSCRIPTEN__ */ + +#endif /* WEB_H */ diff --git a/web/VERSION b/web/VERSION new file mode 100644 index 0000000..e6c7ef5 --- /dev/null +++ b/web/VERSION @@ -0,0 +1 @@ +v2.1.20260913-web1 diff --git a/web/build.sh b/web/build.sh new file mode 100644 index 0000000..66b60f2 --- /dev/null +++ b/web/build.sh @@ -0,0 +1,30 @@ +#!/bin/sh +# OpenTyrian web build (Emscripten 4.0.10). Run from the source root: +# sh web/build.sh [outdir] -> outdir/opentyrian.js + opentyrian.wasm +# Extra compiler flags can be passed via EXTRA_CFLAGS (e.g. -DOT_WEB_TESTHOOKS). +set -e +OUT="${1:-build-web}" +mkdir -p "$OUT/obj" +CFLAGS="-std=gnu99 -O2 -DNDEBUG -DTARGET_UNIX -DTYRIAN_DIR=\"/data\" -sUSE_SDL=2 \ + -Wall -Wextra -Wno-missing-field-initializers -Wno-unused-parameter -Wno-sign-compare ${EXTRA_CFLAGS}" +VER="$(cat web/VERSION 2>/dev/null || echo web)" +CFLAGS="$CFLAGS -DOPENTYRIAN_VERSION=\"$VER\"" +OBJS="" +for f in src/*.c; do + o="$OUT/obj/$(basename "$f" .c).o" + if [ ! -f "$o" ] || [ "$f" -nt "$o" ] || [ web/build.sh -nt "$o" ] || [ -n "$FORCE" ]; then + echo "CC $f" + emcc $CFLAGS -c "$f" -o "$o" + fi + OBJS="$OBJS $o" +done +echo "LINK $OUT/opentyrian.js" +emcc $OBJS -o "$OUT/opentyrian.js" -O2 -sUSE_SDL=2 \ + -sASYNCIFY -sASYNCIFY_STACK_SIZE=65536 -sSTACK_SIZE=1048576 \ + -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=64MB \ + -sFORCE_FILESYSTEM -lidbfs.js -sEXIT_RUNTIME=1 \ + -sINVOKE_RUN=0 -sENVIRONMENT=web \ + -sEXPORTED_RUNTIME_METHODS=FS,FS_createPath,FS_createDataFile,FS_createPreloadedFile,addRunDependency,removeRunDependency,callMain,ENV,HEAPU8 \ + -sEXPORTED_FUNCTIONS=_main,_malloc,_free,_ot_web_state,_ot_web_key,_ot_web_text,_ot_web_mouse_abs,_ot_web_mouse_rel,_ot_web_mouse_button,_ot_web_touch_buttons,_ot_web_touch_begin,_ot_web_touch_move,_ot_web_touch_reset,_ot_web_save_config,_ot_web_debug \ + --pre-js web/opentyrian_pre.js +ls -la "$OUT"/opentyrian.* diff --git a/web/opentyrian_pre.js b/web/opentyrian_pre.js new file mode 100644 index 0000000..269445b --- /dev/null +++ b/web/opentyrian_pre.js @@ -0,0 +1,6 @@ +// OpenTyrian web port – pre-js (Retro Classics). The page (index.html) provides +// Module.otWaitFrame / otPresent / otRelativeMouse / otTextInput / otSaved; these +// fallbacks keep the engine usable without the page shell. +Module.otWaitFrame = Module.otWaitFrame || function () { + return new Promise(function (resolve) { requestAnimationFrame(function () { resolve(0); }); }); +};