diff options
| author | Nicholas Rodrigues Lordello <[email protected]> | 2026-10-10 00:16:57 +0200 |
|---|---|---|
| committer | Nicholas Rodrigues Lordello <[email protected]> | 2026-10-10 00:16:57 +0200 |
| commit | 70d2db07ec4dd5034c6d888258a3fd945c67e4d4 (patch) | |
| tree | 9f0e4d22d1b5fecb0a5cfaf3554c673a8a655dcc /src | |
| parent | 0a98b48593e4ad561c7732387a688797ad5ee1ce (diff) | |
Separate Scene Logic
We now have two separate "scenes":
- cart selection
- game
In their own modules. Instead of implementing some scene management
logic, we just hardcode the scene logic directly in the `picow`
main module - I don't forsee more scenes and there is no need to
over-engineer at this point.
Diffstat (limited to 'src')
| -rw-r--r-- | src/cart.c | 114 | ||||
| -rw-r--r-- | src/cart.h | 32 | ||||
| -rw-r--r-- | src/fb.c | 16 | ||||
| -rw-r--r-- | src/fb.h | 7 | ||||
| -rw-r--r-- | src/game.c | 293 | ||||
| -rw-r--r-- | src/game.h | 58 | ||||
| -rw-r--r-- | src/input.c | 1 | ||||
| -rw-r--r-- | src/input.h | 2 | ||||
| -rw-r--r-- | src/menu.c | 232 | ||||
| -rw-r--r-- | src/menu.h | 43 | ||||
| -rw-r--r-- | src/picow.c | 467 | ||||
| -rw-r--r-- | src/player.h | 2 |
12 files changed, 808 insertions, 459 deletions
@@ -1,5 +1,4 @@ #include <SDL3/SDL_filesystem.h> -#include <SDL3/SDL_surface.h> #include "cart.h" #include "path.h" @@ -255,17 +254,22 @@ error: return NULL; } -bool pw_cart_load(struct pw_cart_entry *entry, struct pw_cart *cart) { - if (!entry) { - SDL_InvalidParamError("entry"); - return false; - } +void pw_cart_free(struct pw_cart *cart) { if (!cart) { SDL_InvalidParamError("cart"); - return false; + return; } - SDL_IOStream *png = SDL_IOFromFile(entry->file.path, "rb"); + if (cart->png) { + SDL_DestroyTexture(cart->png); + } + SDL_free(cart); +} + +static bool load_cart_png(char const *path, SDL_Texture *texture, + uint8_t rom[PW_ROM_SIZE]) { + + SDL_IOStream *png = SDL_IOFromFile(path, "rb"); if (!png) { return false; } @@ -299,15 +303,15 @@ bool pw_cart_load(struct pw_cart_entry *entry, struct pw_cart *cart) { goto cleanup; } - if (!blit_image(image, cart->png)) { + if (texture && !blit_image(image, texture)) { goto cleanup; } // Read steganographically encoded cart ROM. - for (size_t i = 0; i < sizeof cart->rom; i++) { + for (size_t i = 0; i < PW_ROM_SIZE; i++) { union png_pixel px = image[i]; px.raw &= 0x03030303; - cart->rom[i] = (px.ch.a << 6) | (px.ch.r << 4) | (px.ch.g << 2) | px.ch.b; + rom[i] = (px.ch.a << 6) | (px.ch.r << 4) | (px.ch.g << 2) | px.ch.b; } result = true; @@ -323,18 +327,77 @@ cleanup: return result; } +bool pw_cart_load(struct pw_cart_entry *entry, struct pw_cart *cart) { + if (!entry) { + SDL_InvalidParamError("entry"); + return false; + } + if (!cart) { + SDL_InvalidParamError("cart"); + return false; + } + + return load_cart_png(entry->file.path, cart->png, cart->rom); +} + static int cmp_cart_name(void const *a, void const *b) { char const *name = a; struct pw_cart_file const *file = b; return SDL_strcmp(name, file->name); } -bool pw_cart_multi_load(struct pw_cart_entry *entry, struct pw_cart *cart, - char const *name) { +struct pw_multicart *pw_multicart_init(struct pw_cart_entry *entry, + struct pw_cart *cart) { if (!entry) { - SDL_InvalidParamError("entry"); + SDL_InvalidParamError("cart"); return false; } + + struct pw_multicart *multi = SDL_malloc(sizeof(*multi)); + if (!multi) { + return NULL; + } + + struct pw_cart_entry *dst = &multi->entry; + if (entry->nmulti) { + dst->multi = SDL_malloc(entry->nmulti * sizeof(struct pw_cart_file)); + if (!dst->multi) { + goto error; + } + + for (size_t i = 0; i < entry->nmulti; ++i) { + SDL_memcpy(&dst->multi[i], &entry->multi[i], sizeof(struct pw_cart_file)); + } + } + SDL_memcpy(&dst->file, &entry->file, sizeof(struct pw_cart_file)); + dst->nmulti = entry->nmulti; + + if (cart) { + SDL_memcpy(multi->rom, cart->rom, PW_ROM_SIZE); + } else if (!load_cart_png(entry->file.path, NULL, multi->rom)) { + goto error; + } + + return multi; + +error: + pw_multicart_free(multi); + return NULL; +} + +void pw_multicart_free(struct pw_multicart *cart) { + if (!cart) { + SDL_InvalidParamError("cart"); + return; + } + + if (cart->entry.multi) { + SDL_free(cart->entry.multi); + } + SDL_free(cart); +} + +bool pw_multicart_load(struct pw_multicart *cart, char const *name) { if (!cart) { SDL_InvalidParamError("cart"); return false; @@ -369,14 +432,14 @@ bool pw_cart_multi_load(struct pw_cart_entry *entry, struct pw_cart *cart, // Check if we are loading the main cart. If so, fall back to loading the // main cart PNG. - if (!SDL_strcmp(entry->file.name, sanitized_name)) { - return pw_cart_load(entry, cart); + if (!SDL_strcmp(cart->entry.file.name, sanitized_name)) { + return load_cart_png(cart->entry.file.path, NULL, cart->rom); } // Find the multi-cart by name. struct pw_cart_file *file = - SDL_bsearch(sanitized_name, entry->multi, entry->nmulti, - sizeof(*entry->multi), cmp_cart_name); + SDL_bsearch(sanitized_name, cart->entry.multi, cart->entry.nmulti, + sizeof(*cart->entry.multi), cmp_cart_name); if (!file) { return false; } @@ -407,18 +470,3 @@ cleanup: result &= SDL_CloseIO(rom); return result; } - -/** - * Frees a cart and all of its resources. - */ -void pw_cart_free(struct pw_cart *cart) { - if (!cart) { - SDL_InvalidParamError("cart"); - return; - } - - if (cart->png) { - SDL_DestroyTexture(cart->png); - } - SDL_free(cart); -} @@ -58,6 +58,14 @@ struct pw_cart { }; /** + * A selected multi-cart group for running in PICO-8. + */ +struct pw_multicart { + struct pw_cart_entry entry; + uint8_t rom[PW_ROM_SIZE]; +}; + +/** * List all carts in the `dir`. Returns `NULL` on failure. */ struct pw_carts *pw_carts_list(char const *dir); @@ -73,6 +81,11 @@ void pw_carts_free(struct pw_carts *carts); struct pw_cart *pw_cart_init(SDL_Renderer *renderer); /** + * Frees a cart and all of its resources. + */ +void pw_cart_free(struct pw_cart *cart); + +/** * Loads the main cart from an entry. * * This will also decode and load the PNG to the cart `png` texture for use in @@ -81,16 +94,23 @@ struct pw_cart *pw_cart_init(SDL_Renderer *renderer); bool pw_cart_load(struct pw_cart_entry *entry, struct pw_cart *cart); /** - * Loads a multi-cart by name from an entry. The PNG texture is left unchanged. + * Initializes a multi-cart from a cart entry. * - * The name is stripped of `#` and `.(p8|p8.png|p8.rom)` extensions. + * Optionally specify a loaded cart to copy the initial ROM from. */ -bool pw_cart_multi_load(struct pw_cart_entry *entry, struct pw_cart *cart, - char const *name); +struct pw_multicart *pw_multicart_init(struct pw_cart_entry *entry, + struct pw_cart *cart); /** - * Frees a cart and all of its resources. + * Frees a multi-cart and all of its resources. */ -void pw_cart_free(struct pw_cart *cart); +void pw_multicart_free(struct pw_multicart *cart); + +/** + * Loads a multi-cart ROM by name. + * + * The name is stripped of `#` and `.(p8|p8.png|p8.rom)` extensions. + */ +bool pw_multicart_load(struct pw_multicart *cart, char const *name); #endif @@ -113,7 +113,7 @@ bool pw_fb_coordinates(struct pw_framebuffer *fb, float wx, float wy, return true; } -bool pw_fb_flip(struct pw_framebuffer *fb, +bool pw_fb_blit(struct pw_framebuffer *fb, uint32_t const pixels[PW_FB_WIDTH * PW_FB_HEIGHT]) { if (!fb) { SDL_InvalidParamError("fb"); @@ -135,6 +135,20 @@ bool pw_fb_flip(struct pw_framebuffer *fb, SDL_memcpy(buffer, pixels, sizeof(uint32_t[PW_FB_WIDTH * PW_FB_HEIGHT])); SDL_UnlockTexture(fb->texture); + return true; +} + +bool pw_fb_render(struct pw_framebuffer *fb) { + if (!fb) { + SDL_InvalidParamError("fb"); + return false; + } + + SDL_Renderer *renderer = SDL_GetRendererFromTexture(fb->texture); + if (!renderer) { + return false; + } + return SDL_RenderClear(renderer) && SDL_RenderTexture(renderer, fb->texture, NULL, &fb->target) && SDL_RenderPresent(renderer); @@ -46,7 +46,12 @@ bool pw_fb_coordinates(struct pw_framebuffer *fb, float wx, float wy, /** * Blits the pixel data to the framebuffer. */ -bool pw_fb_flip(struct pw_framebuffer *fb, +bool pw_fb_blit(struct pw_framebuffer *fb, uint32_t const pixels[PW_FB_WIDTH * PW_FB_HEIGHT]); +/** + * Renders the the framebuffer. + */ +bool pw_fb_render(struct pw_framebuffer *fb); + #endif diff --git a/src/game.c b/src/game.c new file mode 100644 index 0000000..72d5046 --- /dev/null +++ b/src/game.c @@ -0,0 +1,293 @@ +#include <SDL3/SDL_log.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_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; +} + +struct pw_game *pw_game_init(SDL_Renderer *renderer) { + if (!renderer) { + SDL_InvalidParamError("renderer"); + return NULL; + } + + bool wasm_init = false; + struct pw_game *game = SDL_malloc(sizeof(*game)); + if (!game) { + return NULL; + } + SDL_zerop(game); + + game->fb = pw_fb_init(renderer); + if (!game->fb) { + goto error; + } + + game->input = pw_input_init(); + if (!game->input) { + goto error; + } + + struct RuntimeInitArgs init = { + .mem_alloc_type = Alloc_With_Allocator, + .mem_alloc_option.allocator.malloc_func = &wasm_malloc, + .mem_alloc_option.allocator.realloc_func = &wasm_realloc, + .mem_alloc_option.allocator.free_func = &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}, + }; + 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[] = {}; + if (!wasm_runtime_link_globals(game->module, "env", genv, + SDL_arraysize(genv)) || + !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->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; +} + +void pw_game_free(struct pw_game *game) { + if (!game) { + SDL_InvalidParamError("game"); + return; + } + + 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); +} + +bool pw_game_start(struct pw_game *game, struct pw_multicart *cart) { + if (!game) { + SDL_InvalidParamError("game"); + return false; + } + if (!cart) { + SDL_InvalidParamError("cart"); + return false; + } + + char err[1024]; + + if (game->cart) { + pw_multicart_free(game->cart); + } + game->cart = cart; + + if (game->instance) { + wasm_runtime_deinstantiate(game->instance); + } + 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 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 || !dyncall || !mix) { + return SDL_SetError("could not required exports"); + } + + wasm_exec_env_t exec = wasm_runtime_create_exec_env(game->instance, 1024); + if (exec == NULL) { + return SDL_SetError("failed to create execution environment"); + } + wasm_runtime_set_user_data(exec, game); + + if (!wasm_runtime_call_wasm(exec, ctor, 0, NULL)) { + return SDL_SetError("error calling main"); + } + + uint32_t arg0; + { + char const value[] = "./pico8"; + uint32_t args[] = {(uint32_t)sizeof(value)}; + if (!wasm_runtime_call_wasm(exec, stackalloc, 1, args)) { + return SDL_SetError("error allocating argument 0"); + } + + arg0 = args[0]; + char *target = wasm_runtime_addr_app_to_native(game->instance, arg0); + if (!target) { + return SDL_SetError("invalid argument 0 address"); + } + + SDL_memcpy(target, value, sizeof(value)); + } + + uint32_t argv; + { + uint32_t const value[] = {arg0, 0}; + uint32_t args[] = {(uint32_t)sizeof(value)}; + if (!wasm_runtime_call_wasm(exec, stackalloc, 1, args)) { + return SDL_SetError("error allocating arguments array"); + } + + argv = args[0]; + char *target = wasm_runtime_addr_app_to_native(game->instance, argv); + if (!target) { + return SDL_SetError("invalid arguments array address"); + } + + SDL_memcpy(target, value, sizeof(value)); + } + + game->mainfn = 0; + { + uint32_t args[] = {1, argv}; + if (!wasm_runtime_call_wasm(exec, start, 2, args)) { + return SDL_SetError("error calling main"); + } + if (args[0]) { + return SDL_SetError("main returned exit code"); + } + } + if (!game->mainfn) { + return SDL_SetError("main loop function not set"); + } + + game->exec = exec; + game->dyncall = dyncall; + game->mix = mix; + return true; +} + +bool pw_game_event(struct pw_game *game, struct pw_players *players, + SDL_Event *event) { + if (!game) { + SDL_InvalidParamError("game"); + return false; + } + + return pw_input_event(game->input, players, event); +} + +bool pw_game_iterate(struct pw_game *game) { + if (!game) { + SDL_InvalidParamError("game"); + return false; + } + + 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"); + } + } + { + uint32_t args[] = {42, 1337}; + if (!wasm_runtime_call_wasm(game->exec, game->mix, 2, args)) { + return SDL_SetError("error calling audio mixer"); + } + if (!args[0]) { + return SDL_SetError("audio mixing failed %d %d", args[0], args[1]); + } + } + { + // TODO: pretend that our WASM is modifying some backing buffer. + uint32_t r = (uint32_t)pw_input_btn(game->input, 0) << 1; + uint32_t g = (uint32_t)pw_input_btn(game->input, 1) << 9; + uint32_t px = r | g | 0xff2f0000; + for (int x = 0; x < 128; x++) { + for (int y = 0; y < 128; y++) { + int i = x + y * 128; + if (x == game->input->mouse.pos.x && y == game->input->mouse.pos.y) { + game->fbbuf[i] = 0xff000000; + if (game->input->mouse.button & PW_MOUSE_BUTTON_LEFT) { + game->fbbuf[i] |= 0x0000ff; + } + if (game->input->mouse.button & PW_MOUSE_BUTTON_MIDDLE) { + game->fbbuf[i] |= 0x00ff00; + } + if (game->input->mouse.button & PW_MOUSE_BUTTON_RIGHT) { + game->fbbuf[i] |= 0xff0000; + } + } else { + game->fbbuf[i] = px; + } + } + } + } + + return pw_fb_blit(game->fb, game->fbbuf) && pw_fb_render(game->fb); +} diff --git a/src/game.h b/src/game.h new file mode 100644 index 0000000..d8c7df8 --- /dev/null +++ b/src/game.h @@ -0,0 +1,58 @@ +#ifndef PW_GAME_H +#define PW_GAME_H + +#include <SDL3/SDL_events.h> +#include <SDL3/SDL_render.h> + +#include <wamr/wamr.h> + +#include "cart.h" +#include "fb.h" +#include "input.h" +#include "player.h" + +/** + * Executing PICO-8 game state. + */ +struct pw_game { + 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 dyncall; + wasm_function_inst_t mix; + int32_t mainfn; + + // TODO: Hack until the backing buffer lives in WASM memory. + uint32_t fbbuf[PW_FB_WIDTH * PW_FB_HEIGHT]; +}; + +/** + * Allocates and initializes the game state. + */ +struct pw_game *pw_game_init(SDL_Renderer *renderer); + +/** + * Frees the game state. + */ +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); + +/** + * Handles SDL events for game state. + */ +bool pw_game_event(struct pw_game *game, struct pw_players *players, + SDL_Event *event); + +/** + * Iterate a new frame for the game state. + */ +bool pw_game_iterate(struct pw_game *game); + +#endif diff --git a/src/input.c b/src/input.c index 46c8491..9e41ebe 100644 --- a/src/input.c +++ b/src/input.c @@ -1,6 +1,5 @@ #include <SDL3/SDL_log.h> -#include "fb.h" #include "input.h" struct pw_input *pw_input_init(void) { diff --git a/src/input.h b/src/input.h index 00adfea..13811a6 100644 --- a/src/input.h +++ b/src/input.h @@ -1,6 +1,8 @@ #ifndef PW_INPUT_H #define PW_INPUT_H +#include <SDL3/SDL_events.h> + #include "fb.h" #include "player.h" diff --git a/src/menu.c b/src/menu.c new file mode 100644 index 0000000..441ebcf --- /dev/null +++ b/src/menu.c @@ -0,0 +1,232 @@ +#include <SDL3/SDL_log.h> + +#include "input.h" +#include "menu.h" + +struct pw_menu *pw_menu_init(SDL_Renderer *renderer, char const *carts) { + if (!renderer) { + SDL_InvalidParamError("renderer"); + return NULL; + } + if (!carts) { + SDL_InvalidParamError("carts"); + return NULL; + } + + struct pw_menu *menu = SDL_malloc(sizeof(*menu)); + if (!menu) { + return NULL; + } + SDL_zerop(menu); + + menu->carts = pw_carts_list(carts); + if (!menu->carts) { + goto error; + } + + menu->cart = pw_cart_init(renderer); + if (!menu->cart) { + goto error; + } + + if (!menu->carts->count) { + SDL_LogWarn(0, "empty or missing carts directory"); + } else if (!pw_cart_load(&menu->carts->entries[0], menu->cart)) { + goto error; + } + + return menu; + +error: + if (menu->carts) { + pw_carts_free(menu->carts); + } + if (menu->cart) { + pw_cart_free(menu->cart); + } + SDL_free(menu); + return NULL; +} + +void pw_menu_free(struct pw_menu *menu) { + if (!menu) { + SDL_InvalidParamError("menu"); + return; + } + + pw_carts_free(menu->carts); + pw_cart_free(menu->cart); + SDL_free(menu); +} + +static size_t saturating_add(size_t a, ssize_t b) { + // TODO: yuck... + if (b < 0) { + size_t c = (size_t)(-b); + if (a < c) { + return 0; + } else { + return a - c; + } + } else { + size_t c = a + (size_t)(b); + if (c < a) { + return SIZE_MAX; + } else { + return c; + } + } +} + +bool pw_menu_event(struct pw_menu *menu, SDL_Event *event) { + if (!menu) { + SDL_InvalidParamError("menu"); + return false; + } + if (!event) { + SDL_InvalidParamError("event"); + return false; + } + + if (!menu->carts->count) { + return true; + } + + ssize_t delta = 0; + switch (event->type) { + case SDL_EVENT_GAMEPAD_AXIS_MOTION: + switch (event->gaxis.axis) { + case SDL_GAMEPAD_AXIS_LEFTX: + if (event->gaxis.value < -PW_AXIS_THRESHOLD) { + delta -= 1; + } else if (event->gaxis.value > PW_AXIS_THRESHOLD) { + delta += 1; + } + break; + case SDL_GAMEPAD_AXIS_LEFTY: + if (event->gaxis.value < -PW_AXIS_THRESHOLD) { + delta -= 10; + } else if (event->gaxis.value > PW_AXIS_THRESHOLD) { + delta += 10; + } + break; + } + break; + case SDL_EVENT_GAMEPAD_BUTTON_DOWN: + switch (event->gbutton.button) { + case SDL_GAMEPAD_BUTTON_NORTH: + case SDL_GAMEPAD_BUTTON_SOUTH: + case SDL_GAMEPAD_BUTTON_EAST: + case SDL_GAMEPAD_BUTTON_WEST: + case SDL_GAMEPAD_BUTTON_START: + case SDL_GAMEPAD_BUTTON_BACK: + menu->selection.selected = true; + break; + case SDL_GAMEPAD_BUTTON_DPAD_UP: + delta -= 10; + break; + case SDL_GAMEPAD_BUTTON_DPAD_DOWN: + delta += 10; + break; + case SDL_GAMEPAD_BUTTON_DPAD_LEFT: + delta -= 1; + break; + case SDL_GAMEPAD_BUTTON_DPAD_RIGHT: + delta += 1; + break; + } + break; + case SDL_EVENT_KEY_DOWN: + switch (event->key.key) { + case SDLK_Z: + case SDLK_X: + case SDLK_RETURN: + menu->selection.selected = true; + break; + case SDLK_UP: + case SDLK_K: + delta -= 10; + break; + case SDLK_DOWN: + case SDLK_J: + delta += 10; + break; + case SDLK_LEFT: + case SDLK_H: + delta -= 1; + break; + case SDLK_RIGHT: + case SDLK_L: + delta += 1; + break; + } + } + + menu->selection.next = SDL_min(saturating_add(menu->selection.next, delta), + menu->carts->count - 1); + return true; +} + +static bool center_rect(SDL_Renderer *renderer, SDL_FRect *target) { + int rw, rh; + if (!SDL_GetRenderOutputSize(renderer, &rw, &rh)) { + return false; + } + + int scale = SDL_min(rw / PW_PNG_WIDTH, rh / PW_PNG_HEIGHT); + if (!scale) { + return false; + } + + int w = scale * PW_PNG_WIDTH; + int h = scale * PW_PNG_HEIGHT; + int x = (rw - w) / 2; + int y = (rh - h) / 2; + + target->w = (float)w; + target->h = (float)h; + target->x = (float)x; + target->y = (float)y; + return true; +} + +bool pw_menu_iterate(struct pw_menu *menu, struct pw_multicart **cart) { + if (!menu) { + SDL_InvalidParamError("menu"); + return false; + } + if (!cart) { + SDL_InvalidParamError("cart"); + return false; + } + + if (menu->selection.current != menu->selection.next) { + if (!pw_cart_load(&menu->carts->entries[menu->selection.next], + menu->cart)) { + return false; + } + menu->selection.current = menu->selection.next; + } + + if (menu->selection.selected) { + *cart = pw_multicart_init(&menu->carts->entries[menu->selection.current], + menu->cart); + if (!*cart) { + return false; + } + menu->selection.selected = false; + return true; + } + *cart = NULL; + + SDL_Texture *png = menu->cart->png; + SDL_Renderer *renderer = SDL_GetRendererFromTexture(png); + SDL_FRect target; + if (!renderer || !center_rect(renderer, &target)) { + return false; + } + + return SDL_RenderClear(renderer) && + SDL_RenderTexture(renderer, png, NULL, &target) && + SDL_RenderPresent(renderer); +} diff --git a/src/menu.h b/src/menu.h new file mode 100644 index 0000000..7bd17df --- /dev/null +++ b/src/menu.h @@ -0,0 +1,43 @@ +#ifndef PW_MENU_H +#define PW_MENU_H + +#include <SDL3/SDL_events.h> +#include <SDL3/SDL_render.h> + +#include "cart.h" + +/** + * The cart selection menu state. + */ +struct pw_menu { + struct pw_carts *carts; + struct pw_cart *cart; + struct { + size_t current; + size_t next; + bool selected; + } selection; +}; + +/** + * Allocates and initializes the cart selection menu state. + */ +struct pw_menu *pw_menu_init(SDL_Renderer *renderer, char const *carts); + +/** + * Frees the cart selection menu. + */ +void pw_menu_free(struct pw_menu *menu); + +/** + * Handles SDL events for cart selection. + */ +bool pw_menu_event(struct pw_menu *menu, SDL_Event *event); + +/** + * Iterate a new frame for the cart selection menu. Sets `cart` to non-`NULL` + * if a cart was selected to run in the menu. + */ +bool pw_menu_iterate(struct pw_menu *menu, struct pw_multicart **cart); + +#endif diff --git a/src/picow.c b/src/picow.c index f7b3418..0e6bdde 100644 --- a/src/picow.c +++ b/src/picow.c @@ -4,12 +4,11 @@ #include <SDL3/SDL.h> #include <SDL3/SDL_main.h> -#include <wamr/wamr.h> - #include "cart.h" -#include "input.h" +#include "game.h" +#include "menu.h" #include "path.h" -#include "sysroot.h" +#include "player.h" static void usage(char const *name) { printf("Usage: %s [-c <carts>] [-v[v[v]]]\n" @@ -51,267 +50,12 @@ enum pw_scene { struct pw_appstate { SDL_Window *window; SDL_Renderer *renderer; - SDL_FRect carttarget; - struct pw_framebuffer *fb; - // TODO: Hack until the backing buffer lives in WASM memory. - uint32_t fbbuf[PW_FB_WIDTH * PW_FB_HEIGHT]; struct pw_players *players; - struct pw_input *input; - struct pw_carts *carts; - struct pw_cart *cart; - ssize_t cartidx; - ssize_t cartidx2; - wasm_module_t module; - wasm_module_inst_t instance; - wasm_exec_env_t exec; - wasm_function_inst_t dyncall; - wasm_function_inst_t mix; - int32_t mainfn; + struct pw_menu *menu; + struct pw_game *game; enum pw_scene scene; - enum pw_scene scene2; }; -static bool update_pxtexture_target(SDL_Texture *texture, SDL_FRect *target, - int w, int h) { - float ww = (float)w, wh = (float)h; - float fbw, fbh; - if (!SDL_GetTextureSize(texture, &fbw, &fbh)) { - return false; - } - - float scale = SDL_floor(SDL_min(ww / fbw, wh / fbh)); - target->w = scale * fbw; - target->h = scale * fbh; - - target->x = SDL_floor((ww - target->w) / 2.0); - target->y = SDL_floor((wh - target->h) / 2.0); - - return true; -} - -static SDL_AppResult update_target_rect(struct pw_appstate *state, int w, - int h) { - switch (state->scene) { - case PW_SCENE_CART_SELECTION: - if (!update_pxtexture_target(state->cart->png, &state->carttarget, w, h)) { - return failf("failed to update texture target"); - } - break; - default: - break; - } - - return SDL_APP_CONTINUE; -} - -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 SDL_AppResult scene_cart_selection_event(struct pw_appstate *state) { - // TODO(nlordell): This is slightly incorrect, we actually want to keep track - // of general button states. Fix once we have a proper scene abstraction. - - ssize_t ncarts = (ssize_t)state->carts->count; - if (ncarts <= 0) { - return SDL_APP_CONTINUE; - } - - uint8_t button = pw_input_btn(state->input, 0); - if (button & PW_BUTTON_LEFT) { - state->cartidx2 = SDL_max(0, state->cartidx2 - 1); - } - if (button & PW_BUTTON_RIGHT) { - state->cartidx2 = SDL_min(ncarts - 1, state->cartidx2 + 1); - } - if (button & PW_BUTTON_UP) { - state->cartidx2 = SDL_max(0, state->cartidx2 - 10); - } - if (button & PW_BUTTON_DOWN) { - state->cartidx2 = SDL_min(ncarts - 1, state->cartidx2 + 10); - } - if (button & (PW_BUTTON_O | PW_BUTTON_X | PW_BUTTON_MENU)) { - state->scene2 = PW_SCENE_GAME; - } - - return SDL_APP_CONTINUE; -} - -static SDL_AppResult scene_cart_selection(struct pw_appstate *state) { - if (state->cartidx != state->cartidx2) { - state->cartidx = state->cartidx2; - if (!pw_cart_load(&state->carts->entries[state->cartidx], state->cart)) { - return failf("failed to load cart png"); - } - } - - SDL_RenderClear(state->renderer); - SDL_RenderTexture(state->renderer, state->cart->png, NULL, - &state->carttarget); - SDL_RenderPresent(state->renderer); - - return SDL_APP_CONTINUE; -} - -static SDL_AppResult scene_game_init(struct pw_appstate *state) { - char err[1024]; - - state->instance = - wasm_runtime_instantiate(state->module, 1024, 0, err, sizeof err); - if (!state->instance) { - SDL_SetError("%s", err); - return failf("failed to instantiate PICO-8 WebAssembly module"); - } - - wasm_function_inst_t ctor = wasm_runtime_lookup_function( - state->instance, "___emscripten_environ_constructor"); - wasm_function_inst_t start = - wasm_runtime_lookup_function(state->instance, "_main"); - wasm_function_inst_t stackalloc = - wasm_runtime_lookup_function(state->instance, "stackAlloc"); - wasm_function_inst_t dyncall = - wasm_runtime_lookup_function(state->instance, "dynCall_v"); - wasm_function_inst_t mix = - wasm_runtime_lookup_function(state->instance, "_mix_0"); - if (!ctor || !start || !stackalloc || !dyncall || !mix) { - return failf("could not required exports"); - } - - wasm_exec_env_t exec = wasm_runtime_create_exec_env(state->instance, 1024); - if (exec == NULL) { - return failf("failed to create execution environment"); - } - wasm_runtime_set_user_data(exec, state); - - if (!wasm_runtime_call_wasm(exec, ctor, 0, NULL)) { - return failf("error calling main"); - } - - uint32_t arg0; - { - char const value[] = "./pico8"; - uint32_t args[] = {(uint32_t)sizeof(value)}; - if (!wasm_runtime_call_wasm(exec, stackalloc, 1, args)) { - return failf("error allocating argument 0"); - } - - arg0 = args[0]; - char *target = wasm_runtime_addr_app_to_native(state->instance, arg0); - if (!target) { - return failf("invalid argument 0 address"); - } - - SDL_memcpy(target, value, sizeof(value)); - } - - uint32_t argv; - { - uint32_t const value[] = {arg0, 0}; - uint32_t args[] = {(uint32_t)sizeof(value)}; - if (!wasm_runtime_call_wasm(exec, stackalloc, 1, args)) { - return failf("error allocating arguments array"); - } - - argv = args[0]; - char *target = wasm_runtime_addr_app_to_native(state->instance, argv); - if (!target) { - return failf("invalid arguments array address"); - } - - SDL_memcpy(target, value, sizeof(value)); - } - - state->mainfn = 0; - { - uint32_t args[] = {1, argv}; - if (!wasm_runtime_call_wasm(exec, start, 2, args)) { - return failf("error calling main"); - } - if (args[0]) { - return failf("main returned exit code"); - } - } - if (!state->mainfn) { - return failf("main loop function not set"); - } - - state->exec = exec; - state->dyncall = dyncall; - state->mix = mix; - return SDL_APP_CONTINUE; -} - -static SDL_AppResult scene_game(struct pw_appstate *state) { - pw_fb_iterate(state->fb); - pw_input_iterate(state->input, state->fb); - - { - uint32_t args[] = {state->mainfn}; - if (!wasm_runtime_call_wasm(state->exec, state->dyncall, 1, args)) { - return failf("error calling main loop function"); - } - } - { - uint32_t args[] = {42, 1337}; - if (!wasm_runtime_call_wasm(state->exec, state->mix, 2, args)) { - return failf("error calling audio mixer"); - } - if (!args[0]) { - return failf("audio mixing failed %d %d", args[0], args[1]); - } - } - { - // TODO: pretend that our WASM is modifying some backing buffer. - uint32_t r = (uint32_t)pw_input_btn(state->input, 0) << 1; - uint32_t g = (uint32_t)pw_input_btn(state->input, 1) << 9; - uint32_t px = r | g | 0xff2f0000; - for (int x = 0; x < 128; x++) { - for (int y = 0; y < 128; y++) { - int i = x + y * 128; - if (x == state->input->mouse.pos.x && y == state->input->mouse.pos.y) { - state->fbbuf[i] = 0xff000000; - if (state->input->mouse.button & PW_MOUSE_BUTTON_LEFT) { - state->fbbuf[i] |= 0x0000ff; - } - if (state->input->mouse.button & PW_MOUSE_BUTTON_MIDDLE) { - state->fbbuf[i] |= 0x00ff00; - } - if (state->input->mouse.button & PW_MOUSE_BUTTON_RIGHT) { - state->fbbuf[i] |= 0xff0000; - } - } else { - state->fbbuf[i] = px; - } - } - } - } - - if (!pw_fb_flip(state->fb, state->fbbuf)) { - return SDL_APP_FAILURE; - } - - return SDL_APP_CONTINUE; -} - -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_appstate *state = wasm_runtime_get_user_data(exec); - SDL_LogDebug(0, "setting main loop function: %d", func); - state->mainfn = func; - - // Ignore the fps and simulate infinite loop parameters, they are always 0 - // for PICO-8 anyway. - (void)fps; - (void)simulate_infinite_loop; -} - SDL_AppResult SDL_AppInit(void **appstate, int argc, char **argv) { struct pw_appstate *state = SDL_calloc(1, sizeof *state); *appstate = state; @@ -352,183 +96,81 @@ SDL_AppResult SDL_AppInit(void **appstate, int argc, char **argv) { return failf("failed to create window"); } - if (!SDL_SetWindowMinimumSize(state->window, 160, 205)) { + if (!SDL_SetWindowMinimumSize(state->window, PW_PNG_WIDTH, PW_PNG_HEIGHT)) { return failf("failed to configure minimum window size"); } - state->fb = pw_fb_init(state->renderer); - if (!state->fb) { - return failf("failed to create framebuffer"); - } - state->players = pw_players_init(); if (!state->players) { return failf("failed to initialize player controllers"); } - state->input = pw_input_init(); - if (!state->input) { - return failf("failed to initialize input state"); - } - - state->cart = pw_cart_init(state->renderer); - if (!state->cart) { - return failf("failed to initialize cart"); - } - - state->carts = pw_carts_list(carts); - if (!state->carts) { - return failf("failed to read carts directory"); - } else if (!state->carts->count) { - SDL_LogWarn(0, "empty or missing carts directory"); - } else if (!pw_cart_load(&state->carts->entries[0], state->cart)) { - return failf("failed to load startup cart"); - } - - struct RuntimeInitArgs init = { - .mem_alloc_type = Alloc_With_Allocator, - .mem_alloc_option.allocator.malloc_func = &wasm_malloc, - .mem_alloc_option.allocator.realloc_func = &wasm_realloc, - .mem_alloc_option.allocator.free_func = &wasm_free, - }; - if (!wasm_runtime_full_init(&init)) { - SDL_SetError("unspecified error"); - return failf("failed to initialize the WebAssembly runtime"); + state->menu = pw_menu_init(state->renderer, carts); + if (!state->menu) { + return failf("failed to initialize cart selection state"); } - struct NativeSymbol env[] = { - {"_emscripten_set_main_loop", emrt_set_main_loop, "(iii)", NULL}, - }; - if (!wasm_runtime_register_natives_raw("env", env, SDL_arraysize(env))) { - SDL_SetError("unspecified error"); - return failf("failed to register host functions"); - } - - char err[1024]; - state->module = wasm_runtime_load(stub_pico8_wasm.data, stub_pico8_wasm.size, - err, sizeof err); - if (state->module == NULL) { - SDL_SetError("%s", err); - return failf("failed to load the PICO-8 WebAssembly module"); - } - - struct NativeGlobal genv[] = {}; - if (!wasm_runtime_link_globals(state->module, "env", genv, - SDL_arraysize(genv)) || - !wasm_runtime_link_globals(state->module, "global", genv, - SDL_arraysize(genv))) { - SDL_SetError("unspecified error"); - return failf("failed to register host globals"); + state->game = pw_game_init(state->renderer); + if (!state->game) { + return failf("failed to initialize PICO-8 game state"); } state->scene = PW_SCENE_CART_SELECTION; - state->scene2 = PW_SCENE_CART_SELECTION; return SDL_APP_CONTINUE; } -SDL_AppResult SDL_AppIterate(void *appstate) { +SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event) { struct pw_appstate *state = appstate; - if (state->scene != state->scene2) { - state->scene = state->scene2; - - int w, h; - SDL_GetWindowSizeInPixels(state->window, &w, &h); - update_target_rect(state, w, h); - + switch (event->type) { + case SDL_EVENT_QUIT: + return SDL_APP_SUCCESS; + case SDL_EVENT_GAMEPAD_ADDED: + case SDL_EVENT_GAMEPAD_REMOVED: + if (!pw_players_event(state->players, event)) { + return failf("failed to player controller connection events"); + }; + break; + default: switch (state->scene) { case PW_SCENE_CART_SELECTION: - // TODO(nlordell): re-read cart directory? + if (!pw_menu_event(state->menu, event)) { + return failf("failed to process cart selection events"); + } break; case PW_SCENE_GAME: - return scene_game_init(state); + if (!pw_game_event(state->game, state->players, event)) { + return failf("failed to process PICO-8 game events"); + } + break; } } - switch (state->scene) { - case PW_SCENE_CART_SELECTION: - return scene_cart_selection(state); - case PW_SCENE_GAME: - return scene_game(state); - } -} - -static SDL_AppResult HACK_gamepad_state(struct pw_appstate *state, - enum pw_button button, bool pressed) { - // TODO(nlordell): Just a hack for now before we implement a keyboard - // abstraction and split out the scenes. - - enum pw_button *player = &state->input->players[0]; - if (pressed) { - *player |= button; - } else { - *player &= ~button; - } - - if (state->scene != PW_SCENE_CART_SELECTION) { - return SDL_APP_CONTINUE; - } - - return scene_cart_selection_event(state); -} - -static SDL_AppResult handle_keyboard(struct pw_appstate *state, - SDL_KeyboardEvent *event) { - switch (event->key) { - case SDLK_ESCAPE: - case SDLK_Q: - return SDL_APP_SUCCESS; - case SDLK_Z: - return HACK_gamepad_state(state, PW_BUTTON_O, event->down); - case SDLK_X: - return HACK_gamepad_state(state, PW_BUTTON_X, event->down); - case SDLK_UP: - case SDLK_K: - return HACK_gamepad_state(state, PW_BUTTON_UP, event->down); - case SDLK_DOWN: - case SDLK_J: - return HACK_gamepad_state(state, PW_BUTTON_DOWN, event->down); - case SDLK_LEFT: - case SDLK_H: - return HACK_gamepad_state(state, PW_BUTTON_LEFT, event->down); - case SDLK_RIGHT: - case SDLK_L: - return HACK_gamepad_state(state, PW_BUTTON_RIGHT, event->down); - case SDLK_RETURN: - return HACK_gamepad_state(state, PW_BUTTON_MENU, event->down); - } - return SDL_APP_CONTINUE; } -SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event) { +SDL_AppResult SDL_AppIterate(void *appstate) { struct pw_appstate *state = appstate; - switch (event->type) { - case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED: - return update_target_rect(state, event->window.data1, event->window.data2); - case SDL_EVENT_QUIT: - return SDL_APP_SUCCESS; - case SDL_EVENT_GAMEPAD_ADDED: - case SDL_EVENT_GAMEPAD_REMOVED: - if (!pw_players_event(state->players, event)) { - return SDL_APP_FAILURE; - }; - break; - case SDL_EVENT_GAMEPAD_AXIS_MOTION: - case SDL_EVENT_GAMEPAD_BUTTON_UP: - case SDL_EVENT_GAMEPAD_BUTTON_DOWN: - if (!pw_input_event(state->input, state->players, event)) { - return SDL_APP_FAILURE; - }; - if (state->scene == PW_SCENE_CART_SELECTION) { - return scene_cart_selection_event(state); + if (state->scene == PW_SCENE_CART_SELECTION) { + struct pw_multicart *cart; + if (!pw_menu_iterate(state->menu, &cart)) { + return failf("failed to update cart selection menu state"); + } + if (cart) { + if (!pw_game_start(state->game, cart)) { + return failf("failed to start selected cart"); + } + state->scene = PW_SCENE_GAME; } - break; - case SDL_EVENT_KEY_DOWN: - case SDL_EVENT_KEY_UP: - return handle_keyboard(state, &event->key); } + + if (state->scene == PW_SCENE_GAME) { + if (!pw_game_iterate(state->game)) { + return failf("failed to update PICO-8 game state"); + } + } + return SDL_APP_CONTINUE; } @@ -536,18 +178,9 @@ void SDL_AppQuit(void *appstate, SDL_AppResult result) { struct pw_appstate *state = appstate; (void)result; - if (state->module) { - if (state->instance) { - wasm_runtime_deinstantiate(state->instance); - } - wasm_runtime_unload(state->module); - wasm_runtime_destroy(); - } - pw_fb_free(state->fb); pw_players_free(state->players); - pw_input_free(state->input); - pw_carts_free(state->carts); - pw_cart_free(state->cart); + pw_menu_free(state->menu); + pw_game_free(state->game); SDL_DestroyRenderer(state->renderer); SDL_DestroyWindow(state->window); SDL_free(state); diff --git a/src/player.h b/src/player.h index ce753c8..b75d875 100644 --- a/src/player.h +++ b/src/player.h @@ -2,6 +2,8 @@ #define PW_PLAYER_H #include <SDL3/SDL_events.h> +#include <SDL3/SDL_gamepad.h> +#include <SDL3/SDL_joystick.h> #define PW_PLAYERS_MAX 8 |
