aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNicholas Rodrigues Lordello <[email protected]>2026-10-17 10:52:27 +0200
committerNicholas Rodrigues Lordello <[email protected]>2026-10-17 10:52:27 +0200
commitd3c95fce3f5c8b910d3dc04ed5d8c1673944baf0 (patch)
tree61b36f4cf2c0c77a3ee3bc05a83384b695e58fb5
parentf97bb735065392d639462e90d9abd1bb5f738c61 (diff)
Use `wasm2c` instead of WAMR
Instead of interpreting Wasm, compile it ahead of time to C and run that instead: - it is much faster (no interpreter overhead) - it is easier to implement host functions, they are just C calls This works well for us since we only ever load a single Wasm blob (the PICO-8 runtime that `picow` is built with). There was some fun figuring out how big-endian stuff works (WRT memory layout), but otherwise it was pretty straight forward. Note that traps are still not working, I need to figure that out still...
-rw-r--r--Makefile67
-rw-r--r--src/config.c33
-rw-r--r--src/config.h1
-rw-r--r--src/env.c246
-rw-r--r--src/env.h50
-rw-r--r--src/fb.c32
-rw-r--r--src/fb.h9
-rw-r--r--src/game.c562
-rw-r--r--src/game.h25
-rw-r--r--src/picow.c2
-rw-r--r--src/wasmrt.c142
-rw-r--r--src/wasmrt.h233
-rw-r--r--tools/generate-sysroot.c2
13 files changed, 803 insertions, 601 deletions
diff --git a/Makefile b/Makefile
index 93d1b04..426fc9d 100644
--- a/Makefile
+++ b/Makefile
@@ -1,70 +1,51 @@
-include config.mk
-CC ?= cc
-AR ?= ar
-HOSTCC ?= cc
-PICO8 ?= pico8
+CC ?= cc
+AR ?= ar
+HOSTCC ?= cc
+PICO8 ?= pico8
+WASM2C ?= wasm2c
+
WAT2WASM ?= wat2wasm
-ARCH ?= $(shell uname -m)
-CFLAGS += -std=c99 -Wall -Wextra -O2 -MMD
-SDL3_CFLAGS ?= $(shell pkg-config sdl3 --cflags)
-SDL3_LIBS ?= $(shell pkg-config sdl3 --libs)
+ARCH ?= $(shell uname -m)
+CFLAGS ?= -std=c99 -Wall -Wextra -O2 -MMD -Isrc -Ilib -I$(SYSTEM) \
+ $(shell pkg-config sdl3 --cflags)
+LDFLAGS ?= $(shell pkg-config sdl3 --libs) -lm
+W2CFLAGS ?= --disable-tail-call
TARGET := build/$(ARCH)
OUT := $(TARGET)/out
TOOLS := build/tools
SYSTEM := build/system
-PICOW_CFLAGS := $(CFLAGS) $(SDL3_CFLAGS) -Ilib/
-PICOW_LDFLAGS := $(LDFLAGS) $(SDL3_LIBS) -L$(TARGET) -lwamr -lm
-PICOW_SRC := $(wildcard src/*.c) $(SYSTEM)/sysroot.c
-PICOW_OBJ := $(patsubst %.c,$(OUT)/%.o,$(PICOW_SRC:build/%=%))
-
-WAMR_CFLAGS := $(CFLAGS) -Wno-unused-parameter \
- -DBH_FREE=wasm_runtime_free \
- -DBH_MALLOC=wasm_runtime_malloc \
- -DWASM_ENABLE_FAST_INTERP=1 \
- -DWASM_ENABLE_INTERP=1 \
- -Ilib/wamr/core/iwasm/common \
- -Ilib/wamr/core/iwasm/include \
- -Ilib/wamr/core/iwasm/interpreter \
- -Ilib/wamr/core/shared/mem-alloc \
- -Ilib/wamr/core/shared/platform/include \
- -Ilib/wamr/core/shared/utils \
- -Ilib/wamr/custom
-WAMR_SRC := $(shell find lib/wamr -name '*.c')
-WAMR_OBJ := $(patsubst %.c,$(OUT)/%.o,$(WAMR_SRC))
+SRC := $(wildcard src/*.c) $(SYSTEM)/pico8.c $(SYSTEM)/sysroot.c
+OBJ := $(patsubst %.c,$(OUT)/%.o,$(SRC:build/%=%))
.PHONY: all
all: $(TARGET)/picow ;
-$(TARGET)/picow: $(PICOW_OBJ) $(TARGET)/libwamr.a
+$(TARGET)/picow: $(OBJ)
@ echo "CC\t$@"
- @ $(CC) $(PICOW_OBJ) -o $@ $(PICOW_LDFLAGS)
+ @ $(CC) $(OBJ) -o $@ $(LDFLAGS)
-$(OUT)/src/%.o: src/%.c $(SYSTEM)/sysroot.h
+$(OUT)/src/%.o: src/%.c $(SYSTEM)/pico8.h $(SYSTEM)/sysroot.h
@ echo "CC\t$@"
@ mkdir -p $(dir $@)
- @ $(CC) $(PICOW_CFLAGS) -I$(SYSTEM) -c $< -o $@
+ @ $(CC) $(CFLAGS) -c $< -o $@
$(OUT)/system/%.o: $(SYSTEM)/%.c
@ echo "CC\t$@"
@ mkdir -p $(dir $@)
- @ $(CC) $(PICOW_CFLAGS) -Isrc/ -c $< -o $@
-
-$(TARGET)/libwamr.a: $(WAMR_OBJ)
- @ echo "AR\t$@"
- @ $(AR) rcs $@ $^
+ @ $(CC) $(CFLAGS) -Wno-unused -Wno-unused-parameter -c $< -o $@
-$(OUT)/lib/wamr/%.o: lib/wamr/%.c
- @ echo "CC\t$@"
- @ mkdir -p $(dir $@)
- @ $(CC) $(WAMR_CFLAGS) -c $< -o $@
+$(SYSTEM)/pico8.h $(SYSTEM)/pico8.c: $(SYSTEM)/stub/pico8.wasm \
+ $(SYSTEM)/pico8.wasm
+ @ echo "WASM2C\t$(SYSTEM)/pico8.h $(SYSTEM)/pico8.c"
+ @ $(WASM2C) $(W2CFLAGS) $< -o $(SYSTEM)/pico8.c
+ @ echo '#include "wasmrt.h"' > $(SYSTEM)/wasm-rt.h
$(SYSTEM)/sysroot.h $(SYSTEM)/sysroot.c: $(TOOLS)/generate-sysroot \
$(SYSTEM)/pico8.data.pod \
- $(SYSTEM)/pico8.wasm \
- $(SYSTEM)/stub/pico8.wasm \
$(SYSTEM)/unknown.p8.png \
$(SYSTEM)/font.png
@ echo "TOOL\t$(SYSTEM)/sysroot.h $(SYSTEM)/sysroot.c"
@@ -113,4 +94,4 @@ build/compile_commands.json: $(TOOLS)/ccj
clean:
rm -rf build/
--include $(PICOW_OBJ:.o=.d) $(WAMR_OBJ:.o=.d)
+-include $(OBJ:.o=.d)
diff --git a/src/config.c b/src/config.c
index 48d4208..346e649 100644
--- a/src/config.c
+++ b/src/config.c
@@ -1,3 +1,4 @@
+#include <errno.h>
#include <stdio.h>
// We don't have `getopt` on all platforms (notably, it is not available on
@@ -16,6 +17,7 @@ static void usage(char const *name) {
printf("Usage: %s [-c <carts>] [-d] [-S <mode>] [-v[v[v]]]\n"
" -c <carts> Carts directory.\n"
" -d Print additional debug statistics.\n"
+ " -m <mb> Memory to allocate for PICO-8 in MB.\n"
" -S <mode> Scale mode: 'pp' (default), 'fill' or 'stretch'.\n"
" -v[v[v]] Increasingly verbose logging.\n",
pw_basename(name));
@@ -59,6 +61,24 @@ static bool parse_scale_mode(char const *s, enum pw_scale_mode *m) {
return true;
}
+static bool parse_size(char const *s, size_t *m) {
+ errno = 0;
+ char *end = NULL;
+ long long v = SDL_strtoll(s, &end, 10);
+
+ if (end == s || *end != '\0') {
+ SDL_SetError("invalid digit %c", *end);
+ return false;
+ }
+ if (errno == ERANGE || v < 0 ||
+ (unsigned long long)v > (unsigned long long)SIZE_MAX) {
+ SDL_SetError("size out of range");
+ }
+
+ *m = (size_t)v;
+ return true;
+}
+
static bool parse_log_priority(char const *s, SDL_LogPriority *l) {
struct named_value values[] = {
{"trace", SDL_LOG_PRIORITY_TRACE},
@@ -140,6 +160,11 @@ static void parse_config_ini(struct pw_config *config) {
SDL_LogWarn(0, "%s", SDL_GetError());
SDL_ClearError();
}
+ } else if (!SDL_strcmp(key, "memory")) {
+ if (!parse_size(value, &config->memory)) {
+ SDL_LogWarn(0, "%s", SDL_GetError());
+ SDL_ClearError();
+ }
} else if (!SDL_strcmp(key, "verbosity")) {
if (!parse_log_priority(value, &config->logp)) {
SDL_LogWarn(0, "%s", SDL_GetError());
@@ -180,6 +205,7 @@ struct pw_config *pw_config_load(int argc, char **argv) {
goto cleanup;
}
config->mode = PW_SCALE_MODE_PIXEL_PERFECT;
+ config->memory = 32;
config->logp = SDL_GetLogPriority(0);
// Read default values from the `config.ini` file before parsing command line
@@ -189,7 +215,7 @@ struct pw_config *pw_config_load(int argc, char **argv) {
#if defined(_POSIX_VERSION)
int c;
optind = 1;
- while ((c = getopt(argc, argv, ":hc:dS:v")) != -1) {
+ while ((c = getopt(argc, argv, ":hc:dm:S:v")) != -1) {
switch (c) {
case 'h':
usage(name);
@@ -204,6 +230,11 @@ struct pw_config *pw_config_load(int argc, char **argv) {
case 'd':
config->debug = true;
break;
+ case 'm':
+ if (!parse_size(optarg, &config->memory)) {
+ goto cleanup;
+ }
+ break;
case 'S':
if (!parse_scale_mode(optarg, &config->mode)) {
goto cleanup;
diff --git a/src/config.h b/src/config.h
index 7cc2134..f75669c 100644
--- a/src/config.h
+++ b/src/config.h
@@ -13,6 +13,7 @@ struct pw_config {
bool debug;
char *carts;
enum pw_scale_mode mode;
+ size_t memory;
SDL_LogPriority logp;
};
diff --git a/src/env.c b/src/env.c
new file mode 100644
index 0000000..71858e3
--- /dev/null
+++ b/src/env.c
@@ -0,0 +1,246 @@
+#include <SDL3/SDL_error.h>
+#include <SDL3/SDL_stdinc.h>
+#include <SDL3/SDL_timer.h>
+
+#include "env.h"
+
+struct w2c_env *pw_env_init(size_t memory) {
+ if (memory < 24 || memory > 128) {
+ SDL_InvalidParamError("memory");
+ return NULL;
+ }
+ size_t pages = ((memory << 20) + wasm2c_pico8_pagesize_env_memory - 1) /
+ wasm2c_pico8_pagesize_env_memory;
+ size_t memory_size = pages * wasm2c_pico8_pagesize_env_memory;
+ struct w2c_env *env = SDL_malloc(sizeof(*env) + memory_size);
+ if (!env) {
+ return NULL;
+ }
+
+ env->memory.data = (uint8_t *)env + sizeof(*env);
+ env->memory.data_end = env->memory.data + memory_size;
+ env->memory.size = memory_size;
+ SDL_zerop(&env->context);
+
+ return env;
+}
+
+void pw_env_free(struct w2c_env *env) {
+ if (!env) {
+ SDL_InvalidParamError("env");
+ return;
+ }
+
+ SDL_free(env);
+}
+
+bool pw_env_link(struct w2c_env *env, struct pw_env_ctx context) {
+ if (!env) {
+ return SDL_InvalidParamError("env");
+ }
+ if (!context.fb || !context.input || !context.carts || !context.instance) {
+ return SDL_InvalidParamError("context");
+ }
+
+ env->context = context;
+ env->main_loop = 0;
+ return true;
+}
+
+/**
+ * Convenience macro for writing to wasm memory and moving the wasm pointer
+ * forward for that amount.
+ */
+#define MEM_WRITE(n, e, a, v) \
+ do { \
+ wasm_rt_memory_store##n##_unchecked(&e->memory, a, v); \
+ a += (n / 8); \
+ } while (0)
+
+static uint32_t env_ticks(void) {
+ return (uint32_t)(SDL_GetTicks() & UINT32_MAX);
+}
+
+struct wasm_rt_memory_t *w2c_env_memory(struct w2c_env *env) {
+ return &env->memory;
+}
+
+uint32_t w2c_env_0x5FSDL_GetMouseState(struct w2c_env *env, uint32_t x,
+ uint32_t y) {
+ struct pw_coordinates pos;
+ enum pw_mouse_button button = pw_input_mouse(env->context.input, &pos);
+
+ if (x) {
+ wasm_rt_memory_store32(&env->memory, x, pos.x);
+ }
+ if (y) {
+ wasm_rt_memory_store32(&env->memory, y, pos.y);
+ }
+ return (uint32_t)button;
+}
+
+/* import: 'env' '_SDL_LockSurface' */
+uint32_t w2c_env_0x5FSDL_LockSurface(struct w2c_env *env, uint32_t surface) {
+ if (!surface) {
+ SDL_InvalidParamError("surface");
+ return (uint32_t)(-1);
+ }
+
+ wasm_rt_memory_store32(&env->memory, surface + 28, 1);
+ return 0;
+}
+
+#define ENV_KEYDOWN 0x300
+#define ENV_KEYUP 0x301
+#define ENV_MOUSEMOTION 0x400
+
+uint32_t w2c_env_0x5FSDL_PollEvent(struct w2c_env *env, uint32_t event) {
+ if (!event) {
+ return (uint32_t)pw_input_poll(env->context.input, NULL);
+ }
+
+ union pw_input_event input;
+ bool remaining = pw_input_poll(env->context.input, &input);
+ if (remaining) {
+ wasm_rt_memory_check(&env->memory, event, 36);
+ switch (input.type) {
+ case PW_INPUT_EVENT_KEY:
+ if (input.key.pressed) {
+ MEM_WRITE(32, env, event, ENV_KEYDOWN);
+ } else {
+ MEM_WRITE(32, env, event, ENV_KEYUP);
+ }
+ MEM_WRITE(32, env, event, 1); // windowID
+ MEM_WRITE(8, env, event, (uint8_t)input.key.pressed);
+ MEM_WRITE(8, env, event, (uint8_t)input.key.repeat);
+ MEM_WRITE(8, env, event, 0); // padding2
+ MEM_WRITE(8, env, event, 0); // padding3
+ MEM_WRITE(32, env, event, input.key.scancode);
+ MEM_WRITE(32, env, event, input.key.keycode);
+ MEM_WRITE(16, env, event, (uint16_t)input.key.mod);
+ MEM_WRITE(16, env, event, 0); // keysym.{padding}
+ MEM_WRITE(32, env, event, 0); // keysym.unicode (deprecated)
+ break;
+ case PW_INPUT_EVENT_MOUSE:
+ MEM_WRITE(32, env, event, ENV_MOUSEMOTION);
+ MEM_WRITE(32, env, event, env_ticks());
+ MEM_WRITE(32, env, event, 1); // windowID
+ MEM_WRITE(32, env, event, 1); // which
+ MEM_WRITE(32, env, event, (uint32_t)input.mouse.button);
+ MEM_WRITE(32, env, event, input.mouse.x);
+ MEM_WRITE(32, env, event, input.mouse.y);
+ MEM_WRITE(32, env, event, input.mouse.xrel);
+ MEM_WRITE(32, env, event, input.mouse.yrel);
+ break;
+ };
+ }
+
+ return (uint32_t)remaining;
+}
+
+// PICO-8 engine is compiled with the Emscripten built-in SDL1.3 library, which
+// has a different pixel format encoding than SDL3 which is used on the host.
+// The pixel format used by the engine is:
+#define ENV_PIXELFORMAT_ABGR8888 0x86762004
+
+uint32_t w2c_env_0x5FSDL_SetVideoMode(struct w2c_env *env, uint32_t w,
+ uint32_t h, uint32_t bpp,
+ uint32_t flags) {
+ if (w != PW_FB_WIDTH || h != PW_FB_HEIGHT || bpp != 32 || flags != 0) {
+ SDL_SetError("unsupported video mode");
+ return 0;
+ }
+
+ uint32_t result =
+ w2c_pico8_0x5Fmalloc(env->context.instance, 60 + 44 + PW_FB_SIZE);
+ if (!result) {
+ SDL_SetError("failed to allocate surface");
+ return 0;
+ }
+
+ uint32_t surface = result;
+ uint32_t format = surface + 60;
+ uint32_t pixels = format + 44;
+ wasm_rt_memory_check(&env->memory, pixels, PW_FB_SIZE);
+
+ {
+ MEM_WRITE(32, env, surface, flags);
+ MEM_WRITE(32, env, surface, format);
+ MEM_WRITE(32, env, surface, w);
+ MEM_WRITE(32, env, surface, h);
+ MEM_WRITE(32, env, surface, (w * bpp) / 8);
+ MEM_WRITE(32, env, surface, pixels);
+ MEM_WRITE(32, env, surface, 0); // userdata
+ MEM_WRITE(32, env, surface, 0); // locked
+ MEM_WRITE(32, env, surface, 0); // lock_data
+ MEM_WRITE(32, env, surface, 0); // clip_rect.x
+ MEM_WRITE(32, env, surface, 0); // clip_rect.y
+ MEM_WRITE(32, env, surface, w); // clip_rect.w
+ MEM_WRITE(32, env, surface, h); // clip_rect.h
+ MEM_WRITE(32, env, surface, 0); // map
+ MEM_WRITE(32, env, surface, 1); // refcount
+ }
+ {
+ MEM_WRITE(32, env, format, ENV_PIXELFORMAT_ABGR8888);
+ MEM_WRITE(32, env, format, 0); // palette
+ MEM_WRITE(8, env, format, (uint8_t)bpp);
+ MEM_WRITE(8, env, format, (uint8_t)bpp / 8);
+ MEM_WRITE(16, env, format, 0); // padding
+ MEM_WRITE(32, env, format, 0x000000ff); // rmask
+ MEM_WRITE(32, env, format, 0x0000ff00); // gmask
+ MEM_WRITE(32, env, format, 0x00ff0000); // bmask
+ MEM_WRITE(32, env, format, 0xff000000); // amask
+ MEM_WRITE(8, env, format, 0); // rloss
+ MEM_WRITE(8, env, format, 0); // gloss
+ MEM_WRITE(8, env, format, 0); // bloss
+ MEM_WRITE(8, env, format, 0); // aloss
+ MEM_WRITE(8, env, format, 0); // rshift
+ MEM_WRITE(8, env, format, 8); // gshift
+ MEM_WRITE(8, env, format, 16); // bshift
+ MEM_WRITE(8, env, format, 24); // ashift
+ MEM_WRITE(32, env, format, 1); // refcount
+ MEM_WRITE(32, env, format, 0); // next
+ }
+ {
+ wasm_rt_memory_set(&env->memory, pixels, PW_FB_SIZE, 0);
+ }
+
+ return result;
+}
+
+void w2c_env_0x5FSDL_UnlockSurface(struct w2c_env *env, uint32_t surface) {
+ if (!surface) {
+ SDL_InvalidParamError("surface");
+ return;
+ }
+
+ wasm_rt_memory_check(&env->memory, surface, 60);
+
+ // Always clear the locked flag as unlocking should never fail.
+ wasm_rt_memory_store32_unchecked(&env->memory, surface + 28, 0);
+
+ // Now copy over the screen from wasm memory to our framebuffer. Note that
+ // we bounds check _before_ locking the framebuffer, this prevents OOB access
+ // to trap whitout properly unlocking it.
+ uint32_t pixels = wasm_rt_memory_load32_unchecked(&env->memory, surface + 20);
+ wasm_rt_memory_check(&env->memory, pixels, PW_FB_SIZE);
+ uint8_t *buffer = pw_fb_lock(env->context.fb);
+ if (!buffer) {
+ SDL_SetError("unable to lock framebuffer");
+ return;
+ }
+ wasm_rt_memory_load_unchecked(&env->memory, buffer, pixels, PW_FB_SIZE);
+ pw_fb_unlock(env->context.fb);
+}
+
+/* import: 'env' '_emscripten_set_main_loop' */
+void w2c_env_0x5Femscripten_set_main_loop(struct w2c_env *env, uint32_t func,
+ uint32_t fps,
+ uint32_t simulate_infinite_loop) {
+ env->main_loop = func;
+
+ // Ignore the fps and simulate infinite loop parameters, they are always 0
+ // for PICO-8 anyway.
+ (void)fps;
+ (void)simulate_infinite_loop;
+}
diff --git a/src/env.h b/src/env.h
new file mode 100644
index 0000000..4f99d2e
--- /dev/null
+++ b/src/env.h
@@ -0,0 +1,50 @@
+#ifndef PW_WENV_H
+#define PW_WENV_H
+
+#include "cart.h"
+#include "fb.h"
+#include "input.h"
+#include "pico8.h"
+#include "wasmrt.h"
+
+/**
+ * A host execution context.
+ *
+ * Contains _borrowed_ references to various components required by the
+ * environment host functions.
+ */
+struct pw_env_ctx {
+ struct pw_framebuffer *fb;
+ struct pw_input *input;
+ struct pw_multicart *carts;
+ struct w2c_pico8 *instance;
+};
+
+/**
+ * The Web Assembly host environment.
+ *
+ * This holds the required state to implement the host functions imported by
+ * the PICO-8 `.wasm` module.
+ */
+struct w2c_env {
+ struct wasm_rt_memory_t memory;
+ struct pw_env_ctx context;
+ uint32_t main_loop;
+};
+
+/**
+ * Allocates a new host environment with the specified Web Assembly memory size.
+ */
+struct w2c_env *pw_env_init(size_t memory);
+
+/**
+ * Frees the host environement.
+ */
+void pw_env_free(struct w2c_env *env);
+
+/**
+ * Sets a host environment's execution context.
+ */
+bool pw_env_link(struct w2c_env *env, struct pw_env_ctx context);
+
+#endif
diff --git a/src/fb.c b/src/fb.c
index f59c700..bb229ba 100644
--- a/src/fb.c
+++ b/src/fb.c
@@ -96,34 +96,34 @@ bool pw_fb_coordinates(struct pw_framebuffer *fb, float wx, float wy,
return true;
}
-bool pw_fb_blit(struct pw_framebuffer *fb, uint8_t const pixels[PW_FB_SIZE]) {
+uint8_t *pw_fb_lock(struct pw_framebuffer *fb) {
if (!fb) {
SDL_InvalidParamError("fb");
- return false;
- }
- if (!pixels) {
- SDL_InvalidParamError("pixels");
- return false;
- }
-
- SDL_Renderer *renderer = SDL_GetRendererFromTexture(fb->texture);
- if (!renderer) {
- return false;
+ return NULL;
}
void *buffer;
int pitch;
if (!SDL_LockTexture(fb->texture, NULL, &buffer, &pitch)) {
- return false;
+ return NULL;
}
- bool ok = pitch == PW_FB_WIDTH * PW_FB_BYTES_PER_PIXEL;
- if (ok) {
- SDL_memcpy(buffer, pixels, PW_FB_SIZE);
+ if (pitch != PW_FB_WIDTH * PW_FB_BYTES_PER_PIXEL) {
+ SDL_UnlockTexture(fb->texture);
+ SDL_SetError("unexpected framebuffer pitch");
+ return NULL;
+ }
+
+ return buffer;
+}
+
+void pw_fb_unlock(struct pw_framebuffer *fb) {
+ if (!fb) {
+ SDL_InvalidParamError("fb");
+ return;
}
SDL_UnlockTexture(fb->texture);
- return ok;
}
bool pw_fb_render(struct pw_framebuffer *fb) {
diff --git a/src/fb.h b/src/fb.h
index 7656921..591f6a4 100644
--- a/src/fb.h
+++ b/src/fb.h
@@ -50,9 +50,14 @@ bool pw_fb_coordinates(struct pw_framebuffer *fb, float wx, float wy,
struct pw_coordinates *coords);
/**
- * Blits the pixel data to the framebuffer.
+ * Locks the framebuffer for writing.
*/
-bool pw_fb_blit(struct pw_framebuffer *fb, uint8_t const pixels[PW_FB_SIZE]);
+uint8_t *pw_fb_lock(struct pw_framebuffer *fb);
+
+/**
+ * Unlocks the framebuffer for writing.
+ */
+void pw_fb_unlock(struct pw_framebuffer *fb);
/**
* Renders the the framebuffer.
diff --git a/src/game.c b/src/game.c
index c29f0d3..4803fc0 100644
--- a/src/game.c
+++ b/src/game.c
@@ -1,338 +1,24 @@
-#include <math.h>
-
#include <SDL3/SDL_log.h>
-#include <SDL3/SDL_timer.h>
#include "game.h"
-#include "input.h"
-#include "sysroot.h"
-
-static void *wasm_malloc(unsigned int size) { return SDL_malloc((size_t)size); }
-
-static void *wasm_realloc(void *ptr, unsigned int size) {
- return SDL_realloc(ptr, (size_t)size);
-}
-
-static void wasm_free(void *ptr) { SDL_free(ptr); }
-
-static void *emrt_memory(wasm_exec_env_t exec, uint32_t offset, uint32_t size) {
- wasm_module_inst_t instance = wasm_runtime_get_module_inst(exec);
- if (!instance || !wasm_runtime_validate_app_addr(instance, offset, size)) {
- return NULL;
- }
-
- return wasm_runtime_addr_app_to_native(instance, offset);
-}
+#include "pico8.h"
-#define emrt_write(m, t, v) \
- do { \
- uint8_t **emrt__m = (uint8_t **)(m); \
- t emrt__v = (v); \
- SDL_memcpy(*emrt__m, &emrt__v, sizeof(emrt__v)); \
- *emrt__m += sizeof(emrt__v); \
- } while (0)
-
-static void emrt_set_main_loop(wasm_exec_env_t exec, uint64_t *args) {
- native_raw_get_arg(int32_t, func, args);
- native_raw_get_arg(int32_t, fps, args);
- native_raw_get_arg(int32_t, simulate_infinite_loop, args);
-
- struct pw_game *game = wasm_runtime_get_user_data(exec);
- SDL_LogDebug(0, "setting main loop function: %d", func);
- game->mainfn = func;
-
- // Ignore the fps and simulate infinite loop parameters, they are always 0
- // for PICO-8 anyway.
- (void)fps;
- (void)simulate_infinite_loop;
-}
-
-// PICO-8 engine is compiled with the Emscripten built-in SDL1.3 library, which
-// has a different pixel format encoding than SDL3 which is used on the host.
-// The pixel format used by the engine is:
-#define EMRT_PIXELFORMAT_ABGR8888 0x86762004
-
-static void emrt_set_video_mode(wasm_exec_env_t exec, uint64_t *args) {
- native_raw_return_type(int32_t, args);
- native_raw_get_arg(int32_t, w, args);
- native_raw_get_arg(int32_t, h, args);
- native_raw_get_arg(int32_t, bpp, args);
- native_raw_get_arg(int32_t, flags, args);
-
- struct pw_game *game = wasm_runtime_get_user_data(exec);
-
- if (w != 128 || h != 128 || bpp != 32 || flags != 0) {
- SDL_LogWarn(0, "invalid PICO-8 surface parameters");
- game->error.set = true;
- native_raw_set_return(0);
- return;
- }
-
- // We need to allocate 60 bytes for the surface structure, 44 bytes for the
- // pixel format, and `PW_FB_SIZE` bytes for the pixel data.
- uint32_t surface;
- uint8_t *memory;
- {
- uint32_t size = 60 + 44 + PW_FB_SIZE;
- uint32_t margs[] = {size};
- if (!wasm_runtime_call_wasm(exec, game->malloc, 1, margs) || !margs[0]) {
- SDL_LogWarn(0, "failed to allocate surface");
- game->error.set = true;
- native_raw_set_return(0);
- return;
- }
-
- surface = margs[0];
- memory = emrt_memory(exec, surface, size);
- if (!memory) {
- SDL_LogWarn(0, "invalid surface allocation");
- game->error.set = true;
- native_raw_set_return(0);
- return;
- }
- }
-
- // surface
- {
- void *cursor = memory;
- emrt_write(&cursor, int32_t, flags);
- emrt_write(&cursor, uint32_t, surface + 60);
- emrt_write(&cursor, int32_t, w);
- emrt_write(&cursor, int32_t, h);
- emrt_write(&cursor, int32_t, (w * bpp) / 8);
- emrt_write(&cursor, uint32_t, surface + 60 + 44);
- emrt_write(&cursor, uint32_t, 0); // userdata
- emrt_write(&cursor, uint32_t, 0); // locked
- emrt_write(&cursor, uint32_t, 0); // lock_data
- emrt_write(&cursor, int32_t, 0); // clip_rect.x
- emrt_write(&cursor, int32_t, 0); // clip_rect.y
- emrt_write(&cursor, int32_t, w); // clip_rect.w
- emrt_write(&cursor, int32_t, h); // clip_rect.h
- emrt_write(&cursor, uint32_t, 0); // map
- emrt_write(&cursor, uint32_t, 1); // refcount
- };
- // pixel format
- {
- void *cursor = memory + 60;
- emrt_write(&cursor, uint32_t, EMRT_PIXELFORMAT_ABGR8888);
- emrt_write(&cursor, uint32_t, 0); // palette
- emrt_write(&cursor, int8_t, (int8_t)bpp);
- emrt_write(&cursor, int8_t, (int8_t)bpp / 8);
- emrt_write(&cursor, uint16_t, 0); // padding
- emrt_write(&cursor, uint32_t, 0x000000ff); // rmask
- emrt_write(&cursor, uint32_t, 0x0000ff00); // gmask
- emrt_write(&cursor, uint32_t, 0x00ff0000); // bmask
- emrt_write(&cursor, uint32_t, 0xff000000); // amask
- emrt_write(&cursor, uint8_t, 0); // rloss
- emrt_write(&cursor, uint8_t, 0); // gloss
- emrt_write(&cursor, uint8_t, 0); // bloss
- emrt_write(&cursor, uint8_t, 0); // aloss
- emrt_write(&cursor, uint8_t, 0); // rshift
- emrt_write(&cursor, uint8_t, 8); // gshift
- emrt_write(&cursor, uint8_t, 16); // bshift
- emrt_write(&cursor, uint8_t, 24); // ashift
- emrt_write(&cursor, int32_t, 1); // refcount
- emrt_write(&cursor, uint32_t, 0); // next
- }
- // pixels
- {
- void *cursor = memory + 60 + 44;
- SDL_memset(cursor, 0, PW_FB_SIZE);
- }
-
- native_raw_set_return(surface);
-}
-
-static void emrt_get_mouse_state(wasm_exec_env_t exec, uint64_t *args) {
- native_raw_return_type(int32_t, args);
- native_raw_get_arg(uint32_t, x, args);
- native_raw_get_arg(uint32_t, y, args);
-
- struct pw_game *game = wasm_runtime_get_user_data(exec);
-
- struct pw_coordinates pos;
- enum pw_mouse_button button = pw_input_mouse(game->input, &pos);
-
- if (x) {
- uint8_t *memory = emrt_memory(exec, x, sizeof(int32_t));
- if (memory) {
- emrt_write(&memory, int32_t, pos.x);
- }
- }
- if (y) {
- uint8_t *memory = emrt_memory(exec, y, sizeof(int32_t));
- if (memory) {
- emrt_write(&memory, int32_t, pos.y);
- }
- }
-
- native_raw_set_return(button);
-}
-
-static void emrt_lock_surface(wasm_exec_env_t exec, uint64_t *args) {
- native_raw_return_type(int32_t, args);
- native_raw_get_arg(uint32_t, surface, args);
-
- struct pw_game *game = wasm_runtime_get_user_data(exec);
-
- uint8_t *memory = emrt_memory(exec, surface, 60);
- if (!memory) {
- SDL_LogWarn(0, "invalid surface specified for locking");
- game->error.set = true;
- native_raw_set_return(-1);
- return;
- }
-
- {
- void *cursor = memory + 28;
- emrt_write(&cursor, uint32_t, 1); // locked
- };
-
- native_raw_set_return(0);
-}
-
-static void emrt_unlock_surface(wasm_exec_env_t exec, uint64_t *args) {
- native_raw_get_arg(uint32_t, surface, args);
-
- struct pw_game *game = wasm_runtime_get_user_data(exec);
-
- uint8_t *memory = emrt_memory(exec, surface, 60);
- if (!memory) {
- SDL_LogWarn(0, "invalid surface specified for locking");
- game->error.set = true;
- return;
- }
-
- // Always clear the locked flag as unlocking should never fail.
- {
- void *cursor = memory + 28;
- emrt_write(&cursor, uint32_t, 0); // locked
- };
-
- uint32_t pixels;
- SDL_memcpy(&pixels, memory + 20, sizeof(pixels));
-
- uint8_t *buffer = emrt_memory(exec, pixels, PW_FB_SIZE);
- if (!buffer) {
- SDL_LogWarn(0, "invalid surface pixel buffer");
- game->error.set = true;
- return;
- }
-
- if (!pw_fb_blit(game->fb, buffer)) {
- SDL_LogWarn(0, "failed to blit surface to framebuffer: %s", SDL_GetError());
- game->error.set = true;
- }
-}
-
-static uint32_t truncated_ticks() {
- return (uint32_t)(SDL_GetTicks() & 0xffffffff);
-}
-
-static void emrt_get_ticks(wasm_exec_env_t exec, uint64_t *args) {
- (void)exec;
- native_raw_return_type(uint32_t, args);
- native_raw_set_return(truncated_ticks());
-}
-
-static void emrt_get_error(wasm_exec_env_t exec, uint64_t *args) {
- native_raw_return_type(uint32_t, args);
-
- struct pw_game *game = wasm_runtime_get_user_data(exec);
-
- uint32_t error = game->error.ptr;
- if (!game->error.set) {
- // Just point to the `\0` at the end of the error message, this avoids
- // requiring a separate allocation for the cleared error.
- error = game->error.ptr;
- }
-
- native_raw_set_return(error);
-}
-
-static void emrt_clear_error(wasm_exec_env_t exec, uint64_t *args) {
- (void)args;
- struct pw_game *game = wasm_runtime_get_user_data(exec);
- game->error.set = false;
-}
-
-#define EMRT_KEYDOWN 0x300
-#define EMRT_KEYUP 0x301
-#define EMRT_MOUSEMOTION 0x400
-
-static void emrt_poll_event(wasm_exec_env_t exec, uint64_t *args) {
- native_raw_return_type(int32_t, args);
- native_raw_get_arg(uint32_t, event, args);
-
- struct pw_game *game = wasm_runtime_get_user_data(exec);
-
- bool remaining;
- union pw_input_event input;
- if (event) {
- remaining = pw_input_poll(game->input, &input);
- } else {
- remaining = pw_input_poll(game->input, NULL);
- goto exit;
- }
-
- uint8_t *memory = emrt_memory(exec, event, 36);
- if (!memory) {
- SDL_LogWarn(0, "invalid event address for polling");
- game->error.set = true;
- goto exit;
- }
-
- if (remaining) {
- void *cursor = memory;
-
- switch (input.type) {
- case PW_INPUT_EVENT_KEY:
- if (input.key.pressed) {
- emrt_write(&cursor, uint32_t, EMRT_KEYDOWN);
- } else {
- emrt_write(&cursor, uint32_t, EMRT_KEYUP);
- }
- emrt_write(&cursor, uint32_t, 1); // windowID
- emrt_write(&cursor, uint8_t, (uint8_t)input.key.pressed);
- emrt_write(&cursor, uint8_t, (uint8_t)input.key.repeat);
- emrt_write(&cursor, uint8_t, 0); // padding2
- emrt_write(&cursor, uint8_t, 0); // padding3
- emrt_write(&cursor, uint32_t, input.key.scancode);
- emrt_write(&cursor, int32_t, input.key.keycode);
- emrt_write(&cursor, uint16_t, (uint16_t)input.key.mod);
- emrt_write(&cursor, uint16_t, 0); // keysym.(padding)
- emrt_write(&cursor, uint32_t, 0); // keysym.unicode (deprecated)
- break;
- case PW_INPUT_EVENT_MOUSE:
- emrt_write(&cursor, uint32_t, EMRT_MOUSEMOTION);
- emrt_write(&cursor, uint32_t, truncated_ticks());
- emrt_write(&cursor, uint32_t, 1); // windowID
- emrt_write(&cursor, uint32_t, 1); // which
- emrt_write(&cursor, uint32_t, (uint32_t)input.mouse.button);
- emrt_write(&cursor, int32_t, input.mouse.x);
- emrt_write(&cursor, int32_t, input.mouse.y);
- emrt_write(&cursor, int32_t, input.mouse.xrel);
- emrt_write(&cursor, int32_t, input.mouse.yrel);
- break;
- };
- };
-
-exit:
- native_raw_set_return((int32_t)remaining);
-}
-
-struct pw_game *pw_game_init(SDL_Renderer *renderer, enum pw_scale_mode mode) {
+struct pw_game *pw_game_init(SDL_Renderer *renderer, enum pw_scale_mode mode,
+ size_t memory) {
if (!renderer) {
SDL_InvalidParamError("renderer");
return NULL;
}
- bool wasm_init = false;
- struct pw_game *game = SDL_malloc(sizeof(*game));
+ struct pw_game *game = SDL_calloc(1, sizeof(*game));
if (!game) {
return NULL;
}
- SDL_zerop(game);
+
+ game->env = pw_env_init(memory);
+ if (!game->env) {
+ goto error;
+ }
game->fb = pw_fb_init(renderer, mode);
if (!game->fb) {
@@ -344,67 +30,19 @@ struct pw_game *pw_game_init(SDL_Renderer *renderer, enum pw_scale_mode mode) {
goto error;
}
- struct RuntimeInitArgs init = {
- .mem_alloc_type = Alloc_With_Allocator,
- .mem_alloc_option.allocator.malloc_func = (void *)wasm_malloc,
- .mem_alloc_option.allocator.realloc_func = (void *)wasm_realloc,
- .mem_alloc_option.allocator.free_func = (void *)wasm_free,
- };
- if (!wasm_runtime_full_init(&init)) {
- SDL_SetError("unspecified error initializing WebAssembly runtime");
- goto error;
- }
- wasm_init = true;
-
- struct NativeSymbol env[] = {
- {"_emscripten_set_main_loop", emrt_set_main_loop, "(iii)", NULL},
- {"_SDL_ClearError", emrt_clear_error, "()", NULL},
- {"_SDL_GetError", emrt_get_error, "()i", NULL},
- {"_SDL_GetMouseState", emrt_get_mouse_state, "(ii)i", NULL},
- {"_SDL_GetTicks", emrt_get_ticks, "()i", NULL},
- {"_SDL_LockSurface", emrt_lock_surface, "(i)i", NULL},
- {"_SDL_PollEvent", emrt_poll_event, "(i)i", NULL},
- {"_SDL_SetVideoMode", emrt_set_video_mode, "(iiii)i", NULL},
- {"_SDL_UnlockSurface", emrt_unlock_surface, "(i)", NULL},
- };
- if (!wasm_runtime_register_natives_raw("env", env, SDL_arraysize(env))) {
- SDL_SetError("unspecified error registering host functions");
- goto error;
- }
-
- char err[1024];
- game->module = wasm_runtime_load(stub_pico8_wasm.data, stub_pico8_wasm.size,
- err, sizeof err);
- if (game->module == NULL) {
- SDL_SetError("%s", err);
- goto error;
- }
-
- struct NativeGlobal genv[] = {
- {"NaN", {WASM_F64, .of.f64 = NAN}},
- {"Infinity", {WASM_F64, .of.f64 = INFINITY}},
- };
- if (!wasm_runtime_link_globals(game->module, "global", genv,
- SDL_arraysize(genv))) {
- SDL_SetError("unspecified error registiering host globals");
- goto error;
- }
-
return game;
error:
+ if (game->env) {
+ pw_env_free(game->env);
+ }
if (game->fb) {
pw_fb_free(game->fb);
}
if (game->input) {
pw_input_free(game->input);
}
- if (game->module) {
- wasm_runtime_unload(game->module);
- }
- if (wasm_init) {
- wasm_runtime_destroy();
- }
+
SDL_free(game);
return NULL;
}
@@ -415,157 +53,58 @@ void pw_game_free(struct pw_game *game) {
return;
}
- if (game->exec) {
- wasm_runtime_destroy_exec_env(game->exec);
- }
- if (game->instance) {
- wasm_runtime_deinstantiate(game->instance);
- }
- wasm_runtime_unload(game->module);
- wasm_runtime_destroy();
-
- if (game->cart) {
- pw_multicart_free(game->cart);
- }
pw_input_free(game->input);
pw_fb_free(game->fb);
+ pw_env_free(game->env);
SDL_free(game);
}
-bool pw_game_start(struct pw_game *game, struct pw_multicart *cart) {
+bool pw_game_start(struct pw_game *game, struct pw_multicart *carts) {
if (!game) {
SDL_InvalidParamError("game");
return false;
}
- if (!cart) {
- SDL_InvalidParamError("cart");
+ if (!carts) {
+ SDL_InvalidParamError("carts");
return false;
}
- if (game->cart) {
- pw_multicart_free(game->cart);
- }
- game->cart = cart;
-
- if (game->exec) {
- wasm_runtime_destroy_exec_env(game->exec);
- }
- if (game->instance) {
- wasm_runtime_deinstantiate(game->instance);
- }
- game->instance = NULL;
- game->exec = NULL;
- game->malloc = NULL;
- game->dyncall = NULL;
- game->mix = NULL;
-
- char err[1024];
- game->instance =
- wasm_runtime_instantiate(game->module, 1024, 0, err, sizeof err);
- if (!game->instance) {
- return SDL_SetError("%s", err);
- }
-
- wasm_function_inst_t ctor = wasm_runtime_lookup_function(
- game->instance, "___emscripten_environ_constructor");
- wasm_function_inst_t start =
- wasm_runtime_lookup_function(game->instance, "_main");
- wasm_function_inst_t stackalloc =
- wasm_runtime_lookup_function(game->instance, "stackAlloc");
- wasm_function_inst_t malloc =
- wasm_runtime_lookup_function(game->instance, "_malloc");
- wasm_function_inst_t dyncall =
- wasm_runtime_lookup_function(game->instance, "dynCall_v");
- wasm_function_inst_t mix =
- wasm_runtime_lookup_function(game->instance, "_mix_0");
- if (!ctor || !start || !stackalloc || !malloc || !dyncall || !mix) {
- return SDL_SetError("could not find required exports");
- }
-
- game->exec = wasm_runtime_create_exec_env(game->instance, 1024);
- if (game->exec == NULL) {
- return SDL_SetError("failed to create execution environment");
- }
- wasm_runtime_set_user_data(game->exec, game);
-
- game->malloc = malloc;
- game->dyncall = dyncall;
- game->mix = mix;
- if (!wasm_runtime_call_wasm(game->exec, ctor, 0, NULL)) {
- return SDL_SetError("error calling constructor: %s",
- wasm_runtime_get_exception(game->instance));
+ if (game->carts) {
+ pw_multicart_free(game->carts);
}
+ game->carts = carts;
- uint32_t arg0;
- {
- char const value[] = "./pico8";
- uint32_t args[] = {(uint32_t)sizeof(value)};
- if (!wasm_runtime_call_wasm(game->exec, stackalloc, 1, args)) {
- return SDL_SetError("error allocating argument 0: %s",
- wasm_runtime_get_exception(game->instance));
- }
-
- arg0 = args[0];
- char *target = emrt_memory(game->exec, arg0, sizeof(value));
- if (!target) {
- return SDL_SetError("invalid argument 0 address");
- }
-
- SDL_memcpy(target, value, sizeof(value));
- }
-
- {
- char const value[] = "unspecified error";
- uint32_t args[] = {(uint32_t)sizeof(value)};
- if (!wasm_runtime_call_wasm(game->exec, malloc, 1, args)) {
- return SDL_SetError("error allocating SDL error string: %s",
- wasm_runtime_get_exception(game->instance));
- }
-
- game->error.ptr = args[0];
- game->error.len = sizeof(value) - 1;
- char *target = emrt_memory(game->exec, game->error.ptr, game->error.len);
- if (!target) {
- return SDL_SetError("invalid SDL error string address");
- }
-
- SDL_memcpy(target, value, sizeof(value));
- }
+ pw_env_link(game->env, (struct pw_env_ctx){
+ .fb = game->fb,
+ .input = game->input,
+ .carts = game->carts,
+ .instance = &game->instance,
+ });
+ wasm2c_pico8_instantiate(&game->instance, game->env);
uint32_t argv;
{
- uint32_t const value[] = {arg0, 0};
- uint32_t args[] = {(uint32_t)sizeof(value)};
- if (!wasm_runtime_call_wasm(game->exec, stackalloc, 1, args)) {
- return SDL_SetError("error allocating arguments array: %s",
- wasm_runtime_get_exception(game->instance));
+ char const value[] = "./pico8";
+ uint32_t arg0 = w2c_pico8_stackAlloc(&game->instance, sizeof(value));
+ if (!arg0) {
+ return SDL_OutOfMemory();
}
- argv = args[0];
- char *target = emrt_memory(game->exec, argv, sizeof(value));
- if (!target) {
- return SDL_SetError("invalid arguments array address");
+ wasm_rt_memory_store(&game->env->memory, value, arg0, sizeof(value));
+ argv = w2c_pico8_stackAlloc(&game->instance, 2 * sizeof(arg0));
+ if (!argv) {
+ return SDL_OutOfMemory();
}
- SDL_memcpy(target, value, sizeof(value));
+ wasm_rt_memory_store32(&game->env->memory, argv, arg0);
+ wasm_rt_memory_store32(&game->env->memory, argv + 4, 0);
}
- game->mainfn = 0;
- {
- uint32_t args[] = {1, argv};
- if (!wasm_runtime_call_wasm(game->exec, start, 2, args)) {
- return SDL_SetError("error calling main: %s",
- wasm_runtime_get_exception(game->instance));
- }
- if (args[0]) {
- return SDL_SetError("main returned exit code");
- }
- }
- if (!game->mainfn) {
- return SDL_SetError("main loop function not set");
+ if (w2c_pico8_0x5Fmain(&game->instance, 1, argv)) {
+ return SDL_SetError("main returned exit code");
}
- return true;
+ return game->env->main_loop;
}
bool pw_game_event(struct pw_game *game, struct pw_players *players,
@@ -579,7 +118,7 @@ bool pw_game_event(struct pw_game *game, struct pw_players *players,
}
bool pw_game_iterate(struct pw_game *game) {
- if (!game || !game->exec || !game->dyncall || !game->mix) {
+ if (!game) {
SDL_InvalidParamError("game");
return false;
}
@@ -587,23 +126,8 @@ bool pw_game_iterate(struct pw_game *game) {
pw_fb_iterate(game->fb);
pw_input_iterate(game->input, game->fb);
- {
- uint32_t args[] = {game->mainfn};
- if (!wasm_runtime_call_wasm(game->exec, game->dyncall, 1, args)) {
- return SDL_SetError("error calling main loop function: %s",
- wasm_runtime_get_exception(game->instance));
- }
- }
- {
- uint32_t args[] = {42, 1337};
- if (!wasm_runtime_call_wasm(game->exec, game->mix, 2, args)) {
- return SDL_SetError("error calling audio mixer: %s",
- wasm_runtime_get_exception(game->instance));
- }
- if (!args[0]) {
- return SDL_SetError("audio mixing failed");
- }
- }
+ w2c_pico8_dynCall_v(&game->instance, game->env->main_loop);
+ w2c_pico8_0x5Fmix_0(&game->instance, 42, 1337);
return true;
}
diff --git a/src/game.h b/src/game.h
index 2ad449d..21f931e 100644
--- a/src/game.h
+++ b/src/game.h
@@ -4,11 +4,11 @@
#include <SDL3/SDL_events.h>
#include <SDL3/SDL_render.h>
-#include <wamr/wamr.h>
-
#include "cart.h"
+#include "env.h"
#include "fb.h"
#include "input.h"
+#include "pico8.h"
#include "player.h"
#include "scale.h"
@@ -16,27 +16,18 @@
* Executing PICO-8 game state.
*/
struct pw_game {
+ struct w2c_pico8 instance;
+ struct w2c_env *env;
struct pw_framebuffer *fb;
struct pw_input *input;
- struct pw_multicart *cart;
- wasm_module_t module;
- wasm_module_inst_t instance;
- wasm_exec_env_t exec;
- wasm_function_inst_t malloc;
- wasm_function_inst_t dyncall;
- wasm_function_inst_t mix;
- int32_t mainfn;
- struct {
- bool set;
- uint32_t ptr;
- uint32_t len;
- } error;
+ struct pw_multicart *carts;
};
/**
* Allocates and initializes the game state.
*/
-struct pw_game *pw_game_init(SDL_Renderer *renderer, enum pw_scale_mode mode);
+struct pw_game *pw_game_init(SDL_Renderer *renderer, enum pw_scale_mode mode,
+ size_t memory);
/**
* Frees the game state.
@@ -46,7 +37,7 @@ void pw_game_free(struct pw_game *game);
/**
* Starts a PICO-8 game.
*/
-bool pw_game_start(struct pw_game *game, struct pw_multicart *cart);
+bool pw_game_start(struct pw_game *game, struct pw_multicart *carts);
/**
* Handles SDL events for game state.
diff --git a/src/picow.c b/src/picow.c
index 62d829b..32e54b4 100644
--- a/src/picow.c
+++ b/src/picow.c
@@ -106,7 +106,7 @@ SDL_AppResult SDL_AppInit(void **appstate, int argc, char **argv) {
return failf("failed to initialize cart selection state");
}
- state->game = pw_game_init(state->renderer, state->config->mode);
+ state->game = pw_game_init(state->renderer, state->config->mode, state->config->memory);
if (!state->game) {
return failf("failed to initialize PICO-8 game state");
}
diff --git a/src/wasmrt.c b/src/wasmrt.c
new file mode 100644
index 0000000..23e0c16
--- /dev/null
+++ b/src/wasmrt.c
@@ -0,0 +1,142 @@
+#include <stdlib.h>
+
+#include <SDL3/SDL_endian.h>
+#include <SDL3/SDL_log.h>
+#include <SDL3/SDL_stdinc.h>
+
+#include "wasmrt.h"
+
+bool wasm_rt_is_initialized(void) {
+ // Our simplified Web Assembly runtime does not require initialization, so
+ // just always return `true`.
+ return true;
+}
+
+void wasm_rt_trap(enum wasm_rt_trap_t trap) {
+ (void)trap;
+ SDL_LogCritical(0, "trap!\n");
+ abort();
+}
+
+void wasm_rt_memory_check(struct wasm_rt_memory_t const *mem, uint32_t addr,
+ uint32_t len) {
+ uint32_t end = addr + len;
+ if (UNLIKELY(!addr || end < addr || end >= mem->size)) {
+ wasm_rt_trap(WASM_RT_TRAP_OOB);
+ }
+}
+
+// For Wasm memory operations - `wasm2c` generates code on big-endian systems
+// where the memory is mirrored, this makes it so that storing integers is
+// just a `memcpy` without swapping byte order, but it means that we need to
+// store and load bytes backwards, and compute offsets from the end of the
+// allocated memory segment.
+
+void wasm_rt_memory_load(struct wasm_rt_memory_t const *mem, void *dst,
+ uint32_t addr, uint32_t len) {
+ wasm_rt_memory_check(mem, addr, len);
+ wasm_rt_memory_load_unchecked(mem, dst, addr, len);
+}
+
+void wasm_rt_memory_load_unchecked(struct wasm_rt_memory_t const *mem,
+ void *dst, uint32_t addr, uint32_t len) {
+#if SDL_BYTEORDER == SDL_LIL_ENDIAN
+ SDL_memcpy(dst, mem->data + addr, len);
+#else
+ uint8_t *bytes = dst;
+ for (uint32_t i = 0; i < len; i++) {
+ bytes[i] = mem->data[mem->size - addr - i - 1];
+ }
+#endif
+}
+
+uint32_t wasm_rt_memory_load32(struct wasm_rt_memory_t const *mem,
+ uint32_t addr) {
+ wasm_rt_memory_check(mem, addr, sizeof(uint32_t));
+ return wasm_rt_memory_load32_unchecked(mem, addr);
+}
+
+uint32_t wasm_rt_memory_load32_unchecked(struct wasm_rt_memory_t const *mem,
+ uint32_t addr) {
+ uint32_t value;
+#if SDL_BYTEORDER == SDL_LIL_ENDIAN
+ SDL_memcpy(&value, mem->data + addr, sizeof(value));
+#else
+ SDL_memcpy(&value, mem->data_end - addr - sizeof(value), sizeof(value));
+#endif
+ return value;
+}
+
+void wasm_rt_memory_store(struct wasm_rt_memory_t *mem, void const *src,
+ uint32_t addr, uint32_t len) {
+ wasm_rt_memory_check(mem, addr, len);
+ wasm_rt_memory_store_unchecked(mem, src, addr, len);
+}
+
+void wasm_rt_memory_store_unchecked(struct wasm_rt_memory_t *mem,
+ void const *src, uint32_t addr,
+ uint32_t len) {
+#if SDL_BYTEORDER == SDL_LIL_ENDIAN
+ SDL_memcpy(mem->data + addr, src, len);
+#else
+ uint8_t const *bytes = src;
+ for (uint32_t i = 0; i < len; i++) {
+ mem->data[mem->size - addr - i - 1] = bytes[i];
+ }
+#endif
+}
+
+void wasm_rt_memory_store8(struct wasm_rt_memory_t *mem, uint32_t addr,
+ uint8_t value) {
+ wasm_rt_memory_check(mem, addr, sizeof(uint8_t));
+ wasm_rt_memory_store8_unchecked(mem, addr, value);
+}
+
+void wasm_rt_memory_store8_unchecked(struct wasm_rt_memory_t *mem,
+ uint32_t addr, uint8_t value) {
+#if SDL_BYTEORDER == SDL_LIL_ENDIAN
+ mem->data[addr] = value;
+#else
+ mem->data[size - addr - sizeof(value)] = value;
+#endif
+}
+
+void wasm_rt_memory_store16(struct wasm_rt_memory_t *mem, uint32_t addr,
+ uint16_t value) {
+ wasm_rt_memory_check(mem, addr, sizeof(uint16_t));
+ wasm_rt_memory_store16_unchecked(mem, addr, value);
+}
+
+void wasm_rt_memory_store16_unchecked(struct wasm_rt_memory_t *mem,
+ uint32_t addr, uint16_t value) {
+#if SDL_BYTEORDER == SDL_LIL_ENDIAN
+ SDL_memcpy(mem->data + addr, &value, sizeof(value));
+#else
+ SDL_memcpy(mem->data_end - addr - sizeof(value), &value, sizeof(value));
+#endif
+}
+
+void wasm_rt_memory_store32(struct wasm_rt_memory_t *mem, uint32_t addr,
+ uint32_t value) {
+ wasm_rt_memory_check(mem, addr, sizeof(uint32_t));
+ wasm_rt_memory_store16_unchecked(mem, addr, value);
+}
+
+void wasm_rt_memory_store32_unchecked(struct wasm_rt_memory_t *mem,
+ uint32_t addr, uint32_t value) {
+#if SDL_BYTEORDER == SDL_LIL_ENDIAN
+ SDL_memcpy(mem->data + addr, &value, sizeof(value));
+#else
+ SDL_memcpy(mem->data_end - addr - sizeof(value), &value, sizeof(value));
+#endif
+}
+
+void wasm_rt_memory_set(struct wasm_rt_memory_t *mem, uint32_t addr,
+ uint32_t len, uint8_t value) {
+ wasm_rt_memory_check(mem, addr, len);
+#if SDL_BYTEORDER == SDL_LIL_ENDIAN
+ SDL_memset(mem->data + addr, value, len);
+#else
+ SDL_memset(mem->data_end - addr - len, value, len);
+#endif
+}
diff --git a/src/wasmrt.h b/src/wasmrt.h
new file mode 100644
index 0000000..85cc6ca
--- /dev/null
+++ b/src/wasmrt.h
@@ -0,0 +1,233 @@
+#ifndef PW_WASMRT_H
+#define PW_WASMRT_H
+
+#include <SDL3/SDL_stdinc.h>
+
+#if SDL_HAS_BUILTIN(__builtin_expect)
+#define LIKELY(x) __builtin_expect(!!(x), 1)
+#define UNLIKELY(x) __builtin_expect(!!(x), 0)
+#else
+#define LIKELY(x) (x)
+#define UNLIKELY(x) (x)
+#endif
+#define WASM_RT_NO_RETURN SDL_NORETURN
+
+/**
+ * Use a simple and static configuration for the Web Assembly runtime required
+ * by `wasm2c` instead of using the one provided by `wabt`. This allows us a
+ * few things:
+ *
+ * - Use the same configuration everywhere, and not just enable extra features
+ * on better supported targets (like `amd64`).
+ * - Allows us to back the implementation on SDL3 instead of the standard
+ * library for more consistent behaviour.
+ *
+ * Besides, no platforms with these extra features supported, you are probably
+ * better off using PICO-8 directly anyway.
+ */
+
+#define WASM_RT_MEMCHECK_GUARD_PAGES 0
+#define WASM_RT_MEMCHECK_BOUNDS_CHECK 1
+#define WASM_RT_STACK_DEPTH_COUNT 0
+#define WASM_RT_USE_SEGUE 0
+
+#if SDL_BYTEORDER == SDL_LIL_ENDIAN
+#define WABT_BIG_ENDIAN 0
+#else
+#define WABT_BIG_ENDIAN 1
+#endif
+
+/**
+ * A Web Assembly trap, only the ones used by the PICO-8 `.wasm` export.
+ */
+typedef enum wasm_rt_trap_t {
+ WASM_RT_TRAP_NONE,
+ WASM_RT_TRAP_OOB,
+ WASM_RT_TRAP_INT_OVERFLOW,
+ WASM_RT_TRAP_DIV_BY_ZERO,
+ WASM_RT_TRAP_INVALID_CONVERSION,
+ WASM_RT_TRAP_UNREACHABLE,
+ WASM_RT_TRAP_CALL_INDIRECT,
+} wasm_rt_trap_t;
+
+/**
+ * Web Assembly value types.
+ */
+typedef enum wasm_rt_type_t {
+ WASM_RT_I32,
+ WASM_RT_I64,
+ WASM_RT_F32,
+ WASM_RT_F64,
+} wasm_rt_type_t;
+
+/**
+ * A function pointer.
+ */
+typedef void (*wasm_rt_function_ptr_t)(void);
+
+/**
+ * Tail-call entry points, stubbed as PICO-8 was built without Web Assembly
+ * tail-call support.
+ */
+typedef struct wasm_rt_tailcallee_t {
+ void *_unused;
+} wasm_rt_tailcallee_t;
+
+/**
+ * A function type: a 32-byte signature hash.
+ */
+typedef const char *wasm_rt_func_type_t;
+
+/**
+ * A Web Assembly function reference.
+ */
+typedef struct wasm_rt_funcref_t {
+ wasm_rt_func_type_t func_type;
+ wasm_rt_function_ptr_t func;
+ wasm_rt_tailcallee_t func_tailcallee;
+ void *module_instance;
+} wasm_rt_funcref_t;
+
+/**
+ * A null-function reference.
+ */
+extern struct wasm_rt_funcref_t wasm_rt_funcref_null_value;
+
+/**
+ * A Web Assembly external reference.
+ */
+typedef struct wasm_rt_externref_t {
+ void *_unused;
+} wasm_rt_externref_t;
+
+/**
+ * A null-external reference.
+ */
+extern struct wasm_rt_externref_t wasm_rt_externref_null_value;
+
+/**
+ * Linear Web Assembly memory.
+ */
+typedef struct wasm_rt_memory_t {
+ uint8_t *data;
+ uint8_t *data_end;
+ uint64_t size;
+} wasm_rt_memory_t;
+
+/**
+ * A function reference table.
+ */
+typedef struct wasm_rt_funcref_table_t {
+ wasm_rt_funcref_t *data;
+ uint32_t size;
+} wasm_rt_funcref_table_t;
+
+/**
+ * An external reference table.
+ */
+typedef struct wasm_rt_externref_table_t {
+ wasm_rt_externref_t *data;
+ uint32_t size;
+} wasm_rt_externref_table_t;
+
+/**
+ * Returns whether Web Assembly runtime is initialized.
+ */
+bool wasm_rt_is_initialized(void);
+
+/**
+ * IT'S A TRAP!
+ */
+WASM_RT_NO_RETURN void wasm_rt_trap(wasm_rt_trap_t code);
+
+#define wasm_rt_memcpy SDL_memcpy
+#define wasm_rt_funcref_null_value \
+ ((wasm_rt_funcref_t){NULL, NULL, {NULL}, NULL})
+#define wasm_rt_externref_null_value ((wasm_rt_externref_t){NULL})
+
+/**
+ * Checks whether or not memory `[addr, addr+len)` is a valid memory region.
+ */
+void wasm_rt_memory_check(struct wasm_rt_memory_t const *mem, uint32_t addr,
+ uint32_t len);
+
+/**
+ * Loads bytes from memory.
+ */
+void wasm_rt_memory_load(struct wasm_rt_memory_t const *mem, void *dst,
+ uint32_t addr, uint32_t len);
+
+/**
+ * Loads bytes from memory without bounds checking.
+ */
+void wasm_rt_memory_load_unchecked(struct wasm_rt_memory_t const *mem,
+ void *dst, uint32_t addr, uint32_t len);
+
+/**
+ * Loads a 32-bit word from memory.
+ */
+uint32_t wasm_rt_memory_load32(struct wasm_rt_memory_t const *mem,
+ uint32_t addr);
+
+/**
+ * Loads a 32-bit word from memory without bounds checks.
+ */
+uint32_t wasm_rt_memory_load32_unchecked(struct wasm_rt_memory_t const *mem,
+ uint32_t addr);
+
+/**
+ * Stores bytes to memory.
+ */
+void wasm_rt_memory_store(struct wasm_rt_memory_t *mem, void const *src,
+ uint32_t addr, uint32_t len);
+
+/**
+ * Stores bytes to memory without bounds checking.
+ */
+void wasm_rt_memory_store_unchecked(struct wasm_rt_memory_t *mem,
+ void const *src, uint32_t addr,
+ uint32_t len);
+
+/**
+ * Stores a 32-bit word to memory.
+ */
+void wasm_rt_memory_store8(struct wasm_rt_memory_t *mem, uint32_t addr,
+ uint8_t value);
+
+/**
+ * Loads a 32-bit word from memory without bounds checks.
+ */
+void wasm_rt_memory_store8_unchecked(struct wasm_rt_memory_t *mem,
+ uint32_t addr, uint8_t value);
+
+/**
+ * Stores a 32-bit word to memory.
+ */
+void wasm_rt_memory_store16(struct wasm_rt_memory_t *mem, uint32_t addr,
+ uint16_t value);
+
+/**
+ * Loads a 32-bit word from memory without bounds checks.
+ */
+void wasm_rt_memory_store16_unchecked(struct wasm_rt_memory_t *mem,
+ uint32_t addr, uint16_t value);
+
+/**
+ * Stores a 32-bit word to memory.
+ */
+void wasm_rt_memory_store32(struct wasm_rt_memory_t *mem, uint32_t addr,
+ uint32_t value);
+
+/**
+ * Loads a 32-bit word from memory without bounds checks.
+ */
+void wasm_rt_memory_store32_unchecked(struct wasm_rt_memory_t *mem,
+ uint32_t addr, uint32_t value);
+
+/**
+ * Sets all bytes in a memory range to a value.
+ */
+void wasm_rt_memory_set(struct wasm_rt_memory_t *mem, uint32_t addr,
+ uint32_t len, uint8_t value);
+
+#endif
diff --git a/tools/generate-sysroot.c b/tools/generate-sysroot.c
index 3663144..ff81b2c 100644
--- a/tools/generate-sysroot.c
+++ b/tools/generate-sysroot.c
@@ -122,8 +122,6 @@ int main(int argc, char *argv[argc + 1]) {
char const *file;
} entries[] = {
{"pico8_data_pod", "pico8.data.pod"},
- {"pico8_wasm", "pico8.wasm"},
- {"stub_pico8_wasm", "stub/pico8.wasm"},
{"unknown_p8_png", "unknown.p8.png"},
{"font_png", "font.png"},
};