Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ wasm/opensupaplex.data
wasm/opensupaplex.html
wasm/opensupaplex.js
wasm/opensupaplex.wasm
wasm/deploy/opensupaplex.data
wasm/deploy/opensupaplex.js
wasm/deploy/opensupaplex.wasm

# RISC OS stuff
riscos/*,e1f
Expand Down
76 changes: 76 additions & 0 deletions src/file.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,73 @@

#include "utils.h"

#if defined(__EMSCRIPTEN__)
#include <emscripten.h>

// Writable files (savegames, configs, hall of fame, edited level lists) live
// under /persistent, an IDBFS mount backed by IndexedDB. The mount and the
// sync-in of the previous session's contents must complete before main reads
// any file; with -sJSPI the EM_ASYNC_JS call below suspends main until then.
EM_ASYNC_JS(void, syncInPersistentStorage, (void), {
try
{
FS.mkdir('/persistent');
FS.mount(IDBFS, {}, '/persistent');
await new Promise((resolve, reject) => FS.syncfs(true, (err) => (err ? reject(err) : resolve())));
}
catch (err)
{
// Without IndexedDB (blocked storage, etc.) the game still runs, but
// saves only last for the current page session.
console.warn('OpenSupaplex: persistent storage unavailable: ' + err);
}
});

EM_JS(void, initializePersistentStorageSync, (void), {
let dirty = false;
let syncing = false;
const flush = () => {
if (!dirty || syncing) return;
syncing = true;
dirty = false;
FS.syncfs(false, (err) => {
syncing = false;
if (err)
{
dirty = true;
console.warn('OpenSupaplex: saving to browser storage failed: ' + err);
}
});
};
// openWritableFile returns before the caller writes and closes the file,
// so sync out shortly after a write is triggered; the interval and
// pagehide flushes bound the window in which a reload can lose data.
Module.__markPersistentStorageDirty = () => {
dirty = true;
if (!Module.__persistentStorageSyncTimer)
{
Module.__persistentStorageSyncTimer = setTimeout(() => {
Module.__persistentStorageSyncTimer = 0;
flush();
}, 250);
}
};
setInterval(flush, 5000);
addEventListener('pagehide', flush);
});

EM_JS(void, schedulePersistentStorageSyncOut, (void), {
Module.__markPersistentStorageDirty?.();
});

void initializePersistentStorage(void)
{
syncInPersistentStorage();
initializePersistentStorageSync();
}

#endif

#if defined(FILE_FHS_XDG_DIRS)

#if defined(FILE_DATA_PATH)
Expand Down Expand Up @@ -177,6 +244,9 @@ FILE *openWritableFile(const char *pathname, const char *mode)
#define FILE_BASE_PATH "/apps/OpenSupaplex/"
#elif defined(__WIIU__)
#define FILE_BASE_PATH "fs:/vol/external01/wiiu/apps/OpenSupaplex/"
#elif defined(__EMSCRIPTEN__)
#define FILE_BASE_PATH ""
#define FILE_BASE_WRITABLE_PATH "/persistent/"
#else
#define FILE_BASE_PATH ""
#endif
Expand Down Expand Up @@ -213,6 +283,12 @@ FILE *openWritableFile(const char *pathname, const char *mode)

char finalPathname[kMaxFilePathLength];
getWritableFilePath(pathname, finalPathname);
#if defined(__EMSCRIPTEN__)
if (strpbrk(mode, "wa+") != NULL)
{
schedulePersistentStorageSyncOut();
}
#endif
return fopen(finalPathname, mode);
}

Expand Down
7 changes: 7 additions & 0 deletions src/file.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ FILE *openReadonlyFile(const char *pathname, const char *mode);
FILE *openWritableFile(const char *pathname, const char *mode);
FILE *openWritableFileWithReadonlyFallback(const char *pathname, const char *mode);

#if defined(__EMSCRIPTEN__)
// Mounts the IDBFS-backed directory where writable files live and waits for
// the previous session's contents to be synced in. Must run before any other
// file access.
void initializePersistentStorage(void);
#endif

size_t fileReadUInt16(uint16_t *value, FILE *file);
size_t fileReadUInt8(uint8_t *value, FILE *file);
size_t fileReadBytes(void *buffer, size_t count, FILE *file);
Expand Down
5 changes: 5 additions & 0 deletions src/sdl2/video.c
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,11 @@ void getMouseState(int *x, int *y, uint8_t *leftButton, uint8_t *rightButton)
Uint32 state = SDL_GetMouseState(x, y);
*leftButton = (state & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0;
*rightButton = (state & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
#ifdef __EMSCRIPTEN__
// Menu handlers poll this in tight "wait for button release" loops with
// no frame pacing; without a yield the browser can never deliver mouseup.
SDL_Delay(1);
#endif
}

void toggleFullscreen()
Expand Down
3 changes: 3 additions & 0 deletions src/supaplex.c
Original file line number Diff line number Diff line change
Expand Up @@ -1513,6 +1513,9 @@ void runAdvancedOptionsRootMenu()

int main(int argc, char *argv[])
{
#ifdef __EMSCRIPTEN__
initializePersistentStorage();
#endif
parseCommandLineOptions(argc, argv);

if (gFastMode == FastModeTypeUltra)
Expand Down
17 changes: 17 additions & 0 deletions start-http-wasm.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/bin/sh
# Serves the WASM build over HTTP for browser testing (wasm/ must be built first).
# Usage: $0 [port]

PORT="${1:-8931}"
DIR="$(cd "$(dirname "$0")/wasm" && pwd)"

if [ ! -f "$DIR/opensupaplex.js" ]; then
echo "wasm/opensupaplex.js not found - run 'make' in wasm/ first" >&2
exit 1
fi

echo "Serving $DIR at http://127.0.0.1:$PORT/"
echo " game: http://127.0.0.1:$PORT/opensupaplex.html"
echo "Press Ctrl+C to stop."

exec python3 -m http.server "$PORT" --bind 127.0.0.1 --directory "$DIR"
17 changes: 16 additions & 1 deletion wasm/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,27 @@ CC=emcc
src = $(wildcard ../src/*.c) $(wildcard ../src/sdl2/*.c) $(wildcard ../src/sdl_common/*.c) ../src/null/virtualKeyboard.c ../src/lib/ini/ini.c
obj = $(src:.c=.o)

LDFLAGS = -lSDL2_mixer -lSDL2
# -sJSPI=1 is required: without it SDL_Delay busy-waits on the JS main thread
# and the never-returning main() loop freezes the page (JSPI makes
# emscripten_sleep suspend the wasm stack natively; ASYNCIFY would also work)
# -lidbfs.js backs /persistent (writable files: savegames, configs, hall of
# fame) with IndexedDB so they survive reloads; see src/file.c
# -sSDL2_MIXER_FORMATS=mod compiles libmodplug into the SDL2_mixer port so
# the .xm music files decode; it replaces the default "ogg" (unused, no .ogg
# assets), keeping WAV (always built in) for sound effects
# -sDEFAULT_TO_CXX links the C++ runtime: libmodplug is C++ and all game
# objects are C, so emcc would otherwise leave operator new/delete undefined
LDFLAGS = -sJSPI=1 -lSDL2_mixer -lSDL2 -lidbfs.js -sSDL2_MIXER_FORMATS=mod -sDEFAULT_TO_CXX -sEXPORTED_RUNTIME_METHODS=FS

CFLAGS = -s USE_SDL=2 -s USE_SDL_MIXER=2 -DHAVE_SDL2

opensupaplex.html: $(obj)
$(CC) -s ALLOW_MEMORY_GROWTH=1 -o $@ $^ $(LDFLAGS) --preload-file ../resources@/

# refresh wasm/deploy/ (self-contained browser deployment; index.html and
# README.md are tracked, the copied artifacts are gitignored)
deploy: opensupaplex.html
cp opensupaplex.js opensupaplex.wasm opensupaplex.data deploy/

clean:
rm $(obj)
94 changes: 94 additions & 0 deletions wasm/deploy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# OpenSupaplex — self-contained browser deployment

Everything the game needs is in this folder; nothing is fetched from outside it
(no CDN, no analytics, no external assets). Host it anywhere static files can
be served, or embed it in another site as described below.

## Files

| File | Purpose |
|-----------------------|------------------------------------------------------|
| `index.html` | Minimal loader shell (canvas + `Module` config) |
| `opensupaplex.js` | Emscripten runtime glue, generated by the build |
| `opensupaplex.wasm` | Game engine |
| `opensupaplex.data` | Game assets (~9 MB, packed by `--preload-file`) |

The three `opensupaplex.*` files must stay together in the same directory; the
runtime resolves them relative to the location of `opensupaplex.js`, not the
embedding page.

## Serving it

Any static file server works, e.g.:

```sh
python3 -m http.server 8000
```

Opening `index.html` directly from disk (`file://`) does **not** work: browsers
block fetching the `.wasm`/`.data` files without an HTTP origin.

Serve `.wasm` with `Content-Type: application/wasm` if your server doesn't
already (all common ones do), and enable gzip/brotli if you can — the `.js` and
`.data` compress very well.

## Browser support

The build uses JSPI (JavaScript Promise Integration) for its main loop:

- Chrome / Edge 137+ (May 2025)
- Firefox 139+
- Safari 27+

## Embedding in a third-party site

### Option A — iframe (simplest)

```html
<iframe src="https://your-host.example/opensupaplex/" width="1280" height="800"
style="border:0" allow="fullscreen"></iframe>
```

No CORS configuration needed. Note: when embedded cross-site, browsers may
partition or block storage in third-party iframes, which affects persistent
saves (see below). Serving the iframe from the *same* origin as the embedding
site avoids this.

### Option B — direct embed

Add this where the game should appear:

```html
<div style="width:1280px;height:800px">
<canvas id="canvas" tabindex="-1" oncontextmenu="event.preventDefault()"
style="max-width:100%;max-height:100%"></canvas>
</div>
<script>var Module = { canvas: document.getElementById("canvas") };</script>
<script src="https://your-host.example/opensupaplex/opensupaplex.js"></script>
```

Caveats:

- `Module` is a plain global and the game auto-starts when the script loads —
one instance per page, and don't reuse the name `Module` on that page.
- The canvas **must** keep `id="canvas"`; the runtime looks that id up for the
audio-unlock hook.
- If served from a different origin than the page, the host must send
`Access-Control-Allow-Origin` for `.js`, `.wasm` and `.data` (and `crossorigin`
fetches must not be blocked).

## Persistent saves

Savegames, settings and hall of fame are stored in IndexedDB via IDBFS, keyed
to the origin the game runs on (or the embedding site's origin with option B).
Clearing site data deletes them; there is no other copy.

## Updating this folder

After rebuilding (`make -C wasm`), refresh the artifacts with:

```sh
make -C wasm deploy
```

`index.html` and this README live in git; the copied artifacts are gitignored.
21 changes: 21 additions & 0 deletions wasm/deploy/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>OpenSupaplex</title>
<style>
html,body{height:100%;margin:0;background:#000}
body{display:flex;align-items:center;justify-content:center;overflow:hidden}
/* no border/padding on the canvas, or mouse coords will be wrong */
canvas{max-width:100%;max-height:100%}
</style>
</head>
<body>
<!-- id="canvas" is load-bearing: the runtime resolves the audio-unlock hook
and event targets via document.getElementById('canvas') -->
<canvas id="canvas" tabindex="-1" oncontextmenu="event.preventDefault()"></canvas>
<script>var Module={canvas:document.getElementById("canvas")}</script>
<script src="opensupaplex.js"></script>
</body>
</html>