From a907516ad0a58d2ba64238b387c529d626216f39 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sun, 4 Oct 2026 21:38:27 -0500 Subject: [PATCH 01/19] feat(pico8): add PICO-8 (femto8) Vendors femto8 (benbaker76/femto8 @ f9e5097) as components/pico8 with an esp-box-emu platform: the cart runs in its own task, frames are palette indices scaled by the emulator, audio is rendered on core 1, and the Lua instruction hook is the pause/quit point so the core stops cleanly and relaunches without a reboot (statics reset through linker SURROUND symbols). Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- CMakeLists.txt | 9 + README.md | 16 +- components/pico8/CMakeLists.txt | 25 + components/pico8/VENDOR.md | 35 + components/pico8/femto8/LICENSE | 7 + components/pico8/femto8/README.md | 40 + components/pico8/femto8/src/data/lua_api.h | 131 + components/pico8/femto8/src/data/p8_symbols.h | 174 + components/pico8/femto8/src/data/pico_font.h | 137 + .../pico8/femto8/src/lexaloffle/p8_compress.c | 140 + .../pico8/femto8/src/lexaloffle/pico8.h | 13 + .../src/lexaloffle/pxa_compress_snippets.c | 283 + components/pico8/femto8/src/lodepng/LICENSE | 21 + components/pico8/femto8/src/lodepng/lodepng.c | 7242 +++++++++++++++++ components/pico8/femto8/src/lodepng/lodepng.h | 2178 +++++ components/pico8/femto8/src/lua/.gitignore | 3 + components/pico8/femto8/src/lua/fix32.h | 158 + components/pico8/femto8/src/lua/lapi.c | 1293 +++ components/pico8/femto8/src/lua/lapi.h | 24 + components/pico8/femto8/src/lua/lauxlib.c | 959 +++ components/pico8/femto8/src/lua/lauxlib.h | 212 + components/pico8/femto8/src/lua/lbaselib.c | 487 ++ components/pico8/femto8/src/lua/lcode.c | 902 ++ components/pico8/femto8/src/lua/lcode.h | 88 + components/pico8/femto8/src/lua/lcorolib.c | 155 + components/pico8/femto8/src/lua/lctype.c | 52 + components/pico8/femto8/src/lua/lctype.h | 96 + components/pico8/femto8/src/lua/ldblib.c | 408 + components/pico8/femto8/src/lua/ldebug.c | 620 ++ components/pico8/femto8/src/lua/ldebug.h | 34 + components/pico8/femto8/src/lua/ldo.c | 681 ++ components/pico8/femto8/src/lua/ldo.h | 46 + components/pico8/femto8/src/lua/ldump.c | 173 + components/pico8/femto8/src/lua/lfunc.c | 161 + components/pico8/femto8/src/lua/lfunc.h | 33 + components/pico8/femto8/src/lua/lgc.c | 1220 +++ components/pico8/femto8/src/lua/lgc.h | 157 + components/pico8/femto8/src/lua/linit.c | 67 + components/pico8/femto8/src/lua/llex.c | 609 ++ components/pico8/femto8/src/lua/llex.h | 88 + components/pico8/femto8/src/lua/llimits.h | 228 + components/pico8/femto8/src/lua/lmem.c | 99 + components/pico8/femto8/src/lua/lmem.h | 57 + components/pico8/femto8/src/lua/loadlib.c | 725 ++ components/pico8/femto8/src/lua/lobject.c | 342 + components/pico8/femto8/src/lua/lobject.h | 607 ++ components/pico8/femto8/src/lua/lopcodes.c | 133 + components/pico8/femto8/src/lua/lopcodes.h | 302 + components/pico8/femto8/src/lua/lparser.c | 1830 +++++ components/pico8/femto8/src/lua/lparser.h | 119 + components/pico8/femto8/src/lua/lpico8lib.c | 409 + components/pico8/femto8/src/lua/lstate.c | 324 + components/pico8/femto8/src/lua/lstate.h | 229 + components/pico8/femto8/src/lua/lstring.c | 185 + components/pico8/femto8/src/lua/lstring.h | 46 + components/pico8/femto8/src/lua/lstrlib.c | 1041 +++ components/pico8/femto8/src/lua/ltable.c | 588 ++ components/pico8/femto8/src/lua/ltable.h | 45 + components/pico8/femto8/src/lua/ltablib.c | 285 + components/pico8/femto8/src/lua/ltests.c | 1503 ++++ components/pico8/femto8/src/lua/ltests.h | 93 + components/pico8/femto8/src/lua/ltm.c | 79 + components/pico8/femto8/src/lua/ltm.h | 70 + components/pico8/femto8/src/lua/lua.h | 459 ++ components/pico8/femto8/src/lua/luaconf.h | 671 ++ components/pico8/femto8/src/lua/lualib.h | 57 + components/pico8/femto8/src/lua/lundump.c | 258 + components/pico8/femto8/src/lua/lundump.h | 28 + components/pico8/femto8/src/lua/lvm.c | 963 +++ components/pico8/femto8/src/lua/lvm.h | 45 + components/pico8/femto8/src/lua/lzio.c | 76 + components/pico8/femto8/src/lua/lzio.h | 65 + components/pico8/femto8/src/lua/makefile | 163 + components/pico8/femto8/src/lua/trigtables.h | 412 + components/pico8/femto8/src/p8_audio.c | 650 ++ components/pico8/femto8/src/p8_audio.h | 32 + components/pico8/femto8/src/p8_browse.c | 322 + components/pico8/femto8/src/p8_browse.h | 12 + components/pico8/femto8/src/p8_cstore.c | 119 + components/pico8/femto8/src/p8_cstore.h | 8 + components/pico8/femto8/src/p8_dialog.c | 773 ++ components/pico8/femto8/src/p8_dialog.h | 392 + components/pico8/femto8/src/p8_dsp.c | 134 + components/pico8/femto8/src/p8_dsp.h | 23 + components/pico8/femto8/src/p8_emu.c | 1193 +++ components/pico8/femto8/src/p8_emu.h | 308 + components/pico8/femto8/src/p8_input.c | 506 ++ components/pico8/femto8/src/p8_input.h | 101 + components/pico8/femto8/src/p8_lua.c | 2750 +++++++ components/pico8/femto8/src/p8_lua.h | 27 + components/pico8/femto8/src/p8_lua_helper.h | 759 ++ components/pico8/femto8/src/p8_options.c | 77 + components/pico8/femto8/src/p8_options.h | 13 + .../pico8/femto8/src/p8_overlay_helper.h | 271 + components/pico8/femto8/src/p8_parser.c | 678 ++ components/pico8/femto8/src/p8_parser.h | 17 + components/pico8/femto8/src/p8_pause_menu.c | 200 + components/pico8/femto8/src/p8_pause_menu.h | 50 + components/pico8/femto8/src/p8_print_helper.h | 646 ++ components/pico8/femto8/src/queue.c | 139 + components/pico8/femto8/src/queue.h | 25 + components/pico8/femto8/src/strtcpy.c | 30 + components/pico8/femto8/src/strtcpy.h | 20 + components/pico8/include/pico8.hpp | 27 + components/pico8/linker.lf | 23 + components/pico8/src/pico8.cpp | 390 + components/pico8/src/platform/p8_espbox.h | 25 + components/rom_info/include/rom_info.hpp | 4 +- components/rom_info/src/rom_info.cpp | 4 + main/carts.hpp | 8 + main/pico8_cart.hpp | 130 + 111 files changed, 42597 insertions(+), 2 deletions(-) create mode 100644 components/pico8/CMakeLists.txt create mode 100644 components/pico8/VENDOR.md create mode 100644 components/pico8/femto8/LICENSE create mode 100644 components/pico8/femto8/README.md create mode 100644 components/pico8/femto8/src/data/lua_api.h create mode 100644 components/pico8/femto8/src/data/p8_symbols.h create mode 100644 components/pico8/femto8/src/data/pico_font.h create mode 100644 components/pico8/femto8/src/lexaloffle/p8_compress.c create mode 100644 components/pico8/femto8/src/lexaloffle/pico8.h create mode 100644 components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c create mode 100644 components/pico8/femto8/src/lodepng/LICENSE create mode 100644 components/pico8/femto8/src/lodepng/lodepng.c create mode 100644 components/pico8/femto8/src/lodepng/lodepng.h create mode 100644 components/pico8/femto8/src/lua/.gitignore create mode 100644 components/pico8/femto8/src/lua/fix32.h create mode 100644 components/pico8/femto8/src/lua/lapi.c create mode 100644 components/pico8/femto8/src/lua/lapi.h create mode 100644 components/pico8/femto8/src/lua/lauxlib.c create mode 100644 components/pico8/femto8/src/lua/lauxlib.h create mode 100644 components/pico8/femto8/src/lua/lbaselib.c create mode 100644 components/pico8/femto8/src/lua/lcode.c create mode 100644 components/pico8/femto8/src/lua/lcode.h create mode 100644 components/pico8/femto8/src/lua/lcorolib.c create mode 100644 components/pico8/femto8/src/lua/lctype.c create mode 100644 components/pico8/femto8/src/lua/lctype.h create mode 100644 components/pico8/femto8/src/lua/ldblib.c create mode 100644 components/pico8/femto8/src/lua/ldebug.c create mode 100644 components/pico8/femto8/src/lua/ldebug.h create mode 100644 components/pico8/femto8/src/lua/ldo.c create mode 100644 components/pico8/femto8/src/lua/ldo.h create mode 100644 components/pico8/femto8/src/lua/ldump.c create mode 100644 components/pico8/femto8/src/lua/lfunc.c create mode 100644 components/pico8/femto8/src/lua/lfunc.h create mode 100644 components/pico8/femto8/src/lua/lgc.c create mode 100644 components/pico8/femto8/src/lua/lgc.h create mode 100644 components/pico8/femto8/src/lua/linit.c create mode 100644 components/pico8/femto8/src/lua/llex.c create mode 100644 components/pico8/femto8/src/lua/llex.h create mode 100644 components/pico8/femto8/src/lua/llimits.h create mode 100644 components/pico8/femto8/src/lua/lmem.c create mode 100644 components/pico8/femto8/src/lua/lmem.h create mode 100644 components/pico8/femto8/src/lua/loadlib.c create mode 100644 components/pico8/femto8/src/lua/lobject.c create mode 100644 components/pico8/femto8/src/lua/lobject.h create mode 100644 components/pico8/femto8/src/lua/lopcodes.c create mode 100644 components/pico8/femto8/src/lua/lopcodes.h create mode 100644 components/pico8/femto8/src/lua/lparser.c create mode 100644 components/pico8/femto8/src/lua/lparser.h create mode 100644 components/pico8/femto8/src/lua/lpico8lib.c create mode 100644 components/pico8/femto8/src/lua/lstate.c create mode 100644 components/pico8/femto8/src/lua/lstate.h create mode 100644 components/pico8/femto8/src/lua/lstring.c create mode 100644 components/pico8/femto8/src/lua/lstring.h create mode 100644 components/pico8/femto8/src/lua/lstrlib.c create mode 100644 components/pico8/femto8/src/lua/ltable.c create mode 100644 components/pico8/femto8/src/lua/ltable.h create mode 100644 components/pico8/femto8/src/lua/ltablib.c create mode 100644 components/pico8/femto8/src/lua/ltests.c create mode 100644 components/pico8/femto8/src/lua/ltests.h create mode 100644 components/pico8/femto8/src/lua/ltm.c create mode 100644 components/pico8/femto8/src/lua/ltm.h create mode 100644 components/pico8/femto8/src/lua/lua.h create mode 100644 components/pico8/femto8/src/lua/luaconf.h create mode 100644 components/pico8/femto8/src/lua/lualib.h create mode 100644 components/pico8/femto8/src/lua/lundump.c create mode 100644 components/pico8/femto8/src/lua/lundump.h create mode 100644 components/pico8/femto8/src/lua/lvm.c create mode 100644 components/pico8/femto8/src/lua/lvm.h create mode 100644 components/pico8/femto8/src/lua/lzio.c create mode 100644 components/pico8/femto8/src/lua/lzio.h create mode 100644 components/pico8/femto8/src/lua/makefile create mode 100644 components/pico8/femto8/src/lua/trigtables.h create mode 100644 components/pico8/femto8/src/p8_audio.c create mode 100644 components/pico8/femto8/src/p8_audio.h create mode 100644 components/pico8/femto8/src/p8_browse.c create mode 100644 components/pico8/femto8/src/p8_browse.h create mode 100644 components/pico8/femto8/src/p8_cstore.c create mode 100644 components/pico8/femto8/src/p8_cstore.h create mode 100644 components/pico8/femto8/src/p8_dialog.c create mode 100644 components/pico8/femto8/src/p8_dialog.h create mode 100644 components/pico8/femto8/src/p8_dsp.c create mode 100644 components/pico8/femto8/src/p8_dsp.h create mode 100644 components/pico8/femto8/src/p8_emu.c create mode 100644 components/pico8/femto8/src/p8_emu.h create mode 100644 components/pico8/femto8/src/p8_input.c create mode 100644 components/pico8/femto8/src/p8_input.h create mode 100644 components/pico8/femto8/src/p8_lua.c create mode 100644 components/pico8/femto8/src/p8_lua.h create mode 100644 components/pico8/femto8/src/p8_lua_helper.h create mode 100644 components/pico8/femto8/src/p8_options.c create mode 100644 components/pico8/femto8/src/p8_options.h create mode 100644 components/pico8/femto8/src/p8_overlay_helper.h create mode 100644 components/pico8/femto8/src/p8_parser.c create mode 100644 components/pico8/femto8/src/p8_parser.h create mode 100644 components/pico8/femto8/src/p8_pause_menu.c create mode 100644 components/pico8/femto8/src/p8_pause_menu.h create mode 100644 components/pico8/femto8/src/p8_print_helper.h create mode 100644 components/pico8/femto8/src/queue.c create mode 100644 components/pico8/femto8/src/queue.h create mode 100644 components/pico8/femto8/src/strtcpy.c create mode 100644 components/pico8/femto8/src/strtcpy.h create mode 100644 components/pico8/include/pico8.hpp create mode 100644 components/pico8/linker.lf create mode 100644 components/pico8/src/pico8.cpp create mode 100644 components/pico8/src/platform/p8_espbox.h create mode 100644 main/pico8_cart.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e884187..739c282c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -33,6 +33,9 @@ set(DOOM_COMPONENTS "doom") ### DARK FORCES ### set(DARKFORCES_COMPONENTS "darkforces") +### PICO-8 ### +set(PICO8_COMPONENTS "pico8") + ### SNES ### # set(SNES_COMPONENTS "snes") @@ -78,6 +81,11 @@ if(DARKFORCES_COMPONENTS) add_compile_definitions(ENABLE_DARKFORCES) endif() +# if PICO8_COMPONENTS is set, add compile definitions for PICO-8 +if(PICO8_COMPONENTS) + add_compile_definitions(ENABLE_PICO8) +endif() + # make the components list for the emulators we want set(EMULATOR_COMPONENTS ${NES_COMPONENTS} @@ -88,6 +96,7 @@ set(EMULATOR_COMPONENTS ${GENESIS_COMPONENTS} ${DOOM_COMPONENTS} ${DARKFORCES_COMPONENTS} + ${PICO8_COMPONENTS} ) set( diff --git a/README.md b/README.md index a3251b34..c9f207d5 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ that removes the frame-rate cap for maximum speed. | MSX 1 / 2 | [fmsx](https://fms.komkon.org/fMSX/) | β€” | D-Pad / A / B / Start / Select | | Doom | [prboom](https://prboom.sourceforge.net/) | β€” | Full speed with audio **and haptic feedback** | | Dark Forces | [The Force Engine](https://theforceengine.github.io/) (via [BSzili's Amiga port](https://github.com/BSzili/TheForceEngine/tree/amiga)) | β€” | Software renderer, iMuse sound effects and OPL3 music; see [Dark Forces setup](#dark-forces-setup) | +| PICO-8 | [femto8](https://github.com/benbaker76/femto8) | β€” | `.p8` and `.p8.png` carts; D-Pad, A/Y = O, B/X = X, START = PICO-8 pause menu; cartdata saves to `pico8/cdata/`; see [PICO-8 setup](#pico-8-setup) | > 🧬 **Full-speed Genesis on the S3.** The Genesis core ships with a custom > **dual-core** modification of gwenesis that spreads the workload across both of @@ -252,6 +253,19 @@ darkforces/DARK.GOB, boxart/darkforces.jpg, Star Wars: Dark Forces Settings (`settings.ini`) and agent / save files are written to the same folder. +### PICO-8 setup + +PICO-8 carts are plain `.p8` text files or `.p8.png` cartridge images. Put them +in a folder on the card (for example `pico8/`) and reference them from +`metadata.csv`: + +```csv +pico8/celeste.p8, boxart/celeste.jpg, Celeste Classic +``` + +Carts that use `cartdata()` save to `pico8/cdata/`. The 128x128 screen shows +1:1 in the "original" video mode and scaled to 240x240 in "fit". + ### metadata.csv format Each line maps a ROM to its boxart and display name: @@ -283,7 +297,7 @@ A checklist of what's implemented and what's still in progress. **Emulation** -- [x] Auto-select emulator by ROM extension: NES, GB/GBC, SMS/GG, MSX, Genesis, Doom, Dark Forces +- [x] Auto-select emulator by ROM extension: NES, GB/GBC, SMS/GG, MSX, Genesis, Doom, Dark Forces, PICO-8 - [x] On-demand core loading β€” every emulator and game loads at runtime with no reboot needed to switch games or systems - [x] Custom **dual-core Genesis** (gwenesis): 68000 + VDP on one ESP32-S3 core, sound unit (Z80 + YM2612 + PSG) on the other, for full-speed audio and gameplay - [x] Doom haptic feedback :rocket: diff --git a/components/pico8/CMakeLists.txt b/components/pico8/CMakeLists.txt new file mode 100644 index 00000000..6ae9ccea --- /dev/null +++ b/components/pico8/CMakeLists.txt @@ -0,0 +1,25 @@ +# PICO-8 for esp-box-emu, hosting femto8 (see VENDOR.md). +# COMPONENT_DIR, not CMAKE_CURRENT_SOURCE_DIR: IDF also evaluates this file in +# its early requirements pass, from the build directory. +set(F8 ${COMPONENT_DIR}/femto8/src) + +file(GLOB SRC_FEMTO8 ${F8}/*.c ${F8}/lua/*.c ${F8}/lodepng/*.c ${F8}/lexaloffle/*.c) + +idf_component_register( + INCLUDE_DIRS "include" + SRCS src/pico8.cpp ${SRC_FEMTO8} + PRIV_INCLUDE_DIRS "src/platform" ${F8} ${F8}/data ${F8}/lua ${F8}/lodepng ${F8}/lexaloffle + REQUIRES box-emu statistics esp_timer heap pthread + LDFRAGMENTS "linker.lf" + ) + +# Where carts keep their cartdata() saves (femto8 defaults to a relative "cdata") +target_compile_definitions(${COMPONENT_LIB} PRIVATE + FEMTO8_ESPBOX=1 + CARTDATA_PATH="/sdcard/pico8/cdata" + DEFAULT_CARTS_PATH="/sdcard/pico8") + +target_compile_options(${COMPONENT_LIB} PRIVATE + -O2 + -Wno-error + -w) diff --git a/components/pico8/VENDOR.md b/components/pico8/VENDOR.md new file mode 100644 index 00000000..74d71c73 --- /dev/null +++ b/components/pico8/VENDOR.md @@ -0,0 +1,35 @@ +# Vendored sources + +`femto8/` is **femto8**, Ben Baker's PICO-8 reimplementation for embedded +systems (C, a fixed-point Lua 5.x fork, lodepng for `.p8.png` carts and the +Lexaloffle `.p8.png` code decompressor). + +- Upstream: https://github.com/benbaker76/femto8 (MIT, `femto8/LICENSE`) +- Commit: `f9e5097c882d0c9203616689f3de5531e0597c43` +- Bundled: `src/lua` (Lua, MIT), `src/lodepng` (zlib, `lodepng/LICENSE`), + `src/lexaloffle` (Lexaloffle Games, zlib-style notice in the files) + +Everything under `femto8/src/` except `main.c` (the desktop/SDL entry point). + +## Changes made for esp-box-emu + +A third platform, `FEMTO8_ESPBOX`, next to upstream's SDL and Renesas +DA1470x (`__DA1470x__`) targets. The emulator supplies video, audio and input +through `src/platform/p8_espbox.h`, implemented in `src/pico8.cpp`: + +- `p8_emu.h`: `FEMTO8_ESPBOX` selects `OS_FREERTOS` (FreeRTOS clock/sleep) + and `ENABLE_AUDIO`; the DA1470x heap redirection no longer applies to every + FreeRTOS target. +- `p8_emu.c`: FreeRTOS headers from `freertos/`; the generic renderer (the one + the SDL build uses, with the screen transforms and high-colour modes) also + serves the box, writing 5-bit palette indices into a frame the emulator + provides (`p8_espbox_frame_begin/end`) instead of ARGB pixels; no on-screen + fps counter; the LCD controller and DA1470x renderer are guarded. +- `p8_input.c`: buttons come from `p8_espbox_buttons()`; `p8_pump_events()` + (femto8's Lua instruction hook) calls `p8_espbox_pump()`, where the emulator + menu pauses the cart and a quit from the menu unwinds it through `p8_quit()`. +- `linker.lf`: femto8's statics go to PSRAM and are bracketed by SURROUND + symbols so `src/pico8.cpp` can reset them between launches (femto8 was + written to run once per process). +- `CARTDATA_PATH` / `DEFAULT_CARTS_PATH` are set to `/sdcard/pico8/...` at + build time. diff --git a/components/pico8/femto8/LICENSE b/components/pico8/femto8/LICENSE new file mode 100644 index 00000000..a30963ea --- /dev/null +++ b/components/pico8/femto8/LICENSE @@ -0,0 +1,7 @@ +Copyright 2023 Ben Baker + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the β€œSoftware”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED β€œAS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/components/pico8/femto8/README.md b/components/pico8/femto8/README.md new file mode 100644 index 00000000..883a2c35 --- /dev/null +++ b/components/pico8/femto8/README.md @@ -0,0 +1,40 @@ +# femto8 + +femto8 is an open-source reimplementation of the [PICO-8](https://www.lexaloffle.com/pico-8.php) fantasy console, designed specifically for embedded systems with smaller CPUs and less memory. It provides a platform to play PICO-8 games on devices with resource constraints, making it ideal for environments with limited hardware capabilities. + +## Acknowledgment + +This project has been significantly influenced by the work of [Jacopo Santoni](https://github.com/Jakz) on [retro8](https://github.com/Jakz/retro8), a PICO-8 emulator designed for desktop platforms. We would like to express our gratitude to Jacopo Santoni for his contributions and efforts on retro8, which has been an invaluable resource for the development of femto8. + +## Key Features + +- Written in C for optimal performance on embedded systems. +- Compact and resource-efficient design, suitable for devices with smaller CPUs and limited memory. + +## Screenshots + +![](/images/screenshot1.png) + +![](/images/screenshot2.png) + +![](/images/screenshot3.png) + +## Building + +To build femto8 (desktop): + +1. Clone the repository: `git clone https://github.com/benbaker76/femto8.git` +2. Navigate to the femto8 directory: `cd femto8` +3. Install SDL2 development files for your platform: + - Debian/Ubuntu: `sudo apt install libsdl2-dev pkg-config` + - Fedora: `sudo dnf install SDL2-devel pkgconfig` + - macOS (Homebrew): `brew install sdl2 pkg-config` + - MSYS2 (Windows): install `mingw-w64-*-SDL2` and `pkgconf` via pacman +4. Build a local binary: `make` + +## Credits + +- [benbaker76](https://github.com/benbaker76) - Author and maintainer of [femto8](https://github.com/benbaker76/femto8) +- [Jacopo Santoni](https://github.com/Jakz) - Author of [retro8](https://github.com/Jakz/retro8) +- [Lexaloffle](https://www.lexaloffle.com/) - Creator of PICO-8 +- [atomice1](https://github.com/atomice1) - For updates and improvements diff --git a/components/pico8/femto8/src/data/lua_api.h b/components/pico8/femto8/src/data/lua_api.h new file mode 100644 index 00000000..c311ca32 --- /dev/null +++ b/components/pico8/femto8/src/data/lua_api.h @@ -0,0 +1,131 @@ +#ifndef LUA_API_H +#define LUA_API_H + +const char *lua_api_string = + "function all(t)\n" + " if t == nil then\n" + " return function() end\n" + " end\n" + " local ttype = type(t)\n" + " if ttype == 'string' then\n" + " local i = 0\n" + " local tlen = #t\n" + " return function()\n" + " i = i + 1\n" + " if i <= tlen then\n" + " return sub(t, i, i)\n" + " end\n" + " end\n" + " else\n" + " local i = 0\n" + " local r = nil\n" + " return function()\n" + " if t[i] == r then\n" + " i = i + 1\n" + " end\n" + " while i <= #t and t[i] == nil do\n" + " i = i + 1\n" + " end\n" + " r = t[i]\n" + " return r\n" + " end\n" + " end\n" + "end\n" + "\n" + "function add(t, v, i)\n" + " if type(t) == 'table' then\n" + " if i == nil then\n" + " t[#t+1] = v\n" + " else\n" + " for j = #t, i, -1 do\n" + " t[j+1] = t[j]\n" + " end\n" + " t[i] = v\n" + " end\n" + " return v\n" + " end\n" + "end\n" + "\n" + "function foreach(c, f)\n" + " if c ~= nil then\n" + " for value in all(c) do\n" + " f(value)\n" + " end\n" + " end\n" + "end\n" + "\n" + "\n" + "function mapdraw(...)\n" + " map(table.unpack(arg))\n" + "end\n" + "\n" + "function count(t, v)\n" + " if type(t) ~= 'table' then\n" + " return nil\n" + " end\n" + " if v == nil then\n" + " return #t\n" + " end\n" + " local c = 0\n" + " for i = 1, #t do\n" + " if t[i] == v then\n" + " c = c + 1\n" + " end\n" + " end\n" + " return c\n" + "end\n" + "\n" + "function del(t, v)\n" + " if type(t) == 'table' then\n" + " local found = false\n" + " for i = 1, #t do\n" + " if t[i] == v then\n" + " found = true\n" + " end\n" + " if found then\n" + " t[i] = t[i+1]\n" + " end\n" + " end\n" + " if found then\n" + " return v\n" + " end\n" + " end\n" + "end\n" + "\n" + "function deli(t, i)\n" + " if type(t) == 'table' then\n" + " if i == nil then\n" + " i = #t\n" + " end\n" + " if i < 1 or i > #t then\n" + " return nil\n" + " end\n" + " local v = t[i]\n" + " for j = i, #t do\n" + " t[j] = t[j+1]\n" + " end\n" + " return v\n" + " end\n" + "end\n" + "\n" + "function cocreate(f)\n" + " return coroutine.create(f)\n" + "end\n" + "\n" + "function yield()\n" + " coroutine.yield()\n" + "end\n" + "\n" + "function coresume(f, ...)\n" + " return coroutine.resume(f, ...)\n" + "end\n" + "\n" + "function costatus(f)\n" + " return coroutine.status(f)\n" + "end\n" + "\n" + "function pack(...)\n" + " return {n=select('#',...), ...}\n" + "end"; + +#endif diff --git a/components/pico8/femto8/src/data/p8_symbols.h b/components/pico8/femto8/src/data/p8_symbols.h new file mode 100644 index 00000000..41030fbe --- /dev/null +++ b/components/pico8/femto8/src/data/p8_symbols.h @@ -0,0 +1,174 @@ +#ifndef P8_SYMBOLS_H +#define P8_SYMBOLS_H + +#include + +typedef struct +{ + uint8_t encoding[7]; + uint8_t length; + uint8_t index; +} p8_symbol_t; + +static const p8_symbol_t p8_symbols[] = { + {{0x5c, 0x30}, 2, 0}, + {{0xc2, 0xb9}, 2, 1}, + {{0xc2, 0xb2}, 2, 2}, + {{0xc2, 0xb3}, 2, 3}, + {{0xe2, 0x81, 0xb4}, 3, 4}, + {{0xe2, 0x81, 0xb5}, 3, 5}, + {{0xe2, 0x81, 0xb6}, 3, 6}, + {{0xe2, 0x81, 0xb7}, 3, 7}, + {{0xe2, 0x81, 0xb8}, 3, 8}, + {{0xe1, 0xb5, 0x87}, 3, 11}, + {{0xe1, 0xb6, 0x9c}, 3, 12}, + {{0xe1, 0xb5, 0x89}, 3, 14}, + {{0xe1, 0xb6, 0xa0}, 3, 15}, + {{0xe2, 0x96, 0xae}, 3, 16}, + {{0xe2, 0x96, 0xa0}, 3, 17}, + {{0xe2, 0x96, 0xa1}, 3, 18}, + {{0xe2, 0x81, 0x99}, 3, 19}, + {{0xe2, 0x81, 0x98}, 3, 20}, + {{0xe2, 0x80, 0x96}, 3, 21}, + {{0xe2, 0x97, 0x80}, 3, 22}, + {{0xe2, 0x96, 0xb6}, 3, 23}, + {{0xe3, 0x80, 0x8c}, 3, 24}, + {{0xe3, 0x80, 0x8d}, 3, 25}, + {{0xc2, 0xa5}, 2, 26}, + {{0xe2, 0x80, 0xa2}, 3, 27}, + {{0xe3, 0x80, 0x81}, 3, 28}, + {{0xe3, 0x80, 0x82}, 3, 29}, + {{0xe3, 0x82, 0x9b}, 3, 30}, + {{0xe3, 0x82, 0x9c}, 3, 31}, + {{0xe2, 0x97, 0x8b}, 3, 127}, + {{0xe2, 0x96, 0x88}, 3, 128}, + {{0xe2, 0x96, 0x92}, 3, 129}, + {{0xf0, 0x9f, 0x90, 0xb1}, 4, 130}, + {{0xe2, 0xac, 0x87, 0xef, 0xb8, 0x8f}, 6, 131}, + {{0xe2, 0x96, 0x91}, 3, 132}, + {{0xe2, 0x9c, 0xbd}, 3, 133}, + {{0xe2, 0x97, 0x8f}, 3, 134}, + {{0xe2, 0x99, 0xa5}, 3, 135}, + {{0xe2, 0x98, 0x89}, 3, 136}, + {{0xec, 0x9b, 0x83}, 3, 137}, + {{0xe2, 0x8c, 0x82}, 3, 138}, + {{0xe2, 0xac, 0x85, 0xef, 0xb8, 0x8f}, 6, 139}, + {{0xf0, 0x9f, 0x98, 0x90}, 4, 140}, + {{0xe2, 0x99, 0xaa}, 3, 141}, + {{0xf0, 0x9f, 0x85, 0xbe, 0xef, 0xb8, 0x8f}, 7, 142}, + {{0xe2, 0x97, 0x86}, 3, 143}, + {{0xe2, 0x80, 0xa6}, 3, 144}, + {{0xe2, 0x9e, 0xa1, 0xef, 0xb8, 0x8f}, 6, 145}, + {{0xe2, 0x98, 0x85}, 3, 146}, + {{0xe2, 0xa7, 0x97}, 3, 147}, + {{0xe2, 0xac, 0x86, 0xef, 0xb8, 0x8f}, 6, 148}, + {{0xcb, 0x87}, 2, 149}, + {{0xe2, 0x88, 0xa7}, 3, 150}, + {{0xe2, 0x9d, 0x8e}, 3, 151}, + {{0xe2, 0x96, 0xa4}, 3, 152}, + {{0xe2, 0x96, 0xa5}, 3, 153}, + {{0xe3, 0x81, 0x82}, 3, 154}, + {{0xe3, 0x81, 0x84}, 3, 155}, + {{0xe3, 0x81, 0x86}, 3, 156}, + {{0xe3, 0x81, 0x88}, 3, 157}, + {{0xe3, 0x81, 0x8a}, 3, 158}, + {{0xe3, 0x81, 0x8b}, 3, 159}, + {{0xe3, 0x81, 0x8d}, 3, 160}, + {{0xe3, 0x81, 0x8f}, 3, 161}, + {{0xe3, 0x81, 0x91}, 3, 162}, + {{0xe3, 0x81, 0x93}, 3, 163}, + {{0xe3, 0x81, 0x95}, 3, 164}, + {{0xe3, 0x81, 0x97}, 3, 165}, + {{0xe3, 0x81, 0x99}, 3, 166}, + {{0xe3, 0x81, 0x9b}, 3, 167}, + {{0xe3, 0x81, 0x9d}, 3, 168}, + {{0xe3, 0x81, 0x9f}, 3, 169}, + {{0xe3, 0x81, 0xa1}, 3, 170}, + {{0xe3, 0x81, 0xa4}, 3, 171}, + {{0xe3, 0x81, 0xa6}, 3, 172}, + {{0xe3, 0x81, 0xa8}, 3, 173}, + {{0xe3, 0x81, 0xaa}, 3, 174}, + {{0xe3, 0x81, 0xab}, 3, 175}, + {{0xe3, 0x81, 0xac}, 3, 176}, + {{0xe3, 0x81, 0xad}, 3, 177}, + {{0xe3, 0x81, 0xae}, 3, 178}, + {{0xe3, 0x81, 0xaf}, 3, 179}, + {{0xe3, 0x81, 0xb2}, 3, 180}, + {{0xe3, 0x81, 0xb5}, 3, 181}, + {{0xe3, 0x81, 0xb8}, 3, 182}, + {{0xe3, 0x81, 0xbb}, 3, 183}, + {{0xe3, 0x81, 0xbe}, 3, 184}, + {{0xe3, 0x81, 0xbf}, 3, 185}, + {{0xe3, 0x82, 0x80}, 3, 186}, + {{0xe3, 0x82, 0x81}, 3, 187}, + {{0xe3, 0x82, 0x82}, 3, 188}, + {{0xe3, 0x82, 0x84}, 3, 189}, + {{0xe3, 0x82, 0x86}, 3, 190}, + {{0xe3, 0x82, 0x88}, 3, 191}, + {{0xe3, 0x82, 0x89}, 3, 192}, + {{0xe3, 0x82, 0x8a}, 3, 193}, + {{0xe3, 0x82, 0x8b}, 3, 194}, + {{0xe3, 0x82, 0x8c}, 3, 195}, + {{0xe3, 0x82, 0x8d}, 3, 196}, + {{0xe3, 0x82, 0x8f}, 3, 197}, + {{0xe3, 0x82, 0x92}, 3, 198}, + {{0xe3, 0x82, 0x93}, 3, 199}, + {{0xe3, 0x81, 0xa3}, 3, 200}, + {{0xe3, 0x82, 0x83}, 3, 201}, + {{0xe3, 0x82, 0x85}, 3, 202}, + {{0xe3, 0x82, 0x87}, 3, 203}, + {{0xe3, 0x82, 0xa2}, 3, 204}, + {{0xe3, 0x82, 0xa4}, 3, 205}, + {{0xe3, 0x82, 0xa6}, 3, 206}, + {{0xe3, 0x82, 0xa8}, 3, 207}, + {{0xe3, 0x82, 0xaa}, 3, 208}, + {{0xe3, 0x82, 0xab}, 3, 209}, + {{0xe3, 0x82, 0xad}, 3, 210}, + {{0xe3, 0x82, 0xaf}, 3, 211}, + {{0xe3, 0x82, 0xb1}, 3, 212}, + {{0xe3, 0x82, 0xb3}, 3, 213}, + {{0xe3, 0x82, 0xb5}, 3, 214}, + {{0xe3, 0x82, 0xb7}, 3, 215}, + {{0xe3, 0x82, 0xb9}, 3, 216}, + {{0xe3, 0x82, 0xbb}, 3, 217}, + {{0xe3, 0x82, 0xbd}, 3, 218}, + {{0xe3, 0x82, 0xbf}, 3, 219}, + {{0xe3, 0x83, 0x81}, 3, 220}, + {{0xe3, 0x83, 0x84}, 3, 221}, + {{0xe3, 0x83, 0x86}, 3, 222}, + {{0xe3, 0x83, 0x88}, 3, 223}, + {{0xe3, 0x83, 0x8a}, 3, 224}, + {{0xe3, 0x83, 0x8b}, 3, 225}, + {{0xe3, 0x83, 0x8c}, 3, 226}, + {{0xe3, 0x83, 0x8d}, 3, 227}, + {{0xe3, 0x83, 0x8e}, 3, 228}, + {{0xe3, 0x83, 0x8f}, 3, 229}, + {{0xe3, 0x83, 0x92}, 3, 230}, + {{0xe3, 0x83, 0x95}, 3, 231}, + {{0xe3, 0x83, 0x98}, 3, 232}, + {{0xe3, 0x83, 0x9b}, 3, 233}, + {{0xe3, 0x83, 0x9e}, 3, 234}, + {{0xe3, 0x83, 0x9f}, 3, 235}, + {{0xe3, 0x83, 0xa0}, 3, 236}, + {{0xe3, 0x83, 0xa1}, 3, 237}, + {{0xe3, 0x83, 0xa2}, 3, 238}, + {{0xe3, 0x83, 0xa4}, 3, 239}, + {{0xe3, 0x83, 0xa6}, 3, 240}, + {{0xe3, 0x83, 0xa8}, 3, 241}, + {{0xe3, 0x83, 0xa9}, 3, 242}, + {{0xe3, 0x83, 0xaa}, 3, 243}, + {{0xe3, 0x83, 0xab}, 3, 244}, + {{0xe3, 0x83, 0xac}, 3, 245}, + {{0xe3, 0x83, 0xad}, 3, 246}, + {{0xe3, 0x83, 0xaf}, 3, 247}, + {{0xe3, 0x83, 0xb2}, 3, 248}, + {{0xe3, 0x83, 0xb3}, 3, 249}, + {{0xe3, 0x83, 0x83}, 3, 250}, + {{0xe3, 0x83, 0xa3}, 3, 251}, + {{0xe3, 0x83, 0xa5}, 3, 252}, + {{0xe3, 0x83, 0xa7}, 3, 253}, + {{0xe2, 0x97, 0x9c}, 3, 254}, + {{0xe2, 0x97, 0x9d}, 3, 255}, +}; + +#endif diff --git a/components/pico8/femto8/src/data/pico_font.h b/components/pico8/femto8/src/data/pico_font.h new file mode 100644 index 00000000..aeb41924 --- /dev/null +++ b/components/pico8/femto8/src/data/pico_font.h @@ -0,0 +1,137 @@ +#ifndef PICO_FONT_H +#define PICO_FONT_H + +#include + +static const uint8_t font_map[] = { + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00, + 0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00, + 0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00, + 0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00, + 0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00, + 0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00, + 0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x07,0x00,0x00, + 0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x07,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x00, + 0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00, + 0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00, + 0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x00,0x00,0x00, + 0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x07,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x00, + 0x00,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00, + 0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00, + 0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00, + 0x00,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00, + 0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00, + 0x07,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00, + 0x07,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x07,0x00,0x00,0x07,0x70,0x77,0x77,0x00,0x07,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x07,0x00,0x70,0x07,0x77,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x07,0x00,0x70,0x77,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00, + 0x77,0x77,0x77,0x07,0x70,0x70,0x70,0x00,0x77,0x77,0x77,0x07,0x77,0x00,0x70,0x07,0x00,0x07,0x00,0x07,0x00,0x77,0x77,0x00,0x70,0x77,0x70,0x00,0x70,0x77,0x77,0x00,0x70,0x07,0x77,0x00,0x00,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x77,0x07,0x70,0x07,0x07,0x77,0x07,0x07,0x00,0x70,0x00,0x00,0x77,0x00,0x70,0x07,0x00,0x77,0x07,0x00, + 0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x07,0x77,0x07,0x07,0x77,0x00,0x70,0x07,0x07,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x77,0x07,0x77,0x07,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x07,0x77,0x00,0x70,0x07,0x77,0x77,0x77,0x07,0x00,0x70,0x00,0x00,0x77,0x70,0x70,0x07,0x70,0x77,0x77,0x00, + 0x77,0x77,0x77,0x07,0x70,0x70,0x70,0x00,0x07,0x77,0x07,0x07,0x77,0x07,0x77,0x07,0x00,0x07,0x00,0x07,0x70,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x07,0x00,0x70,0x07,0x77,0x00,0x00,0x77,0x07,0x00,0x70,0x70,0x70,0x00,0x77,0x07,0x70,0x07,0x07,0x00,0x00,0x07,0x70,0x77,0x00,0x00,0x77,0x00,0x70,0x07,0x00,0x77,0x07,0x00, + 0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x07,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x70,0x70,0x77,0x00,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x07,0x70,0x77,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x70,0x77,0x00,0x00,0x07,0x00,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x00,0x07,0x70,0x00,0x70,0x00, + 0x00,0x00,0x00,0x00,0x77,0x00,0x77,0x07,0x00,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x77,0x07,0x77,0x07,0x07,0x07,0x00,0x00,0x07,0x00,0x07,0x00,0x77,0x70,0x70,0x07,0x00,0x00,0x00,0x00,0x07,0x07,0x07,0x07,0x00,0x07,0x00,0x00,0x07,0x00,0x70,0x00,0x70,0x77,0x07,0x00,0x70,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x77,0x77,0x07,0x07, + 0x07,0x07,0x07,0x07,0x77,0x00,0x70,0x07,0x77,0x77,0x77,0x07,0x00,0x70,0x00,0x00,0x77,0x00,0x70,0x07,0x70,0x00,0x07,0x07,0x70,0x70,0x70,0x00,0x77,0x07,0x77,0x07,0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x70,0x77,0x07,0x00,0x07,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x00,0x07,0x00, + 0x00,0x00,0x00,0x00,0x77,0x00,0x77,0x07,0x70,0x77,0x77,0x00,0x00,0x77,0x07,0x00,0x77,0x00,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x07,0x00,0x07,0x77,0x70,0x70,0x07,0x00,0x00,0x00,0x00,0x07,0x07,0x07,0x07,0x07,0x77,0x70,0x00,0x07,0x07,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x70,0x00,0x07,0x07,0x00,0x07,0x70,0x00,0x07,0x00, + 0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x07,0x07,0x07,0x07,0x07,0x70,0x07,0x70,0x00,0x70,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x70,0x70,0x07,0x00,0x70,0x07,0x70,0x00,0x70,0x70,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x70,0x77,0x07,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x70,0x00,0x70,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x07,0x00,0x00,0x77,0x77,0x00,0x70,0x00,0x00,0x00,0x77,0x77,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x77,0x00,0x70,0x70,0x77,0x07, + 0x00,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x70,0x70,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x77,0x77,0x00,0x70,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x77,0x77,0x77,0x00,0x00,0x00,0x07,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x07, + 0x00,0x77,0x77,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x07,0x00,0x70,0x77,0x77,0x07,0x70,0x00,0x77,0x00,0x70,0x77,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x07,0x00,0x70,0x00,0x00,0x00, + 0x07,0x00,0x07,0x00,0x00,0x77,0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x00,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x77,0x07,0x70,0x70,0x00,0x00, + 0x70,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x07,0x00,0x00,0x77,0x77,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x77,0x00,0x70,0x00,0x77,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x77,0x00,0x00,0x70,0x07,0x00,0x70,0x00,0x77,0x07, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x07,0x70,0x00,0x00,0x70,0x70,0x07,0x00,0x00,0x77,0x77,0x00,0x70,0x00,0x07,0x00,0x77,0x00,0x70,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x77,0x77,0x07,0x70,0x77,0x77,0x00,0x70,0x07,0x00,0x00,0x00,0x07,0x70,0x00,0x70,0x70,0x00,0x00,0x70,0x77,0x07,0x00,0x00,0x07,0x07,0x00,0x70,0x70,0x77,0x00,0x00,0x07,0x00,0x00, + 0x70,0x77,0x77,0x00,0x77,0x07,0x70,0x00,0x70,0x70,0x00,0x07,0x70,0x70,0x77,0x00,0x70,0x00,0x70,0x07,0x00,0x00,0x00,0x00,0x00,0x77,0x00,0x00,0x07,0x70,0x77,0x07,0x00,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x70,0x77,0x00,0x07,0x00,0x77,0x77,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x07,0x07,0x07,0x00,0x77,0x07,0x00, + 0x77,0x70,0x00,0x07,0x70,0x00,0x70,0x00,0x07,0x70,0x00,0x07,0x70,0x00,0x07,0x00,0x70,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x07,0x00,0x07,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x07,0x00,0x07,0x00,0x00,0x70,0x70,0x07,0x07,0x70,0x77,0x07,0x00,0x00,0x07,0x70,0x00,0x70,0x00,0x07,0x07,0x00,0x07,0x00,0x00, + 0x07,0x77,0x70,0x07,0x77,0x00,0x77,0x07,0x07,0x70,0x00,0x07,0x70,0x70,0x77,0x00,0x70,0x00,0x70,0x00,0x70,0x70,0x70,0x00,0x07,0x00,0x70,0x00,0x07,0x77,0x77,0x00,0x70,0x77,0x07,0x00,0x70,0x07,0x70,0x00,0x70,0x07,0x00,0x07,0x70,0x07,0x00,0x07,0x00,0x07,0x00,0x07,0x00,0x70,0x00,0x00,0x00,0x00,0x77,0x00,0x70,0x77,0x07,0x00, + 0x70,0x07,0x70,0x07,0x70,0x00,0x77,0x00,0x70,0x07,0x00,0x07,0x70,0x70,0x07,0x00,0x00,0x77,0x07,0x00,0x07,0x77,0x00,0x07,0x00,0x00,0x00,0x07,0x07,0x77,0x07,0x07,0x70,0x77,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x70,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x07,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x70,0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x70,0x07,0x00,0x70,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00, + 0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x00,0x70,0x07,0x00,0x70,0x07,0x77,0x00,0x00,0x70,0x07,0x00,0x77,0x07,0x70,0x00,0x00,0x07,0x70,0x07,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00, + 0x70,0x77,0x77,0x00,0x70,0x07,0x70,0x00,0x00,0x07,0x70,0x00,0x00,0x77,0x70,0x00,0x00,0x07,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x77,0x07,0x00,0x70,0x07,0x00,0x00,0x70,0x77,0x00,0x00,0x77,0x77,0x07,0x00,0x77,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x07,0x00,0x70,0x77,0x00,0x00,0x70,0x00,0x70,0x00,0x00,0x70,0x00,0x00, + 0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x77,0x07,0x70,0x07,0x70,0x00,0x70,0x00,0x00,0x07,0x77,0x00,0x70,0x00,0x00,0x70,0x70,0x00,0x77,0x70,0x70,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x07,0x00,0x07,0x07,0x07,0x00,0x70,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00, + 0x00,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x77,0x00,0x00,0x07,0x70,0x07,0x00,0x00,0x77,0x00,0x70,0x00,0x07,0x00,0x00,0x70,0x77,0x07,0x07,0x70,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x77,0x00,0x00,0x70,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x07,0x00,0x70,0x77,0x77,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x77,0x77,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x70,0x07,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x07,0x00,0x70,0x70,0x70,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00, + 0x70,0x77,0x77,0x07,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x00,0x77,0x77,0x07,0x00,0x00,0x70,0x00,0x70,0x77,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x70,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00, + 0x00,0x70,0x07,0x00,0x00,0x07,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x70,0x00,0x70,0x07,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x70,0x00,0x00,0x00,0x70,0x00,0x07,0x77,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x07,0x00, + 0x00,0x07,0x07,0x00,0x70,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x70,0x00, + 0x70,0x00,0x07,0x00,0x70,0x00,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x77,0x00,0x00,0x70,0x07,0x70,0x00,0x00,0x70,0x77,0x00,0x00,0x77,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x77,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x07,0x70,0x77,0x07,0x00,0x00,0x07,0x00,0x00, + 0x70,0x77,0x77,0x00,0x00,0x77,0x07,0x00,0x00,0x00,0x70,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x70,0x00,0x70,0x77,0x07,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x07,0x00,0x70,0x77,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x70,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x77,0x00, + 0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x70,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x70,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x07,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x00,0x00,0x07,0x00,0x70,0x77,0x07,0x00,0x00,0x07,0x70,0x00, + 0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x70,0x77,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x07,0x70,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x70,0x70,0x70,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x00,0x70,0x70,0x07,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00, + 0x00,0x07,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x70,0x00,0x00,0x70,0x00,0x00,0x70,0x77,0x00,0x00,0x70,0x00,0x00,0x07,0x00,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x70,0x70,0x00,0x00,0x00,0x07,0x00,0x70,0x77,0x07,0x00,0x70,0x77,0x77,0x07,0x70,0x07,0x00,0x00,0x00,0x77,0x77,0x00,0x00,0x07,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x77,0x07,0x00,0x70,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x00,0x07,0x07,0x00,0x70,0x00,0x00,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x70,0x77,0x77,0x00,0x70,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00, + 0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x70,0x00,0x00,0x07,0x07,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x07,0x07,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x07,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x07,0x00, + 0x00,0x00,0x07,0x00,0x70,0x77,0x07,0x00,0x70,0x77,0x77,0x00,0x00,0x07,0x70,0x00,0x00,0x07,0x07,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x77,0x77,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x70,0x77,0x07,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x77,0x00,0x70,0x07,0x77,0x00,0x70,0x07, + 0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00,0x07,0x07,0x07,0x70,0x00,0x07,0x00,0x70,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x07,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x07,0x00,0x00, + 0x70,0x77,0x77,0x00,0x70,0x77,0x07,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x07,0x00,0x70,0x00,0x77,0x00,0x70,0x77,0x00,0x00,0x70,0x77,0x77,0x00,0x00,0x77,0x00,0x00,0x00,0x70,0x07,0x00,0x70,0x77,0x00,0x00,0x70,0x07,0x00,0x00,0x00,0x07,0x00,0x00,0x70,0x77,0x07,0x00,0x00,0x77,0x07,0x00,0x00,0x70,0x00,0x00,0x00,0x70,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, +}; + +#endif // PICO_FONT_H diff --git a/components/pico8/femto8/src/lexaloffle/p8_compress.c b/components/pico8/femto8/src/lexaloffle/p8_compress.c new file mode 100644 index 00000000..abaf599e --- /dev/null +++ b/components/pico8/femto8/src/lexaloffle/p8_compress.c @@ -0,0 +1,140 @@ +/* + p8_compress.c + + (c) Copyright 2014-2016 Lexaloffle Games LLP + author: joseph@lexaloffle.com + + compression used in code section of .p8.png format + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + +*/ + +#include +#include +#include + +#ifndef MAX + #define MAX(x, y) (((x) > (y)) ? (x) : (y)) + #define MIN(x, y) (((x) < (y)) ? (x) : (y)) +#endif + +typedef unsigned char uint8; + +#define HIST_LEN 4096 +#define LITERALS 60 +#define PICO8_CODE_ALLOC_SIZE (0x10000+1) + +#define codo_malloc malloc +#define codo_free free +#define codo_memset memset + +// removed from end of decompressed if it exists +// (injected to maintain 0.1.7 forwards compatibility) +#define FUTURE_CODE "if(_update60)_update=function()_update60()_update60()end" +#define FUTURE_CODE2 "if(_update60)_update=function()_update60()_update_buttons()_update60()end" + +// ^ is dummy -- not a literal. forgot '-', but nevermind! (gets encoded as rare literal) +char *literal = "^\n 0123456789abcdefghijklmnopqrstuvwxyz!#%(){}[]<>+=/*:;.,~_"; +int literal_index[256]; // map literals to 0..LITERALS-1. 0 is reserved (not listed in literals string) + +#define READ_VAL(val) {val = *in; in++;} +int decompress_mini(uint8 *in_p, uint8 *out_p, int max_len) +{ + int block_offset; + int block_length; + int val; + uint8 *in = in_p; + uint8 *out = out_p; + int len; + + // header tag ":c:" + READ_VAL(val); + READ_VAL(val); + READ_VAL(val); + READ_VAL(val); + + // uncompressed length + READ_VAL(val); + len = val * 256; + READ_VAL(val); + len += val; + + // compressed length (to do: use to check) + READ_VAL(val); + READ_VAL(val); + + codo_memset(out_p, 0, max_len); + + if (len > max_len) return 1; // corrupt data + + while (out < out_p + len) + { + READ_VAL(val); + + if (val < LITERALS) + { + // literal + if (val == 0) + { + READ_VAL(val); + //printf("rare literal: %d\n", val); + *out = val; + } + else + { + // printf("common literal: %d (%c)\n", literal[val], literal[val]); + *out = literal[val]; + } + out++; + } + else + { + // block + block_offset = val - LITERALS; + block_offset *= 16; + READ_VAL(val); + block_offset += val % 16; + block_length = (val / 16) + 2; + + memcpy(out, out - block_offset, block_length); + out += block_length; + } + } + + + // remove injected code (needed to be future compatible with PICO-8 C 0.1.7 / FILE_VERSION 8) + // older versions will leave this code intact, allowing it to implement fallback 60fps support + + if (strstr((char *)out_p, FUTURE_CODE)) + if (strlen((char *)out_p)-((char *)strstr((char *)out_p, FUTURE_CODE) - (char *)out_p) == strlen(FUTURE_CODE)) // at end + { + out = out_p + strlen((char *)out_p) - strlen(FUTURE_CODE); + *out = 0; + } + + // queue circus music + if (strstr((char *)out_p, FUTURE_CODE2)) + if (strlen((char *)out_p)-((char *)strstr((char *)out_p, FUTURE_CODE2) - (char *)out_p) == strlen(FUTURE_CODE2)) // at end + { + out = out_p + strlen((char *)out_p) - strlen(FUTURE_CODE2); + *out = 0; + } + + + return out - out_p; +} diff --git a/components/pico8/femto8/src/lexaloffle/pico8.h b/components/pico8/femto8/src/lexaloffle/pico8.h new file mode 100644 index 00000000..a3139a68 --- /dev/null +++ b/components/pico8/femto8/src/lexaloffle/pico8.h @@ -0,0 +1,13 @@ +#ifndef PICO8_H +#define PICO8_H + +#include + +int decompress_mini(uint8_t *in_p, uint8_t *out_p, int max_len); +int is_compressed_format_header(uint8_t *dat); +// max_len should be 0x10000 (64k max code size) +// out_p should allocate 0x10001 (includes null terminator) +int pico8_code_section_decompress(uint8_t *in_p, uint8_t *out_p, int max_len); +int pxa_decompress(uint8_t *in_p, uint8_t *out_p, int max_len); + +#endif diff --git a/components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c b/components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c new file mode 100644 index 00000000..4ccafdf1 --- /dev/null +++ b/components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c @@ -0,0 +1,283 @@ +/* + + pxa compression snippets for PICO-8 cartridge format (as of 0.2.4c) + + author: joseph@lexaloffle.com + + Copyright (c) 2020-22 Lexaloffle Games LLP + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +*/ + +#include +#include + +#include "pico8.h" + +#ifndef MAX + #define MAX(x, y) (((x) > (y)) ? (x) : (y)) + #define MIN(x, y) (((x) < (y)) ? (x) : (y)) +#endif + + +// 3 3 5 4 (gives balanced trees for typical data) + +#define PXA_MIN_BLOCK_LEN 3 +#define BLOCK_LEN_CHAIN_BITS 3 +#define BLOCK_DIST_BITS 5 +#define TINY_LITERAL_BITS 4 + + +// has to be 3 (optimized in find_repeatable_block) +#define MIN_BLOCK_LEN 3 +#define HASH_MAX 4096 +#define MINI_HASH(pp, i) ((pp[i+0]*7 + pp[i+1]*1503 + pp[i+2]*51717) & (HASH_MAX-1)) + +typedef unsigned short int uint16; +typedef unsigned char uint8; + +#define WRITE_VAL(x) {*p_8 = (x); p_8++;} + + +static int bit = 1; +static int byte = 0; +static int src_pos = 0; + + +//------------------------------------------------- +// pxa bit-level read/write help functions +//------------------------------------------------- +; +static uint8 *src_buf = NULL; + + +static int getbit() +{ + int ret; + + ret = (src_buf[src_pos] & bit) ? 1 : 0; + bit <<= 1; + if (bit == 256) + { + bit = 1; + src_pos ++; + } + return ret; +} + +static int getval(int bits) +{ + int i; + int val = 0; + if (bits == 0) return 0; + + for (i = 0; i < bits; i++) + if (getbit()) + val |= (1 << i); + + return val; +} + + +static int getchain(int link_bits, int max_bits) +{ + int max_link_val = (1 << link_bits) - 1; + int val = 0; + int vv = max_link_val; + int bits_read = 0; + + while (vv == max_link_val) + { + vv = getval(link_bits); + bits_read += link_bits; + val += vv; + if (bits_read >= max_bits) return val; // next val is implicitly 0 + } + + return val; +} + + +static int getnum() +{ + int jump = BLOCK_DIST_BITS; + int bits = jump; + int val; + + // 1 15 bits // more frequent so put first + // 01 10 bits + // 00 5 bits + bits = (3 - getchain(1, 2)) * BLOCK_DIST_BITS; + + val = getval(bits); + + if (val == 0 && bits == 10) + return -1; // raw block marker + + return val; +} + +// --------------------- + + +#define PXA_WRITE_VAL(x) {literal_bits_written += putval(x,8);} +#define PXA_READ_VAL(x) getval(8) + + +static void init_literals_state(int *literal, int *literal_pos) +{ + int i; + + // starting state makes little difference + // using 255-i (which seems terrible) only costs 10 bytes more. + + for (i = 0; i < 256; i++) + literal[i] = i; + + for (i = 0; i < 256; i++) + literal_pos[literal[i]] = i; +} + + +#define BACKUP_VLIST_STATE() memcpy(literal_backup, literal, sizeof(literal)); memcpy(literal_pos_backup, literal_pos, sizeof(literal_pos)); +#define RESTORE_VLIST_STATE() memcpy(literal, literal_backup, sizeof(literal)); memcpy(literal_pos, literal_pos_backup, sizeof(literal_pos)); + + +int pxa_decompress(uint8 *in_p, uint8 *out_p, int max_len) +{ + int i; + int literal[256]; + int literal_pos[256]; + int dest_pos = 0; + + bit = 1; + byte = 0; + src_buf = in_p; + src_pos = 0; + + init_literals_state(literal, literal_pos); + + // header + + int header[8]; + for (i = 0; i < 8; i++) + header[i] = PXA_READ_VAL(); + + int raw_len = header[4] * 256 + header[5]; + int comp_len = header[6] * 256 + header[7]; + + // printf(" read raw_len: %d\n", raw_len); + // printf(" read comp_len: %d\n", comp_len); + + while (src_pos < comp_len && dest_pos < raw_len && dest_pos < max_len) + { + int block_type = getbit(); + + // printf("%d %d\n", src_pos, block_type); fflush(stdout); + + if (block_type == 0) + { + // block + + int block_offset = getnum() + 1; + + if (block_offset == 0) + { + // 0.2.0j: raw block + while (dest_pos < raw_len) + { + out_p[dest_pos] = getval(8); + if (out_p[dest_pos] == 0) // found end -- don't advance dest_pos + break; + dest_pos ++; + } + } + else + { + int block_len = getchain(BLOCK_LEN_CHAIN_BITS, 100000) + PXA_MIN_BLOCK_LEN; + + // copy // don't just memcpy because might be copying self for repeating pattern + while (block_len > 0){ + out_p[dest_pos] = out_p[dest_pos - block_offset]; + dest_pos++; + block_len--; + } + + // safety: null terminator. to do: just do at end + if (dest_pos < max_len-1) + out_p[dest_pos] = 0; + } + }else + { + // literal + + int lpos = 0; + int bits = 0; + + int safety = 0; + while (getbit() == 1 && safety++ < 16) + { + lpos += (1 << (TINY_LITERAL_BITS + bits)); + bits ++; + } + + bits += TINY_LITERAL_BITS; + lpos += getval(bits); + + if (lpos > 255) return 0; // something wrong + + // grab character and write + int c = literal[lpos]; + + out_p[dest_pos] = c; + dest_pos++; + out_p[dest_pos] = 0; + + int i; + for (i = lpos; i > 0; i--) + { + literal[i] = literal[i-1]; + literal_pos[literal[i]] ++; + } + literal[0] = c; + literal_pos[c] = 0; + } + } + + + return 0; +} + +int is_compressed_format_header(uint8 *dat) +{ + if (dat[0] == ':' && dat[1] == 'c' && dat[2] == ':' && dat[3] == 0) return 1; + if (dat[0] == 0 && dat[1] == 'p' && dat[2] == 'x' && dat[3] == 'a') return 2; + return 0; +} + +// max_len should be 0x10000 (64k max code size) +// out_p should allocate 0x10001 (includes null terminator) +int pico8_code_section_decompress(uint8 *in_p, uint8 *out_p, int max_len) +{ + if (is_compressed_format_header(in_p) == 0) { memcpy(out_p, in_p, 0x3d00); out_p[0x3d00] = '\0'; return 0; } // legacy: no header -> is raw text + if (is_compressed_format_header(in_p) == 1) return decompress_mini(in_p, out_p, max_len); + if (is_compressed_format_header(in_p) == 2) return pxa_decompress (in_p, out_p, max_len); + return 0; +} diff --git a/components/pico8/femto8/src/lodepng/LICENSE b/components/pico8/femto8/src/lodepng/LICENSE new file mode 100644 index 00000000..83aa1b4b --- /dev/null +++ b/components/pico8/femto8/src/lodepng/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2005-2018 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. + diff --git a/components/pico8/femto8/src/lodepng/lodepng.c b/components/pico8/femto8/src/lodepng/lodepng.c new file mode 100644 index 00000000..a1757995 --- /dev/null +++ b/components/pico8/femto8/src/lodepng/lodepng.c @@ -0,0 +1,7242 @@ +/* +LodePNG version 20250506 + +Copyright (c) 2005-2025 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +/* +The manual and changelog are in the header file "lodepng.h" +Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C. +*/ + +#include "lodepng.h" + +#ifdef LODEPNG_COMPILE_DISK +#include /* LONG_MAX */ +#include /* file handling */ +#endif /* LODEPNG_COMPILE_DISK */ + +#ifdef LODEPNG_COMPILE_ALLOCATORS +#include /* allocations */ +#endif /* LODEPNG_COMPILE_ALLOCATORS */ + +#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/ +#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/ +#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/ +#endif /*_MSC_VER */ + +const char* LODEPNG_VERSION_STRING = "20250506"; + +/* +This source file is divided into the following large parts. The code sections +with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way. +-Tools for C and common code for PNG and Zlib +-C Code for Zlib (huffman, deflate, ...) +-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...) +-The C++ wrapper around all of the above +*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // Tools for C, and common code for PNG and Zlib. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*The malloc, realloc and free functions defined here with "lodepng_" in front +of the name, so that you can easily change them to others related to your +platform if needed. Everything else in the code calls these. Pass +-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out +#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and +define them in your own project's source files without needing to change +lodepng source code. Don't forget to remove "static" if you copypaste them +from here.*/ + +#ifdef LODEPNG_COMPILE_ALLOCATORS +static void* lodepng_malloc(size_t size) { +#ifdef LODEPNG_MAX_ALLOC + if(size > LODEPNG_MAX_ALLOC) return 0; +#endif + return malloc(size); +} + +/* NOTE: when realloc returns NULL, it leaves the original memory untouched */ +static void* lodepng_realloc(void* ptr, size_t new_size) { +#ifdef LODEPNG_MAX_ALLOC + if(new_size > LODEPNG_MAX_ALLOC) return 0; +#endif + return realloc(ptr, new_size); +} + +static void lodepng_free(void* ptr) { + free(ptr); +} +#else /*LODEPNG_COMPILE_ALLOCATORS*/ +/* TODO: support giving additional void* payload to the custom allocators */ +void* lodepng_malloc(size_t size); +void* lodepng_realloc(void* ptr, size_t new_size); +void lodepng_free(void* ptr); +#endif /*LODEPNG_COMPILE_ALLOCATORS*/ + +/* convince the compiler to inline a function, for use when this measurably improves performance */ +/* inline is not available in C90, but use it when supported by the compiler */ +#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(__cplusplus) && (__cplusplus >= 199711L)) +#define LODEPNG_INLINE inline +#else +#define LODEPNG_INLINE /* not available */ +#endif + +/* restrict is not available in C90, but use it when supported by the compiler */ +#if (defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) ||\ + (defined(_MSC_VER) && (_MSC_VER >= 1400)) || \ + (defined(__WATCOMC__) && (__WATCOMC__ >= 1250) && !defined(__cplusplus)) +#define LODEPNG_RESTRICT __restrict +#else +#define LODEPNG_RESTRICT /* not available */ +#endif + +/* Replacements for C library functions such as memcpy and strlen, to support platforms +where a full C library is not available. The compiler can recognize them and compile +to something as fast. */ + +static void lodepng_memcpy(void* LODEPNG_RESTRICT dst, + const void* LODEPNG_RESTRICT src, size_t size) { + size_t i; + for(i = 0; i < size; i++) ((char*)dst)[i] = ((const char*)src)[i]; +} + +static void lodepng_memset(void* LODEPNG_RESTRICT dst, + int value, size_t num) { + size_t i; + for(i = 0; i < num; i++) ((char*)dst)[i] = (char)value; +} + +/* does not check memory out of bounds, do not use on untrusted data */ +static size_t lodepng_strlen(const char* a) { + const char* orig = a; + /* avoid warning about unused function in case of disabled COMPILE... macros */ + (void)(&lodepng_strlen); + while(*a) a++; + return (size_t)(a - orig); +} + +#define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b)) + +#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER) +/* Safely check if adding two integers will overflow (no undefined +behavior, compiler removing the code, etc...) and output result. */ +static int lodepng_addofl(size_t a, size_t b, size_t* result) { + *result = a + b; /* Unsigned addition is well defined and safe in C90 */ + return *result < a; +} +#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER)*/ + +#ifdef LODEPNG_COMPILE_DECODER +/* Safely check if multiplying two integers will overflow (no undefined +behavior, compiler removing the code, etc...) and output result. */ +static int lodepng_mulofl(size_t a, size_t b, size_t* result) { + *result = a * b; /* Unsigned multiplication is well defined and safe in C90 */ + return (a != 0 && *result / a != b); +} + +#ifdef LODEPNG_COMPILE_ZLIB +/* Safely check if a + b > c, even if overflow could happen. */ +static int lodepng_gtofl(size_t a, size_t b, size_t c) { + size_t d; + if(lodepng_addofl(a, b, &d)) return 1; + return d > c; +} +#endif /*LODEPNG_COMPILE_ZLIB*/ +#endif /*LODEPNG_COMPILE_DECODER*/ + + +/* +Often in case of an error a value is assigned to a variable and then it breaks +out of a loop (to go to the cleanup phase of a function). This macro does that. +It makes the error handling code shorter and more readable. + +Example: if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83); +*/ +#define CERROR_BREAK(errorvar, code){\ + errorvar = code;\ + break;\ +} + +/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/ +#define ERROR_BREAK(code) CERROR_BREAK(error, code) + +/*Set error var to the error code, and return it.*/ +#define CERROR_RETURN_ERROR(errorvar, code){\ + errorvar = code;\ + return code;\ +} + +/*Try the code, if it returns error, also return the error.*/ +#define CERROR_TRY_RETURN(call){\ + unsigned error = call;\ + if(error) return error;\ +} + +/*Set error var to the error code, and return from the void function.*/ +#define CERROR_RETURN(errorvar, code){\ + errorvar = code;\ + return;\ +} + +/* +About uivector, ucvector and string: +-All of them wrap dynamic arrays or text strings in a similar way. +-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version. +-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated. +-They're not used in the interface, only internally in this file as static functions. +-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor. +*/ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_ENCODER +/*dynamic vector of unsigned ints*/ +typedef struct uivector { + unsigned* data; + size_t size; /*size in number of unsigned longs*/ + size_t allocsize; /*allocated size in bytes*/ +} uivector; + +static void uivector_cleanup(void* p) { + ((uivector*)p)->size = ((uivector*)p)->allocsize = 0; + lodepng_free(((uivector*)p)->data); + ((uivector*)p)->data = NULL; +} + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned uivector_resize(uivector* p, size_t size) { + size_t allocsize = size * sizeof(unsigned); + if(allocsize > p->allocsize) { + size_t newsize = allocsize + (p->allocsize >> 1u); + void* data = lodepng_realloc(p->data, newsize); + if(data) { + p->allocsize = newsize; + p->data = (unsigned*)data; + } + else return 0; /*error: not enough memory*/ + } + p->size = size; + return 1; /*success*/ +} + +static void uivector_init(uivector* p) { + p->data = NULL; + p->size = p->allocsize = 0; +} + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned uivector_push_back(uivector* p, unsigned c) { + if(!uivector_resize(p, p->size + 1)) return 0; + p->data[p->size - 1] = c; + return 1; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_ZLIB*/ + +/* /////////////////////////////////////////////////////////////////////////// */ + +/*dynamic vector of unsigned chars*/ +typedef struct ucvector { + unsigned char* data; + size_t size; /*used size*/ + size_t allocsize; /*allocated size*/ +} ucvector; + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned ucvector_reserve(ucvector* p, size_t size) { + if(size > p->allocsize) { + size_t newsize = size + (p->allocsize >> 1u); + void* data = lodepng_realloc(p->data, newsize); + if(data) { + p->allocsize = newsize; + p->data = (unsigned char*)data; + } + else return 0; /*error: not enough memory*/ + } + return 1; /*success*/ +} + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned ucvector_resize(ucvector* p, size_t size) { + p->size = size; + return ucvector_reserve(p, size); +} + +static ucvector ucvector_init(unsigned char* buffer, size_t size) { + ucvector v; + v.data = buffer; + v.allocsize = v.size = size; + return v; +} + +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_PNG +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + +/*free string pointer and set it to NULL*/ +static void string_cleanup(char** out) { + lodepng_free(*out); + *out = NULL; +} + +/*also appends null termination character*/ +static char* alloc_string_sized(const char* in, size_t insize) { + char* out = (char*)lodepng_malloc(insize + 1); + if(out) { + lodepng_memcpy(out, in, insize); + out[insize] = 0; + } + return out; +} + +/* dynamically allocates a new string with a copy of the null terminated input text */ +static char* alloc_string(const char* in) { + return alloc_string_sized(in, lodepng_strlen(in)); +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +/* ////////////////////////////////////////////////////////////////////////// */ + +#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG) +static unsigned lodepng_read32bitInt(const unsigned char* buffer) { + return (((unsigned)buffer[0] << 24u) | ((unsigned)buffer[1] << 16u) | + ((unsigned)buffer[2] << 8u) | (unsigned)buffer[3]); +} +#endif /*defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)*/ + +#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER) +/*buffer must have at least 4 allocated bytes available*/ +static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) { + buffer[0] = (unsigned char)((value >> 24) & 0xff); + buffer[1] = (unsigned char)((value >> 16) & 0xff); + buffer[2] = (unsigned char)((value >> 8) & 0xff); + buffer[3] = (unsigned char)((value ) & 0xff); +} +#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / File IO / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_DISK + +/* returns negative value on error. This should be pure C compatible, so no fstat. */ +static long lodepng_filesize(FILE* file) { + long size; + if(fseek(file, 0, SEEK_END) != 0) return -1; + size = ftell(file); + /* It may give LONG_MAX as directory size, this is invalid for us. */ + if(size == LONG_MAX) return -1; + if(fseek(file, 0, SEEK_SET) != 0) return -1; + return size; +} + +/* Allocates the output buffer to the file size and reads the file into it. Returns error code.*/ +static unsigned lodepng_load_file_(unsigned char** out, size_t* outsize, FILE* file) { + long size = lodepng_filesize(file); + if(size < 0) return 78; + *outsize = (size_t)size; + *out = (unsigned char*)lodepng_malloc((size_t)size); + if(!(*out) && size > 0) return 83; /*the above malloc failed*/ + if(fread(*out, 1, *outsize, file) != *outsize) return 78; + return 0; /*ok*/ +} + +unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) { + unsigned error; + FILE* file = fopen(filename, "rb"); + if(!file) return 78; + error = lodepng_load_file_(out, outsize, file); + fclose(file); + return error; +} + +/*write given buffer to the file, overwriting the file, it doesn't append to it.*/ +unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) { + FILE* file = fopen(filename, "wb" ); + if(!file) return 79; + fwrite(buffer, 1, buffersize, file); + fclose(file); + return 0; +} + +#endif /*LODEPNG_COMPILE_DISK*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // End of common code and tools. Begin of Zlib related code. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_ENCODER + +typedef struct { + ucvector* data; + unsigned char bp; /*ok to overflow, indicates bit pos inside byte*/ +} LodePNGBitWriter; + +static void LodePNGBitWriter_init(LodePNGBitWriter* writer, ucvector* data) { + writer->data = data; + writer->bp = 0; +} + +/*TODO: this ignores potential out of memory errors*/ +#define WRITEBIT(writer, bit){\ + /* append new byte */\ + if(((writer->bp) & 7u) == 0) {\ + if(!ucvector_resize(writer->data, writer->data->size + 1)) return;\ + writer->data->data[writer->data->size - 1] = 0;\ + }\ + (writer->data->data[writer->data->size - 1]) |= (bit << ((writer->bp) & 7u));\ + ++writer->bp;\ +} + +/* LSB of value is written first, and LSB of bytes is used first */ +static void writeBits(LodePNGBitWriter* writer, unsigned value, size_t nbits) { + if(nbits == 1) { /* compiler should statically compile this case if nbits == 1 */ + WRITEBIT(writer, value); + } else { + /* TODO: increase output size only once here rather than in each WRITEBIT */ + size_t i; + for(i = 0; i != nbits; ++i) { + WRITEBIT(writer, (unsigned char)((value >> i) & 1)); + } + } +} + +/* This one is to use for adding huffman symbol, the value bits are written MSB first */ +static void writeBitsReversed(LodePNGBitWriter* writer, unsigned value, size_t nbits) { + size_t i; + for(i = 0; i != nbits; ++i) { + /* TODO: increase output size only once here rather than in each WRITEBIT */ + WRITEBIT(writer, (unsigned char)((value >> (nbits - 1u - i)) & 1u)); + } +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +typedef struct { + const unsigned char* data; + size_t size; /*size of data in bytes*/ + size_t bitsize; /*size of data in bits, end of valid bp values, should be 8*size*/ + size_t bp; + unsigned buffer; /*buffer for reading bits. NOTE: 'unsigned' must support at least 32 bits*/ +} LodePNGBitReader; + +/* data size argument is in bytes. Returns error if size too large causing overflow */ +static unsigned LodePNGBitReader_init(LodePNGBitReader* reader, const unsigned char* data, size_t size) { + size_t temp; + reader->data = data; + reader->size = size; + /* size in bits, return error if overflow (if size_t is 32 bit this supports up to 500MB) */ + if(lodepng_mulofl(size, 8u, &reader->bitsize)) return 105; + /*ensure incremented bp can be compared to bitsize without overflow even when it would be incremented 32 too much and + trying to ensure 32 more bits*/ + if(lodepng_addofl(reader->bitsize, 64u, &temp)) return 105; + reader->bp = 0; + reader->buffer = 0; + return 0; /*ok*/ +} + +/* +ensureBits functions: +Ensures the reader can at least read nbits bits in one or more readBits calls, +safely even if not enough bits are available. +The nbits parameter is unused but is given for documentation purposes, error +checking for amount of bits must be done beforehand. +*/ + +/*See ensureBits documentation above. This one ensures up to 9 bits */ +static LODEPNG_INLINE void ensureBits9(LodePNGBitReader* reader, size_t nbits) { + size_t start = reader->bp >> 3u; + size_t size = reader->size; + if(start + 1u < size) { + reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u); + reader->buffer >>= (reader->bp & 7u); + } else { + reader->buffer = 0; + if(start + 0u < size) reader->buffer = reader->data[start + 0]; + reader->buffer >>= (reader->bp & 7u); + } + (void)nbits; +} + +/*See ensureBits documentation above. This one ensures up to 17 bits */ +static LODEPNG_INLINE void ensureBits17(LodePNGBitReader* reader, size_t nbits) { + size_t start = reader->bp >> 3u; + size_t size = reader->size; + if(start + 2u < size) { + reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | + ((unsigned)reader->data[start + 2] << 16u); + reader->buffer >>= (reader->bp & 7u); + } else { + reader->buffer = 0; + if(start + 0u < size) reader->buffer |= reader->data[start + 0]; + if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u); + reader->buffer >>= (reader->bp & 7u); + } + (void)nbits; +} + +/*See ensureBits documentation above. This one ensures up to 25 bits */ +static LODEPNG_INLINE void ensureBits25(LodePNGBitReader* reader, size_t nbits) { + size_t start = reader->bp >> 3u; + size_t size = reader->size; + if(start + 3u < size) { + reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | + ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u); + reader->buffer >>= (reader->bp & 7u); + } else { + reader->buffer = 0; + if(start + 0u < size) reader->buffer |= reader->data[start + 0]; + if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u); + if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u); + reader->buffer >>= (reader->bp & 7u); + } + (void)nbits; +} + +/*See ensureBits documentation above. This one ensures up to 32 bits */ +static LODEPNG_INLINE void ensureBits32(LodePNGBitReader* reader, size_t nbits) { + size_t start = reader->bp >> 3u; + size_t size = reader->size; + if(start + 4u < size) { + reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | + ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u); + reader->buffer >>= (reader->bp & 7u); + reader->buffer |= (((unsigned)reader->data[start + 4] << 24u) << (8u - (reader->bp & 7u))); + } else { + reader->buffer = 0; + if(start + 0u < size) reader->buffer |= reader->data[start + 0]; + if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u); + if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u); + if(start + 3u < size) reader->buffer |= ((unsigned)reader->data[start + 3] << 24u); + reader->buffer >>= (reader->bp & 7u); + } + (void)nbits; +} + +/* Get bits without advancing the bit pointer. Must have enough bits available with ensureBits. Max nbits is 31. */ +static LODEPNG_INLINE unsigned peekBits(LodePNGBitReader* reader, size_t nbits) { + /* The shift allows nbits to be only up to 31. */ + return reader->buffer & ((1u << nbits) - 1u); +} + +/* Must have enough bits available with ensureBits */ +static LODEPNG_INLINE void advanceBits(LodePNGBitReader* reader, size_t nbits) { + reader->buffer >>= nbits; + reader->bp += nbits; +} + +/* Must have enough bits available with ensureBits */ +static LODEPNG_INLINE unsigned readBits(LodePNGBitReader* reader, size_t nbits) { + unsigned result = peekBits(reader, nbits); + advanceBits(reader, nbits); + return result; +} +#endif /*LODEPNG_COMPILE_DECODER*/ + +static unsigned reverseBits(unsigned bits, unsigned num) { + /*TODO: implement faster lookup table based version when needed*/ + unsigned i, result = 0; + for(i = 0; i < num; i++) result |= ((bits >> (num - i - 1u)) & 1u) << i; + return result; +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Deflate - Huffman / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#define FIRST_LENGTH_CODE_INDEX 257 +#define LAST_LENGTH_CODE_INDEX 285 +/*256 literals, the end code, some length codes, and 2 unused codes*/ +#define NUM_DEFLATE_CODE_SYMBOLS 288 +/*the distance codes have their own symbols, 30 used, 2 unused*/ +#define NUM_DISTANCE_SYMBOLS 32 +/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/ +#define NUM_CODE_LENGTH_CODES 19 + +/*the base lengths represented by codes 257-285*/ +static const unsigned LENGTHBASE[29] + = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, + 67, 83, 99, 115, 131, 163, 195, 227, 258}; + +/*the extra bits used by codes 257-285 (added to base length)*/ +static const unsigned LENGTHEXTRA[29] + = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, + 4, 4, 4, 4, 5, 5, 5, 5, 0}; + +/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/ +static const unsigned DISTANCEBASE[30] + = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, + 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; + +/*the extra bits of backwards distances (added to base)*/ +static const unsigned DISTANCEEXTRA[30] + = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, + 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; + +/*the order in which "code length alphabet code lengths" are stored as specified by deflate, out of this the huffman +tree of the dynamic huffman tree lengths is generated*/ +static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES] + = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + +/* ////////////////////////////////////////////////////////////////////////// */ + +/* +Huffman tree struct, containing multiple representations of the tree +*/ +typedef struct HuffmanTree { + unsigned* codes; /*the huffman codes (bit patterns representing the symbols)*/ + unsigned* lengths; /*the lengths of the huffman codes*/ + unsigned maxbitlen; /*maximum number of bits a single code can get*/ + unsigned numcodes; /*number of symbols in the alphabet = number of codes*/ + /* for reading only */ + unsigned char* table_len; /*length of symbol from lookup table, or max length if secondary lookup needed*/ + unsigned short* table_value; /*value of symbol from lookup table, or pointer to secondary table if needed*/ +} HuffmanTree; + +static void HuffmanTree_init(HuffmanTree* tree) { + tree->codes = 0; + tree->lengths = 0; + tree->table_len = 0; + tree->table_value = 0; +} + +static void HuffmanTree_cleanup(HuffmanTree* tree) { + lodepng_free(tree->codes); + lodepng_free(tree->lengths); + lodepng_free(tree->table_len); + lodepng_free(tree->table_value); +} + +/* amount of bits for first huffman table lookup (aka root bits), see HuffmanTree_makeTable and huffmanDecodeSymbol.*/ +/* values 8u and 9u work the fastest */ +#define FIRSTBITS 9u + +/* a symbol value too big to represent any valid symbol, to indicate reading disallowed huffman bits combination, +which is possible in case of only 0 or 1 present symbols. */ +#define INVALIDSYMBOL 65535u + +/* make table for huffman decoding */ +static unsigned HuffmanTree_makeTable(HuffmanTree* tree) { + static const unsigned headsize = 1u << FIRSTBITS; /*size of the first table*/ + static const unsigned mask = (1u << FIRSTBITS) /*headsize*/ - 1u; + size_t i, numpresent, pointer, size; /*total table size*/ + unsigned* maxlens = (unsigned*)lodepng_malloc(headsize * sizeof(unsigned)); + if(!maxlens) return 83; /*alloc fail*/ + + /* compute maxlens: max total bit length of symbols sharing prefix in the first table*/ + lodepng_memset(maxlens, 0, headsize * sizeof(*maxlens)); + for(i = 0; i < tree->numcodes; i++) { + unsigned symbol = tree->codes[i]; + unsigned l = tree->lengths[i]; + unsigned index; + if(l <= FIRSTBITS) continue; /*symbols that fit in first table don't increase secondary table size*/ + /*get the FIRSTBITS MSBs, the MSBs of the symbol are encoded first. See later comment about the reversing*/ + index = reverseBits(symbol >> (l - FIRSTBITS), FIRSTBITS); + maxlens[index] = LODEPNG_MAX(maxlens[index], l); + } + /* compute total table size: size of first table plus all secondary tables for symbols longer than FIRSTBITS */ + size = headsize; + for(i = 0; i < headsize; ++i) { + unsigned l = maxlens[i]; + if(l > FIRSTBITS) size += (((size_t)1) << (l - FIRSTBITS)); + } + tree->table_len = (unsigned char*)lodepng_malloc(size * sizeof(*tree->table_len)); + tree->table_value = (unsigned short*)lodepng_malloc(size * sizeof(*tree->table_value)); + if(!tree->table_len || !tree->table_value) { + lodepng_free(maxlens); + /* freeing tree->table values is done at a higher scope */ + return 83; /*alloc fail*/ + } + /*initialize with an invalid length to indicate unused entries*/ + for(i = 0; i < size; ++i) tree->table_len[i] = 16; + + /*fill in the first table for long symbols: max prefix size and pointer to secondary tables*/ + pointer = headsize; + for(i = 0; i < headsize; ++i) { + unsigned l = maxlens[i]; + if(l <= FIRSTBITS) continue; + tree->table_len[i] = l; + tree->table_value[i] = (unsigned short)pointer; + pointer += (((size_t)1) << (l - FIRSTBITS)); + } + lodepng_free(maxlens); + + /*fill in the first table for short symbols, or secondary table for long symbols*/ + numpresent = 0; + for(i = 0; i < tree->numcodes; ++i) { + unsigned l = tree->lengths[i]; + unsigned symbol, reverse; + if(l == 0) continue; + symbol = tree->codes[i]; /*the huffman bit pattern. i itself is the value.*/ + /*reverse bits, because the huffman bits are given in MSB first order but the bit reader reads LSB first*/ + reverse = reverseBits(symbol, l); + numpresent++; + + if(l <= FIRSTBITS) { + /*short symbol, fully in first table, replicated num times if l < FIRSTBITS*/ + unsigned num = 1u << (FIRSTBITS - l); + unsigned j; + for(j = 0; j < num; ++j) { + /*bit reader will read the l bits of symbol first, the remaining FIRSTBITS - l bits go to the MSB's*/ + unsigned index = reverse | (j << l); + if(tree->table_len[index] != 16) return 55; /*invalid tree: long symbol shares prefix with short symbol*/ + tree->table_len[index] = l; + tree->table_value[index] = (unsigned short)i; + } + } else { + /*long symbol, shares prefix with other long symbols in first lookup table, needs second lookup*/ + /*the FIRSTBITS MSBs of the symbol are the first table index*/ + unsigned index = reverse & mask; + unsigned maxlen = tree->table_len[index]; + /*log2 of secondary table length, should be >= l - FIRSTBITS*/ + unsigned tablelen = maxlen - FIRSTBITS; + unsigned start = tree->table_value[index]; /*starting index in secondary table*/ + unsigned num = 1u << (tablelen - (l - FIRSTBITS)); /*amount of entries of this symbol in secondary table*/ + unsigned j; + if(maxlen < l) return 55; /*invalid tree: long symbol shares prefix with short symbol*/ + for(j = 0; j < num; ++j) { + unsigned reverse2 = reverse >> FIRSTBITS; /* l - FIRSTBITS bits */ + unsigned index2 = start + (reverse2 | (j << (l - FIRSTBITS))); + tree->table_len[index2] = l; + tree->table_value[index2] = (unsigned short)i; + } + } + } + + if(numpresent < 2) { + /* In case of exactly 1 symbol, in theory the huffman symbol needs 0 bits, + but deflate uses 1 bit instead. In case of 0 symbols, no symbols can + appear at all, but such huffman tree could still exist (e.g. if distance + codes are never used). In both cases, not all symbols of the table will be + filled in. Fill them in with an invalid symbol value so returning them from + huffmanDecodeSymbol will cause error. */ + for(i = 0; i < size; ++i) { + if(tree->table_len[i] == 16) { + /* As length, use a value smaller than FIRSTBITS for the head table, + and a value larger than FIRSTBITS for the secondary table, to ensure + valid behavior for advanceBits when reading this symbol. */ + tree->table_len[i] = (i < headsize) ? 1 : (FIRSTBITS + 1); + tree->table_value[i] = INVALIDSYMBOL; + } + } + } else { + /* A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. + If that is not the case (due to too long length codes), the table will not + have been fully used, and this is an error (not all bit combinations can be + decoded): an oversubscribed huffman tree, indicated by error 55. */ + for(i = 0; i < size; ++i) { + if(tree->table_len[i] == 16) return 55; + } + } + + return 0; +} + +/* +Second step for the ...makeFromLengths and ...makeFromFrequencies functions. +numcodes, lengths and maxbitlen must already be filled in correctly. return +value is error. +*/ +static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) { + unsigned* blcount; + unsigned* nextcode; + unsigned error = 0; + unsigned bits, n; + + tree->codes = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned)); + blcount = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned)); + nextcode = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned)); + if(!tree->codes || !blcount || !nextcode) error = 83; /*alloc fail*/ + + if(!error) { + for(n = 0; n != tree->maxbitlen + 1; n++) blcount[n] = nextcode[n] = 0; + /*step 1: count number of instances of each code length*/ + for(bits = 0; bits != tree->numcodes; ++bits) ++blcount[tree->lengths[bits]]; + /*step 2: generate the nextcode values*/ + for(bits = 1; bits <= tree->maxbitlen; ++bits) { + nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1u; + } + /*step 3: generate all the codes*/ + for(n = 0; n != tree->numcodes; ++n) { + if(tree->lengths[n] != 0) { + tree->codes[n] = nextcode[tree->lengths[n]]++; + /*remove superfluous bits from the code*/ + tree->codes[n] &= ((1u << tree->lengths[n]) - 1u); + } + } + } + + lodepng_free(blcount); + lodepng_free(nextcode); + + if(!error) error = HuffmanTree_makeTable(tree); + return error; +} + +/* +given the code lengths (as stored in the PNG file), generate the tree as defined +by Deflate. maxbitlen is the maximum bits that a code in the tree can have. +return value is error. +*/ +static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen, + size_t numcodes, unsigned maxbitlen) { + unsigned i; + tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); + if(!tree->lengths) return 83; /*alloc fail*/ + for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i]; + tree->numcodes = (unsigned)numcodes; /*number of symbols*/ + tree->maxbitlen = maxbitlen; + return HuffmanTree_makeFromLengths2(tree); +} + +#ifdef LODEPNG_COMPILE_ENCODER + +/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding", +Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/ + +/*chain node for boundary package merge*/ +typedef struct BPMNode { + int weight; /*the sum of all weights in this chain*/ + unsigned index; /*index of this leaf node (called "count" in the paper)*/ + struct BPMNode* tail; /*the next nodes in this chain (null if last)*/ + int in_use; +} BPMNode; + +/*lists of chains*/ +typedef struct BPMLists { + /*memory pool*/ + unsigned memsize; + BPMNode* memory; + unsigned numfree; + unsigned nextfree; + BPMNode** freelist; + /*two heads of lookahead chains per list*/ + unsigned listsize; + BPMNode** chains0; + BPMNode** chains1; +} BPMLists; + +/*creates a new chain node with the given parameters, from the memory in the lists */ +static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) { + unsigned i; + BPMNode* result; + + /*memory full, so garbage collect*/ + if(lists->nextfree >= lists->numfree) { + /*mark only those that are in use*/ + for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0; + for(i = 0; i != lists->listsize; ++i) { + BPMNode* node; + for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1; + for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1; + } + /*collect those that are free*/ + lists->numfree = 0; + for(i = 0; i != lists->memsize; ++i) { + if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i]; + } + lists->nextfree = 0; + } + + result = lists->freelist[lists->nextfree++]; + result->weight = weight; + result->index = index; + result->tail = tail; + return result; +} + +/*sort the leaves with stable mergesort*/ +static void bpmnode_sort(BPMNode* leaves, size_t num) { + BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num); + size_t width, counter = 0; + for(width = 1; width < num; width *= 2) { + BPMNode* a = (counter & 1) ? mem : leaves; + BPMNode* b = (counter & 1) ? leaves : mem; + size_t p; + for(p = 0; p < num; p += 2 * width) { + size_t q = (p + width > num) ? num : (p + width); + size_t r = (p + 2 * width > num) ? num : (p + 2 * width); + size_t i = p, j = q, k; + for(k = p; k < r; k++) { + if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++]; + else b[k] = a[j++]; + } + } + counter++; + } + if(counter & 1) lodepng_memcpy(leaves, mem, sizeof(*leaves) * num); + lodepng_free(mem); +} + +/*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/ +static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) { + unsigned lastindex = lists->chains1[c]->index; + + if(c == 0) { + if(lastindex >= numpresent) return; + lists->chains0[c] = lists->chains1[c]; + lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0); + } else { + /*sum of the weights of the head nodes of the previous lookahead chains.*/ + int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight; + lists->chains0[c] = lists->chains1[c]; + if(lastindex < numpresent && sum > leaves[lastindex].weight) { + lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail); + return; + } + lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]); + /*in the end we are only interested in the chain of the last list, so no + need to recurse if we're at the last one (this gives measurable speedup)*/ + if(num + 1 < (int)(2 * numpresent - 2)) { + boundaryPM(lists, leaves, numpresent, c - 1, num); + boundaryPM(lists, leaves, numpresent, c - 1, num); + } + } +} + +unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, + size_t numcodes, unsigned maxbitlen) { + unsigned error = 0; + unsigned i; + size_t numpresent = 0; /*number of symbols with non-zero frequency*/ + BPMNode* leaves; /*the symbols, only those with > 0 frequency*/ + + if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/ + if((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/ + + leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves)); + if(!leaves) return 83; /*alloc fail*/ + + for(i = 0; i != numcodes; ++i) { + if(frequencies[i] > 0) { + leaves[numpresent].weight = (int)frequencies[i]; + leaves[numpresent].index = i; + ++numpresent; + } + } + + lodepng_memset(lengths, 0, numcodes * sizeof(*lengths)); + + /*ensure at least two present symbols. There should be at least one symbol + according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To + make these work as well ensure there are at least two symbols. The + Package-Merge code below also doesn't work correctly if there's only one + symbol, it'd give it the theoretical 0 bits but in practice zlib wants 1 bit*/ + if(numpresent == 0) { + lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/ + } else if(numpresent == 1) { + lengths[leaves[0].index] = 1; + lengths[leaves[0].index == 0 ? 1 : 0] = 1; + } else { + BPMLists lists; + BPMNode* node; + + bpmnode_sort(leaves, numpresent); + + lists.listsize = maxbitlen; + lists.memsize = 2 * maxbitlen * (maxbitlen + 1); + lists.nextfree = 0; + lists.numfree = lists.memsize; + lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory)); + lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*)); + lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); + lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); + if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/ + + if(!error) { + for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i]; + + bpmnode_create(&lists, leaves[0].weight, 1, 0); + bpmnode_create(&lists, leaves[1].weight, 2, 0); + + for(i = 0; i != lists.listsize; ++i) { + lists.chains0[i] = &lists.memory[0]; + lists.chains1[i] = &lists.memory[1]; + } + + /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/ + for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i); + + for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) { + for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index]; + } + } + + lodepng_free(lists.memory); + lodepng_free(lists.freelist); + lodepng_free(lists.chains0); + lodepng_free(lists.chains1); + } + + lodepng_free(leaves); + return error; +} + +/*Create the Huffman tree given the symbol frequencies*/ +static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, + size_t mincodes, size_t numcodes, unsigned maxbitlen) { + unsigned error = 0; + while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/ + tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); + if(!tree->lengths) return 83; /*alloc fail*/ + tree->maxbitlen = maxbitlen; + tree->numcodes = (unsigned)numcodes; /*number of symbols*/ + + error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); + if(!error) error = HuffmanTree_makeFromLengths2(tree); + return error; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/ +static unsigned generateFixedLitLenTree(HuffmanTree* tree) { + unsigned i, error = 0; + unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); + if(!bitlen) return 83; /*alloc fail*/ + + /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/ + for(i = 0; i <= 143; ++i) bitlen[i] = 8; + for(i = 144; i <= 255; ++i) bitlen[i] = 9; + for(i = 256; i <= 279; ++i) bitlen[i] = 7; + for(i = 280; i <= 287; ++i) bitlen[i] = 8; + + error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15); + + lodepng_free(bitlen); + return error; +} + +/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/ +static unsigned generateFixedDistanceTree(HuffmanTree* tree) { + unsigned i, error = 0; + unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); + if(!bitlen) return 83; /*alloc fail*/ + + /*there are 32 distance codes, but 30-31 are unused*/ + for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5; + error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15); + + lodepng_free(bitlen); + return error; +} + +#ifdef LODEPNG_COMPILE_DECODER + +/* +returns the code. The bit reader must already have been ensured at least 15 bits +*/ +static unsigned huffmanDecodeSymbol(LodePNGBitReader* reader, const HuffmanTree* codetree) { + unsigned short code = peekBits(reader, FIRSTBITS); + unsigned short l = codetree->table_len[code]; + unsigned short value = codetree->table_value[code]; + if(l <= FIRSTBITS) { + advanceBits(reader, l); + return value; + } else { + advanceBits(reader, FIRSTBITS); + value += peekBits(reader, l - FIRSTBITS); + advanceBits(reader, codetree->table_len[value] - FIRSTBITS); + return codetree->table_value[value]; + } +} +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Inflator (Decompressor) / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*get the tree of a deflated block with fixed tree, as specified in the deflate specification +Returns error code.*/ +static unsigned getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) { + unsigned error = generateFixedLitLenTree(tree_ll); + if(error) return error; + return generateFixedDistanceTree(tree_d); +} + +/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/ +static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, + LodePNGBitReader* reader) { + /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/ + unsigned error = 0; + unsigned n, HLIT, HDIST, HCLEN, i; + + /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/ + unsigned* bitlen_ll = 0; /*lit,len code lengths*/ + unsigned* bitlen_d = 0; /*dist code lengths*/ + /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/ + unsigned* bitlen_cl = 0; + HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/ + + if(reader->bitsize - reader->bp < 14) return 49; /*error: the bit pointer is or will go past the memory*/ + ensureBits17(reader, 14); + + /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/ + HLIT = readBits(reader, 5) + 257; + /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/ + HDIST = readBits(reader, 5) + 1; + /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/ + HCLEN = readBits(reader, 4) + 4; + + bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned)); + if(!bitlen_cl) return 83 /*alloc fail*/; + + HuffmanTree_init(&tree_cl); + + while(!error) { + /*read the code length codes out of 3 * (amount of code length codes) bits*/ + if(lodepng_gtofl(reader->bp, HCLEN * 3, reader->bitsize)) { + ERROR_BREAK(50); /*error: the bit pointer is or will go past the memory*/ + } + for(i = 0; i != HCLEN; ++i) { + ensureBits9(reader, 3); /*out of bounds already checked above */ + bitlen_cl[CLCL_ORDER[i]] = readBits(reader, 3); + } + for(i = HCLEN; i != NUM_CODE_LENGTH_CODES; ++i) { + bitlen_cl[CLCL_ORDER[i]] = 0; + } + + error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7); + if(error) break; + + /*now we can use this tree to read the lengths for the tree that this function will return*/ + bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); + bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); + if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/); + lodepng_memset(bitlen_ll, 0, NUM_DEFLATE_CODE_SYMBOLS * sizeof(*bitlen_ll)); + lodepng_memset(bitlen_d, 0, NUM_DISTANCE_SYMBOLS * sizeof(*bitlen_d)); + + /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/ + i = 0; + while(i < HLIT + HDIST) { + unsigned code; + ensureBits25(reader, 22); /* up to 15 bits for huffman code, up to 7 extra bits below*/ + code = huffmanDecodeSymbol(reader, &tree_cl); + if(code <= 15) /*a length code*/ { + if(i < HLIT) bitlen_ll[i] = code; + else bitlen_d[i - HLIT] = code; + ++i; + } else if(code == 16) /*repeat previous*/ { + unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/ + unsigned value; /*set value to the previous code*/ + + if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/ + + replength += readBits(reader, 2); + + if(i < HLIT + 1) value = bitlen_ll[i - 1]; + else value = bitlen_d[i - HLIT - 1]; + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) { + if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/ + if(i < HLIT) bitlen_ll[i] = value; + else bitlen_d[i - HLIT] = value; + ++i; + } + } else if(code == 17) /*repeat "0" 3-10 times*/ { + unsigned replength = 3; /*read in the bits that indicate repeat length*/ + replength += readBits(reader, 3); + + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) { + if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/ + + if(i < HLIT) bitlen_ll[i] = 0; + else bitlen_d[i - HLIT] = 0; + ++i; + } + } else if(code == 18) /*repeat "0" 11-138 times*/ { + unsigned replength = 11; /*read in the bits that indicate repeat length*/ + replength += readBits(reader, 7); + + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) { + if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/ + + if(i < HLIT) bitlen_ll[i] = 0; + else bitlen_d[i - HLIT] = 0; + ++i; + } + } else /*if(code == INVALIDSYMBOL)*/ { + ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/ + } + /*check if any of the ensureBits above went out of bounds*/ + if(reader->bp > reader->bitsize) { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + /* TODO: revise error codes 10,11,50: the above comment is no longer valid */ + ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ + } + } + if(error) break; + + if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/ + + /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/ + error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15); + if(error) break; + error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15); + + break; /*end of error-while*/ + } + + lodepng_free(bitlen_cl); + lodepng_free(bitlen_ll); + lodepng_free(bitlen_d); + HuffmanTree_cleanup(&tree_cl); + + return error; +} + +/*inflate a block with dynamic of fixed Huffman tree. btype must be 1 or 2.*/ +static unsigned inflateHuffmanBlock(ucvector* out, LodePNGBitReader* reader, + unsigned btype, size_t max_output_size) { + unsigned error = 0; + HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/ + HuffmanTree tree_d; /*the huffman tree for distance codes*/ + const size_t reserved_size = 260; /* must be at least 258 for max length, and a few extra for adding a few extra literals */ + int done = 0; + + if(!ucvector_reserve(out, out->size + reserved_size)) return 83; /*alloc fail*/ + + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + + if(btype == 1) error = getTreeInflateFixed(&tree_ll, &tree_d); + else /*if(btype == 2)*/ error = getTreeInflateDynamic(&tree_ll, &tree_d, reader); + + + while(!error && !done) /*decode all symbols until end reached, breaks at end code*/ { + /*code_ll is literal, length or end code*/ + unsigned code_ll; + /* ensure enough bits for 2 huffman code reads (15 bits each): if the first is a literal, a second literal is read at once. This + appears to be slightly faster, than ensuring 20 bits here for 1 huffman symbol and the potential 5 extra bits for the length symbol.*/ + ensureBits32(reader, 30); + code_ll = huffmanDecodeSymbol(reader, &tree_ll); + if(code_ll <= 255) { + /*slightly faster code path if multiple literals in a row*/ + out->data[out->size++] = (unsigned char)code_ll; + code_ll = huffmanDecodeSymbol(reader, &tree_ll); + } + if(code_ll <= 255) /*literal symbol*/ { + out->data[out->size++] = (unsigned char)code_ll; + } else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ { + unsigned code_d, distance; + unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/ + size_t start, backward, length; + + /*part 1: get length base*/ + length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX]; + + /*part 2: get extra bits and add the value of that to length*/ + numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX]; + if(numextrabits_l != 0) { + /* bits already ensured above */ + ensureBits25(reader, 5); + length += readBits(reader, numextrabits_l); + } + + /*part 3: get distance code*/ + ensureBits32(reader, 28); /* up to 15 for the huffman symbol, up to 13 for the extra bits */ + code_d = huffmanDecodeSymbol(reader, &tree_d); + if(code_d > 29) { + if(code_d <= 31) { + ERROR_BREAK(18); /*error: invalid distance code (30-31 are never used)*/ + } else /* if(code_d == INVALIDSYMBOL) */{ + ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/ + } + } + distance = DISTANCEBASE[code_d]; + + /*part 4: get extra bits from distance*/ + numextrabits_d = DISTANCEEXTRA[code_d]; + if(numextrabits_d != 0) { + /* bits already ensured above */ + distance += readBits(reader, numextrabits_d); + } + + /*part 5: fill in all the out[n] values based on the length and dist*/ + start = out->size; + if(distance > start) ERROR_BREAK(52); /*too long backward distance*/ + backward = start - distance; + + out->size += length; + if(distance < length) { + size_t forward; + lodepng_memcpy(out->data + start, out->data + backward, distance); + start += distance; + for(forward = distance; forward < length; ++forward) { + out->data[start++] = out->data[backward++]; + } + } else { + lodepng_memcpy(out->data + start, out->data + backward, length); + } + } else if(code_ll == 256) { + done = 1; /*end code, finish the loop*/ + } else /*if(code_ll == INVALIDSYMBOL)*/ { + ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/ + } + if(out->allocsize - out->size < reserved_size) { + if(!ucvector_reserve(out, out->size + reserved_size)) ERROR_BREAK(83); /*alloc fail*/ + } + /*check if any of the ensureBits above went out of bounds*/ + if(reader->bp > reader->bitsize) { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + /* TODO: revise error codes 10,11,50: the above comment is no longer valid */ + ERROR_BREAK(51); /*error, bit pointer jumps past memory*/ + } + if(max_output_size && out->size > max_output_size) { + ERROR_BREAK(109); /*error, larger than max size*/ + } + } + + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + + return error; +} + +static unsigned inflateNoCompression(ucvector* out, LodePNGBitReader* reader, + const LodePNGDecompressSettings* settings) { + size_t bytepos; + size_t size = reader->size; + unsigned LEN, NLEN, error = 0; + + /*go to first boundary of byte*/ + bytepos = (reader->bp + 7u) >> 3u; + + /*read LEN (2 bytes) and NLEN (2 bytes)*/ + if(bytepos + 4 >= size) return 52; /*error, bit pointer will jump past memory*/ + LEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2; + NLEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2; + + /*check if 16-bit NLEN is really the one's complement of LEN*/ + if(!settings->ignore_nlen && LEN + NLEN != 65535) { + return 21; /*error: NLEN is not one's complement of LEN*/ + } + + if(!ucvector_resize(out, out->size + LEN)) return 83; /*alloc fail*/ + + /*read the literal data: LEN bytes are now stored in the out buffer*/ + if(bytepos + LEN > size) return 23; /*error: reading outside of in buffer*/ + + /*out->data can be NULL (when LEN is zero), and arithmetics on NULL ptr is undefined*/ + if (LEN) { + lodepng_memcpy(out->data + out->size - LEN, reader->data + bytepos, LEN); + bytepos += LEN; + } + + reader->bp = bytepos << 3u; + + return error; +} + +static unsigned lodepng_inflatev(ucvector* out, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) { + unsigned BFINAL = 0; + LodePNGBitReader reader; + unsigned error = LodePNGBitReader_init(&reader, in, insize); + + if(error) return error; + + while(!BFINAL) { + unsigned BTYPE; + if(reader.bitsize - reader.bp < 3) return 52; /*error, bit pointer will jump past memory*/ + ensureBits9(&reader, 3); + BFINAL = readBits(&reader, 1); + BTYPE = readBits(&reader, 2); + + if(BTYPE == 3) return 20; /*error: invalid BTYPE*/ + else if(BTYPE == 0) error = inflateNoCompression(out, &reader, settings); /*no compression*/ + else error = inflateHuffmanBlock(out, &reader, BTYPE, settings->max_output_size); /*compression, BTYPE 01 or 10*/ + if(!error && settings->max_output_size && out->size > settings->max_output_size) error = 109; + if(error) break; + } + + return error; +} + +unsigned lodepng_inflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) { + ucvector v = ucvector_init(*out, *outsize); + unsigned error = lodepng_inflatev(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; +} + +static unsigned inflatev(ucvector* out, const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) { + if(settings->custom_inflate) { + unsigned error = settings->custom_inflate(&out->data, &out->size, in, insize, settings); + out->allocsize = out->size; + if(error) { + /*the custom inflate is allowed to have its own error codes, however, we translate it to code 110*/ + error = 110; + /*if there's a max output size, and the custom zlib returned error, then indicate that error instead*/ + if(settings->max_output_size && out->size > settings->max_output_size) error = 109; + } + return error; + } else { + return lodepng_inflatev(out, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Deflator (Compressor) / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +static const unsigned MAX_SUPPORTED_DEFLATE_LENGTH = 258; + +/*search the index in the array, that has the largest value smaller than or equal to the given value, +given array must be sorted (if no value is smaller, it returns the size of the given array)*/ +static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) { + /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/ + size_t left = 1; + size_t right = array_size - 1; + + while(left <= right) { + size_t mid = (left + right) >> 1; + if(array[mid] >= value) right = mid - 1; + else left = mid + 1; + } + if(left >= array_size || array[left] > value) left--; + return left; +} + +static void addLengthDistance(uivector* values, size_t length, size_t distance) { + /*values in encoded vector are those used by deflate: + 0-255: literal bytes + 256: end + 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits) + 286-287: invalid*/ + + unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length); + unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]); + unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance); + unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]); + + size_t pos = values->size; + /*TODO: return error when this fails (out of memory)*/ + unsigned ok = uivector_resize(values, values->size + 4); + if(ok) { + values->data[pos + 0] = length_code + FIRST_LENGTH_CODE_INDEX; + values->data[pos + 1] = extra_length; + values->data[pos + 2] = dist_code; + values->data[pos + 3] = extra_distance; + } +} + +/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3 +bytes as input because 3 is the minimum match length for deflate*/ +static const unsigned HASH_NUM_VALUES = 65536; +static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/ + +typedef struct Hash { + int* head; /*hash value to head circular pos - can be outdated if went around window*/ + /*circular pos to prev circular pos*/ + unsigned short* chain; + int* val; /*circular pos to hash value*/ + + /*TODO: do this not only for zeros but for any repeated byte. However for PNG + it's always going to be the zeros that dominate, so not important for PNG*/ + int* headz; /*similar to head, but for chainz*/ + unsigned short* chainz; /*those with same amount of zeros*/ + unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/ +} Hash; + +static unsigned hash_init(Hash* hash, unsigned windowsize) { + unsigned i; + hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES); + hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize); + hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + + hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1)); + hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + + if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) { + return 83; /*alloc fail*/ + } + + /*initialize hash table*/ + for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1; + for(i = 0; i != windowsize; ++i) hash->val[i] = -1; + for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/ + + for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1; + for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/ + + return 0; +} + +static void hash_cleanup(Hash* hash) { + lodepng_free(hash->head); + lodepng_free(hash->val); + lodepng_free(hash->chain); + + lodepng_free(hash->zeros); + lodepng_free(hash->headz); + lodepng_free(hash->chainz); +} + + + +static unsigned getHash(const unsigned char* data, size_t size, size_t pos) { + unsigned result = 0; + if(pos + 2 < size) { + /*A simple shift and xor hash is used. Since the data of PNGs is dominated + by zeroes due to the filters, a better hash does not have a significant + effect on speed in traversing the chain, and causes more time spend on + calculating the hash.*/ + result ^= ((unsigned)data[pos + 0] << 0u); + result ^= ((unsigned)data[pos + 1] << 4u); + result ^= ((unsigned)data[pos + 2] << 8u); + } else { + size_t amount, i; + if(pos >= size) return 0; + amount = size - pos; + for(i = 0; i != amount; ++i) result ^= ((unsigned)data[pos + i] << (i * 8u)); + } + return result & HASH_BIT_MASK; +} + +static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) { + const unsigned char* start = data + pos; + const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH; + if(end > data + size) end = data + size; + data = start; + while(data != end && *data == 0) ++data; + /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/ + return (unsigned)(data - start); +} + +/*wpos = pos & (windowsize - 1)*/ +static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) { + hash->val[wpos] = (int)hashval; + if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval]; + hash->head[hashval] = (int)wpos; + + hash->zeros[wpos] = numzeros; + if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros]; + hash->headz[numzeros] = (int)wpos; +} + +/* +LZ77-encode the data. Return value is error code. The input are raw bytes, the output +is in the form of unsigned integers with codes representing for example literal bytes, or +length/distance pairs. +It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a +sliding window (of windowsize) is used, and all past bytes in that window can be used as +the "dictionary". A brute force search through all possible distances would be slow, and +this hash technique is one out of several ways to speed this up. +*/ +static unsigned encodeLZ77(uivector* out, Hash* hash, + const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize, + unsigned minmatch, unsigned nicematch, unsigned lazymatching) { + size_t pos; + unsigned i, error = 0; + /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/ + unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8u; + unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64; + + unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/ + unsigned numzeros = 0; + + unsigned offset; /*the offset represents the distance in LZ77 terminology*/ + unsigned length; + unsigned lazy = 0; + unsigned lazylength = 0, lazyoffset = 0; + unsigned hashval; + unsigned current_offset, current_length; + unsigned prev_offset; + const unsigned char *lastptr, *foreptr, *backptr; + unsigned hashpos; + + if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/ + if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/ + + if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH; + + for(pos = inpos; pos < insize; ++pos) { + size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/ + unsigned chainlength = 0; + + hashval = getHash(in, insize, pos); + + if(usezeros && hashval == 0) { + if(numzeros == 0) numzeros = countZeros(in, insize, pos); + else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; + } else { + numzeros = 0; + } + + updateHashChain(hash, wpos, hashval, numzeros); + + /*the length and offset found for the current position*/ + length = 0; + offset = 0; + + hashpos = hash->chain[wpos]; + + lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH]; + + /*search for the longest string*/ + prev_offset = 0; + for(;;) { + if(chainlength++ >= maxchainlength) break; + current_offset = (unsigned)(hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize); + + if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/ + prev_offset = current_offset; + if(current_offset > 0) { + /*test the next characters*/ + foreptr = &in[pos]; + backptr = &in[pos - current_offset]; + + /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/ + if(numzeros >= 3) { + unsigned skip = hash->zeros[hashpos]; + if(skip > numzeros) skip = numzeros; + backptr += skip; + foreptr += skip; + } + + while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ { + ++backptr; + ++foreptr; + } + current_length = (unsigned)(foreptr - &in[pos]); + + if(current_length > length) { + length = current_length; /*the longest length*/ + offset = current_offset; /*the offset that is related to this longest length*/ + /*jump out once a length of max length is found (speed gain). This also jumps + out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/ + if(current_length >= nicematch) break; + } + } + + if(hashpos == hash->chain[hashpos]) break; + + if(numzeros >= 3 && length > numzeros) { + hashpos = hash->chainz[hashpos]; + if(hash->zeros[hashpos] != numzeros) break; + } else { + hashpos = hash->chain[hashpos]; + /*outdated hash value, happens if particular value was not encountered in whole last window*/ + if(hash->val[hashpos] != (int)hashval) break; + } + } + + if(lazymatching) { + if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) { + lazy = 1; + lazylength = length; + lazyoffset = offset; + continue; /*try the next byte*/ + } + if(lazy) { + lazy = 0; + if(pos == 0) ERROR_BREAK(81); + if(length > lazylength + 1) { + /*push the previous character as literal*/ + if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/); + } else { + length = lazylength; + offset = lazyoffset; + hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/ + hash->headz[numzeros] = -1; /*idem*/ + --pos; + } + } + } + if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/); + + /*encode it as length/distance pair or literal value*/ + if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ { + if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); + } else if(length < minmatch || (length == 3 && offset > 4096)) { + /*compensate for the fact that longer offsets have more extra bits, a + length of only 3 may be not worth it then*/ + if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); + } else { + addLengthDistance(out, length, offset); + for(i = 1; i < length; ++i) { + ++pos; + wpos = pos & (windowsize - 1); + hashval = getHash(in, insize, pos); + if(usezeros && hashval == 0) { + if(numzeros == 0) numzeros = countZeros(in, insize, pos); + else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; + } else { + numzeros = 0; + } + updateHashChain(hash, wpos, hashval, numzeros); + } + } + } /*end of the loop through each character of input*/ + + return error; +} + +/* /////////////////////////////////////////////////////////////////////////// */ + +static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) { + /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte, + 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/ + + size_t i, numdeflateblocks = (datasize + 65534u) / 65535u; + size_t datapos = 0; + for(i = 0; i != numdeflateblocks; ++i) { + unsigned BFINAL, BTYPE, LEN, NLEN; + unsigned char firstbyte; + size_t pos = out->size; + + BFINAL = (i == numdeflateblocks - 1); + BTYPE = 0; + + LEN = 65535; + if(datasize - datapos < 65535u) LEN = (unsigned)datasize - (unsigned)datapos; + NLEN = 65535 - LEN; + + if(!ucvector_resize(out, out->size + LEN + 5)) return 83; /*alloc fail*/ + + firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1u) << 1u) + ((BTYPE & 2u) << 1u)); + out->data[pos + 0] = firstbyte; + out->data[pos + 1] = (unsigned char)(LEN & 255); + out->data[pos + 2] = (unsigned char)(LEN >> 8u); + out->data[pos + 3] = (unsigned char)(NLEN & 255); + out->data[pos + 4] = (unsigned char)(NLEN >> 8u); + lodepng_memcpy(out->data + pos + 5, data + datapos, LEN); + datapos += LEN; + } + + return 0; +} + +/* +write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees. +tree_ll: the tree for lit and len codes. +tree_d: the tree for distance codes. +*/ +static void writeLZ77data(LodePNGBitWriter* writer, const uivector* lz77_encoded, + const HuffmanTree* tree_ll, const HuffmanTree* tree_d) { + size_t i = 0; + for(i = 0; i != lz77_encoded->size; ++i) { + unsigned val = lz77_encoded->data[i]; + writeBitsReversed(writer, tree_ll->codes[val], tree_ll->lengths[val]); + if(val > 256) /*for a length code, 3 more things have to be added*/ { + unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; + unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; + unsigned length_extra_bits = lz77_encoded->data[++i]; + + unsigned distance_code = lz77_encoded->data[++i]; + + unsigned distance_index = distance_code; + unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index]; + unsigned distance_extra_bits = lz77_encoded->data[++i]; + + writeBits(writer, length_extra_bits, n_length_extra_bits); + writeBitsReversed(writer, tree_d->codes[distance_code], tree_d->lengths[distance_code]); + writeBits(writer, distance_extra_bits, n_distance_extra_bits); + } + } +} + +/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/ +static unsigned deflateDynamic(LodePNGBitWriter* writer, Hash* hash, + const unsigned char* data, size_t datapos, size_t dataend, + const LodePNGCompressSettings* settings, unsigned final) { + unsigned error = 0; + + /* + A block is compressed as follows: The PNG data is lz77 encoded, resulting in + literal bytes and length/distance pairs. This is then huffman compressed with + two huffman trees. One huffman tree is used for the lit and len values ("ll"), + another huffman tree is used for the dist values ("d"). These two trees are + stored using their code lengths, and to compress even more these code lengths + are also run-length encoded and huffman compressed. This gives a huffman tree + of code lengths "cl". The code lengths used to describe this third tree are + the code length code lengths ("clcl"). + */ + + /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/ + uivector lz77_encoded; + HuffmanTree tree_ll; /*tree for lit,len values*/ + HuffmanTree tree_d; /*tree for distance codes*/ + HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/ + unsigned* frequencies_ll = 0; /*frequency of lit,len codes*/ + unsigned* frequencies_d = 0; /*frequency of dist codes*/ + unsigned* frequencies_cl = 0; /*frequency of code length codes*/ + unsigned* bitlen_lld = 0; /*lit,len,dist code lengths (int bits), literally (without repeat codes).*/ + unsigned* bitlen_lld_e = 0; /*bitlen_lld encoded with repeat codes (this is a rudimentary run length compression)*/ + size_t datasize = dataend - datapos; + + /* + If we could call "bitlen_cl" the the code length code lengths ("clcl"), that is the bit lengths of codes to represent + tree_cl in CLCL_ORDER, then due to the huffman compression of huffman tree representations ("two levels"), there are + some analogies: + bitlen_lld is to tree_cl what data is to tree_ll and tree_d. + bitlen_lld_e is to bitlen_lld what lz77_encoded is to data. + bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded. + */ + + unsigned BFINAL = final; + size_t i; + size_t numcodes_ll, numcodes_d, numcodes_lld, numcodes_lld_e, numcodes_cl; + unsigned HLIT, HDIST, HCLEN; + + uivector_init(&lz77_encoded); + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + HuffmanTree_init(&tree_cl); + /* could fit on stack, but >1KB is on the larger side so allocate instead */ + frequencies_ll = (unsigned*)lodepng_malloc(286 * sizeof(*frequencies_ll)); + frequencies_d = (unsigned*)lodepng_malloc(30 * sizeof(*frequencies_d)); + frequencies_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl)); + + if(!frequencies_ll || !frequencies_d || !frequencies_cl) error = 83; /*alloc fail*/ + + /*This while loop never loops due to a break at the end, it is here to + allow breaking out of it to the cleanup phase on error conditions.*/ + while(!error) { + lodepng_memset(frequencies_ll, 0, 286 * sizeof(*frequencies_ll)); + lodepng_memset(frequencies_d, 0, 30 * sizeof(*frequencies_d)); + lodepng_memset(frequencies_cl, 0, NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl)); + + if(settings->use_lz77) { + error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, + settings->minmatch, settings->nicematch, settings->lazymatching); + if(error) break; + } else { + if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/); + for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/ + } + + /*Count the frequencies of lit, len and dist codes*/ + for(i = 0; i != lz77_encoded.size; ++i) { + unsigned symbol = lz77_encoded.data[i]; + ++frequencies_ll[symbol]; + if(symbol > 256) { + unsigned dist = lz77_encoded.data[i + 2]; + ++frequencies_d[dist]; + i += 3; + } + } + frequencies_ll[256] = 1; /*there will be exactly 1 end code, at the end of the block*/ + + /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/ + error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll, 257, 286, 15); + if(error) break; + /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/ + error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d, 2, 30, 15); + if(error) break; + + numcodes_ll = LODEPNG_MIN(tree_ll.numcodes, 286); + numcodes_d = LODEPNG_MIN(tree_d.numcodes, 30); + /*store the code lengths of both generated trees in bitlen_lld*/ + numcodes_lld = numcodes_ll + numcodes_d; + bitlen_lld = (unsigned*)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld)); + /*numcodes_lld_e never needs more size than bitlen_lld*/ + bitlen_lld_e = (unsigned*)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld_e)); + if(!bitlen_lld || !bitlen_lld_e) ERROR_BREAK(83); /*alloc fail*/ + numcodes_lld_e = 0; + + for(i = 0; i != numcodes_ll; ++i) bitlen_lld[i] = tree_ll.lengths[i]; + for(i = 0; i != numcodes_d; ++i) bitlen_lld[numcodes_ll + i] = tree_d.lengths[i]; + + /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times), + 17 (3-10 zeroes), 18 (11-138 zeroes)*/ + for(i = 0; i != numcodes_lld; ++i) { + unsigned j = 0; /*amount of repetitions*/ + while(i + j + 1 < numcodes_lld && bitlen_lld[i + j + 1] == bitlen_lld[i]) ++j; + + if(bitlen_lld[i] == 0 && j >= 2) /*repeat code for zeroes*/ { + ++j; /*include the first zero*/ + if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ { + bitlen_lld_e[numcodes_lld_e++] = 17; + bitlen_lld_e[numcodes_lld_e++] = j - 3; + } else /*repeat code 18 supports max 138 zeroes*/ { + if(j > 138) j = 138; + bitlen_lld_e[numcodes_lld_e++] = 18; + bitlen_lld_e[numcodes_lld_e++] = j - 11; + } + i += (j - 1); + } else if(j >= 3) /*repeat code for value other than zero*/ { + size_t k; + unsigned num = j / 6u, rest = j % 6u; + bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i]; + for(k = 0; k < num; ++k) { + bitlen_lld_e[numcodes_lld_e++] = 16; + bitlen_lld_e[numcodes_lld_e++] = 6 - 3; + } + if(rest >= 3) { + bitlen_lld_e[numcodes_lld_e++] = 16; + bitlen_lld_e[numcodes_lld_e++] = rest - 3; + } + else j -= rest; + i += j; + } else /*too short to benefit from repeat code*/ { + bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i]; + } + } + + /*generate tree_cl, the huffmantree of huffmantrees*/ + for(i = 0; i != numcodes_lld_e; ++i) { + ++frequencies_cl[bitlen_lld_e[i]]; + /*after a repeat code come the bits that specify the number of repetitions, + those don't need to be in the frequencies_cl calculation*/ + if(bitlen_lld_e[i] >= 16) ++i; + } + + error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl, + NUM_CODE_LENGTH_CODES, NUM_CODE_LENGTH_CODES, 7); + if(error) break; + + /*compute amount of code-length-code-lengths to output*/ + numcodes_cl = NUM_CODE_LENGTH_CODES; + /*trim zeros at the end (using CLCL_ORDER), but minimum size must be 4 (see HCLEN below)*/ + while(numcodes_cl > 4u && tree_cl.lengths[CLCL_ORDER[numcodes_cl - 1u]] == 0) { + numcodes_cl--; + } + + /* + Write everything into the output + + After the BFINAL and BTYPE, the dynamic block consists out of the following: + - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN + - (HCLEN+4)*3 bits code lengths of code length alphabet + - HLIT + 257 code lengths of lit/length alphabet (encoded using the code length + alphabet, + possible repetition codes 16, 17, 18) + - HDIST + 1 code lengths of distance alphabet (encoded using the code length + alphabet, + possible repetition codes 16, 17, 18) + - compressed data + - 256 (end code) + */ + + /*Write block type*/ + writeBits(writer, BFINAL, 1); + writeBits(writer, 0, 1); /*first bit of BTYPE "dynamic"*/ + writeBits(writer, 1, 1); /*second bit of BTYPE "dynamic"*/ + + /*write the HLIT, HDIST and HCLEN values*/ + /*all three sizes take trimmed ending zeroes into account, done either by HuffmanTree_makeFromFrequencies + or in the loop for numcodes_cl above, which saves space. */ + HLIT = (unsigned)(numcodes_ll - 257); + HDIST = (unsigned)(numcodes_d - 1); + HCLEN = (unsigned)(numcodes_cl - 4); + writeBits(writer, HLIT, 5); + writeBits(writer, HDIST, 5); + writeBits(writer, HCLEN, 4); + + /*write the code lengths of the code length alphabet ("bitlen_cl")*/ + for(i = 0; i != numcodes_cl; ++i) writeBits(writer, tree_cl.lengths[CLCL_ORDER[i]], 3); + + /*write the lengths of the lit/len AND the dist alphabet*/ + for(i = 0; i != numcodes_lld_e; ++i) { + writeBitsReversed(writer, tree_cl.codes[bitlen_lld_e[i]], tree_cl.lengths[bitlen_lld_e[i]]); + /*extra bits of repeat codes*/ + if(bitlen_lld_e[i] == 16) writeBits(writer, bitlen_lld_e[++i], 2); + else if(bitlen_lld_e[i] == 17) writeBits(writer, bitlen_lld_e[++i], 3); + else if(bitlen_lld_e[i] == 18) writeBits(writer, bitlen_lld_e[++i], 7); + } + + /*write the compressed data symbols*/ + writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d); + /*error: the length of the end code 256 must be larger than 0*/ + if(tree_ll.lengths[256] == 0) ERROR_BREAK(64); + + /*write the end code*/ + writeBitsReversed(writer, tree_ll.codes[256], tree_ll.lengths[256]); + + break; /*end of error-while*/ + } + + /*cleanup*/ + uivector_cleanup(&lz77_encoded); + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + HuffmanTree_cleanup(&tree_cl); + lodepng_free(frequencies_ll); + lodepng_free(frequencies_d); + lodepng_free(frequencies_cl); + lodepng_free(bitlen_lld); + lodepng_free(bitlen_lld_e); + + return error; +} + +static unsigned deflateFixed(LodePNGBitWriter* writer, Hash* hash, + const unsigned char* data, + size_t datapos, size_t dataend, + const LodePNGCompressSettings* settings, unsigned final) { + HuffmanTree tree_ll; /*tree for literal values and length codes*/ + HuffmanTree tree_d; /*tree for distance codes*/ + + unsigned BFINAL = final; + unsigned error = 0; + size_t i; + + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + + error = generateFixedLitLenTree(&tree_ll); + if(!error) error = generateFixedDistanceTree(&tree_d); + + if(!error) { + writeBits(writer, BFINAL, 1); + writeBits(writer, 1, 1); /*first bit of BTYPE*/ + writeBits(writer, 0, 1); /*second bit of BTYPE*/ + + if(settings->use_lz77) /*LZ77 encoded*/ { + uivector lz77_encoded; + uivector_init(&lz77_encoded); + error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, + settings->minmatch, settings->nicematch, settings->lazymatching); + if(!error) writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d); + uivector_cleanup(&lz77_encoded); + } else /*no LZ77, but still will be Huffman compressed*/ { + for(i = datapos; i < dataend; ++i) { + writeBitsReversed(writer, tree_ll.codes[data[i]], tree_ll.lengths[data[i]]); + } + } + /*add END code*/ + if(!error) writeBitsReversed(writer,tree_ll.codes[256], tree_ll.lengths[256]); + } + + /*cleanup*/ + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + + return error; +} + +static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) { + unsigned error = 0; + size_t i, blocksize, numdeflateblocks; + Hash hash; + LodePNGBitWriter writer; + + LodePNGBitWriter_init(&writer, out); + + if(settings->btype > 2) return 61; + else if(settings->btype == 0) return deflateNoCompression(out, in, insize); + else if(settings->btype == 1) blocksize = insize; + else /*if(settings->btype == 2)*/ { + /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/ + blocksize = insize / 8u + 8; + if(blocksize < 65536) blocksize = 65536; + if(blocksize > 262144) blocksize = 262144; + } + + numdeflateblocks = (insize + blocksize - 1) / blocksize; + if(numdeflateblocks == 0) numdeflateblocks = 1; + + error = hash_init(&hash, settings->windowsize); + + if(!error) { + for(i = 0; i != numdeflateblocks && !error; ++i) { + unsigned final = (i == numdeflateblocks - 1); + size_t start = i * blocksize; + size_t end = start + blocksize; + if(end > insize) end = insize; + + if(settings->btype == 1) error = deflateFixed(&writer, &hash, in, start, end, settings, final); + else if(settings->btype == 2) error = deflateDynamic(&writer, &hash, in, start, end, settings, final); + } + } + + hash_cleanup(&hash); + + return error; +} + +unsigned lodepng_deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) { + ucvector v = ucvector_init(*out, *outsize); + unsigned error = lodepng_deflatev(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; +} + +static unsigned deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) { + if(settings->custom_deflate) { + unsigned error = settings->custom_deflate(out, outsize, in, insize, settings); + /*the custom deflate is allowed to have its own error codes, however, we translate it to code 111*/ + return error ? 111 : 0; + } else { + return lodepng_deflate(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Adler32 / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) { + unsigned s1 = adler & 0xffffu; + unsigned s2 = (adler >> 16u) & 0xffffu; + + while(len != 0u) { + unsigned i; + /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/ + unsigned amount = len > 5552u ? 5552u : len; + len -= amount; + for(i = 0; i != amount; ++i) { + s1 += (*data++); + s2 += s1; + } + s1 %= 65521u; + s2 %= 65521u; + } + + return (s2 << 16u) | s1; +} + +/*Return the adler32 of the bytes data[0..len-1]*/ +static unsigned adler32(const unsigned char* data, unsigned len) { + return update_adler32(1u, data, len); +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Zlib / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_DECODER + +static unsigned lodepng_zlib_decompressv(ucvector* out, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) { + unsigned error = 0; + unsigned CM, CINFO, FDICT; + + if(insize < 2) return 53; /*error, size of zlib data too small*/ + /*read information from zlib header*/ + if((in[0] * 256 + in[1]) % 31 != 0) { + /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/ + return 24; + } + + CM = in[0] & 15; + CINFO = (in[0] >> 4) & 15; + /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/ + FDICT = (in[1] >> 5) & 1; + /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/ + + if(CM != 8 || CINFO > 7) { + /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/ + return 25; + } + if(FDICT != 0) { + /*error: the specification of PNG says about the zlib stream: + "The additional flags shall not specify a preset dictionary."*/ + return 26; + } + + error = inflatev(out, in + 2, insize - 2, settings); + if(error) return error; + + if(!settings->ignore_adler32) { + unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]); + unsigned checksum = adler32(out->data, (unsigned)(out->size)); + if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/ + } + + return 0; /*no error*/ +} + + +unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGDecompressSettings* settings) { + ucvector v = ucvector_init(*out, *outsize); + unsigned error = lodepng_zlib_decompressv(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; +} + +/*expected_size is expected output size, to avoid intermediate allocations. Set to 0 if not known. */ +static unsigned zlib_decompress(unsigned char** out, size_t* outsize, size_t expected_size, + const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { + unsigned error; + if(settings->custom_zlib) { + error = settings->custom_zlib(out, outsize, in, insize, settings); + if(error) { + /*the custom zlib is allowed to have its own error codes, however, we translate it to code 110*/ + error = 110; + /*if there's a max output size, and the custom zlib returned error, then indicate that error instead*/ + if(settings->max_output_size && *outsize > settings->max_output_size) error = 109; + } + } else { + ucvector v = ucvector_init(*out, *outsize); + if(expected_size) { + /*reserve the memory to avoid intermediate reallocations*/ + ucvector_resize(&v, *outsize + expected_size); + v.size = *outsize; + } + error = lodepng_zlib_decompressv(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + } + return error; +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER + +unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) { + size_t i; + unsigned error; + unsigned char* deflatedata = 0; + size_t deflatesize = 0; + + error = deflate(&deflatedata, &deflatesize, in, insize, settings); + + *out = NULL; + *outsize = 0; + if(!error) { + *outsize = deflatesize + 6; + *out = (unsigned char*)lodepng_malloc(*outsize); + if(!*out) error = 83; /*alloc fail*/ + } + + if(!error) { + unsigned ADLER32 = adler32(in, (unsigned)insize); + /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/ + unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/ + unsigned FLEVEL = 0; + unsigned FDICT = 0; + unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64; + unsigned FCHECK = 31 - CMFFLG % 31; + CMFFLG += FCHECK; + + (*out)[0] = (unsigned char)(CMFFLG >> 8); + (*out)[1] = (unsigned char)(CMFFLG & 255); + for(i = 0; i != deflatesize; ++i) (*out)[i + 2] = deflatedata[i]; + lodepng_set32bitInt(&(*out)[*outsize - 4], ADLER32); + } + + lodepng_free(deflatedata); + return error; +} + +/* compress using the default or custom zlib function */ +static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) { + if(settings->custom_zlib) { + unsigned error = settings->custom_zlib(out, outsize, in, insize, settings); + /*the custom zlib is allowed to have its own error codes, however, we translate it to code 111*/ + return error ? 111 : 0; + } else { + return lodepng_zlib_compress(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#else /*no LODEPNG_COMPILE_ZLIB*/ + +#ifdef LODEPNG_COMPILE_DECODER +static unsigned zlib_decompress(unsigned char** out, size_t* outsize, size_t expected_size, + const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { + if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ + (void)expected_size; + return settings->custom_zlib(out, outsize, in, insize, settings); +} +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER +static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) { + if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ + return settings->custom_zlib(out, outsize, in, insize, settings); +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#endif /*LODEPNG_COMPILE_ZLIB*/ + +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_ENCODER + +/*this is a good tradeoff between speed and compression ratio*/ +#define DEFAULT_WINDOWSIZE 2048 + +void lodepng_compress_settings_init(LodePNGCompressSettings* settings) { + /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/ + settings->btype = 2; + settings->use_lz77 = 1; + settings->windowsize = DEFAULT_WINDOWSIZE; + settings->minmatch = 3; + settings->nicematch = 128; + settings->lazymatching = 1; + + settings->custom_zlib = 0; + settings->custom_deflate = 0; + settings->custom_context = 0; +} + +const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0}; + + +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) { + settings->ignore_adler32 = 0; + settings->ignore_nlen = 0; + settings->max_output_size = 0; + + settings->custom_zlib = 0; + settings->custom_inflate = 0; + settings->custom_context = 0; +} + +const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0, 0, 0}; + +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // End of Zlib related code. Begin of PNG related code. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_PNG + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / CRC32 / */ +/* ////////////////////////////////////////////////////////////////////////// */ + + +#ifdef LODEPNG_COMPILE_CRC + +static const unsigned lodepng_crc32_table0[256] = { + 0x00000000u, 0x77073096u, 0xee0e612cu, 0x990951bau, 0x076dc419u, 0x706af48fu, 0xe963a535u, 0x9e6495a3u, + 0x0edb8832u, 0x79dcb8a4u, 0xe0d5e91eu, 0x97d2d988u, 0x09b64c2bu, 0x7eb17cbdu, 0xe7b82d07u, 0x90bf1d91u, + 0x1db71064u, 0x6ab020f2u, 0xf3b97148u, 0x84be41deu, 0x1adad47du, 0x6ddde4ebu, 0xf4d4b551u, 0x83d385c7u, + 0x136c9856u, 0x646ba8c0u, 0xfd62f97au, 0x8a65c9ecu, 0x14015c4fu, 0x63066cd9u, 0xfa0f3d63u, 0x8d080df5u, + 0x3b6e20c8u, 0x4c69105eu, 0xd56041e4u, 0xa2677172u, 0x3c03e4d1u, 0x4b04d447u, 0xd20d85fdu, 0xa50ab56bu, + 0x35b5a8fau, 0x42b2986cu, 0xdbbbc9d6u, 0xacbcf940u, 0x32d86ce3u, 0x45df5c75u, 0xdcd60dcfu, 0xabd13d59u, + 0x26d930acu, 0x51de003au, 0xc8d75180u, 0xbfd06116u, 0x21b4f4b5u, 0x56b3c423u, 0xcfba9599u, 0xb8bda50fu, + 0x2802b89eu, 0x5f058808u, 0xc60cd9b2u, 0xb10be924u, 0x2f6f7c87u, 0x58684c11u, 0xc1611dabu, 0xb6662d3du, + 0x76dc4190u, 0x01db7106u, 0x98d220bcu, 0xefd5102au, 0x71b18589u, 0x06b6b51fu, 0x9fbfe4a5u, 0xe8b8d433u, + 0x7807c9a2u, 0x0f00f934u, 0x9609a88eu, 0xe10e9818u, 0x7f6a0dbbu, 0x086d3d2du, 0x91646c97u, 0xe6635c01u, + 0x6b6b51f4u, 0x1c6c6162u, 0x856530d8u, 0xf262004eu, 0x6c0695edu, 0x1b01a57bu, 0x8208f4c1u, 0xf50fc457u, + 0x65b0d9c6u, 0x12b7e950u, 0x8bbeb8eau, 0xfcb9887cu, 0x62dd1ddfu, 0x15da2d49u, 0x8cd37cf3u, 0xfbd44c65u, + 0x4db26158u, 0x3ab551ceu, 0xa3bc0074u, 0xd4bb30e2u, 0x4adfa541u, 0x3dd895d7u, 0xa4d1c46du, 0xd3d6f4fbu, + 0x4369e96au, 0x346ed9fcu, 0xad678846u, 0xda60b8d0u, 0x44042d73u, 0x33031de5u, 0xaa0a4c5fu, 0xdd0d7cc9u, + 0x5005713cu, 0x270241aau, 0xbe0b1010u, 0xc90c2086u, 0x5768b525u, 0x206f85b3u, 0xb966d409u, 0xce61e49fu, + 0x5edef90eu, 0x29d9c998u, 0xb0d09822u, 0xc7d7a8b4u, 0x59b33d17u, 0x2eb40d81u, 0xb7bd5c3bu, 0xc0ba6cadu, + 0xedb88320u, 0x9abfb3b6u, 0x03b6e20cu, 0x74b1d29au, 0xead54739u, 0x9dd277afu, 0x04db2615u, 0x73dc1683u, + 0xe3630b12u, 0x94643b84u, 0x0d6d6a3eu, 0x7a6a5aa8u, 0xe40ecf0bu, 0x9309ff9du, 0x0a00ae27u, 0x7d079eb1u, + 0xf00f9344u, 0x8708a3d2u, 0x1e01f268u, 0x6906c2feu, 0xf762575du, 0x806567cbu, 0x196c3671u, 0x6e6b06e7u, + 0xfed41b76u, 0x89d32be0u, 0x10da7a5au, 0x67dd4accu, 0xf9b9df6fu, 0x8ebeeff9u, 0x17b7be43u, 0x60b08ed5u, + 0xd6d6a3e8u, 0xa1d1937eu, 0x38d8c2c4u, 0x4fdff252u, 0xd1bb67f1u, 0xa6bc5767u, 0x3fb506ddu, 0x48b2364bu, + 0xd80d2bdau, 0xaf0a1b4cu, 0x36034af6u, 0x41047a60u, 0xdf60efc3u, 0xa867df55u, 0x316e8eefu, 0x4669be79u, + 0xcb61b38cu, 0xbc66831au, 0x256fd2a0u, 0x5268e236u, 0xcc0c7795u, 0xbb0b4703u, 0x220216b9u, 0x5505262fu, + 0xc5ba3bbeu, 0xb2bd0b28u, 0x2bb45a92u, 0x5cb36a04u, 0xc2d7ffa7u, 0xb5d0cf31u, 0x2cd99e8bu, 0x5bdeae1du, + 0x9b64c2b0u, 0xec63f226u, 0x756aa39cu, 0x026d930au, 0x9c0906a9u, 0xeb0e363fu, 0x72076785u, 0x05005713u, + 0x95bf4a82u, 0xe2b87a14u, 0x7bb12baeu, 0x0cb61b38u, 0x92d28e9bu, 0xe5d5be0du, 0x7cdcefb7u, 0x0bdbdf21u, + 0x86d3d2d4u, 0xf1d4e242u, 0x68ddb3f8u, 0x1fda836eu, 0x81be16cdu, 0xf6b9265bu, 0x6fb077e1u, 0x18b74777u, + 0x88085ae6u, 0xff0f6a70u, 0x66063bcau, 0x11010b5cu, 0x8f659effu, 0xf862ae69u, 0x616bffd3u, 0x166ccf45u, + 0xa00ae278u, 0xd70dd2eeu, 0x4e048354u, 0x3903b3c2u, 0xa7672661u, 0xd06016f7u, 0x4969474du, 0x3e6e77dbu, + 0xaed16a4au, 0xd9d65adcu, 0x40df0b66u, 0x37d83bf0u, 0xa9bcae53u, 0xdebb9ec5u, 0x47b2cf7fu, 0x30b5ffe9u, + 0xbdbdf21cu, 0xcabac28au, 0x53b39330u, 0x24b4a3a6u, 0xbad03605u, 0xcdd70693u, 0x54de5729u, 0x23d967bfu, + 0xb3667a2eu, 0xc4614ab8u, 0x5d681b02u, 0x2a6f2b94u, 0xb40bbe37u, 0xc30c8ea1u, 0x5a05df1bu, 0x2d02ef8du +}; + +static const unsigned lodepng_crc32_table1[256] = { + 0x00000000u, 0x191b3141u, 0x32366282u, 0x2b2d53c3u, 0x646cc504u, 0x7d77f445u, 0x565aa786u, 0x4f4196c7u, + 0xc8d98a08u, 0xd1c2bb49u, 0xfaefe88au, 0xe3f4d9cbu, 0xacb54f0cu, 0xb5ae7e4du, 0x9e832d8eu, 0x87981ccfu, + 0x4ac21251u, 0x53d92310u, 0x78f470d3u, 0x61ef4192u, 0x2eaed755u, 0x37b5e614u, 0x1c98b5d7u, 0x05838496u, + 0x821b9859u, 0x9b00a918u, 0xb02dfadbu, 0xa936cb9au, 0xe6775d5du, 0xff6c6c1cu, 0xd4413fdfu, 0xcd5a0e9eu, + 0x958424a2u, 0x8c9f15e3u, 0xa7b24620u, 0xbea97761u, 0xf1e8e1a6u, 0xe8f3d0e7u, 0xc3de8324u, 0xdac5b265u, + 0x5d5daeaau, 0x44469febu, 0x6f6bcc28u, 0x7670fd69u, 0x39316baeu, 0x202a5aefu, 0x0b07092cu, 0x121c386du, + 0xdf4636f3u, 0xc65d07b2u, 0xed705471u, 0xf46b6530u, 0xbb2af3f7u, 0xa231c2b6u, 0x891c9175u, 0x9007a034u, + 0x179fbcfbu, 0x0e848dbau, 0x25a9de79u, 0x3cb2ef38u, 0x73f379ffu, 0x6ae848beu, 0x41c51b7du, 0x58de2a3cu, + 0xf0794f05u, 0xe9627e44u, 0xc24f2d87u, 0xdb541cc6u, 0x94158a01u, 0x8d0ebb40u, 0xa623e883u, 0xbf38d9c2u, + 0x38a0c50du, 0x21bbf44cu, 0x0a96a78fu, 0x138d96ceu, 0x5ccc0009u, 0x45d73148u, 0x6efa628bu, 0x77e153cau, + 0xbabb5d54u, 0xa3a06c15u, 0x888d3fd6u, 0x91960e97u, 0xded79850u, 0xc7cca911u, 0xece1fad2u, 0xf5facb93u, + 0x7262d75cu, 0x6b79e61du, 0x4054b5deu, 0x594f849fu, 0x160e1258u, 0x0f152319u, 0x243870dau, 0x3d23419bu, + 0x65fd6ba7u, 0x7ce65ae6u, 0x57cb0925u, 0x4ed03864u, 0x0191aea3u, 0x188a9fe2u, 0x33a7cc21u, 0x2abcfd60u, + 0xad24e1afu, 0xb43fd0eeu, 0x9f12832du, 0x8609b26cu, 0xc94824abu, 0xd05315eau, 0xfb7e4629u, 0xe2657768u, + 0x2f3f79f6u, 0x362448b7u, 0x1d091b74u, 0x04122a35u, 0x4b53bcf2u, 0x52488db3u, 0x7965de70u, 0x607eef31u, + 0xe7e6f3feu, 0xfefdc2bfu, 0xd5d0917cu, 0xcccba03du, 0x838a36fau, 0x9a9107bbu, 0xb1bc5478u, 0xa8a76539u, + 0x3b83984bu, 0x2298a90au, 0x09b5fac9u, 0x10aecb88u, 0x5fef5d4fu, 0x46f46c0eu, 0x6dd93fcdu, 0x74c20e8cu, + 0xf35a1243u, 0xea412302u, 0xc16c70c1u, 0xd8774180u, 0x9736d747u, 0x8e2de606u, 0xa500b5c5u, 0xbc1b8484u, + 0x71418a1au, 0x685abb5bu, 0x4377e898u, 0x5a6cd9d9u, 0x152d4f1eu, 0x0c367e5fu, 0x271b2d9cu, 0x3e001cddu, + 0xb9980012u, 0xa0833153u, 0x8bae6290u, 0x92b553d1u, 0xddf4c516u, 0xc4eff457u, 0xefc2a794u, 0xf6d996d5u, + 0xae07bce9u, 0xb71c8da8u, 0x9c31de6bu, 0x852aef2au, 0xca6b79edu, 0xd37048acu, 0xf85d1b6fu, 0xe1462a2eu, + 0x66de36e1u, 0x7fc507a0u, 0x54e85463u, 0x4df36522u, 0x02b2f3e5u, 0x1ba9c2a4u, 0x30849167u, 0x299fa026u, + 0xe4c5aeb8u, 0xfdde9ff9u, 0xd6f3cc3au, 0xcfe8fd7bu, 0x80a96bbcu, 0x99b25afdu, 0xb29f093eu, 0xab84387fu, + 0x2c1c24b0u, 0x350715f1u, 0x1e2a4632u, 0x07317773u, 0x4870e1b4u, 0x516bd0f5u, 0x7a468336u, 0x635db277u, + 0xcbfad74eu, 0xd2e1e60fu, 0xf9ccb5ccu, 0xe0d7848du, 0xaf96124au, 0xb68d230bu, 0x9da070c8u, 0x84bb4189u, + 0x03235d46u, 0x1a386c07u, 0x31153fc4u, 0x280e0e85u, 0x674f9842u, 0x7e54a903u, 0x5579fac0u, 0x4c62cb81u, + 0x8138c51fu, 0x9823f45eu, 0xb30ea79du, 0xaa1596dcu, 0xe554001bu, 0xfc4f315au, 0xd7626299u, 0xce7953d8u, + 0x49e14f17u, 0x50fa7e56u, 0x7bd72d95u, 0x62cc1cd4u, 0x2d8d8a13u, 0x3496bb52u, 0x1fbbe891u, 0x06a0d9d0u, + 0x5e7ef3ecu, 0x4765c2adu, 0x6c48916eu, 0x7553a02fu, 0x3a1236e8u, 0x230907a9u, 0x0824546au, 0x113f652bu, + 0x96a779e4u, 0x8fbc48a5u, 0xa4911b66u, 0xbd8a2a27u, 0xf2cbbce0u, 0xebd08da1u, 0xc0fdde62u, 0xd9e6ef23u, + 0x14bce1bdu, 0x0da7d0fcu, 0x268a833fu, 0x3f91b27eu, 0x70d024b9u, 0x69cb15f8u, 0x42e6463bu, 0x5bfd777au, + 0xdc656bb5u, 0xc57e5af4u, 0xee530937u, 0xf7483876u, 0xb809aeb1u, 0xa1129ff0u, 0x8a3fcc33u, 0x9324fd72u +}; + +static const unsigned lodepng_crc32_table2[256] = { + 0x00000000u, 0x01c26a37u, 0x0384d46eu, 0x0246be59u, 0x0709a8dcu, 0x06cbc2ebu, 0x048d7cb2u, 0x054f1685u, + 0x0e1351b8u, 0x0fd13b8fu, 0x0d9785d6u, 0x0c55efe1u, 0x091af964u, 0x08d89353u, 0x0a9e2d0au, 0x0b5c473du, + 0x1c26a370u, 0x1de4c947u, 0x1fa2771eu, 0x1e601d29u, 0x1b2f0bacu, 0x1aed619bu, 0x18abdfc2u, 0x1969b5f5u, + 0x1235f2c8u, 0x13f798ffu, 0x11b126a6u, 0x10734c91u, 0x153c5a14u, 0x14fe3023u, 0x16b88e7au, 0x177ae44du, + 0x384d46e0u, 0x398f2cd7u, 0x3bc9928eu, 0x3a0bf8b9u, 0x3f44ee3cu, 0x3e86840bu, 0x3cc03a52u, 0x3d025065u, + 0x365e1758u, 0x379c7d6fu, 0x35dac336u, 0x3418a901u, 0x3157bf84u, 0x3095d5b3u, 0x32d36beau, 0x331101ddu, + 0x246be590u, 0x25a98fa7u, 0x27ef31feu, 0x262d5bc9u, 0x23624d4cu, 0x22a0277bu, 0x20e69922u, 0x2124f315u, + 0x2a78b428u, 0x2bbade1fu, 0x29fc6046u, 0x283e0a71u, 0x2d711cf4u, 0x2cb376c3u, 0x2ef5c89au, 0x2f37a2adu, + 0x709a8dc0u, 0x7158e7f7u, 0x731e59aeu, 0x72dc3399u, 0x7793251cu, 0x76514f2bu, 0x7417f172u, 0x75d59b45u, + 0x7e89dc78u, 0x7f4bb64fu, 0x7d0d0816u, 0x7ccf6221u, 0x798074a4u, 0x78421e93u, 0x7a04a0cau, 0x7bc6cafdu, + 0x6cbc2eb0u, 0x6d7e4487u, 0x6f38fadeu, 0x6efa90e9u, 0x6bb5866cu, 0x6a77ec5bu, 0x68315202u, 0x69f33835u, + 0x62af7f08u, 0x636d153fu, 0x612bab66u, 0x60e9c151u, 0x65a6d7d4u, 0x6464bde3u, 0x662203bau, 0x67e0698du, + 0x48d7cb20u, 0x4915a117u, 0x4b531f4eu, 0x4a917579u, 0x4fde63fcu, 0x4e1c09cbu, 0x4c5ab792u, 0x4d98dda5u, + 0x46c49a98u, 0x4706f0afu, 0x45404ef6u, 0x448224c1u, 0x41cd3244u, 0x400f5873u, 0x4249e62au, 0x438b8c1du, + 0x54f16850u, 0x55330267u, 0x5775bc3eu, 0x56b7d609u, 0x53f8c08cu, 0x523aaabbu, 0x507c14e2u, 0x51be7ed5u, + 0x5ae239e8u, 0x5b2053dfu, 0x5966ed86u, 0x58a487b1u, 0x5deb9134u, 0x5c29fb03u, 0x5e6f455au, 0x5fad2f6du, + 0xe1351b80u, 0xe0f771b7u, 0xe2b1cfeeu, 0xe373a5d9u, 0xe63cb35cu, 0xe7fed96bu, 0xe5b86732u, 0xe47a0d05u, + 0xef264a38u, 0xeee4200fu, 0xeca29e56u, 0xed60f461u, 0xe82fe2e4u, 0xe9ed88d3u, 0xebab368au, 0xea695cbdu, + 0xfd13b8f0u, 0xfcd1d2c7u, 0xfe976c9eu, 0xff5506a9u, 0xfa1a102cu, 0xfbd87a1bu, 0xf99ec442u, 0xf85cae75u, + 0xf300e948u, 0xf2c2837fu, 0xf0843d26u, 0xf1465711u, 0xf4094194u, 0xf5cb2ba3u, 0xf78d95fau, 0xf64fffcdu, + 0xd9785d60u, 0xd8ba3757u, 0xdafc890eu, 0xdb3ee339u, 0xde71f5bcu, 0xdfb39f8bu, 0xddf521d2u, 0xdc374be5u, + 0xd76b0cd8u, 0xd6a966efu, 0xd4efd8b6u, 0xd52db281u, 0xd062a404u, 0xd1a0ce33u, 0xd3e6706au, 0xd2241a5du, + 0xc55efe10u, 0xc49c9427u, 0xc6da2a7eu, 0xc7184049u, 0xc25756ccu, 0xc3953cfbu, 0xc1d382a2u, 0xc011e895u, + 0xcb4dafa8u, 0xca8fc59fu, 0xc8c97bc6u, 0xc90b11f1u, 0xcc440774u, 0xcd866d43u, 0xcfc0d31au, 0xce02b92du, + 0x91af9640u, 0x906dfc77u, 0x922b422eu, 0x93e92819u, 0x96a63e9cu, 0x976454abu, 0x9522eaf2u, 0x94e080c5u, + 0x9fbcc7f8u, 0x9e7eadcfu, 0x9c381396u, 0x9dfa79a1u, 0x98b56f24u, 0x99770513u, 0x9b31bb4au, 0x9af3d17du, + 0x8d893530u, 0x8c4b5f07u, 0x8e0de15eu, 0x8fcf8b69u, 0x8a809decu, 0x8b42f7dbu, 0x89044982u, 0x88c623b5u, + 0x839a6488u, 0x82580ebfu, 0x801eb0e6u, 0x81dcdad1u, 0x8493cc54u, 0x8551a663u, 0x8717183au, 0x86d5720du, + 0xa9e2d0a0u, 0xa820ba97u, 0xaa6604ceu, 0xaba46ef9u, 0xaeeb787cu, 0xaf29124bu, 0xad6fac12u, 0xacadc625u, + 0xa7f18118u, 0xa633eb2fu, 0xa4755576u, 0xa5b73f41u, 0xa0f829c4u, 0xa13a43f3u, 0xa37cfdaau, 0xa2be979du, + 0xb5c473d0u, 0xb40619e7u, 0xb640a7beu, 0xb782cd89u, 0xb2cddb0cu, 0xb30fb13bu, 0xb1490f62u, 0xb08b6555u, + 0xbbd72268u, 0xba15485fu, 0xb853f606u, 0xb9919c31u, 0xbcde8ab4u, 0xbd1ce083u, 0xbf5a5edau, 0xbe9834edu +}; + +static const unsigned lodepng_crc32_table3[256] = { + 0x00000000u, 0xb8bc6765u, 0xaa09c88bu, 0x12b5afeeu, 0x8f629757u, 0x37def032u, 0x256b5fdcu, 0x9dd738b9u, + 0xc5b428efu, 0x7d084f8au, 0x6fbde064u, 0xd7018701u, 0x4ad6bfb8u, 0xf26ad8ddu, 0xe0df7733u, 0x58631056u, + 0x5019579fu, 0xe8a530fau, 0xfa109f14u, 0x42acf871u, 0xdf7bc0c8u, 0x67c7a7adu, 0x75720843u, 0xcdce6f26u, + 0x95ad7f70u, 0x2d111815u, 0x3fa4b7fbu, 0x8718d09eu, 0x1acfe827u, 0xa2738f42u, 0xb0c620acu, 0x087a47c9u, + 0xa032af3eu, 0x188ec85bu, 0x0a3b67b5u, 0xb28700d0u, 0x2f503869u, 0x97ec5f0cu, 0x8559f0e2u, 0x3de59787u, + 0x658687d1u, 0xdd3ae0b4u, 0xcf8f4f5au, 0x7733283fu, 0xeae41086u, 0x525877e3u, 0x40edd80du, 0xf851bf68u, + 0xf02bf8a1u, 0x48979fc4u, 0x5a22302au, 0xe29e574fu, 0x7f496ff6u, 0xc7f50893u, 0xd540a77du, 0x6dfcc018u, + 0x359fd04eu, 0x8d23b72bu, 0x9f9618c5u, 0x272a7fa0u, 0xbafd4719u, 0x0241207cu, 0x10f48f92u, 0xa848e8f7u, + 0x9b14583du, 0x23a83f58u, 0x311d90b6u, 0x89a1f7d3u, 0x1476cf6au, 0xaccaa80fu, 0xbe7f07e1u, 0x06c36084u, + 0x5ea070d2u, 0xe61c17b7u, 0xf4a9b859u, 0x4c15df3cu, 0xd1c2e785u, 0x697e80e0u, 0x7bcb2f0eu, 0xc377486bu, + 0xcb0d0fa2u, 0x73b168c7u, 0x6104c729u, 0xd9b8a04cu, 0x446f98f5u, 0xfcd3ff90u, 0xee66507eu, 0x56da371bu, + 0x0eb9274du, 0xb6054028u, 0xa4b0efc6u, 0x1c0c88a3u, 0x81dbb01au, 0x3967d77fu, 0x2bd27891u, 0x936e1ff4u, + 0x3b26f703u, 0x839a9066u, 0x912f3f88u, 0x299358edu, 0xb4446054u, 0x0cf80731u, 0x1e4da8dfu, 0xa6f1cfbau, + 0xfe92dfecu, 0x462eb889u, 0x549b1767u, 0xec277002u, 0x71f048bbu, 0xc94c2fdeu, 0xdbf98030u, 0x6345e755u, + 0x6b3fa09cu, 0xd383c7f9u, 0xc1366817u, 0x798a0f72u, 0xe45d37cbu, 0x5ce150aeu, 0x4e54ff40u, 0xf6e89825u, + 0xae8b8873u, 0x1637ef16u, 0x048240f8u, 0xbc3e279du, 0x21e91f24u, 0x99557841u, 0x8be0d7afu, 0x335cb0cau, + 0xed59b63bu, 0x55e5d15eu, 0x47507eb0u, 0xffec19d5u, 0x623b216cu, 0xda874609u, 0xc832e9e7u, 0x708e8e82u, + 0x28ed9ed4u, 0x9051f9b1u, 0x82e4565fu, 0x3a58313au, 0xa78f0983u, 0x1f336ee6u, 0x0d86c108u, 0xb53aa66du, + 0xbd40e1a4u, 0x05fc86c1u, 0x1749292fu, 0xaff54e4au, 0x322276f3u, 0x8a9e1196u, 0x982bbe78u, 0x2097d91du, + 0x78f4c94bu, 0xc048ae2eu, 0xd2fd01c0u, 0x6a4166a5u, 0xf7965e1cu, 0x4f2a3979u, 0x5d9f9697u, 0xe523f1f2u, + 0x4d6b1905u, 0xf5d77e60u, 0xe762d18eu, 0x5fdeb6ebu, 0xc2098e52u, 0x7ab5e937u, 0x680046d9u, 0xd0bc21bcu, + 0x88df31eau, 0x3063568fu, 0x22d6f961u, 0x9a6a9e04u, 0x07bda6bdu, 0xbf01c1d8u, 0xadb46e36u, 0x15080953u, + 0x1d724e9au, 0xa5ce29ffu, 0xb77b8611u, 0x0fc7e174u, 0x9210d9cdu, 0x2aacbea8u, 0x38191146u, 0x80a57623u, + 0xd8c66675u, 0x607a0110u, 0x72cfaefeu, 0xca73c99bu, 0x57a4f122u, 0xef189647u, 0xfdad39a9u, 0x45115eccu, + 0x764dee06u, 0xcef18963u, 0xdc44268du, 0x64f841e8u, 0xf92f7951u, 0x41931e34u, 0x5326b1dau, 0xeb9ad6bfu, + 0xb3f9c6e9u, 0x0b45a18cu, 0x19f00e62u, 0xa14c6907u, 0x3c9b51beu, 0x842736dbu, 0x96929935u, 0x2e2efe50u, + 0x2654b999u, 0x9ee8defcu, 0x8c5d7112u, 0x34e11677u, 0xa9362eceu, 0x118a49abu, 0x033fe645u, 0xbb838120u, + 0xe3e09176u, 0x5b5cf613u, 0x49e959fdu, 0xf1553e98u, 0x6c820621u, 0xd43e6144u, 0xc68bceaau, 0x7e37a9cfu, + 0xd67f4138u, 0x6ec3265du, 0x7c7689b3u, 0xc4caeed6u, 0x591dd66fu, 0xe1a1b10au, 0xf3141ee4u, 0x4ba87981u, + 0x13cb69d7u, 0xab770eb2u, 0xb9c2a15cu, 0x017ec639u, 0x9ca9fe80u, 0x241599e5u, 0x36a0360bu, 0x8e1c516eu, + 0x866616a7u, 0x3eda71c2u, 0x2c6fde2cu, 0x94d3b949u, 0x090481f0u, 0xb1b8e695u, 0xa30d497bu, 0x1bb12e1eu, + 0x43d23e48u, 0xfb6e592du, 0xe9dbf6c3u, 0x516791a6u, 0xccb0a91fu, 0x740cce7au, 0x66b96194u, 0xde0506f1u +}; + +static const unsigned lodepng_crc32_table4[256] = { + 0x00000000u, 0x3d6029b0u, 0x7ac05360u, 0x47a07ad0u, 0xf580a6c0u, 0xc8e08f70u, 0x8f40f5a0u, 0xb220dc10u, + 0x30704bc1u, 0x0d106271u, 0x4ab018a1u, 0x77d03111u, 0xc5f0ed01u, 0xf890c4b1u, 0xbf30be61u, 0x825097d1u, + 0x60e09782u, 0x5d80be32u, 0x1a20c4e2u, 0x2740ed52u, 0x95603142u, 0xa80018f2u, 0xefa06222u, 0xd2c04b92u, + 0x5090dc43u, 0x6df0f5f3u, 0x2a508f23u, 0x1730a693u, 0xa5107a83u, 0x98705333u, 0xdfd029e3u, 0xe2b00053u, + 0xc1c12f04u, 0xfca106b4u, 0xbb017c64u, 0x866155d4u, 0x344189c4u, 0x0921a074u, 0x4e81daa4u, 0x73e1f314u, + 0xf1b164c5u, 0xccd14d75u, 0x8b7137a5u, 0xb6111e15u, 0x0431c205u, 0x3951ebb5u, 0x7ef19165u, 0x4391b8d5u, + 0xa121b886u, 0x9c419136u, 0xdbe1ebe6u, 0xe681c256u, 0x54a11e46u, 0x69c137f6u, 0x2e614d26u, 0x13016496u, + 0x9151f347u, 0xac31daf7u, 0xeb91a027u, 0xd6f18997u, 0x64d15587u, 0x59b17c37u, 0x1e1106e7u, 0x23712f57u, + 0x58f35849u, 0x659371f9u, 0x22330b29u, 0x1f532299u, 0xad73fe89u, 0x9013d739u, 0xd7b3ade9u, 0xead38459u, + 0x68831388u, 0x55e33a38u, 0x124340e8u, 0x2f236958u, 0x9d03b548u, 0xa0639cf8u, 0xe7c3e628u, 0xdaa3cf98u, + 0x3813cfcbu, 0x0573e67bu, 0x42d39cabu, 0x7fb3b51bu, 0xcd93690bu, 0xf0f340bbu, 0xb7533a6bu, 0x8a3313dbu, + 0x0863840au, 0x3503adbau, 0x72a3d76au, 0x4fc3fedau, 0xfde322cau, 0xc0830b7au, 0x872371aau, 0xba43581au, + 0x9932774du, 0xa4525efdu, 0xe3f2242du, 0xde920d9du, 0x6cb2d18du, 0x51d2f83du, 0x167282edu, 0x2b12ab5du, + 0xa9423c8cu, 0x9422153cu, 0xd3826fecu, 0xeee2465cu, 0x5cc29a4cu, 0x61a2b3fcu, 0x2602c92cu, 0x1b62e09cu, + 0xf9d2e0cfu, 0xc4b2c97fu, 0x8312b3afu, 0xbe729a1fu, 0x0c52460fu, 0x31326fbfu, 0x7692156fu, 0x4bf23cdfu, + 0xc9a2ab0eu, 0xf4c282beu, 0xb362f86eu, 0x8e02d1deu, 0x3c220dceu, 0x0142247eu, 0x46e25eaeu, 0x7b82771eu, + 0xb1e6b092u, 0x8c869922u, 0xcb26e3f2u, 0xf646ca42u, 0x44661652u, 0x79063fe2u, 0x3ea64532u, 0x03c66c82u, + 0x8196fb53u, 0xbcf6d2e3u, 0xfb56a833u, 0xc6368183u, 0x74165d93u, 0x49767423u, 0x0ed60ef3u, 0x33b62743u, + 0xd1062710u, 0xec660ea0u, 0xabc67470u, 0x96a65dc0u, 0x248681d0u, 0x19e6a860u, 0x5e46d2b0u, 0x6326fb00u, + 0xe1766cd1u, 0xdc164561u, 0x9bb63fb1u, 0xa6d61601u, 0x14f6ca11u, 0x2996e3a1u, 0x6e369971u, 0x5356b0c1u, + 0x70279f96u, 0x4d47b626u, 0x0ae7ccf6u, 0x3787e546u, 0x85a73956u, 0xb8c710e6u, 0xff676a36u, 0xc2074386u, + 0x4057d457u, 0x7d37fde7u, 0x3a978737u, 0x07f7ae87u, 0xb5d77297u, 0x88b75b27u, 0xcf1721f7u, 0xf2770847u, + 0x10c70814u, 0x2da721a4u, 0x6a075b74u, 0x576772c4u, 0xe547aed4u, 0xd8278764u, 0x9f87fdb4u, 0xa2e7d404u, + 0x20b743d5u, 0x1dd76a65u, 0x5a7710b5u, 0x67173905u, 0xd537e515u, 0xe857cca5u, 0xaff7b675u, 0x92979fc5u, + 0xe915e8dbu, 0xd475c16bu, 0x93d5bbbbu, 0xaeb5920bu, 0x1c954e1bu, 0x21f567abu, 0x66551d7bu, 0x5b3534cbu, + 0xd965a31au, 0xe4058aaau, 0xa3a5f07au, 0x9ec5d9cau, 0x2ce505dau, 0x11852c6au, 0x562556bau, 0x6b457f0au, + 0x89f57f59u, 0xb49556e9u, 0xf3352c39u, 0xce550589u, 0x7c75d999u, 0x4115f029u, 0x06b58af9u, 0x3bd5a349u, + 0xb9853498u, 0x84e51d28u, 0xc34567f8u, 0xfe254e48u, 0x4c059258u, 0x7165bbe8u, 0x36c5c138u, 0x0ba5e888u, + 0x28d4c7dfu, 0x15b4ee6fu, 0x521494bfu, 0x6f74bd0fu, 0xdd54611fu, 0xe03448afu, 0xa794327fu, 0x9af41bcfu, + 0x18a48c1eu, 0x25c4a5aeu, 0x6264df7eu, 0x5f04f6ceu, 0xed242adeu, 0xd044036eu, 0x97e479beu, 0xaa84500eu, + 0x4834505du, 0x755479edu, 0x32f4033du, 0x0f942a8du, 0xbdb4f69du, 0x80d4df2du, 0xc774a5fdu, 0xfa148c4du, + 0x78441b9cu, 0x4524322cu, 0x028448fcu, 0x3fe4614cu, 0x8dc4bd5cu, 0xb0a494ecu, 0xf704ee3cu, 0xca64c78cu +}; + +static const unsigned lodepng_crc32_table5[256] = { + 0x00000000u, 0xcb5cd3a5u, 0x4dc8a10bu, 0x869472aeu, 0x9b914216u, 0x50cd91b3u, 0xd659e31du, 0x1d0530b8u, + 0xec53826du, 0x270f51c8u, 0xa19b2366u, 0x6ac7f0c3u, 0x77c2c07bu, 0xbc9e13deu, 0x3a0a6170u, 0xf156b2d5u, + 0x03d6029bu, 0xc88ad13eu, 0x4e1ea390u, 0x85427035u, 0x9847408du, 0x531b9328u, 0xd58fe186u, 0x1ed33223u, + 0xef8580f6u, 0x24d95353u, 0xa24d21fdu, 0x6911f258u, 0x7414c2e0u, 0xbf481145u, 0x39dc63ebu, 0xf280b04eu, + 0x07ac0536u, 0xccf0d693u, 0x4a64a43du, 0x81387798u, 0x9c3d4720u, 0x57619485u, 0xd1f5e62bu, 0x1aa9358eu, + 0xebff875bu, 0x20a354feu, 0xa6372650u, 0x6d6bf5f5u, 0x706ec54du, 0xbb3216e8u, 0x3da66446u, 0xf6fab7e3u, + 0x047a07adu, 0xcf26d408u, 0x49b2a6a6u, 0x82ee7503u, 0x9feb45bbu, 0x54b7961eu, 0xd223e4b0u, 0x197f3715u, + 0xe82985c0u, 0x23755665u, 0xa5e124cbu, 0x6ebdf76eu, 0x73b8c7d6u, 0xb8e41473u, 0x3e7066ddu, 0xf52cb578u, + 0x0f580a6cu, 0xc404d9c9u, 0x4290ab67u, 0x89cc78c2u, 0x94c9487au, 0x5f959bdfu, 0xd901e971u, 0x125d3ad4u, + 0xe30b8801u, 0x28575ba4u, 0xaec3290au, 0x659ffaafu, 0x789aca17u, 0xb3c619b2u, 0x35526b1cu, 0xfe0eb8b9u, + 0x0c8e08f7u, 0xc7d2db52u, 0x4146a9fcu, 0x8a1a7a59u, 0x971f4ae1u, 0x5c439944u, 0xdad7ebeau, 0x118b384fu, + 0xe0dd8a9au, 0x2b81593fu, 0xad152b91u, 0x6649f834u, 0x7b4cc88cu, 0xb0101b29u, 0x36846987u, 0xfdd8ba22u, + 0x08f40f5au, 0xc3a8dcffu, 0x453cae51u, 0x8e607df4u, 0x93654d4cu, 0x58399ee9u, 0xdeadec47u, 0x15f13fe2u, + 0xe4a78d37u, 0x2ffb5e92u, 0xa96f2c3cu, 0x6233ff99u, 0x7f36cf21u, 0xb46a1c84u, 0x32fe6e2au, 0xf9a2bd8fu, + 0x0b220dc1u, 0xc07ede64u, 0x46eaaccau, 0x8db67f6fu, 0x90b34fd7u, 0x5bef9c72u, 0xdd7beedcu, 0x16273d79u, + 0xe7718facu, 0x2c2d5c09u, 0xaab92ea7u, 0x61e5fd02u, 0x7ce0cdbau, 0xb7bc1e1fu, 0x31286cb1u, 0xfa74bf14u, + 0x1eb014d8u, 0xd5ecc77du, 0x5378b5d3u, 0x98246676u, 0x852156ceu, 0x4e7d856bu, 0xc8e9f7c5u, 0x03b52460u, + 0xf2e396b5u, 0x39bf4510u, 0xbf2b37beu, 0x7477e41bu, 0x6972d4a3u, 0xa22e0706u, 0x24ba75a8u, 0xefe6a60du, + 0x1d661643u, 0xd63ac5e6u, 0x50aeb748u, 0x9bf264edu, 0x86f75455u, 0x4dab87f0u, 0xcb3ff55eu, 0x006326fbu, + 0xf135942eu, 0x3a69478bu, 0xbcfd3525u, 0x77a1e680u, 0x6aa4d638u, 0xa1f8059du, 0x276c7733u, 0xec30a496u, + 0x191c11eeu, 0xd240c24bu, 0x54d4b0e5u, 0x9f886340u, 0x828d53f8u, 0x49d1805du, 0xcf45f2f3u, 0x04192156u, + 0xf54f9383u, 0x3e134026u, 0xb8873288u, 0x73dbe12du, 0x6eded195u, 0xa5820230u, 0x2316709eu, 0xe84aa33bu, + 0x1aca1375u, 0xd196c0d0u, 0x5702b27eu, 0x9c5e61dbu, 0x815b5163u, 0x4a0782c6u, 0xcc93f068u, 0x07cf23cdu, + 0xf6999118u, 0x3dc542bdu, 0xbb513013u, 0x700de3b6u, 0x6d08d30eu, 0xa65400abu, 0x20c07205u, 0xeb9ca1a0u, + 0x11e81eb4u, 0xdab4cd11u, 0x5c20bfbfu, 0x977c6c1au, 0x8a795ca2u, 0x41258f07u, 0xc7b1fda9u, 0x0ced2e0cu, + 0xfdbb9cd9u, 0x36e74f7cu, 0xb0733dd2u, 0x7b2fee77u, 0x662adecfu, 0xad760d6au, 0x2be27fc4u, 0xe0beac61u, + 0x123e1c2fu, 0xd962cf8au, 0x5ff6bd24u, 0x94aa6e81u, 0x89af5e39u, 0x42f38d9cu, 0xc467ff32u, 0x0f3b2c97u, + 0xfe6d9e42u, 0x35314de7u, 0xb3a53f49u, 0x78f9ececu, 0x65fcdc54u, 0xaea00ff1u, 0x28347d5fu, 0xe368aefau, + 0x16441b82u, 0xdd18c827u, 0x5b8cba89u, 0x90d0692cu, 0x8dd55994u, 0x46898a31u, 0xc01df89fu, 0x0b412b3au, + 0xfa1799efu, 0x314b4a4au, 0xb7df38e4u, 0x7c83eb41u, 0x6186dbf9u, 0xaada085cu, 0x2c4e7af2u, 0xe712a957u, + 0x15921919u, 0xdececabcu, 0x585ab812u, 0x93066bb7u, 0x8e035b0fu, 0x455f88aau, 0xc3cbfa04u, 0x089729a1u, + 0xf9c19b74u, 0x329d48d1u, 0xb4093a7fu, 0x7f55e9dau, 0x6250d962u, 0xa90c0ac7u, 0x2f987869u, 0xe4c4abccu +}; + +static const unsigned lodepng_crc32_table6[256] = { + 0x00000000u, 0xa6770bb4u, 0x979f1129u, 0x31e81a9du, 0xf44f2413u, 0x52382fa7u, 0x63d0353au, 0xc5a73e8eu, + 0x33ef4e67u, 0x959845d3u, 0xa4705f4eu, 0x020754fau, 0xc7a06a74u, 0x61d761c0u, 0x503f7b5du, 0xf64870e9u, + 0x67de9cceu, 0xc1a9977au, 0xf0418de7u, 0x56368653u, 0x9391b8ddu, 0x35e6b369u, 0x040ea9f4u, 0xa279a240u, + 0x5431d2a9u, 0xf246d91du, 0xc3aec380u, 0x65d9c834u, 0xa07ef6bau, 0x0609fd0eu, 0x37e1e793u, 0x9196ec27u, + 0xcfbd399cu, 0x69ca3228u, 0x582228b5u, 0xfe552301u, 0x3bf21d8fu, 0x9d85163bu, 0xac6d0ca6u, 0x0a1a0712u, + 0xfc5277fbu, 0x5a257c4fu, 0x6bcd66d2u, 0xcdba6d66u, 0x081d53e8u, 0xae6a585cu, 0x9f8242c1u, 0x39f54975u, + 0xa863a552u, 0x0e14aee6u, 0x3ffcb47bu, 0x998bbfcfu, 0x5c2c8141u, 0xfa5b8af5u, 0xcbb39068u, 0x6dc49bdcu, + 0x9b8ceb35u, 0x3dfbe081u, 0x0c13fa1cu, 0xaa64f1a8u, 0x6fc3cf26u, 0xc9b4c492u, 0xf85cde0fu, 0x5e2bd5bbu, + 0x440b7579u, 0xe27c7ecdu, 0xd3946450u, 0x75e36fe4u, 0xb044516au, 0x16335adeu, 0x27db4043u, 0x81ac4bf7u, + 0x77e43b1eu, 0xd19330aau, 0xe07b2a37u, 0x460c2183u, 0x83ab1f0du, 0x25dc14b9u, 0x14340e24u, 0xb2430590u, + 0x23d5e9b7u, 0x85a2e203u, 0xb44af89eu, 0x123df32au, 0xd79acda4u, 0x71edc610u, 0x4005dc8du, 0xe672d739u, + 0x103aa7d0u, 0xb64dac64u, 0x87a5b6f9u, 0x21d2bd4du, 0xe47583c3u, 0x42028877u, 0x73ea92eau, 0xd59d995eu, + 0x8bb64ce5u, 0x2dc14751u, 0x1c295dccu, 0xba5e5678u, 0x7ff968f6u, 0xd98e6342u, 0xe86679dfu, 0x4e11726bu, + 0xb8590282u, 0x1e2e0936u, 0x2fc613abu, 0x89b1181fu, 0x4c162691u, 0xea612d25u, 0xdb8937b8u, 0x7dfe3c0cu, + 0xec68d02bu, 0x4a1fdb9fu, 0x7bf7c102u, 0xdd80cab6u, 0x1827f438u, 0xbe50ff8cu, 0x8fb8e511u, 0x29cfeea5u, + 0xdf879e4cu, 0x79f095f8u, 0x48188f65u, 0xee6f84d1u, 0x2bc8ba5fu, 0x8dbfb1ebu, 0xbc57ab76u, 0x1a20a0c2u, + 0x8816eaf2u, 0x2e61e146u, 0x1f89fbdbu, 0xb9fef06fu, 0x7c59cee1u, 0xda2ec555u, 0xebc6dfc8u, 0x4db1d47cu, + 0xbbf9a495u, 0x1d8eaf21u, 0x2c66b5bcu, 0x8a11be08u, 0x4fb68086u, 0xe9c18b32u, 0xd82991afu, 0x7e5e9a1bu, + 0xefc8763cu, 0x49bf7d88u, 0x78576715u, 0xde206ca1u, 0x1b87522fu, 0xbdf0599bu, 0x8c184306u, 0x2a6f48b2u, + 0xdc27385bu, 0x7a5033efu, 0x4bb82972u, 0xedcf22c6u, 0x28681c48u, 0x8e1f17fcu, 0xbff70d61u, 0x198006d5u, + 0x47abd36eu, 0xe1dcd8dau, 0xd034c247u, 0x7643c9f3u, 0xb3e4f77du, 0x1593fcc9u, 0x247be654u, 0x820cede0u, + 0x74449d09u, 0xd23396bdu, 0xe3db8c20u, 0x45ac8794u, 0x800bb91au, 0x267cb2aeu, 0x1794a833u, 0xb1e3a387u, + 0x20754fa0u, 0x86024414u, 0xb7ea5e89u, 0x119d553du, 0xd43a6bb3u, 0x724d6007u, 0x43a57a9au, 0xe5d2712eu, + 0x139a01c7u, 0xb5ed0a73u, 0x840510eeu, 0x22721b5au, 0xe7d525d4u, 0x41a22e60u, 0x704a34fdu, 0xd63d3f49u, + 0xcc1d9f8bu, 0x6a6a943fu, 0x5b828ea2u, 0xfdf58516u, 0x3852bb98u, 0x9e25b02cu, 0xafcdaab1u, 0x09baa105u, + 0xfff2d1ecu, 0x5985da58u, 0x686dc0c5u, 0xce1acb71u, 0x0bbdf5ffu, 0xadcafe4bu, 0x9c22e4d6u, 0x3a55ef62u, + 0xabc30345u, 0x0db408f1u, 0x3c5c126cu, 0x9a2b19d8u, 0x5f8c2756u, 0xf9fb2ce2u, 0xc813367fu, 0x6e643dcbu, + 0x982c4d22u, 0x3e5b4696u, 0x0fb35c0bu, 0xa9c457bfu, 0x6c636931u, 0xca146285u, 0xfbfc7818u, 0x5d8b73acu, + 0x03a0a617u, 0xa5d7ada3u, 0x943fb73eu, 0x3248bc8au, 0xf7ef8204u, 0x519889b0u, 0x6070932du, 0xc6079899u, + 0x304fe870u, 0x9638e3c4u, 0xa7d0f959u, 0x01a7f2edu, 0xc400cc63u, 0x6277c7d7u, 0x539fdd4au, 0xf5e8d6feu, + 0x647e3ad9u, 0xc209316du, 0xf3e12bf0u, 0x55962044u, 0x90311ecau, 0x3646157eu, 0x07ae0fe3u, 0xa1d90457u, + 0x579174beu, 0xf1e67f0au, 0xc00e6597u, 0x66796e23u, 0xa3de50adu, 0x05a95b19u, 0x34414184u, 0x92364a30u +}; + +static const unsigned lodepng_crc32_table7[256] = { + 0x00000000u, 0xccaa009eu, 0x4225077du, 0x8e8f07e3u, 0x844a0efau, 0x48e00e64u, 0xc66f0987u, 0x0ac50919u, + 0xd3e51bb5u, 0x1f4f1b2bu, 0x91c01cc8u, 0x5d6a1c56u, 0x57af154fu, 0x9b0515d1u, 0x158a1232u, 0xd92012acu, + 0x7cbb312bu, 0xb01131b5u, 0x3e9e3656u, 0xf23436c8u, 0xf8f13fd1u, 0x345b3f4fu, 0xbad438acu, 0x767e3832u, + 0xaf5e2a9eu, 0x63f42a00u, 0xed7b2de3u, 0x21d12d7du, 0x2b142464u, 0xe7be24fau, 0x69312319u, 0xa59b2387u, + 0xf9766256u, 0x35dc62c8u, 0xbb53652bu, 0x77f965b5u, 0x7d3c6cacu, 0xb1966c32u, 0x3f196bd1u, 0xf3b36b4fu, + 0x2a9379e3u, 0xe639797du, 0x68b67e9eu, 0xa41c7e00u, 0xaed97719u, 0x62737787u, 0xecfc7064u, 0x205670fau, + 0x85cd537du, 0x496753e3u, 0xc7e85400u, 0x0b42549eu, 0x01875d87u, 0xcd2d5d19u, 0x43a25afau, 0x8f085a64u, + 0x562848c8u, 0x9a824856u, 0x140d4fb5u, 0xd8a74f2bu, 0xd2624632u, 0x1ec846acu, 0x9047414fu, 0x5ced41d1u, + 0x299dc2edu, 0xe537c273u, 0x6bb8c590u, 0xa712c50eu, 0xadd7cc17u, 0x617dcc89u, 0xeff2cb6au, 0x2358cbf4u, + 0xfa78d958u, 0x36d2d9c6u, 0xb85dde25u, 0x74f7debbu, 0x7e32d7a2u, 0xb298d73cu, 0x3c17d0dfu, 0xf0bdd041u, + 0x5526f3c6u, 0x998cf358u, 0x1703f4bbu, 0xdba9f425u, 0xd16cfd3cu, 0x1dc6fda2u, 0x9349fa41u, 0x5fe3fadfu, + 0x86c3e873u, 0x4a69e8edu, 0xc4e6ef0eu, 0x084cef90u, 0x0289e689u, 0xce23e617u, 0x40ace1f4u, 0x8c06e16au, + 0xd0eba0bbu, 0x1c41a025u, 0x92cea7c6u, 0x5e64a758u, 0x54a1ae41u, 0x980baedfu, 0x1684a93cu, 0xda2ea9a2u, + 0x030ebb0eu, 0xcfa4bb90u, 0x412bbc73u, 0x8d81bcedu, 0x8744b5f4u, 0x4beeb56au, 0xc561b289u, 0x09cbb217u, + 0xac509190u, 0x60fa910eu, 0xee7596edu, 0x22df9673u, 0x281a9f6au, 0xe4b09ff4u, 0x6a3f9817u, 0xa6959889u, + 0x7fb58a25u, 0xb31f8abbu, 0x3d908d58u, 0xf13a8dc6u, 0xfbff84dfu, 0x37558441u, 0xb9da83a2u, 0x7570833cu, + 0x533b85dau, 0x9f918544u, 0x111e82a7u, 0xddb48239u, 0xd7718b20u, 0x1bdb8bbeu, 0x95548c5du, 0x59fe8cc3u, + 0x80de9e6fu, 0x4c749ef1u, 0xc2fb9912u, 0x0e51998cu, 0x04949095u, 0xc83e900bu, 0x46b197e8u, 0x8a1b9776u, + 0x2f80b4f1u, 0xe32ab46fu, 0x6da5b38cu, 0xa10fb312u, 0xabcaba0bu, 0x6760ba95u, 0xe9efbd76u, 0x2545bde8u, + 0xfc65af44u, 0x30cfafdau, 0xbe40a839u, 0x72eaa8a7u, 0x782fa1beu, 0xb485a120u, 0x3a0aa6c3u, 0xf6a0a65du, + 0xaa4de78cu, 0x66e7e712u, 0xe868e0f1u, 0x24c2e06fu, 0x2e07e976u, 0xe2ade9e8u, 0x6c22ee0bu, 0xa088ee95u, + 0x79a8fc39u, 0xb502fca7u, 0x3b8dfb44u, 0xf727fbdau, 0xfde2f2c3u, 0x3148f25du, 0xbfc7f5beu, 0x736df520u, + 0xd6f6d6a7u, 0x1a5cd639u, 0x94d3d1dau, 0x5879d144u, 0x52bcd85du, 0x9e16d8c3u, 0x1099df20u, 0xdc33dfbeu, + 0x0513cd12u, 0xc9b9cd8cu, 0x4736ca6fu, 0x8b9ccaf1u, 0x8159c3e8u, 0x4df3c376u, 0xc37cc495u, 0x0fd6c40bu, + 0x7aa64737u, 0xb60c47a9u, 0x3883404au, 0xf42940d4u, 0xfeec49cdu, 0x32464953u, 0xbcc94eb0u, 0x70634e2eu, + 0xa9435c82u, 0x65e95c1cu, 0xeb665bffu, 0x27cc5b61u, 0x2d095278u, 0xe1a352e6u, 0x6f2c5505u, 0xa386559bu, + 0x061d761cu, 0xcab77682u, 0x44387161u, 0x889271ffu, 0x825778e6u, 0x4efd7878u, 0xc0727f9bu, 0x0cd87f05u, + 0xd5f86da9u, 0x19526d37u, 0x97dd6ad4u, 0x5b776a4au, 0x51b26353u, 0x9d1863cdu, 0x1397642eu, 0xdf3d64b0u, + 0x83d02561u, 0x4f7a25ffu, 0xc1f5221cu, 0x0d5f2282u, 0x079a2b9bu, 0xcb302b05u, 0x45bf2ce6u, 0x89152c78u, + 0x50353ed4u, 0x9c9f3e4au, 0x121039a9u, 0xdeba3937u, 0xd47f302eu, 0x18d530b0u, 0x965a3753u, 0x5af037cdu, + 0xff6b144au, 0x33c114d4u, 0xbd4e1337u, 0x71e413a9u, 0x7b211ab0u, 0xb78b1a2eu, 0x39041dcdu, 0xf5ae1d53u, + 0x2c8e0fffu, 0xe0240f61u, 0x6eab0882u, 0xa201081cu, 0xa8c40105u, 0x646e019bu, 0xeae10678u, 0x264b06e6u +}; + +/* Computes the cyclic redundancy check as used by PNG chunks*/ +unsigned lodepng_crc32(const unsigned char* data, size_t length) { + /*Using the Slicing by Eight algorithm*/ + unsigned r = 0xffffffffu; + while(length >= 8) { + r = lodepng_crc32_table7[(data[0] ^ (r & 0xffu))] ^ + lodepng_crc32_table6[(data[1] ^ ((r >> 8) & 0xffu))] ^ + lodepng_crc32_table5[(data[2] ^ ((r >> 16) & 0xffu))] ^ + lodepng_crc32_table4[(data[3] ^ ((r >> 24) & 0xffu))] ^ + lodepng_crc32_table3[data[4]] ^ + lodepng_crc32_table2[data[5]] ^ + lodepng_crc32_table1[data[6]] ^ + lodepng_crc32_table0[data[7]]; + data += 8; + length -= 8; + } + while(length--) { + r = lodepng_crc32_table0[(r ^ *data++) & 0xffu] ^ (r >> 8); + } + return r ^ 0xffffffffu; +} +#else /* LODEPNG_COMPILE_CRC */ +/*in this case, the function is only declared here, and must be defined externally +so that it will be linked in. + +Example implementation that uses a much smaller lookup table for memory constrained cases: + +unsigned lodepng_crc32(const unsigned char* data, size_t length) { + unsigned r = 0xffffffffu; + static const unsigned table[16] = { + 0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c + }; + while(length--) { + r = table[(r ^ *data) & 0xf] ^ (r >> 4); + r = table[(r ^ (*data >> 4)) & 0xf] ^ (r >> 4); + data++; + } + return r ^ 0xffffffffu; +} +*/ +unsigned lodepng_crc32(const unsigned char* data, size_t length); +#endif /* LODEPNG_COMPILE_CRC */ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Reading and writing PNG color channel bits / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/* The color channel bits of less-than-8-bit pixels are read with the MSB of bytes first, +so LodePNGBitWriter and LodePNGBitReader can't be used for those. */ + +static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) { + unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1); + ++(*bitpointer); + return result; +} + +#ifdef LODEPNG_COMPILE_COLOR_CONVERT +/* TODO: make this faster */ +static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) { + unsigned result = 0; + size_t i; + for(i = 0 ; i < nbits; ++i) { + result <<= 1u; + result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream); + } + return result; +} +#endif + +static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) { + /*the current bit in bitstream may be 0 or 1 for this to work*/ + if(bit == 0) bitstream[(*bitpointer) >> 3u] &= (unsigned char)(~(1u << (7u - ((*bitpointer) & 7u)))); + else bitstream[(*bitpointer) >> 3u] |= (1u << (7u - ((*bitpointer) & 7u))); + ++(*bitpointer); +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG chunks / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +unsigned lodepng_chunk_length(const unsigned char* chunk) { + return lodepng_read32bitInt(chunk); +} + +void lodepng_chunk_type(char type[5], const unsigned char* chunk) { + unsigned i; + for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i]; + type[4] = 0; /*null termination char*/ +} + +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) { + if(lodepng_strlen(type) != 4) return 0; + return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]); +} + +/* chunk type name must exist only out of alphabetic characters a-z or A-Z */ +static unsigned char lodepng_chunk_type_name_valid(const unsigned char* chunk) { + unsigned i; + for(i = 0; i != 4; ++i) { + char c = (char)chunk[4 + i]; + if(!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) { + return 0; /* not valid */ + } + } + return 1; /* valid */ +} + +unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) { + return((chunk[4] & 32) != 0); +} + +unsigned char lodepng_chunk_private(const unsigned char* chunk) { + return((chunk[5] & 32) != 0); +} + +/* this is an error if it is reserved: the third character must be uppercase in the PNG standard, +lowercasing this character is reserved for possible future extension by the spec*/ +static unsigned char lodepng_chunk_reserved(const unsigned char* chunk) { + return((chunk[6] & 32) != 0); +} + +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) { + return((chunk[7] & 32) != 0); +} + +unsigned char* lodepng_chunk_data(unsigned char* chunk) { + return &chunk[8]; +} + +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) { + return &chunk[8]; +} + +unsigned lodepng_chunk_check_crc(const unsigned char* chunk) { + unsigned length = lodepng_chunk_length(chunk); + unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]); + /*the CRC is taken of the data and the 4 chunk type letters, not the length*/ + unsigned checksum = lodepng_crc32(&chunk[4], length + 4); + if(CRC != checksum) return 1; + else return 0; +} + +void lodepng_chunk_generate_crc(unsigned char* chunk) { + unsigned length = lodepng_chunk_length(chunk); + unsigned CRC = lodepng_crc32(&chunk[4], length + 4); + lodepng_set32bitInt(chunk + 8 + length, CRC); +} + +unsigned char* lodepng_chunk_next(unsigned char* chunk, unsigned char* end) { + size_t available_size = (size_t)(end - chunk); + if(chunk >= end || available_size < 12) return end; /*too small to contain a chunk*/ + if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47 + && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) { + /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */ + return chunk + 8; + } else { + size_t total_chunk_length; + if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end; + if(total_chunk_length > available_size) return end; /*outside of range*/ + return chunk + total_chunk_length; + } +} + +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end) { + size_t available_size = (size_t)(end - chunk); + if(chunk >= end || available_size < 12) return end; /*too small to contain a chunk*/ + if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47 + && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) { + /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */ + return chunk + 8; + } else { + size_t total_chunk_length; + if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end; + if(total_chunk_length > available_size) return end; /*outside of range*/ + return chunk + total_chunk_length; + } +} + +unsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]) { + for(;;) { + if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */ + if(lodepng_chunk_type_equals(chunk, type)) return chunk; + chunk = lodepng_chunk_next(chunk, end); + } +} + +const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]) { + for(;;) { + if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */ + if(lodepng_chunk_type_equals(chunk, type)) return chunk; + chunk = lodepng_chunk_next_const(chunk, end); + } +} + +unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk) { + unsigned i; + size_t total_chunk_length, new_length; + unsigned char *chunk_start, *new_buffer; + + if(!lodepng_chunk_type_name_valid(chunk)) { + return 121; /* invalid chunk type name */ + } + if(lodepng_chunk_reserved(chunk)) { + return 122; /* invalid third lowercase character */ + } + + if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return 77; + if(lodepng_addofl(*outsize, total_chunk_length, &new_length)) return 77; + + new_buffer = (unsigned char*)lodepng_realloc(*out, new_length); + if(!new_buffer) return 83; /*alloc fail*/ + (*out) = new_buffer; + (*outsize) = new_length; + chunk_start = &(*out)[new_length - total_chunk_length]; + + for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i]; + + return 0; +} + +/*Sets length and name and allocates the space for data and crc but does not +set data or crc yet. Returns the start of the chunk in chunk. The start of +the data is at chunk + 8. To finalize chunk, add the data, then use +lodepng_chunk_generate_crc */ +static unsigned lodepng_chunk_init(unsigned char** chunk, + ucvector* out, + size_t length, const char* type) { + size_t new_length = out->size; + if(lodepng_addofl(new_length, length, &new_length)) return 77; + if(lodepng_addofl(new_length, 12, &new_length)) return 77; + if(!ucvector_resize(out, new_length)) return 83; /*alloc fail*/ + *chunk = out->data + new_length - length - 12u; + + /*1: length*/ + lodepng_set32bitInt(*chunk, (unsigned)length); + + /*2: chunk name (4 letters)*/ + lodepng_memcpy(*chunk + 4, type, 4); + + return 0; +} + +/* like lodepng_chunk_create but with custom allocsize */ +static unsigned lodepng_chunk_createv(ucvector* out, + size_t length, const char* type, const unsigned char* data) { + unsigned char* chunk; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, length, type)); + + /*3: the data*/ + lodepng_memcpy(chunk + 8, data, length); + + /*4: CRC (of the chunkname characters and the data)*/ + lodepng_chunk_generate_crc(chunk); + + return 0; +} + +unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, + size_t length, const char* type, const unsigned char* data) { + ucvector v = ucvector_init(*out, *outsize); + unsigned error = lodepng_chunk_createv(&v, length, type, data); + *out = v.data; + *outsize = v.size; + return error; +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Color types, channels, bits / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*checks if the colortype is valid and the bitdepth bd is allowed for this colortype. +Return value is a LodePNG error code.*/ +static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) { + switch(colortype) { + case LCT_GREY: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; + case LCT_RGB: if(!( bd == 8 || bd == 16)) return 37; break; + case LCT_PALETTE: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; + case LCT_GREY_ALPHA: if(!( bd == 8 || bd == 16)) return 37; break; + case LCT_RGBA: if(!( bd == 8 || bd == 16)) return 37; break; + case LCT_MAX_OCTET_VALUE: return 31; /* invalid color type */ + default: return 31; /* invalid color type */ + } + return 0; /*allowed color type / bits combination*/ +} + +static unsigned getNumColorChannels(LodePNGColorType colortype) { + switch(colortype) { + case LCT_GREY: return 1; + case LCT_RGB: return 3; + case LCT_PALETTE: return 1; + case LCT_GREY_ALPHA: return 2; + case LCT_RGBA: return 4; + case LCT_MAX_OCTET_VALUE: return 0; /* invalid color type */ + default: return 0; /*invalid color type*/ + } +} + +static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) { + /*bits per pixel is amount of channels * bits per channel*/ + return getNumColorChannels(colortype) * bitdepth; +} + +/* ////////////////////////////////////////////////////////////////////////// */ + +void lodepng_color_mode_init(LodePNGColorMode* info) { + info->key_defined = 0; + info->key_r = info->key_g = info->key_b = 0; + info->colortype = LCT_RGBA; + info->bitdepth = 8; + info->palette = 0; + info->palettesize = 0; +} + +/*allocates palette memory if needed, and initializes all colors to black*/ +static void lodepng_color_mode_alloc_palette(LodePNGColorMode* info) { + size_t i; + /*if the palette is already allocated, it will have size 1024 so no reallocation needed in that case*/ + /*the palette must have room for up to 256 colors with 4 bytes each.*/ + if(!info->palette) info->palette = (unsigned char*)lodepng_malloc(1024); + if(!info->palette) return; /*alloc fail*/ + for(i = 0; i != 256; ++i) { + /*Initialize all unused colors with black, the value used for invalid palette indices. + This is an error according to the PNG spec, but common PNG decoders make it black instead. + That makes color conversion slightly faster due to no error handling needed.*/ + info->palette[i * 4 + 0] = 0; + info->palette[i * 4 + 1] = 0; + info->palette[i * 4 + 2] = 0; + info->palette[i * 4 + 3] = 255; + } +} + +void lodepng_color_mode_cleanup(LodePNGColorMode* info) { + lodepng_palette_clear(info); +} + +unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) { + lodepng_color_mode_cleanup(dest); + lodepng_memcpy(dest, source, sizeof(LodePNGColorMode)); + if(source->palette) { + dest->palette = (unsigned char*)lodepng_malloc(1024); + if(!dest->palette && source->palettesize) return 83; /*alloc fail*/ + lodepng_memcpy(dest->palette, source->palette, source->palettesize * 4); + } + return 0; +} + +LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth) { + LodePNGColorMode result; + lodepng_color_mode_init(&result); + result.colortype = colortype; + result.bitdepth = bitdepth; + return result; +} + +static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) { + size_t i; + if(a->colortype != b->colortype) return 0; + if(a->bitdepth != b->bitdepth) return 0; + if(a->key_defined != b->key_defined) return 0; + if(a->key_defined) { + if(a->key_r != b->key_r) return 0; + if(a->key_g != b->key_g) return 0; + if(a->key_b != b->key_b) return 0; + } + if(a->palettesize != b->palettesize) return 0; + for(i = 0; i != a->palettesize * 4; ++i) { + if(a->palette[i] != b->palette[i]) return 0; + } + return 1; +} + +void lodepng_palette_clear(LodePNGColorMode* info) { + if(info->palette) lodepng_free(info->palette); + info->palette = 0; + info->palettesize = 0; +} + +unsigned lodepng_palette_add(LodePNGColorMode* info, + unsigned char r, unsigned char g, unsigned char b, unsigned char a) { + if(!info->palette) /*allocate palette if empty*/ { + lodepng_color_mode_alloc_palette(info); + if(!info->palette) return 83; /*alloc fail*/ + } + if(info->palettesize >= 256) { + return 108; /*too many palette values*/ + } + info->palette[4 * info->palettesize + 0] = r; + info->palette[4 * info->palettesize + 1] = g; + info->palette[4 * info->palettesize + 2] = b; + info->palette[4 * info->palettesize + 3] = a; + ++info->palettesize; + return 0; +} + +/*calculate bits per pixel out of colortype and bitdepth*/ +unsigned lodepng_get_bpp(const LodePNGColorMode* info) { + return lodepng_get_bpp_lct(info->colortype, info->bitdepth); +} + +unsigned lodepng_get_channels(const LodePNGColorMode* info) { + return getNumColorChannels(info->colortype); +} + +unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) { + return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA; +} + +unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) { + return (info->colortype & 4) != 0; /*4 or 6*/ +} + +unsigned lodepng_is_palette_type(const LodePNGColorMode* info) { + return info->colortype == LCT_PALETTE; +} + +unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) { + size_t i; + for(i = 0; i != info->palettesize; ++i) { + if(info->palette[i * 4 + 3] < 255) return 1; + } + return 0; +} + +unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) { + return info->key_defined + || lodepng_is_alpha_type(info) + || lodepng_has_palette_alpha(info); +} + +static size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { + size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth); + size_t n = (size_t)w * (size_t)h; + return ((n / 8u) * bpp) + ((n & 7u) * bpp + 7u) / 8u; +} + +size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) { + return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth); +} + + +#ifdef LODEPNG_COMPILE_PNG + +/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer, +and in addition has one extra byte per line: the filter byte. So this gives a larger +result than lodepng_get_raw_size. Set h to 1 to get the size of 1 row including filter byte. */ +static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, unsigned bpp) { + /* + 1 for the filter byte, and possibly plus padding bits per line. */ + /* Ignoring casts, the expression is equal to (w * bpp + 7) / 8 + 1, but avoids overflow of w * bpp */ + size_t line = ((size_t)(w / 8u) * bpp) + 1u + ((w & 7u) * bpp + 7u) / 8u; + return (size_t)h * line; +} + +#ifdef LODEPNG_COMPILE_DECODER +/*Safely checks whether size_t overflow can be caused due to amount of pixels. +This check is overcautious rather than precise. If this check indicates no overflow, +you can safely compute in a size_t (but not an unsigned): +-(size_t)w * (size_t)h * 8 +-amount of bytes in IDAT (including filter, padding and Adam7 bytes) +-amount of bytes in raw color model +Returns 1 if overflow possible, 0 if not. +*/ +static int lodepng_pixel_overflow(unsigned w, unsigned h, + const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) { + size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor)); + size_t numpixels, total; + size_t line; /* bytes per line in worst case */ + + if(lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1; + if(lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */ + + /* Bytes per scanline with the expression "(w / 8u) * bpp) + ((w & 7u) * bpp + 7u) / 8u" */ + if(lodepng_mulofl((size_t)(w / 8u), bpp, &line)) return 1; + if(lodepng_addofl(line, ((w & 7u) * bpp + 7u) / 8u, &line)) return 1; + + if(lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */ + if(lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */ + + return 0; /* no overflow */ +} +#endif /*LODEPNG_COMPILE_DECODER*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + +static void LodePNGUnknownChunks_init(LodePNGInfo* info) { + unsigned i; + for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0; + for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0; +} + +static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) { + unsigned i; + for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]); +} + +static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) { + unsigned i; + + LodePNGUnknownChunks_cleanup(dest); + + for(i = 0; i != 3; ++i) { + size_t j; + dest->unknown_chunks_size[i] = src->unknown_chunks_size[i]; + dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]); + if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/ + for(j = 0; j < src->unknown_chunks_size[i]; ++j) { + dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j]; + } + } + + return 0; +} + +/******************************************************************************/ + +static void LodePNGText_init(LodePNGInfo* info) { + info->text_num = 0; + info->text_keys = NULL; + info->text_strings = NULL; +} + +static void LodePNGText_cleanup(LodePNGInfo* info) { + size_t i; + for(i = 0; i != info->text_num; ++i) { + string_cleanup(&info->text_keys[i]); + string_cleanup(&info->text_strings[i]); + } + lodepng_free(info->text_keys); + lodepng_free(info->text_strings); +} + +static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { + size_t i = 0; + dest->text_keys = NULL; + dest->text_strings = NULL; + dest->text_num = 0; + for(i = 0; i != source->text_num; ++i) { + CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i])); + } + return 0; +} + +static unsigned lodepng_add_text_sized(LodePNGInfo* info, const char* key, const char* str, size_t size) { + char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1))); + char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1))); + + if(new_keys) info->text_keys = new_keys; + if(new_strings) info->text_strings = new_strings; + + if(!new_keys || !new_strings) return 83; /*alloc fail*/ + + ++info->text_num; + info->text_keys[info->text_num - 1] = alloc_string(key); + info->text_strings[info->text_num - 1] = alloc_string_sized(str, size); + if(!info->text_keys[info->text_num - 1] || !info->text_strings[info->text_num - 1]) return 83; /*alloc fail*/ + + return 0; +} + +unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) { + return lodepng_add_text_sized(info, key, str, lodepng_strlen(str)); +} + +void lodepng_clear_text(LodePNGInfo* info) { + LodePNGText_cleanup(info); +} + +/******************************************************************************/ + +static void LodePNGIText_init(LodePNGInfo* info) { + info->itext_num = 0; + info->itext_keys = NULL; + info->itext_langtags = NULL; + info->itext_transkeys = NULL; + info->itext_strings = NULL; +} + +static void LodePNGIText_cleanup(LodePNGInfo* info) { + size_t i; + for(i = 0; i != info->itext_num; ++i) { + string_cleanup(&info->itext_keys[i]); + string_cleanup(&info->itext_langtags[i]); + string_cleanup(&info->itext_transkeys[i]); + string_cleanup(&info->itext_strings[i]); + } + lodepng_free(info->itext_keys); + lodepng_free(info->itext_langtags); + lodepng_free(info->itext_transkeys); + lodepng_free(info->itext_strings); +} + +static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { + size_t i = 0; + dest->itext_keys = NULL; + dest->itext_langtags = NULL; + dest->itext_transkeys = NULL; + dest->itext_strings = NULL; + dest->itext_num = 0; + for(i = 0; i != source->itext_num; ++i) { + CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i], + source->itext_transkeys[i], source->itext_strings[i])); + } + return 0; +} + +void lodepng_clear_itext(LodePNGInfo* info) { + LodePNGIText_cleanup(info); +} + +static unsigned lodepng_add_itext_sized(LodePNGInfo* info, const char* key, const char* langtag, + const char* transkey, const char* str, size_t size) { + char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1))); + char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1))); + char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1))); + char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1))); + + if(new_keys) info->itext_keys = new_keys; + if(new_langtags) info->itext_langtags = new_langtags; + if(new_transkeys) info->itext_transkeys = new_transkeys; + if(new_strings) info->itext_strings = new_strings; + + if(!new_keys || !new_langtags || !new_transkeys || !new_strings) return 83; /*alloc fail*/ + + ++info->itext_num; + + info->itext_keys[info->itext_num - 1] = alloc_string(key); + info->itext_langtags[info->itext_num - 1] = alloc_string(langtag); + info->itext_transkeys[info->itext_num - 1] = alloc_string(transkey); + info->itext_strings[info->itext_num - 1] = alloc_string_sized(str, size); + + return 0; +} + +unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, + const char* transkey, const char* str) { + return lodepng_add_itext_sized(info, key, langtag, transkey, str, lodepng_strlen(str)); +} + +unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) { + if(info->iccp_defined) lodepng_clear_icc(info); + + if(profile_size == 0) return 100; /*invalid ICC profile size*/ + + info->iccp_name = alloc_string(name); + if(!info->iccp_name) return 83; /*alloc fail*/ + + info->iccp_profile = (unsigned char*)lodepng_malloc(profile_size); + if(!info->iccp_profile) { + lodepng_free(info->iccp_name); + return 83; /*alloc fail*/ + } + + lodepng_memcpy(info->iccp_profile, profile, profile_size); + info->iccp_profile_size = profile_size; + info->iccp_defined = 1; + + return 0; /*ok*/ +} + +void lodepng_clear_icc(LodePNGInfo* info) { + string_cleanup(&info->iccp_name); + lodepng_free(info->iccp_profile); + info->iccp_profile = NULL; + info->iccp_profile_size = 0; + info->iccp_defined = 0; +} + +unsigned lodepng_set_exif(LodePNGInfo* info, const unsigned char* exif, unsigned exif_size) { + if(info->exif_defined) lodepng_clear_exif(info); + info->exif = (unsigned char*)lodepng_malloc(exif_size); + + if(!info->exif) return 83; /*alloc fail*/ + + lodepng_memcpy(info->exif, exif, exif_size); + info->exif_size = exif_size; + info->exif_defined = 1; + + return 0; /*ok*/ +} + +void lodepng_clear_exif(LodePNGInfo* info) { + lodepng_free(info->exif); + info->exif = NULL; + info->exif_size = 0; + info->exif_defined = 0; +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +void lodepng_info_init(LodePNGInfo* info) { + lodepng_color_mode_init(&info->color); + info->interlace_method = 0; + info->compression_method = 0; + info->filter_method = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + info->background_defined = 0; + info->background_r = info->background_g = info->background_b = 0; + + LodePNGText_init(info); + LodePNGIText_init(info); + + info->time_defined = 0; + info->phys_defined = 0; + + info->gama_defined = 0; + info->chrm_defined = 0; + info->srgb_defined = 0; + info->iccp_defined = 0; + info->iccp_name = NULL; + info->iccp_profile = NULL; + info->cicp_defined = 0; + info->cicp_color_primaries = 0; + info->cicp_transfer_function = 0; + info->cicp_matrix_coefficients = 0; + info->cicp_video_full_range_flag = 0; + info->mdcv_defined = 0; + info->mdcv_red_x = 0; + info->mdcv_red_y = 0; + info->mdcv_green_x = 0; + info->mdcv_green_y = 0; + info->mdcv_blue_x = 0; + info->mdcv_blue_y = 0; + info->mdcv_white_x = 0; + info->mdcv_white_y = 0; + info->mdcv_max_luminance = 0; + info->mdcv_min_luminance = 0; + info->clli_defined = 0; + info->clli_max_cll = 0; + info->clli_max_fall = 0; + + info->exif_defined = 0; + info->exif = NULL; + info->exif_size = 0; + + info->sbit_defined = 0; + info->sbit_r = info->sbit_g = info->sbit_b = info->sbit_a = 0; + + LodePNGUnknownChunks_init(info); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +void lodepng_info_cleanup(LodePNGInfo* info) { + lodepng_color_mode_cleanup(&info->color); +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + LodePNGText_cleanup(info); + LodePNGIText_cleanup(info); + + lodepng_clear_icc(info); + lodepng_clear_exif(info); + + LodePNGUnknownChunks_cleanup(info); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) { + lodepng_info_cleanup(dest); + lodepng_memcpy(dest, source, sizeof(LodePNGInfo)); + lodepng_color_mode_init(&dest->color); + CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color)); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + CERROR_TRY_RETURN(LodePNGText_copy(dest, source)); + CERROR_TRY_RETURN(LodePNGIText_copy(dest, source)); + if(source->iccp_defined) { + dest->iccp_defined = 0; /*the memcpy above set this to 1 while it shouldn't*/ + CERROR_TRY_RETURN(lodepng_set_icc(dest, source->iccp_name, source->iccp_profile, source->iccp_profile_size)); + } + if(source->exif_defined) { + dest->exif_defined = 0; /*the memcpy above set this to 1 while it shouldn't*/ + CERROR_TRY_RETURN(lodepng_set_exif(dest, source->exif, source->exif_size)); + } + + LodePNGUnknownChunks_init(dest); + CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source)); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + return 0; +} + +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_COLOR_CONVERT +/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/ +static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) { + unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/ + /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/ + unsigned p = index & m; + in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/ + in = in << (bits * (m - p)); + if(p == 0) out[index * bits / 8u] = in; + else out[index * bits / 8u] |= in; +} + +typedef struct ColorTree ColorTree; + +/* +One node of a color tree +This is the data structure used to count the number of unique colors and to get a palette +index for a color. It's like an octree, but because the alpha channel is used too, each +node has 16 instead of 8 children. +*/ +struct ColorTree { + ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/ + int index; /*the payload. Only has a meaningful value if this is in the last level*/ +}; + +static void color_tree_init(ColorTree* tree) { + lodepng_memset(tree->children, 0, 16 * sizeof(*tree->children)); + tree->index = -1; +} + +static void color_tree_cleanup(ColorTree* tree) { + int i; + for(i = 0; i != 16; ++i) { + if(tree->children[i]) { + color_tree_cleanup(tree->children[i]); + lodepng_free(tree->children[i]); + } + } +} + +/*returns -1 if color not present, its index otherwise*/ +static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { + int bit = 0; + for(bit = 0; bit < 8; ++bit) { + int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); + if(!tree->children[i]) return -1; + else tree = tree->children[i]; + } + return tree ? tree->index : -1; +} + +#ifdef LODEPNG_COMPILE_ENCODER +static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { + return color_tree_get(tree, r, g, b, a) >= 0; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/*color is not allowed to already exist. +Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist") +Returns error code, or 0 if ok*/ +static unsigned color_tree_add(ColorTree* tree, + unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) { + int bit; + for(bit = 0; bit < 8; ++bit) { + int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); + if(!tree->children[i]) { + tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree)); + if(!tree->children[i]) return 83; /*alloc fail*/ + color_tree_init(tree->children[i]); + } + tree = tree->children[i]; + } + tree->index = (int)index; + return 0; +} + +/*put a pixel, given its RGBA color, into image of any color type*/ +static unsigned rgba8ToPixel(unsigned char* out, size_t i, + const LodePNGColorMode* mode, ColorTree* tree /*for palette*/, + unsigned char r, unsigned char g, unsigned char b, unsigned char a) { + if(mode->colortype == LCT_GREY) { + unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/ + if(mode->bitdepth == 8) out[i] = gray; + else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = gray; + else { + /*take the most significant bits of gray*/ + gray = ((unsigned)gray >> (8u - mode->bitdepth)) & ((1u << mode->bitdepth) - 1u); + addColorBits(out, i, mode->bitdepth, gray); + } + } else if(mode->colortype == LCT_RGB) { + if(mode->bitdepth == 8) { + out[i * 3 + 0] = r; + out[i * 3 + 1] = g; + out[i * 3 + 2] = b; + } else { + out[i * 6 + 0] = out[i * 6 + 1] = r; + out[i * 6 + 2] = out[i * 6 + 3] = g; + out[i * 6 + 4] = out[i * 6 + 5] = b; + } + } else if(mode->colortype == LCT_PALETTE) { + int index = color_tree_get(tree, r, g, b, a); + if(index < 0) return 82; /*color not in palette*/ + if(mode->bitdepth == 8) out[i] = index; + else addColorBits(out, i, mode->bitdepth, (unsigned)index); + } else if(mode->colortype == LCT_GREY_ALPHA) { + unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/ + if(mode->bitdepth == 8) { + out[i * 2 + 0] = gray; + out[i * 2 + 1] = a; + } else if(mode->bitdepth == 16) { + out[i * 4 + 0] = out[i * 4 + 1] = gray; + out[i * 4 + 2] = out[i * 4 + 3] = a; + } + } else if(mode->colortype == LCT_RGBA) { + if(mode->bitdepth == 8) { + out[i * 4 + 0] = r; + out[i * 4 + 1] = g; + out[i * 4 + 2] = b; + out[i * 4 + 3] = a; + } else { + out[i * 8 + 0] = out[i * 8 + 1] = r; + out[i * 8 + 2] = out[i * 8 + 3] = g; + out[i * 8 + 4] = out[i * 8 + 5] = b; + out[i * 8 + 6] = out[i * 8 + 7] = a; + } + } + + return 0; /*no error*/ +} + +/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/ +static void rgba16ToPixel(unsigned char* out, size_t i, + const LodePNGColorMode* mode, + unsigned short r, unsigned short g, unsigned short b, unsigned short a) { + if(mode->colortype == LCT_GREY) { + unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/ + out[i * 2 + 0] = (gray >> 8) & 255; + out[i * 2 + 1] = gray & 255; + } else if(mode->colortype == LCT_RGB) { + out[i * 6 + 0] = (r >> 8) & 255; + out[i * 6 + 1] = r & 255; + out[i * 6 + 2] = (g >> 8) & 255; + out[i * 6 + 3] = g & 255; + out[i * 6 + 4] = (b >> 8) & 255; + out[i * 6 + 5] = b & 255; + } else if(mode->colortype == LCT_GREY_ALPHA) { + unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/ + out[i * 4 + 0] = (gray >> 8) & 255; + out[i * 4 + 1] = gray & 255; + out[i * 4 + 2] = (a >> 8) & 255; + out[i * 4 + 3] = a & 255; + } else if(mode->colortype == LCT_RGBA) { + out[i * 8 + 0] = (r >> 8) & 255; + out[i * 8 + 1] = r & 255; + out[i * 8 + 2] = (g >> 8) & 255; + out[i * 8 + 3] = g & 255; + out[i * 8 + 4] = (b >> 8) & 255; + out[i * 8 + 5] = b & 255; + out[i * 8 + 6] = (a >> 8) & 255; + out[i * 8 + 7] = a & 255; + } +} + +/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/ +static void getPixelColorRGBA8(unsigned char* r, unsigned char* g, + unsigned char* b, unsigned char* a, + const unsigned char* in, size_t i, + const LodePNGColorMode* mode) { + if(mode->colortype == LCT_GREY) { + if(mode->bitdepth == 8) { + *r = *g = *b = in[i]; + if(mode->key_defined && *r == mode->key_r) *a = 0; + else *a = 255; + } else if(mode->bitdepth == 16) { + *r = *g = *b = in[i * 2 + 0]; + if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; + else *a = 255; + } else { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = i * mode->bitdepth; + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + *r = *g = *b = (value * 255) / highest; + if(mode->key_defined && value == mode->key_r) *a = 0; + else *a = 255; + } + } else if(mode->colortype == LCT_RGB) { + if(mode->bitdepth == 8) { + *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2]; + if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0; + else *a = 255; + } else { + *r = in[i * 6 + 0]; + *g = in[i * 6 + 2]; + *b = in[i * 6 + 4]; + if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; + else *a = 255; + } + } else if(mode->colortype == LCT_PALETTE) { + unsigned index; + if(mode->bitdepth == 8) index = in[i]; + else { + size_t j = i * mode->bitdepth; + index = readBitsFromReversedStream(&j, in, mode->bitdepth); + } + /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ + *r = mode->palette[index * 4 + 0]; + *g = mode->palette[index * 4 + 1]; + *b = mode->palette[index * 4 + 2]; + *a = mode->palette[index * 4 + 3]; + } else if(mode->colortype == LCT_GREY_ALPHA) { + if(mode->bitdepth == 8) { + *r = *g = *b = in[i * 2 + 0]; + *a = in[i * 2 + 1]; + } else { + *r = *g = *b = in[i * 4 + 0]; + *a = in[i * 4 + 2]; + } + } else if(mode->colortype == LCT_RGBA) { + if(mode->bitdepth == 8) { + *r = in[i * 4 + 0]; + *g = in[i * 4 + 1]; + *b = in[i * 4 + 2]; + *a = in[i * 4 + 3]; + } else { + *r = in[i * 8 + 0]; + *g = in[i * 8 + 2]; + *b = in[i * 8 + 4]; + *a = in[i * 8 + 6]; + } + } +} + +/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color +mode test cases, optimized to convert the colors much faster, when converting +to the common case of RGBA with 8 bit per channel. buffer must be RGBA with +enough memory.*/ +static void getPixelColorsRGBA8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels, + const unsigned char* LODEPNG_RESTRICT in, + const LodePNGColorMode* mode) { + unsigned num_channels = 4; + size_t i; + if(mode->colortype == LCT_GREY) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i]; + buffer[3] = 255; + } + if(mode->key_defined) { + buffer -= numpixels * num_channels; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + if(buffer[0] == mode->key_r) buffer[3] = 0; + } + } + } else if(mode->bitdepth == 16) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 2]; + buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255; + } + } else { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; + buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255; + } + } + } else if(mode->colortype == LCT_RGB) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + lodepng_memcpy(buffer, &in[i * 3], 3); + buffer[3] = 255; + } + if(mode->key_defined) { + buffer -= numpixels * num_channels; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + if(buffer[0] == mode->key_r && buffer[1]== mode->key_g && buffer[2] == mode->key_b) buffer[3] = 0; + } + } + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = in[i * 6 + 0]; + buffer[1] = in[i * 6 + 2]; + buffer[2] = in[i * 6 + 4]; + buffer[3] = mode->key_defined + && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255; + } + } + } else if(mode->colortype == LCT_PALETTE) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned index = in[i]; + /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ + lodepng_memcpy(buffer, &mode->palette[index * 4], 4); + } + } else { + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth); + /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ + lodepng_memcpy(buffer, &mode->palette[index * 4], 4); + } + } + } else if(mode->colortype == LCT_GREY_ALPHA) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; + buffer[3] = in[i * 2 + 1]; + } + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; + buffer[3] = in[i * 4 + 2]; + } + } + } else if(mode->colortype == LCT_RGBA) { + if(mode->bitdepth == 8) { + lodepng_memcpy(buffer, in, numpixels * 4); + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = in[i * 8 + 0]; + buffer[1] = in[i * 8 + 2]; + buffer[2] = in[i * 8 + 4]; + buffer[3] = in[i * 8 + 6]; + } + } + } +} + +/*Similar to getPixelColorsRGBA8, but with 3-channel RGB output.*/ +static void getPixelColorsRGB8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels, + const unsigned char* LODEPNG_RESTRICT in, + const LodePNGColorMode* mode) { + const unsigned num_channels = 3; + size_t i; + if(mode->colortype == LCT_GREY) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i]; + } + } else if(mode->bitdepth == 16) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 2]; + } + } else { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; + } + } + } else if(mode->colortype == LCT_RGB) { + if(mode->bitdepth == 8) { + lodepng_memcpy(buffer, in, numpixels * 3); + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = in[i * 6 + 0]; + buffer[1] = in[i * 6 + 2]; + buffer[2] = in[i * 6 + 4]; + } + } + } else if(mode->colortype == LCT_PALETTE) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned index = in[i]; + /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ + lodepng_memcpy(buffer, &mode->palette[index * 4], 3); + } + } else { + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth); + /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ + lodepng_memcpy(buffer, &mode->palette[index * 4], 3); + } + } + } else if(mode->colortype == LCT_GREY_ALPHA) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; + } + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; + } + } + } else if(mode->colortype == LCT_RGBA) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + lodepng_memcpy(buffer, &in[i * 4], 3); + } + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { + buffer[0] = in[i * 8 + 0]; + buffer[1] = in[i * 8 + 2]; + buffer[2] = in[i * 8 + 4]; + } + } + } +} + +/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with +given color type, but the given color type must be 16-bit itself.*/ +static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a, + const unsigned char* in, size_t i, const LodePNGColorMode* mode) { + if(mode->colortype == LCT_GREY) { + *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1]; + if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; + else *a = 65535; + } else if(mode->colortype == LCT_RGB) { + *r = 256u * in[i * 6 + 0] + in[i * 6 + 1]; + *g = 256u * in[i * 6 + 2] + in[i * 6 + 3]; + *b = 256u * in[i * 6 + 4] + in[i * 6 + 5]; + if(mode->key_defined + && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; + else *a = 65535; + } else if(mode->colortype == LCT_GREY_ALPHA) { + *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1]; + *a = 256u * in[i * 4 + 2] + in[i * 4 + 3]; + } else if(mode->colortype == LCT_RGBA) { + *r = 256u * in[i * 8 + 0] + in[i * 8 + 1]; + *g = 256u * in[i * 8 + 2] + in[i * 8 + 3]; + *b = 256u * in[i * 8 + 4] + in[i * 8 + 5]; + *a = 256u * in[i * 8 + 6] + in[i * 8 + 7]; + } +} + +unsigned lodepng_convert(unsigned char* out, const unsigned char* in, + const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, + unsigned w, unsigned h) { + size_t i; + ColorTree tree; + size_t numpixels = (size_t)w * (size_t)h; + unsigned error = 0; + + if(mode_in->colortype == LCT_PALETTE && !mode_in->palette) { + return 107; /* error: must provide palette if input mode is palette */ + } + + if(lodepng_color_mode_equal(mode_out, mode_in)) { + size_t numbytes = lodepng_get_raw_size(w, h, mode_in); + lodepng_memcpy(out, in, numbytes); + return 0; + } + + if(mode_out->colortype == LCT_PALETTE) { + size_t palettesize = mode_out->palettesize; + const unsigned char* palette = mode_out->palette; + size_t palsize = (size_t)1u << mode_out->bitdepth; + /*if the user specified output palette but did not give the values, assume + they want the values of the input color type (assuming that one is palette). + Note that we never create a new palette ourselves.*/ + if(palettesize == 0) { + palettesize = mode_in->palettesize; + palette = mode_in->palette; + /*if the input was also palette with same bitdepth, then the color types are also + equal, so copy literally. This to preserve the exact indices that were in the PNG + even in case there are duplicate colors in the palette.*/ + if(mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) { + size_t numbytes = lodepng_get_raw_size(w, h, mode_in); + lodepng_memcpy(out, in, numbytes); + return 0; + } + } + if(palettesize < palsize) palsize = palettesize; + color_tree_init(&tree); + for(i = 0; i != palsize; ++i) { + const unsigned char* p = &palette[i * 4]; + error = color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i); + if(error) break; + } + } + + if(!error) { + if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) { + for(i = 0; i != numpixels; ++i) { + unsigned short r = 0, g = 0, b = 0, a = 0; + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); + rgba16ToPixel(out, i, mode_out, r, g, b, a); + } + } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) { + getPixelColorsRGBA8(out, numpixels, in, mode_in); + } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) { + getPixelColorsRGB8(out, numpixels, in, mode_in); + } else { + unsigned char r = 0, g = 0, b = 0, a = 0; + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); + error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a); + if(error) break; + } + } + } + + if(mode_out->colortype == LCT_PALETTE) { + color_tree_cleanup(&tree); + } + + return error; +} + + +/* Converts a single rgb color without alpha from one type to another, color bits truncated to +their bitdepth. In case of single channel (gray or palette), only the r channel is used. Slow +function, do not use to process all pixels of an image. Alpha channel not supported on purpose: +this is for bKGD, supporting alpha may prevent it from finding a color in the palette, from the +specification it looks like bKGD should ignore the alpha values of the palette since it can use +any palette index but doesn't have an alpha channel. Idem with ignoring color key. */ +unsigned lodepng_convert_rgb( + unsigned* r_out, unsigned* g_out, unsigned* b_out, + unsigned r_in, unsigned g_in, unsigned b_in, + const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in) { + unsigned r = 0, g = 0, b = 0; + unsigned mul = 65535 / ((1u << mode_in->bitdepth) - 1u); /*65535, 21845, 4369, 257, 1*/ + unsigned shift = 16 - mode_out->bitdepth; + + if(mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) { + r = g = b = r_in * mul; + } else if(mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) { + r = r_in * mul; + g = g_in * mul; + b = b_in * mul; + } else if(mode_in->colortype == LCT_PALETTE) { + if(r_in >= mode_in->palettesize) return 82; + r = mode_in->palette[r_in * 4 + 0] * 257u; + g = mode_in->palette[r_in * 4 + 1] * 257u; + b = mode_in->palette[r_in * 4 + 2] * 257u; + } else { + return 31; + } + + /* now convert to output format */ + if(mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) { + *r_out = r >> shift ; + } else if(mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) { + *r_out = r >> shift ; + *g_out = g >> shift ; + *b_out = b >> shift ; + } else if(mode_out->colortype == LCT_PALETTE) { + unsigned i; + /* a 16-bit color cannot be in the palette */ + if((r >> 8) != (r & 255) || (g >> 8) != (g & 255) || (b >> 8) != (b & 255)) return 82; + for(i = 0; i < mode_out->palettesize; i++) { + unsigned j = i * 4; + if((r >> 8) == mode_out->palette[j + 0] && (g >> 8) == mode_out->palette[j + 1] && + (b >> 8) == mode_out->palette[j + 2]) { + *r_out = i; + return 0; + } + } + return 82; + } else { + return 31; + } + + return 0; +} + +#ifdef LODEPNG_COMPILE_ENCODER + +void lodepng_color_stats_init(LodePNGColorStats* stats) { + /*stats*/ + stats->colored = 0; + stats->key = 0; + stats->key_r = stats->key_g = stats->key_b = 0; + stats->alpha = 0; + stats->numcolors = 0; + stats->bits = 1; + stats->numpixels = 0; + /*settings*/ + stats->allow_palette = 1; + stats->allow_greyscale = 1; +} + +/*function used for debug purposes with C++*/ +/*void printColorStats(LodePNGColorStats* p) { + std::cout << "colored: " << (int)p->colored << ", "; + std::cout << "key: " << (int)p->key << ", "; + std::cout << "key_r: " << (int)p->key_r << ", "; + std::cout << "key_g: " << (int)p->key_g << ", "; + std::cout << "key_b: " << (int)p->key_b << ", "; + std::cout << "alpha: " << (int)p->alpha << ", "; + std::cout << "numcolors: " << (int)p->numcolors << ", "; + std::cout << "bits: " << (int)p->bits << std::endl; +}*/ + +/*Returns how many bits needed to represent given value (max 8 bit)*/ +static unsigned getValueRequiredBits(unsigned char value) { + if(value == 0 || value == 255) return 1; + /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/ + if(value % 17 == 0) return value % 85 == 0 ? 2 : 4; + return 8; +} + +/*stats must already have been inited. */ +unsigned lodepng_compute_color_stats(LodePNGColorStats* stats, + const unsigned char* in, unsigned w, unsigned h, + const LodePNGColorMode* mode_in) { + size_t i; + ColorTree tree; + size_t numpixels = (size_t)w * (size_t)h; + unsigned error = 0; + + /* mark things as done already if it would be impossible to have a more expensive case */ + unsigned colored_done = lodepng_is_greyscale_type(mode_in) ? 1 : 0; + unsigned alpha_done = lodepng_can_have_alpha(mode_in) ? 0 : 1; + unsigned numcolors_done = 0; + unsigned bpp = lodepng_get_bpp(mode_in); + unsigned bits_done = (stats->bits == 1 && bpp == 1) ? 1 : 0; + unsigned sixteen = 0; /* whether the input image is 16 bit */ + unsigned maxnumcolors = 257; + if(bpp <= 8) maxnumcolors = LODEPNG_MIN(257, stats->numcolors + (1u << bpp)); + + stats->numpixels += numpixels; + + /*if palette not allowed, no need to compute numcolors*/ + if(!stats->allow_palette) numcolors_done = 1; + + color_tree_init(&tree); + + /*If the stats was already filled in from previous data, fill its palette in tree + and mark things as done already if we know they are the most expensive case already*/ + if(stats->alpha) alpha_done = 1; + if(stats->colored) colored_done = 1; + if(stats->bits == 16) numcolors_done = 1; + if(stats->bits >= bpp) bits_done = 1; + if(stats->numcolors >= maxnumcolors) numcolors_done = 1; + + if(!numcolors_done) { + for(i = 0; i < stats->numcolors; i++) { + const unsigned char* color = &stats->palette[i * 4]; + error = color_tree_add(&tree, color[0], color[1], color[2], color[3], (unsigned)i); + if(error) goto cleanup; + } + } + + /*Check if the 16-bit input is truly 16-bit*/ + if(mode_in->bitdepth == 16 && !sixteen) { + unsigned short r = 0, g = 0, b = 0, a = 0; + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); + if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) || + (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ { + stats->bits = 16; + sixteen = 1; + bits_done = 1; + numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/ + break; + } + } + } + + if(sixteen) { + unsigned short r = 0, g = 0, b = 0, a = 0; + + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); + + if(!colored_done && (r != g || r != b)) { + stats->colored = 1; + colored_done = 1; + } + + if(!alpha_done) { + unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b); + if(a != 65535 && (a != 0 || (stats->key && !matchkey))) { + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + } else if(a == 0 && !stats->alpha && !stats->key) { + stats->key = 1; + stats->key_r = r; + stats->key_g = g; + stats->key_b = b; + } else if(a == 65535 && stats->key && matchkey) { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + } + } + if(alpha_done && numcolors_done && colored_done && bits_done) break; + } + + if(stats->key && !stats->alpha) { + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); + if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + } + } + } + } else /* < 16-bit */ { + unsigned char r = 0, g = 0, b = 0, a = 0; + unsigned char pr = 0, pg = 0, pb = 0, pa = 0; + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); + + /*skip if color same as before, this speeds up large non-photographic + images with many same colors by avoiding 'color_tree_has' below */ + if(i != 0 && r == pr && g == pg && b == pb && a == pa) continue; + pr = r; + pg = g; + pb = b; + pa = a; + + if(!bits_done && stats->bits < 8) { + /*only r is checked, < 8 bits is only relevant for grayscale*/ + unsigned bits = getValueRequiredBits(r); + if(bits > stats->bits) stats->bits = bits; + } + bits_done = (stats->bits >= bpp); + + if(!colored_done && (r != g || r != b)) { + stats->colored = 1; + colored_done = 1; + if(stats->bits < 8) stats->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/ + } + + if(!alpha_done) { + unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b); + if(a != 255 && (a != 0 || (stats->key && !matchkey))) { + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } else if(a == 0 && !stats->alpha && !stats->key) { + stats->key = 1; + stats->key_r = r; + stats->key_g = g; + stats->key_b = b; + } else if(a == 255 && stats->key && matchkey) { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + } + + if(!numcolors_done) { + if(!color_tree_has(&tree, r, g, b, a)) { + error = color_tree_add(&tree, r, g, b, a, stats->numcolors); + if(error) goto cleanup; + if(stats->numcolors < 256) { + unsigned char* p = stats->palette; + unsigned n = stats->numcolors; + p[n * 4 + 0] = r; + p[n * 4 + 1] = g; + p[n * 4 + 2] = b; + p[n * 4 + 3] = a; + } + ++stats->numcolors; + numcolors_done = stats->numcolors >= maxnumcolors; + } + } + + if(alpha_done && numcolors_done && colored_done && bits_done) break; + } + + if(stats->key && !stats->alpha) { + for(i = 0; i != numpixels; ++i) { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); + if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + stats->alpha = 1; + stats->key = 0; + alpha_done = 1; + if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + } + } + + /*make the stats's key always 16-bit for consistency - repeat each byte twice*/ + stats->key_r += (stats->key_r << 8); + stats->key_g += (stats->key_g << 8); + stats->key_b += (stats->key_b << 8); + } + +cleanup: + color_tree_cleanup(&tree); + return error; +} +#endif + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*Adds a single color to the color stats. The stats must already have been inited. The color must be given as 16-bit +(with 2 bytes repeating for 8-bit and 65535 for opaque alpha channel). This function is expensive, do not call it for +all pixels of an image but only for a few additional values. */ +static unsigned lodepng_color_stats_add(LodePNGColorStats* stats, + unsigned r, unsigned g, unsigned b, unsigned a) { + unsigned error = 0; + unsigned char image[8]; + LodePNGColorMode mode; + lodepng_color_mode_init(&mode); + image[0] = r >> 8; image[1] = r; image[2] = g >> 8; image[3] = g; + image[4] = b >> 8; image[5] = b; image[6] = a >> 8; image[7] = a; + mode.bitdepth = 16; + mode.colortype = LCT_RGBA; + error = lodepng_compute_color_stats(stats, image, 1, 1, &mode); + lodepng_color_mode_cleanup(&mode); + return error; +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/*Computes a minimal PNG color model that can contain all colors as indicated by the stats. +The stats should be computed with lodepng_compute_color_stats. +mode_in is raw color profile of the image the stats were computed on, to copy palette order from when relevant. +Minimal PNG color model means the color type and bit depth that gives smallest amount of bits in the output image, +e.g. gray if only grayscale pixels, palette if less than 256 colors, color key if only single transparent color, ... +This is used if auto_convert is enabled (it is by default). +*/ +static unsigned auto_choose_color(LodePNGColorMode* mode_out, + const LodePNGColorMode* mode_in, + const LodePNGColorStats* stats) { + unsigned error = 0; + unsigned palettebits; + size_t i, n; + size_t numpixels = stats->numpixels; + unsigned palette_ok, gray_ok; + + unsigned alpha = stats->alpha; + unsigned key = stats->key; + unsigned bits = stats->bits; + + mode_out->key_defined = 0; + + if(key && numpixels <= 16) { + alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ + key = 0; + if(bits < 8) bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + + gray_ok = !stats->colored; + if(!stats->allow_greyscale) gray_ok = 0; + if(!gray_ok && bits < 8) bits = 8; + + n = stats->numcolors; + palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8)); + palette_ok = n <= 256 && bits <= 8 && n != 0; /*n==0 means likely numcolors wasn't computed*/ + if(numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ + if(gray_ok && !alpha && bits <= palettebits) palette_ok = 0; /*gray is less overhead*/ + if(!stats->allow_palette) palette_ok = 0; + + if(palette_ok) { + const unsigned char* p = stats->palette; + lodepng_palette_clear(mode_out); /*remove potential earlier palette*/ + for(i = 0; i != stats->numcolors; ++i) { + error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]); + if(error) break; + } + + mode_out->colortype = LCT_PALETTE; + mode_out->bitdepth = palettebits; + + if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize + && mode_in->bitdepth == mode_out->bitdepth) { + /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/ + lodepng_color_mode_cleanup(mode_out); /*clears palette, keeps the above set colortype and bitdepth fields as-is*/ + lodepng_color_mode_copy(mode_out, mode_in); + } + } else /*8-bit or 16-bit per channel*/ { + mode_out->bitdepth = bits; + mode_out->colortype = alpha ? (gray_ok ? LCT_GREY_ALPHA : LCT_RGBA) + : (gray_ok ? LCT_GREY : LCT_RGB); + if(key) { + unsigned mask = (1u << mode_out->bitdepth) - 1u; /*stats always uses 16-bit, mask converts it*/ + mode_out->key_r = stats->key_r & mask; + mode_out->key_g = stats->key_g & mask; + mode_out->key_b = stats->key_b & mask; + mode_out->key_defined = 1; + } + } + + return error; +} + +#endif /* #ifdef LODEPNG_COMPILE_ENCODER */ + +/*Paeth predictor, used by PNG filter type 4*/ +static unsigned char paethPredictor(unsigned char a, unsigned char b, unsigned char c) { + /* the subtractions of unsigned char cast it to a signed type. + With gcc, short is faster than int, with clang int is as fast (as of april 2023)*/ + short pa = (b - c) < 0 ? -(b - c) : (b - c); + short pb = (a - c) < 0 ? -(a - c) : (a - c); + /* writing it out like this compiles to something faster than introducing a temp variable*/ + short pc = (a + b - c - c) < 0 ? -(a + b - c - c) : (a + b - c - c); + /* return input value associated with smallest of pa, pb, pc (with certain priority if equal) */ + if(pb < pa) { a = b; pa = pb; } + return (pc < pa) ? c : a; +} + +/*shared values used by multiple Adam7 related functions*/ + +static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/ +static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/ +static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/ +static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/ + +/* +Outputs various dimensions and positions in the image related to the Adam7 reduced images. +passw: output containing the width of the 7 passes +passh: output containing the height of the 7 passes +filter_passstart: output containing the index of the start and end of each + reduced image with filter bytes +padded_passstart output containing the index of the start and end of each + reduced image when without filter bytes but with padded scanlines +passstart: output containing the index of the start and end of each reduced + image without padding between scanlines, but still padding between the images +w, h: width and height of non-interlaced image +bpp: bits per pixel +"padded" is only relevant if bpp is less than 8 and a scanline or image does not + end at a full byte +*/ +static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8], + size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) { + /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/ + unsigned i; + + /*calculate width and height in pixels of each pass*/ + for(i = 0; i != 7; ++i) { + passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i]; + passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i]; + if(passw[i] == 0) passh[i] = 0; + if(passh[i] == 0) passw[i] = 0; + } + + filter_passstart[0] = padded_passstart[0] = passstart[0] = 0; + for(i = 0; i != 7; ++i) { + /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/ + filter_passstart[i + 1] = filter_passstart[i] + + ((passw[i] && passh[i]) ? passh[i] * (1u + (passw[i] * bpp + 7u) / 8u) : 0); + /*bits padded if needed to fill full byte at end of each scanline*/ + padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7u) / 8u); + /*only padded at end of reduced image*/ + passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7u) / 8u; + } +} + +#ifdef LODEPNG_COMPILE_DECODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG Decoder / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*read the information from the header and store it in the LodePNGInfo. return value is error*/ +unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, + const unsigned char* in, size_t insize) { + unsigned width, height; + LodePNGInfo* info = &state->info_png; + if(insize == 0 || in == 0) { + CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/ + } + if(insize < 33) { + CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/ + } + + /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/ + /* TODO: remove this. One should use a new LodePNGState for new sessions */ + lodepng_info_cleanup(info); + lodepng_info_init(info); + + if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 + || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) { + CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/ + } + if(lodepng_chunk_length(in + 8) != 13) { + CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/ + } + if(!lodepng_chunk_type_equals(in + 8, "IHDR")) { + CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/ + } + + /*read the values given in the header*/ + width = lodepng_read32bitInt(&in[16]); + height = lodepng_read32bitInt(&in[20]); + /*TODO: remove the undocumented feature that allows to give null pointers to width or height*/ + if(w) *w = width; + if(h) *h = height; + info->color.bitdepth = in[24]; + info->color.colortype = (LodePNGColorType)in[25]; + info->compression_method = in[26]; + info->filter_method = in[27]; + info->interlace_method = in[28]; + + /*errors returned only after the parsing so other values are still output*/ + + /*error: invalid image size*/ + if(width == 0 || height == 0) CERROR_RETURN_ERROR(state->error, 93); + /*error: invalid colortype or bitdepth combination*/ + state->error = checkColorValidity(info->color.colortype, info->color.bitdepth); + if(state->error) return state->error; + /*error: only compression method 0 is allowed in the specification*/ + if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32); + /*error: only filter method 0 is allowed in the specification*/ + if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33); + /*error: only interlace methods 0 and 1 exist in the specification*/ + if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34); + + if(!state->decoder.ignore_crc) { + unsigned CRC = lodepng_read32bitInt(&in[29]); + unsigned checksum = lodepng_crc32(&in[12], 17); + if(CRC != checksum) { + CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/ + } + } + + return state->error; +} + +static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, + size_t bytewidth, unsigned char filterType, size_t length) { + /* + For PNG filter method 0 + unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte, + the filter works byte per byte (bytewidth = 1) + precon is the previous unfiltered scanline, recon the result, scanline the current one + the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead + recon and scanline MAY be the same memory address! precon must be disjoint. + */ + + size_t i; + switch(filterType) { + case 0: + for(i = 0; i != length; ++i) recon[i] = scanline[i]; + break; + case 1: { + size_t j = 0; + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; + for(i = bytewidth; i != length; ++i, ++j) recon[i] = scanline[i] + recon[j]; + break; + } + case 2: + if(precon) { + for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i]; + } else { + for(i = 0; i != length; ++i) recon[i] = scanline[i]; + } + break; + case 3: + if(precon) { + size_t j = 0; + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1u); + /* Unroll independent paths of this predictor. A 6x and 8x version is also possible but that adds + too much code. Whether this speeds up anything depends on compiler and settings. */ + if(bytewidth >= 4) { + for(; i + 3 < length; i += 4, j += 4) { + unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2], s3 = scanline[i + 3]; + unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2], r3 = recon[j + 3]; + unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2], p3 = precon[i + 3]; + recon[i + 0] = s0 + ((r0 + p0) >> 1u); + recon[i + 1] = s1 + ((r1 + p1) >> 1u); + recon[i + 2] = s2 + ((r2 + p2) >> 1u); + recon[i + 3] = s3 + ((r3 + p3) >> 1u); + } + } else if(bytewidth >= 3) { + for(; i + 2 < length; i += 3, j += 3) { + unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2]; + unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2]; + unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2]; + recon[i + 0] = s0 + ((r0 + p0) >> 1u); + recon[i + 1] = s1 + ((r1 + p1) >> 1u); + recon[i + 2] = s2 + ((r2 + p2) >> 1u); + } + } else if(bytewidth >= 2) { + for(; i + 1 < length; i += 2, j += 2) { + unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1]; + unsigned char r0 = recon[j + 0], r1 = recon[j + 1]; + unsigned char p0 = precon[i + 0], p1 = precon[i + 1]; + recon[i + 0] = s0 + ((r0 + p0) >> 1u); + recon[i + 1] = s1 + ((r1 + p1) >> 1u); + } + } + for(; i != length; ++i, ++j) recon[i] = scanline[i] + ((recon[j] + precon[i]) >> 1u); + } else { + size_t j = 0; + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; + for(i = bytewidth; i != length; ++i, ++j) recon[i] = scanline[i] + (recon[j] >> 1u); + } + break; + case 4: + if(precon) { + /* Unroll independent paths of this predictor. Whether this speeds up + anything depends on compiler and settings. */ + if(bytewidth == 8) { + unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0; + unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0; + unsigned char a4, b4 = 0, c4, d4 = 0, a5, b5 = 0, c5, d5 = 0; + unsigned char a6, b6 = 0, c6, d6 = 0, a7, b7 = 0, c7, d7 = 0; + for(i = 0; i + 7 < length; i += 8) { + c0 = b0; c1 = b1; c2 = b2; c3 = b3; + c4 = b4; c5 = b5; c6 = b6; c7 = b7; + b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; b3 = precon[i + 3]; + b4 = precon[i + 4]; b5 = precon[i + 5]; b6 = precon[i + 6]; b7 = precon[i + 7]; + a0 = d0; a1 = d1; a2 = d2; a3 = d3; + a4 = d4; a5 = d5; a6 = d6; a7 = d7; + d0 = scanline[i + 0] + paethPredictor(a0, b0, c0); + d1 = scanline[i + 1] + paethPredictor(a1, b1, c1); + d2 = scanline[i + 2] + paethPredictor(a2, b2, c2); + d3 = scanline[i + 3] + paethPredictor(a3, b3, c3); + d4 = scanline[i + 4] + paethPredictor(a4, b4, c4); + d5 = scanline[i + 5] + paethPredictor(a5, b5, c5); + d6 = scanline[i + 6] + paethPredictor(a6, b6, c6); + d7 = scanline[i + 7] + paethPredictor(a7, b7, c7); + recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; recon[i + 3] = d3; + recon[i + 4] = d4; recon[i + 5] = d5; recon[i + 6] = d6; recon[i + 7] = d7; + } + } else if(bytewidth == 6) { + unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0; + unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0; + unsigned char a4, b4 = 0, c4, d4 = 0, a5, b5 = 0, c5, d5 = 0; + for(i = 0; i + 5 < length; i += 6) { + c0 = b0; c1 = b1; c2 = b2; + c3 = b3; c4 = b4; c5 = b5; + b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; + b3 = precon[i + 3]; b4 = precon[i + 4]; b5 = precon[i + 5]; + a0 = d0; a1 = d1; a2 = d2; + a3 = d3; a4 = d4; a5 = d5; + d0 = scanline[i + 0] + paethPredictor(a0, b0, c0); + d1 = scanline[i + 1] + paethPredictor(a1, b1, c1); + d2 = scanline[i + 2] + paethPredictor(a2, b2, c2); + d3 = scanline[i + 3] + paethPredictor(a3, b3, c3); + d4 = scanline[i + 4] + paethPredictor(a4, b4, c4); + d5 = scanline[i + 5] + paethPredictor(a5, b5, c5); + recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; + recon[i + 3] = d3; recon[i + 4] = d4; recon[i + 5] = d5; + } + } else if(bytewidth == 4) { + unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0; + unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0; + for(i = 0; i + 3 < length; i += 4) { + c0 = b0; c1 = b1; c2 = b2; c3 = b3; + b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; b3 = precon[i + 3]; + a0 = d0; a1 = d1; a2 = d2; a3 = d3; + d0 = scanline[i + 0] + paethPredictor(a0, b0, c0); + d1 = scanline[i + 1] + paethPredictor(a1, b1, c1); + d2 = scanline[i + 2] + paethPredictor(a2, b2, c2); + d3 = scanline[i + 3] + paethPredictor(a3, b3, c3); + recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; recon[i + 3] = d3; + } + } else if(bytewidth == 3) { + unsigned char a0, b0 = 0, c0, d0 = 0; + unsigned char a1, b1 = 0, c1, d1 = 0; + unsigned char a2, b2 = 0, c2, d2 = 0; + for(i = 0; i + 2 < length; i += 3) { + c0 = b0; c1 = b1; c2 = b2; + b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; + a0 = d0; a1 = d1; a2 = d2; + d0 = scanline[i + 0] + paethPredictor(a0, b0, c0); + d1 = scanline[i + 1] + paethPredictor(a1, b1, c1); + d2 = scanline[i + 2] + paethPredictor(a2, b2, c2); + recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; + } + } else if(bytewidth == 2) { + unsigned char a0, b0 = 0, c0, d0 = 0; + unsigned char a1, b1 = 0, c1, d1 = 0; + for(i = 0; i + 1 < length; i += 2) { + c0 = b0; c1 = b1; + b0 = precon[i + 0]; + b1 = precon[i + 1]; + a0 = d0; a1 = d1; + d0 = scanline[i + 0] + paethPredictor(a0, b0, c0); + d1 = scanline[i + 1] + paethPredictor(a1, b1, c1); + recon[i + 0] = d0; + recon[i + 1] = d1; + } + } else if(bytewidth == 1) { + unsigned char a, b = 0, c, d = 0; + for(i = 0; i != length; ++i) { + c = b; + b = precon[i]; + a = d; + d = scanline[i] + paethPredictor(a, b, c); + recon[i] = d; + } + } else { + /* Normally not a possible case, but this would handle it correctly */ + for(i = 0; i != bytewidth; ++i) { + recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/ + } + } + /* finish any remaining bytes */ + for(; i != length; ++i) { + recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth])); + } + } else { + size_t j = 0; + for(i = 0; i != bytewidth; ++i) { + recon[i] = scanline[i]; + } + for(i = bytewidth; i != length; ++i, ++j) { + /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/ + recon[i] = (scanline[i] + recon[j]); + } + } + break; + default: return 36; /*error: invalid filter type given*/ + } + return 0; +} + +static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { + /* + For PNG filter method 0 + this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times) + out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline + w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel + in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes) + */ + + unsigned y; + unsigned char* prevline = 0; + + /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ + size_t bytewidth = (bpp + 7u) / 8u; + /*the width of a scanline in bytes, not including the filter type*/ + size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u; + + for(y = 0; y < h; ++y) { + size_t outindex = linebytes * y; + size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + unsigned char filterType = in[inindex]; + + CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes)); + + prevline = &out[outindex]; + } + + return 0; +} + +/* +in: Adam7 interlaced image, with no padding bits between scanlines, but between + reduced images so that each reduced image starts at a byte. +out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h +bpp: bits per pixel +out has the following size in bits: w * h * bpp. +in is possibly bigger due to padding bits between reduced images. +out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation +(because that's likely a little bit faster) +NOTE: comments about padding bits are only relevant if bpp < 8 +*/ +static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + if(bpp >= 8) { + for(i = 0; i != 7; ++i) { + unsigned x, y, b; + size_t bytewidth = bpp / 8u; + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) { + size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth; + size_t pixeloutstart = ((ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * (size_t)w + + ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bytewidth; + for(b = 0; b < bytewidth; ++b) { + out[pixeloutstart + b] = in[pixelinstart + b]; + } + } + } + } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ { + for(i = 0; i != 7; ++i) { + unsigned x, y, b; + unsigned ilinebits = bpp * passw[i]; + unsigned olinebits = bpp * w; + size_t obp, ibp; /*bit pointers (for out and in buffer)*/ + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) { + ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp); + obp = (ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bpp; + for(b = 0; b < bpp; ++b) { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + } + } + } +} + +static void removePaddingBits(unsigned char* out, const unsigned char* in, + size_t olinebits, size_t ilinebits, unsigned h) { + /* + After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need + to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers + for the Adam7 code, the color convert code and the output to the user. + in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must + have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits + also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7 + only useful if (ilinebits - olinebits) is a value in the range 1..7 + */ + unsigned y; + size_t diff = ilinebits - olinebits; + size_t ibp = 0, obp = 0; /*input and output bit pointers*/ + for(y = 0; y < h; ++y) { + size_t x; + for(x = 0; x < olinebits; ++x) { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + ibp += diff; + } +} + +/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from +the IDAT chunks (with filter index bytes and possible padding bits) +return value is error*/ +static unsigned postProcessScanlines(unsigned char* out, unsigned char* in, + unsigned w, unsigned h, const LodePNGInfo* info_png) { + /* + This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype. + Steps: + *) if no Adam7: 1) unfilter 2) remove padding bits (= possible extra bits per scanline if bpp < 8) + *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace + NOTE: the in buffer will be overwritten with intermediate data! + */ + unsigned bpp = lodepng_get_bpp(&info_png->color); + if(bpp == 0) return 31; /*error: invalid colortype*/ + + if(info_png->interlace_method == 0) { + if(bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) { + CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp)); + removePaddingBits(out, in, w * bpp, ((w * bpp + 7u) / 8u) * 8u, h); + } + /*we can immediately filter into the out buffer, no other steps needed*/ + else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp)); + } else /*interlace_method is 1 (Adam7)*/ { + unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + for(i = 0; i != 7; ++i) { + CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp)); + /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline, + move bytes instead of bits or move not at all*/ + if(bpp < 8) { + /*remove padding bits in scanlines; after this there still may be padding + bits between the different reduced images: each reduced image still starts nicely at a byte*/ + removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp, + ((passw[i] * bpp + 7u) / 8u) * 8u, passh[i]); + } + } + + Adam7_deinterlace(out, in, w, h, bpp); + } + + return 0; +} + +static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) { + unsigned pos = 0, i; + color->palettesize = chunkLength / 3u; + if(color->palettesize == 0 || color->palettesize > 256) return 38; /*error: palette too small or big*/ + lodepng_color_mode_alloc_palette(color); + if(!color->palette && color->palettesize) { + color->palettesize = 0; + return 83; /*alloc fail*/ + } + + for(i = 0; i != color->palettesize; ++i) { + color->palette[4 * i + 0] = data[pos++]; /*R*/ + color->palette[4 * i + 1] = data[pos++]; /*G*/ + color->palette[4 * i + 2] = data[pos++]; /*B*/ + color->palette[4 * i + 3] = 255; /*alpha*/ + } + + return 0; /* OK */ +} + +static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) { + unsigned i; + if(color->colortype == LCT_PALETTE) { + /*error: more alpha values given than there are palette entries*/ + if(chunkLength > color->palettesize) return 39; + + for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i]; + } else if(color->colortype == LCT_GREY) { + /*error: this chunk must be 2 bytes for grayscale image*/ + if(chunkLength != 2) return 30; + + color->key_defined = 1; + color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1]; + } else if(color->colortype == LCT_RGB) { + /*error: this chunk must be 6 bytes for RGB image*/ + if(chunkLength != 6) return 41; + + color->key_defined = 1; + color->key_r = 256u * data[0] + data[1]; + color->key_g = 256u * data[2] + data[3]; + color->key_b = 256u * data[4] + data[5]; + } + else return 42; /*error: tRNS chunk not allowed for other color models*/ + + return 0; /* OK */ +} + + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*background color chunk (bKGD)*/ +static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(info->color.colortype == LCT_PALETTE) { + /*error: this chunk must be 1 byte for indexed color image*/ + if(chunkLength != 1) return 43; + + /*error: invalid palette index, or maybe this chunk appeared before PLTE*/ + if(data[0] >= info->color.palettesize) return 103; + + info->background_defined = 1; + info->background_r = info->background_g = info->background_b = data[0]; + } else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { + /*error: this chunk must be 2 bytes for grayscale image*/ + if(chunkLength != 2) return 44; + + /*the values are truncated to bitdepth in the PNG file*/ + info->background_defined = 1; + info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1]; + } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { + /*error: this chunk must be 6 bytes for grayscale image*/ + if(chunkLength != 6) return 45; + + /*the values are truncated to bitdepth in the PNG file*/ + info->background_defined = 1; + info->background_r = 256u * data[0] + data[1]; + info->background_g = 256u * data[2] + data[3]; + info->background_b = 256u * data[4] + data[5]; + } + + return 0; /* OK */ +} + +/*text chunk (tEXt)*/ +static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + unsigned error = 0; + char *key = 0, *str = 0; + + while(!error) /*not really a while loop, only used to break on error*/ { + unsigned length, string2_begin; + + length = 0; + while(length < chunkLength && data[length] != 0) ++length; + /*even though it's not allowed by the standard, no error is thrown if + there's no null termination char, if the text is empty*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(key, data, length); + key[length] = 0; + + string2_begin = length + 1; /*skip keyword null terminator*/ + + length = (unsigned)(chunkLength < string2_begin ? 0 : chunkLength - string2_begin); + str = (char*)lodepng_malloc(length + 1); + if(!str) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(str, data + string2_begin, length); + str[length] = 0; + + error = lodepng_add_text(info, key, str); + + break; + } + + lodepng_free(key); + lodepng_free(str); + + return error; +} + +/*compressed text chunk (zTXt)*/ +static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecoderSettings* decoder, + const unsigned char* data, size_t chunkLength) { + unsigned error = 0; + + /*copy the object to change parameters in it*/ + LodePNGDecompressSettings zlibsettings = decoder->zlibsettings; + + unsigned length, string2_begin; + char *key = 0; + unsigned char* str = 0; + size_t size = 0; + + while(!error) /*not really a while loop, only used to break on error*/ { + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(key, data, length); + key[length] = 0; + + if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ + + string2_begin = length + 2; + if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ + + length = (unsigned)chunkLength - string2_begin; + zlibsettings.max_output_size = decoder->max_text_size; + /*will fail if zlib error, e.g. if length is too small*/ + error = zlib_decompress(&str, &size, 0, &data[string2_begin], + length, &zlibsettings); + /*error: compressed text larger than decoder->max_text_size*/ + if(error && size > zlibsettings.max_output_size) error = 112; + if(error) break; + error = lodepng_add_text_sized(info, key, (char*)str, size); + break; + } + + lodepng_free(key); + lodepng_free(str); + + return error; +} + +/*international text chunk (iTXt)*/ +static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecoderSettings* decoder, + const unsigned char* data, size_t chunkLength) { + unsigned error = 0; + unsigned i; + + /*copy the object to change parameters in it*/ + LodePNGDecompressSettings zlibsettings = decoder->zlibsettings; + + unsigned length, begin, compressed; + char *key = 0, *langtag = 0, *transkey = 0; + + while(!error) /*not really a while loop, only used to break on error*/ { + /*Quick check if the chunk length isn't too small. Even without check + it'd still fail with other error checks below if it's too short. This just gives a different error code.*/ + if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/ + + /*read the key*/ + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(key, data, length); + key[length] = 0; + + /*read the compression method*/ + compressed = data[length + 1]; + if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ + + /*even though it's not allowed by the standard, no error is thrown if + there's no null termination char, if the text is empty for the next 3 texts*/ + + /*read the langtag*/ + begin = length + 3; + length = 0; + for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; + + langtag = (char*)lodepng_malloc(length + 1); + if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(langtag, data + begin, length); + langtag[length] = 0; + + /*read the transkey*/ + begin += length + 1; + length = 0; + for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; + + transkey = (char*)lodepng_malloc(length + 1); + if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/ + + lodepng_memcpy(transkey, data + begin, length); + transkey[length] = 0; + + /*read the actual text*/ + begin += length + 1; + + length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin; + + if(compressed) { + unsigned char* str = 0; + size_t size = 0; + zlibsettings.max_output_size = decoder->max_text_size; + /*will fail if zlib error, e.g. if length is too small*/ + error = zlib_decompress(&str, &size, 0, &data[begin], + length, &zlibsettings); + /*error: compressed text larger than decoder->max_text_size*/ + if(error && size > zlibsettings.max_output_size) error = 112; + if(!error) error = lodepng_add_itext_sized(info, key, langtag, transkey, (char*)str, size); + lodepng_free(str); + } else { + error = lodepng_add_itext_sized(info, key, langtag, transkey, (const char*)(data + begin), length); + } + + break; + } + + lodepng_free(key); + lodepng_free(langtag); + lodepng_free(transkey); + + return error; +} + +static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 7) return 73; /*invalid tIME chunk size*/ + + info->time_defined = 1; + info->time.year = 256u * data[0] + data[1]; + info->time.month = data[2]; + info->time.day = data[3]; + info->time.hour = data[4]; + info->time.minute = data[5]; + info->time.second = data[6]; + + return 0; /* OK */ +} + +static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/ + + info->phys_defined = 1; + info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; + info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7]; + info->phys_unit = data[8]; + + return 0; /* OK */ +} + +static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 4) return 96; /*invalid gAMA chunk size*/ + + info->gama_defined = 1; + info->gama_gamma = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; + + return 0; /* OK */ +} + +static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 32) return 97; /*invalid cHRM chunk size*/ + + info->chrm_defined = 1; + info->chrm_white_x = 16777216u * data[ 0] + 65536u * data[ 1] + 256u * data[ 2] + data[ 3]; + info->chrm_white_y = 16777216u * data[ 4] + 65536u * data[ 5] + 256u * data[ 6] + data[ 7]; + info->chrm_red_x = 16777216u * data[ 8] + 65536u * data[ 9] + 256u * data[10] + data[11]; + info->chrm_red_y = 16777216u * data[12] + 65536u * data[13] + 256u * data[14] + data[15]; + info->chrm_green_x = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19]; + info->chrm_green_y = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23]; + info->chrm_blue_x = 16777216u * data[24] + 65536u * data[25] + 256u * data[26] + data[27]; + info->chrm_blue_y = 16777216u * data[28] + 65536u * data[29] + 256u * data[30] + data[31]; + + return 0; /* OK */ +} + +static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 1) return 98; /*invalid sRGB chunk size (this one is never ignored)*/ + + info->srgb_defined = 1; + info->srgb_intent = data[0]; + + return 0; /* OK */ +} + +static unsigned readChunk_iCCP(LodePNGInfo* info, const LodePNGDecoderSettings* decoder, + const unsigned char* data, size_t chunkLength) { + unsigned error = 0; + unsigned i; + size_t size = 0; + /*copy the object to change parameters in it*/ + LodePNGDecompressSettings zlibsettings = decoder->zlibsettings; + + unsigned length, string2_begin; + + if(info->iccp_defined) lodepng_clear_icc(info); + info->iccp_defined = 1; + + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 2 >= chunkLength) return 75; /*no null termination, corrupt?*/ + if(length < 1 || length > 79) return 89; /*keyword too short or long*/ + + info->iccp_name = (char*)lodepng_malloc(length + 1); + if(!info->iccp_name) return 83; /*alloc fail*/ + + info->iccp_name[length] = 0; + for(i = 0; i != length; ++i) info->iccp_name[i] = (char)data[i]; + + if(data[length + 1] != 0) return 72; /*the 0 byte indicating compression must be 0*/ + + string2_begin = length + 2; + if(string2_begin > chunkLength) return 75; /*no null termination, corrupt?*/ + + length = (unsigned)chunkLength - string2_begin; + zlibsettings.max_output_size = decoder->max_icc_size; + error = zlib_decompress(&info->iccp_profile, &size, 0, + &data[string2_begin], + length, &zlibsettings); + /*error: ICC profile larger than decoder->max_icc_size*/ + if(error && size > zlibsettings.max_output_size) error = 113; + info->iccp_profile_size = (unsigned)size; + if(!error && !info->iccp_profile_size) error = 100; /*invalid ICC profile size*/ + return error; +} + +static unsigned readChunk_cICP(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 4) return 117; /*invalid cICP chunk size*/ + + info->cicp_defined = 1; + /* No error checking for value ranges is done here, that is up to a CICP + handling library, not the PNG decoding. Just pass on the metadata. */ + info->cicp_color_primaries = data[0]; + info->cicp_transfer_function = data[1]; + info->cicp_matrix_coefficients = data[2]; + info->cicp_video_full_range_flag = data[3]; + + return 0; /* OK */ +} + +static unsigned readChunk_mDCV(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 24) return 119; /*invalid mDCV chunk size*/ + + info->mdcv_defined = 1; + info->mdcv_red_x = 256u * data[0] + data[1]; + info->mdcv_red_y = 256u * data[2] + data[3]; + info->mdcv_green_x = 256u * data[4] + data[5]; + info->mdcv_green_y = 256u * data[6] + data[7]; + info->mdcv_blue_x = 256u * data[8] + data[9]; + info->mdcv_blue_y = 256u * data[10] + data[11]; + info->mdcv_white_x = 256u * data[12] + data[13]; + info->mdcv_white_y = 256u * data[14] + data[15]; + info->mdcv_max_luminance = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19]; + info->mdcv_min_luminance = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23]; + + return 0; /* OK */ +} + +static unsigned readChunk_cLLI(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(chunkLength != 8) return 120; /*invalid cLLI chunk size*/ + + info->clli_defined = 1; + info->clli_max_cll = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; + info->clli_max_fall = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7]; + + return 0; /* OK */ +} + +static unsigned readChunk_eXIf(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + return lodepng_set_exif(info, data, (unsigned)chunkLength); +} + +/*significant bits chunk (sBIT)*/ +static unsigned readChunk_sBIT(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + unsigned bitdepth = (info->color.colortype == LCT_PALETTE) ? 8 : info->color.bitdepth; + if(info->color.colortype == LCT_GREY) { + /*error: this chunk must be 1 bytes for grayscale image*/ + if(chunkLength != 1) return 114; + if(data[0] == 0 || data[0] > bitdepth) return 115; + info->sbit_defined = 1; + info->sbit_r = info->sbit_g = info->sbit_b = data[0]; /*setting g and b is not required, but sensible*/ + } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_PALETTE) { + /*error: this chunk must be 3 bytes for RGB and palette image*/ + if(chunkLength != 3) return 114; + if(data[0] == 0 || data[1] == 0 || data[2] == 0) return 115; + if(data[0] > bitdepth || data[1] > bitdepth || data[2] > bitdepth) return 115; + info->sbit_defined = 1; + info->sbit_r = data[0]; + info->sbit_g = data[1]; + info->sbit_b = data[2]; + } else if(info->color.colortype == LCT_GREY_ALPHA) { + /*error: this chunk must be 2 byte for grayscale with alpha image*/ + if(chunkLength != 2) return 114; + if(data[0] == 0 || data[1] == 0) return 115; + if(data[0] > bitdepth || data[1] > bitdepth) return 115; + info->sbit_defined = 1; + info->sbit_r = info->sbit_g = info->sbit_b = data[0]; /*setting g and b is not required, but sensible*/ + info->sbit_a = data[1]; + } else if(info->color.colortype == LCT_RGBA) { + /*error: this chunk must be 4 bytes for grayscale image*/ + if(chunkLength != 4) return 114; + if(data[0] == 0 || data[1] == 0 || data[2] == 0 || data[3] == 0) return 115; + if(data[0] > bitdepth || data[1] > bitdepth || data[2] > bitdepth || data[3] > bitdepth) return 115; + info->sbit_defined = 1; + info->sbit_r = data[0]; + info->sbit_g = data[1]; + info->sbit_b = data[2]; + info->sbit_a = data[3]; + } + + return 0; /* OK */ +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos, + const unsigned char* in, size_t insize) { + const unsigned char* chunk = in + pos; + unsigned chunkLength; + const unsigned char* data; + unsigned unhandled = 0; + unsigned error = 0; + + if(pos + 4 > insize) return 30; + chunkLength = lodepng_chunk_length(chunk); + if(chunkLength > 2147483647) return 63; + data = lodepng_chunk_data_const(chunk); + if(chunkLength + 12 > insize - pos) return 30; + + if(lodepng_chunk_type_equals(chunk, "PLTE")) { + error = readChunk_PLTE(&state->info_png.color, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "tRNS")) { + error = readChunk_tRNS(&state->info_png.color, data, chunkLength); +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + } else if(lodepng_chunk_type_equals(chunk, "bKGD")) { + error = readChunk_bKGD(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "tEXt")) { + error = readChunk_tEXt(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "zTXt")) { + error = readChunk_zTXt(&state->info_png, &state->decoder, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "iTXt")) { + error = readChunk_iTXt(&state->info_png, &state->decoder, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "tIME")) { + error = readChunk_tIME(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "pHYs")) { + error = readChunk_pHYs(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "gAMA")) { + error = readChunk_gAMA(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "cHRM")) { + error = readChunk_cHRM(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "sRGB")) { + error = readChunk_sRGB(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "iCCP")) { + error = readChunk_iCCP(&state->info_png, &state->decoder, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "cICP")) { + error = readChunk_cICP(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "mDCV")) { + error = readChunk_mDCV(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "cLLI")) { + error = readChunk_cLLI(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "eXIf")) { + error = readChunk_eXIf(&state->info_png, data, chunkLength); + } else if(lodepng_chunk_type_equals(chunk, "sBIT")) { + error = readChunk_sBIT(&state->info_png, data, chunkLength); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } else { + /* unhandled chunk is ok (is not an error) */ + unhandled = 1; + } + + if(!error && !unhandled && !state->decoder.ignore_crc) { + if(lodepng_chunk_check_crc(chunk)) return 57; /*invalid CRC*/ + } + + return error; +} + +/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/ +static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize) { + unsigned char IEND = 0; + const unsigned char* chunk; /*points to beginning of next chunk*/ + unsigned char* idat; /*the data from idat chunks, zlib compressed*/ + size_t idatsize = 0; + unsigned char* scanlines = 0; + size_t scanlines_size = 0, expected_size = 0; + size_t outsize = 0; + + /*for unknown chunk order*/ + unsigned unknown = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + + + /* safe output values in case error happens */ + *out = 0; + *w = *h = 0; + + state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ + if(state->error) return; + + if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) { + CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/ + } + + /*the input filesize is a safe upper bound for the sum of idat chunks size*/ + idat = (unsigned char*)lodepng_malloc(insize); + if(!idat) CERROR_RETURN(state->error, 83); /*alloc fail*/ + + chunk = &in[33]; /*first byte of the first chunk after the header*/ + + /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. + IDAT data is put at the start of the in buffer*/ + while(!IEND && !state->error) { + unsigned chunkLength; + const unsigned char* data; /*the data in the chunk*/ + size_t pos = (size_t)(chunk - in); + + /*error: next chunk out of bounds of the in buffer*/ + if(chunk < in || pos + 12 > insize) { + if(state->decoder.ignore_end) break; /*other errors may still happen though*/ + CERROR_BREAK(state->error, 30); + } + + /*length of the data of the chunk, excluding the 12 bytes for length, chunk type and CRC*/ + chunkLength = lodepng_chunk_length(chunk); + /*error: chunk length larger than the max PNG chunk size*/ + if(chunkLength > 2147483647) { + if(state->decoder.ignore_end) break; /*other errors may still happen though*/ + CERROR_BREAK(state->error, 63); + } + + if(pos + (size_t)chunkLength + 12 > insize || pos + (size_t)chunkLength + 12 < pos) { + CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk (or int overflow)*/ + } + + data = lodepng_chunk_data_const(chunk); + + unknown = 0; + + /*IDAT chunk, containing compressed image data*/ + if(lodepng_chunk_type_equals(chunk, "IDAT")) { + size_t newsize; + if(lodepng_addofl(idatsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95); + if(newsize > insize) CERROR_BREAK(state->error, 95); + lodepng_memcpy(idat + idatsize, data, chunkLength); + idatsize += chunkLength; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + critical_pos = 3; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } else if(lodepng_chunk_type_equals(chunk, "IEND")) { + /*IEND chunk*/ + IEND = 1; + } else if(lodepng_chunk_type_equals(chunk, "PLTE")) { + /*palette chunk (PLTE)*/ + state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength); + if(state->error) break; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + critical_pos = 2; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } else if(lodepng_chunk_type_equals(chunk, "tRNS")) { + /*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled + in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that + affects the alpha channel of pixels. */ + state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength); + if(state->error) break; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*background color chunk (bKGD)*/ + } else if(lodepng_chunk_type_equals(chunk, "bKGD")) { + state->error = readChunk_bKGD(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "tEXt")) { + /*text chunk (tEXt)*/ + if(state->decoder.read_text_chunks) { + state->error = readChunk_tEXt(&state->info_png, data, chunkLength); + if(state->error) break; + } + } else if(lodepng_chunk_type_equals(chunk, "zTXt")) { + /*compressed text chunk (zTXt)*/ + if(state->decoder.read_text_chunks) { + state->error = readChunk_zTXt(&state->info_png, &state->decoder, data, chunkLength); + if(state->error) break; + } + } else if(lodepng_chunk_type_equals(chunk, "iTXt")) { + /*international text chunk (iTXt)*/ + if(state->decoder.read_text_chunks) { + state->error = readChunk_iTXt(&state->info_png, &state->decoder, data, chunkLength); + if(state->error) break; + } + } else if(lodepng_chunk_type_equals(chunk, "tIME")) { + state->error = readChunk_tIME(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "pHYs")) { + state->error = readChunk_pHYs(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "gAMA")) { + state->error = readChunk_gAMA(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "cHRM")) { + state->error = readChunk_cHRM(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "sRGB")) { + state->error = readChunk_sRGB(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "iCCP")) { + state->error = readChunk_iCCP(&state->info_png, &state->decoder, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "cICP")) { + state->error = readChunk_cICP(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "mDCV")) { + state->error = readChunk_mDCV(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "cLLI")) { + state->error = readChunk_cLLI(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "eXIf")) { + state->error = readChunk_eXIf(&state->info_png, data, chunkLength); + if(state->error) break; + } else if(lodepng_chunk_type_equals(chunk, "sBIT")) { + state->error = readChunk_sBIT(&state->info_png, data, chunkLength); + if(state->error) break; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } else /*it's not an implemented chunk type, so ignore it: skip over the data*/ { + if(!lodepng_chunk_type_name_valid(chunk)) { + CERROR_BREAK(state->error, 121); /* invalid chunk type name */ + } + if(lodepng_chunk_reserved(chunk)) { + CERROR_BREAK(state->error, 122); /* invalid third lowercase character */ + } + + /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/ + if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) { + CERROR_BREAK(state->error, 69); + } + + unknown = 1; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + if(state->decoder.remember_unknown_chunks) { + state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1], + &state->info_png.unknown_chunks_size[critical_pos - 1], chunk); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } + + if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ { + if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/ + } + + if(!IEND) chunk = lodepng_chunk_next_const(chunk, in + insize); + } + + if(!state->error && state->info_png.color.colortype == LCT_PALETTE && !state->info_png.color.palette) { + state->error = 106; /* error: PNG file must have PLTE chunk if color type is palette */ + } + + if(!state->error) { + /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation. + If the decompressed size does not match the prediction, the image must be corrupt.*/ + if(state->info_png.interlace_method == 0) { + unsigned bpp = lodepng_get_bpp(&state->info_png.color); + expected_size = lodepng_get_raw_size_idat(*w, *h, bpp); + } else { + unsigned bpp = lodepng_get_bpp(&state->info_png.color); + /*Adam-7 interlaced: expected size is the sum of the 7 sub-images sizes*/ + expected_size = 0; + expected_size += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, bpp); + if(*w > 4) expected_size += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, bpp); + expected_size += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, bpp); + if(*w > 2) expected_size += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, bpp); + expected_size += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, bpp); + if(*w > 1) expected_size += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, bpp); + expected_size += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, bpp); + } + + state->error = zlib_decompress(&scanlines, &scanlines_size, expected_size, idat, idatsize, &state->decoder.zlibsettings); + } + if(!state->error && scanlines_size != expected_size) state->error = 91; /*decompressed size doesn't match prediction*/ + lodepng_free(idat); + + if(!state->error) { + outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color); + *out = (unsigned char*)lodepng_malloc(outsize); + if(!*out) state->error = 83; /*alloc fail*/ + } + if(!state->error) { + lodepng_memset(*out, 0, outsize); + state->error = postProcessScanlines(*out, scanlines, *w, *h, &state->info_png); + } + lodepng_free(scanlines); +} + +unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize) { + *out = 0; + decodeGeneric(out, w, h, state, in, insize); + if(state->error) return state->error; +#ifdef LODEPNG_COMPILE_COLOR_CONVERT + if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) { + /*same color type, no copying or converting of data needed*/ + /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype + the raw image has to the end user*/ + if(!state->decoder.color_convert) { + state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color); + if(state->error) return state->error; + } + } else { /*color conversion needed*/ + unsigned char* data = *out; + size_t outsize; + + /*TODO: check if this works according to the statement in the documentation: "The converter can convert + from grayscale input color type, to 8-bit grayscale or grayscale with alpha"*/ + if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA) + && !(state->info_raw.bitdepth == 8)) { + return 56; /*unsupported color mode conversion*/ + } + + outsize = lodepng_get_raw_size(*w, *h, &state->info_raw); + *out = (unsigned char*)lodepng_malloc(outsize); + if(!(*out)) { + state->error = 83; /*alloc fail*/ + } + else state->error = lodepng_convert(*out, data, &state->info_raw, + &state->info_png.color, *w, *h); + lodepng_free(data); + } +#else + if (!lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) + return 56; /*unsupported color mode conversion*/ +#endif + return state->error; +} + +unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, + size_t insize, LodePNGColorType colortype, unsigned bitdepth) { + unsigned error; + LodePNGState state; + lodepng_state_init(&state); + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*disable reading things that this function doesn't output*/ + state.decoder.read_text_chunks = 0; + state.decoder.remember_unknown_chunks = 0; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + error = lodepng_decode(out, w, h, &state, in, insize); + lodepng_state_cleanup(&state); + return error; +} + +unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) { + return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8); +} + +unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) { + return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename, + LodePNGColorType colortype, unsigned bitdepth) { + unsigned char* buffer = 0; + size_t buffersize; + unsigned error; + /* safe output values in case error happens */ + *out = 0; + *w = *h = 0; + error = lodepng_load_file(&buffer, &buffersize, filename); + if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth); + lodepng_free(buffer); + return error; +} + +unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) { + return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8); +} + +unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) { + return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8); +} +#endif /*LODEPNG_COMPILE_DISK*/ + +void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) { +#ifdef LODEPNG_COMPILE_COLOR_CONVERT + settings->color_convert = 1; +#endif +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + settings->read_text_chunks = 1; + settings->remember_unknown_chunks = 0; + settings->max_text_size = 16777216; + settings->max_icc_size = 16777216; /* 16MB is much more than enough for any reasonable ICC profile */ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + settings->ignore_crc = 0; + settings->ignore_critical = 0; + settings->ignore_end = 0; + lodepng_decompress_settings_init(&settings->zlibsettings); +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) + +void lodepng_state_init(LodePNGState* state) { +#ifdef LODEPNG_COMPILE_DECODER + lodepng_decoder_settings_init(&state->decoder); +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER + lodepng_encoder_settings_init(&state->encoder); +#endif /*LODEPNG_COMPILE_ENCODER*/ + lodepng_color_mode_init(&state->info_raw); + lodepng_info_init(&state->info_png); + state->error = 1; +} + +void lodepng_state_cleanup(LodePNGState* state) { + lodepng_color_mode_cleanup(&state->info_raw); + lodepng_info_cleanup(&state->info_png); +} + +void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) { + lodepng_state_cleanup(dest); + *dest = *source; + lodepng_color_mode_init(&dest->info_raw); + lodepng_info_init(&dest->info_png); + dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return; + dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return; +} + +#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ + +#ifdef LODEPNG_COMPILE_ENCODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG Encoder / */ +/* ////////////////////////////////////////////////////////////////////////// */ + + +static unsigned writeSignature(ucvector* out) { + size_t pos = out->size; + const unsigned char signature[] = {137, 80, 78, 71, 13, 10, 26, 10}; + /*8 bytes PNG signature, aka the magic bytes*/ + if(!ucvector_resize(out, out->size + 8)) return 83; /*alloc fail*/ + lodepng_memcpy(out->data + pos, signature, 8); + return 0; +} + +static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) { + unsigned char *chunk, *data; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 13, "IHDR")); + data = chunk + 8; + + lodepng_set32bitInt(data + 0, w); /*width*/ + lodepng_set32bitInt(data + 4, h); /*height*/ + data[8] = (unsigned char)bitdepth; /*bit depth*/ + data[9] = (unsigned char)colortype; /*color type*/ + data[10] = 0; /*compression method*/ + data[11] = 0; /*filter method*/ + data[12] = interlace_method; /*interlace method*/ + + lodepng_chunk_generate_crc(chunk); + return 0; +} + +/* only adds the chunk if needed (there is a key or palette with alpha) */ +static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) { + unsigned char* chunk; + size_t i, j = 8; + + if(info->palettesize == 0 || info->palettesize > 256) { + return 68; /*invalid palette size, it is only allowed to be 1-256*/ + } + + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, info->palettesize * 3, "PLTE")); + + for(i = 0; i != info->palettesize; ++i) { + /*add all channels except alpha channel*/ + chunk[j++] = info->palette[i * 4 + 0]; + chunk[j++] = info->palette[i * 4 + 1]; + chunk[j++] = info->palette[i * 4 + 2]; + } + + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) { + unsigned char* chunk = 0; + + if(info->colortype == LCT_PALETTE) { + size_t i, amount = info->palettesize; + /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/ + for(i = info->palettesize; i != 0; --i) { + if(info->palette[4 * (i - 1) + 3] != 255) break; + --amount; + } + if(amount) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, amount, "tRNS")); + /*add the alpha channel values from the palette*/ + for(i = 0; i != amount; ++i) chunk[8 + i] = info->palette[4 * i + 3]; + } + } else if(info->colortype == LCT_GREY) { + if(info->key_defined) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "tRNS")); + chunk[8] = (unsigned char)(info->key_r >> 8); + chunk[9] = (unsigned char)(info->key_r & 255); + } + } else if(info->colortype == LCT_RGB) { + if(info->key_defined) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "tRNS")); + chunk[8] = (unsigned char)(info->key_r >> 8); + chunk[9] = (unsigned char)(info->key_r & 255); + chunk[10] = (unsigned char)(info->key_g >> 8); + chunk[11] = (unsigned char)(info->key_g & 255); + chunk[12] = (unsigned char)(info->key_b >> 8); + chunk[13] = (unsigned char)(info->key_b & 255); + } + } + + if(chunk) lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize, + LodePNGCompressSettings* zlibsettings) { + unsigned error = 0; + unsigned char* zlib = 0; + size_t pos = 0; + size_t zlibsize = 0; + /* max chunk length allowed by the specification is 2147483647 bytes */ + const size_t max_chunk_length = 2147483647u; + + error = zlib_compress(&zlib, &zlibsize, data, datasize, zlibsettings); + while(!error) { + if(zlibsize - pos > max_chunk_length) { + error = lodepng_chunk_createv(out, max_chunk_length, "IDAT", zlib + pos); + pos += max_chunk_length; + } else { + error = lodepng_chunk_createv(out, zlibsize - pos, "IDAT", zlib + pos); + break; + } + } + lodepng_free(zlib); + return error; +} + +static unsigned addChunk_IEND(ucvector* out) { + return lodepng_chunk_createv(out, 0, "IEND", 0); +} + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + +static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) { + unsigned char* chunk = 0; + size_t keysize = lodepng_strlen(keyword), textsize = lodepng_strlen(textstring); + size_t size = keysize + 1 + textsize; + if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, size, "tEXt")); + lodepng_memcpy(chunk + 8, keyword, keysize); + chunk[8 + keysize] = 0; /*null termination char*/ + lodepng_memcpy(chunk + 9 + keysize, textstring, textsize); + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring, + LodePNGCompressSettings* zlibsettings) { + unsigned error = 0; + unsigned char* chunk = 0; + unsigned char* compressed = 0; + size_t compressedsize = 0; + size_t textsize = lodepng_strlen(textstring); + size_t keysize = lodepng_strlen(keyword); + if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ + + error = zlib_compress(&compressed, &compressedsize, + (const unsigned char*)textstring, textsize, zlibsettings); + if(!error) { + size_t size = keysize + 2 + compressedsize; + error = lodepng_chunk_init(&chunk, out, size, "zTXt"); + } + if(!error) { + lodepng_memcpy(chunk + 8, keyword, keysize); + chunk[8 + keysize] = 0; /*null termination char*/ + chunk[9 + keysize] = 0; /*compression method: 0*/ + lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize); + lodepng_chunk_generate_crc(chunk); + } + + lodepng_free(compressed); + return error; +} + +static unsigned addChunk_iTXt(ucvector* out, unsigned compress, const char* keyword, const char* langtag, + const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) { + unsigned error = 0; + unsigned char* chunk = 0; + unsigned char* compressed = 0; + size_t compressedsize = 0; + size_t textsize = lodepng_strlen(textstring); + size_t keysize = lodepng_strlen(keyword), langsize = lodepng_strlen(langtag), transsize = lodepng_strlen(transkey); + + if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ + + if(compress) { + error = zlib_compress(&compressed, &compressedsize, + (const unsigned char*)textstring, textsize, zlibsettings); + } + if(!error) { + size_t size = keysize + 3 + langsize + 1 + transsize + 1 + (compress ? compressedsize : textsize); + error = lodepng_chunk_init(&chunk, out, size, "iTXt"); + } + if(!error) { + size_t pos = 8; + lodepng_memcpy(chunk + pos, keyword, keysize); + pos += keysize; + chunk[pos++] = 0; /*null termination char*/ + chunk[pos++] = (compress ? 1 : 0); /*compression flag*/ + chunk[pos++] = 0; /*compression method: 0*/ + lodepng_memcpy(chunk + pos, langtag, langsize); + pos += langsize; + chunk[pos++] = 0; /*null termination char*/ + lodepng_memcpy(chunk + pos, transkey, transsize); + pos += transsize; + chunk[pos++] = 0; /*null termination char*/ + if(compress) { + lodepng_memcpy(chunk + pos, compressed, compressedsize); + } else { + lodepng_memcpy(chunk + pos, textstring, textsize); + } + lodepng_chunk_generate_crc(chunk); + } + + lodepng_free(compressed); + return error; +} + +static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) { + unsigned char* chunk = 0; + if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "bKGD")); + chunk[8] = (unsigned char)(info->background_r >> 8); + chunk[9] = (unsigned char)(info->background_r & 255); + } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "bKGD")); + chunk[8] = (unsigned char)(info->background_r >> 8); + chunk[9] = (unsigned char)(info->background_r & 255); + chunk[10] = (unsigned char)(info->background_g >> 8); + chunk[11] = (unsigned char)(info->background_g & 255); + chunk[12] = (unsigned char)(info->background_b >> 8); + chunk[13] = (unsigned char)(info->background_b & 255); + } else if(info->color.colortype == LCT_PALETTE) { + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 1, "bKGD")); + chunk[8] = (unsigned char)(info->background_r & 255); /*palette index*/ + } + if(chunk) lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) { + unsigned char* chunk; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 7, "tIME")); + chunk[8] = (unsigned char)(time->year >> 8); + chunk[9] = (unsigned char)(time->year & 255); + chunk[10] = (unsigned char)time->month; + chunk[11] = (unsigned char)time->day; + chunk[12] = (unsigned char)time->hour; + chunk[13] = (unsigned char)time->minute; + chunk[14] = (unsigned char)time->second; + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) { + unsigned char* chunk; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 9, "pHYs")); + lodepng_set32bitInt(chunk + 8, info->phys_x); + lodepng_set32bitInt(chunk + 12, info->phys_y); + chunk[16] = info->phys_unit; + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) { + unsigned char* chunk; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "gAMA")); + lodepng_set32bitInt(chunk + 8, info->gama_gamma); + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) { + unsigned char* chunk; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 32, "cHRM")); + lodepng_set32bitInt(chunk + 8, info->chrm_white_x); + lodepng_set32bitInt(chunk + 12, info->chrm_white_y); + lodepng_set32bitInt(chunk + 16, info->chrm_red_x); + lodepng_set32bitInt(chunk + 20, info->chrm_red_y); + lodepng_set32bitInt(chunk + 24, info->chrm_green_x); + lodepng_set32bitInt(chunk + 28, info->chrm_green_y); + lodepng_set32bitInt(chunk + 32, info->chrm_blue_x); + lodepng_set32bitInt(chunk + 36, info->chrm_blue_y); + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_sRGB(ucvector* out, const LodePNGInfo* info) { + unsigned char data = info->srgb_intent; + return lodepng_chunk_createv(out, 1, "sRGB", &data); +} + +static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCompressSettings* zlibsettings) { + unsigned error = 0; + unsigned char* chunk = 0; + unsigned char* compressed = 0; + size_t compressedsize = 0; + size_t keysize = lodepng_strlen(info->iccp_name); + + if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ + error = zlib_compress(&compressed, &compressedsize, + info->iccp_profile, info->iccp_profile_size, zlibsettings); + if(!error) { + size_t size = keysize + 2 + compressedsize; + error = lodepng_chunk_init(&chunk, out, size, "iCCP"); + } + if(!error) { + lodepng_memcpy(chunk + 8, info->iccp_name, keysize); + chunk[8 + keysize] = 0; /*null termination char*/ + chunk[9 + keysize] = 0; /*compression method: 0*/ + lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize); + lodepng_chunk_generate_crc(chunk); + } + + lodepng_free(compressed); + return error; +} + +static unsigned addChunk_cICP(ucvector* out, const LodePNGInfo* info) { + unsigned char* chunk; + /* Allow up to 255 since they are bytes. The ITU-R-BT.709 spec has a more + restricted set of valid values for each field, but that's up to the error + handling of a CICP library, not the PNG encoding/decoding, to manage. */ + if(info->cicp_color_primaries > 255) return 116; + if(info->cicp_transfer_function > 255) return 116; + if(info->cicp_matrix_coefficients > 255) return 116; + if(info->cicp_video_full_range_flag > 255) return 116; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "cICP")); + chunk[8 + 0] = (unsigned char)info->cicp_color_primaries; + chunk[8 + 1] = (unsigned char)info->cicp_transfer_function; + chunk[8 + 2] = (unsigned char)info->cicp_matrix_coefficients; + chunk[8 + 3] = (unsigned char)info->cicp_video_full_range_flag; + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_mDCV(ucvector* out, const LodePNGInfo* info) { + unsigned char* chunk; + /* Allow up to 65535 since they are 16-bit ints. */ + if(info->mdcv_red_x > 65535) return 118; + if(info->mdcv_red_y > 65535) return 118; + if(info->mdcv_green_x > 65535) return 118; + if(info->mdcv_green_y > 65535) return 118; + if(info->mdcv_blue_x > 65535) return 118; + if(info->mdcv_blue_y > 65535) return 118; + if(info->mdcv_white_x > 65535) return 118; + if(info->mdcv_white_y > 65535) return 118; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 24, "mDCV")); + chunk[8 + 0] = (unsigned char)((info->mdcv_red_x) >> 8u); + chunk[8 + 1] = (unsigned char)(info->mdcv_red_x); + chunk[8 + 2] = (unsigned char)((info->mdcv_red_y) >> 8u); + chunk[8 + 3] = (unsigned char)(info->mdcv_red_y); + chunk[8 + 4] = (unsigned char)((info->mdcv_green_x) >> 8u); + chunk[8 + 5] = (unsigned char)(info->mdcv_green_x); + chunk[8 + 6] = (unsigned char)((info->mdcv_green_y) >> 8u); + chunk[8 + 7] = (unsigned char)(info->mdcv_green_y); + chunk[8 + 8] = (unsigned char)((info->mdcv_blue_x) >> 8u); + chunk[8 + 9] = (unsigned char)(info->mdcv_blue_x); + chunk[8 + 10] = (unsigned char)((info->mdcv_blue_y) >> 8u); + chunk[8 + 11] = (unsigned char)(info->mdcv_blue_y); + chunk[8 + 12] = (unsigned char)((info->mdcv_white_x) >> 8u); + chunk[8 + 13] = (unsigned char)(info->mdcv_white_x); + chunk[8 + 14] = (unsigned char)((info->mdcv_white_y) >> 8u); + chunk[8 + 15] = (unsigned char)(info->mdcv_white_y); + lodepng_set32bitInt(chunk + 8 + 16, info->mdcv_max_luminance); + lodepng_set32bitInt(chunk + 8 + 20, info->mdcv_min_luminance); + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_cLLI(ucvector* out, const LodePNGInfo* info) { + unsigned char* chunk; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 8, "cLLI")); + lodepng_set32bitInt(chunk + 8 + 0, info->clli_max_cll); + lodepng_set32bitInt(chunk + 8 + 4, info->clli_max_fall); + lodepng_chunk_generate_crc(chunk); + return 0; +} + +static unsigned addChunk_eXIf(ucvector* out, const LodePNGInfo* info) { + return lodepng_chunk_createv(out, info->exif_size, "eXIf", info->exif); +} + +static unsigned addChunk_sBIT(ucvector* out, const LodePNGInfo* info) { + unsigned bitdepth = (info->color.colortype == LCT_PALETTE) ? 8 : info->color.bitdepth; + unsigned char* chunk = 0; + if(info->color.colortype == LCT_GREY) { + if(info->sbit_r == 0 || info->sbit_r > bitdepth) return 115; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 1, "sBIT")); + chunk[8] = info->sbit_r; + } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_PALETTE) { + if(info->sbit_r == 0 || info->sbit_g == 0 || info->sbit_b == 0) return 115; + if(info->sbit_r > bitdepth || info->sbit_g > bitdepth || info->sbit_b > bitdepth) return 115; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 3, "sBIT")); + chunk[8] = info->sbit_r; + chunk[9] = info->sbit_g; + chunk[10] = info->sbit_b; + } else if(info->color.colortype == LCT_GREY_ALPHA) { + if(info->sbit_r == 0 || info->sbit_a == 0) return 115; + if(info->sbit_r > bitdepth || info->sbit_a > bitdepth) return 115; + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "sBIT")); + chunk[8] = info->sbit_r; + chunk[9] = info->sbit_a; + } else if(info->color.colortype == LCT_RGBA) { + if(info->sbit_r == 0 || info->sbit_g == 0 || info->sbit_b == 0 || info->sbit_a == 0 || + info->sbit_r > bitdepth || info->sbit_g > bitdepth || + info->sbit_b > bitdepth || info->sbit_a > bitdepth) { + return 115; + } + CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "sBIT")); + chunk[8] = info->sbit_r; + chunk[9] = info->sbit_g; + chunk[10] = info->sbit_b; + chunk[11] = info->sbit_a; + } + if(chunk) lodepng_chunk_generate_crc(chunk); + return 0; +} + +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline, + size_t length, size_t bytewidth, unsigned char filterType) { + size_t i; + switch(filterType) { + case 0: /*None*/ + for(i = 0; i != length; ++i) out[i] = scanline[i]; + break; + case 1: /*Sub*/ + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth]; + break; + case 2: /*Up*/ + if(prevline) { + for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i]; + } else { + for(i = 0; i != length; ++i) out[i] = scanline[i]; + } + break; + case 3: /*Average*/ + if(prevline) { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1); + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1); + } else { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1); + } + break; + case 4: /*Paeth*/ + if(prevline) { + /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/ + for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]); + for(i = bytewidth; i < length; ++i) { + out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth])); + } + } else { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/ + for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]); + } + break; + default: return; /*invalid filter type given*/ + } +} + +/* integer binary logarithm, max return value is 31 */ +static size_t ilog2(size_t i) { + size_t result = 0; + if(i >= 65536) { result += 16; i >>= 16; } + if(i >= 256) { result += 8; i >>= 8; } + if(i >= 16) { result += 4; i >>= 4; } + if(i >= 4) { result += 2; i >>= 2; } + if(i >= 2) { result += 1; /*i >>= 1;*/ } + return result; +} + +/* integer approximation for i * log2(i), helper function for LFS_ENTROPY */ +static size_t ilog2i(size_t i) { + size_t l; + if(i == 0) return 0; + l = ilog2(i); + /* approximate i*log2(i): l is integer logarithm, ((i - (1u << l)) << 1u) + linearly approximates the missing fractional part multiplied by i */ + return i * l + ((i - (((size_t)1) << l)) << 1u); +} + +static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, + const LodePNGColorMode* color, const LodePNGEncoderSettings* settings) { + /* + For PNG filter method 0 + out must be a buffer with as size: h + (w * h * bpp + 7u) / 8u, because there are + the scanlines with 1 extra byte per scanline + */ + + unsigned bpp = lodepng_get_bpp(color); + /*the width of a scanline in bytes, not including the filter type*/ + size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u; + + /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ + size_t bytewidth = (bpp + 7u) / 8u; + const unsigned char* prevline = 0; + unsigned x, y; + unsigned error = 0; + LodePNGFilterStrategy strategy = settings->filter_strategy; + + if(settings->filter_palette_zero && (color->colortype == LCT_PALETTE || color->bitdepth < 8)) { + /*if the filter_palette_zero setting is enabled, override the filter strategy with + zero for all scanlines for palette and less-than-8-bitdepth images*/ + strategy = LFS_ZERO; + } + + if(bpp == 0) return 31; /*error: invalid color type*/ + + if(strategy >= LFS_ZERO && strategy <= LFS_FOUR) { + unsigned char type = (unsigned char)strategy; + for(y = 0; y != h; ++y) { + size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + size_t inindex = linebytes * y; + out[outindex] = type; /*filter type byte*/ + filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); + prevline = &in[inindex]; + } + } else if(strategy == LFS_MINSUM) { + /*adaptive filtering: independently for each row, try all five filter types and select the one that produces the + smallest sum of absolute values per row.*/ + unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t smallest = 0; + unsigned char type, bestType = 0; + + for(type = 0; type != 5; ++type) { + attempt[type] = (unsigned char*)lodepng_malloc(linebytes); + if(!attempt[type]) error = 83; /*alloc fail*/ + } + + if(!error) { + for(y = 0; y != h; ++y) { + /*try the 5 filter types*/ + for(type = 0; type != 5; ++type) { + size_t sum = 0; + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + + /*calculate the sum of the result*/ + if(type == 0) { + for(x = 0; x != linebytes; ++x) sum += (unsigned char)(attempt[type][x]); + } else { + for(x = 0; x != linebytes; ++x) { + /*For differences, each byte should be treated as signed, values above 127 are negative + (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there. + This means filtertype 0 is almost never chosen, but that is justified.*/ + unsigned char s = attempt[type][x]; + sum += s < 128 ? s : (255U - s); + } + } + + /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || sum < smallest) { + bestType = type; + smallest = sum; + } + } + + prevline = &in[y * linebytes]; + + /*now fill the out values*/ + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } + } + + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } else if(strategy == LFS_ENTROPY) { + unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t bestSum = 0; + unsigned type, bestType = 0; + unsigned count[256]; + + for(type = 0; type != 5; ++type) { + attempt[type] = (unsigned char*)lodepng_malloc(linebytes); + if(!attempt[type]) error = 83; /*alloc fail*/ + } + + if(!error) { + for(y = 0; y != h; ++y) { + /*try the 5 filter types*/ + for(type = 0; type != 5; ++type) { + size_t sum = 0; + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + lodepng_memset(count, 0, 256 * sizeof(*count)); + for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]]; + ++count[type]; /*the filter type itself is part of the scanline*/ + for(x = 0; x != 256; ++x) { + sum += ilog2i(count[x]); + } + /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || sum > bestSum) { + bestType = type; + bestSum = sum; + } + } + + prevline = &in[y * linebytes]; + + /*now fill the out values*/ + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } + } + + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } else if(strategy == LFS_PREDEFINED) { + for(y = 0; y != h; ++y) { + size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + size_t inindex = linebytes * y; + unsigned char type = settings->predefined_filters[y]; + out[outindex] = type; /*filter type byte*/ + filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); + prevline = &in[inindex]; + } + } else if(strategy == LFS_BRUTE_FORCE) { + /*brute force filter chooser. + deflate the scanline after every filter attempt to see which one deflates best. + This is very slow and gives only slightly smaller, sometimes even larger, result*/ + size_t size[5]; + unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t smallest = 0; + unsigned type = 0, bestType = 0; + unsigned char* dummy; + LodePNGCompressSettings zlibsettings; + lodepng_memcpy(&zlibsettings, &settings->zlibsettings, sizeof(LodePNGCompressSettings)); + /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose, + to simulate the true case where the tree is the same for the whole image. Sometimes it gives + better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare + cases better compression. It does make this a bit less slow, so it's worth doing this.*/ + zlibsettings.btype = 1; + /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG + images only, so disable it*/ + zlibsettings.custom_zlib = 0; + zlibsettings.custom_deflate = 0; + for(type = 0; type != 5; ++type) { + attempt[type] = (unsigned char*)lodepng_malloc(linebytes); + if(!attempt[type]) error = 83; /*alloc fail*/ + } + if(!error) { + for(y = 0; y != h; ++y) /*try the 5 filter types*/ { + for(type = 0; type != 5; ++type) { + unsigned testsize = (unsigned)linebytes; + /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ + + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + size[type] = 0; + dummy = 0; + zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings); + lodepng_free(dummy); + /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || size[type] < smallest) { + bestType = type; + smallest = size[type]; + } + } + prevline = &in[y * linebytes]; + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } + } + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } + else return 88; /* unknown filter strategy */ + + return error; +} + +static void addPaddingBits(unsigned char* out, const unsigned char* in, + size_t olinebits, size_t ilinebits, unsigned h) { + /*The opposite of the removePaddingBits function + olinebits must be >= ilinebits*/ + unsigned y; + size_t diff = olinebits - ilinebits; + size_t obp = 0, ibp = 0; /*bit pointers*/ + for(y = 0; y != h; ++y) { + size_t x; + for(x = 0; x < ilinebits; ++x) { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + /*obp += diff; --> no, fill in some value in the padding bits too, to avoid + "Use of uninitialised value of size ###" warning from valgrind*/ + for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0); + } +} + +/* +in: non-interlaced image with size w*h +out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with + no padding bits between scanlines, but between reduced images so that each + reduced image starts at a byte. +bpp: bits per pixel +there are no padding bits, not between scanlines, not between reduced images +in has the following size in bits: w * h * bpp. +out is possibly bigger due to padding bits between reduced images +NOTE: comments about padding bits are only relevant if bpp < 8 +*/ +static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + if(bpp >= 8) { + for(i = 0; i != 7; ++i) { + unsigned x, y, b; + size_t bytewidth = bpp / 8u; + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) { + size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; + size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth; + for(b = 0; b < bytewidth; ++b) { + out[pixeloutstart + b] = in[pixelinstart + b]; + } + } + } + } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ { + for(i = 0; i != 7; ++i) { + unsigned x, y, b; + unsigned ilinebits = bpp * passw[i]; + unsigned olinebits = bpp * w; + size_t obp, ibp; /*bit pointers (for out and in buffer)*/ + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) { + ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; + obp = (8 * passstart[i]) + (y * ilinebits + x * bpp); + for(b = 0; b < bpp; ++b) { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + } + } + } +} + +/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image. +return value is error**/ +static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in, + unsigned w, unsigned h, + const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) { + /* + This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps: + *) if no Adam7: 1) add padding bits (= possible extra bits per scanline if bpp < 8) 2) filter + *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter + */ + size_t bpp = lodepng_get_bpp(&info_png->color); + unsigned error = 0; + if(info_png->interlace_method == 0) { + /*image size plus an extra byte per scanline + possible padding bits*/ + *outsize = (size_t)h + ((size_t)h * (((size_t)w * bpp + 7u) / 8u)); + *out = (unsigned char*)lodepng_malloc(*outsize); + if(!(*out) && (*outsize)) error = 83; /*alloc fail*/ + + if(!error) { + /*non multiple of 8 bits per scanline, padding bits needed per scanline*/ + if(bpp < 8 && (size_t)w * bpp != (((size_t)w * bpp + 7u) / 8u) * 8u) { + unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7u) / 8u)); + if(!padded) error = 83; /*alloc fail*/ + if(!error) { + addPaddingBits(padded, in, (((size_t)w * bpp + 7u) / 8u) * 8u, (size_t)w * bpp, h); + error = filter(*out, padded, w, h, &info_png->color, settings); + } + lodepng_free(padded); + } else { + /*we can immediately filter into the out buffer, no other steps needed*/ + error = filter(*out, in, w, h, &info_png->color, settings); + } + } + } else /*interlace_method is 1 (Adam7)*/ { + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned char* adam7; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, (unsigned)bpp); + + *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/ + *out = (unsigned char*)lodepng_malloc(*outsize); + if(!(*out)) error = 83; /*alloc fail*/ + + adam7 = (unsigned char*)lodepng_malloc(passstart[7]); + if(!adam7 && passstart[7]) error = 83; /*alloc fail*/ + + if(!error) { + unsigned i; + + Adam7_interlace(adam7, in, w, h, (unsigned)bpp); + for(i = 0; i != 7; ++i) { + if(bpp < 8) { + unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]); + if(!padded) ERROR_BREAK(83); /*alloc fail*/ + addPaddingBits(padded, &adam7[passstart[i]], + (((size_t)passw[i] * bpp + 7u) / 8u) * 8u, (size_t)passw[i] * bpp, passh[i]); + error = filter(&(*out)[filter_passstart[i]], padded, + passw[i], passh[i], &info_png->color, settings); + lodepng_free(padded); + } else { + error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]], + passw[i], passh[i], &info_png->color, settings); + } + + if(error) break; + } + } + + lodepng_free(adam7); + } + + return error; +} + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) { + unsigned char* inchunk = data; + while((size_t)(inchunk - data) < datasize) { + CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk)); + out->allocsize = out->size; /*fix the allocsize again*/ + inchunk = lodepng_chunk_next(inchunk, data + datasize); + } + return 0; +} + +static unsigned isGrayICCProfile(const unsigned char* profile, unsigned size) { + /* + It is a gray profile if bytes 16-19 are "GRAY", rgb profile if bytes 16-19 + are "RGB ". We do not perform any full parsing of the ICC profile here, other + than check those 4 bytes to grayscale profile. Other than that, validity of + the profile is not checked. This is needed only because the PNG specification + requires using a non-gray color model if there is an ICC profile with "RGB " + (sadly limiting compression opportunities if the input data is grayscale RGB + data), and requires using a gray color model if it is "GRAY". + */ + if(size < 20) return 0; + return profile[16] == 'G' && profile[17] == 'R' && profile[18] == 'A' && profile[19] == 'Y'; +} + +static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) { + /* See comment in isGrayICCProfile*/ + if(size < 20) return 0; + return profile[16] == 'R' && profile[17] == 'G' && profile[18] == 'B' && profile[19] == ' '; +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +unsigned lodepng_encode(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGState* state) { + unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/ + size_t datasize = 0; + ucvector outv = ucvector_init(NULL, 0); + LodePNGInfo info; + const LodePNGInfo* info_png = &state->info_png; + LodePNGColorMode auto_color; + + lodepng_info_init(&info); + lodepng_color_mode_init(&auto_color); + + /*provide some proper output values if error will happen*/ + *out = 0; + *outsize = 0; + state->error = 0; + + /*check input values validity*/ + if((info_png->color.colortype == LCT_PALETTE || state->encoder.force_palette) + && (info_png->color.palettesize == 0 || info_png->color.palettesize > 256)) { + /*this error is returned even if auto_convert is enabled and thus encoder could + generate the palette by itself: while allowing this could be possible in theory, + it may complicate the code or edge cases, and always requiring to give a palette + when setting this color type is a simpler contract*/ + state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/ + goto cleanup; + } + if(state->encoder.zlibsettings.btype > 2) { + state->error = 61; /*error: invalid btype*/ + goto cleanup; + } + if(info_png->interlace_method > 1) { + state->error = 71; /*error: invalid interlace mode*/ + goto cleanup; + } + state->error = checkColorValidity(info_png->color.colortype, info_png->color.bitdepth); + if(state->error) goto cleanup; /*error: invalid color type given*/ + state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth); + if(state->error) goto cleanup; /*error: invalid color type given*/ + + /* color convert and compute scanline filter types */ + lodepng_info_copy(&info, &state->info_png); + if(state->encoder.auto_convert) { + LodePNGColorStats stats; + unsigned allow_convert = 1; + lodepng_color_stats_init(&stats); +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + if(info_png->iccp_defined && + isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) { + /*the PNG specification does not allow to use palette with a GRAY ICC profile, even + if the palette has only gray colors, so disallow it.*/ + stats.allow_palette = 0; + } + if(info_png->iccp_defined && + isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) { + /*the PNG specification does not allow to use grayscale color with RGB ICC profile, so disallow gray.*/ + stats.allow_greyscale = 0; + } +#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */ + state->error = lodepng_compute_color_stats(&stats, image, w, h, &state->info_raw); + if(state->error) goto cleanup; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + if(info_png->background_defined) { + /*the background chunk's color must be taken into account as well*/ + unsigned r = 0, g = 0, b = 0; + LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGB, 16); + lodepng_convert_rgb(&r, &g, &b, + info_png->background_r, info_png->background_g, info_png->background_b, &mode16, &info_png->color); + state->error = lodepng_color_stats_add(&stats, r, g, b, 65535); + if(state->error) goto cleanup; + } +#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */ + state->error = auto_choose_color(&auto_color, &state->info_raw, &stats); + if(state->error) goto cleanup; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + if(info_png->sbit_defined) { + /*if sbit is defined, due to strict requirements of which sbit values can be present for which color modes, + auto_convert can't be done in many cases. However, do support a few cases here. + TODO: more conversions may be possible, and it may also be possible to get a more appropriate color type out of + auto_choose_color if knowledge about sbit is used beforehand + */ + unsigned sbit_max = LODEPNG_MAX(LODEPNG_MAX(LODEPNG_MAX(info_png->sbit_r, info_png->sbit_g), + info_png->sbit_b), info_png->sbit_a); + unsigned equal = (!info_png->sbit_g || info_png->sbit_g == info_png->sbit_r) + && (!info_png->sbit_b || info_png->sbit_b == info_png->sbit_r) + && (!info_png->sbit_a || info_png->sbit_a == info_png->sbit_r); + allow_convert = 0; + if(info.color.colortype == LCT_PALETTE && + auto_color.colortype == LCT_PALETTE) { + /* input and output are palette, and in this case it may happen that palette data is + expected to be copied from info_raw into the info_png */ + allow_convert = 1; + } + /*going from 8-bit RGB to palette (or 16-bit as long as sbit_max <= 8) is possible + since both are 8-bit RGB for sBIT's purposes*/ + if(info.color.colortype == LCT_RGB && + auto_color.colortype == LCT_PALETTE && sbit_max <= 8) { + allow_convert = 1; + } + /*going from 8-bit RGBA to palette is also ok but only if sbit_a is exactly 8*/ + if(info.color.colortype == LCT_RGBA && auto_color.colortype == LCT_PALETTE && + info_png->sbit_a == 8 && sbit_max <= 8) { + allow_convert = 1; + } + /*going from 16-bit RGB(A) to 8-bit RGB(A) is ok if all sbit values are <= 8*/ + if((info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA) && info.color.bitdepth == 16 && + auto_color.colortype == info.color.colortype && auto_color.bitdepth == 8 && + sbit_max <= 8) { + allow_convert = 1; + } + /*going to less channels is ok if all bit values are equal (all possible values in sbit, + as well as the chosen bitdepth of the result). Due to how auto_convert works, + we already know that auto_color.colortype has less than or equal amount of channels than + info.colortype. Palette is not used here. This conversion is not allowed if + info_png->sbit_r < auto_color.bitdepth, because specifically for alpha, non-presence of + an sbit value heavily implies that alpha's bit depth is equal to the PNG bit depth (rather + than the bit depths set in the r, g and b sbit values, by how the PNG specification describes + handling tRNS chunk case with sBIT), so be conservative here about ignoring user input.*/ + if(info.color.colortype != LCT_PALETTE && auto_color.colortype != LCT_PALETTE && + equal && info_png->sbit_r == auto_color.bitdepth) { + allow_convert = 1; + } + } +#endif + if(state->encoder.force_palette) { + if(info.color.colortype != LCT_GREY && info.color.colortype != LCT_GREY_ALPHA && + (auto_color.colortype == LCT_GREY || auto_color.colortype == LCT_GREY_ALPHA)) { + /*user speficially forced a PLTE palette, so cannot convert to grayscale types because + the PNG specification only allows writing a suggested palette in PLTE for truecolor types*/ + allow_convert = 0; + } + } + if(allow_convert) { + lodepng_color_mode_copy(&info.color, &auto_color); +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*also convert the background chunk*/ + if(info_png->background_defined) { + if(lodepng_convert_rgb(&info.background_r, &info.background_g, &info.background_b, + info_png->background_r, info_png->background_g, info_png->background_b, &info.color, &info_png->color)) { + state->error = 104; + goto cleanup; + } + } +#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */ + } + } +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + if(info_png->iccp_defined) { + unsigned gray_icc = isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size); + unsigned rgb_icc = isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size); + unsigned gray_png = info.color.colortype == LCT_GREY || info.color.colortype == LCT_GREY_ALPHA; + if(!gray_icc && !rgb_icc) { + state->error = 100; /* Disallowed profile color type for PNG */ + goto cleanup; + } + if(gray_icc != gray_png) { + /*Not allowed to use RGB/RGBA/palette with GRAY ICC profile or vice versa, + or in case of auto_convert, it wasn't possible to find appropriate model*/ + state->error = state->encoder.auto_convert ? 102 : 101; + goto cleanup; + } + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) { + unsigned char* converted; + size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7u) / 8u; + + converted = (unsigned char*)lodepng_malloc(size); + if(!converted && size) state->error = 83; /*alloc fail*/ + if(!state->error) { + state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); + } + if(!state->error) { + state->error = preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); + } + lodepng_free(converted); + if(state->error) goto cleanup; + } else { + state->error = preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); + if(state->error) goto cleanup; + } + + /* output all PNG chunks */ { +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + size_t i; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*write signature and chunks*/ + state->error = writeSignature(&outv); + if(state->error) goto cleanup; + /*IHDR*/ + state->error = addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method); + if(state->error) goto cleanup; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*unknown chunks between IHDR and PLTE*/ + if(info.unknown_chunks_data[0]) { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]); + if(state->error) goto cleanup; + } + /*color profile chunks must come before PLTE */ + if(info.cicp_defined) { + state->error = addChunk_cICP(&outv, &info); + if(state->error) goto cleanup; + } + if(info.mdcv_defined) { + state->error = addChunk_mDCV(&outv, &info); + if(state->error) goto cleanup; + } + if(info.clli_defined) { + state->error = addChunk_cLLI(&outv, &info); + if(state->error) goto cleanup; + } + if(info.iccp_defined) { + state->error = addChunk_iCCP(&outv, &info, &state->encoder.zlibsettings); + if(state->error) goto cleanup; + } + if(info.srgb_defined) { + state->error = addChunk_sRGB(&outv, &info); + if(state->error) goto cleanup; + } + if(info.gama_defined) { + state->error = addChunk_gAMA(&outv, &info); + if(state->error) goto cleanup; + } + if(info.chrm_defined) { + state->error = addChunk_cHRM(&outv, &info); + if(state->error) goto cleanup; + } + if(info_png->sbit_defined) { + state->error = addChunk_sBIT(&outv, &info); + if(state->error) goto cleanup; + } + if(info.exif_defined) { + state->error = addChunk_eXIf(&outv, &info); + if(state->error) goto cleanup; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*PLTE*/ + if(info.color.colortype == LCT_PALETTE) { + state->error = addChunk_PLTE(&outv, &info.color); + if(state->error) goto cleanup; + } + if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) { + /*force_palette means: write suggested palette for truecolor in PLTE chunk*/ + state->error = addChunk_PLTE(&outv, &info.color); + if(state->error) goto cleanup; + } + /*tRNS (this will only add if when necessary) */ + state->error = addChunk_tRNS(&outv, &info.color); + if(state->error) goto cleanup; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*bKGD (must come between PLTE and the IDAt chunks*/ + if(info.background_defined) { + state->error = addChunk_bKGD(&outv, &info); + if(state->error) goto cleanup; + } + /*pHYs (must come before the IDAT chunks)*/ + if(info.phys_defined) { + state->error = addChunk_pHYs(&outv, &info); + if(state->error) goto cleanup; + } + + /*unknown chunks between PLTE and IDAT*/ + if(info.unknown_chunks_data[1]) { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]); + if(state->error) goto cleanup; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*IDAT (multiple IDAT chunks must be consecutive)*/ + state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings); + if(state->error) goto cleanup; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*tIME*/ + if(info.time_defined) { + state->error = addChunk_tIME(&outv, &info.time); + if(state->error) goto cleanup; + } + /*tEXt and/or zTXt*/ + for(i = 0; i != info.text_num; ++i) { + if(lodepng_strlen(info.text_keys[i]) > 79) { + state->error = 66; /*text chunk too large*/ + goto cleanup; + } + if(lodepng_strlen(info.text_keys[i]) < 1) { + state->error = 67; /*text chunk too small*/ + goto cleanup; + } + if(state->encoder.text_compression) { + state->error = addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings); + if(state->error) goto cleanup; + } else { + state->error = addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]); + if(state->error) goto cleanup; + } + } + /*LodePNG version id in text chunk*/ + if(state->encoder.add_id) { + unsigned already_added_id_text = 0; + for(i = 0; i != info.text_num; ++i) { + const char* k = info.text_keys[i]; + /* Could use strcmp, but we're not calling or reimplementing this C library function for this use only */ + if(k[0] == 'L' && k[1] == 'o' && k[2] == 'd' && k[3] == 'e' && + k[4] == 'P' && k[5] == 'N' && k[6] == 'G' && k[7] == '\0') { + already_added_id_text = 1; + break; + } + } + if(already_added_id_text == 0) { + state->error = addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/ + if(state->error) goto cleanup; + } + } + /*iTXt*/ + for(i = 0; i != info.itext_num; ++i) { + if(lodepng_strlen(info.itext_keys[i]) > 79) { + state->error = 66; /*text chunk too large*/ + goto cleanup; + } + if(lodepng_strlen(info.itext_keys[i]) < 1) { + state->error = 67; /*text chunk too small*/ + goto cleanup; + } + state->error = addChunk_iTXt( + &outv, state->encoder.text_compression, + info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i], + &state->encoder.zlibsettings); + if(state->error) goto cleanup; + } + + /*unknown chunks between IDAT and IEND*/ + if(info.unknown_chunks_data[2]) { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]); + if(state->error) goto cleanup; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + state->error = addChunk_IEND(&outv); + if(state->error) goto cleanup; + } + +cleanup: + lodepng_info_cleanup(&info); + lodepng_free(data); + lodepng_color_mode_cleanup(&auto_color); + + /*instead of cleaning the vector up, give it to the output*/ + *out = outv.data; + *outsize = outv.size; + + return state->error; +} + +unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image, + unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { + unsigned error; + LodePNGState state; + lodepng_state_init(&state); + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + state.info_png.color.colortype = colortype; + state.info_png.color.bitdepth = bitdepth; + lodepng_encode(out, outsize, image, w, h, &state); + error = state.error; + lodepng_state_cleanup(&state); + return error; +} + +unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) { + return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8); +} + +unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) { + return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) { + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth); + if(!error) error = lodepng_save_file(buffer, buffersize, filename); + lodepng_free(buffer); + return error; +} + +unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) { + return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8); +} + +unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) { + return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8); +} +#endif /*LODEPNG_COMPILE_DISK*/ + +void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) { + lodepng_compress_settings_init(&settings->zlibsettings); + settings->filter_palette_zero = 1; + settings->filter_strategy = LFS_MINSUM; + settings->auto_convert = 1; + settings->force_palette = 0; + settings->predefined_filters = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + settings->add_id = 0; + settings->text_compression = 1; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ERROR_TEXT +/* +This returns the description of a numerical error code in English. This is also +the documentation of all the error codes. +*/ +const char* lodepng_error_text(unsigned code) { + switch(code) { + case 0: return "no error, everything went ok"; + case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/ + case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/ + case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/ + case 13: return "problem while processing dynamic deflate block"; + case 14: return "problem while processing dynamic deflate block"; + case 15: return "problem while processing dynamic deflate block"; + /*this error could happen if there are only 0 or 1 symbols present in the huffman code:*/ + case 16: return "invalid code while processing dynamic deflate block"; + case 17: return "end of out buffer memory reached while inflating"; + case 18: return "invalid distance code while inflating"; + case 19: return "end of out buffer memory reached while inflating"; + case 20: return "invalid deflate block BTYPE encountered while decoding"; + case 21: return "NLEN is not ones complement of LEN in a deflate block"; + + /*end of out buffer memory reached while inflating: + This can happen if the inflated deflate data is longer than the amount of bytes required to fill up + all the pixels of the image, given the color depth and image dimensions. Something that doesn't + happen in a normal, well encoded, PNG image.*/ + case 22: return "end of out buffer memory reached while inflating"; + case 23: return "end of in buffer memory reached while inflating"; + case 24: return "invalid FCHECK in zlib header"; + case 25: return "invalid compression method in zlib header"; + case 26: return "FDICT encountered in zlib header while it's not used for PNG"; + case 27: return "PNG file is smaller than a PNG header"; + /*Checks the magic file header, the first 8 bytes of the PNG file*/ + case 28: return "incorrect PNG signature, it's no PNG or corrupted"; + case 29: return "first chunk is not the header chunk"; + case 30: return "chunk length too large, chunk broken off at end of file"; + case 31: return "illegal PNG color type or bpp"; + case 32: return "illegal PNG compression method"; + case 33: return "illegal PNG filter method"; + case 34: return "illegal PNG interlace method"; + case 35: return "chunk length of a chunk is too large or the chunk too small"; + case 36: return "illegal PNG filter type encountered"; + case 37: return "illegal bit depth for this color type given"; + case 38: return "the palette is too small or too big"; /*0, or more than 256 colors*/ + case 39: return "tRNS chunk before PLTE or has more entries than palette size"; + case 40: return "tRNS chunk has wrong size for grayscale image"; + case 41: return "tRNS chunk has wrong size for RGB image"; + case 42: return "tRNS chunk appeared while it was not allowed for this color type"; + case 43: return "bKGD chunk has wrong size for palette image"; + case 44: return "bKGD chunk has wrong size for grayscale image"; + case 45: return "bKGD chunk has wrong size for RGB image"; + case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?"; + case 49: return "jumped past memory while generating dynamic huffman tree"; + case 50: return "jumped past memory while generating dynamic huffman tree"; + case 51: return "jumped past memory while inflating huffman block"; + case 52: return "jumped past memory while inflating"; + case 53: return "size of zlib data too small"; + case 54: return "repeat symbol in tree while there was no value symbol yet"; + /*jumped past tree while generating huffman tree, this could be when the + tree will have more leaves than symbols after generating it out of the + given lengths. They call this an oversubscribed dynamic bit lengths tree in zlib.*/ + case 55: return "jumped past tree while generating huffman tree"; + case 56: return "given output image colortype or bitdepth not supported for color conversion"; + case 57: return "invalid CRC encountered (checking CRC can be disabled)"; + case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)"; + case 59: return "requested color conversion not supported"; + case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)"; + case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)"; + /*LodePNG leaves the choice of RGB to grayscale conversion formula to the user.*/ + case 62: return "conversion from color to grayscale not supported"; + /*(2^31-1)*/ + case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; + /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/ + case 64: return "the length of the END symbol 256 in the Huffman tree is 0"; + case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes"; + case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte"; + case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors"; + case 69: return "unknown chunk type with 'critical' flag encountered by the decoder"; + case 71: return "invalid interlace mode given to encoder (must be 0 or 1)"; + case 72: return "while decoding, invalid compression method encountering in zTXt or iTXt chunk (it must be 0)"; + case 73: return "invalid tIME chunk size"; + case 74: return "invalid pHYs chunk size"; + /*length could be wrong, or data chopped off*/ + case 75: return "no null termination char found while decoding text chunk"; + case 76: return "iTXt chunk too short to contain required bytes"; + case 77: return "integer overflow in buffer size"; + case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/ + case 79: return "failed to open file for writing"; + case 80: return "tried creating a tree of 0 symbols"; + case 81: return "lazy matching at pos 0 is impossible"; + case 82: return "color conversion to palette requested while a color isn't in palette, or index out of bounds"; + case 83: return "memory allocation failed"; + case 84: return "given image too small to contain all pixels to be encoded"; + case 86: return "impossible offset in lz77 encoding (internal bug)"; + case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined"; + case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy"; + case 89: return "text chunk keyword too short or long: must have size 1-79"; + /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/ + case 90: return "windowsize must be a power of two"; + case 91: return "invalid decompressed idat size"; + case 92: return "integer overflow due to too many pixels"; + case 93: return "zero width or height is invalid"; + case 94: return "header chunk must have a size of 13 bytes"; + case 95: return "integer overflow with combined idat chunk size"; + case 96: return "invalid gAMA chunk size"; + case 97: return "invalid cHRM chunk size"; + case 98: return "invalid sRGB chunk size"; + case 99: return "invalid sRGB rendering intent"; + case 100: return "invalid ICC profile color type, the PNG specification only allows RGB or GRAY"; + case 101: return "PNG specification does not allow RGB ICC profile on gray color types and vice versa"; + case 102: return "not allowed to set grayscale ICC profile with colored pixels by PNG specification"; + case 103: return "invalid palette index in bKGD chunk. Maybe it came before PLTE chunk?"; + case 104: return "invalid bKGD color while encoding (e.g. palette index out of range)"; + case 105: return "integer overflow of bitsize"; + case 106: return "PNG file must have PLTE chunk if color type is palette"; + case 107: return "color convert from palette mode requested without setting the palette data in it"; + case 108: return "tried to add more than 256 values to a palette"; + /*this limit can be configured in LodePNGDecompressSettings*/ + case 109: return "tried to decompress zlib or deflate data larger than desired max_output_size"; + case 110: return "custom zlib or inflate decompression failed"; + case 111: return "custom zlib or deflate compression failed"; + /*max text size limit can be configured in LodePNGDecoderSettings. This error prevents + unreasonable memory consumption when decoding due to impossibly large text sizes.*/ + case 112: return "compressed text unreasonably large"; + /*max ICC size limit can be configured in LodePNGDecoderSettings. This error prevents + unreasonable memory consumption when decoding due to impossibly large ICC profile*/ + case 113: return "ICC profile unreasonably large"; + case 114: return "sBIT chunk has wrong size for the color type of the image"; + case 115: return "sBIT value out of range"; + case 116: return "cICP value out of range"; + case 117: return "invalid cICP chunk size"; + case 118: return "mDCV value out of range"; + case 119: return "invalid mDCV chunk size"; + case 120: return "invalid cLLI chunk size"; + case 121: return "invalid chunk type name: may only contain [a-zA-Z]"; + case 122: return "invalid chunk type name: third character must be uppercase"; + } + return "unknown error code"; +} +#endif /*LODEPNG_COMPILE_ERROR_TEXT*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // C++ Wrapper // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_CPP +namespace lodepng { + +#ifdef LODEPNG_COMPILE_DISK +/* Resizes the vector to the file size and reads the file into it. Returns error code.*/ +static unsigned load_file_(std::vector& buffer, FILE* file) { + long size = lodepng_filesize(file); + if(size < 0) return 78; + buffer.resize((size_t)size); + if(size == 0) return 0; /*ok*/ + if(fread(&buffer[0], 1, buffer.size(), file) != buffer.size()) return 78; + return 0; /*ok*/ +} + +unsigned load_file(std::vector& buffer, const std::string& filename) { + unsigned error; + FILE* file = fopen(filename.c_str(), "rb"); + if(!file) return 78; + error = load_file_(buffer, file); + fclose(file); + return error; +} + +/*write given buffer to the file, overwriting the file, it doesn't append to it.*/ +unsigned save_file(const std::vector& buffer, const std::string& filename) { + return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str()); +} +#endif /* LODEPNG_COMPILE_DISK */ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_DECODER +unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGDecompressSettings& settings) { + unsigned char* buffer = 0; + size_t buffersize = 0; + unsigned error = zlib_decompress(&buffer, &buffersize, 0, in, insize, &settings); + if(buffer) { + out.insert(out.end(), buffer, &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned decompress(std::vector& out, const std::vector& in, + const LodePNGDecompressSettings& settings) { + return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings); +} +#endif /* LODEPNG_COMPILE_DECODER */ + +#ifdef LODEPNG_COMPILE_ENCODER +unsigned compress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings& settings) { + unsigned char* buffer = 0; + size_t buffersize = 0; + unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings); + if(buffer) { + out.insert(out.end(), buffer, &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned compress(std::vector& out, const std::vector& in, + const LodePNGCompressSettings& settings) { + return compress(out, in.empty() ? 0 : &in[0], in.size(), settings); +} +#endif /* LODEPNG_COMPILE_ENCODER */ +#endif /* LODEPNG_COMPILE_ZLIB */ + + +#ifdef LODEPNG_COMPILE_PNG + +State::State() { + lodepng_state_init(this); +} + +State::State(const State& other) { + lodepng_state_init(this); + lodepng_state_copy(this, &other); +} + +State::~State() { + lodepng_state_cleanup(this); +} + +State& State::operator=(const State& other) { + lodepng_state_copy(this, &other); + return *this; +} + +#ifdef LODEPNG_COMPILE_DECODER + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, const unsigned char* in, + size_t insize, LodePNGColorType colortype, unsigned bitdepth) { + unsigned char* buffer = 0; + unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth); + if(buffer && !error) { + State state; + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); + out.insert(out.end(), buffer, &buffer[buffersize]); + } + lodepng_free(buffer); + return error; +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::vector& in, LodePNGColorType colortype, unsigned bitdepth) { + return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth); +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const unsigned char* in, size_t insize) { + unsigned char* buffer = NULL; + unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize); + if(buffer && !error) { + size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); + out.insert(out.end(), buffer, &buffer[buffersize]); + } + lodepng_free(buffer); + return error; +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const std::vector& in) { + return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size()); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::string& filename, + LodePNGColorType colortype, unsigned bitdepth) { + std::vector buffer; + /* safe output values in case error happens */ + w = h = 0; + unsigned error = load_file(buffer, filename); + if(error) return error; + return decode(out, w, h, buffer, colortype, bitdepth); +} +#endif /* LODEPNG_COMPILE_DECODER */ +#endif /* LODEPNG_COMPILE_DISK */ + +#ifdef LODEPNG_COMPILE_ENCODER +unsigned encode(std::vector& out, const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) { + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth); + if(buffer) { + out.insert(out.end(), buffer, &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) { + if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; + return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); +} + +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + State& state) { + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state); + if(buffer) { + out.insert(out.end(), buffer, &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + State& state) { + if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84; + return encode(out, in.empty() ? 0 : &in[0], w, h, state); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned encode(const std::string& filename, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) { + std::vector buffer; + unsigned error = encode(buffer, in, w, h, colortype, bitdepth); + if(!error) error = save_file(buffer, filename); + return error; +} + +unsigned encode(const std::string& filename, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) { + if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; + return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); +} +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_ENCODER */ +#endif /* LODEPNG_COMPILE_PNG */ +} /* namespace lodepng */ +#endif /*LODEPNG_COMPILE_CPP*/ diff --git a/components/pico8/femto8/src/lodepng/lodepng.h b/components/pico8/femto8/src/lodepng/lodepng.h new file mode 100644 index 00000000..ef474ead --- /dev/null +++ b/components/pico8/femto8/src/lodepng/lodepng.h @@ -0,0 +1,2178 @@ +/* +LodePNG version 20250506 + +Copyright (c) 2005-2025 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#ifndef LODEPNG_H +#define LODEPNG_H + +#include /*for size_t*/ + +extern const char* LODEPNG_VERSION_STRING; + +/* +The following #defines are used to create code sections. They can be disabled +to disable code sections, which can give faster compile time and smaller binary. +The "NO_COMPILE" defines are designed to be used to pass as defines to the +compiler command to disable them without modifying this header, e.g. +-DLODEPNG_NO_COMPILE_ZLIB for gcc or clang. +*/ +/*deflate & zlib. If disabled, you must specify alternative zlib functions in +the custom_zlib field of the compress and decompress settings*/ +#ifndef LODEPNG_NO_COMPILE_ZLIB +/*pass -DLODEPNG_NO_COMPILE_ZLIB to the compiler to disable this, or comment out LODEPNG_COMPILE_ZLIB below*/ +#define LODEPNG_COMPILE_ZLIB +#endif + +/*png encoder and png decoder*/ +#ifndef LODEPNG_NO_COMPILE_PNG +/*pass -DLODEPNG_NO_COMPILE_PNG to the compiler to disable this, or comment out LODEPNG_COMPILE_PNG below*/ +#define LODEPNG_COMPILE_PNG +#endif + +/*deflate&zlib decoder and png decoder*/ +#ifndef LODEPNG_NO_COMPILE_DECODER +/*pass -DLODEPNG_NO_COMPILE_DECODER to the compiler to disable this, or comment out LODEPNG_COMPILE_DECODER below*/ +#define LODEPNG_COMPILE_DECODER +#endif + +/*deflate&zlib encoder and png encoder*/ +#ifndef LODEPNG_NO_COMPILE_ENCODER +/*pass -DLODEPNG_NO_COMPILE_ENCODER to the compiler to disable this, or comment out LODEPNG_COMPILE_ENCODER below*/ +#define LODEPNG_COMPILE_ENCODER +#endif + +/*the optional built in harddisk file loading and saving functions*/ +#ifndef LODEPNG_NO_COMPILE_DISK +/*pass -DLODEPNG_NO_COMPILE_DISK to the compiler to disable this, or comment out LODEPNG_COMPILE_DISK below*/ +#define LODEPNG_COMPILE_DISK +#endif + +/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/ +#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS +/*pass -DLODEPNG_NO_COMPILE_ANCILLARY_CHUNKS to the compiler to disable this, +or comment out LODEPNG_COMPILE_ANCILLARY_CHUNKS below*/ +#define LODEPNG_COMPILE_ANCILLARY_CHUNKS +#endif + +/*ability to convert error numerical codes to English text string*/ +#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT +/*pass -DLODEPNG_NO_COMPILE_ERROR_TEXT to the compiler to disable this, +or comment out LODEPNG_COMPILE_ERROR_TEXT below*/ +#define LODEPNG_COMPILE_ERROR_TEXT +#endif + +/*Compile the default allocators (C's free, malloc and realloc). If you disable this, +you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your +source files with custom allocators.*/ +#ifndef LODEPNG_NO_COMPILE_ALLOCATORS +/*pass -DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler to disable the built-in ones, +or comment out LODEPNG_COMPILE_ALLOCATORS below*/ +#define LODEPNG_COMPILE_ALLOCATORS +#endif + +/*Disable built-in CRC function, in that case a custom implementation of +lodepng_crc32 must be defined externally so that it can be linked in. +The default built-in CRC code comes with 8KB of lookup tables, so for memory constrained environment you may want it +disabled and provide a much smaller implementation externally as said above. You can find such an example implementation +in a comment in the lodepng.c(pp) file in the 'else' case of the searchable LODEPNG_COMPILE_CRC section.*/ +#ifndef LODEPNG_NO_COMPILE_CRC +/*pass -DLODEPNG_NO_COMPILE_CRC to the compiler to disable the built-in one, +or comment out LODEPNG_COMPILE_CRC below*/ +#define LODEPNG_COMPILE_CRC +#endif + +/* Disable color conversion*/ +#ifndef LODEPNG_NO_COLOR_CONVERT +#define LODEPNG_COMPILE_COLOR_CONVERT +#endif + +/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/ +#ifdef __cplusplus +#ifndef LODEPNG_NO_COMPILE_CPP +/*pass -DLODEPNG_NO_COMPILE_CPP to the compiler to disable C++ (not needed if a C-only compiler), +or comment out LODEPNG_COMPILE_CPP below*/ +#define LODEPNG_COMPILE_CPP +#endif +#endif + +#ifdef LODEPNG_COMPILE_CPP +#include +#include +#endif /*LODEPNG_COMPILE_CPP*/ + +#ifdef LODEPNG_COMPILE_PNG +/*The PNG color types (also used for raw image).*/ +typedef enum LodePNGColorType { + LCT_GREY = 0, /*grayscale: 1,2,4,8,16 bit*/ + LCT_RGB = 2, /*RGB: 8,16 bit*/ + LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/ + LCT_GREY_ALPHA = 4, /*grayscale with alpha: 8,16 bit*/ + LCT_RGBA = 6, /*RGB with alpha: 8,16 bit*/ + /*LCT_MAX_OCTET_VALUE lets the compiler allow this enum to represent any invalid + byte value from 0 to 255 that could be present in an invalid PNG file header. Do + not use, compare with or set the name LCT_MAX_OCTET_VALUE, instead either use + the valid color type names above, or numeric values like 1 or 7 when checking for + particular disallowed color type byte values, or cast to integer to print it.*/ + LCT_MAX_OCTET_VALUE = 255 +} LodePNGColorType; + +#ifdef LODEPNG_COMPILE_DECODER +/* +Converts PNG data in memory to raw pixel data. +out: Output parameter. Pointer to buffer that will contain the raw pixel data. + After decoding, its size is w * h * (bytes per pixel) bytes larger than + initially. Bytes per pixel depends on colortype and bitdepth. + Must be freed after usage with free(*out). + Note: for 16-bit per channel colors, uses big endian format like PNG does. +w: Output parameter. Pointer to width of pixel data. +h: Output parameter. Pointer to height of pixel data. +in: Memory buffer with the PNG file. +insize: size of the in buffer. +colortype: the desired color type for the raw output image. See explanation on PNG color types. +bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types. +Return value: LodePNG error code (0 means no error). +*/ +unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/ +unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize); + +/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/ +unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize); + +#ifdef LODEPNG_COMPILE_DISK +/* +Load PNG from disk, from file with given name. +Same as the other decode functions, but instead takes a filename as input. + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and decode in-memory.*/ +unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image. + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and decode in-memory.*/ +unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename); + +/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image. + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and decode in-memory.*/ +unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename); +#endif /*LODEPNG_COMPILE_DISK*/ +#endif /*LODEPNG_COMPILE_DECODER*/ + + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Converts raw pixel data into a PNG image in memory. The colortype and bitdepth + of the output PNG image cannot be chosen, they are automatically determined + by the colortype, bitdepth and content of the input pixel data. + Note: for 16-bit per channel colors, needs big endian format like PNG does. +out: Output parameter. Pointer to buffer that will contain the PNG image data. + Must be freed after usage with free(*out). +outsize: Output parameter. Pointer to the size in bytes of the out buffer. +image: The raw pixel data to encode. The size of this buffer should be + w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth. +w: width of the raw pixel data in pixels. +h: height of the raw pixel data in pixels. +colortype: the color type of the raw input image. See explanation on PNG color types. +bitdepth: the bit depth of the raw input image. See explanation on PNG color types. +Return value: LodePNG error code (0 means no error). +*/ +unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/ +unsigned lodepng_encode32(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h); + +/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/ +unsigned lodepng_encode24(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h); + +#ifdef LODEPNG_COMPILE_DISK +/* +Converts raw pixel data into a PNG file on disk. +Same as the other encode functions, but instead takes a filename as output. + +NOTE: This overwrites existing files without warning! + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and encode in-memory.*/ +unsigned lodepng_encode_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image. + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and encode in-memory.*/ +unsigned lodepng_encode32_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h); + +/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image. + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and encode in-memory.*/ +unsigned lodepng_encode24_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h); +#endif /*LODEPNG_COMPILE_DISK*/ +#endif /*LODEPNG_COMPILE_ENCODER*/ + + +#ifdef LODEPNG_COMPILE_CPP +namespace lodepng { +#ifdef LODEPNG_COMPILE_DECODER +/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype +is the format to output the pixels to. Default is RGBA 8-bit per channel.*/ +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const unsigned char* in, size_t insize, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::vector& in, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#ifdef LODEPNG_COMPILE_DISK +/* +Converts PNG file from disk to raw pixel data in memory. +Same as the other decode functions, but instead takes a filename as input. + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and decode in-memory. +*/ +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::string& filename, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_DECODER */ + +#ifdef LODEPNG_COMPILE_ENCODER +/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype +is that of the raw input data. The output PNG color type will be auto chosen.*/ +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#ifdef LODEPNG_COMPILE_DISK +/* +Converts 32-bit RGBA raw pixel data into a PNG file on disk. +Same as the other encode functions, but instead takes a filename as output. + +NOTE: This overwrites existing files without warning! + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and decode in-memory. +*/ +unsigned encode(const std::string& filename, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned encode(const std::string& filename, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_ENCODER */ +} /* namespace lodepng */ +#endif /*LODEPNG_COMPILE_CPP*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ERROR_TEXT +/*Returns an English description of the numerical error code.*/ +const char* lodepng_error_text(unsigned code); +#endif /*LODEPNG_COMPILE_ERROR_TEXT*/ + +#ifdef LODEPNG_COMPILE_DECODER +/*Settings for zlib decompression*/ +typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; +struct LodePNGDecompressSettings { + /* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */ + unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ + unsigned ignore_nlen; /*ignore complement of len checksum in uncompressed blocks*/ + + /*Maximum decompressed size, beyond this the decoder may (and is encouraged to) stop decoding, + return an error, output a data size > max_output_size and all the data up to that point. This is + not hard limit nor a guarantee, but can prevent excessive memory usage. This setting is + ignored by the PNG decoder, but is used by the deflate/zlib decoder and can be used by custom ones. + Set to 0 to impose no limit (the default).*/ + size_t max_output_size; + + /*use custom zlib decoder instead of built in one (default: null). + Should return 0 if success, any non-0 if error (numeric value not exposed).*/ + unsigned (*custom_zlib)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGDecompressSettings*); + /*use custom deflate decoder instead of built in one (default: null) + if custom_zlib is not null, custom_inflate is ignored (the zlib format uses deflate). + Should return 0 if success, any non-0 if error (numeric value not exposed).*/ + unsigned (*custom_inflate)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGDecompressSettings*); + + const void* custom_context; /*optional custom settings for custom functions*/ +}; + +extern const LodePNGDecompressSettings lodepng_default_decompress_settings; +void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Settings for zlib compression. Tweaking these settings tweaks the balance +between speed and compression ratio. +*/ +typedef struct LodePNGCompressSettings LodePNGCompressSettings; +struct LodePNGCompressSettings /*deflate = compress*/ { + /*LZ77 related settings*/ + unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/ + unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/ + unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/ + unsigned minmatch; /*minimum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/ + unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/ + unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/ + + /*use custom zlib encoder instead of built in one (default: null)*/ + unsigned (*custom_zlib)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGCompressSettings*); + /*use custom deflate encoder instead of built in one (default: null) + if custom_zlib is used, custom_deflate is ignored since only the built in + zlib function will call custom_deflate*/ + unsigned (*custom_deflate)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGCompressSettings*); + + const void* custom_context; /*optional custom settings for custom functions*/ +}; + +extern const LodePNGCompressSettings lodepng_default_compress_settings; +void lodepng_compress_settings_init(LodePNGCompressSettings* settings); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_PNG +/* +Color mode of an image. Contains all information required to decode the pixel +bits to RGBA colors. This information is the same as used in the PNG file +format, and is used both for PNG and raw image data in LodePNG. +*/ +typedef struct LodePNGColorMode { + /*header (IHDR)*/ + LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ + unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ + + /* + palette (PLTE and tRNS) + + Dynamically allocated with the colors of the palette, including alpha. + This field may not be allocated directly, use lodepng_color_mode_init first, + then lodepng_palette_add per color to correctly initialize it (to ensure size + of exactly 1024 bytes). + + The alpha channels must be set as well, set them to 255 for opaque images. + + When decoding, with the default settings you can ignore this palette, since + LodePNG already fills the palette colors in the pixels of the raw RGBA output, + but when decoding to the original PNG color mode it is needed to reconstruct + the colors. + + The palette is only supported for color type 3. + */ + unsigned char* palette; /*palette in RGBARGBA... order. Must be either 0, or when allocated must have 1024 bytes*/ + size_t palettesize; /*palette size in number of colors (amount of used bytes is 4 * palettesize)*/ + + /* + transparent color key (tRNS) + + This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit. + For grayscale PNGs, r, g and b will all 3 be set to the same. + + When decoding, by default you can ignore this information, since LodePNG sets + pixels with this key to transparent already in the raw RGBA output. + + The color key is only supported for color types 0 and 2. + */ + unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/ + unsigned key_r; /*red/grayscale component of color key*/ + unsigned key_g; /*green component of color key*/ + unsigned key_b; /*blue component of color key*/ +} LodePNGColorMode; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_color_mode_init(LodePNGColorMode* info); +void lodepng_color_mode_cleanup(LodePNGColorMode* info); +/*return value is error code (0 means no error)*/ +unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source); +/* Makes a temporary LodePNGColorMode that does not need cleanup (no palette) */ +LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth); + +void lodepng_palette_clear(LodePNGColorMode* info); +/*add 1 color to the palette*/ +unsigned lodepng_palette_add(LodePNGColorMode* info, + unsigned char r, unsigned char g, unsigned char b, unsigned char a); + +/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/ +unsigned lodepng_get_bpp(const LodePNGColorMode* info); +/*get the amount of color channels used, based on colortype in the struct. +If a palette is used, it counts as 1 channel.*/ +unsigned lodepng_get_channels(const LodePNGColorMode* info); +/*is it a grayscale type? (only colortype 0 or 4)*/ +unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info); +/*has it got an alpha channel? (only colortype 2 or 6)*/ +unsigned lodepng_is_alpha_type(const LodePNGColorMode* info); +/*has it got a palette? (only colortype 3)*/ +unsigned lodepng_is_palette_type(const LodePNGColorMode* info); +/*only returns true if there is a palette and there is a value in the palette with alpha < 255. +Loops through the palette to check this.*/ +unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info); +/* +Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image. +Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels). +Returns false if the image can only have opaque pixels. +In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values, +or if "key_defined" is true. +*/ +unsigned lodepng_can_have_alpha(const LodePNGColorMode* info); +/*Returns the byte size of a raw image buffer with given width, height and color mode*/ +size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*The information of a Time chunk in PNG.*/ +typedef struct LodePNGTime { + unsigned year; /*2 bytes used (0-65535)*/ + unsigned month; /*1-12*/ + unsigned day; /*1-31*/ + unsigned hour; /*0-23*/ + unsigned minute; /*0-59*/ + unsigned second; /*0-60 (to allow for leap seconds)*/ +} LodePNGTime; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/*Information about the PNG image, except pixels, width and height.*/ +typedef struct LodePNGInfo { + /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ + unsigned compression_method;/*compression method of the original file. Always 0.*/ + unsigned filter_method; /*filter method of the original file*/ + unsigned interlace_method; /*interlace method of the original file: 0=none, 1=Adam7*/ + LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /* + Suggested background color chunk (bKGD) + + This uses the same color mode and bit depth as the PNG (except no alpha channel), + with values truncated to the bit depth in the unsigned integer. + + For grayscale and palette PNGs, the value is stored in background_r. The values + in background_g and background_b are then unused. The decoder will set them + equal to background_r, the encoder ignores them in this case. + + When decoding, you may get these in a different color mode than the one you requested + for the raw pixels: the colortype and bitdepth defined by info_png.color, that is the + ones defined in the header of the PNG image, are used. + + When encoding with auto_convert, you must use the color model defined in info_png.color for + these values. The encoder normally ignores info_png.color when auto_convert is on, but will + use it to interpret these values (and convert copies of them to its chosen color model). + + When encoding, avoid setting this to an expensive color, such as a non-gray value + when the image is gray, or the compression will be worse since it will be forced to + write the PNG with a more expensive color mode (when auto_convert is on). + + The decoder does not use this background color to edit the color of pixels. This is a + completely optional metadata feature. + */ + unsigned background_defined; /*is a suggested background color given?*/ + unsigned background_r; /*red/gray/palette component of suggested background color*/ + unsigned background_g; /*green component of suggested background color*/ + unsigned background_b; /*blue component of suggested background color*/ + + /* + Non-international text chunks (tEXt and zTXt) + + The char** arrays each contain num strings. The actual messages are in + text_strings, while text_keys are keywords that give a short description what + the actual text represents, e.g. Title, Author, Description, or anything else. + + All the string fields below including strings, keys, names and language tags are null terminated. + The PNG specification uses null characters for the keys, names and tags, and forbids null + characters to appear in the main text which is why we can use null termination everywhere here. + + A keyword is minimum 1 character and maximum 79 characters long (plus the + additional null terminator). It's discouraged to use a single line length + longer than 79 characters for texts. + + Don't allocate these text buffers yourself. Use the init/cleanup functions + correctly and use lodepng_add_text and lodepng_clear_text. + + Standard text chunk keywords and strings are encoded using Latin-1. + */ + size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/ + char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/ + char** text_strings; /*the actual text*/ + + /* + International text chunks (iTXt) + Similar to the non-international text chunks, but with additional strings + "langtags" and "transkeys", and the following text encodings are used: + keys: Latin-1, langtags: ASCII, transkeys and strings: UTF-8. + keys must be 1-79 characters (plus the additional null terminator), the other + strings are any length. + */ + size_t itext_num; /*the amount of international texts in this PNG*/ + char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/ + char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/ + char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/ + char** itext_strings; /*the actual international text - UTF-8 string*/ + + /* + Optional exif metadata in exif_size bytes. + Don't allocate this buffer yourself. Use the init/cleanup functions + correctly and use lodepng_set_exif and lodepng_clear_exif. + The exif data is in exif-encoded form but without JPEG markers, starting with the 'II' or 'MM' marker that indicates + endianness. It's up to an exif handling library to encode/decode its information. + */ + unsigned exif_defined; /* Whether exif metadata is present, that is, the PNG image has an eXIf chunk */ + unsigned char* exif; /* The bytes of the exif metadata, if present */ + unsigned exif_size; /* The size of the exif data in bytes */ + + + /*time chunk (tIME)*/ + unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/ + LodePNGTime time; + + /*phys chunk (pHYs)*/ + unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/ + unsigned phys_x; /*pixels per unit in x direction*/ + unsigned phys_y; /*pixels per unit in y direction*/ + unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/ + + /* + Color profile related chunk types: cICP, iCPP, sRGB, gAMA, cHRM, sBIT + + LodePNG does not apply any color conversions on pixels in the encoder or decoder and does not interpret these color + profile values. It merely passes on the information. If you wish to use color profiles and convert colors, a separate + color management library should be used. There is also a limited library for this in lodepng_util.h. + + There are 4 types of (sets of) chunks providing color information. If multiple are present, each will be decoded by + LodePNG, but only one should be handled by the user, with the following order of priority depending on what the user + supports: + 1: cICP: Coding-independent code points (CICP) + 2: iCCP: ICC profile + 3: sRGB: indicates the image is in the sRGB color profile + 4: gAMA and cHRM: indicates a gamma and chromaticity value to define the color profile + */ + + /* + gAMA chunk: Image gamma + Optional, overridden by cICP, iCCP or sRGB if those are present. + Together with cHRM, this is a primitive way of specifying the image color profile. + */ + unsigned gama_defined; /* Whether a gAMA chunk is present (0 = not present, 1 = present). */ + unsigned gama_gamma; /* Gamma exponent times 100000 */ + + /* + cHRM chunk: Primary chromaticities and white point + Optional, overridden by cICP, iCCP or sRGB if those are present. + Together with gAMA, this is a primitive way of specifying the image color profile. + */ + unsigned chrm_defined; /* Whether a cHRM chunk is present (0 = not present, 1 = present). */ + unsigned chrm_white_x; /* White Point x times 100000 */ + unsigned chrm_white_y; /* White Point y times 100000 */ + unsigned chrm_red_x; /* Red x times 100000 */ + unsigned chrm_red_y; /* Red y times 100000 */ + unsigned chrm_green_x; /* Green x times 100000 */ + unsigned chrm_green_y; /* Green y times 100000 */ + unsigned chrm_blue_x; /* Blue x times 100000 */ + unsigned chrm_blue_y; /* Blue y times 100000 */ + + /* + sRGB chunk: Indicates the image is in the sRGB color space. + Optional. Should not appear at the same time as iCCP. + If gAMA is also present gAMA must contain value 45455. + If cHRM is also present cHRM must contain respectively 31270,32900,64000,33000,30000,60000,15000,6000. + */ + unsigned srgb_defined; /* Whether an sRGB chunk is present (0 = not present, 1 = present). */ + unsigned srgb_intent; /* Rendering intent: 0=perceptual, 1=rel. colorimetric, 2=saturation, 3=abs. colorimetric */ + + /* + iCCP chunk: Embedded ICC profile. + Optional. Should not appear at the same time as sRGB. + + Contains ICC profile, which can use any version of the ICC.1 specification by the International Color Consortium. See + its specification for more details. LodePNG does not parse or use the ICC profile (except its color space header + field for "RGB" or "GRAY", see below), a separate library to handle the ICC data format is needed to use it for color + management and conversions. + + For encoding, if iCCP is present, the PNG specification recommends to also add gAMA and cHRM chunks that approximate + the ICC profile, for compatibility with applications that don't use the ICC chunk. This is not required, and it's up + to the user to compute approximate values and set then in the appropriate gama_ and chrm_ fields, LodePNG does not do + this automatically since it does not interpret the ICC profile. + + For encoding, the ICC profile is required by the PNG specification to be an "RGB" profile for non-gray PNG color + types (types 2, 3 and 6) and a "GRAY" profile for gray PNG color types (types 1 and 4). If you disable auto_convert, + you must ensure the ICC profile type matches your requested color type, else the encoder gives an error. If + auto_convert is enabled (the default), and the ICC profile is not a correct match for the pixel data, this will result + in an encoder error if the pixel data has non-gray pixels for a GRAY profile, or a silent less-optimal compression of + the pixel data if the pixels could be encoded as grayscale but the ICC profile is RGB. + + To avoid this do not set an ICC profile in the image unless there is a good reason for it, and when doing so + make sure you compute it carefully to avoid the above problems. + */ + unsigned iccp_defined; /* Whether an iCCP chunk is present (0 = not present, 1 = present). */ + char* iccp_name; /* Null terminated string with profile name, 1-79 bytes */ + /* + The ICC profile in iccp_profile_size bytes. + Don't allocate this buffer yourself. Use the init/cleanup functions + correctly and use lodepng_set_icc and lodepng_clear_icc. + */ + unsigned char* iccp_profile; + unsigned iccp_profile_size; /* The size of iccp_profile in bytes */ + + /* + cICP chunk: Coding-independent code points for video signal type identification. + Optional. If present, and supported, overrides iCCP, sRGB, gAMA and cHRM. + The meaning of the values are as defined in the specification ITU-T-H.273. LodePNG does not + use these values, only passes on the metadata. The meaning of the values is they are enum + values representing certain color spaces, including HDR color spaces, such as Display P3, + PQ and HLG. The video full range flag value should typically be 1 for the use cases of PNG + images, but can be 0 for narrow-range images in certain video editing workflows. + */ + unsigned cicp_defined; /* Whether an cICP chunk is present (0 = not present, 1 = present). */ + unsigned cicp_color_primaries; /* Colour primaries value */ + unsigned cicp_transfer_function; /* Transfer characteristics value */ + unsigned cicp_matrix_coefficients; /* Matrix coefficients value */ + unsigned cicp_video_full_range_flag; /* Video full range flag value */ + + /* + mDCV chunk: Mastering Display Color Volume. + Optional, typically used in conjunction with certain HDR color spaces that can + be represented by the cICP chunk. + See the PNG specification, third edition, for more information on this chunk. + All the red, green, blue and white x and y values are encoded as 16-bit + integers and therefore must be in range 0-65536. The min and max luminance + values are 32-bit integers. + */ + unsigned mdcv_defined; /* Whether an mDCV chunk is present (0 = not present, 1 = present). */ + /* Mastering display color primary chromaticities (CIE 1931 x,y of R,G,B) */ + unsigned mdcv_red_x; /* Red x times 50000 */ + unsigned mdcv_red_y; /* Red y times 50000 */ + unsigned mdcv_green_x; /* Green x times 50000 */ + unsigned mdcv_green_y; /* Green y times 50000 */ + unsigned mdcv_blue_x; /* Blue x times 50000 */ + unsigned mdcv_blue_y; /* Blue y times 50000 */ + /* Mastering display white point chromaticity (CIE 1931 x,y) */ + unsigned mdcv_white_x; /* White Point x times 50000 */ + unsigned mdcv_white_y; /* White Point y times 50000 */ + /* Mastering display luminance */ + unsigned mdcv_max_luminance; /* Max luminance in cd/m^2 times 10000 */ + unsigned mdcv_min_luminance; /* Min luminance in cd/m^2 times 10000 */ + + /* + cLLI chunk: Content Light Level Information. + Optional, typically used in conjunction with certain HDR color spaces that can + be represented by the cICP chunk. + See the PNG specification, third edition, for more information on this chunk. + The clli_max_cll and clli_max_fall values are 32-bit integers. + */ + unsigned clli_defined; /* Whether a cLLI chunk is present (0 = not present, 1 = present). */ + unsigned clli_max_cll; /* Maximum Content Light Level (MaxCLL) in cd/m^2 times 10000 */ + unsigned clli_max_fall; /* Maximum Frame-Average Light Level (MaxFALL) in cd/m^2 times 10000 */ + + /* + sBIT chunk: significant bits. + Optional metadata, only set this if needed. + + If defined, these values give the bit depth of the original data. Since PNG only stores 1, 2, 4, 8 or 16-bit + per channel data, the significant bits value can be used to indicate the original encoded data has another + sample depth, such as 10 or 12. + + Encoders using this value, when storing the pixel data, should use the most significant bits + of the data to store the original bits, and use a good sample depth scaling method such as + "left bit replication" to fill in the least significant bits, rather than fill zeroes. + + Decoders using this value, if able to work with data that's e.g. 10-bit or 12-bit, should right + shift the data to go back to the original bit depth, but decoders are also allowed to ignore + sbit and work e.g. with the 8-bit or 16-bit data from the PNG directly, since thanks + to the encoder contract, the values encoded in PNG are in valid range for the PNG bit depth. + + For grayscale images, sbit_g and sbit_b are not used, and for images that don't use color + type RGBA or grayscale+alpha, sbit_a is not used (it's not used even for palette images with + translucent palette values, or images with color key). The values that are used must be + greater than zero and smaller than or equal to the PNG bit depth. + + The color type from the header in the PNG image defines these used and unused fields: if + decoding with a color mode conversion, such as always decoding to RGBA, this metadata still + only uses the color type of the original PNG, and may e.g. lack the alpha channel info + if the PNG was RGB. When encoding with auto_convert (as well as without), also always the + color model defined in info_png.color determines this. + + NOTE: enabling sbit can hurt compression, because the encoder can then not always use + auto_convert to choose a more optimal color mode for the data, because the PNG format has + strict requirements for the allowed sbit values in combination with color modes. + For example, setting these fields to 10-bit will force the encoder to keep using a 16-bit per channel + color mode, even if the pixel data would in fact fit in a more efficient 8-bit mode. + */ + unsigned sbit_defined; /*is significant bits given? if not, the values below are unused*/ + unsigned sbit_r; /*red or gray component of significant bits*/ + unsigned sbit_g; /*green component of significant bits*/ + unsigned sbit_b; /*blue component of significant bits*/ + unsigned sbit_a; /*alpha component of significant bits*/ + + /* End of color profile related chunks */ + + + /* + unknown chunks: chunks not known by LodePNG, passed on byte for byte. + + There are 3 buffers, one for each position in the PNG where unknown chunks can appear. + Each buffer contains all unknown chunks for that position consecutively. + The 3 positions are: + 0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND. + + For encoding, do not store critical chunks or known chunks that are enabled with a "_defined" flag + above in here, since the encoder will blindly follow this and could then encode an invalid PNG file + (such as one with two IHDR chunks or the disallowed combination of sRGB with iCCP). But do use + this if you wish to store an ancillary chunk that is not supported by LodePNG (such as sPLT or hIST), + or any non-standard PNG chunk. + + Do not allocate or traverse this data yourself. Use the chunk traversing functions declared + later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct. + */ + unsigned char* unknown_chunks_data[3]; + size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGInfo; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_info_init(LodePNGInfo* info); +void lodepng_info_cleanup(LodePNGInfo* info); +/*return value is error code (0 means no error)*/ +unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/ +void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ + +unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, + const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/ +void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/ + +/*replaces if exists*/ +unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size); +void lodepng_clear_icc(LodePNGInfo* info); /*use this to clear the profile again after you filled it in*/ + +/*replaces if exists*/ +unsigned lodepng_set_exif(LodePNGInfo* info, const unsigned char* exif, unsigned exif_size); +void lodepng_clear_exif(LodePNGInfo* info); /*use this to clear the exif metadata again after you filled it in*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/* +Converts raw buffer from one color type to another color type, based on +LodePNGColorMode structs to describe the input and output color type. +See the reference manual at the end of this header file to see which color conversions are supported. +return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported) +The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel +of the output color type (lodepng_get_bpp). +For < 8 bpp images, there should not be padding bits at the end of scanlines. +For 16-bit per channel colors, uses big endian format like PNG does. +Return value is LodePNG error code +*/ +unsigned lodepng_convert(unsigned char* out, const unsigned char* in, + const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, + unsigned w, unsigned h); + +#ifdef LODEPNG_COMPILE_DECODER +/* +Settings for the decoder. This contains settings for the PNG and the Zlib +decoder, but not the Info settings from the Info structs. +*/ +typedef struct LodePNGDecoderSettings { + LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ + + /* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */ + unsigned ignore_crc; /*ignore CRC checksums*/ + unsigned ignore_critical; /*ignore unknown critical chunks*/ + unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/ + /* TODO: make a system involving warnings with levels and a strict mode instead. Other potentially recoverable + errors: srgb rendering intent value, size of content of ancillary chunks, more than 79 characters for some + strings, placement/combination rules for ancillary chunks, crc of unknown chunks, allowed characters + in string keys, invalid characters in chunk types names, etc... */ + + unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/ + + /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/ + unsigned remember_unknown_chunks; + + /* maximum size for decompressed text chunks. If a text chunk's text is larger than this, an error is returned, + unless reading text chunks is disabled or this limit is set higher or disabled. Set to 0 to allow any size. + By default it is a value that prevents unreasonably large strings from hogging memory. */ + size_t max_text_size; + + /* maximum size for compressed ICC chunks. If the ICC profile is larger than this, an error will be returned. Set to + 0 to allow any size. By default this is a value that prevents ICC profiles that would be much larger than any + legitimate profile could be to hog memory. */ + size_t max_icc_size; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGDecoderSettings; + +void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/*strategy to use to choose the PNG filter per scanline. Strategies 0-4 correspond +to each of the 5 filter types PNG supports, the next values are adaptive strategies*/ +typedef enum LodePNGFilterStrategy { + /*every filter at zero*/ + LFS_ZERO = 0, + /*every filter at 1, 2, 3 or 4 (paeth), unlike LFS_ZERO not a good choice, but for testing*/ + LFS_ONE = 1, + LFS_TWO = 2, + LFS_THREE = 3, + LFS_FOUR = 4, + /*Use the filter out of the 5 above types that gives minimum sum, by trying each one. This is the adaptive filtering + suggested heuristic in the PNG standard chapter 'Filter selection'.*/ + LFS_MINSUM, + /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending + on the image, this is better or worse than minsum.*/ + LFS_ENTROPY, + /* + Brute-force-search PNG filters by compressing each filter for each scanline. + Experimental, very slow, and only rarely gives better compression than MINSUM. + */ + LFS_BRUTE_FORCE, + /*use predefined_filters buffer: you specify the filter type for each scanline*/ + LFS_PREDEFINED +} LodePNGFilterStrategy; + +/*Gives characteristics about the integer RGBA colors of the image (count, alpha channel usage, bit depth, ...), +which helps decide which color model to use for encoding. +Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/ +typedef struct LodePNGColorStats { + unsigned colored; /*not grayscale*/ + unsigned key; /*image is not opaque and color key is possible instead of full alpha*/ + unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/ + unsigned short key_g; + unsigned short key_b; + unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/ + unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16 or allow_palette is disabled.*/ + unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order, only valid when numcolors is valid*/ + unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for grayscale only. 16 if 16-bit per channel required.*/ + size_t numpixels; + + /*user settings for computing/using the stats*/ + unsigned allow_palette; /*default 1. if 0, disallow choosing palette colortype in auto_choose_color, and don't count numcolors*/ + unsigned allow_greyscale; /*default 1. if 0, choose RGB or RGBA even if the image only has gray colors*/ +} LodePNGColorStats; + +void lodepng_color_stats_init(LodePNGColorStats* stats); + +/*Get a LodePNGColorStats of the image. The stats must already have been inited. +Returns error code (e.g. alloc fail) or 0 if ok.*/ +unsigned lodepng_compute_color_stats(LodePNGColorStats* stats, + const unsigned char* image, unsigned w, unsigned h, + const LodePNGColorMode* mode_in); + +/*Settings for the encoder.*/ +typedef struct LodePNGEncoderSettings { + LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ + + /*automatically choose output PNG color type. If false, must explicitely choose the output color + type in state.info_png.color.colortype, info_png.color.bitdepth and optionally its palette. + Default: true*/ + unsigned auto_convert; + + /*If true, follows the suggestion in the PNG standard in chapter 'Filter selection': if the PNG uses + a palette or lower than 8 bit depth, set all filters to zero. + In other cases this will use the heuristic from the chosen filter_strategy. The PNG standard + suggests LFS_MINSUM for those cases.*/ + unsigned filter_palette_zero; + /*Which filter strategy to use when not using zeroes due to filter_palette_zero. + Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/ + LodePNGFilterStrategy filter_strategy; + /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with + the same length as the amount of scanlines in the image, and each value must <= 5. You + have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero + must be set to 0 to ensure this is also used on palette or low bitdepth images.*/ + const unsigned char* predefined_filters; + + /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). + If colortype is 3, PLTE is always created. If color type is explicitely set + to a grayscale type (1 or 4), this is not done and is ignored. If enabling this, + a palette must be present in the info_png. + NOTE: enabling this may worsen compression if auto_convert is used to choose + optimal color mode, because it cannot use grayscale color modes in this case*/ + unsigned force_palette; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*add LodePNG identifier and version as a text chunk, for debugging*/ + unsigned add_id; + /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/ + unsigned text_compression; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGEncoderSettings; + +void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings); +#endif /*LODEPNG_COMPILE_ENCODER*/ + + +#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) +/*The settings, state and information for extended encoding and decoding.*/ +typedef struct LodePNGState { +#ifdef LODEPNG_COMPILE_DECODER + LodePNGDecoderSettings decoder; /*the decoding settings*/ +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER + LodePNGEncoderSettings encoder; /*the encoding settings*/ +#endif /*LODEPNG_COMPILE_ENCODER*/ + LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/ + LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/ + unsigned error; +} LodePNGState; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_state_init(LodePNGState* state); +void lodepng_state_cleanup(LodePNGState* state); +void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source); +#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ + +#ifdef LODEPNG_COMPILE_DECODER +/* +Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and +getting much more information about the PNG image and color mode. +*/ +unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize); + +/* +Read the PNG header, but not the actual data. This returns only the information +that is in the IHDR chunk of the PNG, such as width, height and color type. The +information is placed in the info_png field of the LodePNGState. +*/ +unsigned lodepng_inspect(unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize); +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* +Reads one metadata chunk (other than IHDR, which is handled by lodepng_inspect) +of the PNG file and outputs what it read in the state. Returns error code on failure. +Use lodepng_inspect first with a new state, then e.g. lodepng_chunk_find_const +to find the desired chunk type, and if non null use lodepng_inspect_chunk (with +chunk_pointer - start_of_file as pos). +Supports most metadata chunks from the PNG standard (gAMA, bKGD, tEXt, ...). +Ignores unsupported, unknown, non-metadata or IHDR chunks (without error). +Requirements: &in[pos] must point to start of a chunk, must use regular +lodepng_inspect first since format of most other chunks depends on IHDR, and if +there is a PLTE chunk, that one must be inspected before tRNS or bKGD. +*/ +unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos, + const unsigned char* in, size_t insize); + +#ifdef LODEPNG_COMPILE_ENCODER +/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/ +unsigned lodepng_encode(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGState* state); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/* +The lodepng_chunk functions are normally not needed, except to traverse the +unknown chunks stored in the LodePNGInfo struct, or add new ones to it. +It also allows traversing the chunks of an encoded PNG file yourself. + +The chunk pointer always points to the beginning of the chunk itself, that is +the first byte of the 4 length bytes. + +In the PNG file format, chunks have the following format: +-4 bytes length: length of the data of the chunk in bytes (chunk itself is 12 bytes longer) +-4 bytes chunk type (ASCII a-z,A-Z only, see below) +-length bytes of data (may be 0 bytes if length was 0) +-4 bytes of CRC, computed on chunk name + data + +The first chunk starts at the 8th byte of the PNG file, the entire rest of the file +exists out of concatenated chunks with the above format. + +PNG standard chunk ASCII naming conventions: +-First byte: uppercase = critical, lowercase = ancillary +-Second byte: uppercase = public, lowercase = private +-Third byte: must be uppercase +-Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy +*/ + +/* +Gets the length of the data of the chunk. Total chunk length has 12 bytes more. +There must be at least 4 bytes to read from. If the result value is too large, +it may be corrupt data. +*/ +unsigned lodepng_chunk_length(const unsigned char* chunk); + +/*puts the 4-byte type in null terminated string*/ +void lodepng_chunk_type(char type[5], const unsigned char* chunk); + +/*check if the type is the given type*/ +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type); + +/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/ +unsigned char lodepng_chunk_ancillary(const unsigned char* chunk); + +/*0: public, 1: private (see PNG standard)*/ +unsigned char lodepng_chunk_private(const unsigned char* chunk); + +/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/ +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk); + +/*get pointer to the data of the chunk, where the input points to the header of the chunk*/ +unsigned char* lodepng_chunk_data(unsigned char* chunk); +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk); + +/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/ +unsigned lodepng_chunk_check_crc(const unsigned char* chunk); + +/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/ +void lodepng_chunk_generate_crc(unsigned char* chunk); + +/* +Iterate to next chunks, allows iterating through all chunks of the PNG file. +Input must be at the beginning of a chunk (result of a previous lodepng_chunk_next call, +or the 8th byte of a PNG file which always has the first chunk), or alternatively may +point to the first byte of the PNG file (which is not a chunk but the magic header, the +function will then skip over it and return the first real chunk). +Will output pointer to the start of the next chunk, or at or beyond end of the file if there +is no more chunk after this or possibly if the chunk is corrupt. +Start this process at the 8th byte of the PNG file. +In a non-corrupt PNG file, the last chunk should have name "IEND". +*/ +unsigned char* lodepng_chunk_next(unsigned char* chunk, unsigned char* end); +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end); + +/*Finds the first chunk with the given type in the range [chunk, end), or returns NULL if not found.*/ +unsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]); +const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]); + +/* +Appends chunk to the data in out. The given chunk should already have its chunk header. +The out variable and outsize are updated to reflect the new reallocated buffer. +Returns error code (0 if it went ok) +*/ +unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk); + +/* +Appends new chunk to out. The chunk to append is given by giving its length, type +and data separately. The type is a 4-letter string. +The out variable and outsize are updated to reflect the new reallocated buffer. +Returne error code (0 if it went ok) +*/ +unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, size_t length, + const char* type, const unsigned char* data); + + +/*Calculate CRC32 of buffer*/ +unsigned lodepng_crc32(const unsigned char* buf, size_t len); +#endif /*LODEPNG_COMPILE_PNG*/ + + +#ifdef LODEPNG_COMPILE_ZLIB +/* +This zlib part can be used independently to zlib compress and decompress a +buffer. It cannot be used to create gzip files however, and it only supports the +part of zlib that is required for PNG, it does not support dictionaries. +*/ + +#ifdef LODEPNG_COMPILE_DECODER +/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/ +unsigned lodepng_inflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings); + +/* +Decompresses Zlib data. Reallocates the out buffer and appends the data. The +data must be according to the zlib specification. +Either, *out must be NULL and *outsize must be 0, or, *out must be a valid +buffer and *outsize its size in bytes. out must be freed by user after usage. +*/ +unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Compresses data with Zlib. Reallocates the out buffer and appends the data. +Zlib adds a small header and trailer around the deflate data. +The data is output in the format of the zlib specification. +Either, *out must be NULL and *outsize must be 0, or, *out must be a valid +buffer and *outsize its size in bytes. out must be freed by user after usage. +*/ +unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings); + +/* +Find length-limited Huffman code for given frequencies. This function is in the +public interface only for tests, it's used internally by lodepng_deflate. +*/ +unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, + size_t numcodes, unsigned maxbitlen); + +/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/ +unsigned lodepng_deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings); + +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_ZLIB*/ + +#ifdef LODEPNG_COMPILE_DISK +/* +Load a file from disk into buffer. The function allocates the out buffer, and +after usage you should free it. +out: output parameter, contains pointer to loaded buffer. +outsize: output parameter, size of the allocated out buffer +filename: the path to the file to load +return value: error code (0 means ok) + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and decode in-memory. +*/ +unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename); + +/* +Save a file from buffer to disk. Warning, if it exists, this function overwrites +the file without warning! +buffer: the buffer to write +buffersize: size of the buffer to write +filename: the path to the file to save to +return value: error code (0 means ok) + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and encode in-memory +*/ +unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename); +#endif /*LODEPNG_COMPILE_DISK*/ + +#ifdef LODEPNG_COMPILE_CPP +/* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */ +namespace lodepng { +#ifdef LODEPNG_COMPILE_PNG +class State : public LodePNGState { + public: + State(); + State(const State& other); + ~State(); + State& operator=(const State& other); +}; + +#ifdef LODEPNG_COMPILE_DECODER +/* Same as other lodepng::decode, but using a State for more settings and information. */ +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const unsigned char* in, size_t insize); +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const std::vector& in); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/* Same as other lodepng::encode, but using a State for more settings and information. */ +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + State& state); +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + State& state); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DISK +/* +Load a file from disk into an std::vector. +return value: error code (0 means ok) + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and decode in-memory +*/ +unsigned load_file(std::vector& buffer, const std::string& filename); + +/* +Save the binary data in an std::vector to a file on disk. The file is overwritten +without warning. + +NOTE: Wide-character filenames are not supported, you can use an external method +to handle such files and encode in-memory +*/ +unsigned save_file(const std::vector& buffer, const std::string& filename); +#endif /* LODEPNG_COMPILE_DISK */ +#endif /* LODEPNG_COMPILE_PNG */ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_DECODER +/* Zlib-decompress an unsigned char buffer */ +unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); + +/* Zlib-decompress an std::vector */ +unsigned decompress(std::vector& out, const std::vector& in, + const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); +#endif /* LODEPNG_COMPILE_DECODER */ + +#ifdef LODEPNG_COMPILE_ENCODER +/* Zlib-compress an unsigned char buffer */ +unsigned compress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings& settings = lodepng_default_compress_settings); + +/* Zlib-compress an std::vector */ +unsigned compress(std::vector& out, const std::vector& in, + const LodePNGCompressSettings& settings = lodepng_default_compress_settings); +#endif /* LODEPNG_COMPILE_ENCODER */ +#endif /* LODEPNG_COMPILE_ZLIB */ +} /* namespace lodepng */ +#endif /*LODEPNG_COMPILE_CPP*/ + +/* +TODO: +[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often +[.] check compatibility with various compilers - done but needs to be redone for every newer version +[X] converting color to 16-bit per channel types +[X] support color profile chunk types (but never let them touch RGB values by default) +[ ] support all second edition public PNG chunk types (almost done except sPLT and hIST) +[X] support non-animation third edition public PNG chunk types: eXIf, cICP, mDCV, cLLI +[ ] make sure encoder generates no chunks with size > (2^31)-1 +[ ] partial decoding (stream processing) +[X] let the "isFullyOpaque" function check color keys and transparent palettes too +[X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl" +[ ] allow treating some errors like warnings, when image is recoverable (e.g. 69, 57, 58) +[ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in text, ... +[ ] error messages with line numbers (and version) +[ ] errors in state instead of as return code? +[ ] new errors/warnings like suspiciously big decompressed ztxt or iccp chunk +[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes +[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ... +[ ] allow user to give data (void*) to custom allocator +[X] provide alternatives for C library functions not present on some platforms (memcpy, ...) +*/ + +#endif /*LODEPNG_H inclusion guard*/ + +/* +LodePNG Documentation +--------------------- + +0. table of contents +-------------------- + + 1. about + 1.1. supported features + 1.2. features not supported + 2. C and C++ version + 3. security + 4. decoding + 5. encoding + 6. color conversions + 6.1. PNG color types + 6.2. color conversions + 6.3. padding bits + 6.4. A note about 16-bits per channel and endianness + 7. error values + 8. chunks and PNG editing + 9. compiler support + 10. examples + 10.1. decoder C++ example + 10.2. decoder C example + 11. state settings reference + 12. changes + 13. contact information + + +1. about +-------- + +PNG is a file format to store raster images losslessly with good compression, +supporting different color types and alpha channel. + +LodePNG is a PNG codec according to the Portable Network Graphics (PNG) +Specification (Second Edition) - W3C Recommendation 10 November 2003. + +The specifications used are: + +*) Portable Network Graphics (PNG) Specification (Second Edition): + http://www.w3.org/TR/2003/REC-PNG-20031110 +*) RFC 1950 ZLIB Compressed Data Format version 3.3: + http://www.gzip.org/zlib/rfc-zlib.html +*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3: + http://www.gzip.org/zlib/rfc-deflate.html + +The most recent version of LodePNG can currently be found at +http://lodev.org/lodepng/ + +LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds +extra functionality. + +LodePNG exists out of two files: +-lodepng.h: the header file for both C and C++ +-lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage + +If you want to start using LodePNG right away without reading this doc, get the +examples from the LodePNG website to see how to use it in code, or check the +smaller examples in chapter 13 here. + +LodePNG is simple but only supports the basic requirements. To achieve +simplicity, the following design choices were made: There are no dependencies +on any external library. There are functions to decode and encode a PNG with +a single function call, and extended versions of these functions taking a +LodePNGState struct allowing to specify or get more information. By default +the colors of the raw image are always RGB or RGBA, no matter what color type +the PNG file uses. To read and write files, there are simple functions to +convert the files to/from buffers in memory. + +This all makes LodePNG suitable for loading textures in games, demos and small +programs, ... It's less suitable for full fledged image editors, loading PNGs +over network (it requires all the image data to be available before decoding can +begin), life-critical systems, ... + +1.1. supported features +----------------------- + +The following features are supported by the decoder: + +*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image, + or the same color type as the PNG +*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image +*) Adam7 interlace and deinterlace for any color type +*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk +*) support for alpha channels, including RGBA color model, translucent palettes and color keying +*) zlib decompression (inflate) +*) zlib compression (deflate) +*) CRC32 and ADLER32 checksums +*) colorimetric color profile conversions: currently experimentally available in lodepng_util.cpp only, + plus alternatively ability to pass on chroma/gamma/ICC profile information to other color management system. +*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks. +*) the following chunks are supported by both encoder and decoder: + IHDR: header information + PLTE: color palette + IDAT: pixel data + IEND: the final chunk + tRNS: transparency for palettized images + tEXt: textual information + zTXt: compressed textual information + iTXt: international textual information + bKGD: suggested background color + pHYs: physical dimensions + tIME: modification time + cHRM: RGB chromaticities + gAMA: RGB gamma correction + iCCP: ICC color profile + sRGB: rendering intent + sBIT: significant bits + +1.2. features not supported +--------------------------- + +The following features are not (yet) supported: + +*) some features needed to make a conformant PNG-Editor might be still missing. +*) partial loading/stream processing. All data must be available and is processed in one call. +*) The hIST and sPLT public chunks are not (yet) supported but treated as unknown chunks + + +2. C and C++ version +-------------------- + +The C version uses buffers allocated with alloc that you need to free() +yourself. You need to use init and cleanup functions for each struct whenever +using a struct from the C version to avoid exploits and memory leaks. + +The C++ version has extra functions with std::vectors in the interface and the +lodepng::State class which is a LodePNGState with constructor and destructor. + +These files work without modification for both C and C++ compilers because all +the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers +ignore it, and the C code is made to compile both with strict ISO C90 and C++. + +To use the C++ version, you need to rename the source file to lodepng.cpp +(instead of lodepng.c), and compile it with a C++ compiler. + +To use the C version, you need to rename the source file to lodepng.c (instead +of lodepng.cpp), and compile it with a C compiler. + + +3. Security +----------- + +Even if carefully designed, it's always possible that LodePNG contains possible +exploits. If you discover one, please let me know, and it will be fixed. + +When using LodePNG, care has to be taken with the C version of LodePNG, as well +as the C-style structs when working with C++. The following conventions are used +for all C-style structs: + +-if a struct has a corresponding init function, always call the init function when making a new one +-if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks +-if a struct has a corresponding copy function, use the copy function instead of "=". + The destination must also be inited already. + + +4. Decoding +----------- + +Decoding converts a PNG compressed image to a raw pixel buffer. + +Most documentation on using the decoder is at its declarations in the header +above. For C, simple decoding can be done with functions such as +lodepng_decode32, and more advanced decoding can be done with the struct +LodePNGState and lodepng_decode. For C++, all decoding can be done with the +various lodepng::decode functions, and lodepng::State can be used for advanced +features. + +When using the LodePNGState, it uses the following fields for decoding: +*) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here +*) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get +*) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use + +LodePNGInfo info_png +-------------------- + +After decoding, this contains extra information of the PNG image, except the actual +pixels, width and height because these are already gotten directly from the decoder +functions. + +It contains for example the original color type of the PNG image, text comments, +suggested background color, etc... More details about the LodePNGInfo struct are +at its declaration documentation. + +LodePNGColorMode info_raw +------------------------- + +When decoding, here you can specify which color type you want +the resulting raw image to be. If this is different from the colortype of the +PNG, then the decoder will automatically convert the result. This conversion +always works, except if you want it to convert a color PNG to grayscale or to +a palette with missing colors. + +By default, 32-bit color is used for the result. + +LodePNGDecoderSettings decoder +------------------------------ + +The settings can be used to ignore the errors created by invalid CRC and Adler32 +chunks, and to disable the decoding of tEXt chunks. + +There's also a setting color_convert, true by default. If false, no conversion +is done, the resulting data will be as it was in the PNG (after decompression) +and you'll have to puzzle the colors of the pixels together yourself using the +color type information in the LodePNGInfo. + + +5. Encoding +----------- + +Encoding converts a raw pixel buffer to a PNG compressed image. + +Most documentation on using the encoder is at its declarations in the header +above. For C, simple encoding can be done with functions such as +lodepng_encode32, and more advanced decoding can be done with the struct +LodePNGState and lodepng_encode. For C++, all encoding can be done with the +various lodepng::encode functions, and lodepng::State can be used for advanced +features. + +Like the decoder, the encoder can also give errors. However it gives less errors +since the encoder input is trusted, the decoder input (a PNG image that could +be forged by anyone) is not trusted. + +When using the LodePNGState, it uses the following fields for encoding: +*) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be. +*) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has +*) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use + +LodePNGInfo info_png +-------------------- + +When encoding, you use this the opposite way as when decoding: for encoding, +you fill in the values you want the PNG to have before encoding. By default it's +not needed to specify a color type for the PNG since it's automatically chosen, +but it's possible to choose it yourself given the right settings. + +The encoder will not always exactly match the LodePNGInfo struct you give, +it tries as close as possible. Some things are ignored by the encoder. The +encoder uses, for example, the following settings from it when applicable: +colortype and bitdepth, text chunks, time chunk, the color key, the palette, the +background color, the interlace method, unknown chunks, ... + +When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk. +If the palette contains any colors for which the alpha channel is not 255 (so +there are translucent colors in the palette), it'll add a tRNS chunk. + +LodePNGColorMode info_raw +------------------------- + +You specify the color type of the raw image that you give to the input here, +including a possible transparent color key and palette you happen to be using in +your raw image data. + +By default, 32-bit color is assumed, meaning your input has to be in RGBA +format with 4 bytes (unsigned chars) per pixel. + +LodePNGEncoderSettings encoder +------------------------------ + +The following settings are supported (some are in sub-structs): +*) auto_convert: when this option is enabled, the encoder will +automatically choose the smallest possible color mode (including color key) that +can encode the colors of all pixels without information loss. +*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree, + 2 = dynamic huffman tree (best compression). Should be 2 for proper + compression. +*) use_lz77: whether or not to use LZ77 for compressed block types. Should be + true for proper compression. +*) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value + 2048 by default, but can be set to 32768 for better, but slow, compression. +*) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE + chunk if force_palette is true. This can used as suggested palette to convert + to by viewers that don't support more than 256 colors (if those still exist) +*) add_id: add text chunk "Encoder: LodePNG " to the image. +*) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks. + zTXt chunks use zlib compression on the text. This gives a smaller result on + large texts but a larger result on small texts (such as a single program name). + It's all tEXt or all zTXt though, there's no separate setting per text yet. + + +6. color conversions +-------------------- + +An important thing to note about LodePNG, is that the color type of the PNG, and +the color type of the raw image, are completely independent. By default, when +you decode a PNG, you get the result as a raw image in the color type you want, +no matter whether the PNG was encoded with a palette, grayscale or RGBA color. +And if you encode an image, by default LodePNG will automatically choose the PNG +color type that gives good compression based on the values of colors and amount +of colors in the image. It can be configured to let you control it instead as +well, though. + +To be able to do this, LodePNG does conversions from one color mode to another. +It can convert from almost any color type to any other color type, except the +following conversions: RGB to grayscale is not supported, and converting to a +palette when the palette doesn't have a required color is not supported. This is +not supported on purpose: this is information loss which requires a color +reduction algorithm that is beyond the scope of a PNG encoder (yes, RGB to gray +is easy, but there are multiple ways if you want to give some channels more +weight). + +By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB +color, no matter what color type the PNG has. And by default when encoding, +LodePNG automatically picks the best color model for the output PNG, and expects +the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control +the color format of the images yourself, you can skip this chapter. + +6.1. PNG color types +-------------------- + +A PNG image can have many color types, ranging from 1-bit color to 64-bit color, +as well as palettized color modes. After the zlib decompression and unfiltering +in the PNG image is done, the raw pixel data will have that color type and thus +a certain amount of bits per pixel. If you want the output raw image after +decoding to have another color type, a conversion is done by LodePNG. + +The PNG specification gives the following color types: + +0: grayscale, bit depths 1, 2, 4, 8, 16 +2: RGB, bit depths 8 and 16 +3: palette, bit depths 1, 2, 4 and 8 +4: grayscale with alpha, bit depths 8 and 16 +6: RGBA, bit depths 8 and 16 + +Bit depth is the amount of bits per pixel per color channel. So the total amount +of bits per pixel is: amount of channels * bitdepth. + +6.2. color conversions +---------------------- + +As explained in the sections about the encoder and decoder, you can specify +color types and bit depths in info_png and info_raw to change the default +behaviour. + +If, when decoding, you want the raw image to be something else than the default, +you need to set the color type and bit depth you want in the LodePNGColorMode, +or the parameters colortype and bitdepth of the simple decoding function. + +If, when encoding, you use another color type than the default in the raw input +image, you need to specify its color type and bit depth in the LodePNGColorMode +of the raw image, or use the parameters colortype and bitdepth of the simple +encoding function. + +If, when encoding, you don't want LodePNG to choose the output PNG color type +but control it yourself, you need to set auto_convert in the encoder settings +to false, and specify the color type you want in the LodePNGInfo of the +encoder (including palette: it can generate a palette if auto_convert is true, +otherwise not). + +If the input and output color type differ (whether user chosen or auto chosen), +LodePNG will do a color conversion, which follows the rules below, and may +sometimes result in an error. + +To avoid some confusion: +-the decoder converts from PNG to raw image +-the encoder converts from raw image to PNG +-the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image +-the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG +-when encoding, the color type in LodePNGInfo is ignored if auto_convert + is enabled, it is automatically generated instead +-when decoding, the color type in LodePNGInfo is set by the decoder to that of the original + PNG image, but it can be ignored since the raw image has the color type you requested instead +-if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion + between the color types is done if the color types are supported. If it is not + supported, an error is returned. If the types are the same, no conversion is done. +-even though some conversions aren't supported, LodePNG supports loading PNGs from any + colortype and saving PNGs to any colortype, sometimes it just requires preparing + the raw image correctly before encoding. +-both encoder and decoder use the same color converter. + +The function lodepng_convert does the color conversion. It is available in the +interface but normally isn't needed since the encoder and decoder already call +it. + +Non supported color conversions: +-color to grayscale when non-gray pixels are present: no error is thrown, but +the result will look ugly because only the red channel is taken (it assumes all +three channels are the same in this case so ignores green and blue). The reason +no error is given is to allow converting from three-channel grayscale images to +one-channel even if there are numerical imprecisions. +-anything to palette when the palette does not have an exact match for a from-color +in it: in this case an error is thrown + +Supported color conversions: +-anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA +-any gray or gray+alpha, to gray or gray+alpha +-anything to a palette, as long as the palette has the requested colors in it +-removing alpha channel +-higher to smaller bitdepth, and vice versa + +If you want no color conversion to be done (e.g. for speed or control): +-In the encoder, you can make it save a PNG with any color type by giving the +raw color mode and LodePNGInfo the same color mode, and setting auto_convert to +false. +-In the decoder, you can make it store the pixel data in the same color type +as the PNG has, by setting the color_convert setting to false. Settings in +info_raw are then ignored. + +6.3. padding bits +----------------- + +In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines +have a bit amount that isn't a multiple of 8, then padding bits are used so that each +scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output. +The raw input image you give to the encoder, and the raw output image you get from the decoder +will NOT have these padding bits, e.g. in the case of a 1-bit image with a width +of 7 pixels, the first pixel of the second scanline will the 8th bit of the first byte, +not the first bit of a new byte. + +6.4. A note about 16-bits per channel and endianness +---------------------------------------------------- + +LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like +for any other color format. The 16-bit values are stored in big endian (most +significant byte first) in these arrays. This is the opposite order of the +little endian used by x86 CPU's. + +LodePNG always uses big endian because the PNG file format does so internally. +Conversions to other formats than PNG uses internally are not supported by +LodePNG on purpose, there are myriads of formats, including endianness of 16-bit +colors, the order in which you store R, G, B and A, and so on. Supporting and +converting to/from all that is outside the scope of LodePNG. + +This may mean that, depending on your use case, you may want to convert the big +endian output of LodePNG to little endian with a for loop. This is certainly not +always needed, many applications and libraries support big endian 16-bit colors +anyway, but it means you cannot simply cast the unsigned char* buffer to an +unsigned short* buffer on x86 CPUs. + + +7. error values +--------------- + +All functions in LodePNG that return an error code, return 0 if everything went +OK, or a non-zero code if there was an error. + +The meaning of the LodePNG error values can be retrieved with the function +lodepng_error_text: given the numerical error code, it returns a description +of the error in English as a string. + +Check the implementation of lodepng_error_text to see the meaning of each code. + +It is not recommended to use the numerical values to programmatically make +different decisions based on error types as the numbers are not guaranteed to +stay backwards compatible. They are for human consumption only. Programmatically +only 0 or non-0 matter. + + +8. chunks and PNG editing +------------------------- + +If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG +editor that should follow the rules about handling of unknown chunks, or if your +program is able to read other types of chunks than the ones handled by LodePNG, +then that's possible with the chunk functions of LodePNG. + +A PNG chunk has the following layout: + +4 bytes length +4 bytes type name +length bytes data +4 bytes CRC + +8.1. iterating through chunks +----------------------------- + +If you have a buffer containing the PNG image data, then the first chunk (the +IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the +signature of the PNG and are not part of a chunk. But if you start at byte 8 +then you have a chunk, and can check the following things of it. + +NOTE: none of these functions check for memory buffer boundaries. To avoid +exploits, always make sure the buffer contains all the data of the chunks. +When using lodepng_chunk_next, make sure the returned value is within the +allocated memory. + +unsigned lodepng_chunk_length(const unsigned char* chunk): + +Get the length of the chunk's data. The total chunk length is this length + 12. + +void lodepng_chunk_type(char type[5], const unsigned char* chunk): +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type): + +Get the type of the chunk or compare if it's a certain type + +unsigned char lodepng_chunk_critical(const unsigned char* chunk): +unsigned char lodepng_chunk_private(const unsigned char* chunk): +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk): + +Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are). +Check if the chunk is private (public chunks are part of the standard, private ones not). +Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical +chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your +program doesn't handle that type of unknown chunk. + +unsigned char* lodepng_chunk_data(unsigned char* chunk): +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk): + +Get a pointer to the start of the data of the chunk. + +unsigned lodepng_chunk_check_crc(const unsigned char* chunk): +void lodepng_chunk_generate_crc(unsigned char* chunk): + +Check if the crc is correct or generate a correct one. + +unsigned char* lodepng_chunk_next(unsigned char* chunk): +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk): + +Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these +functions do no boundary checking of the allocated data whatsoever, so make sure there is enough +data available in the buffer to be able to go to the next chunk. + +unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk): +unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length, + const char* type, const unsigned char* data): + +These functions are used to create new chunks that are appended to the data in *out that has +length *outsize. The append function appends an existing chunk to the new data. The create +function creates a new chunk with the given parameters and appends it. Type is the 4-letter +name of the chunk. + +8.2. chunks in info_png +----------------------- + +The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3 +buffers (each with size) to contain 3 types of unknown chunks: +the ones that come before the PLTE chunk, the ones that come between the PLTE +and the IDAT chunks, and the ones that come after the IDAT chunks. +It's necessary to make the distinction between these 3 cases because the PNG +standard forces to keep the ordering of unknown chunks compared to the critical +chunks, but does not force any other ordering rules. + +info_png.unknown_chunks_data[0] is the chunks before PLTE +info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT +info_png.unknown_chunks_data[2] is the chunks after IDAT + +The chunks in these 3 buffers can be iterated through and read by using the same +way described in the previous subchapter. + +When using the decoder to decode a PNG, you can make it store all unknown chunks +if you set the option settings.remember_unknown_chunks to 1. By default, this +option is off (0). + +The encoder will always encode unknown chunks that are stored in the info_png. +If you need it to add a particular chunk that isn't known by LodePNG, you can +use lodepng_chunk_append or lodepng_chunk_create to the chunk data in +info_png.unknown_chunks_data[x]. + +Chunks that are known by LodePNG should not be added in that way. E.g. to make +LodePNG add a bKGD chunk, set background_defined to true and add the correct +parameters there instead. + + +9. compiler support +------------------- + +No libraries other than the current standard C library are needed to compile +LodePNG. For the C++ version, only the standard C++ library is needed on top. +Add the files lodepng.c(pp) and lodepng.h to your project, include +lodepng.h where needed, and your program can read/write PNG files. + +It is compatible with C90 and up, and C++03 and up. + +If performance is important, use optimization when compiling! For both the +encoder and decoder, this makes a large difference. + +Make sure that LodePNG is compiled with the same compiler of the same version +and with the same settings as the rest of the program, or the interfaces with +std::vectors and std::strings in C++ can be incompatible. + +CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets. + +*) gcc and g++ + +LodePNG is developed in gcc so this compiler is natively supported. It gives no +warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++ +version 4.7.1 on Linux, 32-bit and 64-bit. + +*) Clang + +Fully supported and warning-free. + +*) Mingw + +The Mingw compiler (a port of gcc for Windows) should be fully supported by +LodePNG. + +*) Visual Studio and Visual C++ Express Edition + +LodePNG should be warning-free with warning level W4. Two warnings were disabled +with pragmas though: warning 4244 about implicit conversions, and warning 4996 +where it wants to use a non-standard function fopen_s instead of the standard C +fopen. + +Visual Studio may want "stdafx.h" files to be included in each source file and +give an error "unexpected end of file while looking for precompiled header". +This is not standard C++ and will not be added to the stock LodePNG. You can +disable it for lodepng.cpp only by right clicking it, Properties, C/C++, +Precompiled Headers, and set it to Not Using Precompiled Headers there. + +NOTE: Modern versions of VS should be fully supported, but old versions, e.g. +VS6, are not guaranteed to work. + +*) Compilers on Macintosh + +LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for +C and C++. + +*) Other Compilers + +If you encounter problems on any compilers, feel free to let me know and I may +try to fix it if the compiler is modern and standards compliant. + + +10. examples +------------ + +This decoder example shows the most basic usage of LodePNG. More complex +examples can be found on the LodePNG website. + +NOTE: these examples do not support wide-character filenames, you can use an +external method to handle such files and encode or decode in-memory + +10.1. decoder C++ example +------------------------- + +#include "lodepng.h" +#include + +int main(int argc, char *argv[]) { + const char* filename = argc > 1 ? argv[1] : "test.png"; + + //load and decode + std::vector image; + unsigned width, height; + unsigned error = lodepng::decode(image, width, height, filename); + + //if there's an error, display it + if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; + + //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... +} + +10.2. decoder C example +----------------------- + +#include "lodepng.h" + +int main(int argc, char *argv[]) { + unsigned error; + unsigned char* image; + size_t width, height; + const char* filename = argc > 1 ? argv[1] : "test.png"; + + error = lodepng_decode32_file(&image, &width, &height, filename); + + if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error)); + + / * use image here * / + + free(image); + return 0; +} + +11. state settings reference +---------------------------- + +A quick reference of some settings to set on the LodePNGState + +For decoding: + +state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums +state.decoder.zlibsettings.custom_...: use custom inflate function +state.decoder.ignore_crc: ignore CRC checksums +state.decoder.ignore_critical: ignore unknown critical chunks +state.decoder.ignore_end: ignore missing IEND chunk. May fail if this corruption causes other errors +state.decoder.color_convert: convert internal PNG color to chosen one +state.decoder.read_text_chunks: whether to read in text metadata chunks +state.decoder.remember_unknown_chunks: whether to read in unknown chunks +state.info_raw.colortype: desired color type for decoded image +state.info_raw.bitdepth: desired bit depth for decoded image +state.info_raw....: more color settings, see struct LodePNGColorMode +state.info_png....: no settings for decoder but ouput, see struct LodePNGInfo + +For encoding: + +state.encoder.zlibsettings.btype: disable compression by setting it to 0 +state.encoder.zlibsettings.use_lz77: use LZ77 in compression +state.encoder.zlibsettings.windowsize: tweak LZ77 windowsize +state.encoder.zlibsettings.minmatch: tweak min LZ77 length to match +state.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching +state.encoder.zlibsettings.lazymatching: try one more LZ77 matching +state.encoder.zlibsettings.custom_...: use custom deflate function +state.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png +state.encoder.filter_palette_zero: PNG filter strategy for palette +state.encoder.filter_strategy: PNG filter strategy to encode with +state.encoder.force_palette: add palette even if not encoding to one +state.encoder.add_id: add LodePNG identifier and version as a text chunk +state.encoder.text_compression: use compressed text chunks for metadata +state.info_raw.colortype: color type of raw input image you provide +state.info_raw.bitdepth: bit depth of raw input image you provide +state.info_raw: more color settings, see struct LodePNGColorMode +state.info_png.color.colortype: desired color type if auto_convert is false +state.info_png.color.bitdepth: desired bit depth if auto_convert is false +state.info_png.color....: more color settings, see struct LodePNGColorMode +state.info_png....: more PNG related settings, see struct LodePNGInfo + + +12. changes +----------- + +The version number of LodePNG is the date of the change given in the format +yyyymmdd. + +Some changes aren't backwards compatible. Those are indicated with a (!) +symbol. + +Not all changes are listed here, the commit history in github lists more: +https://github.com/lvandeve/lodepng + +*) 6 may 2025: renamed mDCv to mDCV and cLLi to cLLI as per the recent rename + in the draft png third edition spec. Please note that while the third + edition is not finalized, backwards-incompatible changes to its features are + possible. +*) 23 dec 2024: added support for the mDCv and cLLi chunks (for png third + edition spec) +*) 22 dec 2024: added support for the cICP chunk (for png third edition spec) +*) 15 dec 2024: added support for the eXIf chunk (for png third edition spec) +*) 10 apr 2023: faster CRC32 implementation, but with larger lookup table. +*) 13 jun 2022: added support for the sBIT chunk. +*) 09 jan 2022: minor decoder speed improvements. +*) 27 jun 2021: added warnings that file reading/writing functions don't support + wide-character filenames (support for this is not planned, opening files is + not the core part of PNG decoding/decoding and is platform dependent). +*) 17 oct 2020: prevent decoding too large text/icc chunks by default. +*) 06 mar 2020: simplified some of the dynamic memory allocations. +*) 12 jan 2020: (!) added 'end' argument to lodepng_chunk_next to allow correct + overflow checks. +*) 14 aug 2019: around 25% faster decoding thanks to huffman lookup tables. +*) 15 jun 2019: (!) auto_choose_color API changed (for bugfix: don't use palette + if gray ICC profile) and non-ICC LodePNGColorProfile renamed to + LodePNGColorStats. +*) 30 dec 2018: code style changes only: removed newlines before opening braces. +*) 10 sep 2018: added way to inspect metadata chunks without full decoding. +*) 19 aug 2018: (!) fixed color mode bKGD is encoded with and made it use + palette index in case of palette. +*) 10 aug 2018: (!) added support for gAMA, cHRM, sRGB and iCCP chunks. This + change is backwards compatible unless you relied on unknown_chunks for those. +*) 11 jun 2018: less restrictive check for pixel size integer overflow +*) 14 jan 2018: allow optionally ignoring a few more recoverable errors +*) 17 sep 2017: fix memory leak for some encoder input error cases +*) 27 nov 2016: grey+alpha auto color model detection bugfix +*) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort). +*) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within + the limits of pure C90). +*) 08 dec 2015: Made load_file function return error if file can't be opened. +*) 24 oct 2015: Bugfix with decoding to palette output. +*) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding. +*) 24 aug 2014: Moved to github +*) 23 aug 2014: Reduced needless memory usage of decoder. +*) 28 jun 2014: Removed fix_png setting, always support palette OOB for + simplicity. Made ColorProfile public. +*) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization. +*) 22 dec 2013: Power of two windowsize required for optimization. +*) 15 apr 2013: Fixed bug with LAC_ALPHA and color key. +*) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png). +*) 11 mar 2013: (!) Bugfix with custom free. Changed from "my" to "lodepng_" + prefix for the custom allocators and made it possible with a new #define to + use custom ones in your project without needing to change lodepng's code. +*) 28 jan 2013: Bugfix with color key. +*) 27 oct 2012: Tweaks in text chunk keyword length error handling. +*) 8 oct 2012: (!) Added new filter strategy (entropy) and new auto color mode. + (no palette). Better deflate tree encoding. New compression tweak settings. + Faster color conversions while decoding. Some internal cleanups. +*) 23 sep 2012: Reduced warnings in Visual Studio a little bit. +*) 1 sep 2012: (!) Removed #define's for giving custom (de)compression functions + and made it work with function pointers instead. +*) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc + and free functions and toggle #defines from compiler flags. Small fixes. +*) 6 may 2012: (!) Made plugging in custom zlib/deflate functions more flexible. +*) 22 apr 2012: (!) Made interface more consistent, renaming a lot. Removed + redundant C++ codec classes. Reduced amount of structs. Everything changed, + but it is cleaner now imho and functionality remains the same. Also fixed + several bugs and shrunk the implementation code. Made new samples. +*) 6 nov 2011: (!) By default, the encoder now automatically chooses the best + PNG color model and bit depth, based on the amount and type of colors of the + raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color. +*) 9 oct 2011: simpler hash chain implementation for the encoder. +*) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching. +*) 23 aug 2011: tweaked the zlib compression parameters after benchmarking. + A bug with the PNG filtertype heuristic was fixed, so that it chooses much + better ones (it's quite significant). A setting to do an experimental, slow, + brute force search for PNG filter types is added. +*) 17 aug 2011: (!) changed some C zlib related function names. +*) 16 aug 2011: made the code less wide (max 120 characters per line). +*) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors. +*) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled. +*) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman + to optimize long sequences of zeros. +*) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and + LodePNG_InfoColor_canHaveAlpha functions for convenience. +*) 7 nov 2010: added LodePNG_error_text function to get error code description. +*) 30 oct 2010: made decoding slightly faster +*) 26 oct 2010: (!) changed some C function and struct names (more consistent). + Reorganized the documentation and the declaration order in the header. +*) 08 aug 2010: only changed some comments and external samples. +*) 05 jul 2010: fixed bug thanks to warnings in the new gcc version. +*) 14 mar 2010: fixed bug where too much memory was allocated for char buffers. +*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could + read by ignoring the problem but windows apps couldn't. +*) 06 jun 2008: added more error checks for out of memory cases. +*) 26 apr 2008: added a few more checks here and there to ensure more safety. +*) 06 mar 2008: crash with encoding of strings fixed +*) 02 feb 2008: support for international text chunks added (iTXt) +*) 23 jan 2008: small cleanups, and #defines to divide code in sections +*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor. +*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder. +*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added + Also various fixes, such as in the deflate and the padding bits code. +*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved + filtering code of encoder. +*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A + C++ wrapper around this provides an interface almost identical to before. + Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code + are together in these files but it works both for C and C++ compilers. +*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks +*) 30 aug 2007: bug fixed which makes this Borland C++ compatible +*) 09 aug 2007: some VS2005 warnings removed again +*) 21 jul 2007: deflate code placed in new namespace separate from zlib code +*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images +*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing + invalid std::vector element [0] fixed, and level 3 and 4 warnings removed +*) 02 jun 2007: made the encoder add a tag with version by default +*) 27 may 2007: zlib and png code separated (but still in the same file), + simple encoder/decoder functions added for more simple usage cases +*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69), + moved some examples from here to lodepng_examples.cpp +*) 12 may 2007: palette decoding bug fixed +*) 24 apr 2007: changed the license from BSD to the zlib license +*) 11 mar 2007: very simple addition: ability to encode bKGD chunks. +*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding + palettized PNG images. Plus little interface change with palette and texts. +*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes. + Fixed a bug where the end code of a block had length 0 in the Huffman tree. +*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented + and supported by the encoder, resulting in smaller PNGs at the output. +*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone. +*) 24 jan 2007: gave encoder an error interface. Added color conversion from any + greyscale type to 8-bit greyscale with or without alpha. +*) 21 jan 2007: (!) Totally changed the interface. It allows more color types + to convert to and is more uniform. See the manual for how it works now. +*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days: + encode/decode custom tEXt chunks, separate classes for zlib & deflate, and + at last made the decoder give errors for incorrect Adler32 or Crc. +*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel. +*) 29 dec 2006: Added support for encoding images without alpha channel, and + cleaned out code as well as making certain parts faster. +*) 28 dec 2006: Added "Settings" to the encoder. +*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now. + Removed some code duplication in the decoder. Fixed little bug in an example. +*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter. + Fixed a bug of the decoder with 16-bit per color. +*) 15 oct 2006: Changed documentation structure +*) 09 oct 2006: Encoder class added. It encodes a valid PNG image from the + given image buffer, however for now it's not compressed. +*) 08 sep 2006: (!) Changed to interface with a Decoder class +*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different + way. Renamed decodePNG to decodePNGGeneric. +*) 29 jul 2006: (!) Changed the interface: image info is now returned as a + struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy. +*) 28 jul 2006: Cleaned the code and added new error checks. + Corrected terminology "deflate" into "inflate". +*) 23 jun 2006: Added SDL example in the documentation in the header, this + example allows easy debugging by displaying the PNG and its transparency. +*) 22 jun 2006: (!) Changed way to obtain error value. Added + loadFile function for convenience. Made decodePNG32 faster. +*) 21 jun 2006: (!) Changed type of info vector to unsigned. + Changed position of palette in info vector. Fixed an important bug that + happened on PNGs with an uncompressed block. +*) 16 jun 2006: Internally changed unsigned into unsigned where + needed, and performed some optimizations. +*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them + in LodePNG namespace. Changed the order of the parameters. Rewrote the + documentation in the header. Renamed files to lodepng.cpp and lodepng.h +*) 22 apr 2006: Optimized and improved some code +*) 07 sep 2005: (!) Changed to std::vector interface +*) 12 aug 2005: Initial release (C++, decoder only) +*/ diff --git a/components/pico8/femto8/src/lua/.gitignore b/components/pico8/femto8/src/lua/.gitignore new file mode 100644 index 00000000..848dd0ba --- /dev/null +++ b/components/pico8/femto8/src/lua/.gitignore @@ -0,0 +1,3 @@ +*.o +*.a +lua diff --git a/components/pico8/femto8/src/lua/fix32.h b/components/pico8/femto8/src/lua/fix32.h new file mode 100644 index 00000000..5c98a45d --- /dev/null +++ b/components/pico8/femto8/src/lua/fix32.h @@ -0,0 +1,158 @@ +/* + * fix32.h - Pure C 16.16 fixed-point arithmetic + * + * Port of z8::fix32 from femto8 (C++ operator overloads -> C inline functions). + * All PICO-8 numbers are stored as int32_t with 16 integer bits and 16 fractional bits. + */ + +#ifndef FIX32_H +#define FIX32_H + +#include +#include + +typedef int32_t fix32_t; + +/* Constants */ +#define FIX32_ZERO ((fix32_t)0) +#define FIX32_ONE ((fix32_t)0x00010000) +#define FIX32_HALF ((fix32_t)0x00008000) +#define FIX32_NEG_ONE ((fix32_t)0xFFFF0000) +#define FIX32_MAX ((fix32_t)0x7FFFFFFF) +#define FIX32_MIN ((fix32_t)0x80000001) /* not 0x80000000, per PICO-8 */ + +/* Construction */ +static inline fix32_t fix32_from_int(int x) { return (fix32_t)x << 16; } +static inline fix32_t fix32_from_double(double d) { return (fix32_t)(int64_t)(d * 65536.0); } +static inline fix32_t fix32_from_bits(int32_t b) { return b; } + +/* Conversion */ +static inline int fix32_to_int(fix32_t x) { return x >> 16; } +static inline double fix32_to_double(fix32_t x) { return (double)x / 65536.0; } +static inline int32_t fix32_bits(fix32_t x) { return x; } + +/* Comparisons */ +static inline int fix32_eq(fix32_t a, fix32_t b) { return a == b; } +static inline int fix32_ne(fix32_t a, fix32_t b) { return a != b; } +static inline int fix32_lt(fix32_t a, fix32_t b) { return a < b; } +static inline int fix32_gt(fix32_t a, fix32_t b) { return a > b; } +static inline int fix32_le(fix32_t a, fix32_t b) { return a <= b; } +static inline int fix32_ge(fix32_t a, fix32_t b) { return a >= b; } +static inline int fix32_bool(fix32_t a) { return a != 0; } + +/* Basic arithmetic - use unsigned to avoid signed overflow UB */ +static inline fix32_t fix32_add(fix32_t a, fix32_t b) { return (fix32_t)((uint32_t)a + (uint32_t)b); } +static inline fix32_t fix32_sub(fix32_t a, fix32_t b) { return (fix32_t)((uint32_t)a - (uint32_t)b); } +static inline fix32_t fix32_neg(fix32_t a) { return (fix32_t)(-(uint32_t)a); } + +static inline fix32_t fix32_mul(fix32_t a, fix32_t b) { + return (fix32_t)((int64_t)a * b >> 16); +} + +static inline fix32_t fix32_div(fix32_t a, fix32_t b) { + /* Special case: 0x8000/0x1 = 0x8000, not 0x8000.0001 */ + if (b == FIX32_ONE) + return a; + + if (b) { + int64_t result = (int64_t)a * 0x10000 / b; + int64_t abs_result = result < 0 ? -result : result; + if (abs_result <= (int64_t)0x7FFFFFFFU) + return (fix32_t)result; + } + + /* Return 0x8000.0001 (not 0x8000.0000) for -Inf, just like PICO-8 */ + return (a ^ b) >= 0 ? (fix32_t)0x7FFFFFFFU : (fix32_t)0x80000001U; +} + +static inline fix32_t fix32_mod(fix32_t a, fix32_t b) { + /* PICO-8 always returns positive values */ + fix32_t abs_b = b < 0 ? -b : b; + /* PICO-8 0.2.5f: x % 0 gives 0 */ + if (!abs_b) return 0; + int32_t result = a % abs_b; + return result >= 0 ? result : result + abs_b; +} + +static inline fix32_t fix32_idiv(fix32_t a, fix32_t b) { + fix32_t d = fix32_div(a, b); + return d & (fix32_t)0xFFFF0000; /* floor = mask off fraction */ +} + +/* Bitwise */ +static inline fix32_t fix32_band(fix32_t a, fix32_t b) { return a & b; } +static inline fix32_t fix32_bor(fix32_t a, fix32_t b) { return a | b; } +static inline fix32_t fix32_bxor(fix32_t a, fix32_t b) { return a ^ b; } +static inline fix32_t fix32_bnot(fix32_t a) { return ~a; } + +/* Forward declaration for mutual recursion */ +static inline fix32_t fix32_lshr(fix32_t x, int y); + +static inline fix32_t fix32_shl(fix32_t x, int y) { + /* Negative y = lshr instead */ + if (y < 0) return fix32_lshr(x, -y); + return y >= 32 ? 0 : x << y; +} + +static inline fix32_t fix32_shr(fix32_t x, int y) { + /* Arithmetic right shift. Negative y = left shift */ + if (y < 0) return fix32_shl(x, -y); + int shift = y < 31 ? y : 31; + return x >> shift; +} + +static inline fix32_t fix32_lshr(fix32_t x, int y) { + /* Logical (unsigned) right shift. Negative y = left shift */ + if (y < 0) return fix32_shl(x, -y); + return y >= 32 ? 0 : (fix32_t)((uint32_t)x >> y); +} + +static inline fix32_t fix32_rotl(fix32_t x, int y) { + y &= 0x1f; + return (x << y) | (fix32_t)((uint32_t)x >> (32 - y)); +} + +static inline fix32_t fix32_rotr(fix32_t x, int y) { + y &= 0x1f; + return (fix32_t)((uint32_t)x >> y) | (x << (32 - y)); +} + +/* Math functions */ + +/* PICO-8 0.2.3: abs(0x8000) should be 0x7fff.ffff */ +static inline fix32_t fix32_abs(fix32_t a) { + if (a >= 0) return a; + if ((a << 1) == 0) return ~a; /* 0x80000000 -> 0x7FFFFFFF */ + return -a; +} + +static inline fix32_t fix32_min(fix32_t a, fix32_t b) { return a < b ? a : b; } +static inline fix32_t fix32_max(fix32_t a, fix32_t b) { return a > b ? a : b; } + +static inline fix32_t fix32_mid(fix32_t a, fix32_t b, fix32_t c) { + if (a > b) { fix32_t t = a; a = b; b = t; } + /* now a <= b */ + if (c <= a) return a; + if (c >= b) return b; + return c; +} + +static inline fix32_t fix32_flr(fix32_t x) { + return x & (fix32_t)0xFFFF0000; +} + +static inline fix32_t fix32_ceil(fix32_t x) { + return fix32_neg(fix32_flr(fix32_neg(x))); +} + +static inline fix32_t fix32_sgn(fix32_t x) { + if (x > 0) return FIX32_ONE; + if (x < 0) return FIX32_NEG_ONE; + return FIX32_ONE; /* PICO-8: sgn(0) = 1 */ +} + +static inline fix32_t fix32_pow(fix32_t x, fix32_t y) { + return fix32_from_double(pow(fix32_to_double(x), fix32_to_double(y))); +} + +#endif /* FIX32_H */ diff --git a/components/pico8/femto8/src/lua/lapi.c b/components/pico8/femto8/src/lua/lapi.c new file mode 100644 index 00000000..e1e43c95 --- /dev/null +++ b/components/pico8/femto8/src/lua/lapi.c @@ -0,0 +1,1293 @@ +/* +** $Id: lapi.c,v 2.171 2013/03/16 21:10:18 roberto Exp $ +** Lua API +** See Copyright Notice in lua.h +*/ + + +#include +#include + +#define lapi_c +#define LUA_CORE + +#include "lua.h" + +#include "lapi.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lundump.h" +#include "lvm.h" + + + +const char lua_ident[] = + "$LuaVersion: " LUA_COPYRIGHT " $" + "$LuaAuthors: " LUA_AUTHORS " $"; + + +/* value at a non-valid index */ +#define NONVALIDVALUE cast(TValue *, luaO_nilobject) + +/* corresponding test */ +#define isvalid(o) ((o) != luaO_nilobject) + +/* test for pseudo index */ +#define ispseudo(i) ((i) <= LUA_REGISTRYINDEX) + +/* test for valid but not pseudo index */ +#define isstackindex(i, o) (isvalid(o) && !ispseudo(i)) + +#define api_checkvalidindex(L, o) api_check(L, isvalid(o), "invalid index") + +#define api_checkstackindex(L, i, o) \ + api_check(L, isstackindex(i, o), "index not in the stack") + + +static TValue *index2addr (lua_State *L, int idx) { + CallInfo *ci = L->ci; + if (idx > 0) { + TValue *o = ci->func + idx; + api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index"); + if (o >= L->top) return NONVALIDVALUE; + else return o; + } + else if (!ispseudo(idx)) { /* negative index */ + api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index"); + return L->top + idx; + } + else if (idx == LUA_REGISTRYINDEX) + return &G(L)->l_registry; + else { /* upvalues */ + idx = LUA_REGISTRYINDEX - idx; + api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large"); + if (ttislcf(ci->func)) /* light C function? */ + return NONVALIDVALUE; /* it has no upvalues */ + else { + CClosure *func = clCvalue(ci->func); + return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : NONVALIDVALUE; + } + } +} + + +/* +** to be called by 'lua_checkstack' in protected mode, to grow stack +** capturing memory errors +*/ +static void growstack (lua_State *L, void *ud) { + int size = *(int *)ud; + luaD_growstack(L, size); +} + + +LUA_API int lua_checkstack (lua_State *L, int size) { + int res; + CallInfo *ci = L->ci; + lua_lock(L); + if (L->stack_last - L->top > size) /* stack large enough? */ + res = 1; /* yes; check is OK */ + else { /* no; need to grow stack */ + int inuse = cast_int(L->top - L->stack) + EXTRA_STACK; + if (inuse > LUAI_MAXSTACK - size) /* can grow without overflow? */ + res = 0; /* no */ + else /* try to grow stack */ + res = (luaD_rawrunprotected(L, &growstack, &size) == LUA_OK); + } + if (res && ci->top < L->top + size) + ci->top = L->top + size; /* adjust frame top */ + lua_unlock(L); + return res; +} + + +LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) { + int i; + if (from == to) return; + lua_lock(to); + api_checknelems(from, n); + api_check(from, G(from) == G(to), "moving among independent states"); + api_check(from, to->ci->top - to->top >= n, "not enough elements to move"); + from->top -= n; + for (i = 0; i < n; i++) { + setobj2s(to, to->top++, from->top + i); + } + lua_unlock(to); +} + + +LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) { + lua_CFunction old; + lua_lock(L); + old = G(L)->panic; + G(L)->panic = panicf; + lua_unlock(L); + return old; +} + + +LUA_API void lua_setpico8memory (lua_State *L, unsigned char const *p) { + lua_lock(L); + G(L)->pico8memory = p; + lua_unlock(L); +} + + +LUA_API const lua_Number *lua_version (lua_State *L) { + static lua_Number version; + version = LUA_VERSION_NUM; + if (L == NULL) return &version; + else return G(L)->version; +} + + + +/* +** basic stack manipulation +*/ + + +/* +** convert an acceptable stack index into an absolute index +*/ +LUA_API int lua_absindex (lua_State *L, int idx) { + return (idx > 0 || ispseudo(idx)) + ? idx + : cast_int(L->top - L->ci->func + idx); +} + + +LUA_API int lua_gettop (lua_State *L) { + return cast_int(L->top - (L->ci->func + 1)); +} + + +LUA_API void lua_settop (lua_State *L, int idx) { + StkId func = L->ci->func; + lua_lock(L); + if (idx >= 0) { + api_check(L, idx <= L->stack_last - (func + 1), "new top too large"); + while (L->top < (func + 1) + idx) + setnilvalue(L->top++); + L->top = (func + 1) + idx; + } + else { + api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top"); + L->top += idx+1; /* `subtract' index (index is negative) */ + } + lua_unlock(L); +} + + +LUA_API void lua_remove (lua_State *L, int idx) { + StkId p; + lua_lock(L); + p = index2addr(L, idx); + api_checkstackindex(L, idx, p); + while (++p < L->top) setobjs2s(L, p-1, p); + L->top--; + lua_unlock(L); +} + + +LUA_API void lua_insert (lua_State *L, int idx) { + StkId p; + StkId q; + lua_lock(L); + p = index2addr(L, idx); + api_checkstackindex(L, idx, p); + for (q = L->top; q > p; q--) /* use L->top as a temporary */ + setobjs2s(L, q, q - 1); + setobjs2s(L, p, L->top); + lua_unlock(L); +} + + +static void moveto (lua_State *L, TValue *fr, int idx) { + TValue *to = index2addr(L, idx); + api_checkvalidindex(L, to); + setobj(L, to, fr); + if (idx < LUA_REGISTRYINDEX) /* function upvalue? */ + luaC_barrier(L, clCvalue(L->ci->func), fr); + /* LUA_REGISTRYINDEX does not need gc barrier + (collector revisits it before finishing collection) */ +} + + +LUA_API void lua_replace (lua_State *L, int idx) { + lua_lock(L); + api_checknelems(L, 1); + moveto(L, L->top - 1, idx); + L->top--; + lua_unlock(L); +} + + +LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) { + TValue *fr; + lua_lock(L); + fr = index2addr(L, fromidx); + moveto(L, fr, toidx); + lua_unlock(L); +} + + +LUA_API void lua_pushvalue (lua_State *L, int idx) { + lua_lock(L); + setobj2s(L, L->top, index2addr(L, idx)); + api_incr_top(L); + lua_unlock(L); +} + + + +/* +** access functions (stack -> C) +*/ + + +LUA_API int lua_type (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + return (isvalid(o) ? ttypenv(o) : LUA_TNONE); +} + + +LUA_API const char *lua_typename (lua_State *L, int t) { + UNUSED(L); + return ttypename(t); +} + + +LUA_API int lua_iscfunction (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + return (ttislcf(o) || (ttisCclosure(o))); +} + + +LUA_API int lua_isnumber (lua_State *L, int idx) { + TValue n; + const TValue *o = index2addr(L, idx); + return tonumber(o, &n); +} + + +LUA_API int lua_isstring (lua_State *L, int idx) { + int t = lua_type(L, idx); + return (t == LUA_TSTRING || t == LUA_TNUMBER); +} + + +LUA_API int lua_isuserdata (lua_State *L, int idx) { + const TValue *o = index2addr(L, idx); + return (ttisuserdata(o) || ttislightuserdata(o)); +} + + +LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { + StkId o1 = index2addr(L, index1); + StkId o2 = index2addr(L, index2); + return (isvalid(o1) && isvalid(o2)) ? luaV_rawequalobj(o1, o2) : 0; +} + + +LUA_API void lua_arith (lua_State *L, int op) { + StkId o1; /* 1st operand */ + StkId o2; /* 2nd operand */ + lua_lock(L); + if (op != LUA_OPUNM && op != LUA_OPBNOT && op != LUA_OPPEEK && + op != LUA_OPPEEK2 && op != LUA_OPPEEK4) /* all other operations expect two operands */ + api_checknelems(L, 2); + else { /* for unary minus, add fake 2nd operand */ + api_checknelems(L, 1); + setobjs2s(L, L->top, L->top - 1); + L->top++; + } + o1 = L->top - 2; + o2 = L->top - 1; + if (ttisnumber(o1) && ttisnumber(o2)) { + setnvalue(o1, luaO_arith(L, op, nvalue(o1), nvalue(o2))); + } + else + luaV_arith(L, o1, o1, o2, cast(TMS, op - LUA_OPADD + TM_ADD)); + L->top--; + lua_unlock(L); +} + + +LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) { + StkId o1, o2; + int i = 0; + lua_lock(L); /* may call tag method */ + o1 = index2addr(L, index1); + o2 = index2addr(L, index2); + if (isvalid(o1) && isvalid(o2)) { + switch (op) { + case LUA_OPEQ: i = equalobj(L, o1, o2); break; + case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break; + case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break; + default: api_check(L, 0, "invalid option"); + } + } + lua_unlock(L); + return i; +} + + +LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *isnum) { + TValue n; + const TValue *o = index2addr(L, idx); + if (tonumber(o, &n)) { + if (isnum) *isnum = 1; + return nvalue(o); + } + else { + if (isnum) *isnum = 0; + return 0; + } +} + + +LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *isnum) { + TValue n; + const TValue *o = index2addr(L, idx); + if (tonumber(o, &n)) { + lua_Integer res; + lua_Number num = nvalue(o); + lua_number2integer(res, num); + if (isnum) *isnum = 1; + return res; + } + else { + if (isnum) *isnum = 0; + return 0; + } +} + + +LUA_API lua_Unsigned lua_tounsignedx (lua_State *L, int idx, int *isnum) { + TValue n; + const TValue *o = index2addr(L, idx); + if (tonumber(o, &n)) { + lua_Unsigned res; + lua_Number num = nvalue(o); + lua_number2unsigned(res, num); + if (isnum) *isnum = 1; + return res; + } + else { + if (isnum) *isnum = 0; + return 0; + } +} + + +LUA_API int lua_toboolean (lua_State *L, int idx) { + const TValue *o = index2addr(L, idx); + return !l_isfalse(o); +} + + +LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { + StkId o = index2addr(L, idx); + if (!ttisstring(o)) { + lua_lock(L); /* `luaV_tostring' may create a new string */ + if (!luaV_tostring(L, o)) { /* conversion failed? */ + if (len != NULL) *len = 0; + lua_unlock(L); + return NULL; + } + luaC_checkGC(L); + o = index2addr(L, idx); /* previous call may reallocate the stack */ + lua_unlock(L); + } + if (len != NULL) *len = tsvalue(o)->len; + return svalue(o); +} + + +LUA_API size_t lua_rawlen (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + switch (ttypenv(o)) { + case LUA_TSTRING: return tsvalue(o)->len; + case LUA_TUSERDATA: return uvalue(o)->len; + case LUA_TTABLE: return luaH_getn(hvalue(o)); + default: return 0; + } +} + + +LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + if (ttislcf(o)) return fvalue(o); + else if (ttisCclosure(o)) + return clCvalue(o)->f; + else return NULL; /* not a C function */ +} + + +LUA_API void *lua_touserdata (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + switch (ttypenv(o)) { + case LUA_TUSERDATA: return (rawuvalue(o) + 1); + case LUA_TLIGHTUSERDATA: return pvalue(o); + default: return NULL; + } +} + + +LUA_API lua_State *lua_tothread (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + return (!ttisthread(o)) ? NULL : thvalue(o); +} + + +LUA_API const void *lua_topointer (lua_State *L, int idx) { + StkId o = index2addr(L, idx); + switch (ttype(o)) { + case LUA_TTABLE: return hvalue(o); + case LUA_TLCL: return clLvalue(o); + case LUA_TCCL: return clCvalue(o); + case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o))); + case LUA_TTHREAD: return thvalue(o); + case LUA_TUSERDATA: + case LUA_TLIGHTUSERDATA: + return lua_touserdata(L, idx); + default: return NULL; + } +} + + + +/* +** push functions (C -> stack) +*/ + + +LUA_API void lua_pushnil (lua_State *L) { + lua_lock(L); + setnilvalue(L->top); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { + lua_lock(L); + setnvalue(L->top, n); + luai_checknum(L, L->top, + luaG_runerror(L, "C API - attempt to push a signaling NaN")); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { + lua_lock(L); + setnvalue(L->top, cast_num(n)); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushunsigned (lua_State *L, lua_Unsigned u) { + lua_Number n; + lua_lock(L); + n = lua_unsigned2number(u); + setnvalue(L->top, n); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) { + TString *ts; + lua_lock(L); + luaC_checkGC(L); + ts = luaS_newlstr(L, s, len); + setsvalue2s(L, L->top, ts); + api_incr_top(L); + lua_unlock(L); + return getstr(ts); +} + + +LUA_API const char *lua_pushstring (lua_State *L, const char *s) { + if (s == NULL) { + lua_pushnil(L); + return NULL; + } + else { + TString *ts; + lua_lock(L); + luaC_checkGC(L); + ts = luaS_new(L, s); + setsvalue2s(L, L->top, ts); + api_incr_top(L); + lua_unlock(L); + return getstr(ts); + } +} + + +LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, + va_list argp) { + const char *ret; + lua_lock(L); + luaC_checkGC(L); + ret = luaO_pushvfstring(L, fmt, argp); + lua_unlock(L); + return ret; +} + + +LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { + const char *ret; + va_list argp; + lua_lock(L); + luaC_checkGC(L); + va_start(argp, fmt); + ret = luaO_pushvfstring(L, fmt, argp); + va_end(argp); + lua_unlock(L); + return ret; +} + + +LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { + lua_lock(L); + if (n == 0) { + setfvalue(L->top, fn); + } + else { + Closure *cl; + api_checknelems(L, n); + api_check(L, n <= MAXUPVAL, "upvalue index too large"); + luaC_checkGC(L); + cl = luaF_newCclosure(L, n); + cl->c.f = fn; + L->top -= n; + while (n--) + setobj2n(L, &cl->c.upvalue[n], L->top + n); + setclCvalue(L, L->top, cl); + } + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushboolean (lua_State *L, int b) { + lua_lock(L); + setbvalue(L->top, (b != 0)); /* ensure that true is 1 */ + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { + lua_lock(L); + setpvalue(L->top, p); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API int lua_pushthread (lua_State *L) { + lua_lock(L); + setthvalue(L, L->top, L); + api_incr_top(L); + lua_unlock(L); + return (G(L)->mainthread == L); +} + + + +/* +** get functions (Lua -> stack) +*/ + + +LUA_API void lua_getglobal (lua_State *L, const char *var) { + Table *reg = hvalue(&G(L)->l_registry); + const TValue *gt; /* global table */ + lua_lock(L); + gt = luaH_getint(reg, LUA_RIDX_GLOBALS); + setsvalue2s(L, L->top++, luaS_new(L, var)); + luaV_gettable(L, gt, L->top - 1, L->top - 1); + lua_unlock(L); +} + + +LUA_API void lua_gettable (lua_State *L, int idx) { + StkId t; + lua_lock(L); + t = index2addr(L, idx); + luaV_gettable(L, t, L->top - 1, L->top - 1); + lua_unlock(L); +} + + +LUA_API void lua_getfield (lua_State *L, int idx, const char *k) { + StkId t; + lua_lock(L); + t = index2addr(L, idx); + setsvalue2s(L, L->top, luaS_new(L, k)); + api_incr_top(L); + luaV_gettable(L, t, L->top - 1, L->top - 1); + lua_unlock(L); +} + + +LUA_API void lua_rawget (lua_State *L, int idx) { + StkId t; + lua_lock(L); + t = index2addr(L, idx); + api_check(L, ttistable(t), "table expected"); + setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1)); + lua_unlock(L); +} + + +LUA_API void lua_rawgeti (lua_State *L, int idx, int n) { + StkId t; + lua_lock(L); + t = index2addr(L, idx); + api_check(L, ttistable(t), "table expected"); + setobj2s(L, L->top, luaH_getint(hvalue(t), n)); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_rawgetp (lua_State *L, int idx, const void *p) { + StkId t; + TValue k; + lua_lock(L); + t = index2addr(L, idx); + api_check(L, ttistable(t), "table expected"); + setpvalue(&k, cast(void *, p)); + setobj2s(L, L->top, luaH_get(hvalue(t), &k)); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_createtable (lua_State *L, int narray, int nrec) { + Table *t; + lua_lock(L); + luaC_checkGC(L); + t = luaH_new(L); + sethvalue(L, L->top, t); + api_incr_top(L); + if (narray > 0 || nrec > 0) + luaH_resize(L, t, narray, nrec); + lua_unlock(L); +} + + +LUA_API int lua_getmetatable (lua_State *L, int objindex) { + const TValue *obj; + Table *mt = NULL; + int res; + lua_lock(L); + obj = index2addr(L, objindex); + switch (ttypenv(obj)) { + case LUA_TTABLE: + mt = hvalue(obj)->metatable; + break; + case LUA_TUSERDATA: + mt = uvalue(obj)->metatable; + break; + default: + mt = G(L)->mt[ttypenv(obj)]; + break; + } + if (mt == NULL) + res = 0; + else { + sethvalue(L, L->top, mt); + api_incr_top(L); + res = 1; + } + lua_unlock(L); + return res; +} + + +LUA_API void lua_getuservalue (lua_State *L, int idx) { + StkId o; + lua_lock(L); + o = index2addr(L, idx); + api_check(L, ttisuserdata(o), "userdata expected"); + if (uvalue(o)->env) { + sethvalue(L, L->top, uvalue(o)->env); + } else + setnilvalue(L->top); + api_incr_top(L); + lua_unlock(L); +} + + +/* +** set functions (stack -> Lua) +*/ + + +LUA_API void lua_setglobal (lua_State *L, const char *var) { + Table *reg = hvalue(&G(L)->l_registry); + const TValue *gt; /* global table */ + lua_lock(L); + api_checknelems(L, 1); + gt = luaH_getint(reg, LUA_RIDX_GLOBALS); + setsvalue2s(L, L->top++, luaS_new(L, var)); + luaV_settable(L, gt, L->top - 1, L->top - 2); + L->top -= 2; /* pop value and key */ + lua_unlock(L); +} + + +LUA_API void lua_settable (lua_State *L, int idx) { + StkId t; + lua_lock(L); + api_checknelems(L, 2); + t = index2addr(L, idx); + luaV_settable(L, t, L->top - 2, L->top - 1); + L->top -= 2; /* pop index and value */ + lua_unlock(L); +} + + +LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { + StkId t; + lua_lock(L); + api_checknelems(L, 1); + t = index2addr(L, idx); + setsvalue2s(L, L->top++, luaS_new(L, k)); + luaV_settable(L, t, L->top - 1, L->top - 2); + L->top -= 2; /* pop value and key */ + lua_unlock(L); +} + + +LUA_API void lua_rawset (lua_State *L, int idx) { + StkId t; + lua_lock(L); + api_checknelems(L, 2); + t = index2addr(L, idx); + api_check(L, ttistable(t), "table expected"); + setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1); + invalidateTMcache(hvalue(t)); + luaC_barrierback(L, gcvalue(t), L->top-1); + L->top -= 2; + lua_unlock(L); +} + + +LUA_API void lua_rawseti (lua_State *L, int idx, int n) { + StkId t; + lua_lock(L); + api_checknelems(L, 1); + t = index2addr(L, idx); + api_check(L, ttistable(t), "table expected"); + luaH_setint(L, hvalue(t), n, L->top - 1); + luaC_barrierback(L, gcvalue(t), L->top-1); + L->top--; + lua_unlock(L); +} + + +LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) { + StkId t; + TValue k; + lua_lock(L); + api_checknelems(L, 1); + t = index2addr(L, idx); + api_check(L, ttistable(t), "table expected"); + setpvalue(&k, cast(void *, p)); + setobj2t(L, luaH_set(L, hvalue(t), &k), L->top - 1); + luaC_barrierback(L, gcvalue(t), L->top - 1); + L->top--; + lua_unlock(L); +} + + +LUA_API int lua_setmetatable (lua_State *L, int objindex) { + TValue *obj; + Table *mt; + lua_lock(L); + api_checknelems(L, 1); + obj = index2addr(L, objindex); + if (ttisnil(L->top - 1)) + mt = NULL; + else { + api_check(L, ttistable(L->top - 1), "table expected"); + mt = hvalue(L->top - 1); + } + switch (ttypenv(obj)) { + case LUA_TTABLE: { + hvalue(obj)->metatable = mt; + if (mt) { + luaC_objbarrierback(L, gcvalue(obj), mt); + luaC_checkfinalizer(L, gcvalue(obj), mt); + } + break; + } + case LUA_TUSERDATA: { + uvalue(obj)->metatable = mt; + if (mt) { + luaC_objbarrier(L, rawuvalue(obj), mt); + luaC_checkfinalizer(L, gcvalue(obj), mt); + } + break; + } + default: { + G(L)->mt[ttypenv(obj)] = mt; + break; + } + } + L->top--; + lua_unlock(L); + return 1; +} + + +LUA_API void lua_setuservalue (lua_State *L, int idx) { + StkId o; + lua_lock(L); + api_checknelems(L, 1); + o = index2addr(L, idx); + api_check(L, ttisuserdata(o), "userdata expected"); + if (ttisnil(L->top - 1)) + uvalue(o)->env = NULL; + else { + api_check(L, ttistable(L->top - 1), "table expected"); + uvalue(o)->env = hvalue(L->top - 1); + luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1)); + } + L->top--; + lua_unlock(L); +} + + +/* +** `load' and `call' functions (run Lua code) +*/ + + +#define checkresults(L,na,nr) \ + api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \ + "results from function overflow current stack size") + + +LUA_API int lua_getctx (lua_State *L, int *ctx) { + if (L->ci->callstatus & CIST_YIELDED) { + if (ctx) *ctx = L->ci->u.c.ctx; + return L->ci->u.c.status; + } + else return LUA_OK; +} + + +LUA_API void lua_callk (lua_State *L, int nargs, int nresults, int ctx, + lua_CFunction k) { + StkId func; + lua_lock(L); + api_check(L, k == NULL || !isLua(L->ci), + "cannot use continuations inside hooks"); + api_checknelems(L, nargs+1); + api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); + checkresults(L, nargs, nresults); + func = L->top - (nargs+1); + if (k != NULL && L->nny == 0) { /* need to prepare continuation? */ + L->ci->u.c.k = k; /* save continuation */ + L->ci->u.c.ctx = ctx; /* save context */ + luaD_call(L, func, nresults, 1); /* do the call */ + } + else /* no continuation or no yieldable */ + luaD_call(L, func, nresults, 0); /* just do the call */ + adjustresults(L, nresults); + lua_unlock(L); +} + + + +/* +** Execute a protected call. +*/ +struct CallS { /* data to `f_call' */ + StkId func; + int nresults; +}; + + +static void f_call (lua_State *L, void *ud) { + struct CallS *c = cast(struct CallS *, ud); + luaD_call(L, c->func, c->nresults, 0); +} + + + +LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc, + int ctx, lua_CFunction k) { + struct CallS c; + int status; + ptrdiff_t func; + lua_lock(L); + api_check(L, k == NULL || !isLua(L->ci), + "cannot use continuations inside hooks"); + api_checknelems(L, nargs+1); + api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); + checkresults(L, nargs, nresults); + if (errfunc == 0) + func = 0; + else { + StkId o = index2addr(L, errfunc); + api_checkstackindex(L, errfunc, o); + func = savestack(L, o); + } + c.func = L->top - (nargs+1); /* function to be called */ + if (k == NULL || L->nny > 0) { /* no continuation or no yieldable? */ + c.nresults = nresults; /* do a 'conventional' protected call */ + status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); + } + else { /* prepare continuation (call is already protected by 'resume') */ + CallInfo *ci = L->ci; + ci->u.c.k = k; /* save continuation */ + ci->u.c.ctx = ctx; /* save context */ + /* save information for error recovery */ + ci->extra = savestack(L, c.func); + ci->u.c.old_allowhook = L->allowhook; + ci->u.c.old_errfunc = L->errfunc; + L->errfunc = func; + /* mark that function may do error recovery */ + ci->callstatus |= CIST_YPCALL; + luaD_call(L, c.func, nresults, 1); /* do the call */ + ci->callstatus &= ~CIST_YPCALL; + L->errfunc = ci->u.c.old_errfunc; + status = LUA_OK; /* if it is here, there were no errors */ + } + adjustresults(L, nresults); + lua_unlock(L); + return status; +} + + +LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, + const char *chunkname, const char *mode) { + ZIO z; + int status; + lua_lock(L); + if (!chunkname) chunkname = "?"; + luaZ_init(L, &z, reader, data); + status = luaD_protectedparser(L, &z, chunkname, mode); + if (status == LUA_OK) { /* no errors? */ + LClosure *f = clLvalue(L->top - 1); /* get newly created function */ + if (f->nupvalues == 1) { /* does it have one upvalue? */ + /* get global table from registry */ + Table *reg = hvalue(&G(L)->l_registry); + const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS); + /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */ + setobj(L, f->upvals[0]->v, gt); + luaC_barrier(L, f->upvals[0], gt); + } + } + lua_unlock(L); + return status; +} + + +LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) { + int status; + TValue *o; + lua_lock(L); + api_checknelems(L, 1); + o = L->top - 1; + if (isLfunction(o)) + status = luaU_dump(L, getproto(o), writer, data, 0); + else + status = 1; + lua_unlock(L); + return status; +} + + +LUA_API int lua_status (lua_State *L) { + return L->status; +} + + +/* +** Garbage-collection function +*/ + +LUA_API int lua_gc (lua_State *L, int what, int data) { + int res = 0; + global_State *g; + lua_lock(L); + g = G(L); + switch (what) { + case LUA_GCSTOP: { + g->gcrunning = 0; + break; + } + case LUA_GCRESTART: { + luaE_setdebt(g, 0); + g->gcrunning = 1; + break; + } + case LUA_GCCOLLECT: { + luaC_fullgc(L, 0); + break; + } + case LUA_GCCOUNT: { + /* GC values are expressed in Kbytes: #bytes/2^10 */ + res = cast_int(gettotalbytes(g) >> 10); + break; + } + case LUA_GCCOUNTB: { + res = cast_int(gettotalbytes(g) & 0x3ff); + break; + } + case LUA_GCSTEP: { + if (g->gckind == KGC_GEN) { /* generational mode? */ + res = (g->GCestimate == 0); /* true if it will do major collection */ + luaC_forcestep(L); /* do a single step */ + } + else { + lu_mem debt = cast(lu_mem, data) * 1024 - GCSTEPSIZE; + if (g->gcrunning) + debt += g->GCdebt; /* include current debt */ + luaE_setdebt(g, debt); + luaC_forcestep(L); + if (g->gcstate == GCSpause) /* end of cycle? */ + res = 1; /* signal it */ + } + break; + } + case LUA_GCSETPAUSE: { + res = g->gcpause; + g->gcpause = data; + break; + } + case LUA_GCSETMAJORINC: { + res = g->gcmajorinc; + g->gcmajorinc = data; + break; + } + case LUA_GCSETSTEPMUL: { + res = g->gcstepmul; + g->gcstepmul = data; + break; + } + case LUA_GCISRUNNING: { + res = g->gcrunning; + break; + } + case LUA_GCGEN: { /* change collector to generational mode */ + luaC_changemode(L, KGC_GEN); + break; + } + case LUA_GCINC: { /* change collector to incremental mode */ + luaC_changemode(L, KGC_NORMAL); + break; + } + default: res = -1; /* invalid option */ + } + lua_unlock(L); + return res; +} + + + +/* +** miscellaneous functions +*/ + + +LUA_API int lua_error (lua_State *L) { + lua_lock(L); + api_checknelems(L, 1); + luaG_errormsg(L); + /* code unreachable; will unlock when control actually leaves the kernel */ + return 0; /* to avoid warnings */ +} + + +LUA_API int lua_next (lua_State *L, int idx) { + StkId t; + int more; + lua_lock(L); + t = index2addr(L, idx); + api_check(L, ttistable(t), "table expected"); + more = luaH_next(L, hvalue(t), L->top - 1); + if (more) { + api_incr_top(L); + } + else /* no more elements */ + L->top -= 1; /* remove key */ + lua_unlock(L); + return more; +} + + +LUA_API void lua_concat (lua_State *L, int n) { + lua_lock(L); + api_checknelems(L, n); + if (n >= 2) { + luaC_checkGC(L); + luaV_concat(L, n); + } + else if (n == 0) { /* push empty string */ + setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); + api_incr_top(L); + } + /* else n == 1; nothing to do */ + lua_unlock(L); +} + + +LUA_API void lua_len (lua_State *L, int idx) { + StkId t; + lua_lock(L); + t = index2addr(L, idx); + luaV_objlen(L, L->top, t); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) { + lua_Alloc f; + lua_lock(L); + if (ud) *ud = G(L)->ud; + f = G(L)->frealloc; + lua_unlock(L); + return f; +} + + +LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) { + lua_lock(L); + G(L)->ud = ud; + G(L)->frealloc = f; + lua_unlock(L); +} + + +LUA_API void *lua_newuserdata (lua_State *L, size_t size) { + Udata *u; + lua_lock(L); + luaC_checkGC(L); + u = luaS_newudata(L, size, NULL); + setuvalue(L, L->top, u); + api_incr_top(L); + lua_unlock(L); + return u + 1; +} + + + +static const char *aux_upvalue (StkId fi, int n, TValue **val, + GCObject **owner) { + switch (ttype(fi)) { + case LUA_TCCL: { /* C closure */ + CClosure *f = clCvalue(fi); + if (!(1 <= n && n <= f->nupvalues)) return NULL; + *val = &f->upvalue[n-1]; + if (owner) *owner = obj2gco(f); + return ""; + } + case LUA_TLCL: { /* Lua closure */ + LClosure *f = clLvalue(fi); + TString *name; + Proto *p = f->p; + if (!(1 <= n && n <= p->sizeupvalues)) return NULL; + *val = f->upvals[n-1]->v; + if (owner) *owner = obj2gco(f->upvals[n - 1]); + name = p->upvalues[n-1].name; + return (name == NULL) ? "" : getstr(name); + } + default: return NULL; /* not a closure */ + } +} + + +LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { + const char *name; + TValue *val = NULL; /* to avoid warnings */ + lua_lock(L); + name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL); + if (name) { + setobj2s(L, L->top, val); + api_incr_top(L); + } + lua_unlock(L); + return name; +} + + +LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { + const char *name; + TValue *val = NULL; /* to avoid warnings */ + GCObject *owner = NULL; /* to avoid warnings */ + StkId fi; + lua_lock(L); + fi = index2addr(L, funcindex); + api_checknelems(L, 1); + name = aux_upvalue(fi, n, &val, &owner); + if (name) { + L->top--; + setobj(L, val, L->top); + luaC_barrier(L, owner, L->top); + } + lua_unlock(L); + return name; +} + + +static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) { + LClosure *f; + StkId fi = index2addr(L, fidx); + api_check(L, ttisLclosure(fi), "Lua function expected"); + f = clLvalue(fi); + api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index"); + if (pf) *pf = f; + return &f->upvals[n - 1]; /* get its upvalue pointer */ +} + + +LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) { + StkId fi = index2addr(L, fidx); + switch (ttype(fi)) { + case LUA_TLCL: { /* lua closure */ + return *getupvalref(L, fidx, n, NULL); + } + case LUA_TCCL: { /* C closure */ + CClosure *f = clCvalue(fi); + api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index"); + return &f->upvalue[n - 1]; + } + default: { + api_check(L, 0, "closure expected"); + return NULL; + } + } +} + + +LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1, + int fidx2, int n2) { + LClosure *f1; + UpVal **up1 = getupvalref(L, fidx1, n1, &f1); + UpVal **up2 = getupvalref(L, fidx2, n2, NULL); + *up1 = *up2; + luaC_objbarrier(L, f1, *up2); +} + diff --git a/components/pico8/femto8/src/lua/lapi.h b/components/pico8/femto8/src/lua/lapi.h new file mode 100644 index 00000000..0909a391 --- /dev/null +++ b/components/pico8/femto8/src/lua/lapi.h @@ -0,0 +1,24 @@ +/* +** $Id: lapi.h,v 2.7 2009/11/27 15:37:59 roberto Exp $ +** Auxiliary functions from Lua API +** See Copyright Notice in lua.h +*/ + +#ifndef lapi_h +#define lapi_h + + +#include "llimits.h" +#include "lstate.h" + +#define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \ + "stack overflow");} + +#define adjustresults(L,nres) \ + { if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; } + +#define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \ + "not enough elements in the stack") + + +#endif diff --git a/components/pico8/femto8/src/lua/lauxlib.c b/components/pico8/femto8/src/lua/lauxlib.c new file mode 100644 index 00000000..ec1fdc93 --- /dev/null +++ b/components/pico8/femto8/src/lua/lauxlib.c @@ -0,0 +1,959 @@ +/* +** $Id: lauxlib.c,v 1.248 2013/03/21 13:54:57 roberto Exp $ +** Auxiliary functions for building Lua libraries +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include +#include +#include + + +/* This file uses only the official API of Lua. +** Any function declared here could be written as an application function. +*/ + +#define lauxlib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" + + +/* +** {====================================================== +** Traceback +** ======================================================= +*/ + + +#define LEVELS1 12 /* size of the first part of the stack */ +#define LEVELS2 10 /* size of the second part of the stack */ + + + +/* +** search for 'objidx' in table at index -1. +** return 1 + string at top if find a good name. +*/ +static int findfield (lua_State *L, int objidx, int level) { + if (level == 0 || !lua_istable(L, -1)) + return 0; /* not found */ + lua_pushnil(L); /* start 'next' loop */ + while (lua_next(L, -2)) { /* for each pair in table */ + if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ + if (lua_rawequal(L, objidx, -1)) { /* found object? */ + lua_pop(L, 1); /* remove value (but keep name) */ + return 1; + } + else if (findfield(L, objidx, level - 1)) { /* try recursively */ + lua_remove(L, -2); /* remove table (but keep name) */ + lua_pushliteral(L, "."); + lua_insert(L, -2); /* place '.' between the two names */ + lua_concat(L, 3); + return 1; + } + } + lua_pop(L, 1); /* remove value */ + } + return 0; /* not found */ +} + + +static int pushglobalfuncname (lua_State *L, lua_Debug *ar) { + int top = lua_gettop(L); + lua_getinfo(L, "f", ar); /* push function */ + lua_pushglobaltable(L); + if (findfield(L, top + 1, 2)) { + lua_copy(L, -1, top + 1); /* move name to proper place */ + lua_pop(L, 2); /* remove pushed values */ + return 1; + } + else { + lua_settop(L, top); /* remove function and global table */ + return 0; + } +} + + +static void pushfuncname (lua_State *L, lua_Debug *ar) { + if (*ar->namewhat != '\0') /* is there a name? */ + lua_pushfstring(L, "function " LUA_QS, ar->name); + else if (*ar->what == 'm') /* main? */ + lua_pushliteral(L, "main chunk"); + else if (*ar->what == 'C') { + if (pushglobalfuncname(L, ar)) { + lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1)); + lua_remove(L, -2); /* remove name */ + } + else + lua_pushliteral(L, "?"); + } + else + lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); +} + + +static int countlevels (lua_State *L) { + lua_Debug ar; + int li = 1, le = 1; + /* find an upper bound */ + while (lua_getstack(L, le, &ar)) { li = le; le *= 2; } + /* do a binary search */ + while (li < le) { + int m = (li + le)/2; + if (lua_getstack(L, m, &ar)) li = m + 1; + else le = m; + } + return le - 1; +} + + +LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, + const char *msg, int level) { + lua_Debug ar; + int top = lua_gettop(L); + int numlevels = countlevels(L1); + int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0; + if (msg) lua_pushfstring(L, "%s\n", msg); + lua_pushliteral(L, "stack traceback:"); + while (lua_getstack(L1, level++, &ar)) { + if (level == mark) { /* too many levels? */ + lua_pushliteral(L, "\n\t..."); /* add a '...' */ + level = numlevels - LEVELS2; /* and skip to last ones */ + } + else { + lua_getinfo(L1, "Slnt", &ar); + lua_pushfstring(L, "\n\t%s:", ar.short_src); + if (ar.currentline > 0) + lua_pushfstring(L, "%d:", ar.currentline); + lua_pushliteral(L, " in "); + pushfuncname(L, &ar); + if (ar.istailcall) + lua_pushliteral(L, "\n\t(...tail calls...)"); + lua_concat(L, lua_gettop(L) - top); + } + } + lua_concat(L, lua_gettop(L) - top); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Error-report functions +** ======================================================= +*/ + +LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) { + lua_Debug ar; + if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ + return luaL_error(L, "bad argument #%d (%s)", narg, extramsg); + lua_getinfo(L, "n", &ar); + if (strcmp(ar.namewhat, "method") == 0) { + narg--; /* do not count `self' */ + if (narg == 0) /* error is in the self argument itself? */ + return luaL_error(L, "calling " LUA_QS " on bad self (%s)", + ar.name, extramsg); + } + if (ar.name == NULL) + ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?"; + return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)", + narg, ar.name, extramsg); +} + + +static int typeerror (lua_State *L, int narg, const char *tname) { + const char *msg = lua_pushfstring(L, "%s expected, got %s", + tname, luaL_typename(L, narg)); + return luaL_argerror(L, narg, msg); +} + + +static void tag_error (lua_State *L, int narg, int tag) { + typeerror(L, narg, lua_typename(L, tag)); +} + + +LUALIB_API void luaL_where (lua_State *L, int level) { + lua_Debug ar; + if (lua_getstack(L, level, &ar)) { /* check function at level */ + lua_getinfo(L, "Sl", &ar); /* get info about it */ + if (ar.currentline > 0) { /* is there info? */ + lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); + return; + } + } + lua_pushliteral(L, ""); /* else, no information available... */ +} + + +LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { + va_list argp; + va_start(argp, fmt); + luaL_where(L, 1); + lua_pushvfstring(L, fmt, argp); + va_end(argp); + lua_concat(L, 2); + return lua_error(L); +} + + +LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) { + int en = errno; /* calls to Lua API may change this value */ + if (stat) { + lua_pushboolean(L, 1); + return 1; + } + else { + lua_pushnil(L); + if (fname) + lua_pushfstring(L, "%s: %s", fname, strerror(en)); + else + lua_pushstring(L, strerror(en)); + lua_pushinteger(L, en); + return 3; + } +} + + +#if !defined(inspectstat) /* { */ + +#if defined(LUA_USE_POSIX) + +#include + +/* +** use appropriate macros to interpret 'pclose' return status +*/ +#define inspectstat(stat,what) \ + if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \ + else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; } + +#else + +#define inspectstat(stat,what) /* no op */ + +#endif + +#endif /* } */ + + +LUALIB_API int luaL_execresult (lua_State *L, int stat) { + const char *what = "exit"; /* type of termination */ + if (stat == -1) /* error? */ + return luaL_fileresult(L, 0, NULL); + else { + inspectstat(stat, what); /* interpret result */ + if (*what == 'e' && stat == 0) /* successful termination? */ + lua_pushboolean(L, 1); + else + lua_pushnil(L); + lua_pushstring(L, what); + lua_pushinteger(L, stat); + return 3; /* return true/nil,what,code */ + } +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Userdata's metatable manipulation +** ======================================================= +*/ + +LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { + luaL_getmetatable(L, tname); /* try to get metatable */ + if (!lua_isnil(L, -1)) /* name already in use? */ + return 0; /* leave previous value on top, but return 0 */ + lua_pop(L, 1); + lua_newtable(L); /* create metatable */ + lua_pushvalue(L, -1); + lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ + return 1; +} + + +LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) { + luaL_getmetatable(L, tname); + lua_setmetatable(L, -2); +} + + +LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) { + void *p = lua_touserdata(L, ud); + if (p != NULL) { /* value is a userdata? */ + if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ + luaL_getmetatable(L, tname); /* get correct metatable */ + if (!lua_rawequal(L, -1, -2)) /* not the same? */ + p = NULL; /* value is a userdata with wrong metatable */ + lua_pop(L, 2); /* remove both metatables */ + return p; + } + } + return NULL; /* value is not a userdata with a metatable */ +} + + +LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { + void *p = luaL_testudata(L, ud, tname); + if (p == NULL) typeerror(L, ud, tname); + return p; +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Argument check functions +** ======================================================= +*/ + +LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def, + const char *const lst[]) { + const char *name = (def) ? luaL_optstring(L, narg, def) : + luaL_checkstring(L, narg); + int i; + for (i=0; lst[i]; i++) + if (strcmp(lst[i], name) == 0) + return i; + return luaL_argerror(L, narg, + lua_pushfstring(L, "invalid option " LUA_QS, name)); +} + + +LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) { + /* keep some extra space to run error routines, if needed */ + const int extra = LUA_MINSTACK; + if (!lua_checkstack(L, space + extra)) { + if (msg) + luaL_error(L, "stack overflow (%s)", msg); + else + luaL_error(L, "stack overflow"); + } +} + + +LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) { + if (lua_type(L, narg) != t) + tag_error(L, narg, t); +} + + +LUALIB_API void luaL_checkany (lua_State *L, int narg) { + if (lua_type(L, narg) == LUA_TNONE) + luaL_argerror(L, narg, "value expected"); +} + + +LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) { + const char *s = lua_tolstring(L, narg, len); + if (!s) tag_error(L, narg, LUA_TSTRING); + return s; +} + + +LUALIB_API const char *luaL_optlstring (lua_State *L, int narg, + const char *def, size_t *len) { + if (lua_isnoneornil(L, narg)) { + if (len) + *len = (def ? strlen(def) : 0); + return def; + } + else return luaL_checklstring(L, narg, len); +} + + +LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) { + int isnum; + lua_Number d = lua_tonumberx(L, narg, &isnum); + if (!isnum) + tag_error(L, narg, LUA_TNUMBER); + return d; +} + + +LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) { + return luaL_opt(L, luaL_checknumber, narg, def); +} + + +LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) { + int isnum; + lua_Integer d = lua_tointegerx(L, narg, &isnum); + if (!isnum) + tag_error(L, narg, LUA_TNUMBER); + return d; +} + + +LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int narg) { + int isnum; + lua_Unsigned d = lua_tounsignedx(L, narg, &isnum); + if (!isnum) + tag_error(L, narg, LUA_TNUMBER); + return d; +} + + +LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg, + lua_Integer def) { + return luaL_opt(L, luaL_checkinteger, narg, def); +} + + +LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int narg, + lua_Unsigned def) { + return luaL_opt(L, luaL_checkunsigned, narg, def); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Generic Buffer manipulation +** ======================================================= +*/ + +/* +** check whether buffer is using a userdata on the stack as a temporary +** buffer +*/ +#define buffonstack(B) ((B)->b != (B)->initb) + + +/* +** returns a pointer to a free area with at least 'sz' bytes +*/ +LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { + lua_State *L = B->L; + if (B->size - B->n < sz) { /* not enough space? */ + char *newbuff; + size_t newsize = B->size * 2; /* double buffer size */ + if (newsize - B->n < sz) /* not big enough? */ + newsize = B->n + sz; + if (newsize < B->n || newsize - B->n < sz) + luaL_error(L, "buffer too large"); + /* create larger buffer */ + newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char)); + /* move content to new buffer */ + memcpy(newbuff, B->b, B->n * sizeof(char)); + if (buffonstack(B)) + lua_remove(L, -2); /* remove old buffer */ + B->b = newbuff; + B->size = newsize; + } + return &B->b[B->n]; +} + + +LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { + char *b = luaL_prepbuffsize(B, l); + memcpy(b, s, l * sizeof(char)); + luaL_addsize(B, l); +} + + +LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { + luaL_addlstring(B, s, strlen(s)); +} + + +LUALIB_API void luaL_pushresult (luaL_Buffer *B) { + lua_State *L = B->L; + lua_pushlstring(L, B->b, B->n); + if (buffonstack(B)) + lua_remove(L, -2); /* remove old buffer */ +} + + +LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) { + luaL_addsize(B, sz); + luaL_pushresult(B); +} + + +LUALIB_API void luaL_addvalue (luaL_Buffer *B) { + lua_State *L = B->L; + size_t l; + const char *s = lua_tolstring(L, -1, &l); + if (buffonstack(B)) + lua_insert(L, -2); /* put value below buffer */ + luaL_addlstring(B, s, l); + lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */ +} + + +LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { + B->L = L; + B->b = B->initb; + B->n = 0; + B->size = LUAL_BUFFERSIZE; +} + + +LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) { + luaL_buffinit(L, B); + return luaL_prepbuffsize(B, sz); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Reference system +** ======================================================= +*/ + +/* index of free-list header */ +#define freelist 0 + + +LUALIB_API int luaL_ref (lua_State *L, int t) { + int ref; + if (lua_isnil(L, -1)) { + lua_pop(L, 1); /* remove from stack */ + return LUA_REFNIL; /* `nil' has a unique fixed reference */ + } + t = lua_absindex(L, t); + lua_rawgeti(L, t, freelist); /* get first free element */ + ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */ + lua_pop(L, 1); /* remove it from stack */ + if (ref != 0) { /* any free element? */ + lua_rawgeti(L, t, ref); /* remove it from list */ + lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */ + } + else /* no free elements */ + ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */ + lua_rawseti(L, t, ref); + return ref; +} + + +LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { + if (ref >= 0) { + t = lua_absindex(L, t); + lua_rawgeti(L, t, freelist); + lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */ + lua_pushinteger(L, ref); + lua_rawseti(L, t, freelist); /* t[freelist] = ref */ + } +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Load functions +** ======================================================= +*/ + +typedef struct LoadF { + int n; /* number of pre-read characters */ + FILE *f; /* file being read */ + char buff[LUAL_BUFFERSIZE]; /* area for reading file */ +} LoadF; + + +static const char *getF (lua_State *L, void *ud, size_t *size) { + LoadF *lf = (LoadF *)ud; + (void)L; /* not used */ + if (lf->n > 0) { /* are there pre-read characters to be read? */ + *size = lf->n; /* return them (chars already in buffer) */ + lf->n = 0; /* no more pre-read characters */ + } + else { /* read a block from file */ + /* 'fread' can return > 0 *and* set the EOF flag. If next call to + 'getF' called 'fread', it might still wait for user input. + The next check avoids this problem. */ + if (feof(lf->f)) return NULL; + *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */ + } + return lf->buff; +} + + +static int errfile (lua_State *L, const char *what, int fnameindex) { + const char *serr = strerror(errno); + const char *filename = lua_tostring(L, fnameindex) + 1; + lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr); + lua_remove(L, fnameindex); + return LUA_ERRFILE; +} + + +static int skipBOM (LoadF *lf) { + const char *p = "\xEF\xBB\xBF"; /* Utf8 BOM mark */ + int c; + lf->n = 0; + do { + c = getc(lf->f); + if (c == EOF || c != *(const unsigned char *)p++) return c; + lf->buff[lf->n++] = c; /* to be read by the parser */ + } while (*p != '\0'); + lf->n = 0; /* prefix matched; discard it */ + return getc(lf->f); /* return next character */ +} + + +/* +** reads the first character of file 'f' and skips an optional BOM mark +** in its beginning plus its first line if it starts with '#'. Returns +** true if it skipped the first line. In any case, '*cp' has the +** first "valid" character of the file (after the optional BOM and +** a first-line comment). +*/ +static int skipcomment (LoadF *lf, int *cp) { + int c = *cp = skipBOM(lf); + if (c == '#') { /* first line is a comment (Unix exec. file)? */ + do { /* skip first line */ + c = getc(lf->f); + } while (c != EOF && c != '\n') ; + *cp = getc(lf->f); /* skip end-of-line, if present */ + return 1; /* there was a comment */ + } + else return 0; /* no comment */ +} + + +LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename, + const char *mode) { + LoadF lf; + int status, readstatus; + int c; + int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ + if (filename == NULL) { + lua_pushliteral(L, "=stdin"); + lf.f = stdin; + } + else { + lua_pushfstring(L, "@%s", filename); + lf.f = fopen(filename, "r"); + if (lf.f == NULL) return errfile(L, "open", fnameindex); + } + if (skipcomment(&lf, &c)) /* read initial portion */ + lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */ + if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ + lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ + if (lf.f == NULL) return errfile(L, "reopen", fnameindex); + skipcomment(&lf, &c); /* re-read initial portion */ + } + if (c != EOF) + lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */ + status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode); + readstatus = ferror(lf.f); + if (filename) fclose(lf.f); /* close file (even in case of errors) */ + if (readstatus) { + lua_settop(L, fnameindex); /* ignore results from `lua_load' */ + return errfile(L, "read", fnameindex); + } + lua_remove(L, fnameindex); + return status; +} + + +typedef struct LoadS { + const char *s; + size_t size; +} LoadS; + + +static const char *getS (lua_State *L, void *ud, size_t *size) { + LoadS *ls = (LoadS *)ud; + (void)L; /* not used */ + if (ls->size == 0) return NULL; + *size = ls->size; + ls->size = 0; + return ls->s; +} + + +LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size, + const char *name, const char *mode) { + LoadS ls; + ls.s = buff; + ls.size = size; + return lua_load(L, getS, &ls, name, mode); +} + + +LUALIB_API int luaL_loadstring (lua_State *L, const char *s) { + return luaL_loadbuffer(L, s, strlen(s), s); +} + +/* }====================================================== */ + + + +LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { + if (!lua_getmetatable(L, obj)) /* no metatable? */ + return 0; + lua_pushstring(L, event); + lua_rawget(L, -2); + if (lua_isnil(L, -1)) { + lua_pop(L, 2); /* remove metatable and metafield */ + return 0; + } + else { + lua_remove(L, -2); /* remove only metatable */ + return 1; + } +} + + +LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { + obj = lua_absindex(L, obj); + if (!luaL_getmetafield(L, obj, event)) /* no metafield? */ + return 0; + lua_pushvalue(L, obj); + lua_call(L, 1, 1); + return 1; +} + + +LUALIB_API int luaL_len (lua_State *L, int idx) { + int l; + int isnum; + lua_len(L, idx); + l = (int)lua_tointegerx(L, -1, &isnum); + if (!isnum) + luaL_error(L, "object length is not a number"); + lua_pop(L, 1); /* remove object */ + return l; +} + + +LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) { + if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */ + switch (lua_type(L, idx)) { + case LUA_TNUMBER: + case LUA_TSTRING: + lua_pushvalue(L, idx); + break; + case LUA_TBOOLEAN: + lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false")); + break; + case LUA_TNIL: + lua_pushliteral(L, "nil"); + break; + default: + lua_pushfstring(L, "%s: %p", luaL_typename(L, idx), + lua_topointer(L, idx)); + break; + } + } + return lua_tolstring(L, -1, len); +} + + +/* +** {====================================================== +** Compatibility with 5.1 module functions +** ======================================================= +*/ +#if defined(LUA_COMPAT_MODULE) + +static const char *luaL_findtable (lua_State *L, int idx, + const char *fname, int szhint) { + const char *e; + if (idx) lua_pushvalue(L, idx); + do { + e = strchr(fname, '.'); + if (e == NULL) e = fname + strlen(fname); + lua_pushlstring(L, fname, e - fname); + lua_rawget(L, -2); + if (lua_isnil(L, -1)) { /* no such field? */ + lua_pop(L, 1); /* remove this nil */ + lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */ + lua_pushlstring(L, fname, e - fname); + lua_pushvalue(L, -2); + lua_settable(L, -4); /* set new table into field */ + } + else if (!lua_istable(L, -1)) { /* field has a non-table value? */ + lua_pop(L, 2); /* remove table and value */ + return fname; /* return problematic part of the name */ + } + lua_remove(L, -2); /* remove previous table */ + fname = e + 1; + } while (*e == '.'); + return NULL; +} + + +/* +** Count number of elements in a luaL_Reg list. +*/ +static int libsize (const luaL_Reg *l) { + int size = 0; + for (; l && l->name; l++) size++; + return size; +} + + +/* +** Find or create a module table with a given name. The function +** first looks at the _LOADED table and, if that fails, try a +** global variable with that name. In any case, leaves on the stack +** the module table. +*/ +LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname, + int sizehint) { + luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */ + lua_getfield(L, -1, modname); /* get _LOADED[modname] */ + if (!lua_istable(L, -1)) { /* not found? */ + lua_pop(L, 1); /* remove previous result */ + /* try global variable (and create one if it does not exist) */ + lua_pushglobaltable(L); + if (luaL_findtable(L, 0, modname, sizehint) != NULL) + luaL_error(L, "name conflict for module " LUA_QS, modname); + lua_pushvalue(L, -1); + lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */ + } + lua_remove(L, -2); /* remove _LOADED table */ +} + + +LUALIB_API void luaL_openlib (lua_State *L, const char *libname, + const luaL_Reg *l, int nup) { + luaL_checkversion(L); + if (libname) { + luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */ + lua_insert(L, -(nup + 1)); /* move library table to below upvalues */ + } + if (l) + luaL_setfuncs(L, l, nup); + else + lua_pop(L, nup); /* remove upvalues */ +} + +#endif +/* }====================================================== */ + +/* +** set functions from list 'l' into table at top - 'nup'; each +** function gets the 'nup' elements at the top as upvalues. +** Returns with only the table at the stack. +*/ +LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { + luaL_checkversion(L); + luaL_checkstack(L, nup, "too many upvalues"); + for (; l->name != NULL; l++) { /* fill the table with given functions */ + int i; + for (i = 0; i < nup; i++) /* copy upvalues to the top */ + lua_pushvalue(L, -nup); + lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ + lua_setfield(L, -(nup + 2), l->name); + } + lua_pop(L, nup); /* remove upvalues */ +} + + +/* +** ensure that stack[idx][fname] has a table and push that table +** into the stack +*/ +LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) { + lua_getfield(L, idx, fname); + if (lua_istable(L, -1)) return 1; /* table already there */ + else { + lua_pop(L, 1); /* remove previous result */ + idx = lua_absindex(L, idx); + lua_newtable(L); + lua_pushvalue(L, -1); /* copy to be left at top */ + lua_setfield(L, idx, fname); /* assign new table to field */ + return 0; /* false, because did not find table there */ + } +} + + +/* +** stripped-down 'require'. Calls 'openf' to open a module, +** registers the result in 'package.loaded' table and, if 'glb' +** is true, also registers the result in the global table. +** Leaves resulting module on the top. +*/ +LUALIB_API void luaL_requiref (lua_State *L, const char *modname, + lua_CFunction openf, int glb) { + lua_pushcfunction(L, openf); + lua_pushstring(L, modname); /* argument to open function */ + lua_call(L, 1, 1); /* open module */ + luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED"); + lua_pushvalue(L, -2); /* make copy of module (call result) */ + lua_setfield(L, -2, modname); /* _LOADED[modname] = module */ + lua_pop(L, 1); /* remove _LOADED table */ + if (glb) { + lua_pushvalue(L, -1); /* copy of 'mod' */ + lua_setglobal(L, modname); /* _G[modname] = module */ + } +} + + +LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p, + const char *r) { + const char *wild; + size_t l = strlen(p); + luaL_Buffer b; + luaL_buffinit(L, &b); + while ((wild = strstr(s, p)) != NULL) { + luaL_addlstring(&b, s, wild - s); /* push prefix */ + luaL_addstring(&b, r); /* push replacement in place of pattern */ + s = wild + l; /* continue after `p' */ + } + luaL_addstring(&b, s); /* push last suffix */ + luaL_pushresult(&b); + return lua_tostring(L, -1); +} + + +static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { + (void)ud; (void)osize; /* not used */ + if (nsize == 0) { + free(ptr); + return NULL; + } + else + return realloc(ptr, nsize); +} + + +static int panic (lua_State *L) { + luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", + lua_tostring(L, -1)); + return 0; /* return to Lua to abort */ +} + + +LUALIB_API lua_State *luaL_newstate (void) { + lua_State *L = lua_newstate(l_alloc, NULL); + if (L) lua_atpanic(L, &panic); + return L; +} + + +LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) { + const lua_Number *v = lua_version(L); + if (v != lua_version(NULL)) + luaL_error(L, "multiple Lua VMs detected"); + else if (*v != ver) + luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f", + ver, *v); + /* check conversions number -> integer types */ + lua_pushnumber(L, fix32_neg(fix32_from_int(0x1234))); + if (lua_tointeger(L, -1) != -0x1234 || + lua_tounsigned(L, -1) != (lua_Unsigned)-0x1234) + luaL_error(L, "bad conversion number->int;" + " must recompile Lua with proper settings"); + lua_pop(L, 1); +} + diff --git a/components/pico8/femto8/src/lua/lauxlib.h b/components/pico8/femto8/src/lua/lauxlib.h new file mode 100644 index 00000000..ac4d15fb --- /dev/null +++ b/components/pico8/femto8/src/lua/lauxlib.h @@ -0,0 +1,212 @@ +/* +** $Id: lauxlib.h,v 1.120 2011/11/29 15:55:08 roberto Exp $ +** Auxiliary functions for building Lua libraries +** See Copyright Notice in lua.h +*/ + + +#ifndef lauxlib_h +#define lauxlib_h + + +#include +#include + +#include "lua.h" + + + +/* extra error code for `luaL_load' */ +#define LUA_ERRFILE (LUA_ERRERR+1) + + +typedef struct luaL_Reg { + const char *name; + lua_CFunction func; +} luaL_Reg; + + +LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver); +#define luaL_checkversion(L) luaL_checkversion_(L, LUA_VERSION_NUM) + +LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); +LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); +LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len); +LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg); +LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg, + size_t *l); +LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg, + const char *def, size_t *l); +LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg); +LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def); + +LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg); +LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg, + lua_Integer def); +LUALIB_API lua_Unsigned (luaL_checkunsigned) (lua_State *L, int numArg); +LUALIB_API lua_Unsigned (luaL_optunsigned) (lua_State *L, int numArg, + lua_Unsigned def); + +LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); +LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t); +LUALIB_API void (luaL_checkany) (lua_State *L, int narg); + +LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); +LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname); +LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); +LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); + +LUALIB_API void (luaL_where) (lua_State *L, int lvl); +LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); + +LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def, + const char *const lst[]); + +LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname); +LUALIB_API int (luaL_execresult) (lua_State *L, int stat); + +/* pre-defined references */ +#define LUA_NOREF (-2) +#define LUA_REFNIL (-1) + +LUALIB_API int (luaL_ref) (lua_State *L, int t); +LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); + +LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename, + const char *mode); + +#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL) + +LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, + const char *name, const char *mode); +LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); + +LUALIB_API lua_State *(luaL_newstate) (void); + +LUALIB_API int (luaL_len) (lua_State *L, int idx); + +LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, + const char *r); + +LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); + +LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname); + +LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1, + const char *msg, int level); + +LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname, + lua_CFunction openf, int glb); + +/* +** =============================================================== +** some useful macros +** =============================================================== +*/ + + +#define luaL_newlibtable(L,l) \ + lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) + +#define luaL_newlib(L,l) (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) + +#define luaL_argcheck(L, cond,numarg,extramsg) \ + ((void)((cond) || luaL_argerror(L, (numarg), (extramsg)))) +#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) +#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) +#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) +#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) +#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) +#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) + +#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) + +#define luaL_dofile(L, fn) \ + (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) + +#define luaL_dostring(L, s) \ + (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) + +#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) + +#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) + +#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL) + + +/* +** {====================================================== +** Generic Buffer manipulation +** ======================================================= +*/ + +typedef struct luaL_Buffer { + char *b; /* buffer address */ + size_t size; /* buffer size */ + size_t n; /* number of characters in buffer */ + lua_State *L; + char initb[LUAL_BUFFERSIZE]; /* initial buffer */ +} luaL_Buffer; + + +#define luaL_addchar(B,c) \ + ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \ + ((B)->b[(B)->n++] = (c))) + +#define luaL_addsize(B,s) ((B)->n += (s)) + +LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); +LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz); +LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); +LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); +LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); +LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); +LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz); +LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz); + +#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE) + +/* }====================================================== */ + + + +/* +** {====================================================== +** File handles for IO library +** ======================================================= +*/ + +/* +** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and +** initial structure 'luaL_Stream' (it may contain other fields +** after that initial structure). +*/ + +#define LUA_FILEHANDLE "FILE*" + + +typedef struct luaL_Stream { + FILE *f; /* stream (NULL for incompletely created streams) */ + lua_CFunction closef; /* to close stream (NULL for closed streams) */ +} luaL_Stream; + +/* }====================================================== */ + + + +/* compatibility with old module system */ +#if defined(LUA_COMPAT_MODULE) + +LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname, + int sizehint); +LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname, + const luaL_Reg *l, int nup); + +#define luaL_register(L,n,l) (luaL_openlib(L,(n),(l),0)) + +#endif + + +#endif + + diff --git a/components/pico8/femto8/src/lua/lbaselib.c b/components/pico8/femto8/src/lua/lbaselib.c new file mode 100644 index 00000000..ee300486 --- /dev/null +++ b/components/pico8/femto8/src/lua/lbaselib.c @@ -0,0 +1,487 @@ +/* +** $Id: lbaselib.c,v 1.276 2013/02/21 13:44:53 roberto Exp $ +** Basic library +** See Copyright Notice in lua.h +*/ + + + +#include +#include +#include +#include + +#define lbaselib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +static int luaB_print (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + int i; + lua_getglobal(L, "tostring"); + for (i=1; i<=n; i++) { + const char *s; + size_t l; + lua_pushvalue(L, -1); /* function to be called */ + lua_pushvalue(L, i); /* value to print */ + lua_call(L, 1, 1); + s = lua_tolstring(L, -1, &l); /* get result */ + if (s == NULL) + return luaL_error(L, + LUA_QL("tostring") " must return a string to " LUA_QL("print")); + if (i>1) luai_writestring("\t", 1); + luai_writestring(s, l); + lua_pop(L, 1); /* pop result */ + } + luai_writeline(); + return 0; +} + + +#define SPACECHARS " \f\n\r\t\v" + +static int luaB_tonumber (lua_State *L) { + if (lua_isnoneornil(L, 2)) { /* standard conversion */ + int isnum; + lua_Number n = lua_tonumberx(L, 1, &isnum); + if (isnum) { + lua_pushnumber(L, n); + return 1; + } /* else not a number; must be something */ + luaL_checkany(L, 1); + } + else { + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + const char *e = s + l; /* end point for 's' */ + int base = luaL_checkint(L, 2); + int neg = 0; + luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); + s += strspn(s, SPACECHARS); /* skip initial spaces */ + if (*s == '-') { s++; neg = 1; } /* handle signal */ + else if (*s == '+') s++; + if (isalnum((unsigned char)*s)) { + lua_Number n = 0; + do { + int digit = (isdigit((unsigned char)*s)) ? *s - '0' + : toupper((unsigned char)*s) - 'A' + 10; + if (digit >= base) break; /* invalid numeral; force a fail */ + n = n * (lua_Number)base + (lua_Number)digit; + s++; + } while (isalnum((unsigned char)*s)); + s += strspn(s, SPACECHARS); /* skip trailing spaces */ + if (s == e) { /* no invalid trailing characters? */ + lua_pushnumber(L, (neg) ? -n : n); + return 1; + } /* else not a number */ + } /* else not a number */ + } + lua_pushnil(L); /* not a number */ + return 1; +} + + +static int luaB_error (lua_State *L) { + int level = luaL_optint(L, 2, 1); + lua_settop(L, 1); + if (lua_isstring(L, 1) && level > 0) { /* add extra information? */ + luaL_where(L, level); + lua_pushvalue(L, 1); + lua_concat(L, 2); + } + return lua_error(L); +} + + +static int luaB_getmetatable (lua_State *L) { + luaL_checkany(L, 1); + if (!lua_getmetatable(L, 1)) { + lua_pushnil(L); + return 1; /* no metatable */ + } + luaL_getmetafield(L, 1, "__metatable"); + return 1; /* returns either __metatable field (if present) or metatable */ +} + + +static int luaB_setmetatable (lua_State *L) { + int t = lua_type(L, 2); + luaL_checktype(L, 1, LUA_TTABLE); + luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, + "nil or table expected"); + if (luaL_getmetafield(L, 1, "__metatable")) + return luaL_error(L, "cannot change a protected metatable"); + lua_settop(L, 2); + lua_setmetatable(L, 1); + return 1; +} + + +static int luaB_rawequal (lua_State *L) { + luaL_checkany(L, 1); + luaL_checkany(L, 2); + lua_pushboolean(L, lua_rawequal(L, 1, 2)); + return 1; +} + + +static int luaB_rawlen (lua_State *L) { + int t = lua_type(L, 1); + luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1, + "table or string expected"); + lua_pushinteger(L, lua_rawlen(L, 1)); + return 1; +} + + +static int luaB_rawget (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + luaL_checkany(L, 2); + lua_settop(L, 2); + lua_rawget(L, 1); + return 1; +} + +static int luaB_rawset (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + luaL_checkany(L, 2); + luaL_checkany(L, 3); + lua_settop(L, 3); + lua_rawset(L, 1); + return 1; +} + + +static int luaB_collectgarbage (lua_State *L) { + static const char *const opts[] = {"stop", "restart", "collect", + "count", "step", "setpause", "setstepmul", + "setmajorinc", "isrunning", "generational", "incremental", NULL}; + static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, + LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL, + LUA_GCSETMAJORINC, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC}; + int o = optsnum[luaL_checkoption(L, 1, "collect", opts)]; + int ex = luaL_optint(L, 2, 0); + int res = lua_gc(L, o, ex); + switch (o) { + case LUA_GCCOUNT: { + int b = lua_gc(L, LUA_GCCOUNTB, 0); + lua_pushnumber(L, res + ((lua_Number)b/1024)); + lua_pushinteger(L, b); + return 2; + } + case LUA_GCSTEP: case LUA_GCISRUNNING: { + lua_pushboolean(L, res); + return 1; + } + default: { + lua_pushinteger(L, res); + return 1; + } + } +} + + +static int luaB_type (lua_State *L) { + // PICO-8: type() returns nothing instead of causing a runtime error + if (lua_isnone(L, 1)) + return 0; + lua_pushstring(L, luaL_typename(L, 1)); + return 1; +} + + +static int _empty(lua_State *L) { return 0; } + + +static int pairsmeta (lua_State *L, const char *method, int iszero, + lua_CFunction iter) { + // PICO-8 0.2.0 changelog: pairs(nil) returns an empty function + if (lua_isnil(L, 1)) { + lua_pushcfunction(L, _empty); + return 1; + } + + if (!luaL_getmetafield(L, 1, method)) { /* no metamethod? */ + luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */ + lua_pushcfunction(L, iter); /* will return generator, */ + lua_pushvalue(L, 1); /* state, */ + if (iszero) lua_pushinteger(L, 0); /* and initial value */ + else lua_pushnil(L); + } + else { + lua_pushvalue(L, 1); /* argument 'self' to metamethod */ + lua_call(L, 1, 3); /* get 3 values from metamethod */ + } + return 3; +} + + +static int luaB_next (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + lua_settop(L, 2); /* create a 2nd argument if there isn't one */ + if (lua_next(L, 1)) + return 2; + else { + lua_pushnil(L); + return 1; + } +} + + +static int luaB_pairs (lua_State *L) { + return pairsmeta(L, "__pairs", 0, luaB_next); +} + + +static int ipairsaux (lua_State *L) { + int i = luaL_checkint(L, 2); + luaL_checktype(L, 1, LUA_TTABLE); + i++; /* next value */ + lua_pushinteger(L, i); + lua_rawgeti(L, 1, i); + return (lua_isnil(L, -1)) ? 1 : 2; +} + + +static int luaB_ipairs (lua_State *L) { + return pairsmeta(L, "__ipairs", 1, ipairsaux); +} + + +static int luaB_inext (lua_State *L) { + int i; + luaL_checktype(L, 1, LUA_TTABLE); + + if (lua_isnoneornil(L, 2)) { + i = 0; + } else { + i = luaL_checkint(L, 2); + } + + lua_settop(L, 1); + lua_pushinteger(L, i); + + return ipairsaux(L); +} + + +static int load_aux (lua_State *L, int status, int envidx) { + if (status == LUA_OK) { + if (envidx != 0) { /* 'env' parameter? */ + lua_pushvalue(L, envidx); /* environment for loaded function */ + if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */ + lua_pop(L, 1); /* remove 'env' if not used by previous call */ + } + return 1; + } + else { /* error (message is on top of the stack) */ + lua_pushnil(L); + lua_insert(L, -2); /* put before error message */ + return 2; /* return nil plus error message */ + } +} + + +static int luaB_loadfile (lua_State *L) { + const char *fname = luaL_optstring(L, 1, NULL); + const char *mode = luaL_optstring(L, 2, NULL); + int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */ + int status = luaL_loadfilex(L, fname, mode); + return load_aux(L, status, env); +} + + +/* +** {====================================================== +** Generic Read function +** ======================================================= +*/ + + +/* +** reserved slot, above all arguments, to hold a copy of the returned +** string to avoid it being collected while parsed. 'load' has four +** optional arguments (chunk, source name, mode, and environment). +*/ +#define RESERVEDSLOT 5 + + +/* +** Reader for generic `load' function: `lua_load' uses the +** stack for internal stuff, so the reader cannot change the +** stack top. Instead, it keeps its resulting string in a +** reserved slot inside the stack. +*/ +static const char *generic_reader (lua_State *L, void *ud, size_t *size) { + (void)(ud); /* not used */ + luaL_checkstack(L, 2, "too many nested functions"); + lua_pushvalue(L, 1); /* get function */ + lua_call(L, 0, 1); /* call it */ + if (lua_isnil(L, -1)) { + lua_pop(L, 1); /* pop result */ + *size = 0; + return NULL; + } + else if (!lua_isstring(L, -1)) + luaL_error(L, "reader function must return a string"); + lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */ + return lua_tolstring(L, RESERVEDSLOT, size); +} + + +static int luaB_load (lua_State *L) { + int status; + size_t l; + const char *s = lua_tolstring(L, 1, &l); + const char *mode = luaL_optstring(L, 3, "bt"); + int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */ + if (s != NULL) { /* loading a string? */ + const char *chunkname = luaL_optstring(L, 2, s); + status = luaL_loadbufferx(L, s, l, chunkname, mode); + } + else { /* loading from a reader function */ + const char *chunkname = luaL_optstring(L, 2, "=(load)"); + luaL_checktype(L, 1, LUA_TFUNCTION); + lua_settop(L, RESERVEDSLOT); /* create reserved slot */ + status = lua_load(L, generic_reader, NULL, chunkname, mode); + } + return load_aux(L, status, env); +} + +/* }====================================================== */ + + +static int dofilecont (lua_State *L) { + return lua_gettop(L) - 1; +} + + +static int luaB_dofile (lua_State *L) { + const char *fname = luaL_optstring(L, 1, NULL); + lua_settop(L, 1); + if (luaL_loadfile(L, fname) != LUA_OK) + return lua_error(L); + lua_callk(L, 0, LUA_MULTRET, 0, dofilecont); + return dofilecont(L); +} + + +static int luaB_assert (lua_State *L) { + if (!lua_toboolean(L, 1)) + return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!")); + return lua_gettop(L); +} + + +static int luaB_select (lua_State *L) { + int n = lua_gettop(L); + if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { + lua_pushinteger(L, n-1); + return 1; + } + else { + int i = luaL_checkint(L, 1); + if (i < 0) i = n + i; + else if (i > n) i = n; + luaL_argcheck(L, 1 <= i, 1, "index out of range"); + return n - i; + } +} + + +static int finishpcall (lua_State *L, int status) { + if (!lua_checkstack(L, 1)) { /* no space for extra boolean? */ + lua_settop(L, 0); /* create space for return values */ + lua_pushboolean(L, 0); + lua_pushstring(L, "stack overflow"); + return 2; /* return false, msg */ + } + lua_pushboolean(L, status); /* first result (status) */ + lua_replace(L, 1); /* put first result in first slot */ + return lua_gettop(L); +} + + +static int pcallcont (lua_State *L) { + int status = lua_getctx(L, NULL); + return finishpcall(L, (status == LUA_YIELD)); +} + + +static int luaB_pcall (lua_State *L) { + int status; + luaL_checkany(L, 1); + lua_pushnil(L); + lua_insert(L, 1); /* create space for status result */ + status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, pcallcont); + return finishpcall(L, (status == LUA_OK)); +} + + +static int luaB_xpcall (lua_State *L) { + int status; + int n = lua_gettop(L); + luaL_argcheck(L, n >= 2, 2, "value expected"); + lua_pushvalue(L, 1); /* exchange function... */ + lua_copy(L, 2, 1); /* ...and error handler */ + lua_replace(L, 2); + status = lua_pcallk(L, n - 2, LUA_MULTRET, 1, 0, pcallcont); + return finishpcall(L, (status == LUA_OK)); +} + + +static int luaB_tostring (lua_State *L) { + luaL_checkany(L, 1); + luaL_tolstring(L, 1, NULL); + return 1; +} + + +static const luaL_Reg base_funcs[] = { + {"assert", luaB_assert}, + {"collectgarbage", luaB_collectgarbage}, + {"dofile", luaB_dofile}, + {"error", luaB_error}, + {"getmetatable", luaB_getmetatable}, + {"inext", luaB_inext}, + {"ipairs", luaB_ipairs}, + {"loadfile", luaB_loadfile}, + {"load", luaB_load}, +#if defined(LUA_COMPAT_LOADSTRING) + {"loadstring", luaB_load}, +#endif + {"next", luaB_next}, + {"pairs", luaB_pairs}, + {"pcall", luaB_pcall}, + {"print", luaB_print}, + {"rawequal", luaB_rawequal}, + {"rawlen", luaB_rawlen}, + {"rawget", luaB_rawget}, + {"rawset", luaB_rawset}, + {"select", luaB_select}, + {"setmetatable", luaB_setmetatable}, + {"tonumber", luaB_tonumber}, + {"tostring", luaB_tostring}, + {"type", luaB_type}, + {"xpcall", luaB_xpcall}, + {NULL, NULL} +}; + + +LUAMOD_API int luaopen_base (lua_State *L) { + /* set global _G */ + lua_pushglobaltable(L); + lua_pushglobaltable(L); + lua_setfield(L, -2, "_G"); + /* open lib into global table */ + luaL_setfuncs(L, base_funcs, 0); + lua_pushliteral(L, LUA_VERSION); + lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */ + return 1; +} + diff --git a/components/pico8/femto8/src/lua/lcode.c b/components/pico8/femto8/src/lua/lcode.c new file mode 100644 index 00000000..73c22617 --- /dev/null +++ b/components/pico8/femto8/src/lua/lcode.c @@ -0,0 +1,902 @@ +/* +** $Id: lcode.c,v 2.62 2012/08/16 17:34:28 roberto Exp $ +** Code generator for Lua +** See Copyright Notice in lua.h +*/ + + +#include + +#define lcode_c +#define LUA_CORE + +#include "lua.h" + +#include "lcode.h" +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "llex.h" +#include "lmem.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" +#include "lstring.h" +#include "ltable.h" +#include "lvm.h" + + +#define hasjumps(e) ((e)->t != (e)->f) + + +static int isnumeral(expdesc *e) { + return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP); +} + + +void luaK_nil (FuncState *fs, int from, int n) { + Instruction *previous; + int l = from + n - 1; /* last register to set nil */ + if (fs->pc > fs->lasttarget) { /* no jumps to current position? */ + previous = &fs->f->code[fs->pc-1]; + if (GET_OPCODE(*previous) == OP_LOADNIL) { + int pfrom = GETARG_A(*previous); + int pl = pfrom + GETARG_B(*previous); + if ((pfrom <= from && from <= pl + 1) || + (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */ + if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ + if (pl > l) l = pl; /* l = max(l, pl) */ + SETARG_A(*previous, from); + SETARG_B(*previous, l - from); + return; + } + } /* else go through */ + } + luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */ +} + + +int luaK_jump (FuncState *fs) { + int jpc = fs->jpc; /* save list of jumps to here */ + int j; + fs->jpc = NO_JUMP; + j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP); + luaK_concat(fs, &j, jpc); /* keep them on hold */ + return j; +} + + +void luaK_ret (FuncState *fs, int first, int nret) { + luaK_codeABC(fs, OP_RETURN, first, nret+1, 0); +} + + +static int condjump (FuncState *fs, OpCode op, int A, int B, int C) { + luaK_codeABC(fs, op, A, B, C); + return luaK_jump(fs); +} + + +static void fixjump (FuncState *fs, int pc, int dest) { + Instruction *jmp = &fs->f->code[pc]; + int offset = dest-(pc+1); + lua_assert(dest != NO_JUMP); + if (abs(offset) > MAXARG_sBx) + luaX_syntaxerror(fs->ls, "control structure too long"); + SETARG_sBx(*jmp, offset); +} + + +/* +** returns current `pc' and marks it as a jump target (to avoid wrong +** optimizations with consecutive instructions not in the same basic block). +*/ +int luaK_getlabel (FuncState *fs) { + fs->lasttarget = fs->pc; + return fs->pc; +} + + +static int getjump (FuncState *fs, int pc) { + int offset = GETARG_sBx(fs->f->code[pc]); + if (offset == NO_JUMP) /* point to itself represents end of list */ + return NO_JUMP; /* end of list */ + else + return (pc+1)+offset; /* turn offset into absolute position */ +} + + +static Instruction *getjumpcontrol (FuncState *fs, int pc) { + Instruction *pi = &fs->f->code[pc]; + if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) + return pi-1; + else + return pi; +} + + +/* +** check whether list has any jump that do not produce a value +** (or produce an inverted value) +*/ +static int need_value (FuncState *fs, int list) { + for (; list != NO_JUMP; list = getjump(fs, list)) { + Instruction i = *getjumpcontrol(fs, list); + if (GET_OPCODE(i) != OP_TESTSET) return 1; + } + return 0; /* not found */ +} + + +static int patchtestreg (FuncState *fs, int node, int reg) { + Instruction *i = getjumpcontrol(fs, node); + if (GET_OPCODE(*i) != OP_TESTSET) + return 0; /* cannot patch other instructions */ + if (reg != NO_REG && reg != GETARG_B(*i)) + SETARG_A(*i, reg); + else /* no register to put value or register already has the value */ + *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i)); + + return 1; +} + + +static void removevalues (FuncState *fs, int list) { + for (; list != NO_JUMP; list = getjump(fs, list)) + patchtestreg(fs, list, NO_REG); +} + + +static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, + int dtarget) { + while (list != NO_JUMP) { + int next = getjump(fs, list); + if (patchtestreg(fs, list, reg)) + fixjump(fs, list, vtarget); + else + fixjump(fs, list, dtarget); /* jump to default target */ + list = next; + } +} + + +static void dischargejpc (FuncState *fs) { + patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc); + fs->jpc = NO_JUMP; +} + + +void luaK_patchlist (FuncState *fs, int list, int target) { + if (target == fs->pc) + luaK_patchtohere(fs, list); + else { + lua_assert(target < fs->pc); + patchlistaux(fs, list, target, NO_REG, target); + } +} + + +LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level) { + level++; /* argument is +1 to reserve 0 as non-op */ + while (list != NO_JUMP) { + int next = getjump(fs, list); + lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP && + (GETARG_A(fs->f->code[list]) == 0 || + GETARG_A(fs->f->code[list]) >= level)); + SETARG_A(fs->f->code[list], level); + list = next; + } +} + + +void luaK_patchtohere (FuncState *fs, int list) { + luaK_getlabel(fs); + luaK_concat(fs, &fs->jpc, list); +} + + +void luaK_concat (FuncState *fs, int *l1, int l2) { + if (l2 == NO_JUMP) return; + else if (*l1 == NO_JUMP) + *l1 = l2; + else { + int list = *l1; + int next; + while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ + list = next; + fixjump(fs, list, l2); + } +} + + +static int luaK_code (FuncState *fs, Instruction i) { + Proto *f = fs->f; + dischargejpc(fs); /* `pc' will change */ + /* put new instruction in code array */ + luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, + MAX_INT, "opcodes"); + f->code[fs->pc] = i; + /* save corresponding line information */ + luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int, + MAX_INT, "opcodes"); + f->lineinfo[fs->pc] = fs->ls->lastline; + return fs->pc++; +} + + +int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) { + lua_assert(getOpMode(o) == iABC); + lua_assert(getBMode(o) != OpArgN || b == 0); + lua_assert(getCMode(o) != OpArgN || c == 0); + lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C); + return luaK_code(fs, CREATE_ABC(o, a, b, c)); +} + + +int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { + lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx); + lua_assert(getCMode(o) == OpArgN); + lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx); + return luaK_code(fs, CREATE_ABx(o, a, bc)); +} + + +static int codeextraarg (FuncState *fs, int a) { + lua_assert(a <= MAXARG_Ax); + return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a)); +} + + +int luaK_codek (FuncState *fs, int reg, int k) { + if (k <= MAXARG_Bx) + return luaK_codeABx(fs, OP_LOADK, reg, k); + else { + int p = luaK_codeABx(fs, OP_LOADKX, reg, 0); + codeextraarg(fs, k); + return p; + } +} + + +void luaK_checkstack (FuncState *fs, int n) { + int newstack = fs->freereg + n; + if (newstack > fs->f->maxstacksize) { + if (newstack >= MAXSTACK) + luaX_syntaxerror(fs->ls, "function or expression too complex"); + fs->f->maxstacksize = cast_byte(newstack); + } +} + + +void luaK_reserveregs (FuncState *fs, int n) { + luaK_checkstack(fs, n); + fs->freereg += n; +} + + +static void freereg (FuncState *fs, int reg) { + if (!ISK(reg) && reg >= fs->nactvar) { + fs->freereg--; + lua_assert(reg == fs->freereg); + } +} + + +static void freeexp (FuncState *fs, expdesc *e) { + if (e->k == VNONRELOC) + freereg(fs, e->u.info); +} + + +static int addk (FuncState *fs, TValue *key, TValue *v) { + lua_State *L = fs->ls->L; + TValue *idx = luaH_set(L, fs->h, key); + Proto *f = fs->f; + int k, oldsize; + if (ttisnumber(idx)) { + lua_Number n = nvalue(idx); + lua_number2int(k, n); + if (luaV_rawequalobj(&f->k[k], v)) + return k; + /* else may be a collision (e.g., between 0.0 and "\0\0\0\0\0\0\0\0"); + go through and create a new entry for this value */ + } + /* constant not found; create a new entry */ + oldsize = f->sizek; + k = fs->nk; + /* numerical value does not need GC barrier; + table has no metatable, so it does not need to invalidate cache */ + setnvalue(idx, cast_num(k)); + luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants"); + while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); + setobj(L, &f->k[k], v); + fs->nk++; + luaC_barrier(L, f, v); + return k; +} + + +int luaK_stringK (FuncState *fs, TString *s) { + TValue o; + setsvalue(fs->ls->L, &o, s); + return addk(fs, &o, &o); +} + + +int luaK_numberK (FuncState *fs, lua_Number r) { + int n; + lua_State *L = fs->ls->L; + TValue o; + setnvalue(&o, r); + if (r == 0 || luai_numisnan(NULL, r)) { /* handle -0 and NaN */ + /* use raw representation as key to avoid numeric problems */ + setsvalue(L, L->top++, luaS_newlstr(L, (char *)&r, sizeof(r))); + n = addk(fs, L->top - 1, &o); + L->top--; + } + else + n = addk(fs, &o, &o); /* regular case */ + return n; +} + + +static int boolK (FuncState *fs, int b) { + TValue o; + setbvalue(&o, b); + return addk(fs, &o, &o); +} + + +static int nilK (FuncState *fs) { + TValue k, v; + setnilvalue(&v); + /* cannot use nil as key; instead use table itself to represent nil */ + sethvalue(fs->ls->L, &k, fs->h); + return addk(fs, &k, &v); +} + + +void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { + if (e->k == VCALL) { /* expression is an open function call? */ + SETARG_C(getcode(fs, e), nresults+1); + } + else if (e->k == VVARARG) { + SETARG_B(getcode(fs, e), nresults+1); + SETARG_A(getcode(fs, e), fs->freereg); + luaK_reserveregs(fs, 1); + } +} + + +void luaK_setoneret (FuncState *fs, expdesc *e) { + if (e->k == VCALL) { /* expression is an open function call? */ + e->k = VNONRELOC; + e->u.info = GETARG_A(getcode(fs, e)); + } + else if (e->k == VVARARG) { + SETARG_B(getcode(fs, e), 2); + e->k = VRELOCABLE; /* can relocate its simple result */ + } +} + + +void luaK_dischargevars (FuncState *fs, expdesc *e) { + switch (e->k) { + case VLOCAL: { + e->k = VNONRELOC; + break; + } + case VUPVAL: { + e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0); + e->k = VRELOCABLE; + break; + } + case VINDEXED: { + OpCode op = OP_GETTABUP; /* assume 't' is in an upvalue */ + freereg(fs, e->u.ind.idx); + if (e->u.ind.vt == VLOCAL) { /* 't' is in a register? */ + freereg(fs, e->u.ind.t); + op = OP_GETTABLE; + } + e->u.info = luaK_codeABC(fs, op, 0, e->u.ind.t, e->u.ind.idx); + e->k = VRELOCABLE; + break; + } + case VVARARG: + case VCALL: { + luaK_setoneret(fs, e); + break; + } + default: break; /* there is one value available (somewhere) */ + } +} + + +static int code_label (FuncState *fs, int A, int b, int jump) { + luaK_getlabel(fs); /* those instructions may be jump targets */ + return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump); +} + + +static void discharge2reg (FuncState *fs, expdesc *e, int reg) { + luaK_dischargevars(fs, e); + switch (e->k) { + case VNIL: { + luaK_nil(fs, reg, 1); + break; + } + case VFALSE: case VTRUE: { + luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0); + break; + } + case VK: { + luaK_codek(fs, reg, e->u.info); + break; + } + case VKNUM: { + luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval)); + break; + } + case VRELOCABLE: { + Instruction *pc = &getcode(fs, e); + SETARG_A(*pc, reg); + break; + } + case VNONRELOC: { + if (reg != e->u.info) + luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0); + break; + } + default: { + lua_assert(e->k == VVOID || e->k == VJMP); + return; /* nothing to do... */ + } + } + e->u.info = reg; + e->k = VNONRELOC; +} + + +static void discharge2anyreg (FuncState *fs, expdesc *e) { + if (e->k != VNONRELOC) { + luaK_reserveregs(fs, 1); + discharge2reg(fs, e, fs->freereg-1); + } +} + + +static void exp2reg (FuncState *fs, expdesc *e, int reg) { + discharge2reg(fs, e, reg); + if (e->k == VJMP) + luaK_concat(fs, &e->t, e->u.info); /* put this jump in `t' list */ + if (hasjumps(e)) { + int final; /* position after whole expression */ + int p_f = NO_JUMP; /* position of an eventual LOAD false */ + int p_t = NO_JUMP; /* position of an eventual LOAD true */ + if (need_value(fs, e->t) || need_value(fs, e->f)) { + int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); + p_f = code_label(fs, reg, 0, 1); + p_t = code_label(fs, reg, 1, 0); + luaK_patchtohere(fs, fj); + } + final = luaK_getlabel(fs); + patchlistaux(fs, e->f, final, reg, p_f); + patchlistaux(fs, e->t, final, reg, p_t); + } + e->f = e->t = NO_JUMP; + e->u.info = reg; + e->k = VNONRELOC; +} + + +void luaK_exp2nextreg (FuncState *fs, expdesc *e) { + luaK_dischargevars(fs, e); + freeexp(fs, e); + luaK_reserveregs(fs, 1); + exp2reg(fs, e, fs->freereg - 1); +} + + +int luaK_exp2anyreg (FuncState *fs, expdesc *e) { + luaK_dischargevars(fs, e); + if (e->k == VNONRELOC) { + if (!hasjumps(e)) return e->u.info; /* exp is already in a register */ + if (e->u.info >= fs->nactvar) { /* reg. is not a local? */ + exp2reg(fs, e, e->u.info); /* put value on it */ + return e->u.info; + } + } + luaK_exp2nextreg(fs, e); /* default */ + return e->u.info; +} + + +void luaK_exp2anyregup (FuncState *fs, expdesc *e) { + if (e->k != VUPVAL || hasjumps(e)) + luaK_exp2anyreg(fs, e); +} + + +void luaK_exp2val (FuncState *fs, expdesc *e) { + if (hasjumps(e)) + luaK_exp2anyreg(fs, e); + else + luaK_dischargevars(fs, e); +} + + +int luaK_exp2RK (FuncState *fs, expdesc *e) { + luaK_exp2val(fs, e); + switch (e->k) { + case VTRUE: + case VFALSE: + case VNIL: { + if (fs->nk <= MAXINDEXRK) { /* constant fits in RK operand? */ + e->u.info = (e->k == VNIL) ? nilK(fs) : boolK(fs, (e->k == VTRUE)); + e->k = VK; + return RKASK(e->u.info); + } + else break; + } + case VKNUM: { + e->u.info = luaK_numberK(fs, e->u.nval); + e->k = VK; + /* go through */ + } + case VK: { + if (e->u.info <= MAXINDEXRK) /* constant fits in argC? */ + return RKASK(e->u.info); + else break; + } + default: break; + } + /* not a constant in the right range: put it in a register */ + return luaK_exp2anyreg(fs, e); +} + + +void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { + switch (var->k) { + case VLOCAL: { + freeexp(fs, ex); + exp2reg(fs, ex, var->u.info); + return; + } + case VUPVAL: { + int e = luaK_exp2anyreg(fs, ex); + luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0); + break; + } + case VINDEXED: { + OpCode op = (var->u.ind.vt == VLOCAL) ? OP_SETTABLE : OP_SETTABUP; + int e = luaK_exp2RK(fs, ex); + luaK_codeABC(fs, op, var->u.ind.t, var->u.ind.idx, e); + break; + } + default: { + lua_assert(0); /* invalid var kind to store */ + break; + } + } + freeexp(fs, ex); +} + + +void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { + int ereg; + luaK_exp2anyreg(fs, e); + ereg = e->u.info; /* register where 'e' was placed */ + freeexp(fs, e); + e->u.info = fs->freereg; /* base register for op_self */ + e->k = VNONRELOC; + luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */ + luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key)); + freeexp(fs, key); +} + + +static void invertjump (FuncState *fs, expdesc *e) { + Instruction *pc = getjumpcontrol(fs, e->u.info); + lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && + GET_OPCODE(*pc) != OP_TEST); + SETARG_A(*pc, !(GETARG_A(*pc))); +} + + +static int jumponcond (FuncState *fs, expdesc *e, int cond) { + if (e->k == VRELOCABLE) { + Instruction ie = getcode(fs, e); + if (GET_OPCODE(ie) == OP_NOT) { + fs->pc--; /* remove previous OP_NOT */ + return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond); + } + /* else go through */ + } + discharge2anyreg(fs, e); + freeexp(fs, e); + return condjump(fs, OP_TESTSET, NO_REG, e->u.info, cond); +} + + +void luaK_goiftrue (FuncState *fs, expdesc *e) { + int pc; /* pc of last jump */ + luaK_dischargevars(fs, e); + switch (e->k) { + case VJMP: { + invertjump(fs, e); + pc = e->u.info; + break; + } + case VK: case VKNUM: case VTRUE: { + pc = NO_JUMP; /* always true; do nothing */ + break; + } + default: { + pc = jumponcond(fs, e, 0); + break; + } + } + luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */ + luaK_patchtohere(fs, e->t); + e->t = NO_JUMP; +} + + +void luaK_goiffalse (FuncState *fs, expdesc *e) { + int pc; /* pc of last jump */ + luaK_dischargevars(fs, e); + switch (e->k) { + case VJMP: { + pc = e->u.info; + break; + } + case VNIL: case VFALSE: { + pc = NO_JUMP; /* always false; do nothing */ + break; + } + default: { + pc = jumponcond(fs, e, 1); + break; + } + } + luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */ + luaK_patchtohere(fs, e->f); + e->f = NO_JUMP; +} + + +static void codenot (FuncState *fs, expdesc *e) { + luaK_dischargevars(fs, e); + switch (e->k) { + case VNIL: case VFALSE: { + e->k = VTRUE; + break; + } + case VK: case VKNUM: case VTRUE: { + e->k = VFALSE; + break; + } + case VJMP: { + invertjump(fs, e); + break; + } + case VRELOCABLE: + case VNONRELOC: { + discharge2anyreg(fs, e); + freeexp(fs, e); + e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0); + e->k = VRELOCABLE; + break; + } + default: { + lua_assert(0); /* cannot happen */ + break; + } + } + /* interchange true and false lists */ + { int temp = e->f; e->f = e->t; e->t = temp; } + removevalues(fs, e->f); + removevalues(fs, e->t); +} + + +void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { + lua_assert(!hasjumps(t)); + t->u.ind.t = t->u.info; + t->u.ind.idx = luaK_exp2RK(fs, k); + t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL + : check_exp(vkisinreg(t->k), VLOCAL); + t->k = VINDEXED; +} + + +static int constfolding (OpCode op, expdesc *e1, expdesc *e2) { + lua_Number r; + if (!isnumeral(e1) || !isnumeral(e2)) return 0; + if ((op == OP_DIV || op == OP_MOD) && e2->u.nval == 0) + return 0; /* do not attempt to divide by 0 */ + if (op == OP_PEEK || op == OP_PEEK2 || op == OP_PEEK4) + return 0; /* const folding cannot work with peek */ + r = luaO_arith(NULL, op - OP_ADD + LUA_OPADD, e1->u.nval, e2->u.nval); + e1->u.nval = r; + return 1; +} + + +static void codearith (FuncState *fs, OpCode op, + expdesc *e1, expdesc *e2, int line) { + if (constfolding(op, e1, e2)) + return; + else { + int o2 = (op != OP_UNM && op != OP_BNOT && op != OP_LEN) ? + luaK_exp2RK(fs, e2) : 0; + int o1 = luaK_exp2RK(fs, e1); + if (o1 > o2) { + freeexp(fs, e1); + freeexp(fs, e2); + } + else { + freeexp(fs, e2); + freeexp(fs, e1); + } + e1->u.info = luaK_codeABC(fs, op, 0, o1, o2); + e1->k = VRELOCABLE; + luaK_fixline(fs, line); + } +} + + +static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1, + expdesc *e2) { + int o1 = luaK_exp2RK(fs, e1); + int o2 = luaK_exp2RK(fs, e2); + freeexp(fs, e2); + freeexp(fs, e1); + if (cond == 0 && op != OP_EQ) { + int temp; /* exchange args to replace by `<' or `<=' */ + temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */ + cond = 1; + } + e1->u.info = condjump(fs, op, cond, o1, o2); + e1->k = VJMP; +} + + +void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) { + expdesc e2; + e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0; + switch (op) { + case OPR_MINUS: { + if (isnumeral(e)) /* minus constant? */ + e->u.nval = luai_numunm(NULL, e->u.nval); /* fold it */ + else { + luaK_exp2anyreg(fs, e); + codearith(fs, OP_UNM, e, &e2, line); + } + break; + } + case OPR_BNOT: { + if (isnumeral(e)) /* bnot constant? */ + e->u.nval = luai_numbnot(NULL, e->u.nval); /* fold it */ + else { + luaK_exp2anyreg(fs, e); + codearith(fs, OP_BNOT, e, &e2, line); + } + break; + } + case OPR_PEEK: case OPR_PEEK2: case OPR_PEEK4: { + luaK_exp2anyreg(fs, e); /* cannot operate on constants */ + codearith(fs, (OpCode)(op - OPR_PEEK + OP_PEEK), e, &e2, line); + break; + } + case OPR_NOT: codenot(fs, e); break; + case OPR_LEN: { + luaK_exp2anyreg(fs, e); /* cannot operate on constants */ + codearith(fs, OP_LEN, e, &e2, line); + break; + } + default: lua_assert(0); + } +} + + +void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { + switch (op) { + case OPR_AND: { + luaK_goiftrue(fs, v); + break; + } + case OPR_OR: { + luaK_goiffalse(fs, v); + break; + } + case OPR_CONCAT: { + luaK_exp2nextreg(fs, v); /* operand must be on the `stack' */ + break; + } + case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: + case OPR_MOD: case OPR_POW: case OPR_IDIV: case OPR_BAND: + case OPR_BOR: case OPR_BXOR: case OPR_SHL: case OPR_SHR: + case OPR_LSHR: case OPR_ROTL: case OPR_ROTR: { + if (!isnumeral(v)) luaK_exp2RK(fs, v); + break; + } + default: { + luaK_exp2RK(fs, v); + break; + } + } +} + + +void luaK_posfix (FuncState *fs, BinOpr op, + expdesc *e1, expdesc *e2, int line) { + switch (op) { + case OPR_AND: { + lua_assert(e1->t == NO_JUMP); /* list must be closed */ + luaK_dischargevars(fs, e2); + luaK_concat(fs, &e2->f, e1->f); + *e1 = *e2; + break; + } + case OPR_OR: { + lua_assert(e1->f == NO_JUMP); /* list must be closed */ + luaK_dischargevars(fs, e2); + luaK_concat(fs, &e2->t, e1->t); + *e1 = *e2; + break; + } + case OPR_CONCAT: { + luaK_exp2val(fs, e2); + if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) { + lua_assert(e1->u.info == GETARG_B(getcode(fs, e2))-1); + freeexp(fs, e1); + SETARG_B(getcode(fs, e2), e1->u.info); + e1->k = VRELOCABLE; e1->u.info = e2->u.info; + } + else { + luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */ + codearith(fs, OP_CONCAT, e1, e2, line); + } + break; + } + case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: + case OPR_MOD: case OPR_POW: case OPR_IDIV: case OPR_BAND: + case OPR_BOR: case OPR_BXOR: case OPR_SHL: case OPR_SHR: + case OPR_LSHR: case OPR_ROTL: case OPR_ROTR: { + codearith(fs, cast(OpCode, op - OPR_ADD + OP_ADD), e1, e2, line); + break; + } + case OPR_EQ: case OPR_LT: case OPR_LE: { + codecomp(fs, cast(OpCode, op - OPR_EQ + OP_EQ), 1, e1, e2); + break; + } + case OPR_NE: case OPR_GT: case OPR_GE: { + codecomp(fs, cast(OpCode, op - OPR_NE + OP_EQ), 0, e1, e2); + break; + } + default: lua_assert(0); + } +} + + +void luaK_fixline (FuncState *fs, int line) { + fs->f->lineinfo[fs->pc - 1] = line; +} + + +void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { + int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1; + int b = (tostore == LUA_MULTRET) ? 0 : tostore; + lua_assert(tostore != 0); + if (c <= MAXARG_C) + luaK_codeABC(fs, OP_SETLIST, base, b, c); + else if (c <= MAXARG_Ax) { + luaK_codeABC(fs, OP_SETLIST, base, b, 0); + codeextraarg(fs, c); + } + else + luaX_syntaxerror(fs->ls, "constructor too long"); + fs->freereg = base + 1; /* free registers with list values */ +} + diff --git a/components/pico8/femto8/src/lua/lcode.h b/components/pico8/femto8/src/lua/lcode.h new file mode 100644 index 00000000..25e1bfdd --- /dev/null +++ b/components/pico8/femto8/src/lua/lcode.h @@ -0,0 +1,88 @@ +/* +** $Id: lcode.h,v 1.58 2011/08/30 16:26:41 roberto Exp $ +** Code generator for Lua +** See Copyright Notice in lua.h +*/ + +#ifndef lcode_h +#define lcode_h + +#include "llex.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" + + +/* +** Marks the end of a patch list. It is an invalid value both as an absolute +** address, and as a list link (would link an element to itself). +*/ +#define NO_JUMP (-1) + + +/* +** grep "ORDER OPR" if you change these enums (ORDER OP) +*/ +typedef enum BinOpr { + OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW, + OPR_IDIV, OPR_BAND, OPR_BOR, OPR_BXOR, OPR_SHL, OPR_SHR, + OPR_LSHR, OPR_ROTL, OPR_ROTR, + OPR_CONCAT, + OPR_EQ, OPR_LT, OPR_LE, + OPR_NE, OPR_GT, OPR_GE, + OPR_AND, OPR_OR, + OPR_NOBINOPR +} BinOpr; + + +typedef enum UnOpr { + OPR_MINUS, OPR_NOT, OPR_BNOT, OPR_PEEK, OPR_PEEK2, OPR_PEEK4, OPR_LEN, + OPR_NOUNOPR +} UnOpr; + + +#define getcode(fs,e) ((fs)->f->code[(e)->u.info]) + +#define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx) + +#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET) + +#define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t) + +LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx); +LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C); +LUAI_FUNC int luaK_codek (FuncState *fs, int reg, int k); +LUAI_FUNC void luaK_fixline (FuncState *fs, int line); +LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n); +LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n); +LUAI_FUNC void luaK_checkstack (FuncState *fs, int n); +LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s); +LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r); +LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e); +LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e); +LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key); +LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k); +LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_goiffalse (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e); +LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults); +LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e); +LUAI_FUNC int luaK_jump (FuncState *fs); +LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret); +LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target); +LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list); +LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level); +LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2); +LUAI_FUNC int luaK_getlabel (FuncState *fs); +LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line); +LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v); +LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, + expdesc *v2, int line); +LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore); + + +#endif diff --git a/components/pico8/femto8/src/lua/lcorolib.c b/components/pico8/femto8/src/lua/lcorolib.c new file mode 100644 index 00000000..1326c814 --- /dev/null +++ b/components/pico8/femto8/src/lua/lcorolib.c @@ -0,0 +1,155 @@ +/* +** $Id: lcorolib.c,v 1.5 2013/02/21 13:44:53 roberto Exp $ +** Coroutine Library +** See Copyright Notice in lua.h +*/ + + +#include + + +#define lcorolib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +static int auxresume (lua_State *L, lua_State *co, int narg) { + int status; + if (!lua_checkstack(co, narg)) { + lua_pushliteral(L, "too many arguments to resume"); + return -1; /* error flag */ + } + if (lua_status(co) == LUA_OK && lua_gettop(co) == 0) { + lua_pushliteral(L, "cannot resume dead coroutine"); + return -1; /* error flag */ + } + lua_xmove(L, co, narg); + status = lua_resume(co, L, narg); + if (status == LUA_OK || status == LUA_YIELD) { + int nres = lua_gettop(co); + if (!lua_checkstack(L, nres + 1)) { + lua_pop(co, nres); /* remove results anyway */ + lua_pushliteral(L, "too many results to resume"); + return -1; /* error flag */ + } + lua_xmove(co, L, nres); /* move yielded values */ + return nres; + } + else { + lua_xmove(co, L, 1); /* move error message */ + return -1; /* error flag */ + } +} + + +static int luaB_coresume (lua_State *L) { + lua_State *co = lua_tothread(L, 1); + int r; + luaL_argcheck(L, co, 1, "coroutine expected"); + r = auxresume(L, co, lua_gettop(L) - 1); + if (r < 0) { + lua_pushboolean(L, 0); + lua_insert(L, -2); + return 2; /* return false + error message */ + } + else { + lua_pushboolean(L, 1); + lua_insert(L, -(r + 1)); + return r + 1; /* return true + `resume' returns */ + } +} + + +static int luaB_auxwrap (lua_State *L) { + lua_State *co = lua_tothread(L, lua_upvalueindex(1)); + int r = auxresume(L, co, lua_gettop(L)); + if (r < 0) { + if (lua_isstring(L, -1)) { /* error object is a string? */ + luaL_where(L, 1); /* add extra info */ + lua_insert(L, -2); + lua_concat(L, 2); + } + return lua_error(L); /* propagate error */ + } + return r; +} + + +static int luaB_cocreate (lua_State *L) { + lua_State *NL; + luaL_checktype(L, 1, LUA_TFUNCTION); + NL = lua_newthread(L); + lua_pushvalue(L, 1); /* move function to top */ + lua_xmove(L, NL, 1); /* move function from L to NL */ + return 1; +} + + +static int luaB_cowrap (lua_State *L) { + luaB_cocreate(L); + lua_pushcclosure(L, luaB_auxwrap, 1); + return 1; +} + + +static int luaB_yield (lua_State *L) { + return lua_yield(L, lua_gettop(L)); +} + + +static int luaB_costatus (lua_State *L) { + lua_State *co = lua_tothread(L, 1); + luaL_argcheck(L, co, 1, "coroutine expected"); + if (L == co) lua_pushliteral(L, "running"); + else { + switch (lua_status(co)) { + case LUA_YIELD: + lua_pushliteral(L, "suspended"); + break; + case LUA_OK: { + lua_Debug ar; + if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */ + lua_pushliteral(L, "normal"); /* it is running */ + else if (lua_gettop(co) == 0) + lua_pushliteral(L, "dead"); + else + lua_pushliteral(L, "suspended"); /* initial state */ + break; + } + default: /* some error occurred */ + lua_pushliteral(L, "dead"); + break; + } + } + return 1; +} + + +static int luaB_corunning (lua_State *L) { + int ismain = lua_pushthread(L); + lua_pushboolean(L, ismain); + return 2; +} + + +static const luaL_Reg co_funcs[] = { + {"create", luaB_cocreate}, + {"resume", luaB_coresume}, + {"running", luaB_corunning}, + {"status", luaB_costatus}, + {"wrap", luaB_cowrap}, + {"yield", luaB_yield}, + {NULL, NULL} +}; + + + +LUAMOD_API int luaopen_coroutine (lua_State *L) { + luaL_newlib(L, co_funcs); + return 1; +} + diff --git a/components/pico8/femto8/src/lua/lctype.c b/components/pico8/femto8/src/lua/lctype.c new file mode 100644 index 00000000..78ecd77c --- /dev/null +++ b/components/pico8/femto8/src/lua/lctype.c @@ -0,0 +1,52 @@ +/* +** $Id: lctype.c,v 1.11 2011/10/03 16:19:23 roberto Exp $ +** 'ctype' functions for Lua +** See Copyright Notice in lua.h +*/ + +#define lctype_c +#define LUA_CORE + +#include "lctype.h" + +#if !LUA_USE_CTYPE /* { */ + +#include + +LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = { + 0x00, /* EOZ */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */ + 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 1. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, /* 2. */ + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, /* 3. */ + 0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 4. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 5. */ + 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05, + 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 6. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */ + 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 8. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 9. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* a. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* b. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* c. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* d. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* e. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* f. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, +}; + +#endif /* } */ diff --git a/components/pico8/femto8/src/lua/lctype.h b/components/pico8/femto8/src/lua/lctype.h new file mode 100644 index 00000000..12a97548 --- /dev/null +++ b/components/pico8/femto8/src/lua/lctype.h @@ -0,0 +1,96 @@ +/* +** $Id: lctype.h,v 1.12 2011/07/15 12:50:29 roberto Exp $ +** 'ctype' functions for Lua +** See Copyright Notice in lua.h +*/ + +#ifndef lctype_h +#define lctype_h + +#include "lua.h" + + +/* +** WARNING: the functions defined here do not necessarily correspond +** to the similar functions in the standard C ctype.h. They are +** optimized for the specific needs of Lua +*/ + +#if !defined(LUA_USE_CTYPE) + +#if 'A' == 65 && '0' == 48 +/* ASCII case: can use its own tables; faster and fixed */ +#define LUA_USE_CTYPE 0 +#else +/* must use standard C ctype */ +#define LUA_USE_CTYPE 1 +#endif + +#endif + + +#if !LUA_USE_CTYPE /* { */ + +#include + +#include "llimits.h" + + +#define ALPHABIT 0 +#define DIGITBIT 1 +#define PRINTBIT 2 +#define SPACEBIT 3 +#define XDIGITBIT 4 + + +#define MASK(B) (1 << (B)) + + +/* +** add 1 to char to allow index -1 (EOZ) +*/ +#define testprop(c,p) (luai_ctype_[(c)+1] & (p)) + +/* +** 'lalpha' (Lua alphabetic) and 'lalnum' (Lua alphanumeric) both include '_' +*/ +#define lislalpha(c) testprop(c, MASK(ALPHABIT)) +#define lislalnum(c) testprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT))) +#define lisdigit(c) testprop(c, MASK(DIGITBIT)) +#define lisspace(c) testprop(c, MASK(SPACEBIT)) +#define lisprint(c) testprop(c, MASK(PRINTBIT)) +#define lisxdigit(c) testprop(c, MASK(XDIGITBIT)) + +/* +** this 'ltolower' only works for alphabetic characters +*/ +#define ltolower(c) ((c) | ('A' ^ 'a')) + + +/* two more entries for 0 and -1 (EOZ) */ +LUAI_DDEC const lu_byte luai_ctype_[UCHAR_MAX + 2]; + + +#else /* }{ */ + +/* +** use standard C ctypes +*/ + +#include + + +#define lisspecial(c) (((int)(c) >= 0x10 && (int)(c) < 0x20) || (int)(c) >= 0x7f) +#define lislalpha(c) (isalpha(c) || (c) == '_' || lisspecial(c)) +#define lislalnum(c) (isalnum(c) || (c) == '_' || lisspecial(c)) +#define lisdigit(c) (isdigit(c)) +#define lisspace(c) (isspace(c)) +#define lisprint(c) (isprint(c)) +#define lisxdigit(c) (isxdigit(c)) + +#define ltolower(c) (tolower(c)) + +#endif /* } */ + +#endif + diff --git a/components/pico8/femto8/src/lua/ldblib.c b/components/pico8/femto8/src/lua/ldblib.c new file mode 100644 index 00000000..f71e1fdd --- /dev/null +++ b/components/pico8/femto8/src/lua/ldblib.c @@ -0,0 +1,408 @@ +/* +** $Id: ldblib.c,v 1.132.1.1 2013/04/12 18:48:47 roberto Exp roberto $ +** Interface from Lua to its debug API +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include + +#define ldblib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +#define HOOKKEY "_HKEY" + + +static void checkstack (lua_State *L, lua_State *L1, int n) { + if (L != L1 && !lua_checkstack(L1, n)) + luaL_error(L, "stack overflow"); +} + + +static int db_getregistry (lua_State *L) { + lua_pushvalue(L, LUA_REGISTRYINDEX); + return 1; +} + + +static int db_getmetatable (lua_State *L) { + luaL_checkany(L, 1); + if (!lua_getmetatable(L, 1)) { + lua_pushnil(L); /* no metatable */ + } + return 1; +} + + +static int db_setmetatable (lua_State *L) { + int t = lua_type(L, 2); + luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, + "nil or table expected"); + lua_settop(L, 2); + lua_setmetatable(L, 1); + return 1; /* return 1st argument */ +} + + +static int db_getuservalue (lua_State *L) { + if (lua_type(L, 1) != LUA_TUSERDATA) + lua_pushnil(L); + else + lua_getuservalue(L, 1); + return 1; +} + + +static int db_setuservalue (lua_State *L) { + if (lua_type(L, 1) == LUA_TLIGHTUSERDATA) + luaL_argerror(L, 1, "full userdata expected, got light userdata"); + luaL_checktype(L, 1, LUA_TUSERDATA); + if (!lua_isnoneornil(L, 2)) + luaL_checktype(L, 2, LUA_TTABLE); + lua_settop(L, 2); + lua_setuservalue(L, 1); + return 1; +} + + +static void settabss (lua_State *L, const char *i, const char *v) { + lua_pushstring(L, v); + lua_setfield(L, -2, i); +} + + +static void settabsi (lua_State *L, const char *i, int v) { + lua_pushinteger(L, v); + lua_setfield(L, -2, i); +} + + +static void settabsb (lua_State *L, const char *i, int v) { + lua_pushboolean(L, v); + lua_setfield(L, -2, i); +} + + +static lua_State *getthread (lua_State *L, int *arg) { + if (lua_isthread(L, 1)) { + *arg = 1; + return lua_tothread(L, 1); + } + else { + *arg = 0; + return L; + } +} + + +static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) { + if (L == L1) { + lua_pushvalue(L, -2); + lua_remove(L, -3); + } + else + lua_xmove(L1, L, 1); + lua_setfield(L, -2, fname); +} + + +static int db_getinfo (lua_State *L) { + lua_Debug ar; + int arg; + lua_State *L1 = getthread(L, &arg); + const char *options = luaL_optstring(L, arg+2, "flnStu"); + checkstack(L, L1, 3); + if (lua_isnumber(L, arg+1)) { + if (!lua_getstack(L1, (int)lua_tointeger(L, arg+1), &ar)) { + lua_pushnil(L); /* level out of range */ + return 1; + } + } + else if (lua_isfunction(L, arg+1)) { + lua_pushfstring(L, ">%s", options); + options = lua_tostring(L, -1); + lua_pushvalue(L, arg+1); + lua_xmove(L, L1, 1); + } + else + return luaL_argerror(L, arg+1, "function or level expected"); + if (!lua_getinfo(L1, options, &ar)) + return luaL_argerror(L, arg+2, "invalid option"); + lua_createtable(L, 0, 2); + if (strchr(options, 'S')) { + settabss(L, "source", ar.source); + settabss(L, "short_src", ar.short_src); + settabsi(L, "linedefined", ar.linedefined); + settabsi(L, "lastlinedefined", ar.lastlinedefined); + settabss(L, "what", ar.what); + } + if (strchr(options, 'l')) + settabsi(L, "currentline", ar.currentline); + if (strchr(options, 'u')) { + settabsi(L, "nups", ar.nups); + settabsi(L, "nparams", ar.nparams); + settabsb(L, "isvararg", ar.isvararg); + } + if (strchr(options, 'n')) { + settabss(L, "name", ar.name); + settabss(L, "namewhat", ar.namewhat); + } + if (strchr(options, 't')) + settabsb(L, "istailcall", ar.istailcall); + if (strchr(options, 'L')) + treatstackoption(L, L1, "activelines"); + if (strchr(options, 'f')) + treatstackoption(L, L1, "func"); + return 1; /* return table */ +} + + +static int db_getlocal (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + lua_Debug ar; + const char *name; + int nvar = luaL_checkint(L, arg+2); /* local-variable index */ + if (lua_isfunction(L, arg + 1)) { /* function argument? */ + lua_pushvalue(L, arg + 1); /* push function */ + lua_pushstring(L, lua_getlocal(L, NULL, nvar)); /* push local name */ + return 1; + } + else { /* stack-level argument */ + if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ + return luaL_argerror(L, arg+1, "level out of range"); + checkstack(L, L1, 1); + name = lua_getlocal(L1, &ar, nvar); + if (name) { + lua_xmove(L1, L, 1); /* push local value */ + lua_pushstring(L, name); /* push name */ + lua_pushvalue(L, -2); /* re-order */ + return 2; + } + else { + lua_pushnil(L); /* no name (nor value) */ + return 1; + } + } +} + + +static int db_setlocal (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + lua_Debug ar; + if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ + return luaL_argerror(L, arg+1, "level out of range"); + luaL_checkany(L, arg+3); + lua_settop(L, arg+3); + checkstack(L, L1, 1); + lua_xmove(L, L1, 1); + lua_pushstring(L, lua_setlocal(L1, &ar, luaL_checkint(L, arg+2))); + return 1; +} + + +static int auxupvalue (lua_State *L, int get) { + const char *name; + int n = luaL_checkint(L, 2); + luaL_checktype(L, 1, LUA_TFUNCTION); + name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n); + if (name == NULL) return 0; + lua_pushstring(L, name); + lua_insert(L, -(get+1)); + return get + 1; +} + + +static int db_getupvalue (lua_State *L) { + return auxupvalue(L, 1); +} + + +static int db_setupvalue (lua_State *L) { + luaL_checkany(L, 3); + return auxupvalue(L, 0); +} + + +static int checkupval (lua_State *L, int argf, int argnup) { + lua_Debug ar; + int nup = luaL_checkint(L, argnup); + luaL_checktype(L, argf, LUA_TFUNCTION); + lua_pushvalue(L, argf); + lua_getinfo(L, ">u", &ar); + luaL_argcheck(L, 1 <= nup && nup <= ar.nups, argnup, "invalid upvalue index"); + return nup; +} + + +static int db_upvalueid (lua_State *L) { + int n = checkupval(L, 1, 2); + lua_pushlightuserdata(L, lua_upvalueid(L, 1, n)); + return 1; +} + + +static int db_upvaluejoin (lua_State *L) { + int n1 = checkupval(L, 1, 2); + int n2 = checkupval(L, 3, 4); + luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected"); + luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected"); + lua_upvaluejoin(L, 1, n1, 3, n2); + return 0; +} + + +#define gethooktable(L) luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY) + + +static void hookf (lua_State *L, lua_Debug *ar) { + static const char *const hooknames[] = + {"call", "return", "line", "count", "tail call"}; + gethooktable(L); + lua_pushthread(L); + lua_rawget(L, -2); + if (lua_isfunction(L, -1)) { + lua_pushstring(L, hooknames[(int)ar->event]); + if (ar->currentline >= 0) + lua_pushinteger(L, ar->currentline); + else lua_pushnil(L); + lua_assert(lua_getinfo(L, "lS", ar)); + lua_call(L, 2, 0); + } +} + + +static int makemask (const char *smask, int count) { + int mask = 0; + if (strchr(smask, 'c')) mask |= LUA_MASKCALL; + if (strchr(smask, 'r')) mask |= LUA_MASKRET; + if (strchr(smask, 'l')) mask |= LUA_MASKLINE; + if (count > 0) mask |= LUA_MASKCOUNT; + return mask; +} + + +static char *unmakemask (int mask, char *smask) { + int i = 0; + if (mask & LUA_MASKCALL) smask[i++] = 'c'; + if (mask & LUA_MASKRET) smask[i++] = 'r'; + if (mask & LUA_MASKLINE) smask[i++] = 'l'; + smask[i] = '\0'; + return smask; +} + + +static int db_sethook (lua_State *L) { + int arg, mask, count; + lua_Hook func; + lua_State *L1 = getthread(L, &arg); + if (lua_isnoneornil(L, arg+1)) { + lua_settop(L, arg+1); + func = NULL; mask = 0; count = 0; /* turn off hooks */ + } + else { + const char *smask = luaL_checkstring(L, arg+2); + luaL_checktype(L, arg+1, LUA_TFUNCTION); + count = luaL_optint(L, arg+3, 0); + func = hookf; mask = makemask(smask, count); + } + if (gethooktable(L) == 0) { /* creating hook table? */ + lua_pushstring(L, "k"); + lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */ + lua_pushvalue(L, -1); + lua_setmetatable(L, -2); /* setmetatable(hooktable) = hooktable */ + } + checkstack(L, L1, 1); + lua_pushthread(L1); lua_xmove(L1, L, 1); + lua_pushvalue(L, arg+1); + lua_rawset(L, -3); /* set new hook */ + lua_sethook(L1, func, mask, count); /* set hooks */ + return 0; +} + + +static int db_gethook (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + char buff[5]; + int mask = lua_gethookmask(L1); + lua_Hook hook = lua_gethook(L1); + if (hook != NULL && hook != hookf) /* external hook? */ + lua_pushliteral(L, "external hook"); + else { + gethooktable(L); + checkstack(L, L1, 1); + lua_pushthread(L1); lua_xmove(L1, L, 1); + lua_rawget(L, -2); /* get hook */ + lua_remove(L, -2); /* remove hook table */ + } + lua_pushstring(L, unmakemask(mask, buff)); + lua_pushinteger(L, lua_gethookcount(L1)); + return 3; +} + + +static int db_debug (lua_State *L) { + for (;;) { + char buffer[250]; + luai_writestringerror("%s", "lua_debug> "); + if (fgets(buffer, sizeof(buffer), stdin) == 0 || + strcmp(buffer, "cont\n") == 0) + return 0; + if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || + lua_pcall(L, 0, 0, 0)) + luai_writestringerror("%s\n", lua_tostring(L, -1)); + lua_settop(L, 0); /* remove eventual returns */ + } +} + + +static int db_traceback (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + const char *msg = lua_tostring(L, arg + 1); + if (msg == NULL && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */ + lua_pushvalue(L, arg + 1); /* return it untouched */ + else { + int level = luaL_optint(L, arg + 2, (L == L1) ? 1 : 0); + luaL_traceback(L, L1, msg, level); + } + return 1; +} + + +static const luaL_Reg dblib[] = { + {"debug", db_debug}, + {"getuservalue", db_getuservalue}, + {"gethook", db_gethook}, + {"getinfo", db_getinfo}, + {"getlocal", db_getlocal}, + {"getregistry", db_getregistry}, + {"getmetatable", db_getmetatable}, + {"getupvalue", db_getupvalue}, + {"upvaluejoin", db_upvaluejoin}, + {"upvalueid", db_upvalueid}, + {"setuservalue", db_setuservalue}, + {"sethook", db_sethook}, + {"setlocal", db_setlocal}, + {"setmetatable", db_setmetatable}, + {"setupvalue", db_setupvalue}, + {"traceback", db_traceback}, + {NULL, NULL} +}; + + +LUAMOD_API int luaopen_debug (lua_State *L) { + luaL_newlib(L, dblib); + return 1; +} + diff --git a/components/pico8/femto8/src/lua/ldebug.c b/components/pico8/femto8/src/lua/ldebug.c new file mode 100644 index 00000000..7868d0fe --- /dev/null +++ b/components/pico8/femto8/src/lua/ldebug.c @@ -0,0 +1,620 @@ +/* +** $Id: ldebug.c,v 2.90.1.3 2013/05/16 16:04:15 roberto Exp roberto $ +** Debug Interface +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include + + +#define ldebug_c +#define LUA_CORE + +#include "lua.h" + +#include "lapi.h" +#include "lcode.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lvm.h" + + + +#define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_TCCL) + + +static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name); + + +static int currentpc (CallInfo *ci) { + lua_assert(isLua(ci)); + return pcRel(ci->u.l.savedpc, ci_func(ci)->p); +} + + +static int currentline (CallInfo *ci) { + return getfuncline(ci_func(ci)->p, currentpc(ci)); +} + + +static void swapextra (lua_State *L) { + if (L->status == LUA_YIELD) { + CallInfo *ci = L->ci; /* get function that yielded */ + StkId temp = ci->func; /* exchange its 'func' and 'extra' values */ + ci->func = restorestack(L, ci->extra); + ci->extra = savestack(L, temp); + } +} + + +/* +** this function can be called asynchronous (e.g. during a signal) +*/ +LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { + if (func == NULL || mask == 0) { /* turn off hooks? */ + mask = 0; + func = NULL; + } + if (isLua(L->ci)) + L->oldpc = L->ci->u.l.savedpc; + L->hook = func; + L->basehookcount = count; + resethookcount(L); + L->hookmask = cast_byte(mask); + return 1; +} + + +LUA_API lua_Hook lua_gethook (lua_State *L) { + return L->hook; +} + + +LUA_API int lua_gethookmask (lua_State *L) { + return L->hookmask; +} + + +LUA_API int lua_gethookcount (lua_State *L) { + return L->basehookcount; +} + + +LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { + int status; + CallInfo *ci; + if (level < 0) return 0; /* invalid (negative) level */ + lua_lock(L); + for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous) + level--; + if (level == 0 && ci != &L->base_ci) { /* level found? */ + status = 1; + ar->i_ci = ci; + } + else status = 0; /* no such level */ + lua_unlock(L); + return status; +} + + +static const char *upvalname (Proto *p, int uv) { + TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name); + if (s == NULL) return "?"; + else return getstr(s); +} + + +static const char *findvararg (CallInfo *ci, int n, StkId *pos) { + int nparams = clLvalue(ci->func)->p->numparams; + if (n >= ci->u.l.base - ci->func - nparams) + return NULL; /* no such vararg */ + else { + *pos = ci->func + nparams + n; + return "(*vararg)"; /* generic name for any vararg */ + } +} + + +static const char *findlocal (lua_State *L, CallInfo *ci, int n, + StkId *pos) { + const char *name = NULL; + StkId base; + if (isLua(ci)) { + if (n < 0) /* access to vararg values? */ + return findvararg(ci, -n, pos); + else { + base = ci->u.l.base; + name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci)); + } + } + else + base = ci->func + 1; + if (name == NULL) { /* no 'standard' name? */ + StkId limit = (ci == L->ci) ? L->top : ci->next->func; + if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */ + name = "(*temporary)"; /* generic name for any valid slot */ + else + return NULL; /* no name */ + } + *pos = base + (n - 1); + return name; +} + + +LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { + const char *name; + lua_lock(L); + swapextra(L); + if (ar == NULL) { /* information about non-active function? */ + if (!isLfunction(L->top - 1)) /* not a Lua function? */ + name = NULL; + else /* consider live variables at function start (parameters) */ + name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0); + } + else { /* active function; get information through 'ar' */ + StkId pos = 0; /* to avoid warnings */ + name = findlocal(L, ar->i_ci, n, &pos); + if (name) { + setobj2s(L, L->top, pos); + api_incr_top(L); + } + } + swapextra(L); + lua_unlock(L); + return name; +} + + +LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { + StkId pos = 0; /* to avoid warnings */ + const char *name; + lua_lock(L); + swapextra(L); + name = findlocal(L, ar->i_ci, n, &pos); + if (name) + setobjs2s(L, pos, L->top - 1); + L->top--; /* pop value */ + swapextra(L); + lua_unlock(L); + return name; +} + + +static void funcinfo (lua_Debug *ar, Closure *cl) { + if (noLuaClosure(cl)) { + ar->source = "=[C]"; + ar->linedefined = -1; + ar->lastlinedefined = -1; + ar->what = "C"; + } + else { + Proto *p = cl->l.p; + ar->source = p->source ? getstr(p->source) : "=?"; + ar->linedefined = p->linedefined; + ar->lastlinedefined = p->lastlinedefined; + ar->what = (ar->linedefined == 0) ? "main" : "Lua"; + } + luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); +} + + +static void collectvalidlines (lua_State *L, Closure *f) { + if (noLuaClosure(f)) { + setnilvalue(L->top); + api_incr_top(L); + } + else { + int i; + TValue v; + int *lineinfo = f->l.p->lineinfo; + Table *t = luaH_new(L); /* new table to store active lines */ + sethvalue(L, L->top, t); /* push it on stack */ + api_incr_top(L); + setbvalue(&v, 1); /* boolean 'true' to be the value of all indices */ + for (i = 0; i < f->l.p->sizelineinfo; i++) /* for all lines with code */ + luaH_setint(L, t, lineinfo[i], &v); /* table[line] = true */ + } +} + + +static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, + Closure *f, CallInfo *ci) { + int status = 1; + for (; *what; what++) { + switch (*what) { + case 'S': { + funcinfo(ar, f); + break; + } + case 'l': { + ar->currentline = (ci && isLua(ci)) ? currentline(ci) : -1; + break; + } + case 'u': { + ar->nups = (f == NULL) ? 0 : f->c.nupvalues; + if (noLuaClosure(f)) { + ar->isvararg = 1; + ar->nparams = 0; + } + else { + ar->isvararg = f->l.p->is_vararg; + ar->nparams = f->l.p->numparams; + } + break; + } + case 't': { + ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0; + break; + } + case 'n': { + /* calling function is a known Lua function? */ + if (ci && !(ci->callstatus & CIST_TAIL) && isLua(ci->previous)) + ar->namewhat = getfuncname(L, ci->previous, &ar->name); + else + ar->namewhat = NULL; + if (ar->namewhat == NULL) { + ar->namewhat = ""; /* not found */ + ar->name = NULL; + } + break; + } + case 'L': + case 'f': /* handled by lua_getinfo */ + break; + default: status = 0; /* invalid option */ + } + } + return status; +} + + +LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { + int status; + Closure *cl; + CallInfo *ci; + StkId func; + lua_lock(L); + swapextra(L); + if (*what == '>') { + ci = NULL; + func = L->top - 1; + api_check(L, ttisfunction(func), "function expected"); + what++; /* skip the '>' */ + L->top--; /* pop function */ + } + else { + ci = ar->i_ci; + func = ci->func; + lua_assert(ttisfunction(ci->func)); + } + cl = ttisclosure(func) ? clvalue(func) : NULL; + status = auxgetinfo(L, what, ar, cl, ci); + if (strchr(what, 'f')) { + setobjs2s(L, L->top, func); + api_incr_top(L); + } + swapextra(L); + if (strchr(what, 'L')) + collectvalidlines(L, cl); + lua_unlock(L); + return status; +} + + +/* +** {====================================================== +** Symbolic Execution +** ======================================================= +*/ + +static const char *getobjname (Proto *p, int lastpc, int reg, + const char **name); + + +/* +** find a "name" for the RK value 'c' +*/ +static void kname (Proto *p, int pc, int c, const char **name) { + if (ISK(c)) { /* is 'c' a constant? */ + TValue *kvalue = &p->k[INDEXK(c)]; + if (ttisstring(kvalue)) { /* literal constant? */ + *name = svalue(kvalue); /* it is its own name */ + return; + } + /* else no reasonable name found */ + } + else { /* 'c' is a register */ + const char *what = getobjname(p, pc, c, name); /* search for 'c' */ + if (what && *what == 'c') { /* found a constant name? */ + return; /* 'name' already filled */ + } + /* else no reasonable name found */ + } + *name = "?"; /* no reasonable name found */ +} + + +static int filterpc (int pc, int jmptarget) { + if (pc < jmptarget) /* is code conditional (inside a jump)? */ + return -1; /* cannot know who sets that register */ + else return pc; /* current position sets that register */ +} + + +/* +** try to find last instruction before 'lastpc' that modified register 'reg' +*/ +static int findsetreg (Proto *p, int lastpc, int reg) { + int pc; + int setreg = -1; /* keep last instruction that changed 'reg' */ + int jmptarget = 0; /* any code before this address is conditional */ + for (pc = 0; pc < lastpc; pc++) { + Instruction i = p->code[pc]; + OpCode op = GET_OPCODE(i); + int a = GETARG_A(i); + switch (op) { + case OP_LOADNIL: { + int b = GETARG_B(i); + if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */ + setreg = filterpc(pc, jmptarget); + break; + } + case OP_TFORCALL: { + if (reg >= a + 2) /* affect all regs above its base */ + setreg = filterpc(pc, jmptarget); + break; + } + case OP_CALL: + case OP_TAILCALL: { + if (reg >= a) /* affect all registers above base */ + setreg = filterpc(pc, jmptarget); + break; + } + case OP_JMP: { + int b = GETARG_sBx(i); + int dest = pc + 1 + b; + /* jump is forward and do not skip `lastpc'? */ + if (pc < dest && dest <= lastpc) { + if (dest > jmptarget) + jmptarget = dest; /* update 'jmptarget' */ + } + break; + } + case OP_TEST: { + if (reg == a) /* jumped code can change 'a' */ + setreg = filterpc(pc, jmptarget); + break; + } + default: + if (testAMode(op) && reg == a) /* any instruction that set A */ + setreg = filterpc(pc, jmptarget); + break; + } + } + return setreg; +} + + +static const char *getobjname (Proto *p, int lastpc, int reg, + const char **name) { + int pc; + *name = luaF_getlocalname(p, reg + 1, lastpc); + if (*name) /* is a local? */ + return "local"; + /* else try symbolic execution */ + pc = findsetreg(p, lastpc, reg); + if (pc != -1) { /* could find instruction? */ + Instruction i = p->code[pc]; + OpCode op = GET_OPCODE(i); + switch (op) { + case OP_MOVE: { + int b = GETARG_B(i); /* move from 'b' to 'a' */ + if (b < GETARG_A(i)) + return getobjname(p, pc, b, name); /* get name for 'b' */ + break; + } + case OP_GETTABUP: + case OP_GETTABLE: { + int k = GETARG_C(i); /* key index */ + int t = GETARG_B(i); /* table index */ + const char *vn = (op == OP_GETTABLE) /* name of indexed variable */ + ? luaF_getlocalname(p, t + 1, pc) + : upvalname(p, t); + kname(p, pc, k, name); + return (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field"; + } + case OP_GETUPVAL: { + *name = upvalname(p, GETARG_B(i)); + return "upvalue"; + } + case OP_LOADK: + case OP_LOADKX: { + int b = (op == OP_LOADK) ? GETARG_Bx(i) + : GETARG_Ax(p->code[pc + 1]); + if (ttisstring(&p->k[b])) { + *name = svalue(&p->k[b]); + return "constant"; + } + break; + } + case OP_SELF: { + int k = GETARG_C(i); /* key index */ + kname(p, pc, k, name); + return "method"; + } + default: break; /* go through to return NULL */ + } + } + return NULL; /* could not find reasonable name */ +} + + +static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { + TMS tm; + Proto *p = ci_func(ci)->p; /* calling function */ + int pc = currentpc(ci); /* calling instruction index */ + Instruction i = p->code[pc]; /* calling instruction */ + switch (GET_OPCODE(i)) { + case OP_CALL: + case OP_TAILCALL: /* get function name */ + return getobjname(p, pc, GETARG_A(i), name); + case OP_TFORCALL: { /* for iterator */ + *name = "for iterator"; + return "for iterator"; + } + /* all other instructions can call only through metamethods */ + case OP_SELF: + case OP_GETTABUP: + case OP_GETTABLE: tm = TM_INDEX; break; + case OP_SETTABUP: + case OP_SETTABLE: tm = TM_NEWINDEX; break; + case OP_EQ: tm = TM_EQ; break; + case OP_ADD: tm = TM_ADD; break; + case OP_SUB: tm = TM_SUB; break; + case OP_MUL: tm = TM_MUL; break; + case OP_DIV: tm = TM_DIV; break; + case OP_MOD: tm = TM_MOD; break; + case OP_POW: tm = TM_POW; break; + case OP_IDIV: tm = TM_IDIV; break; + case OP_BAND: tm = TM_BAND; break; + case OP_BOR: tm = TM_BOR; break; + case OP_BXOR: tm = TM_BXOR; break; + case OP_SHL: tm = TM_SHL; break; + case OP_SHR: tm = TM_SHR; break; + case OP_LSHR: tm = TM_LSHR; break; + case OP_ROTL: tm = TM_ROTL; break; + case OP_ROTR: tm = TM_ROTR; break; + case OP_UNM: tm = TM_UNM; break; + case OP_BNOT: tm = TM_BNOT; break; + case OP_LEN: tm = TM_LEN; break; + case OP_LT: tm = TM_LT; break; + case OP_LE: tm = TM_LE; break; + case OP_CONCAT: tm = TM_CONCAT; break; + default: + return NULL; /* else no useful name can be found */ + } + *name = getstr(G(L)->tmname[tm]); + return "metamethod"; +} + +/* }====================================================== */ + + + +/* +** only ANSI way to check whether a pointer points to an array +** (used only for error messages, so efficiency is not a big concern) +*/ +static int isinstack (CallInfo *ci, const TValue *o) { + StkId p; + for (p = ci->u.l.base; p < ci->top; p++) + if (o == p) return 1; + return 0; +} + + +static const char *getupvalname (CallInfo *ci, const TValue *o, + const char **name) { + LClosure *c = ci_func(ci); + int i; + for (i = 0; i < c->nupvalues; i++) { + if (c->upvals[i]->v == o) { + *name = upvalname(c->p, i); + return "upvalue"; + } + } + return NULL; +} + + +l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) { + CallInfo *ci = L->ci; + const char *name = NULL; + const char *t = objtypename(o); + const char *kind = NULL; + if (isLua(ci)) { + kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */ + if (!kind && isinstack(ci, o)) /* no? try a register */ + kind = getobjname(ci_func(ci)->p, currentpc(ci), + cast_int(o - ci->u.l.base), &name); + } + if (kind) + luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)", + op, kind, name, t); + else + luaG_runerror(L, "attempt to %s a %s value", op, t); +} + + +l_noret luaG_concaterror (lua_State *L, StkId p1, StkId p2) { + if (ttisstring(p1) || ttisnumber(p1)) p1 = p2; + lua_assert(!ttisstring(p1) && !ttisnumber(p1)); + luaG_typeerror(L, p1, "concatenate"); +} + + +l_noret luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) { + TValue temp; + if (luaV_tonumber(p1, &temp) == NULL) + p2 = p1; /* first operand is wrong */ + luaG_typeerror(L, p2, "perform arithmetic on"); +} + + +l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { + const char *t1 = objtypename(p1); + const char *t2 = objtypename(p2); + if (t1 == t2) + luaG_runerror(L, "attempt to compare two %s values", t1); + else + luaG_runerror(L, "attempt to compare %s with %s", t1, t2); +} + + +static void addinfo (lua_State *L, const char *msg) { + CallInfo *ci = L->ci; + if (isLua(ci)) { /* is Lua code? */ + char buff[LUA_IDSIZE]; /* add file:line information */ + int line = currentline(ci); + TString *src = ci_func(ci)->p->source; + if (src) + luaO_chunkid(buff, getstr(src), LUA_IDSIZE); + else { /* no source available; use "?" instead */ + buff[0] = '?'; buff[1] = '\0'; + } + luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); + } +} + + +l_noret luaG_errormsg (lua_State *L) { + if (L->errfunc != 0) { /* is there an error handling function? */ + StkId errfunc = restorestack(L, L->errfunc); + if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR); + setobjs2s(L, L->top, L->top - 1); /* move argument */ + setobjs2s(L, L->top - 1, errfunc); /* push function */ + L->top++; + luaD_call(L, L->top - 2, 1, 0); /* call it */ + } + luaD_throw(L, LUA_ERRRUN); +} + + +l_noret luaG_runerror (lua_State *L, const char *fmt, ...) { + va_list argp; + va_start(argp, fmt); + addinfo(L, luaO_pushvfstring(L, fmt, argp)); + va_end(argp); + luaG_errormsg(L); +} + diff --git a/components/pico8/femto8/src/lua/ldebug.h b/components/pico8/femto8/src/lua/ldebug.h new file mode 100644 index 00000000..fe39556b --- /dev/null +++ b/components/pico8/femto8/src/lua/ldebug.h @@ -0,0 +1,34 @@ +/* +** $Id: ldebug.h,v 2.7 2011/10/07 20:45:19 roberto Exp $ +** Auxiliary functions from Debug Interface module +** See Copyright Notice in lua.h +*/ + +#ifndef ldebug_h +#define ldebug_h + + +#include "lstate.h" + + +#define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1) + +#define getfuncline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0) + +#define resethookcount(L) (L->hookcount = L->basehookcount) + +/* Active Lua function (given call info) */ +#define ci_func(ci) (clLvalue((ci)->func)) + + +LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o, + const char *opname); +LUAI_FUNC l_noret luaG_concaterror (lua_State *L, StkId p1, StkId p2); +LUAI_FUNC l_noret luaG_aritherror (lua_State *L, const TValue *p1, + const TValue *p2); +LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1, + const TValue *p2); +LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...); +LUAI_FUNC l_noret luaG_errormsg (lua_State *L); + +#endif diff --git a/components/pico8/femto8/src/lua/ldo.c b/components/pico8/femto8/src/lua/ldo.c new file mode 100644 index 00000000..7ab9312f --- /dev/null +++ b/components/pico8/femto8/src/lua/ldo.c @@ -0,0 +1,681 @@ +/* +** $Id: ldo.c,v 2.108.1.2 2013/04/19 21:03:23 roberto Exp roberto $ +** Stack and Call structure of Lua +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include + +#define ldo_c +#define LUA_CORE + +#include "lua.h" + +#include "lapi.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lundump.h" +#include "lvm.h" +#include "lzio.h" + + + + +/* +** {====================================================== +** Error-recovery functions +** ======================================================= +*/ + +/* +** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By +** default, Lua handles errors with exceptions when compiling as +** C++ code, with _longjmp/_setjmp when asked to use them, and with +** longjmp/setjmp otherwise. +*/ +#if !defined(LUAI_THROW) + +#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) +/* C++ exceptions */ +#define LUAI_THROW(L,c) throw(c) +#define LUAI_TRY(L,c,a) \ + try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; } +#define luai_jmpbuf int /* dummy variable */ + +#elif defined(LUA_USE_ULONGJMP) +/* in Unix, try _longjmp/_setjmp (more efficient) */ +#define LUAI_THROW(L,c) _longjmp((c)->b, 1) +#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a } +#define luai_jmpbuf jmp_buf + +#else +/* default handling with long jumps */ +#define LUAI_THROW(L,c) longjmp((c)->b, 1) +#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } +#define luai_jmpbuf jmp_buf + +#endif + +#endif + + + +/* chain list of long jump buffers */ +struct lua_longjmp { + struct lua_longjmp *previous; + luai_jmpbuf b; + volatile int status; /* error code */ +}; + + +static void seterrorobj (lua_State *L, int errcode, StkId oldtop) { + switch (errcode) { + case LUA_ERRMEM: { /* memory error? */ + setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */ + break; + } + case LUA_ERRERR: { + setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); + break; + } + default: { + setobjs2s(L, oldtop, L->top - 1); /* error message on current top */ + break; + } + } + L->top = oldtop + 1; +} + + +l_noret luaD_throw (lua_State *L, int errcode) { + if (L->errorJmp) { /* thread has an error handler? */ + L->errorJmp->status = errcode; /* set status */ + LUAI_THROW(L, L->errorJmp); /* jump to it */ + } + else { /* thread has no error handler */ + L->status = cast_byte(errcode); /* mark it as dead */ + if (G(L)->mainthread->errorJmp) { /* main thread has a handler? */ + setobjs2s(L, G(L)->mainthread->top++, L->top - 1); /* copy error obj. */ + luaD_throw(G(L)->mainthread, errcode); /* re-throw in main thread */ + } + else { /* no handler at all; abort */ + if (G(L)->panic) { /* panic function? */ + lua_unlock(L); + G(L)->panic(L); /* call it (last chance to jump out) */ + } + abort(); + } + } +} + + +int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { + unsigned short oldnCcalls = L->nCcalls; + struct lua_longjmp lj; + lj.status = LUA_OK; + lj.previous = L->errorJmp; /* chain new error handler */ + L->errorJmp = &lj; + LUAI_TRY(L, &lj, + (*f)(L, ud); + ); + L->errorJmp = lj.previous; /* restore old error handler */ + L->nCcalls = oldnCcalls; + return lj.status; +} + +/* }====================================================== */ + + +static void correctstack (lua_State *L, TValue *oldstack) { + CallInfo *ci; + GCObject *up; + L->top = (L->top - oldstack) + L->stack; + for (up = L->openupval; up != NULL; up = up->gch.next) + gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack; + for (ci = L->ci; ci != NULL; ci = ci->previous) { + ci->top = (ci->top - oldstack) + L->stack; + ci->func = (ci->func - oldstack) + L->stack; + if (isLua(ci)) + ci->u.l.base = (ci->u.l.base - oldstack) + L->stack; + } +} + + +/* some space for error handling */ +#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200) + + +void luaD_reallocstack (lua_State *L, int newsize) { + TValue *oldstack = L->stack; + int lim = L->stacksize; + lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE); + lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK); + luaM_reallocvector(L, L->stack, L->stacksize, newsize, TValue); + for (; lim < newsize; lim++) + setnilvalue(L->stack + lim); /* erase new segment */ + L->stacksize = newsize; + L->stack_last = L->stack + newsize - EXTRA_STACK; + correctstack(L, oldstack); +} + + +void luaD_growstack (lua_State *L, int n) { + int size = L->stacksize; + if (size > LUAI_MAXSTACK) /* error after extra size? */ + luaD_throw(L, LUA_ERRERR); + else { + int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK; + int newsize = 2 * size; + if (newsize > LUAI_MAXSTACK) newsize = LUAI_MAXSTACK; + if (newsize < needed) newsize = needed; + if (newsize > LUAI_MAXSTACK) { /* stack overflow? */ + luaD_reallocstack(L, ERRORSTACKSIZE); + luaG_runerror(L, "stack overflow"); + } + else + luaD_reallocstack(L, newsize); + } +} + + +static int stackinuse (lua_State *L) { + CallInfo *ci; + StkId lim = L->top; + for (ci = L->ci; ci != NULL; ci = ci->previous) { + lua_assert(ci->top <= L->stack_last); + if (lim < ci->top) lim = ci->top; + } + return cast_int(lim - L->stack) + 1; /* part of stack in use */ +} + + +void luaD_shrinkstack (lua_State *L) { + int inuse = stackinuse(L); + int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK; + if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK; + if (inuse > LUAI_MAXSTACK || /* handling stack overflow? */ + goodsize >= L->stacksize) /* would grow instead of shrink? */ + condmovestack(L); /* don't change stack (change only for debugging) */ + else + luaD_reallocstack(L, goodsize); /* shrink it */ +} + + +void luaD_hook (lua_State *L, int event, int line) { + lua_Hook hook = L->hook; + if (hook && L->allowhook) { + CallInfo *ci = L->ci; + ptrdiff_t top = savestack(L, L->top); + ptrdiff_t ci_top = savestack(L, ci->top); + lua_Debug ar; + ar.event = event; + ar.currentline = line; + ar.i_ci = ci; + luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ + ci->top = L->top + LUA_MINSTACK; + lua_assert(ci->top <= L->stack_last); + L->allowhook = 0; /* cannot call hooks inside a hook */ + ci->callstatus |= CIST_HOOKED; + lua_unlock(L); + (*hook)(L, &ar); + lua_lock(L); + lua_assert(!L->allowhook); + L->allowhook = 1; + ci->top = restorestack(L, ci_top); + L->top = restorestack(L, top); + ci->callstatus &= ~CIST_HOOKED; + } +} + + +static void callhook (lua_State *L, CallInfo *ci) { + int hook = LUA_HOOKCALL; + ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */ + if (isLua(ci->previous) && + GET_OPCODE(*(ci->previous->u.l.savedpc - 1)) == OP_TAILCALL) { + ci->callstatus |= CIST_TAIL; + hook = LUA_HOOKTAILCALL; + } + luaD_hook(L, hook, -1); + ci->u.l.savedpc--; /* correct 'pc' */ +} + + +static StkId adjust_varargs (lua_State *L, Proto *p, int actual) { + int i; + int nfixargs = p->numparams; + StkId base, fixed; + lua_assert(actual >= nfixargs); + /* move fixed parameters to final position */ + luaD_checkstack(L, p->maxstacksize); /* check again for new 'base' */ + fixed = L->top - actual; /* first fixed argument */ + base = L->top; /* final position of first argument */ + for (i=0; itop++, fixed + i); + setnilvalue(fixed + i); + } + return base; +} + + +static StkId tryfuncTM (lua_State *L, StkId func) { + const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL); + StkId p; + ptrdiff_t funcr = savestack(L, func); + if (!ttisfunction(tm)) + luaG_typeerror(L, func, "call"); + /* Open a hole inside the stack at `func' */ + for (p = L->top; p > func; p--) setobjs2s(L, p, p-1); + incr_top(L); + func = restorestack(L, funcr); /* previous call may change stack */ + setobj2s(L, func, tm); /* tag method is the new function to be called */ + return func; +} + + + +#define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L))) + + +/* +** returns true if function has been executed (C function) +*/ +int luaD_precall (lua_State *L, StkId func, int nresults) { + lua_CFunction f; + CallInfo *ci; + int n; /* number of arguments (Lua) or returns (C) */ + ptrdiff_t funcr = savestack(L, func); + switch (ttype(func)) { + case LUA_TLCF: /* light C function */ + f = fvalue(func); + goto Cfunc; + case LUA_TCCL: { /* C closure */ + f = clCvalue(func)->f; + Cfunc: + luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ + ci = next_ci(L); /* now 'enter' new function */ + ci->nresults = nresults; + ci->func = restorestack(L, funcr); + ci->top = L->top + LUA_MINSTACK; + lua_assert(ci->top <= L->stack_last); + ci->callstatus = 0; + luaC_checkGC(L); /* stack grow uses memory */ + if (L->hookmask & LUA_MASKCALL) + luaD_hook(L, LUA_HOOKCALL, -1); + lua_unlock(L); + n = (*f)(L); /* do the actual call */ + lua_lock(L); + api_checknelems(L, n); + luaD_poscall(L, L->top - n); + return 1; + } + case LUA_TLCL: { /* Lua function: prepare its call */ + StkId base; + Proto *p = clLvalue(func)->p; + n = cast_int(L->top - func) - 1; /* number of real arguments */ + luaD_checkstack(L, p->maxstacksize); + for (; n < p->numparams; n++) + setnilvalue(L->top++); /* complete missing arguments */ + if (!p->is_vararg) { + func = restorestack(L, funcr); + base = func + 1; + } + else { + base = adjust_varargs(L, p, n); + func = restorestack(L, funcr); /* previous call can change stack */ + } + ci = next_ci(L); /* now 'enter' new function */ + ci->nresults = nresults; + ci->func = func; + ci->u.l.base = base; + ci->top = base + p->maxstacksize; + lua_assert(ci->top <= L->stack_last); + ci->u.l.savedpc = p->code; /* starting point */ + ci->callstatus = CIST_LUA; + L->top = ci->top; + luaC_checkGC(L); /* stack grow uses memory */ + if (L->hookmask & LUA_MASKCALL) + callhook(L, ci); + return 0; + } + default: { /* not a function */ + func = tryfuncTM(L, func); /* retry with 'function' tag method */ + return luaD_precall(L, func, nresults); /* now it must be a function */ + } + } +} + + +int luaD_poscall (lua_State *L, StkId firstResult) { + StkId res; + int wanted, i; + CallInfo *ci = L->ci; + if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) { + if (L->hookmask & LUA_MASKRET) { + ptrdiff_t fr = savestack(L, firstResult); /* hook may change stack */ + luaD_hook(L, LUA_HOOKRET, -1); + firstResult = restorestack(L, fr); + } + L->oldpc = ci->previous->u.l.savedpc; /* 'oldpc' for caller function */ + } + res = ci->func; /* res == final position of 1st result */ + wanted = ci->nresults; + L->ci = ci = ci->previous; /* back to caller */ + /* move results to correct place */ + for (i = wanted; i != 0 && firstResult < L->top; i--) + setobjs2s(L, res++, firstResult++); + while (i-- > 0) + setnilvalue(res++); + L->top = res; + return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */ +} + + +/* +** Call a function (C or Lua). The function to be called is at *func. +** The arguments are on the stack, right after the function. +** When returns, all the results are on the stack, starting at the original +** function position. +*/ +void luaD_call (lua_State *L, StkId func, int nResults, int allowyield) { + if (++L->nCcalls >= LUAI_MAXCCALLS) { + if (L->nCcalls == LUAI_MAXCCALLS) + luaG_runerror(L, "C stack overflow"); + else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) + luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ + } + if (!allowyield) L->nny++; + if (!luaD_precall(L, func, nResults)) /* is a Lua function? */ + luaV_execute(L); /* call it */ + if (!allowyield) L->nny--; + L->nCcalls--; +} + + +static void finishCcall (lua_State *L) { + CallInfo *ci = L->ci; + int n; + lua_assert(ci->u.c.k != NULL); /* must have a continuation */ + lua_assert(L->nny == 0); + if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */ + ci->callstatus &= ~CIST_YPCALL; /* finish 'lua_pcall' */ + L->errfunc = ci->u.c.old_errfunc; + } + /* finish 'lua_callk'/'lua_pcall' */ + adjustresults(L, ci->nresults); + /* call continuation function */ + if (!(ci->callstatus & CIST_STAT)) /* no call status? */ + ci->u.c.status = LUA_YIELD; /* 'default' status */ + lua_assert(ci->u.c.status != LUA_OK); + ci->callstatus = (ci->callstatus & ~(CIST_YPCALL | CIST_STAT)) | CIST_YIELDED; + lua_unlock(L); + n = (*ci->u.c.k)(L); + lua_lock(L); + api_checknelems(L, n); + /* finish 'luaD_precall' */ + luaD_poscall(L, L->top - n); +} + + +static void unroll (lua_State *L, void *ud) { + UNUSED(ud); + for (;;) { + if (L->ci == &L->base_ci) /* stack is empty? */ + return; /* coroutine finished normally */ + if (!isLua(L->ci)) /* C function? */ + finishCcall(L); + else { /* Lua function */ + luaV_finishOp(L); /* finish interrupted instruction */ + luaV_execute(L); /* execute down to higher C 'boundary' */ + } + } +} + + +/* +** check whether thread has a suspended protected call +*/ +static CallInfo *findpcall (lua_State *L) { + CallInfo *ci; + for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */ + if (ci->callstatus & CIST_YPCALL) + return ci; + } + return NULL; /* no pending pcall */ +} + + +static int recover (lua_State *L, int status) { + StkId oldtop; + CallInfo *ci = findpcall(L); + if (ci == NULL) return 0; /* no recovery point */ + /* "finish" luaD_pcall */ + oldtop = restorestack(L, ci->extra); + luaF_close(L, oldtop); + seterrorobj(L, status, oldtop); + L->ci = ci; + L->allowhook = ci->u.c.old_allowhook; + L->nny = 0; /* should be zero to be yieldable */ + luaD_shrinkstack(L); + L->errfunc = ci->u.c.old_errfunc; + ci->callstatus |= CIST_STAT; /* call has error status */ + ci->u.c.status = status; /* (here it is) */ + return 1; /* continue running the coroutine */ +} + + +/* +** signal an error in the call to 'resume', not in the execution of the +** coroutine itself. (Such errors should not be handled by any coroutine +** error handler and should not kill the coroutine.) +*/ +static l_noret resume_error (lua_State *L, const char *msg, StkId firstArg) { + L->top = firstArg; /* remove args from the stack */ + setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */ + api_incr_top(L); + luaD_throw(L, -1); /* jump back to 'lua_resume' */ +} + + +/* +** do the work for 'lua_resume' in protected mode +*/ +static void resume (lua_State *L, void *ud) { + int nCcalls = L->nCcalls; + StkId firstArg = cast(StkId, ud); + CallInfo *ci = L->ci; + if (nCcalls >= LUAI_MAXCCALLS) + resume_error(L, "C stack overflow", firstArg); + if (L->status == LUA_OK) { /* may be starting a coroutine */ + if (ci != &L->base_ci) /* not in base level? */ + resume_error(L, "cannot resume non-suspended coroutine", firstArg); + /* coroutine is in base level; start running it */ + if (!luaD_precall(L, firstArg - 1, LUA_MULTRET)) /* Lua function? */ + luaV_execute(L); /* call it */ + } + else if (L->status != LUA_YIELD) + resume_error(L, "cannot resume dead coroutine", firstArg); + else { /* resuming from previous yield */ + L->status = LUA_OK; + ci->func = restorestack(L, ci->extra); + if (isLua(ci)) /* yielded inside a hook? */ + luaV_execute(L); /* just continue running Lua code */ + else { /* 'common' yield */ + if (ci->u.c.k != NULL) { /* does it have a continuation? */ + int n; + ci->u.c.status = LUA_YIELD; /* 'default' status */ + ci->callstatus |= CIST_YIELDED; + lua_unlock(L); + n = (*ci->u.c.k)(L); /* call continuation */ + lua_lock(L); + api_checknelems(L, n); + firstArg = L->top - n; /* yield results come from continuation */ + } + luaD_poscall(L, firstArg); /* finish 'luaD_precall' */ + } + unroll(L, NULL); + } + lua_assert(nCcalls == L->nCcalls); +} + + +LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) { + int status; + int oldnny = L->nny; /* save 'nny' */ + lua_lock(L); + luai_userstateresume(L, nargs); + L->nCcalls = (from) ? from->nCcalls + 1 : 1; + L->nny = 0; /* allow yields */ + api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs); + status = luaD_rawrunprotected(L, resume, L->top - nargs); + if (status == -1) /* error calling 'lua_resume'? */ + status = LUA_ERRRUN; + else { /* yield or regular error */ + while (status != LUA_OK && status != LUA_YIELD) { /* error? */ + if (recover(L, status)) /* recover point? */ + status = luaD_rawrunprotected(L, unroll, NULL); /* run continuation */ + else { /* unrecoverable error */ + L->status = cast_byte(status); /* mark thread as `dead' */ + seterrorobj(L, status, L->top); + L->ci->top = L->top; + break; + } + } + lua_assert(status == L->status); + } + L->nny = oldnny; /* restore 'nny' */ + L->nCcalls--; + lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0)); + lua_unlock(L); + return status; +} + + +LUA_API int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k) { + CallInfo *ci = L->ci; + luai_userstateyield(L, nresults); + lua_lock(L); + api_checknelems(L, nresults); + if (L->nny > 0) { + if (L != G(L)->mainthread) + luaG_runerror(L, "attempt to yield across a C-call boundary"); + else + luaG_runerror(L, "attempt to yield from outside a coroutine"); + } + L->status = LUA_YIELD; + ci->extra = savestack(L, ci->func); /* save current 'func' */ + if (isLua(ci)) { /* inside a hook? */ + api_check(L, k == NULL, "hooks cannot continue after yielding"); + } + else { + if ((ci->u.c.k = k) != NULL) /* is there a continuation? */ + ci->u.c.ctx = ctx; /* save context */ + ci->func = L->top - nresults - 1; /* protect stack below results */ + luaD_throw(L, LUA_YIELD); + } + lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */ + lua_unlock(L); + return 0; /* return to 'luaD_hook' */ +} + + +int luaD_pcall (lua_State *L, Pfunc func, void *u, + ptrdiff_t old_top, ptrdiff_t ef) { + int status; + CallInfo *old_ci = L->ci; + lu_byte old_allowhooks = L->allowhook; + unsigned short old_nny = L->nny; + ptrdiff_t old_errfunc = L->errfunc; + L->errfunc = ef; + status = luaD_rawrunprotected(L, func, u); + if (status != LUA_OK) { /* an error occurred? */ + StkId oldtop = restorestack(L, old_top); + luaF_close(L, oldtop); /* close possible pending closures */ + seterrorobj(L, status, oldtop); + L->ci = old_ci; + L->allowhook = old_allowhooks; + L->nny = old_nny; + luaD_shrinkstack(L); + } + L->errfunc = old_errfunc; + return status; +} + + + +/* +** Execute a protected parser. +*/ +struct SParser { /* data to `f_parser' */ + ZIO *z; + Mbuffer buff; /* dynamic structure used by the scanner */ + Dyndata dyd; /* dynamic structures used by the parser */ + const char *mode; + const char *name; +}; + + +static void checkmode (lua_State *L, const char *mode, const char *x) { + if (mode && strchr(mode, x[0]) == NULL) { + luaO_pushfstring(L, + "attempt to load a %s chunk (mode is " LUA_QS ")", x, mode); + luaD_throw(L, LUA_ERRSYNTAX); + } +} + + +static void f_parser (lua_State *L, void *ud) { + int i; + Closure *cl; + struct SParser *p = cast(struct SParser *, ud); + int c = zgetc(p->z); /* read first character */ + if (c == LUA_SIGNATURE[0]) { + checkmode(L, p->mode, "binary"); + cl = luaU_undump(L, p->z, &p->buff, p->name); + } + else { + checkmode(L, p->mode, "text"); + cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c); + } + lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues); + for (i = 0; i < cl->l.nupvalues; i++) { /* initialize upvalues */ + UpVal *up = luaF_newupval(L); + cl->l.upvals[i] = up; + luaC_objbarrier(L, cl, up); + } +} + + +int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, + const char *mode) { + struct SParser p; + int status; + L->nny++; /* cannot yield during parsing */ + p.z = z; p.name = name; p.mode = mode; + p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0; + p.dyd.gt.arr = NULL; p.dyd.gt.size = 0; + p.dyd.label.arr = NULL; p.dyd.label.size = 0; + luaZ_initbuffer(L, &p.buff); + status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc); + luaZ_freebuffer(L, &p.buff); + luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size); + luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size); + luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size); + L->nny--; + return status; +} + + diff --git a/components/pico8/femto8/src/lua/ldo.h b/components/pico8/femto8/src/lua/ldo.h new file mode 100644 index 00000000..27b837d9 --- /dev/null +++ b/components/pico8/femto8/src/lua/ldo.h @@ -0,0 +1,46 @@ +/* +** $Id: ldo.h,v 2.20 2011/11/29 15:55:08 roberto Exp $ +** Stack and Call structure of Lua +** See Copyright Notice in lua.h +*/ + +#ifndef ldo_h +#define ldo_h + + +#include "lobject.h" +#include "lstate.h" +#include "lzio.h" + + +#define luaD_checkstack(L,n) if (L->stack_last - L->top <= (n)) \ + luaD_growstack(L, n); else condmovestack(L); + + +#define incr_top(L) {L->top++; luaD_checkstack(L,0);} + +#define savestack(L,p) ((char *)(p) - (char *)L->stack) +#define restorestack(L,n) ((TValue *)((char *)L->stack + (n))) + + +/* type of protected functions, to be ran by `runprotected' */ +typedef void (*Pfunc) (lua_State *L, void *ud); + +LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, + const char *mode); +LUAI_FUNC void luaD_hook (lua_State *L, int event, int line); +LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults); +LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults, + int allowyield); +LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, + ptrdiff_t oldtop, ptrdiff_t ef); +LUAI_FUNC int luaD_poscall (lua_State *L, StkId firstResult); +LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize); +LUAI_FUNC void luaD_growstack (lua_State *L, int n); +LUAI_FUNC void luaD_shrinkstack (lua_State *L); + +LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode); +LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); + +#endif + diff --git a/components/pico8/femto8/src/lua/ldump.c b/components/pico8/femto8/src/lua/ldump.c new file mode 100644 index 00000000..d5e6a47c --- /dev/null +++ b/components/pico8/femto8/src/lua/ldump.c @@ -0,0 +1,173 @@ +/* +** $Id: ldump.c,v 2.17 2012/01/23 23:02:10 roberto Exp $ +** save precompiled Lua chunks +** See Copyright Notice in lua.h +*/ + +#include + +#define ldump_c +#define LUA_CORE + +#include "lua.h" + +#include "lobject.h" +#include "lstate.h" +#include "lundump.h" + +typedef struct { + lua_State* L; + lua_Writer writer; + void* data; + int strip; + int status; +} DumpState; + +#define DumpMem(b,n,size,D) DumpBlock(b,(n)*(size),D) +#define DumpVar(x,D) DumpMem(&x,1,sizeof(x),D) + +static void DumpBlock(const void* b, size_t size, DumpState* D) +{ + if (D->status==0) + { + lua_unlock(D->L); + D->status=(*D->writer)(D->L,b,size,D->data); + lua_lock(D->L); + } +} + +static void DumpChar(int y, DumpState* D) +{ + char x=(char)y; + DumpVar(x,D); +} + +static void DumpInt(int x, DumpState* D) +{ + DumpVar(x,D); +} + +static void DumpNumber(lua_Number x, DumpState* D) +{ + DumpVar(x,D); +} + +static void DumpVector(const void* b, int n, size_t size, DumpState* D) +{ + DumpInt(n,D); + DumpMem(b,n,size,D); +} + +static void DumpString(const TString* s, DumpState* D) +{ + if (s==NULL) + { + size_t size=0; + DumpVar(size,D); + } + else + { + size_t size=s->tsv.len+1; /* include trailing '\0' */ + DumpVar(size,D); + DumpBlock(getstr(s),size*sizeof(char),D); + } +} + +#define DumpCode(f,D) DumpVector(f->code,f->sizecode,sizeof(Instruction),D) + +static void DumpFunction(const Proto* f, DumpState* D); + +static void DumpConstants(const Proto* f, DumpState* D) +{ + int i,n=f->sizek; + DumpInt(n,D); + for (i=0; ik[i]; + DumpChar(ttypenv(o),D); + switch (ttypenv(o)) + { + case LUA_TNIL: + break; + case LUA_TBOOLEAN: + DumpChar(bvalue(o),D); + break; + case LUA_TNUMBER: + DumpNumber(nvalue(o),D); + break; + case LUA_TSTRING: + DumpString(rawtsvalue(o),D); + break; + default: lua_assert(0); + } + } + n=f->sizep; + DumpInt(n,D); + for (i=0; ip[i],D); +} + +static void DumpUpvalues(const Proto* f, DumpState* D) +{ + int i,n=f->sizeupvalues; + DumpInt(n,D); + for (i=0; iupvalues[i].instack,D); + DumpChar(f->upvalues[i].idx,D); + } +} + +static void DumpDebug(const Proto* f, DumpState* D) +{ + int i,n; + DumpString((D->strip) ? NULL : f->source,D); + n= (D->strip) ? 0 : f->sizelineinfo; + DumpVector(f->lineinfo,n,sizeof(int),D); + n= (D->strip) ? 0 : f->sizelocvars; + DumpInt(n,D); + for (i=0; ilocvars[i].varname,D); + DumpInt(f->locvars[i].startpc,D); + DumpInt(f->locvars[i].endpc,D); + } + n= (D->strip) ? 0 : f->sizeupvalues; + DumpInt(n,D); + for (i=0; iupvalues[i].name,D); +} + +static void DumpFunction(const Proto* f, DumpState* D) +{ + DumpInt(f->linedefined,D); + DumpInt(f->lastlinedefined,D); + DumpChar(f->numparams,D); + DumpChar(f->is_vararg,D); + DumpChar(f->maxstacksize,D); + DumpCode(f,D); + DumpConstants(f,D); + DumpUpvalues(f,D); + DumpDebug(f,D); +} + +static void DumpHeader(DumpState* D) +{ + lu_byte h[LUAC_HEADERSIZE]; + luaU_header(h); + DumpBlock(h,LUAC_HEADERSIZE,D); +} + +/* +** dump Lua function as precompiled chunk +*/ +int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip) +{ + DumpState D; + D.L=L; + D.writer=w; + D.data=data; + D.strip=strip; + D.status=0; + DumpHeader(&D); + DumpFunction(f,&D); + return D.status; +} diff --git a/components/pico8/femto8/src/lua/lfunc.c b/components/pico8/femto8/src/lua/lfunc.c new file mode 100644 index 00000000..c2128405 --- /dev/null +++ b/components/pico8/femto8/src/lua/lfunc.c @@ -0,0 +1,161 @@ +/* +** $Id: lfunc.c,v 2.30 2012/10/03 12:36:46 roberto Exp $ +** Auxiliary functions to manipulate prototypes and closures +** See Copyright Notice in lua.h +*/ + + +#include + +#define lfunc_c +#define LUA_CORE + +#include "lua.h" + +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" + + + +Closure *luaF_newCclosure (lua_State *L, int n) { + Closure *c = &luaC_newobj(L, LUA_TCCL, sizeCclosure(n), NULL, 0)->cl; + c->c.nupvalues = cast_byte(n); + return c; +} + + +Closure *luaF_newLclosure (lua_State *L, int n) { + Closure *c = &luaC_newobj(L, LUA_TLCL, sizeLclosure(n), NULL, 0)->cl; + c->l.p = NULL; + c->l.nupvalues = cast_byte(n); + while (n--) c->l.upvals[n] = NULL; + return c; +} + + +UpVal *luaF_newupval (lua_State *L) { + UpVal *uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), NULL, 0)->uv; + uv->v = &uv->u.value; + setnilvalue(uv->v); + return uv; +} + + +UpVal *luaF_findupval (lua_State *L, StkId level) { + global_State *g = G(L); + GCObject **pp = &L->openupval; + UpVal *p; + UpVal *uv; + while (*pp != NULL && (p = gco2uv(*pp))->v >= level) { + GCObject *o = obj2gco(p); + lua_assert(p->v != &p->u.value); + lua_assert(!isold(o) || isold(obj2gco(L))); + if (p->v == level) { /* found a corresponding upvalue? */ + if (isdead(g, o)) /* is it dead? */ + changewhite(o); /* resurrect it */ + return p; + } + pp = &p->next; + } + /* not found: create a new one */ + uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), pp, 0)->uv; + uv->v = level; /* current value lives in the stack */ + uv->u.l.prev = &g->uvhead; /* double link it in `uvhead' list */ + uv->u.l.next = g->uvhead.u.l.next; + uv->u.l.next->u.l.prev = uv; + g->uvhead.u.l.next = uv; + lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); + return uv; +} + + +static void unlinkupval (UpVal *uv) { + lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); + uv->u.l.next->u.l.prev = uv->u.l.prev; /* remove from `uvhead' list */ + uv->u.l.prev->u.l.next = uv->u.l.next; +} + + +void luaF_freeupval (lua_State *L, UpVal *uv) { + if (uv->v != &uv->u.value) /* is it open? */ + unlinkupval(uv); /* remove from open list */ + luaM_free(L, uv); /* free upvalue */ +} + + +void luaF_close (lua_State *L, StkId level) { + UpVal *uv; + global_State *g = G(L); + while (L->openupval != NULL && (uv = gco2uv(L->openupval))->v >= level) { + GCObject *o = obj2gco(uv); + lua_assert(!isblack(o) && uv->v != &uv->u.value); + L->openupval = uv->next; /* remove from `open' list */ + if (isdead(g, o)) + luaF_freeupval(L, uv); /* free upvalue */ + else { + unlinkupval(uv); /* remove upvalue from 'uvhead' list */ + setobj(L, &uv->u.value, uv->v); /* move value to upvalue slot */ + uv->v = &uv->u.value; /* now current value lives here */ + gch(o)->next = g->allgc; /* link upvalue into 'allgc' list */ + g->allgc = o; + luaC_checkupvalcolor(g, uv); + } + } +} + + +Proto *luaF_newproto (lua_State *L) { + Proto *f = &luaC_newobj(L, LUA_TPROTO, sizeof(Proto), NULL, 0)->p; + f->k = NULL; + f->sizek = 0; + f->p = NULL; + f->sizep = 0; + f->code = NULL; + f->cache = NULL; + f->sizecode = 0; + f->lineinfo = NULL; + f->sizelineinfo = 0; + f->upvalues = NULL; + f->sizeupvalues = 0; + f->numparams = 0; + f->is_vararg = 0; + f->maxstacksize = 0; + f->locvars = NULL; + f->sizelocvars = 0; + f->linedefined = 0; + f->lastlinedefined = 0; + f->source = NULL; + return f; +} + + +void luaF_freeproto (lua_State *L, Proto *f) { + luaM_freearray(L, f->code, f->sizecode); + luaM_freearray(L, f->p, f->sizep); + luaM_freearray(L, f->k, f->sizek); + luaM_freearray(L, f->lineinfo, f->sizelineinfo); + luaM_freearray(L, f->locvars, f->sizelocvars); + luaM_freearray(L, f->upvalues, f->sizeupvalues); + luaM_free(L, f); +} + + +/* +** Look for n-th local variable at line `line' in function `func'. +** Returns NULL if not found. +*/ +const char *luaF_getlocalname (const Proto *f, int local_number, int pc) { + int i; + for (i = 0; isizelocvars && f->locvars[i].startpc <= pc; i++) { + if (pc < f->locvars[i].endpc) { /* is variable active? */ + local_number--; + if (local_number == 0) + return getstr(f->locvars[i].varname); + } + } + return NULL; /* not found */ +} + diff --git a/components/pico8/femto8/src/lua/lfunc.h b/components/pico8/femto8/src/lua/lfunc.h new file mode 100644 index 00000000..e236a717 --- /dev/null +++ b/components/pico8/femto8/src/lua/lfunc.h @@ -0,0 +1,33 @@ +/* +** $Id: lfunc.h,v 2.8 2012/05/08 13:53:33 roberto Exp $ +** Auxiliary functions to manipulate prototypes and closures +** See Copyright Notice in lua.h +*/ + +#ifndef lfunc_h +#define lfunc_h + + +#include "lobject.h" + + +#define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \ + cast(int, sizeof(TValue)*((n)-1))) + +#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \ + cast(int, sizeof(TValue *)*((n)-1))) + + +LUAI_FUNC Proto *luaF_newproto (lua_State *L); +LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems); +LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems); +LUAI_FUNC UpVal *luaF_newupval (lua_State *L); +LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); +LUAI_FUNC void luaF_close (lua_State *L, StkId level); +LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); +LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv); +LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, + int pc); + + +#endif diff --git a/components/pico8/femto8/src/lua/lgc.c b/components/pico8/femto8/src/lua/lgc.c new file mode 100644 index 00000000..9e77f9b3 --- /dev/null +++ b/components/pico8/femto8/src/lua/lgc.c @@ -0,0 +1,1220 @@ +/* +** $Id: lgc.c,v 2.140.1.2 2013/04/26 18:22:05 roberto Exp roberto $ +** Garbage Collector +** See Copyright Notice in lua.h +*/ + +#include + +#define lgc_c +#define LUA_CORE + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" + + + +/* +** cost of sweeping one element (the size of a small object divided +** by some adjust for the sweep speed) +*/ +#define GCSWEEPCOST ((sizeof(TString) + 4) / 4) + +/* maximum number of elements to sweep in each single step */ +#define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4)) + +/* maximum number of finalizers to call in each GC step */ +#define GCFINALIZENUM 4 + + +/* +** macro to adjust 'stepmul': 'stepmul' is actually used like +** 'stepmul / STEPMULADJ' (value chosen by tests) +*/ +#define STEPMULADJ 200 + + +/* +** macro to adjust 'pause': 'pause' is actually used like +** 'pause / PAUSEADJ' (value chosen by tests) +*/ +#define PAUSEADJ 100 + + +/* +** 'makewhite' erases all color bits plus the old bit and then +** sets only the current white bit +*/ +#define maskcolors (~(bit2mask(BLACKBIT, OLDBIT) | WHITEBITS)) +#define makewhite(g,x) \ + (gch(x)->marked = cast_byte((gch(x)->marked & maskcolors) | luaC_white(g))) + +#define white2gray(x) resetbits(gch(x)->marked, WHITEBITS) +#define black2gray(x) resetbit(gch(x)->marked, BLACKBIT) + + +#define isfinalized(x) testbit(gch(x)->marked, FINALIZEDBIT) + +#define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n))) + + +#define checkconsistency(obj) \ + lua_longassert(!iscollectable(obj) || righttt(obj)) + + +#define markvalue(g,o) { checkconsistency(o); \ + if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } + +#define markobject(g,t) { if ((t) && iswhite(obj2gco(t))) \ + reallymarkobject(g, obj2gco(t)); } + +static void reallymarkobject (global_State *g, GCObject *o); + + +/* +** {====================================================== +** Generic functions +** ======================================================= +*/ + + +/* +** one after last element in a hash array +*/ +#define gnodelast(h) gnode(h, cast(size_t, sizenode(h))) + + +/* +** link table 'h' into list pointed by 'p' +*/ +#define linktable(h,p) ((h)->gclist = *(p), *(p) = obj2gco(h)) + + +/* +** if key is not marked, mark its entry as dead (therefore removing it +** from the table) +*/ +static void removeentry (Node *n) { + lua_assert(ttisnil(gval(n))); + if (valiswhite(gkey(n))) + setdeadvalue(gkey(n)); /* unused and unmarked key; remove it */ +} + + +/* +** tells whether a key or value can be cleared from a weak +** table. Non-collectable objects are never removed from weak +** tables. Strings behave as `values', so are never removed too. for +** other objects: if really collected, cannot keep them; for objects +** being finalized, keep them in keys, but not in values +*/ +static int iscleared (global_State *g, const TValue *o) { + if (!iscollectable(o)) return 0; + else if (ttisstring(o)) { + markobject(g, rawtsvalue(o)); /* strings are `values', so are never weak */ + return 0; + } + else return iswhite(gcvalue(o)); +} + + +/* +** barrier that moves collector forward, that is, mark the white object +** being pointed by a black object. +*/ +void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) { + global_State *g = G(L); + lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); + lua_assert(g->gcstate != GCSpause); + lua_assert(gch(o)->tt != LUA_TTABLE); + if (keepinvariantout(g)) /* must keep invariant? */ + reallymarkobject(g, v); /* restore invariant */ + else { /* sweep phase */ + lua_assert(issweepphase(g)); + makewhite(g, o); /* mark main obj. as white to avoid other barriers */ + } +} + + +/* +** barrier that moves collector backward, that is, mark the black object +** pointing to a white object as gray again. (Current implementation +** only works for tables; access to 'gclist' is not uniform across +** different types.) +*/ +void luaC_barrierback_ (lua_State *L, GCObject *o) { + global_State *g = G(L); + lua_assert(isblack(o) && !isdead(g, o) && gch(o)->tt == LUA_TTABLE); + black2gray(o); /* make object gray (again) */ + gco2t(o)->gclist = g->grayagain; + g->grayagain = o; +} + + +/* +** barrier for prototypes. When creating first closure (cache is +** NULL), use a forward barrier; this may be the only closure of the +** prototype (if it is a "regular" function, with a single instance) +** and the prototype may be big, so it is better to avoid traversing +** it again. Otherwise, use a backward barrier, to avoid marking all +** possible instances. +*/ +LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c) { + global_State *g = G(L); + lua_assert(isblack(obj2gco(p))); + if (p->cache == NULL) { /* first time? */ + luaC_objbarrier(L, p, c); + } + else { /* use a backward barrier */ + black2gray(obj2gco(p)); /* make prototype gray (again) */ + p->gclist = g->grayagain; + g->grayagain = obj2gco(p); + } +} + + +/* +** check color (and invariants) for an upvalue that was closed, +** i.e., moved into the 'allgc' list +*/ +void luaC_checkupvalcolor (global_State *g, UpVal *uv) { + GCObject *o = obj2gco(uv); + lua_assert(!isblack(o)); /* open upvalues are never black */ + if (isgray(o)) { + if (keepinvariant(g)) { + resetoldbit(o); /* see MOVE OLD rule */ + gray2black(o); /* it is being visited now */ + markvalue(g, uv->v); + } + else { + lua_assert(issweepphase(g)); + makewhite(g, o); + } + } +} + + +/* +** create a new collectable object (with given type and size) and link +** it to '*list'. 'offset' tells how many bytes to allocate before the +** object itself (used only by states). +*/ +GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, GCObject **list, + int offset) { + global_State *g = G(L); + char *raw = cast(char *, luaM_newobject(L, novariant(tt), sz)); + GCObject *o = obj2gco(raw + offset); + if (list == NULL) + list = &g->allgc; /* standard list for collectable objects */ + gch(o)->marked = luaC_white(g); + gch(o)->tt = tt; + gch(o)->next = *list; + *list = o; + return o; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** Mark functions +** ======================================================= +*/ + + +/* +** mark an object. Userdata, strings, and closed upvalues are visited +** and turned black here. Other objects are marked gray and added +** to appropriate list to be visited (and turned black) later. (Open +** upvalues are already linked in 'headuv' list.) +*/ +static void reallymarkobject (global_State *g, GCObject *o) { + lu_mem size; + white2gray(o); + switch (gch(o)->tt) { + case LUA_TSHRSTR: + case LUA_TLNGSTR: { + size = sizestring(gco2ts(o)); + break; /* nothing else to mark; make it black */ + } + case LUA_TUSERDATA: { + Table *mt = gco2u(o)->metatable; + markobject(g, mt); + markobject(g, gco2u(o)->env); + size = sizeudata(gco2u(o)); + break; + } + case LUA_TUPVAL: { + UpVal *uv = gco2uv(o); + markvalue(g, uv->v); + if (uv->v != &uv->u.value) /* open? */ + return; /* open upvalues remain gray */ + size = sizeof(UpVal); + break; + } + case LUA_TLCL: { + gco2lcl(o)->gclist = g->gray; + g->gray = o; + return; + } + case LUA_TCCL: { + gco2ccl(o)->gclist = g->gray; + g->gray = o; + return; + } + case LUA_TTABLE: { + linktable(gco2t(o), &g->gray); + return; + } + case LUA_TTHREAD: { + gco2th(o)->gclist = g->gray; + g->gray = o; + return; + } + case LUA_TPROTO: { + gco2p(o)->gclist = g->gray; + g->gray = o; + return; + } + default: lua_assert(0); return; + } + gray2black(o); + g->GCmemtrav += size; +} + + +/* +** mark metamethods for basic types +*/ +static void markmt (global_State *g) { + int i; + for (i=0; i < LUA_NUMTAGS; i++) + markobject(g, g->mt[i]); +} + + +/* +** mark all objects in list of being-finalized +*/ +static void markbeingfnz (global_State *g) { + GCObject *o; + for (o = g->tobefnz; o != NULL; o = gch(o)->next) { + makewhite(g, o); + reallymarkobject(g, o); + } +} + + +/* +** mark all values stored in marked open upvalues. (See comment in +** 'lstate.h'.) +*/ +static void remarkupvals (global_State *g) { + UpVal *uv; + for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) { + if (isgray(obj2gco(uv))) + markvalue(g, uv->v); + } +} + + +/* +** mark root set and reset all gray lists, to start a new +** incremental (or full) collection +*/ +static void restartcollection (global_State *g) { + g->gray = g->grayagain = NULL; + g->weak = g->allweak = g->ephemeron = NULL; + markobject(g, g->mainthread); + markvalue(g, &g->l_registry); + markmt(g); + markbeingfnz(g); /* mark any finalizing object left from previous cycle */ +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Traverse functions +** ======================================================= +*/ + +static void traverseweakvalue (global_State *g, Table *h) { + Node *n, *limit = gnodelast(h); + /* if there is array part, assume it may have white values (do not + traverse it just to check) */ + int hasclears = (h->sizearray > 0); + for (n = gnode(h, 0); n < limit; n++) { + checkdeadkey(n); + if (ttisnil(gval(n))) /* entry is empty? */ + removeentry(n); /* remove it */ + else { + lua_assert(!ttisnil(gkey(n))); + markvalue(g, gkey(n)); /* mark key */ + if (!hasclears && iscleared(g, gval(n))) /* is there a white value? */ + hasclears = 1; /* table will have to be cleared */ + } + } + if (hasclears) + linktable(h, &g->weak); /* has to be cleared later */ + else /* no white values */ + linktable(h, &g->grayagain); /* no need to clean */ +} + + +static int traverseephemeron (global_State *g, Table *h) { + int marked = 0; /* true if an object is marked in this traversal */ + int hasclears = 0; /* true if table has white keys */ + int prop = 0; /* true if table has entry "white-key -> white-value" */ + Node *n, *limit = gnodelast(h); + int i; + /* traverse array part (numeric keys are 'strong') */ + for (i = 0; i < h->sizearray; i++) { + if (valiswhite(&h->array[i])) { + marked = 1; + reallymarkobject(g, gcvalue(&h->array[i])); + } + } + /* traverse hash part */ + for (n = gnode(h, 0); n < limit; n++) { + checkdeadkey(n); + if (ttisnil(gval(n))) /* entry is empty? */ + removeentry(n); /* remove it */ + else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */ + hasclears = 1; /* table must be cleared */ + if (valiswhite(gval(n))) /* value not marked yet? */ + prop = 1; /* must propagate again */ + } + else if (valiswhite(gval(n))) { /* value not marked yet? */ + marked = 1; + reallymarkobject(g, gcvalue(gval(n))); /* mark it now */ + } + } + if (g->gcstate != GCSatomic || prop) + linktable(h, &g->ephemeron); /* have to propagate again */ + else if (hasclears) /* does table have white keys? */ + linktable(h, &g->allweak); /* may have to clean white keys */ + else /* no white keys */ + linktable(h, &g->grayagain); /* no need to clean */ + return marked; +} + + +static void traversestrongtable (global_State *g, Table *h) { + Node *n, *limit = gnodelast(h); + int i; + for (i = 0; i < h->sizearray; i++) /* traverse array part */ + markvalue(g, &h->array[i]); + for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ + checkdeadkey(n); + if (ttisnil(gval(n))) /* entry is empty? */ + removeentry(n); /* remove it */ + else { + lua_assert(!ttisnil(gkey(n))); + markvalue(g, gkey(n)); /* mark key */ + markvalue(g, gval(n)); /* mark value */ + } + } +} + + +static lu_mem traversetable (global_State *g, Table *h) { + const char *weakkey, *weakvalue; + const TValue *mode = gfasttm(g, h->metatable, TM_MODE); + markobject(g, h->metatable); + if (mode && ttisstring(mode) && /* is there a weak mode? */ + ((weakkey = strchr(svalue(mode), 'k')), + (weakvalue = strchr(svalue(mode), 'v')), + (weakkey || weakvalue))) { /* is really weak? */ + black2gray(obj2gco(h)); /* keep table gray */ + if (!weakkey) /* strong keys? */ + traverseweakvalue(g, h); + else if (!weakvalue) /* strong values? */ + traverseephemeron(g, h); + else /* all weak */ + linktable(h, &g->allweak); /* nothing to traverse now */ + } + else /* not weak */ + traversestrongtable(g, h); + return sizeof(Table) + sizeof(TValue) * h->sizearray + + sizeof(Node) * cast(size_t, sizenode(h)); +} + + +static int traverseproto (global_State *g, Proto *f) { + int i; + if (f->cache && iswhite(obj2gco(f->cache))) + f->cache = NULL; /* allow cache to be collected */ + markobject(g, f->source); + for (i = 0; i < f->sizek; i++) /* mark literals */ + markvalue(g, &f->k[i]); + for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */ + markobject(g, f->upvalues[i].name); + for (i = 0; i < f->sizep; i++) /* mark nested protos */ + markobject(g, f->p[i]); + for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */ + markobject(g, f->locvars[i].varname); + return sizeof(Proto) + sizeof(Instruction) * f->sizecode + + sizeof(Proto *) * f->sizep + + sizeof(TValue) * f->sizek + + sizeof(int) * f->sizelineinfo + + sizeof(LocVar) * f->sizelocvars + + sizeof(Upvaldesc) * f->sizeupvalues; +} + + +static lu_mem traverseCclosure (global_State *g, CClosure *cl) { + int i; + for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ + markvalue(g, &cl->upvalue[i]); + return sizeCclosure(cl->nupvalues); +} + +static lu_mem traverseLclosure (global_State *g, LClosure *cl) { + int i; + markobject(g, cl->p); /* mark its prototype */ + for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ + markobject(g, cl->upvals[i]); + return sizeLclosure(cl->nupvalues); +} + + +static lu_mem traversestack (global_State *g, lua_State *th) { + int n = 0; + StkId o = th->stack; + if (o == NULL) + return 1; /* stack not completely built yet */ + for (; o < th->top; o++) /* mark live elements in the stack */ + markvalue(g, o); + if (g->gcstate == GCSatomic) { /* final traversal? */ + StkId lim = th->stack + th->stacksize; /* real end of stack */ + for (; o < lim; o++) /* clear not-marked stack slice */ + setnilvalue(o); + } + else { /* count call infos to compute size */ + CallInfo *ci; + for (ci = &th->base_ci; ci != th->ci; ci = ci->next) + n++; + } + return sizeof(lua_State) + sizeof(TValue) * th->stacksize + + sizeof(CallInfo) * n; +} + + +/* +** traverse one gray object, turning it to black (except for threads, +** which are always gray). +*/ +static void propagatemark (global_State *g) { + lu_mem size; + GCObject *o = g->gray; + lua_assert(isgray(o)); + gray2black(o); + switch (gch(o)->tt) { + case LUA_TTABLE: { + Table *h = gco2t(o); + g->gray = h->gclist; /* remove from 'gray' list */ + size = traversetable(g, h); + break; + } + case LUA_TLCL: { + LClosure *cl = gco2lcl(o); + g->gray = cl->gclist; /* remove from 'gray' list */ + size = traverseLclosure(g, cl); + break; + } + case LUA_TCCL: { + CClosure *cl = gco2ccl(o); + g->gray = cl->gclist; /* remove from 'gray' list */ + size = traverseCclosure(g, cl); + break; + } + case LUA_TTHREAD: { + lua_State *th = gco2th(o); + g->gray = th->gclist; /* remove from 'gray' list */ + th->gclist = g->grayagain; + g->grayagain = o; /* insert into 'grayagain' list */ + black2gray(o); + size = traversestack(g, th); + break; + } + case LUA_TPROTO: { + Proto *p = gco2p(o); + g->gray = p->gclist; /* remove from 'gray' list */ + size = traverseproto(g, p); + break; + } + default: lua_assert(0); return; + } + g->GCmemtrav += size; +} + + +static void propagateall (global_State *g) { + while (g->gray) propagatemark(g); +} + + +static void propagatelist (global_State *g, GCObject *l) { + lua_assert(g->gray == NULL); /* no grays left */ + g->gray = l; + propagateall(g); /* traverse all elements from 'l' */ +} + +/* +** retraverse all gray lists. Because tables may be reinserted in other +** lists when traversed, traverse the original lists to avoid traversing +** twice the same table (which is not wrong, but inefficient) +*/ +static void retraversegrays (global_State *g) { + GCObject *weak = g->weak; /* save original lists */ + GCObject *grayagain = g->grayagain; + GCObject *ephemeron = g->ephemeron; + g->weak = g->grayagain = g->ephemeron = NULL; + propagateall(g); /* traverse main gray list */ + propagatelist(g, grayagain); + propagatelist(g, weak); + propagatelist(g, ephemeron); +} + + +static void convergeephemerons (global_State *g) { + int changed; + do { + GCObject *w; + GCObject *next = g->ephemeron; /* get ephemeron list */ + g->ephemeron = NULL; /* tables will return to this list when traversed */ + changed = 0; + while ((w = next) != NULL) { + next = gco2t(w)->gclist; + if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */ + propagateall(g); /* propagate changes */ + changed = 1; /* will have to revisit all ephemeron tables */ + } + } + } while (changed); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Sweep Functions +** ======================================================= +*/ + + +/* +** clear entries with unmarked keys from all weaktables in list 'l' up +** to element 'f' +*/ +static void clearkeys (global_State *g, GCObject *l, GCObject *f) { + for (; l != f; l = gco2t(l)->gclist) { + Table *h = gco2t(l); + Node *n, *limit = gnodelast(h); + for (n = gnode(h, 0); n < limit; n++) { + if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) { + setnilvalue(gval(n)); /* remove value ... */ + removeentry(n); /* and remove entry from table */ + } + } + } +} + + +/* +** clear entries with unmarked values from all weaktables in list 'l' up +** to element 'f' +*/ +static void clearvalues (global_State *g, GCObject *l, GCObject *f) { + for (; l != f; l = gco2t(l)->gclist) { + Table *h = gco2t(l); + Node *n, *limit = gnodelast(h); + int i; + for (i = 0; i < h->sizearray; i++) { + TValue *o = &h->array[i]; + if (iscleared(g, o)) /* value was collected? */ + setnilvalue(o); /* remove value */ + } + for (n = gnode(h, 0); n < limit; n++) { + if (!ttisnil(gval(n)) && iscleared(g, gval(n))) { + setnilvalue(gval(n)); /* remove value ... */ + removeentry(n); /* and remove entry from table */ + } + } + } +} + + +static void freeobj (lua_State *L, GCObject *o) { + switch (gch(o)->tt) { + case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break; + case LUA_TLCL: { + luaM_freemem(L, o, sizeLclosure(gco2lcl(o)->nupvalues)); + break; + } + case LUA_TCCL: { + luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues)); + break; + } + case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break; + case LUA_TTABLE: luaH_free(L, gco2t(o)); break; + case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break; + case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break; + case LUA_TSHRSTR: + G(L)->strt.nuse--; + /* go through */ + case LUA_TLNGSTR: { + luaM_freemem(L, o, sizestring(gco2ts(o))); + break; + } + default: lua_assert(0); + } +} + + +#define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM) +static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count); + + +/* +** sweep the (open) upvalues of a thread and resize its stack and +** list of call-info structures. +*/ +static void sweepthread (lua_State *L, lua_State *L1) { + if (L1->stack == NULL) return; /* stack not completely built yet */ + sweepwholelist(L, &L1->openupval); /* sweep open upvalues */ + luaE_freeCI(L1); /* free extra CallInfo slots */ + /* should not change the stack during an emergency gc cycle */ + if (G(L)->gckind != KGC_EMERGENCY) + luaD_shrinkstack(L1); +} + + +/* +** sweep at most 'count' elements from a list of GCObjects erasing dead +** objects, where a dead (not alive) object is one marked with the "old" +** (non current) white and not fixed. +** In non-generational mode, change all non-dead objects back to white, +** preparing for next collection cycle. +** In generational mode, keep black objects black, and also mark them as +** old; stop when hitting an old object, as all objects after that +** one will be old too. +** When object is a thread, sweep its list of open upvalues too. +*/ +static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) { + global_State *g = G(L); + int ow = otherwhite(g); + int toclear, toset; /* bits to clear and to set in all live objects */ + int tostop; /* stop sweep when this is true */ + if (isgenerational(g)) { /* generational mode? */ + toclear = ~0; /* clear nothing */ + toset = bitmask(OLDBIT); /* set the old bit of all surviving objects */ + tostop = bitmask(OLDBIT); /* do not sweep old generation */ + } + else { /* normal mode */ + toclear = maskcolors; /* clear all color bits + old bit */ + toset = luaC_white(g); /* make object white */ + tostop = 0; /* do not stop */ + } + while (*p != NULL && count-- > 0) { + GCObject *curr = *p; + int marked = gch(curr)->marked; + if (isdeadm(ow, marked)) { /* is 'curr' dead? */ + *p = gch(curr)->next; /* remove 'curr' from list */ + freeobj(L, curr); /* erase 'curr' */ + } + else { + if (testbits(marked, tostop)) + return NULL; /* stop sweeping this list */ + if (gch(curr)->tt == LUA_TTHREAD) + sweepthread(L, gco2th(curr)); /* sweep thread's upvalues */ + /* update marks */ + gch(curr)->marked = cast_byte((marked & toclear) | toset); + p = &gch(curr)->next; /* go to next element */ + } + } + return (*p == NULL) ? NULL : p; +} + + +/* +** sweep a list until a live object (or end of list) +*/ +static GCObject **sweeptolive (lua_State *L, GCObject **p, int *n) { + GCObject ** old = p; + int i = 0; + do { + i++; + p = sweeplist(L, p, 1); + } while (p == old); + if (n) *n += i; + return p; +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Finalization +** ======================================================= +*/ + +static void checkSizes (lua_State *L) { + global_State *g = G(L); + if (g->gckind != KGC_EMERGENCY) { /* do not change sizes in emergency */ + int hs = g->strt.size / 2; /* half the size of the string table */ + if (g->strt.nuse < cast(lu_int32, hs)) /* using less than that half? */ + luaS_resize(L, hs); /* halve its size */ + luaZ_freebuffer(L, &g->buff); /* free concatenation buffer */ + } +} + + +static GCObject *udata2finalize (global_State *g) { + GCObject *o = g->tobefnz; /* get first element */ + lua_assert(isfinalized(o)); + g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */ + gch(o)->next = g->allgc; /* return it to 'allgc' list */ + g->allgc = o; + resetbit(gch(o)->marked, SEPARATED); /* mark that it is not in 'tobefnz' */ + lua_assert(!isold(o)); /* see MOVE OLD rule */ + if (!keepinvariantout(g)) /* not keeping invariant? */ + makewhite(g, o); /* "sweep" object */ + return o; +} + + +static void dothecall (lua_State *L, void *ud) { + UNUSED(ud); + luaD_call(L, L->top - 2, 0, 0); +} + + +static void GCTM (lua_State *L, int propagateerrors) { + global_State *g = G(L); + const TValue *tm; + TValue v; + setgcovalue(L, &v, udata2finalize(g)); + tm = luaT_gettmbyobj(L, &v, TM_GC); + if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */ + int status; + lu_byte oldah = L->allowhook; + int running = g->gcrunning; + L->allowhook = 0; /* stop debug hooks during GC metamethod */ + g->gcrunning = 0; /* avoid GC steps */ + setobj2s(L, L->top, tm); /* push finalizer... */ + setobj2s(L, L->top + 1, &v); /* ... and its argument */ + L->top += 2; /* and (next line) call the finalizer */ + status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0); + L->allowhook = oldah; /* restore hooks */ + g->gcrunning = running; /* restore state */ + if (status != LUA_OK && propagateerrors) { /* error while running __gc? */ + if (status == LUA_ERRRUN) { /* is there an error object? */ + const char *msg = (ttisstring(L->top - 1)) + ? svalue(L->top - 1) + : "no message"; + luaO_pushfstring(L, "error in __gc metamethod (%s)", msg); + status = LUA_ERRGCMM; /* error in __gc metamethod */ + } + luaD_throw(L, status); /* re-throw error */ + } + } +} + + +/* +** move all unreachable objects (or 'all' objects) that need +** finalization from list 'finobj' to list 'tobefnz' (to be finalized) +*/ +static void separatetobefnz (lua_State *L, int all) { + global_State *g = G(L); + GCObject **p = &g->finobj; + GCObject *curr; + GCObject **lastnext = &g->tobefnz; + /* find last 'next' field in 'tobefnz' list (to add elements in its end) */ + while (*lastnext != NULL) + lastnext = &gch(*lastnext)->next; + while ((curr = *p) != NULL) { /* traverse all finalizable objects */ + lua_assert(!isfinalized(curr)); + lua_assert(testbit(gch(curr)->marked, SEPARATED)); + if (!(iswhite(curr) || all)) /* not being collected? */ + p = &gch(curr)->next; /* don't bother with it */ + else { + l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */ + *p = gch(curr)->next; /* remove 'curr' from 'finobj' list */ + gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */ + *lastnext = curr; + lastnext = &gch(curr)->next; + } + } +} + + +/* +** if object 'o' has a finalizer, remove it from 'allgc' list (must +** search the list to find it) and link it in 'finobj' list. +*/ +void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) { + global_State *g = G(L); + if (testbit(gch(o)->marked, SEPARATED) || /* obj. is already separated... */ + isfinalized(o) || /* ... or is finalized... */ + gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */ + return; /* nothing to be done */ + else { /* move 'o' to 'finobj' list */ + GCObject **p; + GCheader *ho = gch(o); + if (g->sweepgc == &ho->next) { /* avoid removing current sweep object */ + lua_assert(issweepphase(g)); + g->sweepgc = sweeptolive(L, g->sweepgc, NULL); + } + /* search for pointer pointing to 'o' */ + for (p = &g->allgc; *p != o; p = &gch(*p)->next) { /* empty */ } + *p = ho->next; /* remove 'o' from root list */ + ho->next = g->finobj; /* link it in list 'finobj' */ + g->finobj = o; + l_setbit(ho->marked, SEPARATED); /* mark it as such */ + if (!keepinvariantout(g)) /* not keeping invariant? */ + makewhite(g, o); /* "sweep" object */ + else + resetoldbit(o); /* see MOVE OLD rule */ + } +} + +/* }====================================================== */ + + +/* +** {====================================================== +** GC control +** ======================================================= +*/ + + +/* +** set a reasonable "time" to wait before starting a new GC cycle; +** cycle will start when memory use hits threshold +*/ +static void setpause (global_State *g, l_mem estimate) { + l_mem debt, threshold; + estimate = estimate / PAUSEADJ; /* adjust 'estimate' */ + threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */ + ? estimate * g->gcpause /* no overflow */ + : MAX_LMEM; /* overflow; truncate to maximum */ + debt = -cast(l_mem, threshold - gettotalbytes(g)); + luaE_setdebt(g, debt); +} + + +#define sweepphases \ + (bitmask(GCSsweepstring) | bitmask(GCSsweepudata) | bitmask(GCSsweep)) + + +/* +** enter first sweep phase (strings) and prepare pointers for other +** sweep phases. The calls to 'sweeptolive' make pointers point to an +** object inside the list (instead of to the header), so that the real +** sweep do not need to skip objects created between "now" and the start +** of the real sweep. +** Returns how many objects it swept. +*/ +static int entersweep (lua_State *L) { + global_State *g = G(L); + int n = 0; + g->gcstate = GCSsweepstring; + lua_assert(g->sweepgc == NULL && g->sweepfin == NULL); + /* prepare to sweep strings, finalizable objects, and regular objects */ + g->sweepstrgc = 0; + g->sweepfin = sweeptolive(L, &g->finobj, &n); + g->sweepgc = sweeptolive(L, &g->allgc, &n); + return n; +} + + +/* +** change GC mode +*/ +void luaC_changemode (lua_State *L, int mode) { + global_State *g = G(L); + if (mode == g->gckind) return; /* nothing to change */ + if (mode == KGC_GEN) { /* change to generational mode */ + /* make sure gray lists are consistent */ + luaC_runtilstate(L, bitmask(GCSpropagate)); + g->GCestimate = gettotalbytes(g); + g->gckind = KGC_GEN; + } + else { /* change to incremental mode */ + /* sweep all objects to turn them back to white + (as white has not changed, nothing extra will be collected) */ + g->gckind = KGC_NORMAL; + entersweep(L); + luaC_runtilstate(L, ~sweepphases); + } +} + + +/* +** call all pending finalizers +*/ +static void callallpendingfinalizers (lua_State *L, int propagateerrors) { + global_State *g = G(L); + while (g->tobefnz) { + resetoldbit(g->tobefnz); + GCTM(L, propagateerrors); + } +} + + +void luaC_freeallobjects (lua_State *L) { + global_State *g = G(L); + int i; + separatetobefnz(L, 1); /* separate all objects with finalizers */ + lua_assert(g->finobj == NULL); + callallpendingfinalizers(L, 0); + g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */ + g->gckind = KGC_NORMAL; + sweepwholelist(L, &g->finobj); /* finalizers can create objs. in 'finobj' */ + sweepwholelist(L, &g->allgc); + for (i = 0; i < g->strt.size; i++) /* free all string lists */ + sweepwholelist(L, &g->strt.hash[i]); + lua_assert(g->strt.nuse == 0); +} + + +static l_mem atomic (lua_State *L) { + global_State *g = G(L); + l_mem work = -cast(l_mem, g->GCmemtrav); /* start counting work */ + GCObject *origweak, *origall; + lua_assert(!iswhite(obj2gco(g->mainthread))); + markobject(g, L); /* mark running thread */ + /* registry and global metatables may be changed by API */ + markvalue(g, &g->l_registry); + markmt(g); /* mark basic metatables */ + /* remark occasional upvalues of (maybe) dead threads */ + remarkupvals(g); + propagateall(g); /* propagate changes */ + work += g->GCmemtrav; /* stop counting (do not (re)count grays) */ + /* traverse objects caught by write barrier and by 'remarkupvals' */ + retraversegrays(g); + work -= g->GCmemtrav; /* restart counting */ + convergeephemerons(g); + /* at this point, all strongly accessible objects are marked. */ + /* clear values from weak tables, before checking finalizers */ + clearvalues(g, g->weak, NULL); + clearvalues(g, g->allweak, NULL); + origweak = g->weak; origall = g->allweak; + work += g->GCmemtrav; /* stop counting (objects being finalized) */ + separatetobefnz(L, 0); /* separate objects to be finalized */ + markbeingfnz(g); /* mark objects that will be finalized */ + propagateall(g); /* remark, to propagate `preserveness' */ + work -= g->GCmemtrav; /* restart counting */ + convergeephemerons(g); + /* at this point, all resurrected objects are marked. */ + /* remove dead objects from weak tables */ + clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */ + clearkeys(g, g->allweak, NULL); /* clear keys from all allweak tables */ + /* clear values from resurrected weak tables */ + clearvalues(g, g->weak, origweak); + clearvalues(g, g->allweak, origall); + g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */ + work += g->GCmemtrav; /* complete counting */ + return work; /* estimate of memory marked by 'atomic' */ +} + + +static lu_mem singlestep (lua_State *L) { + global_State *g = G(L); + switch (g->gcstate) { + case GCSpause: { + /* start to count memory traversed */ + g->GCmemtrav = g->strt.size * sizeof(GCObject*); + lua_assert(!isgenerational(g)); + restartcollection(g); + g->gcstate = GCSpropagate; + return g->GCmemtrav; + } + case GCSpropagate: { + if (g->gray) { + lu_mem oldtrav = g->GCmemtrav; + propagatemark(g); + return g->GCmemtrav - oldtrav; /* memory traversed in this step */ + } + else { /* no more `gray' objects */ + lu_mem work; + int sw; + g->gcstate = GCSatomic; /* finish mark phase */ + g->GCestimate = g->GCmemtrav; /* save what was counted */; + work = atomic(L); /* add what was traversed by 'atomic' */ + g->GCestimate += work; /* estimate of total memory traversed */ + sw = entersweep(L); + return work + sw * GCSWEEPCOST; + } + } + case GCSsweepstring: { + int i; + for (i = 0; i < GCSWEEPMAX && g->sweepstrgc + i < g->strt.size; i++) + sweepwholelist(L, &g->strt.hash[g->sweepstrgc + i]); + g->sweepstrgc += i; + if (g->sweepstrgc >= g->strt.size) /* no more strings to sweep? */ + g->gcstate = GCSsweepudata; + return i * GCSWEEPCOST; + } + case GCSsweepudata: { + if (g->sweepfin) { + g->sweepfin = sweeplist(L, g->sweepfin, GCSWEEPMAX); + return GCSWEEPMAX*GCSWEEPCOST; + } + else { + g->gcstate = GCSsweep; + return 0; + } + } + case GCSsweep: { + if (g->sweepgc) { + g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX); + return GCSWEEPMAX*GCSWEEPCOST; + } + else { + /* sweep main thread */ + GCObject *mt = obj2gco(g->mainthread); + sweeplist(L, &mt, 1); + checkSizes(L); + g->gcstate = GCSpause; /* finish collection */ + return GCSWEEPCOST; + } + } + default: lua_assert(0); return 0; + } +} + + +/* +** advances the garbage collector until it reaches a state allowed +** by 'statemask' +*/ +void luaC_runtilstate (lua_State *L, int statesmask) { + global_State *g = G(L); + while (!testbit(statesmask, g->gcstate)) + singlestep(L); +} + + +static void generationalcollection (lua_State *L) { + global_State *g = G(L); + lua_assert(g->gcstate == GCSpropagate); + if (g->GCestimate == 0) { /* signal for another major collection? */ + luaC_fullgc(L, 0); /* perform a full regular collection */ + g->GCestimate = gettotalbytes(g); /* update control */ + } + else { + lu_mem estimate = g->GCestimate; + luaC_runtilstate(L, bitmask(GCSpause)); /* run complete (minor) cycle */ + g->gcstate = GCSpropagate; /* skip restart */ + if (gettotalbytes(g) > (estimate / 100) * g->gcmajorinc) + g->GCestimate = 0; /* signal for a major collection */ + else + g->GCestimate = estimate; /* keep estimate from last major coll. */ + + } + setpause(g, gettotalbytes(g)); + lua_assert(g->gcstate == GCSpropagate); +} + + +static void incstep (lua_State *L) { + global_State *g = G(L); + l_mem debt = g->GCdebt; + int stepmul = g->gcstepmul; + if (stepmul < 40) stepmul = 40; /* avoid ridiculous low values (and 0) */ + /* convert debt from Kb to 'work units' (avoid zero debt and overflows) */ + debt = (debt / STEPMULADJ) + 1; + debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM; + do { /* always perform at least one single step */ + lu_mem work = singlestep(L); /* do some work */ + debt -= work; + } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause); + if (g->gcstate == GCSpause) + setpause(g, g->GCestimate); /* pause until next cycle */ + else { + debt = (debt / stepmul) * STEPMULADJ; /* convert 'work units' to Kb */ + luaE_setdebt(g, debt); + } +} + + +/* +** performs a basic GC step +*/ +void luaC_forcestep (lua_State *L) { + global_State *g = G(L); + int i; + if (isgenerational(g)) generationalcollection(L); + else incstep(L); + /* run a few finalizers (or all of them at the end of a collect cycle) */ + for (i = 0; g->tobefnz && (i < GCFINALIZENUM || g->gcstate == GCSpause); i++) + GCTM(L, 1); /* call one finalizer */ +} + + +/* +** performs a basic GC step only if collector is running +*/ +void luaC_step (lua_State *L) { + global_State *g = G(L); + if (g->gcrunning) luaC_forcestep(L); + else luaE_setdebt(g, -GCSTEPSIZE); /* avoid being called too often */ +} + + + +/* +** performs a full GC cycle; if "isemergency", does not call +** finalizers (which could change stack positions) +*/ +void luaC_fullgc (lua_State *L, int isemergency) { + global_State *g = G(L); + int origkind = g->gckind; + lua_assert(origkind != KGC_EMERGENCY); + if (isemergency) /* do not run finalizers during emergency GC */ + g->gckind = KGC_EMERGENCY; + else { + g->gckind = KGC_NORMAL; + callallpendingfinalizers(L, 1); + } + if (keepinvariant(g)) { /* may there be some black objects? */ + /* must sweep all objects to turn them back to white + (as white has not changed, nothing will be collected) */ + entersweep(L); + } + /* finish any pending sweep phase to start a new cycle */ + luaC_runtilstate(L, bitmask(GCSpause)); + luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */ + luaC_runtilstate(L, bitmask(GCSpause)); /* run entire collection */ + if (origkind == KGC_GEN) { /* generational mode? */ + /* generational mode must be kept in propagate phase */ + luaC_runtilstate(L, bitmask(GCSpropagate)); + } + g->gckind = origkind; + setpause(g, gettotalbytes(g)); + if (!isemergency) /* do not run finalizers during emergency GC */ + callallpendingfinalizers(L, 1); +} + +/* }====================================================== */ + + diff --git a/components/pico8/femto8/src/lua/lgc.h b/components/pico8/femto8/src/lua/lgc.h new file mode 100644 index 00000000..dee270b4 --- /dev/null +++ b/components/pico8/femto8/src/lua/lgc.h @@ -0,0 +1,157 @@ +/* +** $Id: lgc.h,v 2.58 2012/09/11 12:53:08 roberto Exp $ +** Garbage Collector +** See Copyright Notice in lua.h +*/ + +#ifndef lgc_h +#define lgc_h + + +#include "lobject.h" +#include "lstate.h" + +/* +** Collectable objects may have one of three colors: white, which +** means the object is not marked; gray, which means the +** object is marked, but its references may be not marked; and +** black, which means that the object and all its references are marked. +** The main invariant of the garbage collector, while marking objects, +** is that a black object can never point to a white one. Moreover, +** any gray object must be in a "gray list" (gray, grayagain, weak, +** allweak, ephemeron) so that it can be visited again before finishing +** the collection cycle. These lists have no meaning when the invariant +** is not being enforced (e.g., sweep phase). +*/ + + + +/* how much to allocate before next GC step */ +#if !defined(GCSTEPSIZE) +/* ~100 small strings */ +#define GCSTEPSIZE (cast_int(100 * sizeof(TString))) +#endif + + +/* +** Possible states of the Garbage Collector +*/ +#define GCSpropagate 0 +#define GCSatomic 1 +#define GCSsweepstring 2 +#define GCSsweepudata 3 +#define GCSsweep 4 +#define GCSpause 5 + + +#define issweepphase(g) \ + (GCSsweepstring <= (g)->gcstate && (g)->gcstate <= GCSsweep) + +#define isgenerational(g) ((g)->gckind == KGC_GEN) + +/* +** macros to tell when main invariant (white objects cannot point to black +** ones) must be kept. During a non-generational collection, the sweep +** phase may break the invariant, as objects turned white may point to +** still-black objects. The invariant is restored when sweep ends and +** all objects are white again. During a generational collection, the +** invariant must be kept all times. +*/ + +#define keepinvariant(g) (isgenerational(g) || g->gcstate <= GCSatomic) + + +/* +** Outside the collector, the state in generational mode is kept in +** 'propagate', so 'keepinvariant' is always true. +*/ +#define keepinvariantout(g) \ + check_exp(g->gcstate == GCSpropagate || !isgenerational(g), \ + g->gcstate <= GCSatomic) + + +/* +** some useful bit tricks +*/ +#define resetbits(x,m) ((x) &= cast(lu_byte, ~(m))) +#define setbits(x,m) ((x) |= (m)) +#define testbits(x,m) ((x) & (m)) +#define bitmask(b) (1<<(b)) +#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) +#define l_setbit(x,b) setbits(x, bitmask(b)) +#define resetbit(x,b) resetbits(x, bitmask(b)) +#define testbit(x,b) testbits(x, bitmask(b)) + + +/* Layout for bit use in `marked' field: */ +#define WHITE0BIT 0 /* object is white (type 0) */ +#define WHITE1BIT 1 /* object is white (type 1) */ +#define BLACKBIT 2 /* object is black */ +#define FINALIZEDBIT 3 /* object has been separated for finalization */ +#define SEPARATED 4 /* object is in 'finobj' list or in 'tobefnz' */ +#define FIXEDBIT 5 /* object is fixed (should not be collected) */ +#define OLDBIT 6 /* object is old (only in generational mode) */ +/* bit 7 is currently used by tests (luaL_checkmemory) */ + +#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) + + +#define iswhite(x) testbits((x)->gch.marked, WHITEBITS) +#define isblack(x) testbit((x)->gch.marked, BLACKBIT) +#define isgray(x) /* neither white nor black */ \ + (!testbits((x)->gch.marked, WHITEBITS | bitmask(BLACKBIT))) + +#define isold(x) testbit((x)->gch.marked, OLDBIT) + +/* MOVE OLD rule: whenever an object is moved to the beginning of + a GC list, its old bit must be cleared */ +#define resetoldbit(o) resetbit((o)->gch.marked, OLDBIT) + +#define otherwhite(g) (g->currentwhite ^ WHITEBITS) +#define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow))) +#define isdead(g,v) isdeadm(otherwhite(g), (v)->gch.marked) + +#define changewhite(x) ((x)->gch.marked ^= WHITEBITS) +#define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT) + +#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) + +#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) + + +#define luaC_condGC(L,c) \ + {if (G(L)->GCdebt > 0) {c;}; condchangemem(L);} +#define luaC_checkGC(L) luaC_condGC(L, luaC_step(L);) + + +#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ + luaC_barrier_(L,obj2gco(p),gcvalue(v)); } + +#define luaC_barrierback(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ + luaC_barrierback_(L,p); } + +#define luaC_objbarrier(L,p,o) \ + { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \ + luaC_barrier_(L,obj2gco(p),obj2gco(o)); } + +#define luaC_objbarrierback(L,p,o) \ + { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) luaC_barrierback_(L,p); } + +#define luaC_barrierproto(L,p,c) \ + { if (isblack(obj2gco(p))) luaC_barrierproto_(L,p,c); } + +LUAI_FUNC void luaC_freeallobjects (lua_State *L); +LUAI_FUNC void luaC_step (lua_State *L); +LUAI_FUNC void luaC_forcestep (lua_State *L); +LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask); +LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency); +LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, + GCObject **list, int offset); +LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v); +LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o); +LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c); +LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt); +LUAI_FUNC void luaC_checkupvalcolor (global_State *g, UpVal *uv); +LUAI_FUNC void luaC_changemode (lua_State *L, int mode); + +#endif diff --git a/components/pico8/femto8/src/lua/linit.c b/components/pico8/femto8/src/lua/linit.c new file mode 100644 index 00000000..3c953947 --- /dev/null +++ b/components/pico8/femto8/src/lua/linit.c @@ -0,0 +1,67 @@ +/* +** $Id: linit.c,v 1.32 2011/04/08 19:17:36 roberto Exp $ +** Initialization of libraries for lua.c and other clients +** See Copyright Notice in lua.h +*/ + + +/* +** If you embed Lua in your program and need to open the standard +** libraries, call luaL_openlibs in your program. If you need a +** different set of libraries, copy this file to your project and edit +** it to suit your needs. +*/ + + +#define linit_c +#define LUA_LIB + +#include "lua.h" + +#include "lualib.h" +#include "lauxlib.h" + + +/* +** these libs are loaded by lua.c and are readily available to any Lua +** program +*/ +static const luaL_Reg loadedlibs[] = { + {"_G", luaopen_base}, + {"_G", luaopen_pico8}, + {LUA_COLIBNAME, luaopen_coroutine}, + {LUA_STRLIBNAME, luaopen_string}, + {NULL, NULL} +}; + + +/* +** these libs are preloaded and must be required before used +*/ +static const luaL_Reg preloadedlibs[] = { + {NULL, NULL} +}; + + +LUALIB_API void luaL_openlibs (lua_State *L) { + const luaL_Reg *lib; + /* call open functions from 'loadedlibs' and set results to global table */ + for (lib = loadedlibs; lib->func; lib++) { + luaL_requiref(L, lib->name, lib->func, 1); + lua_pop(L, 1); /* remove lib */ + } + luaL_requiref(L, LUA_TABLIBNAME, luaopen_table, 0); + lua_getfield(L, -1, "unpack"); + lua_setglobal(L, "unpack"); + lua_pop(L, 1); /* remove table lib */ + lua_pushnil(L); + lua_setglobal(L, "_G"); + /* add open functions from 'preloadedlibs' into 'package.preload' table */ + luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD"); + for (lib = preloadedlibs; lib->func; lib++) { + lua_pushcfunction(L, lib->func); + lua_setfield(L, -2, lib->name); + } + lua_pop(L, 1); /* remove _PRELOAD table */ +} + diff --git a/components/pico8/femto8/src/lua/llex.c b/components/pico8/femto8/src/lua/llex.c new file mode 100644 index 00000000..ee91ad21 --- /dev/null +++ b/components/pico8/femto8/src/lua/llex.c @@ -0,0 +1,609 @@ +/* +** $Id: llex.c,v 2.63.1.2 2013/08/30 15:49:41 roberto Exp roberto $ +** Lexical Analyzer +** See Copyright Notice in lua.h +*/ + + +#include +#include + +#define llex_c +#define LUA_CORE + +#include "lua.h" + +#include "lctype.h" +#include "ldo.h" +#include "llex.h" +#include "lobject.h" +#include "lparser.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "lzio.h" + + + +#define next(ls) (ls->current = zgetc(ls->z)) + + + +#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') + + +/* ORDER RESERVED */ +static const char *const luaX_tokens [] = { + "and", "break", "do", "else", "elseif", + "end", "false", "for", "function", "goto", "if", + "in", "local", "nil", "not", "or", "repeat", + "return", "then", "true", "until", "while", + "..", "...", "==", ">=", "<=", "~=", "!=", "::", + "", "", "", "", "?", + "", "^^", "<<", ">>", ">>>", "<<>", ">><", + "+=", "-=", "*=", "/=", "%=", "^=", "\\=", "&=", "|=", + "^^=", "<<=", ">>=", ">>>=", "<<>=", ">><=", "..=", +}; + + +#define save_and_next(ls) (save(ls, ls->current), next(ls)) + + +static l_noret lexerror (LexState *ls, const char *msg, int token); + + +static void save (LexState *ls, int c) { + Mbuffer *b = ls->buff; + if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) { + size_t newsize; + if (luaZ_sizebuffer(b) >= MAX_SIZET/2) + lexerror(ls, "lexical element too long", 0); + newsize = luaZ_sizebuffer(b) * 2; + luaZ_resizebuffer(ls->L, b, newsize); + } + b->buffer[luaZ_bufflen(b)++] = cast(char, c); +} + + +void luaX_init (lua_State *L) { + int i; + for (i=0; itsv.extra = cast_byte(i+1); /* reserved word */ + } +} + + +const char *luaX_token2str (LexState *ls, int token) { + if (token < FIRST_RESERVED) { /* single-byte symbols? */ + lua_assert(token == cast(unsigned char, token)); + return (lisprint(token)) ? luaO_pushfstring(ls->L, LUA_QL("%c"), token) : + luaO_pushfstring(ls->L, "char(%d)", token); + } + else { + const char *s = luaX_tokens[token - FIRST_RESERVED]; + if (token < TK_EOS) /* fixed format (symbols and reserved words)? */ + return luaO_pushfstring(ls->L, LUA_QS, s); + else /* names, strings, and numerals */ + return s; + } +} + + +void luaX_trackbraces (LexState *ls) { + ls->braces = ls->t.token == '(' ? 1 : -1; +} + + +static const char *txtToken (LexState *ls, int token) { + switch (token) { + case TK_NAME: + case TK_STRING: + case TK_NUMBER: + save(ls, '\0'); + return luaO_pushfstring(ls->L, LUA_QS, luaZ_buffer(ls->buff)); + default: + return luaX_token2str(ls, token); + } +} + + +static l_noret lexerror (LexState *ls, const char *msg, int token) { + char buff[LUA_IDSIZE]; + luaO_chunkid(buff, getstr(ls->source), LUA_IDSIZE); + msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg); + if (token) + luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token)); + luaD_throw(ls->L, LUA_ERRSYNTAX); +} + + +l_noret luaX_syntaxerror (LexState *ls, const char *msg) { + lexerror(ls, msg, ls->t.token); +} + + +/* +** creates a new string and anchors it in function's table so that +** it will not be collected until the end of the function's compilation +** (by that time it should be anchored in function's prototype) +*/ +TString *luaX_newstring (LexState *ls, const char *str, size_t l) { + lua_State *L = ls->L; + TValue *o; /* entry for `str' */ + TString *ts = luaS_newlstr(L, str, l); /* create new string */ + setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */ + o = luaH_set(L, ls->fs->h, L->top - 1); + if (ttisnil(o)) { /* not in use yet? (see 'addK') */ + /* boolean value does not need GC barrier; + table has no metatable, so it does not need to invalidate cache */ + setbvalue(o, 1); /* t[string] = true */ + luaC_checkGC(L); + } + else { /* string already present */ + ts = rawtsvalue(keyfromval(o)); /* re-use value previously stored */ + } + L->top--; /* remove string from stack */ + return ts; +} + + +/* +** increment line number and skips newline sequence (any of +** \n, \r, \n\r, or \r\n) +*/ +static void inclinenumber (LexState *ls) { + int old = ls->current; + lua_assert(currIsNewline(ls)); + next(ls); /* skip `\n' or `\r' */ + if (currIsNewline(ls) && ls->current != old) + next(ls); /* skip `\n\r' or `\r\n' */ + if (++ls->linenumber >= MAX_INT) + lexerror(ls, "chunk has too many lines", 0); +} + + +void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source, + int firstchar) { + ls->decpoint = '.'; + ls->L = L; + ls->current = firstchar; + ls->lookahead.token = TK_EOS; /* no look-ahead token */ + ls->z = z; + ls->fs = NULL; + ls->linenumber = 1; + ls->emiteol = 0; + ls->lastline = 1; + ls->braces = -1; + ls->source = source; + ls->envn = luaS_new(L, LUA_ENV); /* create env name */ + ls->short_nest = 0; + luaS_fix(ls->envn); /* never collect this name */ + luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ +} + + + +/* +** ======================================================= +** LEXICAL ANALYZER +** ======================================================= +*/ + + + +static int check_next (LexState *ls, const char *set) { + if (ls->current == '\0' || !strchr(set, ls->current)) + return 0; + save_and_next(ls); + return 1; +} + + +/* +** change all characters 'from' in buffer to 'to' +*/ +static void buffreplace (LexState *ls, char from, char to) { + size_t n = luaZ_bufflen(ls->buff); + char *p = luaZ_buffer(ls->buff); + while (n--) + if (p[n] == from) p[n] = to; +} + + +#if !defined(getlocaledecpoint) +#define getlocaledecpoint() (localeconv()->decimal_point[0]) +#endif + + +#define buff2d(b,e) luaO_str2d(luaZ_buffer(b), luaZ_bufflen(b) - 1, e) + +/* +** in case of format error, try to change decimal point separator to +** the one defined in the current locale and check again +*/ +static void trydecpoint (LexState *ls, SemInfo *seminfo) { + char old = ls->decpoint; + ls->decpoint = getlocaledecpoint(); + buffreplace(ls, old, ls->decpoint); /* try new decimal separator */ + if (!buff2d(ls->buff, &seminfo->r)) { + /* format error with correct decimal point: no more options */ + buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */ + lexerror(ls, "malformed number", TK_NUMBER); + } +} + + +/* LUA_NUMBER */ +/* +** this function is quite liberal in what it accepts, as 'luaO_str2d' +** will reject ill-formed numerals. +*/ +static void read_numeral (LexState *ls, SemInfo *seminfo) { + int first = ls->current; + lua_assert(lisdigit(ls->current)); + save_and_next(ls); + int hexa = 0; + if (first == '0') { + if (check_next(ls, "Xx")) { /* hexadecimal? */ + hexa = 1; + } else check_next(ls, "Bb"); /* binary? */ + } + for (;;) { + if ((hexa ? lisxdigit(ls->current) : lisdigit(ls->current)) || ls->current == '.') + save_and_next(ls); + else break; + } + save(ls, '\0'); + buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */ + if (!buff2d(ls->buff, &seminfo->r)) /* format error? */ + trydecpoint(ls, seminfo); /* try to update decimal point separator */ +} + + +/* +** skip a sequence '[=*[' or ']=*]' and return its number of '='s or +** -1 if sequence is malformed +*/ +static int skip_sep (LexState *ls) { + int count = 0; + int s = ls->current; + lua_assert(s == '[' || s == ']'); + save_and_next(ls); + while (ls->current == '=') { + save_and_next(ls); + count++; + } + return (ls->current == s) ? count : (-count) - 1; +} + + +static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { + save_and_next(ls); /* skip 2nd `[' */ + if (currIsNewline(ls)) /* string starts with a newline? */ + inclinenumber(ls); /* skip it */ + for (;;) { + switch (ls->current) { + case EOZ: + lexerror(ls, (seminfo) ? "unfinished long string" : + "unfinished long comment", TK_EOS); + break; /* to avoid warnings */ + case ']': { + if (skip_sep(ls) == sep) { + save_and_next(ls); /* skip 2nd `]' */ + goto endloop; + } + break; + } + case '\n': case '\r': { + save(ls, '\n'); + inclinenumber(ls); + if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ + break; + } + default: { + if (seminfo) save_and_next(ls); + else next(ls); + } + } + } endloop: + if (seminfo) + seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep), + luaZ_bufflen(ls->buff) - 2*(2 + sep)); +} + + +static void escerror (LexState *ls, int *c, int n, const char *msg) { + int i; + luaZ_resetbuffer(ls->buff); /* prepare error message */ + save(ls, '\\'); + for (i = 0; i < n && c[i] != EOZ; i++) + save(ls, c[i]); + lexerror(ls, msg, TK_STRING); +} + + +static int readhexaesc (LexState *ls) { + int c[3], i; /* keep input for error message */ + int r = 0; /* result accumulator */ + c[0] = 'x'; /* for error message */ + for (i = 1; i < 3; i++) { /* read two hexadecimal digits */ + c[i] = next(ls); + if (!lisxdigit(c[i])) + escerror(ls, c, i + 1, "hexadecimal digit expected"); + r = (r << 4) + luaO_hexavalue(c[i]); + } + return r; +} + + +static int readdecesc (LexState *ls) { + int c[3], i; + int r = 0; /* result accumulator */ + for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */ + c[i] = ls->current; + r = 10*r + c[i] - '0'; + next(ls); + } + if (r > UCHAR_MAX) + escerror(ls, c, i, "decimal escape too large"); + return r; +} + + +static void read_string (LexState *ls, int del, SemInfo *seminfo) { + save_and_next(ls); /* keep delimiter (for error messages) */ + while (ls->current != del) { + switch (ls->current) { + case EOZ: + lexerror(ls, "unfinished string", TK_EOS); + break; /* to avoid warnings */ + case '\n': + case '\r': + lexerror(ls, "unfinished string", TK_STRING); + break; /* to avoid warnings */ + case '\\': { /* escape sequences */ + int c; /* final character to be saved */ + next(ls); /* do not save the `\' */ + switch (ls->current) { + case '*': c = '\1'; goto read_save; + case '#': c = '\2'; goto read_save; + case '-': c = '\3'; goto read_save; + case '|': c = '\4'; goto read_save; + case '+': c = '\5'; goto read_save; + case '^': c = '\6'; goto read_save; + case 'a': c = '\a'; goto read_save; + case 'b': c = '\b'; goto read_save; + case 'f': c = '\f'; goto read_save; + case 'n': c = '\n'; goto read_save; + case 'r': c = '\r'; goto read_save; + case 't': c = '\t'; goto read_save; + case 'v': c = '\v'; goto read_save; + case 'x': c = readhexaesc(ls); goto read_save; + case '\n': case '\r': + inclinenumber(ls); c = '\n'; goto only_save; + case '\\': case '\"': case '\'': + c = ls->current; goto read_save; + case EOZ: goto no_save; /* will raise an error next loop */ + case 'z': { /* zap following span of spaces */ + next(ls); /* skip the 'z' */ + while (lisspace(ls->current)) { + if (currIsNewline(ls)) inclinenumber(ls); + else next(ls); + } + goto no_save; + } + default: { + if (!lisdigit(ls->current)) + escerror(ls, &ls->current, 1, "invalid escape sequence"); + /* digital escape \ddd */ + c = readdecesc(ls); + goto only_save; + } + } + read_save: next(ls); /* read next character */ + only_save: save(ls, c); /* save 'c' */ + no_save: break; + } + default: + save_and_next(ls); + } + } + save_and_next(ls); /* skip delimiter */ + seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, + luaZ_bufflen(ls->buff) - 2); +} + + +static int llex (LexState *ls, SemInfo *seminfo) { + luaZ_resetbuffer(ls->buff); + for (;;) { + switch (ls->current) { + case '\n': case '\r': { /* line breaks */ + inclinenumber(ls); + if (ls->emiteol) { ls->emiteol = 0; return TK_EOL; } + break; + } + case ' ': case '\f': case '\t': case '\v': { /* spaces */ + next(ls); + break; + } + case '?': { /* '?' (shorthand print) */ + next(ls); + ls->emiteol = 1; + return TK_PRINT; + } + case '-': { /* '-' or '-=' or '--' (comment) */ + next(ls); + if (ls->current == '=') { next(ls); return TK_SUBE; } + else if (ls->current != '-') return '-'; + /* else is a comment */ + next(ls); + if (ls->current == '[') { /* long comment? */ + int sep = skip_sep(ls); + luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */ + if (sep >= 0) { + read_long_string(ls, NULL, sep); /* skip long comment */ + luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */ + break; + } + } + /* else short comment */ + while (!currIsNewline(ls) && ls->current != EOZ) + next(ls); /* skip until end of line (or end of file) */ + break; + } + case '/': { /* '/' or '/=' or '//' (short comment) */ + next(ls); + if (ls->current == '=') { next(ls); return TK_DIVE; } + else if (ls->current != '/') return '/'; + next(ls); + while (!currIsNewline(ls) && ls->current != EOZ) + next(ls); /* skip until end of line (or end of file) */ + break; + } + case '+': case '*': case '%': case '&': + case '|': case '~': case '!': case '\\': { + /* '+', '*', '%', '\', '&', '|', '!', '~', and + the '+=' etc. counterparts */ + int c = ls->current; + next(ls); + if (ls->current != '=') return c; + else { + next(ls); + switch (c) { + case '+': return TK_ADDE; + case '*': return TK_MULE; + case '%': return TK_MODE; + case '&': return TK_BANDE; + case '|': return TK_BORE; + case '~': return TK_NE; + case '!': return TK_NE2; + case '\\': default: return TK_IDIVE; + } + } + } + case '[': { /* long string or simply '[' */ + int sep = skip_sep(ls); + if (sep >= 0) { + read_long_string(ls, seminfo, sep); + return TK_STRING; + } + else if (sep == -1) return '['; + else lexerror(ls, "invalid long string delimiter", TK_STRING); + } + case '=': { + next(ls); + if (ls->current != '=') return '='; + else { next(ls); return TK_EQ; } + } + case '<': { /* '<=' or '<' or '<<=' or '<<' or '<<>=' or '<<>' */ + next(ls); + if (ls->current == '=') { next(ls); return TK_LE; } + else if (ls->current != '<') return '<'; + next(ls); + if (ls->current == '=') { next(ls); return TK_SHLE; } + else if (ls->current != '>') return TK_SHL; + next(ls); + if (ls->current == '=') { next(ls); return TK_ROTLE; } + else return TK_ROTL; + } + case '^': { /* '^=' or '^' or '^^' or '^^=' */ + next(ls); + if (ls->current == '=') { next(ls); return TK_POWE; } + else if (ls->current != '^') return '^'; + next(ls); + if (ls->current == '=') { next(ls); return TK_BXORE; } + else return TK_BXOR; + } + case '>': { /* '>=', '>', '>>=', '>><=', >><', '>>', '>>>=', or '>>>' */ + next(ls); + if (ls->current == '=') { next(ls); return TK_GE; } + else if (ls->current != '>') return '>'; + next(ls); + if (ls->current == '=') { next(ls); return TK_SHRE; } + else if (ls->current == '<') { + next(ls); + if (ls->current == '=') { next(ls); return TK_ROTRE; } + else return TK_ROTR; + } + else if (ls->current != '>') return TK_SHR; + next(ls); + if (ls->current == '=') { next(ls); return TK_LSHRE; } + else return TK_LSHR; + } + case ':': { + next(ls); + if (ls->current != ':') return ':'; + else { next(ls); return TK_DBCOLON; } + } + case '"': case '\'': { /* short literal strings */ + read_string(ls, ls->current, seminfo); + return TK_STRING; + } + case '.': { /* '.', '..', '..=', '...', or number */ + save_and_next(ls); + if (check_next(ls, ".")) { + if (check_next(ls, ".")) + return TK_DOTS; /* '...' */ + else if (check_next(ls, "=")) + return TK_CONCATE; /* '..=' */ + else return TK_CONCAT; /* '..' */ + } + else if (!lisdigit(ls->current)) return '.'; + /* else go through */ + } + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + read_numeral(ls, seminfo); + return TK_NUMBER; + } + case EOZ: { + return TK_EOS; + } + default: { + if (lislalpha(ls->current)) { /* identifier or reserved word? */ + TString *ts; + do { + save_and_next(ls); + } while (lislalnum(ls->current)); + ts = luaX_newstring(ls, luaZ_buffer(ls->buff), + luaZ_bufflen(ls->buff)); + seminfo->ts = ts; + if (isreserved(ts)) /* reserved word? */ + return ts->tsv.extra - 1 + FIRST_RESERVED; + else { + return TK_NAME; + } + } + else { /* single-char tokens (+ - / ...) */ + int c = ls->current; + ls->braces += c == ')' ? -1 : /* handle brace count for short if */ + c == '(' ? ls->braces > 0 ? 1 : -1 : 0; + next(ls); + return c; + } + } + } + } +} + + +void luaX_next (LexState *ls) { + ls->lastline = ls->linenumber; + if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ + ls->t = ls->lookahead; /* use this one */ + ls->lookahead.token = TK_EOS; /* and discharge it */ + } + else + ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ +} + + +int luaX_lookahead (LexState *ls) { + lua_assert(ls->lookahead.token == TK_EOS); + ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); + return ls->lookahead.token; +} + diff --git a/components/pico8/femto8/src/lua/llex.h b/components/pico8/femto8/src/lua/llex.h new file mode 100644 index 00000000..510baac5 --- /dev/null +++ b/components/pico8/femto8/src/lua/llex.h @@ -0,0 +1,88 @@ +/* +** $Id: llex.h,v 1.72 2011/11/30 12:43:51 roberto Exp $ +** Lexical Analyzer +** See Copyright Notice in lua.h +*/ + +#ifndef llex_h +#define llex_h + +#include "lobject.h" +#include "lzio.h" + + +#define FIRST_RESERVED 257 + + + +/* +* WARNING: if you change the order of this enumeration, +* grep "ORDER RESERVED" +*/ +enum RESERVED { + /* terminal symbols denoted by reserved words */ + TK_AND = FIRST_RESERVED, TK_BREAK, + TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION, + TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, + TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE, + /* other terminal symbols */ + TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NE2, TK_DBCOLON, + TK_EOS, TK_NUMBER, TK_NAME, TK_STRING, TK_PRINT, TK_EOL, + TK_BXOR, TK_SHL, TK_SHR, TK_LSHR, TK_ROTL, TK_ROTR, + /* these must be last and match "ORDER OPR" */ + TK_ADDE, TK_SUBE, TK_MULE, TK_DIVE, TK_MODE, TK_POWE, TK_IDIVE, + TK_BANDE, TK_BORE, TK_BXORE, TK_SHLE, TK_SHRE, TK_LSHRE, TK_ROTLE, + TK_ROTRE, TK_CONCATE, +}; + +/* number of reserved words */ +#define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1)) + + +typedef union { + lua_Number r; + TString *ts; +} SemInfo; /* semantics information */ + + +typedef struct Token { + int token; + SemInfo seminfo; +} Token; + + +/* state of the lexer plus state of the parser when shared by all + functions */ +typedef struct LexState { + int current; /* current character (charint) */ + int linenumber; /* input line counter */ + int atsol; /* are we at start of line? */ + int emiteol; /* should EOL be emitted? */ + int lastline; /* line of last token `consumed' */ + int braces; /* braces context */ + int short_nest; /* nesting depth of active short-if/while blocks */ + Token t; /* current token */ + Token lookahead; /* look ahead token */ + struct FuncState *fs; /* current function (parser) */ + struct lua_State *L; + ZIO *z; /* input stream */ + Mbuffer *buff; /* buffer for tokens */ + struct Dyndata *dyd; /* dynamic structures used by the parser */ + TString *source; /* current source name */ + TString *envn; /* environment variable name */ + char decpoint; /* locale decimal point */ +} LexState; + + +LUAI_FUNC void luaX_init (lua_State *L); +LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, + TString *source, int firstchar); +LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l); +LUAI_FUNC void luaX_next (LexState *ls); +LUAI_FUNC int luaX_lookahead (LexState *ls); +LUAI_FUNC l_noret luaX_syntaxerror (LexState *ls, const char *s); +LUAI_FUNC const char *luaX_token2str (LexState *ls, int token); +LUAI_FUNC void luaX_trackbraces (LexState *ls); + + +#endif diff --git a/components/pico8/femto8/src/lua/llimits.h b/components/pico8/femto8/src/lua/llimits.h new file mode 100644 index 00000000..927ad490 --- /dev/null +++ b/components/pico8/femto8/src/lua/llimits.h @@ -0,0 +1,228 @@ +/* +** $Id: llimits.h,v 1.103 2013/02/20 14:08:56 roberto Exp $ +** Limits, basic types, and some other `installation-dependent' definitions +** See Copyright Notice in lua.h +*/ + +#ifndef llimits_h +#define llimits_h + + +#include +#include + + +#include "lua.h" + + +typedef unsigned LUA_INT32 lu_int32; + +typedef LUAI_UMEM lu_mem; + +typedef LUAI_MEM l_mem; + + + +/* chars used as small naturals (so that `char' is reserved for characters) */ +typedef unsigned char lu_byte; + + +#define MAX_SIZET ((size_t)(~(size_t)0)-2) + +#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2) + +#define MAX_LMEM ((l_mem) ((MAX_LUMEM >> 1) - 2)) + + +#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */ + +/* +** conversion of pointer to integer +** this is for hashing only; there is no problem if the integer +** cannot hold the whole pointer value +*/ +#define IntPoint(p) ((unsigned int)(lu_mem)(p)) + + + +/* type to ensure maximum alignment */ +#if !defined(LUAI_USER_ALIGNMENT_T) +#define LUAI_USER_ALIGNMENT_T union { double u; void *s; long l; } +#endif + +typedef LUAI_USER_ALIGNMENT_T L_Umaxalign; + + +/* result of a `usual argument conversion' over lua_Number */ +typedef LUAI_UACNUMBER l_uacNumber; + + +/* internal assertions for in-house debugging */ +#if defined(lua_assert) +#define check_exp(c,e) (lua_assert(c), (e)) +/* to avoid problems with conditions too long */ +#define lua_longassert(c) { if (!(c)) lua_assert(0); } +#else +#define lua_assert(c) ((void)0) +#define check_exp(c,e) (e) +#define lua_longassert(c) ((void)0) +#endif + +/* +** assertion for checking API calls +*/ +#if !defined(luai_apicheck) + +#if defined(LUA_USE_APICHECK) +#include +#define luai_apicheck(L,e) assert(e) +#else +#define luai_apicheck(L,e) lua_assert(e) +#endif + +#endif + +#define api_check(l,e,msg) luai_apicheck(l,(e) && msg) + + +#if !defined(UNUSED) +#define UNUSED(x) ((void)(x)) /* to avoid warnings */ +#endif + + +#define cast(t, exp) ((t)(exp)) + +#define cast_byte(i) cast(lu_byte, (i)) +#define cast_num(i) fix32_from_int(i) +#define cast_int(i) cast(int, (i)) +#define cast_uchar(i) cast(unsigned char, (i)) + + +/* +** non-return type +*/ +#if defined(__GNUC__) +#define l_noret void __attribute__((noreturn)) +#elif defined(_MSC_VER) +#define l_noret void __declspec(noreturn) +#else +#define l_noret void +#endif + + + +/* +** maximum depth for nested C calls and syntactical nested non-terminals +** in a program. (Value must fit in an unsigned short int.) +*/ +#if !defined(LUAI_MAXCCALLS) +#define LUAI_MAXCCALLS 200 +#endif + +/* +** maximum number of upvalues in a closure (both C and Lua). (Value +** must fit in an unsigned char.) +*/ +#define MAXUPVAL UCHAR_MAX + + +/* +** type for virtual-machine instructions +** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h) +*/ +typedef lu_int32 Instruction; + + + +/* maximum stack for a Lua function */ +#define MAXSTACK 250 + + + +/* minimum size for the string table (must be power of 2) */ +#if !defined(MINSTRTABSIZE) +#define MINSTRTABSIZE 32 +#endif + + +/* minimum size for string buffer */ +#if !defined(LUA_MINBUFFER) +#define LUA_MINBUFFER 32 +#endif + + +#if !defined(lua_lock) +#define lua_lock(L) ((void) 0) +#define lua_unlock(L) ((void) 0) +#endif + +#if !defined(luai_threadyield) +#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} +#endif + + +/* +** these macros allow user-specific actions on threads when you defined +** LUAI_EXTRASPACE and need to do something extra when a thread is +** created/deleted/resumed/yielded. +*/ +#if !defined(luai_userstateopen) +#define luai_userstateopen(L) ((void)L) +#endif + +#if !defined(luai_userstateclose) +#define luai_userstateclose(L) ((void)L) +#endif + +#if !defined(luai_userstatethread) +#define luai_userstatethread(L,L1) ((void)L) +#endif + +#if !defined(luai_userstatefree) +#define luai_userstatefree(L,L1) ((void)L) +#endif + +#if !defined(luai_userstateresume) +#define luai_userstateresume(L,n) ((void)L) +#endif + +#if !defined(luai_userstateyield) +#define luai_userstateyield(L,n) ((void)L) +#endif + +/* +** lua_number2int is a macro to convert lua_Number (fix32_t) to int. +** lua_number2integer is a macro to convert lua_Number to lua_Integer. +** lua_number2unsigned is a macro to convert a lua_Number to a lua_Unsigned. +** lua_unsigned2number is a macro to convert a lua_Unsigned to a lua_Number. +** luai_hashnum is defined in luaconf.h for fix32. +** +** For fix32_t, these all use fix32_to_int which does >> 16. +*/ + +#define lua_number2int(i,n) ((i) = fix32_to_int(n)) +#define lua_number2integer(i,n) ((i) = (lua_Integer)fix32_to_int(n)) +#define lua_number2unsigned(i,n) ((i) = (lua_Unsigned)(uint16_t)fix32_to_int(n)) + +#define lua_unsigned2number(u) fix32_from_int((int)(u)) + + + +/* +** macro to control inclusion of some hard tests on stack reallocation +*/ +#if !defined(HARDSTACKTESTS) +#define condmovestack(L) ((void)0) +#else +/* realloc stack keeping its size */ +#define condmovestack(L) luaD_reallocstack((L), (L)->stacksize) +#endif + +#if !defined(HARDMEMTESTS) +#define condchangemem(L) condmovestack(L) +#else +#define condchangemem(L) \ + ((void)(!(G(L)->gcrunning) || (luaC_fullgc(L, 0), 1))) +#endif + +#endif diff --git a/components/pico8/femto8/src/lua/lmem.c b/components/pico8/femto8/src/lua/lmem.c new file mode 100644 index 00000000..3f88496e --- /dev/null +++ b/components/pico8/femto8/src/lua/lmem.c @@ -0,0 +1,99 @@ +/* +** $Id: lmem.c,v 1.84 2012/05/23 15:41:53 roberto Exp $ +** Interface to Memory Manager +** See Copyright Notice in lua.h +*/ + + +#include + +#define lmem_c +#define LUA_CORE + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" + + + +/* +** About the realloc function: +** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize); +** (`osize' is the old size, `nsize' is the new size) +** +** * frealloc(ud, NULL, x, s) creates a new block of size `s' (no +** matter 'x'). +** +** * frealloc(ud, p, x, 0) frees the block `p' +** (in this specific case, frealloc must return NULL); +** particularly, frealloc(ud, NULL, 0, 0) does nothing +** (which is equivalent to free(NULL) in ANSI C) +** +** frealloc returns NULL if it cannot create or reallocate the area +** (any reallocation to an equal or smaller size cannot fail!) +*/ + + + +#define MINSIZEARRAY 4 + + +void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems, + int limit, const char *what) { + void *newblock; + int newsize; + if (*size >= limit/2) { /* cannot double it? */ + if (*size >= limit) /* cannot grow even a little? */ + luaG_runerror(L, "too many %s (limit is %d)", what, limit); + newsize = limit; /* still have at least one free place */ + } + else { + newsize = (*size)*2; + if (newsize < MINSIZEARRAY) + newsize = MINSIZEARRAY; /* minimum size */ + } + newblock = luaM_reallocv(L, block, *size, newsize, size_elems); + *size = newsize; /* update only when everything else is OK */ + return newblock; +} + + +l_noret luaM_toobig (lua_State *L) { + luaG_runerror(L, "memory allocation error: block too big"); +} + + + +/* +** generic allocation routine. +*/ +void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { + void *newblock; + global_State *g = G(L); + size_t realosize = (block) ? osize : 0; + lua_assert((realosize == 0) == (block == NULL)); +#if defined(HARDMEMTESTS) + if (nsize > realosize && g->gcrunning) + luaC_fullgc(L, 1); /* force a GC whenever possible */ +#endif + newblock = (*g->frealloc)(g->ud, block, osize, nsize); + if (newblock == NULL && nsize > 0) { + api_check(L, nsize > realosize, + "realloc cannot fail when shrinking a block"); + if (g->gcrunning) { + luaC_fullgc(L, 1); /* try to free some memory... */ + newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */ + } + if (newblock == NULL) + luaD_throw(L, LUA_ERRMEM); + } + lua_assert((nsize == 0) == (newblock == NULL)); + g->GCdebt = (g->GCdebt + nsize) - realosize; + return newblock; +} + diff --git a/components/pico8/femto8/src/lua/lmem.h b/components/pico8/femto8/src/lua/lmem.h new file mode 100644 index 00000000..5f850999 --- /dev/null +++ b/components/pico8/femto8/src/lua/lmem.h @@ -0,0 +1,57 @@ +/* +** $Id: lmem.h,v 1.40 2013/02/20 14:08:21 roberto Exp $ +** Interface to Memory Manager +** See Copyright Notice in lua.h +*/ + +#ifndef lmem_h +#define lmem_h + + +#include + +#include "llimits.h" +#include "lua.h" + + +/* +** This macro avoids the runtime division MAX_SIZET/(e), as 'e' is +** always constant. +** The macro is somewhat complex to avoid warnings: +** +1 avoids warnings of "comparison has constant result"; +** cast to 'void' avoids warnings of "value unused". +*/ +#define luaM_reallocv(L,b,on,n,e) \ + (cast(void, \ + (cast(size_t, (n)+1) > MAX_SIZET/(e)) ? (luaM_toobig(L), 0) : 0), \ + luaM_realloc_(L, (b), (on)*(e), (n)*(e))) + +#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0) +#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0) +#define luaM_freearray(L, b, n) luaM_reallocv(L, (b), n, 0, sizeof((b)[0])) + +#define luaM_malloc(L,s) luaM_realloc_(L, NULL, 0, (s)) +#define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t))) +#define luaM_newvector(L,n,t) \ + cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t))) + +#define luaM_newobject(L,tag,s) luaM_realloc_(L, NULL, tag, (s)) + +#define luaM_growvector(L,v,nelems,size,t,limit,e) \ + if ((nelems)+1 > (size)) \ + ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e))) + +#define luaM_reallocvector(L, v,oldn,n,t) \ + ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t)))) + +LUAI_FUNC l_noret luaM_toobig (lua_State *L); + +/* not to be called directly */ +LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, + size_t size); +LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size, + size_t size_elem, int limit, + const char *what); + +#endif + diff --git a/components/pico8/femto8/src/lua/loadlib.c b/components/pico8/femto8/src/lua/loadlib.c new file mode 100644 index 00000000..a9959277 --- /dev/null +++ b/components/pico8/femto8/src/lua/loadlib.c @@ -0,0 +1,725 @@ +/* +** $Id: loadlib.c,v 1.111 2012/05/30 12:33:44 roberto Exp $ +** Dynamic library loader for Lua +** See Copyright Notice in lua.h +** +** This module contains an implementation of loadlib for Unix systems +** that have dlfcn, an implementation for Windows, and a stub for other +** systems. +*/ + + +/* +** if needed, includes windows header before everything else +*/ +#if defined(_WIN32) +#include +#endif + + +#include +#include + + +#define loadlib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +/* +** LUA_PATH and LUA_CPATH are the names of the environment +** variables that Lua check to set its paths. +*/ +#if !defined(LUA_PATH) +#define LUA_PATH "LUA_PATH" +#endif + +#if !defined(LUA_CPATH) +#define LUA_CPATH "LUA_CPATH" +#endif + +#define LUA_PATHSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR + +#define LUA_PATHVERSION LUA_PATH LUA_PATHSUFFIX +#define LUA_CPATHVERSION LUA_CPATH LUA_PATHSUFFIX + +/* +** LUA_PATH_SEP is the character that separates templates in a path. +** LUA_PATH_MARK is the string that marks the substitution points in a +** template. +** LUA_EXEC_DIR in a Windows path is replaced by the executable's +** directory. +** LUA_IGMARK is a mark to ignore all before it when building the +** luaopen_ function name. +*/ +#if !defined (LUA_PATH_SEP) +#define LUA_PATH_SEP ";" +#endif +#if !defined (LUA_PATH_MARK) +#define LUA_PATH_MARK "?" +#endif +#if !defined (LUA_EXEC_DIR) +#define LUA_EXEC_DIR "!" +#endif +#if !defined (LUA_IGMARK) +#define LUA_IGMARK "-" +#endif + + +/* +** LUA_CSUBSEP is the character that replaces dots in submodule names +** when searching for a C loader. +** LUA_LSUBSEP is the character that replaces dots in submodule names +** when searching for a Lua loader. +*/ +#if !defined(LUA_CSUBSEP) +#define LUA_CSUBSEP LUA_DIRSEP +#endif + +#if !defined(LUA_LSUBSEP) +#define LUA_LSUBSEP LUA_DIRSEP +#endif + + +/* prefix for open functions in C libraries */ +#define LUA_POF "luaopen_" + +/* separator for open functions in C libraries */ +#define LUA_OFSEP "_" + + +/* table (in the registry) that keeps handles for all loaded C libraries */ +#define CLIBS "_CLIBS" + +#define LIB_FAIL "open" + + +/* error codes for ll_loadfunc */ +#define ERRLIB 1 +#define ERRFUNC 2 + +#define setprogdir(L) ((void)0) + + +/* +** system-dependent functions +*/ +static void ll_unloadlib (void *lib); +static void *ll_load (lua_State *L, const char *path, int seeglb); +static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym); + + + +#if defined(LUA_USE_DLOPEN) +/* +** {======================================================================== +** This is an implementation of loadlib based on the dlfcn interface. +** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD, +** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least +** as an emulation layer on top of native functions. +** ========================================================================= +*/ + +#include + +static void ll_unloadlib (void *lib) { + dlclose(lib); +} + + +static void *ll_load (lua_State *L, const char *path, int seeglb) { + void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL)); + if (lib == NULL) lua_pushstring(L, dlerror()); + return lib; +} + + +static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { + lua_CFunction f = (lua_CFunction)dlsym(lib, sym); + if (f == NULL) lua_pushstring(L, dlerror()); + return f; +} + +/* }====================================================== */ + + + +#elif defined(LUA_DL_DLL) +/* +** {====================================================================== +** This is an implementation of loadlib for Windows using native functions. +** ======================================================================= +*/ + +#undef setprogdir + +/* +** optional flags for LoadLibraryEx +*/ +#if !defined(LUA_LLE_FLAGS) +#define LUA_LLE_FLAGS 0 +#endif + + +static void setprogdir (lua_State *L) { + char buff[MAX_PATH + 1]; + char *lb; + DWORD nsize = sizeof(buff)/sizeof(char); + DWORD n = GetModuleFileNameA(NULL, buff, nsize); + if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) + luaL_error(L, "unable to get ModuleFileName"); + else { + *lb = '\0'; + luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff); + lua_remove(L, -2); /* remove original string */ + } +} + + +static void pusherror (lua_State *L) { + int error = GetLastError(); + char buffer[128]; + if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL)) + lua_pushstring(L, buffer); + else + lua_pushfstring(L, "system error %d\n", error); +} + +static void ll_unloadlib (void *lib) { + FreeLibrary((HMODULE)lib); +} + + +static void *ll_load (lua_State *L, const char *path, int seeglb) { + HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS); + (void)(seeglb); /* not used: symbols are 'global' by default */ + if (lib == NULL) pusherror(L); + return lib; +} + + +static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { + lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym); + if (f == NULL) pusherror(L); + return f; +} + +/* }====================================================== */ + + +#else +/* +** {====================================================== +** Fallback for other systems +** ======================================================= +*/ + +#undef LIB_FAIL +#define LIB_FAIL "absent" + + +#define DLMSG "dynamic libraries not enabled; check your Lua installation" + + +static void ll_unloadlib (void *lib) { + (void)(lib); /* not used */ +} + + +static void *ll_load (lua_State *L, const char *path, int seeglb) { + (void)(path); (void)(seeglb); /* not used */ + lua_pushliteral(L, DLMSG); + return NULL; +} + + +static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { + (void)(lib); (void)(sym); /* not used */ + lua_pushliteral(L, DLMSG); + return NULL; +} + +/* }====================================================== */ +#endif + + +static void *ll_checkclib (lua_State *L, const char *path) { + void *plib; + lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); + lua_getfield(L, -1, path); + plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */ + lua_pop(L, 2); /* pop CLIBS table and 'plib' */ + return plib; +} + + +static void ll_addtoclib (lua_State *L, const char *path, void *plib) { + lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); + lua_pushlightuserdata(L, plib); + lua_pushvalue(L, -1); + lua_setfield(L, -3, path); /* CLIBS[path] = plib */ + lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */ + lua_pop(L, 1); /* pop CLIBS table */ +} + + +/* +** __gc tag method for CLIBS table: calls 'll_unloadlib' for all lib +** handles in list CLIBS +*/ +static int gctm (lua_State *L) { + int n = luaL_len(L, 1); + for (; n >= 1; n--) { /* for each handle, in reverse order */ + lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */ + ll_unloadlib(lua_touserdata(L, -1)); + lua_pop(L, 1); /* pop handle */ + } + return 0; +} + + +static int ll_loadfunc (lua_State *L, const char *path, const char *sym) { + void *reg = ll_checkclib(L, path); /* check loaded C libraries */ + if (reg == NULL) { /* must load library? */ + reg = ll_load(L, path, *sym == '*'); + if (reg == NULL) return ERRLIB; /* unable to load library */ + ll_addtoclib(L, path, reg); + } + if (*sym == '*') { /* loading only library (no function)? */ + lua_pushboolean(L, 1); /* return 'true' */ + return 0; /* no errors */ + } + else { + lua_CFunction f = ll_sym(L, reg, sym); + if (f == NULL) + return ERRFUNC; /* unable to find function */ + lua_pushcfunction(L, f); /* else create new function */ + return 0; /* no errors */ + } +} + + +static int ll_loadlib (lua_State *L) { + const char *path = luaL_checkstring(L, 1); + const char *init = luaL_checkstring(L, 2); + int stat = ll_loadfunc(L, path, init); + if (stat == 0) /* no errors? */ + return 1; /* return the loaded function */ + else { /* error; error message is on stack top */ + lua_pushnil(L); + lua_insert(L, -2); + lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); + return 3; /* return nil, error message, and where */ + } +} + + + +/* +** {====================================================== +** 'require' function +** ======================================================= +*/ + + +static int readable (const char *filename) { + FILE *f = fopen(filename, "r"); /* try to open file */ + if (f == NULL) return 0; /* open failed */ + fclose(f); + return 1; +} + + +static const char *pushnexttemplate (lua_State *L, const char *path) { + const char *l; + while (*path == *LUA_PATH_SEP) path++; /* skip separators */ + if (*path == '\0') return NULL; /* no more templates */ + l = strchr(path, *LUA_PATH_SEP); /* find next separator */ + if (l == NULL) l = path + strlen(path); + lua_pushlstring(L, path, l - path); /* template */ + return l; +} + + +static const char *searchpath (lua_State *L, const char *name, + const char *path, + const char *sep, + const char *dirsep) { + luaL_Buffer msg; /* to build error message */ + luaL_buffinit(L, &msg); + if (*sep != '\0') /* non-empty separator? */ + name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */ + while ((path = pushnexttemplate(L, path)) != NULL) { + const char *filename = luaL_gsub(L, lua_tostring(L, -1), + LUA_PATH_MARK, name); + lua_remove(L, -2); /* remove path template */ + if (readable(filename)) /* does file exist and is readable? */ + return filename; /* return that file name */ + lua_pushfstring(L, "\n\tno file " LUA_QS, filename); + lua_remove(L, -2); /* remove file name */ + luaL_addvalue(&msg); /* concatenate error msg. entry */ + } + luaL_pushresult(&msg); /* create error message */ + return NULL; /* not found */ +} + + +static int ll_searchpath (lua_State *L) { + const char *f = searchpath(L, luaL_checkstring(L, 1), + luaL_checkstring(L, 2), + luaL_optstring(L, 3, "."), + luaL_optstring(L, 4, LUA_DIRSEP)); + if (f != NULL) return 1; + else { /* error message is on top of the stack */ + lua_pushnil(L); + lua_insert(L, -2); + return 2; /* return nil + error message */ + } +} + + +static const char *findfile (lua_State *L, const char *name, + const char *pname, + const char *dirsep) { + const char *path; + lua_getfield(L, lua_upvalueindex(1), pname); + path = lua_tostring(L, -1); + if (path == NULL) + luaL_error(L, LUA_QL("package.%s") " must be a string", pname); + return searchpath(L, name, path, ".", dirsep); +} + + +static int checkload (lua_State *L, int stat, const char *filename) { + if (stat) { /* module loaded successfully? */ + lua_pushstring(L, filename); /* will be 2nd argument to module */ + return 2; /* return open function and file name */ + } + else + return luaL_error(L, "error loading module " LUA_QS + " from file " LUA_QS ":\n\t%s", + lua_tostring(L, 1), filename, lua_tostring(L, -1)); +} + + +static int searcher_Lua (lua_State *L) { + const char *filename; + const char *name = luaL_checkstring(L, 1); + filename = findfile(L, name, "path", LUA_LSUBSEP); + if (filename == NULL) return 1; /* module not found in this path */ + return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename); +} + + +static int loadfunc (lua_State *L, const char *filename, const char *modname) { + const char *funcname; + const char *mark; + modname = luaL_gsub(L, modname, ".", LUA_OFSEP); + mark = strchr(modname, *LUA_IGMARK); + if (mark) { + int stat; + funcname = lua_pushlstring(L, modname, mark - modname); + funcname = lua_pushfstring(L, LUA_POF"%s", funcname); + stat = ll_loadfunc(L, filename, funcname); + if (stat != ERRFUNC) return stat; + modname = mark + 1; /* else go ahead and try old-style name */ + } + funcname = lua_pushfstring(L, LUA_POF"%s", modname); + return ll_loadfunc(L, filename, funcname); +} + + +static int searcher_C (lua_State *L) { + const char *name = luaL_checkstring(L, 1); + const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP); + if (filename == NULL) return 1; /* module not found in this path */ + return checkload(L, (loadfunc(L, filename, name) == 0), filename); +} + + +static int searcher_Croot (lua_State *L) { + const char *filename; + const char *name = luaL_checkstring(L, 1); + const char *p = strchr(name, '.'); + int stat; + if (p == NULL) return 0; /* is root */ + lua_pushlstring(L, name, p - name); + filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP); + if (filename == NULL) return 1; /* root not found */ + if ((stat = loadfunc(L, filename, name)) != 0) { + if (stat != ERRFUNC) + return checkload(L, 0, filename); /* real error */ + else { /* open function not found */ + lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS, + name, filename); + return 1; + } + } + lua_pushstring(L, filename); /* will be 2nd argument to module */ + return 2; +} + + +static int searcher_preload (lua_State *L) { + const char *name = luaL_checkstring(L, 1); + lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD"); + lua_getfield(L, -1, name); + if (lua_isnil(L, -1)) /* not found? */ + lua_pushfstring(L, "\n\tno field package.preload['%s']", name); + return 1; +} + + +static void findloader (lua_State *L, const char *name) { + int i; + luaL_Buffer msg; /* to build error message */ + luaL_buffinit(L, &msg); + lua_getfield(L, lua_upvalueindex(1), "searchers"); /* will be at index 3 */ + if (!lua_istable(L, 3)) + luaL_error(L, LUA_QL("package.searchers") " must be a table"); + /* iterate over available searchers to find a loader */ + for (i = 1; ; i++) { + lua_rawgeti(L, 3, i); /* get a searcher */ + if (lua_isnil(L, -1)) { /* no more searchers? */ + lua_pop(L, 1); /* remove nil */ + luaL_pushresult(&msg); /* create error message */ + luaL_error(L, "module " LUA_QS " not found:%s", + name, lua_tostring(L, -1)); + } + lua_pushstring(L, name); + lua_call(L, 1, 2); /* call it */ + if (lua_isfunction(L, -2)) /* did it find a loader? */ + return; /* module loader found */ + else if (lua_isstring(L, -2)) { /* searcher returned error message? */ + lua_pop(L, 1); /* remove extra return */ + luaL_addvalue(&msg); /* concatenate error message */ + } + else + lua_pop(L, 2); /* remove both returns */ + } +} + + +static int ll_require (lua_State *L) { + const char *name = luaL_checkstring(L, 1); + lua_settop(L, 1); /* _LOADED table will be at index 2 */ + lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); + lua_getfield(L, 2, name); /* _LOADED[name] */ + if (lua_toboolean(L, -1)) /* is it there? */ + return 1; /* package is already loaded */ + /* else must load package */ + lua_pop(L, 1); /* remove 'getfield' result */ + findloader(L, name); + lua_pushstring(L, name); /* pass name as argument to module loader */ + lua_insert(L, -2); /* name is 1st argument (before search data) */ + lua_call(L, 2, 1); /* run loader to load module */ + if (!lua_isnil(L, -1)) /* non-nil return? */ + lua_setfield(L, 2, name); /* _LOADED[name] = returned value */ + lua_getfield(L, 2, name); + if (lua_isnil(L, -1)) { /* module did not set a value? */ + lua_pushboolean(L, 1); /* use true as result */ + lua_pushvalue(L, -1); /* extra copy to be returned */ + lua_setfield(L, 2, name); /* _LOADED[name] = true */ + } + return 1; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** 'module' function +** ======================================================= +*/ +#if defined(LUA_COMPAT_MODULE) + +/* +** changes the environment variable of calling function +*/ +static void set_env (lua_State *L) { + lua_Debug ar; + if (lua_getstack(L, 1, &ar) == 0 || + lua_getinfo(L, "f", &ar) == 0 || /* get calling function */ + lua_iscfunction(L, -1)) + luaL_error(L, LUA_QL("module") " not called from a Lua function"); + lua_pushvalue(L, -2); /* copy new environment table to top */ + lua_setupvalue(L, -2, 1); + lua_pop(L, 1); /* remove function */ +} + + +static void dooptions (lua_State *L, int n) { + int i; + for (i = 2; i <= n; i++) { + if (lua_isfunction(L, i)) { /* avoid 'calling' extra info. */ + lua_pushvalue(L, i); /* get option (a function) */ + lua_pushvalue(L, -2); /* module */ + lua_call(L, 1, 0); + } + } +} + + +static void modinit (lua_State *L, const char *modname) { + const char *dot; + lua_pushvalue(L, -1); + lua_setfield(L, -2, "_M"); /* module._M = module */ + lua_pushstring(L, modname); + lua_setfield(L, -2, "_NAME"); + dot = strrchr(modname, '.'); /* look for last dot in module name */ + if (dot == NULL) dot = modname; + else dot++; + /* set _PACKAGE as package name (full module name minus last part) */ + lua_pushlstring(L, modname, dot - modname); + lua_setfield(L, -2, "_PACKAGE"); +} + + +static int ll_module (lua_State *L) { + const char *modname = luaL_checkstring(L, 1); + int lastarg = lua_gettop(L); /* last parameter */ + luaL_pushmodule(L, modname, 1); /* get/create module table */ + /* check whether table already has a _NAME field */ + lua_getfield(L, -1, "_NAME"); + if (!lua_isnil(L, -1)) /* is table an initialized module? */ + lua_pop(L, 1); + else { /* no; initialize it */ + lua_pop(L, 1); + modinit(L, modname); + } + lua_pushvalue(L, -1); + set_env(L); + dooptions(L, lastarg); + return 1; +} + + +static int ll_seeall (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + if (!lua_getmetatable(L, 1)) { + lua_createtable(L, 0, 1); /* create new metatable */ + lua_pushvalue(L, -1); + lua_setmetatable(L, 1); + } + lua_pushglobaltable(L); + lua_setfield(L, -2, "__index"); /* mt.__index = _G */ + return 0; +} + +#endif +/* }====================================================== */ + + + +/* auxiliary mark (for internal use) */ +#define AUXMARK "\1" + + +/* +** return registry.LUA_NOENV as a boolean +*/ +static int noenv (lua_State *L) { + int b; + lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); + b = lua_toboolean(L, -1); + lua_pop(L, 1); /* remove value */ + return b; +} + + +static void setpath (lua_State *L, const char *fieldname, const char *envname1, + const char *envname2, const char *def) { + const char *path = getenv(envname1); + if (path == NULL) /* no environment variable? */ + path = getenv(envname2); /* try alternative name */ + if (path == NULL || noenv(L)) /* no environment variable? */ + lua_pushstring(L, def); /* use default */ + else { + /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */ + path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP, + LUA_PATH_SEP AUXMARK LUA_PATH_SEP); + luaL_gsub(L, path, AUXMARK, def); + lua_remove(L, -2); + } + setprogdir(L); + lua_setfield(L, -2, fieldname); +} + + +static const luaL_Reg pk_funcs[] = { + {"loadlib", ll_loadlib}, + {"searchpath", ll_searchpath}, +#if defined(LUA_COMPAT_MODULE) + {"seeall", ll_seeall}, +#endif + {NULL, NULL} +}; + + +static const luaL_Reg ll_funcs[] = { +#if defined(LUA_COMPAT_MODULE) + {"module", ll_module}, +#endif + {"require", ll_require}, + {NULL, NULL} +}; + + +static void createsearcherstable (lua_State *L) { + static const lua_CFunction searchers[] = + {searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL}; + int i; + /* create 'searchers' table */ + lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0); + /* fill it with pre-defined searchers */ + for (i=0; searchers[i] != NULL; i++) { + lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */ + lua_pushcclosure(L, searchers[i], 1); + lua_rawseti(L, -2, i+1); + } +} + + +LUAMOD_API int luaopen_package (lua_State *L) { + /* create table CLIBS to keep track of loaded C libraries */ + luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); + lua_createtable(L, 0, 1); /* metatable for CLIBS */ + lua_pushcfunction(L, gctm); + lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */ + lua_setmetatable(L, -2); + /* create `package' table */ + luaL_newlib(L, pk_funcs); + createsearcherstable(L); +#if defined(LUA_COMPAT_LOADERS) + lua_pushvalue(L, -1); /* make a copy of 'searchers' table */ + lua_setfield(L, -3, "loaders"); /* put it in field `loaders' */ +#endif + lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */ + /* set field 'path' */ + setpath(L, "path", LUA_PATHVERSION, LUA_PATH, LUA_PATH_DEFAULT); + /* set field 'cpath' */ + setpath(L, "cpath", LUA_CPATHVERSION, LUA_CPATH, LUA_CPATH_DEFAULT); + /* store config information */ + lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" + LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); + lua_setfield(L, -2, "config"); + /* set field `loaded' */ + luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED"); + lua_setfield(L, -2, "loaded"); + /* set field `preload' */ + luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD"); + lua_setfield(L, -2, "preload"); + lua_pushglobaltable(L); + lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ + luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */ + lua_pop(L, 1); /* pop global table */ + return 1; /* return 'package' table */ +} + diff --git a/components/pico8/femto8/src/lua/lobject.c b/components/pico8/femto8/src/lua/lobject.c new file mode 100644 index 00000000..eae16684 --- /dev/null +++ b/components/pico8/femto8/src/lua/lobject.c @@ -0,0 +1,342 @@ +/* +** $Id: lobject.c,v 2.58 2013/02/20 14:08:56 roberto Exp $ +** Some generic functions over Lua objects +** See Copyright Notice in lua.h +*/ + +#include +#include +#include +#include + +#define lobject_c +#define LUA_CORE + +#include "lua.h" + +#include "lctype.h" +#include "ldebug.h" +#include "ldo.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "lvm.h" + + + +LUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT}; + + +/* +** converts an integer to a "floating point byte", represented as +** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if +** eeeee != 0 and (xxx) otherwise. +*/ +int luaO_int2fb (unsigned int x) { + int e = 0; /* exponent */ + if (x < 8) return x; + while (x >= 0x10) { + x = (x+1) >> 1; + e++; + } + return ((e+1) << 3) | (cast_int(x) - 8); +} + + +/* converts back */ +int luaO_fb2int (int x) { + int e = (x >> 3) & 0x1f; + if (e == 0) return x; + else return ((x & 7) + 8) << (e - 1); +} + + +int luaO_ceillog2 (unsigned int x) { + static const lu_byte log_2[256] = { + 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 + }; + int l = 0; + x--; + while (x >= 256) { l += 8; x >>= 8; } + return l + log_2[x]; +} + + +lua_Number luaO_arith (lua_State *L, int op, lua_Number v1, lua_Number v2) { + switch (op) { + case LUA_OPADD: return luai_numadd(NULL, v1, v2); + case LUA_OPSUB: return luai_numsub(NULL, v1, v2); + case LUA_OPMUL: return luai_nummul(NULL, v1, v2); + case LUA_OPDIV: return luai_numdiv(NULL, v1, v2); + case LUA_OPMOD: return luai_nummod(NULL, v1, v2); + case LUA_OPPOW: return luai_numpow(NULL, v1, v2); + case LUA_OPIDIV: return luai_numidiv(NULL, v1, v2); + case LUA_OPBAND: return luai_numband(NULL, v1, v2); + case LUA_OPBOR: return luai_numbor(NULL, v1, v2); + case LUA_OPBXOR: return luai_numbxor(NULL, v1, v2); + case LUA_OPSHL: return luai_numshl(NULL, v1, v2); + case LUA_OPSHR: return luai_numshr(NULL, v1, v2); + case LUA_OPLSHR: return luai_numlshr(NULL, v1, v2); + case LUA_OPROTL: return luai_numrotl(NULL, v1, v2); + case LUA_OPROTR: return luai_numrotr(NULL, v1, v2); + case LUA_OPUNM: return luai_numunm(NULL, v1); + case LUA_OPBNOT: return luai_numbnot(NULL, v1); + case LUA_OPPEEK: return luai_numpeek(L, v1); + case LUA_OPPEEK2: return luai_numpeek2(L, v1); + case LUA_OPPEEK4: return luai_numpeek4(L, v1); + default: lua_assert(0); return 0; + } +} + + +int luaO_hexavalue (int c) { + if (lisdigit(c)) return c - '0'; + else return ltolower(c) - 'a' + 10; +} + + +static int isneg (const char **s) { + if (**s == '-') { (*s)++; return 1; } + else if (**s == '+') (*s)++; + return 0; +} + + +#if false && !defined(lua_strx2number) + +#include + + +static lua_Number readhexa (const char **s, lua_Number r, int *count) { + for (; lisxdigit(cast_uchar(**s)); (*s)++) { /* read integer part */ + r = (r * cast_num(16.0)) + cast_num(luaO_hexavalue(cast_uchar(**s))); + (*count)++; + } + return r; +} + + +/* +** convert an hexadecimal numeric string to a number, following +** C99 specification for 'strtod' +*/ +static lua_Number lua_strx2number (const char *s, char **endptr) { + lua_Number r = 0.0; + int e = 0, i = 0; + int neg = 0; /* 1 if number is negative */ + *endptr = cast(char *, s); /* nothing is valid yet */ + while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ + neg = isneg(&s); /* check signal */ + if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */ + return 0.0; /* invalid format (no '0x') */ + s += 2; /* skip '0x' */ + r = readhexa(&s, r, &i); /* read integer part */ + if (*s == '.') { + s++; /* skip dot */ + r = readhexa(&s, r, &e); /* read fractional part */ + } + if (i == 0 && e == 0) + return 0.0; /* invalid format (no digit) */ + e *= -4; /* each fractional digit divides value by 2^-4 */ + *endptr = cast(char *, s); /* valid up to here */ + if (*s == 'p' || *s == 'P') { /* exponent part? */ + int exp1 = 0; + int neg1; + s++; /* skip 'p' */ + neg1 = isneg(&s); /* signal */ + if (!lisdigit(cast_uchar(*s))) + goto ret; /* must have at least one digit */ + while (lisdigit(cast_uchar(*s))) /* read exponent */ + exp1 = exp1 * 10 + *(s++) - '0'; + if (neg1) exp1 = -exp1; + e += exp1; + } + *endptr = cast(char *, s); /* valid up to here */ + ret: + if (neg) r = -r; + return l_mathop(ldexp)(r, e); +} + +#endif + + +static lua_Number readany (const char **s, lua_Number r, int *count, int base, int max) { + for (; lisxdigit(cast_uchar(**s)); (*s)++, max--) { + if (max > 0) { + int d = luaO_hexavalue(cast_uchar(**s)); + if (d >= base) break; + r = fix32_add(fix32_mul(r, cast_num(base)), cast_num(d)); + (*count)++; + } + } + return r; +} + + +/* +** convert an hexadecimal or binary numeric string to a number +*/ +static lua_Number lua_strany2number (const char *s, char **endptr, int base) { + lua_Number r = FIX32_ZERO, f = FIX32_ZERO; + int e = 0, i = 0; + int neg = 0; /* 1 if number is negative */ + *endptr = cast(char *, s); /* nothing is valid yet */ + while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ + neg = isneg(&s); /* check sign */ + if (*s != '0' || (base == 2 && *(s + 1) != 'b' && *(s + 1) != 'B') + || (base == 16 && *(s + 1) != 'x' && *(s + 1) != 'X')) + return FIX32_ZERO; /* invalid format (no '0b' or '0x') */ + s += 2; /* skip '0x' or '0b' */ + r = readany(&s, r, &i, base, INT_MAX); /* read integer part */ + if (*s == '.') { + s++; /* skip dot */ + f = readany(&s, f, &e, base, base == 2 ? 16 : 4); /* read fractional part */ + } + if (i == 0 && e == 0) + return FIX32_ZERO; /* invalid format (no digit) */ + *endptr = cast(char *, s); /* valid up to here */ + r = fix32_from_bits(fix32_bits(r) | (uint32_t)fix32_bits(f) >> (base == 2 ? e : e * 4)); + return neg ? fix32_neg(r) : r; +} + + +int luaO_str2d (const char *s, size_t len, lua_Number *result) { + char *endptr; + if (strpbrk(s, "nN")) /* reject 'inf' and 'nan' */ + return 0; + else if (strpbrk(s, "xX")) /* hexa? */ + *result = lua_strany2number(s, &endptr, 16); + else if (strpbrk(s, "bB")) /* binary? */ + *result = lua_strany2number(s, &endptr, 2); + else + *result = lua_str2number(s, &endptr); + if (endptr == s) return 0; /* nothing recognized */ + while (lisspace(cast_uchar(*endptr))) endptr++; + return (endptr == s + len); /* OK if no trailing characters */ +} + + + +static void pushstr (lua_State *L, const char *str, size_t l) { + setsvalue2s(L, L->top++, luaS_newlstr(L, str, l)); +} + + +/* this function handles only `%d', `%c', %f, %p, and `%s' formats */ +const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { + int n = 0; + for (;;) { + const char *e = strchr(fmt, '%'); + if (e == NULL) break; + luaD_checkstack(L, 2); /* fmt + item */ + pushstr(L, fmt, e - fmt); + switch (*(e+1)) { + case 's': { + const char *s = va_arg(argp, char *); + if (s == NULL) s = "(null)"; + pushstr(L, s, strlen(s)); + break; + } + case 'c': { + char buff; + buff = cast(char, va_arg(argp, int)); + pushstr(L, &buff, 1); + break; + } + case 'd': { + setnvalue(L->top++, cast_num(va_arg(argp, int))); + break; + } + case 'f': { + setnvalue(L->top++, (lua_Number)va_arg(argp, l_uacNumber)); + break; + } + case 'p': { + char buff[4*sizeof(void *) + 8]; /* should be enough space for a `0x%llx' */ + int l = sprintf(buff, "0x%llx", (long long int)(intptr_t)va_arg(argp, void *)); + pushstr(L, buff, l); + break; + } + case '%': { + pushstr(L, "%", 1); + break; + } + default: { + luaG_runerror(L, + "invalid option " LUA_QL("%%%c") " to " LUA_QL("lua_pushfstring"), + *(e + 1)); + } + } + n += 2; + fmt = e+2; + } + luaD_checkstack(L, 1); + pushstr(L, fmt, strlen(fmt)); + if (n > 0) luaV_concat(L, n + 1); + return svalue(L->top - 1); +} + + +const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) { + const char *msg; + va_list argp; + va_start(argp, fmt); + msg = luaO_pushvfstring(L, fmt, argp); + va_end(argp); + return msg; +} + + +/* number of chars of a literal string without the ending \0 */ +#define LL(x) (sizeof(x)/sizeof(char) - 1) + +#define RETS "..." +#define PRE "[string \"" +#define POS "\"]" + +#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) ) + +void luaO_chunkid (char *out, const char *source, size_t bufflen) { + size_t l = strlen(source); + if (*source == '=') { /* 'literal' source */ + if (l <= bufflen) /* small enough? */ + memcpy(out, source + 1, l * sizeof(char)); + else { /* truncate it */ + addstr(out, source + 1, bufflen - 1); + *out = '\0'; + } + } + else if (*source == '@') { /* file name */ + if (l <= bufflen) /* small enough? */ + memcpy(out, source + 1, l * sizeof(char)); + else { /* add '...' before rest of name */ + addstr(out, RETS, LL(RETS)); + bufflen -= LL(RETS); + memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char)); + } + } + else { /* string; format as [string "source"] */ + const char *nl = strchr(source, '\n'); /* find first new line (if any) */ + addstr(out, PRE, LL(PRE)); /* add prefix */ + bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */ + if (l < bufflen && nl == NULL) { /* small one-line source? */ + addstr(out, source, l); /* keep it */ + } + else { + if (nl != NULL) l = nl - source; /* stop at first newline */ + if (l > bufflen) l = bufflen; + addstr(out, source, l); + addstr(out, RETS, LL(RETS)); + } + memcpy(out, POS, (LL(POS) + 1) * sizeof(char)); + } +} + diff --git a/components/pico8/femto8/src/lua/lobject.h b/components/pico8/femto8/src/lua/lobject.h new file mode 100644 index 00000000..411dbd85 --- /dev/null +++ b/components/pico8/femto8/src/lua/lobject.h @@ -0,0 +1,607 @@ +/* +** $Id: lobject.h,v 2.71.1.1 2013/04/12 18:48:47 roberto Exp roberto $ +** Type definitions for Lua objects +** See Copyright Notice in lua.h +*/ + + +#ifndef lobject_h +#define lobject_h + + +#include + + +#include "llimits.h" +#include "lua.h" + + +/* +** Extra tags for non-values +*/ +#define LUA_TPROTO LUA_NUMTAGS +#define LUA_TUPVAL (LUA_NUMTAGS+1) +#define LUA_TDEADKEY (LUA_NUMTAGS+2) + +/* +** number of all possible tags (including LUA_TNONE but excluding DEADKEY) +*/ +#define LUA_TOTALTAGS (LUA_TUPVAL+2) + + +/* +** tags for Tagged Values have the following use of bits: +** bits 0-3: actual tag (a LUA_T* value) +** bits 4-5: variant bits +** bit 6: whether value is collectable +*/ + +#define VARBITS (3 << 4) + + +/* +** LUA_TFUNCTION variants: +** 0 - Lua function +** 1 - light C function +** 2 - regular C function (closure) +*/ + +/* Variant tags for functions */ +#define LUA_TLCL (LUA_TFUNCTION | (0 << 4)) /* Lua closure */ +#define LUA_TLCF (LUA_TFUNCTION | (1 << 4)) /* light C function */ +#define LUA_TCCL (LUA_TFUNCTION | (2 << 4)) /* C closure */ + + +/* Variant tags for strings */ +#define LUA_TSHRSTR (LUA_TSTRING | (0 << 4)) /* short strings */ +#define LUA_TLNGSTR (LUA_TSTRING | (1 << 4)) /* long strings */ + + +/* Bit mark for collectable types */ +#define BIT_ISCOLLECTABLE (1 << 6) + +/* mark a tag as collectable */ +#define ctb(t) ((t) | BIT_ISCOLLECTABLE) + + +/* +** Union of all collectable objects +*/ +typedef union GCObject GCObject; + + +/* +** Common Header for all collectable objects (in macro form, to be +** included in other objects) +*/ +#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked + + +/* +** Common header in struct form +*/ +typedef struct GCheader { + CommonHeader; +} GCheader; + + + +/* +** Union of all Lua values +*/ +typedef union Value Value; + + +#define numfield lua_Number n; /* numbers */ + + + +/* +** Tagged Values. This is the basic representation of values in Lua, +** an actual value plus a tag with its type. +*/ + +#define TValuefields Value value_; int tt_ + +typedef struct lua_TValue TValue; + + +/* macro defining a nil value */ +#define NILCONSTANT {NULL}, LUA_TNIL + + +#define val_(o) ((o)->value_) +#define num_(o) (val_(o).n) + + +/* raw type tag of a TValue */ +#define rttype(o) ((o)->tt_) + +/* tag with no variants (bits 0-3) */ +#define novariant(x) ((x) & 0x0F) + +/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */ +#define ttype(o) (rttype(o) & 0x3F) + +/* type tag of a TValue with no variants (bits 0-3) */ +#define ttypenv(o) (novariant(rttype(o))) + + +/* Macros to test type */ +#define checktag(o,t) (rttype(o) == (t)) +#define checktype(o,t) (ttypenv(o) == (t)) +#define ttisnumber(o) checktag((o), LUA_TNUMBER) +#define ttisnil(o) checktag((o), LUA_TNIL) +#define ttisboolean(o) checktag((o), LUA_TBOOLEAN) +#define ttislightuserdata(o) checktag((o), LUA_TLIGHTUSERDATA) +#define ttisstring(o) checktype((o), LUA_TSTRING) +#define ttisshrstring(o) checktag((o), ctb(LUA_TSHRSTR)) +#define ttislngstring(o) checktag((o), ctb(LUA_TLNGSTR)) +#define ttistable(o) checktag((o), ctb(LUA_TTABLE)) +#define ttisfunction(o) checktype(o, LUA_TFUNCTION) +#define ttisclosure(o) ((rttype(o) & 0x1F) == LUA_TFUNCTION) +#define ttisCclosure(o) checktag((o), ctb(LUA_TCCL)) +#define ttisLclosure(o) checktag((o), ctb(LUA_TLCL)) +#define ttislcf(o) checktag((o), LUA_TLCF) +#define ttisuserdata(o) checktag((o), ctb(LUA_TUSERDATA)) +#define ttisthread(o) checktag((o), ctb(LUA_TTHREAD)) +#define ttisdeadkey(o) checktag((o), LUA_TDEADKEY) + +#define ttisequal(o1,o2) (rttype(o1) == rttype(o2)) + +/* Macros to access values */ +#define nvalue(o) check_exp(ttisnumber(o), num_(o)) +#define gcvalue(o) check_exp(iscollectable(o), val_(o).gc) +#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p) +#define rawtsvalue(o) check_exp(ttisstring(o), &val_(o).gc->ts) +#define tsvalue(o) (&rawtsvalue(o)->tsv) +#define rawuvalue(o) check_exp(ttisuserdata(o), &val_(o).gc->u) +#define uvalue(o) (&rawuvalue(o)->uv) +#define clvalue(o) check_exp(ttisclosure(o), &val_(o).gc->cl) +#define clLvalue(o) check_exp(ttisLclosure(o), &val_(o).gc->cl.l) +#define clCvalue(o) check_exp(ttisCclosure(o), &val_(o).gc->cl.c) +#define fvalue(o) check_exp(ttislcf(o), val_(o).f) +#define hvalue(o) check_exp(ttistable(o), &val_(o).gc->h) +#define bvalue(o) check_exp(ttisboolean(o), val_(o).b) +#define thvalue(o) check_exp(ttisthread(o), &val_(o).gc->th) +/* a dead value may get the 'gc' field, but cannot access its contents */ +#define deadvalue(o) check_exp(ttisdeadkey(o), cast(void *, val_(o).gc)) + +#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) + + +#define iscollectable(o) (rttype(o) & BIT_ISCOLLECTABLE) + + +/* Macros for internal tests */ +#define righttt(obj) (ttype(obj) == gcvalue(obj)->gch.tt) + +#define checkliveness(g,obj) \ + lua_longassert(!iscollectable(obj) || \ + (righttt(obj) && !isdead(g,gcvalue(obj)))) + + +/* Macros to set values */ +#define settt_(o,t) ((o)->tt_=(t)) + +#define setnvalue(obj,x) \ + { TValue *io=(obj); num_(io)=(x); settt_(io, LUA_TNUMBER); } + +#define setnilvalue(obj) settt_(obj, LUA_TNIL) + +#define setfvalue(obj,x) \ + { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_TLCF); } + +#define setpvalue(obj,x) \ + { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_TLIGHTUSERDATA); } + +#define setbvalue(obj,x) \ + { TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); } + +#define setgcovalue(L,obj,x) \ + { TValue *io=(obj); GCObject *i_g=(x); \ + val_(io).gc=i_g; settt_(io, ctb(gch(i_g)->tt)); } + +#define setsvalue(L,obj,x) \ + { TValue *io=(obj); \ + TString *x_ = (x); \ + val_(io).gc=cast(GCObject *, x_); settt_(io, ctb(x_->tsv.tt)); \ + checkliveness(G(L),io); } + +#define setuvalue(L,obj,x) \ + { TValue *io=(obj); \ + val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TUSERDATA)); \ + checkliveness(G(L),io); } + +#define setthvalue(L,obj,x) \ + { TValue *io=(obj); \ + val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTHREAD)); \ + checkliveness(G(L),io); } + +#define setclLvalue(L,obj,x) \ + { TValue *io=(obj); \ + val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TLCL)); \ + checkliveness(G(L),io); } + +#define setclCvalue(L,obj,x) \ + { TValue *io=(obj); \ + val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TCCL)); \ + checkliveness(G(L),io); } + +#define sethvalue(L,obj,x) \ + { TValue *io=(obj); \ + val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTABLE)); \ + checkliveness(G(L),io); } + +#define setdeadvalue(obj) settt_(obj, LUA_TDEADKEY) + + + +#define setobj(L,obj1,obj2) \ + { const TValue *io2=(obj2); TValue *io1=(obj1); \ + io1->value_ = io2->value_; io1->tt_ = io2->tt_; \ + checkliveness(G(L),io1); } + + +/* +** different types of assignments, according to destination +*/ + +/* from stack to (same) stack */ +#define setobjs2s setobj +/* to stack (not from same stack) */ +#define setobj2s setobj +#define setsvalue2s setsvalue +#define sethvalue2s sethvalue +#define setptvalue2s setptvalue +/* from table to same table */ +#define setobjt2t setobj +/* to table */ +#define setobj2t setobj +/* to new object */ +#define setobj2n setobj +#define setsvalue2n setsvalue + + +/* check whether a number is valid (useful only for NaN trick) */ +#define luai_checknum(L,o,c) { /* empty */ } + + +/* +** {====================================================== +** NaN Trick +** ======================================================= +*/ +#if defined(LUA_NANTRICK) + +/* +** numbers are represented in the 'd_' field. All other values have the +** value (NNMARK | tag) in 'tt__'. A number with such pattern would be +** a "signaled NaN", which is never generated by regular operations by +** the CPU (nor by 'strtod') +*/ + +/* allows for external implementation for part of the trick */ +#if !defined(NNMARK) /* { */ + + +#if !defined(LUA_IEEEENDIAN) +#error option 'LUA_NANTRICK' needs 'LUA_IEEEENDIAN' +#endif + + +#define NNMARK 0x7FF7A500 +#define NNMASK 0x7FFFFF00 + +#undef TValuefields +#undef NILCONSTANT + +#if (LUA_IEEEENDIAN == 0) /* { */ + +/* little endian */ +#define TValuefields \ + union { struct { Value v__; int tt__; } i; double d__; } u +#define NILCONSTANT {{{NULL}, tag2tt(LUA_TNIL)}} +/* field-access macros */ +#define v_(o) ((o)->u.i.v__) +#define d_(o) ((o)->u.d__) +#define tt_(o) ((o)->u.i.tt__) + +#else /* }{ */ + +/* big endian */ +#define TValuefields \ + union { struct { int tt__; Value v__; } i; double d__; } u +#define NILCONSTANT {{tag2tt(LUA_TNIL), {NULL}}} +/* field-access macros */ +#define v_(o) ((o)->u.i.v__) +#define d_(o) ((o)->u.d__) +#define tt_(o) ((o)->u.i.tt__) + +#endif /* } */ + +#endif /* } */ + + +/* correspondence with standard representation */ +#undef val_ +#define val_(o) v_(o) +#undef num_ +#define num_(o) d_(o) + + +#undef numfield +#define numfield /* no such field; numbers are the entire struct */ + +/* basic check to distinguish numbers from non-numbers */ +#undef ttisnumber +#define ttisnumber(o) ((tt_(o) & NNMASK) != NNMARK) + +#define tag2tt(t) (NNMARK | (t)) + +#undef rttype +#define rttype(o) (ttisnumber(o) ? LUA_TNUMBER : tt_(o) & 0xff) + +#undef settt_ +#define settt_(o,t) (tt_(o) = tag2tt(t)) + +#undef setnvalue +#define setnvalue(obj,x) \ + { TValue *io_=(obj); num_(io_)=(x); lua_assert(ttisnumber(io_)); } + +#undef setobj +#define setobj(L,obj1,obj2) \ + { const TValue *o2_=(obj2); TValue *o1_=(obj1); \ + o1_->u = o2_->u; \ + checkliveness(G(L),o1_); } + + +/* +** these redefinitions are not mandatory, but these forms are more efficient +*/ + +#undef checktag +#undef checktype +#define checktag(o,t) (tt_(o) == tag2tt(t)) +#define checktype(o,t) (ctb(tt_(o) | VARBITS) == ctb(tag2tt(t) | VARBITS)) + +#undef ttisequal +#define ttisequal(o1,o2) \ + (ttisnumber(o1) ? ttisnumber(o2) : (tt_(o1) == tt_(o2))) + + +#undef luai_checknum +#define luai_checknum(L,o,c) { if (!ttisnumber(o)) c; } + +#endif +/* }====================================================== */ + + + +/* +** {====================================================== +** types and prototypes +** ======================================================= +*/ + + +union Value { + GCObject *gc; /* collectable objects */ + void *p; /* light userdata */ + int b; /* booleans */ + lua_CFunction f; /* light C functions */ + numfield /* numbers */ +}; + + +struct lua_TValue { + TValuefields; +}; + + +typedef TValue *StkId; /* index to stack elements */ + + + + +/* +** Header for string value; string bytes follow the end of this structure +*/ +typedef union TString { + L_Umaxalign dummy; /* ensures maximum alignment for strings */ + struct { + CommonHeader; + lu_byte extra; /* reserved words for short strings; "has hash" for longs */ + unsigned int hash; + size_t len; /* number of characters in string */ + } tsv; +} TString; + + +/* get the actual string (array of bytes) from a TString */ +#define getstr(ts) cast(const char *, (ts) + 1) + +/* get the actual string (array of bytes) from a Lua value */ +#define svalue(o) getstr(rawtsvalue(o)) + + +/* +** Header for userdata; memory area follows the end of this structure +*/ +typedef union Udata { + L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ + struct { + CommonHeader; + struct Table *metatable; + struct Table *env; + size_t len; /* number of bytes */ + } uv; +} Udata; + + + +/* +** Description of an upvalue for function prototypes +*/ +typedef struct Upvaldesc { + TString *name; /* upvalue name (for debug information) */ + lu_byte instack; /* whether it is in stack */ + lu_byte idx; /* index of upvalue (in stack or in outer function's list) */ +} Upvaldesc; + + +/* +** Description of a local variable for function prototypes +** (used for debug information) +*/ +typedef struct LocVar { + TString *varname; + int startpc; /* first point where variable is active */ + int endpc; /* first point where variable is dead */ +} LocVar; + + +/* +** Function Prototypes +*/ +typedef struct Proto { + CommonHeader; + TValue *k; /* constants used by the function */ + Instruction *code; + struct Proto **p; /* functions defined inside the function */ + int *lineinfo; /* map from opcodes to source lines (debug information) */ + LocVar *locvars; /* information about local variables (debug information) */ + Upvaldesc *upvalues; /* upvalue information */ + union Closure *cache; /* last created closure with this prototype */ + TString *source; /* used for debug information */ + int sizeupvalues; /* size of 'upvalues' */ + int sizek; /* size of `k' */ + int sizecode; + int sizelineinfo; + int sizep; /* size of `p' */ + int sizelocvars; + int linedefined; + int lastlinedefined; + GCObject *gclist; + lu_byte numparams; /* number of fixed parameters */ + lu_byte is_vararg; + lu_byte maxstacksize; /* maximum stack used by this function */ +} Proto; + + + +/* +** Lua Upvalues +*/ +typedef struct UpVal { + CommonHeader; + TValue *v; /* points to stack or to its own value */ + union { + TValue value; /* the value (when closed) */ + struct { /* double linked list (when open) */ + struct UpVal *prev; + struct UpVal *next; + } l; + } u; +} UpVal; + + +/* +** Closures +*/ + +#define ClosureHeader \ + CommonHeader; lu_byte nupvalues; GCObject *gclist + +typedef struct CClosure { + ClosureHeader; + lua_CFunction f; + TValue upvalue[1]; /* list of upvalues */ +} CClosure; + + +typedef struct LClosure { + ClosureHeader; + struct Proto *p; + UpVal *upvals[1]; /* list of upvalues */ +} LClosure; + + +typedef union Closure { + CClosure c; + LClosure l; +} Closure; + + +#define isLfunction(o) ttisLclosure(o) + +#define getproto(o) (clLvalue(o)->p) + + +/* +** Tables +*/ + +typedef union TKey { + struct { + TValuefields; + struct Node *next; /* for chaining */ + } nk; + TValue tvk; +} TKey; + + +typedef struct Node { + TValue i_val; + TKey i_key; +} Node; + + +typedef struct Table { + CommonHeader; + lu_byte flags; /* 1<

lsizenode)) + + +/* +** (address of) a fixed nil value +*/ +#define luaO_nilobject (&luaO_nilobject_) + + +LUAI_DDEC const TValue luaO_nilobject_; + + +LUAI_FUNC int luaO_int2fb (unsigned int x); +LUAI_FUNC int luaO_fb2int (int x); +LUAI_FUNC int luaO_ceillog2 (unsigned int x); +LUAI_FUNC lua_Number luaO_arith (lua_State *L, int op, lua_Number v1, lua_Number v2); +LUAI_FUNC int luaO_str2d (const char *s, size_t len, lua_Number *result); +LUAI_FUNC int luaO_hexavalue (int c); +LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, + va_list argp); +LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); +LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len); + + +#endif + diff --git a/components/pico8/femto8/src/lua/lopcodes.c b/components/pico8/femto8/src/lua/lopcodes.c new file mode 100644 index 00000000..6b1f6a2d --- /dev/null +++ b/components/pico8/femto8/src/lua/lopcodes.c @@ -0,0 +1,133 @@ +/* +** $Id: lopcodes.c,v 1.49 2012/05/14 13:34:18 roberto Exp $ +** Opcodes for Lua virtual machine +** See Copyright Notice in lua.h +*/ + + +#define lopcodes_c +#define LUA_CORE + + +#include "lopcodes.h" + + +/* ORDER OP */ + +LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = { + "MOVE", + "LOADK", + "LOADKX", + "LOADBOOL", + "LOADNIL", + "GETUPVAL", + "GETTABUP", + "GETTABLE", + "SETTABUP", + "SETUPVAL", + "SETTABLE", + "NEWTABLE", + "SELF", + "ADD", + "SUB", + "MUL", + "DIV", + "MOD", + "POW", + "IDIV", + "BAND", + "BOR", + "BXOR", + "SHL", + "SHR", + "LSHR", + "ROTL", + "ROTR", + "UNM", + "BNOT", + "NOT", + "PEEK", + "PEEK2", + "PEEK4", + "LEN", + "CONCAT", + "JMP", + "EQ", + "LT", + "LE", + "TEST", + "TESTSET", + "CALL", + "TAILCALL", + "RETURN", + "FORLOOP", + "FORPREP", + "TFORCALL", + "TFORLOOP", + "SETLIST", + "CLOSURE", + "VARARG", + "EXTRAARG", + NULL +}; + + +#define opmode(t,a,b,c,m) (((t)<<7) | ((a)<<6) | ((b)<<4) | ((c)<<2) | (m)) + +LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = { +/* T A B C mode opcode */ + opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */ + ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */ + ,opmode(0, 1, OpArgN, OpArgN, iABx) /* OP_LOADKX */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */ + ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_LOADNIL */ + ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */ + ,opmode(0, 1, OpArgU, OpArgK, iABC) /* OP_GETTABUP */ + ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */ + ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABUP */ + ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_SETUPVAL */ + ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABLE */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_NEWTABLE */ + ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_SELF */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ADD */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SUB */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MUL */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_DIV */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MOD */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_POW */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_IDIV */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BAND */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BOR */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BXOR */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHL */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHR */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_LSHR */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ROTL */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ROTR */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_UNM */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_BNOT */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_NOT */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_PEEK */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_PEEK2 */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_PEEK4 */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LEN */ + ,opmode(0, 1, OpArgR, OpArgR, iABC) /* OP_CONCAT */ + ,opmode(0, 0, OpArgR, OpArgN, iAsBx) /* OP_JMP */ + ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */ + ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */ + ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */ + ,opmode(1, 0, OpArgN, OpArgU, iABC) /* OP_TEST */ + ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */ + ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_RETURN */ + ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORLOOP */ + ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORPREP */ + ,opmode(0, 0, OpArgN, OpArgU, iABC) /* OP_TFORCALL */ + ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_TFORLOOP */ + ,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */ + ,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */ + ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */ + ,opmode(0, 0, OpArgU, OpArgU, iAx) /* OP_EXTRAARG */ +}; + diff --git a/components/pico8/femto8/src/lua/lopcodes.h b/components/pico8/femto8/src/lua/lopcodes.h new file mode 100644 index 00000000..ca828ec4 --- /dev/null +++ b/components/pico8/femto8/src/lua/lopcodes.h @@ -0,0 +1,302 @@ +/* +** $Id: lopcodes.h,v 1.142.1.1 2013/04/12 18:48:47 roberto Exp roberto $ +** Opcodes for Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#ifndef lopcodes_h +#define lopcodes_h + +#include "llimits.h" + + +/*=========================================================================== + We assume that instructions are unsigned numbers. + All instructions have an opcode in the first 6 bits. + Instructions can have the following fields: + `A' : 8 bits + `B' : 9 bits + `C' : 9 bits + 'Ax' : 26 bits ('A', 'B', and 'C' together) + `Bx' : 18 bits (`B' and `C' together) + `sBx' : signed Bx + + A signed argument is represented in excess K; that is, the number + value is the unsigned value minus K. K is exactly the maximum value + for that argument (so that -max is represented by 0, and +max is + represented by 2*max), which is half the maximum for the corresponding + unsigned argument. +===========================================================================*/ + + +enum OpMode {iABC, iABx, iAsBx, iAx}; /* basic instruction format */ + + +/* +** size and position of opcode arguments. +*/ +#define SIZE_C 9 +#define SIZE_B 9 +#define SIZE_Bx (SIZE_C + SIZE_B) +#define SIZE_A 8 +#define SIZE_Ax (SIZE_C + SIZE_B + SIZE_A) + +#define SIZE_OP 6 + +#define POS_OP 0 +#define POS_A (POS_OP + SIZE_OP) +#define POS_C (POS_A + SIZE_A) +#define POS_B (POS_C + SIZE_C) +#define POS_Bx POS_C +#define POS_Ax POS_A + + +/* +** limits for opcode arguments. +** we use (signed) int to manipulate most arguments, +** so they must fit in LUAI_BITSINT-1 bits (-1 for sign) +*/ +#if SIZE_Bx < LUAI_BITSINT-1 +#define MAXARG_Bx ((1<>1) /* `sBx' is signed */ +#else +#define MAXARG_Bx MAX_INT +#define MAXARG_sBx MAX_INT +#endif + +#if SIZE_Ax < LUAI_BITSINT-1 +#define MAXARG_Ax ((1<>POS_OP) & MASK1(SIZE_OP,0))) +#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \ + ((cast(Instruction, o)<>pos) & MASK1(size,0))) +#define setarg(i,v,pos,size) ((i) = (((i)&MASK0(size,pos)) | \ + ((cast(Instruction, v)<> RK(C) */ +OP_LSHR,/* A B C R(A) := RK(B) >>> RK(C) */ +OP_ROTL,/* A B C R(A) := RK(B) <<> RK(C) */ +OP_ROTR,/* A B C R(A) := RK(B) >>< RK(C) */ + +OP_UNM,/* A B R(A) := -R(B) */ +OP_BNOT,/* A B R(A) := ~R(B) */ +OP_NOT,/* A B R(A) := not R(B) */ +OP_PEEK,/* A B R(A) := @ R(B) */ +OP_PEEK2,/* A B R(A) := % R(B) */ +OP_PEEK4,/* A B R(A) := $ R(B) */ +OP_LEN,/* A B R(A) := length of R(B) */ + +OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */ + +OP_JMP,/* A sBx pc+=sBx; if (A) close all upvalues >= R(A - 1) */ +OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */ +OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ +OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ + +OP_TEST,/* A C if not (R(A) <=> C) then pc++ */ +OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ + +OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */ +OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */ +OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */ + +OP_FORLOOP,/* A sBx R(A)+=R(A+2); + if R(A) > 4) & 3)) +#define getCMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3)) +#define testAMode(m) (luaP_opmodes[m] & (1 << 6)) +#define testTMode(m) (luaP_opmodes[m] & (1 << 7)) + + +LUAI_DDEC const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names */ + + +/* number of list items to accumulate before a SETLIST instruction */ +#define LFIELDS_PER_FLUSH 50 + + +#endif diff --git a/components/pico8/femto8/src/lua/lparser.c b/components/pico8/femto8/src/lua/lparser.c new file mode 100644 index 00000000..1c6a81f4 --- /dev/null +++ b/components/pico8/femto8/src/lua/lparser.c @@ -0,0 +1,1830 @@ +/* +** $Id: lparser.c,v 2.130 2013/02/06 13:37:39 roberto Exp $ +** Lua Parser +** See Copyright Notice in lua.h +*/ + + +#include + +#define lparser_c +#define LUA_CORE + +#include "lua.h" + +#include "lcode.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "llex.h" +#include "lmem.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" + + + +/* maximum number of local variables per function (must be smaller + than 250, due to the bytecode format) */ +#define MAXVARS 200 + + +#define hasmultret(k) ((k) == VCALL || (k) == VVARARG) + + + +/* +** nodes for block list (list of active blocks) +*/ +typedef struct BlockCnt { + struct BlockCnt *previous; /* chain */ + short firstlabel; /* index of first label in this block */ + short firstgoto; /* index of first pending goto in this block */ + lu_byte nactvar; /* # active locals outside the block */ + lu_byte upval; /* true if some variable in the block is an upvalue */ + lu_byte isloop; /* true if `block' is a loop */ +} BlockCnt; + + + +/* +** prototypes for recursive non-terminal functions +*/ +static void statement (LexState *ls); +static void expr (LexState *ls, expdesc *v); + + +static void anchor_token (LexState *ls) { + /* last token from outer function must be EOS */ + lua_assert(ls->fs != NULL || ls->t.token == TK_EOS); + if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) { + TString *ts = ls->t.seminfo.ts; + luaX_newstring(ls, getstr(ts), ts->tsv.len); + } +} + + +/* semantic error */ +static l_noret semerror (LexState *ls, const char *msg) { + ls->t.token = 0; /* remove 'near to' from final message */ + luaX_syntaxerror(ls, msg); +} + + +static l_noret error_expected (LexState *ls, int token) { + luaX_syntaxerror(ls, + luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token))); +} + + +static l_noret errorlimit (FuncState *fs, int limit, const char *what) { + lua_State *L = fs->ls->L; + const char *msg; + int line = fs->f->linedefined; + const char *where = (line == 0) + ? "main function" + : luaO_pushfstring(L, "function at line %d", line); + msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s", + what, limit, where); + luaX_syntaxerror(fs->ls, msg); +} + + +static void checklimit (FuncState *fs, int v, int l, const char *what) { + if (v > l) errorlimit(fs, l, what); +} + + +static int testnext (LexState *ls, int c) { + if (ls->t.token == c) { + luaX_next(ls); + return 1; + } + else return 0; +} + + +static void check (LexState *ls, int c) { + if (ls->t.token != c) + error_expected(ls, c); +} + + +static void checknext (LexState *ls, int c) { + check(ls, c); + luaX_next(ls); +} + + +#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); } + + + +static void check_match (LexState *ls, int what, int who, int where) { + if (!testnext(ls, what)) { + if (where == ls->linenumber) + error_expected(ls, what); + else { + luaX_syntaxerror(ls, luaO_pushfstring(ls->L, + "%s expected (to close %s at line %d)", + luaX_token2str(ls, what), luaX_token2str(ls, who), where)); + } + } +} + + +static TString *str_checkname (LexState *ls) { + TString *ts; + check(ls, TK_NAME); + ts = ls->t.seminfo.ts; + luaX_next(ls); + return ts; +} + + +static void init_exp (expdesc *e, expkind k, int i) { + e->f = e->t = NO_JUMP; + e->k = k; + e->u.info = i; +} + + +static void codestring (LexState *ls, expdesc *e, TString *s) { + init_exp(e, VK, luaK_stringK(ls->fs, s)); +} + + +static void checkname (LexState *ls, expdesc *e) { + codestring(ls, e, str_checkname(ls)); +} + + +static int registerlocalvar (LexState *ls, TString *varname) { + FuncState *fs = ls->fs; + Proto *f = fs->f; + int oldsize = f->sizelocvars; + luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars, + LocVar, SHRT_MAX, "local variables"); + while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL; + f->locvars[fs->nlocvars].varname = varname; + luaC_objbarrier(ls->L, f, varname); + return fs->nlocvars++; +} + + +static void new_localvar (LexState *ls, TString *name) { + FuncState *fs = ls->fs; + Dyndata *dyd = ls->dyd; + int reg = registerlocalvar(ls, name); + checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal, + MAXVARS, "local variables"); + luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1, + dyd->actvar.size, Vardesc, MAX_INT, "local variables"); + dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg); +} + + +static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) { + new_localvar(ls, luaX_newstring(ls, name, sz)); +} + +#define new_localvarliteral(ls,v) \ + new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1) + + +static LocVar *getlocvar (FuncState *fs, int i) { + int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx; + lua_assert(idx < fs->nlocvars); + return &fs->f->locvars[idx]; +} + + +static void adjustlocalvars (LexState *ls, int nvars) { + FuncState *fs = ls->fs; + fs->nactvar = cast_byte(fs->nactvar + nvars); + for (; nvars; nvars--) { + getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc; + } +} + + +static void removevars (FuncState *fs, int tolevel) { + fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel); + while (fs->nactvar > tolevel) + getlocvar(fs, --fs->nactvar)->endpc = fs->pc; +} + + +static int searchupvalue (FuncState *fs, TString *name) { + int i; + Upvaldesc *up = fs->f->upvalues; + for (i = 0; i < fs->nups; i++) { + if (luaS_eqstr(up[i].name, name)) return i; + } + return -1; /* not found */ +} + + +static int newupvalue (FuncState *fs, TString *name, expdesc *v) { + Proto *f = fs->f; + int oldsize = f->sizeupvalues; + checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues"); + luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues, + Upvaldesc, MAXUPVAL, "upvalues"); + while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL; + f->upvalues[fs->nups].instack = (v->k == VLOCAL); + f->upvalues[fs->nups].idx = cast_byte(v->u.info); + f->upvalues[fs->nups].name = name; + luaC_objbarrier(fs->ls->L, f, name); + return fs->nups++; +} + + +static int searchvar (FuncState *fs, TString *n) { + int i; + for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) { + if (luaS_eqstr(n, getlocvar(fs, i)->varname)) + return i; + } + return -1; /* not found */ +} + + +/* + Mark block where variable at given level was defined + (to emit close instructions later). +*/ +static void markupval (FuncState *fs, int level) { + BlockCnt *bl = fs->bl; + while (bl->nactvar > level) bl = bl->previous; + bl->upval = 1; +} + + +/* + Find variable with given name 'n'. If it is an upvalue, add this + upvalue into all intermediate functions. +*/ +static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { + if (fs == NULL) /* no more levels? */ + return VVOID; /* default is global */ + else { + int v = searchvar(fs, n); /* look up locals at current level */ + if (v >= 0) { /* found? */ + init_exp(var, VLOCAL, v); /* variable is local */ + if (!base) + markupval(fs, v); /* local will be used as an upval */ + return VLOCAL; + } + else { /* not found as local at current level; try upvalues */ + int idx = searchupvalue(fs, n); /* try existing upvalues */ + if (idx < 0) { /* not found? */ + if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */ + return VVOID; /* not found; is a global */ + /* else was LOCAL or UPVAL */ + idx = newupvalue(fs, n, var); /* will be a new upvalue */ + } + init_exp(var, VUPVAL, idx); + return VUPVAL; + } + } +} + + +/* +** PICO-8 compat: certain math/bitwise functions are compiled as custom VM +** opcodes in PICO-8 and therefore bypass any local _ENV parameter entirely. +** Functions NOT in this list (sqrt, sgn, abs, add, del, all, printh, ...) go +** through _ENV as normal β€” carts that use them inside _ENV-param functions +** rely on the passed table having __index set to the real global env. +*/ +static int is_pico8_builtin (TString *name) { + static const char * const builtins[] = { + "flr","ceil","sin","cos","max","min","mid","atan2", + "band","bor","bxor","bnot","shl","shr","lshr","rotl","rotr", + "tostr","tonum","chr","ord", + NULL + }; + const char *s = getstr(name); + int i; + for (i = 0; builtins[i]; i++) + if (strcmp(s, builtins[i]) == 0) return 1; + return 0; +} + +static void singlevar (LexState *ls, expdesc *var) { + TString *varname = str_checkname(ls); + FuncState *fs = ls->fs; + if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */ + expdesc key; + /* PICO-8 compat: if _ENV is a function parameter and the variable is a + known pico-8 builtin, resolve it via the outer real _ENV (as an upvalue) + instead of the local _ENV param, matching PICO-8's opcode behavior. */ + { + int env_reg = searchvar(fs, ls->envn); + if (env_reg >= 0 && env_reg < (int)fs->f->numparams + && fs->prev != NULL && is_pico8_builtin(varname)) { + TString *outerenvname = luaS_newliteral(ls->L, "__p8oe"); + int outer_upval = searchupvalue(fs, outerenvname); + if (outer_upval < 0) { + expdesc outerenv; + if (singlevaraux(fs->prev, ls->envn, &outerenv, 0) != VVOID) + outer_upval = newupvalue(fs, outerenvname, &outerenv); + } + if (outer_upval >= 0) { + init_exp(var, VUPVAL, outer_upval); + codestring(ls, &key, varname); + luaK_indexed(fs, var, &key); + return; + } + } + } + singlevaraux(fs, ls->envn, var, 1); /* get environment variable */ + lua_assert(var->k == VLOCAL || var->k == VUPVAL); + codestring(ls, &key, varname); /* key is variable name */ + luaK_indexed(fs, var, &key); /* env[varname] */ + } +} + + +static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { + FuncState *fs = ls->fs; + int extra = nvars - nexps; + if (hasmultret(e->k)) { + extra++; /* includes call itself */ + if (extra < 0) extra = 0; + luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ + if (extra > 1) luaK_reserveregs(fs, extra-1); + } + else { + if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */ + if (extra > 0) { + int reg = fs->freereg; + luaK_reserveregs(fs, extra); + luaK_nil(fs, reg, extra); + } + } +} + + +static void enterlevel (LexState *ls) { + lua_State *L = ls->L; + ++L->nCcalls; + checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels"); +} + + +#define leavelevel(ls) ((ls)->L->nCcalls--) + + +static void closegoto (LexState *ls, int g, Labeldesc *label) { + int i; + FuncState *fs = ls->fs; + Labellist *gl = &ls->dyd->gt; + Labeldesc *gt = &gl->arr[g]; + lua_assert(luaS_eqstr(gt->name, label->name)); + if (gt->nactvar < label->nactvar) { + TString *vname = getlocvar(fs, gt->nactvar)->varname; + const char *msg = luaO_pushfstring(ls->L, + " at line %d jumps into the scope of local " LUA_QS, + getstr(gt->name), gt->line, getstr(vname)); + semerror(ls, msg); + } + luaK_patchlist(fs, gt->pc, label->pc); + /* remove goto from pending list */ + for (i = g; i < gl->n - 1; i++) + gl->arr[i] = gl->arr[i + 1]; + gl->n--; +} + + +/* +** try to close a goto with existing labels; this solves backward jumps +*/ +static int findlabel (LexState *ls, int g) { + int i; + BlockCnt *bl = ls->fs->bl; + Dyndata *dyd = ls->dyd; + Labeldesc *gt = &dyd->gt.arr[g]; + /* check labels in current block for a match */ + for (i = bl->firstlabel; i < dyd->label.n; i++) { + Labeldesc *lb = &dyd->label.arr[i]; + if (luaS_eqstr(lb->name, gt->name)) { /* correct label? */ + if (gt->nactvar > lb->nactvar && + (bl->upval || dyd->label.n > bl->firstlabel)) + luaK_patchclose(ls->fs, gt->pc, lb->nactvar); + closegoto(ls, g, lb); /* close it */ + return 1; + } + } + return 0; /* label not found; cannot close goto */ +} + + +static int newlabelentry (LexState *ls, Labellist *l, TString *name, + int line, int pc) { + int n = l->n; + luaM_growvector(ls->L, l->arr, n, l->size, + Labeldesc, SHRT_MAX, "labels/gotos"); + l->arr[n].name = name; + l->arr[n].line = line; + l->arr[n].nactvar = ls->fs->nactvar; + l->arr[n].pc = pc; + l->n++; + return n; +} + + +/* +** check whether new label 'lb' matches any pending gotos in current +** block; solves forward jumps +*/ +static void findgotos (LexState *ls, Labeldesc *lb) { + Labellist *gl = &ls->dyd->gt; + int i = ls->fs->bl->firstgoto; + while (i < gl->n) { + if (luaS_eqstr(gl->arr[i].name, lb->name)) + closegoto(ls, i, lb); + else + i++; + } +} + + +/* +** "export" pending gotos to outer level, to check them against +** outer labels; if the block being exited has upvalues, and +** the goto exits the scope of any variable (which can be the +** upvalue), close those variables being exited. +*/ +static void movegotosout (FuncState *fs, BlockCnt *bl) { + int i = bl->firstgoto; + Labellist *gl = &fs->ls->dyd->gt; + /* correct pending gotos to current block and try to close it + with visible labels */ + while (i < gl->n) { + Labeldesc *gt = &gl->arr[i]; + if (gt->nactvar > bl->nactvar) { + if (bl->upval) + luaK_patchclose(fs, gt->pc, bl->nactvar); + gt->nactvar = bl->nactvar; + } + if (!findlabel(fs->ls, i)) + i++; /* move to next one */ + } +} + + +static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) { + bl->isloop = isloop; + bl->nactvar = fs->nactvar; + bl->firstlabel = fs->ls->dyd->label.n; + bl->firstgoto = fs->ls->dyd->gt.n; + bl->upval = 0; + bl->previous = fs->bl; + fs->bl = bl; + lua_assert(fs->freereg == fs->nactvar); +} + + +/* +** create a label named "break" to resolve break statements +*/ +static void breaklabel (LexState *ls) { + TString *n = luaS_new(ls->L, "break"); + int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc); + findgotos(ls, &ls->dyd->label.arr[l]); +} + +/* +** generates an error for an undefined 'goto'; choose appropriate +** message when label name is a reserved word (which can only be 'break') +*/ +static l_noret undefgoto (LexState *ls, Labeldesc *gt) { + const char *msg = isreserved(gt->name) + ? "<%s> at line %d not inside a loop" + : "no visible label " LUA_QS " for at line %d"; + msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line); + semerror(ls, msg); +} + + +static void leaveblock (FuncState *fs) { + BlockCnt *bl = fs->bl; + LexState *ls = fs->ls; + if (bl->previous && bl->upval) { + /* create a 'jump to here' to close upvalues */ + int j = luaK_jump(fs); + luaK_patchclose(fs, j, bl->nactvar); + luaK_patchtohere(fs, j); + } + if (bl->isloop) + breaklabel(ls); /* close pending breaks */ + fs->bl = bl->previous; + removevars(fs, bl->nactvar); + lua_assert(bl->nactvar == fs->nactvar); + fs->freereg = fs->nactvar; /* free registers */ + ls->dyd->label.n = bl->firstlabel; /* remove local labels */ + if (bl->previous) /* inner block? */ + movegotosout(fs, bl); /* update pending gotos to outer block */ + else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */ + undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */ +} + + +/* +** adds a new prototype into list of prototypes +*/ +static Proto *addprototype (LexState *ls) { + Proto *clp; + lua_State *L = ls->L; + FuncState *fs = ls->fs; + Proto *f = fs->f; /* prototype of current function */ + if (fs->np >= f->sizep) { + int oldsize = f->sizep; + luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions"); + while (oldsize < f->sizep) f->p[oldsize++] = NULL; + } + f->p[fs->np++] = clp = luaF_newproto(L); + luaC_objbarrier(L, f, clp); + return clp; +} + + +/* +** codes instruction to create new closure in parent function. +** The OP_CLOSURE instruction must use the last available register, +** so that, if it invokes the GC, the GC knows which registers +** are in use at that time. +*/ +static void codeclosure (LexState *ls, expdesc *v) { + FuncState *fs = ls->fs->prev; + init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1)); + luaK_exp2nextreg(fs, v); /* fix it at the last register */ +} + + +static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) { + lua_State *L = ls->L; + Proto *f; + fs->prev = ls->fs; /* linked list of funcstates */ + fs->ls = ls; + ls->fs = fs; + fs->pc = 0; + fs->lasttarget = 0; + fs->jpc = NO_JUMP; + fs->freereg = 0; + fs->nk = 0; + fs->np = 0; + fs->nups = 0; + fs->nlocvars = 0; + fs->nactvar = 0; + fs->firstlocal = ls->dyd->actvar.n; + fs->bl = NULL; + f = fs->f; + f->source = ls->source; + f->maxstacksize = 2; /* registers 0/1 are always valid */ + fs->h = luaH_new(L); + /* anchor table of constants (to avoid being collected) */ + sethvalue2s(L, L->top, fs->h); + incr_top(L); + enterblock(fs, bl, 0); +} + + +static void close_func (LexState *ls) { + lua_State *L = ls->L; + FuncState *fs = ls->fs; + Proto *f = fs->f; + luaK_ret(fs, 0, 0); /* final return */ + leaveblock(fs); + luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction); + f->sizecode = fs->pc; + luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int); + f->sizelineinfo = fs->pc; + luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue); + f->sizek = fs->nk; + luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *); + f->sizep = fs->np; + luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar); + f->sizelocvars = fs->nlocvars; + luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc); + f->sizeupvalues = fs->nups; + lua_assert(fs->bl == NULL); + ls->fs = fs->prev; + /* last token read was anchored in defunct function; must re-anchor it */ + anchor_token(ls); + L->top--; /* pop table of constants */ + luaC_checkGC(L); +} + + + +/*============================================================*/ +/* GRAMMAR RULES */ +/*============================================================*/ + + +/* +** check whether current token is in the follow set of a block. +** 'until' closes syntactical blocks, but do not close scope, +** so it handled in separate. +*/ +static int block_follow (LexState *ls, int withuntil) { + switch (ls->t.token) { + case TK_ELSE: case TK_ELSEIF: + case TK_END: case TK_EOS: + case TK_EOL: /* EOL indicates end of short IF or WHILE */ + return 1; + case TK_UNTIL: return withuntil; + default: return 0; + } +} + + +static void statlist (LexState *ls) { + /* statlist -> { stat [`;'] } */ + while (!block_follow(ls, 1)) { + if (ls->t.token == TK_RETURN) { + statement(ls); + return; /* 'return' must be last statement */ + } + statement(ls); + } +} + + +static void fieldsel (LexState *ls, expdesc *v) { + /* fieldsel -> ['.' | ':'] NAME */ + FuncState *fs = ls->fs; + expdesc key; + luaK_exp2anyregup(fs, v); + luaX_next(ls); /* skip the dot or colon */ + checkname(ls, &key); + luaK_indexed(fs, v, &key); +} + + +static void yindex (LexState *ls, expdesc *v) { + /* index -> '[' expr ']' */ + luaX_next(ls); /* skip the '[' */ + expr(ls, v); + luaK_exp2val(ls->fs, v); + checknext(ls, ']'); +} + + +/* +** {====================================================================== +** Rules for Constructors +** ======================================================================= +*/ + + +struct ConsControl { + expdesc v; /* last list item read */ + expdesc *t; /* table descriptor */ + int nh; /* total number of `record' elements */ + int na; /* total number of array elements */ + int tostore; /* number of array elements pending to be stored */ +}; + + +static void recfield (LexState *ls, struct ConsControl *cc) { + /* recfield -> (NAME | `['exp1`]') = exp1 */ + FuncState *fs = ls->fs; + int reg = ls->fs->freereg; + expdesc key, val; + int rkkey; + if (ls->t.token == TK_NAME) { + checklimit(fs, cc->nh, MAX_INT, "items in a constructor"); + checkname(ls, &key); + } + else /* ls->t.token == '[' */ + yindex(ls, &key); + cc->nh++; + checknext(ls, '='); + rkkey = luaK_exp2RK(fs, &key); + expr(ls, &val); + luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val)); + fs->freereg = reg; /* free registers */ +} + + +static void closelistfield (FuncState *fs, struct ConsControl *cc) { + if (cc->v.k == VVOID) return; /* there is no list item */ + luaK_exp2nextreg(fs, &cc->v); + cc->v.k = VVOID; + if (cc->tostore == LFIELDS_PER_FLUSH) { + luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */ + cc->tostore = 0; /* no more items pending */ + } +} + + +static void lastlistfield (FuncState *fs, struct ConsControl *cc) { + if (cc->tostore == 0) return; + if (hasmultret(cc->v.k)) { + luaK_setmultret(fs, &cc->v); + luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET); + cc->na--; /* do not count last expression (unknown number of elements) */ + } + else { + if (cc->v.k != VVOID) + luaK_exp2nextreg(fs, &cc->v); + luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); + } +} + + +static void listfield (LexState *ls, struct ConsControl *cc) { + /* listfield -> exp */ + expr(ls, &cc->v); + checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor"); + cc->na++; + cc->tostore++; +} + + +static void field (LexState *ls, struct ConsControl *cc) { + /* field -> listfield | recfield */ + switch(ls->t.token) { + case TK_NAME: { /* may be 'listfield' or 'recfield' */ + if (luaX_lookahead(ls) != '=') /* expression? */ + listfield(ls, cc); + else + recfield(ls, cc); + break; + } + case '[': { + recfield(ls, cc); + break; + } + default: { + listfield(ls, cc); + break; + } + } +} + + +static void constructor (LexState *ls, expdesc *t) { + /* constructor -> '{' [ field { sep field } [sep] ] '}' + sep -> ',' | ';' */ + FuncState *fs = ls->fs; + int line = ls->linenumber; + int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0); + struct ConsControl cc; + cc.na = cc.nh = cc.tostore = 0; + cc.t = t; + init_exp(t, VRELOCABLE, pc); + init_exp(&cc.v, VVOID, 0); /* no value (yet) */ + luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */ + checknext(ls, '{'); + do { + lua_assert(cc.v.k == VVOID || cc.tostore > 0); + if (ls->t.token == '}') break; + closelistfield(fs, &cc); + field(ls, &cc); + } while (testnext(ls, ',') || testnext(ls, ';')); + check_match(ls, '}', '{', line); + lastlistfield(fs, &cc); + SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */ + SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */ +} + +/* }====================================================================== */ + + + +static void parlist (LexState *ls) { + /* parlist -> [ param { `,' param } ] */ + FuncState *fs = ls->fs; + Proto *f = fs->f; + int nparams = 0; + f->is_vararg = 0; + if (ls->t.token != ')') { /* is `parlist' not empty? */ + do { + switch (ls->t.token) { + case TK_NAME: { /* param -> NAME */ + new_localvar(ls, str_checkname(ls)); + nparams++; + break; + } + case TK_DOTS: { /* param -> `...' */ + luaX_next(ls); + f->is_vararg = 1; + break; + } + default: luaX_syntaxerror(ls, " or " LUA_QL("...") " expected"); + } + } while (!f->is_vararg && testnext(ls, ',')); + } + adjustlocalvars(ls, nparams); + f->numparams = cast_byte(fs->nactvar); + luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */ +} + + +static void body (LexState *ls, expdesc *e, int ismethod, int line) { + /* body -> `(' parlist `)' block END */ + FuncState new_fs; + BlockCnt bl; + new_fs.f = addprototype(ls); + new_fs.f->linedefined = line; + open_func(ls, &new_fs, &bl); + checknext(ls, '('); + if (ismethod) { + new_localvarliteral(ls, "self"); /* create 'self' parameter */ + adjustlocalvars(ls, 1); + } + parlist(ls); + checknext(ls, ')'); + statlist(ls); + new_fs.f->lastlinedefined = ls->linenumber; + check_match(ls, TK_END, TK_FUNCTION, line); + codeclosure(ls, e); + close_func(ls); +} + + +static int explist (LexState *ls, expdesc *v) { + /* explist -> expr { `,' expr } */ + int n = 1; /* at least one expression */ + expr(ls, v); + while (testnext(ls, ',')) { + luaK_exp2nextreg(ls->fs, v); + expr(ls, v); + n++; + } + return n; +} + + +static void funcargs (LexState *ls, expdesc *f, int line) { + FuncState *fs = ls->fs; + expdesc args; + int base, nparams; + switch (ls->t.token) { + case '(': { /* funcargs -> `(' [ explist ] `)' */ + luaX_next(ls); + if (ls->t.token == ')') /* arg list is empty? */ + args.k = VVOID; + else { + explist(ls, &args); + luaK_setmultret(fs, &args); + } + check_match(ls, ')', '(', line); + break; + } + case '{': { /* funcargs -> constructor */ + constructor(ls, &args); + break; + } + case TK_STRING: { /* funcargs -> STRING */ + codestring(ls, &args, ls->t.seminfo.ts); + luaX_next(ls); /* must use `seminfo' before `next' */ + break; + } + default: { + luaX_syntaxerror(ls, "function arguments expected"); + } + } + lua_assert(f->k == VNONRELOC); + base = f->u.info; /* base register for call */ + if (hasmultret(args.k)) + nparams = LUA_MULTRET; /* open call */ + else { + if (args.k != VVOID) + luaK_exp2nextreg(fs, &args); /* close last argument */ + nparams = fs->freereg - (base+1); + } + init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); + luaK_fixline(fs, line); + fs->freereg = base+1; /* call remove function and arguments and leaves + (unless changed) one result */ +} + + + + +/* +** {====================================================================== +** Expression parsing +** ======================================================================= +*/ + + +static void primaryexp (LexState *ls, expdesc *v) { + /* primaryexp -> NAME | '(' expr ')' */ + switch (ls->t.token) { + case '(': { + int line = ls->linenumber; + luaX_next(ls); + expr(ls, v); + check_match(ls, ')', '(', line); + luaK_dischargevars(ls->fs, v); + return; + } + case TK_NAME: { + singlevar(ls, v); + return; + } + default: { + luaX_syntaxerror(ls, "unexpected symbol"); + } + } +} + + +static void suffixedexp (LexState *ls, expdesc *v) { + /* suffixedexp -> + primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */ + FuncState *fs = ls->fs; + int line = ls->linenumber; + primaryexp(ls, v); + for (;;) { + switch (ls->t.token) { + case '.': { /* fieldsel */ + fieldsel(ls, v); + break; + } + case '[': { /* `[' exp1 `]' */ + expdesc key; + luaK_exp2anyregup(fs, v); + yindex(ls, &key); + luaK_indexed(fs, v, &key); + break; + } + case ':': { /* `:' NAME funcargs */ + expdesc key; + luaX_next(ls); + checkname(ls, &key); + luaK_self(fs, v, &key); + funcargs(ls, v, line); + break; + } + case '(': case TK_STRING: case '{': { /* funcargs */ + luaK_exp2nextreg(fs, v); + funcargs(ls, v, line); + break; + } + default: return; + } + } +} + + +static void simpleexp (LexState *ls, expdesc *v) { + /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... | + constructor | FUNCTION body | suffixedexp */ + switch (ls->t.token) { + case TK_NUMBER: { + init_exp(v, VKNUM, 0); + v->u.nval = ls->t.seminfo.r; + break; + } + case TK_STRING: { + codestring(ls, v, ls->t.seminfo.ts); + break; + } + case TK_NIL: { + init_exp(v, VNIL, 0); + break; + } + case TK_TRUE: { + init_exp(v, VTRUE, 0); + break; + } + case TK_FALSE: { + init_exp(v, VFALSE, 0); + break; + } + case TK_DOTS: { /* vararg */ + FuncState *fs = ls->fs; + check_condition(ls, fs->f->is_vararg, + "cannot use " LUA_QL("...") " outside a vararg function"); + init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0)); + break; + } + case '{': { /* constructor */ + constructor(ls, v); + return; + } + case TK_FUNCTION: { + luaX_next(ls); + body(ls, v, 0, ls->linenumber); + return; + } + default: { + suffixedexp(ls, v); + return; + } + } + luaX_next(ls); +} + + +static UnOpr getunopr (int op) { + switch (op) { + case TK_NOT: return OPR_NOT; + case '-': return OPR_MINUS; + case '~': return OPR_BNOT; + case '@': return OPR_PEEK; + case '%': return OPR_PEEK2; + case '$': return OPR_PEEK4; + case '#': return OPR_LEN; + default: return OPR_NOUNOPR; + } +} + + +static BinOpr getbinopr (int op) { + switch (op) { + case '+': return OPR_ADD; + case '-': return OPR_SUB; + case '*': return OPR_MUL; + case '/': return OPR_DIV; + case '%': return OPR_MOD; + case '^': return OPR_POW; + case '\\': return OPR_IDIV; + case '&': return OPR_BAND; + case '|': return OPR_BOR; + case TK_BXOR: return OPR_BXOR; + case TK_SHL: return OPR_SHL; + case TK_SHR: return OPR_SHR; + case TK_LSHR: return OPR_LSHR; + case TK_ROTL: return OPR_ROTL; + case TK_ROTR: return OPR_ROTR; + case TK_CONCAT: return OPR_CONCAT; + case TK_NE: case TK_NE2: return OPR_NE; + case TK_EQ: return OPR_EQ; + case '<': return OPR_LT; + case TK_LE: return OPR_LE; + case '>': return OPR_GT; + case TK_GE: return OPR_GE; + case TK_AND: return OPR_AND; + case TK_OR: return OPR_OR; + default: return OPR_NOBINOPR; + } +} + + +static const struct { + lu_byte left; /* left priority for each binary operator */ + lu_byte right; /* right priority */ +} priority[] = { /* ORDER OPR */ + {10, 10}, {10, 10}, /* `+' `-' */ + {11, 11}, {11, 11}, {11, 11}, /* `*' `/' `%' */ + {13, 12}, /* ^ (right associative) */ + {11, 11}, /* `\' */ + {6, 6}, {4, 4}, {5, 5}, /* `&' `|' `^^' */ + {7, 7}, {7, 7}, {7, 7}, /* `<<' `>>' `>>>' */ + {7, 7}, {7, 7}, /* `<<>' `>><' */ + {9, 8}, /* .. (right associative) */ + {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */ + {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */ + {2, 2}, {1, 1} /* and, or */ +}; + +#define UNARY_PRIORITY 12 /* priority for unary operators */ + + +/* +** subexpr -> (simpleexp | unop subexpr) { binop subexpr } +** where `binop' is any binary operator with a priority higher than `limit' +*/ +static BinOpr subexpr (LexState *ls, expdesc *v, int limit) { + BinOpr op; + UnOpr uop; + enterlevel(ls); + uop = getunopr(ls->t.token); + if (uop != OPR_NOUNOPR) { + int line = ls->linenumber; + luaX_next(ls); + subexpr(ls, v, UNARY_PRIORITY); + luaK_prefix(ls->fs, uop, v, line); + } + else simpleexp(ls, v); + /* expand while operators have priorities higher than `limit' */ + op = getbinopr(ls->t.token); + while (op != OPR_NOBINOPR && priority[op].left > limit) { + expdesc v2; + BinOpr nextop; + int line = ls->linenumber; + luaX_next(ls); + luaK_infix(ls->fs, op, v); + /* read sub-expression with higher priority */ + nextop = subexpr(ls, &v2, priority[op].right); + luaK_posfix(ls->fs, op, v, &v2, line); + op = nextop; + } + leavelevel(ls); + return op; /* return first untreated operator */ +} + + +static void expr (LexState *ls, expdesc *v) { + subexpr(ls, v, 0); +} + +/* }==================================================================== */ + + + +/* +** {====================================================================== +** Rules for Statements +** ======================================================================= +*/ + + +static void block (LexState *ls) { + /* block -> statlist */ + FuncState *fs = ls->fs; + BlockCnt bl; + enterblock(fs, &bl, 0); + statlist(ls); + leaveblock(fs); +} + + +/* +** structure to chain all variables in the left-hand side of an +** assignment +*/ +struct LHS_assign { + struct LHS_assign *prev; + expdesc v; /* variable (global, local, upvalue, or indexed) */ +}; + + +/* +** check whether, in an assignment to an upvalue/local variable, the +** upvalue/local variable is begin used in a previous assignment to a +** table. If so, save original upvalue/local value in a safe place and +** use this safe copy in the previous assignment. +*/ +static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { + FuncState *fs = ls->fs; + int extra = fs->freereg; /* eventual position to save local variable */ + int conflict = 0; + for (; lh; lh = lh->prev) { /* check all previous assignments */ + if (lh->v.k == VINDEXED) { /* assigning to a table? */ + /* table is the upvalue/local being assigned now? */ + if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) { + conflict = 1; + lh->v.u.ind.vt = VLOCAL; + lh->v.u.ind.t = extra; /* previous assignment will use safe copy */ + } + /* index is the local being assigned? (index cannot be upvalue) */ + if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) { + conflict = 1; + lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */ + } + } + } + if (conflict) { + /* copy upvalue/local value to a temporary (in position 'extra') */ + OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL; + luaK_codeABC(fs, op, extra, v->u.info, 0); + luaK_reserveregs(fs, 1); + } +} + + +static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) { + expdesc e; + check_condition(ls, vkisvar(lh->v.k), "syntax error"); + if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */ + struct LHS_assign nv; + nv.prev = lh; + suffixedexp(ls, &nv.v); + if (nv.v.k != VINDEXED) + check_conflict(ls, lh, &nv.v); + checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS, + "C levels"); + assignment(ls, &nv, nvars+1); + } + else { /* assignment -> `=' explist */ + int nexps; + checknext(ls, '='); + nexps = explist(ls, &e); + if (nexps != nvars) { + adjust_assign(ls, nvars, nexps, &e); + if (nexps > nvars) + ls->fs->freereg -= nexps - nvars; /* remove extra values */ + } + else { + luaK_setoneret(ls->fs, &e); /* close last expression */ + luaK_storevar(ls->fs, &lh->v, &e); + return; /* avoid default */ + } + } + init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */ + luaK_storevar(ls->fs, &lh->v, &e); +} + + +static void compound (LexState *ls, expdesc *v) { + int i, line, extra; + FuncState *fs = ls->fs; + expdesc e1 = *v, e2; + /* compound -> ( `+=' | `-=' | `*=' | `/=' | etc. ) expression */ + BinOpr op = ls->t.token >= TK_ADDE && ls->t.token <= TK_CONCATE ? + (BinOpr)(ls->t.token - TK_ADDE + OPR_ADD) : + OPR_NOBINOPR; + extra = fs->freereg - fs->nactvar; + for (i = 0; i < extra; ++i) + new_localvarliteral(ls, "(for compound)"); + adjustlocalvars(ls, extra); + + luaX_next(ls); + line = ls->linenumber; + + enterlevel(ls); + luaK_infix(fs, op, &e1); + expr(ls, &e2); + luaK_posfix(fs, op, &e1, &e2, line); + leavelevel(ls); + + luaK_exp2nextreg(fs, &e1); + luaK_setoneret(ls->fs, &e1); + luaK_storevar(ls->fs, v, &e1); +} + + +static int cond (LexState *ls) { + /* cond -> exp */ + expdesc v; + expr(ls, &v); /* read condition */ + if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */ + luaK_goiftrue(ls->fs, &v); + return v.f; +} + + +static void gotostat (LexState *ls, int pc) { + int line = ls->linenumber; + TString *label; + int g; + if (testnext(ls, TK_GOTO)) + label = str_checkname(ls); + else { + luaX_next(ls); /* skip break */ + label = luaS_new(ls->L, "break"); + } + g = newlabelentry(ls, &ls->dyd->gt, label, line, pc); + findlabel(ls, g); /* close it if label already defined */ +} + + +/* check for repeated labels on the same block */ +static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) { + int i; + for (i = fs->bl->firstlabel; i < ll->n; i++) { + if (luaS_eqstr(label, ll->arr[i].name)) { + const char *msg = luaO_pushfstring(fs->ls->L, + "label " LUA_QS " already defined on line %d", + getstr(label), ll->arr[i].line); + semerror(fs->ls, msg); + } + } +} + + +/* skip no-op statements */ +static void skipnoopstat (LexState *ls) { + while (ls->t.token == ';' || ls->t.token == TK_DBCOLON) + statement(ls); +} + + +static void labelstat (LexState *ls, TString *label, int line) { + /* label -> '::' NAME '::' */ + FuncState *fs = ls->fs; + Labellist *ll = &ls->dyd->label; + int l; /* index of new label being created */ + checkrepeated(fs, ll, label); /* check for repeated labels */ + checknext(ls, TK_DBCOLON); /* skip double colon */ + /* create new entry for this label */ + l = newlabelentry(ls, ll, label, line, fs->pc); + skipnoopstat(ls); /* skip other no-op statements */ + if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */ + /* assume that locals are already out of scope */ + ll->arr[l].nactvar = fs->bl->nactvar; + } + findgotos(ls, &ll->arr[l]); +} + + +static void whilestat (LexState *ls, int line) { + /* whilestat -> WHILE cond DO block END */ + FuncState *fs = ls->fs; + int whileinit; + int condexit; + BlockCnt bl; + luaX_next(ls); /* skip WHILE */ + luaX_trackbraces(ls); /* track braces for short WHILE */ + whileinit = luaK_getlabel(fs); + condexit = cond(ls); + enterblock(fs, &bl, 1); + int short_while = ls->t.token != TK_DO && ls->t.token != TK_EOS + && ls->braces == 0 && line == ls->linenumber; + if (short_while) { + ls->emiteol = 1; + ls->short_nest++; + } + else + checknext(ls, TK_DO); + block(ls); + luaK_jumpto(fs, whileinit); + if (!short_while) + check_match(ls, TK_END, TK_WHILE, line); + else { + ls->short_nest--; + if (ls->t.token == TK_EOL || ls->t.token == TK_EOS) + luaX_next(ls); /* eat EOL or EOS */ + else if (block_follow(ls, 1)) + ls->emiteol = 0; /* close the short WHILE */ + else + check_match(ls, TK_EOL, TK_WHILE, line); /* we expected EOL */ + } + leaveblock(fs); + luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ +} + + +static void repeatstat (LexState *ls, int line) { + /* repeatstat -> REPEAT block UNTIL cond */ + int condexit; + FuncState *fs = ls->fs; + int repeat_init = luaK_getlabel(fs); + BlockCnt bl1, bl2; + enterblock(fs, &bl1, 1); /* loop block */ + enterblock(fs, &bl2, 0); /* scope block */ + luaX_next(ls); /* skip REPEAT */ + statlist(ls); + check_match(ls, TK_UNTIL, TK_REPEAT, line); + condexit = cond(ls); /* read condition (inside scope block) */ + if (bl2.upval) /* upvalues? */ + luaK_patchclose(fs, condexit, bl2.nactvar); + leaveblock(fs); /* finish scope */ + luaK_patchlist(fs, condexit, repeat_init); /* close the loop */ + leaveblock(fs); /* finish loop */ +} + + +static int exp1 (LexState *ls) { + expdesc e; + int reg; + expr(ls, &e); + luaK_exp2nextreg(ls->fs, &e); + lua_assert(e.k == VNONRELOC); + reg = e.u.info; + return reg; +} + + +static void forbody (LexState *ls, int base, int line, int nvars, int isnum) { + /* forbody -> DO block */ + BlockCnt bl; + FuncState *fs = ls->fs; + int prep, endfor; + adjustlocalvars(ls, 3); /* control variables */ + checknext(ls, TK_DO); + prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs); + enterblock(fs, &bl, 0); /* scope for declared variables */ + adjustlocalvars(ls, nvars); + luaK_reserveregs(fs, nvars); + block(ls); + leaveblock(fs); /* end of scope for declared variables */ + luaK_patchtohere(fs, prep); + if (isnum) /* numeric for? */ + endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP); + else { /* generic for */ + luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars); + luaK_fixline(fs, line); + endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP); + } + luaK_patchlist(fs, endfor, prep + 1); + luaK_fixline(fs, line); +} + + +static void fornum (LexState *ls, TString *varname, int line) { + /* fornum -> NAME = exp1,exp1[,exp1] forbody */ + FuncState *fs = ls->fs; + int base = fs->freereg; + new_localvarliteral(ls, "(for index)"); + new_localvarliteral(ls, "(for limit)"); + new_localvarliteral(ls, "(for step)"); + new_localvar(ls, varname); + checknext(ls, '='); + exp1(ls); /* initial value */ + checknext(ls, ','); + exp1(ls); /* limit */ + if (testnext(ls, ',')) + exp1(ls); /* optional step */ + else { /* default step = 1 */ + luaK_codek(fs, fs->freereg, luaK_numberK(fs, cast_num(1))); + luaK_reserveregs(fs, 1); + } + forbody(ls, base, line, 1, 1); +} + + +static void forlist (LexState *ls, TString *indexname) { + /* forlist -> NAME {,NAME} IN explist forbody */ + FuncState *fs = ls->fs; + expdesc e; + int nvars = 4; /* gen, state, control, plus at least one declared var */ + int line; + int base = fs->freereg; + /* create control variables */ + new_localvarliteral(ls, "(for generator)"); + new_localvarliteral(ls, "(for state)"); + new_localvarliteral(ls, "(for control)"); + /* create declared variables */ + new_localvar(ls, indexname); + while (testnext(ls, ',')) { + new_localvar(ls, str_checkname(ls)); + nvars++; + } + checknext(ls, TK_IN); + line = ls->linenumber; + adjust_assign(ls, 3, explist(ls, &e), &e); + luaK_checkstack(fs, 3); /* extra space to call generator */ + forbody(ls, base, line, nvars - 3, 0); +} + + +static void forstat (LexState *ls, int line) { + /* forstat -> FOR (fornum | forlist) END */ + FuncState *fs = ls->fs; + TString *varname; + BlockCnt bl; + enterblock(fs, &bl, 1); /* scope for loop and control variables */ + luaX_next(ls); /* skip `for' */ + varname = str_checkname(ls); /* first variable name */ + switch (ls->t.token) { + case '=': fornum(ls, varname, line); break; + case ',': case TK_IN: forlist(ls, varname); break; + default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected"); + } + check_match(ls, TK_END, TK_FOR, line); + leaveblock(fs); /* loop scope (`break' jumps to this point) */ +} + + +static int test_then_block (LexState *ls, int *escapelist) { + /* test_then_block -> [IF | ELSEIF] cond THEN block */ + BlockCnt bl; + FuncState *fs = ls->fs; + expdesc v; + int jf; /* instruction to skip 'then' code (if condition is false) */ + int line = ls->linenumber; + int short_if = (ls->t.token == TK_IF); /* if TK_IF, can be a short IF */ + luaX_next(ls); /* skip IF or ELSEIF */ + luaX_trackbraces(ls); /* track braces for short IF */ + expr(ls, &v); /* read condition */ + short_if &= ls->t.token != TK_THEN && ls->t.token != TK_DO && ls->t.token != TK_EOS + && ls->braces == 0 && line == ls->linenumber; + if (short_if) { + ls->emiteol = 1; + ls->short_nest++; + } + else { + /* PICO-8 allows 'do' as alternative to 'then' in if statements */ + if (ls->t.token == TK_DO || ls->t.token == TK_THEN) + luaX_next(ls); /* skip THEN or DO */ + else + luaX_syntaxerror(ls, "'then' expected"); + } + if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) { + luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */ + enterblock(fs, &bl, 0); /* must enter block before 'goto' */ + gotostat(ls, v.t); /* handle goto/break */ + skipnoopstat(ls); /* skip other no-op statements */ + if (block_follow(ls, 0)) { /* 'goto' is the entire block? */ + leaveblock(fs); + return short_if; /* and that is it */ + } + else /* must skip over 'then' part if condition is false */ + jf = luaK_jump(fs); + } + else { /* regular case (not goto/break) */ + luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */ + enterblock(fs, &bl, 0); + jf = v.f; + } + statlist(ls); /* `then' part */ + leaveblock(fs); + if (ls->t.token == TK_ELSE || + ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */ + luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */ + luaK_patchtohere(fs, jf); + return short_if; +} + + +static void ifstat (LexState *ls, int line) { + /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ + FuncState *fs = ls->fs; + int escapelist = NO_JUMP; /* exit list for finished parts */ + int short_if = test_then_block(ls, &escapelist); /* IF cond THEN block */ + while (ls->t.token == TK_ELSEIF) + test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */ + if (testnext(ls, TK_ELSE)) + block(ls); /* `else' part */ + if (!short_if) + check_match(ls, TK_END, TK_IF, line); + else { + ls->short_nest--; + if (ls->t.token == TK_EOL || ls->t.token == TK_EOS) + luaX_next(ls); /* eat EOL or EOS */ + else if (block_follow(ls, 1)) + ls->emiteol = 0; /* close the short IF */ + else + check_match(ls, TK_EOL, TK_IF, line); /* we expected EOL */ + } + luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */ +} + + +static void localfunc (LexState *ls) { + expdesc b; + FuncState *fs = ls->fs; + new_localvar(ls, str_checkname(ls)); /* new local variable */ + adjustlocalvars(ls, 1); /* enter its scope */ + body(ls, &b, 0, ls->linenumber); /* function created in next register */ + /* debug information will only see the variable after this point! */ + getlocvar(fs, b.u.info)->startpc = fs->pc; +} + + +static void localstat (LexState *ls) { + /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */ + int nvars = 0; + int nexps; + expdesc e; + do { + new_localvar(ls, str_checkname(ls)); + nvars++; + } while (testnext(ls, ',')); + if (testnext(ls, '=')) + nexps = explist(ls, &e); + else { + e.k = VVOID; + nexps = 0; + } + adjust_assign(ls, nvars, nexps, &e); + adjustlocalvars(ls, nvars); +} + + +static int funcname (LexState *ls, expdesc *v) { + /* funcname -> NAME {fieldsel} [`:' NAME] */ + int ismethod = 0; + singlevar(ls, v); + while (ls->t.token == '.') + fieldsel(ls, v); + if (ls->t.token == ':') { + ismethod = 1; + fieldsel(ls, v); + } + return ismethod; +} + + +static void funcstat (LexState *ls, int line) { + /* funcstat -> FUNCTION funcname body */ + int ismethod; + expdesc v, b; + luaX_next(ls); /* skip FUNCTION */ + ismethod = funcname(ls, &v); + body(ls, &b, ismethod, line); + luaK_storevar(ls->fs, &v, &b); + luaK_fixline(ls->fs, line); /* definition `happens' in the first line */ +} + + +static void exprstat (LexState *ls) { + /* stat -> func | compound | assignment */ + FuncState *fs = ls->fs; + struct LHS_assign v; + suffixedexp(ls, &v.v); + if (ls->t.token >= TK_ADDE && ls->t.token <= TK_CONCATE) { + v.prev = NULL; + compound(ls, &v.v); + } + else if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */ + v.prev = NULL; + assignment(ls, &v, 1); + } + else { /* stat -> func */ + check_condition(ls, v.v.k == VCALL, "syntax error"); + SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */ + } +} + + +static void retstat (LexState *ls) { + /* stat -> RETURN [explist] [';'] */ + FuncState *fs = ls->fs; + expdesc e; + int first, nret; /* registers with returned values */ + if (block_follow(ls, 1) || ls->t.token == ';') + first = nret = 0; /* return no values */ + else { + nret = explist(ls, &e); /* optional return values */ + if (hasmultret(e.k)) { + luaK_setmultret(fs, &e); + if (e.k == VCALL && nret == 1) { /* tail call? */ + SET_OPCODE(getcode(fs,&e), OP_TAILCALL); + lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar); + } + first = fs->nactvar; + nret = LUA_MULTRET; /* return all values */ + } + else { + if (nret == 1) /* only one single value? */ + first = luaK_exp2anyreg(fs, &e); + else { + luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */ + first = fs->nactvar; /* return all `active' values */ + lua_assert(nret == fs->freereg - first); + } + } + } + luaK_ret(fs, first, nret); + testnext(ls, ';'); /* skip optional semicolon */ +} + + +static void shortprint (LexState *ls) { + int line = ls->linenumber; + FuncState *fs = ls->fs; + + /* same as suffixedexp() except we push "print" first */ + expdesc f; + TString *n = luaS_new(ls->L, "print"); + ls->t.seminfo.ts = n; + ls->t.token = TK_NAME; + singlevar(ls, &f); + luaK_exp2nextreg(fs, &f); + + /* now we do the same as funcargs() */ + expdesc args; + if (ls->t.token == TK_EOL || ls->t.token == TK_EOS) /* arg list is empty? */ + args.k = VVOID; + else { + explist(ls, &args); + luaK_setmultret(fs, &args); + } + + if (!testnext(ls, TK_EOS)) /* check that we are at EOL or EOS */ + check_match(ls, TK_EOL, '?', line); + + /* If we're inside a short-if/while, it was relying on TK_EOL to terminate + itself, but shortprint just consumed that EOL. Re-inject a synthetic + TK_EOL so the enclosing short block can still see it and terminate. */ + if (ls->short_nest > 0) { + ls->lookahead = ls->t; + ls->t.token = TK_EOL; + } + + int base, nparams; + lua_assert(f.k == VNONRELOC); + base = f.u.info; /* base register for call */ + if (hasmultret(args.k)) + nparams = LUA_MULTRET; /* open call */ + else { + if (args.k != VVOID) + luaK_exp2nextreg(fs, &args); /* close last argument */ + nparams = fs->freereg - (base+1); + } + + init_exp(&f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); + luaK_fixline(fs, line); + fs->freereg = fs->nactvar; +} + + +static void statement (LexState *ls) { + int line = ls->linenumber; /* may be needed for error messages */ + enterlevel(ls); + switch (ls->t.token) { + case ';': { /* stat -> ';' (empty statement) */ + luaX_next(ls); /* skip ';' */ + break; + } + case TK_PRINT: { + shortprint(ls); /* stat -> shortprint (on a single line) */ + break; + } + case TK_IF: { /* stat -> ifstat */ + ifstat(ls, line); + break; + } + case TK_WHILE: { /* stat -> whilestat */ + whilestat(ls, line); + break; + } + case TK_DO: { /* stat -> DO block END */ + luaX_next(ls); /* skip DO */ + block(ls); + check_match(ls, TK_END, TK_DO, line); + break; + } + case TK_FOR: { /* stat -> forstat */ + forstat(ls, line); + break; + } + case TK_REPEAT: { /* stat -> repeatstat */ + repeatstat(ls, line); + break; + } + case TK_FUNCTION: { /* stat -> funcstat */ + funcstat(ls, line); + break; + } + case TK_LOCAL: { /* stat -> localstat */ + luaX_next(ls); /* skip LOCAL */ + if (testnext(ls, TK_FUNCTION)) /* local function? */ + localfunc(ls); + else + localstat(ls); + break; + } + case TK_DBCOLON: { /* stat -> label */ + luaX_next(ls); /* skip double colon */ + labelstat(ls, str_checkname(ls), line); + break; + } + case TK_RETURN: { /* stat -> retstat */ + luaX_next(ls); /* skip RETURN */ + retstat(ls); + break; + } + case TK_BREAK: /* stat -> breakstat */ + case TK_GOTO: { /* stat -> 'goto' NAME */ + gotostat(ls, luaK_jump(ls->fs)); + break; + } + default: { /* stat -> func | assignment */ + exprstat(ls); + break; + } + } + lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && + ls->fs->freereg >= ls->fs->nactvar); + ls->fs->freereg = ls->fs->nactvar; /* free registers */ + leavelevel(ls); +} + +/* }====================================================================== */ + + +/* +** compiles the main function, which is a regular vararg function with an +** upvalue named LUA_ENV +*/ +static void mainfunc (LexState *ls, FuncState *fs) { + BlockCnt bl; + expdesc v; + open_func(ls, fs, &bl); + fs->f->is_vararg = 1; /* main function is always vararg */ + init_exp(&v, VLOCAL, 0); /* create and... */ + newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */ + luaX_next(ls); /* read first token */ + statlist(ls); /* parse main body */ + check(ls, TK_EOS); + close_func(ls); +} + + +Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, + Dyndata *dyd, const char *name, int firstchar) { + LexState lexstate; + FuncState funcstate; + Closure *cl = luaF_newLclosure(L, 1); /* create main closure */ + /* anchor closure (to avoid being collected) */ + setclLvalue(L, L->top, cl); + incr_top(L); + funcstate.f = cl->l.p = luaF_newproto(L); + funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ + lexstate.buff = buff; + lexstate.dyd = dyd; + dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; + luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar); + mainfunc(&lexstate, &funcstate); + lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs); + /* all scopes should be correctly finished */ + lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0); + return cl; /* it's on the stack too */ +} + diff --git a/components/pico8/femto8/src/lua/lparser.h b/components/pico8/femto8/src/lua/lparser.h new file mode 100644 index 00000000..301167d4 --- /dev/null +++ b/components/pico8/femto8/src/lua/lparser.h @@ -0,0 +1,119 @@ +/* +** $Id: lparser.h,v 1.70 2012/05/08 13:53:33 roberto Exp $ +** Lua Parser +** See Copyright Notice in lua.h +*/ + +#ifndef lparser_h +#define lparser_h + +#include "llimits.h" +#include "lobject.h" +#include "lzio.h" + + +/* +** Expression descriptor +*/ + +typedef enum { + VVOID, /* no value */ + VNIL, + VTRUE, + VFALSE, + VK, /* info = index of constant in `k' */ + VKNUM, /* nval = numerical value */ + VNONRELOC, /* info = result register */ + VLOCAL, /* info = local register */ + VUPVAL, /* info = index of upvalue in 'upvalues' */ + VINDEXED, /* t = table register/upvalue; idx = index R/K */ + VJMP, /* info = instruction pc */ + VRELOCABLE, /* info = instruction pc */ + VCALL, /* info = instruction pc */ + VVARARG /* info = instruction pc */ +} expkind; + + +#define vkisvar(k) (VLOCAL <= (k) && (k) <= VINDEXED) +#define vkisinreg(k) ((k) == VNONRELOC || (k) == VLOCAL) + +typedef struct expdesc { + expkind k; + union { + struct { /* for indexed variables (VINDEXED) */ + short idx; /* index (R/K) */ + lu_byte t; /* table (register or upvalue) */ + lu_byte vt; /* whether 't' is register (VLOCAL) or upvalue (VUPVAL) */ + } ind; + int info; /* for generic use */ + lua_Number nval; /* for VKNUM */ + } u; + int t; /* patch list of `exit when true' */ + int f; /* patch list of `exit when false' */ +} expdesc; + + +/* description of active local variable */ +typedef struct Vardesc { + short idx; /* variable index in stack */ +} Vardesc; + + +/* description of pending goto statements and label statements */ +typedef struct Labeldesc { + TString *name; /* label identifier */ + int pc; /* position in code */ + int line; /* line where it appeared */ + lu_byte nactvar; /* local level where it appears in current block */ +} Labeldesc; + + +/* list of labels or gotos */ +typedef struct Labellist { + Labeldesc *arr; /* array */ + int n; /* number of entries in use */ + int size; /* array size */ +} Labellist; + + +/* dynamic structures used by the parser */ +typedef struct Dyndata { + struct { /* list of active local variables */ + Vardesc *arr; + int n; + int size; + } actvar; + Labellist gt; /* list of pending gotos */ + Labellist label; /* list of active labels */ +} Dyndata; + + +/* control of blocks */ +struct BlockCnt; /* defined in lparser.c */ + + +/* state needed to generate code for a given function */ +typedef struct FuncState { + Proto *f; /* current function header */ + Table *h; /* table to find (and reuse) elements in `k' */ + struct FuncState *prev; /* enclosing function */ + struct LexState *ls; /* lexical state */ + struct BlockCnt *bl; /* chain of current blocks */ + int pc; /* next position to code (equivalent to `ncode') */ + int lasttarget; /* 'label' of last 'jump label' */ + int jpc; /* list of pending jumps to `pc' */ + int nk; /* number of elements in `k' */ + int np; /* number of elements in `p' */ + int firstlocal; /* index of first local var (in Dyndata array) */ + short nlocvars; /* number of elements in 'f->locvars' */ + lu_byte nactvar; /* number of active local variables */ + lu_byte nups; /* number of upvalues */ + lu_byte freereg; /* first free register */ +} FuncState; + + +LUAI_FUNC Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, + Dyndata *dyd, const char *name, int firstchar); + + +#endif diff --git a/components/pico8/femto8/src/lua/lpico8lib.c b/components/pico8/femto8/src/lua/lpico8lib.c new file mode 100644 index 00000000..ccecdd36 --- /dev/null +++ b/components/pico8/femto8/src/lua/lpico8lib.c @@ -0,0 +1,409 @@ +/* +** PICO-8 library functions - ported from ZEPTO-8 (C++ -> pure C) +** +** Original: Copyright 2016-2024 Sam Hocevar (WTFPL) +** Port: fix32_t function calls instead of C++ operator overloads. +*/ + +#include +#include +#include +#include + +#define lpico8lib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "llimits.h" +#include "lobject.h" + +#include "trigtables.h" + +static int pico8_max(lua_State *l) { + lua_pushnumber(l, fix32_max(lua_tonumber(l, 1), lua_tonumber(l, 2))); + return 1; +} + +static int pico8_min(lua_State *l) { + lua_pushnumber(l, fix32_min(lua_tonumber(l, 1), lua_tonumber(l, 2))); + return 1; +} + +static int pico8_mid(lua_State *l) { + lua_pushnumber(l, fix32_mid(lua_tonumber(l, 1), + lua_tonumber(l, 2), + lua_tonumber(l, 3))); + return 1; +} + +static int pico8_ceil(lua_State *l) { + lua_pushnumber(l, fix32_ceil(lua_tonumber(l, 1))); + return 1; +} + +static int pico8_flr(lua_State *l) { + lua_pushnumber(l, fix32_flr(lua_tonumber(l, 1))); + return 1; +} + +static lua_Number sin_helper(lua_Number x) { + /* Reduce angle to 0x0 ... 0x0.3fff, with the following PICO-8 rules: + * - sin(x) = -sin(x + 0.5) + * - sin(x) equals sin(~x) rather than sin(-x) + * - the last two bits are rounded + * We use a lookup table of sin(x)-4x generated by PICO-8 to ensure + * that we get the exact same results. */ + int32_t xbits = fix32_bits(x); + int32_t base = (xbits & 0x4000) ? fix32_bits(fix32_bnot(x)) : xbits; + int32_t a = (base & 0x3fff) + 2; + int32_t idx = a >> 2; + if (idx > 4095) idx = 4095; /* clamp to table bounds */ + fix32_t ret = fix32_from_bits((idx << 4) + sintable[idx]); + return (xbits & 0x8000) ? ret : fix32_neg(ret); +} + +static int pico8_cos(lua_State *l) { + lua_pushnumber(l, sin_helper(fix32_sub(lua_tonumber(l, 1), fix32_from_bits(0x4000)))); + return 1; +} + +static int pico8_sin(lua_State *l) { + lua_pushnumber(l, sin_helper(lua_tonumber(l, 1))); + return 1; +} + +static int pico8_atan2(lua_State *l) { + lua_Number x = lua_tonumber(l, 1); + lua_Number y = lua_tonumber(l, 2); + int32_t xbits = fix32_bits(x); + int32_t ybits = fix32_bits(y); + int32_t bits = 0x4000; + if (xbits != 0) { + /* Use integer abs instead of fix32_abs to emulate PICO-8’s behaviour + * with e.g. atan2(0x8000, 0x8000.0001) */ + int64_t ax = (int64_t)xbits; if (ax < 0) ax = -ax; + int64_t ay = (int64_t)ybits; if (ay < 0) ay = -ay; + int64_t q = (ay << 16) / ax; + if (q > 0x10000) + bits -= atantable[((int64_t)1 << 32) / q >> 5]; + else + bits = atantable[q >> 5]; + } + if (xbits < 0) bits = 0x8000 - bits; + if (ybits > 0) bits = -bits & 0xffff; + /* Emulate a bug in PICO-8 with e.g. atan2(1, 0x8000) */ + if (xbits != 0 && ybits == (int32_t)0x80000000) bits = -bits & 0xffff; + lua_pushnumber(l, fix32_from_bits(bits)); + return 1; +} + +static int pico8_sqrt(lua_State *l) { + int64_t root = 0, x = (int64_t)fix32_bits(lua_tonumber(l, 1)) << 16; + if (x > 0) { + /* Square root by abacus algorithm, Martin Guy @ UKC, June 1985. */ + int64_t a; + for (a = (int64_t)1 << 46; a; a >>= 2, root >>= 1) { + if (x >= a + root) { + x -= a + root; + root += a << 1; + } + } + } + lua_pushnumber(l, fix32_from_bits((int32_t)root)); + return 1; +} + +static int pico8_abs(lua_State *l) { + lua_pushnumber(l, fix32_abs(lua_tonumber(l, 1))); + return 1; +} + +static int pico8_sgn(lua_State *l) { + lua_pushnumber(l, fix32_sgn(lua_tonumber(l, 1))); + return 1; +} + +static int pico8_band(lua_State *l) { + lua_pushnumber(l, fix32_band(lua_tonumber(l, 1), lua_tonumber(l, 2))); + return 1; +} + +static int pico8_bor(lua_State *l) { + lua_pushnumber(l, fix32_bor(lua_tonumber(l, 1), lua_tonumber(l, 2))); + return 1; +} + +static int pico8_bxor(lua_State *l) { + lua_pushnumber(l, fix32_bxor(lua_tonumber(l, 1), lua_tonumber(l, 2))); + return 1; +} + +static int pico8_bnot(lua_State *l) { + lua_pushnumber(l, fix32_bnot(lua_tonumber(l, 1))); + return 1; +} + +static int pico8_shl(lua_State *l) { + lua_pushnumber(l, fix32_shl(lua_tonumber(l, 1), fix32_to_int(lua_tonumber(l, 2)))); + return 1; +} + +static int pico8_lshr(lua_State *l) { + lua_pushnumber(l, fix32_lshr(lua_tonumber(l, 1), fix32_to_int(lua_tonumber(l, 2)))); + return 1; +} + +static int pico8_shr(lua_State *l) { + lua_pushnumber(l, fix32_shr(lua_tonumber(l, 1), fix32_to_int(lua_tonumber(l, 2)))); + return 1; +} + +static int pico8_rotl(lua_State *l) { + lua_pushnumber(l, fix32_rotl(lua_tonumber(l, 1), fix32_to_int(lua_tonumber(l, 2)))); + return 1; +} + +static int pico8_rotr(lua_State *l) { + lua_pushnumber(l, fix32_rotr(lua_tonumber(l, 1), fix32_to_int(lua_tonumber(l, 2)))); + return 1; +} + +static int pico8_tostr(lua_State *l) { + char buffer[20]; + char const *s = buffer; + + uint16_t flags = 0; + if (lua_isboolean(l, 2)) { + flags = lua_toboolean(l, 2) ? 1 : 0; + } + else if (lua_isnumber(l, 2)) { + flags = (uint16_t)lua_tointeger(l, 2); + } + + switch (lua_type(l, 1)) + { + case LUA_TNONE: + /* PICO-8 0.2.2 changelog: tostr() returns "" instead of nil */ + buffer[0] = '\0'; + break; + case LUA_TNUMBER: { + lua_Number x = lua_tonumber(l, 1); + if (flags) { + uint32_t b = (uint32_t)fix32_bits(x); + if ((flags & 0x3) == 0x3) { + sprintf(buffer, "0x%04x%04x", (unsigned)((b >> 16) & 0xffff), (unsigned)(b & 0xffff)); + } + else if ((flags & 0x2) == 0x2) { + sprintf(buffer, "%d", (int)b); + } + else { + sprintf(buffer, "0x%04x.%04x", (unsigned)((b >> 16) & 0xffff), (unsigned)(b & 0xffff)); + } + } else { + lua_number2str(buffer, x); + } + break; + } + case LUA_TSTRING: + lua_pushvalue(l, 1); + return 1; + case LUA_TBOOLEAN: s = lua_toboolean(l, 1) ? "true" : "false"; break; + case LUA_TTABLE: + /* PICO-8 0.1.12d changelog: "__tostring metatable method + * observed by tostr() / print() / printh()" */ + if (luaL_callmeta(l, 1, "__tostring")) { + return 1; + } + /* fall through */ + case LUA_TFUNCTION: + /* PICO-8 0.1.12d changelog: "tostr(x,true) can also be used to view + * the hex value of functions and tables (uses Lua's tostring)" */ + if (flags) { + luaL_tolstring(l, 1, NULL); + return 1; + } + /* fall through */ + default: sprintf(buffer, "[%s]", luaL_typename(l, 1)); break; + } + lua_pushstring(l, s); + return 1; +} + +static int pico8_tonum(lua_State *l) { + lua_Number ret; + switch (lua_type(l, 1)) + { + case LUA_TSTRING: { + char const *s = lua_tostring(l, 1); + uint16_t flags = lua_gettop(l) >= 2 ? (uint16_t)lua_tointeger(l, 2) : 0; + if (flags & 0x1) { + char buf[12]; + size_t i; + for (i = 0; s[i] != '\0' && i < 11; ++i) + buf[i] = isxdigit((unsigned char)s[i]) ? s[i] : '0'; + buf[i] = '\0'; + uint32_t bits = (uint32_t)strtol(buf, NULL, 16); + if (flags & 0x2) + lua_pushnumber(l, fix32_from_bits((int32_t)bits)); + else + lua_pushnumber(l, fix32_from_int((int)(uint16_t)bits)); + return 1; + } + else if (flags & 0x2) { + uint32_t bits = (uint32_t)strtol(s, NULL, 10); + lua_pushnumber(l, fix32_from_bits((int32_t)bits)); + return 1; + } + /* If parsing failed, PICO-8 returns nothing */ + if (!luaO_str2d(s, strlen(s), &ret)) return 0; + break; + } + case LUA_TNUMBER: ret = lua_tonumber(l, 1); break; + /* PICO-8 0.2.3 changelog: "tonum(boolean_value) returns 1 or 0 instead of nil" */ + case LUA_TBOOLEAN: ret = lua_toboolean(l, 1) ? FIX32_ONE : FIX32_ZERO; break; + default: return 0; + } + lua_pushnumber(l, ret); + return 1; +} + +static int pico8_chr(lua_State *l) { + char stack_buf[256]; + char *s; + int numargs = lua_gettop(l); + int allocated = 0; + int i; + + if ((size_t)numargs <= sizeof(stack_buf)) { + s = stack_buf; + } else { + s = (char *)malloc((size_t)numargs); + if (!s) { + lua_pushstring(l, ""); + return 1; + } + allocated = 1; + } + + for (i = 0; i < numargs; i++) { + s[i] = (char)(uint8_t)fix32_to_int(lua_tonumber(l, i + 1)); + } + lua_pushlstring(l, s, (size_t)numargs); + + if (allocated) { + free(s); + } + return 1; +} + +static int pico8_ord(lua_State *l) { + size_t len; + int n = 0; + int count = 1; + int i; + char const *s = luaL_checklstring(l, 1, &len); + if (!lua_isnone(l, 3)) { + if (!lua_isnumber(l, 3)) return 0; + count = fix32_to_int(lua_tonumber(l, 3)); + } + if (!lua_isnone(l, 2)) { + if (!lua_isnumber(l, 2)) return 0; + n = fix32_to_int(lua_tonumber(l, 2)) - 1; + } + if (n < 0 || (size_t)n >= len || count < 1) + return 0; + if ((size_t)(n + count) > len) + count = (int)(len - (size_t)n); + /* min stack is only 20. This could be a much longer string */ + lua_checkstack(l, count); + for (i = 0; i < count; ++i) + lua_pushnumber(l, fix32_from_int((int)(uint8_t)s[n + i])); + return count; +} + +static int pico8_split(lua_State *l) { + size_t count = 0, hlen; + char const *haystack; + int size = 0; + char needle = ','; + int convert; + char const *end; + char const *parser; + + if (lua_isnil(l, 1)) { + return 0; + } + haystack = luaL_checklstring(l, 1, &hlen); + if (!haystack) + return 0; + lua_newtable(l); + /* Split either by chunk size or by needle position */ + if (lua_isnumber(l, 2)) { + size = fix32_to_int(lua_tonumber(l, 2)); + if (size <= 0) + size = 1; + } else if (lua_isstring(l, 2)) { + needle = *lua_tostring(l, 2); + } + convert = lua_isnone(l, 3) || lua_toboolean(l, 3); + end = haystack + hlen + (!size && needle); + for (parser = haystack; parser < end; ) { + lua_Number num; + char const *next = size ? parser + size + : needle ? (char const*)memchr(parser, needle, (size_t)(end - parser)) : parser + 1; + char saved; + if (!next || next > end) + next = haystack + hlen; + saved = *next; /* temporarily put a null terminator here */ + *(char *)next = '\0'; + if (convert && luaO_str2d(parser, (size_t)(next - parser), &num)) + lua_pushnumber(l, num); + else + lua_pushlstring(l, parser, (size_t)(next - parser)); + *(char *)next = saved; + lua_rawseti(l, -2, (int)(++count)); + parser = next + (!size && needle); + } + return 1; +} + +static const luaL_Reg pico8lib[] = { + {"max", pico8_max}, + {"min", pico8_min}, + {"mid", pico8_mid}, + {"ceil", pico8_ceil}, + {"flr", pico8_flr}, + {"cos", pico8_cos}, + {"sin", pico8_sin}, + {"atan2", pico8_atan2}, + {"sqrt", pico8_sqrt}, + {"abs", pico8_abs}, + {"sgn", pico8_sgn}, + {"band", pico8_band}, + {"bor", pico8_bor}, + {"bxor", pico8_bxor}, + {"bnot", pico8_bnot}, + {"shl", pico8_shl}, + {"shr", pico8_shr}, + {"lshr", pico8_lshr}, + {"rotl", pico8_rotl}, + {"rotr", pico8_rotr}, + {"tostr", pico8_tostr}, + {"tonum", pico8_tonum}, + {"chr", pico8_chr}, + {"ord", pico8_ord}, + {"split", pico8_split}, + {NULL, NULL} +}; + + +/* +** Register PICO-8 functions in global table +*/ +LUAMOD_API int luaopen_pico8 (lua_State *L) { + lua_pushglobaltable(L); + luaL_setfuncs(L, pico8lib, 0); + return 1; +} diff --git a/components/pico8/femto8/src/lua/lstate.c b/components/pico8/femto8/src/lua/lstate.c new file mode 100644 index 00000000..4ba4fe6d --- /dev/null +++ b/components/pico8/femto8/src/lua/lstate.c @@ -0,0 +1,324 @@ +/* +** $Id: lstate.c,v 2.99.1.1 2013/04/12 18:48:47 roberto Exp roberto $ +** Global State +** See Copyright Notice in lua.h +*/ + + +#include +#include + +#define lstate_c +#define LUA_CORE + +#include "lua.h" + +#include "lapi.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "llex.h" +#include "lmem.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" + + +#if !defined(LUAI_GCPAUSE) +#define LUAI_GCPAUSE 200 /* 200% */ +#endif + +#if !defined(LUAI_GCMAJOR) +#define LUAI_GCMAJOR 200 /* 200% */ +#endif + +#if !defined(LUAI_GCMUL) +#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */ +#endif + + +#define MEMERRMSG "not enough memory" + + +/* +** a macro to help the creation of a unique random seed when a state is +** created; the seed is used to randomize hashes. +*/ +#if !defined(luai_makeseed) +#include +#define luai_makeseed() cast(unsigned int, time(NULL)) +#endif + + + +/* +** thread state + extra space +*/ +typedef struct LX { +#if defined(LUAI_EXTRASPACE) + char buff[LUAI_EXTRASPACE]; +#endif + lua_State l; +} LX; + + +/* +** Main thread combines a thread state and the global state +*/ +typedef struct LG { + LX l; + global_State g; +} LG; + + + +#define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l))) + + +/* +** Compute an initial seed as random as possible. In ANSI, rely on +** Address Space Layout Randomization (if present) to increase +** randomness.. +*/ +#define addbuff(b,p,e) \ + { size_t t = cast(size_t, e); \ + memcpy(buff + p, &t, sizeof(t)); p += sizeof(t); } + +static unsigned int makeseed (lua_State *L) { + char buff[4 * sizeof(size_t)]; + unsigned int h = luai_makeseed(); + int p = 0; + addbuff(buff, p, L); /* heap variable */ + addbuff(buff, p, &h); /* local variable */ + addbuff(buff, p, luaO_nilobject); /* global variable */ + addbuff(buff, p, &lua_newstate); /* public function */ + lua_assert(p == sizeof(buff)); + return luaS_hash(buff, p, h); +} + + +/* +** set GCdebt to a new value keeping the value (totalbytes + GCdebt) +** invariant +*/ +void luaE_setdebt (global_State *g, l_mem debt) { + g->totalbytes -= (debt - g->GCdebt); + g->GCdebt = debt; +} + + +CallInfo *luaE_extendCI (lua_State *L) { + CallInfo *ci = luaM_new(L, CallInfo); + lua_assert(L->ci->next == NULL); + L->ci->next = ci; + ci->previous = L->ci; + ci->next = NULL; + return ci; +} + + +void luaE_freeCI (lua_State *L) { + CallInfo *ci = L->ci; + CallInfo *next = ci->next; + ci->next = NULL; + while ((ci = next) != NULL) { + next = ci->next; + luaM_free(L, ci); + } +} + + +static void stack_init (lua_State *L1, lua_State *L) { + int i; CallInfo *ci; + /* initialize stack array */ + L1->stack = luaM_newvector(L, BASIC_STACK_SIZE, TValue); + L1->stacksize = BASIC_STACK_SIZE; + for (i = 0; i < BASIC_STACK_SIZE; i++) + setnilvalue(L1->stack + i); /* erase new stack */ + L1->top = L1->stack; + L1->stack_last = L1->stack + L1->stacksize - EXTRA_STACK; + /* initialize first ci */ + ci = &L1->base_ci; + ci->next = ci->previous = NULL; + ci->callstatus = 0; + ci->func = L1->top; + setnilvalue(L1->top++); /* 'function' entry for this 'ci' */ + ci->top = L1->top + LUA_MINSTACK; + L1->ci = ci; +} + + +static void freestack (lua_State *L) { + if (L->stack == NULL) + return; /* stack not completely built yet */ + L->ci = &L->base_ci; /* free the entire 'ci' list */ + luaE_freeCI(L); + luaM_freearray(L, L->stack, L->stacksize); /* free stack array */ +} + + +/* +** Create registry table and its predefined values +*/ +static void init_registry (lua_State *L, global_State *g) { + TValue mt; + /* create registry */ + Table *registry = luaH_new(L); + sethvalue(L, &g->l_registry, registry); + luaH_resize(L, registry, LUA_RIDX_LAST, 0); + /* registry[LUA_RIDX_MAINTHREAD] = L */ + setthvalue(L, &mt, L); + luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &mt); + /* registry[LUA_RIDX_GLOBALS] = table of globals */ + sethvalue(L, &mt, luaH_new(L)); + luaH_setint(L, registry, LUA_RIDX_GLOBALS, &mt); +} + + +/* +** open parts of the state that may cause memory-allocation errors +*/ +static void f_luaopen (lua_State *L, void *ud) { + global_State *g = G(L); + UNUSED(ud); + stack_init(L, L); /* init stack */ + init_registry(L, g); + luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */ + luaT_init(L); + luaX_init(L); + /* pre-create memory-error message */ + g->memerrmsg = luaS_newliteral(L, MEMERRMSG); + luaS_fix(g->memerrmsg); /* it should never be collected */ + g->gcrunning = 1; /* allow gc */ + g->version = lua_version(NULL); + luai_userstateopen(L); +} + + +/* +** preinitialize a state with consistent values without allocating +** any memory (to avoid errors) +*/ +static void preinit_state (lua_State *L, global_State *g) { + G(L) = g; + L->stack = NULL; + L->ci = NULL; + L->stacksize = 0; + L->errorJmp = NULL; + L->nCcalls = 0; + L->hook = NULL; + L->hookmask = 0; + L->basehookcount = 0; + L->allowhook = 1; + resethookcount(L); + L->openupval = NULL; + L->nny = 1; + L->status = LUA_OK; + L->errfunc = 0; +} + + +static void close_state (lua_State *L) { + global_State *g = G(L); + luaF_close(L, L->stack); /* close all upvalues for this thread */ + luaC_freeallobjects(L); /* collect all objects */ + if (g->version) /* closing a fully built state? */ + luai_userstateclose(L); + luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size); + luaZ_freebuffer(L, &g->buff); + freestack(L); + lua_assert(gettotalbytes(g) == sizeof(LG)); + (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); /* free main block */ +} + + +LUA_API lua_State *lua_newthread (lua_State *L) { + lua_State *L1; + lua_lock(L); + luaC_checkGC(L); + L1 = &luaC_newobj(L, LUA_TTHREAD, sizeof(LX), NULL, offsetof(LX, l))->th; + setthvalue(L, L->top, L1); + api_incr_top(L); + preinit_state(L1, G(L)); + L1->hookmask = L->hookmask; + L1->basehookcount = L->basehookcount; + L1->hook = L->hook; + resethookcount(L1); + luai_userstatethread(L, L1); + stack_init(L1, L); /* init stack */ + lua_unlock(L); + return L1; +} + + +void luaE_freethread (lua_State *L, lua_State *L1) { + LX *l = fromstate(L1); + luaF_close(L1, L1->stack); /* close all upvalues for this thread */ + lua_assert(L1->openupval == NULL); + luai_userstatefree(L, L1); + freestack(L1); + luaM_free(L, l); +} + + +LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { + int i; + lua_State *L; + global_State *g; + LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG))); + if (l == NULL) return NULL; + L = &l->l.l; + g = &l->g; + L->next = NULL; + L->tt = LUA_TTHREAD; + g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT); + L->marked = luaC_white(g); + g->gckind = KGC_NORMAL; + preinit_state(L, g); + g->frealloc = f; + g->ud = ud; + g->mainthread = L; + g->seed = makeseed(L); + g->uvhead.u.l.prev = &g->uvhead; + g->uvhead.u.l.next = &g->uvhead; + g->gcrunning = 0; /* no GC while building state */ + g->GCestimate = 0; + g->strt.size = 0; + g->strt.nuse = 0; + g->strt.hash = NULL; + setnilvalue(&g->l_registry); + luaZ_initbuffer(L, &g->buff); + g->panic = NULL; + g->version = NULL; + g->gcstate = GCSpause; + g->allgc = NULL; + g->finobj = NULL; + g->tobefnz = NULL; + g->sweepgc = g->sweepfin = NULL; + g->gray = g->grayagain = NULL; + g->weak = g->ephemeron = g->allweak = NULL; + g->totalbytes = sizeof(LG); + g->GCdebt = 0; + g->gcpause = LUAI_GCPAUSE; + g->gcmajorinc = LUAI_GCMAJOR; + g->gcstepmul = LUAI_GCMUL; + for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL; + g->pico8memory = NULL; + if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) { + /* memory allocation error: free partial state */ + close_state(L); + L = NULL; + } + return L; +} + + +LUA_API void lua_close (lua_State *L) { + L = G(L)->mainthread; /* only the main thread can be closed */ + lua_lock(L); + close_state(L); +} + + diff --git a/components/pico8/femto8/src/lua/lstate.h b/components/pico8/femto8/src/lua/lstate.h new file mode 100644 index 00000000..0cd0ec37 --- /dev/null +++ b/components/pico8/femto8/src/lua/lstate.h @@ -0,0 +1,229 @@ +/* +** $Id: lstate.h,v 2.82 2012/07/02 13:37:04 roberto Exp $ +** Global State +** See Copyright Notice in lua.h +*/ + +#ifndef lstate_h +#define lstate_h + +#include "lua.h" + +#include "lobject.h" +#include "ltm.h" +#include "lzio.h" + + +/* + +** Some notes about garbage-collected objects: All objects in Lua must +** be kept somehow accessible until being freed. +** +** Lua keeps most objects linked in list g->allgc. The link uses field +** 'next' of the CommonHeader. +** +** Strings are kept in several lists headed by the array g->strt.hash. +** +** Open upvalues are not subject to independent garbage collection. They +** are collected together with their respective threads. Lua keeps a +** double-linked list with all open upvalues (g->uvhead) so that it can +** mark objects referred by them. (They are always gray, so they must +** be remarked in the atomic step. Usually their contents would be marked +** when traversing the respective threads, but the thread may already be +** dead, while the upvalue is still accessible through closures.) +** +** Objects with finalizers are kept in the list g->finobj. +** +** The list g->tobefnz links all objects being finalized. + +*/ + + +struct lua_longjmp; /* defined in ldo.c */ + + + +/* extra stack space to handle TM calls and some other extras */ +#define EXTRA_STACK 5 + + +#define BASIC_STACK_SIZE (2*LUA_MINSTACK) + + +/* kinds of Garbage Collection */ +#define KGC_NORMAL 0 +#define KGC_EMERGENCY 1 /* gc was forced by an allocation failure */ +#define KGC_GEN 2 /* generational collection */ + + +typedef struct stringtable { + GCObject **hash; + lu_int32 nuse; /* number of elements */ + int size; +} stringtable; + + +/* +** information about a call +*/ +typedef struct CallInfo { + StkId func; /* function index in the stack */ + StkId top; /* top for this function */ + struct CallInfo *previous, *next; /* dynamic call link */ + short nresults; /* expected number of results from this function */ + lu_byte callstatus; + ptrdiff_t extra; + union { + struct { /* only for Lua functions */ + StkId base; /* base for this function */ + const Instruction *savedpc; + } l; + struct { /* only for C functions */ + int ctx; /* context info. in case of yields */ + lua_CFunction k; /* continuation in case of yields */ + ptrdiff_t old_errfunc; + lu_byte old_allowhook; + lu_byte status; + } c; + } u; +} CallInfo; + + +/* +** Bits in CallInfo status +*/ +#define CIST_LUA (1<<0) /* call is running a Lua function */ +#define CIST_HOOKED (1<<1) /* call is running a debug hook */ +#define CIST_REENTRY (1<<2) /* call is running on same invocation of + luaV_execute of previous call */ +#define CIST_YIELDED (1<<3) /* call reentered after suspension */ +#define CIST_YPCALL (1<<4) /* call is a yieldable protected call */ +#define CIST_STAT (1<<5) /* call has an error status (pcall) */ +#define CIST_TAIL (1<<6) /* call was tail called */ +#define CIST_HOOKYIELD (1<<7) /* last hook called yielded */ + + +#define isLua(ci) ((ci)->callstatus & CIST_LUA) + + +/* +** `global state', shared by all threads of this state +*/ +typedef struct global_State { + lua_Alloc frealloc; /* function to reallocate memory */ + void *ud; /* auxiliary data to `frealloc' */ + lu_mem totalbytes; /* number of bytes currently allocated - GCdebt */ + l_mem GCdebt; /* bytes allocated not yet compensated by the collector */ + lu_mem GCmemtrav; /* memory traversed by the GC */ + lu_mem GCestimate; /* an estimate of the non-garbage memory in use */ + stringtable strt; /* hash table for strings */ + TValue l_registry; + unsigned int seed; /* randomized seed for hashes */ + lu_byte currentwhite; + lu_byte gcstate; /* state of garbage collector */ + lu_byte gckind; /* kind of GC running */ + lu_byte gcrunning; /* true if GC is running */ + int sweepstrgc; /* position of sweep in `strt' */ + GCObject *allgc; /* list of all collectable objects */ + GCObject *finobj; /* list of collectable objects with finalizers */ + GCObject **sweepgc; /* current position of sweep in list 'allgc' */ + GCObject **sweepfin; /* current position of sweep in list 'finobj' */ + GCObject *gray; /* list of gray objects */ + GCObject *grayagain; /* list of objects to be traversed atomically */ + GCObject *weak; /* list of tables with weak values */ + GCObject *ephemeron; /* list of ephemeron tables (weak keys) */ + GCObject *allweak; /* list of all-weak tables */ + GCObject *tobefnz; /* list of userdata to be GC */ + UpVal uvhead; /* head of double-linked list of all open upvalues */ + Mbuffer buff; /* temporary buffer for string concatenation */ + int gcpause; /* size of pause between successive GCs */ + int gcmajorinc; /* pause between major collections (only in gen. mode) */ + int gcstepmul; /* GC `granularity' */ + lua_CFunction panic; /* to be called in unprotected errors */ + lu_byte const *pico8memory; /* pointer to PICO-8 RAM */ + struct lua_State *mainthread; + const lua_Number *version; /* pointer to version number */ + TString *memerrmsg; /* memory-error message */ + TString *tmname[TM_N]; /* array with tag-method names */ + struct Table *mt[LUA_NUMTAGS]; /* metatables for basic types */ +} global_State; + + +/* +** `per thread' state +*/ +struct lua_State { + CommonHeader; + lu_byte status; + StkId top; /* first free slot in the stack */ + global_State *l_G; + CallInfo *ci; /* call info for current function */ + const Instruction *oldpc; /* last pc traced */ + StkId stack_last; /* last free slot in the stack */ + StkId stack; /* stack base */ + int stacksize; + unsigned short nny; /* number of non-yieldable calls in stack */ + unsigned short nCcalls; /* number of nested C calls */ + lu_byte hookmask; + lu_byte allowhook; + int basehookcount; + int hookcount; + lua_Hook hook; + GCObject *openupval; /* list of open upvalues in this stack */ + GCObject *gclist; + struct lua_longjmp *errorJmp; /* current error recover point */ + ptrdiff_t errfunc; /* current error handling function (stack index) */ + CallInfo base_ci; /* CallInfo for first level (C calling Lua) */ +}; + + +#define G(L) (L->l_G) + + +/* +** Union of all collectable objects +*/ +union GCObject { + GCheader gch; /* common header */ + union TString ts; + union Udata u; + union Closure cl; + struct Table h; + struct Proto p; + struct UpVal uv; + struct lua_State th; /* thread */ +}; + + +#define gch(o) (&(o)->gch) + +/* macros to convert a GCObject into a specific value */ +#define rawgco2ts(o) \ + check_exp(novariant((o)->gch.tt) == LUA_TSTRING, &((o)->ts)) +#define gco2ts(o) (&rawgco2ts(o)->tsv) +#define rawgco2u(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u)) +#define gco2u(o) (&rawgco2u(o)->uv) +#define gco2lcl(o) check_exp((o)->gch.tt == LUA_TLCL, &((o)->cl.l)) +#define gco2ccl(o) check_exp((o)->gch.tt == LUA_TCCL, &((o)->cl.c)) +#define gco2cl(o) \ + check_exp(novariant((o)->gch.tt) == LUA_TFUNCTION, &((o)->cl)) +#define gco2t(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h)) +#define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p)) +#define gco2uv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv)) +#define gco2th(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th)) + +/* macro to convert any Lua object into a GCObject */ +#define obj2gco(v) (cast(GCObject *, (v))) + + +/* actual number of total bytes allocated */ +#define gettotalbytes(g) ((g)->totalbytes + (g)->GCdebt) + +LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt); +LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); +LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L); +LUAI_FUNC void luaE_freeCI (lua_State *L); + + +#endif + diff --git a/components/pico8/femto8/src/lua/lstring.c b/components/pico8/femto8/src/lua/lstring.c new file mode 100644 index 00000000..8b5af0b2 --- /dev/null +++ b/components/pico8/femto8/src/lua/lstring.c @@ -0,0 +1,185 @@ +/* +** $Id: lstring.c,v 2.26 2013/01/08 13:50:10 roberto Exp $ +** String table (keeps all strings handled by Lua) +** See Copyright Notice in lua.h +*/ + + +#include + +#define lstring_c +#define LUA_CORE + +#include "lua.h" + +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" + + +/* +** Lua will use at most ~(2^LUAI_HASHLIMIT) bytes from a string to +** compute its hash +*/ +#if !defined(LUAI_HASHLIMIT) +#define LUAI_HASHLIMIT 5 +#endif + + +/* +** equality for long strings +*/ +int luaS_eqlngstr (TString *a, TString *b) { + size_t len = a->tsv.len; + lua_assert(a->tsv.tt == LUA_TLNGSTR && b->tsv.tt == LUA_TLNGSTR); + return (a == b) || /* same instance or... */ + ((len == b->tsv.len) && /* equal length and ... */ + (memcmp(getstr(a), getstr(b), len) == 0)); /* equal contents */ +} + + +/* +** equality for strings +*/ +int luaS_eqstr (TString *a, TString *b) { + return (a->tsv.tt == b->tsv.tt) && + (a->tsv.tt == LUA_TSHRSTR ? eqshrstr(a, b) : luaS_eqlngstr(a, b)); +} + + +unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) { + unsigned int h = seed ^ cast(unsigned int, l); + size_t l1; + size_t step = (l >> LUAI_HASHLIMIT) + 1; + for (l1 = l; l1 >= step; l1 -= step) + h = h ^ ((h<<5) + (h>>2) + cast_byte(str[l1 - 1])); + return h; +} + + +/* +** resizes the string table +*/ +void luaS_resize (lua_State *L, int newsize) { + int i; + stringtable *tb = &G(L)->strt; + /* cannot resize while GC is traversing strings */ + luaC_runtilstate(L, ~bitmask(GCSsweepstring)); + if (newsize > tb->size) { + luaM_reallocvector(L, tb->hash, tb->size, newsize, GCObject *); + for (i = tb->size; i < newsize; i++) tb->hash[i] = NULL; + } + /* rehash */ + for (i=0; isize; i++) { + GCObject *p = tb->hash[i]; + tb->hash[i] = NULL; + while (p) { /* for each node in the list */ + GCObject *next = gch(p)->next; /* save next */ + unsigned int h = lmod(gco2ts(p)->hash, newsize); /* new position */ + gch(p)->next = tb->hash[h]; /* chain it */ + tb->hash[h] = p; + resetoldbit(p); /* see MOVE OLD rule */ + p = next; + } + } + if (newsize < tb->size) { + /* shrinking slice must be empty */ + lua_assert(tb->hash[newsize] == NULL && tb->hash[tb->size - 1] == NULL); + luaM_reallocvector(L, tb->hash, tb->size, newsize, GCObject *); + } + tb->size = newsize; +} + + +/* +** creates a new string object +*/ +static TString *createstrobj (lua_State *L, const char *str, size_t l, + int tag, unsigned int h, GCObject **list) { + TString *ts; + size_t totalsize; /* total size of TString object */ + totalsize = sizeof(TString) + ((l + 1) * sizeof(char)); + ts = &luaC_newobj(L, tag, totalsize, list, 0)->ts; + ts->tsv.len = l; + ts->tsv.hash = h; + ts->tsv.extra = 0; + memcpy(ts+1, str, l*sizeof(char)); + ((char *)(ts+1))[l] = '\0'; /* ending 0 */ + return ts; +} + + +/* +** creates a new short string, inserting it into string table +*/ +static TString *newshrstr (lua_State *L, const char *str, size_t l, + unsigned int h) { + GCObject **list; /* (pointer to) list where it will be inserted */ + stringtable *tb = &G(L)->strt; + TString *s; + if (tb->nuse >= cast(lu_int32, tb->size) && tb->size <= MAX_INT/2) + luaS_resize(L, tb->size*2); /* too crowded */ + list = &tb->hash[lmod(h, tb->size)]; + s = createstrobj(L, str, l, LUA_TSHRSTR, h, list); + tb->nuse++; + return s; +} + + +/* +** checks whether short string exists and reuses it or creates a new one +*/ +static TString *internshrstr (lua_State *L, const char *str, size_t l) { + GCObject *o; + global_State *g = G(L); + unsigned int h = luaS_hash(str, l, g->seed); + for (o = g->strt.hash[lmod(h, g->strt.size)]; + o != NULL; + o = gch(o)->next) { + TString *ts = rawgco2ts(o); + if (h == ts->tsv.hash && + l == ts->tsv.len && + (memcmp(str, getstr(ts), l * sizeof(char)) == 0)) { + if (isdead(G(L), o)) /* string is dead (but was not collected yet)? */ + changewhite(o); /* resurrect it */ + return ts; + } + } + return newshrstr(L, str, l, h); /* not found; create a new string */ +} + + +/* +** new string (with explicit length) +*/ +TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { + if (l <= LUAI_MAXSHORTLEN) /* short string? */ + return internshrstr(L, str, l); + else { + if (l + 1 > (MAX_SIZET - sizeof(TString))/sizeof(char)) + luaM_toobig(L); + return createstrobj(L, str, l, LUA_TLNGSTR, G(L)->seed, NULL); + } +} + + +/* +** new zero-terminated string +*/ +TString *luaS_new (lua_State *L, const char *str) { + return luaS_newlstr(L, str, strlen(str)); +} + + +Udata *luaS_newudata (lua_State *L, size_t s, Table *e) { + Udata *u; + if (s > MAX_SIZET - sizeof(Udata)) + luaM_toobig(L); + u = &luaC_newobj(L, LUA_TUSERDATA, sizeof(Udata) + s, NULL, 0)->u; + u->uv.len = s; + u->uv.metatable = NULL; + u->uv.env = e; + return u; +} + diff --git a/components/pico8/femto8/src/lua/lstring.h b/components/pico8/femto8/src/lua/lstring.h new file mode 100644 index 00000000..d312ff3d --- /dev/null +++ b/components/pico8/femto8/src/lua/lstring.h @@ -0,0 +1,46 @@ +/* +** $Id: lstring.h,v 1.49 2012/02/01 21:57:15 roberto Exp $ +** String table (keep all strings handled by Lua) +** See Copyright Notice in lua.h +*/ + +#ifndef lstring_h +#define lstring_h + +#include "lgc.h" +#include "lobject.h" +#include "lstate.h" + + +#define sizestring(s) (sizeof(union TString)+((s)->len+1)*sizeof(char)) + +#define sizeudata(u) (sizeof(union Udata)+(u)->len) + +#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \ + (sizeof(s)/sizeof(char))-1)) + +#define luaS_fix(s) l_setbit((s)->tsv.marked, FIXEDBIT) + + +/* +** test whether a string is a reserved word +*/ +#define isreserved(s) ((s)->tsv.tt == LUA_TSHRSTR && (s)->tsv.extra > 0) + + +/* +** equality for short strings, which are always internalized +*/ +#define eqshrstr(a,b) check_exp((a)->tsv.tt == LUA_TSHRSTR, (a) == (b)) + + +LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed); +LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b); +LUAI_FUNC int luaS_eqstr (TString *a, TString *b); +LUAI_FUNC void luaS_resize (lua_State *L, int newsize); +LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e); +LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l); +LUAI_FUNC TString *luaS_new (lua_State *L, const char *str); + + +#endif diff --git a/components/pico8/femto8/src/lua/lstrlib.c b/components/pico8/femto8/src/lua/lstrlib.c new file mode 100644 index 00000000..d2df1ed0 --- /dev/null +++ b/components/pico8/femto8/src/lua/lstrlib.c @@ -0,0 +1,1041 @@ +/* +** $Id: lstrlib.c,v 1.178 2012/08/14 18:12:34 roberto Exp $ +** Standard library for string operations and pattern-matching +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include +#include +#include + +#define lstrlib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" +#include "fix32.h" + + +/* +** maximum number of captures that a pattern can do during +** pattern-matching. This limit is arbitrary. +*/ +#if !defined(LUA_MAXCAPTURES) +#define LUA_MAXCAPTURES 32 +#endif + + +/* macro to `unsign' a character */ +#define uchar(c) ((unsigned char)(c)) + + + +static int str_len (lua_State *L) { + size_t l; + luaL_checklstring(L, 1, &l); + lua_pushinteger(L, (lua_Integer)l); + return 1; +} + + +/* translate a relative string position: negative means back from end */ +static size_t posrelat (ptrdiff_t pos, size_t len) { + if (pos >= 0) return (size_t)pos; + else if (0u - (size_t)pos > len) return 0; + else return len - ((size_t)-pos) + 1; +} + + +static int str_sub (lua_State *L) { + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + size_t start = posrelat(luaL_checkinteger(L, 2), l); + size_t end = posrelat(luaL_optinteger(L, 3, -1), l); + if (start < 1) start = 1; + if (end > l) end = l; + if (start <= end) + lua_pushlstring(L, s + start - 1, end - start + 1); + else lua_pushliteral(L, ""); + return 1; +} + + +static int str_index (lua_State *L) { + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + if (lua_type(L, 2) == LUA_TNUMBER) { + int k = fix32_to_int(lua_tonumber(L, 2)); + size_t idx = k > 0 ? k - 1 : l + k; + if (idx >= l) + lua_pushnil(L); + else + lua_pushlstring(L, s + idx, 1); + return 1; + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_pushvalue(L, 2); + lua_gettable(L, -2); + lua_remove(L, -2); + return 1; +} + + +static int str_reverse (lua_State *L) { + size_t l, i; + luaL_Buffer b; + const char *s = luaL_checklstring(L, 1, &l); + char *p = luaL_buffinitsize(L, &b, l); + for (i = 0; i < l; i++) + p[i] = s[l - i - 1]; + luaL_pushresultsize(&b, l); + return 1; +} + + +static int str_lower (lua_State *L) { + size_t l; + size_t i; + luaL_Buffer b; + const char *s = luaL_checklstring(L, 1, &l); + char *p = luaL_buffinitsize(L, &b, l); + for (i=0; i> 1) + +static int str_rep (lua_State *L) { + size_t l, lsep; + const char *s = luaL_checklstring(L, 1, &l); + int n = luaL_checkint(L, 2); + const char *sep = luaL_optlstring(L, 3, "", &lsep); + if (n <= 0) lua_pushliteral(L, ""); + else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */ + return luaL_error(L, "resulting string too large"); + else { + size_t totallen = n * l + (n - 1) * lsep; + luaL_Buffer b; + char *p = luaL_buffinitsize(L, &b, totallen); + while (n-- > 1) { /* first n-1 copies (followed by separator) */ + memcpy(p, s, l * sizeof(char)); p += l; + if (lsep > 0) { /* avoid empty 'memcpy' (may be expensive) */ + memcpy(p, sep, lsep * sizeof(char)); p += lsep; + } + } + memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */ + luaL_pushresultsize(&b, totallen); + } + return 1; +} + + +static int str_byte (lua_State *L) { + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + size_t posi = posrelat(luaL_optinteger(L, 2, 1), l); + size_t pose = posrelat(luaL_optinteger(L, 3, posi), l); + int n, i; + if (posi < 1) posi = 1; + if (pose > l) pose = l; + if (posi > pose) return 0; /* empty interval; return no values */ + n = (int)(pose - posi + 1); + if (posi + n <= pose) /* (size_t -> int) overflow? */ + return luaL_error(L, "string slice too long"); + luaL_checkstack(L, n, "string slice too long"); + for (i=0; i= ms->level || ms->capture[l].len == CAP_UNFINISHED) + return luaL_error(ms->L, "invalid capture index %%%d", l + 1); + return l; +} + + +static int capture_to_close (MatchState *ms) { + int level = ms->level; + for (level--; level>=0; level--) + if (ms->capture[level].len == CAP_UNFINISHED) return level; + return luaL_error(ms->L, "invalid pattern capture"); +} + + +static const char *classend (MatchState *ms, const char *p) { + switch (*p++) { + case L_ESC: { + if (p == ms->p_end) + luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")"); + return p+1; + } + case '[': { + if (*p == '^') p++; + do { /* look for a `]' */ + if (p == ms->p_end) + luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")"); + if (*(p++) == L_ESC && p < ms->p_end) + p++; /* skip escapes (e.g. `%]') */ + } while (*p != ']'); + return p+1; + } + default: { + return p; + } + } +} + + +static int match_class (int c, int cl) { + int res; + switch (tolower(cl)) { + case 'a' : res = isalpha(c); break; + case 'c' : res = iscntrl(c); break; + case 'd' : res = isdigit(c); break; + case 'g' : res = isgraph(c); break; + case 'l' : res = islower(c); break; + case 'p' : res = ispunct(c); break; + case 's' : res = isspace(c); break; + case 'u' : res = isupper(c); break; + case 'w' : res = isalnum(c); break; + case 'x' : res = isxdigit(c); break; + case 'z' : res = (c == 0); break; /* deprecated option */ + default: return (cl == c); + } + return (islower(cl) ? res : !res); +} + + +static int matchbracketclass (int c, const char *p, const char *ec) { + int sig = 1; + if (*(p+1) == '^') { + sig = 0; + p++; /* skip the `^' */ + } + while (++p < ec) { + if (*p == L_ESC) { + p++; + if (match_class(c, uchar(*p))) + return sig; + } + else if ((*(p+1) == '-') && (p+2 < ec)) { + p+=2; + if (uchar(*(p-2)) <= c && c <= uchar(*p)) + return sig; + } + else if (uchar(*p) == c) return sig; + } + return !sig; +} + + +static int singlematch (MatchState *ms, const char *s, const char *p, + const char *ep) { + if (s >= ms->src_end) + return 0; + else { + int c = uchar(*s); + switch (*p) { + case '.': return 1; /* matches any char */ + case L_ESC: return match_class(c, uchar(*(p+1))); + case '[': return matchbracketclass(c, p, ep-1); + default: return (uchar(*p) == c); + } + } +} + + +static const char *matchbalance (MatchState *ms, const char *s, + const char *p) { + if (p >= ms->p_end - 1) + luaL_error(ms->L, "malformed pattern " + "(missing arguments to " LUA_QL("%%b") ")"); + if (*s != *p) return NULL; + else { + int b = *p; + int e = *(p+1); + int cont = 1; + while (++s < ms->src_end) { + if (*s == e) { + if (--cont == 0) return s+1; + } + else if (*s == b) cont++; + } + } + return NULL; /* string ends out of balance */ +} + + +static const char *max_expand (MatchState *ms, const char *s, + const char *p, const char *ep) { + ptrdiff_t i = 0; /* counts maximum expand for item */ + while (singlematch(ms, s + i, p, ep)) + i++; + /* keeps trying to match with the maximum repetitions */ + while (i>=0) { + const char *res = match(ms, (s+i), ep+1); + if (res) return res; + i--; /* else didn't match; reduce 1 repetition to try again */ + } + return NULL; +} + + +static const char *min_expand (MatchState *ms, const char *s, + const char *p, const char *ep) { + for (;;) { + const char *res = match(ms, s, ep+1); + if (res != NULL) + return res; + else if (singlematch(ms, s, p, ep)) + s++; /* try with one more repetition */ + else return NULL; + } +} + + +static const char *start_capture (MatchState *ms, const char *s, + const char *p, int what) { + const char *res; + int level = ms->level; + if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); + ms->capture[level].init = s; + ms->capture[level].len = what; + ms->level = level+1; + if ((res=match(ms, s, p)) == NULL) /* match failed? */ + ms->level--; /* undo capture */ + return res; +} + + +static const char *end_capture (MatchState *ms, const char *s, + const char *p) { + int l = capture_to_close(ms); + const char *res; + ms->capture[l].len = s - ms->capture[l].init; /* close capture */ + if ((res = match(ms, s, p)) == NULL) /* match failed? */ + ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ + return res; +} + + +static const char *match_capture (MatchState *ms, const char *s, int l) { + size_t len; + l = check_capture(ms, l); + len = ms->capture[l].len; + if ((size_t)(ms->src_end-s) >= len && + memcmp(ms->capture[l].init, s, len) == 0) + return s+len; + else return NULL; +} + + +static const char *match (MatchState *ms, const char *s, const char *p) { + if (ms->matchdepth-- == 0) + luaL_error(ms->L, "pattern too complex"); + init: /* using goto's to optimize tail recursion */ + if (p != ms->p_end) { /* end of pattern? */ + switch (*p) { + case '(': { /* start capture */ + if (*(p + 1) == ')') /* position capture? */ + s = start_capture(ms, s, p + 2, CAP_POSITION); + else + s = start_capture(ms, s, p + 1, CAP_UNFINISHED); + break; + } + case ')': { /* end capture */ + s = end_capture(ms, s, p + 1); + break; + } + case '$': { + if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */ + goto dflt; /* no; go to default */ + s = (s == ms->src_end) ? s : NULL; /* check end of string */ + break; + } + case L_ESC: { /* escaped sequences not in the format class[*+?-]? */ + switch (*(p + 1)) { + case 'b': { /* balanced string? */ + s = matchbalance(ms, s, p + 2); + if (s != NULL) { + p += 4; goto init; /* return match(ms, s, p + 4); */ + } /* else fail (s == NULL) */ + break; + } + case 'f': { /* frontier? */ + const char *ep; char previous; + p += 2; + if (*p != '[') + luaL_error(ms->L, "missing " LUA_QL("[") " after " + LUA_QL("%%f") " in pattern"); + ep = classend(ms, p); /* points to what is next */ + previous = (s == ms->src_init) ? '\0' : *(s - 1); + if (!matchbracketclass(uchar(previous), p, ep - 1) && + matchbracketclass(uchar(*s), p, ep - 1)) { + p = ep; goto init; /* return match(ms, s, ep); */ + } + s = NULL; /* match failed */ + break; + } + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + case '8': case '9': { /* capture results (%0-%9)? */ + s = match_capture(ms, s, uchar(*(p + 1))); + if (s != NULL) { + p += 2; goto init; /* return match(ms, s, p + 2) */ + } + break; + } + default: goto dflt; + } + break; + } + default: dflt: { /* pattern class plus optional suffix */ + const char *ep = classend(ms, p); /* points to optional suffix */ + /* does not match at least once? */ + if (!singlematch(ms, s, p, ep)) { + if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */ + p = ep + 1; goto init; /* return match(ms, s, ep + 1); */ + } + else /* '+' or no suffix */ + s = NULL; /* fail */ + } + else { /* matched once */ + switch (*ep) { /* handle optional suffix */ + case '?': { /* optional */ + const char *res; + if ((res = match(ms, s + 1, ep + 1)) != NULL) + s = res; + else { + p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */ + } + break; + } + case '+': /* 1 or more repetitions */ + s++; /* 1 match already done */ + /* go through */ + case '*': /* 0 or more repetitions */ + s = max_expand(ms, s, p, ep); + break; + case '-': /* 0 or more repetitions (minimum) */ + s = min_expand(ms, s, p, ep); + break; + default: /* no suffix */ + s++; p = ep; goto init; /* return match(ms, s + 1, ep); */ + } + } + break; + } + } + } + ms->matchdepth++; + return s; +} + + + +static const char *lmemfind (const char *s1, size_t l1, + const char *s2, size_t l2) { + if (l2 == 0) return s1; /* empty strings are everywhere */ + else if (l2 > l1) return NULL; /* avoids a negative `l1' */ + else { + const char *init; /* to search for a `*s2' inside `s1' */ + l2--; /* 1st char will be checked by `memchr' */ + l1 = l1-l2; /* `s2' cannot be found after that */ + while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { + init++; /* 1st char is already checked */ + if (memcmp(init, s2+1, l2) == 0) + return init-1; + else { /* correct `l1' and `s1' to try again */ + l1 -= init-s1; + s1 = init; + } + } + return NULL; /* not found */ + } +} + + +static void push_onecapture (MatchState *ms, int i, const char *s, + const char *e) { + if (i >= ms->level) { + if (i == 0) /* ms->level == 0, too */ + lua_pushlstring(ms->L, s, e - s); /* add whole match */ + else + luaL_error(ms->L, "invalid capture index"); + } + else { + ptrdiff_t l = ms->capture[i].len; + if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture"); + if (l == CAP_POSITION) + lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1); + else + lua_pushlstring(ms->L, ms->capture[i].init, l); + } +} + + +static int push_captures (MatchState *ms, const char *s, const char *e) { + int i; + int nlevels = (ms->level == 0 && s) ? 1 : ms->level; + luaL_checkstack(ms->L, nlevels, "too many captures"); + for (i = 0; i < nlevels; i++) + push_onecapture(ms, i, s, e); + return nlevels; /* number of strings pushed */ +} + + +/* check whether pattern has no special characters */ +static int nospecials (const char *p, size_t l) { + size_t upto = 0; + do { + if (strpbrk(p + upto, SPECIALS)) + return 0; /* pattern has a special character */ + upto += strlen(p + upto) + 1; /* may have more after \0 */ + } while (upto <= l); + return 1; /* no special chars found */ +} + + +static int str_find_aux (lua_State *L, int find) { + size_t ls, lp; + const char *s = luaL_checklstring(L, 1, &ls); + const char *p = luaL_checklstring(L, 2, &lp); + size_t init = posrelat(luaL_optinteger(L, 3, 1), ls); + if (init < 1) init = 1; + else if (init > ls + 1) { /* start after string's end? */ + lua_pushnil(L); /* cannot find anything */ + return 1; + } + /* explicit request or no special characters? */ + if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) { + /* do a plain search */ + const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp); + if (s2) { + lua_pushinteger(L, s2 - s + 1); + lua_pushinteger(L, s2 - s + lp); + return 2; + } + } + else { + MatchState ms; + const char *s1 = s + init - 1; + int anchor = (*p == '^'); + if (anchor) { + p++; lp--; /* skip anchor character */ + } + ms.L = L; + ms.matchdepth = MAXCCALLS; + ms.src_init = s; + ms.src_end = s + ls; + ms.p_end = p + lp; + do { + const char *res; + ms.level = 0; + lua_assert(ms.matchdepth == MAXCCALLS); + if ((res=match(&ms, s1, p)) != NULL) { + if (find) { + lua_pushinteger(L, s1 - s + 1); /* start */ + lua_pushinteger(L, res - s); /* end */ + return push_captures(&ms, NULL, 0) + 2; + } + else + return push_captures(&ms, s1, res); + } + } while (s1++ < ms.src_end && !anchor); + } + lua_pushnil(L); /* not found */ + return 1; +} + + +static int str_find (lua_State *L) { + return str_find_aux(L, 1); +} + + +static int str_match (lua_State *L) { + return str_find_aux(L, 0); +} + + +static int gmatch_aux (lua_State *L) { + MatchState ms; + size_t ls, lp; + const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls); + const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp); + const char *src; + ms.L = L; + ms.matchdepth = MAXCCALLS; + ms.src_init = s; + ms.src_end = s+ls; + ms.p_end = p + lp; + for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3)); + src <= ms.src_end; + src++) { + const char *e; + ms.level = 0; + lua_assert(ms.matchdepth == MAXCCALLS); + if ((e = match(&ms, src, p)) != NULL) { + lua_Integer newstart = e-s; + if (e == src) newstart++; /* empty match? go at least one position */ + lua_pushinteger(L, newstart); + lua_replace(L, lua_upvalueindex(3)); + return push_captures(&ms, src, e); + } + } + return 0; /* not found */ +} + + +static int gmatch (lua_State *L) { + luaL_checkstring(L, 1); + luaL_checkstring(L, 2); + lua_settop(L, 2); + lua_pushinteger(L, 0); + lua_pushcclosure(L, gmatch_aux, 3); + return 1; +} + + +static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, + const char *e) { + size_t l, i; + const char *news = lua_tolstring(ms->L, 3, &l); + for (i = 0; i < l; i++) { + if (news[i] != L_ESC) + luaL_addchar(b, news[i]); + else { + i++; /* skip ESC */ + if (!isdigit(uchar(news[i]))) { + if (news[i] != L_ESC) + luaL_error(ms->L, "invalid use of " LUA_QL("%c") + " in replacement string", L_ESC); + luaL_addchar(b, news[i]); + } + else if (news[i] == '0') + luaL_addlstring(b, s, e - s); + else { + push_onecapture(ms, news[i] - '1', s, e); + luaL_addvalue(b); /* add capture to accumulated result */ + } + } + } +} + + +static void add_value (MatchState *ms, luaL_Buffer *b, const char *s, + const char *e, int tr) { + lua_State *L = ms->L; + switch (tr) { + case LUA_TFUNCTION: { + int n; + lua_pushvalue(L, 3); + n = push_captures(ms, s, e); + lua_call(L, n, 1); + break; + } + case LUA_TTABLE: { + push_onecapture(ms, 0, s, e); + lua_gettable(L, 3); + break; + } + default: { /* LUA_TNUMBER or LUA_TSTRING */ + add_s(ms, b, s, e); + return; + } + } + if (!lua_toboolean(L, -1)) { /* nil or false? */ + lua_pop(L, 1); + lua_pushlstring(L, s, e - s); /* keep original text */ + } + else if (!lua_isstring(L, -1)) + luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); + luaL_addvalue(b); /* add result to accumulator */ +} + + +static int str_gsub (lua_State *L) { + size_t srcl, lp; + const char *src = luaL_checklstring(L, 1, &srcl); + const char *p = luaL_checklstring(L, 2, &lp); + int tr = lua_type(L, 3); + size_t max_s = luaL_optinteger(L, 4, srcl+1); + int anchor = (*p == '^'); + size_t n = 0; + MatchState ms; + luaL_Buffer b; + luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || + tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, + "string/function/table expected"); + luaL_buffinit(L, &b); + if (anchor) { + p++; lp--; /* skip anchor character */ + } + ms.L = L; + ms.matchdepth = MAXCCALLS; + ms.src_init = src; + ms.src_end = src+srcl; + ms.p_end = p + lp; + while (n < max_s) { + const char *e; + ms.level = 0; + lua_assert(ms.matchdepth == MAXCCALLS); + e = match(&ms, src, p); + if (e) { + n++; + add_value(&ms, &b, src, e, tr); + } + if (e && e>src) /* non empty match? */ + src = e; /* skip it */ + else if (src < ms.src_end) + luaL_addchar(&b, *src++); + else break; + if (anchor) break; + } + luaL_addlstring(&b, src, ms.src_end-src); + luaL_pushresult(&b); + lua_pushinteger(L, n); /* number of substitutions */ + return 2; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** STRING FORMAT +** ======================================================= +*/ + +/* +** LUA_INTFRMLEN is the length modifier for integer conversions in +** 'string.format'; LUA_INTFRM_T is the integer type corresponding to +** the previous length +*/ +#if !defined(LUA_INTFRMLEN) /* { */ +#if defined(LUA_USE_LONGLONG) + +#define LUA_INTFRMLEN "ll" +#define LUA_INTFRM_T long long + +#else + +#define LUA_INTFRMLEN "l" +#define LUA_INTFRM_T long + +#endif +#endif /* } */ + + +/* +** LUA_FLTFRMLEN is the length modifier for float conversions in +** 'string.format'; LUA_FLTFRM_T is the float type corresponding to +** the previous length +*/ +#if !defined(LUA_FLTFRMLEN) + +#define LUA_FLTFRMLEN "" +#define LUA_FLTFRM_T double + +#endif + + +/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */ +#define MAX_ITEM 512 +/* valid flags in a format specification */ +#define FLAGS "-+ #0" +/* +** maximum size of each format specification (such as '%-099.99d') +** (+10 accounts for %99.99x plus margin of error) +*/ +#define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10) + + +static void addquoted (lua_State *L, luaL_Buffer *b, int arg) { + size_t l; + const char *s = luaL_checklstring(L, arg, &l); + luaL_addchar(b, '"'); + while (l--) { + if (*s == '"' || *s == '\\' || *s == '\n') { + luaL_addchar(b, '\\'); + luaL_addchar(b, *s); + } + else if (*s == '\0' || iscntrl(uchar(*s))) { + char buff[10]; + if (!isdigit(uchar(*(s+1)))) + sprintf(buff, "\\%d", (int)uchar(*s)); + else + sprintf(buff, "\\%03d", (int)uchar(*s)); + luaL_addstring(b, buff); + } + else + luaL_addchar(b, *s); + s++; + } + luaL_addchar(b, '"'); +} + +static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { + const char *p = strfrmt; + while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */ + if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char)) + luaL_error(L, "invalid format (repeated flags)"); + if (isdigit(uchar(*p))) p++; /* skip width */ + if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ + if (*p == '.') { + p++; + if (isdigit(uchar(*p))) p++; /* skip precision */ + if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ + } + if (isdigit(uchar(*p))) + luaL_error(L, "invalid format (width or precision too long)"); + *(form++) = '%'; + memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char)); + form += p - strfrmt + 1; + *form = '\0'; + return p; +} + + +/* +** add length modifier into formats +*/ +static void addlenmod (char *form, const char *lenmod) { + size_t l = strlen(form); + size_t lm = strlen(lenmod); + char spec = form[l - 1]; + strcpy(form + l - 1, lenmod); + form[l + lm - 1] = spec; + form[l + lm] = '\0'; +} + + +static int str_format (lua_State *L) { + int top = lua_gettop(L); + int arg = 1; + size_t sfl; + const char *strfrmt = luaL_checklstring(L, arg, &sfl); + const char *strfrmt_end = strfrmt+sfl; + luaL_Buffer b; + luaL_buffinit(L, &b); + while (strfrmt < strfrmt_end) { + if (*strfrmt != L_ESC) + luaL_addchar(&b, *strfrmt++); + else if (*++strfrmt == L_ESC) + luaL_addchar(&b, *strfrmt++); /* %% */ + else { /* format item */ + char form[MAX_FORMAT]; /* to store the format (`%...') */ + char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */ + int nb = 0; /* number of bytes in added item */ + if (++arg > top) + luaL_argerror(L, arg, "no value"); + strfrmt = scanformat(L, strfrmt, form); + switch (*strfrmt++) { + case 'c': { + nb = sprintf(buff, form, luaL_checkint(L, arg)); + break; + } + case 'd': case 'i': { + lua_Number n = luaL_checknumber(L, arg); + LUA_INTFRM_T ni = (LUA_INTFRM_T)fix32_to_int(n); + lua_Number diff = fix32_sub(n, fix32_from_int((int)(int16_t)ni)); + luaL_argcheck(L, fix32_lt(fix32_from_int(-1), diff) && fix32_lt(diff, fix32_from_int(1)), arg, + "not a number in proper range"); + addlenmod(form, LUA_INTFRMLEN); + nb = sprintf(buff, form, ni); + break; + } + case 'o': case 'u': case 'x': case 'X': { + lua_Number n = luaL_checknumber(L, arg); + unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)(unsigned)fix32_to_int(n); + lua_Number diff = fix32_sub(n, fix32_from_int((int)(uint16_t)ni)); + luaL_argcheck(L, fix32_lt(fix32_from_int(-1), diff) && fix32_lt(diff, fix32_from_int(1)), arg, + "not a non-negative number in proper range"); + addlenmod(form, LUA_INTFRMLEN); + nb = sprintf(buff, form, ni); + break; + } + case 'e': case 'E': case 'f': +#if defined(LUA_USE_AFORMAT) + case 'a': case 'A': +#endif + case 'g': case 'G': { + addlenmod(form, LUA_FLTFRMLEN); + nb = sprintf(buff, form, (LUA_FLTFRM_T)fix32_to_double(luaL_checknumber(L, arg))); + break; + } + case 'q': { + addquoted(L, &b, arg); + break; + } + case 's': { + size_t l; + const char *s = luaL_tolstring(L, arg, &l); + if (!strchr(form, '.') && l >= 100) { + /* no precision and string is too long to be formatted; + keep original string */ + luaL_addvalue(&b); + break; + } + else { + nb = sprintf(buff, form, s); + lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ + break; + } + } + default: { /* also treat cases `pnLlh' */ + return luaL_error(L, "invalid option " LUA_QL("%%%c") " to " + LUA_QL("format"), *(strfrmt - 1)); + } + } + luaL_addsize(&b, nb); + } + } + luaL_pushresult(&b); + return 1; +} + +/* }====================================================== */ + + +static const luaL_Reg strlib[] = { + {"byte", str_byte}, + {"char", str_char}, + {"dump", str_dump}, + {"find", str_find}, + {"format", str_format}, + {"gmatch", gmatch}, + {"gsub", str_gsub}, + {"len", str_len}, + {"lower", str_lower}, + {"match", str_match}, + {"rep", str_rep}, + {"reverse", str_reverse}, + {"sub", str_sub}, + {"upper", str_upper}, + {NULL, NULL} +}; + + +static void createmetatable (lua_State *L) { + lua_createtable(L, 0, 1); /* table to be metatable for strings */ + lua_pushliteral(L, ""); /* dummy string */ + lua_pushvalue(L, -2); /* copy table */ + lua_setmetatable(L, -2); /* set table as metatable for strings */ + lua_pop(L, 1); /* pop dummy string */ + lua_pushvalue(L, -2); /* get string library */ + lua_pushcclosure(L, str_index, 1); + lua_setfield(L, -2, "__index"); /* numeric indexing plus string methods */ + lua_pop(L, 1); /* pop metatable */ +} + + +/* +** Open string library +*/ +LUAMOD_API int luaopen_string (lua_State *L) { + luaL_newlib(L, strlib); + createmetatable(L); + return 1; +} + diff --git a/components/pico8/femto8/src/lua/ltable.c b/components/pico8/femto8/src/lua/ltable.c new file mode 100644 index 00000000..4532cc80 --- /dev/null +++ b/components/pico8/femto8/src/lua/ltable.c @@ -0,0 +1,588 @@ +/* +** $Id: ltable.c,v 2.72 2012/09/11 19:37:16 roberto Exp $ +** Lua tables (hash) +** See Copyright Notice in lua.h +*/ + + +/* +** Implementation of tables (aka arrays, objects, or hash tables). +** Tables keep its elements in two parts: an array part and a hash part. +** Non-negative integer keys are all candidates to be kept in the array +** part. The actual size of the array is the largest `n' such that at +** least half the slots between 0 and n are in use. +** Hash uses a mix of chained scatter table with Brent's variation. +** A main invariant of these tables is that, if an element is not +** in its main position (i.e. the `original' position that its hash gives +** to it), then the colliding element is in its own main position. +** Hence even when the load factor reaches 100%, performance remains good. +*/ + +#include + +#define ltable_c +#define LUA_CORE + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "lvm.h" + + +/* +** max size of array part is 2^MAXBITS +*/ +#if LUAI_BITSINT >= 32 +#define MAXBITS 30 +#else +#define MAXBITS (LUAI_BITSINT-2) +#endif + +#define MAXASIZE (1 << MAXBITS) + + +#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) + +#define hashstr(t,str) hashpow2(t, (str)->tsv.hash) +#define hashboolean(t,p) hashpow2(t, p) + + +/* +** for some types, it is better to avoid modulus by power of 2, as +** they tend to have many 2 factors. +*/ +#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) + + +#define hashpointer(t,p) hashmod(t, IntPoint(p)) + + +#define dummynode (&dummynode_) + +#define isdummy(n) ((n) == dummynode) + +static const Node dummynode_ = { + {NILCONSTANT}, /* value */ + {{NILCONSTANT, NULL}} /* key */ +}; + + +/* +** hash for lua_Numbers +*/ +static Node *hashnum (const Table *t, lua_Number n) { + int i; + luai_hashnum(i, n); + if (i < 0) { + if (cast(unsigned int, i) == 0u - i) /* use unsigned to avoid overflows */ + i = 0; /* handle INT_MIN */ + i = -i; /* must be a positive value */ + } + return hashmod(t, i); +} + + + +/* +** returns the `main' position of an element in a table (that is, the index +** of its hash value) +*/ +static Node *mainposition (const Table *t, const TValue *key) { + switch (ttype(key)) { + case LUA_TNUMBER: + return hashnum(t, nvalue(key)); + case LUA_TLNGSTR: { + TString *s = rawtsvalue(key); + if (s->tsv.extra == 0) { /* no hash? */ + s->tsv.hash = luaS_hash(getstr(s), s->tsv.len, s->tsv.hash); + s->tsv.extra = 1; /* now it has its hash */ + } + return hashstr(t, rawtsvalue(key)); + } + case LUA_TSHRSTR: + return hashstr(t, rawtsvalue(key)); + case LUA_TBOOLEAN: + return hashboolean(t, bvalue(key)); + case LUA_TLIGHTUSERDATA: + return hashpointer(t, pvalue(key)); + case LUA_TLCF: + return hashpointer(t, fvalue(key)); + default: + return hashpointer(t, gcvalue(key)); + } +} + + +/* +** returns the index for `key' if `key' is an appropriate key to live in +** the array part of the table, -1 otherwise. +*/ +static int arrayindex (const TValue *key) { + if (ttisnumber(key)) { + lua_Number n = nvalue(key); + int k; + lua_number2int(k, n); + if (luai_numeq(cast_num(k), n)) + return k; + } + return -1; /* `key' did not match some condition */ +} + + +/* +** returns the index of a `key' for table traversals. First goes all +** elements in the array part, then elements in the hash part. The +** beginning of a traversal is signaled by -1. +*/ +static int findindex (lua_State *L, Table *t, StkId key) { + int i; + if (ttisnil(key)) return -1; /* first iteration */ + i = arrayindex(key); + if (0 < i && i <= t->sizearray) /* is `key' inside array part? */ + return i-1; /* yes; that's the index (corrected to C) */ + else { + Node *n = mainposition(t, key); + for (;;) { /* check whether `key' is somewhere in the chain */ + /* key may be dead already, but it is ok to use it in `next' */ + if (luaV_rawequalobj(gkey(n), key) || + (ttisdeadkey(gkey(n)) && iscollectable(key) && + deadvalue(gkey(n)) == gcvalue(key))) { + i = cast_int(n - gnode(t, 0)); /* key index in hash table */ + /* hash elements are numbered after array ones */ + return i + t->sizearray; + } + else n = gnext(n); + if (n == NULL) + luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */ + } + } +} + + +int luaH_next (lua_State *L, Table *t, StkId key) { + int i = findindex(L, t, key); /* find original element */ + for (i++; i < t->sizearray; i++) { /* try first array part */ + if (!ttisnil(&t->array[i])) { /* a non-nil value? */ + setnvalue(key, cast_num(i+1)); + setobj2s(L, key+1, &t->array[i]); + return 1; + } + } + for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */ + if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ + setobj2s(L, key, gkey(gnode(t, i))); + setobj2s(L, key+1, gval(gnode(t, i))); + return 1; + } + } + return 0; /* no more elements */ +} + + +/* +** {============================================================= +** Rehash +** ============================================================== +*/ + + +static int computesizes (int nums[], int *narray) { + int i; + int twotoi; /* 2^i */ + int a = 0; /* number of elements smaller than 2^i */ + int na = 0; /* number of elements to go to array part */ + int n = 0; /* optimal size for array part */ + for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) { + if (nums[i] > 0) { + a += nums[i]; + if (a > twotoi/2) { /* more than half elements present? */ + n = twotoi; /* optimal size (till now) */ + na = a; /* all elements smaller than n will go to array part */ + } + } + if (a == *narray) break; /* all elements already counted */ + } + *narray = n; + lua_assert(*narray/2 <= na && na <= *narray); + return na; +} + + +static int countint (const TValue *key, int *nums) { + int k = arrayindex(key); + if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */ + nums[luaO_ceillog2(k)]++; /* count as such */ + return 1; + } + else + return 0; +} + + +static int numusearray (const Table *t, int *nums) { + int lg; + int ttlg; /* 2^lg */ + int ause = 0; /* summation of `nums' */ + int i = 1; /* count to traverse all array keys */ + for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */ + int lc = 0; /* counter */ + int lim = ttlg; + if (lim > t->sizearray) { + lim = t->sizearray; /* adjust upper limit */ + if (i > lim) + break; /* no more elements to count */ + } + /* count elements in range (2^(lg-1), 2^lg] */ + for (; i <= lim; i++) { + if (!ttisnil(&t->array[i-1])) + lc++; + } + nums[lg] += lc; + ause += lc; + } + return ause; +} + + +static int numusehash (const Table *t, int *nums, int *pnasize) { + int totaluse = 0; /* total number of elements */ + int ause = 0; /* summation of `nums' */ + int i = sizenode(t); + while (i--) { + Node *n = &t->node[i]; + if (!ttisnil(gval(n))) { + ause += countint(gkey(n), nums); + totaluse++; + } + } + *pnasize += ause; + return totaluse; +} + + +static void setarrayvector (lua_State *L, Table *t, int size) { + int i; + luaM_reallocvector(L, t->array, t->sizearray, size, TValue); + for (i=t->sizearray; iarray[i]); + t->sizearray = size; +} + + +static void setnodevector (lua_State *L, Table *t, int size) { + int lsize; + if (size == 0) { /* no elements to hash part? */ + t->node = cast(Node *, dummynode); /* use common `dummynode' */ + lsize = 0; + } + else { + int i; + lsize = luaO_ceillog2(size); + if (lsize > MAXBITS) + luaG_runerror(L, "table overflow"); + size = twoto(lsize); + t->node = luaM_newvector(L, size, Node); + for (i=0; ilsizenode = cast_byte(lsize); + t->lastfree = gnode(t, size); /* all positions are free */ +} + + +void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) { + int i; + int oldasize = t->sizearray; + int oldhsize = t->lsizenode; + Node *nold = t->node; /* save old hash ... */ + if (nasize > oldasize) /* array part must grow? */ + setarrayvector(L, t, nasize); + /* create new hash part with appropriate size */ + setnodevector(L, t, nhsize); + if (nasize < oldasize) { /* array part must shrink? */ + t->sizearray = nasize; + /* re-insert elements from vanishing slice */ + for (i=nasize; iarray[i])) + luaH_setint(L, t, i + 1, &t->array[i]); + } + /* shrink array */ + luaM_reallocvector(L, t->array, oldasize, nasize, TValue); + } + /* re-insert elements from hash part */ + for (i = twoto(oldhsize) - 1; i >= 0; i--) { + Node *old = nold+i; + if (!ttisnil(gval(old))) { + /* doesn't need barrier/invalidate cache, as entry was + already present in the table */ + setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old)); + } + } + if (!isdummy(nold)) + luaM_freearray(L, nold, cast(size_t, twoto(oldhsize))); /* free old array */ +} + + +void luaH_resizearray (lua_State *L, Table *t, int nasize) { + int nsize = isdummy(t->node) ? 0 : sizenode(t); + luaH_resize(L, t, nasize, nsize); +} + + +static void rehash (lua_State *L, Table *t, const TValue *ek) { + int nasize, na; + int nums[MAXBITS+1]; /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */ + int i; + int totaluse; + for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */ + nasize = numusearray(t, nums); /* count keys in array part */ + totaluse = nasize; /* all those keys are integer keys */ + totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */ + /* count extra key */ + nasize += countint(ek, nums); + totaluse++; + /* compute new size for array part */ + na = computesizes(nums, &nasize); + /* resize the table to new computed sizes */ + luaH_resize(L, t, nasize, totaluse - na); +} + + + +/* +** }============================================================= +*/ + + +Table *luaH_new (lua_State *L) { + Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table), NULL, 0)->h; + t->metatable = NULL; + t->flags = cast_byte(~0); + t->array = NULL; + t->sizearray = 0; + setnodevector(L, t, 0); + return t; +} + + +void luaH_free (lua_State *L, Table *t) { + if (!isdummy(t->node)) + luaM_freearray(L, t->node, cast(size_t, sizenode(t))); + luaM_freearray(L, t->array, t->sizearray); + luaM_free(L, t); +} + + +static Node *getfreepos (Table *t) { + while (t->lastfree > t->node) { + t->lastfree--; + if (ttisnil(gkey(t->lastfree))) + return t->lastfree; + } + return NULL; /* could not find a free place */ +} + + + +/* +** inserts a new key into a hash table; first, check whether key's main +** position is free. If not, check whether colliding node is in its main +** position or not: if it is not, move colliding node to an empty place and +** put new key in its main position; otherwise (colliding node is in its main +** position), new key goes to an empty position. +*/ +TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) { + Node *mp; + if (ttisnil(key)) luaG_runerror(L, "table index is nil"); + else if (ttisnumber(key) && luai_numisnan(L, nvalue(key))) + luaG_runerror(L, "table index is NaN"); + mp = mainposition(t, key); + if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */ + Node *othern; + Node *n = getfreepos(t); /* get a free place */ + if (n == NULL) { /* cannot find a free place? */ + rehash(L, t, key); /* grow table */ + /* whatever called 'newkey' take care of TM cache and GC barrier */ + return luaH_set(L, t, key); /* insert key into grown table */ + } + lua_assert(!isdummy(n)); + othern = mainposition(t, gkey(mp)); + if (othern != mp) { /* is colliding node out of its main position? */ + /* yes; move colliding node into free position */ + while (gnext(othern) != mp) othern = gnext(othern); /* find previous */ + gnext(othern) = n; /* redo the chain with `n' in place of `mp' */ + *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */ + gnext(mp) = NULL; /* now `mp' is free */ + setnilvalue(gval(mp)); + } + else { /* colliding node is in its own main position */ + /* new node will go into free position */ + gnext(n) = gnext(mp); /* chain new position */ + gnext(mp) = n; + mp = n; + } + } + setobj2t(L, gkey(mp), key); + luaC_barrierback(L, obj2gco(t), key); + lua_assert(ttisnil(gval(mp))); + return gval(mp); +} + + +/* +** search function for integers +*/ +const TValue *luaH_getint (Table *t, int key) { + /* (1 <= key && key <= t->sizearray) */ + if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray)) + return &t->array[key-1]; + else { + lua_Number nk = cast_num(key); + Node *n = hashnum(t, nk); + do { /* check whether `key' is somewhere in the chain */ + if (ttisnumber(gkey(n)) && luai_numeq((lua_Number)nvalue(gkey(n)), nk)) + return gval(n); /* that's it */ + else n = gnext(n); + } while (n); + return luaO_nilobject; + } +} + + +/* +** search function for short strings +*/ +const TValue *luaH_getstr (Table *t, TString *key) { + Node *n = hashstr(t, key); + lua_assert(key->tsv.tt == LUA_TSHRSTR); + do { /* check whether `key' is somewhere in the chain */ + if (ttisshrstring(gkey(n)) && eqshrstr(rawtsvalue(gkey(n)), key)) + return gval(n); /* that's it */ + else n = gnext(n); + } while (n); + return luaO_nilobject; +} + + +/* +** main search function +*/ +const TValue *luaH_get (Table *t, const TValue *key) { + switch (ttype(key)) { + case LUA_TSHRSTR: return luaH_getstr(t, rawtsvalue(key)); + case LUA_TNIL: return luaO_nilobject; + case LUA_TNUMBER: { + int k; + lua_Number n = nvalue(key); + lua_number2int(k, n); + if (luai_numeq(cast_num(k), n)) /* index is int? */ + return luaH_getint(t, k); /* use specialized version */ + /* else go through */ + } + default: { + Node *n = mainposition(t, key); + do { /* check whether `key' is somewhere in the chain */ + if (luaV_rawequalobj(gkey(n), key)) + return gval(n); /* that's it */ + else n = gnext(n); + } while (n); + return luaO_nilobject; + } + } +} + + +/* +** beware: when using this function you probably need to check a GC +** barrier and invalidate the TM cache. +*/ +TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { + const TValue *p = luaH_get(t, key); + if (p != luaO_nilobject) + return cast(TValue *, p); + else return luaH_newkey(L, t, key); +} + + +void luaH_setint (lua_State *L, Table *t, int key, TValue *value) { + const TValue *p = luaH_getint(t, key); + TValue *cell; + if (p != luaO_nilobject) + cell = cast(TValue *, p); + else { + TValue k; + setnvalue(&k, cast_num(key)); + cell = luaH_newkey(L, t, &k); + } + setobj2t(L, cell, value); +} + + +static int unbound_search (Table *t, unsigned int j) { + unsigned int i = j; /* i is zero or a present index */ + j++; + /* find `i' and `j' such that i is present and j is not */ + while (!ttisnil(luaH_getint(t, j))) { + i = j; + j *= 2; + if (j > cast(unsigned int, MAX_INT)) { /* overflow? */ + /* table was built with bad purposes: resort to linear search */ + i = 1; + while (!ttisnil(luaH_getint(t, i))) i++; + return i - 1; + } + } + /* now do a binary search between them */ + while (j - i > 1) { + unsigned int m = (i+j)/2; + if (ttisnil(luaH_getint(t, m))) j = m; + else i = m; + } + return i; +} + + +/* +** Try to find a boundary in table `t'. A `boundary' is an integer index +** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil). +*/ +int luaH_getn (Table *t) { + unsigned int j = t->sizearray; + if (j > 0 && ttisnil(&t->array[j - 1])) { + /* there is a boundary in the array part: (binary) search for it */ + unsigned int i = 0; + while (j - i > 1) { + unsigned int m = (i+j)/2; + if (ttisnil(&t->array[m - 1])) j = m; + else i = m; + } + return i; + } + /* else must find a boundary in hash part */ + else if (isdummy(t->node)) /* hash part is empty? */ + return j; /* that is easy... */ + else return unbound_search(t, j); +} + + + +#if defined(LUA_DEBUG) + +Node *luaH_mainposition (const Table *t, const TValue *key) { + return mainposition(t, key); +} + +int luaH_isdummy (Node *n) { return isdummy(n); } + +#endif diff --git a/components/pico8/femto8/src/lua/ltable.h b/components/pico8/femto8/src/lua/ltable.h new file mode 100644 index 00000000..b28b6e62 --- /dev/null +++ b/components/pico8/femto8/src/lua/ltable.h @@ -0,0 +1,45 @@ +/* +** $Id: ltable.h,v 2.16.1.1 2013/04/12 18:48:47 roberto Exp roberto $ +** Lua tables (hash) +** See Copyright Notice in lua.h +*/ + +#ifndef ltable_h +#define ltable_h + +#include "lobject.h" + + +#define gnode(t,i) (&(t)->node[i]) +#define gkey(n) (&(n)->i_key.tvk) +#define gval(n) (&(n)->i_val) +#define gnext(n) ((n)->i_key.nk.next) + +#define invalidateTMcache(t) ((t)->flags = 0) + +/* returns the key, given the value of a table entry */ +#define keyfromval(v) \ + (gkey(cast(Node *, cast(char *, (v)) - offsetof(Node, i_val)))) + + +LUAI_FUNC const TValue *luaH_getint (Table *t, int key); +LUAI_FUNC void luaH_setint (lua_State *L, Table *t, int key, TValue *value); +LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); +LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); +LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key); +LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key); +LUAI_FUNC Table *luaH_new (lua_State *L); +LUAI_FUNC void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize); +LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, int nasize); +LUAI_FUNC void luaH_free (lua_State *L, Table *t); +LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key); +LUAI_FUNC int luaH_getn (Table *t); + + +#if defined(LUA_DEBUG) +LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); +LUAI_FUNC int luaH_isdummy (Node *n); +#endif + + +#endif diff --git a/components/pico8/femto8/src/lua/ltablib.c b/components/pico8/femto8/src/lua/ltablib.c new file mode 100644 index 00000000..56abfe1c --- /dev/null +++ b/components/pico8/femto8/src/lua/ltablib.c @@ -0,0 +1,285 @@ +/* +** $Id: ltablib.c,v 1.65.1.1 2013/04/12 18:48:47 roberto Exp roberto $ +** Library for Table Manipulation +** See Copyright Notice in lua.h +*/ + + +#include +#include + +#define ltablib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +#define aux_getn(L,n) (luaL_checktype(L, n, LUA_TTABLE), luaL_len(L, n)) + + + +#if defined(LUA_COMPAT_MAXN) +static int maxn (lua_State *L) { + lua_Number max = 0; + luaL_checktype(L, 1, LUA_TTABLE); + lua_pushnil(L); /* first key */ + while (lua_next(L, 1)) { + lua_pop(L, 1); /* remove value */ + if (lua_type(L, -1) == LUA_TNUMBER) { + lua_Number v = lua_tonumber(L, -1); + if (v > max) max = v; + } + } + lua_pushnumber(L, max); + return 1; +} +#endif + + +static int tinsert (lua_State *L) { + int e = aux_getn(L, 1) + 1; /* first empty element */ + int pos; /* where to insert new element */ + switch (lua_gettop(L)) { + case 2: { /* called with only 2 arguments */ + pos = e; /* insert new element at the end */ + break; + } + case 3: { + int i; + pos = luaL_checkint(L, 2); /* 2nd argument is the position */ + luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds"); + for (i = e; i > pos; i--) { /* move up elements */ + lua_rawgeti(L, 1, i-1); + lua_rawseti(L, 1, i); /* t[i] = t[i-1] */ + } + break; + } + default: { + return luaL_error(L, "wrong number of arguments to " LUA_QL("insert")); + } + } + lua_rawseti(L, 1, pos); /* t[pos] = v */ + return 0; +} + + +static int tremove (lua_State *L) { + int size = aux_getn(L, 1); + int pos = luaL_optint(L, 2, size); + if (pos != size) /* validate 'pos' if given */ + luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds"); + lua_rawgeti(L, 1, pos); /* result = t[pos] */ + for ( ; pos < size; pos++) { + lua_rawgeti(L, 1, pos+1); + lua_rawseti(L, 1, pos); /* t[pos] = t[pos+1] */ + } + lua_pushnil(L); + lua_rawseti(L, 1, pos); /* t[pos] = nil */ + return 1; +} + + +static void addfield (lua_State *L, luaL_Buffer *b, int i) { + lua_rawgeti(L, 1, i); + if (!lua_isstring(L, -1)) + luaL_error(L, "invalid value (%s) at index %d in table for " + LUA_QL("concat"), luaL_typename(L, -1), i); + luaL_addvalue(b); +} + + +static int tconcat (lua_State *L) { + luaL_Buffer b; + size_t lsep; + int i, last; + const char *sep = luaL_optlstring(L, 2, "", &lsep); + luaL_checktype(L, 1, LUA_TTABLE); + i = luaL_optint(L, 3, 1); + last = luaL_opt(L, luaL_checkint, 4, luaL_len(L, 1)); + luaL_buffinit(L, &b); + for (; i < last; i++) { + addfield(L, &b, i); + luaL_addlstring(&b, sep, lsep); + } + if (i == last) /* add last value (if interval was not empty) */ + addfield(L, &b, i); + luaL_pushresult(&b); + return 1; +} + + +/* +** {====================================================== +** Pack/unpack +** ======================================================= +*/ + +static int pack (lua_State *L) { + int n = lua_gettop(L); /* number of elements to pack */ + lua_createtable(L, n, 1); /* create result table */ + lua_pushinteger(L, n); + lua_setfield(L, -2, "n"); /* t.n = number of elements */ + if (n > 0) { /* at least one element? */ + int i; + lua_pushvalue(L, 1); + lua_rawseti(L, -2, 1); /* insert first element */ + lua_replace(L, 1); /* move table into index 1 */ + for (i = n; i >= 2; i--) /* assign other elements */ + lua_rawseti(L, 1, i); + } + return 1; /* return table */ +} + + +static int unpack (lua_State *L) { + int i, e; + unsigned int n; + luaL_checktype(L, 1, LUA_TTABLE); + i = luaL_optint(L, 2, 1); + e = luaL_opt(L, luaL_checkint, 3, luaL_len(L, 1)); + if (i > e) return 0; /* empty range */ + n = (unsigned int)e - (unsigned int)i; /* number of elements minus 1 */ + if (n > (INT_MAX - 10) || !lua_checkstack(L, ++n)) + return luaL_error(L, "too many results to unpack"); + lua_rawgeti(L, 1, i); /* push arg[i] (avoiding overflow problems) */ + while (i++ < e) /* push arg[i + 1...e] */ + lua_rawgeti(L, 1, i); + return n; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** Quicksort +** (based on `Algorithms in MODULA-3', Robert Sedgewick; +** Addison-Wesley, 1993.) +** ======================================================= +*/ + + +static void set2 (lua_State *L, int i, int j) { + lua_rawseti(L, 1, i); + lua_rawseti(L, 1, j); +} + +static int sort_comp (lua_State *L, int a, int b) { + if (!lua_isnil(L, 2)) { /* function? */ + int res; + lua_pushvalue(L, 2); + lua_pushvalue(L, a-1); /* -1 to compensate function */ + lua_pushvalue(L, b-2); /* -2 to compensate function and `a' */ + lua_call(L, 2, 1); + res = lua_toboolean(L, -1); + lua_pop(L, 1); + return res; + } + else /* a < b? */ + return lua_compare(L, a, b, LUA_OPLT); +} + +static void auxsort (lua_State *L, int l, int u) { + while (l < u) { /* for tail recursion */ + int i, j; + /* sort elements a[l], a[(l+u)/2] and a[u] */ + lua_rawgeti(L, 1, l); + lua_rawgeti(L, 1, u); + if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */ + set2(L, l, u); /* swap a[l] - a[u] */ + else + lua_pop(L, 2); + if (u-l == 1) break; /* only 2 elements */ + i = (l+u)/2; + lua_rawgeti(L, 1, i); + lua_rawgeti(L, 1, l); + if (sort_comp(L, -2, -1)) /* a[i]= P */ + while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) { + if (i>=u) luaL_error(L, "invalid order function for sorting"); + lua_pop(L, 1); /* remove a[i] */ + } + /* repeat --j until a[j] <= P */ + while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) { + if (j<=l) luaL_error(L, "invalid order function for sorting"); + lua_pop(L, 1); /* remove a[j] */ + } + if (j +#include +#include +#include + +#define ltests_c +#define LUA_CORE + +#include "lua.h" + +#include "lapi.h" +#include "lauxlib.h" +#include "lcode.h" +#include "lctype.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lmem.h" +#include "lopcodes.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "lualib.h" + + + +/* +** The whole module only makes sense with LUA_DEBUG on +*/ +#if defined(LUA_DEBUG) + + +void *l_Trick = 0; + + +int islocked = 0; + + +#define obj_at(L,k) (L->ci->func + (k)) + + +static void setnameval (lua_State *L, const char *name, int val) { + lua_pushstring(L, name); + lua_pushinteger(L, val); + lua_settable(L, -3); +} + + +static void pushobject (lua_State *L, const TValue *o) { + setobj2s(L, L->top, o); + api_incr_top(L); +} + + +static int tpanic (lua_State *L) { + fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n", + lua_tostring(L, -1)); + return (exit(EXIT_FAILURE), 0); /* do not return to Lua */ +} + + +/* +** {====================================================================== +** Controlled version for realloc. +** ======================================================================= +*/ + +#define MARK 0x55 /* 01010101 (a nice pattern) */ + +typedef union Header { + L_Umaxalign a; /* ensures maximum alignment for Header */ + struct { + size_t size; + int type; + } d; +} Header; + + +#if !defined(EXTERNMEMCHECK) + +/* full memory check */ +#define MARKSIZE 16 /* size of marks after each block */ +#define fillmem(mem,size) memset(mem, -MARK, size) + +#else + +/* external memory check: don't do it twice */ +#define MARKSIZE 0 +#define fillmem(mem,size) /* empty */ + +#endif + + +Memcontrol l_memcontrol = + {0L, 0L, 0L, 0L, {0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L}}; + + +static void freeblock (Memcontrol *mc, Header *block) { + if (block) { + size_t size = block->d.size; + int i; + for (i = 0; i < MARKSIZE; i++) /* check marks after block */ + lua_assert(*(cast(char *, block + 1) + size + i) == MARK); + mc->objcount[block->d.type]--; + fillmem(block, sizeof(Header) + size + MARKSIZE); /* erase block */ + free(block); /* actually free block */ + mc->numblocks--; /* update counts */ + mc->total -= size; + } +} + + +void *debug_realloc (void *ud, void *b, size_t oldsize, size_t size) { + Memcontrol *mc = cast(Memcontrol *, ud); + Header *block = cast(Header *, b); + int type; + if (mc->memlimit == 0) { /* first time? */ + char *limit = getenv("MEMLIMIT"); /* initialize memory limit */ + mc->memlimit = limit ? strtoul(limit, NULL, 10) : ULONG_MAX; + } + if (block == NULL) { + type = (oldsize < LUA_NUMTAGS) ? oldsize : 0; + oldsize = 0; + } + else { + block--; /* go to real header */ + type = block->d.type; + lua_assert(oldsize == block->d.size); + } + if (size == 0) { + freeblock(mc, block); + return NULL; + } + else if (size > oldsize && mc->total+size-oldsize > mc->memlimit) + return NULL; /* fake a memory allocation error */ + else { + Header *newblock; + int i; + size_t commonsize = (oldsize < size) ? oldsize : size; + size_t realsize = sizeof(Header) + size + MARKSIZE; + if (realsize < size) return NULL; /* arithmetic overflow! */ + newblock = cast(Header *, malloc(realsize)); /* alloc a new block */ + if (newblock == NULL) return NULL; /* really out of memory? */ + if (block) { + memcpy(newblock + 1, block + 1, commonsize); /* copy old contents */ + freeblock(mc, block); /* erase (and check) old copy */ + } + /* initialize new part of the block with something `weird' */ + fillmem(cast(char *, newblock + 1) + commonsize, size - commonsize); + /* initialize marks after block */ + for (i = 0; i < MARKSIZE; i++) + *(cast(char *, newblock + 1) + size + i) = MARK; + newblock->d.size = size; + newblock->d.type = type; + mc->total += size; + if (mc->total > mc->maxmem) + mc->maxmem = mc->total; + mc->numblocks++; + mc->objcount[type]++; + return newblock + 1; + } +} + + +/* }====================================================================== */ + + + +/* +** {====================================================== +** Functions to check memory consistency +** ======================================================= +*/ + + +static int testobjref1 (global_State *g, GCObject *f, GCObject *t) { + if (isdead(g,t)) return 0; + if (!issweepphase(g)) + return !(isblack(f) && iswhite(t)); + else return 1; +} + + +static void printobj (global_State *g, GCObject *o) { + int i = 1; + GCObject *p; + for (p = g->allgc; p != o && p != NULL; p = gch(p)->next) i++; + if (p == NULL) { + i = 1; + for (p = g->finobj; p != o && p != NULL; p = gch(p)->next) i++; + if (p == NULL) i = 0; /* zero means 'not found' */ + else i = -i; /* negative means 'found in findobj list */ + } + printf("||%d:%s(%p)-%c(%02X)||", i, ttypename(gch(o)->tt), (void *)o, + isdead(g,o)?'d':isblack(o)?'b':iswhite(o)?'w':'g', gch(o)->marked); +} + + +static int testobjref (global_State *g, GCObject *f, GCObject *t) { + int r = testobjref1(g,f,t); + if (!r) { + printf("%d(%02X) - ", g->gcstate, g->currentwhite); + printobj(g, f); + printf("\t-> "); + printobj(g, t); + printf("\n"); + } + return r; +} + +#define checkobjref(g,f,t) lua_assert(testobjref(g,f,obj2gco(t))) + + +static void checkvalref (global_State *g, GCObject *f, const TValue *t) { + if (iscollectable(t)) { + lua_assert(righttt(t)); + lua_assert(testobjref(g, f, gcvalue(t))); + } +} + + +static void checktable (global_State *g, Table *h) { + int i; + Node *n, *limit = gnode(h, sizenode(h)); + GCObject *hgc = obj2gco(h); + if (h->metatable) + checkobjref(g, hgc, h->metatable); + for (i = 0; i < h->sizearray; i++) + checkvalref(g, hgc, &h->array[i]); + for (n = gnode(h, 0); n < limit; n++) { + if (!ttisnil(gval(n))) { + lua_assert(!ttisnil(gkey(n))); + checkvalref(g, hgc, gkey(n)); + checkvalref(g, hgc, gval(n)); + } + } +} + + +/* +** All marks are conditional because a GC may happen while the +** prototype is still being created +*/ +static void checkproto (global_State *g, Proto *f) { + int i; + GCObject *fgc = obj2gco(f); + if (f->source) checkobjref(g, fgc, f->source); + for (i=0; isizek; i++) { + if (ttisstring(f->k+i)) + checkobjref(g, fgc, rawtsvalue(f->k+i)); + } + for (i=0; isizeupvalues; i++) { + if (f->upvalues[i].name) + checkobjref(g, fgc, f->upvalues[i].name); + } + for (i=0; isizep; i++) { + if (f->p[i]) + checkobjref(g, fgc, f->p[i]); + } + for (i=0; isizelocvars; i++) { + if (f->locvars[i].varname) + checkobjref(g, fgc, f->locvars[i].varname); + } +} + + + +static void checkCclosure (global_State *g, CClosure *cl) { + GCObject *clgc = obj2gco(cl); + int i; + for (i = 0; i < cl->nupvalues; i++) + checkvalref(g, clgc, &cl->upvalue[i]); +} + + +static void checkLclosure (global_State *g, LClosure *cl) { + GCObject *clgc = obj2gco(cl); + int i; + if (cl->p) checkobjref(g, clgc, cl->p); + for (i=0; inupvalues; i++) { + if (cl->upvals[i]) { + lua_assert(cl->upvals[i]->tt == LUA_TUPVAL); + checkobjref(g, clgc, cl->upvals[i]); + } + } +} + + +static int lua_checkpc (pCallInfo ci) { + if (!isLua(ci)) return 1; + else { + Proto *p = ci_func(ci)->p; + return p->code <= ci->u.l.savedpc && + ci->u.l.savedpc <= p->code + p->sizecode; + } +} + + +static void checkstack (global_State *g, lua_State *L1) { + StkId o; + CallInfo *ci; + GCObject *uvo; + lua_assert(!isdead(g, obj2gco(L1))); + for (uvo = L1->openupval; uvo != NULL; uvo = gch(uvo)->next) { + UpVal *uv = gco2uv(uvo); + lua_assert(uv->v != &uv->u.value); /* must be open */ + lua_assert(!isblack(uvo)); /* open upvalues cannot be black */ + } + for (ci = L1->ci; ci != NULL; ci = ci->previous) { + lua_assert(ci->top <= L1->stack_last); + lua_assert(lua_checkpc(ci)); + } + if (L1->stack) { + for (o = L1->stack; o < L1->top; o++) + checkliveness(g, o); + } + else lua_assert(L1->stacksize == 0); +} + + +static void checkobject (global_State *g, GCObject *o, int maybedead) { + if (isdead(g, o)) + lua_assert(maybedead); + else { + if (g->gcstate == GCSpause) + lua_assert(iswhite(o)); + switch (gch(o)->tt) { + case LUA_TUPVAL: { + UpVal *uv = gco2uv(o); + lua_assert(uv->v == &uv->u.value); /* must be closed */ + lua_assert(!isgray(o)); /* closed upvalues are never gray */ + checkvalref(g, o, uv->v); + break; + } + case LUA_TUSERDATA: { + Table *mt = gco2u(o)->metatable; + if (mt) checkobjref(g, o, mt); + break; + } + case LUA_TTABLE: { + checktable(g, gco2t(o)); + break; + } + case LUA_TTHREAD: { + checkstack(g, gco2th(o)); + break; + } + case LUA_TLCL: { + checkLclosure(g, gco2lcl(o)); + break; + } + case LUA_TCCL: { + checkCclosure(g, gco2ccl(o)); + break; + } + case LUA_TPROTO: { + checkproto(g, gco2p(o)); + break; + } + case LUA_TSHRSTR: + case LUA_TLNGSTR: break; + default: lua_assert(0); + } + } +} + + +#define TESTGRAYBIT 7 + +static void checkgraylist (GCObject *l) { + while (l) { + lua_assert(isgray(l)); + lua_assert(!testbit(l->gch.marked, TESTGRAYBIT)); + l_setbit(l->gch.marked, TESTGRAYBIT); + switch (gch(l)->tt) { + case LUA_TTABLE: l = gco2t(l)->gclist; break; + case LUA_TLCL: l = gco2lcl(l)->gclist; break; + case LUA_TCCL: l = gco2ccl(l)->gclist; break; + case LUA_TTHREAD: l = gco2th(l)->gclist; break; + case LUA_TPROTO: l = gco2p(l)->gclist; break; + default: lua_assert(0); /* other objects cannot be gray */ + } + } +} + + +/* +** mark all objects in gray lists with the TESTGRAYBIT, so that +** 'checkmemory' can check that all gray objects are in a gray list +*/ +static void markgrays (global_State *g) { + if (!keepinvariant(g)) return; + checkgraylist(g->gray); + checkgraylist(g->grayagain); + checkgraylist(g->weak); + checkgraylist(g->ephemeron); + checkgraylist(g->allweak); +} + + +static void checkold (global_State *g, GCObject *o) { + int isold = 0; + for (; o != NULL; o = gch(o)->next) { + if (isold(o)) { /* old generation? */ + lua_assert(isgenerational(g)); + if (!issweepphase(g)) + isold = 1; + } + else lua_assert(!isold); /* non-old object cannot be after an old one */ + if (isgray(o)) { + lua_assert(!keepinvariant(g) || testbit(o->gch.marked, TESTGRAYBIT)); + resetbit(o->gch.marked, TESTGRAYBIT); + } + lua_assert(!testbit(o->gch.marked, TESTGRAYBIT)); + } +} + + +int lua_checkmemory (lua_State *L) { + global_State *g = G(L); + GCObject *o; + UpVal *uv; + int maybedead; + if (keepinvariant(g)) { + lua_assert(!iswhite(obj2gco(g->mainthread))); + lua_assert(!iswhite(gcvalue(&g->l_registry))); + } + else /* generational mode keeps collector in 'propagate' state */ + lua_assert(!isgenerational(g)); + lua_assert(!isdead(g, gcvalue(&g->l_registry))); + checkstack(g, g->mainthread); + resetbit(g->mainthread->marked, TESTGRAYBIT); + /* check 'allgc' list */ + markgrays(g); + checkold(g, g->allgc); + lua_assert(g->sweepgc == NULL || issweepphase(g)); + maybedead = 0; + for (o = g->allgc; o != NULL; o = gch(o)->next) { + if (g->sweepgc && o == *g->sweepgc) + maybedead = 1; /* part of the list not yet swept */ + checkobject(g, o, maybedead); + lua_assert(!testbit(o->gch.marked, SEPARATED)); + } + /* check 'finobj' list */ + checkold(g, g->finobj); + for (o = g->finobj; o != NULL; o = gch(o)->next) { + lua_assert(testbit(o->gch.marked, SEPARATED)); + lua_assert(gch(o)->tt == LUA_TUSERDATA || + gch(o)->tt == LUA_TTABLE); + checkobject(g, o, 0); + } + /* check 'tobefnz' list */ + checkold(g, g->tobefnz); + for (o = g->tobefnz; o != NULL; o = gch(o)->next) { + lua_assert(!iswhite(o) || g->gcstate == GCSpause); + lua_assert(!isdead(g, o) && testbit(o->gch.marked, SEPARATED)); + lua_assert(gch(o)->tt == LUA_TUSERDATA || + gch(o)->tt == LUA_TTABLE); + } + /* check 'uvhead' list */ + for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) { + lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); + lua_assert(uv->v != &uv->u.value); /* must be open */ + lua_assert(!isblack(obj2gco(uv))); /* open upvalues are never black */ + if (!isdead(g, obj2gco(uv))) + checkvalref(g, obj2gco(uv), uv->v); + } + return 0; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** Disassembler +** ======================================================= +*/ + + +static char *buildop (Proto *p, int pc, char *buff) { + Instruction i = p->code[pc]; + OpCode o = GET_OPCODE(i); + const char *name = luaP_opnames[o]; + int line = getfuncline(p, pc); + sprintf(buff, "(%4d) %4d - ", line, pc); + switch (getOpMode(o)) { + case iABC: + sprintf(buff+strlen(buff), "%-12s%4d %4d %4d", name, + GETARG_A(i), GETARG_B(i), GETARG_C(i)); + break; + case iABx: + sprintf(buff+strlen(buff), "%-12s%4d %4d", name, GETARG_A(i), GETARG_Bx(i)); + break; + case iAsBx: + sprintf(buff+strlen(buff), "%-12s%4d %4d", name, GETARG_A(i), GETARG_sBx(i)); + break; + case iAx: + sprintf(buff+strlen(buff), "%-12s%4d", name, GETARG_Ax(i)); + break; + } + return buff; +} + + +#if 0 +void luaI_printcode (Proto *pt, int size) { + int pc; + for (pc=0; pcmaxstacksize); + setnameval(L, "numparams", p->numparams); + for (pc=0; pcsizecode; pc++) { + char buff[100]; + lua_pushinteger(L, pc+1); + lua_pushstring(L, buildop(p, pc, buff)); + lua_settable(L, -3); + } + return 1; +} + + +static int listk (lua_State *L) { + Proto *p; + int i; + luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), + 1, "Lua function expected"); + p = getproto(obj_at(L, 1)); + lua_createtable(L, p->sizek, 0); + for (i=0; isizek; i++) { + pushobject(L, p->k+i); + lua_rawseti(L, -2, i+1); + } + return 1; +} + + +static int listlocals (lua_State *L) { + Proto *p; + int pc = luaL_checkint(L, 2) - 1; + int i = 0; + const char *name; + luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), + 1, "Lua function expected"); + p = getproto(obj_at(L, 1)); + while ((name = luaF_getlocalname(p, ++i, pc)) != NULL) + lua_pushstring(L, name); + return i-1; +} + +/* }====================================================== */ + + + + +static int get_limits (lua_State *L) { + lua_createtable(L, 0, 5); + setnameval(L, "BITS_INT", LUAI_BITSINT); + setnameval(L, "LFPF", LFIELDS_PER_FLUSH); + setnameval(L, "MAXSTACK", MAXSTACK); + setnameval(L, "NUM_OPCODES", NUM_OPCODES); + return 1; +} + + +static int mem_query (lua_State *L) { + if (lua_isnone(L, 1)) { + lua_pushinteger(L, l_memcontrol.total); + lua_pushinteger(L, l_memcontrol.numblocks); + lua_pushinteger(L, l_memcontrol.maxmem); + return 3; + } + else if (lua_isnumber(L, 1)) { + l_memcontrol.memlimit = luaL_checkint(L, 1); + return 0; + } + else { + const char *t = luaL_checkstring(L, 1); + int i; + for (i = LUA_NUMTAGS - 1; i >= 0; i--) { + if (strcmp(t, ttypename(i)) == 0) { + lua_pushinteger(L, l_memcontrol.objcount[i]); + return 1; + } + } + return luaL_error(L, "unkown type '%s'", t); + } +} + + +static int settrick (lua_State *L) { + if (ttisnil(obj_at(L, 1))) + l_Trick = NULL; + else + l_Trick = gcvalue(obj_at(L, 1)); + return 0; +} + + +static int get_gccolor (lua_State *L) { + TValue *o; + luaL_checkany(L, 1); + o = obj_at(L, 1); + if (!iscollectable(o)) + lua_pushstring(L, "no collectable"); + else { + int marked = gcvalue(o)->gch.marked; + int n = 1; + lua_pushstring(L, iswhite(gcvalue(o)) ? "white" : + isblack(gcvalue(o)) ? "black" : "grey"); + if (testbit(marked, FINALIZEDBIT)) { + lua_pushliteral(L, "/finalized"); n++; + } + if (testbit(marked, SEPARATED)) { + lua_pushliteral(L, "/separated"); n++; + } + if (testbit(marked, FIXEDBIT)) { + lua_pushliteral(L, "/fixed"); n++; + } + if (testbit(marked, OLDBIT)) { + lua_pushliteral(L, "/old"); n++; + } + lua_concat(L, n); + } + return 1; +} + + +static int gc_state (lua_State *L) { + static const char *statenames[] = {"propagate", "atomic", + "sweepstring", "sweepudata", "sweep", "pause", ""}; + int option = luaL_checkoption(L, 1, "", statenames); + if (option == GCSpause + 1) { + lua_pushstring(L, statenames[G(L)->gcstate]); + return 1; + } + else { + global_State *g = G(L); + if (g->gckind == KGC_GEN && option == GCSpause) + luaL_error(L, "cannot go to 'pause' state in generational mode"); + lua_lock(L); + if (option < g->gcstate) { /* must cross 'pause'? */ + luaC_runtilstate(L, bitmask(GCSpause)); /* run until pause */ + if (g->gckind == KGC_GEN) + g->gcstate = GCSpropagate; /* skip pause in gen. mode */ + } + luaC_runtilstate(L, bitmask(option)); + lua_assert(G(L)->gcstate == option); + lua_unlock(L); + return 0; + } +} + + +static int hash_query (lua_State *L) { + if (lua_isnone(L, 2)) { + luaL_argcheck(L, lua_type(L, 1) == LUA_TSTRING, 1, "string expected"); + lua_pushinteger(L, tsvalue(obj_at(L, 1))->hash); + } + else { + TValue *o = obj_at(L, 1); + Table *t; + luaL_checktype(L, 2, LUA_TTABLE); + t = hvalue(obj_at(L, 2)); + lua_pushinteger(L, luaH_mainposition(t, o) - t->node); + } + return 1; +} + + +static int stacklevel (lua_State *L) { + unsigned long a = 0; + lua_pushinteger(L, (L->top - L->stack)); + lua_pushinteger(L, (L->stack_last - L->stack)); + lua_pushinteger(L, (unsigned long)&a); + return 5; +} + + +static int table_query (lua_State *L) { + const Table *t; + int i = luaL_optint(L, 2, -1); + luaL_checktype(L, 1, LUA_TTABLE); + t = hvalue(obj_at(L, 1)); + if (i == -1) { + lua_pushinteger(L, t->sizearray); + lua_pushinteger(L, luaH_isdummy(t->node) ? 0 : sizenode(t)); + lua_pushinteger(L, t->lastfree - t->node); + } + else if (i < t->sizearray) { + lua_pushinteger(L, i); + pushobject(L, &t->array[i]); + lua_pushnil(L); + } + else if ((i -= t->sizearray) < sizenode(t)) { + if (!ttisnil(gval(gnode(t, i))) || + ttisnil(gkey(gnode(t, i))) || + ttisnumber(gkey(gnode(t, i)))) { + pushobject(L, gkey(gnode(t, i))); + } + else + lua_pushliteral(L, ""); + pushobject(L, gval(gnode(t, i))); + if (gnext(&t->node[i])) + lua_pushinteger(L, gnext(&t->node[i]) - t->node); + else + lua_pushnil(L); + } + return 3; +} + + +static int string_query (lua_State *L) { + stringtable *tb = &G(L)->strt; + int s = luaL_optint(L, 2, 0) - 1; + if (s==-1) { + lua_pushinteger(L ,tb->nuse); + lua_pushinteger(L ,tb->size); + return 2; + } + else if (s < tb->size) { + GCObject *ts; + int n = 0; + for (ts = tb->hash[s]; ts; ts = gch(ts)->next) { + setsvalue2s(L, L->top, rawgco2ts(ts)); + api_incr_top(L); + n++; + } + return n; + } + return 0; +} + + +static int tref (lua_State *L) { + int level = lua_gettop(L); + luaL_checkany(L, 1); + lua_pushvalue(L, 1); + lua_pushinteger(L, luaL_ref(L, LUA_REGISTRYINDEX)); + lua_assert(lua_gettop(L) == level+1); /* +1 for result */ + return 1; +} + +static int getref (lua_State *L) { + int level = lua_gettop(L); + lua_rawgeti(L, LUA_REGISTRYINDEX, luaL_checkint(L, 1)); + lua_assert(lua_gettop(L) == level+1); + return 1; +} + +static int unref (lua_State *L) { + int level = lua_gettop(L); + luaL_unref(L, LUA_REGISTRYINDEX, luaL_checkint(L, 1)); + lua_assert(lua_gettop(L) == level); + return 0; +} + + +static int upvalue (lua_State *L) { + int n = luaL_checkint(L, 2); + luaL_checktype(L, 1, LUA_TFUNCTION); + if (lua_isnone(L, 3)) { + const char *name = lua_getupvalue(L, 1, n); + if (name == NULL) return 0; + lua_pushstring(L, name); + return 2; + } + else { + const char *name = lua_setupvalue(L, 1, n); + lua_pushstring(L, name); + return 1; + } +} + + +static int newuserdata (lua_State *L) { + size_t size = luaL_checkint(L, 1); + char *p = cast(char *, lua_newuserdata(L, size)); + while (size--) *p++ = '\0'; + return 1; +} + + +static int pushuserdata (lua_State *L) { + lua_pushlightuserdata(L, cast(void *, luaL_checkinteger(L, 1))); + return 1; +} + + +static int udataval (lua_State *L) { + lua_pushinteger(L, cast(long, lua_touserdata(L, 1))); + return 1; +} + + +static int doonnewstack (lua_State *L) { + lua_State *L1 = lua_newthread(L); + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + int status = luaL_loadbuffer(L1, s, l, s); + if (status == LUA_OK) + status = lua_pcall(L1, 0, 0, 0); + lua_pushinteger(L, status); + return 1; +} + + +static int s2d (lua_State *L) { + lua_pushnumber(L, *cast(const double *, luaL_checkstring(L, 1))); + return 1; +} + + +static int d2s (lua_State *L) { + double d = luaL_checknumber(L, 1); + lua_pushlstring(L, cast(char *, &d), sizeof(d)); + return 1; +} + + +static int num2int (lua_State *L) { + lua_pushinteger(L, lua_tointeger(L, 1)); + return 1; +} + + +static int newstate (lua_State *L) { + void *ud; + lua_Alloc f = lua_getallocf(L, &ud); + lua_State *L1 = lua_newstate(f, ud); + if (L1) { + lua_atpanic(L1, tpanic); + lua_pushlightuserdata(L, L1); + } + else + lua_pushnil(L); + return 1; +} + + +static lua_State *getstate (lua_State *L) { + lua_State *L1 = cast(lua_State *, lua_touserdata(L, 1)); + luaL_argcheck(L, L1 != NULL, 1, "state expected"); + return L1; +} + + +static int loadlib (lua_State *L) { + static const luaL_Reg libs[] = { + {"_G", luaopen_base}, + {"_G", luaopen_pico8}, + {"coroutine", luaopen_coroutine}, + {"string", luaopen_string}, + {"debug", luaopen_debug}, + {"table", luaopen_table}, + {NULL, NULL} + }; + lua_State *L1 = getstate(L); + int i; + luaL_getsubtable(L1, LUA_REGISTRYINDEX, "_PRELOAD"); + for (i = 0; libs[i].name; i++) { + lua_pushcfunction(L1, libs[i].func); + lua_setfield(L1, -2, libs[i].name); + } + return 0; +} + +static int closestate (lua_State *L) { + lua_State *L1 = getstate(L); + lua_close(L1); + return 0; +} + +static int doremote (lua_State *L) { + lua_State *L1 = getstate(L); + size_t lcode; + const char *code = luaL_checklstring(L, 2, &lcode); + int status; + lua_settop(L1, 0); + status = luaL_loadbuffer(L1, code, lcode, code); + if (status == LUA_OK) + status = lua_pcall(L1, 0, LUA_MULTRET, 0); + if (status != LUA_OK) { + lua_pushnil(L); + lua_pushstring(L, lua_tostring(L1, -1)); + lua_pushinteger(L, status); + return 3; + } + else { + int i = 0; + while (!lua_isnone(L1, ++i)) + lua_pushstring(L, lua_tostring(L1, i)); + lua_pop(L1, i-1); + return i-1; + } +} + + +static int int2fb_aux (lua_State *L) { + int b = luaO_int2fb(luaL_checkint(L, 1)); + lua_pushinteger(L, b); + lua_pushinteger(L, luaO_fb2int(b)); + return 2; +} + + + +/* +** {====================================================== +** function to test the API with C. It interprets a kind of assembler +** language with calls to the API, so the test can be driven by Lua code +** ======================================================= +*/ + + +static void sethookaux (lua_State *L, int mask, int count, const char *code); + +static const char *const delimits = " \t\n,;"; + +static void skip (const char **pc) { + for (;;) { + if (**pc != '\0' && strchr(delimits, **pc)) (*pc)++; + else if (**pc == '#') { + while (**pc != '\n' && **pc != '\0') (*pc)++; + } + else break; + } +} + +static int getnum_aux (lua_State *L, lua_State *L1, const char **pc) { + int res = 0; + int sig = 1; + skip(pc); + if (**pc == '.') { + res = lua_tointeger(L1, -1); + lua_pop(L1, 1); + (*pc)++; + return res; + } + else if (**pc == '-') { + sig = -1; + (*pc)++; + } + if (!lisdigit(cast_uchar(**pc))) + luaL_error(L, "number expected (%s)", *pc); + while (lisdigit(cast_uchar(**pc))) res = res*10 + (*(*pc)++) - '0'; + return sig*res; +} + +static const char *getstring_aux (lua_State *L, char *buff, const char **pc) { + int i = 0; + skip(pc); + if (**pc == '"' || **pc == '\'') { /* quoted string? */ + int quote = *(*pc)++; + while (**pc != quote) { + if (**pc == '\0') luaL_error(L, "unfinished string in C script"); + buff[i++] = *(*pc)++; + } + (*pc)++; + } + else { + while (**pc != '\0' && !strchr(delimits, **pc)) + buff[i++] = *(*pc)++; + } + buff[i] = '\0'; + return buff; +} + + +static int getindex_aux (lua_State *L, lua_State *L1, const char **pc) { + skip(pc); + switch (*(*pc)++) { + case 'R': return LUA_REGISTRYINDEX; + case 'G': return luaL_error(L, "deprecated index 'G'"); + case 'U': return lua_upvalueindex(getnum_aux(L, L1, pc)); + default: (*pc)--; return getnum_aux(L, L1, pc); + } +} + + +static void pushcode (lua_State *L, int code) { + static const char *const codes[] = {"OK", "YIELD", "ERRRUN", + "ERRSYNTAX", "ERRMEM", "ERRGCMM", "ERRERR"}; + lua_pushstring(L, codes[code]); +} + + +#define EQ(s1) (strcmp(s1, inst) == 0) + +#define getnum (getnum_aux(L, L1, &pc)) +#define getstring (getstring_aux(L, buff, &pc)) +#define getindex (getindex_aux(L, L1, &pc)) + + +static int testC (lua_State *L); +static int Cfunck (lua_State *L); + +static int runC (lua_State *L, lua_State *L1, const char *pc) { + char buff[300]; + int status = 0; + if (pc == NULL) return luaL_error(L, "attempt to runC null script"); + for (;;) { + const char *inst = getstring; + if EQ("") return 0; + else if EQ("absindex") { + lua_pushnumber(L1, lua_absindex(L1, getindex)); + } + else if EQ("isnumber") { + lua_pushboolean(L1, lua_isnumber(L1, getindex)); + } + else if EQ("isstring") { + lua_pushboolean(L1, lua_isstring(L1, getindex)); + } + else if EQ("istable") { + lua_pushboolean(L1, lua_istable(L1, getindex)); + } + else if EQ("iscfunction") { + lua_pushboolean(L1, lua_iscfunction(L1, getindex)); + } + else if EQ("isfunction") { + lua_pushboolean(L1, lua_isfunction(L1, getindex)); + } + else if EQ("isuserdata") { + lua_pushboolean(L1, lua_isuserdata(L1, getindex)); + } + else if EQ("isudataval") { + lua_pushboolean(L1, lua_islightuserdata(L1, getindex)); + } + else if EQ("isnil") { + lua_pushboolean(L1, lua_isnil(L1, getindex)); + } + else if EQ("isnull") { + lua_pushboolean(L1, lua_isnone(L1, getindex)); + } + else if EQ("tonumber") { + lua_pushnumber(L1, lua_tonumber(L1, getindex)); + } + else if EQ("topointer") { + lua_pushnumber(L1, cast(size_t, lua_topointer(L1, getindex))); + } + else if EQ("tostring") { + const char *s = lua_tostring(L1, getindex); + const char *s1 = lua_pushstring(L1, s); + lua_assert((s == NULL && s1 == NULL) || (strcmp)(s, s1) == 0); + } + else if EQ("objsize") { + lua_pushinteger(L1, lua_rawlen(L1, getindex)); + } + else if EQ("len") { + lua_len(L1, getindex); + } + else if EQ("Llen") { + lua_pushinteger(L1, luaL_len(L1, getindex)); + } + else if EQ("tocfunction") { + lua_pushcfunction(L1, lua_tocfunction(L1, getindex)); + } + else if EQ("func2num") { + lua_CFunction func = lua_tocfunction(L1, getindex); + lua_pushnumber(L1, cast(size_t, func)); + } + else if EQ("return") { + int n = getnum; + if (L1 != L) { + int i; + for (i = 0; i < n; i++) + lua_pushstring(L, lua_tostring(L1, -(n - i))); + } + return n; + } + else if EQ("gettop") { + lua_pushinteger(L1, lua_gettop(L1)); + } + else if EQ("settop") { + lua_settop(L1, getnum); + } + else if EQ("pop") { + lua_pop(L1, getnum); + } + else if EQ("pushnum") { + lua_pushinteger(L1, getnum); + } + else if EQ("pushstring") { + lua_pushstring(L1, getstring); + } + else if EQ("pushnil") { + lua_pushnil(L1); + } + else if EQ("pushbool") { + lua_pushboolean(L1, getnum); + } + else if EQ("newtable") { + lua_newtable(L1); + } + else if EQ("newuserdata") { + lua_newuserdata(L1, getnum); + } + else if EQ("tobool") { + lua_pushboolean(L1, lua_toboolean(L1, getindex)); + } + else if EQ("pushvalue") { + lua_pushvalue(L1, getindex); + } + else if EQ("pushcclosure") { + lua_pushcclosure(L1, testC, getnum); + } + else if EQ("pushupvalueindex") { + lua_pushinteger(L1, lua_upvalueindex(getnum)); + } + else if EQ("remove") { + lua_remove(L1, getnum); + } + else if EQ("insert") { + lua_insert(L1, getnum); + } + else if EQ("replace") { + lua_replace(L1, getindex); + } + else if EQ("copy") { + int f = getindex; + lua_copy(L1, f, getindex); + } + else if EQ("gettable") { + lua_gettable(L1, getindex); + } + else if EQ("getglobal") { + lua_getglobal(L1, getstring); + } + else if EQ("getfield") { + int t = getindex; + lua_getfield(L1, t, getstring); + } + else if EQ("setfield") { + int t = getindex; + lua_setfield(L1, t, getstring); + } + else if EQ("rawgeti") { + int t = getindex; + lua_rawgeti(L1, t, getnum); + } + else if EQ("settable") { + lua_settable(L1, getindex); + } + else if EQ("setglobal") { + lua_setglobal(L1, getstring); + } + else if EQ("next") { + lua_next(L1, -2); + } + else if EQ("concat") { + lua_concat(L1, getnum); + } + else if EQ("print") { + int n = getnum; + if (n != 0) { + printf("%s\n", luaL_tolstring(L1, n, NULL)); + lua_pop(L1, 1); + } + else { + int i; + n = lua_gettop(L1); + for (i = 1; i <= n; i++) { + printf("%s ", luaL_tolstring(L1, i, NULL)); + lua_pop(L1, 1); + } + printf("\n"); + } + } + else if EQ("arith") { + static char ops[] = "+-*/%^_"; + int op; + skip(&pc); + op = strchr(ops, *pc++) - ops; + lua_arith(L1, op); + } + else if EQ("compare") { + int a = getindex; + int b = getindex; + lua_pushboolean(L1, lua_compare(L1, a, b, getnum)); + } + else if EQ("call") { + int narg = getnum; + int nres = getnum; + lua_call(L1, narg, nres); + } + else if EQ("pcall") { + int narg = getnum; + int nres = getnum; + status = lua_pcall(L1, narg, nres, 0); + } + else if EQ("pcallk") { + int narg = getnum; + int nres = getnum; + int i = getindex; + status = lua_pcallk(L1, narg, nres, 0, i, Cfunck); + } + else if EQ("callk") { + int narg = getnum; + int nres = getnum; + int i = getindex; + lua_callk(L1, narg, nres, i, Cfunck); + } + else if EQ("yield") { + return lua_yield(L1, getnum); + } + else if EQ("yieldk") { + int nres = getnum; + int i = getindex; + return lua_yieldk(L1, nres, i, Cfunck); + } + else if EQ("newthread") { + lua_newthread(L1); + } + else if EQ("resume") { + int i = getindex; + status = lua_resume(lua_tothread(L1, i), L, getnum); + } + else if EQ("pushstatus") { + pushcode(L1, status); + } + else if EQ("xmove") { + int f = getindex; + int t = getindex; + lua_State *fs = (f == 0) ? L1 : lua_tothread(L1, f); + lua_State *ts = (t == 0) ? L1 : lua_tothread(L1, t); + int n = getnum; + if (n == 0) n = lua_gettop(fs); + lua_xmove(fs, ts, n); + } + else if EQ("loadstring") { + size_t sl; + const char *s = luaL_checklstring(L1, getnum, &sl); + luaL_loadbuffer(L1, s, sl, s); + } + else if EQ("loadfile") { + luaL_loadfile(L1, luaL_checkstring(L1, getnum)); + } + else if EQ("setmetatable") { + lua_setmetatable(L1, getindex); + } + else if EQ("getmetatable") { + if (lua_getmetatable(L1, getindex) == 0) + lua_pushnil(L1); + } + else if EQ("type") { + lua_pushstring(L1, luaL_typename(L1, getnum)); + } + else if EQ("append") { + int t = getindex; + int i = lua_rawlen(L1, t); + lua_rawseti(L1, t, i + 1); + } + else if EQ("getctx") { + int i = 0; + int s = lua_getctx(L1, &i); + pushcode(L1, s); + lua_pushinteger(L1, i); + } + else if EQ("checkstack") { + int sz = getnum; + luaL_checkstack(L1, sz, getstring); + } + else if EQ("newmetatable") { + lua_pushboolean(L1, luaL_newmetatable(L1, getstring)); + } + else if EQ("testudata") { + int i = getindex; + lua_pushboolean(L1, luaL_testudata(L1, i, getstring) != NULL); + } + else if EQ("gsub") { + int a = getnum; int b = getnum; int c = getnum; + luaL_gsub(L1, lua_tostring(L1, a), + lua_tostring(L1, b), + lua_tostring(L1, c)); + } + else if EQ("sethook") { + int mask = getnum; + int count = getnum; + sethookaux(L1, mask, count, getstring); + } + else if EQ("throw") { +#if defined(__cplusplus) +static struct X { int x; } x; + throw x; +#else + luaL_error(L1, "C++"); +#endif + break; + } + else luaL_error(L, "unknown instruction %s", buff); + } + return 0; +} + + +static int testC (lua_State *L) { + lua_State *L1; + const char *pc; + if (lua_isuserdata(L, 1)) { + L1 = getstate(L); + pc = luaL_checkstring(L, 2); + } + else if (lua_isthread(L, 1)) { + L1 = lua_tothread(L, 1); + pc = luaL_checkstring(L, 2); + } + else { + L1 = L; + pc = luaL_checkstring(L, 1); + } + return runC(L, L1, pc); +} + + +static int Cfunc (lua_State *L) { + return runC(L, L, lua_tostring(L, lua_upvalueindex(1))); +} + + +static int Cfunck (lua_State *L) { + int i = 0; + lua_getctx(L, &i); + return runC(L, L, lua_tostring(L, i)); +} + + +static int makeCfunc (lua_State *L) { + luaL_checkstring(L, 1); + lua_pushcclosure(L, Cfunc, lua_gettop(L)); + return 1; +} + + +/* }====================================================== */ + + +/* +** {====================================================== +** tests for C hooks +** ======================================================= +*/ + +/* +** C hook that runs the C script stored in registry.C_HOOK[L] +*/ +static void Chook (lua_State *L, lua_Debug *ar) { + const char *scpt; + const char *const events [] = {"call", "ret", "line", "count", "tailcall"}; + lua_getfield(L, LUA_REGISTRYINDEX, "C_HOOK"); + lua_pushlightuserdata(L, L); + lua_gettable(L, -2); /* get C_HOOK[L] (script saved by sethookaux) */ + scpt = lua_tostring(L, -1); /* not very religious (string will be popped) */ + lua_pop(L, 2); /* remove C_HOOK and script */ + lua_pushstring(L, events[ar->event]); /* may be used by script */ + lua_pushinteger(L, ar->currentline); /* may be used by script */ + runC(L, L, scpt); /* run script from C_HOOK[L] */ +} + + +/* +** sets registry.C_HOOK[L] = scpt and sets Chook as a hook +*/ +static void sethookaux (lua_State *L, int mask, int count, const char *scpt) { + if (*scpt == '\0') { /* no script? */ + lua_sethook(L, NULL, 0, 0); /* turn off hooks */ + return; + } + lua_getfield(L, LUA_REGISTRYINDEX, "C_HOOK"); /* get C_HOOK table */ + if (!lua_istable(L, -1)) { /* no hook table? */ + lua_pop(L, 1); /* remove previous value */ + lua_newtable(L); /* create new C_HOOK table */ + lua_pushvalue(L, -1); + lua_setfield(L, LUA_REGISTRYINDEX, "C_HOOK"); /* register it */ + } + lua_pushlightuserdata(L, L); + lua_pushstring(L, scpt); + lua_settable(L, -3); /* C_HOOK[L] = script */ + lua_sethook(L, Chook, mask, count); +} + + +static int sethook (lua_State *L) { + if (lua_isnoneornil(L, 1)) + lua_sethook(L, NULL, 0, 0); /* turn off hooks */ + else { + const char *scpt = luaL_checkstring(L, 1); + const char *smask = luaL_checkstring(L, 2); + int count = luaL_optint(L, 3, 0); + int mask = 0; + if (strchr(smask, 'c')) mask |= LUA_MASKCALL; + if (strchr(smask, 'r')) mask |= LUA_MASKRET; + if (strchr(smask, 'l')) mask |= LUA_MASKLINE; + if (count > 0) mask |= LUA_MASKCOUNT; + sethookaux(L, mask, count, scpt); + } + return 0; +} + + +static int coresume (lua_State *L) { + int status; + lua_State *co = lua_tothread(L, 1); + luaL_argcheck(L, co, 1, "coroutine expected"); + status = lua_resume(co, L, 0); + if (status != LUA_OK && status != LUA_YIELD) { + lua_pushboolean(L, 0); + lua_insert(L, -2); + return 2; /* return false + error message */ + } + else { + lua_pushboolean(L, 1); + return 1; + } +} + +/* }====================================================== */ + + + +static const struct luaL_Reg tests_funcs[] = { + {"checkmemory", lua_checkmemory}, + {"closestate", closestate}, + {"d2s", d2s}, + {"doonnewstack", doonnewstack}, + {"doremote", doremote}, + {"gccolor", get_gccolor}, + {"gcstate", gc_state}, + {"getref", getref}, + {"hash", hash_query}, + {"int2fb", int2fb_aux}, + {"limits", get_limits}, + {"listcode", listcode}, + {"listk", listk}, + {"listlocals", listlocals}, + {"loadlib", loadlib}, + {"newstate", newstate}, + {"newuserdata", newuserdata}, + {"num2int", num2int}, + {"pushuserdata", pushuserdata}, + {"querystr", string_query}, + {"querytab", table_query}, + {"ref", tref}, + {"resume", coresume}, + {"s2d", s2d}, + {"sethook", sethook}, + {"stacklevel", stacklevel}, + {"testC", testC}, + {"makeCfunc", makeCfunc}, + {"totalmem", mem_query}, + {"trick", settrick}, + {"udataval", udataval}, + {"unref", unref}, + {"upvalue", upvalue}, + {NULL, NULL} +}; + + +static void checkfinalmem (void) { + lua_assert(l_memcontrol.numblocks == 0); + lua_assert(l_memcontrol.total == 0); +} + + +int luaB_opentests (lua_State *L) { + void *ud; + lua_atpanic(L, &tpanic); + atexit(checkfinalmem); + lua_assert(lua_getallocf(L, &ud) == debug_realloc); + lua_assert(ud == cast(void *, &l_memcontrol)); + lua_setallocf(L, lua_getallocf(L, NULL), ud); + luaL_newlib(L, tests_funcs); + return 1; +} + +#endif diff --git a/components/pico8/femto8/src/lua/ltests.h b/components/pico8/femto8/src/lua/ltests.h new file mode 100644 index 00000000..7a9d329d --- /dev/null +++ b/components/pico8/femto8/src/lua/ltests.h @@ -0,0 +1,93 @@ +/* +** $Id: ltests.h,v 2.33 2010/07/28 15:51:59 roberto Exp $ +** Internal Header for Debugging of the Lua Implementation +** See Copyright Notice in lua.h +*/ + +#ifndef ltests_h +#define ltests_h + + +#include + +/* do not use compatibility macros in Lua code */ +#undef LUA_COMPAT_API + +#define LUA_DEBUG + +#undef NDEBUG +#include +#define lua_assert(c) assert(c) + + +/* to avoid warnings, and to make sure value is really unused */ +#define UNUSED(x) (x=0, (void)(x)) + + +/* memory allocator control variables */ +typedef struct Memcontrol { + unsigned long numblocks; + unsigned long total; + unsigned long maxmem; + unsigned long memlimit; + unsigned long objcount[LUA_NUMTAGS]; +} Memcontrol; + +extern Memcontrol l_memcontrol; + + +/* +** generic variable for debug tricks +*/ +extern void *l_Trick; + + +void *debug_realloc (void *ud, void *block, size_t osize, size_t nsize); + + +typedef struct CallInfo *pCallInfo; + +int lua_checkmemory (lua_State *L); + + +/* test for lock/unlock */ +#undef luai_userstateopen +#undef luai_userstatethread +#undef lua_lock +#undef lua_unlock + +struct L_EXTRA { int lock; int *plock; }; +#define LUAI_EXTRASPACE sizeof(struct L_EXTRA) +#define getlock(l) (cast(struct L_EXTRA *, l) - 1) +#define luai_userstateopen(l) \ + (getlock(l)->lock = 0, getlock(l)->plock = &(getlock(l)->lock)) +#define luai_userstatethread(l,l1) (getlock(l1)->plock = getlock(l)->plock) +#define luai_userstatefree(l,l1) \ + lua_assert(getlock(l)->plock == getlock(l1)->plock) +#define lua_lock(l) lua_assert((*getlock(l)->plock)++ == 0) +#define lua_unlock(l) lua_assert(--(*getlock(l)->plock) == 0) + + +int luaB_opentests (lua_State *L); + + +#if defined(lua_c) +#define luaL_newstate() lua_newstate(debug_realloc, &l_memcontrol) +#define luaL_openlibs(L) \ + { (luaL_openlibs)(L); luaL_requiref(L, "T", luaB_opentests, 1); } +#endif + + + +/* change some sizes to give some bugs a chance */ + +#undef LUAL_BUFFERSIZE +#define LUAL_BUFFERSIZE 23 +#define MINSTRTABSIZE 2 + + +#undef LUAI_USER_ALIGNMENT_T +#define LUAI_USER_ALIGNMENT_T union { char b[32]; } + + +#endif diff --git a/components/pico8/femto8/src/lua/ltm.c b/components/pico8/femto8/src/lua/ltm.c new file mode 100644 index 00000000..620f4f81 --- /dev/null +++ b/components/pico8/femto8/src/lua/ltm.c @@ -0,0 +1,79 @@ +/* +** $Id: ltm.c,v 2.14 2011/06/02 19:31:40 roberto Exp $ +** Tag methods +** See Copyright Notice in lua.h +*/ + + +#include + +#define ltm_c +#define LUA_CORE + +#include "lua.h" + +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" + + +static const char udatatypename[] = "userdata"; + +LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTAGS] = { + "no value", + "nil", "boolean", udatatypename, "number", + "string", "table", "function", udatatypename, "thread", + "proto", "upval" /* these last two cases are used for tests only */ +}; + + +void luaT_init (lua_State *L) { + static const char *const luaT_eventname[] = { /* ORDER TM */ + "__index", "__newindex", + "__gc", "__mode", "__len", "__eq", + "__add", "__sub", "__mul", "__div", "__mod", + "__pow", "_idiv", "__and", "__or", "__xor", + "__shl", "__shr", "__lshr", "__rotl", "rotr", + "__unm", "__not", "__peek", "__peek2", "__peek4", + "__lt", "__le", "__concat", "__call" + }; + int i; + for (i=0; itmname[i] = luaS_new(L, luaT_eventname[i]); + luaS_fix(G(L)->tmname[i]); /* never collect these names */ + } +} + + +/* +** function to be used with macro "fasttm": optimized for absence of +** tag methods +*/ +const TValue *luaT_gettm (Table *events, TMS event, TString *ename) { + const TValue *tm = luaH_getstr(events, ename); + lua_assert(event <= TM_EQ); + if (ttisnil(tm)) { /* no tag method? */ + events->flags |= cast_byte(1u<metatable; + break; + case LUA_TUSERDATA: + mt = uvalue(o)->metatable; + break; + default: + mt = G(L)->mt[ttypenv(o)]; + } + return (mt ? luaH_getstr(mt, G(L)->tmname[event]) : luaO_nilobject); +} + diff --git a/components/pico8/femto8/src/lua/ltm.h b/components/pico8/femto8/src/lua/ltm.h new file mode 100644 index 00000000..3c772bcf --- /dev/null +++ b/components/pico8/femto8/src/lua/ltm.h @@ -0,0 +1,70 @@ +/* +** $Id: ltm.h,v 2.11 2011/02/28 17:32:10 roberto Exp $ +** Tag methods +** See Copyright Notice in lua.h +*/ + +#ifndef ltm_h +#define ltm_h + + +#include "lobject.h" + + +/* +* WARNING: if you change the order of this enumeration, +* grep "ORDER TM" +*/ +typedef enum { + TM_INDEX, + TM_NEWINDEX, + TM_GC, + TM_MODE, + TM_LEN, + TM_EQ, /* last tag method with `fast' access */ + TM_ADD, + TM_SUB, + TM_MUL, + TM_DIV, + TM_MOD, + TM_POW, + TM_IDIV, + TM_BAND, + TM_BOR, + TM_BXOR, + TM_SHL, + TM_SHR, + TM_LSHR, + TM_ROTL, + TM_ROTR, + TM_UNM, + TM_BNOT, + TM_PEEK, + TM_PEEK2, + TM_PEEK4, + TM_LT, + TM_LE, + TM_CONCAT, + TM_CALL, + TM_N /* number of elements in the enum */ +} TMS; + + + +#define gfasttm(g,et,e) ((et) == NULL ? NULL : \ + ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e])) + +#define fasttm(l,et,e) gfasttm(G(l), et, e) + +#define ttypename(x) luaT_typenames_[(x) + 1] +#define objtypename(x) ttypename(ttypenv(x)) + +LUAI_DDEC const char *const luaT_typenames_[LUA_TOTALTAGS]; + + +LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename); +LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, + TMS event); +LUAI_FUNC void luaT_init (lua_State *L); + +#endif diff --git a/components/pico8/femto8/src/lua/lua.h b/components/pico8/femto8/src/lua/lua.h new file mode 100644 index 00000000..25fd9974 --- /dev/null +++ b/components/pico8/femto8/src/lua/lua.h @@ -0,0 +1,459 @@ +/* +** $Id: lua.h,v 1.285.1.3 2014/05/07 14:15:55 roberto Exp roberto $ +** Lua - A Scripting Language +** Lua.org, PUC-Rio, Brazil (http://www.lua.org) +** See Copyright Notice at the end of this file +*/ + + +#ifndef lua_h +#define lua_h + +#include +#include + + +#include "luaconf.h" + + +#define LUA_VERSION_MAJOR "5" +#define LUA_VERSION_MINOR "2" +#define LUA_VERSION_NUM 502 +#define LUA_VERSION_RELEASE "4" + +#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR +#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE +#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2015 Lua.org, PUC-Rio" +#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" + + +/* mark for precompiled code ('Lua') */ +#define LUA_SIGNATURE "\033Lua" + +/* option for multiple returns in 'lua_pcall' and 'lua_call' */ +#define LUA_MULTRET (-1) + + +/* +** pseudo-indices +*/ +#define LUA_REGISTRYINDEX LUAI_FIRSTPSEUDOIDX +#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i)) + + +/* thread status */ +#define LUA_OK 0 +#define LUA_YIELD 1 +#define LUA_ERRRUN 2 +#define LUA_ERRSYNTAX 3 +#define LUA_ERRMEM 4 +#define LUA_ERRGCMM 5 +#define LUA_ERRERR 6 + + +typedef struct lua_State lua_State; + +typedef int (*lua_CFunction) (lua_State *L); + + +/* +** functions that read/write blocks when loading/dumping Lua chunks +*/ +typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); + +typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); + + +/* +** prototype for memory-allocation functions +*/ +typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); + + +/* +** basic types +*/ +#define LUA_TNONE (-1) + +#define LUA_TNIL 0 +#define LUA_TBOOLEAN 1 +#define LUA_TLIGHTUSERDATA 2 +#define LUA_TNUMBER 3 +#define LUA_TSTRING 4 +#define LUA_TTABLE 5 +#define LUA_TFUNCTION 6 +#define LUA_TUSERDATA 7 +#define LUA_TTHREAD 8 + +#define LUA_NUMTAGS 9 + + + +/* minimum Lua stack available to a C function */ +#define LUA_MINSTACK 20 + + +/* predefined values in the registry */ +#define LUA_RIDX_MAINTHREAD 1 +#define LUA_RIDX_GLOBALS 2 +#define LUA_RIDX_LAST LUA_RIDX_GLOBALS + + +/* type of numbers in Lua */ +typedef LUA_NUMBER lua_Number; + + +/* type for integer functions */ +typedef LUA_INTEGER lua_Integer; + +/* unsigned integer type */ +typedef LUA_UNSIGNED lua_Unsigned; + + + +/* +** generic extra include file +*/ +#if defined(LUA_USER_H) +#include LUA_USER_H +#endif + + +/* +** RCS ident string +*/ +extern const char lua_ident[]; + + +/* +** state manipulation +*/ +LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); +LUA_API void (lua_close) (lua_State *L); +LUA_API lua_State *(lua_newthread) (lua_State *L); + +LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); + + +LUA_API const lua_Number *(lua_version) (lua_State *L); + + +/* +** basic stack manipulation +*/ +LUA_API int (lua_absindex) (lua_State *L, int idx); +LUA_API int (lua_gettop) (lua_State *L); +LUA_API void (lua_settop) (lua_State *L, int idx); +LUA_API void (lua_pushvalue) (lua_State *L, int idx); +LUA_API void (lua_remove) (lua_State *L, int idx); +LUA_API void (lua_insert) (lua_State *L, int idx); +LUA_API void (lua_replace) (lua_State *L, int idx); +LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx); +LUA_API int (lua_checkstack) (lua_State *L, int sz); + +LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); + + +/* +** access functions (stack -> C) +*/ + +LUA_API int (lua_isnumber) (lua_State *L, int idx); +LUA_API int (lua_isstring) (lua_State *L, int idx); +LUA_API int (lua_iscfunction) (lua_State *L, int idx); +LUA_API int (lua_isuserdata) (lua_State *L, int idx); +LUA_API int (lua_type) (lua_State *L, int idx); +LUA_API const char *(lua_typename) (lua_State *L, int tp); + +LUA_API lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum); +LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum); +LUA_API lua_Unsigned (lua_tounsignedx) (lua_State *L, int idx, int *isnum); +LUA_API int (lua_toboolean) (lua_State *L, int idx); +LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); +LUA_API size_t (lua_rawlen) (lua_State *L, int idx); +LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); +LUA_API void *(lua_touserdata) (lua_State *L, int idx); +LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); +LUA_API const void *(lua_topointer) (lua_State *L, int idx); + + +/* +** Comparison and arithmetic functions +*/ + +#define LUA_OPADD 0 /* ORDER TM */ +#define LUA_OPSUB 1 +#define LUA_OPMUL 2 +#define LUA_OPDIV 3 +#define LUA_OPMOD 4 +#define LUA_OPPOW 5 +#define LUA_OPIDIV 6 +#define LUA_OPBAND 7 +#define LUA_OPBOR 8 +#define LUA_OPBXOR 9 +#define LUA_OPSHL 10 +#define LUA_OPSHR 11 +#define LUA_OPLSHR 12 +#define LUA_OPROTL 13 +#define LUA_OPROTR 14 +#define LUA_OPUNM 15 +#define LUA_OPBNOT 16 +#define LUA_OPPEEK 17 +#define LUA_OPPEEK2 18 +#define LUA_OPPEEK4 19 + +LUA_API void (lua_arith) (lua_State *L, int op); + +#define LUA_OPEQ 0 +#define LUA_OPLT 1 +#define LUA_OPLE 2 + +LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); +LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op); + + +/* +** push functions (C -> stack) +*/ +LUA_API void (lua_pushnil) (lua_State *L); +LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); +LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); +LUA_API void (lua_pushunsigned) (lua_State *L, lua_Unsigned n); +LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t l); +LUA_API const char *(lua_pushstring) (lua_State *L, const char *s); +LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, + va_list argp); +LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); +LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); +LUA_API void (lua_pushboolean) (lua_State *L, int b); +LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); +LUA_API int (lua_pushthread) (lua_State *L); + + +/* +** get functions (Lua -> stack) +*/ +LUA_API void (lua_getglobal) (lua_State *L, const char *var); +LUA_API void (lua_gettable) (lua_State *L, int idx); +LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k); +LUA_API void (lua_rawget) (lua_State *L, int idx); +LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n); +LUA_API void (lua_rawgetp) (lua_State *L, int idx, const void *p); +LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); +LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); +LUA_API int (lua_getmetatable) (lua_State *L, int objindex); +LUA_API void (lua_getuservalue) (lua_State *L, int idx); + + +/* +** set functions (stack -> Lua) +*/ +LUA_API void (lua_setglobal) (lua_State *L, const char *var); +LUA_API void (lua_settable) (lua_State *L, int idx); +LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); +LUA_API void (lua_rawset) (lua_State *L, int idx); +LUA_API void (lua_rawseti) (lua_State *L, int idx, int n); +LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p); +LUA_API int (lua_setmetatable) (lua_State *L, int objindex); +LUA_API void (lua_setuservalue) (lua_State *L, int idx); + +LUA_API void (lua_setpico8memory) (lua_State *L, unsigned char const *p); + +/* +** 'load' and 'call' functions (load and run Lua code) +*/ +LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults, int ctx, + lua_CFunction k); +#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL) + +LUA_API int (lua_getctx) (lua_State *L, int *ctx); + +LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc, + int ctx, lua_CFunction k); +#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) + +LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, + const char *chunkname, + const char *mode); + +LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data); + + +/* +** coroutine functions +*/ +LUA_API int (lua_yieldk) (lua_State *L, int nresults, int ctx, + lua_CFunction k); +#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) +LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg); +LUA_API int (lua_status) (lua_State *L); + +/* +** garbage-collection function and options +*/ + +#define LUA_GCSTOP 0 +#define LUA_GCRESTART 1 +#define LUA_GCCOLLECT 2 +#define LUA_GCCOUNT 3 +#define LUA_GCCOUNTB 4 +#define LUA_GCSTEP 5 +#define LUA_GCSETPAUSE 6 +#define LUA_GCSETSTEPMUL 7 +#define LUA_GCSETMAJORINC 8 +#define LUA_GCISRUNNING 9 +#define LUA_GCGEN 10 +#define LUA_GCINC 11 + +LUA_API int (lua_gc) (lua_State *L, int what, int data); + + +/* +** miscellaneous functions +*/ + +LUA_API int (lua_error) (lua_State *L); + +LUA_API int (lua_next) (lua_State *L, int idx); + +LUA_API void (lua_concat) (lua_State *L, int n); +LUA_API void (lua_len) (lua_State *L, int idx); + +LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); +LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud); + + + +/* +** =============================================================== +** some useful macros +** =============================================================== +*/ + +#define lua_tonumber(L,i) lua_tonumberx(L,i,NULL) +#define lua_tointeger(L,i) lua_tointegerx(L,i,NULL) +#define lua_tounsigned(L,i) lua_tounsignedx(L,i,NULL) + +#define lua_pop(L,n) lua_settop(L, -(n)-1) + +#define lua_newtable(L) lua_createtable(L, 0, 0) + +#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) + +#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) + +#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) +#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) +#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) +#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) +#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) +#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) +#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) +#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) + +#define lua_pushliteral(L, s) \ + lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) + +#define lua_pushglobaltable(L) \ + lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS) + +#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) +#define lua_to_or_default(L, w, i, d) lua_gettop(L) >= i ? lua_to##w(L, i) : d + + + +/* +** {====================================================================== +** Debug API +** ======================================================================= +*/ + + +/* +** Event codes +*/ +#define LUA_HOOKCALL 0 +#define LUA_HOOKRET 1 +#define LUA_HOOKLINE 2 +#define LUA_HOOKCOUNT 3 +#define LUA_HOOKTAILCALL 4 + + +/* +** Event masks +*/ +#define LUA_MASKCALL (1 << LUA_HOOKCALL) +#define LUA_MASKRET (1 << LUA_HOOKRET) +#define LUA_MASKLINE (1 << LUA_HOOKLINE) +#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) + +typedef struct lua_Debug lua_Debug; /* activation record */ + + +/* Functions to be called by the debugger in specific events */ +typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); + + +LUA_API int (lua_getstack) (lua_State *L, int level, lua_Debug *ar); +LUA_API int (lua_getinfo) (lua_State *L, const char *what, lua_Debug *ar); +LUA_API const char *(lua_getlocal) (lua_State *L, const lua_Debug *ar, int n); +LUA_API const char *(lua_setlocal) (lua_State *L, const lua_Debug *ar, int n); +LUA_API const char *(lua_getupvalue) (lua_State *L, int funcindex, int n); +LUA_API const char *(lua_setupvalue) (lua_State *L, int funcindex, int n); + +LUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n); +LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1, + int fidx2, int n2); + +LUA_API int (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count); +LUA_API lua_Hook (lua_gethook) (lua_State *L); +LUA_API int (lua_gethookmask) (lua_State *L); +LUA_API int (lua_gethookcount) (lua_State *L); + + +struct lua_Debug { + int event; + const char *name; /* (n) */ + const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */ + const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */ + const char *source; /* (S) */ + int currentline; /* (l) */ + int linedefined; /* (S) */ + int lastlinedefined; /* (S) */ + unsigned char nups; /* (u) number of upvalues */ + unsigned char nparams;/* (u) number of parameters */ + char isvararg; /* (u) */ + char istailcall; /* (t) */ + char short_src[LUA_IDSIZE]; /* (S) */ + /* private part */ + struct CallInfo *i_ci; /* active function */ +}; + +/* }====================================================================== */ + + +/****************************************************************************** +* Copyright (C) 1994-2015 Lua.org, PUC-Rio. +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +******************************************************************************/ + + +#endif diff --git a/components/pico8/femto8/src/lua/luaconf.h b/components/pico8/femto8/src/lua/luaconf.h new file mode 100644 index 00000000..fc400b7f --- /dev/null +++ b/components/pico8/femto8/src/lua/luaconf.h @@ -0,0 +1,671 @@ +/* +** $Id: luaconf.h,v 1.176.1.1 2013/04/12 18:48:47 roberto Exp roberto $ +** Configuration file for Lua +** See Copyright Notice in lua.h +*/ + + +#ifndef lconfig_h +#define lconfig_h + +#include +#include + + +/* +** ================================================================== +** Search for "@@" to find all configurable definitions. +** =================================================================== +*/ + + +/* +@@ LUA_ANSI controls the use of non-ansi features. +** CHANGE it (define it) if you want Lua to avoid the use of any +** non-ansi feature or library. +*/ +#if !defined(LUA_ANSI) && defined(__STRICT_ANSI__) +#define LUA_ANSI +#endif + + +#if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE) +#define LUA_WIN /* enable goodies for regular Windows platforms */ +#endif + +#if defined(LUA_WIN) +#define LUA_DL_DLL +#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */ +#endif + + + +#if defined(LUA_USE_LINUX) +#define LUA_USE_POSIX +#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ +#define LUA_USE_READLINE /* needs some extra libraries */ +#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */ +#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */ +#define LUA_USE_LONGLONG /* assume support for long long */ +#endif + +#if defined(LUA_USE_MACOSX) +#define LUA_USE_POSIX +#define LUA_USE_DLOPEN /* does not need -ldl */ +#define LUA_USE_READLINE /* needs an extra library: -lreadline */ +#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */ +#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */ +#define LUA_USE_LONGLONG /* assume support for long long */ +#endif + + + +/* +@@ LUA_USE_POSIX includes all functionality listed as X/Open System +@* Interfaces Extension (XSI). +** CHANGE it (define it) if your system is XSI compatible. +*/ +#if defined(LUA_USE_POSIX) +#define LUA_USE_MKSTEMP +#define LUA_USE_ISATTY +#define LUA_USE_POPEN +#define LUA_USE_ULONGJMP +#define LUA_USE_GMTIME_R +#endif + + + +/* +@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for +@* Lua libraries. +@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for +@* C libraries. +** CHANGE them if your machine has a non-conventional directory +** hierarchy or if you want to install your libraries in +** non-conventional directories. +*/ +#if defined(_WIN32) /* { */ +/* +** In Windows, any exclamation mark ('!') in the path is replaced by the +** path of the directory of the executable file of the current process. +*/ +#define LUA_LDIR "!\\lua\\" +#define LUA_CDIR "!\\" +#define LUA_PATH_DEFAULT \ + LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ + LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" ".\\?.lua" +#define LUA_CPATH_DEFAULT \ + LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll;" ".\\?.dll" + +#else /* }{ */ + +#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "/" +#define LUA_ROOT "/usr/local/" +#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR +#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR +#define LUA_PATH_DEFAULT \ + LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ + LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" "./?.lua" +#define LUA_CPATH_DEFAULT \ + LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so" +#endif /* } */ + + +/* +@@ LUA_DIRSEP is the directory separator (for submodules). +** CHANGE it if your machine does not use "/" as the directory separator +** and is not Windows. (On Windows Lua automatically uses "\".) +*/ +#if defined(_WIN32) +#define LUA_DIRSEP "\\" +#else +#define LUA_DIRSEP "/" +#endif + + +/* +@@ LUA_ENV is the name of the variable that holds the current +@@ environment, used to access global names. +** CHANGE it if you do not like this name. +*/ +#define LUA_ENV "_ENV" + + +/* +@@ LUA_API is a mark for all core API functions. +@@ LUALIB_API is a mark for all auxiliary library functions. +@@ LUAMOD_API is a mark for all standard library opening functions. +** CHANGE them if you need to define those functions in some special way. +** For instance, if you want to create one Windows DLL with the core and +** the libraries, you may want to use the following definition (define +** LUA_BUILD_AS_DLL to get it). +*/ +#if defined(LUA_BUILD_AS_DLL) /* { */ + +#if defined(LUA_CORE) || defined(LUA_LIB) /* { */ +#define LUA_API __declspec(dllexport) +#else /* }{ */ +#define LUA_API __declspec(dllimport) +#endif /* } */ + +#else /* }{ */ + +#define LUA_API extern + +#endif /* } */ + + +/* more often than not the libs go together with the core */ +#define LUALIB_API LUA_API +#define LUAMOD_API LUALIB_API + + +/* +@@ LUAI_FUNC is a mark for all extern functions that are not to be +@* exported to outside modules. +@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables +@* that are not to be exported to outside modules (LUAI_DDEF for +@* definitions and LUAI_DDEC for declarations). +** CHANGE them if you need to mark them in some special way. Elf/gcc +** (versions 3.2 and later) mark them as "hidden" to optimize access +** when Lua is compiled as a shared library. Not all elf targets support +** this attribute. Unfortunately, gcc does not offer a way to check +** whether the target offers that support, and those without support +** give a warning about it. To avoid these warnings, change to the +** default definition. +*/ +#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ + defined(__ELF__) /* { */ +#define LUAI_FUNC __attribute__((visibility("hidden"))) extern +#define LUAI_DDEC LUAI_FUNC +#define LUAI_DDEF /* empty */ + +#else /* }{ */ +#define LUAI_FUNC extern +#define LUAI_DDEC extern +#define LUAI_DDEF /* empty */ +#endif /* } */ + + + +/* +@@ LUA_QL describes how error messages quote program elements. +** CHANGE it if you want a different appearance. +*/ +#define LUA_QL(x) "'" x "'" +#define LUA_QS LUA_QL("%s") + + +/* +@@ LUA_IDSIZE gives the maximum size for the description of the source +@* of a function in debug information. +** CHANGE it if you want a different size. +*/ +#define LUA_IDSIZE 60 + + +/* +@@ luai_writestring/luai_writeline define how 'print' prints its results. +** They are only used in libraries and the stand-alone program. (The #if +** avoids including 'stdio.h' everywhere.) +*/ +#if defined(LUA_LIB) || defined(lua_c) +#include +#define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) +#define luai_writeline() (luai_writestring("\n", 1), fflush(stdout)) +#endif + +/* +@@ luai_writestringerror defines how to print error messages. +** (A format string with one argument is enough for Lua...) +*/ +#define luai_writestringerror(s,p) \ + (fprintf(stderr, (s), (p)), fflush(stderr)) + + +/* +@@ LUAI_MAXSHORTLEN is the maximum length for short strings, that is, +** strings that are internalized. (Cannot be smaller than reserved words +** or tags for metamethods, as these strings must be internalized; +** #("function") = 8, #("__newindex") = 10.) +*/ +#define LUAI_MAXSHORTLEN 40 + + + +/* +** {================================================================== +** Compatibility with previous versions +** =================================================================== +*/ + +/* +@@ LUA_COMPAT_ALL controls all compatibility options. +** You can define it to get all options, or change specific options +** to fit your specific needs. +*/ +#if defined(LUA_COMPAT_ALL) /* { */ + +/* +@@ LUA_COMPAT_UNPACK controls the presence of global 'unpack'. +** You can replace it with 'table.unpack'. +*/ +#define LUA_COMPAT_UNPACK + +/* +@@ LUA_COMPAT_LOADERS controls the presence of table 'package.loaders'. +** You can replace it with 'package.searchers'. +*/ +#define LUA_COMPAT_LOADERS + +/* +@@ macro 'lua_cpcall' emulates deprecated function lua_cpcall. +** You can call your C function directly (with light C functions). +*/ +#define lua_cpcall(L,f,u) \ + (lua_pushcfunction(L, (f)), \ + lua_pushlightuserdata(L,(u)), \ + lua_pcall(L,1,0,0)) + + +/* +@@ LUA_COMPAT_LOG10 defines the function 'log10' in the math library. +** You can rewrite 'log10(x)' as 'log(x, 10)'. +*/ +#define LUA_COMPAT_LOG10 + +/* +@@ LUA_COMPAT_LOADSTRING defines the function 'loadstring' in the base +** library. You can rewrite 'loadstring(s)' as 'load(s)'. +*/ +#define LUA_COMPAT_LOADSTRING + +/* +@@ LUA_COMPAT_MAXN defines the function 'maxn' in the table library. +*/ +#define LUA_COMPAT_MAXN + +/* +@@ The following macros supply trivial compatibility for some +** changes in the API. The macros themselves document how to +** change your code to avoid using them. +*/ +#define lua_strlen(L,i) lua_rawlen(L, (i)) + +#define lua_objlen(L,i) lua_rawlen(L, (i)) + +#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) +#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) + +/* +@@ LUA_COMPAT_MODULE controls compatibility with previous +** module functions 'module' (Lua) and 'luaL_register' (C). +*/ +#define LUA_COMPAT_MODULE + +#endif /* } */ + +/* }================================================================== */ + + + +/* +@@ LUAI_BITSINT defines the number of bits in an int. +** CHANGE here if Lua cannot automatically detect the number of bits of +** your machine. Probably you do not need to change this. +*/ +/* avoid overflows in comparison */ +#if INT_MAX-20 < 32760 /* { */ +#define LUAI_BITSINT 16 +#elif INT_MAX > 2147483640L /* }{ */ +/* int has at least 32 bits */ +#define LUAI_BITSINT 32 +#else /* }{ */ +#error "you must define LUA_BITSINT with number of bits in an integer" +#endif /* } */ + + +/* +@@ LUA_INT32 is a signed integer with exactly 32 bits. +@@ LUAI_UMEM is an unsigned integer big enough to count the total +@* memory used by Lua. +@@ LUAI_MEM is a signed integer big enough to count the total memory +@* used by Lua. +** CHANGE here if for some weird reason the default definitions are not +** good enough for your machine. Probably you do not need to change +** this. +*/ +#if LUAI_BITSINT >= 32 /* { */ +#define LUA_INT32 int +#define LUAI_UMEM size_t +#define LUAI_MEM ptrdiff_t +#else /* }{ */ +/* 16-bit ints */ +#define LUA_INT32 long +#define LUAI_UMEM unsigned long +#define LUAI_MEM long +#endif /* } */ + + +/* +@@ LUAI_MAXSTACK limits the size of the Lua stack. +** CHANGE it if you need a different limit. This limit is arbitrary; +** its only purpose is to stop Lua from consuming unlimited stack +** space (and to reserve some numbers for pseudo-indices). +*/ +#if LUAI_BITSINT >= 32 +#define LUAI_MAXSTACK 1000000 +#else +#define LUAI_MAXSTACK 15000 +#endif + +/* reserve some space for error handling */ +#define LUAI_FIRSTPSEUDOIDX (-LUAI_MAXSTACK - 1000) + + + + +/* +@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. +** CHANGE it if it uses too much C-stack space. +*/ +#define LUAL_BUFFERSIZE BUFSIZ + + + + +/* +** {================================================================== +@@ LUA_NUMBER is the type of numbers in Lua. +** CHANGE the following definitions only if you want to build Lua +** with a number type different from double. You may also need to +** change lua_number2int & lua_number2integer. +** =================================================================== +*/ + +#define LUA_NUMBER_DOUBLE +#define LUA_NUMBER double + +/* +@@ LUAI_UACNUMBER is the result of an 'usual argument conversion' +@* over a number. +*/ +#define LUAI_UACNUMBER double + + +/* +@@ LUA_NUMBER_SCAN is the format for reading numbers. +@@ LUA_NUMBER_FMT is the format for writing numbers. +@@ lua_number2str converts a number to a string. +@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion. +*/ +#define LUA_NUMBER_SCAN "%lf" +#define LUA_NUMBER_FMT "%.14g" +#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) +#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */ + + +/* +@@ l_mathop allows the addition of an 'l' or 'f' to all math operations +*/ +#define l_mathop(x) (x) + + +/* +@@ lua_str2number converts a decimal numeric string to a number. +@@ lua_strx2number converts an hexadecimal numeric string to a number. +** In C99, 'strtod' does both conversions. C89, however, has no function +** to convert floating hexadecimal strings to numbers. For these +** systems, you can leave 'lua_strx2number' undefined and Lua will +** provide its own implementation. +*/ +#define lua_str2number(s,p) strtod((s), (p)) + +#if defined(LUA_USE_STRTODHEX) +#define lua_strx2number(s,p) strtod((s), (p)) +#endif + + +/* +@@ The luai_num* macros define the primitive operations over numbers. +*/ + +/* the following operations need the math library */ +#if defined(lobject_c) || defined(lvm_c) +#include +#define luai_nummod(L,a,b) ((a)%(b)) +#define luai_numpow(L,a,b) (l_mathop(pow)(a,b)) +#endif + +/* these are quite standard operations */ +#if defined(LUA_CORE) +#define luai_numadd(L,a,b) ((a)+(b)) +#define luai_numsub(L,a,b) ((a)-(b)) +#define luai_nummul(L,a,b) ((a)*(b)) +#define luai_numdiv(L,a,b) ((a)/(b)) +#define luai_numunm(L,a) (-(a)) +#define luai_numeq(a,b) ((a)==(b)) +#define luai_numlt(L,a,b) ((a)<(b)) +#define luai_numle(L,a,b) ((a)<=(b)) +#define luai_numisnan(L,a) (!luai_numeq((a), (a))) +#endif + + + +/* +@@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger. +** CHANGE that if ptrdiff_t is not adequate on your machine. (On most +** machines, ptrdiff_t gives a good choice between int or long.) +*/ +#define LUA_INTEGER ptrdiff_t + +/* +@@ LUA_UNSIGNED is the integral type used by lua_pushunsigned/lua_tounsigned. +** It must have at least 32 bits. +*/ +#define LUA_UNSIGNED unsigned LUA_INT32 + + + +/* +** Some tricks with doubles +*/ + +#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) /* { */ +/* +** The next definitions activate some tricks to speed up the +** conversion from doubles to integer types, mainly to LUA_UNSIGNED. +** +@@ LUA_MSASMTRICK uses Microsoft assembler to avoid clashes with a +** DirectX idiosyncrasy. +** +@@ LUA_IEEE754TRICK uses a trick that should work on any machine +** using IEEE754 with a 32-bit integer type. +** +@@ LUA_IEEELL extends the trick to LUA_INTEGER; should only be +** defined when LUA_INTEGER is a 32-bit integer. +** +@@ LUA_IEEEENDIAN is the endianness of doubles in your machine +** (0 for little endian, 1 for big endian); if not defined, Lua will +** check it dynamically for LUA_IEEE754TRICK (but not for LUA_NANTRICK). +** +@@ LUA_NANTRICK controls the use of a trick to pack all types into +** a single double value, using NaN values to represent non-number +** values. The trick only works on 32-bit machines (ints and pointers +** are 32-bit values) with numbers represented as IEEE 754-2008 doubles +** with conventional endianess (12345678 or 87654321), in CPUs that do +** not produce signaling NaN values (all NaNs are quiet). +*/ + +/* Microsoft compiler on a Pentium (32 bit) ? */ +#if defined(LUA_WIN) && defined(_MSC_VER) && defined(_M_IX86) /* { */ + +#define LUA_MSASMTRICK +#define LUA_IEEEENDIAN 0 +#define LUA_NANTRICK + + +/* pentium 32 bits? */ +#elif defined(__i386__) || defined(__i386) || defined(__X86__) /* }{ */ + +#define LUA_IEEE754TRICK +#define LUA_IEEELL +#define LUA_IEEEENDIAN 0 +#define LUA_NANTRICK + +/* pentium 64 bits? */ +#elif defined(__x86_64) /* }{ */ + +#define LUA_IEEE754TRICK +#define LUA_IEEEENDIAN 0 + +#elif defined(__POWERPC__) || defined(__ppc__) /* }{ */ + +#define LUA_IEEE754TRICK +#define LUA_IEEEENDIAN 1 + +#else /* }{ */ + +/* assume IEEE754 and a 32-bit integer type */ +#define LUA_IEEE754TRICK + +#endif /* } */ + +#endif /* } */ + +/* }================================================================== */ + + + + +/* =================================================================== */ + +/* +** Local configuration. You can use this space to add your redefinitions +** without modifying the main part of the file. +*/ + + +#include +#include +#include +#include "fix32.h" + +#undef LUA_USE_STRTODHEX +#undef LUA_USE_LONGLONG +#undef LUA_INTEGER +#undef LUA_UNSIGNED +#undef LUA_NUMBER_DOUBLE +#undef LUA_NUMBER +#undef LUA_IEEE754TRICK +#undef LUA_MSASMTRICK +#undef LUAI_UACNUMBER +#undef LUA_NANTRICK + +#undef lua_number2str +#undef l_mathop +#undef lua_str2number + +#undef LUA_NUMBER_SCAN +#undef LUA_NUMBER_FMT +#undef LUAI_MAXNUMBER2STR + +#undef luai_nummod +#undef luai_numpow +#undef luai_numadd +#undef luai_numsub +#undef luai_nummul +#undef luai_numdiv +#undef luai_numunm +#undef luai_numeq +#undef luai_numlt +#undef luai_numle +#undef luai_numisnan + +#define LUA_PROGNAME "nextp8" +#define LUA_INTEGER int16_t +#define LUA_UNSIGNED uint16_t +#define LUA_NUMBER fix32_t +#define LUAI_UACNUMBER fix32_t +#define LUA_NBITS 16 +#define LUAI_MAXNUMBER2STR 32 + +#define LUA_USE_LONGJMP + +#define LUA_COMPAT_UNPACK + +/* +** lua_str2number: parse a decimal string to fix32_t +** We parse via strtod, then convert to fix32. +*/ +static inline fix32_t lua_str2number_fn(const char *s, char **endptr) { + double d = strtod(s, endptr); + return fix32_from_double(d); +} +#define lua_str2number(s,p) lua_str2number_fn((s), (p)) + +/* +** lua_number2str: convert fix32_t to string. +** Returns the length written (matching the C++ lambda that was here before). +*/ +static inline int lua_number2str_fn(char *s, fix32_t n) { + int i = sprintf(s, "%1.4f", fix32_to_double(n)); + while (i > 0 && s[i - 1] == '0') s[--i] = '\0'; + if (i > 0 && s[i - 1] == '.') s[--i] = '\0'; + return i; +} +#define lua_number2str(s,n) lua_number2str_fn((s), (n)) + +/* +** Arithmetic macros using our pure C fix32 functions. +*/ +#if defined(lobject_c) || defined(lvm_c) +#include +#endif + +/* these are used everywhere in LUA_CORE */ +#if defined(LUA_CORE) +#define luai_numadd(L,a,b) fix32_add((a),(b)) +#define luai_numsub(L,a,b) fix32_sub((a),(b)) +#define luai_nummul(L,a,b) fix32_mul((a),(b)) +#define luai_numdiv(L,a,b) fix32_div((a),(b)) +#define luai_numunm(L,a) fix32_neg(a) +#define luai_numeq(a,b) fix32_eq((a),(b)) +#define luai_numlt(L,a,b) fix32_lt((a),(b)) +#define luai_numle(L,a,b) fix32_le((a),(b)) +#define luai_numisnan(L,a) (0) /* fix32 has no NaN */ +#endif + +#define luai_nummod(L,a,b) fix32_mod((a),(b)) +#define luai_numpow(L,a,b) fix32_pow((a),(b)) +#define luai_numidiv(L,a,b) fix32_idiv((a),(b)) + +/* Bitwise operations on fix32 */ +#define luai_numband(L,a,b) fix32_band((a),(b)) +#define luai_numbor(L,a,b) fix32_bor((a),(b)) +#define luai_numbxor(L,a,b) fix32_bxor((a),(b)) +#define luai_numshl(L,a,b) fix32_shl((a), fix32_to_int(b)) +#define luai_numshr(L,a,b) fix32_shr((a), fix32_to_int(b)) +#define luai_numlshr(L,a,b) fix32_lshr((a), fix32_to_int(b)) +#define luai_numrotl(L,a,b) fix32_rotl((a), fix32_to_int(b)) +#define luai_numrotr(L,a,b) fix32_rotr((a), fix32_to_int(b)) +#define luai_numbnot(L,a) fix32_bnot(a) +#define luai_numpeek(L,a) (luaV_peek(L,a,1)) +#define luai_numpeek2(L,a) (luaV_peek(L,a,2)) +#define luai_numpeek4(L,a) (luaV_peek(L,a,4)) + +/* +** Hash for fix32 numbers. +** Multiply by golden ratio in fix32, take raw bits. +*/ +#define luai_hashnum(i,n) \ + (i = (int)fix32_bits(fix32_mul((n), fix32_from_bits((int32_t)2654435769u)))) + +/* +** l_mathop is not used in fix32 mode, but define it to avoid errors +** in dead code paths. +*/ +#define l_mathop(x) (x) + +#endif + diff --git a/components/pico8/femto8/src/lua/lualib.h b/components/pico8/femto8/src/lua/lualib.h new file mode 100644 index 00000000..6c1d307a --- /dev/null +++ b/components/pico8/femto8/src/lua/lualib.h @@ -0,0 +1,57 @@ +/* +** $Id: lualib.h,v 1.43 2011/12/08 12:11:37 roberto Exp $ +** Lua standard libraries +** See Copyright Notice in lua.h +*/ + + +#ifndef lualib_h +#define lualib_h + +#include "lua.h" + + + +LUAMOD_API int (luaopen_base) (lua_State *L); + +LUAMOD_API int (luaopen_pico8) (lua_State *L); + +#define LUA_COLIBNAME "coroutine" +LUAMOD_API int (luaopen_coroutine) (lua_State *L); + +#define LUA_TABLIBNAME "table" +LUAMOD_API int (luaopen_table) (lua_State *L); + +#define LUA_IOLIBNAME "io" +LUAMOD_API int (luaopen_io) (lua_State *L); + +#define LUA_OSLIBNAME "os" +LUAMOD_API int (luaopen_os) (lua_State *L); + +#define LUA_STRLIBNAME "string" +LUAMOD_API int (luaopen_string) (lua_State *L); + +#define LUA_BITLIBNAME "bit32" +LUAMOD_API int (luaopen_bit32) (lua_State *L); + +#define LUA_MATHLIBNAME "math" +LUAMOD_API int (luaopen_math) (lua_State *L); + +#define LUA_DBLIBNAME "debug" +LUAMOD_API int (luaopen_debug) (lua_State *L); + +#define LUA_LOADLIBNAME "package" +LUAMOD_API int (luaopen_package) (lua_State *L); + + +/* open all previous libraries */ +LUALIB_API void (luaL_openlibs) (lua_State *L); + + + +#if !defined(lua_assert) +#define lua_assert(x) ((void)0) +#endif + + +#endif diff --git a/components/pico8/femto8/src/lua/lundump.c b/components/pico8/femto8/src/lua/lundump.c new file mode 100644 index 00000000..54de011a --- /dev/null +++ b/components/pico8/femto8/src/lua/lundump.c @@ -0,0 +1,258 @@ +/* +** $Id: lundump.c,v 2.22 2012/05/08 13:53:33 roberto Exp $ +** load precompiled Lua chunks +** See Copyright Notice in lua.h +*/ + +#include + +#define lundump_c +#define LUA_CORE + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstring.h" +#include "lundump.h" +#include "lzio.h" + +typedef struct { + lua_State* L; + ZIO* Z; + Mbuffer* b; + const char* name; +} LoadState; + +static l_noret error(LoadState* S, const char* why) +{ + luaO_pushfstring(S->L,"%s: %s precompiled chunk",S->name,why); + luaD_throw(S->L,LUA_ERRSYNTAX); +} + +#define LoadMem(S,b,n,size) LoadBlock(S,b,(n)*(size)) +#define LoadByte(S) (lu_byte)LoadChar(S) +#define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x)) +#define LoadVector(S,b,n,size) LoadMem(S,b,n,size) + +#if !defined(luai_verifycode) +#define luai_verifycode(L,b,f) /* empty */ +#endif + +static void LoadBlock(LoadState* S, void* b, size_t size) +{ + if (luaZ_read(S->Z,b,size)!=0) error(S,"truncated"); +} + +static int LoadChar(LoadState* S) +{ + char x; + LoadVar(S,x); + return x; +} + +static int LoadInt(LoadState* S) +{ + int x; + LoadVar(S,x); + if (x<0) error(S,"corrupted"); + return x; +} + +static lua_Number LoadNumber(LoadState* S) +{ + lua_Number x; + LoadVar(S,x); + return x; +} + +static TString* LoadString(LoadState* S) +{ + size_t size; + LoadVar(S,size); + if (size==0) + return NULL; + else + { + char* s=luaZ_openspace(S->L,S->b,size); + LoadBlock(S,s,size*sizeof(char)); + return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */ + } +} + +static void LoadCode(LoadState* S, Proto* f) +{ + int n=LoadInt(S); + f->code=luaM_newvector(S->L,n,Instruction); + f->sizecode=n; + LoadVector(S,f->code,n,sizeof(Instruction)); +} + +static void LoadFunction(LoadState* S, Proto* f); + +static void LoadConstants(LoadState* S, Proto* f) +{ + int i,n; + n=LoadInt(S); + f->k=luaM_newvector(S->L,n,TValue); + f->sizek=n; + for (i=0; ik[i]); + for (i=0; ik[i]; + int t=LoadChar(S); + switch (t) + { + case LUA_TNIL: + setnilvalue(o); + break; + case LUA_TBOOLEAN: + setbvalue(o,LoadChar(S)); + break; + case LUA_TNUMBER: + setnvalue(o,LoadNumber(S)); + break; + case LUA_TSTRING: + setsvalue2n(S->L,o,LoadString(S)); + break; + default: lua_assert(0); + } + } + n=LoadInt(S); + f->p=luaM_newvector(S->L,n,Proto*); + f->sizep=n; + for (i=0; ip[i]=NULL; + for (i=0; ip[i]=luaF_newproto(S->L); + LoadFunction(S,f->p[i]); + } +} + +static void LoadUpvalues(LoadState* S, Proto* f) +{ + int i,n; + n=LoadInt(S); + f->upvalues=luaM_newvector(S->L,n,Upvaldesc); + f->sizeupvalues=n; + for (i=0; iupvalues[i].name=NULL; + for (i=0; iupvalues[i].instack=LoadByte(S); + f->upvalues[i].idx=LoadByte(S); + } +} + +static void LoadDebug(LoadState* S, Proto* f) +{ + int i,n; + f->source=LoadString(S); + n=LoadInt(S); + f->lineinfo=luaM_newvector(S->L,n,int); + f->sizelineinfo=n; + LoadVector(S,f->lineinfo,n,sizeof(int)); + n=LoadInt(S); + f->locvars=luaM_newvector(S->L,n,LocVar); + f->sizelocvars=n; + for (i=0; ilocvars[i].varname=NULL; + for (i=0; ilocvars[i].varname=LoadString(S); + f->locvars[i].startpc=LoadInt(S); + f->locvars[i].endpc=LoadInt(S); + } + n=LoadInt(S); + for (i=0; iupvalues[i].name=LoadString(S); +} + +static void LoadFunction(LoadState* S, Proto* f) +{ + f->linedefined=LoadInt(S); + f->lastlinedefined=LoadInt(S); + f->numparams=LoadByte(S); + f->is_vararg=LoadByte(S); + f->maxstacksize=LoadByte(S); + LoadCode(S,f); + LoadConstants(S,f); + LoadUpvalues(S,f); + LoadDebug(S,f); +} + +/* the code below must be consistent with the code in luaU_header */ +#define N0 LUAC_HEADERSIZE +#define N1 (sizeof(LUA_SIGNATURE)-sizeof(char)) +#define N2 N1+2 +#define N3 N2+6 + +static void LoadHeader(LoadState* S) +{ + lu_byte h[LUAC_HEADERSIZE]; + lu_byte s[LUAC_HEADERSIZE]; + luaU_header(h); + memcpy(s,h,sizeof(char)); /* first char already read */ + LoadBlock(S,s+sizeof(char),LUAC_HEADERSIZE-sizeof(char)); + if (memcmp(h,s,N0)==0) return; + if (memcmp(h,s,N1)!=0) error(S,"not a"); + if (memcmp(h,s,N2)!=0) error(S,"version mismatch in"); + if (memcmp(h,s,N3)!=0) error(S,"incompatible"); else error(S,"corrupted"); +} + +/* +** load precompiled chunk +*/ +Closure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name) +{ + LoadState S; + Closure* cl; + if (*name=='@' || *name=='=') + S.name=name+1; + else if (*name==LUA_SIGNATURE[0]) + S.name="binary string"; + else + S.name=name; + S.L=L; + S.Z=Z; + S.b=buff; + LoadHeader(&S); + cl=luaF_newLclosure(L,1); + setclLvalue(L,L->top,cl); incr_top(L); + cl->l.p=luaF_newproto(L); + LoadFunction(&S,cl->l.p); + if (cl->l.p->sizeupvalues != 1) + { + Proto* p=cl->l.p; + cl=luaF_newLclosure(L,cl->l.p->sizeupvalues); + cl->l.p=p; + setclLvalue(L,L->top-1,cl); + } + luai_verifycode(L,buff,cl->l.p); + return cl; +} + +#define MYINT(s) (s[0]-'0') +#define VERSION MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR) +#define FORMAT 0 /* this is the official format */ + +/* +* make header for precompiled chunks +* if you change the code below be sure to update LoadHeader and FORMAT above +* and LUAC_HEADERSIZE in lundump.h +*/ +void luaU_header (lu_byte* h) +{ + int x=1; + memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-sizeof(char)); + h+=sizeof(LUA_SIGNATURE)-sizeof(char); + *h++=cast_byte(VERSION); + *h++=cast_byte(FORMAT); + *h++=cast_byte(*(char*)&x); /* endianness */ + *h++=cast_byte(sizeof(int)); + *h++=cast_byte(sizeof(size_t)); + *h++=cast_byte(sizeof(Instruction)); + *h++=cast_byte(sizeof(lua_Number)); + *h++=cast_byte(((lua_Number)0.5)==0); /* is lua_Number integral? */ + memcpy(h,LUAC_TAIL,sizeof(LUAC_TAIL)-sizeof(char)); +} diff --git a/components/pico8/femto8/src/lua/lundump.h b/components/pico8/femto8/src/lua/lundump.h new file mode 100644 index 00000000..2b8accec --- /dev/null +++ b/components/pico8/femto8/src/lua/lundump.h @@ -0,0 +1,28 @@ +/* +** $Id: lundump.h,v 1.39 2012/05/08 13:53:33 roberto Exp $ +** load precompiled Lua chunks +** See Copyright Notice in lua.h +*/ + +#ifndef lundump_h +#define lundump_h + +#include "lobject.h" +#include "lzio.h" + +/* load one chunk; from lundump.c */ +LUAI_FUNC Closure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name); + +/* make header; from lundump.c */ +LUAI_FUNC void luaU_header (lu_byte* h); + +/* dump one chunk; from ldump.c */ +LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip); + +/* data to catch conversion errors */ +#define LUAC_TAIL "\x19\x93\r\n\x1a\n" + +/* size in bytes of header of binary files */ +#define LUAC_HEADERSIZE (sizeof(LUA_SIGNATURE)-sizeof(char)+2+6+sizeof(LUAC_TAIL)-sizeof(char)) + +#endif diff --git a/components/pico8/femto8/src/lua/lvm.c b/components/pico8/femto8/src/lua/lvm.c new file mode 100644 index 00000000..09fc1fd9 --- /dev/null +++ b/components/pico8/femto8/src/lua/lvm.c @@ -0,0 +1,963 @@ +/* +** $Id: lvm.c,v 2.155 2013/03/16 21:10:18 roberto Exp $ +** Lua virtual machine +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include +#include + +#define lvm_c +#define LUA_CORE + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lvm.h" + + + +/* limit for table tag-method chains (to avoid loops) */ +#define MAXTAGLOOP 100 + + +const TValue *luaV_tonumber (const TValue *obj, TValue *n) { + lua_Number num; + if (ttisnumber(obj)) return obj; + if (ttisstring(obj) && luaO_str2d(svalue(obj), tsvalue(obj)->len, &num)) { + setnvalue(n, num); + return n; + } + else + return NULL; +} + + +int luaV_tostring (lua_State *L, StkId obj) { + if (!ttisnumber(obj)) + return 0; + else { + char s[LUAI_MAXNUMBER2STR]; + lua_Number n = nvalue(obj); + int l = lua_number2str(s, n); + setsvalue2s(L, obj, luaS_newlstr(L, s, l)); + return 1; + } +} + + +static void traceexec (lua_State *L) { + CallInfo *ci = L->ci; + lu_byte mask = L->hookmask; + int counthook = ((mask & LUA_MASKCOUNT) && L->hookcount == 0); + if (counthook) + resethookcount(L); /* reset count */ + if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */ + ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */ + return; /* do not call hook again (VM yielded, so it did not move) */ + } + if (counthook) + luaD_hook(L, LUA_HOOKCOUNT, -1); /* call count hook */ + if (mask & LUA_MASKLINE) { + Proto *p = ci_func(ci)->p; + int npc = pcRel(ci->u.l.savedpc, p); + int newline = getfuncline(p, npc); + if (npc == 0 || /* call linehook when enter a new function, */ + ci->u.l.savedpc <= L->oldpc || /* when jump back (loop), or when */ + newline != getfuncline(p, pcRel(L->oldpc, p))) /* enter a new line */ + luaD_hook(L, LUA_HOOKLINE, newline); /* call line hook */ + } + L->oldpc = ci->u.l.savedpc; + if (L->status == LUA_YIELD) { /* did hook yield? */ + if (counthook) + L->hookcount = 1; /* undo decrement to zero */ + ci->u.l.savedpc--; /* undo increment (resume will increment it again) */ + ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */ + ci->func = L->top - 1; /* protect stack below results */ + luaD_throw(L, LUA_YIELD); + } +} + + +static void callTM (lua_State *L, const TValue *f, const TValue *p1, + const TValue *p2, TValue *p3, int hasres) { + ptrdiff_t result = savestack(L, p3); + setobj2s(L, L->top++, f); /* push function */ + setobj2s(L, L->top++, p1); /* 1st argument */ + setobj2s(L, L->top++, p2); /* 2nd argument */ + if (!hasres) /* no result? 'p3' is third argument */ + setobj2s(L, L->top++, p3); /* 3rd argument */ + /* metamethod may yield only when called from Lua code */ + luaD_call(L, L->top - (4 - hasres), hasres, isLua(L->ci)); + if (hasres) { /* if has result, move it to its place */ + p3 = restorestack(L, result); + setobjs2s(L, p3, --L->top); + } +} + + +void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { + // PICO-8 0.2.5 changelog: sub(str,pos,pos) can be written as str[pos] + if (ttisstring(t)) { + const char *s = svalue(t); + size_t ls = tsvalue(t)->len; + int k = fix32_to_int(nvalue(key)); + size_t idx = k > 0 ? k - 1 : ls + k; + if (idx >= ls) + setnilvalue(val); + else + setsvalue2s(L, val, luaS_newlstr(L, s + idx, 1)); + return; + } + int loop; + for (loop = 0; loop < MAXTAGLOOP; loop++) { + const TValue *tm; + if (ttistable(t)) { /* `t' is a table? */ + Table *h = hvalue(t); + const TValue *res = luaH_get(h, key); /* do a primitive get */ + if (!ttisnil(res) || /* result is not nil? */ + (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */ + setobj2s(L, val, res); + return; + } + /* else will try the tag method */ + } + else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX))) + luaG_typeerror(L, t, "index"); + if (ttisfunction(tm)) { + callTM(L, tm, t, key, val, 1); + return; + } + t = tm; /* else repeat with 'tm' */ + } + luaG_runerror(L, "loop in gettable"); +} + + +void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { + int loop; + for (loop = 0; loop < MAXTAGLOOP; loop++) { + const TValue *tm; + if (ttistable(t)) { /* `t' is a table? */ + Table *h = hvalue(t); + TValue *oldval = cast(TValue *, luaH_get(h, key)); + /* if previous value is not nil, there must be a previous entry + in the table; moreover, a metamethod has no relevance */ + if (!ttisnil(oldval) || + /* previous value is nil; must check the metamethod */ + ((tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL && + /* no metamethod; is there a previous entry in the table? */ + (oldval != luaO_nilobject || + /* no previous entry; must create one. (The next test is + always true; we only need the assignment.) */ + (oldval = luaH_newkey(L, h, key), 1)))) { + /* no metamethod and (now) there is an entry with given key */ + setobj2t(L, oldval, val); /* assign new value to that entry */ + invalidateTMcache(h); + luaC_barrierback(L, obj2gco(h), val); + return; + } + /* else will try the metamethod */ + } + else /* not a table; check metamethod */ + if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX))) + luaG_typeerror(L, t, "index"); + /* there is a metamethod */ + if (ttisfunction(tm)) { + callTM(L, tm, t, key, val, 0); + return; + } + t = tm; /* else repeat with 'tm' */ + } + luaG_runerror(L, "loop in settable"); +} + + +static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2, + StkId res, TMS event) { + const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ + if (ttisnil(tm)) + tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ + if (ttisnil(tm)) return 0; + callTM(L, tm, p1, p2, res, 1); + return 1; +} + + +static const TValue *get_equalTM (lua_State *L, Table *mt1, Table *mt2, + TMS event) { + const TValue *tm1 = fasttm(L, mt1, event); + const TValue *tm2; + if (tm1 == NULL) return NULL; /* no metamethod */ + if (mt1 == mt2) return tm1; /* same metatables => same metamethods */ + tm2 = fasttm(L, mt2, event); + if (tm2 == NULL) return NULL; /* no metamethod */ + if (luaV_rawequalobj(tm1, tm2)) /* same metamethods? */ + return tm1; + return NULL; +} + + +static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2, + TMS event) { + if (!call_binTM(L, p1, p2, L->top, event)) + return -1; /* no metamethod */ + else + return !l_isfalse(L->top); +} + + +static unsigned char PEEK(unsigned char const *ram, unsigned address) +{ + if (!ram || address > 0x10000) + return 0; + if (address >= 0x0000 && address < 0x2000) + address = (ram[0x5f54] << 8) | (address & 0x1fff); + else if (address >= 0x6000 && address < 0x8000) + address = (ram[0x5f55] << 8) | (address & 0x1fff); + return ram[address]; +} + +lua_Number luaV_peek(struct lua_State *L, lua_Number a, int count) +{ + unsigned char const *p = G(L)->pico8memory; + int address = fix32_to_int(a) & 0xffff; + uint32_t ret = 0; + switch (count) { + case 4: + ret |= PEEK(p, address + 1) << 8; + ret |= PEEK(p, address); + address += 2; + case 2: + ret |= PEEK(p, address + 1) << 24; + case 1: + ret |= PEEK(p, address) << 16; + break; + } + return fix32_from_bits(ret); +} + + +static int l_strcmp (const TString *ls, const TString *rs) { + const char *l = getstr(ls); + size_t ll = ls->tsv.len; + const char *r = getstr(rs); + size_t lr = rs->tsv.len; + for (;;) { + int temp = strcoll(l, r); + if (temp != 0) return temp; + else { /* strings are equal up to a `\0' */ + size_t len = strlen(l); /* index of first `\0' in both strings */ + if (len == lr) /* r is finished? */ + return (len == ll) ? 0 : 1; + else if (len == ll) /* l is finished? */ + return -1; /* l is smaller than r (because r is not finished) */ + /* both strings longer than `len'; go on comparing (after the `\0') */ + len++; + l += len; ll -= len; r += len; lr -= len; + } + } +} + + +int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { + int res; + if (ttisnumber(l) && ttisnumber(r)) + return luai_numlt(L, nvalue(l), nvalue(r)); + else if (ttisstring(l) && ttisstring(r)) + return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0; + else if ((res = call_orderTM(L, l, r, TM_LT)) < 0) + luaG_ordererror(L, l, r); + return res; +} + + +int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) { + int res; + if (ttisnumber(l) && ttisnumber(r)) + return luai_numle(L, nvalue(l), nvalue(r)); + else if (ttisstring(l) && ttisstring(r)) + return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0; + else if ((res = call_orderTM(L, l, r, TM_LE)) >= 0) /* first try `le' */ + return res; + else if ((res = call_orderTM(L, r, l, TM_LT)) < 0) /* else try `lt' */ + luaG_ordererror(L, l, r); + return !res; +} + + +/* +** equality of Lua values. L == NULL means raw equality (no metamethods) +*/ +int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2) { + const TValue *tm; + lua_assert(ttisequal(t1, t2)); + switch (ttype(t1)) { + case LUA_TNIL: return 1; + case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); + case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */ + case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); + case LUA_TLCF: return fvalue(t1) == fvalue(t2); + case LUA_TSHRSTR: return eqshrstr(rawtsvalue(t1), rawtsvalue(t2)); + case LUA_TLNGSTR: return luaS_eqlngstr(rawtsvalue(t1), rawtsvalue(t2)); + case LUA_TUSERDATA: { + if (uvalue(t1) == uvalue(t2)) return 1; + else if (L == NULL) return 0; + tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ); + break; /* will try TM */ + } + case LUA_TTABLE: { + if (hvalue(t1) == hvalue(t2)) return 1; + else if (L == NULL) return 0; + tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ); + break; /* will try TM */ + } + default: + lua_assert(iscollectable(t1)); + return gcvalue(t1) == gcvalue(t2); + } + if (tm == NULL) return 0; /* no TM? */ + callTM(L, tm, t1, t2, L->top, 1); /* call TM */ + return !l_isfalse(L->top); +} + + +void luaV_concat (lua_State *L, int total) { + lua_assert(total >= 2); + do { + StkId top = L->top; + int n = 2; /* number of elements handled in this pass (at least 2) */ + if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) { + if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT)) + luaG_concaterror(L, top-2, top-1); + } + else if (tsvalue(top-1)->len == 0) /* second operand is empty? */ + (void)tostring(L, top - 2); /* result is first operand */ + else if (ttisstring(top-2) && tsvalue(top-2)->len == 0) { + setobjs2s(L, top - 2, top - 1); /* result is second op. */ + } + else { + /* at least two non-empty string values; get as many as possible */ + size_t tl = tsvalue(top-1)->len; + char *buffer; + int i; + /* collect total length */ + for (i = 1; i < total && tostring(L, top-i-1); i++) { + size_t l = tsvalue(top-i-1)->len; + if (l >= (MAX_SIZET/sizeof(char)) - tl) + luaG_runerror(L, "string length overflow"); + tl += l; + } + buffer = luaZ_openspace(L, &G(L)->buff, tl); + tl = 0; + n = i; + do { /* concat all strings */ + size_t l = tsvalue(top-i)->len; + memcpy(buffer+tl, svalue(top-i), l * sizeof(char)); + tl += l; + } while (--i > 0); + setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl)); + } + total -= n-1; /* got 'n' strings to create 1 new */ + L->top -= n-1; /* popped 'n' strings and pushed one */ + } while (total > 1); /* repeat until only 1 result left */ +} + + +void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) { + const TValue *tm; + switch (ttypenv(rb)) { + case LUA_TTABLE: { + Table *h = hvalue(rb); + tm = fasttm(L, h->metatable, TM_LEN); + if (tm) break; /* metamethod? break switch to call it */ + setnvalue(ra, cast_num(luaH_getn(h))); /* else primitive len */ + return; + } + case LUA_TSTRING: { + setnvalue(ra, cast_num((int)(uint64_t)tsvalue(rb)->len)); + return; + } + default: { /* try metamethod */ + tm = luaT_gettmbyobj(L, rb, TM_LEN); + if (ttisnil(tm)) /* no metamethod? */ + luaG_typeerror(L, rb, "get length of"); + break; + } + } + callTM(L, tm, rb, rb, ra, 1); +} + + +void luaV_arith (lua_State *L, StkId ra, const TValue *rb, + const TValue *rc, TMS op) { + TValue tempb, tempc; + const TValue *b, *c; + if ((b = luaV_tonumber(rb, &tempb)) != NULL && + (c = luaV_tonumber(rc, &tempc)) != NULL) { + lua_Number res = luaO_arith(L, op - TM_ADD + LUA_OPADD, nvalue(b), nvalue(c)); + setnvalue(ra, res); + } + else if (!call_binTM(L, rb, rc, ra, op)) + luaG_aritherror(L, rb, rc); +} + + +/* +** check whether cached closure in prototype 'p' may be reused, that is, +** whether there is a cached closure with the same upvalues needed by +** new closure to be created. +*/ +static Closure *getcached (Proto *p, UpVal **encup, StkId base) { + Closure *c = p->cache; + if (c != NULL) { /* is there a cached closure? */ + int nup = p->sizeupvalues; + Upvaldesc *uv = p->upvalues; + int i; + for (i = 0; i < nup; i++) { /* check whether it has right upvalues */ + TValue *v = uv[i].instack ? base + uv[i].idx : encup[uv[i].idx]->v; + if (c->l.upvals[i]->v != v) + return NULL; /* wrong upvalue; cannot reuse closure */ + } + } + return c; /* return cached closure (or NULL if no cached closure) */ +} + + +/* +** create a new Lua closure, push it in the stack, and initialize +** its upvalues. Note that the call to 'luaC_barrierproto' must come +** before the assignment to 'p->cache', as the function needs the +** original value of that field. +*/ +static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base, + StkId ra) { + int nup = p->sizeupvalues; + Upvaldesc *uv = p->upvalues; + int i; + Closure *ncl = luaF_newLclosure(L, nup); + ncl->l.p = p; + setclLvalue(L, ra, ncl); /* anchor new closure in stack */ + for (i = 0; i < nup; i++) { /* fill in its upvalues */ + if (uv[i].instack) /* upvalue refers to local variable? */ + ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx); + else /* get upvalue from enclosing function */ + ncl->l.upvals[i] = encup[uv[i].idx]; + } + luaC_barrierproto(L, p, ncl); + p->cache = ncl; /* save it on cache for reuse */ +} + + +/* +** finish execution of an opcode interrupted by an yield +*/ +void luaV_finishOp (lua_State *L) { + CallInfo *ci = L->ci; + StkId base = ci->u.l.base; + Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */ + OpCode op = GET_OPCODE(inst); + switch (op) { /* finish its execution */ + case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: + case OP_MOD: case OP_POW: case OP_IDIV: case OP_BAND: + case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR: + case OP_LSHR: case OP_ROTL: case OP_ROTR: + case OP_UNM: case OP_BNOT: case OP_LEN: + case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: { + setobjs2s(L, base + GETARG_A(inst), --L->top); + break; + } + case OP_LE: case OP_LT: case OP_EQ: { + int res = !l_isfalse(L->top - 1); + L->top--; + /* metamethod should not be called when operand is K */ + lua_assert(!ISK(GETARG_B(inst))); + if (op == OP_LE && /* "<=" using "<" instead? */ + ttisnil(luaT_gettmbyobj(L, base + GETARG_B(inst), TM_LE))) + res = !res; /* invert result */ + lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP); + if (res != GETARG_A(inst)) /* condition failed? */ + ci->u.l.savedpc++; /* skip jump instruction */ + break; + } + case OP_CONCAT: { + StkId top = L->top - 1; /* top when 'call_binTM' was called */ + int b = GETARG_B(inst); /* first element to concatenate */ + int total = cast_int(top - 1 - (base + b)); /* yet to concatenate */ + setobj2s(L, top - 2, top); /* put TM result in proper position */ + if (total > 1) { /* are there elements to concat? */ + L->top = top - 1; /* top is one after last element (at top-2) */ + luaV_concat(L, total); /* concat them (may yield again) */ + } + /* move final result to final position */ + setobj2s(L, ci->u.l.base + GETARG_A(inst), L->top - 1); + L->top = ci->top; /* restore top */ + break; + } + case OP_TFORCALL: { + lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_TFORLOOP); + L->top = ci->top; /* correct top */ + break; + } + case OP_CALL: { + if (GETARG_C(inst) - 1 >= 0) /* nresults >= 0? */ + L->top = ci->top; /* adjust results */ + break; + } + case OP_TAILCALL: case OP_SETTABUP: case OP_SETTABLE: + break; + default: lua_assert(0); + } +} + + + +/* +** some macros for common tasks in `luaV_execute' +*/ + +#if !defined luai_runtimecheck +#define luai_runtimecheck(L, c) /* void */ +#endif + + +#define RA(i) (base+GETARG_A(i)) +/* to be used after possible stack reallocation */ +#define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i)) +#define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i)) +#define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \ + ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i)) +#define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \ + ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i)) +#define KBx(i) \ + (k + (GETARG_Bx(i) != 0 ? GETARG_Bx(i) - 1 : GETARG_Ax(*ci->u.l.savedpc++))) + + +/* execute a jump instruction */ +#define dojump(ci,i,e) \ + { int a = GETARG_A(i); \ + if (a > 0) luaF_close(L, ci->u.l.base + a - 1); \ + ci->u.l.savedpc += GETARG_sBx(i) + e; } + +/* for test instructions, execute the jump instruction that follows it */ +#define donextjump(ci) { i = *ci->u.l.savedpc; dojump(ci, i, 1); } + + +#define Protect(x) { {x;}; base = ci->u.l.base; } + +#define checkGC(L,c) \ + Protect( luaC_condGC(L,{L->top = (c); /* limit of live values */ \ + luaC_step(L); \ + L->top = ci->top;}) /* restore top */ \ + luai_threadyield(L); ) + + +#define arith_op(op,tm) { \ + TValue *rb = RKB(i); \ + TValue *rc = RKC(i); \ + if (ttisnumber(rb) && ttisnumber(rc)) { \ + lua_Number nb = nvalue(rb), nc = nvalue(rc); \ + setnvalue(ra, op(L, nb, nc)); \ + } \ + else { Protect(luaV_arith(L, ra, rb, rc, tm)); } } + +#define unary_op(op,tm) {\ + TValue *rb = RB(i); \ + if (ttisnumber(rb)) { \ + lua_Number nb = nvalue(rb); \ + setnvalue(ra, op(L, nb)); \ + } \ + else { Protect(luaV_arith(L, ra, rb, rb, tm)); } } + +#define vmdispatch(o) switch(o) +#define vmcase(l,b) case l: {b} break; +#define vmcasenb(l,b) case l: {b} /* nb = no break */ + +void luaV_execute (lua_State *L) { + CallInfo *ci = L->ci; + LClosure *cl; + TValue *k; + StkId base; + newframe: /* reentry point when frame changes (call/return) */ + lua_assert(ci == L->ci); + cl = clLvalue(ci->func); + k = cl->p->k; + base = ci->u.l.base; + /* main loop of interpreter */ + for (;;) { + Instruction i = *(ci->u.l.savedpc++); + StkId ra; + if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) && + (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) { + Protect(traceexec(L)); + } + /* WARNING: several calls may realloc the stack and invalidate `ra' */ + ra = RA(i); + lua_assert(base == ci->u.l.base); + lua_assert(base <= L->top && L->top < L->stack + L->stacksize); + vmdispatch (GET_OPCODE(i)) { + vmcase(OP_MOVE, + setobjs2s(L, ra, RB(i)); + ) + vmcase(OP_LOADK, + TValue *rb = k + GETARG_Bx(i); + setobj2s(L, ra, rb); + ) + vmcase(OP_LOADKX, + TValue *rb; + lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG); + rb = k + GETARG_Ax(*ci->u.l.savedpc++); + setobj2s(L, ra, rb); + ) + vmcase(OP_LOADBOOL, + setbvalue(ra, GETARG_B(i)); + if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */ + ) + vmcase(OP_LOADNIL, + int b = GETARG_B(i); + do { + setnilvalue(ra++); + } while (b--); + ) + vmcase(OP_GETUPVAL, + int b = GETARG_B(i); + setobj2s(L, ra, cl->upvals[b]->v); + ) + vmcase(OP_GETTABUP, + int b = GETARG_B(i); + Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra)); + ) + vmcase(OP_GETTABLE, + Protect(luaV_gettable(L, RB(i), RKC(i), ra)); + ) + vmcase(OP_SETTABUP, + int a = GETARG_A(i); + Protect(luaV_settable(L, cl->upvals[a]->v, RKB(i), RKC(i))); + ) + vmcase(OP_SETUPVAL, + UpVal *uv = cl->upvals[GETARG_B(i)]; + setobj(L, uv->v, ra); + luaC_barrier(L, uv, ra); + ) + vmcase(OP_SETTABLE, + Protect(luaV_settable(L, ra, RKB(i), RKC(i))); + ) + vmcase(OP_NEWTABLE, + int b = GETARG_B(i); + int c = GETARG_C(i); + Table *t = luaH_new(L); + sethvalue(L, ra, t); + if (b != 0 || c != 0) + luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c)); + checkGC(L, ra + 1); + ) + vmcase(OP_SELF, + StkId rb = RB(i); + setobjs2s(L, ra+1, rb); + Protect(luaV_gettable(L, rb, RKC(i), ra)); + ) + vmcase(OP_ADD, + arith_op(luai_numadd, TM_ADD); + ) + vmcase(OP_SUB, + arith_op(luai_numsub, TM_SUB); + ) + vmcase(OP_MUL, + arith_op(luai_nummul, TM_MUL); + ) + vmcase(OP_DIV, + arith_op(luai_numdiv, TM_DIV); + ) + vmcase(OP_MOD, + arith_op(luai_nummod, TM_MOD); + ) + vmcase(OP_POW, + arith_op(luai_numpow, TM_POW); + ) + vmcase(OP_IDIV, + arith_op(luai_numidiv, TM_IDIV); + ) + vmcase(OP_BAND, + arith_op(luai_numband, TM_BAND); + ) + vmcase(OP_BOR, + arith_op(luai_numbor, TM_BOR); + ) + vmcase(OP_BXOR, + arith_op(luai_numbxor, TM_BXOR); + ) + vmcase(OP_SHL, + arith_op(luai_numshl, TM_SHL); + ) + vmcase(OP_SHR, + arith_op(luai_numshr, TM_SHR); + ) + vmcase(OP_LSHR, + arith_op(luai_numlshr, TM_LSHR); + ) + vmcase(OP_ROTL, + arith_op(luai_numrotl, TM_ROTL); + ) + vmcase(OP_ROTR, + arith_op(luai_numrotr, TM_ROTR); + ) + vmcase(OP_UNM, + unary_op(luai_numunm, TM_UNM); + ) + vmcase(OP_BNOT, + unary_op(luai_numbnot, TM_BNOT); + ) + vmcase(OP_PEEK, + unary_op(luai_numpeek, TM_PEEK); + ) + vmcase(OP_PEEK2, + unary_op(luai_numpeek2, TM_PEEK2); + ) + vmcase(OP_PEEK4, + unary_op(luai_numpeek4, TM_PEEK4); + ) + vmcase(OP_NOT, + TValue *rb = RB(i); + int res = l_isfalse(rb); /* next assignment may change this value */ + setbvalue(ra, res); + ) + vmcase(OP_LEN, + Protect(luaV_objlen(L, ra, RB(i))); + ) + vmcase(OP_CONCAT, + int b = GETARG_B(i); + int c = GETARG_C(i); + StkId rb; + L->top = base + c + 1; /* mark the end of concat operands */ + Protect(luaV_concat(L, c - b + 1)); + ra = RA(i); /* 'luav_concat' may invoke TMs and move the stack */ + rb = b + base; + setobjs2s(L, ra, rb); + checkGC(L, (ra >= rb ? ra + 1 : rb)); + L->top = ci->top; /* restore top */ + ) + vmcase(OP_JMP, + dojump(ci, i, 0); + ) + vmcase(OP_EQ, + TValue *rb = RKB(i); + TValue *rc = RKC(i); + Protect( + if (cast_int(equalobj(L, rb, rc)) != GETARG_A(i)) + ci->u.l.savedpc++; + else + donextjump(ci); + ) + ) + vmcase(OP_LT, + Protect( + if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i)) + ci->u.l.savedpc++; + else + donextjump(ci); + ) + ) + vmcase(OP_LE, + Protect( + if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i)) + ci->u.l.savedpc++; + else + donextjump(ci); + ) + ) + vmcase(OP_TEST, + if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra)) + ci->u.l.savedpc++; + else + donextjump(ci); + ) + vmcase(OP_TESTSET, + TValue *rb = RB(i); + if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb)) + ci->u.l.savedpc++; + else { + setobjs2s(L, ra, rb); + donextjump(ci); + } + ) + vmcase(OP_CALL, + int b = GETARG_B(i); + int nresults = GETARG_C(i) - 1; + if (b != 0) L->top = ra+b; /* else previous instruction set top */ + if (luaD_precall(L, ra, nresults)) { /* C function? */ + if (nresults >= 0) L->top = ci->top; /* adjust results */ + base = ci->u.l.base; + } + else { /* Lua function */ + ci = L->ci; + ci->callstatus |= CIST_REENTRY; + goto newframe; /* restart luaV_execute over new Lua function */ + } + ) + vmcase(OP_TAILCALL, + int b = GETARG_B(i); + if (b != 0) L->top = ra+b; /* else previous instruction set top */ + lua_assert(GETARG_C(i) - 1 == LUA_MULTRET); + if (luaD_precall(L, ra, LUA_MULTRET)) /* C function? */ + base = ci->u.l.base; + else { + /* tail call: put called frame (n) in place of caller one (o) */ + CallInfo *nci = L->ci; /* called frame */ + CallInfo *oci = nci->previous; /* caller frame */ + StkId nfunc = nci->func; /* called function */ + StkId ofunc = oci->func; /* caller function */ + /* last stack slot filled by 'precall' */ + StkId lim = nci->u.l.base + getproto(nfunc)->numparams; + int aux; + /* close all upvalues from previous call */ + if (cl->p->sizep > 0) luaF_close(L, oci->u.l.base); + /* move new frame into old one */ + for (aux = 0; nfunc + aux < lim; aux++) + setobjs2s(L, ofunc + aux, nfunc + aux); + oci->u.l.base = ofunc + (nci->u.l.base - nfunc); /* correct base */ + oci->top = L->top = ofunc + (L->top - nfunc); /* correct top */ + oci->u.l.savedpc = nci->u.l.savedpc; + oci->callstatus |= CIST_TAIL; /* function was tail called */ + ci = L->ci = oci; /* remove new frame */ + lua_assert(L->top == oci->u.l.base + getproto(ofunc)->maxstacksize); + goto newframe; /* restart luaV_execute over new Lua function */ + } + ) + vmcasenb(OP_RETURN, + int b = GETARG_B(i); + if (b != 0) L->top = ra+b-1; + if (cl->p->sizep > 0) luaF_close(L, base); + b = luaD_poscall(L, ra); + if (!(ci->callstatus & CIST_REENTRY)) /* 'ci' still the called one */ + return; /* external invocation: return */ + else { /* invocation via reentry: continue execution */ + ci = L->ci; + if (b) L->top = ci->top; + lua_assert(isLua(ci)); + lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL); + goto newframe; /* restart luaV_execute over new Lua function */ + } + ) + vmcase(OP_FORLOOP, + lua_Number step = nvalue(ra+2); + lua_Number prev = nvalue(ra); /* index before increment */ + lua_Number idx = luai_numadd(L, prev, step); /* increment index */ + lua_Number limit = nvalue(ra+1); + /* fix32 addition wraps on overflow. Detect when idx wrapped past the + representable range: for a positive step idx should never decrease, + and for a negative step it should never increase. When a wrap is + detected AND prev was still inside the loop bounds, the loop is + done (we overflowed past the limit rather than wrapping back to + init as FORPREP does for loops starting at FIX32_MIN). */ + int wrapped = luai_numlt(L, 0, step) + ? (luai_numlt(L, idx, prev) && luai_numle(L, prev, limit)) + : (luai_numlt(L, prev, idx) && luai_numle(L, limit, prev)); + if (!wrapped && (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit) + : luai_numle(L, limit, idx))) { + ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ + setnvalue(ra, idx); /* update internal index... */ + setnvalue(ra+3, idx); /* ...and external index */ + } + ) + vmcase(OP_FORPREP, + const TValue *init = ra; + const TValue *plimit = ra+1; + const TValue *pstep = ra+2; + if (!tonumber(init, ra)) + luaG_runerror(L, LUA_QL("for") " initial value must be a number"); + else if (!tonumber(plimit, ra+1)) + luaG_runerror(L, LUA_QL("for") " limit must be a number"); + else if (!tonumber(pstep, ra+2)) + luaG_runerror(L, LUA_QL("for") " step must be a number"); + setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep))); + ci->u.l.savedpc += GETARG_sBx(i); + ) + vmcasenb(OP_TFORCALL, + StkId cb = ra + 3; /* call base */ + setobjs2s(L, cb+2, ra+2); + setobjs2s(L, cb+1, ra+1); + setobjs2s(L, cb, ra); + L->top = cb + 3; /* func. + 2 args (state and index) */ + Protect(luaD_call(L, cb, GETARG_C(i), 1)); + L->top = ci->top; + i = *(ci->u.l.savedpc++); /* go to next instruction */ + ra = RA(i); + lua_assert(GET_OPCODE(i) == OP_TFORLOOP); + goto l_tforloop; + ) + vmcase(OP_TFORLOOP, + l_tforloop: + if (!ttisnil(ra + 1)) { /* continue loop? */ + setobjs2s(L, ra, ra + 1); /* save control variable */ + ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ + } + ) + vmcase(OP_SETLIST, + int n = GETARG_B(i); + int c = GETARG_C(i); + int last; + Table *h; + if (n == 0) n = cast_int(L->top - ra) - 1; + if (c == 0) { + lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG); + c = GETARG_Ax(*ci->u.l.savedpc++); + } + luai_runtimecheck(L, ttistable(ra)); + h = hvalue(ra); + last = ((c-1)*LFIELDS_PER_FLUSH) + n; + if (last > h->sizearray) /* needs more space? */ + luaH_resizearray(L, h, last); /* pre-allocate it at once */ + for (; n > 0; n--) { + TValue *val = ra+n; + luaH_setint(L, h, last--, val); + luaC_barrierback(L, obj2gco(h), val); + } + L->top = ci->top; /* correct top (in case of previous open call) */ + ) + vmcase(OP_CLOSURE, + Proto *p = cl->p->p[GETARG_Bx(i)]; + Closure *ncl = getcached(p, cl->upvals, base); /* cached closure */ + if (ncl == NULL) /* no match? */ + pushclosure(L, p, cl->upvals, base, ra); /* create a new one */ + else + setclLvalue(L, ra, ncl); /* push cashed closure */ + checkGC(L, ra + 1); + ) + vmcase(OP_VARARG, + int b = GETARG_B(i) - 1; + int j; + int n = cast_int(base - ci->func) - cl->p->numparams - 1; + if (b < 0) { /* B == 0? */ + b = n; /* get all var. arguments */ + Protect(luaD_checkstack(L, n)); + ra = RA(i); /* previous call may change the stack */ + L->top = ra + n; + } + for (j = 0; j < b; j++) { + if (j < n) { + setobjs2s(L, ra + j, base - n + j); + } + else { + setnilvalue(ra + j); + } + } + ) + vmcase(OP_EXTRAARG, + lua_assert(0); + ) + } + } +} + diff --git a/components/pico8/femto8/src/lua/lvm.h b/components/pico8/femto8/src/lua/lvm.h new file mode 100644 index 00000000..920c64bb --- /dev/null +++ b/components/pico8/femto8/src/lua/lvm.h @@ -0,0 +1,45 @@ +/* +** $Id: lvm.h,v 2.18 2013/01/08 14:06:55 roberto Exp $ +** Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#ifndef lvm_h +#define lvm_h + + +#include "ldo.h" +#include "lobject.h" +#include "ltm.h" + + +#define tostring(L,o) (ttisstring(o) || (luaV_tostring(L, o))) + +#define tonumber(o,n) (ttisnumber(o) || (((o) = luaV_tonumber(o,n)) != NULL)) + +#define equalobj(L,o1,o2) (ttisequal(o1, o2) && luaV_equalobj_(L, o1, o2)) + +#define luaV_rawequalobj(o1,o2) equalobj(NULL,o1,o2) + + +/* not to called directly */ +LUAI_FUNC int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2); + + +LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); +LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r); +LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n); +LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj); +LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key, + StkId val); +LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key, + StkId val); +LUAI_FUNC void luaV_finishOp (lua_State *L); +LUAI_FUNC void luaV_execute (lua_State *L); +LUAI_FUNC void luaV_concat (lua_State *L, int total); +LUAI_FUNC void luaV_arith (lua_State *L, StkId ra, const TValue *rb, + const TValue *rc, TMS op); +LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb); + +LUAI_FUNC lua_Number luaV_peek(struct lua_State *L, lua_Number a, int count); +#endif diff --git a/components/pico8/femto8/src/lua/lzio.c b/components/pico8/femto8/src/lua/lzio.c new file mode 100644 index 00000000..8b77054e --- /dev/null +++ b/components/pico8/femto8/src/lua/lzio.c @@ -0,0 +1,76 @@ +/* +** $Id: lzio.c,v 1.35 2012/05/14 13:34:18 roberto Exp $ +** Buffered streams +** See Copyright Notice in lua.h +*/ + + +#include + +#define lzio_c +#define LUA_CORE + +#include "lua.h" + +#include "llimits.h" +#include "lmem.h" +#include "lstate.h" +#include "lzio.h" + + +int luaZ_fill (ZIO *z) { + size_t size; + lua_State *L = z->L; + const char *buff; + lua_unlock(L); + buff = z->reader(L, z->data, &size); + lua_lock(L); + if (buff == NULL || size == 0) + return EOZ; + z->n = size - 1; /* discount char being returned */ + z->p = buff; + return cast_uchar(*(z->p++)); +} + + +void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { + z->L = L; + z->reader = reader; + z->data = data; + z->n = 0; + z->p = NULL; +} + + +/* --------------------------------------------------------------- read --- */ +size_t luaZ_read (ZIO *z, void *b, size_t n) { + while (n) { + size_t m; + if (z->n == 0) { /* no bytes in buffer? */ + if (luaZ_fill(z) == EOZ) /* try to read more */ + return n; /* no more input; return number of missing bytes */ + else { + z->n++; /* luaZ_fill consumed first byte; put it back */ + z->p--; + } + } + m = (n <= z->n) ? n : z->n; /* min. between n and z->n */ + memcpy(b, z->p, m); + z->n -= m; + z->p += m; + b = (char *)b + m; + n -= m; + } + return 0; +} + +/* ------------------------------------------------------------------------ */ +char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) { + if (n > buff->buffsize) { + if (n < LUA_MINBUFFER) n = LUA_MINBUFFER; + luaZ_resizebuffer(L, buff, n); + } + return buff->buffer; +} + + diff --git a/components/pico8/femto8/src/lua/lzio.h b/components/pico8/femto8/src/lua/lzio.h new file mode 100644 index 00000000..08682301 --- /dev/null +++ b/components/pico8/femto8/src/lua/lzio.h @@ -0,0 +1,65 @@ +/* +** $Id: lzio.h,v 1.26 2011/07/15 12:48:03 roberto Exp $ +** Buffered streams +** See Copyright Notice in lua.h +*/ + + +#ifndef lzio_h +#define lzio_h + +#include "lua.h" + +#include "lmem.h" + + +#define EOZ (-1) /* end of stream */ + +typedef struct Zio ZIO; + +#define zgetc(z) (((z)->n--)>0 ? cast_uchar(*(z)->p++) : luaZ_fill(z)) + + +typedef struct Mbuffer { + char *buffer; + size_t n; + size_t buffsize; +} Mbuffer; + +#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0) + +#define luaZ_buffer(buff) ((buff)->buffer) +#define luaZ_sizebuffer(buff) ((buff)->buffsize) +#define luaZ_bufflen(buff) ((buff)->n) + +#define luaZ_resetbuffer(buff) ((buff)->n = 0) + + +#define luaZ_resizebuffer(L, buff, size) \ + (luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \ + (buff)->buffsize = size) + +#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) + + +LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n); +LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, + void *data); +LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n bytes */ + + + +/* --------- Private Part ------------------ */ + +struct Zio { + size_t n; /* bytes still unread */ + const char *p; /* current position in buffer */ + lua_Reader reader; /* reader function */ + void* data; /* additional data */ + lua_State *L; /* Lua state (for reader) */ +}; + + +LUAI_FUNC int luaZ_fill (ZIO *z); + +#endif diff --git a/components/pico8/femto8/src/lua/makefile b/components/pico8/femto8/src/lua/makefile new file mode 100644 index 00000000..706bab48 --- /dev/null +++ b/components/pico8/femto8/src/lua/makefile @@ -0,0 +1,163 @@ +# makefile for building Lua +# see INSTALL for installation instructions +# see ../Makefile and luaconf.h for further customization + +# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT ======================= + +CWARNS= -pedantic -Wcast-align -Wpointer-arith -Wshadow \ + -Wsign-compare -Wundef -Wwrite-strings +# -Wcast-qual + +# -DEXTERNMEMCHECK -DHARDSTACKTESTS +# -g -DLUA_USER_H='"ltests.h"' +# -fomit-frame-pointer #-pg -malign-double +TESTS= -g -DLUA_USER_H='"ltests.h"' + +LOCAL = $(CWARNS) + + +CC= g++ +CFLAGS= -Wall -Wno-deprecated -std=c++17 $(MYCFLAGS) -O2 +AR= ar rcu +RANLIB= ranlib +RM= rm -f + +MYCFLAGS= $(LOCAL) +MYLDFLAGS= +MYLIBS= + + +# enable Linux goodies +ifneq ($(OS),Windows_NT) +MYCFLAGS= $(LOCAL) -DLUA_USE_LINUX +MYLDFLAGS= -Wl,-E +MYLIBS= -ldl +endif +MYLIBS= -lreadline -lhistory + + + +# == END OF USER SETTINGS. NO NEED TO CHANGE ANYTHING BELOW THIS LINE ========= + + +LIBS = -lm + +CORE_T= liblua.a +CORE_O= lapi.o lcode.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o \ + lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o \ + lundump.o lvm.o lzio.o lctype.o +AUX_O= lauxlib.o +LIB_O= lbaselib.o lcorolib.o ldblib.o ltablib.o lstrlib.o lpico8lib.o linit.o + +LUA_T= z8lua +LUA_O= lua.o + +#LUAC_T= luac +#LUAC_O= luac.o print.o + +ALL_T= $(CORE_T) $(LUA_T) $(LUAC_T) +ALL_O= $(CORE_O) $(LUA_O) $(LUAC_O) $(AUX_O) $(LIB_O) +ALL_A= $(CORE_T) + +all: $(ALL_T) + +o: $(ALL_O) + +a: $(ALL_A) + +$(CORE_T): $(CORE_O) $(AUX_O) $(LIB_O) + $(AR) $@ $? + $(RANLIB) $@ + +$(LUA_T): $(LUA_O) $(CORE_T) + $(CC) -o $@ $(MYLDFLAGS) $(LUA_O) $(CORE_T) $(LIBS) $(MYLIBS) $(DL) + +$(LUAC_T): $(LUAC_O) $(CORE_T) + $(CC) -o $@ $(MYLDFLAGS) $(LUAC_O) $(CORE_T) $(LIBS) $(MYLIBS) + +clean: + rcsclean -u || true + $(RM) $(ALL_T) $(ALL_O) + +depend: + @$(CC) $(CFLAGS) -MM *.c + +echo: + @echo "CC = $(CC)" + @echo "CFLAGS = $(CFLAGS)" + @echo "AR = $(AR)" + @echo "RANLIB = $(RANLIB)" + @echo "RM = $(RM)" + @echo "MYCFLAGS = $(MYCFLAGS)" + @echo "MYLDFLAGS = $(MYLDFLAGS)" + @echo "MYLIBS = $(MYLIBS)" + @echo "DL = $(DL)" + +# DO NOT DELETE + +lapi.o: lapi.c lua.h luaconf.h fix32.h lapi.h llimits.h lstate.h \ + lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h \ + ltable.h lundump.h lvm.h +lauxlib.o: lauxlib.c lua.h luaconf.h fix32.h lauxlib.h +lbaselib.o: lbaselib.c lua.h luaconf.h fix32.h lauxlib.h lualib.h +lbitlib.o: lbitlib.c lua.h luaconf.h fix32.h lauxlib.h lualib.h +lcode.o: lcode.c lua.h luaconf.h fix32.h lcode.h llex.h lobject.h \ + llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \ + ldo.h lgc.h lstring.h ltable.h lvm.h +lcorolib.o: lcorolib.c lua.h luaconf.h fix32.h lauxlib.h lualib.h +lctype.o: lctype.c lctype.h lua.h luaconf.h fix32.h llimits.h +ldblib.o: ldblib.c lua.h luaconf.h fix32.h lauxlib.h lualib.h +ldebug.o: ldebug.c lua.h luaconf.h fix32.h lapi.h llimits.h lstate.h \ + lobject.h ltm.h lzio.h lmem.h lcode.h llex.h lopcodes.h lparser.h \ + ldebug.h ldo.h lfunc.h lstring.h lgc.h ltable.h lvm.h +ldo.o: ldo.c lua.h luaconf.h fix32.h lapi.h llimits.h lstate.h lobject.h \ + ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h lparser.h \ + lstring.h ltable.h lundump.h lvm.h +ldump.o: ldump.c lua.h luaconf.h fix32.h lobject.h llimits.h lstate.h \ + ltm.h lzio.h lmem.h lundump.h +lfunc.o: lfunc.c lua.h luaconf.h fix32.h lfunc.h lobject.h llimits.h \ + lgc.h lstate.h ltm.h lzio.h lmem.h +lgc.o: lgc.c lua.h luaconf.h fix32.h ldebug.h lstate.h lobject.h \ + llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h +linit.o: linit.c lua.h luaconf.h fix32.h lualib.h lauxlib.h +liolib.o: liolib.c lua.h luaconf.h fix32.h lauxlib.h lualib.h +llex.o: llex.c lua.h luaconf.h fix32.h lctype.h llimits.h ldo.h lobject.h \ + lstate.h ltm.h lzio.h lmem.h llex.h lparser.h lstring.h lgc.h ltable.h +lmathlib.o: lmathlib.c lua.h luaconf.h fix32.h lauxlib.h lualib.h +lmem.o: lmem.c lua.h luaconf.h fix32.h ldebug.h lstate.h lobject.h \ + llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h +loadlib.o: loadlib.c lua.h luaconf.h fix32.h lauxlib.h lualib.h +lobject.o: lobject.c lua.h luaconf.h fix32.h lctype.h llimits.h ldebug.h \ + lstate.h lobject.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h lvm.h +lopcodes.o: lopcodes.c lopcodes.h llimits.h lua.h luaconf.h fix32.h +loslib.o: loslib.c lua.h luaconf.h fix32.h lauxlib.h lualib.h +lparser.o: lparser.c lua.h luaconf.h fix32.h lcode.h llex.h lobject.h \ + llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \ + ldo.h lfunc.h lstring.h lgc.h ltable.h +lpico8lib.o: lpico8lib.c lua.h luaconf.h fix32.h lauxlib.h llimits.h \ + lobject.h lstate.h ltm.h lzio.h lmem.h +lstate.o: lstate.c lua.h luaconf.h fix32.h lapi.h llimits.h lstate.h \ + lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h \ + lstring.h ltable.h +lstring.o: lstring.c lua.h luaconf.h fix32.h lmem.h llimits.h lobject.h \ + lstate.h ltm.h lzio.h lstring.h lgc.h +lstrlib.o: lstrlib.c lua.h luaconf.h fix32.h lauxlib.h lualib.h +ltable.o: ltable.c lua.h luaconf.h fix32.h ldebug.h lstate.h lobject.h \ + llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h +ltablib.o: ltablib.c lua.h luaconf.h fix32.h lauxlib.h lualib.h +ltests.o: ltests.c lua.h luaconf.h fix32.h lapi.h llimits.h lstate.h \ + lobject.h ltm.h lzio.h lmem.h lauxlib.h lcode.h llex.h lopcodes.h \ + lparser.h lctype.h ldebug.h ldo.h lfunc.h lstring.h lgc.h ltable.h \ + lualib.h +ltm.o: ltm.c lua.h luaconf.h fix32.h lobject.h llimits.h lstate.h ltm.h \ + lzio.h lmem.h lstring.h lgc.h ltable.h +lua.o: lua.c lua.h luaconf.h fix32.h lauxlib.h lualib.h +lundump.o: lundump.c lua.h luaconf.h fix32.h ldebug.h lstate.h lobject.h \ + llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h lundump.h +lvm.o: lvm.c lua.h luaconf.h fix32.h ldebug.h lstate.h lobject.h \ + llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h \ + ltable.h lvm.h +lzio.o: lzio.c lua.h luaconf.h fix32.h llimits.h lmem.h lstate.h \ + lobject.h ltm.h lzio.h + +# (end of Makefile) diff --git a/components/pico8/femto8/src/lua/trigtables.h b/components/pico8/femto8/src/lua/trigtables.h new file mode 100644 index 00000000..d7615616 --- /dev/null +++ b/components/pico8/femto8/src/lua/trigtables.h @@ -0,0 +1,412 @@ +// +// ZEPTO-8 β€” Fantasy console emulator +// +// Copyright Β© 2016–2024 Sam Hocevar +// +// This program is free software. It comes without any warranty, to +// the extent permitted by applicable law. You can redistribute it +// and/or modify it under the terms of the Do What the Fuck You Want +// to Public License, Version 2, as published by the WTFPL Task Force. +// See http://www.wtfpl.net/ for more details. +// + + +#include + +// This table was generated using the following PICO-8 code: +// for i = 0,0.25,0x.0004 do x = i * -4 - sin(i) printh('0x'..sub(tostr(x,1),8,11)..', ') end +static uint16_t sintable[] = +{ + 0x0000, 0x0009, 0x0012, 0x001b, 0x0025, 0x002e, 0x0037, 0x0040, 0x0049, 0x0052, 0x005b, 0x0064, 0x006e, 0x0077, 0x0080, 0x0089, + 0x0092, 0x009b, 0x00a4, 0x00ae, 0x00b7, 0x00c0, 0x00c9, 0x00d2, 0x00db, 0x00e4, 0x00ed, 0x00f7, 0x0100, 0x0109, 0x0112, 0x011b, + 0x0124, 0x012d, 0x0136, 0x0140, 0x0149, 0x0152, 0x015b, 0x0164, 0x016d, 0x0176, 0x0180, 0x0189, 0x0192, 0x019b, 0x01a4, 0x01ad, + 0x01b6, 0x01bf, 0x01c9, 0x01d2, 0x01db, 0x01e4, 0x01ed, 0x01f6, 0x01ff, 0x0208, 0x0212, 0x021b, 0x0224, 0x022d, 0x0236, 0x023f, + 0x0248, 0x0251, 0x025b, 0x0264, 0x026d, 0x0276, 0x027f, 0x0288, 0x0291, 0x029a, 0x02a4, 0x02ad, 0x02b6, 0x02bf, 0x02c8, 0x02d1, + 0x02da, 0x02e3, 0x02ed, 0x02f6, 0x02ff, 0x0308, 0x0311, 0x031a, 0x0323, 0x032c, 0x0335, 0x033f, 0x0348, 0x0351, 0x035a, 0x0363, + 0x036c, 0x0375, 0x037e, 0x0388, 0x0391, 0x039a, 0x03a3, 0x03ac, 0x03b5, 0x03be, 0x03c7, 0x03d0, 0x03da, 0x03e3, 0x03ec, 0x03f5, + 0x03fe, 0x0407, 0x0410, 0x0419, 0x0422, 0x042c, 0x0435, 0x043e, 0x0447, 0x0450, 0x0459, 0x0462, 0x046b, 0x0474, 0x047d, 0x0487, + 0x0490, 0x0499, 0x04a2, 0x04ab, 0x04b4, 0x04bd, 0x04c6, 0x04cf, 0x04d9, 0x04e2, 0x04eb, 0x04f4, 0x04fd, 0x0506, 0x050f, 0x0518, + 0x0521, 0x052a, 0x0533, 0x053d, 0x0546, 0x054f, 0x0558, 0x0561, 0x056a, 0x0573, 0x057c, 0x0585, 0x058e, 0x0597, 0x05a1, 0x05aa, + 0x05b3, 0x05bc, 0x05c5, 0x05ce, 0x05d7, 0x05e0, 0x05e9, 0x05f2, 0x05fb, 0x0604, 0x060e, 0x0617, 0x0620, 0x0629, 0x0632, 0x063b, + 0x0644, 0x064d, 0x0656, 0x065f, 0x0668, 0x0671, 0x067a, 0x0684, 0x068d, 0x0696, 0x069f, 0x06a8, 0x06b1, 0x06ba, 0x06c3, 0x06cc, + 0x06d5, 0x06de, 0x06e7, 0x06f0, 0x06f9, 0x0702, 0x070c, 0x0715, 0x071e, 0x0727, 0x0730, 0x0739, 0x0742, 0x074b, 0x0754, 0x075d, + 0x0766, 0x076f, 0x0778, 0x0781, 0x078a, 0x0793, 0x079c, 0x07a5, 0x07ae, 0x07b8, 0x07c1, 0x07ca, 0x07d3, 0x07dc, 0x07e5, 0x07ee, + 0x07f7, 0x0800, 0x0809, 0x0812, 0x081b, 0x0824, 0x082d, 0x0836, 0x083f, 0x0848, 0x0851, 0x085a, 0x0863, 0x086c, 0x0875, 0x087e, + 0x0887, 0x0890, 0x0899, 0x08a2, 0x08ab, 0x08b4, 0x08bd, 0x08c7, 0x08d0, 0x08d9, 0x08e2, 0x08eb, 0x08f4, 0x08fd, 0x0906, 0x090f, + 0x0918, 0x0921, 0x092a, 0x0933, 0x093c, 0x0945, 0x094e, 0x0957, 0x0960, 0x0969, 0x0972, 0x097b, 0x0984, 0x098d, 0x0996, 0x099f, + 0x09a8, 0x09b1, 0x09ba, 0x09c3, 0x09cc, 0x09d5, 0x09de, 0x09e7, 0x09f0, 0x09f9, 0x0a02, 0x0a0b, 0x0a14, 0x0a1d, 0x0a26, 0x0a2f, + 0x0a38, 0x0a41, 0x0a49, 0x0a52, 0x0a5b, 0x0a64, 0x0a6d, 0x0a76, 0x0a7f, 0x0a88, 0x0a91, 0x0a9a, 0x0aa3, 0x0aac, 0x0ab5, 0x0abe, + 0x0ac7, 0x0ad0, 0x0ad9, 0x0ae2, 0x0aeb, 0x0af4, 0x0afd, 0x0b06, 0x0b0f, 0x0b18, 0x0b21, 0x0b2a, 0x0b33, 0x0b3b, 0x0b44, 0x0b4d, + 0x0b56, 0x0b5f, 0x0b68, 0x0b71, 0x0b7a, 0x0b83, 0x0b8c, 0x0b95, 0x0b9e, 0x0ba7, 0x0bb0, 0x0bb9, 0x0bc2, 0x0bca, 0x0bd3, 0x0bdc, + 0x0be5, 0x0bee, 0x0bf7, 0x0c00, 0x0c09, 0x0c12, 0x0c1b, 0x0c24, 0x0c2d, 0x0c36, 0x0c3e, 0x0c47, 0x0c50, 0x0c59, 0x0c62, 0x0c6b, + 0x0c74, 0x0c7d, 0x0c86, 0x0c8f, 0x0c97, 0x0ca0, 0x0ca9, 0x0cb2, 0x0cbb, 0x0cc4, 0x0ccd, 0x0cd6, 0x0cdf, 0x0ce8, 0x0cf0, 0x0cf9, + 0x0d02, 0x0d0b, 0x0d14, 0x0d1d, 0x0d26, 0x0d2f, 0x0d37, 0x0d40, 0x0d49, 0x0d52, 0x0d5b, 0x0d64, 0x0d6d, 0x0d76, 0x0d7e, 0x0d87, + 0x0d90, 0x0d99, 0x0da2, 0x0dab, 0x0db4, 0x0dbc, 0x0dc5, 0x0dce, 0x0dd7, 0x0de0, 0x0de9, 0x0df2, 0x0dfa, 0x0e03, 0x0e0c, 0x0e15, + 0x0e1e, 0x0e27, 0x0e2f, 0x0e38, 0x0e41, 0x0e4a, 0x0e53, 0x0e5c, 0x0e64, 0x0e6d, 0x0e76, 0x0e7f, 0x0e88, 0x0e90, 0x0e99, 0x0ea2, + 0x0eab, 0x0eb4, 0x0ebd, 0x0ec5, 0x0ece, 0x0ed7, 0x0ee0, 0x0ee9, 0x0ef1, 0x0efa, 0x0f03, 0x0f0c, 0x0f15, 0x0f1d, 0x0f26, 0x0f2f, + 0x0f38, 0x0f41, 0x0f49, 0x0f52, 0x0f5b, 0x0f64, 0x0f6c, 0x0f75, 0x0f7e, 0x0f87, 0x0f90, 0x0f98, 0x0fa1, 0x0faa, 0x0fb3, 0x0fbb, + 0x0fc4, 0x0fcd, 0x0fd6, 0x0fde, 0x0fe7, 0x0ff0, 0x0ff9, 0x1001, 0x100a, 0x1013, 0x101c, 0x1024, 0x102d, 0x1036, 0x103f, 0x1047, + 0x1050, 0x1059, 0x1062, 0x106a, 0x1073, 0x107c, 0x1085, 0x108d, 0x1096, 0x109f, 0x10a7, 0x10b0, 0x10b9, 0x10c2, 0x10ca, 0x10d3, + 0x10dc, 0x10e4, 0x10ed, 0x10f6, 0x10ff, 0x1107, 0x1110, 0x1119, 0x1121, 0x112a, 0x1133, 0x113b, 0x1144, 0x114d, 0x1155, 0x115e, + 0x1167, 0x116f, 0x1178, 0x1181, 0x118a, 0x1192, 0x119b, 0x11a4, 0x11ac, 0x11b5, 0x11be, 0x11c6, 0x11cf, 0x11d7, 0x11e0, 0x11e9, + 0x11f1, 0x11fa, 0x1203, 0x120b, 0x1214, 0x121d, 0x1225, 0x122e, 0x1237, 0x123f, 0x1248, 0x1250, 0x1259, 0x1262, 0x126a, 0x1273, + 0x127c, 0x1284, 0x128d, 0x1295, 0x129e, 0x12a7, 0x12af, 0x12b8, 0x12c0, 0x12c9, 0x12d2, 0x12da, 0x12e3, 0x12eb, 0x12f4, 0x12fd, + 0x1305, 0x130e, 0x1316, 0x131f, 0x1328, 0x1330, 0x1339, 0x1341, 0x134a, 0x1352, 0x135b, 0x1364, 0x136c, 0x1375, 0x137d, 0x1386, + 0x138e, 0x1397, 0x13a0, 0x13a8, 0x13b1, 0x13b9, 0x13c2, 0x13ca, 0x13d3, 0x13db, 0x13e4, 0x13ec, 0x13f5, 0x13fd, 0x1406, 0x140e, + 0x1417, 0x1420, 0x1428, 0x1431, 0x1439, 0x1442, 0x144a, 0x1453, 0x145b, 0x1464, 0x146c, 0x1475, 0x147d, 0x1486, 0x148e, 0x1497, + 0x149f, 0x14a8, 0x14b0, 0x14b9, 0x14c1, 0x14ca, 0x14d2, 0x14da, 0x14e3, 0x14eb, 0x14f4, 0x14fc, 0x1505, 0x150d, 0x1516, 0x151e, + 0x1527, 0x152f, 0x1538, 0x1540, 0x1548, 0x1551, 0x1559, 0x1562, 0x156a, 0x1573, 0x157b, 0x1583, 0x158c, 0x1594, 0x159d, 0x15a5, + 0x15ae, 0x15b6, 0x15be, 0x15c7, 0x15cf, 0x15d8, 0x15e0, 0x15e8, 0x15f1, 0x15f9, 0x1602, 0x160a, 0x1612, 0x161b, 0x1623, 0x162c, + 0x1634, 0x163c, 0x1645, 0x164d, 0x1655, 0x165e, 0x1666, 0x166f, 0x1677, 0x167f, 0x1688, 0x1690, 0x1698, 0x16a1, 0x16a9, 0x16b1, + 0x16ba, 0x16c2, 0x16ca, 0x16d3, 0x16db, 0x16e3, 0x16ec, 0x16f4, 0x16fc, 0x1705, 0x170d, 0x1715, 0x171e, 0x1726, 0x172e, 0x1737, + 0x173f, 0x1747, 0x174f, 0x1758, 0x1760, 0x1768, 0x1771, 0x1779, 0x1781, 0x178a, 0x1792, 0x179a, 0x17a2, 0x17ab, 0x17b3, 0x17bb, + 0x17c3, 0x17cc, 0x17d4, 0x17dc, 0x17e4, 0x17ed, 0x17f5, 0x17fd, 0x1805, 0x180e, 0x1816, 0x181e, 0x1826, 0x182f, 0x1837, 0x183f, + 0x1847, 0x1850, 0x1858, 0x1860, 0x1868, 0x1870, 0x1879, 0x1881, 0x1889, 0x1891, 0x1899, 0x18a2, 0x18aa, 0x18b2, 0x18ba, 0x18c2, + 0x18cb, 0x18d3, 0x18db, 0x18e3, 0x18eb, 0x18f3, 0x18fc, 0x1904, 0x190c, 0x1914, 0x191c, 0x1924, 0x192c, 0x1935, 0x193d, 0x1945, + 0x194d, 0x1955, 0x195d, 0x1965, 0x196e, 0x1976, 0x197e, 0x1986, 0x198e, 0x1996, 0x199e, 0x19a6, 0x19af, 0x19b7, 0x19bf, 0x19c7, + 0x19cf, 0x19d7, 0x19df, 0x19e7, 0x19ef, 0x19f7, 0x19ff, 0x1a08, 0x1a10, 0x1a18, 0x1a20, 0x1a28, 0x1a30, 0x1a38, 0x1a40, 0x1a48, + 0x1a50, 0x1a58, 0x1a60, 0x1a68, 0x1a70, 0x1a78, 0x1a80, 0x1a88, 0x1a90, 0x1a98, 0x1aa0, 0x1aa8, 0x1ab1, 0x1ab9, 0x1ac1, 0x1ac9, + 0x1ad1, 0x1ad9, 0x1ae1, 0x1ae9, 0x1af1, 0x1af9, 0x1b01, 0x1b09, 0x1b10, 0x1b18, 0x1b20, 0x1b28, 0x1b30, 0x1b38, 0x1b40, 0x1b48, + 0x1b50, 0x1b58, 0x1b60, 0x1b68, 0x1b70, 0x1b78, 0x1b80, 0x1b88, 0x1b90, 0x1b98, 0x1ba0, 0x1ba8, 0x1bb0, 0x1bb7, 0x1bbf, 0x1bc7, + 0x1bcf, 0x1bd7, 0x1bdf, 0x1be7, 0x1bef, 0x1bf7, 0x1bff, 0x1c07, 0x1c0e, 0x1c16, 0x1c1e, 0x1c26, 0x1c2e, 0x1c36, 0x1c3e, 0x1c46, + 0x1c4d, 0x1c55, 0x1c5d, 0x1c65, 0x1c6d, 0x1c75, 0x1c7d, 0x1c84, 0x1c8c, 0x1c94, 0x1c9c, 0x1ca4, 0x1cac, 0x1cb3, 0x1cbb, 0x1cc3, + 0x1ccb, 0x1cd3, 0x1cdb, 0x1ce2, 0x1cea, 0x1cf2, 0x1cfa, 0x1d02, 0x1d09, 0x1d11, 0x1d19, 0x1d21, 0x1d28, 0x1d30, 0x1d38, 0x1d40, + 0x1d48, 0x1d4f, 0x1d57, 0x1d5f, 0x1d67, 0x1d6e, 0x1d76, 0x1d7e, 0x1d86, 0x1d8d, 0x1d95, 0x1d9d, 0x1da4, 0x1dac, 0x1db4, 0x1dbc, + 0x1dc3, 0x1dcb, 0x1dd3, 0x1ddb, 0x1de2, 0x1dea, 0x1df2, 0x1df9, 0x1e01, 0x1e09, 0x1e10, 0x1e18, 0x1e20, 0x1e27, 0x1e2f, 0x1e37, + 0x1e3e, 0x1e46, 0x1e4e, 0x1e55, 0x1e5d, 0x1e65, 0x1e6c, 0x1e74, 0x1e7c, 0x1e83, 0x1e8b, 0x1e93, 0x1e9a, 0x1ea2, 0x1ea9, 0x1eb1, + 0x1eb9, 0x1ec0, 0x1ec8, 0x1ecf, 0x1ed7, 0x1edf, 0x1ee6, 0x1eee, 0x1ef5, 0x1efd, 0x1f05, 0x1f0c, 0x1f14, 0x1f1b, 0x1f23, 0x1f2a, + 0x1f32, 0x1f3a, 0x1f41, 0x1f49, 0x1f50, 0x1f58, 0x1f5f, 0x1f67, 0x1f6e, 0x1f76, 0x1f7d, 0x1f85, 0x1f8c, 0x1f94, 0x1f9b, 0x1fa3, + 0x1faa, 0x1fb2, 0x1fb9, 0x1fc1, 0x1fc8, 0x1fd0, 0x1fd7, 0x1fdf, 0x1fe6, 0x1fee, 0x1ff5, 0x1ffd, 0x2004, 0x200c, 0x2013, 0x201b, + 0x2022, 0x202a, 0x2031, 0x2038, 0x2040, 0x2047, 0x204f, 0x2056, 0x205e, 0x2065, 0x206c, 0x2074, 0x207b, 0x2083, 0x208a, 0x2091, + 0x2099, 0x20a0, 0x20a8, 0x20af, 0x20b6, 0x20be, 0x20c5, 0x20cc, 0x20d4, 0x20db, 0x20e3, 0x20ea, 0x20f1, 0x20f9, 0x2100, 0x2107, + 0x210f, 0x2116, 0x211d, 0x2125, 0x212c, 0x2133, 0x213b, 0x2142, 0x2149, 0x2151, 0x2158, 0x215f, 0x2166, 0x216e, 0x2175, 0x217c, + 0x2184, 0x218b, 0x2192, 0x2199, 0x21a1, 0x21a8, 0x21af, 0x21b6, 0x21be, 0x21c5, 0x21cc, 0x21d3, 0x21db, 0x21e2, 0x21e9, 0x21f0, + 0x21f8, 0x21ff, 0x2206, 0x220d, 0x2214, 0x221c, 0x2223, 0x222a, 0x2231, 0x2238, 0x2240, 0x2247, 0x224e, 0x2255, 0x225c, 0x2263, + 0x226b, 0x2272, 0x2279, 0x2280, 0x2287, 0x228e, 0x2295, 0x229d, 0x22a4, 0x22ab, 0x22b2, 0x22b9, 0x22c0, 0x22c7, 0x22ce, 0x22d6, + 0x22dd, 0x22e4, 0x22eb, 0x22f2, 0x22f9, 0x2300, 0x2307, 0x230e, 0x2315, 0x231c, 0x2323, 0x232b, 0x2332, 0x2339, 0x2340, 0x2347, + 0x234e, 0x2355, 0x235c, 0x2363, 0x236a, 0x2371, 0x2378, 0x237f, 0x2386, 0x238d, 0x2394, 0x239b, 0x23a2, 0x23a9, 0x23b0, 0x23b7, + 0x23be, 0x23c5, 0x23cc, 0x23d3, 0x23da, 0x23e1, 0x23e8, 0x23ef, 0x23f6, 0x23fd, 0x2403, 0x240a, 0x2411, 0x2418, 0x241f, 0x2426, + 0x242d, 0x2434, 0x243b, 0x2442, 0x2449, 0x2450, 0x2456, 0x245d, 0x2464, 0x246b, 0x2472, 0x2479, 0x2480, 0x2487, 0x248d, 0x2494, + 0x249b, 0x24a2, 0x24a9, 0x24b0, 0x24b6, 0x24bd, 0x24c4, 0x24cb, 0x24d2, 0x24d9, 0x24df, 0x24e6, 0x24ed, 0x24f4, 0x24fb, 0x2501, + 0x2508, 0x250f, 0x2516, 0x251d, 0x2523, 0x252a, 0x2531, 0x2538, 0x253e, 0x2545, 0x254c, 0x2553, 0x2559, 0x2560, 0x2567, 0x256e, + 0x2574, 0x257b, 0x2582, 0x2588, 0x258f, 0x2596, 0x259c, 0x25a3, 0x25aa, 0x25b1, 0x25b7, 0x25be, 0x25c5, 0x25cb, 0x25d2, 0x25d9, + 0x25df, 0x25e6, 0x25ed, 0x25f3, 0x25fa, 0x2600, 0x2607, 0x260e, 0x2614, 0x261b, 0x2622, 0x2628, 0x262f, 0x2635, 0x263c, 0x2643, + 0x2649, 0x2650, 0x2656, 0x265d, 0x2663, 0x266a, 0x2671, 0x2677, 0x267e, 0x2684, 0x268b, 0x2691, 0x2698, 0x269e, 0x26a5, 0x26ab, + 0x26b2, 0x26b9, 0x26bf, 0x26c6, 0x26cc, 0x26d3, 0x26d9, 0x26e0, 0x26e6, 0x26ec, 0x26f3, 0x26f9, 0x2700, 0x2706, 0x270d, 0x2713, + 0x271a, 0x2720, 0x2727, 0x272d, 0x2733, 0x273a, 0x2740, 0x2747, 0x274d, 0x2754, 0x275a, 0x2760, 0x2767, 0x276d, 0x2774, 0x277a, + 0x2780, 0x2787, 0x278d, 0x2793, 0x279a, 0x27a0, 0x27a7, 0x27ad, 0x27b3, 0x27ba, 0x27c0, 0x27c6, 0x27cd, 0x27d3, 0x27d9, 0x27e0, + 0x27e6, 0x27ec, 0x27f2, 0x27f9, 0x27ff, 0x2805, 0x280c, 0x2812, 0x2818, 0x281e, 0x2825, 0x282b, 0x2831, 0x2838, 0x283e, 0x2844, + 0x284a, 0x2850, 0x2857, 0x285d, 0x2863, 0x2869, 0x2870, 0x2876, 0x287c, 0x2882, 0x2888, 0x288f, 0x2895, 0x289b, 0x28a1, 0x28a7, + 0x28ad, 0x28b4, 0x28ba, 0x28c0, 0x28c6, 0x28cc, 0x28d2, 0x28d9, 0x28df, 0x28e5, 0x28eb, 0x28f1, 0x28f7, 0x28fd, 0x2903, 0x2909, + 0x2910, 0x2916, 0x291c, 0x2922, 0x2928, 0x292e, 0x2934, 0x293a, 0x2940, 0x2946, 0x294c, 0x2952, 0x2958, 0x295e, 0x2964, 0x296a, + 0x2970, 0x2976, 0x297c, 0x2982, 0x2988, 0x298e, 0x2994, 0x299a, 0x29a0, 0x29a6, 0x29ac, 0x29b2, 0x29b8, 0x29be, 0x29c4, 0x29ca, + 0x29d0, 0x29d6, 0x29dc, 0x29e2, 0x29e8, 0x29ee, 0x29f4, 0x29fa, 0x29ff, 0x2a05, 0x2a0b, 0x2a11, 0x2a17, 0x2a1d, 0x2a23, 0x2a29, + 0x2a2f, 0x2a34, 0x2a3a, 0x2a40, 0x2a46, 0x2a4c, 0x2a52, 0x2a58, 0x2a5d, 0x2a63, 0x2a69, 0x2a6f, 0x2a75, 0x2a7a, 0x2a80, 0x2a86, + 0x2a8c, 0x2a92, 0x2a97, 0x2a9d, 0x2aa3, 0x2aa9, 0x2aaf, 0x2ab4, 0x2aba, 0x2ac0, 0x2ac6, 0x2acb, 0x2ad1, 0x2ad7, 0x2adc, 0x2ae2, + 0x2ae8, 0x2aee, 0x2af3, 0x2af9, 0x2aff, 0x2b04, 0x2b0a, 0x2b10, 0x2b15, 0x2b1b, 0x2b21, 0x2b26, 0x2b2c, 0x2b32, 0x2b37, 0x2b3d, + 0x2b43, 0x2b48, 0x2b4e, 0x2b54, 0x2b59, 0x2b5f, 0x2b64, 0x2b6a, 0x2b70, 0x2b75, 0x2b7b, 0x2b80, 0x2b86, 0x2b8c, 0x2b91, 0x2b97, + 0x2b9c, 0x2ba2, 0x2ba7, 0x2bad, 0x2bb2, 0x2bb8, 0x2bbd, 0x2bc3, 0x2bc9, 0x2bce, 0x2bd4, 0x2bd9, 0x2bdf, 0x2be4, 0x2bea, 0x2bef, + 0x2bf5, 0x2bfa, 0x2bff, 0x2c05, 0x2c0a, 0x2c10, 0x2c15, 0x2c1b, 0x2c20, 0x2c26, 0x2c2b, 0x2c30, 0x2c36, 0x2c3b, 0x2c41, 0x2c46, + 0x2c4c, 0x2c51, 0x2c56, 0x2c5c, 0x2c61, 0x2c66, 0x2c6c, 0x2c71, 0x2c77, 0x2c7c, 0x2c81, 0x2c87, 0x2c8c, 0x2c91, 0x2c97, 0x2c9c, + 0x2ca1, 0x2ca7, 0x2cac, 0x2cb1, 0x2cb6, 0x2cbc, 0x2cc1, 0x2cc6, 0x2ccc, 0x2cd1, 0x2cd6, 0x2cdb, 0x2ce1, 0x2ce6, 0x2ceb, 0x2cf0, + 0x2cf6, 0x2cfb, 0x2d00, 0x2d05, 0x2d0a, 0x2d10, 0x2d15, 0x2d1a, 0x2d1f, 0x2d24, 0x2d2a, 0x2d2f, 0x2d34, 0x2d39, 0x2d3e, 0x2d44, + 0x2d49, 0x2d4e, 0x2d53, 0x2d58, 0x2d5d, 0x2d62, 0x2d67, 0x2d6d, 0x2d72, 0x2d77, 0x2d7c, 0x2d81, 0x2d86, 0x2d8b, 0x2d90, 0x2d95, + 0x2d9a, 0x2d9f, 0x2da5, 0x2daa, 0x2daf, 0x2db4, 0x2db9, 0x2dbe, 0x2dc3, 0x2dc8, 0x2dcd, 0x2dd2, 0x2dd7, 0x2ddc, 0x2de1, 0x2de6, + 0x2deb, 0x2df0, 0x2df5, 0x2dfa, 0x2dff, 0x2e04, 0x2e09, 0x2e0e, 0x2e13, 0x2e17, 0x2e1c, 0x2e21, 0x2e26, 0x2e2b, 0x2e30, 0x2e35, + 0x2e3a, 0x2e3f, 0x2e44, 0x2e49, 0x2e4d, 0x2e52, 0x2e57, 0x2e5c, 0x2e61, 0x2e66, 0x2e6b, 0x2e6f, 0x2e74, 0x2e79, 0x2e7e, 0x2e83, + 0x2e88, 0x2e8c, 0x2e91, 0x2e96, 0x2e9b, 0x2ea0, 0x2ea4, 0x2ea9, 0x2eae, 0x2eb3, 0x2eb7, 0x2ebc, 0x2ec1, 0x2ec6, 0x2eca, 0x2ecf, + 0x2ed4, 0x2ed9, 0x2edd, 0x2ee2, 0x2ee7, 0x2eeb, 0x2ef0, 0x2ef5, 0x2ef9, 0x2efe, 0x2f03, 0x2f07, 0x2f0c, 0x2f11, 0x2f15, 0x2f1a, + 0x2f1f, 0x2f23, 0x2f28, 0x2f2d, 0x2f31, 0x2f36, 0x2f3a, 0x2f3f, 0x2f44, 0x2f48, 0x2f4d, 0x2f51, 0x2f56, 0x2f5a, 0x2f5f, 0x2f64, + 0x2f68, 0x2f6d, 0x2f71, 0x2f76, 0x2f7a, 0x2f7f, 0x2f83, 0x2f88, 0x2f8c, 0x2f91, 0x2f95, 0x2f9a, 0x2f9e, 0x2fa3, 0x2fa7, 0x2fac, + 0x2fb0, 0x2fb5, 0x2fb9, 0x2fbe, 0x2fc2, 0x2fc6, 0x2fcb, 0x2fcf, 0x2fd4, 0x2fd8, 0x2fdd, 0x2fe1, 0x2fe5, 0x2fea, 0x2fee, 0x2ff2, + 0x2ff7, 0x2ffb, 0x3000, 0x3004, 0x3008, 0x300d, 0x3011, 0x3015, 0x301a, 0x301e, 0x3022, 0x3027, 0x302b, 0x302f, 0x3033, 0x3038, + 0x303c, 0x3040, 0x3045, 0x3049, 0x304d, 0x3051, 0x3056, 0x305a, 0x305e, 0x3062, 0x3067, 0x306b, 0x306f, 0x3073, 0x3077, 0x307c, + 0x3080, 0x3084, 0x3088, 0x308c, 0x3090, 0x3095, 0x3099, 0x309d, 0x30a1, 0x30a5, 0x30a9, 0x30ad, 0x30b2, 0x30b6, 0x30ba, 0x30be, + 0x30c2, 0x30c6, 0x30ca, 0x30ce, 0x30d2, 0x30d6, 0x30da, 0x30df, 0x30e3, 0x30e7, 0x30eb, 0x30ef, 0x30f3, 0x30f7, 0x30fb, 0x30ff, + 0x3103, 0x3107, 0x310b, 0x310f, 0x3113, 0x3117, 0x311b, 0x311f, 0x3123, 0x3127, 0x312a, 0x312e, 0x3132, 0x3136, 0x313a, 0x313e, + 0x3142, 0x3146, 0x314a, 0x314e, 0x3152, 0x3156, 0x3159, 0x315d, 0x3161, 0x3165, 0x3169, 0x316d, 0x3171, 0x3174, 0x3178, 0x317c, + 0x3180, 0x3184, 0x3187, 0x318b, 0x318f, 0x3193, 0x3197, 0x319a, 0x319e, 0x31a2, 0x31a6, 0x31a9, 0x31ad, 0x31b1, 0x31b5, 0x31b8, + 0x31bc, 0x31c0, 0x31c3, 0x31c7, 0x31cb, 0x31cf, 0x31d2, 0x31d6, 0x31da, 0x31dd, 0x31e1, 0x31e5, 0x31e8, 0x31ec, 0x31f0, 0x31f3, + 0x31f7, 0x31fa, 0x31fe, 0x3202, 0x3205, 0x3209, 0x320c, 0x3210, 0x3214, 0x3217, 0x321b, 0x321e, 0x3222, 0x3225, 0x3229, 0x322c, + 0x3230, 0x3233, 0x3237, 0x323b, 0x323e, 0x3242, 0x3245, 0x3249, 0x324c, 0x324f, 0x3253, 0x3256, 0x325a, 0x325d, 0x3261, 0x3264, + 0x3268, 0x326b, 0x326e, 0x3272, 0x3275, 0x3279, 0x327c, 0x327f, 0x3283, 0x3286, 0x328a, 0x328d, 0x3290, 0x3294, 0x3297, 0x329a, + 0x329e, 0x32a1, 0x32a4, 0x32a8, 0x32ab, 0x32ae, 0x32b2, 0x32b5, 0x32b8, 0x32bb, 0x32bf, 0x32c2, 0x32c5, 0x32c8, 0x32cc, 0x32cf, + 0x32d2, 0x32d5, 0x32d9, 0x32dc, 0x32df, 0x32e2, 0x32e5, 0x32e9, 0x32ec, 0x32ef, 0x32f2, 0x32f5, 0x32f8, 0x32fc, 0x32ff, 0x3302, + 0x3305, 0x3308, 0x330b, 0x330e, 0x3312, 0x3315, 0x3318, 0x331b, 0x331e, 0x3321, 0x3324, 0x3327, 0x332a, 0x332d, 0x3330, 0x3333, + 0x3336, 0x3339, 0x333c, 0x333f, 0x3342, 0x3345, 0x3348, 0x334b, 0x334e, 0x3351, 0x3354, 0x3357, 0x335a, 0x335d, 0x3360, 0x3363, + 0x3366, 0x3369, 0x336c, 0x336f, 0x3372, 0x3375, 0x3377, 0x337a, 0x337d, 0x3380, 0x3383, 0x3386, 0x3389, 0x338c, 0x338e, 0x3391, + 0x3394, 0x3397, 0x339a, 0x339d, 0x339f, 0x33a2, 0x33a5, 0x33a8, 0x33aa, 0x33ad, 0x33b0, 0x33b3, 0x33b6, 0x33b8, 0x33bb, 0x33be, + 0x33c1, 0x33c3, 0x33c6, 0x33c9, 0x33cb, 0x33ce, 0x33d1, 0x33d3, 0x33d6, 0x33d9, 0x33db, 0x33de, 0x33e1, 0x33e3, 0x33e6, 0x33e9, + 0x33eb, 0x33ee, 0x33f1, 0x33f3, 0x33f6, 0x33f8, 0x33fb, 0x33fd, 0x3400, 0x3403, 0x3405, 0x3408, 0x340a, 0x340d, 0x340f, 0x3412, + 0x3414, 0x3417, 0x3419, 0x341c, 0x341e, 0x3421, 0x3423, 0x3426, 0x3428, 0x342b, 0x342d, 0x3430, 0x3432, 0x3435, 0x3437, 0x3439, + 0x343c, 0x343e, 0x3441, 0x3443, 0x3445, 0x3448, 0x344a, 0x344d, 0x344f, 0x3451, 0x3454, 0x3456, 0x3458, 0x345b, 0x345d, 0x345f, + 0x3462, 0x3464, 0x3466, 0x3469, 0x346b, 0x346d, 0x346f, 0x3472, 0x3474, 0x3476, 0x3478, 0x347b, 0x347d, 0x347f, 0x3481, 0x3484, + 0x3486, 0x3488, 0x348a, 0x348c, 0x348e, 0x3491, 0x3493, 0x3495, 0x3497, 0x3499, 0x349b, 0x349e, 0x34a0, 0x34a2, 0x34a4, 0x34a6, + 0x34a8, 0x34aa, 0x34ac, 0x34ae, 0x34b0, 0x34b3, 0x34b5, 0x34b7, 0x34b9, 0x34bb, 0x34bd, 0x34bf, 0x34c1, 0x34c3, 0x34c5, 0x34c7, + 0x34c9, 0x34cb, 0x34cd, 0x34cf, 0x34d1, 0x34d3, 0x34d5, 0x34d7, 0x34d8, 0x34da, 0x34dc, 0x34de, 0x34e0, 0x34e2, 0x34e4, 0x34e6, + 0x34e8, 0x34ea, 0x34eb, 0x34ed, 0x34ef, 0x34f1, 0x34f3, 0x34f5, 0x34f7, 0x34f8, 0x34fa, 0x34fc, 0x34fe, 0x3500, 0x3501, 0x3503, + 0x3505, 0x3507, 0x3508, 0x350a, 0x350c, 0x350e, 0x350f, 0x3511, 0x3513, 0x3515, 0x3516, 0x3518, 0x351a, 0x351b, 0x351d, 0x351f, + 0x3520, 0x3522, 0x3524, 0x3525, 0x3527, 0x3529, 0x352a, 0x352c, 0x352d, 0x352f, 0x3531, 0x3532, 0x3534, 0x3535, 0x3537, 0x3539, + 0x353a, 0x353c, 0x353d, 0x353f, 0x3540, 0x3542, 0x3543, 0x3545, 0x3546, 0x3548, 0x3549, 0x354b, 0x354c, 0x354e, 0x354f, 0x3551, + 0x3552, 0x3554, 0x3555, 0x3556, 0x3558, 0x3559, 0x355b, 0x355c, 0x355d, 0x355f, 0x3560, 0x3562, 0x3563, 0x3564, 0x3566, 0x3567, + 0x3568, 0x356a, 0x356b, 0x356c, 0x356e, 0x356f, 0x3570, 0x3571, 0x3573, 0x3574, 0x3575, 0x3576, 0x3578, 0x3579, 0x357a, 0x357b, + 0x357d, 0x357e, 0x357f, 0x3580, 0x3581, 0x3583, 0x3584, 0x3585, 0x3586, 0x3587, 0x3588, 0x358a, 0x358b, 0x358c, 0x358d, 0x358e, + 0x358f, 0x3590, 0x3591, 0x3593, 0x3594, 0x3595, 0x3596, 0x3597, 0x3598, 0x3599, 0x359a, 0x359b, 0x359c, 0x359d, 0x359e, 0x359f, + 0x35a0, 0x35a1, 0x35a2, 0x35a3, 0x35a4, 0x35a5, 0x35a6, 0x35a7, 0x35a8, 0x35a9, 0x35aa, 0x35aa, 0x35ab, 0x35ac, 0x35ad, 0x35ae, + 0x35af, 0x35b0, 0x35b1, 0x35b2, 0x35b2, 0x35b3, 0x35b4, 0x35b5, 0x35b6, 0x35b7, 0x35b7, 0x35b8, 0x35b9, 0x35ba, 0x35bb, 0x35bb, + 0x35bc, 0x35bd, 0x35be, 0x35be, 0x35bf, 0x35c0, 0x35c1, 0x35c1, 0x35c2, 0x35c3, 0x35c3, 0x35c4, 0x35c5, 0x35c5, 0x35c6, 0x35c7, + 0x35c7, 0x35c8, 0x35c9, 0x35c9, 0x35ca, 0x35cb, 0x35cb, 0x35cc, 0x35cc, 0x35cd, 0x35ce, 0x35ce, 0x35cf, 0x35cf, 0x35d0, 0x35d0, + 0x35d1, 0x35d1, 0x35d2, 0x35d2, 0x35d3, 0x35d3, 0x35d4, 0x35d4, 0x35d5, 0x35d5, 0x35d6, 0x35d6, 0x35d7, 0x35d7, 0x35d8, 0x35d8, + 0x35d8, 0x35d9, 0x35d9, 0x35da, 0x35da, 0x35da, 0x35db, 0x35db, 0x35dc, 0x35dc, 0x35dc, 0x35dd, 0x35dd, 0x35dd, 0x35de, 0x35de, + 0x35de, 0x35de, 0x35df, 0x35df, 0x35df, 0x35e0, 0x35e0, 0x35e0, 0x35e0, 0x35e1, 0x35e1, 0x35e1, 0x35e1, 0x35e1, 0x35e2, 0x35e2, + 0x35e2, 0x35e2, 0x35e2, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, + 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, + 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e4, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e3, 0x35e2, 0x35e2, + 0x35e2, 0x35e2, 0x35e2, 0x35e2, 0x35e1, 0x35e1, 0x35e1, 0x35e1, 0x35e1, 0x35e0, 0x35e0, 0x35e0, 0x35e0, 0x35df, 0x35df, 0x35df, + 0x35de, 0x35de, 0x35de, 0x35dd, 0x35dd, 0x35dd, 0x35dc, 0x35dc, 0x35dc, 0x35db, 0x35db, 0x35db, 0x35da, 0x35da, 0x35da, 0x35d9, + 0x35d9, 0x35d8, 0x35d8, 0x35d7, 0x35d7, 0x35d7, 0x35d6, 0x35d6, 0x35d5, 0x35d5, 0x35d4, 0x35d4, 0x35d3, 0x35d3, 0x35d2, 0x35d2, + 0x35d1, 0x35d1, 0x35d0, 0x35cf, 0x35cf, 0x35ce, 0x35ce, 0x35cd, 0x35cd, 0x35cc, 0x35cb, 0x35cb, 0x35ca, 0x35c9, 0x35c9, 0x35c8, + 0x35c7, 0x35c7, 0x35c6, 0x35c5, 0x35c5, 0x35c4, 0x35c3, 0x35c3, 0x35c2, 0x35c1, 0x35c1, 0x35c0, 0x35bf, 0x35be, 0x35be, 0x35bd, + 0x35bc, 0x35bb, 0x35ba, 0x35ba, 0x35b9, 0x35b8, 0x35b7, 0x35b6, 0x35b5, 0x35b5, 0x35b4, 0x35b3, 0x35b2, 0x35b1, 0x35b0, 0x35af, + 0x35ae, 0x35ae, 0x35ad, 0x35ac, 0x35ab, 0x35aa, 0x35a9, 0x35a8, 0x35a7, 0x35a6, 0x35a5, 0x35a4, 0x35a3, 0x35a2, 0x35a1, 0x35a0, + 0x359f, 0x359e, 0x359d, 0x359c, 0x359b, 0x359a, 0x3599, 0x3598, 0x3597, 0x3595, 0x3594, 0x3593, 0x3592, 0x3591, 0x3590, 0x358f, + 0x358e, 0x358c, 0x358b, 0x358a, 0x3589, 0x3588, 0x3587, 0x3585, 0x3584, 0x3583, 0x3582, 0x3580, 0x357f, 0x357e, 0x357d, 0x357b, + 0x357a, 0x3579, 0x3578, 0x3576, 0x3575, 0x3574, 0x3572, 0x3571, 0x3570, 0x356e, 0x356d, 0x356c, 0x356a, 0x3569, 0x3567, 0x3566, + 0x3565, 0x3563, 0x3562, 0x3560, 0x355f, 0x355e, 0x355c, 0x355b, 0x3559, 0x3558, 0x3556, 0x3555, 0x3553, 0x3552, 0x3550, 0x354f, + 0x354d, 0x354c, 0x354a, 0x3549, 0x3547, 0x3545, 0x3544, 0x3542, 0x3541, 0x353f, 0x353e, 0x353c, 0x353a, 0x3539, 0x3537, 0x3535, + 0x3534, 0x3532, 0x3530, 0x352f, 0x352d, 0x352b, 0x352a, 0x3528, 0x3526, 0x3525, 0x3523, 0x3521, 0x351f, 0x351e, 0x351c, 0x351a, + 0x3518, 0x3516, 0x3515, 0x3513, 0x3511, 0x350f, 0x350d, 0x350c, 0x350a, 0x3508, 0x3506, 0x3504, 0x3502, 0x3500, 0x34ff, 0x34fd, + 0x34fb, 0x34f9, 0x34f7, 0x34f5, 0x34f3, 0x34f1, 0x34ef, 0x34ed, 0x34eb, 0x34e9, 0x34e7, 0x34e5, 0x34e3, 0x34e1, 0x34df, 0x34dd, + 0x34db, 0x34d9, 0x34d7, 0x34d5, 0x34d3, 0x34d1, 0x34cf, 0x34cd, 0x34cb, 0x34c9, 0x34c6, 0x34c4, 0x34c2, 0x34c0, 0x34be, 0x34bc, + 0x34ba, 0x34b7, 0x34b5, 0x34b3, 0x34b1, 0x34af, 0x34ac, 0x34aa, 0x34a8, 0x34a6, 0x34a4, 0x34a1, 0x349f, 0x349d, 0x349a, 0x3498, + 0x3496, 0x3494, 0x3491, 0x348f, 0x348d, 0x348a, 0x3488, 0x3486, 0x3483, 0x3481, 0x347f, 0x347c, 0x347a, 0x3477, 0x3475, 0x3473, + 0x3470, 0x346e, 0x346b, 0x3469, 0x3466, 0x3464, 0x3461, 0x345f, 0x345c, 0x345a, 0x3458, 0x3455, 0x3452, 0x3450, 0x344d, 0x344b, + 0x3448, 0x3446, 0x3443, 0x3441, 0x343e, 0x343b, 0x3439, 0x3436, 0x3434, 0x3431, 0x342e, 0x342c, 0x3429, 0x3426, 0x3424, 0x3421, + 0x341e, 0x341c, 0x3419, 0x3416, 0x3414, 0x3411, 0x340e, 0x340b, 0x3409, 0x3406, 0x3403, 0x3400, 0x33fe, 0x33fb, 0x33f8, 0x33f5, + 0x33f2, 0x33f0, 0x33ed, 0x33ea, 0x33e7, 0x33e4, 0x33e1, 0x33df, 0x33dc, 0x33d9, 0x33d6, 0x33d3, 0x33d0, 0x33cd, 0x33ca, 0x33c7, + 0x33c4, 0x33c1, 0x33be, 0x33bb, 0x33b8, 0x33b5, 0x33b2, 0x33af, 0x33ac, 0x33a9, 0x33a6, 0x33a3, 0x33a0, 0x339d, 0x339a, 0x3397, + 0x3394, 0x3391, 0x338e, 0x338b, 0x3388, 0x3385, 0x3381, 0x337e, 0x337b, 0x3378, 0x3375, 0x3372, 0x336f, 0x336b, 0x3368, 0x3365, + 0x3362, 0x335f, 0x335b, 0x3358, 0x3355, 0x3352, 0x334e, 0x334b, 0x3348, 0x3345, 0x3341, 0x333e, 0x333b, 0x3337, 0x3334, 0x3331, + 0x332d, 0x332a, 0x3327, 0x3323, 0x3320, 0x331c, 0x3319, 0x3316, 0x3312, 0x330f, 0x330b, 0x3308, 0x3305, 0x3301, 0x32fe, 0x32fa, + 0x32f7, 0x32f3, 0x32f0, 0x32ec, 0x32e9, 0x32e5, 0x32e2, 0x32de, 0x32db, 0x32d7, 0x32d4, 0x32d0, 0x32cc, 0x32c9, 0x32c5, 0x32c2, + 0x32be, 0x32ba, 0x32b7, 0x32b3, 0x32b0, 0x32ac, 0x32a8, 0x32a5, 0x32a1, 0x329d, 0x3299, 0x3296, 0x3292, 0x328e, 0x328b, 0x3287, + 0x3283, 0x327f, 0x327c, 0x3278, 0x3274, 0x3270, 0x326d, 0x3269, 0x3265, 0x3261, 0x325d, 0x3259, 0x3256, 0x3252, 0x324e, 0x324a, + 0x3246, 0x3242, 0x323e, 0x323a, 0x3237, 0x3233, 0x322f, 0x322b, 0x3227, 0x3223, 0x321f, 0x321b, 0x3217, 0x3213, 0x320f, 0x320b, + 0x3207, 0x3203, 0x31ff, 0x31fb, 0x31f7, 0x31f3, 0x31ef, 0x31eb, 0x31e7, 0x31e2, 0x31de, 0x31da, 0x31d6, 0x31d2, 0x31ce, 0x31ca, + 0x31c6, 0x31c1, 0x31bd, 0x31b9, 0x31b5, 0x31b1, 0x31ad, 0x31a8, 0x31a4, 0x31a0, 0x319c, 0x3197, 0x3193, 0x318f, 0x318b, 0x3186, + 0x3182, 0x317e, 0x3179, 0x3175, 0x3171, 0x316d, 0x3168, 0x3164, 0x315f, 0x315b, 0x3157, 0x3152, 0x314e, 0x314a, 0x3145, 0x3141, + 0x313c, 0x3138, 0x3133, 0x312f, 0x312b, 0x3126, 0x3122, 0x311d, 0x3119, 0x3114, 0x3110, 0x310b, 0x3107, 0x3102, 0x30fe, 0x30f9, + 0x30f4, 0x30f0, 0x30eb, 0x30e7, 0x30e2, 0x30de, 0x30d9, 0x30d4, 0x30d0, 0x30cb, 0x30c6, 0x30c2, 0x30bd, 0x30b8, 0x30b4, 0x30af, + 0x30aa, 0x30a6, 0x30a1, 0x309c, 0x3097, 0x3093, 0x308e, 0x3089, 0x3084, 0x3080, 0x307b, 0x3076, 0x3071, 0x306d, 0x3068, 0x3063, + 0x305e, 0x3059, 0x3054, 0x304f, 0x304b, 0x3046, 0x3041, 0x303c, 0x3037, 0x3032, 0x302d, 0x3028, 0x3023, 0x301e, 0x3019, 0x3015, + 0x3010, 0x300b, 0x3006, 0x3001, 0x2ffc, 0x2ff7, 0x2ff2, 0x2fec, 0x2fe7, 0x2fe2, 0x2fdd, 0x2fd8, 0x2fd3, 0x2fce, 0x2fc9, 0x2fc4, + 0x2fbf, 0x2fba, 0x2fb5, 0x2faf, 0x2faa, 0x2fa5, 0x2fa0, 0x2f9b, 0x2f96, 0x2f90, 0x2f8b, 0x2f86, 0x2f81, 0x2f7c, 0x2f76, 0x2f71, + 0x2f6c, 0x2f67, 0x2f61, 0x2f5c, 0x2f57, 0x2f51, 0x2f4c, 0x2f47, 0x2f42, 0x2f3c, 0x2f37, 0x2f32, 0x2f2c, 0x2f27, 0x2f21, 0x2f1c, + 0x2f17, 0x2f11, 0x2f0c, 0x2f06, 0x2f01, 0x2efc, 0x2ef6, 0x2ef1, 0x2eeb, 0x2ee6, 0x2ee0, 0x2edb, 0x2ed5, 0x2ed0, 0x2eca, 0x2ec5, + 0x2ebf, 0x2eba, 0x2eb4, 0x2eaf, 0x2ea9, 0x2ea3, 0x2e9e, 0x2e98, 0x2e93, 0x2e8d, 0x2e87, 0x2e82, 0x2e7c, 0x2e77, 0x2e71, 0x2e6b, + 0x2e66, 0x2e60, 0x2e5a, 0x2e55, 0x2e4f, 0x2e49, 0x2e43, 0x2e3e, 0x2e38, 0x2e32, 0x2e2c, 0x2e27, 0x2e21, 0x2e1b, 0x2e15, 0x2e0f, + 0x2e0a, 0x2e04, 0x2dfe, 0x2df8, 0x2df2, 0x2dec, 0x2de7, 0x2de1, 0x2ddb, 0x2dd5, 0x2dcf, 0x2dc9, 0x2dc3, 0x2dbd, 0x2db7, 0x2db1, + 0x2dab, 0x2da6, 0x2da0, 0x2d9a, 0x2d94, 0x2d8e, 0x2d88, 0x2d82, 0x2d7c, 0x2d76, 0x2d6f, 0x2d69, 0x2d63, 0x2d5d, 0x2d57, 0x2d51, + 0x2d4b, 0x2d45, 0x2d3f, 0x2d39, 0x2d33, 0x2d2c, 0x2d26, 0x2d20, 0x2d1a, 0x2d14, 0x2d0e, 0x2d07, 0x2d01, 0x2cfb, 0x2cf5, 0x2cef, + 0x2ce8, 0x2ce2, 0x2cdc, 0x2cd6, 0x2ccf, 0x2cc9, 0x2cc3, 0x2cbc, 0x2cb6, 0x2cb0, 0x2caa, 0x2ca3, 0x2c9d, 0x2c96, 0x2c90, 0x2c8a, + 0x2c83, 0x2c7d, 0x2c77, 0x2c70, 0x2c6a, 0x2c63, 0x2c5d, 0x2c56, 0x2c50, 0x2c4a, 0x2c43, 0x2c3d, 0x2c36, 0x2c30, 0x2c29, 0x2c23, + 0x2c1c, 0x2c16, 0x2c0f, 0x2c08, 0x2c02, 0x2bfb, 0x2bf5, 0x2bee, 0x2be8, 0x2be1, 0x2bda, 0x2bd4, 0x2bcd, 0x2bc7, 0x2bc0, 0x2bb9, + 0x2bb3, 0x2bac, 0x2ba5, 0x2b9f, 0x2b98, 0x2b91, 0x2b8a, 0x2b84, 0x2b7d, 0x2b76, 0x2b6f, 0x2b69, 0x2b62, 0x2b5b, 0x2b54, 0x2b4e, + 0x2b47, 0x2b40, 0x2b39, 0x2b32, 0x2b2b, 0x2b25, 0x2b1e, 0x2b17, 0x2b10, 0x2b09, 0x2b02, 0x2afb, 0x2af4, 0x2aed, 0x2ae7, 0x2ae0, + 0x2ad9, 0x2ad2, 0x2acb, 0x2ac4, 0x2abd, 0x2ab6, 0x2aaf, 0x2aa8, 0x2aa1, 0x2a9a, 0x2a93, 0x2a8c, 0x2a85, 0x2a7d, 0x2a76, 0x2a6f, + 0x2a68, 0x2a61, 0x2a5a, 0x2a53, 0x2a4c, 0x2a45, 0x2a3d, 0x2a36, 0x2a2f, 0x2a28, 0x2a21, 0x2a1a, 0x2a12, 0x2a0b, 0x2a04, 0x29fd, + 0x29f5, 0x29ee, 0x29e7, 0x29e0, 0x29d8, 0x29d1, 0x29ca, 0x29c3, 0x29bb, 0x29b4, 0x29ad, 0x29a5, 0x299e, 0x2997, 0x298f, 0x2988, + 0x2980, 0x2979, 0x2972, 0x296a, 0x2963, 0x295b, 0x2954, 0x294c, 0x2945, 0x293e, 0x2936, 0x292f, 0x2927, 0x2920, 0x2918, 0x2911, + 0x2909, 0x2901, 0x28fa, 0x28f2, 0x28eb, 0x28e3, 0x28dc, 0x28d4, 0x28cc, 0x28c5, 0x28bd, 0x28b6, 0x28ae, 0x28a6, 0x289f, 0x2897, + 0x288f, 0x2888, 0x2880, 0x2878, 0x2871, 0x2869, 0x2861, 0x2859, 0x2852, 0x284a, 0x2842, 0x283a, 0x2833, 0x282b, 0x2823, 0x281b, + 0x2813, 0x280b, 0x2804, 0x27fc, 0x27f4, 0x27ec, 0x27e4, 0x27dc, 0x27d4, 0x27cd, 0x27c5, 0x27bd, 0x27b5, 0x27ad, 0x27a5, 0x279d, + 0x2795, 0x278d, 0x2785, 0x277d, 0x2775, 0x276d, 0x2765, 0x275d, 0x2755, 0x274d, 0x2745, 0x273d, 0x2735, 0x272d, 0x2724, 0x271c, + 0x2714, 0x270c, 0x2704, 0x26fc, 0x26f4, 0x26ec, 0x26e3, 0x26db, 0x26d3, 0x26cb, 0x26c3, 0x26ba, 0x26b2, 0x26aa, 0x26a2, 0x269a, + 0x2691, 0x2689, 0x2681, 0x2678, 0x2670, 0x2668, 0x2660, 0x2657, 0x264f, 0x2647, 0x263e, 0x2636, 0x262d, 0x2625, 0x261d, 0x2614, + 0x260c, 0x2603, 0x25fb, 0x25f3, 0x25ea, 0x25e2, 0x25d9, 0x25d1, 0x25c8, 0x25c0, 0x25b7, 0x25af, 0x25a6, 0x259e, 0x2595, 0x258d, + 0x2584, 0x257c, 0x2573, 0x256a, 0x2562, 0x2559, 0x2551, 0x2548, 0x253f, 0x2537, 0x252e, 0x2525, 0x251d, 0x2514, 0x250b, 0x2503, + 0x24fa, 0x24f1, 0x24e9, 0x24e0, 0x24d7, 0x24ce, 0x24c6, 0x24bd, 0x24b4, 0x24ab, 0x24a3, 0x249a, 0x2491, 0x2488, 0x247f, 0x2476, + 0x246e, 0x2465, 0x245c, 0x2453, 0x244a, 0x2441, 0x2438, 0x242f, 0x2426, 0x241e, 0x2415, 0x240c, 0x2403, 0x23fa, 0x23f1, 0x23e8, + 0x23df, 0x23d6, 0x23cd, 0x23c4, 0x23bb, 0x23b2, 0x23a9, 0x23a0, 0x2396, 0x238d, 0x2384, 0x237b, 0x2372, 0x2369, 0x2360, 0x2357, + 0x234e, 0x2344, 0x233b, 0x2332, 0x2329, 0x2320, 0x2317, 0x230d, 0x2304, 0x22fb, 0x22f2, 0x22e8, 0x22df, 0x22d6, 0x22cd, 0x22c3, + 0x22ba, 0x22b1, 0x22a7, 0x229e, 0x2295, 0x228b, 0x2282, 0x2279, 0x226f, 0x2266, 0x225d, 0x2253, 0x224a, 0x2240, 0x2237, 0x222e, + 0x2224, 0x221b, 0x2211, 0x2208, 0x21fe, 0x21f5, 0x21eb, 0x21e2, 0x21d8, 0x21cf, 0x21c5, 0x21bc, 0x21b2, 0x21a9, 0x219f, 0x2195, + 0x218c, 0x2182, 0x2179, 0x216f, 0x2165, 0x215c, 0x2152, 0x2148, 0x213f, 0x2135, 0x212b, 0x2122, 0x2118, 0x210e, 0x2105, 0x20fb, + 0x20f1, 0x20e7, 0x20de, 0x20d4, 0x20ca, 0x20c0, 0x20b6, 0x20ad, 0x20a3, 0x2099, 0x208f, 0x2085, 0x207b, 0x2072, 0x2068, 0x205e, + 0x2054, 0x204a, 0x2040, 0x2036, 0x202c, 0x2022, 0x2018, 0x200e, 0x2005, 0x1ffb, 0x1ff1, 0x1fe7, 0x1fdd, 0x1fd3, 0x1fc9, 0x1fbf, + 0x1fb4, 0x1faa, 0x1fa0, 0x1f96, 0x1f8c, 0x1f82, 0x1f78, 0x1f6e, 0x1f64, 0x1f5a, 0x1f50, 0x1f45, 0x1f3b, 0x1f31, 0x1f27, 0x1f1d, + 0x1f13, 0x1f08, 0x1efe, 0x1ef4, 0x1eea, 0x1ee0, 0x1ed5, 0x1ecb, 0x1ec1, 0x1eb6, 0x1eac, 0x1ea2, 0x1e98, 0x1e8d, 0x1e83, 0x1e79, + 0x1e6e, 0x1e64, 0x1e5a, 0x1e4f, 0x1e45, 0x1e3a, 0x1e30, 0x1e26, 0x1e1b, 0x1e11, 0x1e06, 0x1dfc, 0x1df2, 0x1de7, 0x1ddd, 0x1dd2, + 0x1dc8, 0x1dbd, 0x1db3, 0x1da8, 0x1d9e, 0x1d93, 0x1d88, 0x1d7e, 0x1d73, 0x1d69, 0x1d5e, 0x1d54, 0x1d49, 0x1d3e, 0x1d34, 0x1d29, + 0x1d1f, 0x1d14, 0x1d09, 0x1cff, 0x1cf4, 0x1ce9, 0x1cde, 0x1cd4, 0x1cc9, 0x1cbe, 0x1cb4, 0x1ca9, 0x1c9e, 0x1c93, 0x1c89, 0x1c7e, + 0x1c73, 0x1c68, 0x1c5d, 0x1c53, 0x1c48, 0x1c3d, 0x1c32, 0x1c27, 0x1c1c, 0x1c11, 0x1c07, 0x1bfc, 0x1bf1, 0x1be6, 0x1bdb, 0x1bd0, + 0x1bc5, 0x1bba, 0x1baf, 0x1ba4, 0x1b99, 0x1b8e, 0x1b83, 0x1b78, 0x1b6d, 0x1b62, 0x1b57, 0x1b4c, 0x1b41, 0x1b36, 0x1b2b, 0x1b20, + 0x1b15, 0x1b0a, 0x1aff, 0x1af3, 0x1ae8, 0x1add, 0x1ad2, 0x1ac7, 0x1abc, 0x1ab0, 0x1aa5, 0x1a9a, 0x1a8f, 0x1a84, 0x1a78, 0x1a6d, + 0x1a62, 0x1a57, 0x1a4b, 0x1a40, 0x1a35, 0x1a2a, 0x1a1e, 0x1a13, 0x1a08, 0x19fc, 0x19f1, 0x19e6, 0x19da, 0x19cf, 0x19c4, 0x19b8, + 0x19ad, 0x19a1, 0x1996, 0x198b, 0x197f, 0x1974, 0x1968, 0x195d, 0x1951, 0x1946, 0x193a, 0x192f, 0x1923, 0x1918, 0x190c, 0x1901, + 0x18f5, 0x18ea, 0x18de, 0x18d2, 0x18c7, 0x18bb, 0x18b0, 0x18a4, 0x1898, 0x188d, 0x1881, 0x1876, 0x186a, 0x185e, 0x1853, 0x1847, + 0x183b, 0x182f, 0x1824, 0x1818, 0x180c, 0x1801, 0x17f5, 0x17e9, 0x17dd, 0x17d1, 0x17c6, 0x17ba, 0x17ae, 0x17a2, 0x1796, 0x178b, + 0x177f, 0x1773, 0x1767, 0x175b, 0x174f, 0x1743, 0x1737, 0x172b, 0x1720, 0x1714, 0x1708, 0x16fc, 0x16f0, 0x16e4, 0x16d8, 0x16cc, + 0x16c0, 0x16b4, 0x16a8, 0x169c, 0x1690, 0x1684, 0x1678, 0x166c, 0x165f, 0x1653, 0x1647, 0x163b, 0x162f, 0x1623, 0x1617, 0x160b, + 0x15fe, 0x15f2, 0x15e6, 0x15da, 0x15ce, 0x15c2, 0x15b5, 0x15a9, 0x159d, 0x1591, 0x1584, 0x1578, 0x156c, 0x1560, 0x1553, 0x1547, + 0x153b, 0x152e, 0x1522, 0x1516, 0x1509, 0x14fd, 0x14f1, 0x14e4, 0x14d8, 0x14cb, 0x14bf, 0x14b3, 0x14a6, 0x149a, 0x148d, 0x1481, + 0x1474, 0x1468, 0x145c, 0x144f, 0x1443, 0x1436, 0x1429, 0x141d, 0x1410, 0x1404, 0x13f7, 0x13eb, 0x13de, 0x13d2, 0x13c5, 0x13b8, + 0x13ac, 0x139f, 0x1393, 0x1386, 0x1379, 0x136d, 0x1360, 0x1353, 0x1347, 0x133a, 0x132d, 0x1320, 0x1314, 0x1307, 0x12fa, 0x12ed, + 0x12e1, 0x12d4, 0x12c7, 0x12ba, 0x12ae, 0x12a1, 0x1294, 0x1287, 0x127a, 0x126d, 0x1261, 0x1254, 0x1247, 0x123a, 0x122d, 0x1220, + 0x1213, 0x1206, 0x11f9, 0x11ec, 0x11df, 0x11d2, 0x11c5, 0x11b8, 0x11ab, 0x119e, 0x1191, 0x1184, 0x1177, 0x116a, 0x115d, 0x1150, + 0x1143, 0x1136, 0x1129, 0x111c, 0x110f, 0x1102, 0x10f5, 0x10e7, 0x10da, 0x10cd, 0x10c0, 0x10b3, 0x10a6, 0x1098, 0x108b, 0x107e, + 0x1071, 0x1063, 0x1056, 0x1049, 0x103c, 0x102e, 0x1021, 0x1014, 0x1007, 0x0ff9, 0x0fec, 0x0fdf, 0x0fd1, 0x0fc4, 0x0fb7, 0x0fa9, + 0x0f9c, 0x0f8e, 0x0f81, 0x0f74, 0x0f66, 0x0f59, 0x0f4b, 0x0f3e, 0x0f30, 0x0f23, 0x0f15, 0x0f08, 0x0efa, 0x0eed, 0x0edf, 0x0ed2, + 0x0ec4, 0x0eb7, 0x0ea9, 0x0e9c, 0x0e8e, 0x0e81, 0x0e73, 0x0e65, 0x0e58, 0x0e4a, 0x0e3d, 0x0e2f, 0x0e21, 0x0e14, 0x0e06, 0x0df8, + 0x0deb, 0x0ddd, 0x0dcf, 0x0dc1, 0x0db4, 0x0da6, 0x0d98, 0x0d8b, 0x0d7d, 0x0d6f, 0x0d61, 0x0d53, 0x0d46, 0x0d38, 0x0d2a, 0x0d1c, + 0x0d0e, 0x0d00, 0x0cf3, 0x0ce5, 0x0cd7, 0x0cc9, 0x0cbb, 0x0cad, 0x0c9f, 0x0c91, 0x0c83, 0x0c75, 0x0c68, 0x0c5a, 0x0c4c, 0x0c3e, + 0x0c30, 0x0c22, 0x0c14, 0x0c06, 0x0bf8, 0x0bea, 0x0bdb, 0x0bcd, 0x0bbf, 0x0bb1, 0x0ba3, 0x0b95, 0x0b87, 0x0b79, 0x0b6b, 0x0b5d, + 0x0b4e, 0x0b40, 0x0b32, 0x0b24, 0x0b16, 0x0b08, 0x0af9, 0x0aeb, 0x0add, 0x0acf, 0x0ac0, 0x0ab2, 0x0aa4, 0x0a96, 0x0a87, 0x0a79, + 0x0a6b, 0x0a5c, 0x0a4e, 0x0a40, 0x0a31, 0x0a23, 0x0a15, 0x0a06, 0x09f8, 0x09ea, 0x09db, 0x09cd, 0x09be, 0x09b0, 0x09a2, 0x0993, + 0x0985, 0x0976, 0x0968, 0x0959, 0x094b, 0x093c, 0x092e, 0x091f, 0x0911, 0x0902, 0x08f4, 0x08e5, 0x08d6, 0x08c8, 0x08b9, 0x08ab, + 0x089c, 0x088d, 0x087f, 0x0870, 0x0862, 0x0853, 0x0844, 0x0836, 0x0827, 0x0818, 0x0809, 0x07fb, 0x07ec, 0x07dd, 0x07cf, 0x07c0, + 0x07b1, 0x07a2, 0x0794, 0x0785, 0x0776, 0x0767, 0x0758, 0x0749, 0x073b, 0x072c, 0x071d, 0x070e, 0x06ff, 0x06f0, 0x06e1, 0x06d2, + 0x06c4, 0x06b5, 0x06a6, 0x0697, 0x0688, 0x0679, 0x066a, 0x065b, 0x064c, 0x063d, 0x062e, 0x061f, 0x0610, 0x0601, 0x05f2, 0x05e3, + 0x05d4, 0x05c5, 0x05b5, 0x05a6, 0x0597, 0x0588, 0x0579, 0x056a, 0x055b, 0x054c, 0x053c, 0x052d, 0x051e, 0x050f, 0x0500, 0x04f0, + 0x04e1, 0x04d2, 0x04c3, 0x04b3, 0x04a4, 0x0495, 0x0486, 0x0476, 0x0467, 0x0458, 0x0448, 0x0439, 0x042a, 0x041a, 0x040b, 0x03fc, + 0x03ec, 0x03dd, 0x03cd, 0x03be, 0x03af, 0x039f, 0x0390, 0x0380, 0x0371, 0x0361, 0x0352, 0x0342, 0x0333, 0x0323, 0x0314, 0x0304, + 0x02f5, 0x02e5, 0x02d6, 0x02c6, 0x02b7, 0x02a7, 0x0297, 0x0288, 0x0278, 0x0269, 0x0259, 0x0249, 0x023a, 0x022a, 0x021a, 0x020b, + 0x01fb, 0x01eb, 0x01dc, 0x01cc, 0x01bc, 0x01ac, 0x019d, 0x018d, 0x017d, 0x016d, 0x015e, 0x014e, 0x013e, 0x012e, 0x011e, 0x010f, + 0x00ff, 0x00ef, 0x00df, 0x00cf, 0x00bf, 0x00af, 0x00a0, 0x0090, 0x0080, 0x0070, 0x0060, 0x0050, 0x0040, 0x0030, 0x0020, 0x0010, + 0x0000, +}; + +// This table was generated using the following PICO-8 code: +// for i=0,1,0x.002 do printh('0x'..sub(tostr(atan2(1,-i),1),8,13)) end +static uint16_t atantable[] = +{ + 0x0000, 0x0005, 0x000a, 0x000f, 0x0014, 0x0019, 0x001f, 0x0024, 0x0029, 0x002e, 0x0033, 0x0038, 0x003d, 0x0042, 0x0047, 0x004c, + 0x0051, 0x0057, 0x005c, 0x0061, 0x0066, 0x006b, 0x0070, 0x0075, 0x007a, 0x007f, 0x0084, 0x008a, 0x008f, 0x0094, 0x0099, 0x009e, + 0x00a3, 0x00a8, 0x00ad, 0x00b2, 0x00b7, 0x00bc, 0x00c2, 0x00c7, 0x00cc, 0x00d1, 0x00d6, 0x00db, 0x00e0, 0x00e5, 0x00ea, 0x00ef, + 0x00f4, 0x00fa, 0x00ff, 0x0104, 0x0109, 0x010e, 0x0113, 0x0118, 0x011d, 0x0122, 0x0127, 0x012c, 0x0131, 0x0137, 0x013c, 0x0141, + 0x0146, 0x014b, 0x0150, 0x0155, 0x015a, 0x015f, 0x0164, 0x0169, 0x016f, 0x0174, 0x0179, 0x017e, 0x0183, 0x0188, 0x018d, 0x0192, + 0x0197, 0x019c, 0x01a1, 0x01a6, 0x01ac, 0x01b1, 0x01b6, 0x01bb, 0x01c0, 0x01c5, 0x01ca, 0x01cf, 0x01d4, 0x01d9, 0x01de, 0x01e3, + 0x01e9, 0x01ee, 0x01f3, 0x01f8, 0x01fd, 0x0202, 0x0207, 0x020c, 0x0211, 0x0216, 0x021b, 0x0220, 0x0226, 0x022b, 0x0230, 0x0235, + 0x023a, 0x023f, 0x0244, 0x0249, 0x024e, 0x0253, 0x0258, 0x025d, 0x0262, 0x0268, 0x026d, 0x0272, 0x0277, 0x027c, 0x0281, 0x0286, + 0x028b, 0x0290, 0x0295, 0x029a, 0x029f, 0x02a4, 0x02a9, 0x02af, 0x02b4, 0x02b9, 0x02be, 0x02c3, 0x02c8, 0x02cd, 0x02d2, 0x02d7, + 0x02dc, 0x02e1, 0x02e6, 0x02eb, 0x02f0, 0x02f6, 0x02fb, 0x0300, 0x0305, 0x030a, 0x030f, 0x0314, 0x0319, 0x031e, 0x0323, 0x0328, + 0x032d, 0x0332, 0x0337, 0x033c, 0x0341, 0x0347, 0x034c, 0x0351, 0x0356, 0x035b, 0x0360, 0x0365, 0x036a, 0x036f, 0x0374, 0x0379, + 0x037e, 0x0383, 0x0388, 0x038d, 0x0392, 0x0397, 0x039c, 0x03a2, 0x03a7, 0x03ac, 0x03b1, 0x03b6, 0x03bb, 0x03c0, 0x03c5, 0x03ca, + 0x03cf, 0x03d4, 0x03d9, 0x03de, 0x03e3, 0x03e8, 0x03ed, 0x03f2, 0x03f7, 0x03fc, 0x0401, 0x0407, 0x040c, 0x0411, 0x0416, 0x041b, + 0x0420, 0x0425, 0x042a, 0x042f, 0x0434, 0x0439, 0x043e, 0x0443, 0x0448, 0x044d, 0x0452, 0x0457, 0x045c, 0x0461, 0x0466, 0x046b, + 0x0470, 0x0475, 0x047a, 0x047f, 0x0484, 0x0489, 0x048e, 0x0494, 0x0499, 0x049e, 0x04a3, 0x04a8, 0x04ad, 0x04b2, 0x04b7, 0x04bc, + 0x04c1, 0x04c6, 0x04cb, 0x04d0, 0x04d5, 0x04da, 0x04df, 0x04e4, 0x04e9, 0x04ee, 0x04f3, 0x04f8, 0x04fd, 0x0502, 0x0507, 0x050c, + 0x0511, 0x0516, 0x051b, 0x0520, 0x0525, 0x052a, 0x052f, 0x0534, 0x0539, 0x053e, 0x0543, 0x0548, 0x054d, 0x0552, 0x0557, 0x055c, + 0x0561, 0x0566, 0x056b, 0x0570, 0x0575, 0x057a, 0x057f, 0x0584, 0x0589, 0x058e, 0x0593, 0x0598, 0x059d, 0x05a2, 0x05a7, 0x05ac, + 0x05b1, 0x05b6, 0x05bb, 0x05c0, 0x05c5, 0x05ca, 0x05cf, 0x05d4, 0x05d9, 0x05de, 0x05e3, 0x05e8, 0x05ed, 0x05f2, 0x05f7, 0x05fc, + 0x0601, 0x0606, 0x060b, 0x0610, 0x0615, 0x061a, 0x061f, 0x0624, 0x0629, 0x062e, 0x0633, 0x0638, 0x063d, 0x0642, 0x0647, 0x064c, + 0x0651, 0x0656, 0x065b, 0x0660, 0x0665, 0x066a, 0x066e, 0x0673, 0x0678, 0x067d, 0x0682, 0x0687, 0x068c, 0x0691, 0x0696, 0x069b, + 0x06a0, 0x06a5, 0x06aa, 0x06af, 0x06b4, 0x06b9, 0x06be, 0x06c3, 0x06c8, 0x06cd, 0x06d2, 0x06d7, 0x06dc, 0x06e1, 0x06e5, 0x06ea, + 0x06ef, 0x06f4, 0x06f9, 0x06fe, 0x0703, 0x0708, 0x070d, 0x0712, 0x0717, 0x071c, 0x0721, 0x0726, 0x072b, 0x0730, 0x0735, 0x0739, + 0x073e, 0x0743, 0x0748, 0x074d, 0x0752, 0x0757, 0x075c, 0x0761, 0x0766, 0x076b, 0x0770, 0x0775, 0x077a, 0x077e, 0x0783, 0x0788, + 0x078d, 0x0792, 0x0797, 0x079c, 0x07a1, 0x07a6, 0x07ab, 0x07b0, 0x07b5, 0x07b9, 0x07be, 0x07c3, 0x07c8, 0x07cd, 0x07d2, 0x07d7, + 0x07dc, 0x07e1, 0x07e6, 0x07eb, 0x07ef, 0x07f4, 0x07f9, 0x07fe, 0x0803, 0x0808, 0x080d, 0x0812, 0x0817, 0x081c, 0x0820, 0x0825, + 0x082a, 0x082f, 0x0834, 0x0839, 0x083e, 0x0843, 0x0848, 0x084c, 0x0851, 0x0856, 0x085b, 0x0860, 0x0865, 0x086a, 0x086f, 0x0873, + 0x0878, 0x087d, 0x0882, 0x0887, 0x088c, 0x0891, 0x0896, 0x089a, 0x089f, 0x08a4, 0x08a9, 0x08ae, 0x08b3, 0x08b8, 0x08bd, 0x08c1, + 0x08c6, 0x08cb, 0x08d0, 0x08d5, 0x08da, 0x08df, 0x08e3, 0x08e8, 0x08ed, 0x08f2, 0x08f7, 0x08fc, 0x0901, 0x0905, 0x090a, 0x090f, + 0x0914, 0x0919, 0x091e, 0x0922, 0x0927, 0x092c, 0x0931, 0x0936, 0x093b, 0x093f, 0x0944, 0x0949, 0x094e, 0x0953, 0x0958, 0x095c, + 0x0961, 0x0966, 0x096b, 0x0970, 0x0975, 0x0979, 0x097e, 0x0983, 0x0988, 0x098d, 0x0992, 0x0996, 0x099b, 0x09a0, 0x09a5, 0x09aa, + 0x09ae, 0x09b3, 0x09b8, 0x09bd, 0x09c2, 0x09c6, 0x09cb, 0x09d0, 0x09d5, 0x09da, 0x09de, 0x09e3, 0x09e8, 0x09ed, 0x09f2, 0x09f6, + 0x09fb, 0x0a00, 0x0a05, 0x0a0a, 0x0a0e, 0x0a13, 0x0a18, 0x0a1d, 0x0a22, 0x0a26, 0x0a2b, 0x0a30, 0x0a35, 0x0a39, 0x0a3e, 0x0a43, + 0x0a48, 0x0a4d, 0x0a51, 0x0a56, 0x0a5b, 0x0a60, 0x0a64, 0x0a69, 0x0a6e, 0x0a73, 0x0a77, 0x0a7c, 0x0a81, 0x0a86, 0x0a8b, 0x0a8f, + 0x0a94, 0x0a99, 0x0a9e, 0x0aa2, 0x0aa7, 0x0aac, 0x0ab1, 0x0ab5, 0x0aba, 0x0abf, 0x0ac4, 0x0ac8, 0x0acd, 0x0ad2, 0x0ad7, 0x0adb, + 0x0ae0, 0x0ae5, 0x0ae9, 0x0aee, 0x0af3, 0x0af8, 0x0afc, 0x0b01, 0x0b06, 0x0b0b, 0x0b0f, 0x0b14, 0x0b19, 0x0b1e, 0x0b22, 0x0b27, + 0x0b2c, 0x0b30, 0x0b35, 0x0b3a, 0x0b3f, 0x0b43, 0x0b48, 0x0b4d, 0x0b51, 0x0b56, 0x0b5b, 0x0b60, 0x0b64, 0x0b69, 0x0b6e, 0x0b72, + 0x0b77, 0x0b7c, 0x0b80, 0x0b85, 0x0b8a, 0x0b8f, 0x0b93, 0x0b98, 0x0b9d, 0x0ba1, 0x0ba6, 0x0bab, 0x0baf, 0x0bb4, 0x0bb9, 0x0bbd, + 0x0bc2, 0x0bc7, 0x0bcb, 0x0bd0, 0x0bd5, 0x0bd9, 0x0bde, 0x0be3, 0x0be7, 0x0bec, 0x0bf1, 0x0bf5, 0x0bfa, 0x0bff, 0x0c03, 0x0c08, + 0x0c0d, 0x0c11, 0x0c16, 0x0c1b, 0x0c1f, 0x0c24, 0x0c29, 0x0c2d, 0x0c32, 0x0c37, 0x0c3b, 0x0c40, 0x0c45, 0x0c49, 0x0c4e, 0x0c53, + 0x0c57, 0x0c5c, 0x0c60, 0x0c65, 0x0c6a, 0x0c6e, 0x0c73, 0x0c78, 0x0c7c, 0x0c81, 0x0c86, 0x0c8a, 0x0c8f, 0x0c93, 0x0c98, 0x0c9d, + 0x0ca1, 0x0ca6, 0x0cab, 0x0caf, 0x0cb4, 0x0cb8, 0x0cbd, 0x0cc2, 0x0cc6, 0x0ccb, 0x0ccf, 0x0cd4, 0x0cd9, 0x0cdd, 0x0ce2, 0x0ce6, + 0x0ceb, 0x0cf0, 0x0cf4, 0x0cf9, 0x0cfd, 0x0d02, 0x0d07, 0x0d0b, 0x0d10, 0x0d14, 0x0d19, 0x0d1e, 0x0d22, 0x0d27, 0x0d2b, 0x0d30, + 0x0d34, 0x0d39, 0x0d3e, 0x0d42, 0x0d47, 0x0d4b, 0x0d50, 0x0d54, 0x0d59, 0x0d5e, 0x0d62, 0x0d67, 0x0d6b, 0x0d70, 0x0d74, 0x0d79, + 0x0d7d, 0x0d82, 0x0d87, 0x0d8b, 0x0d90, 0x0d94, 0x0d99, 0x0d9d, 0x0da2, 0x0da6, 0x0dab, 0x0daf, 0x0db4, 0x0db9, 0x0dbd, 0x0dc2, + 0x0dc6, 0x0dcb, 0x0dcf, 0x0dd4, 0x0dd8, 0x0ddd, 0x0de1, 0x0de6, 0x0dea, 0x0def, 0x0df3, 0x0df8, 0x0dfc, 0x0e01, 0x0e05, 0x0e0a, + 0x0e0f, 0x0e13, 0x0e18, 0x0e1c, 0x0e21, 0x0e25, 0x0e2a, 0x0e2e, 0x0e33, 0x0e37, 0x0e3c, 0x0e40, 0x0e45, 0x0e49, 0x0e4e, 0x0e52, + 0x0e56, 0x0e5b, 0x0e5f, 0x0e64, 0x0e68, 0x0e6d, 0x0e71, 0x0e76, 0x0e7a, 0x0e7f, 0x0e83, 0x0e88, 0x0e8c, 0x0e91, 0x0e95, 0x0e9a, + 0x0e9e, 0x0ea3, 0x0ea7, 0x0eac, 0x0eb0, 0x0eb4, 0x0eb9, 0x0ebd, 0x0ec2, 0x0ec6, 0x0ecb, 0x0ecf, 0x0ed4, 0x0ed8, 0x0edc, 0x0ee1, + 0x0ee5, 0x0eea, 0x0eee, 0x0ef3, 0x0ef7, 0x0efc, 0x0f00, 0x0f04, 0x0f09, 0x0f0d, 0x0f12, 0x0f16, 0x0f1b, 0x0f1f, 0x0f23, 0x0f28, + 0x0f2c, 0x0f31, 0x0f35, 0x0f3a, 0x0f3e, 0x0f42, 0x0f47, 0x0f4b, 0x0f50, 0x0f54, 0x0f58, 0x0f5d, 0x0f61, 0x0f66, 0x0f6a, 0x0f6e, + 0x0f73, 0x0f77, 0x0f7c, 0x0f80, 0x0f84, 0x0f89, 0x0f8d, 0x0f91, 0x0f96, 0x0f9a, 0x0f9f, 0x0fa3, 0x0fa7, 0x0fac, 0x0fb0, 0x0fb5, + 0x0fb9, 0x0fbd, 0x0fc2, 0x0fc6, 0x0fca, 0x0fcf, 0x0fd3, 0x0fd7, 0x0fdc, 0x0fe0, 0x0fe5, 0x0fe9, 0x0fed, 0x0ff2, 0x0ff6, 0x0ffa, + 0x0fff, 0x1003, 0x1007, 0x100c, 0x1010, 0x1014, 0x1019, 0x101d, 0x1021, 0x1026, 0x102a, 0x102e, 0x1033, 0x1037, 0x103b, 0x1040, + 0x1044, 0x1048, 0x104d, 0x1051, 0x1055, 0x105a, 0x105e, 0x1062, 0x1067, 0x106b, 0x106f, 0x1073, 0x1078, 0x107c, 0x1080, 0x1085, + 0x1089, 0x108d, 0x1092, 0x1096, 0x109a, 0x109e, 0x10a3, 0x10a7, 0x10ab, 0x10b0, 0x10b4, 0x10b8, 0x10bc, 0x10c1, 0x10c5, 0x10c9, + 0x10ce, 0x10d2, 0x10d6, 0x10da, 0x10df, 0x10e3, 0x10e7, 0x10eb, 0x10f0, 0x10f4, 0x10f8, 0x10fd, 0x1101, 0x1105, 0x1109, 0x110e, + 0x1112, 0x1116, 0x111a, 0x111f, 0x1123, 0x1127, 0x112b, 0x1130, 0x1134, 0x1138, 0x113c, 0x1140, 0x1145, 0x1149, 0x114d, 0x1151, + 0x1156, 0x115a, 0x115e, 0x1162, 0x1166, 0x116b, 0x116f, 0x1173, 0x1177, 0x117c, 0x1180, 0x1184, 0x1188, 0x118c, 0x1191, 0x1195, + 0x1199, 0x119d, 0x11a1, 0x11a6, 0x11aa, 0x11ae, 0x11b2, 0x11b6, 0x11bb, 0x11bf, 0x11c3, 0x11c7, 0x11cb, 0x11cf, 0x11d4, 0x11d8, + 0x11dc, 0x11e0, 0x11e4, 0x11e9, 0x11ed, 0x11f1, 0x11f5, 0x11f9, 0x11fd, 0x1202, 0x1206, 0x120a, 0x120e, 0x1212, 0x1216, 0x121a, + 0x121f, 0x1223, 0x1227, 0x122b, 0x122f, 0x1233, 0x1237, 0x123c, 0x1240, 0x1244, 0x1248, 0x124c, 0x1250, 0x1254, 0x1259, 0x125d, + 0x1261, 0x1265, 0x1269, 0x126d, 0x1271, 0x1275, 0x127a, 0x127e, 0x1282, 0x1286, 0x128a, 0x128e, 0x1292, 0x1296, 0x129a, 0x129f, + 0x12a3, 0x12a7, 0x12ab, 0x12af, 0x12b3, 0x12b7, 0x12bb, 0x12bf, 0x12c3, 0x12c7, 0x12cc, 0x12d0, 0x12d4, 0x12d8, 0x12dc, 0x12e0, + 0x12e4, 0x12e8, 0x12ec, 0x12f0, 0x12f4, 0x12f8, 0x12fc, 0x1301, 0x1305, 0x1309, 0x130d, 0x1311, 0x1315, 0x1319, 0x131d, 0x1321, + 0x1325, 0x1329, 0x132d, 0x1331, 0x1335, 0x1339, 0x133d, 0x1341, 0x1345, 0x1349, 0x134d, 0x1351, 0x1355, 0x135a, 0x135e, 0x1362, + 0x1366, 0x136a, 0x136e, 0x1372, 0x1376, 0x137a, 0x137e, 0x1382, 0x1386, 0x138a, 0x138e, 0x1392, 0x1396, 0x139a, 0x139e, 0x13a2, + 0x13a6, 0x13aa, 0x13ae, 0x13b2, 0x13b6, 0x13ba, 0x13be, 0x13c2, 0x13c6, 0x13ca, 0x13ce, 0x13d2, 0x13d6, 0x13da, 0x13de, 0x13e2, + 0x13e6, 0x13e9, 0x13ed, 0x13f1, 0x13f5, 0x13f9, 0x13fd, 0x1401, 0x1405, 0x1409, 0x140d, 0x1411, 0x1415, 0x1419, 0x141d, 0x1421, + 0x1425, 0x1429, 0x142d, 0x1431, 0x1435, 0x1439, 0x143d, 0x1440, 0x1444, 0x1448, 0x144c, 0x1450, 0x1454, 0x1458, 0x145c, 0x1460, + 0x1464, 0x1468, 0x146c, 0x1470, 0x1473, 0x1477, 0x147b, 0x147f, 0x1483, 0x1487, 0x148b, 0x148f, 0x1493, 0x1497, 0x149b, 0x149e, + 0x14a2, 0x14a6, 0x14aa, 0x14ae, 0x14b2, 0x14b6, 0x14ba, 0x14be, 0x14c1, 0x14c5, 0x14c9, 0x14cd, 0x14d1, 0x14d5, 0x14d9, 0x14dd, + 0x14e0, 0x14e4, 0x14e8, 0x14ec, 0x14f0, 0x14f4, 0x14f8, 0x14fb, 0x14ff, 0x1503, 0x1507, 0x150b, 0x150f, 0x1513, 0x1516, 0x151a, + 0x151e, 0x1522, 0x1526, 0x152a, 0x152d, 0x1531, 0x1535, 0x1539, 0x153d, 0x1541, 0x1544, 0x1548, 0x154c, 0x1550, 0x1554, 0x1558, + 0x155b, 0x155f, 0x1563, 0x1567, 0x156b, 0x156e, 0x1572, 0x1576, 0x157a, 0x157e, 0x1581, 0x1585, 0x1589, 0x158d, 0x1591, 0x1594, + 0x1598, 0x159c, 0x15a0, 0x15a4, 0x15a7, 0x15ab, 0x15af, 0x15b3, 0x15b7, 0x15ba, 0x15be, 0x15c2, 0x15c6, 0x15c9, 0x15cd, 0x15d1, + 0x15d5, 0x15d8, 0x15dc, 0x15e0, 0x15e4, 0x15e8, 0x15eb, 0x15ef, 0x15f3, 0x15f7, 0x15fa, 0x15fe, 0x1602, 0x1606, 0x1609, 0x160d, + 0x1611, 0x1614, 0x1618, 0x161c, 0x1620, 0x1623, 0x1627, 0x162b, 0x162f, 0x1632, 0x1636, 0x163a, 0x163e, 0x1641, 0x1645, 0x1649, + 0x164c, 0x1650, 0x1654, 0x1658, 0x165b, 0x165f, 0x1663, 0x1666, 0x166a, 0x166e, 0x1671, 0x1675, 0x1679, 0x167d, 0x1680, 0x1684, + 0x1688, 0x168b, 0x168f, 0x1693, 0x1696, 0x169a, 0x169e, 0x16a1, 0x16a5, 0x16a9, 0x16ac, 0x16b0, 0x16b4, 0x16b7, 0x16bb, 0x16bf, + 0x16c2, 0x16c6, 0x16ca, 0x16cd, 0x16d1, 0x16d5, 0x16d8, 0x16dc, 0x16e0, 0x16e3, 0x16e7, 0x16eb, 0x16ee, 0x16f2, 0x16f6, 0x16f9, + 0x16fd, 0x1700, 0x1704, 0x1708, 0x170b, 0x170f, 0x1713, 0x1716, 0x171a, 0x171d, 0x1721, 0x1725, 0x1728, 0x172c, 0x1730, 0x1733, + 0x1737, 0x173a, 0x173e, 0x1742, 0x1745, 0x1749, 0x174c, 0x1750, 0x1754, 0x1757, 0x175b, 0x175e, 0x1762, 0x1766, 0x1769, 0x176d, + 0x1770, 0x1774, 0x1778, 0x177b, 0x177f, 0x1782, 0x1786, 0x1789, 0x178d, 0x1791, 0x1794, 0x1798, 0x179b, 0x179f, 0x17a2, 0x17a6, + 0x17aa, 0x17ad, 0x17b1, 0x17b4, 0x17b8, 0x17bb, 0x17bf, 0x17c2, 0x17c6, 0x17c9, 0x17cd, 0x17d1, 0x17d4, 0x17d8, 0x17db, 0x17df, + 0x17e2, 0x17e6, 0x17e9, 0x17ed, 0x17f0, 0x17f4, 0x17f7, 0x17fb, 0x17fe, 0x1802, 0x1806, 0x1809, 0x180d, 0x1810, 0x1814, 0x1817, + 0x181b, 0x181e, 0x1822, 0x1825, 0x1829, 0x182c, 0x1830, 0x1833, 0x1837, 0x183a, 0x183e, 0x1841, 0x1845, 0x1848, 0x184c, 0x184f, + 0x1853, 0x1856, 0x185a, 0x185d, 0x1860, 0x1864, 0x1867, 0x186b, 0x186e, 0x1872, 0x1875, 0x1879, 0x187c, 0x1880, 0x1883, 0x1887, + 0x188a, 0x188e, 0x1891, 0x1894, 0x1898, 0x189b, 0x189f, 0x18a2, 0x18a6, 0x18a9, 0x18ad, 0x18b0, 0x18b3, 0x18b7, 0x18ba, 0x18be, + 0x18c1, 0x18c5, 0x18c8, 0x18cc, 0x18cf, 0x18d2, 0x18d6, 0x18d9, 0x18dd, 0x18e0, 0x18e3, 0x18e7, 0x18ea, 0x18ee, 0x18f1, 0x18f5, + 0x18f8, 0x18fb, 0x18ff, 0x1902, 0x1906, 0x1909, 0x190c, 0x1910, 0x1913, 0x1917, 0x191a, 0x191d, 0x1921, 0x1924, 0x1928, 0x192b, + 0x192e, 0x1932, 0x1935, 0x1938, 0x193c, 0x193f, 0x1943, 0x1946, 0x1949, 0x194d, 0x1950, 0x1953, 0x1957, 0x195a, 0x195d, 0x1961, + 0x1964, 0x1968, 0x196b, 0x196e, 0x1972, 0x1975, 0x1978, 0x197c, 0x197f, 0x1982, 0x1986, 0x1989, 0x198c, 0x1990, 0x1993, 0x1996, + 0x199a, 0x199d, 0x19a0, 0x19a4, 0x19a7, 0x19aa, 0x19ae, 0x19b1, 0x19b4, 0x19b8, 0x19bb, 0x19be, 0x19c2, 0x19c5, 0x19c8, 0x19cc, + 0x19cf, 0x19d2, 0x19d5, 0x19d9, 0x19dc, 0x19df, 0x19e3, 0x19e6, 0x19e9, 0x19ed, 0x19f0, 0x19f3, 0x19f6, 0x19fa, 0x19fd, 0x1a00, + 0x1a04, 0x1a07, 0x1a0a, 0x1a0d, 0x1a11, 0x1a14, 0x1a17, 0x1a1b, 0x1a1e, 0x1a21, 0x1a24, 0x1a28, 0x1a2b, 0x1a2e, 0x1a31, 0x1a35, + 0x1a38, 0x1a3b, 0x1a3e, 0x1a42, 0x1a45, 0x1a48, 0x1a4b, 0x1a4f, 0x1a52, 0x1a55, 0x1a58, 0x1a5c, 0x1a5f, 0x1a62, 0x1a65, 0x1a69, + 0x1a6c, 0x1a6f, 0x1a72, 0x1a76, 0x1a79, 0x1a7c, 0x1a7f, 0x1a83, 0x1a86, 0x1a89, 0x1a8c, 0x1a8f, 0x1a93, 0x1a96, 0x1a99, 0x1a9c, + 0x1a9f, 0x1aa3, 0x1aa6, 0x1aa9, 0x1aac, 0x1ab0, 0x1ab3, 0x1ab6, 0x1ab9, 0x1abc, 0x1ac0, 0x1ac3, 0x1ac6, 0x1ac9, 0x1acc, 0x1acf, + 0x1ad3, 0x1ad6, 0x1ad9, 0x1adc, 0x1adf, 0x1ae3, 0x1ae6, 0x1ae9, 0x1aec, 0x1aef, 0x1af2, 0x1af6, 0x1af9, 0x1afc, 0x1aff, 0x1b02, + 0x1b05, 0x1b09, 0x1b0c, 0x1b0f, 0x1b12, 0x1b15, 0x1b18, 0x1b1c, 0x1b1f, 0x1b22, 0x1b25, 0x1b28, 0x1b2b, 0x1b2e, 0x1b32, 0x1b35, + 0x1b38, 0x1b3b, 0x1b3e, 0x1b41, 0x1b44, 0x1b48, 0x1b4b, 0x1b4e, 0x1b51, 0x1b54, 0x1b57, 0x1b5a, 0x1b5d, 0x1b61, 0x1b64, 0x1b67, + 0x1b6a, 0x1b6d, 0x1b70, 0x1b73, 0x1b76, 0x1b79, 0x1b7d, 0x1b80, 0x1b83, 0x1b86, 0x1b89, 0x1b8c, 0x1b8f, 0x1b92, 0x1b95, 0x1b98, + 0x1b9c, 0x1b9f, 0x1ba2, 0x1ba5, 0x1ba8, 0x1bab, 0x1bae, 0x1bb1, 0x1bb4, 0x1bb7, 0x1bba, 0x1bbd, 0x1bc1, 0x1bc4, 0x1bc7, 0x1bca, + 0x1bcd, 0x1bd0, 0x1bd3, 0x1bd6, 0x1bd9, 0x1bdc, 0x1bdf, 0x1be2, 0x1be5, 0x1be8, 0x1beb, 0x1bee, 0x1bf2, 0x1bf5, 0x1bf8, 0x1bfb, + 0x1bfe, 0x1c01, 0x1c04, 0x1c07, 0x1c0a, 0x1c0d, 0x1c10, 0x1c13, 0x1c16, 0x1c19, 0x1c1c, 0x1c1f, 0x1c22, 0x1c25, 0x1c28, 0x1c2b, + 0x1c2e, 0x1c31, 0x1c34, 0x1c37, 0x1c3a, 0x1c3d, 0x1c40, 0x1c43, 0x1c46, 0x1c49, 0x1c4c, 0x1c4f, 0x1c52, 0x1c55, 0x1c58, 0x1c5b, + 0x1c5e, 0x1c61, 0x1c64, 0x1c67, 0x1c6a, 0x1c6d, 0x1c70, 0x1c73, 0x1c76, 0x1c79, 0x1c7c, 0x1c7f, 0x1c82, 0x1c85, 0x1c88, 0x1c8b, + 0x1c8e, 0x1c91, 0x1c94, 0x1c97, 0x1c9a, 0x1c9d, 0x1ca0, 0x1ca3, 0x1ca6, 0x1ca9, 0x1cac, 0x1caf, 0x1cb2, 0x1cb5, 0x1cb8, 0x1cbb, + 0x1cbe, 0x1cc1, 0x1cc3, 0x1cc6, 0x1cc9, 0x1ccc, 0x1ccf, 0x1cd2, 0x1cd5, 0x1cd8, 0x1cdb, 0x1cde, 0x1ce1, 0x1ce4, 0x1ce7, 0x1cea, + 0x1ced, 0x1cf0, 0x1cf3, 0x1cf5, 0x1cf8, 0x1cfb, 0x1cfe, 0x1d01, 0x1d04, 0x1d07, 0x1d0a, 0x1d0d, 0x1d10, 0x1d13, 0x1d16, 0x1d18, + 0x1d1b, 0x1d1e, 0x1d21, 0x1d24, 0x1d27, 0x1d2a, 0x1d2d, 0x1d30, 0x1d33, 0x1d35, 0x1d38, 0x1d3b, 0x1d3e, 0x1d41, 0x1d44, 0x1d47, + 0x1d4a, 0x1d4d, 0x1d4f, 0x1d52, 0x1d55, 0x1d58, 0x1d5b, 0x1d5e, 0x1d61, 0x1d64, 0x1d66, 0x1d69, 0x1d6c, 0x1d6f, 0x1d72, 0x1d75, + 0x1d78, 0x1d7b, 0x1d7d, 0x1d80, 0x1d83, 0x1d86, 0x1d89, 0x1d8c, 0x1d8e, 0x1d91, 0x1d94, 0x1d97, 0x1d9a, 0x1d9d, 0x1da0, 0x1da2, + 0x1da5, 0x1da8, 0x1dab, 0x1dae, 0x1db1, 0x1db3, 0x1db6, 0x1db9, 0x1dbc, 0x1dbf, 0x1dc2, 0x1dc4, 0x1dc7, 0x1dca, 0x1dcd, 0x1dd0, + 0x1dd3, 0x1dd5, 0x1dd8, 0x1ddb, 0x1dde, 0x1de1, 0x1de3, 0x1de6, 0x1de9, 0x1dec, 0x1def, 0x1df1, 0x1df4, 0x1df7, 0x1dfa, 0x1dfd, + 0x1dff, 0x1e02, 0x1e05, 0x1e08, 0x1e0b, 0x1e0d, 0x1e10, 0x1e13, 0x1e16, 0x1e19, 0x1e1b, 0x1e1e, 0x1e21, 0x1e24, 0x1e26, 0x1e29, + 0x1e2c, 0x1e2f, 0x1e32, 0x1e34, 0x1e37, 0x1e3a, 0x1e3d, 0x1e3f, 0x1e42, 0x1e45, 0x1e48, 0x1e4a, 0x1e4d, 0x1e50, 0x1e53, 0x1e55, + 0x1e58, 0x1e5b, 0x1e5e, 0x1e60, 0x1e63, 0x1e66, 0x1e69, 0x1e6b, 0x1e6e, 0x1e71, 0x1e74, 0x1e76, 0x1e79, 0x1e7c, 0x1e7f, 0x1e81, + 0x1e84, 0x1e87, 0x1e8a, 0x1e8c, 0x1e8f, 0x1e92, 0x1e94, 0x1e97, 0x1e9a, 0x1e9d, 0x1e9f, 0x1ea2, 0x1ea5, 0x1ea8, 0x1eaa, 0x1ead, + 0x1eb0, 0x1eb2, 0x1eb5, 0x1eb8, 0x1eba, 0x1ebd, 0x1ec0, 0x1ec3, 0x1ec5, 0x1ec8, 0x1ecb, 0x1ecd, 0x1ed0, 0x1ed3, 0x1ed5, 0x1ed8, + 0x1edb, 0x1ede, 0x1ee0, 0x1ee3, 0x1ee6, 0x1ee8, 0x1eeb, 0x1eee, 0x1ef0, 0x1ef3, 0x1ef6, 0x1ef8, 0x1efb, 0x1efe, 0x1f00, 0x1f03, + 0x1f06, 0x1f08, 0x1f0b, 0x1f0e, 0x1f10, 0x1f13, 0x1f16, 0x1f18, 0x1f1b, 0x1f1e, 0x1f20, 0x1f23, 0x1f26, 0x1f28, 0x1f2b, 0x1f2e, + 0x1f30, 0x1f33, 0x1f36, 0x1f38, 0x1f3b, 0x1f3d, 0x1f40, 0x1f43, 0x1f45, 0x1f48, 0x1f4b, 0x1f4d, 0x1f50, 0x1f53, 0x1f55, 0x1f58, + 0x1f5a, 0x1f5d, 0x1f60, 0x1f62, 0x1f65, 0x1f68, 0x1f6a, 0x1f6d, 0x1f6f, 0x1f72, 0x1f75, 0x1f77, 0x1f7a, 0x1f7c, 0x1f7f, 0x1f82, + 0x1f84, 0x1f87, 0x1f8a, 0x1f8c, 0x1f8f, 0x1f91, 0x1f94, 0x1f97, 0x1f99, 0x1f9c, 0x1f9e, 0x1fa1, 0x1fa4, 0x1fa6, 0x1fa9, 0x1fab, + 0x1fae, 0x1fb0, 0x1fb3, 0x1fb6, 0x1fb8, 0x1fbb, 0x1fbd, 0x1fc0, 0x1fc3, 0x1fc5, 0x1fc8, 0x1fca, 0x1fcd, 0x1fcf, 0x1fd2, 0x1fd5, + 0x1fd7, 0x1fda, 0x1fdc, 0x1fdf, 0x1fe1, 0x1fe4, 0x1fe6, 0x1fe9, 0x1fec, 0x1fee, 0x1ff1, 0x1ff3, 0x1ff6, 0x1ff8, 0x1ffb, 0x1ffd, + 0x2000, +}; diff --git a/components/pico8/femto8/src/p8_audio.c b/components/pico8/femto8/src/p8_audio.c new file mode 100644 index 00000000..915939bb --- /dev/null +++ b/components/pico8/femto8/src/p8_audio.c @@ -0,0 +1,650 @@ +/* + * p8_audio.c + * + * Created on: Dec 13, 2023 + * Author: bbaker + */ + +#include +#include +#include +#include +#include +#include +#include "p8_audio.h" +#include "p8_dsp.h" +#include "p8_emu.h" +#include "queue.h" + +#ifdef SDL +#include "SDL.h" +#endif + +#define EFFECT_MASK 0x7000 +#define VOLUME_MASK 0x0E00 +#define WAVEFORM_MASK 0x01C0 +#define PITCH_MASK 0x003F + +#define EFFECT_SHIFT 12 +#define VOLUME_SHIFT 9 +#define WAVEFORM_SHIFT 6 + +#define PCM_BUFFER_SIZE 2048 + +enum +{ + SOUNDMODE_NONE, + SOUNDMODE_SOUND, + SOUNDMODE_MUSIC +}; + +typedef struct +{ + int pattern; + uint8_t channel_mask; +} musicstate_t; + +typedef struct +{ + int sound_mode; + int sound_index; + int sample; + int position; + int end; +} soundstate_t; + +typedef struct +{ + int32_t index; + int32_t channel; + uint32_t start; + uint32_t end; +} sound_t; + +typedef struct +{ + int32_t index; + int32_t fadems; + int32_t mask; +} music_t; + +typedef struct +{ + int sound_mode; + + union + { + sound_t sound; + music_t music; + }; +} soundcommand_t; + +enum +{ + TONE_C, + TONE_CS, + TONE_D, + TONE_DS, + TONE_E, + TONE_F, + TONE_FS, + TONE_G, + TONE_GS, + TONE_A, + TONE_AS, + TONE_B +}; + +enum +{ + WAVEFORM_TRIANGLE, + WAVEFORM_TILTEDSAW, + WAVEFORM_SAW, + WAVEFORM_SQUARE, + WAVEFORM_PULSE, + WAVEFORM_ORGAN, + WAVEFORM_NOISE, + WAVEFORM_PHASER +}; + +enum +{ + EFFECT_NONE, + EFFECT_SLIDE, + EFFECT_VIBRATO, + EFFECT_DROP, + EFFECT_FADEIN, + EFFECT_FADEOUT, + EFFECT_ARPEGGIOFAST, + EFFECT_ARPEGGIOSLOW +}; + +const char *m_tone_map[] = { + "C ", "C#", "D ", "D#", "E ", "F ", "F#", "G ", "G#", "A ", "A#", "B "}; + +const float m_tone_frequencies[] = { + 130.81f, 138.59f, 146.83f, 155.56f, 164.81f, 174.61f, 185.00f, 196.00f, 207.65f, 220.0f, 233.08f, 246.94f}; + +void render_sounds(int16_t *buffer, int total_samples); + +bool m_music_enabled = true; +bool m_sound_enabled = true; + +soundcommand_t m_sound_buffer[SOUND_QUEUE_SIZE]; + +queue_t m_sound_queue = { + .data_buf = m_sound_buffer, + .elements_num_max = SOUND_QUEUE_SIZE, + .elements_size = sizeof(soundcommand_t), +}; + +pthread_mutex_t m_sound_queue_mutex; + +soundstate_t m_channels[CHANNEL_COUNT]; +musicstate_t m_music_state; + +uint8_t m_pcm_buffer[PCM_BUFFER_SIZE]; +int m_pcm_write_pos = 0; +int m_pcm_read_pos = 0; +int m_pcm_buffered = 0; +int m_pcm_repeat = 0; +int16_t m_pcm_dampen = 0; + +#ifdef SDL +SDL_AudioSpec m_audio_spec; +#endif + +void audio_callback(void *userdata, uint8_t *cbuffer, int length) +{ + render_sounds((int16_t *)cbuffer, length / sizeof(int16_t)); +} + +void audio_init() +{ + _queue_init(&m_sound_queue); + +#ifdef SDL + m_audio_spec.freq = SAMPLE_RATE; + m_audio_spec.format = AUDIO_S16SYS; + m_audio_spec.channels = 1; + m_audio_spec.samples = SOUND_BUFFER_SIZE; + m_audio_spec.userdata = NULL; + m_audio_spec.callback = audio_callback; + + int ret = SDL_OpenAudio(&m_audio_spec, &m_audio_spec); + + if (ret != 0) + { + printf("Error on SDL_OpenAudio()\n"); + } + + SDL_PauseAudio(0); +#endif +} + +void audio_resume() +{ +#ifdef SDL + SDL_PauseAudio(0); +#endif +} + +void audio_pause() +{ +#ifdef SDL + SDL_PauseAudio(1); +#endif +} + +void audio_close() +{ +#ifdef SDL + SDL_CloseAudio(); +#endif +} + +void audio_sound(int32_t index, int32_t channel, uint32_t start, uint32_t end) +{ + soundcommand_t sound_command; + sound_command.sound_mode = SOUNDMODE_SOUND; + sound_command.sound.index = index; + sound_command.sound.channel = channel; + sound_command.sound.start = start; + sound_command.sound.end = end; + + pthread_mutex_lock(&m_sound_queue_mutex); + queue_add_back(&m_sound_queue, &sound_command); + pthread_mutex_unlock(&m_sound_queue_mutex); +} + +void audio_music(int32_t index, int32_t fadems, int32_t mask) +{ + soundcommand_t sound_command; + sound_command.sound_mode = SOUNDMODE_MUSIC; + sound_command.music.index = index; + sound_command.music.fadems = fadems; + sound_command.music.mask = mask; + + pthread_mutex_lock(&m_sound_queue_mutex); + queue_add_back(&m_sound_queue, &sound_command); + pthread_mutex_unlock(&m_sound_queue_mutex); +} + +int32_t audio_stat(int32_t index) +{ + if (index >= 16 && index <= 19) + { + int channel = index - 16; + if (m_channels[channel].sound_mode == SOUNDMODE_NONE) + return -1; + return m_channels[channel].sound_index; + } + if (index >= 20 && index <= 23) { + int channel = index - 20; + if (m_channels[channel].sound_mode == SOUNDMODE_NONE) + return -1; + return m_channels[channel].position; + } + if (index >= 46 && index <= 49) { + int channel = index - 46; + if (m_channels[channel].sound_mode == SOUNDMODE_NONE) + return -1; + return m_channels[channel].sound_index; + } + if (index >= 50 && index <= 53) { + int channel = index - 50; + if (m_channels[channel].sound_mode == SOUNDMODE_NONE) + return -1; + return m_channels[channel].position; + } + if (index == 24 || index == 54) { + bool any_music = false; + for (int i = 0; i < CHANNEL_COUNT; ++i) { + if (m_channels[i].sound_mode == SOUNDMODE_MUSIC) { + any_music = true; + break; + } + } + return any_music ? m_music_state.pattern : -1; + } + if (index == 25 || index == 55) { + bool any_music = false; + for (int i = 0; i < CHANNEL_COUNT; ++i) { + if (m_channels[i].sound_mode == SOUNDMODE_MUSIC) { + any_music = true; + break; + } + } + return any_music ? m_music_state.pattern : -1; + } + if (index == 26 || index == 56) { + int ticks = 0; + for (int i = 0; i < CHANNEL_COUNT; ++i) + if (m_channels[i].sound_mode == SOUNDMODE_MUSIC) + ticks = MAX(ticks, m_channels[i].sample); + return ticks; + } + if (index == 57) { + for (int i = 0; i < CHANNEL_COUNT; ++i) { + if (m_channels[i].sound_mode == SOUNDMODE_MUSIC) + return 1; + } + return 0; + } + return 0; +} + +void update_channel(soundstate_t *channel) +{ + if (channel->sound_mode == SOUNDMODE_NONE) + return; + + if (channel->sound_mode == SOUNDMODE_MUSIC) + { + if (channel->sample >= channel->end) + { + bool is_loop_begin = m_memory[MEMORY_MUSIC + 4 * m_music_state.pattern] & (1 << 7); + bool is_loop_end = m_memory[MEMORY_MUSIC + 4 * m_music_state.pattern + 1] & (1 << 7); + bool is_stop = m_memory[MEMORY_MUSIC + 4 * m_music_state.pattern + 2] & (1 << 7); + if (is_stop) + { + return; + } + m_music_state.pattern++; + if (is_loop_end || m_music_state.pattern == MUSIC_COUNT) + { + int i = m_music_state.pattern - 1; + while (i >= 0) + { + is_loop_begin = (m_memory[MEMORY_MUSIC + 4 * i] & (1 << 7)); + if (is_loop_begin || i == 0) + break; + i--; + } + m_music_state.pattern = i; + } + for (int i = 0; i < CHANNEL_COUNT; i++) + { + uint8_t channel_data = m_memory[MEMORY_MUSIC + 4 * m_music_state.pattern + i]; + bool enabled = (channel_data & (1 << 6)) == 0; + if (enabled) + { + m_channels[i].sound_mode = SOUNDMODE_MUSIC; + m_channels[i].sound_index = channel_data & 0x7F; + m_channels[i].sample = 0; + m_channels[i].position = 0; + m_channels[i].end = 31; + } + else + m_channels[i].sound_mode = SOUNDMODE_NONE; + } + } + } + else if (channel->sound_mode == SOUNDMODE_SOUND) + { + if (channel->sample >= channel->end) + channel->sound_mode = SOUNDMODE_NONE; + } +} + +void update_sound_queue() +{ + pthread_mutex_lock(&m_sound_queue_mutex); + + soundcommand_t sound_command; + + while (queue_get_front(&m_sound_queue, &sound_command)) + { + if (sound_command.sound_mode == SOUNDMODE_SOUND) + { + sound_t *sound = &sound_command.sound; + + if (sound->index == -1) + { + if (sound->channel >= 0 && sound->channel <= CHANNEL_COUNT) + m_channels[sound->channel].sound_mode = SOUNDMODE_NONE; + continue; + } + else if (sound->index == -2) + continue; + else if (sound->channel == -2) + { + for (int i = 0; i < CHANNEL_COUNT; i++) + { + soundstate_t *channel = &m_channels[i]; + + if (channel->sound_index == sound->index) + channel->sound_mode = SOUNDMODE_NONE; + } + continue; + } + else if (sound->channel == -1) + { + for (int i = 0; i < CHANNEL_COUNT; i++) + { + if (m_channels[i].sound_mode == SOUNDMODE_NONE) + { + sound->channel = i; + break; + } + } + } + if (sound->channel >= 0 && sound->channel < CHANNEL_COUNT && sound->index >= 0 && sound->index <= SOUND_COUNT) + { + soundstate_t *channel = &m_channels[sound->channel]; + uint8_t speed = m_memory[MEMORY_SFX + 68 * sound->index + 64 + 1]; + int sample_per_tick = (SAMPLE_RATE / 128) * (speed + 1); + channel->sound_mode = SOUNDMODE_SOUND; + channel->sound_index = sound->index; + channel->end = sound->end; + channel->sample = sound->start; + channel->position = sound->start * sample_per_tick; + } + } + else if (sound_command.sound_mode == SOUNDMODE_MUSIC) + { + music_t *music = &sound_command.music; + + if (music->index == -1) + { + for (int i = 0; i < CHANNEL_COUNT; i++) + m_channels[i].sound_mode = SOUNDMODE_NONE; + } + else + { + m_music_state.pattern = music->index; + m_music_state.channel_mask = music->mask; + for (int i = 0; i < CHANNEL_COUNT; i++) + { + uint8_t channel_data = m_memory[MEMORY_MUSIC + 4 * m_music_state.pattern + i]; + bool enabled = (channel_data & (1 << 6)) == 0; + if (enabled) + { + m_channels[i].sound_mode = SOUNDMODE_MUSIC; + m_channels[i].sound_index = channel_data & 0x7F; + m_channels[i].sample = 0; + m_channels[i].position = 0; + m_channels[i].end = 31; + } + else + { + m_channels[i].sound_mode = SOUNDMODE_NONE; + } + } + } + } + } + + pthread_mutex_unlock(&m_sound_queue_mutex); +} + +float get_frequency(int pitch) +{ + return m_tone_frequencies[pitch % 12] / 2 * (1 << (pitch / 12)); +} + +void render_sound(int waveform, int pitch, int volume, int position, int offset, int length, int16_t *buffer) +{ + int16_t amplitude = (int16_t)((MAX_VOLUME / 8) * volume); + unsigned int frequency = (unsigned int)get_frequency(pitch); + switch (waveform) + { + case WAVEFORM_TRIANGLE: + dsp_triangle_wave(frequency, amplitude, 0, position, offset, length, buffer); + break; + case WAVEFORM_TILTEDSAW: + dsp_tilted_sawtooth_wave(frequency, amplitude, 0, 0.85f, position, offset, length, buffer); + break; + case WAVEFORM_SAW: + dsp_sawtooth_wave(frequency, amplitude, 0, position, offset, length, buffer); + break; + case WAVEFORM_SQUARE: + dsp_square_wave(frequency, amplitude, 0, position, offset, length, buffer); + break; + case WAVEFORM_PULSE: + dsp_pulse_wave(frequency, amplitude, 0, 1.0f / 3.0f, position, offset, length, buffer); + break; + case WAVEFORM_ORGAN: + dsp_organ_wave(frequency, amplitude, 0, 0.5f, position, offset, length, buffer); + break; + case WAVEFORM_NOISE: + dsp_noise(frequency, amplitude, position, offset, length, buffer); + break; + case WAVEFORM_PHASER: + break; + } +} + +void render_sounds(int16_t *buffer, int total_samples) +{ + update_sound_queue(); + + memset(buffer, 0, sizeof(int16_t) * total_samples); + + // 0x5f2f == 1: audio engine is paused + if (m_memory[MEMORY_AUDIO_PAUSE] == 1) + return; + + for (int i = 0; i < CHANNEL_COUNT; i++) + { + soundstate_t *channel = &m_channels[i]; + + if ((channel->sound_mode == SOUNDMODE_MUSIC && m_music_enabled) || (channel->sound_mode == SOUNDMODE_SOUND && m_sound_enabled)) + { + // uint8_t editor_mode = m_memory[MEMORY_SFX + 68 * channel->sound_index + 64]; + uint8_t speed = m_memory[MEMORY_SFX + 68 * channel->sound_index + 64 + 1]; + // uint8_t loop_start = m_memory[MEMORY_SFX + 68 * channel->sound_index + 64 + 2]; + // uint8_t loop_end = m_memory[MEMORY_SFX + 68 * channel->sound_index + 64 + 3]; + int sample_per_tick = (SAMPLE_RATE / 128) * (speed + 1); + int index = 0; + + while (index < total_samples) + { + uint8_t data_lo = m_memory[MEMORY_SFX + 68 * channel->sound_index + channel->sample * 2]; + uint8_t data_hi = m_memory[MEMORY_SFX + 68 * channel->sound_index + channel->sample * 2 + 1]; + uint16_t data = (uint16_t)((data_hi << 8) | data_lo); + // bool use_sfx = data & 0x8000; + uint8_t effect = (data & EFFECT_MASK) >> EFFECT_SHIFT; + uint8_t volume = (data & VOLUME_MASK) >> VOLUME_SHIFT; + uint8_t waveform = (data & WAVEFORM_MASK) >> WAVEFORM_SHIFT; + uint8_t pitch = data & PITCH_MASK; + + int length = MIN(total_samples - index, sample_per_tick - (channel->position % sample_per_tick)); + + /* Apply effect: compute modified pitch and volume */ + int eff_pitch = pitch; + int eff_volume = volume; + if (effect != EFFECT_NONE) + { + float t = (float)(channel->position % sample_per_tick) / (float)sample_per_tick; + switch (effect) + { + case EFFECT_SLIDE: + { + int prev_pitch = pitch; + if (channel->sample > 0) + { + uint8_t plo = m_memory[MEMORY_SFX + 68 * channel->sound_index + (channel->sample - 1) * 2]; + uint8_t phi = m_memory[MEMORY_SFX + 68 * channel->sound_index + (channel->sample - 1) * 2 + 1]; + prev_pitch = ((uint16_t)((phi << 8) | plo)) & PITCH_MASK; + } + eff_pitch = (int)(prev_pitch + (pitch - prev_pitch) * t); + } + break; + case EFFECT_VIBRATO: + eff_pitch = pitch + (int)(sinf(t * 2.0f * PI) * 1.0f); + break; + case EFFECT_DROP: + eff_pitch = (int)(pitch * (1.0f - t)); + break; + case EFFECT_FADEIN: + eff_volume = (int)(volume * t); + break; + case EFFECT_FADEOUT: + eff_volume = (int)(volume * (1.0f - t)); + break; + case EFFECT_ARPEGGIOFAST: + { + int phase = (int)(t * 4.0f) % 3; + if (phase == 1) eff_pitch = pitch + 4; + else if (phase == 2) eff_pitch = pitch + 7; + } + break; + case EFFECT_ARPEGGIOSLOW: + { + int phase = (int)(t * 2.0f) % 3; + if (phase == 1) eff_pitch = pitch + 4; + else if (phase == 2) eff_pitch = pitch + 7; + } + break; + } + if (eff_pitch < 0) eff_pitch = 0; + if (eff_pitch > 63) eff_pitch = 63; + if (eff_volume < 0) eff_volume = 0; + if (eff_volume > 7) eff_volume = 7; + } + + render_sound(waveform, eff_pitch, eff_volume, channel->position, index, length, buffer); + + index += length; + channel->position += length; + channel->sample = channel->position / sample_per_tick; + + update_channel(channel); + } + } + } + + const bool dampen_enabled = (m_memory[MEMORY_MISCFLAGS] & 0x20) == 0; + + for (int i = 0; i < total_samples; i++) + { + if (m_pcm_buffered > 0) + { + uint8_t pcm_sample = m_pcm_buffer[m_pcm_read_pos]; + int16_t sample16 = (int16_t)((pcm_sample - 128) * 256); + + if (dampen_enabled) + { + m_pcm_dampen = (sample16 + m_pcm_dampen * 3) / 4; + buffer[i] = (int16_t)(buffer[i] + m_pcm_dampen); + } + else + { + buffer[i] = (int16_t)(buffer[i] + sample16); + } + + m_pcm_repeat++; + if (m_pcm_repeat >= 8) + { + m_pcm_repeat = 0; + m_pcm_read_pos = (m_pcm_read_pos + 1) % PCM_BUFFER_SIZE; + m_pcm_buffered--; + } + } + else + { + m_pcm_repeat = 0; + m_pcm_dampen = 0; + } + } +} + +void audio_pcm_write(unsigned address, unsigned length) +{ +#ifdef ENABLE_AUDIO + if (address >= MEMORY_SIZE || length == 0) + return; + + if (address + length > MEMORY_SIZE) + length = MEMORY_SIZE - address; + + if (length > PCM_BUFFER_SIZE - m_pcm_buffered) + length = PCM_BUFFER_SIZE - m_pcm_buffered; + + for (uint32_t i = 0; i < length; i++) + { + m_pcm_buffer[m_pcm_write_pos] = m_memory[address + i]; + m_pcm_write_pos = (m_pcm_write_pos + 1) % PCM_BUFFER_SIZE; + m_pcm_buffered++; + } +#endif +} + +int16_t audio_pcm_buffered() +{ +#ifdef ENABLE_AUDIO + return m_pcm_buffered; +#else + return 0; +#endif +} + +int16_t audio_pcm_app_buffer() +{ +#ifdef ENABLE_AUDIO + return PCM_BUFFER_SIZE / 4; +#else + return 0; +#endif +} diff --git a/components/pico8/femto8/src/p8_audio.h b/components/pico8/femto8/src/p8_audio.h new file mode 100644 index 00000000..6b1b3a3e --- /dev/null +++ b/components/pico8/femto8/src/p8_audio.h @@ -0,0 +1,32 @@ +/* + * p8_audio.h + * + * Created on: Dec 13, 2023 + * Author: bbaker + */ + +#include + +#ifndef P8_AUDIO_H +#define P8_AUDIO_H + +#define SAMPLE_RATE 44100 +#define MAX_VOLUME 4096 +#define CHANNEL_COUNT 4 +#define SOUND_BUFFER_SIZE 2048 +#define SOUND_COUNT 64 +#define MUSIC_COUNT 64 +#define SOUND_QUEUE_SIZE 8 + +void audio_init(); +void audio_resume(); +void audio_pause(); +void audio_close(); +void audio_sound(int32_t index, int32_t channel, uint32_t start, uint32_t end); +void audio_music(int32_t index, int32_t fade_ms, int32_t mask); +int32_t audio_stat(int32_t index); +void audio_pcm_write(unsigned address, unsigned length); +int16_t audio_pcm_buffered(); +int16_t audio_pcm_app_buffer(); + +#endif \ No newline at end of file diff --git a/components/pico8/femto8/src/p8_browse.c b/components/pico8/femto8/src/p8_browse.c new file mode 100644 index 00000000..5089b270 --- /dev/null +++ b/components/pico8/femto8/src/p8_browse.c @@ -0,0 +1,322 @@ +/** + * Copyright (C) 2025 Chris January + */ + +#include +#include +#include +#if defined(__APPLE__) + #include + #include +#elif defined(__OpenBSD__) + #include +#else + #include +#endif +#include +#include +#include +#include +#include +#include + +#include "p8_browse.h" +#include "p8_dialog.h" +#include "p8_emu.h" +#include "p8_lua_helper.h" +#include "p8_options.h" +#include "p8_overlay_helper.h" +#include "p8_pause_menu.h" +#include "strtcpy.h" + +#define FALLBACK_CARTS_PATH "." + +#define INITIAL_FILENAME_MEM_SIZE 8192 +#define INITIAL_CAPACITY 100 + +static char *filename_mem = NULL; +static char *filename_mem_ptr = NULL; +static char *filename_mem_end = NULL; + +struct dir_entry { + char *file_name; + bool is_dir; +}; + +static struct dir_entry *dir_contents = NULL; +static int nitems = 0; +static int capacity = 0; +static int current_item = 0; +static void clear_dir_contents(void) { + filename_mem_ptr = filename_mem; + nitems = 0; + current_item = 0; +} +static void append_dir_entry(const char *file_name, bool is_dir) +{ + if (nitems >= capacity) { + int new_capacity; + if (capacity == 0) + new_capacity = 10; + else + new_capacity = capacity * 2; + struct dir_entry *new_contents = realloc(dir_contents, sizeof(dir_contents[0]) * new_capacity); + if (!new_contents) { + fputs("Out of memory\n", stderr); + return; + } + dir_contents = new_contents; + capacity = new_capacity; + } + struct dir_entry *dir_entry = &dir_contents[nitems]; + size_t name_len = strlen(file_name); + if (filename_mem_ptr + name_len + 1 > filename_mem_end) { + size_t old_size = filename_mem_end - filename_mem; + size_t new_size = old_size * 2; + size_t offset = filename_mem_ptr - filename_mem; + char *new_filename_mem = realloc(filename_mem, new_size); + if (!new_filename_mem) { + fputs("Out of memory\n", stderr); + return; + } + filename_mem_ptr = new_filename_mem + offset; + filename_mem_end = new_filename_mem + new_size; + filename_mem = new_filename_mem; + } + dir_entry->file_name = filename_mem_ptr; + memcpy(dir_entry->file_name, file_name, name_len + 1); + filename_mem_ptr += name_len + 1; + dir_entry->is_dir = is_dir; + nitems++; +} + +static int compare_dir_entry(const void *p1, const void *p2) +{ + struct dir_entry *dir_entry1 = (struct dir_entry *)p1; + struct dir_entry *dir_entry2 = (struct dir_entry *)p2; + if (dir_entry1->is_dir != dir_entry2->is_dir) + return (dir_entry1->is_dir ? 0 : 1) - (dir_entry2->is_dir ? 0 : 1); + else + return strcmp(dir_entry1->file_name, dir_entry2->file_name); +} +static void list_dir(const char* path) { + if (strtcpy(m_current_cart_dir, path, sizeof(m_current_cart_dir)) < 0) { + fputs("Path too long\n", stderr); + return; + } + p8_show_io_icon(true); + DIR *dir = opendir(path); + if (dir == NULL) { + fprintf(stderr, "%s: %s\n", path, strerror(errno)); + } else { + clear_dir_contents(); + char full_path[PATH_MAX]; + for (;;) { + struct dirent *dirent; + errno = 0; + dirent = readdir(dir); + if (dirent == NULL) { + if (errno != 0) + fprintf(stderr, "%s: %s\n", path, strerror(errno)); + break; + } + if (strcmp(dirent->d_name, ".") == 0) + continue; + if (p8_make_full_path(full_path, sizeof(full_path), m_current_cart_dir, dirent->d_name) != 0) { + fputs("Path too long\n", stderr); + continue; + } + bool is_dir = false; + if (full_path[0] == '\0' || + (full_path[1] == ':' && + (full_path[2] == '/' || full_path[2] == '\\') && + full_path[3] == '\0')) { + is_dir = true; + } else { + struct stat statbuf; + int res = stat(full_path, &statbuf); + if (res == 0) + is_dir = S_ISDIR(statbuf.st_mode); + else + fprintf(stderr, "%s: %s\n", full_path, strerror(errno)); + } + append_dir_entry(dirent->d_name, is_dir); + } + closedir(dir); + } + qsort(dir_contents, nitems, sizeof(dir_contents[0]), compare_dir_entry); + strtcpy(m_current_cart_dir, path, sizeof(m_current_cart_dir)); + p8_show_io_icon(false); +} + +void draw_file_name(const char *str, int x, int y, int col) +{ + int cursor_x = x; + for (const char *c = str; *c != '\0'; c++) { + char display_char; + if (*c >= 'a' && *c <= 'z') { + display_char = *c - ('a' - 'A'); + } else if (*c >= 'A' && *c <= 'Z') { + display_char = *c + ('a' - 'A'); + } else if (*c >= 0x20 && *c <= 0x7F) { + display_char = *c; + } else { + display_char = '?'; + } + overlay_draw_char(display_char, cursor_x, y, col); + cursor_x += GLYPH_WIDTH; + } +} + +static void render_file_item(const p8_dialog_t *dialog, void *user_data, int index, bool selected, int x, int y, int width, int height, int fg_color, int bg_color) +{ + (void)dialog; + (void)user_data; + struct dir_entry *dir_entry = &dir_contents[index]; + + if (selected) + overlay_draw_rectfill(x, y - 1, x + width - 1, y + height - 1, bg_color); + + // // Clip to avoid drawing filename over "

" suffix + int clip_x, clip_y, clip_w, clip_h; + overlay_clip_get(&clip_x, &clip_y, &clip_w, &clip_h); + if (dir_entry->is_dir) + overlay_clip_set(x, y, width - GLYPH_WIDTH * 6, height); + else + overlay_clip_set(x, y, width, height); + + // Draw filename with case conversion + draw_file_name(dir_entry->file_name, x, y, fg_color); + + overlay_clip_set(clip_x, clip_y, clip_w, clip_h); + + // Draw " " suffix for directories + if (dir_entry->is_dir) + overlay_draw_simple_text(" ", x + width - GLYPH_WIDTH * 6, y, fg_color); +} + +static int show_menu(void) +{ + p8_dialog_control_t controls[] = { + DIALOG_MENUITEM("show version", 1), + DIALOG_MENUITEM("controls", 2), + DIALOG_MENUITEM("back", 3) + }; + + p8_dialog_t dialog; + p8_dialog_init(&dialog, NULL, controls, sizeof(controls) / sizeof(controls[0]), 0); + p8_dialog_action_t result = p8_dialog_run(&dialog); + p8_dialog_cleanup(&dialog); + + if (result.type == DIALOG_RESULT_BUTTON) + return result.action_id; + else + return 0; +} + +int browse_for_cart(char *cart_path, size_t cart_path_size) +{ + filename_mem = (char *)malloc(INITIAL_FILENAME_MEM_SIZE); + dir_contents = (struct dir_entry *)malloc(sizeof(struct dir_entry) * INITIAL_CAPACITY); + if (!filename_mem || !dir_contents) { + free(filename_mem); + free(dir_contents); + fputs("Out of memory\n", stderr); + return -1; + } + capacity = INITIAL_CAPACITY; + filename_mem_end = filename_mem + INITIAL_FILENAME_MEM_SIZE; + clear_dir_contents(); + + p8_reset(); + + if (access(DEFAULT_CARTS_PATH, F_OK) == 0) + list_dir(DEFAULT_CARTS_PATH); + else + list_dir(FALLBACK_CARTS_PATH); + + int selected_index = 0; + + // Create dialog with custom listbox renderer + p8_dialog_control_t controls[] = { + DIALOG_LABEL_INVERTED(""), + DIALOG_LISTBOX_CUSTOM_FULLSCREEN(NULL, nitems, &selected_index, render_file_item, NULL), + DIALOG_LABEL_INVERTED("\216: select file \227: menu"), + }; + + p8_dialog_t dialog; + p8_dialog_init(&dialog, NULL, controls, sizeof(controls) / sizeof(controls[0]), P8_WIDTH); + dialog.draw_border = false; + dialog.padding = 0; + + p8_dialog_action_t result = { DIALOG_RESULT_NONE, 0 }; + p8_dialog_set_showing(&dialog, true); + + while (!p8_is_quit_requested()) { + selected_index = 0; + controls[0].label = m_current_cart_dir; + controls[1].data.listbox.item_count = nitems; + + // Main dialog loop + do { + p8_dialog_draw(&dialog); + p8_flip(); + + result = p8_dialog_update(&dialog); + + if (result.type == DIALOG_RESULT_NONE && ((m_buttonsp[0] & BUTTON_MASK_ACTION2) != 0)) { + int action_id = show_menu(); + switch (action_id) { + case 1: + p8_show_version_dialog(); + break; + case 2: + p8_show_controls_dialog(); + break; + default: + break; + } + } + } while (result.type == DIALOG_RESULT_NONE && !p8_is_quit_requested()); + + if (cart_path[0]) + break; + + if (result.type == DIALOG_RESULT_CANCELLED) + break; + + if (result.type == DIALOG_RESULT_ACCEPTED && selected_index >= 0 && selected_index < nitems) { + struct dir_entry *dir_entry = &dir_contents[selected_index]; + char full_path[PATH_MAX] = {'\0'}; + if (p8_make_full_path(full_path, sizeof(full_path), m_current_cart_dir, dir_entry->file_name) < 0) { + fputs("Path too long\n", stderr); + continue; + } + if (dir_entry->is_dir) { + list_dir(full_path); + selected_index = 0; + } else { + if (strtcpy(cart_path, full_path, cart_path_size) < 0) { + fputs("Path too long\n", stderr); + continue; + } + break; + } + } + } + + p8_dialog_set_showing(&dialog, false); + p8_dialog_cleanup(&dialog); + + overlay_clear(); + p8_flip(); + + clear_dir_contents(); + + free(filename_mem); + free(dir_contents); + filename_mem = NULL; + dir_contents = NULL; + + return 0; +} diff --git a/components/pico8/femto8/src/p8_browse.h b/components/pico8/femto8/src/p8_browse.h new file mode 100644 index 00000000..3f0e48a1 --- /dev/null +++ b/components/pico8/femto8/src/p8_browse.h @@ -0,0 +1,12 @@ +/** + * Copyright (C) 2025 Chris January + */ + +#ifndef P8_BROWSE_H +#define P8_BROWSE_H + +#include + +int browse_for_cart(char *cart_path, size_t cart_path_size); + +#endif diff --git a/components/pico8/femto8/src/p8_cstore.c b/components/pico8/femto8/src/p8_cstore.c new file mode 100644 index 00000000..631cd9e7 --- /dev/null +++ b/components/pico8/femto8/src/p8_cstore.c @@ -0,0 +1,119 @@ +#include +#include +#include +#include "p8_emu.h" +#include "p8_cstore.h" +#include "p8_symbols.h" + +static void write_sfx(FILE *f, const uint8_t *src) +{ + for (int entry = 0; entry < 64; entry++) { + const uint8_t *e = src + entry * 68; + uint8_t editor_mode = e[64]; + uint8_t speed = e[65]; + uint8_t loop_start = e[66]; + uint8_t loop_end = e[67]; + fprintf(f, "%02x%02x%02x%02x", editor_mode, speed, loop_start, loop_end); + for (int pair = 0; pair < 16; pair++) { + uint16_t note1 = (uint16_t)e[pair*4] | ((uint16_t)e[pair*4+1] << 8); + uint16_t note2 = (uint16_t)e[pair*4+2] | ((uint16_t)e[pair*4+3] << 8); + uint8_t n1_pitch = note1 & 0x3F; + uint8_t n1_waveform = ((note1 >> 6) & 0x7) + ((note1 & 0x8000) ? 8 : 0); + uint8_t n1_volume = (note1 >> 9) & 0x7; + uint8_t n1_effect = (note1 >> 12) & 0x7; + uint8_t n2_pitch = note2 & 0x3F; + uint8_t n2_waveform = ((note2 >> 6) & 0x7) + ((note2 & 0x8000) ? 8 : 0); + uint8_t n2_volume = (note2 >> 9) & 0x7; + uint8_t n2_effect = (note2 >> 12) & 0x7; + uint8_t byte_a = n1_pitch; + uint8_t byte_b = (n1_waveform << 4) | n1_volume; + uint8_t byte_c = (n1_effect << 4) | (n2_pitch >> 4); + uint8_t byte_d = ((n2_pitch & 0xF) << 4) | n2_waveform; + uint8_t byte_e = (n2_volume << 4) | n2_effect; + fprintf(f, "%02x%02x%02x%02x%02x", byte_a, byte_b, byte_c, byte_d, byte_e); + } + fprintf(f, "\n"); + } +} + +static void write_music(FILE *f, const uint8_t *src) +{ + for (int i = 0; i < 64; i++) { + uint8_t b0 = src[i*4]; + uint8_t b1 = src[i*4+1]; + uint8_t b2 = src[i*4+2]; + uint8_t b3 = src[i*4+3]; + uint8_t flags = ((b0 >> 7) & 1) | (((b1 >> 7) & 1) << 1) + | (((b2 >> 7) & 1) << 2) | (((b3 >> 7) & 1) << 3); + fprintf(f, "%02x %02x%02x%02x%02x\n", + flags, b0 & 0x7F, b1 & 0x7F, b2 & 0x7F, b3 & 0x7F); + } +} + +int write_cart_p8(const char *path, const char *lua_script, const uint8_t *memory) +{ + FILE *f = fopen(path, "w"); + if (!f) return -1; + + fprintf(f, "pico-8 cartridge // http://www.pico-8.com\nversion 43\n__lua__\n"); + if (lua_script && *lua_script) { + const char *p = lua_script; + for (; *p; p++) { + uint8_t c = *p; + if (c < 32 || c >= 127) { + bool found = false; + for (int i=0; i + +int write_cart_p8(const char *path, const char *lua_script, const uint8_t *memory); + +#endif diff --git a/components/pico8/femto8/src/p8_dialog.c b/components/pico8/femto8/src/p8_dialog.c new file mode 100644 index 00000000..f07a8901 --- /dev/null +++ b/components/pico8/femto8/src/p8_dialog.c @@ -0,0 +1,773 @@ +/** + * Copyright (C) 2026 Chris January + * + * Dialog API for femto8 + */ + +#include "p8_dialog.h" +#include "p8_emu.h" +#include "p8_input.h" +#include "p8_overlay_helper.h" +#include +#include + +/* Control Dimensions */ +#define CONTROL_PADDING_X 3 // Horizontal padding inside dialog +#define CONTROL_PADDING_Y 4 // Vertical padding at top/bottom +#define SEPARATOR_HEIGHT 2 +#define SPACING_HEIGHT 2 + +#define MAX_DIALOG_NESTING 4 // Maximum depth of nested dialogs + +/* Global Dialog State */ +static int m_dialog_nest_count = 0; +static p8_dialog_t *m_dialog_stack[MAX_DIALOG_NESTING]; +bool m_dialog_showing = false; + +/* Helper function to get control height */ +static int get_control_height(const p8_dialog_control_t *control) +{ + switch (control->type) { + case DIALOG_SPACING: + return SPACING_HEIGHT; + case DIALOG_BUTTON: + case DIALOG_BUTTONBAR: + case DIALOG_CHECKBOX: + return GLYPH_HEIGHT + 2; + case DIALOG_INPUTBOX: + return GLYPH_HEIGHT + 4; + case DIALOG_LISTBOX: { + int visible_lines = control->data.listbox.visible_lines; + if (visible_lines == 0) { + if (!control->data.listbox.draw_border) + return P8_HEIGHT - GLYPH_HEIGHT * 2; // Max height without border + + // Auto-size based on item count (max 8 lines) + visible_lines = control->data.listbox.item_count; + if (visible_lines > 8) + visible_lines = 8; + } + return visible_lines * GLYPH_HEIGHT + (control->data.listbox.draw_border ? 2 : 0); + } + case DIALOG_CUSTOM: + return control->data.custom.height; + default: + return GLYPH_HEIGHT; + } +} + +/* Helper function to check if dialog is in quick mode */ +static bool is_quick_dialog_mode(const p8_dialog_t *dialog) +{ + int selectable_count = 0; + int listbox_or_inputbox_count = 0; + int buttonbar_count = 0; + + for (int i = 0; i < dialog->control_count; i++) { + if (dialog->controls[i].selectable) { + selectable_count++; + if (dialog->controls[i].type == DIALOG_LISTBOX || + dialog->controls[i].type == DIALOG_INPUTBOX) + listbox_or_inputbox_count++; + if (dialog->controls[i].type == DIALOG_BUTTONBAR) + buttonbar_count++; + } + } + + if (selectable_count == buttonbar_count + listbox_or_inputbox_count && + buttonbar_count == 1 && listbox_or_inputbox_count <= 1) + return true; + + return false; +} + +/* Initialize dialog structure */ +void p8_dialog_init(p8_dialog_t *dialog, + const char *title, + p8_dialog_control_t *controls, + int count, + int width) +{ + memset(dialog, 0, sizeof(p8_dialog_t)); + + dialog->title = title; + dialog->controls = controls; + dialog->control_count = count; + dialog->width = width; + dialog->padding = 1; + dialog->draw_border = true; + + // Auto-size width if needed + if (dialog->width == 0) { + int max_width = 64; + + // Consider title + if (title) { + int title_width = overlay_get_text_width(title) + 2; + if (title_width > max_width) + max_width = title_width; + } + + // Consider all control labels + for (int i = 0; i < count; i++) { + if (controls[i].label) { + int label_width = overlay_get_text_width(controls[i].label) + 2; + if (label_width > max_width) + max_width = label_width; + } + if (controls[i].type == DIALOG_CUSTOM && controls[i].data.custom.width > 0) { + if (controls[i].data.custom.width > max_width) + max_width = controls[i].data.custom.width; + } + } + + // Add some margin for borders + max_width += CONTROL_PADDING_X * 2; + + if (max_width < 64) + max_width = 64; + if (max_width > P8_WIDTH - 20) + max_width = P8_WIDTH - 20; + + dialog->width = max_width; + } + + // Calculate height + int height = 0; + + if (dialog->draw_border) { + height += 2 * CONTROL_PADDING_Y; // Top and bottom padding + } + + if (title) { + height += GLYPH_HEIGHT + SEPARATOR_HEIGHT + CONTROL_PADDING_Y; // Title + separator + } + + for (int i = 0; i < count; i++) { + height += get_control_height(&controls[i]); + if (i < count - 1 && dialog->padding > 0) { + height += dialog->padding; + } + } + + dialog->height = height; + if (dialog->height > P8_HEIGHT) dialog->height = P8_HEIGHT; + + // Center dialog + dialog->x = (P8_WIDTH - dialog->width) / 2; + dialog->y = (P8_HEIGHT - dialog->height) / 2; + + // Find first selectable control + dialog->focused_control = -1; + for (int i = 0; i < count; i++) { + if (controls[i].selectable) { + dialog->focused_control = i; + break; + } + } + + dialog->focused_subcontrol = 0; + dialog->cursor_blink = 0; +} + +/* Draw a control */ +static void draw_control(const p8_dialog_t *dialog, int control_idx, int x, int y, int width, bool focused) +{ + const p8_dialog_control_t *control = &dialog->controls[control_idx]; + + int bg_color = control->inverted ? DIALOG_BG_INVERTED : DIALOG_BG_NORMAL; + int fg_color = control->inverted ? DIALOG_TEXT_INVERTED : DIALOG_TEXT_NORMAL; + + if (focused && !control->inverted) { + bg_color = DIALOG_BG_HIGHLIGHT; + fg_color = DIALOG_TEXT_HIGHLIGHT; + } + + switch (control->type) { + case DIALOG_LABEL: { + // Fill background for inverted labels + if (control->inverted) + overlay_draw_rectfill(x, y, x + width - 1, y + GLYPH_HEIGHT - 1, bg_color); + if (control->label) + overlay_draw_simple_text(control->label, x + 1, y, fg_color); + break; + } + + case DIALOG_BUTTON: { + int button_width = control->label ? overlay_get_text_width(control->label) + 2 : 20; + if (focused) + overlay_draw_rectfill(x, y, x + button_width - 1, y + GLYPH_HEIGHT + 1, bg_color); + overlay_draw_simple_text(control->label, x + 1, y + 2, fg_color); + break; + } + + case DIALOG_MENUITEM: { + if (focused) + overlay_draw_rectfill(x, y, x + width - 1, y + GLYPH_HEIGHT, bg_color); + overlay_draw_simple_text(control->label, x + 1, y + 1, fg_color); + break; + } + + case DIALOG_CHECKBOX: { + if (focused) + overlay_draw_rectfill(x, y, x + width - 1, y + GLYPH_HEIGHT + 1, bg_color); + + // Draw checkbox box + int box_x = x + 1; + int box_y = y + 1; + overlay_draw_rect(box_x, box_y, box_x + 5, box_y + 5, fg_color); + + // Draw square if checked + if (control->data.checkbox.value && *control->data.checkbox.value) + overlay_draw_rectfill(box_x + 2, box_y + 2, box_x + 3, box_y + 3, fg_color); + + // Draw label + if (control->label) + overlay_draw_simple_text(control->label, box_x + 8, y + 2, fg_color); + break; + } + + case DIALOG_INPUTBOX: { + // Draw border + int border_color = focused ? DIALOG_BG_HIGHLIGHT : DIALOG_TEXT_NORMAL; + overlay_draw_rect(x + 1, y, x + width - 2, y + GLYPH_HEIGHT + 3, border_color); + + // Draw background + overlay_draw_rectfill(x + 2, y + 1, x + width - 3, y + GLYPH_HEIGHT + 2, DIALOG_BG_NORMAL); + + // Draw text + if (control->data.inputbox.buffer) { + overlay_draw_simple_text(control->data.inputbox.buffer, x + 3, y + 3, DIALOG_TEXT_NORMAL); + + // Draw cursor if in input mode + if (focused && (dialog->cursor_blink & 8)) { + int cursor_x = x + 3 + overlay_get_text_width(control->data.inputbox.buffer); + overlay_draw_vline(cursor_x, y + 3, y + GLYPH_HEIGHT + 1, DIALOG_TEXT_NORMAL); + } + } + break; + } + + case DIALOG_SPACING: { + // Just empty space - no rendering needed + break; + } + + case DIALOG_BUTTONBAR: { + bool quick_mode = is_quick_dialog_mode(dialog); + const char *left_text = NULL; + const char *right_text = NULL; + bool show_shortcuts = quick_mode; + + switch (control->data.buttonbar.type) { + case BUTTONBAR_OK_ONLY: + left_text = show_shortcuts ? "\x8e ok" : "ok"; + break; + case BUTTONBAR_OK_CANCEL: + left_text = show_shortcuts ? "\x8e ok" : "ok"; + right_text = show_shortcuts ? "\x97 cancel" : "cancel"; + break; + case BUTTONBAR_YES_NO: + left_text = show_shortcuts ? "\x8e yes" : "yes"; + right_text = show_shortcuts ? "\x97 no" : "no"; + break; + case BUTTONBAR_CANCEL_ONLY: + left_text = show_shortcuts ? "\x97 cancel" : "cancel"; + break; + } + + if (!quick_mode && focused) { + // Highlight the focused button + if (dialog->focused_subcontrol == 0 && left_text) { + int text_width = overlay_get_text_width(left_text); + overlay_draw_rectfill(x, y, x + text_width + 1, y + GLYPH_HEIGHT + 1, DIALOG_BG_HIGHLIGHT); + } else if (dialog->focused_subcontrol == 1 && right_text) { + int left_width = left_text ? overlay_get_text_width(left_text) + 4 : 0; + int text_width = overlay_get_text_width(right_text); + overlay_draw_rectfill(x + left_width, y, x + left_width + text_width + 1, + y + GLYPH_HEIGHT + 1, DIALOG_BG_HIGHLIGHT); + } + } + + int text_x = x + 1; + if (left_text) { + int text_color = (!quick_mode && focused && dialog->focused_subcontrol == 0) ? + DIALOG_TEXT_HIGHLIGHT : DIALOG_TEXT_NORMAL; + overlay_draw_simple_text(left_text, text_x, y + 2, text_color); + text_x += overlay_get_text_width(left_text) + 4; + } + + if (right_text) { + int text_color = (!quick_mode && focused && dialog->focused_subcontrol == 1) ? + DIALOG_TEXT_HIGHLIGHT : DIALOG_TEXT_NORMAL; + overlay_draw_simple_text(right_text, text_x, y + 2, text_color); + } + break; + } + + case DIALOG_LISTBOX: { + int list_height = get_control_height(control); + + // Draw border and background + if (control->data.listbox.draw_border) { + overlay_draw_rect(x + 1, y, x + width - 2, y + list_height - 1, DIALOG_TEXT_NORMAL); + overlay_draw_rectfill(x + 2, y + 1, x + width - 4, y + list_height - 2, DIALOG_BG_NORMAL); + } else { + overlay_draw_rectfill(x, y, x + width - 1, y + list_height - 1, DIALOG_BG_NORMAL); + } + + // Draw items + int selected_idx = control->data.listbox.selected_index ? *control->data.listbox.selected_index : 0; + int scroll_offset = control->data.listbox.scroll_offset; + int item_offset_x = control->data.listbox.draw_border ? 2 : 0; + int item_offset_y = control->data.listbox.draw_border ? 1 : 0; + int content_height = list_height - item_offset_y * 2; + + // Adjust scroll to keep selected item visible + if (selected_idx * (GLYPH_HEIGHT + 1) < scroll_offset) + scroll_offset = selected_idx * (GLYPH_HEIGHT + 1); + else if ((selected_idx + 1) * (GLYPH_HEIGHT + 1) >= scroll_offset + list_height - item_offset_y - 1) + scroll_offset = (selected_idx + 1) * (GLYPH_HEIGHT + 1) - content_height; + + // Clamp scroll + if (scroll_offset > (control->data.listbox.item_count * (GLYPH_HEIGHT + 1)) - content_height) + scroll_offset = (control->data.listbox.item_count * (GLYPH_HEIGHT + 1)) - content_height; + if (scroll_offset < 0) + scroll_offset = 0; + + // Update scroll offset (casting away const - this is internal state) + ((p8_dialog_control_t *)control)->data.listbox.scroll_offset = scroll_offset; + + int text_offset = control->data.listbox.draw_border ? 3 : 1; + int first_visible_line = scroll_offset / (GLYPH_HEIGHT + 1); + int last_visible_lne = (scroll_offset + list_height + GLYPH_HEIGHT - 2) / (GLYPH_HEIGHT + 1); + + overlay_clip_set(x + item_offset_x, y + item_offset_y, width - item_offset_x * 2, list_height - item_offset_y * 2); + + for (int i = first_visible_line; i < last_visible_lne && i < control->data.listbox.item_count; i++) { + int item_y = y + item_offset_y + 1 + i * (GLYPH_HEIGHT + 1) - scroll_offset; + bool is_selected = (i == selected_idx); + + // Determine colors based on selection and focus state + int item_bg_color, item_fg_color; + if (is_selected) { + if (focused) { + // Focused listbox with selected item: yellow background + item_bg_color = DIALOG_BG_HIGHLIGHT; + item_fg_color = DIALOG_TEXT_HIGHLIGHT; + } else { + // Unfocused listbox with selected item: white background (inverted label style) + item_bg_color = DIALOG_BG_INVERTED; + item_fg_color = DIALOG_TEXT_INVERTED; + } + } else { + // Unselected item: normal colors + item_bg_color = DIALOG_BG_NORMAL; + item_fg_color = DIALOG_TEXT_NORMAL; + } + + if (control->data.listbox.render_callback) { + // Use custom rendering callback + int item_x = x + item_offset_x; + int item_w = width - item_offset_x * 2; + control->data.listbox.render_callback( + dialog, + control->data.listbox.user_data, + i, + is_selected, + item_x, + item_y, + item_w, + GLYPH_HEIGHT, + item_fg_color, + item_bg_color + ); + } else { + // Default rendering for string items + if (is_selected) { + int hl_x0 = x + item_offset_x; + int hl_x1 = x + width - item_offset_x - 1; + overlay_draw_rectfill(hl_x0, item_y - 1, hl_x1, item_y + GLYPH_HEIGHT - 1, item_bg_color); + } + + const char *item_text = control->data.listbox.items[i]; + overlay_draw_simple_text(item_text, x + text_offset, item_y, item_fg_color); + } + } + + overlay_clip_reset(); + break; + } + + case DIALOG_CUSTOM: { + if (control->data.custom.draw_fn) + control->data.custom.draw_fn(dialog, control->data.custom.user_data, x, y, width, get_control_height(control)); + break; + } + } +} + +/* Draw the dialog */ +void p8_dialog_draw(const p8_dialog_t *dialog) +{ + int x = dialog->x; + int y = dialog->y; + int width = dialog->width; + int height = dialog->height; + + // Draw border if enabled + if (dialog->draw_border) { + overlay_draw_rect(x, y, x + width - 1, y + height - 1, DIALOG_BORDER_OUTER); + overlay_draw_rect(x + 1, y + 1, x + width - 2, y + height - 2, DIALOG_BORDER_INNER); + } + + // Draw background + int bg_x0 = dialog->draw_border ? x + 2 : x; + int bg_y0 = dialog->draw_border ? y + 2 : y; + int bg_x1 = dialog->draw_border ? x + width - 3 : x + width - 1; + int bg_y1 = dialog->draw_border ? y + height - 3 : y + height - 1; + overlay_draw_rectfill(bg_x0, bg_y0, bg_x1, bg_y1, DIALOG_BG_NORMAL); + + int content_y = dialog->draw_border ? y + CONTROL_PADDING_Y : y; + int content_x = dialog->draw_border ? x + CONTROL_PADDING_X : x; + int content_width = dialog->draw_border ? width - CONTROL_PADDING_X * 2 : width; + + // Draw title if present + if (dialog->title) { + overlay_draw_simple_text(dialog->title, content_x + 1, content_y, DIALOG_TEXT_NORMAL); + content_y += GLYPH_HEIGHT; + + // Draw separator line + overlay_draw_hline(content_x + 1, content_x + content_width - 2, content_y + 1, DIALOG_TEXT_NORMAL); + content_y += SEPARATOR_HEIGHT + CONTROL_PADDING_Y; + } + + // Draw controls + for (int i = 0; i < dialog->control_count; i++) { + bool focused = (i == dialog->focused_control); + draw_control(dialog, i, content_x, content_y, content_width, focused); + + content_y += get_control_height(&dialog->controls[i]); + if (i < dialog->control_count - 1 && dialog->padding > 0) { + content_y += dialog->padding; + } + } +} + +/* Draw all currently showing dialogs in the stack (for refreshing underlying dialogs). */ +void p8_dialog_draw_stack(void) +{ + for (int i = 0; i < m_dialog_nest_count; i++) + p8_dialog_draw(m_dialog_stack[i]); +} + +/* Clear the dialog overlay region */ +void p8_dialog_clear(p8_dialog_t *dialog) +{ + int x = dialog->x; + int y = dialog->y; + int width = dialog->width; + int height = dialog->height; + + overlay_draw_rectfill(x, y, x + width - 1, y + height - 1, 0); +} + +/* Helper function to move to next selectable control */ +static bool move_to_next_control(p8_dialog_t *dialog, bool quick_mode) +{ + int next = dialog->focused_control + 1; + while (next < dialog->control_count && + (!dialog->controls[next].selectable || + (quick_mode && dialog->controls[next].type == DIALOG_BUTTONBAR))) { + next++; + } + + if (next < dialog->control_count) { + dialog->focused_control = next; + dialog->focused_subcontrol = 0; + } + + return next < dialog->control_count; +} + +/* Helper function to move to previous selectable control */ +static bool move_to_prev_control(p8_dialog_t *dialog, bool quick_mode) +{ + int prev = dialog->focused_control - 1; + while (prev >= 0 && + (!dialog->controls[prev].selectable || + (quick_mode && dialog->controls[prev].type == DIALOG_BUTTONBAR))) { + prev--; + } + + if (prev >= 0) { + dialog->focused_control = prev; + dialog->focused_subcontrol = 0; + } + + return prev >= 0; +} + +/* Process dialog input and update state */ +p8_dialog_action_t p8_dialog_update(p8_dialog_t *dialog) +{ + p8_dialog_action_t result = { DIALOG_RESULT_NONE, 0 }; + + uint16_t buttons = m_buttonsp[0]; + + bool quick_mode = is_quick_dialog_mode(dialog); + + // Update cursor blink + dialog->cursor_blink++; + + if (dialog->focused_control >= 0) { + // Handle input mode (for input boxes) + if (dialog->controls[dialog->focused_control].type == DIALOG_INPUTBOX) { + p8_dialog_control_t *control = &dialog->controls[dialog->focused_control]; + + uint8_t keypress; + while (p8_get_next_keypress(NULL, &keypress, NULL)) { + // Handle Return + if (keypress == 13) { + if (!move_to_next_control(dialog, quick_mode)) { + // No more controls, accept the dialog + result.type = DIALOG_RESULT_ACCEPTED; + } + + return result; + } + // Handle printable characters + else if (keypress >= 32 && keypress <= 126) { + int len = strlen(control->data.inputbox.buffer); + if (len < control->data.inputbox.buffer_size - 1) { + control->data.inputbox.buffer[len] = keypress; + control->data.inputbox.buffer[len + 1] = '\0'; + } + return result; + } + // Handle backspace + else if (keypress == 8) { + int len = strlen(control->data.inputbox.buffer); + if (len > 0) { + control->data.inputbox.buffer[len - 1] = '\0'; + } + return result; + } + } + } else { + // Action buttons + p8_dialog_control_t *control = &dialog->controls[dialog->focused_control]; + + // Button 1 (O) / Space activates focused control + if (buttons & (BUTTON_MASK_ACTION1 | BUTTON_MASK_SPACE | BUTTON_MASK_RETURN)) { + switch (control->type) { + case DIALOG_BUTTON: + case DIALOG_MENUITEM: + result.type = DIALOG_RESULT_BUTTON; + result.action_id = control->data.button.action_id; + break; + + case DIALOG_CHECKBOX: + if (control->data.checkbox.value) { + *control->data.checkbox.value = !*control->data.checkbox.value; + } + break; + + case DIALOG_LISTBOX: + if (!move_to_next_control(dialog, quick_mode)) { + // No more controls, accept the dialog + result.type = DIALOG_RESULT_ACCEPTED; + } + break; + + case DIALOG_BUTTONBAR: + if (!quick_mode) { + // Activate the focused button + p8_dialog_control_t *buttonbar = &dialog->controls[dialog->focused_control]; + if (buttonbar->data.buttonbar.type == BUTTONBAR_CANCEL_ONLY) { + result.type = DIALOG_RESULT_CANCELLED; + } else if (dialog->focused_subcontrol == 0) { + result.type = DIALOG_RESULT_ACCEPTED; + } else { + result.type = DIALOG_RESULT_CANCELLED; + } + } + break; + + default: + break; + } + } + } + } + + // Handle Return / (Button 1 / Space in quick mode) (before checking focused control) + if ((quick_mode && (buttons & (BUTTON_MASK_RETURN | BUTTON_MASK_ACTION1 | BUTTON_MASK_SPACE)))) { + result.type = DIALOG_RESULT_ACCEPTED; + return result; + } + + // Escape / (Button 2 (X) in quick mode) cancels dialog + if ((buttons & BUTTON_MASK_ESCAPE) || (quick_mode && (buttons & BUTTON_MASK_ACTION2))) { + result.type = DIALOG_RESULT_CANCELLED; + return result; + } + + // Navigation - Up/Down for controls + if (buttons & BUTTON_MASK_UP) { + if (dialog->focused_control >= 0) { + // Special handling for listbox + p8_dialog_control_t *control = &dialog->controls[dialog->focused_control]; + if (control->type == DIALOG_LISTBOX && control->data.listbox.selected_index) { + int *sel = control->data.listbox.selected_index; + if (*sel > 0) { + (*sel)--; + } + return result; // Stay in listbox, don't change focus + } + + // Move to previous selectable control + move_to_prev_control(dialog, quick_mode); + } + } + + if (buttons & BUTTON_MASK_DOWN) { + if (dialog->focused_control >= 0) { + // Special handling for listbox + p8_dialog_control_t *control = &dialog->controls[dialog->focused_control]; + if (control->type == DIALOG_LISTBOX && control->data.listbox.selected_index) { + int *sel = control->data.listbox.selected_index; + if (*sel < control->data.listbox.item_count - 1) { + (*sel)++; + } + return result; // Stay in listbox, don't change focus + } + + // Move to next selectable control + move_to_next_control(dialog, quick_mode); + } + } + + if (buttons & (BUTTON_MASK_PAGE_UP | BUTTON_MASK_PAGE_DOWN)) { + if (dialog->focused_control >= 0) { + p8_dialog_control_t *control = &dialog->controls[dialog->focused_control]; + if (control->type == DIALOG_LISTBOX && control->data.listbox.selected_index) { + int *sel = control->data.listbox.selected_index; + // Compute page size as the number of fully-visible items based + // on the actual pixel height of the listbox. + int item_offset_y = control->data.listbox.draw_border ? 1 : 0; + int content_height = get_control_height(control) - item_offset_y * 2; + int page_size = content_height / (GLYPH_HEIGHT + 1); + if (page_size < 1) page_size = 1; + if (buttons & BUTTON_MASK_PAGE_UP) { + *sel -= page_size; + if (*sel < 0) *sel = 0; + } else { + *sel += page_size; + if (*sel >= control->data.listbox.item_count) + *sel = control->data.listbox.item_count - 1; + } + return result; + } + } + } + + // Left/Right for button bar sub-controls and listbox navigation + if (dialog->focused_control >= 0) { + p8_dialog_control_t *control = &dialog->controls[dialog->focused_control]; + if (control->type == DIALOG_BUTTONBAR) { + int max_subcontrol = (control->data.buttonbar.type == BUTTONBAR_OK_ONLY || + control->data.buttonbar.type == BUTTONBAR_CANCEL_ONLY) ? 0 : 1; + + if (buttons & BUTTON_MASK_LEFT) { + if (dialog->focused_subcontrol > 0) { + dialog->focused_subcontrol--; + return result; + } + } + if (buttons & BUTTON_MASK_RIGHT) { + if (dialog->focused_subcontrol < max_subcontrol) { + dialog->focused_subcontrol++; + return result; + } + } + } + } + + // MENUITEM controls capture Left/Right and return them as a button event + // rather than navigating focus, so the cart callback receives them. + if (buttons & (BUTTON_MASK_LEFT | BUTTON_MASK_RIGHT)) { + if (dialog->focused_control >= 0) { + p8_dialog_control_t *ctrl = &dialog->controls[dialog->focused_control]; + if (ctrl->type == DIALOG_MENUITEM) { + result.type = DIALOG_RESULT_BUTTON; + result.action_id = ctrl->data.button.action_id; + result.button_mask = buttons & (BUTTON_MASK_LEFT | BUTTON_MASK_RIGHT); + return result; + } + } + } + + // LEFT/RIGHT navigate to previous/next control + if (buttons & BUTTON_MASK_LEFT) { + move_to_prev_control(dialog, quick_mode); + } + if (buttons & BUTTON_MASK_RIGHT) { + move_to_next_control(dialog, quick_mode); + } + + return result; +} + +/* Run modal dialog loop */ +p8_dialog_action_t p8_dialog_run(p8_dialog_t *dialog) +{ + p8_dialog_action_t result = { DIALOG_RESULT_NONE, 0 }; + + p8_dialog_set_showing(dialog, true); + + // Main dialog loop + do { + p8_dialog_draw(dialog); + p8_flip(); // p8_flip calls p8_update_input internally + + result = p8_dialog_update(dialog); + } while (result.type == DIALOG_RESULT_NONE && !p8_is_quit_requested()); + + p8_dialog_set_showing(dialog, false); + + while (p8_get_next_keypress(NULL, NULL, NULL)) { + // Clear any remaining keypresses to avoid them affecting the next dialog + } + + return result; +} + +/* Clean up dialog resources */ +void p8_dialog_cleanup(p8_dialog_t *dialog) +{ + if (m_dialog_nest_count > 0 && m_dialog_stack[m_dialog_nest_count - 1] == dialog) + p8_dialog_set_showing(dialog, false); +} + +/* Set the dialog showing state */ +void p8_dialog_set_showing(p8_dialog_t *dialog, bool showing) +{ + (void)dialog; + if (!showing) { + if (m_dialog_nest_count > 0) { + assert(m_dialog_stack[m_dialog_nest_count - 1] == dialog); + m_dialog_nest_count--; + m_dialog_stack[m_dialog_nest_count] = NULL; + } + // Draw the dialogs underneath the closed one to refresh the screen + p8_dialog_clear(dialog); + p8_dialog_draw_stack(); + p8_flip(); + } else if (showing) { + assert(m_dialog_nest_count < MAX_DIALOG_NESTING); + m_dialog_stack[m_dialog_nest_count] = dialog; + m_dialog_nest_count++; + } + m_dialog_showing = m_dialog_nest_count > 0; +} diff --git a/components/pico8/femto8/src/p8_dialog.h b/components/pico8/femto8/src/p8_dialog.h new file mode 100644 index 00000000..867f3939 --- /dev/null +++ b/components/pico8/femto8/src/p8_dialog.h @@ -0,0 +1,392 @@ +/** + * Copyright (C) 2026 Chris January + * + * Dialog API for femto8 + */ + +#ifndef P8_DIALOG_H +#define P8_DIALOG_H + +#include +#include + +/* Forward declaration for dialog type used in callbacks */ +typedef struct p8_dialog p8_dialog_t; + +/* Dialog Control Types */ +typedef enum { + DIALOG_LABEL, // Read-only text label + DIALOG_BUTTON, // Selectable button (highlighted when focused) + DIALOG_MENUITEM, // Menu item button (full width) + DIALOG_CHECKBOX, // Toggle checkbox with label + DIALOG_INPUTBOX, // Single-line text input field + DIALOG_SPACING, // Visual separator (non-interactive) + DIALOG_BUTTONBAR, // Horizontal Ok/Cancel button bar (conditionally selectable, acts on O/X) + DIALOG_LISTBOX, // Scrollable list box with selection (selectable) + DIALOG_CUSTOM // Custom-drawn region with user-supplied draw function +} p8_dialog_control_type_t; + +/* Button Bar Types */ +typedef enum { + BUTTONBAR_OK_ONLY, // Single Ok button + BUTTONBAR_OK_CANCEL, // Ok and Cancel buttons + BUTTONBAR_YES_NO, // Yes and No buttons + BUTTONBAR_CANCEL_ONLY // Single Cancel button +} p8_dialog_buttonbar_type_t; + +/* Dialog Control Structure */ +typedef struct { + p8_dialog_control_type_t type; + const char *label; // Display text (all control types) + + // Type-specific data (union) + union { + struct { + bool *value; // Pointer to checkbox state (CHECKBOX) + } checkbox; + + struct { + char *buffer; // Text buffer (INPUTBOX) + int buffer_size; // Maximum buffer size + int cursor_pos; // Current cursor position + } inputbox; + + struct { + int action_id; // Button action identifier (BUTTON) + } button; + + struct { + p8_dialog_buttonbar_type_t type; // Button bar variant (BUTTONBAR) + } buttonbar; + + struct { + int width; // Minimum content width required (0 = no constraint) + int height; // Control height in pixels + void (*draw_fn)(const p8_dialog_t *dialog, void *user_data, int x, int y, int width, int height); // Draw function + void *user_data; // User data pointer passed to draw function + } custom; + + struct { + union { + const char **items; // Array of item strings (standard listbox) + void *user_data; // Custom user data (when using render callback) + }; + int item_count; // Number of items in list + int *selected_index; // Pointer to selected item index + int visible_lines; // Number of visible lines (0 = auto) + int scroll_offset; // Current scroll position (internal) + bool draw_border; // Whether to draw border around listbox + void (*render_callback)(const p8_dialog_t *dialog, void *user_data, int index, bool selected, int x, int y, int width, int height, int fg_color, int bg_color); + } listbox; + } data; + + bool selectable; // Whether control can receive focus + bool enabled; // Whether control is active + bool inverted; // Use inverted colors (for headers/footers) +} p8_dialog_control_t; + +/* Dialog Structure */ +struct p8_dialog { + const char *title; // Dialog title (optional, can be NULL) + p8_dialog_control_t *controls; // Array of controls + int control_count; // Number of controls + + int focused_control; // Currently focused control index + int focused_subcontrol; // Currently focused sub-control (for button bar) + int width; // Dialog width in pixels + int height; // Dialog height in pixels (auto-calculated) + int padding; // Pixels of spacing between controls (default: 2) + bool draw_border; // Whether to draw double border (default: true) + + // Position (auto-centered if set to -1) + int x; + int y; + + // Internal state + int cursor_blink; // Cursor blink counter for input boxes + bool input_mode; // True when actively editing an inputbox +}; + +/* Dialog Result */ +typedef enum { + DIALOG_RESULT_NONE, // No action yet + DIALOG_RESULT_ACCEPTED, // Dialog accepted (Button 1 / Return) + DIALOG_RESULT_CANCELLED, // Dialog cancelled (Button 2 / Escape) + DIALOG_RESULT_BUTTON // Specific button pressed (check action_id) +} p8_dialog_result_t; + +typedef struct { + p8_dialog_result_t type; + int action_id; // For DIALOG_RESULT_BUTTON + uint16_t button_mask; // For DIALOG_RESULT_BUTTON on MENUITEM: button mask of triggering button(s) +} p8_dialog_action_t; + +/* Color Scheme */ +#define DIALOG_BORDER_OUTER 1 // Dark blue (outer border) +#define DIALOG_BORDER_INNER 7 // White (inner border) +#define DIALOG_BG_NORMAL 1 // Dark blue (dialog background) +#define DIALOG_BG_HIGHLIGHT 10 // Yellow (focused/selected control) +#define DIALOG_TEXT_NORMAL 7 // White (normal text) +#define DIALOG_TEXT_HIGHLIGHT 1 // Dark blue (text on highlighted background) +#define DIALOG_BG_INVERTED 7 // White (inverted background) +#define DIALOG_TEXT_INVERTED 1 // Dark blue (inverted text) + +/* Global Dialog State */ +extern bool m_dialog_showing; + +/* Control Initialization Macros */ + +/** + * Create a label control (non-selectable text). + */ +#define DIALOG_LABEL(text) \ + { .type = DIALOG_LABEL, .label = (text), \ + .selectable = false, .enabled = true, \ + .inverted = false } + +/** + * Create an inverted label control (white-on-dark-blue for headers/footers). + */ +#define DIALOG_LABEL_INVERTED(text) \ + { .type = DIALOG_LABEL, .label = (text), \ + .selectable = false, .enabled = true, \ + .inverted = true } + +/** + * Create a button control. + */ +#define DIALOG_BUTTON(text, id) \ + { .type = DIALOG_BUTTON, .label = (text), \ + .data.button.action_id = (id), \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/** + * Create a menu item control (full width, no vertical padding). + */ +#define DIALOG_MENUITEM(text, id) \ + { .type = DIALOG_MENUITEM, .label = (text), \ + .data.button.action_id = (id), \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/** + * Create a checkbox control. + */ +#define DIALOG_CHECKBOX(text, val_ptr) \ + { .type = DIALOG_CHECKBOX, .label = (text), \ + .data.checkbox.value = (val_ptr), \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/** + * Create an input box control. + */ +#define DIALOG_INPUTBOX(text, buf, size) \ + { .type = DIALOG_INPUTBOX, .label = (text), \ + .data.inputbox = { .buffer = (buf), \ + .buffer_size = (size), \ + .cursor_pos = 0 }, \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/** + * Create a visual separator (non-selectable). + */ +#define DIALOG_SPACING() \ + { .type = DIALOG_SPACING, .label = NULL, \ + .selectable = false, .enabled = true, \ + .inverted = false } + +/** + * Create a horizontal button bar with Ok/Cancel buttons. + * Displays as: "ok cancel" + * Uses fixed action IDs: DIALOG_ACTION_OK and DIALOG_ACTION_CANCEL. + */ +#define DIALOG_BUTTONBAR() \ + { .type = DIALOG_BUTTONBAR, .label = NULL, \ + .data.buttonbar.type = BUTTONBAR_OK_CANCEL, \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/** + * Create a button bar with only an Ok button (for message boxes). + * Use this for simple message dialogs where cancel doesn't make sense. + */ +#define DIALOG_BUTTONBAR_OK_ONLY() \ + { .type = DIALOG_BUTTONBAR, .label = NULL, \ + .data.buttonbar.type = BUTTONBAR_OK_ONLY, \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/** + * Create a horizontal button bar with Yes/No buttons. + * Uses fixed action IDs: DIALOG_ACTION_YES and DIALOG_ACTION_NO. + */ +#define DIALOG_BUTTONBAR_YES_NO() \ + { .type = DIALOG_BUTTONBAR, .label = NULL, \ + .data.buttonbar.type = BUTTONBAR_YES_NO, \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/** + * Create a button bar with only a Cancel button. + * Use this for waiting dialogs where the user can only cancel. + */ +#define DIALOG_BUTTONBAR_CANCEL_ONLY() \ + { .type = DIALOG_BUTTONBAR, .label = NULL, \ + .data.buttonbar.type = BUTTONBAR_CANCEL_ONLY, \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/** + * Create a scrollable list box. + * Use Up/Down to navigate, O/Space to select (quick dialog mode only). + * visible_lines: number of lines to display (0 for auto-sizing based on item_count) + */ +#define DIALOG_LISTBOX(title, item_array, count, sel_idx_ptr, lines) \ + { .type = DIALOG_LISTBOX, .label = (title), \ + .data.listbox = { .items = (item_array), \ + .item_count = (count), \ + .selected_index = (sel_idx_ptr), \ + .visible_lines = (lines), \ + .scroll_offset = 0, \ + .draw_border = true, \ + .render_callback = NULL }, \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/** + * Create a custom-rendered list box with a rendering callback. + * Use this when you need complete control over item rendering (e.g., file browsers with metadata). + * The callback receives: user_data, index, x, y, width, height, fg_color, bg_color + */ +#define DIALOG_LISTBOX_CUSTOM(title, usr_data, count, sel_idx_ptr, lines, callback) \ + { .type = DIALOG_LISTBOX, .label = (title), \ + .data.listbox = { .user_data = (usr_data), \ + .item_count = (count), \ + .selected_index = (sel_idx_ptr), \ + .visible_lines = (lines), \ + .scroll_offset = 0, \ + .draw_border = true, \ + .render_callback = (callback) }, \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/** + * Create a scrollable list box without a border. + * Use this variant for full-screen file browsers or when integrating with custom borders. + */ +#define DIALOG_LISTBOX_FULLSCREEN(title, item_array, count, sel_idx_ptr) \ + { .type = DIALOG_LISTBOX, .label = (title), \ + .data.listbox = { .items = (item_array), \ + .item_count = (count), \ + .selected_index = (sel_idx_ptr), \ + .visible_lines = 0, \ + .scroll_offset = 0, \ + .draw_border = false, \ + .render_callback = NULL }, \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/** + * Create a custom-rendered list box with a rendering callback. + * Use this when you need complete control over item rendering (e.g., file browsers with metadata). + * The callback receives: user_data, index, x, y, width, height, fg_color, bg_color + */ +/** + * Create a custom-drawn control with a user-supplied draw function. + * The draw function receives the top-left coordinates, available width, and + * the control height as declared here. + * @param w Minimum content width needed (0 = no constraint; use for auto-sizing). + * @param h Control height in pixels. + * @param fn Draw callback: void fn(int x, int y, int width, int height) + * @param user_data User data pointer passed to draw function (can be NULL) + */ +#define DIALOG_CUSTOM_CONTROL(w, h, fn, usr_data) \ + { .type = DIALOG_CUSTOM, .label = NULL, \ + .data.custom = { .width = (w), .height = (h), .draw_fn = (fn), .user_data = (usr_data) }, \ + .selectable = false, .enabled = true, \ + .inverted = false } + +/** + * Create a custom-rendered list box with a rendering callback. + * Use this when you need complete control over item rendering (e.g., file browsers with metadata). + * The callback receives: user_data, index, x, y, width, height, fg_color, bg_color + */ +#define DIALOG_LISTBOX_CUSTOM_FULLSCREEN(title, count, sel_idx_ptr, callback, usr_data) \ + { .type = DIALOG_LISTBOX, .label = (title), \ + .data.listbox = { .user_data = (usr_data), \ + .item_count = (count), \ + .selected_index = (sel_idx_ptr), \ + .visible_lines = 0, \ + .scroll_offset = 0, \ + .draw_border = false, \ + .render_callback = (callback) }, \ + .selectable = true, .enabled = true, \ + .inverted = false } + +/* Core API Functions */ + +/** + * Initialize a dialog structure with default values. + * Sets draw_border=true and padding=2 by default. + * + * @param dialog Pointer to dialog structure to initialize + * @param title Dialog title (can be NULL) + * @param controls Array of controls to display + * @param count Number of controls in array + * @param width Dialog width (or 0 for auto-sizing) + */ +void p8_dialog_init(p8_dialog_t *dialog, + const char *title, + p8_dialog_control_t *controls, + int count, + int width); + +/** + * Draw the dialog to the overlay buffer. + * This function is stateless and can be called multiple times. + * + * @param dialog Pointer to dialog to render + */ +void p8_dialog_draw(const p8_dialog_t *dialog); + +/** + * Draw all currently showing dialogs in the stack (for refreshing underlying dialogs). + */ +void p8_dialog_draw_stack(void); + +/** + * Process input for the dialog and update its state. + * Returns action indicating what happened (if anything). + * Uses m_buttonsp and m_keypress global variables. + * + * @param dialog Pointer to dialog to update + * @return Action result + */ +p8_dialog_action_t p8_dialog_update(p8_dialog_t *dialog); + +/** + * Run a modal dialog loop until accepted or cancelled. + * Handles input, drawing, and flipping automatically. + * + * @param dialog Pointer to dialog to run + * @return Final dialog action + */ +p8_dialog_action_t p8_dialog_run(p8_dialog_t *dialog); + +/** + * Set the dialog showing state. + * + * @param dialog Pointer to dialog (unused) + * @param showing True if a dialog is being shown, false otherwise + */ +void p8_dialog_set_showing(p8_dialog_t *dialog, bool showing); + +/** + * Clean up dialog resources (if any were allocated). + */ +void p8_dialog_cleanup(p8_dialog_t *dialog); + +#endif /* P8_DIALOG_H */ diff --git a/components/pico8/femto8/src/p8_dsp.c b/components/pico8/femto8/src/p8_dsp.c new file mode 100644 index 00000000..05e93ec5 --- /dev/null +++ b/components/pico8/femto8/src/p8_dsp.c @@ -0,0 +1,134 @@ +/* + * p8_dsp.c + * + * Created on: Dec 13, 2023 + * Author: bbaker + */ + +#include +#include +#include +#include "p8_audio.h" +#include "p8_dsp.h" + +int random_range(int min, int max) +{ + return min + ((float)rand() / (float)RAND_MAX) * (max - min); +} + +void dsp_square_wave(uint32_t frequency, int16_t amplitude, int16_t offset, int position, int dest_offset, int dest_length, int16_t *dest) +{ + int period_length = (float)SAMPLE_RATE / frequency; + int half_period = period_length / 2; + for (int i = 0; i < dest_length; i++) + { + int smaple_in_period = position % period_length; + dest[dest_offset + i] += (offset + smaple_in_period < half_period ? -amplitude : amplitude); + position++; + } +} + +void dsp_pulse_wave(uint32_t frequency, int16_t amplitude, int16_t offset, float duty_cycle, int position, int dest_offset, int dest_length, int16_t *dest) +{ + int period_length = (float)SAMPLE_RATE / frequency; + int duty_on_length = duty_cycle * period_length; + for (int i = 0; i < dest_length; i++) + { + int smaple_in_period = position % period_length; + dest[dest_offset + i] += (offset + smaple_in_period < duty_on_length ? amplitude : -amplitude); + position++; + } +} + +void dsp_triangle_wave(uint32_t frequency, int16_t amplitude, int16_t offset, int position, int dest_offset, int dest_length, int16_t *dest) +{ + int period_length = (float)SAMPLE_RATE / frequency; + for (int i = 0; i < dest_length; i++) + { + int repetitions = position / period_length; + float p = position / (float)period_length - repetitions; + if (p < 0.50f) + dest[dest_offset + i] += (offset + amplitude - amplitude * 2 * (p / 0.5f)); + else + dest[dest_offset + i] += (offset - amplitude + amplitude * 2 * ((p - 0.5f) / 0.5f)); + position++; + } +} + +void dsp_sawtooth_wave(uint32_t frequency, int16_t amplitude, int16_t offset, int position, int dest_offset, int dest_length, int16_t *dest) +{ + int period_length = (float)SAMPLE_RATE / frequency; + for (int i = 0; i < dest_length; i++) + { + int repetitions = position / period_length; + float p = position / (float)period_length - repetitions; + dest[dest_offset + i] += (offset - amplitude + amplitude * 2 * p); + position++; + } +} + +void dsp_tilted_sawtooth_wave(uint32_t frequency, int16_t amplitude, int16_t offset, float duty_cycle, int position, int dest_offset, int dest_length, int16_t *dest) +{ + int period_length = (float)SAMPLE_RATE / frequency; + for (int i = 0; i < dest_length; i++) + { + int repetitions = position / period_length; + float p = position / (float)period_length - repetitions; + if (p < duty_cycle) + dest[dest_offset + i] += (offset - amplitude + amplitude * 2 * (p / duty_cycle)); + else + { + float op = (p - duty_cycle) / (1.0f - duty_cycle); + dest[dest_offset + i] += (offset + amplitude - amplitude * 2 * op); + } + position++; + } +} + +void dsp_organ_wave(uint32_t frequency, int16_t amplitude, int16_t offset, float coefficient, int position, int dest_offset, int dest_length, int16_t *dest) +{ + int period_length = (float)SAMPLE_RATE / frequency; + for (int i = 0; i < dest_length; i++) + { + int repetitions = position / period_length; + float p = position / (float)period_length - repetitions; + if (p < 0.25f) + dest[dest_offset + i] += (offset + amplitude - amplitude * 2 * (p / 0.25f)); + else if (p < 0.50f) + dest[dest_offset + i] += (offset - amplitude + amplitude * (1.0f + coefficient) * (p - 0.25f) / 0.25f); + else if (p < 0.75f) + dest[dest_offset + i] += (offset + amplitude * coefficient - amplitude * (1.0f + coefficient) * (p - 0.50f) / 0.25f); + else + dest[dest_offset + i] += (offset - amplitude + amplitude * 2 * (p - 0.75f) / 0.25f); + position++; + } +} + +void dsp_noise(uint32_t frequency, int16_t amplitude, int position, int dest_offset, int dest_length, int16_t *dest) +{ + for (int i = 0; i < dest_length; i++) + { + dest[dest_offset + i] += (int16_t)random_range(-amplitude / 2, amplitude / 2); + position++; + } +} + +void dsp_fade_in(int16_t amplitude, int dest_offset, int dest_length, int16_t *dest) +{ + float incr = 1.0f / dest_length; + for (int i = 0; i < dest_length; i++) + { + float v = dest[dest_offset + i] / (float)amplitude; + dest[dest_offset + i] = (int16_t)(v * incr * i * amplitude); + } +} + +void dsp_fade_out(int16_t amplitude, int dest_offset, int dest_length, int16_t *dest) +{ + float incr = 1.0f / dest_length; + for (int i = 0; i < dest_length; i++) + { + float v = dest[dest_offset + i] / (float)amplitude; + dest[dest_offset + i] = (int16_t)(v * incr * (dest_length - i - 1) * amplitude); + } +} diff --git a/components/pico8/femto8/src/p8_dsp.h b/components/pico8/femto8/src/p8_dsp.h new file mode 100644 index 00000000..583e037d --- /dev/null +++ b/components/pico8/femto8/src/p8_dsp.h @@ -0,0 +1,23 @@ +/* + * p8_dsp.h + * + * Created on: Dec 13, 2023 + * Author: bbaker + */ + +#ifndef P8_DSP_H +#define P8_DSP_H + +#include + +void dsp_square_wave(uint32_t frequency, int16_t amplitude, int16_t offset, int position, int dest_offset, int dest_length, int16_t *dest); +void dsp_pulse_wave(uint32_t frequency, int16_t amplitude, int16_t offset, float duty_cycle, int position, int dest_offset, int dest_length, int16_t *dest); +void dsp_triangle_wave(uint32_t frequency, int16_t amplitude, int16_t offset, int position, int dest_offset, int dest_length, int16_t *dest); +void dsp_sawtooth_wave(uint32_t frequency, int16_t amplitude, int16_t offset, int position, int dest_offset, int dest_length, int16_t *dest); +void dsp_tilted_sawtooth_wave(uint32_t frequency, int16_t amplitude, int16_t offset, float duty_cycle, int position, int dest_offset, int dest_length, int16_t *dest); +void dsp_organ_wave(uint32_t frequency, int16_t amplitude, int16_t offset, float coefficient, int position, int dest_offset, int dest_length, int16_t *dest); +void dsp_noise(uint32_t frequency, int16_t amplitude, int position, int dest_offset, int dest_length, int16_t *dest); +void dsp_fade_in(int16_t amplitude, int dest_offset, int dest_length, int16_t *dest); +void dsp_fade_out(int16_t amplitude, int dest_offset, int dest_length, int16_t *dest); + +#endif \ No newline at end of file diff --git a/components/pico8/femto8/src/p8_emu.c b/components/pico8/femto8/src/p8_emu.c new file mode 100644 index 00000000..22d45b64 --- /dev/null +++ b/components/pico8/femto8/src/p8_emu.c @@ -0,0 +1,1193 @@ +/* + * p8_emu.c + * + * Created on: Dec 13, 2023 + * Author: bbaker + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "strtcpy.h" +#if defined(FEMTO8_ESPBOX) +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/semphr.h" +#include "p8_espbox.h" +#elif defined(OS_FREERTOS) +#include +#include +#include "retro_heap.h" +#include "ble_controller.h" +#endif +#include "p8_audio.h" +#include "p8_dialog.h" +#include "p8_emu.h" +#include "p8_input.h" +#include "p8_lua.h" +#include "p8_lua_helper.h" +#include "p8_overlay_helper.h" +#include "p8_parser.h" +#include "p8_pause_menu.h" + +#ifdef SDL +#include "SDL.h" +#elif defined(__DA1470x__) +#include "gdi.h" +#endif + +#ifdef SDL +// ARGB +uint32_t m_colors[32] = { + 0x00000000, 0x001d2b53, 0x007e2553, 0x00008751, 0x00ab5236, 0x005f574f, 0x00c2c3c7, 0x00fff1e8, + 0x00ff004d, 0x00ffa300, 0x00ffec27, 0x0000e436, 0x0029adff, 0x0083769c, 0x00ff77a8, 0x00ffccaa, + 0x00291814, 0x00111D35, 0x00422136, 0x00125359, 0x00742F29, 0x0049333B, 0x00A28879, 0x00F3EF7D, + 0x00BE1250, 0x00FF6C24, 0x00A8E72E, 0x0000B54E, 0x00065AB5, 0x00754665, 0x00FF6E59, 0x00FF9D81}; +#else +// RGB565 +uint16_t m_colors[32] = { + 0x0000, 0x194a, 0x792a, 0x042a, 0xaa86, 0x5aa9, 0xc618, 0xff9d, 0xf809, 0xfd00, 0xff64, 0x0726, 0x2d7f, 0x83b3, 0xfbb5, 0xfe75, + 0x28c2, 0x10e6, 0x4106, 0x128b, 0x7165, 0x4987, 0xa44f, 0xf76f, 0xb88a, 0xfb64, 0xaf25, 0x05a9, 0x02d6, 0x722c, 0xfb6b, 0xfcf0}; +#endif + +// Convert 8-bit screen palette value to 5-bit color index. +static inline int color_index(uint8_t c) +{ + return ((c >> 3) & 0x10) | (c & 0xf); +} + +static int p8_init_lcd(void); +static int p8_main_loop(); + +uint8_t *m_memory = NULL; +uint8_t *m_cart_memory = NULL; +uint8_t *m_temp_cart_memory = NULL; +uint8_t *m_overlay_memory = NULL; +uint8_t *m_file_buffer = NULL; +uint8_t *m_decompression_buffer = NULL; +char *m_lua_script = NULL; +char *m_temp_lua_script = NULL; + +unsigned m_fps = 30; +unsigned m_actual_fps = 0; +unsigned m_frames = 0; + +p8_clock_t m_start_time; + +static jmp_buf jmpbuf_restart; +static bool restart; +static bool cart_running = false; +static bool lua_running = false; +static bool quit_requested = false; + +char m_current_cart_dir[PATH_MAX]; +char m_current_cart_file_name[PATH_MAX]; +char m_breadcrumb[256]; +char m_param_string[256]; +char m_clipboard[1024]; + +static bool skip_main_loop_if_no_callbacks = false; + +#ifdef SDL +SDL_Window *m_window = NULL; +SDL_Renderer *m_renderer = NULL; +SDL_Texture *m_texture = NULL; +SDL_Surface *m_output = NULL; +SDL_PixelFormat *m_format = NULL; +#else +SemaphoreHandle_t m_drawSemaphore; +#endif + + +static FILE *cartdata = NULL; +static bool cartdata_needs_flush = false; + +static int m_initialized = 0; + +const uint8_t io_icon[32] = { + 0x00, 0x77, 0x77, 0x77, + 0x00, 0x17, 0x11, 0x71, + 0x00, 0x17, 0x77, 0x71, + 0x00, 0x17, 0x77, 0x71, + 0x00, 0x17, 0x11, 0x71, + 0x00, 0x77, 0x77, 0x77, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, +}; + +p8_clock_t p8_clock(void) +{ +#ifdef OS_FREERTOS + return xTaskGetTickCount(); +#else + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec * UINT64_C(1000000) + ts.tv_nsec / UINT64_C(1000); +#endif +} + +unsigned p8_clock_ms(p8_clock_t clocks) +{ +#ifdef OS_FREERTOS + return clocks * portTICK_PERIOD_MS; +#else + return clocks / UINT64_C(1000); +#endif +} + +p8_clock_t p8_clock_delta(p8_clock_t start, p8_clock_t end) +{ + return end - start; +} + +static void p8_sleep(unsigned ms) +{ +#ifdef OS_FREERTOS + vTaskDelay(pdMS_TO_TICKS(ms)); +#else + usleep(ms * 1000); +#endif +} + +int p8_init() +{ + assert(!m_initialized); + + srand((unsigned int)time(NULL)); + +#ifdef SDL + m_memory = (uint8_t *)malloc(MEMORY_SIZE); + m_cart_memory = (uint8_t *)malloc(CART_MEMORY_SIZE); + m_overlay_memory = (uint8_t *)malloc(MEMORY_SCREEN_SIZE); + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) + { + printf("Error on SDL_Init().\n"); + return 1; + } + + SDL_ShowCursor(SDL_DISABLE); + + /* Create SDL2 window/renderer/texture and an output surface we render into. */ + m_window = SDL_CreateWindow("femto-8", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); + if (!m_window) { + printf("Error creating SDL window.\n"); + return 1; + } + m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); + if (!m_renderer) { + SDL_DestroyWindow(m_window); + m_window = NULL; + printf("Error creating SDL renderer.\n"); + return 1; + } + + /* Texture at native P8 resolution; we'll update it from the output surface. */ + m_texture = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, P8_WIDTH, P8_HEIGHT); + m_output = SDL_CreateRGBSurfaceWithFormat(0, P8_WIDTH, P8_HEIGHT, 32, SDL_PIXELFORMAT_ARGB8888); + m_format = m_output->format; + + SDL_SetWindowTitle(m_window, "femto-8"); +#endif +#ifdef OS_FREERTOS + m_drawSemaphore = xSemaphoreCreateBinary(); + + xSemaphoreGive(m_drawSemaphore); +#endif + + m_memory = (uint8_t *)malloc(MEMORY_SIZE); + m_cart_memory = (uint8_t *)malloc(CART_MEMORY_SIZE); + m_temp_cart_memory = (uint8_t *)malloc(CART_MEMORY_SIZE); + m_overlay_memory = (uint8_t *)malloc(MEMORY_SCREEN_SIZE); + m_file_buffer = (uint8_t *)malloc(FILE_BUFFER_SIZE); + m_decompression_buffer = (uint8_t *)malloc(DECOMPRESSION_BUFFER_SIZE); + m_lua_script = (char *)malloc(LUA_SCRIPT_SIZE); + m_temp_lua_script = (char *)malloc(LUA_SCRIPT_SIZE); + + if (!m_memory || !m_cart_memory || !m_overlay_memory || !m_file_buffer || !m_decompression_buffer || !m_lua_script || !m_temp_lua_script) { + fputs("Out of memory\n", stderr); + free(m_memory); + free(m_cart_memory); + free(m_temp_cart_memory); + free(m_overlay_memory); + free(m_file_buffer); + free(m_decompression_buffer); + free(m_lua_script); + free(m_temp_lua_script); + return 1; + } + + memset(m_memory, 0, MEMORY_SIZE); + memset(m_cart_memory, 0, CART_MEMORY_SIZE); + memset(m_overlay_memory, (OVERLAY_TRANSPARENT_COLOR << 4) | OVERLAY_TRANSPARENT_COLOR, MEMORY_SCREEN_SIZE); + m_lua_script[0] = '\0'; + +#ifdef ENABLE_AUDIO + audio_init(); +#endif + + p8_init_lcd(); + p8_init_input(); + + int ret = lua_load_api(); + if (ret != 0) + return ret; + + m_initialized = 1; + + return 0; +} + +static int p8_init_lcd(void) +{ +#ifdef __DA1470x__ + gdi_set_layer_start(HW_LCDC_LAYER_0, 0, 0); + + gdi_set_layer_enable(HW_LCDC_LAYER_0, true); + + uint16_t *fb = (uint16_t *)gdi_get_frame_buffer_addr(HW_LCDC_LAYER_0); + + gdi_set_layer_src(HW_LCDC_LAYER_0, fb, SCREEN_WIDTH, SCREEN_HEIGHT, GDI_FORMAT_RGB565); +#endif + + return 0; +} + +static void p8_wait_for_any_key(void) +{ + int x, y; + cursor_get(&x, &y); + y = scroll(y, GLYPH_HEIGHT); + draw_simple_text("press any key...", 0, y, 7); + cursor_set(0, y + GLYPH_HEIGHT, -1); + p8_flip(); + while (!p8_is_quit_requested()) { + p8_update_input(); + unsigned scancode = 0, keymod = 0; + uint8_t keypress = 0; + if (p8_get_next_keypress(&scancode, &keypress, &keymod)) + break; + } +} + +int p8_load(const char *file_name, const char *param, const char *bbs_cart_id, const char *breadcrumb) +{ + assert(m_initialized); + + p8_show_io_icon(true); + + printf("Loading %s\n", file_name); + if (parse_cart_file(file_name, m_cart_memory, m_file_buffer, m_decompression_buffer, m_lua_script, NULL) != 0) { + p8_show_io_icon(false); + return -1; + } + + strtcpy(m_param_string, param ? param : "", sizeof(m_param_string)); + strtcpy(m_breadcrumb, breadcrumb ? breadcrumb : "", sizeof(m_breadcrumb)); + + strtcpy(m_current_cart_file_name, file_name, sizeof(m_current_cart_file_name)); + strtcpy(m_current_cart_dir, ".", sizeof(m_current_cart_dir)); + + if (cart_running) + p8_reset_cart(); + + p8_show_io_icon(false); + return 0; +} + +int p8_load_ram(uint8_t *buffer, int size) +{ + assert(m_initialized); + + p8_show_io_icon(true); + + int ret = parse_cart_ram(buffer, size, m_cart_memory, m_decompression_buffer, m_lua_script, NULL); + + p8_show_io_icon(false); + return ret; +} + +int p8_run(void) +{ + assert(m_initialized); + assert(m_lua_script); + + if (lua_running) { + restart = true; + longjmp(jmpbuf_restart, 1); + } else if (cart_running) { + p8_restart(); + // should not be reachable + abort(); + } + assert(!cart_running); + + if (setjmp(jmpbuf_restart)) { + cart_running = false; + if (!restart) + return 0; + } + restart = false; + + p8_reset_cart(); + + cart_running = true; + + int ret = lua_init_script(m_current_cart_file_name, m_lua_script); + if (ret != 0) { + cart_running = false; + return ret; + } + + ret = lua_init(); + if (ret != 0) { + cart_running = false; + return ret; + } + + if (lua_has_main_loop_callbacks()) { + ret = p8_main_loop(); + if (ret != 0) { + cart_running = false; + return ret; + } + } else if (!skip_main_loop_if_no_callbacks) { + p8_wait_for_any_key(); + } + + cart_running = false; + + p8_reset_cart(); + + return 0; +} + +int p8_shutdown() +{ + audio_close(); + + lua_shutdown_api(); + + p8_close_cartdata(); + +#ifdef SDL + if (m_texture) { SDL_DestroyTexture(m_texture); m_texture = NULL; } + if (m_renderer) { SDL_DestroyRenderer(m_renderer); m_renderer = NULL; } + if (m_window) { SDL_DestroyWindow(m_window); m_window = NULL; } + if (m_output) { SDL_FreeSurface(m_output); m_output = NULL; } + SDL_Quit(); +#endif + + free(m_cart_memory); + free(m_temp_cart_memory); + free(m_memory); + free(m_overlay_memory); + free(m_file_buffer); + free(m_decompression_buffer); + free(m_lua_script); + free(m_temp_lua_script); + m_cart_memory = NULL; + m_memory = NULL; + m_overlay_memory = NULL; + m_file_buffer = NULL; + m_decompression_buffer = NULL; + m_lua_script = NULL; + m_temp_lua_script = NULL; + + m_initialized = 0; + + return 0; +} + +#if defined(SDL) || defined(FEMTO8_ESPBOX) +// Map output pixel (ox, oy) to source framebuffer pixel (sx, sy) based on +// the screen transform mode at 0x5f2c. +static void screen_transform_pixel(uint8_t mode, int ox, int oy, int *sx, int *sy) +{ + switch (mode) { + default: + case 0: // normal + *sx = ox; *sy = oy; + break; + case 1: // horizontal stretch: 64x128 β†’ 128x128 + *sx = ox >> 1; *sy = oy; + break; + case 2: // vertical stretch: 128x64 β†’ 128x128 + *sx = ox; *sy = oy >> 1; + break; + case 3: // both stretch: 64x64 β†’ 128x128 + *sx = ox >> 1; *sy = oy >> 1; + break; + case 5: // horizontal mirror: left half mirrored to right + *sx = (ox < 64) ? ox : (127 - ox); *sy = oy; + break; + case 6: // vertical mirror: top half mirrored to bottom + *sx = ox; *sy = (oy < 64) ? oy : (127 - oy); + break; + case 7: // both mirror: top-left quarter mirrored to all + *sx = (ox < 64) ? ox : (127 - ox); + *sy = (oy < 64) ? oy : (127 - oy); + break; + case 129: // horizontal flip + *sx = 127 - ox; *sy = oy; + break; + case 130: // vertical flip + *sx = ox; *sy = 127 - oy; + break; + case 131: // both flip (180 degree rotation) + *sx = 127 - ox; *sy = 127 - oy; + break; + case 133: // clockwise 90 degree rotation + *sx = 127 - oy; *sy = ox; + break; + case 134: // 180 degree rotation + *sx = 127 - ox; *sy = 127 - oy; + break; + case 135: // counterclockwise 90 degree rotation + *sx = oy; *sy = 127 - ox; + break; + } +} + +// Resolve palette for a framebuffer pixel given the high-color mode. +// pix_index is the raw 4-bit pixel value, sy is the source scanline, +// sx is the source x coordinate. +static uint8_t high_color_resolve(uint8_t hc_mode, uint8_t pix_index, int sx, int sy) +{ + if (hc_mode == 0x10) { + // Per-line palette swap: use secondary palette if bit set in bitfield + uint8_t bf = m_memory[0x5f70 + (sy >> 3)]; + if (bf & (1 << (sy & 7))) + return color_get(PALTYPE_SECONDARY, pix_index); + return color_get(PALTYPE_SCREEN, pix_index); + } + if (hc_mode == 0x20) { + // 5-bitplane mode: requires 0x5f2c == 1 (horizontal stretch). + // If the corresponding pixel in the hidden right half (sx+64) is + // non-zero, use secondary palette. + int hidden_offset = (m_memory[MEMORY_SCREEN_PHYS] << 8) + ((sx + 64) >> 1) + sy * 64; + uint8_t hidden_val = m_memory[hidden_offset]; + uint8_t hidden_pix = IS_EVEN(sx + 64) ? (hidden_val & 0xF) : (hidden_val >> 4); + if (hidden_pix != 0) + return color_get(PALTYPE_SECONDARY, pix_index); + return color_get(PALTYPE_SCREEN, pix_index); + } + if ((hc_mode & 0xf0) == 0x30) { + // Gradient fill: replace color n with per-section gradient + uint8_t replace_color = hc_mode & 0x0f; + uint8_t screen_index = color_get(PALTYPE_SCREEN, pix_index); + if ((screen_index & 0x0f) == replace_color) { + int section = sy >> 3; + uint8_t bf = m_memory[0x5f70 + (sy >> 3)]; + if (bf & (1 << (sy & 7))) + section = (section + 1) & 0x0f; + return color_get(PALTYPE_SECONDARY, section); + } + return screen_index; + } + return color_get(PALTYPE_SCREEN, pix_index); +} + +void p8_render() +{ +#ifdef FEMTO8_ESPBOX + /* 128x128 of 5-bit colour indices; the emulator applies m_colors as the + * display palette and scales the frame (no on-screen fps counter) */ + uint8_t *output = p8_espbox_frame_begin(); + if (!output) + return; +#else + sprintf(m_str_buffer, "%d", (int)m_actual_fps); + draw_simple_text(m_str_buffer, 0, 0, 1); + + uint32_t *output = m_output->pixels; +#endif + uint8_t transform = m_memory[MEMORY_SCREEN_TRANSFORM]; + uint8_t hc_mode = m_memory[MEMORY_HIGH_COLOUR_MODE]; + + for (int y = 0; y < P8_HEIGHT; y++) + { + for (int x = 0; x < P8_WIDTH; x++) + { + int sx, sy; + screen_transform_pixel(transform, x, y, &sx, &sy); + int screen_offset = (m_memory[MEMORY_SCREEN_PHYS] << 8) + (sx >> 1) + sy * 64; + uint8_t value = m_memory[screen_offset]; + uint8_t pix = IS_EVEN(sx) ? value & 0xF : value >> 4; + uint8_t index; + if (hc_mode != 0) + index = high_color_resolve(hc_mode, pix, sx, sy); + else + index = color_get(PALTYPE_SCREEN, pix); +#ifdef FEMTO8_ESPBOX + output[x + (y * P8_WIDTH)] = color_index(index); +#else + uint32_t color = m_colors[color_index(index)]; + + output[x + (y * P8_WIDTH)] = color; +#endif + } + } + + uint8_t *overlay_mem = m_overlay_memory; + + for (int y = 0; y < P8_HEIGHT; y++) + { + for (int x = 0; x < P8_WIDTH; x++) + { + int overlay_offset = (x >> 1) + y * 64; + uint8_t value = overlay_mem[overlay_offset]; + uint8_t pixel_color = IS_EVEN(x) ? (value & 0xF) : (value >> 4); + + if (pixel_color != OVERLAY_TRANSPARENT_COLOR) + { +#ifdef FEMTO8_ESPBOX + output[x + (y * P8_WIDTH)] = color_index(pixel_color); +#else + uint32_t color = m_colors[color_index(pixel_color)]; + output[x + (y * P8_WIDTH)] = color; +#endif + } + } + } + +#ifdef FEMTO8_ESPBOX + p8_espbox_frame_end(); +#else + SDL_Rect rectDest = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT}; +#endif +#ifdef SDL + if (m_texture && m_renderer) { + SDL_UpdateTexture(m_texture, NULL, m_output->pixels, m_output->pitch); + SDL_RenderClear(m_renderer); + SDL_RenderCopy(m_renderer, m_texture, NULL, &rectDest); + SDL_RenderPresent(m_renderer); + } +#elif !defined(FEMTO8_ESPBOX) + (void)rectDest; +#endif +} +#elif defined(__DA1470x__) + +void draw_complete(bool underflow, void *user_data) +{ + xSemaphoreGive(m_drawSemaphore); +} + +void p8_render() +{ + if (xSemaphoreTake(m_drawSemaphore, portMAX_DELAY) != pdTRUE) + return; + + sprintf(m_str_buffer, "%d", (int)m_actual_fps); + draw_text(m_str_buffer, strlen(m_str_buffer), 0, 0, 1, 0, false, NULL, NULL, NULL); + + uint16_t *output = gdi_get_frame_buffer_addr(HW_LCDC_LAYER_0); + uint8_t *screen_mem = &m_memory[(m_memory[MEMORY_SCREEN_PHYS] << 8)]; + uint8_t *pal = &m_memory[MEMORY_PALETTES + PALTYPE_SCREEN * 16]; + + for (int y = 1; y <= 128; y++) + { + if (y & 0x7) + { + uint16_t *top = output; + uint16_t *bottom = output + 240; + + for (int x = 0; x < 128; x += 8) + { + + uint8_t left = (*screen_mem) & 0xF; + uint8_t right = (*screen_mem) >> 4; + + uint8_t index_left = pal[left]; + uint8_t index_right = color_pal[right]; + + uint16_t c_left = m_colors[color_index(index_left)]; + uint16_t c_right = m_colors[color_index(index_right)]; + + *top++ = c_left; + *top++ = c_left; + *top++ = c_right; + *top++ = c_right; + + *bottom++ = c_left; + *bottom++ = c_left; + *bottom++ = c_right; + *bottom++ = c_right; + + screen_mem++; + + left = (*screen_mem) & 0xF; + right = (*screen_mem) >> 4; + + index_left = pal[left]; + index_right = pal[right]; + + c_left = m_colors[color_index(index_left)]; + c_right = m_colors[color_index(index_right)]; + + *top++ = c_left; + *top++ = c_left; + *top++ = c_right; + *top++ = c_right; + + *bottom++ = c_left; + *bottom++ = c_left; + *bottom++ = c_right; + *bottom++ = c_right; + + screen_mem++; + + left = (*screen_mem) & 0xF; + right = (*screen_mem) >> 4; + + index_left = pal[left]; + index_right = pal[right]; + + c_left = m_colors[color_index(index_left)]; + c_right = m_colors[color_index(index_right)]; + + *top++ = c_left; + *top++ = c_left; + *top++ = c_right; + *top++ = c_right; + + *bottom++ = c_left; + *bottom++ = c_left; + *bottom++ = c_right; + *bottom++ = c_right; + + screen_mem++; + + left = (*screen_mem) & 0xF; + right = (*screen_mem) >> 4; + + index_left = pal[left]; + index_right = pal[right]; + + c_left = m_colors[color_index(index_left)]; + c_right = m_colors[color_index(index_right)]; + + *top++ = c_left; + *top++ = c_left; + *top++ = c_right; + + *bottom++ = c_left; + *bottom++ = c_right; + *bottom++ = c_right; + + screen_mem++; + } + + output += 480; + } + else + { + uint16_t *top = output; + + for (int x = 0; x < 128; x += 8) + { + + uint8_t left = (*screen_mem) & 0xF; + uint8_t right = (*screen_mem) >> 4; + + uint8_t index_left = pal[left]; + uint8_t index_right = pal[right]; + + uint16_t c_left = m_colors[color_index(index_left)]; + uint16_t c_right = m_colors[color_index(index_right)]; + + *top++ = c_left; + *top++ = c_left; + *top++ = c_right; + *top++ = c_right; + + screen_mem++; + + left = (*screen_mem) & 0xF; + right = (*screen_mem) >> 4; + + index_left = pal[left]; + index_right = pal[right]; + + c_left = m_colors[color_index(index_left)]; + c_right = m_colors[color_index(index_right)]; + + *top++ = c_left; + *top++ = c_left; + *top++ = c_right; + *top++ = c_right; + + screen_mem++; + + left = (*screen_mem) & 0xF; + right = (*screen_mem) >> 4; + + index_left = pal[left]; + index_right = pal[right]; + + c_left = m_colors[color_index(index_left)]; + c_right = m_colors[color_index(index_right)]; + + *top++ = c_left; + *top++ = c_left; + *top++ = c_right; + *top++ = c_right; + + screen_mem++; + + left = (*screen_mem) & 0xF; + right = (*screen_mem) >> 4; + + index_left = pal[left]; + index_right = pal[right]; + + c_left = m_colors[color_index(index_left)]; + c_right = m_colors[color_index(index_right)]; + + *top++ = c_left; + *top++ = c_left; + *top++ = c_right; + + screen_mem++; + } + + output += 240; + } + } + + output = gdi_get_frame_buffer_addr(HW_LCDC_LAYER_0); + + for (int y = 1; y <= P8_HEIGHT; y++) + { + if (y & 0x7) + { + uint16_t *top = output; + + for (int x = 0; x < 128; x += 2) + { + int overlay_offset = (x >> 1) + (y - 1) * 64; + uint8_t value = m_overlay_memory[overlay_offset]; + uint8_t left = value & 0xF; + uint8_t right = value >> 4; + + if (left != OVERLAY_TRANSPARENT_COLOR) + { + uint16_t c_left = m_colors[color_index(left)]; + *top = c_left; + *(top + 1) = c_left; + } + top += 2; + + if (right != OVERLAY_TRANSPARENT_COLOR) + { + uint16_t c_right = m_colors[color_index(right)]; + *top = c_right; + *(top + 1) = c_right; + } + top += 2; + } + + output += 240; + } + } + + gdi_display_update_async(draw_complete, NULL); +} +#endif + +static void p8_post_flip(void) +{ + p8_flush_cartdata(); + p8_update_input(); + p8_check_for_pause(); + m_frames++; +} + +void p8_flip() +{ + p8_render(); + + unsigned elapsed_time = p8_elapsed_time(); + const unsigned target_frame_time = 1000 / m_fps; + int sleep_time = target_frame_time - elapsed_time; + if (sleep_time < 0) + sleep_time = 0; + m_actual_fps = 1000 / (elapsed_time + sleep_time); + + if (sleep_time > 0) + p8_sleep(sleep_time); + + m_start_time = p8_clock(); + + p8_post_flip(); +} + +static int p8_main_loop() +{ + int time_debt = 0; + unsigned updates_since_last_flip = 0; + + for (;;) + { + const int target_frame_time = 1000 / m_fps; + + int ret = lua_update(); + if (ret != 0) + return ret; + updates_since_last_flip++; + + unsigned elapsed = p8_elapsed_time(); + + time_debt += elapsed; + + if (time_debt < target_frame_time || updates_since_last_flip >= m_fps) { + ret = lua_draw(); + if (ret != 0) + return ret; + time_debt += p8_elapsed_time() - elapsed; + + p8_flip(); + + if (updates_since_last_flip >= m_fps) { + time_debt = 0; + } else { + time_debt -= target_frame_time; + if (time_debt < -target_frame_time) time_debt = -target_frame_time; + } + + updates_since_last_flip = 0; + } else { + p8_post_flip(); + + time_debt -= target_frame_time; + } + } +} + +unsigned p8_elapsed_time(void) +{ + p8_clock_t now = p8_clock(); + unsigned elapsed_time; + if (m_start_time == 0) + elapsed_time = 0; + else + elapsed_time = p8_clock_ms(p8_clock_delta(m_start_time, now)); + return elapsed_time; +} + +void p8_check_for_pause(void) +{ + if (!m_dialog_showing) { + if (cart_running || lua_running) { + if ((m_buttonsp[0] & BUTTON_MASK_ESCAPE) != 0) + p8_abort(); + } + if (cart_running) { + if ((m_buttonsp[0] & BUTTON_MASK_PAUSE) != 0) + p8_show_pause_menu(); + } + } +} + +void p8_seed_rng_state(uint32_t seed) +{ + uint32_t hi, lo; + + if (seed == 0) { + hi = 0x60009755; + lo = 0xdeadbeef; + } else { + seed &= 0x7fffffff; + + // seed is already a full 32-bit fix32 value; use it directly. + hi = seed ^ 0xbead29ba; + lo = seed; + } + + for (int i = 0; i < 32; i++) { + hi = (hi << 16) | (hi >> 16); + hi += lo; + lo += hi; + } + + m_memory[MEMORY_RNG_STATE] = hi & 0xFF; + m_memory[MEMORY_RNG_STATE + 1] = (hi >> 8) & 0xFF; + m_memory[MEMORY_RNG_STATE + 2] = (hi >> 16) & 0xFF; + m_memory[MEMORY_RNG_STATE + 3] = (hi >> 24) & 0xFF; + m_memory[MEMORY_RNG_STATE + 4] = lo & 0xFF; + m_memory[MEMORY_RNG_STATE + 5] = (lo >> 8) & 0xFF; + m_memory[MEMORY_RNG_STATE + 6] = (lo >> 16) & 0xFF; + m_memory[MEMORY_RNG_STATE + 7] = (lo >> 24) & 0xFF; +} + +void p8_reset(void) +{ + uint8_t cursor_x = m_memory[MEMORY_CURSOR]; + uint8_t cursor_y = m_memory[MEMORY_CURSOR + 1]; + memset(m_memory + MEMORY_DRAWSTATE, 0, MEMORY_DRAWSTATE_SIZE); + memset(m_memory + MEMORY_HARDWARESTATE, 0, MEMORY_HARDWARESTATE_SIZE); + m_memory[MEMORY_SCREEN_PHYS] = 0x60; + m_memory[MEMORY_MAP_START] = 0x20; + m_memory[MEMORY_MAP_WIDTH] = 128; + m_memory[MEMORY_RW_MASK] = 0xff; + pencolor_set(6); + reset_color(); + clip_set(0, 0, P8_WIDTH, P8_HEIGHT); + // time(NULL) is a plain integer; shift left 16 to make it a fix32 integer. + p8_seed_rng_state((uint32_t)time(NULL) << 16); + m_memory[MEMORY_CURSOR] = cursor_x; + m_memory[MEMORY_CURSOR + 1] = cursor_y; +} + +static void p8_common_reset_cart() +{ + assert(!cart_running); + p8_close_cartdata(); + lua_shutdown_api(); + lua_load_api(); + p8_reset(); + m_frames = 0; + p8_reset_input(); + p8_update_input(); +} + +void p8_new_cart(void) +{ + assert(!cart_running); + m_current_cart_file_name[0] = '\0'; + memset(m_cart_memory, 0, CART_MEMORY_SIZE); + memset(m_memory, 0, CART_MEMORY_SIZE); + p8_common_reset_cart(); +} + +void p8_reset_cart(void) +{ + assert(!cart_running); + memcpy(m_memory, m_cart_memory, CART_MEMORY_SIZE); + p8_common_reset_cart(); +} + +void __attribute__ ((noreturn)) p8_abort() +{ + assert(cart_running); + longjmp(jmpbuf_restart, 1); +} + +void __attribute__ ((noreturn)) p8_restart() +{ + assert(cart_running); + restart = true; + p8_abort(); +} + +void p8_quit() +{ + quit_requested = true; + if (cart_running || lua_running) + p8_abort(); +} + +bool p8_is_cart_running(void) +{ + return cart_running; +} + +bool p8_is_quit_requested(void) +{ + return quit_requested; +} + +int p8_make_full_path(char *ret, int ret_size, const char *dir_path, const char *file_name) +{ + if (!ret || !dir_path || !file_name) { + errno = EINVAL; + return -1; + } + + size_t dir_len = strlen(dir_path); + size_t file_len = strlen(file_name); + if (dir_len > PATH_MAX || file_len > PATH_MAX || dir_len + 1 + file_len > PATH_MAX) + return -1; + + if (strcmp(file_name, "..") == 0) { + strcpy(ret, dir_path); + char *slash = strrchr(ret, '/'); + if (!slash) + slash = strrchr(ret, '\\'); + if (slash) { + if (slash[1] == '\0' && ret[1] == ':' && slash==ret+2) { + // If going up a directory from the root of a drive, + // go up to the list of drives rather than the current + // directory of the drive. + // i.e. "C:\" -> "" rather than "C:\" -> "C:" + ret[0] = '\0'; + } else if (ret[1] == ':' && slash==ret+2) { + // If going up to the root of the drive don't erase + // the trailing slash. + slash[1] = '\0'; + } else { + slash[0] = '\0'; + } + } + } else { + strcpy(ret, dir_path); + if (dir_len > 0 && + ret[dir_len - 1] != '/' && + ret[dir_len - 1] != '\\') + strcat(ret, "/"); + strcat(ret, file_name); + } + return 0; +} + +int p8_resolve_relative_path(char *dest_filename, const char *src_filename, size_t dest_size, bool for_cstore) +{ + if (src_filename[0] == '/' || src_filename[1] == ':') + return strtcpy(dest_filename, src_filename, dest_size); + + if (!m_current_cart_dir[0]) + return strtcpy(dest_filename, src_filename, dest_size); + + for (int pass=1;pass<=(for_cstore?1:2);pass++) { + const char *cart_dir = (pass == 1) ? DEFAULT_CARTS_PATH : m_current_cart_dir; + int ret = snprintf(dest_filename, dest_size, "%s/%s", cart_dir, src_filename); + if (pass == (for_cstore ? 1 : 2) || access(dest_filename, F_OK) == 0) + return (ret > 0 && (size_t)ret < dest_size) ? ret : -1; + } + + return -1; +} + +void p8_set_skip_main_loop_if_no_callbacks(bool skip) +{ + skip_main_loop_if_no_callbacks = skip; +} + +bool p8_get_skip_main_loop_if_no_callbacks(void) +{ + return skip_main_loop_if_no_callbacks; +} + +bool p8_open_cartdata(const char *id) +{ + if (cartdata) + return false; + int ret = MKDIR(CARTDATA_PATH); + if (ret == -1 && errno != EEXIST) { + return false; + } + char *path = alloca(strlen(CARTDATA_PATH) + 1 + strlen(id) + 1); + sprintf(path, "%s/%s", CARTDATA_PATH, id); + cartdata = fopen(path, "r+b"); + if (!cartdata) { + cartdata = fopen(path, "w+b"); + if (!cartdata) { + return false; + } + } + fseek(cartdata, 0, SEEK_SET); + uint8_t *dst = m_memory + MEMORY_CARTDATA; + size_t n = fread(dst, 1, 0x100, cartdata); + if (n < 0x100) { + memset(dst + n, 0, 0x100 - n); + } + return true; +} + +void p8_flush_cartdata(void) +{ + if (cartdata && cartdata_needs_flush) { + cartdata_needs_flush = false; + fseek(cartdata, 0, SEEK_SET); + fwrite(m_memory + MEMORY_CARTDATA, 0x100, 1, cartdata); + fflush(cartdata); + } +} + +void p8_delayed_flush_cartdata(void) +{ + cartdata_needs_flush = true; +} + +void p8_close_cartdata(void) +{ + if (cartdata) { + p8_flush_cartdata(); + fclose(cartdata); + cartdata = NULL; + } +} + +void p8_show_io_icon(bool show) +{ + if (show) { + overlay_draw_icon(io_icon, P8_WIDTH - 8, 0); + } else { + overlay_draw_rectfill(P8_WIDTH - 8, 0, P8_WIDTH-1, 7, OVERLAY_TRANSPARENT_COLOR); + p8_dialog_draw_stack(); + } + p8_flip(); +} + +void p8_show_error_dialog(const char **lines, int line_count, p8_error_severity_t severity) +{ + assert(line_count <= 4); + + int control_count = line_count + 2; + p8_dialog_control_t controls[6]; + + /* Add label controls for each line */ + for (int i = 0; i < line_count; i++) { + controls[i] = (p8_dialog_control_t)DIALOG_LABEL(lines[i]); + } + + /* Add spacing and button bar */ + controls[line_count] = (p8_dialog_control_t)DIALOG_SPACING(); + controls[line_count + 1] = (p8_dialog_control_t)DIALOG_BUTTONBAR_OK_ONLY(); + + p8_dialog_t error_dialog; + const char *title = (severity == P8_ERROR_WARNING) ? "warning" : "error"; + p8_dialog_init(&error_dialog, title, controls, control_count, 120); + p8_dialog_run(&error_dialog); + p8_dialog_cleanup(&error_dialog); +} + +void p8_show_version_dialog(void) +{ + extern const char *femto8_version; + char femto8_version_string[50]; + sprintf(femto8_version_string, "femto8 %s", femto8_version); + + p8_dialog_control_t controls[] = { + DIALOG_LABEL(femto8_version_string), + DIALOG_SPACING(), + DIALOG_BUTTONBAR_OK_ONLY() + }; + + p8_dialog_t dialog; + p8_dialog_init(&dialog, "femto8 version", controls, sizeof(controls) / sizeof(controls[0]), 0); + p8_dialog_run(&dialog); + p8_dialog_cleanup(&dialog); +} + +void p8_show_lua_error_dialog(void) +{ + const char *err_type; + char err_msg[256]; + err_msg[0] = '\0'; + lua_get_error(&err_type, err_msg, sizeof(err_msg), NULL, NULL); + + const char *lines[] = { + err_type ? err_type : "", + err_msg + }; + p8_show_error_dialog(lines, 2, P8_ERROR_ERROR); +} diff --git a/components/pico8/femto8/src/p8_emu.h b/components/pico8/femto8/src/p8_emu.h new file mode 100644 index 00000000..3a1fb50d --- /dev/null +++ b/components/pico8/femto8/src/p8_emu.h @@ -0,0 +1,308 @@ +/* + * p8_emu.h + * + * Created on: Dec 13, 2023 + * Author: bbaker + */ + +#ifndef P8_EMU_H +#define P8_EMU_H + +#if defined(_WIN32) +#include // _mkdir +#else +#include // mkdir +#endif +#include +#include +#include +#include +#include + +#define PROGNAME "femto8" + +#if defined(__DA1470x__) +#define OS_FREERTOS +#elif defined(FEMTO8_ESPBOX) +/* esp-box-emu: FreeRTOS clock/sleep, the emulator supplies video, audio and + * input (see p8_espbox.h) */ +#define OS_FREERTOS +#define ENABLE_AUDIO +#else +#define SDL +#define ENABLE_AUDIO +#endif + +#ifndef CARTDATA_PATH +#define CARTDATA_PATH "cdata" +#endif + +#ifndef DEFAULT_CARTS_PATH +#define DEFAULT_CARTS_PATH "carts" +#endif + +// #define BOOL_NULL -1 +#define PI 3.14159265358f +#define TWO_PI 6.28318530718f + +#ifndef MAX +#define MAX(a, b) ((a) > (b) ? a : b) +#define MIN(a, b) ((a) < (b) ? a : b) +#endif +#define IS_EVEN(n) (((n) ^ 1) == ((n) + 1)) +#define NIBBLE_SWAP(n) (((n) << 4) | ((n) >> 4)) +#define ARGB_TO_RGB565(argb) ((((argb) >> 8) & 0xF800) | (((argb) >> 5) & 0x07E0) | (((argb) >> 3) & 0x001F)) + +#if defined(_WIN32) +#define MKDIR(p) _mkdir(p) +#else +#define MKDIR(p) mkdir((p), 0777) +#endif + +#ifdef __DA1470x__ +#define SCREEN_WIDTH 240 +#define SCREEN_HEIGHT 240 +#else +#define SCREEN_WIDTH 512 +#define SCREEN_HEIGHT 512 +#endif + +#ifdef __DA1470x__ +#define malloc(x) rh_malloc(x) +#define free(x) rh_free(x) +#endif + +#ifndef PATH_MAX +#define PATH_MAX 256 +#endif + +#define P8_WIDTH 128 +#define P8_HEIGHT 128 +#define MEMORY_SPRITES 0 +#define MEMORY_SPRITES_SIZE 0x1000 +#define MEMORY_SPRITES_MAP 0x1000 +#define MEMORY_SPRITES_MAP_SIZE 0x1000 +#define MEMORY_MAP 0x2000 +#define MEMORY_MAP_SIZE 0x1000 +#define MEMORY_SPRITEFLAGS 0x3000 +#define MEMORY_SPRITEFLAGS_SIZE 0x100 +#define MEMORY_MUSIC 0x3100 +#define MEMORY_MUSIC_SIZE 0x100 +#define MEMORY_SFX 0x3200 +#define MEMORY_SFX_SIZE 0x1100 +#define MEMORY_WORKRAM 0x4300 +#define MEMORY_WORKRAM_SIZE 0x1b00 +#define MEMORY_FONT 0x5600 +#define MEMORY_FONT_SIZE 0x2000 +#define MEMORY_CARTDATA 0x5e00 +#define MEMORY_CARTDATA_SIZE 0x100 +#define MEMORY_DRAWSTATE 0x5f00 +#define MEMORY_DRAWSTATE_SIZE 0x40 +#define MEMORY_HARDWARESTATE 0x5f40 +#define MEMORY_HARDWARESTATE_SIZE 0x40 +#define MEMORY_GPIO 0x5f80 +#define MEMORY_GPIO_SIZE 0x80 +#define MEMORY_SCREEN 0x6000 +#define MEMORY_SCREEN_SIZE 0x2000 + +#define MEMORY_SIZE (1024 * 64) +#define CART_MEMORY_SIZE 0x4300 + +#define MEMORY_PALETTES 0x5f00 +#define MEMORY_CLIPRECT 0x5f20 +#define MEMORY_LEFT_MARGIN 0x5f24 +#define MEMORY_PENCOLOR 0x5f25 +#define MEMORY_CURSOR 0x5f26 +#define MEMORY_CAMERA 0x5f28 +#define MEMORY_SCREEN_TRANSFORM 0x5f2c +#define MEMORY_DEVKIT_MODE 0x5f2d +#define MEMORY_AUDIO_PAUSE 0x5f2f +#define MEMORY_SUPPRESS_PAUSE 0x5f30 +#define MEMORY_FILLP 0x5f31 +#define MEMORY_FILLP_ATTR 0x5f33 +#define MEMORY_COLOR_FILLP 0x5f34 +#define MEMORY_LINE_VALID 0x5f35 +#define MEMORY_MISCFLAGS 0x5f36 +#define MEMORY_TLINE_MASK_X 0x5f38 +#define MEMORY_TLINE_MASK_Y 0x5f39 +#define MEMORY_TLINE_OFFSET_X 0x5f3a +#define MEMORY_TLINE_OFFSET_Y 0x5f3b +#define MEMORY_LINE_X 0x5f3c +#define MEMORY_LINE_Y 0x5f3e +#define MEMORY_RNG_STATE 0x5f44 +#define MEMORY_BUTTON_STATE 0x5f4c +#define MEMORY_SPRITE_PHYS 0x5f54 +#define MEMORY_SCREEN_PHYS 0x5f55 +#define MEMORY_MAP_START 0x5f56 +#define MEMORY_MAP_WIDTH 0x5f57 +#define MEMORY_TEXT_ATTRS 0x5f58 +#define MEMORY_SGET_DEFAULT 0x5f59 +#define MEMORY_MGET_DEFAULT 0x5f5a +#define MEMORY_PGET_DEFAULT 0x5f5b +#define MEMORY_TEXT_CHAR_SIZE 0x5f59 +#define MEMORY_TEXT_CHAR_SIZE2 0x5f5a +#define MEMORY_TEXT_OFFSET 0x5f5b +#define MEMORY_AUTO_REPEAT_DELAY 0x5f5c +#define MEMORY_AUTO_REPEAT_INTERVAL 0x5f5d +#define MEMORY_RW_MASK 0x5f5e +#define MEMORY_HIGH_COLOUR_MODE 0x5f5f +#define MEMORY_PALETTE_SECONDARY 0x5f60 + +#define TICKS_PER_SECOND 128 +#define SCREEN_SIZE 128 * 128 * 4 +#define GLYPH_WIDTH 4 +#define GLYPH_HEIGHT 6 +#define SPRITE_WIDTH 8 +#define SPRITE_HEIGHT 8 +#define BUTTON_COUNT 7 +#define BUTTON_REPEAT_COUNT 6 +#define BUTTON_INTERNAL_COUNT 13 +#define PLAYER_COUNT 2 + +#define STAT_MEM_USAGE 0 +#define STAT_CPU_USAGE 1 +#define STAT_SYSTEM_CPU_USAGE 2 +#define STAT_CURRENT_DISPLAY 3 +#define STAT_CLIPBOARD 4 +#define STAT_VERSION 5 +#define STAT_PARAM 6 +#define STAT_FRAMERATE 7 +#define STAT_TARGET_FRAMERATE 8 +#define STAT_NUM_DISPLAYS 11 +#define STAT_PAUSE_MENU_X1 12 +#define STAT_PAUSE_MENU_Y1 13 +#define STAT_PAUSE_MENU_X2 14 +#define STAT_PAUSE_MENU_Y2 15 +#define STAT_RAW_KEYBOARD 28 +#define STAT_KEY_PRESSED 30 +#define STAT_KEY_NAME 31 +#define STAT_MOUSE_X 32 +#define STAT_MOUSE_Y 33 +#define STAT_MOUSE_BUTTONS 34 +#define STAT_MOUSE_WHEEL 36 +#define STAT_MOUSE_XREL 38 +#define STAT_MOUSE_YREL 39 +#define STAT_YEAR_UTC 80 +#define STAT_MONTH_UTC 81 +#define STAT_DAY_UTC 82 +#define STAT_HOUR_UTC 83 +#define STAT_MINUTE_UTC 84 +#define STAT_SECOND_UTC 85 +#define STAT_YEAR 90 +#define STAT_MONTH 91 +#define STAT_DAY 92 +#define STAT_HOUR 93 +#define STAT_MINUTE 94 +#define STAT_SECOND 95 +#define STAT_RAW_GC 99 +#define STAT_BREADCRUMB 100 +#define STAT_BBS_CART_ID 101 +#define STAT_LOAD_RESULT 107 +#define STAT_PCM_BUFFER_SIZE 108 +#define STAT_PCM_APP_BUFFER 109 +#define STAT_CURRENT_PATH 124 + +#define DEFAULT_AUTO_REPEAT_DELAY 15 +#define DEFAULT_AUTO_REPEAT_INTERVAL 4 + +#define OVERLAY_TRANSPARENT_COLOR 0 + +#define FILE_BUFFER_SIZE (128 * 1024) +#define DECOMPRESSION_BUFFER_SIZE (128 * 1024) +#define LUA_SCRIPT_SIZE (128 * 1024) + +enum +{ + PALTYPE_DRAW, + PALTYPE_SCREEN, + PALTYPE_SECONDARY +}; + +enum +{ + DRAWTYPE_DEFAULT, + DRAWTYPE_GRAPHIC, + DRAWTYPE_SPRITE +}; + +enum { + COMPAT_OK = 0, + COMPAT_SOME, + COMPAT_NONE +}; + +/* Error dialog severity levels */ +typedef enum { + P8_ERROR_WARNING, + P8_ERROR_ERROR +} p8_error_severity_t; + +extern unsigned m_fps; +extern unsigned m_actual_fps; +extern unsigned m_frames; + +#ifdef OS_FREERTOS +typedef long p8_clock_t; +#else +typedef uint_fast64_t p8_clock_t; +#endif + +extern p8_clock_t m_start_time; + +extern uint8_t *m_memory; +extern uint8_t *m_cart_memory; +extern uint8_t *m_temp_cart_memory; +extern uint8_t *m_overlay_memory; +extern uint8_t *m_file_buffer; +extern uint8_t *m_decompression_buffer; +extern char *m_lua_script; +extern char *m_temp_lua_script; + +extern char *m_font; + +extern char m_current_cart_dir[PATH_MAX]; +extern char m_current_cart_file_name[PATH_MAX]; +extern char m_breadcrumb[256]; +extern char m_clipboard[1024]; +extern char m_param_string[256]; + +extern bool m_load_available; + +void __attribute__ ((noreturn)) p8_abort(); +void p8_quit(); +void p8_check_for_pause(void); +p8_clock_t p8_clock(void); +unsigned p8_clock_ms(p8_clock_t clocks); +p8_clock_t p8_clock_delta(p8_clock_t start, p8_clock_t end); +void p8_close_cartdata(void); +void p8_delayed_flush_cartdata(void); +unsigned p8_elapsed_time(void); +int p8_exec(const char *input, const char **err_type, char *err, int err_size, const char **filename, int *lineno); +void p8_flip(void); +void p8_flush_cartdata(void); +bool p8_get_skip_main_loop_if_no_callbacks(void); +int p8_init(void); +bool p8_is_cart_running(void); +bool p8_is_quit_requested(void); +int p8_load(const char *file_name, const char *param, const char *bbs_cart_id, const char *breadcrumb); +int p8_load_ram(uint8_t *buffer, int size); +int p8_make_full_path(char *ret, int ret_size, const char *dir_path, const char *file_name); +void p8_new_cart(void); +bool p8_open_cartdata(const char *id); +void p8_pump_events(void); +int p8_shutdown(void); +void p8_render(); +void p8_reset_cart(void); +void p8_reset(void); +int p8_resolve_relative_path(char *dest_filename, const char *src_filename, size_t dest_size, bool for_cstore); +int p8_run(void); +void __attribute__ ((noreturn)) p8_restart(); +void p8_seed_rng_state(uint32_t seed); +void p8_set_skip_main_loop_if_no_callbacks(bool skip); +void p8_show_error_dialog(const char **lines, int line_count, p8_error_severity_t severity); +void p8_show_io_icon(bool show); +void p8_show_lua_error_dialog(void); +void p8_show_version_dialog(void); +int p8_shutdown(void); + +#endif diff --git a/components/pico8/femto8/src/p8_input.c b/components/pico8/femto8/src/p8_input.c new file mode 100644 index 00000000..3dae7960 --- /dev/null +++ b/components/pico8/femto8/src/p8_input.c @@ -0,0 +1,506 @@ +/** + * Copyright (C) 2026 Chris January, Ben Baker, and contributors + */ + +#include + +#include "p8_emu.h" +#include "p8_input.h" + +#if defined(SDL) +#include "SDL.h" +#elif defined(__DA1470x__) +#include "gdi.h" +#elif defined(FEMTO8_ESPBOX) +#include "p8_espbox.h" +#endif + +#ifdef SDL +/* Expose window from p8_emu for mouse grab/relative mode changes. */ +extern SDL_Window *m_window; +#endif + +#define DEFAULT_AUTO_REPEAT_DELAY_MS (DEFAULT_AUTO_REPEAT_DELAY * 1000 / 30) +#define DEFAULT_AUTO_REPEAT_INTERVAL_MS (DEFAULT_AUTO_REPEAT_INTERVAL * 1000 / 30) + +int16_t m_mouse_x, m_mouse_y; +int16_t mouse_x4, mouse_y4; +int16_t m_mouse_xrel, m_mouse_yrel; +uint8_t m_mouse_buttons, m_mouse_buttonsp; +int8_t m_mouse_wheel; +unsigned m_mouse_keymod; +static uint8_t m_mouse_click_buttons; +static int16_t m_mouse_click_x; +static int16_t m_mouse_click_y; +static unsigned m_mouse_click_mod; + +#define MAX_KEY_EVENTS 8 + +struct key_event { + unsigned scancode; + unsigned keymod; + uint8_t ch; +}; + +static int m_key_queue_write_index = 0; +static int m_key_queue_read_index = 0; +static struct key_event m_key_queue_buffer[MAX_KEY_EVENTS]; +bool m_scancodes[NUM_SCANCODES]; + +uint16_t m_buttons[PLAYER_COUNT]; +uint16_t m_buttonsp[PLAYER_COUNT]; +static uint16_t m_button_first_repeat[PLAYER_COUNT]; +static unsigned m_button_down_time[PLAYER_COUNT][BUTTON_INTERNAL_COUNT]; +#ifdef SDL +static uint16_t m_buttons_latch[PLAYER_COUNT]; +#endif + +static bool m_prev_pointer_lock; + +#ifdef SDL +static void update_buttons(int index, int button, bool state) +{ + uint16_t mask = m_buttons[index]; + mask = state ? mask | (1 << button) : mask & ~(1 << button); + m_buttons[index] = mask; + m_memory[MEMORY_BUTTON_STATE + index] = mask & 0xff; + if (state) + m_buttons_latch[index] |= (1 << button); +} +#endif + +bool p8_is_key_down(unsigned scancode) +{ + if (scancode >= NUM_SCANCODES) + return false; + return m_scancodes[scancode]; +} + +static bool is_modifier(unsigned sdl2_sc) +{ + switch (sdl2_sc) { + case 225: + case 229: + case 224: + case 228: + case 226: + case 230: + case 227: + case 231: + return true; + default: + return false; + } +} + +static void clear_input_queue(void) +{ + m_key_queue_read_index = m_key_queue_write_index; + m_mouse_click_buttons = 0; + m_mouse_click_x = 0; + m_mouse_click_y = 0; + m_mouse_click_mod = 0; +} + +static void queue_keypress(unsigned scancode, uint8_t keychar, unsigned mod) +{ + if (is_modifier(scancode)) + return; + if ((m_key_queue_write_index + 1) % MAX_KEY_EVENTS == m_key_queue_read_index) + { + // buffer is full, avoid overflow + return; + } + m_key_queue_buffer[m_key_queue_write_index].scancode = scancode; + m_key_queue_buffer[m_key_queue_write_index].ch = keychar; + m_key_queue_buffer[m_key_queue_write_index].keymod = mod; + m_key_queue_write_index = (m_key_queue_write_index + 1) % MAX_KEY_EVENTS; +} + +static void queue_mouse_click(int buttons, int x, int y, unsigned mod) +{ + m_mouse_click_buttons = buttons; + m_mouse_click_x = x; + m_mouse_click_y = y; + m_mouse_click_mod = mod; +} + +bool p8_get_next_keypress(unsigned *scancode, uint8_t *keychar, unsigned *mod) +{ + if (m_key_queue_read_index == m_key_queue_write_index) { + // buffer is empty + return false; + } + + *scancode = m_key_queue_buffer[m_key_queue_read_index].scancode; + *keychar = m_key_queue_buffer[m_key_queue_read_index].ch; + *mod = m_key_queue_buffer[m_key_queue_read_index].keymod; + m_key_queue_read_index = (m_key_queue_read_index + 1) % MAX_KEY_EVENTS; + return true; +} + +bool p8_get_next_mouse_click(int *x, int *y, int *button, unsigned *mod) +{ + bool has_click = (m_mouse_click_buttons != 0); + + if (x) *x = m_mouse_click_x; + if (y) *y = m_mouse_click_y; + if (button) *button = m_mouse_click_buttons; + + m_mouse_click_x = 0; + m_mouse_click_y = 0; + m_mouse_click_buttons = 0; + + return has_click; +} + +bool p8_has_pending_keypress(void) +{ + return m_key_queue_read_index != m_key_queue_write_index; +} + +void p8_init_input(void) +{ + p8_reset_input(); +} + +void p8_pump_events(void) +{ +#if defined(FEMTO8_ESPBOX) + /* called from the Lua instruction hook: the VM is at a safe point, so + * this is where the emulator menu pauses the cart and where a quit + * requested from outside unwinds it */ + p8_espbox_pump(); +#elif defined(SDL) + SDL_PumpEvents(); + + // SDL_QUIT must be consumed and acted on immediately. + SDL_Event event; + while (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) + p8_abort(); + + // Consume all pending keydown/keyup events. Handle pause/escape immediately, + // and re-queue everything else so p8_update_input processes it normally. + SDL_Event keyevents[64]; + int n = SDL_PeepEvents(keyevents, 64, SDL_GETEVENT, SDL_KEYDOWN, SDL_KEYUP); + for (int i = 0; i < n; i++) { + SDL_Keycode sym = keyevents[i].key.keysym.sym; + bool is_pause = (sym == SDLK_RETURN || sym == SDLK_p); + bool is_escape = (sym == INPUT_ESCAPE); + if (is_pause || is_escape) { + if (sym == SDLK_RETURN) { + if (keyevents[i].type == SDL_KEYDOWN) { + if ((m_buttons[0] & BUTTON_MASK_PAUSE) == 0) + m_buttonsp[0] |= BUTTON_MASK_PAUSE; + if ((m_buttons[0] & BUTTON_MASK_RETURN) == 0) + m_buttonsp[0] |= BUTTON_MASK_RETURN; + m_buttons[0] |= BUTTON_MASK_PAUSE | BUTTON_MASK_RETURN; + m_button_down_time[0][BUTTON_PAUSE] = UINT_MAX; + m_button_down_time[0][BUTTON_RETURN] = UINT_MAX; + } else { + m_buttons[0] &= ~(BUTTON_MASK_PAUSE | BUTTON_MASK_RETURN); + } + } else if (sym == SDLK_p) { + if (keyevents[i].type == SDL_KEYDOWN) { + if ((m_buttons[0] & BUTTON_MASK_PAUSE) == 0) + m_buttonsp[0] |= BUTTON_MASK_PAUSE; + m_buttons[0] |= BUTTON_MASK_PAUSE; + m_button_down_time[0][BUTTON_PAUSE] = UINT_MAX; + } else { + m_buttons[0] &= ~BUTTON_MASK_PAUSE; + } + } else if (sym == INPUT_ESCAPE) { + if (keyevents[i].type == SDL_KEYDOWN) { + if ((m_buttons[0] & BUTTON_MASK_ESCAPE) == 0) + m_buttonsp[0] |= BUTTON_MASK_ESCAPE; + m_buttons[0] |= BUTTON_MASK_ESCAPE; + m_button_down_time[0][BUTTON_ESCAPE] = UINT_MAX; + } else { + m_buttons[0] &= ~BUTTON_MASK_ESCAPE; + } + } + } else { + SDL_PushEvent(&keyevents[i]); + } + } +#endif +} + +void p8_reset_input() +{ + for (unsigned p=0;p<2;++p) { + for (unsigned i=0;i 0 && event.key.keysym.scancode < NUM_SCANCODES) + m_scancodes[event.key.keysym.scancode] = true; + queue_keypress(event.key.keysym.scancode, event.key.keysym.sym < 32 ? event.key.keysym.sym : 0, event.key.keysym.mod); + m_mouse_keymod = event.key.keysym.mod; + } + break; + case SDL_KEYUP: + switch (event.key.keysym.sym) + { + case INPUT_LEFT: + update_buttons(0, BUTTON_LEFT, false); + break; + case INPUT_RIGHT: + update_buttons(0, BUTTON_RIGHT, false); + break; + case INPUT_UP: + update_buttons(0, BUTTON_UP, false); + break; + case INPUT_DOWN: + update_buttons(0, BUTTON_DOWN, false); + break; + case INPUT_ACTION1: + update_buttons(0, BUTTON_ACTION1, false); + break; + case INPUT_ACTION2: + update_buttons(0, BUTTON_ACTION2, false); + break; + case SDLK_RETURN: + update_buttons(0, BUTTON_PAUSE, false); + update_buttons(0, BUTTON_RETURN, false); + break; + case SDLK_p: + update_buttons(0, BUTTON_PAUSE, false); + break; + case SDLK_SPACE: + update_buttons(0, BUTTON_SPACE, false); + break; + case SDLK_PAGEUP: + update_buttons(0, BUTTON_PAGE_UP, false); + break; + case SDLK_PAGEDOWN: + update_buttons(0, BUTTON_PAGE_DOWN, false); + break; + case INPUT_ESCAPE: + update_buttons(0, BUTTON_ESCAPE, false); + break; + default: + break; + } + { + if (event.key.keysym.scancode > 0 && event.key.keysym.scancode < NUM_SCANCODES) + m_scancodes[event.key.keysym.scancode] = false; + m_mouse_keymod = event.key.keysym.mod; + } + break; + case SDL_QUIT: + p8_quit(); + break; + default: + break; + } + } +#elif defined(FEMTO8_ESPBOX) + m_buttons[0] = p8_espbox_buttons(); + m_memory[MEMORY_BUTTON_STATE] = m_buttons[0] & 0xff; +#elif defined(OS_FREERTOS) + uint16_t mask = 0; + + if (gamepad & AXIS_L_LEFT) + mask |= BUTTON_MASK_LEFT; + if (gamepad & AXIS_L_RIGHT) + mask |= BUTTON_MASK_RIGHT; + if (gamepad & AXIS_L_UP) + mask |= BUTTON_MASK_UP; + if (gamepad & AXIS_L_DOWN) + mask |= BUTTON_MASK_DOWN; + if (gamepad & AXIS_L_TRIGGER) + mask |= BUTTON_MASK_ACTION1; + if (gamepad & AXIS_R_LEFT) + mask |= BUTTON_MASK_LEFT; + if (gamepad & AXIS_R_RIGHT) + mask |= BUTTON_MASK_RIGHT; + if (gamepad & AXIS_R_UP) + mask |= BUTTON_MASK_UP; + if (gamepad & AXIS_R_DOWN) + mask |= BUTTON_MASK_DOWN; + if (gamepad & AXIS_R_TRIGGER) + mask |= BUTTON_MASK_ACTION2; + if (gamepad & DPAD_UP) + mask |= BUTTON_MASK_UP; + if (gamepad & DPAD_RIGHT) + mask |= BUTTON_MASK_RIGHT; + if (gamepad & DPAD_DOWN) + mask |= BUTTON_MASK_DOWN; + if (gamepad & DPAD_LEFT) + mask |= BUTTON_MASK_LEFT; + if (gamepad & BUTTON_1) + mask |= BUTTON_MASK_ACTION1; + if (gamepad & BUTTON_2) + mask |= BUTTON_MASK_ACTION2; + + m_buttons[0] = mask; +#endif + + uint8_t delay = m_memory[MEMORY_AUTO_REPEAT_DELAY]; + if (delay == 0) + delay = DEFAULT_AUTO_REPEAT_DELAY; + uint8_t interval = m_memory[MEMORY_AUTO_REPEAT_INTERVAL]; + if (interval == 0) + interval = DEFAULT_AUTO_REPEAT_INTERVAL; + for (unsigned p=0;p= delay) { + m_button_down_time[p][i] = m_frames; + m_button_first_repeat[p] |= 1 << i; + m_buttonsp[p] |= 1 << i; + } else if ((m_button_first_repeat[p] & (1 << i)) && m_frames - m_button_down_time[p][i] >= interval) { + m_button_down_time[p][i] = m_frames; + m_buttonsp[p] |= 1 << i; + } + } + } else { +#ifdef SDL + // Catch a press-and-release within one frame via latch + if ((m_buttons_latch[p] & (1 << i)) && !m_button_down_time[p][i]) { + m_buttonsp[p] |= 1 << i; + } +#endif + if (m_button_down_time[p][i]) { + m_button_down_time[p][i] = 0; + m_button_first_repeat[p] &= ~(1 << i); + } + } + } +#ifdef SDL + m_buttons_latch[p] = 0; +#endif + } +} diff --git a/components/pico8/femto8/src/p8_input.h b/components/pico8/femto8/src/p8_input.h new file mode 100644 index 00000000..b15a36eb --- /dev/null +++ b/components/pico8/femto8/src/p8_input.h @@ -0,0 +1,101 @@ +/** + * Copyright (C) 2026 Chris January, Ben Baker, and contributors + */ + +#ifndef P8_INPUT_H +#define P8_INPUT_H + +#include "p8_emu.h" + +#if defined(SDL) +#include "SDL.h" +#elif defined(__DA1470x__) +#include "gdi.h" +#endif + +#ifdef SDL +#define INPUT_LEFT SDLK_LEFT +#define INPUT_RIGHT SDLK_RIGHT +#define INPUT_UP SDLK_UP +#define INPUT_DOWN SDLK_DOWN +#define INPUT_ACTION1 SDLK_z +#define INPUT_ACTION2 SDLK_x +#define INPUT_ESCAPE SDLK_ESCAPE +#define NUM_SCANCODES 512 +#else +#define NUM_SCANCODES 256 +#endif + +enum +{ + BUTTON_LEFT = 0, + BUTTON_RIGHT = 1, + BUTTON_UP = 2, + BUTTON_DOWN = 3, + BUTTON_ACTION1 = 4, + BUTTON_ACTION2 = 5, + BUTTON_PAUSE = 6, + BUTTON_ESCAPE = 8, + BUTTON_RETURN = 9, + BUTTON_SPACE = 10, + BUTTON_PAGE_UP = 11, + BUTTON_PAGE_DOWN = 12, +}; + +enum +{ + BUTTON_MASK_LEFT = (1 << BUTTON_LEFT), + BUTTON_MASK_RIGHT = (1 << BUTTON_RIGHT), + BUTTON_MASK_UP = (1 << BUTTON_UP), + BUTTON_MASK_DOWN = (1 << BUTTON_DOWN), + BUTTON_MASK_ACTION1 = (1 << BUTTON_ACTION1), + BUTTON_MASK_ACTION2 = (1 << BUTTON_ACTION2), + BUTTON_MASK_PAUSE = (1 << BUTTON_PAUSE), + BUTTON_MASK_ESCAPE = (1 << BUTTON_ESCAPE), + BUTTON_MASK_RETURN = (1 << BUTTON_RETURN), + BUTTON_MASK_SPACE = (1 << BUTTON_SPACE), + BUTTON_MASK_PAGE_UP = (1 << BUTTON_PAGE_UP), + BUTTON_MASK_PAGE_DOWN = (1 << BUTTON_PAGE_DOWN), +}; + +#ifndef SDL +#define KMOD_LSHIFT 0x000001 // shift, caps shift +#define KMOD_RSHIFT 0x000002 +#define KMOD_LCTRL 0x000040 +#define KMOD_RCTRL 0x000080 +#define KMOD_LALT 0x000100 // alt, option, symbol shift +#define KMOD_RALT 0x000200 +#define KMOD_LMETA 0x000400 // Windows, command, meta +#define KMOD_RMETA 0x000800 +#define KMOD_NUM_LOCK 0x001000 +#define KMOD_CAPS_LOCK 0x002000 +#define KMOD_SCROLL_LOCK 0x008000 + +#define KMOD_SHIFT (KMOD_LSHIFT | KMOD_RSHIFT) +#define KMOD_CTRL (KMOD_LCTRL | KMOD_RCTRL) +#define KMOD_ALT (KMOD_LALT | KMOD_RALT) +#define KMOD_META (KMOD_LMETA | KMOD_RMETA) +#endif + +extern int16_t m_mouse_x, m_mouse_y; +extern int16_t m_mouse_xrel, m_mouse_yrel; +extern uint8_t m_mouse_buttons, m_mouse_buttonsp; +extern int8_t m_mouse_wheel; +extern unsigned m_mouse_keymod; +#ifndef NEXTP8 +extern bool m_scancodes[NUM_SCANCODES]; +#endif + +extern uint16_t m_buttons[PLAYER_COUNT]; +extern uint16_t m_buttonsp[PLAYER_COUNT]; + +bool p8_get_next_keypress(unsigned *scancode, uint8_t *keychar, unsigned *mod); +bool p8_get_next_mouse_click(int *x, int *y, int *button, unsigned *mod); +bool p8_has_pending_keypress(void); +bool p8_is_key_down(unsigned scancode); +void p8_init_input(void); +void p8_pump_events(void); +void p8_reset_input(void); +void p8_update_input(void); + +#endif diff --git a/components/pico8/femto8/src/p8_lua.c b/components/pico8/femto8/src/p8_lua.c new file mode 100644 index 00000000..827eea35 --- /dev/null +++ b/components/pico8/femto8/src/p8_lua.c @@ -0,0 +1,2750 @@ + +/* + * p8_lua.c + * + * Created on: Dec 13, 2023 + * Author: bbaker + */ + +#include +#include "p8_symbols.h" +#include "pico_font.h" +#include "p8_audio.h" +#include "p8_browse.h" +#include "p8_emu.h" +#include "p8_input.h" +#include "p8_lua.h" +#if defined(_WIN32) +#include +#include // GetProcessMemoryInfo +#elif defined(__GLIBC__) +#if defined(__APPLE__) + #include + #include +#else + #include // mallinfo / mallinfo2 +#endif +#else +#include // sysconf +#include // fopen/fscanf +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "p8_lua_helper.h" +#include "p8_print_helper.h" +#include "pico_font.h" +#include "p8_parser.h" +#include "p8_cstore.h" +#include "p8_pause_menu.h" +#include "lua_api.h" +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" +#include "strtcpy.h" + +lua_State *L = NULL; +static int m_status = 0; + +const void *m_lua_init = NULL; +const void *m_lua_update = NULL; +const void *m_lua_update60 = NULL; +const void *m_lua_draw = NULL; + +/* m_clipboard is a fixed-size buffer defined in p8_emu.c */ + +char m_str_buffer[256] = {0}; + +static int m_tline_precision = 13; + +static int m_load_result = 0; /* stat(107): 1=success, -1=not found, -2=fetch failed, -3=no bbs */ + +int lua_load_api(); +int lua_shutdown_api(); +void lua_print_error(); +int lua_init_script(const char *file_name, const char *script); +int lua_call_function(const char *name, int ret); +int lua_update(); +int lua_draw(); +int lua_init(); + +void lua_register_functions(lua_State *L); + +static unsigned addr_remap(unsigned address) +{ + if (address >= 0x0000 && address < 0x2000) + address = (m_memory[MEMORY_SPRITE_PHYS] << 8) | (address & 0x1fff); + else if (address >= 0x6000 && address < 0x8000) + address = (m_memory[MEMORY_SCREEN_PHYS] << 8) | (address & 0x1fff); + return address; +} + +// **************************************************************** +// *** Graphics *** +// **************************************************************** + +// camera([x,] [y]) +int camera(lua_State *L) +{ + int prev_cx, prev_cy; + camera_get(&prev_cx, &prev_cy); + + int cx = lua_gettop(L) >= 1 ? lua_tointeger(L, 1) : 0; + int cy = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0; + + camera_set(cx, cy); + + lua_pushinteger(L, prev_cx); + lua_pushinteger(L, prev_cy); + return 2; +} + +// circ(x, y, [r,] [col]) +int circ(lua_State *L) +{ + int x = lua_tointeger(L, 1); + int y = lua_tointeger(L, 2); + int r = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : 4; + int col = lua_gettop(L) >= 4 ? lua_tointeger(L, 4) : pencolor_get(); + int fillp = lua_gettop(L) >= 4 ? (fix32_bits(lua_tonumber(L, 4)) & 0xffff) : 0; + + if (lua_gettop(L) >= 3 && (m_memory[MEMORY_MISCFLAGS] & 0x2)) { + double r_real = fix32_to_double(lua_tonumber(L, 3)); + if (r_real - r >= 0.5) + r++; + } + + if (lua_gettop(L) >= 4) + pencolor_set(col); + + draw_circ(x, y, r, col, fillp); + + return 0; +} + +// circfill(x, y, [r,] [col]) +int circfill(lua_State *L) +{ + int x = lua_tointeger(L, 1); + int y = lua_tointeger(L, 2); + int r = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : 4; + int col = lua_gettop(L) >= 4 ? lua_tointeger(L, 4) : pencolor_get(); + int fillp = lua_gettop(L) >= 4 ? (fix32_bits(lua_tonumber(L, 4)) & 0xffff) : 0; + + if (lua_gettop(L) >= 3 && (m_memory[MEMORY_MISCFLAGS] & 0x2)) { + double r_real = fix32_to_double(lua_tonumber(L, 3)); + if (r_real - r >= 0.5) + r++; + } + + if (lua_gettop(L) >= 4) + pencolor_set(col); + + draw_circfill(x, y, r, col, fillp); + + return 0; +} + +// clip(x, y, w, h) +int clip(lua_State *L) +{ + int prev_x0, prev_y0, prev_x1, prev_y1; + clip_get(&prev_x0, &prev_y0, &prev_x1, &prev_y1); + + if (lua_gettop(L) == 0) + clip_set(0, 0, P8_WIDTH, P8_HEIGHT); + else + { + int x0 = lua_tointeger(L, 1); + int y0 = lua_tointeger(L, 2); + int w = lua_tointeger(L, 3); + int h = lua_tointeger(L, 4); + bool clip_previous = lua_gettop(L) >= 5 ? lua_toboolean(L, 5) : false; + + int clamp_x0 = 0, clamp_y0 = 0, clamp_x1 = P8_WIDTH, clamp_y1 = P8_HEIGHT; + if (clip_previous) { clamp_x0 = prev_x0; clamp_y0 = prev_y0; clamp_x1 = prev_x1; clamp_y1 = prev_y1; } + + int x1 = x0 + w; + int y1 = y0 + h; + x0 = MAX(x0, clamp_x0); + y0 = MAX(y0, clamp_y0); + x1 = MIN(x1, clamp_x1); + y1 = MIN(y1, clamp_y1); + + clip_set(x0, y0, x1-x0, y1-y0); + } + + lua_pushinteger(L, prev_x0); + lua_pushinteger(L, prev_y0); + lua_pushinteger(L, prev_x1 - prev_x0); + lua_pushinteger(L, prev_y1 - prev_y0); + return 4; +} + +// cls([color]) +int cls(lua_State *L) +{ + int color = lua_gettop(L) == 1 ? lua_tointeger(L, -1) : 0; + + clear_screen(color); + + return 0; +} + +// color(col) +int color(lua_State *L) +{ + int prev = pencolor_get(); + int col = lua_gettop(L) == 1 ? lua_tointeger(L, 1) : 6; + + pencolor_set(col); + + lua_pushinteger(L, prev); + return 1; +} + +// cursor([x,] [y,] [col]) +int cursor(lua_State *L) +{ + int prev_x, prev_y; + cursor_get(&prev_x, &prev_y); + + int x = lua_gettop(L) >= 1 ? lua_tointeger(L, 1) : 0; + int y = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0; + int color = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : -1; + + cursor_set(x, y, (color == -1) ? -1 : color); + left_margin_set(x); + + lua_pushinteger(L, prev_x); + lua_pushinteger(L, prev_y); + return 2; +} + +// fget(n, [f]) +int fget(lua_State *L) +{ + int n = lua_tointeger(L, 1); + uint8_t flags = m_memory[MEMORY_SPRITEFLAGS + n]; + + if (lua_gettop(L) == 2) + { + int f = lua_tointeger(L, 2); + lua_pushboolean(L, (flags & (1 << f)) != 0); + } + else + { + lua_pushinteger(L, flags); + } + + return 1; +} + +// fillp([pat]) +int fillp(lua_State *L) +{ + if (lua_gettop(L) == 0) { + m_memory[MEMORY_FILLP] = 0; + m_memory[MEMORY_FILLP + 1] = 0; + m_memory[MEMORY_FILLP_ATTR] = 0; + } else { + uint32_t n = fix32_bits(lua_tonumber(L, 1)); + m_memory[MEMORY_FILLP] = (n >> 16) & 0xff; + m_memory[MEMORY_FILLP + 1] = (n >> 24) & 0xff; + m_memory[MEMORY_FILLP_ATTR] = ((n & 0x8000) ? 1 : 0) | ((n & 0x4000) ? 2 : 0) | ((n & 0x2000) ? 4: 0); + + } + return 0; +} + +// flip() +int flip(lua_State *L) +{ + p8_flip(); + + return 0; +} + +int holdframe(lua_State *L) +{ + (void)L; + return 0; +} + +int _update_buttons(lua_State *L) +{ + (void)L; + p8_update_input(); + return 0; +} + +// fset(n, [f,] v) +int fset(lua_State *L) +{ + int n = lua_tointeger(L, 1); + assert(n >= 0 && n <= 255); + + if (lua_gettop(L) == 3) + { + int f = lua_tointeger(L, 2); + bool v = lua_toboolean(L, 3); + assert(f >= 0 && f <= 7); + + if (v) + m_memory[MEMORY_SPRITEFLAGS + n] |= (1 << f); + else + m_memory[MEMORY_SPRITEFLAGS + n] &= ~(1 << f); + } + else + { + int f = lua_tointeger(L, 2); + assert(f >= 0 && f <= 255); + m_memory[MEMORY_SPRITEFLAGS + n] = f; + } + + return 0; +} + +// line([x0,] [y0,] x1, y1, [col]) +int line(lua_State *L) +{ + int x0, y0, x1, y1, col, fillp, valid; + + if (lua_gettop(L) == 0) { + m_memory[MEMORY_LINE_VALID] = 1; + } else { + if (lua_gettop(L) >= 4) { + valid = 1; + x0 = lua_tointeger(L, 1); + y0 = lua_tointeger(L, 2); + x1 = lua_tointeger(L, 3); + y1 = lua_tointeger(L, 4); + col = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : pencolor_get(); + fillp = lua_gettop(L) >= 5 ? (fix32_bits(lua_tonumber(L, 5)) & 0xffff) : 0; + if (lua_gettop(L) >= 5) + pencolor_set(col); + } else { + valid = !m_memory[MEMORY_LINE_VALID]; + x0 = m_memory[MEMORY_LINE_X] | (m_memory[MEMORY_LINE_X + 1] << 8); + y0 = m_memory[MEMORY_LINE_Y] | (m_memory[MEMORY_LINE_Y + 1] << 8); + x1 = lua_tointeger(L, 1); + y1 = lua_tointeger(L, 2); + col = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : pencolor_get(); + fillp = lua_gettop(L) >= 3 ? (fix32_bits(lua_tonumber(L, 3)) & 0xffff) : 0; + if (lua_gettop(L) >= 3) + pencolor_set(col); + } + + if (valid) + draw_line(x0, y0, x1, y1, col, fillp); + + m_memory[MEMORY_LINE_X] = x1 & 0xff; + m_memory[MEMORY_LINE_X + 1] = (x1 >> 8) & 0xff; + m_memory[MEMORY_LINE_Y] = y1 & 0xff; + m_memory[MEMORY_LINE_Y + 1] = (y1 >> 8) & 0xff; + m_memory[MEMORY_LINE_VALID] = 0; + } + + return 0; +} + +// oval(x0, y0, x1, y1, [col]) +int oval(lua_State *L) +{ + int x0 = lua_tointeger(L, 1); + int y0 = lua_tointeger(L, 2); + int x1 = lua_tointeger(L, 3); + int y1 = lua_tointeger(L, 4); + int col = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : pencolor_get(); + int fillp = lua_gettop(L) >= 5 ? (fix32_bits(lua_tonumber(L, 5)) & 0xffff) : 0; + + if (lua_gettop(L) >= 5) + pencolor_set(col); + + draw_oval(x0, y0, x1, y1, col, fillp); + + return 0; +} + +// ovalfill(x0, y0, x1, y1, [col]) +int ovalfill(lua_State *L) +{ + int x0 = lua_tointeger(L, 1); + int y0 = lua_tointeger(L, 2); + int x1 = lua_tointeger(L, 3); + int y1 = lua_tointeger(L, 4); + int col = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : pencolor_get(); + int fillp = lua_gettop(L) >= 5 ? (fix32_bits(lua_tonumber(L, 5)) & 0xffff) : 0; + + if (lua_gettop(L) >= 5) + pencolor_set(col); + + draw_ovalfill(x0, y0, x1, y1, col, fillp); + + return 0; +} + +// pal(c0, c1, [p]) +// pal(tbl, [p]) +int pal(lua_State *L) +{ + if (lua_gettop(L) == 0) + { + reset_color(); + } + else if (lua_istable(L, 1)) + { + int p = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : PALTYPE_DRAW; + lua_pushnil(L); + while (lua_next(L, 1)) + { + int c0 = lua_tointeger(L, -2); + int c1 = lua_tointeger(L, -1); + uint8_t new_val; + if (p == PALTYPE_DRAW) { + uint8_t old_val = color_get(p, c0); + new_val = (c1 & 0xf) | (old_val & 0xf0); + } else { + new_val = c1 & 0xff; + } + color_set(p, c0, new_val); + lua_pop(L, 1); + } + lua_pop(L, 1); + } + else if (lua_gettop(L) == 1) + { + int p = lua_tointeger(L, 1); + if (p == PALTYPE_DRAW) { + for (int i=0;i<16;++i) + color_set(PALTYPE_DRAW, i, i == 0 ? i | 0x10 : i); + } else if (p == PALTYPE_SCREEN) { + for (int i=0;i<16;++i) + color_set(PALTYPE_SCREEN, i, i); + } else if (p == PALTYPE_SECONDARY) { + color_set(PALTYPE_SECONDARY, 0, 0x00); + color_set(PALTYPE_SECONDARY, 1, 0x01); + color_set(PALTYPE_SECONDARY, 2, 0x12); + color_set(PALTYPE_SECONDARY, 3, 0x13); + color_set(PALTYPE_SECONDARY, 4, 0x24); + color_set(PALTYPE_SECONDARY, 5, 0x15); + color_set(PALTYPE_SECONDARY, 6, 0xd6); + color_set(PALTYPE_SECONDARY, 7, 0x67); + color_set(PALTYPE_SECONDARY, 8, 0x48); + color_set(PALTYPE_SECONDARY, 9, 0x49); + color_set(PALTYPE_SECONDARY, 10, 0x9a); + color_set(PALTYPE_SECONDARY, 11, 0x3b); + color_set(PALTYPE_SECONDARY, 12, 0xdc); + color_set(PALTYPE_SECONDARY, 13, 0x5d); + color_set(PALTYPE_SECONDARY, 14, 0x8e); + color_set(PALTYPE_SECONDARY, 15, 0xef); + } + } + else + { + int c0 = lua_tointeger(L, 1); + int c1 = lua_tointeger(L, 2); + int p = lua_gettop(L) == 3 ? lua_tointeger(L, 3) : PALTYPE_DRAW; + + uint8_t old_val = color_get(p, c0); + uint8_t new_val; + if (p == PALTYPE_DRAW) { + new_val = (c1 & 0xf) | (old_val & 0xf0); + } else { + new_val = c1 & 0xff; + } + color_set(p, c0, new_val); + + // Return the old mapped color for this slot + lua_pushinteger(L, old_val & 0xf); + return 1; + } + + return 0; +} + +// palt([col,] [t]) +int palt(lua_State *L) +{ + if (lua_gettop(L) == 0) + { + for (int col=0;col<16;++col) { + uint8_t c = color_get(PALTYPE_DRAW, col); + color_set(PALTYPE_DRAW, col, col == 0 ? (c | 0x10) : (c & 0xf)); + } + } + else if (lua_gettop(L) == 1) + { + int b = lua_tounsigned(L, 1); + for (int col=0;col<16;++col) { + int t = (b >> (15-col)) & 1; + uint8_t c = color_get(PALTYPE_DRAW, col); + + color_set(PALTYPE_DRAW, col, t ? (c | 0x10) : (c & 0xF)); + } + } + else + { + int col = lua_tointeger(L, 1); + int t = lua_toboolean(L, 2); + uint8_t c = color_get(PALTYPE_DRAW, col); + bool prev_transparent = (c & 0x10) != 0; + + color_set(PALTYPE_DRAW, col, t ? (c | 0x10) : (c & 0xF)); + + lua_pushboolean(L, prev_transparent); + return 1; + } + + return 0; +} + +// pget(x, y) +int pget(lua_State *L) +{ + int x = lua_tointeger(L, 1); + int y = lua_tointeger(L, 2); + + int x0, y0, x1, y1; + clip_get(&x0, &y0, &x1, &y1); + + if (x >= x0 && y >= y0 && x < x1 && y < y1) { + lua_pushinteger(L, gfx_get(x, y, MEMORY_SCREEN, MEMORY_SCREEN_SIZE)); + } else { + int default_val = (m_memory[MEMORY_MISCFLAGS] & 0x10) ? m_memory[MEMORY_PGET_DEFAULT] : 0; + lua_pushinteger(L, default_val); + } + + return 1; +} + +// print(str, [x,] [y,] [col]) +int print(lua_State *L) +{ + size_t len = 0; + const char *str = lua_gettop(L) >= 1 ? lua_tolstring(L, 1, &len) : NULL; + if (!str) { str = ""; len = 0; } + int right; + + if (lua_gettop(L) <= 2) + { + int x, y; + cursor_get(&x, &y); + int col = lua_gettop(L) == 2 ? lua_tointeger(L, 2) : pencolor_get(); + if (lua_gettop(L) == 2) + pencolor_set(col); + draw_text(str, len, x, y, col, left_margin_get(), false, &x, &y, &right); + cursor_set(x, y, -1); + } + else + { + int x = lua_tointeger(L, 2); + int y = lua_tointeger(L, 3); + int col = lua_gettop(L) >= 4 ? lua_tointeger(L, 4) : pencolor_get(); + if (lua_gettop(L) >= 4) + pencolor_set(col); + left_margin_set(x); + draw_text(str, len, x, y, col, x, true, &x, &y, &right); + cursor_set(x, y, -1); + } + + lua_pushinteger(L, right); + return 1; +} + +// pset(x, y, [c]) +int pset(lua_State *L) +{ + int x = lua_tointeger(L, 1); + int y = lua_tointeger(L, 2); + int c = lua_gettop(L) == 3 ? lua_tointeger(L, 3) : pencolor_get(); + int fillp = lua_gettop(L) >= 3 ? (fix32_bits(lua_tonumber(L, 3)) & 0xffff) : 0; + if (lua_gettop(L) == 3) + pencolor_set(c); + pixel_set(x, y, c, fillp, DRAWTYPE_GRAPHIC); + + return 0; +} + +// rect(x0, y0, x1, y1, [col]) +int rect(lua_State *L) +{ + int x0 = lua_tointeger(L, 1); + int y0 = lua_tointeger(L, 2); + int x1 = lua_tointeger(L, 3); + int y1 = lua_tointeger(L, 4); + int col = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : pencolor_get(); + int fillp = lua_gettop(L) >= 5 ? (fix32_bits(lua_tonumber(L, 5)) & 0xffff) : 0; + + int left = MIN(x0, x1); + int top = MIN(y0, y1); + int right = MAX(x0, x1); + int bottom = MAX(y0, y1); + + if (lua_gettop(L) >= 5) + pencolor_set(col); + + draw_rect(left, top, right, bottom, col, fillp); + + return 0; +} + +// rectfill(x0, y0, x1, y1, [col]) +int rectfill(lua_State *L) +{ + int x0 = lua_tointeger(L, 1); + int y0 = lua_tointeger(L, 2); + int x1 = lua_tointeger(L, 3); + int y1 = lua_tointeger(L, 4); + int col = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : pencolor_get(); + int fillp = lua_gettop(L) >= 5 ? (fix32_bits(lua_tonumber(L, 5)) & 0xffff) : 0; + + int left = MIN(x0, x1); + int top = MIN(y0, y1); + int right = MAX(x0, x1); + int bottom = MAX(y0, y1); + + if (lua_gettop(L) >= 5) + pencolor_set(col); + + draw_rectfill(left, top, right, bottom, col, fillp); + + return 0; +} + +// rrect(x, y, w, h, r, [col]) +int rrect(lua_State *L) +{ + int left = lua_tointeger(L, 1); + int top = lua_tointeger(L, 2); + int w = lua_tointeger(L, 3); + int h = lua_tointeger(L, 4); + int r = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : 0; + int col = lua_gettop(L) >= 6 ? lua_tointeger(L, 6) : pencolor_get(); + int fillp = lua_gettop(L) >= 6 ? (fix32_bits(lua_tonumber(L, 6)) & 0xffff) : 0; + + if (lua_gettop(L) >= 6) + pencolor_set(col); + + int right = left + w-1; + int bottom = top + h-1; + r = MAX(0, MIN(r, MIN(w, h) / 2)); + + if (is_bbox_offscreen(left, top, right, bottom)) return 0; + + draw_hline(left+r, top, right-r, col, fillp); + draw_hline(left+r, bottom, right-r, col, fillp); + draw_vline(left, top+r, bottom-r, col, fillp); + draw_vline(right, top+r, bottom-r, col, fillp); + draw_circ_mask(left+r, top+r, r, col, fillp, 1 << 3 | 1 << 7); + draw_circ_mask(right-r, top+r, r, col, fillp, 1 << 2 | 1 << 6); + draw_circ_mask(left+r, bottom-r, r, col, fillp, 1 << 1 | 1 << 5); + draw_circ_mask(right-r, bottom-r, r, col, fillp, 1 << 0 | 1 << 4); + + return 0; +} + +// rrectfill(x, y, w, h, r, [col]) +int rrectfill(lua_State *L) +{ + int left = lua_tointeger(L, 1); + int top = lua_tointeger(L, 2); + int w = lua_tointeger(L, 3); + int h = lua_tointeger(L, 4); + int r = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : 0; + int col = lua_gettop(L) >= 6 ? lua_tointeger(L, 6) : pencolor_get(); + int fillp = lua_gettop(L) >= 6 ? (fix32_bits(lua_tonumber(L, 6)) & 0xffff) : 0; + bool invert = fillp_invert_enabled(col); + + if (lua_gettop(L) >= 6) + pencolor_set(col); + + int right = left + w; + int bottom = top + h; + r = MAX(0, MIN(r, MIN(w, h) / 2)); + + if (!invert && is_bbox_offscreen(left, top, right, bottom)) return 0; + + if (invert) { + int cx, cy; + camera_get(&cx, &cy); + int clip_x0, clip_y0, clip_x1, clip_y1; + clip_get(&clip_x0, &clip_y0, &clip_x1, &clip_y1); + for (int y = clip_y0; y < clip_y1; y++) { + for (int x = clip_x0; x < clip_x1; x++) { + int wx = x + cx; + int wy = y + cy; + if (!point_in_round_rect(wx, wy, left, top, right, bottom, r)) + pixel_set(wx, wy, col, fillp, DRAWTYPE_GRAPHIC); + } + } + return 0; + } + + draw_rectfill(left, top+r, right, bottom-r, col, fillp); + draw_rectfill(left+r, top, right-r, top+r, col, fillp); + draw_rectfill(left+r, bottom-r, right-r, bottom, col, fillp); + draw_circfill_mask(left+r, top+r, r, col, fillp, 1 << 3 | 1 << 7); + draw_circfill_mask(right-r, top+r, r, col, fillp, 1 << 2 | 1 << 6); + draw_circfill_mask(left+r, bottom-r, r, col, fillp, 1 << 1 | 1 << 5); + draw_circfill_mask(right-r, bottom-r, r, col, fillp, 1 << 0 | 1 << 4); + + return 0; +} + +// sget(x, y) +int sget(lua_State *L) +{ + int x = lua_tointeger(L, 1); + int y = lua_tointeger(L, 2); + + if (x >= 0 && y >= 0 && x < P8_WIDTH && y < P8_HEIGHT) { + lua_pushinteger(L, gfx_get(x, y, MEMORY_SPRITES, MEMORY_SPRITES_SIZE)); + } else { + int default_val = (m_memory[MEMORY_MISCFLAGS] & 0x10) ? m_memory[MEMORY_SGET_DEFAULT] : 0; + lua_pushinteger(L, default_val); + } + + return 1; +} + +// spr(n, x, y, [w,] [h,] [flip_x,] [flip_y]) +int spr(lua_State *L) +{ + int n = lua_tointeger(L, 1); + int x = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0; + int y = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : 0; + bool flip_x = false, flip_y = false; + + if (lua_gettop(L) > 3) + { + assert(lua_gettop(L) >= 5); + + lua_Number w_raw = lua_tonumber(L, 4); + lua_Number h_raw = lua_tonumber(L, 5); + + if (lua_gettop(L) >= 6) + flip_x = lua_toboolean(L, 6); + + if (lua_gettop(L) >= 7) + flip_y = lua_toboolean(L, 7); + + // fix32 stores integers with no fractional bits (lower 16 bits == 0) + if ((w_raw & 0xFFFF) == 0 && (h_raw & 0xFFFF) == 0) + { + // Integer w/h: draw a w x h grid of sprites (standard path) + int w = fix32_to_int(w_raw); + int h = fix32_to_int(h_raw); + draw_sprites(n, x, y, w, h, flip_x, flip_y); + } + else + { + // Fractional w/h: compute pixel dimensions and draw at 1:1 scale + int sw = (int)(fix32_to_double(w_raw) * SPRITE_WIDTH + 0.5); + int sh = (int)(fix32_to_double(h_raw) * SPRITE_HEIGHT + 0.5); + int ssx = (n & 0xF) * SPRITE_WIDTH; + int ssy = (n >> 4) * SPRITE_HEIGHT; + draw_scaled_sprite(ssx, ssy, sw, sh, x, y, 1.0f, 1.0f, flip_x, flip_y); + } + } + else + { + draw_sprites(n, x, y, 1, 1, flip_x, flip_y); + } + + return 0; +} + +// sset(x, y, [c]) +int sset(lua_State *L) +{ + int x = lua_tointeger(L, 1); + int y = lua_tointeger(L, 2); + int c = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : pencolor_get(); + + if (lua_gettop(L) >= 3) + pencolor_set(c); + if (x >= 0 && y >= 0 && x < P8_WIDTH && y < P8_HEIGHT) + gfx_set(x, y, MEMORY_SPRITES, MEMORY_SPRITES_SIZE, c); + + return 0; +} + +// sspr(sx, sy, sw, sh, dx, dy, [dw,] [dh,] [flip_x,] [flip_y]) +int sspr(lua_State *L) +{ + int sx = lua_tointeger(L, 1); + int sy = lua_tointeger(L, 2); + int sw = lua_tointeger(L, 3); + int sh = lua_tointeger(L, 4); + int dx = lua_tointeger(L, 5); + int dy = lua_tointeger(L, 6); + int dw = lua_to_or_default(L, integer, 7, sw); + int dh = lua_to_or_default(L, integer, 8, sh); + bool flip_x = lua_to_or_default(L, boolean, 9, false); + bool flip_y = lua_to_or_default(L, boolean, 10, false); + float scale_x = (float)dw / sw; + float scale_y = (float)dh / sh; + + draw_scaled_sprite(sx, sy, sw, sh, dx, dy, scale_x, scale_y, flip_x, flip_y); + + return 0; +} + +// tline( x0, y0, x1, y1, mx, my, [mdx,] [mdy]) +// tline( precision ) +int tline(lua_State *L) +{ + if (lua_gettop(L) == 1) { + m_tline_precision = lua_tointeger(L, 1); + return 0; + } + + int x0 = lua_tointeger(L, 1); + int y0 = lua_tointeger(L, 2); + int x1 = lua_tointeger(L, 3); + int y1 = lua_tointeger(L, 4); + lua_Number mx = lua_tonumber(L, 5); + lua_Number my = lua_tonumber(L, 6); + lua_Number mdx = lua_to_or_default(L, number, 7, fix32_div(fix32_from_int(1), fix32_from_int(8))); + lua_Number mdy = lua_to_or_default(L, number, 8, fix32_from_int(0)); + int layer = lua_to_or_default(L, integer, 9, 0); + + int cx, cy; + camera_get(&cx, &cy); + int clip_x0, clip_y0, clip_x1, clip_y1; + clip_get(&clip_x0, &clip_y0, &clip_x1, &clip_y1); + + uint8_t map_start = m_memory[MEMORY_MAP_START]; + bool map_invalid = (map_start >= 0x10 && map_start < 0x20) || + (map_start >= 0x30 && map_start < 0x3f); + uint8_t map_start_upper = map_start; + uint8_t map_start_lower = map_start; + if (!map_invalid) { + if (map_start < 0x10 || (map_start >= 0x40 && map_start < 0x80)) + map_start_upper = 0x20; + else + map_start_upper = map_start; + map_start_lower = (map_start_upper < 0x80) ? 0x10 : map_start_upper; + } + int map_width = m_memory[MEMORY_MAP_WIDTH]; + if (map_width == 0) map_width = 256; + + int sprite_base = m_memory[MEMORY_SPRITE_PHYS] << 8; + int screen_base = m_memory[MEMORY_SCREEN_PHYS] << 8; + + int offset_x = m_memory[MEMORY_TLINE_OFFSET_X] * 8; + int offset_y = m_memory[MEMORY_TLINE_OFFSET_Y] * 8; + int precision = m_tline_precision; + + uint32_t mask_x_bits = ((uint32_t)m_memory[MEMORY_TLINE_MASK_X] << (precision + 3)) - 1; + uint32_t mask_y_bits = ((uint32_t)m_memory[MEMORY_TLINE_MASK_Y] << (precision + 3)) - 1; + + uint32_t mx_bits = fix32_bits(mx); + uint32_t my_bits = fix32_bits(my); + uint32_t mdx_bits = fix32_bits(mdx); + uint32_t mdy_bits = fix32_bits(mdy); + + int dx = abs(x1 - x0); + int sx = x0 < x1 ? 1 : -1; + int dy = -abs(y1 - y0); + int sy = y0 < y1 ? 1 : -1; + int err = dx + dy; + + uint8_t *draw_pal = &m_memory[MEMORY_PALETTES + PALTYPE_DRAW * 16]; + uint8_t *sprite_flags_base = &m_memory[MEMORY_SPRITEFLAGS]; + bool sprite_0_opaque = (m_memory[MEMORY_MISCFLAGS] & 0x8) != 0; + uint8_t rw_mask = m_memory[MEMORY_RW_MASK]; + + while (true) + { + uint32_t tmx = mx_bits & mask_x_bits; + uint32_t tmy = my_bits & mask_y_bits; + + int tx_raw = ((int32_t)tmx) >> precision; + int ty_raw = ((int32_t)tmy) >> precision; + int tx = tx_raw + offset_x; + int ty = ty_raw + offset_y; + + int celx = tx >> 3; + int cely = ty >> 3; + int index = 0; + // Bounds check uses pre-offset coordinates (PICO-8 behaviour: offset doesn't + // make a negative texture coordinate valid for map lookup). + if (!map_invalid && (tx_raw >> 3) >= 0 && (ty_raw >> 3) >= 0) { + uint8_t ms = (cely >= 32 && map_start_upper < 0x80) ? map_start_lower : map_start_upper; + int adj_cely = (cely >= 32 && map_start_upper < 0x80) ? cely - 32 : cely; + int address = (ms << 8) + celx + adj_cely * map_width; + if (address >= 0x1000 && address < 0x10000 && + !(address >= 0x3000 && address < 0x8000)) + index = m_memory[address]; + } + if ((index != 0 || sprite_0_opaque) && (layer == 0 || ((layer & sprite_flags_base[index]) == layer))) { + int spx = (index & 0xF) * 8 + (tx & 7); + int spy = (index >> 4) * 8 + (ty & 7); + + int spr_offset = sprite_base + (spx >> 1) + spy * 64; + uint8_t col = IS_EVEN(spx) ? m_memory[spr_offset] & 0xF : m_memory[spr_offset] >> 4; + + uint8_t mapped = draw_pal[col & 0xf]; + int px = x0 - cx; + int py = y0 - cy; + if ((mapped & 0xf0) == 0) { + if (px >= clip_x0 && px < clip_x1 && py >= clip_y0 && py < clip_y1) { + int scr_offset = screen_base + (px >> 1) + py * 64; + if (rw_mask != 0xff) { + uint8_t write_mask = rw_mask & 0xf; + uint8_t read_mask = (rw_mask >> 4) & 0xf; + uint8_t dst = IS_EVEN(px) ? m_memory[scr_offset] & 0xf : m_memory[scr_offset] >> 4; + uint8_t src = mapped & 0xf; + uint8_t result = (dst & ~write_mask) | (src & write_mask & read_mask); + m_memory[scr_offset] = IS_EVEN(px) + ? (m_memory[scr_offset] & 0xF0) | result + : (result << 4) | (m_memory[scr_offset] & 0xF); + } else { + m_memory[scr_offset] = IS_EVEN(px) + ? (m_memory[scr_offset] & 0xF0) | (mapped & 0xF) + : (mapped << 4) | (m_memory[scr_offset] & 0xF); + } + } + } + } + + if (x0 == x1 && y0 == y1) + break; + + int e2 = 2 * err; + + if (e2 >= dy) + { + err += dy; + x0 += sx; + } + + if (e2 <= dx) + { + err += dx; + y0 += sy; + } + + mx_bits += mdx_bits; + my_bits += mdy_bits; + } + + return 0; +} + +// **************************************************************** +// *** Tables *** +// **************************************************************** + +// add(tbl, v) +// all(tbl) +// count(tbl) +// del(tbl, v) +// foreach(tbl, func) +// pairs(tbl) + +// **************************************************************** +// *** Input *** +// **************************************************************** + +// btn([i,] [p]) +int btn(lua_State *L) +{ + // button + if (lua_gettop(L) >= 1) + { + int i = lua_tointeger(L, 1); + int p = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0; + + if (i < BUTTON_COUNT && p < PLAYER_COUNT) + lua_pushboolean(L, is_button_set(p, i, false)); + else + lua_pushboolean(L, false); + } + // mask + else + { + lua_pushinteger(L, (m_buttons[0] & 0xff) | ((m_buttons[1] & 0xff) << 8)); + } + + return 1; +} + +// btnp([i,] [p]) +int btnp(lua_State *L) +{ + // button + if (lua_gettop(L) >= 1) + { + int i = lua_tointeger(L, 1); + int p = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0; + + if (i < BUTTON_COUNT && p < PLAYER_COUNT) + lua_pushboolean(L, is_button_set(p, i, true)); + else + lua_pushboolean(L, false); + } + // mask + else + { + lua_pushinteger(L, (m_buttonsp[0] & 0xff) | ((m_buttons[1] & 0xff) << 8)); + } + + return 1; +} + +// **************************************************************** +// *** Sound *** +// **************************************************************** + +// music(n, [fadems,] [channelmask]) +int music(lua_State *L) +{ +#ifdef ENABLE_AUDIO + int prev = audio_stat(54); // stat(54) = current music pattern, -1 if none + + int n = lua_tointeger(L, 1); + int fadems = lua_to_or_default(L, integer, 2, 1); + int channelmask = lua_to_or_default(L, integer, 3, 0); + + audio_music(n, fadems, channelmask); + + lua_pushinteger(L, prev); + return 1; +#else + lua_pushinteger(L, -1); + return 1; +#endif +} + +// sfx(n, [channel,] [offset,] [length]) +int sfx(lua_State *L) +{ +#ifdef ENABLE_AUDIO + int n = lua_tointeger(L, 1); + int channel = lua_to_or_default(L, integer, 2, -1); + int offset = lua_to_or_default(L, integer, 3, 0); + int length = lua_to_or_default(L, integer, 4, 32 - offset); + + audio_sound(n, channel, offset, length); +#endif + + return 0; +} + +// **************************************************************** +// *** Map *** +// **************************************************************** + +static void map_get_visible_cells(int sx, int sy, int celw, int celh, + int *start_x, int *start_y, int *end_x, int *end_y) +{ + int cam_x, cam_y; + camera_get(&cam_x, &cam_y); + + int clip_x0, clip_y0, clip_x1, clip_y1; + clip_get(&clip_x0, &clip_y0, &clip_x1, &clip_y1); + + int screen_x0 = cam_x + clip_x0; + int screen_y0 = cam_y + clip_y0; + int screen_x1 = cam_x + clip_x1; + int screen_y1 = cam_y + clip_y1; + + int visible_x0 = (screen_x0 - sx) / SPRITE_WIDTH; + int visible_y0 = (screen_y0 - sy) / SPRITE_HEIGHT; + int visible_x1 = (screen_x1 - sx + SPRITE_WIDTH - 1) / SPRITE_WIDTH; + int visible_y1 = (screen_y1 - sy + SPRITE_HEIGHT - 1) / SPRITE_HEIGHT; + + *start_x = MAX(0, visible_x0); + *start_y = MAX(0, visible_y0); + *end_x = MIN(celw, visible_x1); + *end_y = MIN(celh, visible_y1); +} + +// map(celx, cely, sx, sy, celw, celh, [layer]) +int map(lua_State *L) +{ + int default_celw = m_memory[MEMORY_MAP_WIDTH]; + if (default_celw == 0) + default_celw = 128; + int map_start = m_memory[MEMORY_MAP_START]; + int max_map_cells = (map_start >= 0x80) ? (0x10000 - (map_start << 8)) : 0x2000; + int default_celh = (default_celw > 0) ? (max_map_cells / default_celw) : 64; + + int celx = lua_gettop(L) >= 1 ? lua_tointeger(L, 1) : 0; + int cely = lua_gettop(L) >= 2 ? lua_tointeger(L, 2) : 0; + int sx = lua_gettop(L) >= 3 ? lua_tointeger(L, 3) : 0; + int sy = lua_gettop(L) >= 4 ? lua_tointeger(L, 4) : 0; + int celw = lua_gettop(L) >= 5 ? lua_tointeger(L, 5) : default_celw; + int celh = lua_gettop(L) >= 6 ? lua_tointeger(L, 6) : default_celh; + int layer = lua_gettop(L) >= 7 ? lua_tointeger(L, 7) : 0; + + int start_x, start_y, end_x, end_y; + map_get_visible_cells(sx, sy, celw, celh, &start_x, &start_y, &end_x, &end_y); + + for (int y = start_y; y < end_y; y++) + { + for (int x = start_x; x < end_x; x++) + { + uint8_t index = map_get(celx + x, cely + y); + uint8_t sprite_flags = m_memory[MEMORY_SPRITEFLAGS + index]; + bool sprite_0_opaque = (m_memory[MEMORY_MISCFLAGS] & 0x8) != 0; + bool should_draw = (index != 0 || sprite_0_opaque) && (layer == 0 || ((layer & sprite_flags) == layer)); + + if (should_draw) + { + int left = sx + x * SPRITE_WIDTH; + int top = sy + y * SPRITE_HEIGHT; + draw_sprite(index, left, top, false, false); + } + } + } + + return 0; +} + +// mget(celx, cely) +int mget(lua_State *L) +{ + int celx = lua_tointeger(L, 1); + int cely = lua_tointeger(L, 2); + + int address = map_cell_addr(celx, cely); + if (address == 0) { + int default_val = (m_memory[MEMORY_MISCFLAGS] & 0x10) ? m_memory[MEMORY_MGET_DEFAULT] : 0; + lua_pushinteger(L, default_val); + } else { + lua_pushinteger(L, m_memory[address]); + } + + return 1; +} + +// mset(celx, cely, snum) +int mset(lua_State *L) +{ + int celx = lua_tointeger(L, 1); + int cely = lua_tointeger(L, 2); + int snum = lua_tointeger(L, 3); + + map_set(celx, cely, snum); + + return 0; +} + +// **************************************************************** +// *** Memory *** +// **************************************************************** + +// cstore(destaddr, sourceaddr, len, [filename]) +int cstore(lua_State *L) +{ + int nargs = lua_gettop(L); + unsigned destaddr = nargs >= 1 ? lua_tounsigned(L, 1) : 0; + unsigned srcaddr = nargs >= 2 ? lua_tounsigned(L, 2) : 0; + unsigned len = nargs >= 3 ? lua_tounsigned(L, 3) : CART_MEMORY_SIZE; + const char *file_name = nargs >= 4 ? lua_tostring(L, 4) : NULL; + + if (destaddr + len > CART_MEMORY_SIZE || srcaddr + len > (1 << 16)) { + lua_pushinteger(L, 0); + return 1; + } + + char resolved_path[PATH_MAX]; + if (file_name != NULL) { + // Append .p8 if no extension given + char full_filename[PATH_MAX]; + if (strstr(file_name, ".p8") == NULL && strstr(file_name, ".P8") == NULL) { + snprintf(full_filename, sizeof(full_filename), "%s.p8", file_name); + file_name = full_filename; + } + if (p8_resolve_relative_path(resolved_path, file_name, sizeof(resolved_path), true) < 0) { + lua_pushinteger(L, 0); + return 1; + } + } else { + if (!m_current_cart_file_name[0]) { + lua_pushinteger(L, 0); + return 1; + } + strtcpy(resolved_path, m_current_cart_file_name, sizeof(resolved_path)); + } + + // Refuse to write .p8.png (not supported) + size_t rlen = strlen(resolved_path); + if (rlen >= 7 && strcmp(resolved_path + rlen - 7, ".p8.png") == 0) { + fprintf(stderr, "cstore: .p8.png output is not supported\n"); + lua_pushinteger(L, 0); + return 1; + } + + p8_show_io_icon(true); + + int ret = MKDIR(DEFAULT_CARTS_PATH); + if (ret == -1 && errno != EEXIST) { + fprintf(stderr, "cstore: failed to create carts directory: %s\n", strerror(errno)); + p8_show_io_icon(false); + lua_pushinteger(L, 0); + return 1; + } + + memset(m_temp_cart_memory, 0, CART_MEMORY_SIZE); + m_temp_lua_script[0] = '\0'; + if (access(resolved_path, F_OK) == -1) { + if (errno != ENOENT) { + fprintf(stderr, "cstore: failed to access existing cart: %s\n", strerror(errno)); + p8_show_io_icon(false); + lua_pushinteger(L, 0); + return 1; + } + } else if (parse_cart_file(resolved_path, m_temp_cart_memory, m_file_buffer, m_decompression_buffer, m_temp_lua_script, NULL) != 0) { + fprintf(stderr, "cstore: failed to read existing cart\n"); + p8_show_io_icon(false); + lua_pushinteger(L, 0); + return 1; + } + + // Patch the requested region from runtime memory + memcpy(m_temp_cart_memory + destaddr, m_memory + srcaddr, len); + + // Also update m_cart_memory when writing to the current cart + if (nargs < 4 || lua_isnil(L, 4)) + memcpy(m_cart_memory + destaddr, m_memory + srcaddr, len); + + write_cart_p8(resolved_path, m_temp_lua_script, m_temp_cart_memory); + + p8_show_io_icon(false); + lua_pushinteger(L, len); + return 1; +} + +// memcpy(destaddr, sourceaddr, len) +int _memcpy(lua_State *L) +{ + unsigned destaddr = lua_tounsigned(L, 1); + unsigned orig_destaddr = destaddr; + unsigned sourceaddr = lua_tounsigned(L, 2); + unsigned len = lua_tounsigned(L, 3); + + if (len < 1 || destaddr == sourceaddr) + { + lua_pushinteger(L, orig_destaddr); + return 1; + } + + if (sourceaddr < 0 || (sourceaddr + len) > (1 << 16)) + { + lua_pushinteger(L, orig_destaddr); + return 1; + } + + if (destaddr < 0 || (destaddr + len) > (1 << 16)) + { + lua_pushinteger(L, orig_destaddr); + return 1; + } + + while (len > 0) { + unsigned chunk = MIN(MIN(len, 0x2000 - (sourceaddr & 0x1fff)), 0x2000 - (destaddr & 0x1fff)); + unsigned destaddr1 = addr_remap(destaddr); + unsigned sourceaddr1 = addr_remap(sourceaddr); + memmove(m_memory + destaddr1, m_memory + sourceaddr1, chunk); + destaddr += chunk; + sourceaddr += chunk; + len -= chunk; + } + + lua_pushinteger(L, orig_destaddr); + return 1; +} + +// memset(destaddr, val, len) +int _memset(lua_State *L) +{ + unsigned destaddr = lua_tounsigned(L, 1); + int val = lua_tointeger(L, 2); + unsigned len = lua_tounsigned(L, 3); + + while (len > 0) { + unsigned chunk = MIN(len, 0x2000 - (destaddr & 0x1fff)); + unsigned destaddr1 = addr_remap(destaddr); + memset(m_memory + destaddr1, val, chunk); + destaddr += chunk; + len -= chunk; + } + + return 0; +} + +// peek(addr, [n]) +int peek(lua_State *L) +{ + unsigned addr = lua_tounsigned(L, 1); + unsigned n = lua_gettop(L) >= 2 ? lua_tounsigned(L, 2) : 1; + + addr = addr_remap(addr); + + luaL_checkstack(L, n, "too many values"); + + for (unsigned i=0;i= 2 ? lua_tounsigned(L, 2) : 1; + + addr = addr_remap(addr); + + luaL_checkstack(L, n, "too many values"); + + for (unsigned i=0;i= 2 ? lua_tounsigned(L, 2) : 1; + + addr = addr_remap(addr); + + luaL_checkstack(L, n, "too many values"); + + for (unsigned i=0;i= MEMORY_CARTDATA && addr + 1 <= MEMORY_CARTDATA + MEMORY_CARTDATA_SIZE) + p8_delayed_flush_cartdata(); + + lua_pushinteger(L, 0); + return 1; +} + +// poke2(addr, val1, ...) +int poke2(lua_State *L) +{ + unsigned addr = lua_tounsigned(L, 1); + + addr = addr_remap(addr); + + for (int i=2;i<=lua_gettop(L);++i) { + unsigned val = lua_tounsigned(L, i); + + m_memory[addr + (i-2)*2] = val; + m_memory[addr + (i-2)*2 + 1] = val >> 8; + } + + if (addr >= MEMORY_CARTDATA && addr + 2 <= MEMORY_CARTDATA + MEMORY_CARTDATA_SIZE) + p8_delayed_flush_cartdata(); + + lua_pushinteger(L, 0); + return 1; +} + +// poke4(addr, val1, ...) +int poke4(lua_State *L) +{ + unsigned addr = lua_tounsigned(L, 1); + + addr = addr_remap(addr); + + for (int i=2;i<=lua_gettop(L);++i) { + uint32_t val = lua_tonumber(L, i); + + m_memory[addr + (i-2)*4] = val; + m_memory[addr + (i-2)*4 + 1] = val >> 8; + m_memory[addr + (i-2)*4 + 2] = val >> 16; + m_memory[addr + (i-2)*4 + 3] = val >> 24; + } + + if (addr >= MEMORY_CARTDATA && addr + 4 <= MEMORY_CARTDATA + MEMORY_CARTDATA_SIZE) + p8_delayed_flush_cartdata(); + + lua_pushinteger(L, 0); + return 1; +} + +// reload(destaddr, sourceaddr, len, [filename]) +int reload(lua_State *L) +{ + int nargs = lua_gettop(L); + unsigned destaddr = nargs >= 1 ? lua_tounsigned(L, 1) : 0; + unsigned srcaddr = nargs >= 2 ? lua_tounsigned(L, 2) : 0; + unsigned len = nargs >= 3 ? lua_tounsigned(L, 3) : 0x4300; + destaddr = addr_remap(destaddr); + const char *file_name = nargs >= 4 ? lua_tostring(L, 4) : NULL; + uint8_t *src_mem = NULL; + if (file_name != NULL) { + char full_filename[PATH_MAX]; + if (strstr(file_name, ".p8") == NULL && strstr(file_name, ".P8") == NULL) { + snprintf(full_filename, sizeof(full_filename), "%s.p8", file_name); + file_name = full_filename; + } + char resolved_path[PATH_MAX]; + p8_show_io_icon(true); + if (p8_resolve_relative_path(resolved_path, file_name, sizeof(resolved_path), false) < 0) { + p8_show_io_icon(false); + lua_pushinteger(L, 0); + return 1; + } + int ret = parse_cart_file(resolved_path, m_temp_cart_memory, m_file_buffer, m_decompression_buffer, NULL, NULL); + p8_show_io_icon(false); + if (ret < 0) { + lua_pushinteger(L, 0); + return 1; + } + src_mem = m_temp_cart_memory; + } else { + src_mem = m_cart_memory; + } + if (destaddr >= 0 && destaddr + len <= 0x10000 && srcaddr >= 0 && srcaddr + len <= CART_MEMORY_SIZE) + memcpy(m_memory + destaddr, src_mem + srcaddr, len); + lua_pushinteger(L, len); + return 1; +} + +// **************************************************************** +// *** Math *** +// **************************************************************** + +// rnd(max) +int rnd(lua_State *L) +{ + int is_table = 0; + + if (lua_gettop(L) >= 1) + { + if (lua_istable(L, 1)) + { + is_table = 1; + } + } + + uint32_t hi = m_memory[MEMORY_RNG_STATE] | (m_memory[MEMORY_RNG_STATE + 1] << 8) | + (m_memory[MEMORY_RNG_STATE + 2] << 16) | (m_memory[MEMORY_RNG_STATE + 3] << 24); + uint32_t lo = m_memory[MEMORY_RNG_STATE + 4] | (m_memory[MEMORY_RNG_STATE + 5] << 8) | + (m_memory[MEMORY_RNG_STATE + 6] << 16) | (m_memory[MEMORY_RNG_STATE + 7] << 24); + + hi = (hi << 16) | (hi >> 16); + hi += lo; + lo += hi; + + m_memory[MEMORY_RNG_STATE] = hi & 0xFF; + m_memory[MEMORY_RNG_STATE + 1] = (hi >> 8) & 0xFF; + m_memory[MEMORY_RNG_STATE + 2] = (hi >> 16) & 0xFF; + m_memory[MEMORY_RNG_STATE + 3] = (hi >> 24) & 0xFF; + m_memory[MEMORY_RNG_STATE + 4] = lo & 0xFF; + m_memory[MEMORY_RNG_STATE + 5] = (lo >> 8) & 0xFF; + m_memory[MEMORY_RNG_STATE + 6] = (lo >> 16) & 0xFF; + m_memory[MEMORY_RNG_STATE + 7] = (lo >> 24) & 0xFF; + + if (is_table) + { + size_t len = lua_rawlen(L, 1); + if (len > 0) + { + int index = ((hi >> 16) % len) + 1; + lua_rawgeti(L, 1, index); + } + else + { + lua_pushnil(L); + } + } + else + { + uint32_t max_fixed = (lua_gettop(L) >= 1) ? fix32_bits(lua_tonumber(L, 1)) : 0x10000; + uint32_t result_fixed = (max_fixed == 0) ? 0 : (hi % max_fixed); + lua_pushnumber(L, fix32_from_bits(result_fixed)); + } + + return 1; +} + +// srand(val) +int _srand(lua_State *L) +{ + // Capture the current RNG state as the "previous seed" (lo word is the seed) + uint32_t prev_lo = m_memory[MEMORY_RNG_STATE+4] | (m_memory[MEMORY_RNG_STATE+5] << 8) | + (m_memory[MEMORY_RNG_STATE+6] << 16) | (m_memory[MEMORY_RNG_STATE+7] << 24); + + // Use the full 32-bit raw fix32 representation so that srand(0x5b04.17cb) + // seeds with 0x5b0417cb, not just the integer part 0x5b04. + uint32_t n = (uint32_t)fix32_bits(lua_tonumber(L, 1)); + + p8_seed_rng_state(n); + + lua_pushnumber(L, fix32_from_bits(prev_lo)); + return 1; +} + +// **************************************************************** +// *** Cartridge data *** +// **************************************************************** + +// cartdata(id) +int cartdata(lua_State *L) +{ + const char *id = lua_tostring(L, 1); + bool success = p8_open_cartdata(id); + lua_pushboolean(L, success); + return 1; +} + +// dget(index) +int dget(lua_State *L) +{ + unsigned index = lua_tounsigned(L, 1); + + lua_pushnumber(L, fix32_from_bits((m_memory[MEMORY_CARTDATA + index*4 + 3] << 24) | (m_memory[MEMORY_CARTDATA + index*4 + 2] << 16) | (m_memory[MEMORY_CARTDATA + index*4 + 1] << 8) | m_memory[MEMORY_CARTDATA + index*4])); + + return 1; +} + +// dset(index, value) +int dset(lua_State *L) +{ + unsigned index = lua_tounsigned(L, 1); + lua_Number val_num = lua_tonumber(L, 2); + uint32_t value = fix32_bits(val_num); + + m_memory[MEMORY_CARTDATA + index*4] = value; + m_memory[MEMORY_CARTDATA + index*4 + 1] = value >> 8; + m_memory[MEMORY_CARTDATA + index*4 + 2] = value >> 16; + m_memory[MEMORY_CARTDATA + index*4 + 3] = value >> 24; + + p8_delayed_flush_cartdata(); + + lua_pushnumber(L, val_num); + return 1; +} + +// **************************************************************** +// *** Coroutines *** +// **************************************************************** + +// cocreate(func) +// coresume(cor) +// costatus(cor) +// yield() + +// **************************************************************** +// *** Values and objects *** +// **************************************************************** + +// setmetatable(tbl, metatbl) +// getmetatable(tbl) +// type(v) +// sub(str, from, [to]) +int sub(lua_State *L) +{ + const char *str = lua_tostring(L, 1); + int start = lua_tointeger(L, 2); + int end = lua_to_or_default(L, integer, 3, -1); + int str_len = strlen(str); + + if (start < 1) start = 1; + if (start > str_len + 1) start = str_len + 1; + + if (end == -1) + { + int len = str_len - start + 1; + if (len < 0) len = 0; + lua_pushlstring(L, str + start - 1, len); + return 1; + } + + if (end < 0) end = str_len + end + 1; + if (end < 1) end = 1; + if (end > str_len) end = str_len; + + int len = end - start + 1; + if (len < 0) len = 0; + lua_pushlstring(L, str + start - 1, len); + + return 1; +} + +// **************************************************************** +// *** Time *** +// **************************************************************** + +// time() +int _time(lua_State *L) +{ + lua_pushnumber(L, fix32_from_double((double)m_frames / (double)m_fps)); + + return 1; +} + +// **************************************************************** +// *** System *** +// **************************************************************** + +// menuitem(index, [label, callback]) +int menuitem(lua_State *L) +{ + int index = luaL_checkinteger(L, 1); + + if (index < 1 || index > MAX_CUSTOM_MENUITEMS) + return 0; + + /* menuitem(i) with no label removes the item */ + if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { + p8_menuitem_clear(index); + return 0; + } + + const char *label = lua_tostring(L, 2); /* may be nil/non-string */ + + if (lua_gettop(L) >= 3 && lua_isfunction(L, 3)) { + // Full set: update label and callback + lua_pushvalue(L, 3); + int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX); + p8_menuitem_set(index, label ? label : "", callback_ref); + } else { + // Label-only update: preserve existing callback + p8_menuitem_set_label(index, label ? label : ""); + } + return 0; +} + +// extcmd(cmd) +int extcmd(lua_State *L) +{ + const char *cmd = luaL_checkstring(L, 1); + + if (strcmp(cmd, "pause") == 0) { + p8_show_pause_menu(); + } else if (strcmp(cmd, "reset") == 0) { + p8_restart(); + } else if (strcmp(cmd, "shutdown") == 0) { + p8_abort(); + } else { + fprintf(stderr, "unsupported extcmd command: %s\n", cmd); + } + + return 0; +} + +int reset(lua_State *L) +{ + p8_reset(); + + return 0; +} + +int run(lua_State *L) +{ + const char *param = (lua_gettop(L) >= 1) ? lua_tostring(L, 1) : ""; + strtcpy(m_param_string, param, sizeof(m_param_string)); + + return p8_run(); +} + +// load(filename [,breadcrumb] [,param]) +int _load(lua_State *L) +{ + if (access(".", F_OK) == -1 && errno != EACCES) + luaL_error(L, "load() requires a filesystem"); + + int nargs = lua_gettop(L); + + if (nargs < 1) + luaL_error(L, "load() requires at least 1 argument"); + + const char *filename = lua_tostring(L, 1); + if (!filename) + luaL_error(L, "load() filename must be a string"); + + char full_filename[PATH_MAX]; + char resolved_path[PATH_MAX]; + const char *bbs_cart_id = NULL; + + if (strstr(filename, ".p8") == NULL && strstr(filename, ".P8") == NULL) { + snprintf(full_filename, sizeof(full_filename), "%s.p8", filename); + filename = full_filename; + } + + if (p8_resolve_relative_path(resolved_path, filename, sizeof(resolved_path), false) < 0) { + luaL_error(L, "out of memory"); + } + + if (p8_resolve_relative_path(resolved_path, filename, sizeof(resolved_path), false) < 0) { + luaL_error(L, "out of memory"); + } + + if (access(resolved_path, F_OK) != 0) { + fprintf(stderr, "load: could not find cart %s\n", filename); + m_load_result = -1; + if (p8_is_cart_running()) { + lua_pushboolean(L, 0); + lua_pushstring(L, "could not find cart"); + return 2; + } else { + return luaL_error(L, "could not find cart"); + } + } + + const char *breadcrumb = NULL; + if (nargs >= 2) + breadcrumb = lua_tostring(L, 2); + + const char *param = NULL; + if (nargs >= 3) + param = lua_tostring(L, 3); + + int ret = p8_load(resolved_path, param, bbs_cart_id, breadcrumb); + if (ret != 0) { + m_load_result = -1; + if (p8_is_cart_running()) { + lua_pushboolean(L, 0); + lua_pushstring(L, "could not load cart"); + return 2; + } else { + return luaL_error(L, "could not load cart"); + } + } + + m_load_result = 1; + + if (p8_is_cart_running()) { + return p8_run(); + } else { + lua_pushboolean(L, 1); + return 1; + } +} + +// **************************************************************** +// *** Debugging *** +// **************************************************************** + +// assert(cond, [message]) +// printh(str, [filename], [overwrite]) +int printh(lua_State *L) +{ + const char *str = NULL; + const char *filename = NULL; + bool overwrite = false; + + if (lua_gettop(L) >= 1) + str = lua_tostring(L, 1); + if (lua_gettop(L) >= 2) + filename = lua_tostring(L, 2); + if (lua_gettop(L) >= 3) + overwrite = lua_toboolean(L, 3); + + if (!str) str = ""; + + if (filename && strcmp(filename, "@clip") == 0) { + strtcpy(m_clipboard, str, sizeof(m_clipboard)); + lua_pushboolean(L, 1); + return 1; + } + + FILE *f = NULL; + if (!filename) { + f = stdout; + } else { + f = fopen(filename, overwrite ? "w" : "a"); + if (!f) { + lua_pushboolean(L, 0); + return 1; + } + } + + fprintf(f, "%s\n", str); + if (f != stdout) + fclose(f); + + lua_pushboolean(L, 1); + return 1; +} + +// stat(n) +int lua_stat(lua_State *L) +{ + int n = lua_tointeger(L, 1); + + switch (n) + { + case STAT_MEM_USAGE: { + lua_gc(L, LUA_GCCOLLECT, 0); + int kb = lua_gc(L, LUA_GCCOUNT, 0); + lua_pushnumber(L, fix32_from_int(kb)); + break; + } + case STAT_RAW_GC: { + int kb = lua_gc(L, LUA_GCCOUNT, 0); + lua_pushnumber(L, fix32_from_int(kb)); + break; + } + case STAT_CPU_USAGE: + case STAT_SYSTEM_CPU_USAGE: { + unsigned elapsed_time = p8_elapsed_time(); + const unsigned target_frame_time = 1000 / m_fps; + float f = (float)elapsed_time / (float)target_frame_time; + lua_pushnumber(L, fix32_from_double(f)); + break; + } + case STAT_CURRENT_DISPLAY: + lua_pushinteger(L, 0); + break; + case STAT_CLIPBOARD: + lua_pushstring(L, m_clipboard); + break; + case STAT_VERSION: + lua_pushnumber(L, fix32_from_double(0.43)); + break; + case STAT_PARAM: + lua_pushstring(L, m_param_string); + break; + case STAT_FRAMERATE: + lua_pushinteger(L, m_fps); + break; + case STAT_TARGET_FRAMERATE: + lua_pushinteger(L, m_fps); + break; + case STAT_NUM_DISPLAYS: + lua_pushinteger(L, 1); + break; + case STAT_PAUSE_MENU_X1: + lua_pushinteger(L, 0); + break; + case STAT_PAUSE_MENU_Y1: + lua_pushinteger(L, 0); + break; + case STAT_PAUSE_MENU_X2: + lua_pushinteger(L, P8_WIDTH); + break; + case STAT_PAUSE_MENU_Y2: + lua_pushinteger(L, P8_HEIGHT); + break; + case STAT_RAW_KEYBOARD: { + int scancode = lua_tointeger(L, 2); + lua_pushboolean(L, p8_is_key_down(scancode)); + break; + } + case STAT_KEY_PRESSED: + lua_pushboolean(L, p8_has_pending_keypress()); + break; + case STAT_KEY_NAME: { + uint8_t keypress = 0; + p8_get_next_keypress(NULL, &keypress, NULL); + char s[2] = {(char)keypress, '\0'}; + lua_pushstring(L, s); + break; + } + case STAT_MOUSE_X: + lua_pushinteger(L, m_mouse_x); + break; + case STAT_MOUSE_Y: + lua_pushinteger(L, m_mouse_y); + break; + case STAT_MOUSE_BUTTONS: + lua_pushinteger(L, m_mouse_buttons); + break; + case STAT_MOUSE_WHEEL: + lua_pushinteger(L, m_mouse_wheel); + break; + case STAT_MOUSE_XREL: + lua_pushinteger(L, m_mouse_xrel); + break; + case STAT_MOUSE_YREL: + lua_pushinteger(L, m_mouse_yrel); + break; + case STAT_YEAR: + case STAT_MONTH: + case STAT_DAY: + case STAT_HOUR: + case STAT_MINUTE: + case STAT_SECOND: { + time_t t = time(NULL); + struct tm *tm = localtime(&t); + switch (n) + { + case STAT_YEAR: + lua_pushinteger(L, tm->tm_year + 1900); + break; + case STAT_MONTH: + lua_pushinteger(L, tm->tm_mon + 1); + break; + case STAT_DAY: + lua_pushinteger(L, tm->tm_mday); + break; + case STAT_HOUR: + lua_pushinteger(L, tm->tm_hour); + break; + case STAT_MINUTE: + lua_pushinteger(L, tm->tm_min); + break; + case STAT_SECOND: + lua_pushinteger(L, tm->tm_sec); + break; + } + break; + } + case STAT_YEAR_UTC: + case STAT_MONTH_UTC: + case STAT_DAY_UTC: + case STAT_HOUR_UTC: + case STAT_MINUTE_UTC: + case STAT_SECOND_UTC: { + time_t t = time(NULL); + struct tm *tm = gmtime(&t); + switch (n) + { + case STAT_YEAR_UTC: + lua_pushinteger(L, tm->tm_year + 1900); + break; + case STAT_MONTH_UTC: + lua_pushinteger(L, tm->tm_mon + 1); + break; + case STAT_DAY_UTC: + lua_pushinteger(L, tm->tm_mday); + break; + case STAT_HOUR_UTC: + lua_pushinteger(L, tm->tm_hour); + break; + case STAT_MINUTE_UTC: + lua_pushinteger(L, tm->tm_min); + break; + case STAT_SECOND_UTC: + lua_pushinteger(L, tm->tm_sec); + break; + } + break; + } + case STAT_PCM_BUFFER_SIZE: + lua_pushinteger(L, audio_pcm_buffered()); + break; + case STAT_PCM_APP_BUFFER: + lua_pushinteger(L, audio_pcm_app_buffer()); + break; + case STAT_BREADCRUMB: + lua_pushstring(L, m_breadcrumb); + break; + case STAT_BBS_CART_ID: + lua_pushstring(L, ""); + break; + case STAT_LOAD_RESULT: + lua_pushinteger(L, m_load_result); + break; + case STAT_CURRENT_PATH: + lua_pushstring(L, m_current_cart_dir[0] ? m_current_cart_dir : "."); + break; + default: + if (n == 57) { + lua_pushboolean(L, audio_stat(n) != 0); + } else if ((n >= 46 && n <= 57) || (n >= 16 && n <= 26)) { + lua_pushinteger(L, audio_stat(n)); + } else { + lua_pushinteger(L, 0); + } + break; + } + + return 1; +} + +// stop([message,] [x,] [y,] [col]) +int _stop(lua_State *L) +{ + int nargs = lua_gettop(L); + if (nargs >= 1 && !lua_isnil(L, 1)) { + size_t len; + const char *str = lua_tolstring(L, 1, &len); + + if (str) { + if (nargs >= 3) { + int x = lua_tointeger(L, 2); + int y = lua_tointeger(L, 3); + int col = nargs >= 4 ? lua_tointeger(L, 4) : pencolor_get(); + int right; + draw_text(str, len, x, y, col, x, true, &x, &y, &right); + cursor_set(x, y, -1); + } else { + int x, y; + cursor_get(&x, &y); + int col = nargs >= 2 ? lua_tointeger(L, 2) : pencolor_get(); + int right; + draw_text(str, len, x, y, col, left_margin_get(), false, &x, &y, &right); + cursor_set(x, y, -1); + } + p8_render(); + } + } + p8_abort(); +} + +// trace([coroutine,] [message,] [skip]) +// Returns a description of the current call stack as a string. +// Mirrors debug.traceback() with PICO-8's default skip of 1. +int _trace(lua_State *L) +{ + int arg = 0; + lua_State *L1 = L; + + if (lua_isthread(L, 1)) { + L1 = lua_tothread(L, 1); + arg = 1; + } + + const char *msg = lua_isnoneornil(L, arg + 1) ? NULL : lua_tostring(L, arg + 1); + int level = lua_isnoneornil(L, arg + 2) ? 1 : lua_tointeger(L, arg + 2); + + luaL_traceback(L, L1, msg, level); + return 1; +} + +// **************************************************************** +// *** Misc *** +// **************************************************************** + +// **************************************************************** +// **************************************************************** + +int warning(lua_State *L) +{ + const char *msg = lua_tostring(L, 1); + + printf("WARNING: %s\r\n", msg); + + return 0; +} + +int set_fps(lua_State *L) +{ + int fps = lua_tointeger(L, 1); + m_fps = MAX(0, fps); + + return 0; +} + +int get_mouse_x(lua_State *L) +{ + lua_pushinteger(L, m_mouse_x); + + return 1; +} + +int get_mouse_y(lua_State *L) +{ + lua_pushinteger(L, m_mouse_y); + + return 1; +} + +// serial(channel, address, [length]) +int serial(lua_State *L) +{ + int channel = lua_tointeger(L, 1); + uint32_t address = addr_remap(lua_tounsigned(L, 2)); + uint32_t length = lua_gettop(L) >= 3 ? lua_tounsigned(L, 3) : 1; + if (length < 0) + length = 0; + + switch (channel) { + case 0x0ff: { + usleep(length); + break; + } + case 0x804: { + if (address >= MEMORY_SIZE) + length = 0; + else if (length > MEMORY_SIZE - address) + length = MEMORY_SIZE - address; + + if (length > 0) { + size_t bytes_read = fread(m_memory + address, 1, length, stdin); + (void)bytes_read; + } + break; + } + case 0x805: { + if (address >= MEMORY_SIZE) + length = 0; + else if (length > MEMORY_SIZE - address) + length = MEMORY_SIZE - address; + + if (length > 0) + fwrite(m_memory + address, 1, length, stdout); + + fflush(stdout); + break; + } + case 0x808: + // PCM audio output +#ifdef ENABLE_AUDIO + audio_pcm_write(address, length); +#endif + break; + } + + return 0; +} + +// **************************************************************** +// *** Filesystem *** +// **************************************************************** + +// save([filename]) +// Save the current cartridge to disk. +int save(lua_State *L) +{ + const char *filename = lua_gettop(L) >= 1 ? lua_tostring(L, 1) : NULL; + + char resolved[PATH_MAX]; + if (filename) { + if (p8_resolve_relative_path(resolved, filename, sizeof(resolved), true) < 0) { + luaL_error(L, "out of memory"); + return 0; + } + } else { + if (!m_current_cart_file_name[0]) { + lua_pushboolean(L, 0); + return 1; + } + strtcpy(resolved, m_current_cart_file_name, sizeof(resolved)); + } + + p8_show_io_icon(true); + int ret = write_cart_p8(resolved, m_lua_script, m_cart_memory); + p8_show_io_icon(false); + + if (ret != 0) { + lua_pushboolean(L, 0); + return 1; + } + lua_pushboolean(L, 1); + return 1; +} + +// ls([directory]) +// List .p8 and .p8.png files in the given directory (relative to current_cart_dir). +// Directories are returned with a trailing '/'. +// Returns nil when called from a BBS cart. +int ls(lua_State *L) +{ + const char *path = NULL; + char resolved[PATH_MAX]; + + if (lua_gettop(L) >= 1 && !lua_isnil(L, 1)) { + const char *arg = lua_tostring(L, 1); + if (arg) { + if (p8_resolve_relative_path(resolved, arg, sizeof(resolved), false) < 0) { + luaL_error(L, "Path too long"); + return 0; + } + path = resolved; + } + } + + if (!path) + path = m_current_cart_dir[0] ? m_current_cart_dir : "."; + + DIR *dir = opendir(path); + if (!dir) + return 0; /* nil */ + + lua_newtable(L); + int idx = 1; + + struct dirent *de; + char full_path[PATH_MAX]; + while ((de = readdir(dir)) != NULL) { + char *name = de->d_name; + if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) + continue; + + /* Build full path for stat */ + if (p8_make_full_path(full_path, sizeof(full_path), path, name) < 0) + continue; + + struct stat st; + bool is_dir = false; + if (stat(full_path, &st) == 0) + is_dir = S_ISDIR(st.st_mode); + + size_t name_len = strlen(name); + if (is_dir) { + /* Append trailing '/' */ + if (name_len < sizeof(de->d_name) - 2) { + name[name_len] = '/'; + name[name_len + 1] = '\0'; + lua_pushstring(L, name); + lua_rawseti(L, -2, idx++); + } + } else { + /* Only include .p8 and .p8.png files */ + bool is_p8 = (name_len > 3 && strcmp(name + name_len - 3, ".p8") == 0) || + (name_len > 7 && strcmp(name + name_len - 7, ".p8.png") == 0); + if (is_p8) { + lua_pushstring(L, name); + lua_rawseti(L, -2, idx++); + } + } + } + closedir(dir); + return 1; +} + +// reboot() +// Reboot the machine / start a new project. +int lua_reboot(lua_State *L) +{ + (void)L; + p8_abort(); + return 0; +} + +// cd([directory]) +// Change the current cartridge directory. +int cd(lua_State *L) +{ + if (lua_gettop(L) < 1 || lua_isnil(L, 1)) + return 0; + + const char *dir = lua_tostring(L, 1); + if (!dir) + return 0; + + char new_dir[PATH_MAX]; + if (p8_resolve_relative_path(new_dir, dir, sizeof(new_dir), false) < 0) { + luaL_error(L, "Path too long"); + return 0; + } + + struct stat st; + if (stat(new_dir, &st) != 0 || !S_ISDIR(st.st_mode)) { + luaL_error(L, "%s: not a directory", dir); + return 0; + } + + strtcpy(m_current_cart_dir, new_dir, sizeof(m_current_cart_dir)); + return 0; +} + +// mkdir(directory) +// Create a directory. +int lua_mkdir(lua_State *L) +{ + const char *dir = lua_gettop(L) >= 1 ? lua_tostring(L, 1) : NULL; + if (!dir) { + lua_pushboolean(L, 0); + return 1; + } + + char resolved[PATH_MAX]; + if (p8_resolve_relative_path(resolved, dir, sizeof(resolved), true) < 0) { + luaL_error(L, "Path too long"); + return 0; + } + + int ret = MKDIR(resolved); + + if (ret != 0 && errno != EEXIST) { + lua_pushboolean(L, 0); + return 1; + } + lua_pushboolean(L, 1); + return 1; +} + +void lua_register_functions(lua_State *L) +{ + // **************************************************************** + // *** Graphics *** + // **************************************************************** + lua_register(L, "camera", camera); + lua_register(L, "circ", circ); + lua_register(L, "circfill", circfill); + lua_register(L, "clip", clip); + lua_register(L, "cls", cls); + lua_register(L, "color", color); + lua_register(L, "cursor", cursor); + lua_register(L, "fget", fget); + lua_register(L, "fillp", fillp); + lua_register(L, "flip", flip); + lua_register(L, "holdframe", holdframe); + lua_register(L, "fset", fset); + lua_register(L, "line", line); + lua_register(L, "oval", oval); + lua_register(L, "ovalfill", ovalfill); + lua_register(L, "pal", pal); + lua_register(L, "palt", palt); + lua_register(L, "pget", pget); + lua_register(L, "print", print); + lua_register(L, "pset", pset); + lua_register(L, "rect", rect); + lua_register(L, "rectfill", rectfill); + lua_register(L, "rrect", rrect); + lua_register(L, "rrectfill", rrectfill); + lua_register(L, "sget", sget); + lua_register(L, "spr", spr); + lua_register(L, "sset", sset); + lua_register(L, "sspr", sspr); + lua_register(L, "tline", tline); + // **************************************************************** + // *** Tables *** + // **************************************************************** + // lua_register(L, "add", add); + // lua_register(L, "all", all); + // lua_register(L, "count", count); + // lua_register(L, "del", del); + // lua_register(L, "foreach", foreach); + // lua_register(L, "pairs", pairs); + // **************************************************************** + // *** Input *** + // **************************************************************** + lua_register(L, "btn", btn); + lua_register(L, "btnp", btnp); + lua_register(L, "_update_buttons", _update_buttons); + // **************************************************************** + // *** Sound *** + // **************************************************************** + lua_register(L, "music", music); + lua_register(L, "sfx", sfx); + // **************************************************************** + // *** Map *** + // **************************************************************** + lua_register(L, "map", map); + lua_register(L, "mget", mget); + lua_register(L, "mset", mset); + // **************************************************************** + // *** Memory *** + // **************************************************************** + lua_register(L, "cstore", cstore); + lua_register(L, "memcpy", _memcpy); + lua_register(L, "memset", _memset); + lua_register(L, "peek", peek); + lua_register(L, "peek2", peek2); + lua_register(L, "peek4", peek4); + lua_register(L, "poke", poke); + lua_register(L, "poke2", poke2); + lua_register(L, "poke4", poke4); + lua_register(L, "reload", reload); + // **************************************************************** + // *** Math *** + // **************************************************************** + // lua_register(L, "abs", _abs); // in lpico8lib.c + // lua_register(L, "atan2", _atan2); // in lpico8lib.c + // lua_register(L, "band", band); // in lpico8lib.c + // lua_register(L, "bnot", bnot); // in lpico8lib.c + // lua_register(L, "bor", bor); // in lpico8lib.c + // lua_register(L, "bxor", bxor); // in lpico8lib.c + // lua_register(L, "ceil", _ceil); // in lpico8lib.c + // lua_register(L, "cos", _cos); // in lpico8lib.c + // lua_register(L, "flr", flr); // in lpico8lib.c + // lua_register(L, "lshr", lshr); // in lpico8lib.c + // lua_register(L, "max", max); // in lpico8lib.c + // lua_register(L, "mid", mid); // in lpico8lib.c + // lua_register(L, "min", min); // in lpico8lib.c + lua_register(L, "rnd", rnd); + // lua_register(L, "rotl", rotl); // in lpico8lib.c + // lua_register(L, "rotr", rotr); // in lpico8lib.c + // lua_register(L, "sgn", sgn); // in lpico8lib.c + // lua_register(L, "shl", shl); // in lpico8lib.c + // lua_register(L, "shr", shr); // in lpico8lib.c + // lua_register(L, "sin", _sin); // in lpico8lib.c + // lua_register(L, "sqrt", _sqrt); // in lpico8lib.c + lua_register(L, "srand", _srand); + // **************************************************************** + // *** Cartridge data *** + // **************************************************************** + lua_register(L, "cartdata", cartdata); + lua_register(L, "dget", dget); + lua_register(L, "dset", dset); + // **************************************************************** + // *** Coroutines *** + // **************************************************************** + // lua_register(L, "cocreate", cocreate); + // lua_register(L, "coresume", coresume); + // lua_register(L, "costatus", costatus); + // lua_register(L, "yield", yield); + // **************************************************************** + // *** Values and objects *** + // **************************************************************** + // lua_register(L, "chr", chr); // in lpico8lib.c + // lua_register(L, "ord", ord); // in lpico8lib.c + // lua_register(L, "setmetatable", setmetatable); + // lua_register(L, "getmetatable", getmetatable); + // lua_register(L, "type", type); + lua_register(L, "sub", sub); + // lua_register(L, "tonum", tonum); + // lua_register(L, "tostr", tostr); // in lpico8lib.c + // **************************************************************** + // *** Time *** + // **************************************************************** + lua_register(L, "t", _time); + lua_register(L, "time", _time); + // **************************************************************** + // *** System *** + // **************************************************************** + lua_register(L, "menuitem", menuitem); + lua_register(L, "extcmd", extcmd); + lua_register(L, "load", _load); + lua_register(L, "reset", reset); + lua_register(L, "run", run); + lua_register(L, "serial", serial); + lua_register(L, "_set_fps", set_fps); + lua_register(L, "save", save); + lua_register(L, "ls", ls); + lua_register(L, "reboot", lua_reboot); + lua_register(L, "cd", cd); + lua_register(L, "mkdir", lua_mkdir); + // **************************************************************** + // *** Debugging *** + // **************************************************************** + // lua_register(L, "assert", assert); + lua_register(L, "printh", printh); + lua_register(L, "stat", lua_stat); + lua_register(L, "stop", _stop); + lua_register(L, "trace", _trace); + // **************************************************************** + // *** Misc *** + // **************************************************************** + + // **************************************************************** + // *** P8SCII glyphs *** + // **************************************************************** + lua_pushinteger(L, 0); lua_setglobal(L, "\x8b"); // 139 ⬅️ left + lua_pushinteger(L, 1); lua_setglobal(L, "\x91"); // 145 ➑️ right + lua_pushinteger(L, 2); lua_setglobal(L, "\x94"); // 148 ⬆️ up + lua_pushinteger(L, 3); lua_setglobal(L, "\x83"); // 131 ⬇️ down + lua_pushinteger(L, 4); lua_setglobal(L, "\x8e"); // 142 πŸ…ΎοΈ O/Z + lua_pushinteger(L, 5); lua_setglobal(L, "\x97"); // 151 ❎ X + + lua_pushnumber(L, fix32_from_bits(0x00008000)); lua_setglobal(L, "\x80"); // 128 β–ˆ + lua_pushnumber(L, fix32_from_bits(0x5a5a8000)); lua_setglobal(L, "\x81"); // 129 β–’ + lua_pushnumber(L, fix32_from_bits(0x511f8000)); lua_setglobal(L, "\x82"); // 130 🐱 + lua_pushnumber(L, fix32_from_bits(0x7d7d8000)); lua_setglobal(L, "\x84"); // 132 β–‘ + lua_pushnumber(L, fix32_from_bits(0xb81d8000)); lua_setglobal(L, "\x85"); // 133 ✽ + lua_pushnumber(L, fix32_from_bits(0xf99f8000)); lua_setglobal(L, "\x86"); // 134 ● + lua_pushnumber(L, fix32_from_bits(0x51bf8000)); lua_setglobal(L, "\x87"); // 135 β™₯ + lua_pushnumber(L, fix32_from_bits(0xb5bf8000)); lua_setglobal(L, "\x88"); // 136 β˜‰ + lua_pushnumber(L, fix32_from_bits(0x999f8000)); lua_setglobal(L, "\x89"); // 137 웃 + lua_pushnumber(L, fix32_from_bits(0xb11f8000)); lua_setglobal(L, "\x8a"); // 138 βŒ‚ + lua_pushnumber(L, fix32_from_bits(0xa0e08000)); lua_setglobal(L, "\x8c"); // 140 😐 + lua_pushnumber(L, fix32_from_bits(0x9b3f8000)); lua_setglobal(L, "\x8d"); // 141 β™ͺ + lua_pushnumber(L, fix32_from_bits(0xb1bf8000)); lua_setglobal(L, "\x8f"); // 143 β—† + lua_pushnumber(L, fix32_from_bits(0xf5ff8000)); lua_setglobal(L, "\x90"); // 144 … + lua_pushnumber(L, fix32_from_bits(0xb15f8000)); lua_setglobal(L, "\x92"); // 146 β˜… + lua_pushnumber(L, fix32_from_bits(0x1b1f8000)); lua_setglobal(L, "\x93"); // 147 β§— + lua_pushnumber(L, fix32_from_bits(0xf5bf8000)); lua_setglobal(L, "\x95"); // 149 Λ‡ + lua_pushnumber(L, fix32_from_bits(0x7adf8000)); lua_setglobal(L, "\x96"); // 150 ∧ + lua_pushnumber(L, fix32_from_bits(0x0f0f8000)); lua_setglobal(L, "\x98"); // 152 β–€ + lua_pushnumber(L, fix32_from_bits(0x55558000)); lua_setglobal(L, "\x99"); // 153 β–₯ +} + +static void lua_event_pump_hook(lua_State *L, lua_Debug *ar) +{ + (void)L; + (void)ar; + p8_pump_events(); + p8_check_for_pause(); +} + +int lua_load_api() +{ + if (!L) + { + L = luaL_newstate(); + } + + luaL_openlibs(L); + + lua_register_functions(L); + + int ret = luaL_dostring(L, lua_api_string); + if (ret != 0) + return ret; + lua_setpico8memory(L, m_memory); + + // Set debug hook to pump events every ~3000 instructions + lua_sethook(L, lua_event_pump_hook, LUA_MASKCOUNT, 3000); + + return 0; +} + +int lua_shutdown_api() +{ + if (L) { + p8_menuitem_reset_all(); + lua_close(L); + L = NULL; + } + return 0; +} + +static void print_script_context(const char *filename, int lineno) +{ + (void) filename; + if (lineno <= 0) + return; + int lo = lineno - 3, hi = lineno + 3; + if (lo < 1) lo = 1; + const char *p = m_lua_script; + int cur = 1; + while (*p && cur < lo) { + if (*p++ == '\n') cur++; + } + while (*p && cur <= hi) { + const char *eol = p; + while (*eol && *eol != '\n') eol++; + printf("%s %4d: %.*s\n", + cur == lineno ? ">>>" : " ", + cur, (int)(eol - p), p); + if (*eol) eol++; + p = eol; + cur++; + } +} + +void lua_print_error() +{ + const char *err_type = NULL; + char err_msg[96] = {0}; + const char *filename = NULL; + int lineno = -1; + lua_get_error(&err_type, err_msg, sizeof(err_msg), &filename, &lineno); + if (err_type) { + if (lineno > 0) + fprintf(stderr, "%s line %d\n", err_type, lineno); + else + fprintf(stderr, "%s\n", err_type); + } else if (lineno > 0) { + fprintf(stderr, "line %d\n", lineno); + } + if (err_msg[0]) + fprintf(stderr, "%s\n", err_msg); + if (!err_type && !err_msg[0]) + fprintf(stderr, "unknown error\n"); + if (lineno != -1) + print_script_context(filename, lineno); +} + +int lua_init_script(const char *file_name, const char *script) +{ + if (!L) + L = luaL_newstate(); + + char temp_file_name[PATH_MAX + 1]; + temp_file_name[0] = '@'; + if (file_name) + strtcpy(temp_file_name + 1, file_name, PATH_MAX); + else + temp_file_name[1] = '\0'; + + lua_settop(L, 0); + + size_t script_len = strnlen(script, LUA_SCRIPT_SIZE); + m_status = luaL_loadbuffer(L, script, script_len, temp_file_name); + + if (m_status) + return m_status; + + m_status = lua_pcall(L, 0, 0, 0); + + if (m_status) + return m_status; + + lua_getglobal(L, "_update"); + + if (lua_isfunction(L, -1)) + { + m_lua_update = lua_topointer(L, -1); + m_fps = 30; + lua_pop(L, 1); + } + + lua_getglobal(L, "_update60"); + + if (lua_isfunction(L, -1)) + { + m_lua_update60 = lua_topointer(L, -1); + m_fps = 60; + lua_pop(L, 1); + } + + lua_getglobal(L, "_draw"); + + if (lua_isfunction(L, -1)) + { + m_lua_draw = lua_topointer(L, -1); + lua_pop(L, 1); + } + + lua_getglobal(L, "_init"); + + if (lua_isfunction(L, -1)) + { + m_lua_init = lua_topointer(L, -1); + lua_pop(L, 1); + } + + return 0; +} + +int lua_call_function(const char *name, int ret) +{ + lua_settop(L, 0); + lua_getglobal(L, name); + m_status = lua_pcall(L, 0, ret, 0); + return m_status; +} + +int lua_update() +{ + if (!m_lua_update && !m_lua_update60) + { + lua_getglobal(L, "_update"); + if (lua_isfunction(L, -1)) + { + m_lua_update = lua_topointer(L, -1); + m_fps = 30; + } + lua_pop(L, 1); + + lua_getglobal(L, "_update60"); + if (lua_isfunction(L, -1)) + { + m_lua_update60 = lua_topointer(L, -1); + m_fps = 60; + } + lua_pop(L, 1); + } + + lua_settop(L, 0); + m_status = 0; + + if (m_lua_update60) + return lua_call_function("_update60", 0); + else if (m_lua_update) + return lua_call_function("_update", 0); + return 0; +} + +int lua_draw() +{ + if (!m_lua_draw) + { + lua_getglobal(L, "_draw"); + if (lua_isfunction(L, -1)) + m_lua_draw = lua_topointer(L, -1); + lua_pop(L, 1); + } + + lua_settop(L, 0); + m_status = 0; + + if (m_lua_draw) + return lua_call_function("_draw", 0); + return 0; +} + +bool lua_has_main_loop_callbacks() +{ + return (m_lua_update != NULL || m_lua_update60 != NULL || m_lua_draw != NULL); +} + +int lua_init() +{ + m_status = 0; + if (m_lua_init) + return lua_call_function("_init", 0); + return 0; +} + +void lua_get_error(const char **err_type, char *err, int err_size, const char **filename, int *lineno) +{ + if (!L) { + strtcpy(err, "no lua state", err_size); + return; + } + + switch (m_status ){ + case LUA_ERRSYNTAX: + *err_type = "syntax error"; + break; + case LUA_ERRMEM: + *err_type = "out of memory"; + break; + case LUA_ERRRUN: + *err_type = "runtime error"; + break; + case LUA_ERRERR: + *err_type = "error in error handler"; + break; + default: + *err_type = "unknown error"; + break; + } + if (lua_gettop(L) > 0 && lua_isstring(L, -1)) { + const char *err_msg = lua_tostring(L, -1); + if (err_msg) { + const char *colon = strrchr(err_msg, ':'); + if (colon) + err_msg = colon + 2; + const char *near_kw = strstr(err_msg, " near "); + if (near_kw) + *(char *)near_kw = '\0'; + if (strstr(err_msg, "syntax error") == NULL) + strtcpy(err, err_msg, err_size); + } + + if (lineno) { + const char *message = lua_tostring(L, -1); + // Extract line number from error string like "...:1292:" + const char *colon = message; + *lineno = 0; + if (*colon == ':') { + *lineno = atoi(colon + 1); + } else { + while (*colon) { + if (*colon != ']' && *(colon+1) == ':') { + *lineno = atoi(colon + 2); + if (*lineno > 0) break; + } + colon++; + } + } + } + } +} diff --git a/components/pico8/femto8/src/p8_lua.h b/components/pico8/femto8/src/p8_lua.h new file mode 100644 index 00000000..07010ff3 --- /dev/null +++ b/components/pico8/femto8/src/p8_lua.h @@ -0,0 +1,27 @@ +/* + * p8_lua.h + * + * Created on: Dec 13, 2023 + * Author: bbaker + */ + +#ifndef P8_LUA_H +#define P8_LUA_H + +#include +#include + +int lua_load_api(); +int lua_shutdown_api(); +void lua_print_error(); +int lua_init_script(const char *file_name, const char *script); +int lua_call_function(const char *name, int ret); +int lua_update(); +int lua_draw(); +int lua_init(); +bool lua_has_main_loop_callbacks(); +void lua_get_error(const char **err_type, char *err, int err_size, const char **filename, int *lineno); + +extern char m_str_buffer[256]; + +#endif diff --git a/components/pico8/femto8/src/p8_lua_helper.h b/components/pico8/femto8/src/p8_lua_helper.h new file mode 100644 index 00000000..b04d8dfa --- /dev/null +++ b/components/pico8/femto8/src/p8_lua_helper.h @@ -0,0 +1,759 @@ +/* + * p8_lua_helper.h + * + * Created on: Dec 26, 2023 + * Author: bbaker + */ + +#ifndef P8_LUA_HELPER_H +#define P8_LUA_HELPER_H + +#include +#include +#include +#include +#include +#include "p8_emu.h" +#include "p8_input.h" +#include "p8_symbols.h" +#include "pico_font.h" + +static inline void clear_screen(int color); +static inline void draw_circ(int x, int y, int r, int col, int fillp); +static inline void draw_circ_mask(int x, int y, int r, int col, int fillp, int mask); +static inline void draw_circfill(int x, int y, int r, int col, int fillp); +static inline void draw_circfill_mask(int x, int y, int r, int col, int fillp, int mask); +static inline void draw_oval(int x0, int y0, int x1, int y1, int col, int fillp); +static inline void draw_ovalfill(int x0, int y0, int x1, int y1, int col, int fillp); +static inline void draw_sprite(int n, int left, int top, bool flip_x, bool flip_y); +static inline void draw_scaled_sprite(int sx, int sy, int sw, int sh, int dx, int dy, float scale_x, float scale_y, bool flip_x, bool flip_y); +static inline void draw_sprites(int n, int x, int y, int w, int h, bool flip_x, bool flip_y); +static inline void draw_hline(int x0, int x1, int y, int col, int fillp); +static inline void draw_vline(int x, int y0, int y1, int col, int fillp); +static inline void draw_line(int x0, int y0, int x1, int y1, int col, int fillp); +static inline void draw_char(int n, int left, int top, int col); +static inline void draw_rect(int x0, int y0, int x1, int y1, int col, int fillp); +static inline void draw_rectfill(int x0, int y0, int x1, int y1, int col, int fillp); +static inline uint8_t gfx_addr_get(int x, int y, uint8_t *memory, int location, int size); +static inline uint8_t gfx_get(int x, int y, int location, int size); +static inline void gfx_set(int x, int y, int location, int size, int col); +static inline void camera_get(int *x, int *y); +static inline void camera_set(int x, int y); +static inline uint8_t pencolor_get(void); +static inline void pencolor_set(uint8_t col); +static inline uint8_t color_get(int type, int index); +static inline void color_set(int type, int index, int col); +static inline void clip_get(int *x0, int *y0, int *x1, int *y1); +static inline void clip_set(int x, int y, int w, int h); +static inline void cursor_get(int *x, int *y); +static inline void cursor_set(int x, int y, int col); +static inline void pixel_set(int x, int y, int c, int fillp, int draw_type); +static inline void draw_simple_text(const char *str, int x, int y, int col); +static inline bool is_button_set(int index, int button, bool prev_buttons); +static inline int map_cell_addr(int celx, int cely); +static inline void map_set(int celx, int cely, int snum); +static inline uint8_t map_get(int celx, int cely); +static inline void reset_color(void); +static inline int scroll(int y, int line_height); +static inline int scroll_newline(int y); +static inline void left_margin_set(int x); +static inline int left_margin_get(void); + +static inline void clear_screen(int color) +{ + color = color_get(PALTYPE_DRAW, color); + + for (int y = 0; y < P8_HEIGHT; y++) + for (int x = 0; x < P8_WIDTH; x++) + gfx_set(x, y, MEMORY_SCREEN, MEMORY_SCREEN_SIZE, color); + + clip_set(0, 0, P8_WIDTH, P8_HEIGHT); + cursor_set(0, 0, -1); +} + +static inline int dash_direction_x(int facing) +{ + return 0; +} + +static inline int dash_direction_y(int facing) +{ + return 0; +} + +// Returns true if the world-space bounding box [wx0,wy0]..[wx1,wy1] is entirely +// outside the effective clip region (clip rect intersected with screen bounds). +static inline bool is_bbox_offscreen(int wx0, int wy0, int wx1, int wy1) +{ + int cx, cy; + camera_get(&cx, &cy); + int ccx0, ccy0, ccx1, ccy1; + clip_get(&ccx0, &ccy0, &ccx1, &ccy1); + if (ccx0 < 0) ccx0 = 0; + if (ccy0 < 0) ccy0 = 0; + if (ccx1 > P8_WIDTH) ccx1 = P8_WIDTH; + if (ccy1 > P8_HEIGHT) ccy1 = P8_HEIGHT; + int sx0 = wx0 - cx, sy0 = wy0 - cy; + int sx1 = wx1 - cx, sy1 = wy1 - cy; + return sx1 < ccx0 || sx0 >= ccx1 || sy1 < ccy0 || sy0 >= ccy1; +} + +static inline void draw_oval_segment(int xc, int yc, int x, int y, int r, int xr, int yr, int col, int fillp, int mask) +{ + if (mask & 1) + pixel_set(xc + x * xr / r, yc + y * yr / r, col, fillp, DRAWTYPE_GRAPHIC); + if (mask & 2) + pixel_set(xc - x * xr / r, yc + y * yr / r, col, fillp, DRAWTYPE_GRAPHIC); + if (mask & 4) + pixel_set(xc + x * xr / r, yc - y * yr / r, col, fillp, DRAWTYPE_GRAPHIC); + if (mask & 8) + pixel_set(xc - x * xr / r, yc - y * yr / r, col, fillp, DRAWTYPE_GRAPHIC); + if (mask & 16) + pixel_set(xc + y * xr / r, yc + x * yr / r, col, fillp, DRAWTYPE_GRAPHIC); + if (mask & 32) + pixel_set(xc - y * xr / r, yc + x * yr / r, col, fillp, DRAWTYPE_GRAPHIC); + if (mask & 64) + pixel_set(xc + y * xr / r, yc - x * yr / r, col, fillp, DRAWTYPE_GRAPHIC); + if (mask & 128) + pixel_set(xc - y * xr / r, yc - x * yr / r, col, fillp, DRAWTYPE_GRAPHIC); +} + +static inline void draw_oval_mask(int xc, int yc, int xr, int yr, int col, int fillp, int mask) +{ + int r = MAX(xr, yr); + if (r <= 0) + return; + if (is_bbox_offscreen(xc - xr, yc - yr, xc + xr, yc + yr)) return; + int x = 0, y = abs(r); + int d = 3 - 2 * abs(r); + + draw_oval_segment(xc, yc, x, y, r, xr, yr, col, fillp, mask); + + while (y >= x) + { + x++; + + if (d > 0) + { + y--; + d = d + 4 * (x - y) + 10; + } + else + d = d + 4 * x + 6; + + draw_oval_segment(xc, yc, x, y, r, xr, yr, col, fillp, mask); + } +} + +static inline void draw_circ_mask(int xc, int yc, int r, int col, int fillp, int mask) +{ + draw_oval_mask(xc, yc, r, r, col, fillp, mask); +} + +static inline void draw_circ(int xc, int yc, int r, int col, int fillp) +{ + draw_circ_mask(xc, yc, r, col, fillp, 0xff); +} + +static inline void draw_line(int x0, int y0, int x1, int y1, int col, int fillp) +{ + if (is_bbox_offscreen(MIN(x0, x1), MIN(y0, y1), MAX(x0, x1), MAX(y0, y1))) return; + int dx = abs(x1 - x0); + int sx = x0 < x1 ? 1 : -1; + int dy = -abs(y1 - y0); + int sy = y0 < y1 ? 1 : -1; + int err = dx + dy; + + while (true) + { + pixel_set(x0, y0, col, fillp, DRAWTYPE_GRAPHIC); + + if (x0 == x1 && y0 == y1) + break; + + int e2 = 2 * err; + + if (e2 >= dy) + { + err += dy; + + x0 += sx; + } + + if (e2 <= dx) + { + err += dx; + y0 += sy; + } + } +} + +static inline void draw_hline(int x0, int y, int x1, int col, int fillp) +{ + for (int x=x0;x<=x1;x++) + pixel_set(x, y, col, fillp, DRAWTYPE_GRAPHIC); +} + +static inline void draw_vline(int x, int y0, int y1, int col, int fillp) +{ + for (int y=y0;y<=y1;y++) + pixel_set(x, y, col, fillp, DRAWTYPE_GRAPHIC); +} + +static inline void draw_ovalfill_segment(int xc, int yc, int x, int y, int r, int xr, int yr, int col, int fillp, int mask) +{ + if (mask & 1) + draw_hline(xc, yc + y * yr / r, xc + x * xr / r, col, fillp); + if (mask & 2) + draw_hline(xc - x * xr / r, yc + y * yr / r, xc, col, fillp); + if (mask & 4) + draw_hline(xc, yc - y * yr / r, xc + x * xr / r, col, fillp); + if (mask & 8) + draw_hline(xc - x * xr / r, yc - y * yr / r, xc, col, fillp); + if (mask & 16) + draw_hline(xc, yc + x * yr / r, xc + y * xr / r, col, fillp); + if (mask & 32) + draw_hline(xc - y * xr / r, yc + x * yr / r, xc, col, fillp); + if (mask & 64) + draw_hline(xc, yc - x * yr / r, xc + y * xr / r, col, fillp); + if (mask & 128) + draw_hline(xc - y * xr / r, yc - x * yr / r, xc, col, fillp); +} + +static inline bool fillp_invert_enabled(int color) +{ + return (m_memory[MEMORY_COLOR_FILLP] & 0x3) == 0x3 && (color & 0x1800) == 0x1800; +} + +static inline bool point_in_oval(int x, int y, int xc, int yc, int xr, int yr) +{ + if (xr <= 0 || yr <= 0) + return false; + + int dx = x - xc; + int dy = y - yc; + int64_t lhs = (int64_t)dx * dx * yr * yr + (int64_t)dy * dy * xr * xr; + int64_t rhs = (int64_t)xr * xr * yr * yr; + return lhs <= rhs; +} + +static inline void draw_ovalfill_mask(int xc, int yc, int xr, int yr, int col, int fillp, int mask) +{ + int r = MAX(xr, yr); + if (r <= 0) + return; + if (!fillp_invert_enabled(col) && is_bbox_offscreen(xc - xr, yc - yr, xc + xr, yc + yr)) return; + + if (fillp_invert_enabled(col)) { + int left = xc - xr; + int top = yc - yr; + int right = xc + xr; + int bottom = yc + yr; + for (int y = top; y <= bottom; y++) { + for (int x = left; x <= right; x++) { + if (!point_in_oval(x, y, xc, yc, xr, yr)) + pixel_set(x, y, col, fillp, DRAWTYPE_GRAPHIC); + } + } + return; + } + + int x = 0, y = abs(r); + int d = 3 - 2 * abs(r); + + draw_ovalfill_segment(xc, yc, x, y, r, xr, yr, col, fillp, mask); + + while (y >= x) + { + x++; + + if (d > 0) + { + y--; + d = d + 4 * (x - y) + 10; + } + else + d = d + 4 * x + 6; + + draw_ovalfill_segment(xc, yc, x, y, r, xr, yr, col, fillp, mask); + } +} + +static inline void draw_circfill_mask(int xc, int yc, int r, int col, int fillp, int mask) +{ + draw_ovalfill_mask(xc, yc, r, r, col, fillp, mask); +} + +static inline void draw_circfill(int xc, int yc, int r, int col, int fillp) +{ + draw_circfill_mask(xc, yc, r, col, fillp, 0xff); +} + +static inline void draw_rect(int x0, int y0, int x1, int y1, int col, int fillp) +{ + if (is_bbox_offscreen(x0, y0, x1, y1)) return; + draw_hline(x0, y0, x1, col, fillp); + draw_hline(x0, y1, x1, col, fillp); + draw_vline(x0, y0, y1, col, fillp); + draw_vline(x1, y0, y1, col, fillp); +} + +static inline bool point_in_rect(int x, int y, int x0, int y0, int x1, int y1) +{ + return x >= x0 && x <= x1 && y >= y0 && y <= y1; +} + +static inline void draw_rectfill(int x0, int y0, int x1, int y1, int col, int fillp) +{ + bool invert = fillp_invert_enabled(col); + if (invert) { + int cx, cy; + camera_get(&cx, &cy); + int clip_x0, clip_y0, clip_x1, clip_y1; + clip_get(&clip_x0, &clip_y0, &clip_x1, &clip_y1); + + for (int y = clip_y0; y < clip_y1; y++) { + for (int x = clip_x0; x < clip_x1; x++) { + if (!point_in_rect(x, y, x0, y0, x1, y1)) + pixel_set(x + cx, y + cy, col, fillp, DRAWTYPE_GRAPHIC); + } + } + return; + } + + for (int x=x0;x<=x1;x++) + for(int y=y0;y<=y1;y++) + pixel_set(x, y, col, fillp, DRAWTYPE_GRAPHIC); +} + +static inline bool point_in_round_rect(int x, int y, int left, int top, int right, int bottom, int r) +{ + if (x < left || x > right || y < top || y > bottom) + return false; + + if (r <= 0) + return true; + + if (x >= left + r && x <= right - r) + return true; + if (y >= top + r && y <= bottom - r) + return true; + + int cx = (x < left + r) ? (left + r) : (right - r); + int cy = (y < top + r) ? (top + r) : (bottom - r); + return point_in_oval(x, y, cx, cy, r, r); +} + +static inline void draw_oval(int x0, int y0, int x1, int y1, int col, int fillp) +{ + int x = (x0 + x1) / 2; + int y = (y0 + y1) / 2; + int xr = (x1 - x0) / 2; + int yr = (y1 - y0) / 2; + draw_oval_mask(x, y, xr, yr, col, fillp, 0xff); +} + +static inline void draw_ovalfill(int x0, int y0, int x1, int y1, int col, int fillp) +{ + int x = (x0 + x1) / 2; + int y = (y0 + y1) / 2; + int xr = (x1 - x0) / 2; + int yr = (y1 - y0) / 2; + draw_ovalfill_mask(x, y, xr, yr, col, fillp, 0xff); +} + +static inline void pixel_set(int x, int y, int c, int fillp, int draw_type) +{ + int cx, cy; + camera_get(&cx, &cy); + x -= cx; + y -= cy; + int x0, y0, x1, y1; + clip_get(&x0, &y0, &x1, &y1); + + if (x >= x0 && x < x1 && y >= y0 && y < y1) + { + bool fillp_sprites, fillp_graphics_secondary, transparency; + if (c & 0x1000) { + transparency = (c & 0x100) != 0; + fillp_sprites = (c & 0x200) != 0; + fillp_graphics_secondary = (c & 0x400) != 0; + } else { + fillp = m_memory[MEMORY_FILLP] | (m_memory[MEMORY_FILLP + 1] << 8); + transparency = (m_memory[MEMORY_FILLP_ATTR] & 1) != 0; + fillp_sprites = (m_memory[MEMORY_FILLP_ATTR] & 2) != 0; + fillp_graphics_secondary = (m_memory[MEMORY_FILLP_ATTR] & 4) != 0; + } + unsigned bit = ((3-y) & 0x3) * 4 + ((3-x) & 0x3); + bool on = (fillp & (1 << bit)) != 0; + bool use_fillp = (draw_type == DRAWTYPE_GRAPHIC) || (draw_type == DRAWTYPE_SPRITE && fillp_sprites); + bool use_secondary_palette = (draw_type == DRAWTYPE_SPRITE && fillp_sprites) || (draw_type == DRAWTYPE_GRAPHIC && fillp_graphics_secondary); + if (!use_fillp || (use_fillp && !transparency) || !on) { + uint8_t col; + if (c == -1) + c = pencolor_get(); + if (use_secondary_palette) { + uint8_t col_draw = color_get(PALTYPE_DRAW, (uint8_t)c); + uint8_t col_secondary = color_get(PALTYPE_SECONDARY, col_draw); + if (on) + col = (col_secondary >> 4) & 0xf; + else + col = col_secondary & 0xf; + } else { + if (use_fillp) { + if (on) + c = (c >> 4) & 0xf; + else + c = c & 0xf; + } + col = color_get(PALTYPE_DRAW, c); + } + gfx_set(x, y, MEMORY_SCREEN, MEMORY_SCREEN_SIZE, col); + } + } +} + +static inline void draw_scaled_sprite(int sx, int sy, int sw, int sh, int dx, int dy, float scale_x, float scale_y, bool flip_x, bool flip_y) +{ + int dw = roundf(sw * scale_x); + int dh = roundf(sh * scale_y); + + if (dw <= 0 || dh <= 0) + return; + + for (int y = 0; y < dh; y++) + { + for (int x = 0; x < dw; x++) + { + int src_x = sx + (flip_x ? (sw - 1 - (x * sw) / dw) : (x * sw) / dw); + int src_y = sy + (flip_y ? (sh - 1 - (y * sh) / dh) : (y * sh) / dh); + uint8_t index = gfx_get(src_x, src_y, MEMORY_SPRITES, MEMORY_SPRITES_SIZE); + uint8_t color = color_get(PALTYPE_DRAW, (int)index); + + if ((color & 0xf0) == 0) + pixel_set(dx + x, dy + y, index, 0, DRAWTYPE_SPRITE); + } + } +} + +static inline void draw_sprite(int n, int left, int top, bool flip_x, bool flip_y) +{ + int sx = (n & 0xF) * SPRITE_WIDTH; + int sy = (n >> 4) * SPRITE_HEIGHT; + + for (int y = 0; y < SPRITE_HEIGHT; y++) + { + for (int x = 0; x < SPRITE_WIDTH; x++) + { + int fx = flip_x ? (SPRITE_WIDTH - x - 1) : x; + int fy = flip_y ? (SPRITE_HEIGHT - y - 1) : y; + uint8_t index = gfx_get(sx + x, sy + y, MEMORY_SPRITES, MEMORY_SPRITES_SIZE); + uint8_t color = color_get(PALTYPE_DRAW, index); + + if ((color & 0xf0) == 0) + pixel_set(left + fx, top + fy, index, 0, DRAWTYPE_SPRITE); + } + } +} + +static inline void draw_sprites(int n, int x, int y, int w, int h, bool flip_x, bool flip_y) +{ + for (int sy = 0; sy < h; sy++) + { + for (int sx = 0; sx < w; sx++) + { + int index = (n == -1 ? 0 : n) + sx + sy * 16; + int left = x + (flip_x ? (w - 1 - sx) : sx) * 8; + int top = y + (flip_y ? (h - 1 - sy) : sy) * 8; + draw_sprite(index, left, top, flip_x, flip_y); + } + } +} + +static inline void draw_char(int n, int left, int top, int col) +{ + int sx = n % 16 * 8; + int sy = n / 16 * 8; + + for (int y = 0; y < 8; y++) + { + for (int x = 0; x < 8; x++) + { + uint8_t index = gfx_addr_get(sx + x, sy + y, (uint8_t *)font_map, 0, sizeof(font_map)); + if (index == 7) + pixel_set(left + x, top + y, col, 0, DRAWTYPE_DEFAULT); + } + } +} + +static inline int get_p8_symbol(const char *str, int str_len, uint8_t *symbol_length) +{ + int p8_symbols_len = sizeof(p8_symbols) / sizeof(p8_symbol_t); + + for (int i = 0; i < p8_symbols_len; i++) + { + const uint8_t *encoding = p8_symbols[i].encoding; + *symbol_length = p8_symbols[i].length; + + if (*symbol_length > str_len) + continue; + + if (memcmp(str, encoding, *symbol_length) == 0) + return p8_symbols[i].index; + } + + return -1; +} + +// Simple text drawing - draws a single line with no P8SCII support +static inline void draw_simple_text(const char *str, int x, int y, int col) +{ + int cursor_x = x; + for (const char *c = str; *c != '\0'; c++) { + draw_char((uint8_t)*c, cursor_x, y, col); + if ((uint8_t)*c >= 0x80) + cursor_x += GLYPH_WIDTH * 2; + else + cursor_x += GLYPH_WIDTH; + } +} + +static inline int gfx_addr_remap(int location) +{ + if (location == MEMORY_SPRITES) + return m_memory[MEMORY_SPRITE_PHYS] << 8; + else if (location == MEMORY_SCREEN) + return m_memory[MEMORY_SCREEN_PHYS] << 8; + else + return location; +} + +static inline uint8_t gfx_addr_get(int x, int y, uint8_t *memory, int location, int size) +{ + if (x < 0 || y < 0 || x > P8_WIDTH || y > P8_HEIGHT) + return 0; + int offset = gfx_addr_remap(location) + (x >> 1) + y * 64; + + return IS_EVEN(x) ? memory[offset] & 0xF : memory[offset] >> 4; +} + +static inline uint8_t gfx_get(int x, int y, int location, int size) +{ + if (x < 0 || y < 0 || x > P8_WIDTH || y > P8_HEIGHT) + return 0; + return gfx_addr_get(x, y, m_memory, location, size); +} + +static inline void gfx_set(int x, int y, int location, int size, int col) +{ + if (x < 0 || y < 0 || x > P8_WIDTH || y > P8_HEIGHT) + return; + + int offset = gfx_addr_remap(location) + (x >> 1) + y * 64; + uint8_t rw_mask = m_memory[MEMORY_RW_MASK]; + if (location == MEMORY_SCREEN && rw_mask != 0xff) { + uint8_t write_mask = rw_mask & 0xf; + uint8_t read_mask = (rw_mask >> 4) & 0xf; + uint8_t dst = IS_EVEN(x) ? m_memory[offset] & 0xf : m_memory[offset] >> 4; + uint8_t src = col & 0xf; + uint8_t result = (dst & ~write_mask) | (src & write_mask & read_mask); + m_memory[offset] = IS_EVEN(x) ? (m_memory[offset] & 0xF0) | result : (result << 4) | (m_memory[offset] & 0xF); + } else { + m_memory[offset] = IS_EVEN(x) ? (m_memory[offset] & 0xF0) | (col & 0xF) : (col << 4) | (m_memory[offset] & 0xF); + } +} + +static inline void camera_get(int *x, int *y) +{ + int16_t cx = (m_memory[MEMORY_CAMERA + 1] << 8) | m_memory[MEMORY_CAMERA]; + int16_t cy = (m_memory[MEMORY_CAMERA + 3] << 8) | m_memory[MEMORY_CAMERA + 2]; + *x = cx; + *y = cy; +} + +static inline void camera_set(int x, int y) +{ + m_memory[MEMORY_CAMERA] = x & 0xff; + m_memory[MEMORY_CAMERA + 1] = x >> 8; + m_memory[MEMORY_CAMERA + 2] = y & 0xff; + m_memory[MEMORY_CAMERA + 3] = y >> 8; +} + +static inline uint8_t pencolor_get() +{ + return m_memory[MEMORY_PENCOLOR]; +} + +static inline void pencolor_set(uint8_t col) +{ + m_memory[MEMORY_PENCOLOR] = col; +} + +static inline uint8_t color_get(int type, int index) +{ + if (type == PALTYPE_SECONDARY) + return m_memory[MEMORY_PALETTE_SECONDARY + (index & 0xf)]; + else + return m_memory[MEMORY_PALETTES + type * 16 + (index & 0xf)]; +} + +static inline void color_set(int type, int index, int col) +{ + if (type == PALTYPE_SECONDARY) + m_memory[MEMORY_PALETTE_SECONDARY + (index & 0xf)] = col; + else + m_memory[MEMORY_PALETTES + type * 16 + (index & 0xf)] = col; +} + +static inline void clip_set(int x, int y, int w, int h) +{ + int x1 = x + w; + int y1 = y + h; + if (x1 < 0) x1 = 0; + if (y1 < 0) y1 = 0; + m_memory[MEMORY_CLIPRECT] = x; + m_memory[MEMORY_CLIPRECT + 1] = y; + m_memory[MEMORY_CLIPRECT + 2] = (uint8_t)x1; + m_memory[MEMORY_CLIPRECT + 3] = (uint8_t)y1; +} + +static inline void clip_get(int *x0, int *y0, int *x1, int *y1) +{ + *x0 = m_memory[MEMORY_CLIPRECT]; + *y0 = m_memory[MEMORY_CLIPRECT + 1]; + *x1 = m_memory[MEMORY_CLIPRECT + 2]; + *y1 = m_memory[MEMORY_CLIPRECT + 3]; +} + +static inline void cursor_set(int x, int y, int col) +{ + m_memory[MEMORY_CURSOR] = x; + m_memory[MEMORY_CURSOR + 1] = y; + + if (col != -1) + pencolor_set(col); +} + +static inline void cursor_get(int *x, int *y) +{ + *x = (int)m_memory[MEMORY_CURSOR]; + *y = (int)m_memory[MEMORY_CURSOR + 1]; +} + +static inline int map_cell_addr(int celx, int cely) +{ + if (celx < 0 || cely < 0) + return 0; + + uint8_t map_start = m_memory[MEMORY_MAP_START]; + if ((map_start >= 0x10 && map_start < 0x20) || + (map_start >= 0x30 && map_start < 0x3f)) + return 0; + if (map_start < 0x10 || + (map_start >= 0x40 && map_start < 0x80)) + map_start = 0x20; + if (map_start < 0x80) { + int start_offset = m_memory[MEMORY_MAP_START] & 0x0f; + if (cely >= 32 && cely + start_offset >= 64) + return 0; + } + if (cely >= 32 && map_start < 0x80) { + map_start = 0x10; + cely -= 32; + } + + int map_width = m_memory[MEMORY_MAP_WIDTH]; + if (map_width == 0) + map_width = 256; + + int map_base = map_start << 8; + int offset = celx + cely * map_width; + int address = map_base + offset; + + if (address < 0x1000 || address >= 0x10000 || + (address >= 0x3000 && address < 0x8000)) + return 0; + + return address; +} + +static inline uint8_t map_get(int celx, int cely) +{ + int address = map_cell_addr(celx, cely); + if (address == 0) + return 0; + return m_memory[address]; +} + +static inline void map_set(int celx, int cely, int snum) +{ + int address = map_cell_addr(celx, cely); + if (address == 0) + return; + m_memory[address] = snum; +} + +static inline void reset_color() +{ + for (int i = 0; i < 16; i++) + { + color_set(PALTYPE_DRAW, i, i == 0 ? i | 0x10 : i); + color_set(PALTYPE_SCREEN, i, i); + } + color_set(PALTYPE_SECONDARY, 0, 0x00); + color_set(PALTYPE_SECONDARY, 1, 0x01); + color_set(PALTYPE_SECONDARY, 2, 0x12); + color_set(PALTYPE_SECONDARY, 3, 0x13); + color_set(PALTYPE_SECONDARY, 4, 0x24); + color_set(PALTYPE_SECONDARY, 5, 0x15); + color_set(PALTYPE_SECONDARY, 6, 0xd6); + color_set(PALTYPE_SECONDARY, 7, 0x67); + color_set(PALTYPE_SECONDARY, 8, 0x48); + color_set(PALTYPE_SECONDARY, 9, 0x49); + color_set(PALTYPE_SECONDARY, 10, 0x9a); + color_set(PALTYPE_SECONDARY, 11, 0x3b); + color_set(PALTYPE_SECONDARY, 12, 0xdc); + color_set(PALTYPE_SECONDARY, 13, 0x5d); + color_set(PALTYPE_SECONDARY, 14, 0x8e); + color_set(PALTYPE_SECONDARY, 15, 0xef); +} + +static inline bool is_button_set(int index, int button, bool btnp) +{ + uint16_t mask = (btnp?m_buttonsp:m_buttons)[index]; + return mask & (1 << button); +} + +static inline int scroll(int y, int line_height) +{ + int bottom = P8_HEIGHT - line_height; + int scrolly = MAX(y - bottom, 0); + if (scrolly == 0) + return y; + memmove(m_memory + (m_memory[MEMORY_SCREEN_PHYS] << 8), m_memory + (m_memory[MEMORY_SCREEN_PHYS] << 8) + 64 * scrolly, 0x2000 - 64 * scrolly); + memset(m_memory + (m_memory[MEMORY_SCREEN_PHYS] << 8) + 0x2000 - 64 * scrolly, 0, 64 * scrolly); + return y - scrolly; +} + +static inline int scroll_newline(int y) +{ + int threshold = P8_HEIGHT - GLYPH_HEIGHT; + if (y <= threshold) + return y; + int scrolly = MAX(y - threshold, GLYPH_HEIGHT); + memmove(m_memory + (m_memory[MEMORY_SCREEN_PHYS] << 8), m_memory + (m_memory[MEMORY_SCREEN_PHYS] << 8) + 64 * scrolly, 0x2000 - 64 * scrolly); + memset(m_memory + (m_memory[MEMORY_SCREEN_PHYS] << 8) + 0x2000 - 64 * scrolly, 0, 64 * scrolly); + return y - scrolly; +} + +static inline int left_margin_get(void) +{ + return m_memory[MEMORY_LEFT_MARGIN]; +} + +static inline void left_margin_set(int x) +{ + m_memory[MEMORY_LEFT_MARGIN] = x; +} + +#endif diff --git a/components/pico8/femto8/src/p8_options.c b/components/pico8/femto8/src/p8_options.c new file mode 100644 index 00000000..7af263e4 --- /dev/null +++ b/components/pico8/femto8/src/p8_options.c @@ -0,0 +1,77 @@ +/** + * Copyright (C) 2026 Chris January + */ + +#include + +#include "p8_options.h" +#include "p8_dialog.h" +#include "p8_emu.h" +#include "p8_overlay_helper.h" + +/* Height of the keyboard reference card drawing area (in pixels) */ +#define CONTROLS_CARD_HEIGHT 38 + +/* Draw the keyboard reference card for the controls dialog */ +static void draw_controls_card(const p8_dialog_t *dialog, void *user_data, int x, int y, int width, int height) +{ + (void)dialog; + (void)user_data; + (void)height; + + int col_w = width / 2; + int col2 = x + col_w; + int ry = y; + + /* Inverted header row: "player 1" left, "player 2" right */ + overlay_draw_rectfill(x, ry, x + col_w - GLYPH_WIDTH - 1, ry + GLYPH_HEIGHT - 1, DIALOG_BG_INVERTED); + overlay_draw_simple_text("player 1", x + 1, ry, DIALOG_TEXT_INVERTED); + overlay_draw_rectfill(col2, ry, col2 + col_w - 1, ry + GLYPH_HEIGHT - 1, DIALOG_BG_INVERTED); + overlay_draw_simple_text("player 2", col2 + 1, ry, DIALOG_TEXT_INVERTED); + ry += GLYPH_HEIGHT + 2; + + /* Movement row */ + overlay_draw_simple_text("arrows", x, ry, DIALOG_TEXT_NORMAL); + overlay_draw_simple_text("move", x + 7 * GLYPH_WIDTH, ry, DIALOG_TEXT_NORMAL); + overlay_draw_simple_text("s/d/e/f", col2, ry, DIALOG_TEXT_NORMAL); + overlay_draw_simple_text("move", col2 + 9 * GLYPH_WIDTH, ry, DIALOG_TEXT_NORMAL); + ry += GLYPH_HEIGHT + 1; + + /* Button 1 row */ + overlay_draw_simple_text("z,c,n", x, ry, DIALOG_TEXT_NORMAL); + overlay_draw_simple_text("btn 1", x + 7 * GLYPH_WIDTH, ry, DIALOG_TEXT_NORMAL); + overlay_draw_simple_text("tab/shft", col2, ry, DIALOG_TEXT_NORMAL); + overlay_draw_simple_text("btn 1", col2 + 9 * GLYPH_WIDTH, ry, DIALOG_TEXT_NORMAL); + ry += GLYPH_HEIGHT + 1; + + /* Button 2 row */ + overlay_draw_simple_text("x,m,v", x, ry, DIALOG_TEXT_NORMAL); + overlay_draw_simple_text("btn 2", x + 7 * GLYPH_WIDTH, ry, DIALOG_TEXT_NORMAL); + overlay_draw_simple_text("q,a", col2, ry, DIALOG_TEXT_NORMAL); + overlay_draw_simple_text("btn 2", col2 + 9 * GLYPH_WIDTH, ry, DIALOG_TEXT_NORMAL); + ry += GLYPH_HEIGHT + 2; + + /* Separator line */ + overlay_draw_hline(x, x + width - 1, ry, DIALOG_TEXT_NORMAL); + ry += 2; + + /* Pause row (spans both columns) */ + overlay_draw_simple_text("p/enter", x, ry, DIALOG_TEXT_NORMAL); + overlay_draw_simple_text("pause", x + 8 * GLYPH_WIDTH, ry, DIALOG_TEXT_NORMAL); +} + +/* Show the keyboard controls reference card dialog */ +void p8_show_controls_dialog(void) +{ + p8_dialog_control_t controls[] = { + DIALOG_CUSTOM_CONTROL(110, CONTROLS_CARD_HEIGHT, draw_controls_card, NULL), + DIALOG_SPACING(), + DIALOG_BUTTONBAR_OK_ONLY() + }; + + p8_dialog_t dialog; + p8_dialog_init(&dialog, "controls", controls, + sizeof(controls) / sizeof(controls[0]), 120); + p8_dialog_run(&dialog); + p8_dialog_cleanup(&dialog); +} diff --git a/components/pico8/femto8/src/p8_options.h b/components/pico8/femto8/src/p8_options.h new file mode 100644 index 00000000..99eb7e4e --- /dev/null +++ b/components/pico8/femto8/src/p8_options.h @@ -0,0 +1,13 @@ +/** + * Copyright (C) 2026 Chris January + */ + +#ifndef P8_OPTIONS_H +#define P8_OPTIONS_H + +/** + * Show the keyboard controls reference card dialog. + */ +void p8_show_controls_dialog(void); + +#endif /* P8_OPTIONS_H */ diff --git a/components/pico8/femto8/src/p8_overlay_helper.h b/components/pico8/femto8/src/p8_overlay_helper.h new file mode 100644 index 00000000..9c3c6234 --- /dev/null +++ b/components/pico8/femto8/src/p8_overlay_helper.h @@ -0,0 +1,271 @@ +/** + * Copyright (C) 2026 Chris January + */ + +#ifndef P8_OVERLAY_HELPER_H +#define P8_OVERLAY_HELPER_H + +#include +#include +#include +#include +#include "p8_emu.h" +#include "pico_font.h" + +/* Overlay clip region (global state) */ +static int overlay_clip_x0 = 0; +static int overlay_clip_y0 = 0; +static int overlay_clip_x1 = P8_WIDTH; +static int overlay_clip_y1 = P8_HEIGHT; + +static inline void overlay_clip_set(int x, int y, int w, int h) +{ + overlay_clip_x0 = x; + overlay_clip_y0 = y; + overlay_clip_x1 = x + w; + overlay_clip_y1 = y + h; +} + +static inline void overlay_clip_reset(void) +{ + overlay_clip_x0 = 0; + overlay_clip_y0 = 0; + overlay_clip_x1 = P8_WIDTH; + overlay_clip_y1 = P8_HEIGHT; +} + +static inline void overlay_clip_get(int *x, int *y, int *w, int *h) +{ + *x = overlay_clip_x0; + *y = overlay_clip_y0; + *w = overlay_clip_x1 - overlay_clip_x0; + *h = overlay_clip_y1 - overlay_clip_y0; +} + +static inline void overlay_draw_hline(int x0, int x1, int y, int col) +{ + if (y < overlay_clip_y0 || y >= overlay_clip_y1) + return; + + if (x0 > x1) { + int tmp = x0; + x0 = x1; + x1 = tmp; + } + + if (x0 < overlay_clip_x0) x0 = overlay_clip_x0; + if (x1 >= overlay_clip_x1) x1 = overlay_clip_x1 - 1; + + uint8_t *dest = m_overlay_memory + ((x0 >> 1) + y * 64); + + + // Handle odd start + if (x0 & 1) { + *dest = (col << 4) | (*dest & 0xF); + dest++; + x0++; + } + + for (int x = x0; x < x1; x += 2) + *dest++ = (col & 0xF) | (col << 4); + + if ((x1 & 1) == 0) + *dest = (*dest & 0xF0) | (col & 0xF); +} + +static inline void overlay_draw_vline(int x, int y0, int y1, int col) +{ + if (x < overlay_clip_x0 || x >= overlay_clip_x1) + return; + + if (y0 > y1) { + int tmp = y0; + y0 = y1; + y1 = tmp; + } + + if (y0 < overlay_clip_y0) y0 = overlay_clip_y0; + if (y1 >= overlay_clip_y1) y1 = overlay_clip_y1 - 1; + + uint8_t *dest = m_overlay_memory + (x >> 1) + y0 * 64; + + if ((x & 1) == 0) { + for (int y = y0; y <= y1; y++) { + *dest = (*dest & 0xF0) | (col & 0xF); + dest += 64; + } + } else { + for (int y = y0; y <= y1; y++) { + *dest = (col << 4) | (*dest & 0xF); + dest += 64; + } + } +} + +static inline void overlay_draw_rect(int x0, int y0, int x1, int y1, int col) +{ + overlay_draw_hline(x0, x1, y0, col); + overlay_draw_hline(x0, x1, y1, col); + overlay_draw_vline(x0, y0, y1, col); + overlay_draw_vline(x1, y0, y1, col); +} + +static inline void overlay_draw_rectfill(int x0, int y0, int x1, int y1, int col) +{ + if (x0 > x1) { + int tmp = x0; + x0 = x1; + x1 = tmp; + } + + if (y0 > y1) { + int tmp = y0; + y0 = y1; + y1 = tmp; + } + + if (x0 < overlay_clip_x0) x0 = overlay_clip_x0; + if (y0 < overlay_clip_y0) y0 = overlay_clip_y0; + if (x1 >= overlay_clip_x1) x1 = overlay_clip_x1 - 1; + if (y1 >= overlay_clip_y1) y1 = overlay_clip_y1 - 1; + + if (x0 & 1) { + uint8_t *dest = m_overlay_memory + ((x0 >> 1) + y0 * 64); + for (int y = y0; y <= y1; y++) { + *dest = (col << 4) | (*dest & 0xF); + dest += 64; + } + x0++; + } + + for (int y = y0; y <= y1; y++) { + uint8_t *dest = m_overlay_memory + ((x0 >> 1) + y * 64); + for (int x = x0; x < x1; x += 2) + *dest++ = (col & 0xF) | (col << 4); + } + + if ((x1 & 1) == 0) { + uint8_t *dest = m_overlay_memory + ((x1 >> 1) + y0 * 64); + for (int y = y0; y <= y1; y++) { + *dest = (*dest & 0xF0) | (col & 0xF); + dest += 64; + } + } +} + +static inline int overlay_get_text_width(const char *text) +{ + int w = 0; + for (const char *c = text; *c != '\0'; c++) { + if ((uint8_t)*c >= 0x80) + w += GLYPH_WIDTH * 2; + else + w += GLYPH_WIDTH; + } + return w; +} + +static inline int overlay_get_text_width_len(const char *text, size_t len) +{ + int w = 0; + for (size_t i = 0; i < len && text[i] != '\0'; i++) { + if ((uint8_t)text[i] >= 0x80) + w += GLYPH_WIDTH * 2; + else + w += GLYPH_WIDTH; + } + return w; +} + +static inline void overlay_pixel(int x, int y, int col) +{ + if (x < overlay_clip_x0 || y < overlay_clip_y0 || x >= overlay_clip_x1 || y >= overlay_clip_y1) + return; + + uint8_t *dest = m_overlay_memory + (x >> 1) + y * 64; + if (x & 1) + *dest = (col << 4) | (*dest & 0xF); + else + *dest = (*dest & 0xF0) | (col & 0xF); +} + +static inline void overlay_draw_char(int n, int left, int top, int col) +{ + int sx = n % 16 * 8; + int sy = n / 16 * 8; + + for (int y = 0; y < 8; y++) + { + for (int x = 0; x < 8; x++) + { + uint8_t index = font_map[(sx + x) / 2 + (sy + y) * 64]; + if (((sx + x) & 1) == 0) + index = index & 0xF; + else + index = index >> 4; + + if (index == 7) + overlay_pixel(left + x, top + y, col); + } + } +} + +static inline void overlay_scroll_one_line() +{ + memmove(m_overlay_memory, m_overlay_memory + 64 * GLYPH_HEIGHT, 0x2000 - 64 * GLYPH_HEIGHT); + memset(m_overlay_memory + 0x2000 - 64 * GLYPH_HEIGHT, 0, 64 * GLYPH_HEIGHT); +} + +static inline int overlay_draw_text(const char *str, int x, int y, int col) +{ + int cursor_x = x; + int cursor_y = y; + for (const char *c = str; *c != '\0'; c++) { + overlay_draw_char((uint8_t)*c, cursor_x, cursor_y, col); + if ((uint8_t)*c >= 0x80) + cursor_x += GLYPH_WIDTH * 2; + else + cursor_x += GLYPH_WIDTH; + if (cursor_x >= P8_WIDTH) { + cursor_x = 0; + cursor_y += GLYPH_HEIGHT; + } + if (cursor_y > P8_HEIGHT - GLYPH_HEIGHT) { + overlay_scroll_one_line(); + cursor_y -= GLYPH_HEIGHT; + } + } + return cursor_x; +} + +static inline void overlay_draw_simple_text(const char *str, int x, int y, int col) +{ + int cursor_x = x; + for (const char *c = str; *c != '\0'; c++) { + overlay_draw_char((uint8_t)*c, cursor_x, y, col); + if ((uint8_t)*c >= 0x80) + cursor_x += GLYPH_WIDTH * 2; + else + cursor_x += GLYPH_WIDTH; + } +} + +static inline void overlay_clear(void) +{ + memset(m_overlay_memory, OVERLAY_TRANSPARENT_COLOR, MEMORY_SCREEN_SIZE); +} + +static inline void overlay_draw_icon(const uint8_t *icon, int x, int y) +{ + assert((x & 1) == 0); + uint8_t *dest = m_overlay_memory + (x >> 1) + y * 64; + for (int r=0;r<8;++r) { + *dest++ = *icon++; + *dest++ = *icon++; + *dest++ = *icon++; + *dest++ = *icon++; + dest += 60; + } +} + +#endif /* P8_OVERLAY_HELPER_H */ diff --git a/components/pico8/femto8/src/p8_parser.c b/components/pico8/femto8/src/p8_parser.c new file mode 100644 index 00000000..0063682f --- /dev/null +++ b/components/pico8/femto8/src/p8_parser.c @@ -0,0 +1,678 @@ +/* + * p8_parser.c + * + * Created on: Dec 13, 2023 + * Author: bbaker + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "lodepng.h" +#include "p8_emu.h" +#include "pico8.h" +#include "p8_lua_helper.h" +#include "strtcpy.h" + +#ifndef PATH_MAX +#define PATH_MAX 256 +#endif + +#define RAW_DATA_LENGTH 0x4300 +#define IMAGE_WIDTH 160 +#define IMAGE_HEIGHT 205 + +enum P8Type +{ + P8TYPE_START = 0, + P8TYPE_IDENT, + P8TYPE_VERSION, + P8TYPE_LUA, + P8TYPE_GFX_4BIT, + P8TYPE_GFX_8BIT, + P8TYPE_GFF, + P8TYPE_LABEL, + P8TYPE_MAP, + P8TYPE_SFX, + P8TYPE_MUSIC, + P8TYPE_COUNT, +}; + +static const char *m_p8_name[] = { + NULL, + "pico-8 cartridge", + "version", + "__lua__", + "__gfx__", + "__gfx8__", + "__gff__", + "__label__", + "__map__", + "__sfx__", + "__music__", +}; + +static int m_p8_mem_offset[] = { + 0, + 0, + 0, + 0, + MEMORY_SPRITES, + 0, + MEMORY_SPRITEFLAGS, + 0, + MEMORY_MAP, + MEMORY_SFX, + MEMORY_MUSIC, +}; + +#if defined(_WIN32) || defined(__MINGW32__) +static char* strsep_portable(char **stringp, const char *delim) +{ + char *start, *p; + if (stringp == NULL || *stringp == NULL) return NULL; + + start = *stringp; + for (p = start; *p; ++p) { + const char *d; + for (d = delim; *d; ++d) { + if (*p == *d) { + *p = '\0'; + *stringp = p + 1; + return start; + } + } + } + *stringp = NULL; + return start; +} +#define strsep strsep_portable +#endif + +int parse_cart_ram(uint8_t *buffer, int size, uint8_t *memory, uint8_t *decompression_buffer, char *lua_script_out, uint8_t *label_image); +int parse_cart_file(const char *file_name, uint8_t *memory, uint8_t *file_buffer, uint8_t *decompression_buffer, char *lua_script_out, uint8_t *label_image); +int parse_png_ram(const char *file_name, uint8_t *buffer, int file_size, uint8_t *memory, uint8_t *decompression_buffer, const char **lua_script, uint8_t *label_image); +static int parse_p8_ram(const char *file_name, uint8_t *buffer, int size, uint8_t *memory, uint8_t *decompression_buffer, const char **lua_script, uint8_t *label_image); +static int process_includes(char *lua_script_out, const char *lua_script, const char *cart_dir); +static void convert_utf8_to_p8scii(uint8_t *buffer, size_t len); + +static uint8_t PNG_SIGNATURE[8] = {137, 80, 78, 71, 13, 10, 26, 10}; + +static int parse_cart_ram0(const char *file_name, uint8_t *buffer, int size, uint8_t *memory, uint8_t *decompression_buffer, const char **lua_script, uint8_t *label_image) +{ + if (size >= 8 && + memcmp(buffer, PNG_SIGNATURE, 8) == 0) { + return parse_png_ram(file_name, buffer, size, memory, decompression_buffer, lua_script, label_image); + } else { + return parse_p8_ram(file_name, buffer, size, memory, decompression_buffer, lua_script, label_image); + } +} + +int parse_cart_ram(uint8_t *buffer, int size, uint8_t *memory, uint8_t *decompression_buffer, char *lua_script_out, uint8_t *label_image) +{ + const char *lua_script = NULL; + if (parse_cart_ram0(NULL, buffer, size, memory, decompression_buffer, &lua_script, label_image) != 0) + return -1; + + if (lua_script) { + size_t lua_len = strnlen(lua_script, LUA_SCRIPT_SIZE); + memcpy(lua_script_out, lua_script, lua_len); + lua_script_out[lua_len] = '\0'; + } else { + lua_script_out[0] = '\0'; + } + + return 0; +} + +// process_includes: expand #include directives from lua_script into lua_script_out. +// Returns true if any includes were processed and lua_script_out was populated. +// Returns false if no includes found (caller should copy lua_script into lua_script_out). +static int process_includes(char *lua_script_out, const char *lua_script, const char *cart_dir) +{ + // Quick scan: any #include lines present? + const char *scan = lua_script; + bool has_includes = false; + while ((scan = strstr(scan, "#include")) != NULL) { + // Must be at start of line (or start of string) + if (scan == lua_script || scan[-1] == '\n') { + has_includes = true; + break; + } + scan += 8; + } + if (!has_includes) { + strtcpy(lua_script_out, lua_script, LUA_SCRIPT_SIZE); + return 0; + } + + // Build expanded content into lua_script_out + size_t capacity = LUA_SCRIPT_SIZE - 1; + size_t length = 0; + char *result = lua_script_out; + + const char *p = lua_script; + while (*p) { + // Find end of current line + const char *eol = strchr(p, '\n'); + int line_len = eol ? (int)(eol - p) : (int)strlen(p); + + // Check for #include at start of line + if (strncmp(p, "#include ", 9) == 0) { + // Extract filename (skip "#include ") + const char *fname_start = p + 9; + int fname_len = line_len - 9; + // Trim trailing whitespace/CR + while (fname_len > 0 && (fname_start[fname_len - 1] == ' ' || + fname_start[fname_len - 1] == '\r')) + fname_len--; + + if (fname_len > 0) { + // Build full path relative to the cart file's directory + char include_path[PATH_MAX]; + ssize_t dir_len_p = strtcpy(include_path, cart_dir, sizeof(include_path)); + size_t avail = (dir_len_p >= 0) ? sizeof(include_path) - (size_t)dir_len_p : 0; + if (avail >= 2 && (size_t)fname_len < avail - 1) { + include_path[dir_len_p] = '/'; + memcpy(include_path + dir_len_p + 1, fname_start, fname_len); + include_path[dir_len_p + 1 + fname_len] = '\0'; + } else { + fprintf(stderr, "Warning: #include path too long\n"); + errno = ENAMETOOLONG; + return -1; + } + + FILE *inc = fopen(include_path, "rb"); + if (inc) { + fseek(inc, 0, SEEK_END); + long inc_size = ftell(inc); + rewind(inc); + + if (length + (size_t)inc_size >= capacity) { + fprintf(stderr, "Warning: #include would exceed lua script buffer\n"); + fclose(inc); + errno = E2BIG; + return -1; + } else { + if (fread(result + length, 1, inc_size, inc) != (size_t)inc_size) { + int orig_errno = errno; + fprintf(stderr, "Error reading include file: %s\n", include_path); + fclose(inc); + errno = orig_errno; + return -1; + } + convert_utf8_to_p8scii((uint8_t *)(result + length), inc_size); + length += strlen(result + length); + fclose(inc); + + // Ensure included content ends with newline + if (length > 0 && result[length - 1] != '\n' && length < capacity) + result[length++] = '\n'; + } + } else { + int orig_errno = errno; + fprintf(stderr, "Warning: #include file not found: %s\n", include_path); + errno = orig_errno; + return -1; + } + } + } else { + // Copy line as-is (including newline) + int copy_len = eol ? line_len + 1 : line_len; + if (length + (size_t)copy_len >= capacity) { + fprintf(stderr, "Warning: lua script truncated at buffer limit\n"); + errno = E2BIG; + return -1; + } + memcpy(result + length, p, copy_len); + length += copy_len; + } + + p += line_len; + if (eol) + p++; // skip newline + } + + result[length] = '\0'; + return length; +} + +int parse_cart_file(const char *file_name, uint8_t *memory, uint8_t *file_buffer, uint8_t *decompression_buffer, char *lua_script_out, uint8_t *label_image) +{ + FILE *file = fopen(file_name, "rb"); + + if (file == NULL) + { + fprintf(stderr, "Error opening file: %s\n", file_name); + return -1; + } + + fseek(file, 0, SEEK_END); + long file_size = ftell(file); + rewind(file); + + if ((size_t)file_size >= FILE_BUFFER_SIZE) { + fprintf(stderr, "Error: cart file too large (%ld bytes): %s\n", file_size, file_name); + fclose(file); + return -1; + } + + if (fread(m_file_buffer, 1, file_size, file) != (size_t)file_size) { + fprintf(stderr, "Error reading file: %s\n", file_name); + fclose(file); + return -1; + } + + fclose(file); + + m_file_buffer[file_size] = '\0'; + + const char *lua_script = NULL; + if (parse_cart_ram0(file_name, m_file_buffer, (int)file_size, memory, decompression_buffer, &lua_script, label_image) != 0) + return -1; + + // lua_script either points into file_buffer or decompression_buffer + + if (lua_script_out) { + // Process #include directives in the Lua section + if (lua_script && file_name) { + const char *last_slash = strrchr(file_name, '/'); + char cart_dir[PATH_MAX]; + if (last_slash) { + size_t dir_len = last_slash - file_name; + if (dir_len >= sizeof(cart_dir)) + dir_len = sizeof(cart_dir) - 1; + memcpy(cart_dir, file_name, dir_len); + cart_dir[dir_len] = '\0'; + } else { + strtcpy(cart_dir, ".", sizeof(cart_dir)); + } + + // process_includes writes into lua_script_out directly + int ret = process_includes(lua_script_out, lua_script, cart_dir); + if (ret < 0) + return ret; + } else if (lua_script) { + size_t lua_len = strnlen(lua_script, LUA_SCRIPT_SIZE); + memcpy(lua_script_out, lua_script, lua_len); + lua_script_out[lua_len] = '\0'; + } else { + lua_script_out[0] = '\0'; + } + } + + return 0; +} + +static void convert_utf8_to_p8scii(uint8_t *buffer, size_t len) +{ + uint8_t *read_ptr = buffer; + uint8_t *write_ptr = buffer; + uint8_t *end_ptr = buffer + len; + + while (read_ptr < end_ptr) { + if (*read_ptr >= 0x80) { + uint8_t symbol_length; + int p8_index = get_p8_symbol((const char *)read_ptr, end_ptr - read_ptr, &symbol_length); + + if (p8_index >= 0) { + *write_ptr++ = (uint8_t)p8_index; + read_ptr += symbol_length; + } else { + *write_ptr++ = *read_ptr++; + } + } else { + *write_ptr++ = *read_ptr++; + } + } + + *write_ptr = '\0'; +} + +void hex_to_bytes(uint8_t *memory, char *str, int str_len, int *write_length) +{ + *write_length = 0; + + if (str == NULL) + return; + + if (str_len == 0) + return; + + int read_offset = 0; + int write_offset = 0; + + while (read_offset < str_len) + { + if (!isxdigit(str[read_offset])) + { + read_offset++; + continue; + } + unsigned int v; + sscanf(str + read_offset, "%2x", &v); + memory[write_offset] = (uint8_t)v; + read_offset += 2; + write_offset++; + } + + *write_length = write_offset; +} + +void read_sfx(uint8_t *dest, uint8_t *src, int read_length, int *write_length) +{ + int read_offset = 0; + int write_offset = 0; + + while (read_offset < read_length) + { + uint8_t byte_0 = src[read_offset++]; + uint8_t byte_1 = src[read_offset++]; + uint8_t byte_2 = src[read_offset++]; + uint8_t byte_3 = src[read_offset++]; + + for (int i = 0; i < 16; i++) + { + uint8_t byte_a = src[read_offset++]; + uint8_t byte_b = src[read_offset++]; + uint8_t byte_c = src[read_offset++]; + uint8_t byte_d = src[read_offset++]; + uint8_t byte_e = src[read_offset++]; + + uint8_t note1_pitch = byte_a; + uint8_t note1_waveform = byte_b >> 4; + uint8_t note1_volume = byte_b & 0xF; + uint8_t note1_effect = byte_c >> 4; + + uint8_t note2_pitch = (byte_c << 4) | (byte_d >> 4); + uint8_t note2_waveform = byte_d & 0xF; + uint8_t note2_volume = byte_e >> 4; + uint8_t note2_effect = byte_e & 0xF; + + uint16_t note1 = (note1_waveform > 7 ? 1 << 15 : 0) | + (note1_effect << 12) | (note1_volume << 9) | + ((note1_waveform > 7 ? note1_waveform - 8 : note1_waveform) << 6) | + note1_pitch; + uint16_t note2 = (note2_waveform > 7 ? 1 << 15 : 0) | + (note2_effect << 12) | (note2_volume << 9) | + ((note2_waveform > 7 ? note2_waveform - 8 : note2_waveform) << 6) | + note2_pitch; + + dest[write_offset++] = note1; + dest[write_offset++] = note1 >> 8; + dest[write_offset++] = note2; + dest[write_offset++] = note2 >> 8; + } + + dest[write_offset++] = byte_0; // Editor Mode + dest[write_offset++] = byte_1; // Speed + dest[write_offset++] = byte_2; // Loop Start + dest[write_offset++] = byte_3; // Loop End + } + + *write_length = write_offset; +} + +void read_music(uint8_t *dest, uint8_t *src, int read_length, int *write_length) +{ + int read_offset = 0; + int write_offset = 0; + + while (read_offset < read_length) + { + uint8_t flags_byte = src[read_offset++]; + uint8_t effect_id1 = src[read_offset++]; + uint8_t effect_id2 = src[read_offset++]; + uint8_t effect_id3 = src[read_offset++]; + uint8_t effect_id4 = src[read_offset++]; + + // On-disk flags bits 0-3 map to bit 7 of in-memory bytes 0-3 + dest[write_offset++] = (effect_id1 & 0x7F) | ((flags_byte & (1 << 0)) ? 0x80 : 0); + dest[write_offset++] = (effect_id2 & 0x7F) | ((flags_byte & (1 << 1)) ? 0x80 : 0); + dest[write_offset++] = (effect_id3 & 0x7F) | ((flags_byte & (1 << 2)) ? 0x80 : 0); + dest[write_offset++] = (effect_id4 & 0x7F) | ((flags_byte & (1 << 3)) ? 0x80 : 0); + } + + *write_length = write_offset; +} + +static int parse_p8_ram(const char *file_name, uint8_t *buffer, int size, uint8_t *memory, uint8_t *decompression_buffer, const char **lua_script, uint8_t *label_image) +{ + static uint8_t tmpbuf[180]; + char *line; + char *rest = (char *)buffer; + int lua_start = 0, lua_end = 0; + int p8_type = P8TYPE_START; + int file_offset = 0; + int write_offset = 0; + int read_length = 0; + int write_length = 0; + bool seen_ident = false; + + if (lua_script) + *lua_script = NULL; + + if (label_image) + memset(label_image, 0, 0x4000); + + while ((line = strsep(&rest, "\n")) != NULL) + { + int token_found = 0; + int line_length = rest ? (rest - line) : (size - file_offset); + + if (file_offset > 0) + line[-1] = '\n'; + + file_offset += line_length; + + for (int i = P8TYPE_IDENT; i < P8TYPE_COUNT; i++) + { + if (strncmp(line, m_p8_name[i], strlen(m_p8_name[i])) == 0) + { + p8_type = i; + write_offset = 0; + token_found = 1; + break; + } + } + + if (token_found) + { + if (p8_type == P8TYPE_LUA) + { + lua_start = file_offset; + lua_end = file_offset; + } + else if (p8_type == P8TYPE_IDENT) + { + seen_ident = true; + } + continue; + } + + switch (p8_type) + { + case P8TYPE_LUA: + { + lua_end += line_length; + break; + } + case P8TYPE_GFX_4BIT: + // case P8TYPE_GFX_8BIT: + case P8TYPE_GFF: + case P8TYPE_MAP: + { + uint8_t *write_mem = memory + m_p8_mem_offset[p8_type] + write_offset; + hex_to_bytes(write_mem, line, line_length-1, &write_length); + + write_offset += write_length; + break; + } + case P8TYPE_LABEL: + { + if (label_image) { + const char *hex_chars = "0123456789abcdefghijklmnopqrstuv"; + int x = 0; + for (int i = 0; i < line_length - 1 && x < 128; i++) { + char c = line[i]; + const char *pos = strchr(hex_chars, c); + if (pos) { + label_image[write_offset * 128 + x] = (uint8_t)(pos - hex_chars); + x++; + } + } + if (x > 0) write_offset++; + } + break; + } + case P8TYPE_SFX: + { + uint8_t *write_mem = memory + MEMORY_SFX + write_offset; + + hex_to_bytes(tmpbuf, line, line_length-1, &read_length); + + if (read_length > 0) + read_sfx(write_mem, tmpbuf, read_length, &write_length); + + write_offset += write_length; + break; + } + case P8TYPE_MUSIC: + { + uint8_t *write_mem = memory + MEMORY_MUSIC + write_offset; + + hex_to_bytes(tmpbuf, line, line_length-1, &read_length); + + if (read_length > 0) + read_music(write_mem, tmpbuf, read_length, &write_length); + + write_offset += write_length; + break; + } + } + } + + if (!seen_ident) { + fprintf(stderr, "Error: %s: missing pico-8 cartridge header\n", file_name ? file_name : ""); + return 1; + } + + for (int i = MEMORY_SPRITES; i < MEMORY_SPRITES + MEMORY_SPRITES_SIZE; i++) + memory[i] = NIBBLE_SWAP(memory[i]); + + for (int i = MEMORY_SPRITES_MAP; i < MEMORY_SPRITES_MAP + MEMORY_SPRITES_MAP_SIZE; i++) + memory[i] = NIBBLE_SWAP(memory[i]); + + buffer[lua_end] = '\0'; + + convert_utf8_to_p8scii(&buffer[lua_start], lua_end - lua_start); + + if (lua_script && lua_start) + *lua_script = (const char *) &buffer[lua_start]; + + return 0; +} + +#define PNG_WIDTH 160 +#define PNG_HEIGHT 205 + +int parse_png_ram(const char *file_name, uint8_t *buffer, int file_size, uint8_t *memory, uint8_t *decompression_buffer, const char **lua_script, uint8_t *label_image) +{ + if (lua_script) + *lua_script = NULL; + uint8_t *px_buffer = NULL; + unsigned width = 0, height = 0; + unsigned ret = lodepng_decode32(&px_buffer, &width, &height, buffer, file_size); + if (ret != 0) { + fprintf(stderr, "%s\n", lodepng_error_text(ret)); + return -1; + } + if (width != PNG_WIDTH || height != PNG_HEIGHT) { + free(px_buffer); + if (file_name) + fprintf(stderr, "%s: ", file_name); + fprintf(stderr, "PNG has wrong size: %dx%d (expected 160x205)\n", width, height); + return -1; + } + + if (label_image) { + // 32-colour extended palette (R, G, B) with the two least significant bits masked off + static const uint8_t palette[32][3] = { + {0, 0, 0}, {28, 40, 80}, {124, 36, 80}, {0, 132, 80}, + {168, 80, 52}, {92, 84, 76}, {192, 192, 196}, {252, 240, 232}, + {252, 0, 76}, {252, 160, 0}, {252, 236, 36}, {0, 228, 52}, + {40, 172, 252}, {128, 116, 156}, {252, 116, 168}, {252, 204, 168}, + {40, 24, 20}, {16, 28, 52}, {64, 32, 52}, {16, 80, 88}, + {116, 44, 40}, {72, 48, 56}, {160, 136, 120}, {240, 236, 124}, + {188, 16, 80}, {252, 108, 36}, {168, 228, 44}, {0, 180, 64}, + {4, 88, 180}, {116, 68, 100}, {252, 108, 88}, {252, 156, 128} + }; + + const int label_left = 16; + const int label_top = 24; + + for (int y = 0; y < 128; y++) { + for (int x = 0; x < 128; x += 2) { + int left_offset = ((label_top + y) * PNG_WIDTH + (label_left + x)) << 2; + int right_offset = ((label_top + y) * PNG_WIDTH + (label_left + x + 1)) << 2; + + uint8_t left_r = px_buffer[left_offset] & 0xFC; + uint8_t left_g = px_buffer[left_offset + 1] & 0xFC; + uint8_t left_b = px_buffer[left_offset + 2] & 0xFC; + + uint8_t right_r = px_buffer[right_offset] & 0xFC; + uint8_t right_g = px_buffer[right_offset + 1] & 0xFC; + uint8_t right_b = px_buffer[right_offset + 2] & 0xFC; + + // Find matching palette colour index for each pixel + uint8_t left_color = 0; + for (int i = 0; i < 32; i++) { + if (palette[i][0] == left_r && + palette[i][1] == left_g && + palette[i][2] == left_b) { + left_color = i; + break; + } + } + + uint8_t right_color = 0; + for (int i = 0; i < 32; i++) { + if (palette[i][0] == right_r && + palette[i][1] == right_g && + palette[i][2] == right_b) { + right_color = i; + break; + } + } + + label_image[y * 128 + x] = left_color; + label_image[y * 128 + x + 1] = right_color; + } + } + } + + uint8_t *px_buffer_in = px_buffer; + uint8_t *byte_buffer = px_buffer; + uint8_t *byte_buffer_out = byte_buffer; + for (unsigned i=0;i + +int parse_cart_ram(uint8_t *buffer, int size, uint8_t *memory, uint8_t *decompression_buffer, char *lua_script, uint8_t *label_image); +int parse_cart_file(const char *file_name, uint8_t *memory, uint8_t *file_buffer, uint8_t *decompression_buffer, char *lua_script, uint8_t *label_image); +int parse_png_ram(const char *file_name, uint8_t *buffer, int file_size, uint8_t *memory, uint8_t *decompression_buffer, const char **lua_script, uint8_t *label_image); + +#endif diff --git a/components/pico8/femto8/src/p8_pause_menu.c b/components/pico8/femto8/src/p8_pause_menu.c new file mode 100644 index 00000000..ab65d0df --- /dev/null +++ b/components/pico8/femto8/src/p8_pause_menu.c @@ -0,0 +1,200 @@ +/** + * Copyright (C) 2025 Chris January + */ + +#include +#include +#include +#include +#include "strtcpy.h" + +#include "p8_pause_menu.h" +#include "p8_emu.h" +#include "p8_dialog.h" +#include "p8_input.h" +#include "p8_overlay_helper.h" +#include "p8_options.h" +#include "p8_audio.h" +#include "lua.h" +#include "lauxlib.h" + +// Global Lua state (defined in p8_lua.c) +extern lua_State *L; + +// Custom menu item storage +p8_custom_menuitem_t m_custom_menuitems[MAX_CUSTOM_MENUITEMS]; + +void p8_menuitem_set(int index, const char *label, int lua_callback_ref) +{ + if (index < 1 || index > MAX_CUSTOM_MENUITEMS) + return; + p8_custom_menuitem_t *item = &m_custom_menuitems[index - 1]; + // Release old callback ref if any + if (item->lua_callback_ref != LUA_NOREF && L) + luaL_unref(L, LUA_REGISTRYINDEX, item->lua_callback_ref); + item->active = true; + strtcpy(item->label, label ? label : "", sizeof(item->label)); + item->lua_callback_ref = lua_callback_ref; +} + +void p8_menuitem_set_label(int index, const char *label) +{ + if (index < 1 || index > MAX_CUSTOM_MENUITEMS) + return; + p8_custom_menuitem_t *item = &m_custom_menuitems[index - 1]; + item->active = true; + strtcpy(item->label, label ? label : "", sizeof(item->label)); +} + +void p8_menuitem_clear(int index) +{ + if (index < 1 || index > MAX_CUSTOM_MENUITEMS) + return; + p8_custom_menuitem_t *item = &m_custom_menuitems[index - 1]; + if (item->lua_callback_ref != LUA_NOREF && L) + luaL_unref(L, LUA_REGISTRYINDEX, item->lua_callback_ref); + item->active = false; + item->label[0] = '\0'; + item->lua_callback_ref = LUA_NOREF; +} + +void p8_menuitem_reset_all(void) +{ + for (int i = 0; i < MAX_CUSTOM_MENUITEMS; i++) { + if (m_custom_menuitems[i].lua_callback_ref != LUA_NOREF && L) + luaL_unref(L, LUA_REGISTRYINDEX, m_custom_menuitems[i].lua_callback_ref); + m_custom_menuitems[i].active = false; + m_custom_menuitems[i].label[0] = '\0'; + m_custom_menuitems[i].lua_callback_ref = LUA_NOREF; + } +} + +// Call a custom menuitem Lua callback. +// button: button bitmask (1=left, 2=right, 112=selected/O+X+Pause) +// Returns true if the callback returned a truthy value (keep menu open). +static bool call_menuitem_callback(int lua_callback_ref, int button) +{ + if (lua_callback_ref == LUA_NOREF || !L) + return false; + lua_rawgeti(L, LUA_REGISTRYINDEX, lua_callback_ref); + lua_pushinteger(L, button); + bool stay_open = false; + if (lua_pcall(L, 1, 1, 0) == 0) { + stay_open = lua_toboolean(L, -1); + lua_pop(L, 1); + } + return stay_open; +} + +// Action IDs for custom menu items: index 0..4 β†’ 100..104 +#define CUSTOM_MENUITEM_ACTION_BASE 100 + +void p8_show_pause_menu(void) +{ + if (m_dialog_showing) + return; + + /* 0x5f30: suppress next pause menu activation */ + if (m_memory[MEMORY_SUPPRESS_PAUSE] == 1) { + m_memory[MEMORY_SUPPRESS_PAUSE] = 0; + return; + } + + /* Pause audio during pause menu unless 0x5f2f == 2 */ + bool should_pause_audio = m_memory[MEMORY_AUDIO_PAUSE] != 2; + if (should_pause_audio) + audio_pause(); + + // Build dynamic controls array: + // "continue" + up to 5 custom items + "restart" + "show version" + "controls" + "quit" + p8_dialog_control_t pause_controls[5 + MAX_CUSTOM_MENUITEMS]; + int num_controls = 0; + + pause_controls[num_controls++] = (p8_dialog_control_t)DIALOG_MENUITEM("continue", 0); + + for (int i = 0; i < MAX_CUSTOM_MENUITEMS; i++) { + if (m_custom_menuitems[i].active) { + pause_controls[num_controls++] = (p8_dialog_control_t) + DIALOG_MENUITEM(m_custom_menuitems[i].label, + CUSTOM_MENUITEM_ACTION_BASE + i); + } + } + + pause_controls[num_controls++] = (p8_dialog_control_t)DIALOG_MENUITEM("restart", 1); + pause_controls[num_controls++] = (p8_dialog_control_t)DIALOG_MENUITEM("show version", 2); + pause_controls[num_controls++] = (p8_dialog_control_t)DIALOG_MENUITEM("controls", 3); + pause_controls[num_controls++] = (p8_dialog_control_t)DIALOG_MENUITEM("quit", 4); + + p8_dialog_t pause_dialog; + p8_dialog_init(&pause_dialog, NULL, pause_controls, num_controls, P8_WIDTH / 2); + + // Run dialog loop, allowing menuitem callbacks to keep the menu open + p8_dialog_set_showing(&pause_dialog, true); + + int action_id = -1; + while (!p8_is_quit_requested()) { + p8_dialog_draw(&pause_dialog); + p8_flip(); + p8_dialog_action_t result = p8_dialog_update(&pause_dialog); + + if (result.type == DIALOG_RESULT_NONE) + continue; + + if (result.type == DIALOG_RESULT_CANCELLED) { + // Escape pressed: treat as "continue" + break; + } + + if (result.type == DIALOG_RESULT_BUTTON) { + action_id = result.action_id; + + if (action_id >= CUSTOM_MENUITEM_ACTION_BASE && + action_id < CUSTOM_MENUITEM_ACTION_BASE + MAX_CUSTOM_MENUITEMS) { + // Custom menu item: translate button_mask to PICO-8 button bitmask + int idx = action_id - CUSTOM_MENUITEM_ACTION_BASE; + int button; + if (result.button_mask & BUTTON_MASK_LEFT) + button = 1; + else if (result.button_mask & BUTTON_MASK_RIGHT) + button = 2; + else + button = 112; // Selected: O + X + Pause bits combined + + bool stay = call_menuitem_callback( + m_custom_menuitems[idx].lua_callback_ref, button); + if (stay) + continue; // Keep menu open + break; + } + break; + } + + break; + } + + p8_dialog_set_showing(&pause_dialog, false); + p8_dialog_cleanup(&pause_dialog); + p8_flip(); // Ensure dialog hides immediately even if next flip is some time away + + if (should_pause_audio) + audio_resume(); + + switch (action_id) { + case 0: // Continue + break; + case 1: // Restart + p8_restart(); + break; + case 2: // Show version + p8_show_version_dialog(); + break; + case 3: // Controls + p8_show_controls_dialog(); + break; + case 4: // Quit + p8_abort(); + break; + default: + break; + } +} diff --git a/components/pico8/femto8/src/p8_pause_menu.h b/components/pico8/femto8/src/p8_pause_menu.h new file mode 100644 index 00000000..9e6fd25c --- /dev/null +++ b/components/pico8/femto8/src/p8_pause_menu.h @@ -0,0 +1,50 @@ +/** + * Copyright (C) 2025 Chris January + */ + +#ifndef P8_PAUSE_MENU_H +#define P8_PAUSE_MENU_H + +#include + +#define MAX_CUSTOM_MENUITEMS 5 + +typedef struct { + bool active; + char label[64]; + int lua_callback_ref; /* LUA_NOREF if no callback */ +} p8_custom_menuitem_t; + +extern p8_custom_menuitem_t m_custom_menuitems[MAX_CUSTOM_MENUITEMS]; + +extern void p8_show_pause_menu(void); + +/** + * Register or update a custom pause menu item. + * @param index 1-based item index (1..MAX_CUSTOM_MENUITEMS) + * @param label Display text (copied internally) + * @param lua_callback_ref Lua registry reference for callback, or LUA_NOREF + */ +void p8_menuitem_set(int index, const char *label, int lua_callback_ref); + +/** + * Update only the label of an existing custom pause menu item. + * The callback is preserved; the item is made active. + * @param index 1-based item index (1..MAX_CUSTOM_MENUITEMS) + * @param label New display text (copied internally) + */ +void p8_menuitem_set_label(int index, const char *label); + +/** + * Remove a custom pause menu item. + * @param index 1-based item index + */ +void p8_menuitem_clear(int index); + +/** + * Release all Lua callback refs and clear all custom menu items. + * Must be called with a valid lua_State before closing it. + */ +void p8_menuitem_reset_all(void); + +#endif diff --git a/components/pico8/femto8/src/p8_print_helper.h b/components/pico8/femto8/src/p8_print_helper.h new file mode 100644 index 00000000..942af524 --- /dev/null +++ b/components/pico8/femto8/src/p8_print_helper.h @@ -0,0 +1,646 @@ +/* + * p8_print_helper.h + * + * Print and P8SCII support + */ + +#ifndef P8_PRINT_HELPER_H +#define P8_PRINT_HELPER_H + +#include +#include +#include +#include +#include "p8_emu.h" +#include "p8_symbols.h" +#include "pico_font.h" +#include "p8_audio.h" +#include "p8_lua_helper.h" + +static inline int hexy(int c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + else if (c >= 'a' && c <= 'z') + return c - 'a' + 10; + else if (c >= 'A' && c <= 'Z') + return c - 'A' + 10; + else + return c; +} + +typedef struct { + bool wide; + bool tall; + bool stripey; + bool invert; + bool border; + bool solid_bg; + int char_w; + int char_h; + int char_w2; + bool outline_enabled; + int outline_colour; + int outline_mask; + bool outline_skip_interior; + bool use_custom_font; + int delay_frames; +} print_state_t; + +static inline int get_custom_font_char_width(int char_index) +{ + int base_width = (char_index < 128) ? m_memory[MEMORY_FONT] : m_memory[MEMORY_FONT + 1]; + + if (!(m_memory[MEMORY_FONT + 5] & 0x1) || char_index < 16) { + return base_width; + } + + int nibble_index = char_index - 16; + int byte_offset = 8 + nibble_index / 2; + uint8_t byte_val = m_memory[MEMORY_FONT + byte_offset]; + + int nibble = (nibble_index & 1) ? (byte_val >> 4) : (byte_val & 0xF); + + int adjust = (nibble & 0x7); + if (adjust >= 4) adjust -= 8; + + return base_width + adjust; +} + +static inline bool get_custom_font_y_offset(int char_index) +{ + if (!(m_memory[MEMORY_FONT + 5] & 0x1) || char_index < 16) { + return false; + } + + int nibble_index = char_index - 16; + int byte_offset = 8 + nibble_index / 2; + uint8_t byte_val = m_memory[MEMORY_FONT + byte_offset]; + + int nibble = (nibble_index & 1) ? (byte_val >> 4) : (byte_val & 0xF); + return (nibble & 0x8) != 0; +} + +static inline bool get_font_pixel(int char_index, int x, int y, bool use_custom_font) +{ + if (use_custom_font) { + if (char_index < 16) { + int sx = (char_index % 16) * 8; + int sy = (char_index / 16) * 8; + uint8_t index = gfx_addr_get(sx + x, sy + y, (uint8_t *)font_map, 0, sizeof(font_map)); + return (index == 7); + } + int offset = MEMORY_FONT + 128 + (char_index - 16) * 8 + y; + if (offset < MEMORY_FONT + MEMORY_FONT_SIZE) { + uint8_t row = m_memory[offset]; + return (row & (1 << x)) != 0; + } + return false; + } else { + int sx = (char_index % 16) * 8; + int sy = (char_index / 16) * 8; + uint8_t index = gfx_addr_get(sx + x, sy + y, (uint8_t *)font_map, 0, sizeof(font_map)); + return (index == 7); + } +} + +static inline void draw_char_styled(int n, int left, int top, int fg, int bg, print_state_t *state) +{ + int x_offset = 0; + int y_offset = 0; + + if (state->use_custom_font) { + x_offset += m_memory[MEMORY_FONT + 3]; + y_offset += m_memory[MEMORY_FONT + 4]; + + if (get_custom_font_y_offset(n)) { + y_offset -= 1; + } + } + + int scale_x = state->wide ? 2 : 1; + int scale_y = state->tall ? 2 : 1; + + int render_width = state->use_custom_font ? get_custom_font_char_width(n) : (n >= 0x80 ? state->char_w2 : state->char_w); + int render_height = state->char_h; + if (render_width > 8) render_width = 8; + if (render_height > 8) render_height = 8; + + int outline_dx[] = {-1, 0, 1, -1, 1, -1, 0, 1}; + int outline_dy[] = {-1, -1, -1, 0, 0, 1, 1, 1}; + + for (int y = 0; y < state->char_h; y++) { + for (int x = 0; x < render_width; x++) { + bool is_fg = get_font_pixel(n, x, y, state->use_custom_font); + + if (state->invert) + is_fg = !is_fg; + + int colour = is_fg ? fg : bg; + if (colour == -1 && !is_fg) continue; + + if (state->outline_enabled && is_fg) { + for (int nb = 0; nb < 8; nb++) { + if (state->outline_mask & (1 << nb)) { + int nx = x + outline_dx[nb]; + int ny = y + outline_dy[nb]; + + bool neighbour_is_fg = false; + if (nx >= 0 && nx < 8 && ny >= 0 && ny < 8) { + neighbour_is_fg = get_font_pixel(n, nx, ny, state->use_custom_font); + if (state->invert) + neighbour_is_fg = !neighbour_is_fg; + } + + if (!neighbour_is_fg) { + for (int dy = 0; dy < scale_y; dy++) { + for (int dx = 0; dx < scale_x; dx++) { + if (state->stripey && !((dx + dy) & 1)) + continue; + int px = left + x_offset + x * scale_x + dx + outline_dx[nb]; + int py = top + y_offset + y * scale_y + dy + outline_dy[nb]; + pixel_set(px, py, state->outline_colour, 0, DRAWTYPE_DEFAULT); + } + } + } + } + } + } + + if (!state->outline_skip_interior || !is_fg) { + for (int dy = 0; dy < scale_y; dy++) { + for (int dx = 0; dx < scale_x; dx++) { + if (state->stripey && !((dx + dy) & 1)) + continue; + + int px = left + x_offset + x * scale_x + dx; + int py = top + y_offset + y * scale_y + dy; + pixel_set(px, py, colour, 0, DRAWTYPE_DEFAULT); + } + } + } + } + } +} + +static inline void draw_text(const char *str, unsigned str_len, int x, int y, int col, int left_margin, bool no_scroll, int *out_left, int *out_top, int *out_right) +{ + int right = x; + int repeat = 1; + int bg = 0; + int fg = col; + int tab_width = 16; + int wrap_boundary = 128; + int last_advance = GLYPH_WIDTH; + int home_x = x; + int home_y = y; + + uint8_t text_attrs = m_memory[MEMORY_TEXT_ATTRS]; + bool use_defaults = (text_attrs & 0x1) != 0; + + print_state_t state = { + .wide = use_defaults && (text_attrs & 0x4), + .tall = use_defaults && (text_attrs & 0x8), + .stripey = use_defaults && (text_attrs & 0x40), + .invert = use_defaults && (text_attrs & 0x20), + .border = use_defaults ? ((text_attrs & 0x2) != 0) : true, + .solid_bg = use_defaults && (text_attrs & 0x10), + .char_w = GLYPH_WIDTH, + .char_h = GLYPH_HEIGHT, + .char_w2 = GLYPH_WIDTH * 2, + .outline_enabled = false, + .outline_colour = 0, + .outline_mask = 0, + .outline_skip_interior = false, + .use_custom_font = use_defaults && (text_attrs & 0x80), + .delay_frames = 0 + }; + + if (state.use_custom_font) { + int font_height = m_memory[MEMORY_FONT + 2]; + if (font_height > 0) state.char_h = font_height; + } + + uint8_t char_size = m_memory[MEMORY_TEXT_CHAR_SIZE]; + uint8_t char_size2 = m_memory[MEMORY_TEXT_CHAR_SIZE2]; + int cw = char_size & 0xf; + int ch = (char_size >> 4) & 0xf; + int cw2 = char_size2 & 0xf; + int tw = (char_size2 >> 4) & 0xf; + if (cw > 0) + state.char_w = cw; + if (cw2 > 0) + state.char_w2 = cw2; + if (ch > 0) + state.char_h = ch; + if (tw > 0) + tab_width = tw; + + bool add_newline = (m_memory[MEMORY_MISCFLAGS] & 0x4) == 0; + bool wrap_enabled = (m_memory[MEMORY_MISCFLAGS] & 0x80) != 0; + bool memory_no_scroll = (m_memory[MEMORY_MISCFLAGS] & 0x40) != 0; + bool do_scroll = !memory_no_scroll && !no_scroll; + + for (unsigned i = 0; i < str_len; i++) + { + uint8_t character = str[i]; + int index = -1; + int old_repeat = repeat; + repeat = 1; + + for (int j = 0; j < old_repeat; j++) + { + if (character < 16) + { + switch (character) { + case 0: // "\0" + add_newline = false; + str_len = 0; + break; + case 1: // "\*" + if (i + 1 < str_len) + repeat = hexy(str[++i]); + break; + case 2: // "\#" + if (i + 1 < str_len) + { + bg = hexy(str[++i]); + state.solid_bg = true; + } + break; + case 3: // "\-" + if (i + 1 < str_len) + x += hexy(str[++i]) - 16; + break; + case 4: // "\|" + if (i + 1 < str_len) + y += hexy(str[++i]) - 16; + break; + case 5: // "\+" + if (i + 2 < str_len) { + x += hexy(str[++i]) - 16; + y += hexy(str[++i]) - 16; + } + break; + case 6: // "\^" + if (i + 1 < str_len) { + uint8_t cmd = str[++i]; + switch (cmd) { + case '1': case '2': case '3': case '4': case '5': + case '6': case '7': case '8': case '9': + { + int frames = 1 << (cmd - '1'); + for (int f = 0; f < frames; f++) { + p8_flip(); + } + } + break; + case 'c': + if (i + 1 < str_len) { + int clear_col = hexy(str[++i]); + clear_screen(clear_col); + x = 0; + y = 0; + home_x = 0; + home_y = 0; + left_margin = 0; + } + break; + case 'd': // "\^d" + if (i + 1 < str_len) { + state.delay_frames = hexy(str[++i]); + } + break; + case 'g': + x = home_x; + y = home_y; + break; + case 'h': + home_x = x; + home_y = y; + break; + case 'j': + if (i + 2 < str_len) { + x = hexy(str[++i]) * 4; + y = hexy(str[++i]) * 4; + } + break; + case 'r': + if (i + 1 < str_len) { + wrap_boundary = hexy(str[++i]) * 4; + wrap_enabled = true; + } + break; + case 's': + if (i + 1 < str_len) { + tab_width = hexy(str[++i]); + } + break; + case 'x': + if (i + 1 < str_len) { + state.char_w = hexy(str[++i]); + } + break; + case 'y': + if (i + 1 < str_len) { + state.char_h = hexy(str[++i]); + } + break; + case 'u': + break; + case 'w': + state.wide = true; + break; + case 't': + state.tall = true; + break; + case '=': + state.stripey = true; + break; + case 'p': + state.wide = true; + state.tall = true; + state.stripey = true; + break; + case 'i': + state.invert = true; + break; + case 'b': + state.border = !state.border; + break; + case '#': + state.solid_bg = true; + break; + case '-': + if (i + 1 < str_len) { + uint8_t flag = str[++i]; + switch (flag) { + case 'w': state.wide = false; break; + case 't': state.tall = false; break; + case '=': state.stripey = false; break; + case 'p': + state.wide = false; + state.tall = false; + state.stripey = false; + break; + case 'i': state.invert = false; break; + case 'b': state.border = !state.border; break; + case '#': + state.solid_bg = false; + break; + } + } + break; + case '.': + case ',': + if (i + 8 < str_len) { + bool respect_padding = (cmd == ','); + int draw_x = x + (respect_padding && state.border ? 1 : 0); + int draw_y = y + (respect_padding && state.border ? 1 : 0); + + for (int row = 0; row < 8 && i + 1 < str_len; row++) { + uint8_t byte = str[++i]; + for (int bit = 0; bit < 8; bit++) { + if (byte & (1 << bit)) { + pixel_set(draw_x + bit, draw_y + row, fg, 0, DRAWTYPE_DEFAULT); + } else if (state.solid_bg) { + pixel_set(draw_x + bit, draw_y + row, bg, 0, DRAWTYPE_DEFAULT); + } + } + } + x += 8; + last_advance = 8; + } + break; + case ':': + case ';': + if (i + 16 < str_len) { + bool respect_padding = (cmd == ';'); + int draw_x = x + (respect_padding && state.border ? 1 : 0); + int draw_y = y + (respect_padding && state.border ? 1 : 0); + + for (int row = 0; row < 8; row++) { + uint8_t byte = (hexy(str[i + row*2 + 1]) << 4) | hexy(str[i + row*2 + 2]); + for (int bit = 0; bit < 8; bit++) { + if (byte & (1 << bit)) { + pixel_set(draw_x + bit, draw_y + row, fg, 0, DRAWTYPE_DEFAULT); + } else if (state.solid_bg) { + pixel_set(draw_x + bit, draw_y + row, bg, 0, DRAWTYPE_DEFAULT); + } + } + } + i += 16; + x += 8; + last_advance = 8; + } + break; + case '@': + // \^@addrnnnn[data] β€” poke nnnn bytes to address addr + // addr and nnnn are 4 hex chars each + if (i + 8 < str_len) { + int addr = (hexy(str[i+1]) << 12) | (hexy(str[i+2]) << 8) | + (hexy(str[i+3]) << 4) | hexy(str[i+4]); + int count = (hexy(str[i+5]) << 12) | (hexy(str[i+6]) << 8) | + (hexy(str[i+7]) << 4) | hexy(str[i+8]); + i += 8; + for (int k = 0; k < count && i + 1 < str_len; k++) { + uint8_t byte = str[++i]; + if ((unsigned)(addr + k) < MEMORY_SIZE) + m_memory[addr + k] = byte; + } + + add_newline = (m_memory[MEMORY_MISCFLAGS] & 0x4) == 0; + wrap_enabled = (m_memory[MEMORY_MISCFLAGS] & 0x80) != 0; + memory_no_scroll = (m_memory[MEMORY_MISCFLAGS] & 0x40) != 0; + do_scroll = !memory_no_scroll && !no_scroll; + } + break; + case '!': + // \^!addr[data] β€” poke all remaining characters to address addr + // addr is 4 hex chars; remaining string bytes are data (not printed) + if (i + 4 < str_len) { + int addr = (hexy(str[i+1]) << 12) | (hexy(str[i+2]) << 8) | + (hexy(str[i+3]) << 4) | hexy(str[i+4]); + i += 4; + int k = 0; + while (i + 1 < str_len) { + uint8_t byte = str[++i]; + if ((unsigned)(addr + k) < MEMORY_SIZE) + m_memory[addr + k] = byte; + k++; + } + } + break; + case 'o': + if (i + 3 < str_len) { + uint8_t colour_char = str[++i]; + uint8_t mask_h = hexy(str[++i]); + uint8_t mask_l = hexy(str[++i]); + + state.outline_mask = (mask_h << 4) | mask_l; + + if (colour_char == '$') { + state.outline_colour = fg; + state.outline_skip_interior = false; + } else if (colour_char == '!') { + state.outline_colour = fg; + state.outline_skip_interior = true; + } else { + state.outline_colour = hexy(colour_char); + state.outline_skip_interior = false; + } + + state.outline_enabled = (state.outline_mask != 0); + } + break; + default: + break; + } + } + break; + case 7: // "\a" + if (i + 1 < str_len && hexy(str[i + 1]) != -1) { + if (i + 2 < str_len && hexy(str[i + 2]) != -1) { + int sfx_index = (hexy(str[i + 1]) << 4) | hexy(str[i + 2]); +#ifdef ENABLE_AUDIO + audio_sound(sfx_index, -1, 0, 32); +#endif + i += 2; + } + } else { + // TODO: note data support + } + break; + case 8: // "\b" + x -= last_advance; + break; + case 9: // "\t" + x = ((x / tab_width) + 1) * tab_width; + break; + case 0xa: // "\n" + x = left_margin; + y += state.char_h * (state.tall ? 2 : 1); + if (do_scroll) + y = scroll_newline(y); + break; + case 0xb: // "\v" + if (i + 2 < str_len) { + int offset_code = hexy(str[++i]); + uint8_t decoration_char = str[++i]; + + int offset_x = (offset_code % 4) - 2; + int offset_y = (offset_code / 4) - 8; + + int save_x = x; + int save_y = y; + + int dec_x = save_x - last_advance + offset_x; + int dec_y = save_y + offset_y; + + uint8_t symbol_length = 0; + int dec_index = get_p8_symbol((const char*)&decoration_char, 1, &symbol_length); + if (dec_index == -1) { + dec_index = decoration_char; + } + + if (dec_index >= 0x20 && dec_index < 0x7F) { + draw_char(dec_index, dec_x, dec_y, fg); + } + } + break; + case 0xc: // "\f" + if (i + 1 < str_len) { + fg = hexy(str[++i]); + if (fg > 15) fg = 16; + m_memory[MEMORY_PENCOLOR] = fg; + } + break; + case 0xd: // "\r" + x = left_margin; + break; + case 0xe: // "\014" + state.use_custom_font = true; + if (m_memory[MEMORY_FONT + 6] != 0) { + tab_width = m_memory[MEMORY_FONT + 6]; + } + if (m_memory[MEMORY_FONT + 2] != 0) { + state.char_h = m_memory[MEMORY_FONT + 2]; + } + break; + case 0xf: // "\015" + state.use_custom_font = false; + break; + default: + break; + } + } + else + { + if (character >= 0x20 && character < 0x7F) + { + index = character; + } + else + { + uint8_t symbol_length = 0; + index = get_p8_symbol(&str[i], str_len - i, &symbol_length); + + if (index != -1) + i += symbol_length - 1; + else + index = character; + } + + if (index >= 0) { + int base_char_width = state.use_custom_font ? get_custom_font_char_width(index) : (index >= 0x80 ? state.char_w2 : state.char_w); + int char_width = base_char_width * (state.wide ? 2 : 1); + + bool use_styled = state.wide || state.tall || state.invert || !state.border || state.outline_enabled || state.use_custom_font || (state.char_w != GLYPH_WIDTH) || (state.char_w2 != GLYPH_WIDTH) || (state.char_h != GLYPH_HEIGHT); + + if (wrap_enabled && x + char_width > wrap_boundary) { + x = left_margin; + y += state.char_h * (state.tall ? 2 : 1); + } + if (do_scroll) + y = scroll(y, state.char_h * (state.tall ? 2 : 1)); + + int draw_bg = state.solid_bg ? bg : -1; + if (use_styled) { + draw_char_styled(index, x, y, fg, draw_bg, &state); + } else if (draw_bg != -1) { + int char_height = state.char_h * (state.tall ? 2 : 1); + draw_rectfill(x, y, x + char_width - 1, y + char_height - 1, draw_bg, 0); + draw_char(index, x, y, fg); + } else { + draw_char(index, x, y, fg); + } + + x += char_width; + last_advance = char_width; + + for (int f = 0; f < state.delay_frames; f++) { + p8_flip(); + } + + if (x > right) right = x; + } + } + } + } + + if (add_newline) { + x = left_margin; + y += state.char_h * (state.tall ? 2 : 1); + if (do_scroll) + y = scroll_newline(y); + } + + if (out_left) + *out_left = x; + if (out_top) + *out_top = y; + if (out_right) + *out_right = right; +} + +#endif // P8_PRINT_HELPER_H diff --git a/components/pico8/femto8/src/queue.c b/components/pico8/femto8/src/queue.c new file mode 100644 index 00000000..a214c25b --- /dev/null +++ b/components/pico8/femto8/src/queue.c @@ -0,0 +1,139 @@ +/** + * \file queue.c + * + * \brief A double-ended queue (deque). Elements can be added or removed from + * either the front or the back side. + * \warning The current implementation is NOT interrupt safe. Make sure interrupts + * are disabled before access the QUEUE otherwise the program might yield + * unexpected results. + */ + +#include +#include +#include +#include "queue.h" + +#define INCREASE_INDEX(queue, ptr) queue->ptr = (queue->ptr + queue->elements_size) >= (queue->data_buf + queue->elements_num_max * queue->elements_size) ? queue->data_buf : (queue->ptr + queue->elements_size) +#define DECREASE_INDEX(queue, ptr) queue->ptr = (queue->ptr - queue->elements_size) < queue->data_buf ? (queue->data_buf + (queue->elements_num_max - 1) * queue->elements_size) : (queue->ptr - queue->elements_size) + +/** + * Initializes - resets the queue. + */ +void _queue_init(queue_t *queue) +{ + memset((uint8_t *)queue->data_buf, 0, queue->elements_num_max * queue->elements_size); + + queue->back = queue->data_buf; + queue->front = queue->data_buf; + queue->elements = 0; +} + +/** + * Checks if queue is full. + * + * \returns true if queue is full. + */ +bool queue_is_full(queue_t *queue) +{ + return (queue->elements == queue->elements_num_max); +} + +/** + * Checks if queue is empty + * + * \returns true if queue is empty. + */ +bool queue_is_empty(queue_t *queue) +{ + return (queue->elements == 0); +} + +/** + * Adds one element to the front of the queue. + * + * \returns false if the queue is full. + */ +bool queue_add_front(queue_t *queue, + void *data) +{ + if (queue_is_full(queue)) + { + return false; + } + + if (queue_is_empty(queue) == false) + { + INCREASE_INDEX(queue, front); + } + + memcpy((uint8_t *)queue->front, (uint8_t *)data, queue->elements_size); + queue->elements++; + return true; +} + +/** + * Adds one element to the back of the queue. + * + * \returns false if the queue is full. + */ +bool queue_add_back(queue_t *queue, + void *data) +{ + if (queue_is_full(queue)) + { + return false; + } + + if (queue_is_empty(queue) == false) + { + DECREASE_INDEX(queue, back); + } + + memcpy((uint8_t *)queue->back, (uint8_t *)data, queue->elements_size); + queue->elements++; + return true; +} + +/** + * Reads one element from the front of the queue. + * + * \returns false if the queue is empty. + */ +bool queue_get_front(queue_t *queue, + void *data) +{ + if (queue_is_empty(queue)) + { + return false; + } + + memcpy((uint8_t *)data, (uint8_t *)queue->front, queue->elements_size); + if (queue->front != queue->back) + { + DECREASE_INDEX(queue, front); + } + queue->elements--; + return true; +} + +/** + * Reads one element from the back of the queue. + * + * \returns false if the queue is empty. + */ +bool queue_get_back(queue_t *queue, + void *data) +{ + if (queue_is_empty(queue)) + { + return false; + } + + memcpy((uint8_t *)data, (uint8_t *)queue->back, queue->elements_size); + if (queue->front != queue->back) + { + INCREASE_INDEX(queue, back); + } + queue->elements--; + return true; +} diff --git a/components/pico8/femto8/src/queue.h b/components/pico8/femto8/src/queue.h new file mode 100644 index 00000000..c128381d --- /dev/null +++ b/components/pico8/femto8/src/queue.h @@ -0,0 +1,25 @@ +#ifndef QUEUE_H +#define QUEUE_H + +#include +#include + +typedef struct +{ + void *data_buf; + void *front; + void *back; + const uint16_t elements_num_max; + const uint16_t elements_size; + uint16_t elements; +} queue_t; + +void _queue_init(queue_t *queue); +bool queue_is_full(queue_t *queue); +bool queue_is_empty(queue_t *queue); +bool queue_add_front(queue_t *queue, void *data); +bool queue_add_back(queue_t *queue, void *data); +bool queue_get_front(queue_t *queue, void *data); +bool queue_get_back(queue_t *queue, void *data); + +#endif diff --git a/components/pico8/femto8/src/strtcpy.c b/components/pico8/femto8/src/strtcpy.c new file mode 100644 index 00000000..3e3f877d --- /dev/null +++ b/components/pico8/femto8/src/strtcpy.c @@ -0,0 +1,30 @@ +/* This code is in the public domain. */ + +#include +#include +#include +#include + +#include "strtcpy.h" + +ssize_t +strtcpy(char *restrict dst, const char *restrict src, size_t dsize) +{ + bool trunc; + size_t dlen, slen; + + if (dsize == 0) { + errno = ENOBUFS; + return -1; + } + + slen = strnlen(src, dsize); + trunc = (slen == dsize); + dlen = slen - trunc; + + memcpy(dst, src, dlen); + dst[dlen] = '\0'; + if (trunc) + errno = E2BIG; + return trunc ? -1 : slen; +} \ No newline at end of file diff --git a/components/pico8/femto8/src/strtcpy.h b/components/pico8/femto8/src/strtcpy.h new file mode 100644 index 00000000..7d859722 --- /dev/null +++ b/components/pico8/femto8/src/strtcpy.h @@ -0,0 +1,20 @@ +/* This code is in the public domain. */ + +#ifndef STRTCPY_H +#define STRTCPY_H + +#include +#include + +/* + * strtcpy - Copy a string into a sized buffer, always NUL-terminating. + * + * Copies at most dsize-1 characters from src into dst, always appends '\0'. + * + * Returns: + * >= 0 number of characters written (excluding NUL) when src fits + * -1 if dsize == 0 (errno = ENOBUFS) or src was truncated (errno = E2BIG) + */ +ssize_t strtcpy(char *restrict dst, const char *restrict src, size_t dsize); + +#endif /* STRTCPY_H */ diff --git a/components/pico8/include/pico8.hpp b/components/pico8/include/pico8.hpp new file mode 100644 index 00000000..714c2013 --- /dev/null +++ b/components/pico8/include/pico8.hpp @@ -0,0 +1,27 @@ +#pragma once + +#include +#include +#include +#include + +// PICO-8 (femto8) for esp-box-emu. The cart runs in its own FreeRTOS task; +// run_pico8_rom() only paces the emulator loop. `rom_filename` is a .p8 or +// .p8.png cart. +void init_pico8(const std::string& rom_filename, uint8_t* romdata, size_t rom_data_size); +void reset_pico8(); +void run_pico8_rom(); +void deinit_pico8(); + +void pause_pico8_tasks(); +void resume_pico8_tasks(); + +// true once the cart has ended (PICO-8's own exit, a Lua error, or a load +// failure); the cart then returns to the emulator menu +bool pico8_quit_requested(); + +// Save states are not supported; carts keep their own cartdata() files. +void load_pico8(std::string_view save_path, int save_slot); +void save_pico8(std::string_view save_path, int save_slot); + +std::span get_pico8_video_buffer(); diff --git a/components/pico8/linker.lf b/components/pico8/linker.lf new file mode 100644 index 00000000..ce53322f --- /dev/null +++ b/components/pico8/linker.lf @@ -0,0 +1,23 @@ +# PICO-8 (femto8): the emulator's statics. +# +# femto8's .bss lives in PSRAM (CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY); +# the SURROUND symbols (_pico8_bss_start/_end, _pico8_common_start/_end, +# _pico8_data_start/_end) let src/pico8.cpp reset femto8's state between +# launches: it was written to run once per process (Lua state, setjmp buffers, +# cart flags are statics) and this core must be relaunchable without a reboot. +[scheme:pico8_statics] +entries: + bss -> extern_ram + common -> extern_ram + data -> dram0_data + +[mapping:pico8] +archive: libpico8.a +entries: + * (pico8_statics); + bss -> extern_ram SURROUND(pico8_bss), + common -> extern_ram SURROUND(pico8_common), + data -> dram0_data SURROUND(pico8_data) + # the emulator-side glue owns the reset (the .data snapshot, the lifecycle + # flags) and must survive it: keep it in the default sections + pico8 (default) diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp new file mode 100644 index 00000000..0e6f660e --- /dev/null +++ b/components/pico8/src/pico8.cpp @@ -0,0 +1,390 @@ +// PICO-8 glue for esp-box-emu, hosting femto8. +// +// femto8's p8_run() owns the cart's main loop (Lua _update/_draw, flip, frame +// pacing) and returns only when the cart ends, so the cart runs in its own +// FreeRTOS task and run_pico8_rom() just paces the emulator loop. The platform +// seams femto8 exposes (p8_espbox.h) are small: a frame of palette indices to +// present, the buttons, and a pump called from the Lua instruction hook β€” +// which is where the emulator menu pauses the cart and where a quit from the +// menu unwinds it (p8_quit() longjmps out of the interpreter exactly the way +// femto8's own escape key does). +// +// femto8 was written to run once per process; its statics (the Lua state, +// setjmp buffers, cart flags) are reset between launches through the linker +// SURROUND symbols in linker.lf, the same way the MGS core does it. +#include "pico8.hpp" + +#include "box-emu.hpp" +#include "statistics.hpp" +#include "platform/p8_espbox.h" + +extern "C" { +#include "p8_emu.h" +#include "p8_input.h" +#include "p8_audio.h" +#include "p8_lua.h" +void render_sounds(int16_t* buffer, int total_samples); // p8_audio.c +} + +#include +#include +#include +#include + +#include +#include +#include +#include + +extern "C" { +// linker.lf SURROUND symbols for libpico8.a's statics +extern char _pico8_bss_start[], _pico8_bss_end[]; +extern char _pico8_common_start[], _pico8_common_end[]; +extern char _pico8_data_start[], _pico8_data_end[]; +// femto8's 32-entry RGB565 palette (p8_emu.c) +extern uint16_t m_colors[32]; +} + +namespace { + constexpr int P8_W = 128; + constexpr int P8_H = 128; + constexpr size_t FRAME_BYTES = P8_W * P8_H; // 8-bit indices + // the cart task: Lua recursion and lodepng want a roomy stack; internal RAM + // because the cart loader reads from the card + constexpr size_t CART_TASK_STACK = 24 * 1024; + constexpr UBaseType_t CART_TASK_PRIO = 5; + constexpr UBaseType_t EMU_TASK_PRIO_WHILE_RUNNING = 6; + // audio: femto8 renders mono S16 at SAMPLE_RATE; the box wants stereo frames + constexpr int AUDIO_CHUNK = 512; // frames per write (~11.6ms at 44.1kHz) + + std::string s_cartPath; + bool s_initialized = false; + std::atomic s_paused{false}; + std::atomic s_quit{false}; // the cart is over (or never started) + std::atomic s_stopRequested{false}; // the emulator wants the cart gone + std::atomic s_cartTaskDone{false}; + uint8_t* s_dataSnapshot = nullptr; + + TaskHandle_t s_cartTask = nullptr; + StackType_t* s_cartStack = nullptr; + StaticTask_t* s_cartTcb = nullptr; + TaskHandle_t s_audioTask = nullptr; + std::atomic s_audioRun{false}; + std::atomic s_audioTaskDone{false}; + int16_t* s_audioMono = nullptr; + int16_t* s_audioStereo = nullptr; + UBaseType_t s_emuTaskPrio = 1; + + uint8_t* s_frames[2] = {nullptr, nullptr}; // 128x128 indices, in frame_buffer0 + int s_frameIndex = 0; + const uint8_t* s_lastFrame = nullptr; + unsigned s_framesPresented = 0; + unsigned s_lastPresented = 0; + int64_t s_lastFrameUs = 0, s_lastReportUs = 0; + unsigned s_framesAtReport = 0; + + void logMemory(const char* when) { + fmt::print("[PICO8] {}: free internal {} B (largest {} B), free PSRAM {} B (largest {} B)\n", when, + heap_caps_get_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL), + heap_caps_get_free_size(MALLOC_CAP_SPIRAM), heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)); + } + + // Put every static of libpico8.a back to its as-linked value. Only valid + // while none of femto8's tasks exist. + void resetStatics() { + const size_t dataSize = _pico8_data_end - _pico8_data_start; + if (!s_dataSnapshot) { + s_dataSnapshot = (uint8_t*)heap_caps_malloc(dataSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (s_dataSnapshot) { + memcpy(s_dataSnapshot, _pico8_data_start, dataSize); + } + fmt::print("[PICO8] statics: bss {} B, common {} B, data {} B (snapshot {})\n", + _pico8_bss_end - _pico8_bss_start, _pico8_common_end - _pico8_common_start, dataSize, + s_dataSnapshot ? "ok" : "FAILED"); + return; + } + memset(_pico8_bss_start, 0, _pico8_bss_end - _pico8_bss_start); + memset(_pico8_common_start, 0, _pico8_common_end - _pico8_common_start); + memcpy(_pico8_data_start, s_dataSnapshot, dataSize); + } + + void cartTask(void*) { + fmt::print("[PICO8] cart task on core {}\n", xPortGetCoreID()); + if (p8_init() != 0) { + fmt::print("[PICO8] p8_init failed\n"); + } else if (p8_load(s_cartPath.c_str(), nullptr, nullptr, nullptr) != 0) { + fmt::print("[PICO8] could not load '{}'\n", s_cartPath); + } else { + const int ret = p8_run(); + if (ret != 0) { + fmt::print("[PICO8] cart ended with an error ({})\n", ret); + lua_print_error(); + } else { + fmt::print("[PICO8] cart ended\n"); + } + } + p8_shutdown(); + s_quit = true; + s_cartTaskDone = true; + vTaskSuspend(nullptr); + for (;;) { + vTaskDelay(portMAX_DELAY); + } + } + + void audioTask(void*) { + auto& box = BoxEmu::get(); + while (s_audioRun) { + if (s_paused) { + vTaskDelay(pdMS_TO_TICKS(20)); + continue; + } + // what femto8's SDL callback does, fed by hand + render_sounds(s_audioMono, AUDIO_CHUNK); + for (int i = 0; i < AUDIO_CHUNK; i++) { + s_audioStereo[2 * i] = s_audioMono[i]; + s_audioStereo[2 * i + 1] = s_audioMono[i]; + } + // blocks until the codec has room, which paces this task + box.play_audio((const uint8_t*)s_audioStereo, AUDIO_CHUNK * 2 * sizeof(int16_t)); + } + s_audioTaskDone = true; + vTaskSuspend(nullptr); + for (;;) { + vTaskDelay(portMAX_DELAY); + } + } + + // Wait for a task to park itself after being asked to stop. + bool waitFor(std::atomic& flag, int maxMs) { + for (int waited = 0; waited < maxMs && !flag; waited += 5) { + vTaskDelay(pdMS_TO_TICKS(5)); + } + return flag; + } +} + +// femto8's main.c (not built) defines this for the version dialog +extern "C" const char* femto8_version = "1.0.00"; + +// ---- femto8 platform hooks (p8_espbox.h) ----------------------------------- + +extern "C" uint8_t* p8_espbox_frame_begin(void) { + return s_frames[s_frameIndex]; +} + +extern "C" void p8_espbox_frame_end(void) { + const uint8_t* frame = s_frames[s_frameIndex]; + s_frameIndex ^= 1; + s_lastFrame = frame; + s_framesPresented++; + if (!s_paused) { + BoxEmu::get().push_frame(frame); + } +} + +extern "C" uint16_t p8_espbox_buttons(void) { + // PICO-8: left right up down O X; pause opens PICO-8's own menu + const GamepadState state = BoxEmu::get().gamepad_state(); + uint16_t mask = 0; + if (state.left) mask |= BUTTON_MASK_LEFT; + if (state.right) mask |= BUTTON_MASK_RIGHT; + if (state.up) mask |= BUTTON_MASK_UP; + if (state.down) mask |= BUTTON_MASK_DOWN; + if (state.a || state.y) mask |= BUTTON_MASK_ACTION1; // O + if (state.b || state.x) mask |= BUTTON_MASK_ACTION2; // X + if (state.start && !state.select) mask |= BUTTON_MASK_PAUSE; + return mask; +} + +extern "C" void p8_espbox_pump(void) { + // the emulator menu holds the cart here (the Lua VM is at a safe point) + while (s_paused && !s_stopRequested) { + vTaskDelay(pdMS_TO_TICKS(10)); + } + if (s_stopRequested) { + p8_quit(); // longjmps out of the interpreter; p8_run() returns + } +} + +// ---- emulator API ----------------------------------------------------------- + +void init_pico8(const std::string& rom_filename, uint8_t* romdata, size_t rom_data_size) { + (void)romdata; (void)rom_data_size; + if (s_initialized) { + return; + } + s_cartPath = rom_filename; + s_quit = false; + s_paused = false; + s_stopRequested = false; + s_cartTaskDone = false; + s_audioTaskDone = false; + s_lastFrame = nullptr; + s_frameIndex = 0; + s_framesPresented = s_lastPresented = s_framesAtReport = 0; + s_lastFrameUs = s_lastReportUs = esp_timer_get_time(); + logMemory("before init"); + + resetStatics(); + + auto& box = BoxEmu::get(); + // two index frames in frame_buffer0 (it is far bigger than 2 x 16KB) + s_frames[0] = box.frame_buffer0(); + s_frames[1] = box.frame_buffer0() + FRAME_BYTES; + memset(s_frames[0], 0, 2 * FRAME_BYTES); + box.native_size(P8_W, P8_H); + box.palette(m_colors, 32); + + s_audioMono = (int16_t*)heap_caps_malloc(AUDIO_CHUNK * sizeof(int16_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + s_audioStereo = (int16_t*)heap_caps_malloc(AUDIO_CHUNK * 2 * sizeof(int16_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + s_cartStack = (StackType_t*)heap_caps_malloc(CART_TASK_STACK, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + s_cartTcb = (StaticTask_t*)heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + if (!s_audioMono || !s_audioStereo || !s_cartStack || !s_cartTcb) { + fmt::print("[PICO8] ERROR: out of internal memory\n"); + heap_caps_free(s_audioMono); s_audioMono = nullptr; + heap_caps_free(s_audioStereo); s_audioStereo = nullptr; + heap_caps_free(s_cartStack); s_cartStack = nullptr; + heap_caps_free(s_cartTcb); s_cartTcb = nullptr; + s_quit = true; + return; + } + + s_emuTaskPrio = uxTaskPriorityGet(nullptr); + vTaskPrioritySet(nullptr, EMU_TASK_PRIO_WHILE_RUNNING); + + box.audio_sample_rate(SAMPLE_RATE); + s_audioRun = true; + // the cart on core 0 (with the emulator loop, which outranks it), audio on core 1 + s_cartTask = xTaskCreateStaticPinnedToCore(cartTask, "pico8", CART_TASK_STACK, nullptr, CART_TASK_PRIO, + s_cartStack, s_cartTcb, 0); + if (xTaskCreatePinnedToCore(audioTask, "pico8_snd", 4096, nullptr, 6, &s_audioTask, 1) != pdPASS) { + s_audioTask = nullptr; + s_audioRun = false; + s_audioTaskDone = true; + } + if (!s_cartTask) { + fmt::print("[PICO8] ERROR: could not start the cart task\n"); + s_quit = true; + s_cartTaskDone = true; + } + s_initialized = true; + logMemory("after init"); + reset_frame_time(); +} + +void reset_pico8() { + const std::string cart = s_cartPath; + deinit_pico8(); + init_pico8(cart, nullptr, 0); +} + +void run_pico8_rom() { + if (!s_initialized || s_quit) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + return; + } + const int64_t now = esp_timer_get_time(); + const unsigned presented = s_framesPresented; + if (presented != s_lastPresented) { + update_frame_time((now - s_lastFrameUs) / (presented - s_lastPresented)); + s_lastPresented = presented; + s_lastFrameUs = now; + } + if (now - s_lastReportUs > 5000000) { + fmt::print("[PICO8] {:.1f} fps, free internal {} B, PSRAM {} B\n", + (presented - s_framesAtReport) * 1000000.0 / double(now - s_lastReportUs), + heap_caps_get_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_free_size(MALLOC_CAP_SPIRAM)); + s_lastReportUs = now; + s_framesAtReport = presented; + } + std::this_thread::sleep_for(std::chrono::milliseconds(8)); +} + +bool pico8_quit_requested() { + return s_quit; +} + +void pause_pico8_tasks() { + if (!s_initialized || s_paused) { + return; + } + // the cart parks itself in the pump at the next Lua hook (a few ms at most); + // audio stops on its next chunk + s_paused = true; + audio_pause(); + vTaskDelay(pdMS_TO_TICKS(30)); +} + +void resume_pico8_tasks() { + if (!s_initialized || !s_paused) { + return; + } + // the menu overwrote the screen and palette + auto& box = BoxEmu::get(); + box.palette(m_colors, 32); + if (s_lastFrame) { + box.push_frame(s_lastFrame); + } + audio_resume(); + s_paused = false; +} + +void load_pico8(std::string_view, int) { + fmt::print("[PICO8] save states are not supported\n"); +} + +void save_pico8(std::string_view, int) { + fmt::print("[PICO8] save states are not supported\n"); +} + +std::span get_pico8_video_buffer() { + // RGB565 copy of the last frame (for the pause screenshot) in frame_buffer1 + uint16_t* dst = (uint16_t*)BoxEmu::get().frame_buffer1(); + if (!s_lastFrame || !dst) { + return std::span(); + } + for (size_t i = 0; i < FRAME_BYTES; i++) { + dst[i] = m_colors[s_lastFrame[i] & 0x1f]; + } + return std::span((uint8_t*)dst, FRAME_BYTES * sizeof(uint16_t)); +} + +void deinit_pico8() { + if (!s_initialized) { + return; + } + s_initialized = false; + + // ask the cart to unwind; the pump handles it at the next Lua hook, and + // p8_run() then returns through p8_shutdown() + s_stopRequested = true; + s_paused = false; + if (!waitFor(s_cartTaskDone, 2000)) { + fmt::print("[PICO8] cart task did not stop (stuck in a load?); deleting it\n"); + } + if (s_cartTask) { + vTaskDelete(s_cartTask); + s_cartTask = nullptr; + } + s_audioRun = false; + waitFor(s_audioTaskDone, 500); + if (s_audioTask) { + vTaskDelete(s_audioTask); + s_audioTask = nullptr; + } + vTaskDelay(pdMS_TO_TICKS(5)); + heap_caps_free(s_cartStack); s_cartStack = nullptr; + heap_caps_free(s_cartTcb); s_cartTcb = nullptr; + heap_caps_free(s_audioMono); s_audioMono = nullptr; + heap_caps_free(s_audioStereo); s_audioStereo = nullptr; + s_lastFrame = nullptr; + s_frames[0] = s_frames[1] = nullptr; + + // femto8 is gone: its statics can be put back for the next launch + resetStatics(); + + BoxEmu::get().audio_sample_rate(48000); + vTaskPrioritySet(nullptr, s_emuTaskPrio); + logMemory("after deinit"); +} diff --git a/components/pico8/src/platform/p8_espbox.h b/components/pico8/src/platform/p8_espbox.h new file mode 100644 index 00000000..3b7b3f30 --- /dev/null +++ b/components/pico8/src/platform/p8_espbox.h @@ -0,0 +1,25 @@ +#pragma once +/* esp-box-emu platform for femto8 (FEMTO8_ESPBOX): the emulator supplies + * video, audio and input. Implemented in src/pico8.cpp. */ +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* p8_render(): a 128x128 buffer of 5-bit colour indices (into m_colors) to + * draw the frame into, or NULL to skip the frame; frame_end() presents it. */ +uint8_t* p8_espbox_frame_begin(void); +void p8_espbox_frame_end(void); + +/* p8_update_input(): the player's buttons, BUTTON_MASK_* bits of p8_input.h */ +uint16_t p8_espbox_buttons(void); + +/* p8_pump_events() (the Lua instruction hook): blocks while the emulator menu + * has the cart paused; unwinds the cart (p8_quit) when the emulator asked for + * it to stop. */ +void p8_espbox_pump(void); + +#ifdef __cplusplus +} +#endif diff --git a/components/rom_info/include/rom_info.hpp b/components/rom_info/include/rom_info.hpp index e5a4cbba..28b8c6e2 100644 --- a/components/rom_info/include/rom_info.hpp +++ b/components/rom_info/include/rom_info.hpp @@ -8,7 +8,7 @@ #include "format.hpp" #include "string_utils.hpp" -enum class Emulator { UNKNOWN, NES, GAMEBOY, GAMEBOY_COLOR, SEGA_MASTER_SYSTEM, SEGA_GAME_GEAR, SEGA_GENESIS, SEGA_MEGA_DRIVE, SNES, MSX, DOOM, DARK_FORCES }; +enum class Emulator { UNKNOWN, NES, GAMEBOY, GAMEBOY_COLOR, SEGA_MASTER_SYSTEM, SEGA_GAME_GEAR, SEGA_GENESIS, SEGA_MEGA_DRIVE, SNES, MSX, DOOM, DARK_FORCES, PICO8 }; struct RomInfo { std::string name; @@ -60,6 +60,8 @@ struct fmt::formatter { return fmt::format_to(ctx.out(), "DOOM"); case Emulator::DARK_FORCES: return fmt::format_to(ctx.out(), "DARK_FORCES"); + case Emulator::PICO8: + return fmt::format_to(ctx.out(), "PICO8"); default: return fmt::format_to(ctx.out(), "UNKNOWN"); } diff --git a/components/rom_info/src/rom_info.cpp b/components/rom_info/src/rom_info.cpp index 3b37c30b..54444260 100644 --- a/components/rom_info/src/rom_info.cpp +++ b/components/rom_info/src/rom_info.cpp @@ -86,6 +86,10 @@ std::vector parse_metadata(const std::string& metadata_path) { } else if (endsWith(rom_path, ".gob") || endsWith(rom_path, ".GOB")) { // dark forces (DARK.GOB) #ifdef ENABLE_DARKFORCES platform = Emulator::DARK_FORCES; +#endif + } else if (endsWith(rom_path, ".p8") || endsWith(rom_path, ".p8.png") || endsWith(rom_path, ".P8") || endsWith(rom_path, ".P8.PNG")) { // pico-8 +#ifdef ENABLE_PICO8 + platform = Emulator::PICO8; #endif } if (platform != Emulator::UNKNOWN) { diff --git a/main/carts.hpp b/main/carts.hpp index b7eee9a7..c2dec9bf 100644 --- a/main/carts.hpp +++ b/main/carts.hpp @@ -10,6 +10,7 @@ #include "genesis_cart.hpp" #include "msx_cart.hpp" #include "nes_cart.hpp" +#include "pico8_cart.hpp" #include "sms_cart.hpp" std::unique_ptr make_cart(const RomInfo& info, std::shared_ptr> display) { @@ -63,6 +64,13 @@ std::unique_ptr make_cart(const RomInfo& info, std::shared_ptr(Cart::Config{ + .info = info, + .copy_romdata = false, + .display = display, + .verbosity = espp::Logger::Verbosity::WARN + }); default: return nullptr; } diff --git a/main/pico8_cart.hpp b/main/pico8_cart.hpp new file mode 100644 index 00000000..db7ba617 --- /dev/null +++ b/main/pico8_cart.hpp @@ -0,0 +1,130 @@ +#pragma once + +#include "cart.hpp" +#if defined(ENABLE_PICO8) +#include "pico8.hpp" +#endif + +// PICO-8 carts (.p8 / .p8.png) through femto8. +class Pico8Cart : public Cart { +public: + explicit Pico8Cart(const Cart::Config& config) + : Cart(config) { + handle_video_setting(); + init(); + } + + virtual ~Pico8Cart() override { + deinit(); + } + + // cppcheck-suppress uselessOverride + virtual void reset() override { + Cart::reset(); +#if defined(ENABLE_PICO8) + reset_pico8(); +#endif + } + + // cppcheck-suppress uselessOverride + virtual void load() override { + Cart::load(); +#if defined(ENABLE_PICO8) + load_pico8(get_save_path(), get_selected_save_slot()); +#endif + } + + // cppcheck-suppress uselessOverride + virtual void save() override { + Cart::save(); +#if defined(ENABLE_PICO8) + save_pico8(get_save_path(true), get_selected_save_slot()); +#endif + } + + void init() { +#if defined(ENABLE_PICO8) + init_pico8(get_rom_filename(), romdata_, rom_size_bytes_); +#endif + } + + void deinit() { +#if defined(ENABLE_PICO8) + deinit_pico8(); +#endif + } + + // cppcheck-suppress uselessOverride + virtual bool run() override { +#if defined(ENABLE_PICO8) + run_pico8_rom(); + if (pico8_quit_requested()) { + running_ = false; + return false; + } +#endif + return Cart::run(); + } + +protected: + static constexpr size_t P8_WIDTH = 128; + static constexpr size_t P8_HEIGHT = 128; + + // cppcheck-suppress uselessOverride + virtual void pre_menu() override { + Cart::pre_menu(); +#if defined(ENABLE_PICO8) + logger_.info("pico8::pre_menu()"); + pause_pico8_tasks(); +#endif + } + + // cppcheck-suppress uselessOverride + virtual void post_menu() override { + Cart::post_menu(); +#if defined(ENABLE_PICO8) + logger_.info("pico8::post_menu()"); + resume_pico8_tasks(); +#endif + } + + virtual void set_original_video_setting() override { +#if defined(ENABLE_PICO8) + // 1:1 pixels (128x128 centered); "fit" is the sensible default + logger_.info("pico8::video: original"); + BoxEmu::get().display_size(P8_WIDTH, P8_HEIGHT); +#endif + } + + virtual std::pair get_video_size() const override { + return std::make_pair(P8_WIDTH, P8_HEIGHT); + } + + // cppcheck-suppress uselessOverride + virtual std::span get_video_buffer() const override { +#if defined(ENABLE_PICO8) + return get_pico8_video_buffer(); +#else + return std::span(); +#endif + } + + virtual void set_fit_video_setting() override { +#if defined(ENABLE_PICO8) + // a square screen on the 4:3 panel: 240x240 + logger_.info("pico8::video: fit"); + BoxEmu::get().display_size(SCREEN_HEIGHT, SCREEN_HEIGHT); +#endif + } + + virtual void set_fill_video_setting() override { +#if defined(ENABLE_PICO8) + logger_.info("pico8::video: fill"); + BoxEmu::get().display_size(SCREEN_WIDTH, SCREEN_HEIGHT); +#endif + } + + virtual std::string get_save_extension() const override { + return "_pico8.sav"; + } +}; From 982271f9a7e15d577dd68568ed459a679dc070ac Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sun, 4 Oct 2026 21:40:44 -0500 Subject: [PATCH 02/19] fix(pico8): pace the audio task on the bytes the BSP actually queued Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/src/pico8.cpp | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp index 0e6f660e..589cdc1b 100644 --- a/components/pico8/src/pico8.cpp +++ b/components/pico8/src/pico8.cpp @@ -133,20 +133,29 @@ namespace { } void audioTask(void*) { - auto& box = BoxEmu::get(); + constexpr size_t CHUNK_BYTES = AUDIO_CHUNK * 2 * sizeof(int16_t); + size_t queued = CHUNK_BYTES; // nothing pending yet while (s_audioRun) { if (s_paused) { vTaskDelay(pdMS_TO_TICKS(20)); continue; } - // what femto8's SDL callback does, fed by hand - render_sounds(s_audioMono, AUDIO_CHUNK); - for (int i = 0; i < AUDIO_CHUNK; i++) { - s_audioStereo[2 * i] = s_audioMono[i]; - s_audioStereo[2 * i + 1] = s_audioMono[i]; + if (queued >= CHUNK_BYTES) { + // what femto8's SDL callback does, fed by hand + render_sounds(s_audioMono, AUDIO_CHUNK); + for (int i = 0; i < AUDIO_CHUNK; i++) { + s_audioStereo[2 * i] = s_audioMono[i]; + s_audioStereo[2 * i + 1] = s_audioMono[i]; + } + queued = 0; + } + // play_audio queues what fits and returns the count; the I2S stream + // buffer drains at the sample rate, so wait a little when it is full + // (the BSP's play_audio returns the count; BoxEmu's wrapper discards it) + queued += BoxEmu::Bsp::get().play_audio((const uint8_t*)s_audioStereo + queued, CHUNK_BYTES - queued); + if (queued < CHUNK_BYTES) { + vTaskDelay(pdMS_TO_TICKS(3)); } - // blocks until the codec has room, which paces this task - box.play_audio((const uint8_t*)s_audioStereo, AUDIO_CHUNK * 2 * sizeof(int16_t)); } s_audioTaskDone = true; vTaskSuspend(nullptr); From 5537eeca867943b3fb9de0b2e58a92e0c5e5ba82 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Mon, 5 Oct 2026 12:17:13 -0500 Subject: [PATCH 03/19] fix(pico8): clear static-analysis findings; exclude femto8 from the scan Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- .github/workflows/static_analysis.yml | 2 +- components/pico8/src/pico8.cpp | 46 ++++++++++++++++++--------- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/.github/workflows/static_analysis.yml b/.github/workflows/static_analysis.yml index 51f991f7..a7262484 100644 --- a/.github/workflows/static_analysis.yml +++ b/.github/workflows/static_analysis.yml @@ -26,4 +26,4 @@ jobs: use_cmake: false # (Optional) cppcheck args - cppcheck_args: -i$GITHUB_WORKSPACE/components/gbc/gnuboy -i$GITHUB_WORKSPACE/components/nes/nofrendo -i$GITHUB_WORKSPACE/components/msx/fmsx -i$GITHUB_WORKSPACE/components/doom/prboom -i$GITHUB_WORKSPACE/components/sms/smsplus -i$GITHUB_WORKSPACE/components/genesis/gwenesis -i$GITHUB_WORKSPACE/components/darkforces/tfe -i$GITHUB_WORKSPACE/components/gui/generated -i$GITHUB_WORKSPACE/components/menu/generated -i$GITHUB_WORKSPACE/components/jpegdec --check-level=exhaustive --force --enable=all --inline-suppr --inconclusive --platform=mips32 --std=c++17 --suppressions-list=$GITHUB_WORKSPACE/suppressions.txt + cppcheck_args: -i$GITHUB_WORKSPACE/components/gbc/gnuboy -i$GITHUB_WORKSPACE/components/nes/nofrendo -i$GITHUB_WORKSPACE/components/msx/fmsx -i$GITHUB_WORKSPACE/components/doom/prboom -i$GITHUB_WORKSPACE/components/sms/smsplus -i$GITHUB_WORKSPACE/components/genesis/gwenesis -i$GITHUB_WORKSPACE/components/darkforces/tfe -i$GITHUB_WORKSPACE/components/gui/generated -i$GITHUB_WORKSPACE/components/menu/generated -i$GITHUB_WORKSPACE/components/jpegdec -i$GITHUB_WORKSPACE/components/pico8/femto8 --check-level=exhaustive --force --enable=all --inline-suppr --inconclusive --platform=mips32 --std=c++17 --suppressions-list=$GITHUB_WORKSPACE/suppressions.txt diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp index 589cdc1b..b27a2b56 100644 --- a/components/pico8/src/pico8.cpp +++ b/components/pico8/src/pico8.cpp @@ -38,9 +38,11 @@ void render_sounds(int16_t* buffer, int total_samples); // p8_audio.c extern "C" { // linker.lf SURROUND symbols for libpico8.a's statics -extern char _pico8_bss_start[], _pico8_bss_end[]; -extern char _pico8_common_start[], _pico8_common_end[]; -extern char _pico8_data_start[], _pico8_data_end[]; +// (declared as single chars: only their addresses mean anything, and the +// section bounds are computed as integers below) +extern char _pico8_bss_start, _pico8_bss_end; +extern char _pico8_common_start, _pico8_common_end; +extern char _pico8_data_start, _pico8_data_end; // femto8's 32-entry RGB565 palette (p8_emu.c) extern uint16_t m_colors[32]; } @@ -83,6 +85,18 @@ namespace { int64_t s_lastFrameUs = 0, s_lastReportUs = 0; unsigned s_framesAtReport = 0; + + // A section delimited by two linker symbols. + struct Section { + uint8_t* begin; + size_t size; + }; + Section section(char& start, char& end) { + const uintptr_t b = reinterpret_cast(&start); + const uintptr_t e = reinterpret_cast(&end); + return Section{reinterpret_cast(b), static_cast(e - b)}; + } + void logMemory(const char* when) { fmt::print("[PICO8] {}: free internal {} B (largest {} B), free PSRAM {} B (largest {} B)\n", when, heap_caps_get_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL), @@ -92,20 +106,21 @@ namespace { // Put every static of libpico8.a back to its as-linked value. Only valid // while none of femto8's tasks exist. void resetStatics() { - const size_t dataSize = _pico8_data_end - _pico8_data_start; + const Section bss = section(_pico8_bss_start, _pico8_bss_end); + const Section common = section(_pico8_common_start, _pico8_common_end); + const Section data = section(_pico8_data_start, _pico8_data_end); if (!s_dataSnapshot) { - s_dataSnapshot = (uint8_t*)heap_caps_malloc(dataSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + s_dataSnapshot = static_cast(heap_caps_malloc(data.size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); if (s_dataSnapshot) { - memcpy(s_dataSnapshot, _pico8_data_start, dataSize); + memcpy(s_dataSnapshot, data.begin, data.size); } - fmt::print("[PICO8] statics: bss {} B, common {} B, data {} B (snapshot {})\n", - _pico8_bss_end - _pico8_bss_start, _pico8_common_end - _pico8_common_start, dataSize, + fmt::print("[PICO8] statics: bss {} B, common {} B, data {} B (snapshot {})\n", bss.size, common.size, data.size, s_dataSnapshot ? "ok" : "FAILED"); return; } - memset(_pico8_bss_start, 0, _pico8_bss_end - _pico8_bss_start); - memset(_pico8_common_start, 0, _pico8_common_end - _pico8_common_start); - memcpy(_pico8_data_start, s_dataSnapshot, dataSize); + memset(bss.begin, 0, bss.size); + memset(common.begin, 0, common.size); + memcpy(data.begin, s_dataSnapshot, data.size); } void cartTask(void*) { @@ -152,7 +167,7 @@ namespace { // play_audio queues what fits and returns the count; the I2S stream // buffer drains at the sample rate, so wait a little when it is full // (the BSP's play_audio returns the count; BoxEmu's wrapper discards it) - queued += BoxEmu::Bsp::get().play_audio((const uint8_t*)s_audioStereo + queued, CHUNK_BYTES - queued); + queued += BoxEmu::Bsp::get().play_audio(reinterpret_cast(s_audioStereo) + queued, CHUNK_BYTES - queued); if (queued < CHUNK_BYTES) { vTaskDelay(pdMS_TO_TICKS(3)); } @@ -283,7 +298,8 @@ void init_pico8(const std::string& rom_filename, uint8_t* romdata, size_t rom_da } void reset_pico8() { - const std::string cart = s_cartPath; + // deinit does not touch s_cartPath, but init takes it by reference: copy first + const std::string cart(s_cartPath); deinit_pico8(); init_pico8(cart, nullptr, 0); } @@ -349,14 +365,14 @@ void save_pico8(std::string_view, int) { std::span get_pico8_video_buffer() { // RGB565 copy of the last frame (for the pause screenshot) in frame_buffer1 - uint16_t* dst = (uint16_t*)BoxEmu::get().frame_buffer1(); + uint16_t* dst = reinterpret_cast(BoxEmu::get().frame_buffer1()); if (!s_lastFrame || !dst) { return std::span(); } for (size_t i = 0; i < FRAME_BYTES; i++) { dst[i] = m_colors[s_lastFrame[i] & 0x1f]; } - return std::span((uint8_t*)dst, FRAME_BYTES * sizeof(uint16_t)); + return std::span(reinterpret_cast(dst), FRAME_BYTES * sizeof(uint16_t)); } void deinit_pico8() { From be209acc039770bb21a28afd1bb917e494d71654 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Mon, 5 Oct 2026 12:20:51 -0500 Subject: [PATCH 04/19] chore(pico8): suppress cppcheck findings in the vendored femto8 tree Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- suppressions.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/suppressions.txt b/suppressions.txt index 3455d2e3..52b2c658 100644 --- a/suppressions.txt +++ b/suppressions.txt @@ -26,6 +26,9 @@ duplicateExpressionTernary:components/genesis/src/genesis.cpp // exclude in static_analysis.yml only covers the base-tree pass; the PR // tree is checked under pr_tree/, so suppress by relative path here.) *:components/darkforces/tfe/* +// PICO-8: femto8 is vendored third-party code (components/pico8/VENDOR.md); +// only the glue in components/pico8/src is ours. +*:components/pico8/femto8/* // The Dark Forces ESP32 port layer (components/darkforces/src/platform) bridges // to the vendored TFE engine. The findings that can't be acted on -- pointer // parameters that implement TFE's engine/callback signatures -- are suppressed From 88b595aa0edc8ac626b95982991f08983ceb0dda Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 6 Oct 2026 08:49:07 -0500 Subject: [PATCH 05/19] fix(pico8): gate audio on femto8's memory; any-button "press any key"; backtrace on a stuck cart The audio task rendered before p8_init() had allocated PICO-8 RAM (a NULL-base LoadProhibited at 0x5f2f). femto8's keyboard-only "press any key" loop now takes a button and honours the emulator's stop request. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/femto8/src/p8_emu.c | 10 ++++++++++ components/pico8/src/pico8.cpp | 29 +++++++++++++++++++--------- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/components/pico8/femto8/src/p8_emu.c b/components/pico8/femto8/src/p8_emu.c index 22d45b64..98ad1023 100644 --- a/components/pico8/femto8/src/p8_emu.c +++ b/components/pico8/femto8/src/p8_emu.c @@ -270,10 +270,20 @@ static void p8_wait_for_any_key(void) p8_flip(); while (!p8_is_quit_requested()) { p8_update_input(); +#ifdef FEMTO8_ESPBOX + /* no keyboard: any button is "any key", and the emulator's own stop + * request has to get through (this loop never enters the Lua VM, so + * the instruction-hook pump would never see it) */ + p8_espbox_pump(); + if (m_buttonsp[0] != 0) + break; + p8_sleep(16); +#else unsigned scancode = 0, keymod = 0; uint8_t keypress = 0; if (p8_get_next_keypress(&scancode, &keypress, &keymod)) break; +#endif } } diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp index b27a2b56..8068d216 100644 --- a/components/pico8/src/pico8.cpp +++ b/components/pico8/src/pico8.cpp @@ -26,6 +26,7 @@ extern "C" { void render_sounds(int16_t* buffer, int total_samples); // p8_audio.c } +#include #include #include #include @@ -72,6 +73,7 @@ namespace { StaticTask_t* s_cartTcb = nullptr; TaskHandle_t s_audioTask = nullptr; std::atomic s_audioRun{false}; + std::atomic s_audioReady{false}; // femto8's memory exists (between p8_init and p8_shutdown) std::atomic s_audioTaskDone{false}; int16_t* s_audioMono = nullptr; int16_t* s_audioStereo = nullptr; @@ -127,17 +129,23 @@ namespace { fmt::print("[PICO8] cart task on core {}\n", xPortGetCoreID()); if (p8_init() != 0) { fmt::print("[PICO8] p8_init failed\n"); - } else if (p8_load(s_cartPath.c_str(), nullptr, nullptr, nullptr) != 0) { - fmt::print("[PICO8] could not load '{}'\n", s_cartPath); } else { - const int ret = p8_run(); - if (ret != 0) { - fmt::print("[PICO8] cart ended with an error ({})\n", ret); - lua_print_error(); + s_audioReady = true; + if (p8_load(s_cartPath.c_str(), nullptr, nullptr, nullptr) != 0) { + fmt::print("[PICO8] could not load '{}'\n", s_cartPath); } else { - fmt::print("[PICO8] cart ended\n"); + const int ret = p8_run(); + if (ret != 0) { + fmt::print("[PICO8] cart ended with an error ({})\n", ret); + lua_print_error(); + } else { + fmt::print("[PICO8] cart ended\n"); + } } } + // the audio task must not touch femto8's memory once it is freed + s_audioReady = false; + vTaskDelay(pdMS_TO_TICKS(20)); p8_shutdown(); s_quit = true; s_cartTaskDone = true; @@ -151,7 +159,7 @@ namespace { constexpr size_t CHUNK_BYTES = AUDIO_CHUNK * 2 * sizeof(int16_t); size_t queued = CHUNK_BYTES; // nothing pending yet while (s_audioRun) { - if (s_paused) { + if (s_paused || !s_audioReady) { vTaskDelay(pdMS_TO_TICKS(20)); continue; } @@ -386,7 +394,10 @@ void deinit_pico8() { s_stopRequested = true; s_paused = false; if (!waitFor(s_cartTaskDone, 2000)) { - fmt::print("[PICO8] cart task did not stop (stuck in a load?); deleting it\n"); + // wedged outside the Lua VM (the pump never ran): show where, then kill it. + // femto8's buffers leak in this case (p8_shutdown never runs). + fmt::print("[PICO8] cart task did not stop; where it is stuck:\n"); + esp_backtrace_print_all_tasks(16); } if (s_cartTask) { vTaskDelete(s_cartTask); From 10a7345c97d31873bf295061d582820ae1322d55 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 6 Oct 2026 08:59:04 -0500 Subject: [PATCH 06/19] fix(pico8): PICO-8 compatibility: _ENV fallback to the API, lenient split() Carts that override _ENV (`for _ENV in all(objs) do circfill(...) end`, `function f(_ENV)`) could not reach the API: a string-keyed lookup that comes back nil now falls back to a snapshot of the API globals taken before the cart ran (the same approach as fake-08's z8lua). split() no longer raises on a non-string argument, as PICO-8 does not. Reproduced and verified with femto8's desktop build: all 7 test carts run (Mossmoss and Pico Ball failed before). Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/femto8/src/lua/lpico8lib.c | 9 ++++++++- components/pico8/femto8/src/lua/lvm.c | 19 +++++++++++++++++++ components/pico8/femto8/src/p8_lua.c | 14 ++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/components/pico8/femto8/src/lua/lpico8lib.c b/components/pico8/femto8/src/lua/lpico8lib.c index ccecdd36..160f7fd7 100644 --- a/components/pico8/femto8/src/lua/lpico8lib.c +++ b/components/pico8/femto8/src/lua/lpico8lib.c @@ -335,7 +335,14 @@ static int pico8_split(lua_State *l) { if (lua_isnil(l, 1)) { return 0; } - haystack = luaL_checklstring(l, 1, &hlen); + /* PICO-8 does not raise on a non-string: numbers are split as their text, + * anything else (a boolean from an `a and "x" or b and "y"` chain that fell + * through) gives an empty table */ + if (lua_type(l, 1) != LUA_TSTRING && !lua_isnumber(l, 1)) { + lua_newtable(l); + return 1; + } + haystack = lua_tolstring(l, 1, &hlen); if (!haystack) return 0; lua_newtable(l); diff --git a/components/pico8/femto8/src/lua/lvm.c b/components/pico8/femto8/src/lua/lvm.c index 09fc1fd9..65e41a27 100644 --- a/components/pico8/femto8/src/lua/lvm.c +++ b/components/pico8/femto8/src/lua/lvm.c @@ -585,6 +585,22 @@ void luaV_finishOp (lua_State *L) { #define vmcase(l,b) case l: {b} break; #define vmcasenb(l,b) case l: {b} /* nb = no break */ +/* PICO-8 lets a cart override _ENV (`for _ENV in all(objs) do circfill(...)`, + * `function f(_ENV)`) and still reach the API: a string-keyed lookup that + * comes back nil falls back to the API table snapshotted in the registry + * before the cart ran (p8_lua.c). The same approach as fake-08's z8lua. */ +static void pico8_sandbox_fallback (lua_State *L, StkId ra, const TValue *key) { + if (ttisnil(ra) && ttisstring(key)) { + Table *reg = hvalue(&G(L)->l_registry); + const TValue *sandbox = luaH_getstr(reg, luaS_newliteral(L, "__PICO8_SANDBOX")); + if (ttistable(sandbox)) { + const TValue *res = luaH_get(hvalue(sandbox), key); + if (!ttisnil(res)) + setobj2s(L, ra, res); + } + } +} + void luaV_execute (lua_State *L) { CallInfo *ci = L->ci; LClosure *cl; @@ -638,9 +654,12 @@ void luaV_execute (lua_State *L) { vmcase(OP_GETTABUP, int b = GETARG_B(i); Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra)); + pico8_sandbox_fallback(L, ra, RKC(i)); ) vmcase(OP_GETTABLE, Protect(luaV_gettable(L, RB(i), RKC(i), ra)); + if (ttistable(RB(i))) + pico8_sandbox_fallback(L, ra, RKC(i)); ) vmcase(OP_SETTABUP, int a = GETARG_A(i); diff --git a/components/pico8/femto8/src/p8_lua.c b/components/pico8/femto8/src/p8_lua.c index 827eea35..d2486c7c 100644 --- a/components/pico8/femto8/src/p8_lua.c +++ b/components/pico8/femto8/src/p8_lua.c @@ -2497,6 +2497,20 @@ int lua_load_api() return ret; lua_setpico8memory(L, m_memory); + // Snapshot the API globals for the VM's _ENV fallback (lvm.c): carts that + // override _ENV still see circfill() and friends, as they do on PICO-8. + lua_newtable(L); + lua_pushglobaltable(L); + lua_pushnil(L); + while (lua_next(L, -2) != 0) { + lua_pushvalue(L, -2); // key + lua_pushvalue(L, -2); // value + lua_rawset(L, -6); // sandbox[key] = value + lua_pop(L, 1); + } + lua_pop(L, 1); // globals + lua_setfield(L, LUA_REGISTRYINDEX, "__PICO8_SANDBOX"); + // Set debug hook to pump events every ~3000 instructions lua_sethook(L, lua_event_pump_hook, LUA_MASKCOUNT, 3000); From f9b80ccb3fb43687a57557e5279e92476f8ec5da Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 6 Oct 2026 09:11:30 -0500 Subject: [PATCH 07/19] fix(pico8): clip sspr() to the visible area; load() of sibling carts; audio gate on the kill path - draw_scaled_sprite walked every destination pixel of a scaled sprite before clipping: a cart scaling a sprite to thousands of pixels spent seconds per frame on the S3 and looked hung (Cattle Crisis). The loops now cover only the clip rectangle. - load(): no working-directory check on the box, the cart's own folder is the base, and "#bbs_id" (multi-cart games) resolves to a sibling bbs_id.p8.png / .p8. - The _ENV fallback caches its table pointers instead of interning the registry key on every nil lookup. - A cart killed while wedged left the audio task armed; the next launch rendered before p8_init() and crashed. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/femto8/src/lua/lvm.c | 27 +++++++++++-------- components/pico8/femto8/src/p8_emu.c | 13 ++++++++- components/pico8/femto8/src/p8_lua.c | 30 +++++++++++++++++---- components/pico8/femto8/src/p8_lua_helper.h | 21 +++++++++++++-- components/pico8/src/pico8.cpp | 2 ++ 5 files changed, 74 insertions(+), 19 deletions(-) diff --git a/components/pico8/femto8/src/lua/lvm.c b/components/pico8/femto8/src/lua/lvm.c index 65e41a27..17f71a69 100644 --- a/components/pico8/femto8/src/lua/lvm.c +++ b/components/pico8/femto8/src/lua/lvm.c @@ -589,15 +589,19 @@ void luaV_finishOp (lua_State *L) { * `function f(_ENV)`) and still reach the API: a string-keyed lookup that * comes back nil falls back to the API table snapshotted in the registry * before the cart ran (p8_lua.c). The same approach as fake-08's z8lua. */ -static void pico8_sandbox_fallback (lua_State *L, StkId ra, const TValue *key) { - if (ttisnil(ra) && ttisstring(key)) { - Table *reg = hvalue(&G(L)->l_registry); - const TValue *sandbox = luaH_getstr(reg, luaS_newliteral(L, "__PICO8_SANDBOX")); - if (ttistable(sandbox)) { - const TValue *res = luaH_get(hvalue(sandbox), key); - if (!ttisnil(res)) - setobj2s(L, ra, res); - } +static Table *pico8_sandbox_table; /* the API snapshot (anchored in the registry) */ +static Table *pico8_globals_table; /* lookups on the real globals need no fallback */ + +void pico8_set_env_fallback (const void *sandbox, const void *globals) { + pico8_sandbox_table = (Table *)sandbox; + pico8_globals_table = (Table *)globals; +} + +static void pico8_sandbox_fallback (lua_State *L, StkId ra, const TValue *key, Table *src) { + if (pico8_sandbox_table && src != pico8_globals_table && ttisnil(ra) && ttisstring(key)) { + const TValue *res = luaH_get(pico8_sandbox_table, key); + if (!ttisnil(res)) + setobj2s(L, ra, res); } } @@ -654,12 +658,13 @@ void luaV_execute (lua_State *L) { vmcase(OP_GETTABUP, int b = GETARG_B(i); Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra)); - pico8_sandbox_fallback(L, ra, RKC(i)); + if (ttistable(cl->upvals[b]->v)) + pico8_sandbox_fallback(L, ra, RKC(i), hvalue(cl->upvals[b]->v)); ) vmcase(OP_GETTABLE, Protect(luaV_gettable(L, RB(i), RKC(i), ra)); if (ttistable(RB(i))) - pico8_sandbox_fallback(L, ra, RKC(i)); + pico8_sandbox_fallback(L, ra, RKC(i), hvalue(RB(i))); ) vmcase(OP_SETTABUP, int a = GETARG_A(i); diff --git a/components/pico8/femto8/src/p8_emu.c b/components/pico8/femto8/src/p8_emu.c index 98ad1023..a1c2ed8f 100644 --- a/components/pico8/femto8/src/p8_emu.c +++ b/components/pico8/femto8/src/p8_emu.c @@ -303,7 +303,18 @@ int p8_load(const char *file_name, const char *param, const char *bbs_cart_id, c strtcpy(m_breadcrumb, breadcrumb ? breadcrumb : "", sizeof(m_breadcrumb)); strtcpy(m_current_cart_file_name, file_name, sizeof(m_current_cart_file_name)); - strtcpy(m_current_cart_dir, ".", sizeof(m_current_cart_dir)); + { + /* the cart's own folder, so load()/cstore() of sibling carts and + * relative names resolve against it rather than a working directory */ + const char *slash = strrchr(file_name, '/'); + if (slash && slash - file_name < (long)sizeof(m_current_cart_dir) - 1) { + size_t n = (size_t)(slash - file_name); + memcpy(m_current_cart_dir, file_name, n); + m_current_cart_dir[n] = '\0'; + } else { + strtcpy(m_current_cart_dir, ".", sizeof(m_current_cart_dir)); + } + } if (cart_running) p8_reset_cart(); diff --git a/components/pico8/femto8/src/p8_lua.c b/components/pico8/femto8/src/p8_lua.c index d2486c7c..4e8d22dc 100644 --- a/components/pico8/femto8/src/p8_lua.c +++ b/components/pico8/femto8/src/p8_lua.c @@ -1680,8 +1680,10 @@ int run(lua_State *L) // load(filename [,breadcrumb] [,param]) int _load(lua_State *L) { +#ifndef FEMTO8_ESPBOX /* the ESP-IDF VFS has no working directory; carts resolve against their own folder */ if (access(".", F_OK) == -1 && errno != EACCES) luaL_error(L, "load() requires a filesystem"); +#endif int nargs = lua_gettop(L); @@ -1696,7 +1698,18 @@ int _load(lua_State *L) char resolved_path[PATH_MAX]; const char *bbs_cart_id = NULL; - if (strstr(filename, ".p8") == NULL && strstr(filename, ".P8") == NULL) { + /* "#bbs_id" (a multi-cart game jumping to its other carts on the BBS): + * there is no network, so look for a cart of that name next to this one + * (bbs_id.p8.png, then bbs_id.p8) */ + if (filename[0] == '#') { + bbs_cart_id = filename + 1; + snprintf(full_filename, sizeof(full_filename), "%s.p8.png", bbs_cart_id); + if (p8_resolve_relative_path(resolved_path, full_filename, sizeof(resolved_path), false) < 0) + luaL_error(L, "out of memory"); + if (access(resolved_path, F_OK) != 0) + snprintf(full_filename, sizeof(full_filename), "%s.p8", bbs_cart_id); + filename = full_filename; + } else if (strstr(filename, ".p8") == NULL && strstr(filename, ".P8") == NULL) { snprintf(full_filename, sizeof(full_filename), "%s.p8", filename); filename = full_filename; } @@ -1705,10 +1718,6 @@ int _load(lua_State *L) luaL_error(L, "out of memory"); } - if (p8_resolve_relative_path(resolved_path, filename, sizeof(resolved_path), false) < 0) { - luaL_error(L, "out of memory"); - } - if (access(resolved_path, F_OK) != 0) { fprintf(stderr, "load: could not find cart %s\n", filename); m_load_result = -1; @@ -2509,6 +2518,13 @@ int lua_load_api() lua_pop(L, 1); } lua_pop(L, 1); // globals + { + extern void pico8_set_env_fallback(const void *sandbox, const void *globals); + const void *sandbox = lua_topointer(L, -1); + lua_pushglobaltable(L); + pico8_set_env_fallback(sandbox, lua_topointer(L, -1)); + lua_pop(L, 1); + } lua_setfield(L, LUA_REGISTRYINDEX, "__PICO8_SANDBOX"); // Set debug hook to pump events every ~3000 instructions @@ -2519,6 +2535,10 @@ int lua_load_api() int lua_shutdown_api() { + { + extern void pico8_set_env_fallback(const void *sandbox, const void *globals); + pico8_set_env_fallback(NULL, NULL); + } if (L) { p8_menuitem_reset_all(); lua_close(L); diff --git a/components/pico8/femto8/src/p8_lua_helper.h b/components/pico8/femto8/src/p8_lua_helper.h index b04d8dfa..810f7a0f 100644 --- a/components/pico8/femto8/src/p8_lua_helper.h +++ b/components/pico8/femto8/src/p8_lua_helper.h @@ -415,15 +415,32 @@ static inline void pixel_set(int x, int y, int c, int fillp, int draw_type) static inline void draw_scaled_sprite(int sx, int sy, int sw, int sh, int dx, int dy, float scale_x, float scale_y, bool flip_x, bool flip_y) { + if (sw <= 0 || sh <= 0) + return; + int dw = roundf(sw * scale_x); int dh = roundf(sh * scale_y); if (dw <= 0 || dh <= 0) return; - for (int y = 0; y < dh; y++) + /* Only walk the destination pixels that can land inside the clip + * rectangle (pixel_set applies the camera and clips per pixel): a cart + * that scales a sprite to thousands of pixels otherwise spends seconds in + * here on a slow CPU, and looks hung. */ + int cam_x, cam_y, clip_x0, clip_y0, clip_x1, clip_y1; + camera_get(&cam_x, &cam_y); + clip_get(&clip_x0, &clip_y0, &clip_x1, &clip_y1); + int x_begin = clip_x0 + cam_x - dx, x_end = clip_x1 + cam_x - dx; + int y_begin = clip_y0 + cam_y - dy, y_end = clip_y1 + cam_y - dy; + if (x_begin < 0) x_begin = 0; + if (y_begin < 0) y_begin = 0; + if (x_end > dw) x_end = dw; + if (y_end > dh) y_end = dh; + + for (int y = y_begin; y < y_end; y++) { - for (int x = 0; x < dw; x++) + for (int x = x_begin; x < x_end; x++) { int src_x = sx + (flip_x ? (sw - 1 - (x * sw) / dw) : (x * sw) / dw); int src_y = sy + (flip_y ? (sh - 1 - (y * sh) / dh) : (y * sh) / dh); diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp index 8068d216..886201ae 100644 --- a/components/pico8/src/pico8.cpp +++ b/components/pico8/src/pico8.cpp @@ -388,6 +388,8 @@ void deinit_pico8() { return; } s_initialized = false; + // whatever happens below, the audio task must not touch femto8's memory + s_audioReady = false; // ask the cart to unwind; the pump handles it at the next Lua hook, and // p8_run() then returns through p8_shutdown() From 342701072ff044b63bb59afb16d378484cc2393a Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 6 Oct 2026 09:29:16 -0500 Subject: [PATCH 08/19] perf(pico8): PICO-8 RAM in internal SRAM; say "could not find cart" once The 64KB PICO-8 RAM (screen, sprites, map, draw state) is read a dozen times per pixel drawn; it came from the PSRAM heap. A multi-cart menu retrying load() every frame no longer floods the console. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/femto8/src/p8_emu.c | 15 ++++++++++++++- components/pico8/femto8/src/p8_lua.c | 8 +++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/components/pico8/femto8/src/p8_emu.c b/components/pico8/femto8/src/p8_emu.c index a1c2ed8f..3f212a23 100644 --- a/components/pico8/femto8/src/p8_emu.c +++ b/components/pico8/femto8/src/p8_emu.c @@ -20,6 +20,7 @@ #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" +#include "esp_heap_caps.h" #include "p8_espbox.h" #elif defined(OS_FREERTOS) #include @@ -202,10 +203,22 @@ int p8_init() xSemaphoreGive(m_drawSemaphore); #endif +#ifdef FEMTO8_ESPBOX + /* PICO-8 RAM (screen, sprites, map, draw state) is touched a dozen times + * per pixel drawn: keep it in internal SRAM rather than PSRAM. Falls back + * to the default heap if the emulator left too little internal RAM. */ + m_memory = (uint8_t *)heap_caps_malloc(MEMORY_SIZE, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + if (!m_memory) + m_memory = (uint8_t *)malloc(MEMORY_SIZE); + m_overlay_memory = (uint8_t *)heap_caps_malloc(MEMORY_SCREEN_SIZE, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + if (!m_overlay_memory) + m_overlay_memory = (uint8_t *)malloc(MEMORY_SCREEN_SIZE); +#else m_memory = (uint8_t *)malloc(MEMORY_SIZE); + m_overlay_memory = (uint8_t *)malloc(MEMORY_SCREEN_SIZE); +#endif m_cart_memory = (uint8_t *)malloc(CART_MEMORY_SIZE); m_temp_cart_memory = (uint8_t *)malloc(CART_MEMORY_SIZE); - m_overlay_memory = (uint8_t *)malloc(MEMORY_SCREEN_SIZE); m_file_buffer = (uint8_t *)malloc(FILE_BUFFER_SIZE); m_decompression_buffer = (uint8_t *)malloc(DECOMPRESSION_BUFFER_SIZE); m_lua_script = (char *)malloc(LUA_SCRIPT_SIZE); diff --git a/components/pico8/femto8/src/p8_lua.c b/components/pico8/femto8/src/p8_lua.c index 4e8d22dc..30294c56 100644 --- a/components/pico8/femto8/src/p8_lua.c +++ b/components/pico8/femto8/src/p8_lua.c @@ -1719,7 +1719,13 @@ int _load(lua_State *L) } if (access(resolved_path, F_OK) != 0) { - fprintf(stderr, "load: could not find cart %s\n", filename); + { /* a menu cart retries every frame: say it once per name */ + static char last_missing[PATH_MAX]; + if (strcmp(last_missing, filename) != 0) { + strtcpy(last_missing, filename, sizeof(last_missing)); + fprintf(stderr, "load: could not find cart %s\n", filename); + } + } m_load_result = -1; if (p8_is_cart_running()) { lua_pushboolean(L, 0); From 07749973bff628dfd363f64d08440582209a4d06 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 6 Oct 2026 11:10:11 -0500 Subject: [PATCH 09/19] perf(pico8): pooled Lua allocator; API profiler (PICO8_PROFILE) The interpreter, not the drawing API, dominates the slow carts (Cattle Crisis in play: >90% Lua; Mossmoss: ~86%), and a string creation cost ~12k cycles through the locked system heap. Lua's small objects now come from size-class free lists over 64KB PSRAM slabs (src/platform/ p8_lua_alloc.c, host-tested under ASan); larger blocks still use the heap. PICO8_PROFILE wraps every API function with a cycle counter and reports the top entries with the fps line. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/CMakeLists.txt | 4 +- components/pico8/femto8/src/p8_lua.c | 82 +++++++++++- components/pico8/femto8/src/p8_lua.h | 6 + components/pico8/src/pico8.cpp | 33 +++++ components/pico8/src/platform/p8_lua_alloc.c | 125 +++++++++++++++++++ components/pico8/src/platform/p8_lua_alloc.h | 16 +++ 6 files changed, 263 insertions(+), 3 deletions(-) create mode 100644 components/pico8/src/platform/p8_lua_alloc.c create mode 100644 components/pico8/src/platform/p8_lua_alloc.h diff --git a/components/pico8/CMakeLists.txt b/components/pico8/CMakeLists.txt index 6ae9ccea..805f458f 100644 --- a/components/pico8/CMakeLists.txt +++ b/components/pico8/CMakeLists.txt @@ -7,7 +7,7 @@ file(GLOB SRC_FEMTO8 ${F8}/*.c ${F8}/lua/*.c ${F8}/lodepng/*.c ${F8}/lexaloffle/ idf_component_register( INCLUDE_DIRS "include" - SRCS src/pico8.cpp ${SRC_FEMTO8} + SRCS src/pico8.cpp src/platform/p8_lua_alloc.c ${SRC_FEMTO8} PRIV_INCLUDE_DIRS "src/platform" ${F8} ${F8}/data ${F8}/lua ${F8}/lodepng ${F8}/lexaloffle REQUIRES box-emu statistics esp_timer heap pthread LDFRAGMENTS "linker.lf" @@ -16,6 +16,8 @@ idf_component_register( # Where carts keep their cartdata() saves (femto8 defaults to a relative "cdata") target_compile_definitions(${COMPONENT_LIB} PRIVATE FEMTO8_ESPBOX=1 + # PICO8_PROFILE=1: cycle-count every API call and report it with the fps line + PICO8_PROFILE=1 CARTDATA_PATH="/sdcard/pico8/cdata" DEFAULT_CARTS_PATH="/sdcard/pico8") diff --git a/components/pico8/femto8/src/p8_lua.c b/components/pico8/femto8/src/p8_lua.c index 30294c56..6086ac8d 100644 --- a/components/pico8/femto8/src/p8_lua.c +++ b/components/pico8/femto8/src/p8_lua.c @@ -79,6 +79,26 @@ int lua_init(); void lua_register_functions(lua_State *L); +#ifdef FEMTO8_ESPBOX +#include "p8_lua_alloc.h" +/* esp-box-emu: the interpreter's small objects come from pooled free lists + * rather than the locked system heap (p8_lua_alloc.c) */ +static int p8_lua_panic(lua_State *state) +{ + fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n", lua_tostring(state, -1)); + return 0; +} +static lua_State *p8_new_lua_state(void) +{ + lua_State *state = lua_newstate(p8_lua_alloc, NULL); + if (state) + lua_atpanic(state, p8_lua_panic); + return state; +} +#else +#define p8_new_lua_state() luaL_newstate() +#endif + static unsigned addr_remap(unsigned address) { if (address >= 0x0000 && address < 0x2000) @@ -2302,6 +2322,61 @@ int lua_mkdir(lua_State *L) return 1; } +#ifdef PICO8_PROFILE +/* esp-box-emu: cycle-count every API call so the glue can report where a + * slow cart spends its frame (API vs. Lua interpretation). */ +#include "esp_cpu.h" +#define PICO8_PROF_MAX 128 +pico8_prof_entry_t pico8_prof[PICO8_PROF_MAX]; +int pico8_prof_count; +static int pico8_prof_wrapper(lua_State *L) +{ + lua_CFunction fn = (lua_CFunction)lua_touserdata(L, lua_upvalueindex(1)); + pico8_prof_entry_t *e = &pico8_prof[lua_tointeger(L, lua_upvalueindex(2))]; + uint32_t t0 = esp_cpu_get_cycle_count(); + int ret = fn(L); + e->cycles += esp_cpu_get_cycle_count() - t0; + e->calls++; + return ret; +} +static void pico8_prof_register(lua_State *L, const char *name, lua_CFunction fn) +{ + if (pico8_prof_count < PICO8_PROF_MAX) { + pico8_prof[pico8_prof_count].name = name; + lua_pushlightuserdata(L, (void *)fn); + lua_pushinteger(L, pico8_prof_count); + lua_pushcclosure(L, pico8_prof_wrapper, 2); + lua_setglobal(L, name); + pico8_prof_count++; + } else { + lua_pushcfunction(L, fn); + lua_setglobal(L, name); + } +} +#undef lua_register +#define lua_register(L, n, f) pico8_prof_register(L, n, f) + +/* raw interpreter speed on this hardware: arithmetic, table and string loops */ +void pico8_lua_bench(void) +{ + static const struct { const char *name; const char *src; int ops; } tests[] = { + { "arith", "local t=0 for i=1,100000 do t=t+i*2-1 end", 100000 }, + { "table", "local a={} for i=1,20000 do a[i]=i end local s=0 for j=1,5 do for i=1,20000 do s=s+a[i] end end", 120000 }, + { "field", "local o={x=1,y=2} local s=0 for i=1,50000 do s=s+o.x+o.y o.x=o.x+1 end", 50000 }, + { "call", "local function f(a) return a+1 end local s=0 for i=1,50000 do s=f(s) end", 50000 }, + { "string", "local s=0 for i=1,5000 do local q=\"a\"..i s=s+#q end", 5000 }, + }; + for (unsigned i = 0; i < sizeof(tests) / sizeof(tests[0]); i++) { + uint32_t t0 = esp_cpu_get_cycle_count(); + int ret = luaL_dostring(L, tests[i].src); + uint32_t dt = esp_cpu_get_cycle_count() - t0; + printf("[PICO8] bench %-6s %s: %u us, %u cycles/iter\n", tests[i].name, ret ? "ERR" : "ok", + (unsigned)(dt / 240), (unsigned)(dt / tests[i].ops)); + if (ret) lua_pop(L, 1); + } +} +#endif + void lua_register_functions(lua_State *L) { // **************************************************************** @@ -2500,7 +2575,7 @@ int lua_load_api() { if (!L) { - L = luaL_newstate(); + L = p8_new_lua_state(); } luaL_openlibs(L); @@ -2549,6 +2624,9 @@ int lua_shutdown_api() p8_menuitem_reset_all(); lua_close(L); L = NULL; +#ifdef FEMTO8_ESPBOX + p8_lua_alloc_close(); +#endif } return 0; } @@ -2603,7 +2681,7 @@ void lua_print_error() int lua_init_script(const char *file_name, const char *script) { if (!L) - L = luaL_newstate(); + L = p8_new_lua_state(); char temp_file_name[PATH_MAX + 1]; temp_file_name[0] = '@'; diff --git a/components/pico8/femto8/src/p8_lua.h b/components/pico8/femto8/src/p8_lua.h index 07010ff3..e86b7a87 100644 --- a/components/pico8/femto8/src/p8_lua.h +++ b/components/pico8/femto8/src/p8_lua.h @@ -6,6 +6,12 @@ */ #ifndef P8_LUA_H +#ifdef PICO8_PROFILE +#include +typedef struct { const char *name; uint32_t cycles; uint32_t calls; } pico8_prof_entry_t; +extern pico8_prof_entry_t pico8_prof[]; +extern int pico8_prof_count; +#endif #define P8_LUA_H #include diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp index 886201ae..808994ab 100644 --- a/components/pico8/src/pico8.cpp +++ b/components/pico8/src/pico8.cpp @@ -18,12 +18,16 @@ #include "statistics.hpp" #include "platform/p8_espbox.h" +#define PICO8_PROF_MAX_REPORT 8 extern "C" { #include "p8_emu.h" #include "p8_input.h" #include "p8_audio.h" #include "p8_lua.h" void render_sounds(int16_t* buffer, int total_samples); // p8_audio.c +#ifdef PICO8_PROFILE +void pico8_lua_bench(void); // p8_lua.c +#endif } #include @@ -328,6 +332,35 @@ void run_pico8_rom() { fmt::print("[PICO8] {:.1f} fps, free internal {} B, PSRAM {} B\n", (presented - s_framesAtReport) * 1000000.0 / double(now - s_lastReportUs), heap_caps_get_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_free_size(MALLOC_CAP_SPIRAM)); +#ifdef PICO8_PROFILE + { + // cycles spent in the PICO-8 API since the last report, by function; + // the rest of the wall time is the Lua interpreter (and our flip) + const double elapsedCycles = double(now - s_lastReportUs) * 240.0; // 240MHz + uint64_t apiTotal = 0; + int order[PICO8_PROF_MAX_REPORT]; + int n = 0; + for (int i = 0; i < pico8_prof_count; i++) { + apiTotal += pico8_prof[i].cycles; + if (pico8_prof[i].cycles == 0) continue; + if (n < PICO8_PROF_MAX_REPORT) { order[n++] = i; } + else { + int minIdx = 0; + for (int k = 1; k < n; k++) if (pico8_prof[order[k]].cycles < pico8_prof[order[minIdx]].cycles) minIdx = k; + if (pico8_prof[i].cycles > pico8_prof[order[minIdx]].cycles) order[minIdx] = i; + } + } + for (int a = 0; a < n; a++) for (int b = a + 1; b < n; b++) + if (pico8_prof[order[b]].cycles > pico8_prof[order[a]].cycles) std::swap(order[a], order[b]); + std::string line = fmt::format("[PICO8] profile: api {:.0f}% ", 100.0 * double(apiTotal) / elapsedCycles); + for (int a = 0; a < n; a++) { + const auto& e = pico8_prof[order[a]]; + line += fmt::format("{} {:.0f}%/{} ", e.name, 100.0 * double(e.cycles) / elapsedCycles, e.calls); + } + fmt::print("{}\n", line); + for (int i = 0; i < pico8_prof_count; i++) { pico8_prof[i].cycles = 0; pico8_prof[i].calls = 0; } + } +#endif s_lastReportUs = now; s_framesAtReport = presented; } diff --git a/components/pico8/src/platform/p8_lua_alloc.c b/components/pico8/src/platform/p8_lua_alloc.c new file mode 100644 index 00000000..c4098715 --- /dev/null +++ b/components/pico8/src/platform/p8_lua_alloc.c @@ -0,0 +1,125 @@ +/* A Lua allocator for the ESP32-S3. + * + * The interpreter allocates and frees small objects constantly (TValues in + * tables, closures, strings, upvalues); the system heap serves each one + * through a lock and a general-purpose search, and on this board a string + * creation measured ~12k cycles. Lua's lua_Alloc contract hands us the old + * size on every free and realloc, so small blocks can come from size-class + * free lists with no header and no locking (one Lua state, one task). + * Blocks larger than the biggest class go to the heap as before. + * + * Chunks for the free lists are carved from PSRAM in 64KB slabs and returned + * to the heap when the allocator is closed (femto8 closes the Lua state at + * shutdown; the glue calls p8_lua_alloc_close() afterwards). + */ +#include "p8_lua_alloc.h" + +#include +#include +#include +#include "esp_heap_caps.h" + +#define SLAB_BYTES (64 * 1024) +#define MAX_SLABS 128 /* 8MB of small objects at most */ +#define NUM_CLASSES 16 /* 16, 32, ..., 256 bytes */ +#define CLASS_STEP 16 +#define MAX_SMALL (NUM_CLASSES * CLASS_STEP) + +typedef struct free_node { struct free_node *next; } free_node_t; + +static free_node_t *s_free[NUM_CLASSES]; +static void *s_slabs[MAX_SLABS]; +static int s_num_slabs; +static uint8_t *s_bump, *s_bump_end; /* unallocated tail of the newest slab */ +static size_t s_small_live, s_large_live; + +static inline int class_of(size_t n) { return (int)((n + CLASS_STEP - 1) / CLASS_STEP) - 1; } + +static void *small_alloc(size_t n) +{ + int c = class_of(n); + free_node_t *node = s_free[c]; + if (node) { + s_free[c] = node->next; + return node; + } + size_t sz = (size_t)(c + 1) * CLASS_STEP; + if (s_bump + sz > s_bump_end) { + if (s_num_slabs >= MAX_SLABS) + return NULL; + void *slab = heap_caps_malloc(SLAB_BYTES, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (!slab) + return NULL; + s_slabs[s_num_slabs++] = slab; + s_bump = (uint8_t *)slab; + s_bump_end = s_bump + SLAB_BYTES; + } + void *p = s_bump; + s_bump += sz; + return p; +} + +static void small_free(void *p, size_t n) +{ + int c = class_of(n); + free_node_t *node = (free_node_t *)p; + node->next = s_free[c]; + s_free[c] = node; +} + +void *p8_lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize) +{ + (void)ud; + if (nsize == 0) { + if (ptr) { + if (osize <= MAX_SMALL) { small_free(ptr, osize); s_small_live -= osize; } + else { free(ptr); s_large_live -= osize; } + } + return NULL; + } + if (ptr == NULL) { + /* Lua passes the object type in osize for a fresh allocation; it is + * not a size, so only nsize matters here */ + if (nsize <= MAX_SMALL) { + void *p = small_alloc(nsize); + if (p) s_small_live += nsize; + return p; + } + void *p = malloc(nsize); + if (p) s_large_live += nsize; + return p; + } + /* realloc: same class stays put, otherwise move */ + if (osize <= MAX_SMALL && nsize <= MAX_SMALL && class_of(osize) == class_of(nsize)) { + s_small_live += nsize - osize; + return ptr; + } + if (osize > MAX_SMALL && nsize > MAX_SMALL) { + void *p = realloc(ptr, nsize); + if (p) s_large_live += nsize - osize; + return p; + } + void *np = p8_lua_alloc(ud, NULL, 0, nsize); + if (!np) + return NULL; + memcpy(np, ptr, osize < nsize ? osize : nsize); + p8_lua_alloc(ud, ptr, osize, 0); + return np; +} + +void p8_lua_alloc_close(void) +{ + for (int i = 0; i < s_num_slabs; i++) + heap_caps_free(s_slabs[i]); + s_num_slabs = 0; + s_bump = s_bump_end = NULL; + memset(s_free, 0, sizeof(s_free)); + s_small_live = s_large_live = 0; +} + +void p8_lua_alloc_stats(size_t *small_live, size_t *large_live, size_t *slab_bytes) +{ + if (small_live) *small_live = s_small_live; + if (large_live) *large_live = s_large_live; + if (slab_bytes) *slab_bytes = (size_t)s_num_slabs * SLAB_BYTES; +} diff --git a/components/pico8/src/platform/p8_lua_alloc.h b/components/pico8/src/platform/p8_lua_alloc.h new file mode 100644 index 00000000..1d94f25f --- /dev/null +++ b/components/pico8/src/platform/p8_lua_alloc.h @@ -0,0 +1,16 @@ +#pragma once +/* esp-box-emu: a pooled lua_Alloc for femto8's Lua state (see p8_lua_alloc.c) */ +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void *p8_lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize); +/* release the pools; only after the Lua state that used them is closed */ +void p8_lua_alloc_close(void); +void p8_lua_alloc_stats(size_t *small_live, size_t *large_live, size_t *slab_bytes); + +#ifdef __cplusplus +} +#endif From 607b3488eec5cb16e1b57d90cfe9eeca9a91bf24 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 6 Oct 2026 13:21:08 -0500 Subject: [PATCH 10/19] perf(pico8): faster circfill/ovalfill, hline and cls; Lua slabs from internal SRAM first; VM core in IRAM circfill cost ~0.5ms per call (a third of some carts' frame): the octant walk drew every scanline several times over, each pixel through the full pixel_set. The fill now records one extent per row and draws it once; draw_hline writes screen nibbles directly when no fill pattern, secondary palette, mask or per-call attributes are in play; cls is a memset. Verified pixel-identical against the previous code with a test cart on the desktop build (circles of every radius, camera/clip, ovals, fillp). The interpreter itself is the limit for heavy carts (~1.3M Lua instructions/s from PSRAM, GC 1%): its small objects now come from internal SRAM first up to a budget, lvm/ltable/lstring run from IRAM, and PICO-8 RAM goes back to the default heap (measured ~10% of a frame). PICO8_PROFILE also reports instructions/s and GC share. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/femto8/src/lua/lgc.c | 18 +++++ components/pico8/femto8/src/p8_emu.c | 10 ++- components/pico8/femto8/src/p8_lua.c | 6 ++ components/pico8/femto8/src/p8_lua_helper.h | 76 +++++++++++++++++++- components/pico8/linker.lf | 5 ++ components/pico8/src/pico8.cpp | 24 ++++++- components/pico8/src/platform/p8_lua_alloc.c | 29 +++++++- components/pico8/src/platform/p8_lua_alloc.h | 3 + 8 files changed, 156 insertions(+), 15 deletions(-) diff --git a/components/pico8/femto8/src/lua/lgc.c b/components/pico8/femto8/src/lua/lgc.c index 9e77f9b3..35ae6165 100644 --- a/components/pico8/femto8/src/lua/lgc.c +++ b/components/pico8/femto8/src/lua/lgc.c @@ -1174,10 +1174,21 @@ void luaC_forcestep (lua_State *L) { /* ** performs a basic GC step only if collector is running */ +#ifdef PICO8_PROFILE +#include "esp_cpu.h" +uint32_t pico8_prof_gc_cycles, pico8_prof_gc_steps; +#endif void luaC_step (lua_State *L) { global_State *g = G(L); +#ifdef PICO8_PROFILE + uint32_t t0 = esp_cpu_get_cycle_count(); +#endif if (g->gcrunning) luaC_forcestep(L); else luaE_setdebt(g, -GCSTEPSIZE); /* avoid being called too often */ +#ifdef PICO8_PROFILE + pico8_prof_gc_cycles += esp_cpu_get_cycle_count() - t0; + pico8_prof_gc_steps++; +#endif } @@ -1189,6 +1200,9 @@ void luaC_step (lua_State *L) { void luaC_fullgc (lua_State *L, int isemergency) { global_State *g = G(L); int origkind = g->gckind; +#ifdef PICO8_PROFILE + uint32_t t0 = esp_cpu_get_cycle_count(); +#endif lua_assert(origkind != KGC_EMERGENCY); if (isemergency) /* do not run finalizers during emergency GC */ g->gckind = KGC_EMERGENCY; @@ -1210,6 +1224,10 @@ void luaC_fullgc (lua_State *L, int isemergency) { luaC_runtilstate(L, bitmask(GCSpropagate)); } g->gckind = origkind; +#ifdef PICO8_PROFILE + pico8_prof_gc_cycles += esp_cpu_get_cycle_count() - t0; + pico8_prof_gc_steps++; +#endif setpause(g, gettotalbytes(g)); if (!isemergency) /* do not run finalizers during emergency GC */ callallpendingfinalizers(L, 1); diff --git a/components/pico8/femto8/src/p8_emu.c b/components/pico8/femto8/src/p8_emu.c index 3f212a23..dae9fe1c 100644 --- a/components/pico8/femto8/src/p8_emu.c +++ b/components/pico8/femto8/src/p8_emu.c @@ -207,12 +207,10 @@ int p8_init() /* PICO-8 RAM (screen, sprites, map, draw state) is touched a dozen times * per pixel drawn: keep it in internal SRAM rather than PSRAM. Falls back * to the default heap if the emulator left too little internal RAM. */ - m_memory = (uint8_t *)heap_caps_malloc(MEMORY_SIZE, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); - if (!m_memory) - m_memory = (uint8_t *)malloc(MEMORY_SIZE); - m_overlay_memory = (uint8_t *)heap_caps_malloc(MEMORY_SCREEN_SIZE, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); - if (!m_overlay_memory) - m_overlay_memory = (uint8_t *)malloc(MEMORY_SCREEN_SIZE); + /* (measured: the drawing API is ~10% of a slow cart's frame; internal + * SRAM is better spent on the interpreter's objects, see the glue) */ + m_memory = (uint8_t *)malloc(MEMORY_SIZE); + m_overlay_memory = (uint8_t *)malloc(MEMORY_SCREEN_SIZE); #else m_memory = (uint8_t *)malloc(MEMORY_SIZE); m_overlay_memory = (uint8_t *)malloc(MEMORY_SCREEN_SIZE); diff --git a/components/pico8/femto8/src/p8_lua.c b/components/pico8/femto8/src/p8_lua.c index 6086ac8d..46660f1b 100644 --- a/components/pico8/femto8/src/p8_lua.c +++ b/components/pico8/femto8/src/p8_lua.c @@ -2563,10 +2563,16 @@ void lua_register_functions(lua_State *L) lua_pushnumber(L, fix32_from_bits(0x55558000)); lua_setglobal(L, "\x99"); // 153 β–₯ } +#ifdef PICO8_PROFILE +uint32_t pico8_prof_hooks; /* x3000 = Lua VM instructions executed */ +#endif static void lua_event_pump_hook(lua_State *L, lua_Debug *ar) { (void)L; (void)ar; +#ifdef PICO8_PROFILE + pico8_prof_hooks++; +#endif p8_pump_events(); p8_check_for_pause(); } diff --git a/components/pico8/femto8/src/p8_lua_helper.h b/components/pico8/femto8/src/p8_lua_helper.h index 810f7a0f..88dc7d78 100644 --- a/components/pico8/femto8/src/p8_lua_helper.h +++ b/components/pico8/femto8/src/p8_lua_helper.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include "p8_emu.h" @@ -34,6 +35,7 @@ static inline void draw_line(int x0, int y0, int x1, int y1, int col, int fillp) static inline void draw_char(int n, int left, int top, int col); static inline void draw_rect(int x0, int y0, int x1, int y1, int col, int fillp); static inline void draw_rectfill(int x0, int y0, int x1, int y1, int col, int fillp); +static inline int gfx_addr_remap(int location); static inline uint8_t gfx_addr_get(int x, int y, uint8_t *memory, int location, int size); static inline uint8_t gfx_get(int x, int y, int location, int size); static inline void gfx_set(int x, int y, int location, int size, int col); @@ -63,9 +65,14 @@ static inline void clear_screen(int color) { color = color_get(PALTYPE_DRAW, color); - for (int y = 0; y < P8_HEIGHT; y++) - for (int x = 0; x < P8_WIDTH; x++) - gfx_set(x, y, MEMORY_SCREEN, MEMORY_SCREEN_SIZE, color); + if (m_memory[MEMORY_RW_MASK] == 0xff) { + uint8_t pix = color & 0xf; + memset(&m_memory[gfx_addr_remap(MEMORY_SCREEN)], pix | (pix << 4), MEMORY_SCREEN_SIZE); + } else { + for (int y = 0; y < P8_HEIGHT; y++) + for (int x = 0; x < P8_WIDTH; x++) + gfx_set(x, y, MEMORY_SCREEN, MEMORY_SCREEN_SIZE, color); + } clip_set(0, 0, P8_WIDTH, P8_HEIGHT); cursor_set(0, 0, -1); @@ -190,6 +197,39 @@ static inline void draw_line(int x0, int y0, int x1, int y1, int col, int fillp) static inline void draw_hline(int x0, int y, int x1, int col, int fillp) { + /* Fast path for the common case -- no per-call attributes, no fill + * pattern, no secondary palette, default read/write mask: resolve the + * camera, clip and palette once and write the screen nibbles directly. + * Everything else goes through pixel_set() exactly as before. */ + if (!(col & 0x1000) && m_memory[MEMORY_FILLP] == 0 && m_memory[MEMORY_FILLP + 1] == 0 && + !(m_memory[MEMORY_FILLP_ATTR] & 4) && m_memory[MEMORY_RW_MASK] == 0xff) + { + int cx, cy, cx0, cy0, cx1, cy1; + camera_get(&cx, &cy); + clip_get(&cx0, &cy0, &cx1, &cy1); + y -= cy; + if (y < cy0 || y >= cy1) + return; + x0 -= cx; + x1 -= cx; + if (x0 < cx0) x0 = cx0; + if (x1 >= cx1) x1 = cx1 - 1; + if (x0 > x1) + return; + int c = (col == -1) ? pencolor_get() : col; + uint8_t pix = color_get(PALTYPE_DRAW, c & 0xf) & 0xf; + uint8_t *row = &m_memory[gfx_addr_remap(MEMORY_SCREEN) + y * 64]; + int x = x0; + if (x & 1) { + row[x >> 1] = (uint8_t)((pix << 4) | (row[x >> 1] & 0x0f)); + x++; + } + for (; x + 1 <= x1; x += 2) + row[x >> 1] = (uint8_t)(pix | (pix << 4)); + if (x <= x1) + row[x >> 1] = (uint8_t)((row[x >> 1] & 0xf0) | pix); + return; + } for (int x=x0;x<=x1;x++) pixel_set(x, y, col, fillp, DRAWTYPE_GRAPHIC); } @@ -261,6 +301,36 @@ static inline void draw_ovalfill_mask(int xc, int yc, int xr, int yr, int col, i int x = 0, y = abs(r); int d = 3 - 2 * abs(r); + if (mask == 0xff && yr <= 127) { + /* The octant walk below draws every scanline several times over + * (the segments overlap); with the full mask the result is just the + * widest extent per row, so collect that and fill each row once. */ + int16_t ext[256]; + int rows = 2 * yr + 1; + for (int i = 0; i < rows; i++) ext[i] = -1; + #define OVAL_EXT(row, half) do { int rr = (row) + yr; if (rr >= 0 && rr < rows && (half) > ext[rr]) ext[rr] = (half); } while (0) + OVAL_EXT(y * yr / r, x * xr / r); OVAL_EXT(-(y * yr / r), x * xr / r); + OVAL_EXT(x * yr / r, y * xr / r); OVAL_EXT(-(x * yr / r), y * xr / r); + while (y >= x) + { + x++; + if (d > 0) + { + y--; + d = d + 4 * (x - y) + 10; + } + else + d = d + 4 * x + 6; + OVAL_EXT(y * yr / r, x * xr / r); OVAL_EXT(-(y * yr / r), x * xr / r); + OVAL_EXT(x * yr / r, y * xr / r); OVAL_EXT(-(x * yr / r), y * xr / r); + } + #undef OVAL_EXT + for (int i = 0; i < rows; i++) + if (ext[i] >= 0) + draw_hline(xc - ext[i], yc + i - yr, xc + ext[i], col, fillp); + return; + } + draw_ovalfill_segment(xc, yc, x, y, r, xr, yr, col, fillp, mask); while (y >= x) diff --git a/components/pico8/linker.lf b/components/pico8/linker.lf index ce53322f..a2a67e79 100644 --- a/components/pico8/linker.lf +++ b/components/pico8/linker.lf @@ -21,3 +21,8 @@ entries: # the emulator-side glue owns the reset (the .data snapshot, the lifecycle # flags) and must survive it: keep it in the default sections pico8 (default) + # the interpreter's hot loop and table/string access run from IRAM rather + # than through the flash cache (their statics still follow pico8_statics) + lvm (noflash_text) + ltable (noflash_text) + lstring (noflash_text) diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp index 808994ab..17d28765 100644 --- a/components/pico8/src/pico8.cpp +++ b/components/pico8/src/pico8.cpp @@ -17,6 +17,7 @@ #include "box-emu.hpp" #include "statistics.hpp" #include "platform/p8_espbox.h" +#include "platform/p8_lua_alloc.h" #define PICO8_PROF_MAX_REPORT 8 extern "C" { @@ -27,6 +28,7 @@ extern "C" { void render_sounds(int16_t* buffer, int total_samples); // p8_audio.c #ifdef PICO8_PROFILE void pico8_lua_bench(void); // p8_lua.c +extern uint32_t pico8_prof_gc_cycles, pico8_prof_gc_steps, pico8_prof_hooks; #endif } @@ -289,6 +291,15 @@ void init_pico8(const std::string& rom_filename, uint8_t* romdata, size_t rom_da s_emuTaskPrio = uxTaskPriorityGet(nullptr); vTaskPrioritySet(nullptr, EMU_TASK_PRIO_WHILE_RUNNING); + // the interpreter's small objects come from internal SRAM first: leave the + // emulator (menu, display path, SD) a reserve and hand Lua the rest + { + constexpr size_t INTERNAL_RESERVE = 48 * 1024; + const size_t freeInternal = heap_caps_get_free_size(MALLOC_CAP_INTERNAL); + const size_t budget = freeInternal > INTERNAL_RESERVE ? freeInternal - INTERNAL_RESERVE : 0; + p8_lua_alloc_set_internal_budget(budget); + fmt::print("[PICO8] Lua internal-SRAM budget {} B\n", budget); + } box.audio_sample_rate(SAMPLE_RATE); s_audioRun = true; // the cart on core 0 (with the emulator loop, which outranks it), audio on core 1 @@ -329,9 +340,12 @@ void run_pico8_rom() { s_lastFrameUs = now; } if (now - s_lastReportUs > 5000000) { - fmt::print("[PICO8] {:.1f} fps, free internal {} B, PSRAM {} B\n", + size_t luaSmall = 0, luaLarge = 0, luaInternal = 0; + p8_lua_alloc_stats(&luaSmall, &luaLarge, &luaInternal); + fmt::print("[PICO8] {:.1f} fps, free internal {} B, PSRAM {} B, lua small {} B large {} B (internal slabs {} B)\n", (presented - s_framesAtReport) * 1000000.0 / double(now - s_lastReportUs), - heap_caps_get_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_free_size(MALLOC_CAP_SPIRAM)); + heap_caps_get_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_free_size(MALLOC_CAP_SPIRAM), + luaSmall, luaLarge, luaInternal); #ifdef PICO8_PROFILE { // cycles spent in the PICO-8 API since the last report, by function; @@ -352,7 +366,11 @@ void run_pico8_rom() { } for (int a = 0; a < n; a++) for (int b = a + 1; b < n; b++) if (pico8_prof[order[b]].cycles > pico8_prof[order[a]].cycles) std::swap(order[a], order[b]); - std::string line = fmt::format("[PICO8] profile: api {:.0f}% ", 100.0 * double(apiTotal) / elapsedCycles); + std::string line = fmt::format("[PICO8] profile: lua {:.2f} Minstr/s, gc {:.0f}%/{} steps, api {:.0f}% ", + double(pico8_prof_hooks) * 3000.0 / (double(now - s_lastReportUs) / 1e6) / 1e6, + 100.0 * double(pico8_prof_gc_cycles) / elapsedCycles, pico8_prof_gc_steps, + 100.0 * double(apiTotal) / elapsedCycles); + pico8_prof_gc_cycles = pico8_prof_gc_steps = pico8_prof_hooks = 0; for (int a = 0; a < n; a++) { const auto& e = pico8_prof[order[a]]; line += fmt::format("{} {:.0f}%/{} ", e.name, 100.0 * double(e.cycles) / elapsedCycles, e.calls); diff --git a/components/pico8/src/platform/p8_lua_alloc.c b/components/pico8/src/platform/p8_lua_alloc.c index c4098715..9277878e 100644 --- a/components/pico8/src/platform/p8_lua_alloc.c +++ b/components/pico8/src/platform/p8_lua_alloc.c @@ -20,6 +20,7 @@ #include "esp_heap_caps.h" #define SLAB_BYTES (64 * 1024) +#define INTERNAL_SLAB_BYTES (16 * 1024) /* small, so they fit a fragmented internal heap */ #define MAX_SLABS 128 /* 8MB of small objects at most */ #define NUM_CLASSES 16 /* 16, 32, ..., 256 bytes */ #define CLASS_STEP 16 @@ -32,6 +33,10 @@ static void *s_slabs[MAX_SLABS]; static int s_num_slabs; static uint8_t *s_bump, *s_bump_end; /* unallocated tail of the newest slab */ static size_t s_small_live, s_large_live; +/* Internal SRAM is several times faster than PSRAM for the interpreter's + * constant pointer chasing; the first slabs come from it, up to a budget set + * by the glue (p8_lua_alloc_set_internal_budget), the rest from PSRAM. */ +static size_t s_internal_budget, s_internal_used; static inline int class_of(size_t n) { return (int)((n + CLASS_STEP - 1) / CLASS_STEP) - 1; } @@ -45,14 +50,26 @@ static void *small_alloc(size_t n) } size_t sz = (size_t)(c + 1) * CLASS_STEP; if (s_bump + sz > s_bump_end) { + void *slab = NULL; + size_t slab_bytes = INTERNAL_SLAB_BYTES; if (s_num_slabs >= MAX_SLABS) return NULL; - void *slab = heap_caps_malloc(SLAB_BYTES, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (s_internal_used + INTERNAL_SLAB_BYTES <= s_internal_budget) { + slab = heap_caps_malloc(INTERNAL_SLAB_BYTES, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + if (slab) + s_internal_used += INTERNAL_SLAB_BYTES; + else + s_internal_budget = 0; /* nothing that size left: stop asking */ + } + if (!slab) { + slab = heap_caps_malloc(SLAB_BYTES, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + slab_bytes = SLAB_BYTES; + } if (!slab) return NULL; s_slabs[s_num_slabs++] = slab; s_bump = (uint8_t *)slab; - s_bump_end = s_bump + SLAB_BYTES; + s_bump_end = s_bump + slab_bytes; } void *p = s_bump; s_bump += sz; @@ -115,11 +132,17 @@ void p8_lua_alloc_close(void) s_bump = s_bump_end = NULL; memset(s_free, 0, sizeof(s_free)); s_small_live = s_large_live = 0; + s_internal_used = 0; +} + +void p8_lua_alloc_set_internal_budget(size_t bytes) +{ + s_internal_budget = bytes; } void p8_lua_alloc_stats(size_t *small_live, size_t *large_live, size_t *slab_bytes) { if (small_live) *small_live = s_small_live; if (large_live) *large_live = s_large_live; - if (slab_bytes) *slab_bytes = (size_t)s_num_slabs * SLAB_BYTES; + if (slab_bytes) *slab_bytes = s_internal_used; } diff --git a/components/pico8/src/platform/p8_lua_alloc.h b/components/pico8/src/platform/p8_lua_alloc.h index 1d94f25f..d25e1001 100644 --- a/components/pico8/src/platform/p8_lua_alloc.h +++ b/components/pico8/src/platform/p8_lua_alloc.h @@ -9,6 +9,9 @@ extern "C" { void *p8_lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize); /* release the pools; only after the Lua state that used them is closed */ void p8_lua_alloc_close(void); +/* how much internal SRAM the small-object slabs may take (0 = PSRAM only) */ +void p8_lua_alloc_set_internal_budget(size_t bytes); +/* slab_bytes reports the internal SRAM in use by the slabs */ void p8_lua_alloc_stats(size_t *small_live, size_t *large_live, size_t *slab_bytes); #ifdef __cplusplus From db7914f393f95bd0af1bbf2e4caeb5fc1bb13fb1 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 6 Oct 2026 13:36:43 -0500 Subject: [PATCH 11/19] docs(pico8): compatibility work, performance envelope and limits; profiler off by default Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- README.md | 10 +++++++++- components/pico8/CMakeLists.txt | 5 +++-- components/pico8/VENDOR.md | 27 +++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c9f207d5..e7c207e8 100644 --- a/README.md +++ b/README.md @@ -264,7 +264,15 @@ pico8/celeste.p8, boxart/celeste.jpg, Celeste Classic ``` Carts that use `cartdata()` save to `pico8/cdata/`. The 128x128 screen shows -1:1 in the "original" video mode and scaled to 240x240 in "fit". +1:1 in the "original" video mode and scaled to 240x240 in "fit". Multi-cart +games that `load("#id")` their other carts work when those carts sit in the +same folder as `id.p8.png` / `id.p8`. + +What to expect: the Lua interpreter runs at roughly 1.3M instructions per +second on the S3 (its heap lives in PSRAM), enough for carts of Celeste's +weight at full speed, but CPU-heavy carts close to PICO-8's limit run at a +few frames per second. Save states are not available (carts' own +`cartdata()` saves are); there is no mouse or keyboard. ### metadata.csv format diff --git a/components/pico8/CMakeLists.txt b/components/pico8/CMakeLists.txt index 805f458f..bbca8a1d 100644 --- a/components/pico8/CMakeLists.txt +++ b/components/pico8/CMakeLists.txt @@ -16,8 +16,9 @@ idf_component_register( # Where carts keep their cartdata() saves (femto8 defaults to a relative "cdata") target_compile_definitions(${COMPONENT_LIB} PRIVATE FEMTO8_ESPBOX=1 - # PICO8_PROFILE=1: cycle-count every API call and report it with the fps line - PICO8_PROFILE=1 + # PICO8_PROFILE=1: report Lua instructions/s, GC share and the cycle count of + # every API function with the fps line (see src/pico8.cpp) + # PICO8_PROFILE=1 CARTDATA_PATH="/sdcard/pico8/cdata" DEFAULT_CARTS_PATH="/sdcard/pico8") diff --git a/components/pico8/VENDOR.md b/components/pico8/VENDOR.md index 74d71c73..46ed1410 100644 --- a/components/pico8/VENDOR.md +++ b/components/pico8/VENDOR.md @@ -33,3 +33,30 @@ through `src/platform/p8_espbox.h`, implemented in `src/pico8.cpp`: written to run once per process). - `CARTDATA_PATH` / `DEFAULT_CARTS_PATH` are set to `/sdcard/pico8/...` at build time. +- PICO-8 compatibility (also fixed in the desktop build, which is the + reference used to verify them): a cart that overrides `_ENV` + (`for _ENV in all(objs) do circfill(...) end`, `function f(_ENV)`) still + reaches the API through a fallback in `lua/lvm.c` (the same approach as + fake-08's z8lua); `split()` accepts a non-string; `load("#bbs_id")` + resolves to a sibling `bbs_id.p8.png` / `.p8` so multi-cart games work when + their carts sit next to each other; `load()` resolves against the cart's + own folder (no working directory on the ESP-IDF VFS); `p8_wait_for_any_key` + accepts a gamepad button. +- Performance (`p8_lua_helper.h`): `sspr()` only walks the destination pixels + inside the clip rectangle (a cart scaling a sprite to thousands of pixels + looked hung); `circfill`/`ovalfill` draw each scanline once; `draw_hline` + writes screen nibbles directly in the common case; `cls` is a memset. All + verified pixel-identical against the previous code with a test cart. +- `p8_lua.c`: the Lua state uses the pooled allocator in + `src/platform/p8_lua_alloc.c` (small objects from internal SRAM first, then + PSRAM); `lvm`/`ltable`/`lstring` run from IRAM (`linker.lf`); a + `PICO8_PROFILE` build wraps every API function with a cycle counter. + +## Status and limits + +Measured on the BOX-3: the interpreter executes ~1.3M Lua instructions/s +with its heap in PSRAM (GC ~1%, the drawing API ~5-15% of a frame), which +runs Celeste at its full 30 fps but leaves CPU-heavy carts near PICO-8's +limit (e.g. Cattle Crisis, Mossmoss) at a few fps. Known: Pico Ball shows a +blank screen in upstream femto8 as well; no save states (the Lua state cannot +be snapshotted) -- carts' own `cartdata()` saves work; no mouse/keyboard. From eac44c71f492f907c030e9dd1edec62cacdd5964 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 6 Oct 2026 20:14:59 -0500 Subject: [PATCH 12/19] feat(pico8): save states A state is PICO-8's RAM, the overlay, the frame counters, the audio channels and the cart's Lua heap, serialized with Eris (Lua 5.2's persistence library, as fake-08 does; vendored from its z8lua tree with the fixed-point number I/O and the populateperms helper). Everything the cart created or replaced in _G is persisted as a graph; the API functions and library tables recorded before the cart ran are permanents referenced by name. The menu's save/load request is carried out by the cart task at its next frame boundary, where no cart code is on the Lua stack. Host-tested: a round trip through a fresh Lua state keeps closures with upvalues, metatables, captured library functions, a suspended coroutine, replaced originals, and clears globals created after the save. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/CMakeLists.txt | 2 +- components/pico8/femto8/src/lua/eris.c | 2727 +++++++++++++++++++++ components/pico8/femto8/src/lua/eris.h | 153 ++ components/pico8/femto8/src/p8_audio.c | 24 + components/pico8/femto8/src/p8_audio.h | 6 + components/pico8/femto8/src/p8_emu.c | 6 + components/pico8/femto8/src/p8_lua.c | 5 + components/pico8/include/pico8.hpp | 3 +- components/pico8/src/pico8.cpp | 55 +- components/pico8/src/platform/p8_espbox.h | 4 + components/pico8/src/platform/p8_state.c | 238 ++ components/pico8/src/platform/p8_state.h | 18 + 12 files changed, 3233 insertions(+), 8 deletions(-) create mode 100644 components/pico8/femto8/src/lua/eris.c create mode 100644 components/pico8/femto8/src/lua/eris.h create mode 100644 components/pico8/src/platform/p8_state.c create mode 100644 components/pico8/src/platform/p8_state.h diff --git a/components/pico8/CMakeLists.txt b/components/pico8/CMakeLists.txt index bbca8a1d..24986b8e 100644 --- a/components/pico8/CMakeLists.txt +++ b/components/pico8/CMakeLists.txt @@ -7,7 +7,7 @@ file(GLOB SRC_FEMTO8 ${F8}/*.c ${F8}/lua/*.c ${F8}/lodepng/*.c ${F8}/lexaloffle/ idf_component_register( INCLUDE_DIRS "include" - SRCS src/pico8.cpp src/platform/p8_lua_alloc.c ${SRC_FEMTO8} + SRCS src/pico8.cpp src/platform/p8_lua_alloc.c src/platform/p8_state.c ${SRC_FEMTO8} PRIV_INCLUDE_DIRS "src/platform" ${F8} ${F8}/data ${F8}/lua ${F8}/lodepng ${F8}/lexaloffle REQUIRES box-emu statistics esp_timer heap pthread LDFRAGMENTS "linker.lf" diff --git a/components/pico8/femto8/src/lua/eris.c b/components/pico8/femto8/src/lua/eris.c new file mode 100644 index 00000000..358a4b70 --- /dev/null +++ b/components/pico8/femto8/src/lua/eris.c @@ -0,0 +1,2727 @@ +/* +Eris - Heavy-duty persistence for Lua 5.2.4 - Based on Pluto +Copyright (c) 2013-2015 by Florian Nuecke. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +/* Standard library headers. */ +#include +#include +#include +#include +#include + +#include + +/* Mark us as part of the Lua core to get access to what we need. */ +#define eris_c +#define LUA_CORE + +/* Public Lua headers. */ +#include "lua.h" +#include "lauxlib.h" +#include "lualib.h" + +/* Internal Lua headers. */ +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "lzio.h" + +/* Eris header. */ +#include "eris.h" + +static void populateperms(lua_State *L, bool forUnpersist); + +/* +** {=========================================================================== +** Default settings. +** ============================================================================ +*/ + +/* Note that these are the default settings. They can be changed either from C + * by calling eris_g|set_setting() or from Lua using eris.settings(). */ + +/* The metatable key we use to allow customized persistence for tables and + * userdata. */ +static const char *const kPersistKey = "__persist"; + +/* Whether to pass the IO object (reader/writer) to the special function + * defined in the metafield or not. This is disabled per default because it + * mey allow Lua scripts to do more than they should. Enable this as needed. */ +static const bool kPassIOToPersist = false; + +/* Whether to persist debug information such as line numbers and upvalue and + * local variable names. */ +static const bool kWriteDebugInformation = true; + +/* Generate a human readable "path" that is shown together with error messages + * to indicate where in the object the error occurred. For example: + * eris.persist({false, bad = setmetatable({}, {__persist = false})}) + * Will produce: main:1: attempt to persist forbidden table (root.bad) + * This can be used for debugging, but is disabled per default due to the + * processing and memory overhead this introduces. */ +static const bool kGeneratePath = false; + +/* The maximum object complexity. This is the number of allowed recursions when + * persisting or unpersisting an object, for example for nested tables. This is + * used to avoid segfaults when writing or reading user data. */ +static const lua_Unsigned kMaxComplexity = 10000; + +/* +** ============================================================================ +** Lua internals interfacing. +** ============================================================================ +*/ + +/* Lua internals we use. We define these as macros to make it easier to swap + * them out, should the need ever arise. For example, the later Pluto versions + * copied these function to own files (presumably to allow building it as an + * extra shared library). These should be all functions we use that are not + * declared in lua.h or lauxlib.h. If there are some still directly in the code + * they were missed and should be replaced with a macro added here instead. */ +/* I'm quite sure we won't ever want to do this, because Eris needs a slightly + * patched Lua version to be able to persist some of the library functions, + * anyway: it needs to put the continuation C functions in the perms table. */ +/* ldebug.h */ +#define eris_ci_func ci_func +/* ldo.h */ +#define eris_incr_top incr_top +#define eris_savestack savestack +#define eris_restorestack restorestack +#define eris_reallocstack luaD_reallocstack +/* lfunc.h */ +#define eris_newproto luaF_newproto +#define eris_newLclosure luaF_newLclosure +#define eris_newupval luaF_newupval +#define eris_findupval luaF_findupval +/* lgc.h */ +#define eris_barrierproto luaC_barrierproto +/* lmem.h */ +#define eris_reallocvector luaM_reallocvector +/* lobject.h */ +#define eris_ttypenv ttypenv +#define eris_clLvalue clLvalue +#define eris_setnilvalue setnilvalue +#define eris_setclLvalue setclLvalue +#define eris_setobj setobj +#define eris_setsvalue2n setsvalue2n +/* lstate.h */ +#define eris_isLua isLua +#define eris_gch gch +#define eris_gco2uv gco2uv +#define eris_obj2gco obj2gco +#define eris_extendCI luaE_extendCI +/* lstring. h */ +#define eris_newlstr luaS_newlstr +/* lzio.h */ +#define eris_initbuffer luaZ_initbuffer +#define eris_buffer luaZ_buffer +#define eris_sizebuffer luaZ_sizebuffer +#define eris_bufflen luaZ_bufflen +#define eris_init luaZ_init +#define eris_read luaZ_read + +/* These are required for cross-platform support, since the size of TValue may + * differ, so the byte offset used by savestack/restorestack in Lua it is not a + * valid measure. */ +#define eris_savestackidx(L, p) ((p) - (L)->stack) +#define eris_restorestackidx(L, n) ((L)->stack + (n)) + +/* +** ============================================================================ +** Language strings for errors. +** ============================================================================ +*/ + +#define ERIS_ERR_CFUNC "attempt to persist a light C function (%p)" +#define ERIS_ERR_COMPLEXITY "object too complex" +#define ERIS_ERR_METATABLE "bad metatable, not nil or table" +#define ERIS_ERR_NOFUNC "attempt to persist unknown function type" +#define ERIS_ERR_READ "could not read data" +#define ERIS_ERR_SPER_FUNC "%s did not return a function" +#define ERIS_ERR_SPER_LOAD "bad unpersist function (%s expected, returned %s)" +#define ERIS_ERR_SPER_PROT "attempt to persist forbidden table" +#define ERIS_ERR_SPER_TYPE "%d not nil, boolean, or function" +#define ERIS_ERR_SPER_UFUNC "invalid restore function" +#define ERIS_ERR_SPER_UPERM "bad permanent value (%s expected, got %s)" +#define ERIS_ERR_SPER_UPERMNIL "bad permanent value (no value)" +#define ERIS_ERR_STACKBOUNDS "stack index out of bounds" +#define ERIS_ERR_TABLE "bad table value, got a nil value" +#define ERIS_ERR_THREAD "cannot persist currently running thread" +#define ERIS_ERR_THREADCI "invalid callinfo" +#define ERIS_ERR_THREADCTX "bad C continuation function" +#define ERIS_ERR_THREADERRF "invalid errfunc" +#define ERIS_ERR_THREADPC "saved program counter out of bounds" +#define ERIS_ERR_TRUNC_INT "int value would get truncated" +#define ERIS_ERR_TRUNC_SIZE "size_t value would get truncated" +#define ERIS_ERR_TYPE_FLOAT "unsupported lua_Number type" +#define ERIS_ERR_TYPE_INT "unsupported int type" +#define ERIS_ERR_TYPE_SIZE "unsupported size_t type" +#define ERIS_ERR_TYPEP "trying to persist unknown type %d" +#define ERIS_ERR_TYPEU "trying to unpersist unknown type %d" +#define ERIS_ERR_UCFUNC "bad C closure (C function expected, got %s)" +#define ERIS_ERR_UCFUNCNULL "bad C closure (C function expected, got null)" +#define ERIS_ERR_USERDATA "attempt to literally persist userdata" +#define ERIS_ERR_WRITE "could not write data" +#define ERIS_ERR_REF "invalid reference #%d. this usually means a special "\ + "persistence callback of a table referenced said table "\ + "(directly or indirectly via an upvalue)." + +/* +** ============================================================================ +** Constants, settings, types and forward declarations. +** ============================================================================ +*/ + +/* The "type" we write when we persist a value via a replacement from the + * permanents table. This is just an arbitrary number, but it must we lower + * than the reference offset (below) and outside the range Lua uses for its + * types (> LUA_TOTALTAGS). */ +#define ERIS_PERMANENT (LUA_TOTALTAGS + 1) + +/* This is essentially the first reference we'll use. We do this to save one + * field in our persisted data: if the value is smaller than this, the object + * itself follows, otherwise we have a reference to an already unpersisted + * object. Note that in the reftable the actual entries are still stored + * starting at the first array index to have a sequence (when unpersisting). */ +#define ERIS_REFERENCE_OFFSET (ERIS_PERMANENT + 1) + +/* Avoids having to write the NULL all the time, plus makes it easier adding + * a custom error message should you ever decide you want one. */ +#define eris_checkstack(L, n) luaL_checkstack(L, n, NULL) + +/* Used for internal consistency checks, for debugging. These are true asserts + * in the sense that they should never fire, even for bad inputs. */ +#if 0 +#define eris_assert(c) assert(c) +#define eris_ifassert(e) e +#else +#define eris_assert(c) ((void)0) +#define eris_ifassert(e) ((void)0) +#endif + +/* State information when persisting an object. */ +typedef struct PersistInfo { + lua_Writer writer; + void *ud; + const char *metafield; + bool writeDebugInfo; +} PersistInfo; + +/* State information when unpersisting an object. */ +typedef struct UnpersistInfo { + ZIO zio; + size_t sizeof_int; + size_t sizeof_size_t; +} UnpersistInfo; + +/* Info shared in persist and unpersist. */ +typedef struct Info { + lua_State *L; + lua_Unsigned level; + int refcount; /* int because rawseti/rawgeti takes an int. */ + lua_Unsigned maxComplexity; + bool generatePath; + bool passIOToPersist; + /* Which one it really is will always be clear from the context. */ + union { + PersistInfo pi; + UnpersistInfo upi; + } u; +} Info; + +/* Type names, used for error messages. */ +static const char *const kTypenames[] = { + "nil", "boolean", "lightuserdata", "number", "string", + "table", "function", "userdata", "thread", "proto", "upval", + "deadkey", "permanent" +}; + +/* Setting names as used in eris.settings / eris_g|set_setting. Also, the + * addresses of these static variables are used as keys in the registry of Lua + * states to save the current values of the settings (as light userdata). */ +static const char *const kSettingMetafield = "spkey"; +static const char *const kSettingPassIOToPersist = "spio"; +static const char *const kSettingGeneratePath = "path"; +static const char *const kSettingWriteDebugInfo = "debug"; +static const char *const kSettingMaxComplexity = "maxrec"; + +/* Header we prefix to persisted data for a quick check when unpersisting. */ +static char const kHeader[] = { 'E', 'R', 'I', 'S' }; +#define HEADER_LENGTH sizeof(kHeader) + +/* Floating point number used to check compatibility of loaded data. */ +static const lua_Number kHeaderNumber = (lua_Number)-1.234567890; + +/* Stack indices of some internal values/tables, to avoid magic numbers. */ +#define PERMIDX 1 +#define REFTIDX 2 +#define BUFFIDX 3 +#define PATHIDX 4 + +/* Table indices for upvalue tables, keeping track of upvals to open. */ +#define UVTOCL 1 +#define UVTONU 2 +#define UVTVAL 3 +#define UVTREF 4 + +/* }======================================================================== */ + +/* +** {=========================================================================== +** Utility functions. +** ============================================================================ +*/ + +/* Pushes an object into the reference table when unpersisting. This creates an + * entry pointing from the id the object is referenced by to the object. */ +static int +registerobject(Info *info) { /* perms reftbl ... obj */ + const int reference = ++(info->refcount); + eris_checkstack(info->L, 1); + lua_pushvalue(info->L, -1); /* perms reftbl ... obj obj */ + lua_rawseti(info->L, REFTIDX, reference); /* perms reftbl ... obj */ + return reference; +} + +/** ======================================================================== */ + +/* Pushes a TString* onto the stack if it holds a value, nil if it is NULL. */ +static void +pushtstring(lua_State* L, TString *ts) { /* ... */ + if (ts) { + eris_setsvalue2n(L, L->top, ts); + eris_incr_top(L); /* ... str */ + } + else { + lua_pushnil(L); /* ... nil */ + } +} + +/* Creates a copy of the string on top of the stack and sets it as the value + * of the specified TString**. */ +static void +copytstring(lua_State* L, TString **ts) { + size_t length; + const char *value = lua_tolstring(L, -1, &length); + *ts = eris_newlstr(L, value, length); +} + +/** ======================================================================== */ + +/* Pushes the specified segment to the current path, if we're generating one. + * This supports formatting strings using Lua's formatting capabilities. */ +static void +pushpath(Info *info, const char* fmt, ...) { /* perms reftbl var path ... */ + if (!info->generatePath) { + return; + } + else { + va_list argp; + eris_checkstack(info->L, 1); + va_start(argp, fmt); + lua_pushvfstring(info->L, fmt, argp); /* perms reftbl var path ... str */ + va_end(argp); + lua_rawseti(info->L, PATHIDX, luaL_len(info->L, PATHIDX) + 1); + } /* perms reftbl var path ... */ +} + +/* Pops the last added segment from the current path if we're generating one. */ +static void +poppath(Info *info) { /* perms reftbl var path ... */ + if (!info->generatePath) { + return; + } + eris_checkstack(info->L, 1); + lua_pushnil(info->L); /* perms reftbl var path ... nil */ + lua_rawseti(info->L, PATHIDX, luaL_len(info->L, PATHIDX)); +} /* perms reftbl var path ... */ + +/* Concatenates all current path segments into one string, pushes it and + * returns it. This is relatively inefficient, but it's for errors only and + * keeps the stack small, so it's better this way. */ +static const char* +path(Info *info) { /* perms reftbl var path ... */ + if (!info->generatePath) { + return ""; + } + eris_checkstack(info->L, 3); + lua_pushstring(info->L, ""); /* perms reftbl var path ... str */ + lua_pushnil(info->L); /* perms reftbl var path ... str nil */ + while (lua_next(info->L, PATHIDX)) { /* perms reftbl var path ... str k v */ + lua_insert(info->L, -2); /* perms reftbl var path ... str v k */ + lua_insert(info->L, -3); /* perms reftbl var path ... k str v */ + lua_concat(info->L, 2); /* perms reftbl var path ... k str */ + lua_insert(info->L, -2); /* perms reftbl var path ... str k */ + } /* perms reftbl var path ... str */ + return lua_tostring(info->L, -1); +} + +/* Generates an error message with the appended path, if available. */ +static int +eris_error(Info *info, const char *fmt, ...) { /* ... */ + va_list argp; + eris_checkstack(info->L, 5); + + luaL_where(info->L, 1); /* ... where */ + va_start(argp, fmt); + lua_pushvfstring(info->L, fmt, argp); /* ... where str */ + va_end(argp); + if (info->generatePath) { + lua_pushstring(info->L, " ("); /* ... where str " (" */ + path(info); /* ... where str " (" path */ + lua_pushstring(info->L, ")"); /* ... where str " (" path ")" */ + lua_concat(info->L, 5); /* ... msg */ + } + else { + lua_concat(info->L, 2); /* ... msg */ + } + return lua_error(info->L); +} + +/** ======================================================================== */ + +/* Tries to get a setting from the registry. */ +static bool +get_setting(lua_State *L, void *key) { /* ... */ + eris_checkstack(L, 1); + lua_pushlightuserdata(L, key); /* ... key */ + lua_gettable(L, LUA_REGISTRYINDEX); /* ... value/nil */ + if (lua_isnil(L, -1)) { /* ... nil */ + lua_pop(L, 1); /* ... */ + return false; + } /* ... value */ + return true; +} + +/* Stores a setting in the registry (or removes it if the value is nil). */ +static void +set_setting(lua_State *L, void *key) { /* ... value */ + eris_checkstack(L, 2); + lua_pushlightuserdata(L, key); /* ... value key */ + lua_insert(L, -2); /* ... key value */ + lua_settable(L, LUA_REGISTRYINDEX); /* ... */ +} + +/* Used as a callback for luaL_opt to check boolean setting values. */ +static bool +checkboolean(lua_State *L, int narg) { /* ... bool? ... */ + if (!lua_isboolean(L, narg)) { /* ... :( ... */ + return luaL_argerror(L, narg, lua_pushfstring(L, + "boolean expected, got %s", lua_typename(L, lua_type(L, narg)))); + } /* ... bool ... */ + return lua_toboolean(L, narg); +} + +/* }======================================================================== */ + +/* +** {=========================================================================== +** Persist and unpersist. +** ============================================================================ +*/ + +/* I have macros and I'm not afraid to use them! These are highly situational + * and assume an Info* named 'info' is available. */ + +/* Writes a raw memory block with the specified size. */ +#define WRITE_RAW(value, size) {\ + if (info->u.pi.writer(info->L, (value), (size), info->u.pi.ud)) \ + eris_error(info, ERIS_ERR_WRITE); } + +/* Writes a single value with the specified type. */ +#define WRITE_VALUE(value, type) write_##type(info, value) + +/* Writes a typed array with the specified length. */ +#define WRITE(value, length, type) { \ + int i; for (i = 0; i < length; ++i) WRITE_VALUE((value)[i], type); } + +/** ======================================================================== */ + +/* Reads a raw block of memory with the specified size. */ +#define READ_RAW(value, size) {\ + if (eris_read(&info->u.upi.zio, (value), (size))) \ + eris_error(info, ERIS_ERR_READ); } + +/* Reads a single value with the specified type. */ +#define READ_VALUE(type) read_##type(info) + +/* Reads a typed array with the specified length. */ +#define READ(value, length, type) { \ + int i; for (i = 0; i < length; ++i) (value)[i] = READ_VALUE(type); } + +/** ======================================================================== */ + +static void +write_uint8_t(Info *info, uint8_t value) { + WRITE_RAW(&value, sizeof(uint8_t)); +} + +static void +write_uint16_t(Info *info, uint16_t value) { + write_uint8_t(info, value); + write_uint8_t(info, value >> 8); +} + +static void +write_uint32_t(Info *info, uint32_t value) { + write_uint8_t(info, value); + write_uint8_t(info, value >> 8); + write_uint8_t(info, value >> 16); + write_uint8_t(info, value >> 24); +} + +static void +write_uint64_t(Info *info, uint64_t value) { + write_uint8_t(info, value); + write_uint8_t(info, value >> 8); + write_uint8_t(info, value >> 16); + write_uint8_t(info, value >> 24); + write_uint8_t(info, value >> 32); + write_uint8_t(info, value >> 40); + write_uint8_t(info, value >> 48); + write_uint8_t(info, value >> 56); +} + +static void +write_int16_t(Info *info, int16_t value) { + write_uint16_t(info, (uint16_t)value); +} + +static void +write_int32_t(Info *info, int32_t value) { + write_uint32_t(info, (uint32_t)value); +} + +static void +write_int64_t(Info *info, int64_t value) { + write_uint64_t(info, (uint64_t)value); +} + +static void +write_float32(Info *info, float value) { + uint32_t rep; + memcpy(&rep, &value, sizeof(float)); + write_uint32_t(info, rep); +} + +static void +write_float64(Info *info, double value) { + uint64_t rep; + memcpy(&rep, &value, sizeof(double)); + write_uint64_t(info, rep); +} + +/* Note regarding the following: any decent compiler should be able + * to reduce these to just the write call, since sizeof is constant. */ + +static void +write_int(Info *info, int value) { + if (sizeof(int) == sizeof(int16_t)) { + write_int16_t(info, value); + } + else if (sizeof(int) == sizeof(int32_t)) { + write_int32_t(info, value); + } + else if (sizeof(int) == sizeof(int64_t)) { + write_int64_t(info, value); + } + else { + eris_error(info, ERIS_ERR_TYPE_INT); + } +} + +static void +write_size_t(Info *info, size_t value) { + if (sizeof(size_t) == sizeof(uint16_t)) { + write_uint16_t(info, value); + } + else if (sizeof(size_t) == sizeof(uint32_t)) { + write_uint32_t(info, value); + } + else if (sizeof(size_t) == sizeof(uint64_t)) { + write_uint64_t(info, value); + } + else { + eris_error(info, ERIS_ERR_TYPE_SIZE); + } +} + +static void +write_lua_Number(Info *info, lua_Number value) { + /* femto8: lua_Number is a 16.16 fixed-point int32 */ + write_int32_t(info, (int32_t)value); +} + +/* Note that Lua only ever uses 32 bits of the Instruction type, so we can + * assert that there will be no truncation, even if the underlying type has + * more bits (might be the case on some 64 bit systems). */ + +static void +write_Instruction(Info *info, Instruction value) { + if (sizeof(Instruction) == sizeof(uint32_t)) { + write_uint32_t(info, value); + } + else { + uint32_t pvalue = (uint32_t)value; + /* Lua only uses 32 bits for its instructions. */ + eris_assert((Instruction)pvalue == value); + write_uint32_t(info, pvalue); + } +} + +/** ======================================================================== */ + +static uint8_t +read_uint8_t(Info *info) { + uint8_t value; + READ_RAW(&value, sizeof(uint8_t)); + return value; +} + +static uint16_t +read_uint16_t(Info *info) { + uint16_t value = (uint16_t)read_uint8_t(info); + value |= (uint16_t)read_uint8_t(info) << 8; + return value; +} + +static uint32_t +read_uint32_t(Info *info) { + uint32_t value = (uint32_t)read_uint8_t(info); + value |= (uint32_t)read_uint8_t(info) << 8; + value |= (uint32_t)read_uint8_t(info) << 16; + value |= (uint32_t)read_uint8_t(info) << 24; + return value; +} + +static uint64_t +read_uint64_t(Info *info) { + uint64_t value = (uint64_t)read_uint8_t(info); + value |= (uint64_t)read_uint8_t(info) << 8; + value |= (uint64_t)read_uint8_t(info) << 16; + value |= (uint64_t)read_uint8_t(info) << 24; + value |= (uint64_t)read_uint8_t(info) << 32; + value |= (uint64_t)read_uint8_t(info) << 40; + value |= (uint64_t)read_uint8_t(info) << 48; + value |= (uint64_t)read_uint8_t(info) << 56; + return value; +} + +static int16_t +read_int16_t(Info *info) { + return (int16_t)read_uint16_t(info); +} + +static int32_t +read_int32_t(Info *info) { + return (int32_t)read_uint32_t(info); +} + +static int64_t +read_int64_t(Info *info) { + return (int64_t)read_uint64_t(info); +} + +static float +read_float32(Info *info) { + float value; + uint32_t rep = read_uint32_t(info); + memcpy(&value, &rep, sizeof(float)); + return value; +} + +static double +read_float64(Info *info) { + double value; + uint64_t rep = read_uint64_t(info); + memcpy(&value, &rep, sizeof(double)); + return value; +} + +/* Note regarding the following: unlike with writing the sizeof check will be + * impossible to optimize away, since it depends on the input; however, the + * truncation check may be optimized away in the case where the read data size + * equals the native one, so reading data written on the same machine should be + * reasonably quick. Doing a (rather rudimentary) benchmark this did not have + * any measurable impact on performance. */ + +static int +read_int(Info *info) { + int value; + if (info->u.upi.sizeof_int == sizeof(int16_t)) { + int16_t pvalue = read_int16_t(info); + value = (int)pvalue; + if ((int32_t)value != pvalue) { + eris_error(info, ERIS_ERR_TRUNC_INT); + } + } + else if (info->u.upi.sizeof_int == sizeof(int32_t)) { + int32_t pvalue = read_int32_t(info); + value = (int)pvalue; + if ((int32_t)value != pvalue) { + eris_error(info, ERIS_ERR_TRUNC_INT); + } + } + else if (info->u.upi.sizeof_int == sizeof(int64_t)) { + int64_t pvalue = read_int64_t(info); + value = (int)pvalue; + if ((int64_t)value != pvalue) { + eris_error(info, ERIS_ERR_TRUNC_INT); + } + } + else { + eris_error(info, ERIS_ERR_TYPE_INT); + value = 0; /* not reached */ + } + return value; +} + +static size_t +read_size_t(Info *info) { + size_t value; + if (info->u.upi.sizeof_size_t == sizeof(uint16_t)) { + uint16_t pvalue = read_uint16_t(info); + value = (size_t)pvalue; + if ((uint32_t)value != pvalue) { + eris_error(info, ERIS_ERR_TRUNC_SIZE); + } + } + else if (info->u.upi.sizeof_size_t == sizeof(uint32_t)) { + uint32_t pvalue = read_uint32_t(info); + value = (size_t)pvalue; + if ((uint32_t)value != pvalue) { + eris_error(info, ERIS_ERR_TRUNC_SIZE); + } + } + else if (info->u.upi.sizeof_size_t == sizeof(uint64_t)) { + uint64_t pvalue = read_uint64_t(info); + value = (size_t)pvalue; + if ((uint64_t)value != pvalue) { + eris_error(info, ERIS_ERR_TRUNC_SIZE); + } + } + else { + eris_error(info, ERIS_ERR_TYPE_SIZE); + value = 0; /* not reached */ + } + return value; +} + +static lua_Number +read_lua_Number(Info *info) { + return (lua_Number)read_int32_t(info); +} + +static Instruction +read_Instruction(Info *info) { + return (Instruction)read_uint32_t(info); +} + +/** ======================================================================== */ + +/* Forward declarations for recursively called top-level functions. */ +static void persist_keyed(Info*, int type); +static void persist(Info*); +static void unpersist(Info*); + +/* +** ============================================================================ +** Simple types. +** ============================================================================ +*/ + +static void +p_boolean(Info *info) { /* ... bool */ + WRITE_VALUE(lua_toboolean(info->L, -1), uint8_t); +} + +static void +u_boolean(Info *info) { /* ... */ + eris_checkstack(info->L, 1); + lua_pushboolean(info->L, READ_VALUE(uint8_t)); /* ... bool */ + + eris_assert(lua_type(info->L, -1) == LUA_TBOOLEAN); +} + +/** ======================================================================== */ + +static void +p_pointer(Info *info) { /* ... ludata */ + WRITE_VALUE((size_t)lua_touserdata(info->L, -1), size_t); +} + +static void +u_pointer(Info *info) { /* ... */ + eris_checkstack(info->L, 1); + lua_pushlightuserdata(info->L, (void*)READ_VALUE(size_t)); /* ... ludata */ + + eris_assert(lua_type(info->L, -1) == LUA_TLIGHTUSERDATA); +} + +/** ======================================================================== */ + +static void +p_number(Info *info) { /* ... num */ + WRITE_VALUE(lua_tonumber(info->L, -1), lua_Number); +} + +static void +u_number(Info *info) { /* ... */ + eris_checkstack(info->L, 1); + lua_pushnumber(info->L, READ_VALUE(lua_Number)); /* ... num */ + + eris_assert(lua_type(info->L, -1) == LUA_TNUMBER); +} + +/** ======================================================================== */ + +static void +p_string(Info *info) { /* ... str */ + size_t length; + const char *value = lua_tolstring(info->L, -1, &length); + WRITE_VALUE(length, size_t); + WRITE_RAW(value, length); +} + +static void +u_string(Info *info) { /* ... */ + eris_checkstack(info->L, 2); + { + /* TODO Can we avoid this copy somehow? (Without it getting too nasty) */ + const size_t length = READ_VALUE(size_t); + char *value = (char*)lua_newuserdata(info->L, length * sizeof(char)); /* ... tmp */ + READ_RAW(value, length); + lua_pushlstring(info->L, value, length); /* ... tmp str */ + lua_replace(info->L, -2); /* ... str */ + } + registerobject(info); + + eris_assert(lua_type(info->L, -1) == LUA_TSTRING); +} + +/* +** ============================================================================ +** Tables and userdata. +** ============================================================================ +*/ + +static void +p_metatable(Info *info) { /* ... obj */ + eris_checkstack(info->L, 1); + pushpath(info, "@metatable"); + if (!lua_getmetatable(info->L, -1)) { /* ... obj mt? */ + lua_pushnil(info->L); /* ... obj nil */ + } /* ... obj mt/nil */ + persist(info); /* ... obj mt/nil */ + lua_pop(info->L, 1); /* ... obj */ + poppath(info); +} + +static void +u_metatable(Info *info) { /* ... tbl */ + eris_checkstack(info->L, 1); + pushpath(info, "@metatable"); + unpersist(info); /* ... tbl mt/nil? */ + if (lua_istable(info->L, -1)) { /* ... tbl mt */ + lua_setmetatable(info->L, -2); /* ... tbl */ + } + else if (lua_isnil(info->L, -1)) { /* ... tbl nil */ + lua_pop(info->L, 1); /* ... tbl */ + } + else { /* tbl :( */ + eris_error(info, ERIS_ERR_METATABLE); + } + poppath(info); +} + +/** ======================================================================== */ + +static void +p_literaltable(Info *info) { /* ... tbl */ + eris_checkstack(info->L, 3); + + /* Persist all key / value pairs. */ + lua_pushnil(info->L); /* ... tbl nil */ + while (lua_next(info->L, -2)) { /* ... tbl k v */ + lua_pushvalue(info->L, -2); /* ... tbl k v k */ + + if (info->generatePath) { + if (lua_type(info->L, -1) == LUA_TSTRING) { + const char *key = lua_tostring(info->L, -1); + pushpath(info, ".%s", key); + } + else { + const char *key = luaL_tolstring(info->L, -1, NULL); + pushpath(info, "[%s]", key); + lua_pop(info->L, 1); + } + } + + persist(info); /* ... tbl k v k */ + lua_pop(info->L, 1); /* ... tbl k v */ + persist(info); /* ... tbl k v */ + lua_pop(info->L, 1); /* ... tbl k */ + + poppath(info); + } /* ... tbl */ + + /* Terminate list. */ + lua_pushnil(info->L); /* ... tbl nil */ + persist(info); /* ... tbl nil */ + lua_pop(info->L, 1); /* ... tbl */ + + p_metatable(info); +} + +static void +u_literaltable(Info *info) { /* ... */ + eris_checkstack(info->L, 3); + + lua_newtable(info->L); /* ... tbl */ + + /* Preregister table for handling of cycles (keys, values or metatable). */ + registerobject(info); + + /* Unpersist all key / value pairs. */ + for (;;) { + pushpath(info, "@key"); + unpersist(info); /* ... tbl key/nil */ + poppath(info); + if (lua_isnil(info->L, -1)) { /* ... tbl nil */ + lua_pop(info->L, 1); /* ... tbl */ + break; + } /* ... tbl key */ + + if (info->generatePath) { + if (lua_type(info->L, -1) == LUA_TSTRING) { + const char *key = lua_tostring(info->L, -1); + pushpath(info, ".%s", key); + } + else { + const char *key = luaL_tolstring(info->L, -1, NULL); + pushpath(info, "[%s]", key); + lua_pop(info->L, 1); + } + } + + unpersist(info); /* ... tbl key value? */ + if (!lua_isnil(info->L, -1)) { /* ... tbl key value */ + lua_rawset(info->L, -3); /* ... tbl */ + } + else { + eris_error(info, ERIS_ERR_TABLE); + } + + poppath(info); + } + + u_metatable(info); /* ... tbl */ +} + +/** ======================================================================== */ + +static void +p_literaluserdata(Info *info) { /* ... udata */ + const size_t size = lua_rawlen(info->L, -1); + const void *value = lua_touserdata(info->L, -1); + WRITE_VALUE(size, size_t); + WRITE_RAW(value, size); + p_metatable(info); /* ... udata */ +} + +static void +u_literaluserdata(Info *info) { /* ... */ + eris_checkstack(info->L, 1); + { + size_t size = READ_VALUE(size_t); + void *value = lua_newuserdata(info->L, size); /* ... udata */ + READ_RAW(value, size); /* ... udata */ + } + registerobject(info); + u_metatable(info); +} + +/** ======================================================================== */ + +typedef void (*Callback) (Info*); + +static void +p_special(Info *info, Callback literal) { /* ... obj */ + int allow = (lua_type(info->L, -1) == LUA_TTABLE); + eris_checkstack(info->L, 4); + + /* Check whether we should persist literally, or via the metafunction. */ + if (lua_getmetatable(info->L, -1)) { /* ... obj mt */ + lua_pushstring(info->L, info->u.pi.metafield); /* ... obj mt pkey */ + lua_rawget(info->L, -2); /* ... obj mt persist? */ + switch (lua_type(info->L, -1)) { + /* No entry, act according to default. */ + case LUA_TNIL: /* ... obj mt nil */ + lua_pop(info->L, 2); /* ... obj */ + break; + + /* Boolean value, tells us whether allowed or not. */ + case LUA_TBOOLEAN: /* ... obj mt bool */ + allow = lua_toboolean(info->L, -1); + lua_pop(info->L, 2); /* ... obj */ + break; + + /* Function value, call it and don't persist literally. */ + case LUA_TFUNCTION: /* ... obj mt func */ + lua_replace(info->L, -2); /* ... obj func */ + lua_pushvalue(info->L, -2); /* ... obj func obj */ + + if (info->passIOToPersist) { + lua_pushlightuserdata(info->L, (void*)info->u.pi.writer); + /* ... obj func obj writer */ + lua_pushlightuserdata(info->L, info->u.pi.ud); + /* ... obj func obj writer ud */ + lua_call(info->L, 3, 1); /* ... obj func? */ + } + else { + lua_call(info->L, 1, 1); /* ... obj func? */ + } + if (!lua_isfunction(info->L, -1)) { /* ... obj :( */ + eris_error(info, ERIS_ERR_SPER_FUNC, info->u.pi.metafield); + } /* ... obj func */ + + /* Special persistence, call this function when unpersisting. */ + WRITE_VALUE(true, uint8_t); + persist(info); /* ... obj func */ + lua_pop(info->L, 1); /* ... obj */ + return; + default: /* ... obj mt :( */ + eris_error(info, ERIS_ERR_SPER_TYPE, info->u.pi.metafield); + return; /* not reached */ + } + } + + if (allow) { + /* Not special but literally persisted object. */ + WRITE_VALUE(false, uint8_t); + literal(info); /* ... obj */ + } + else if (lua_type(info->L, -1) == LUA_TTABLE) { + eris_error(info, ERIS_ERR_SPER_PROT); + } + else { + eris_error(info, ERIS_ERR_USERDATA); + } +} + +static void +u_special(Info *info, int type, Callback literal) { /* ... */ + eris_checkstack(info->L, 2); + if (READ_VALUE(uint8_t)) { + int reference; + /* Reserve entry in the reftable before unpersisting the function to keep + * the reference order intact. We can set this to nil at first, because + * there's no way the special function would access this. */ + lua_pushnil(info->L); /* ... nil */ + reference = registerobject(info); + lua_pop(info->L, 1); /* ... */ + /* Increment reference counter by one to compensate for the increment when + * persisting a special object. */ + unpersist(info); /* ... spfunc? */ + if (!lua_isfunction(info->L, -1)) { /* ... :( */ + eris_error(info, ERIS_ERR_SPER_UFUNC); + } /* ... spfunc */ + + if (info->passIOToPersist) { + lua_pushlightuserdata(info->L, &info->u.upi.zio); /* ... spfunc zio */ + lua_call(info->L, 1, 1); /* ... obj? */ + } else { + lua_call(info->L, 0, 1); /* ... obj? */ + } + + if (lua_type(info->L, -1) != type) { /* ... :( */ + const char *want = kTypenames[type]; + const char *have = kTypenames[lua_type(info->L, -1)]; + eris_error(info, ERIS_ERR_SPER_LOAD, want, have); + } /* ... obj */ + + /* Update the reftable entry. */ + lua_pushvalue(info->L, -1); /* ... obj obj */ + lua_rawseti(info->L, 2, reference); /* ... obj */ + } + else { + literal(info); /* ... obj */ + } +} + +/** ======================================================================== */ + +static void +p_table(Info *info) { /* ... tbl */ + p_special(info, p_literaltable); /* ... tbl */ +} + +static void +u_table(Info *info) { /* ... */ + u_special(info, LUA_TTABLE, u_literaltable); /* ... tbl */ + + eris_assert(lua_type(info->L, -1) == LUA_TTABLE); +} + +/** ======================================================================== */ + +static void +p_userdata(Info *info) { /* perms reftbl ... udata */ + p_special(info, p_literaluserdata); +} + +static void +u_userdata(Info *info) { /* ... */ + u_special(info, LUA_TUSERDATA, u_literaluserdata); /* ... udata */ + + eris_assert(lua_type(info->L, -1) == LUA_TUSERDATA); +} + +/* +** ============================================================================ +** Closures and threads. +** ============================================================================ +*/ + +/* We track the actual upvalues themselves by pushing their "id" (meaning a + * pointer to them) as lightuserdata to the reftable. This is safe because + * lightuserdata will not normally end up in there, because simple value types + * are always persisted directly (because that'll be just as large, memory- + * wise as when pointing to the first instance). Same for protos. */ + +static void +p_proto(Info *info) { /* ... proto */ + int i; + const Proto *p = (Proto*)lua_touserdata(info->L, -1); + eris_checkstack(info->L, 3); + + /* Write general information. */ + WRITE_VALUE(p->linedefined, int); + WRITE_VALUE(p->lastlinedefined, int); + WRITE_VALUE(p->numparams, uint8_t); + WRITE_VALUE(p->is_vararg, uint8_t); + WRITE_VALUE(p->maxstacksize, uint8_t); + + /* Write byte code. */ + WRITE_VALUE(p->sizecode, int); + WRITE(p->code, p->sizecode, Instruction); + + /* Write constants. */ + WRITE_VALUE(p->sizek, int); + pushpath(info, ".constants"); + for (i = 0; i < p->sizek; ++i) { + pushpath(info, "[%d]", i); + eris_setobj(info->L, info->L->top++, &p->k[i]); /* ... lcl proto obj */ + persist(info); /* ... lcl proto obj */ + lua_pop(info->L, 1); /* ... lcl proto */ + poppath(info); + } + poppath(info); + + /* Write child protos. */ + WRITE_VALUE(p->sizep, int); + pushpath(info, ".protos"); + for (i = 0; i < p->sizep; ++i) { + pushpath(info, "[%d]", i); + lua_pushlightuserdata(info->L, p->p[i]); /* ... lcl proto proto */ + lua_pushvalue(info->L, -1); /* ... lcl proto proto proto */ + persist_keyed(info, LUA_TPROTO); /* ... lcl proto proto */ + lua_pop(info->L, 1); /* ... lcl proto */ + poppath(info); + } + poppath(info); + + /* Write upvalues. */ + WRITE_VALUE(p->sizeupvalues, int); + for (i = 0; i < p->sizeupvalues; ++i) { + WRITE_VALUE(p->upvalues[i].instack, uint8_t); + WRITE_VALUE(p->upvalues[i].idx, uint8_t); + } + + /* If we don't have to persist debug information skip the rest. */ + WRITE_VALUE(info->u.pi.writeDebugInfo, uint8_t); + if (!info->u.pi.writeDebugInfo) { + return; + } + + /* Write function source code. */ + pushtstring(info->L, p->source); /* ... lcl proto source */ + persist(info); /* ... lcl proto source */ + lua_pop(info->L, 1); /* ... lcl proto */ + + /* Write line information. */ + WRITE_VALUE(p->sizelineinfo, int); + WRITE(p->lineinfo, p->sizelineinfo, int); + + /* Write locals info. */ + WRITE_VALUE(p->sizelocvars, int); + pushpath(info, ".locvars"); + for (i = 0; i < p->sizelocvars; ++i) { + pushpath(info, "[%d]", i); + WRITE_VALUE(p->locvars[i].startpc, int); + WRITE_VALUE(p->locvars[i].endpc, int); + pushtstring(info->L, p->locvars[i].varname); /* ... lcl proto varname */ + persist(info); /* ... lcl proto varname */ + lua_pop(info->L, 1); /* ... lcl proto */ + poppath(info); + } + poppath(info); + + /* Write upvalue names. */ + pushpath(info, ".upvalnames"); + for (i = 0; i < p->sizeupvalues; ++i) { + pushpath(info, "[%d]", i); + pushtstring(info->L, p->upvalues[i].name); /* ... lcl proto name */ + persist(info); /* ... lcl proto name */ + lua_pop(info->L, 1); /* ... lcl proto */ + poppath(info); + } + poppath(info); +} + +static void +u_proto(Info *info) { /* ... proto */ + int i, n; + Proto *p = (Proto*)lua_touserdata(info->L, -1); + eris_assert(p); + + eris_checkstack(info->L, 2); + + /* Preregister proto for handling of cycles (probably impossible, but + * maybe via the constants of the proto... not worth taking the risk). */ + registerobject(info); + + /* Read general information. */ + p->linedefined = READ_VALUE(int); + p->lastlinedefined = READ_VALUE(int); + p->numparams = READ_VALUE(uint8_t); + p->is_vararg = READ_VALUE(uint8_t); + p->maxstacksize = READ_VALUE(uint8_t); + + /* Read byte code. */ + p->sizecode = READ_VALUE(int); + eris_reallocvector(info->L, p->code, 0, p->sizecode, Instruction); + READ(p->code, p->sizecode, Instruction); + + /* Read constants. */ + p->sizek = READ_VALUE(int); + eris_reallocvector(info->L, p->k, 0, p->sizek, TValue); + /* Set all values to nil to avoid confusing the GC. */ + for (i = 0, n = p->sizek; i < n; ++i) { + eris_setnilvalue(&p->k[i]); + } + pushpath(info, ".constants"); + for (i = 0, n = p->sizek; i < n; ++i) { + pushpath(info, "[%d]", i); + unpersist(info); /* ... proto obj */ + eris_setobj(info->L, &p->k[i], info->L->top - 1); + lua_pop(info->L, 1); /* ... proto */ + poppath(info); + } + poppath(info); + + /* Read child protos. */ + p->sizep = READ_VALUE(int); + eris_reallocvector(info->L, p->p, 0, p->sizep, Proto*); + /* Null all entries to avoid confusing the GC. */ + memset(p->p, 0, p->sizep * sizeof(Proto*)); + pushpath(info, ".protos"); + for (i = 0, n = p->sizep; i < n; ++i) { + Proto *cp; + pushpath(info, "[%d]", i); + p->p[i] = eris_newproto(info->L); + lua_pushlightuserdata(info->L, (void*)p->p[i]); /* ... proto nproto */ + unpersist(info); /* ... proto nproto nproto/oproto */ + cp = (Proto*)lua_touserdata(info->L, -1); + if (cp != p->p[i]) { /* ... proto nproto oproto */ + /* Just overwrite it, GC will clean this up. */ + p->p[i] = cp; + } + lua_pop(info->L, 2); /* ... proto */ + poppath(info); + } + poppath(info); + + /* Read upvalues. */ + p->sizeupvalues = READ_VALUE(int); + eris_reallocvector(info->L, p->upvalues, 0, p->sizeupvalues, Upvaldesc); + for (i = 0, n = p->sizeupvalues; i < n; ++i) { + p->upvalues[i].name = NULL; + p->upvalues[i].instack = READ_VALUE(uint8_t); + p->upvalues[i].idx = READ_VALUE(uint8_t); + } + + /* Read debug information if any is present. */ + if (!READ_VALUE(uint8_t)) { + /* Match stack behaviour of alternative branch. */ + lua_pushvalue(info->L, -1); /* ... proto proto */ + return; + } + + /* Read function source code. */ + unpersist(info); /* ... proto str */ + copytstring(info->L, &p->source); + lua_pop(info->L, 1); /* ... proto */ + + /* Read line information. */ + p->sizelineinfo = READ_VALUE(int); + eris_reallocvector(info->L, p->lineinfo, 0, p->sizelineinfo, int); + READ(p->lineinfo, p->sizelineinfo, int); + + /* Read locals info. */ + p->sizelocvars = READ_VALUE(int); + eris_reallocvector(info->L, p->locvars, 0, p->sizelocvars, LocVar); + /* Null the variable names to avoid confusing the GC. */ + for (i = 0, n = p->sizelocvars; i < n; ++i) { + p->locvars[i].varname = NULL; + } + pushpath(info, ".locvars"); + for (i = 0, n = p->sizelocvars; i < n; ++i) { + pushpath(info, "[%d]", i); + p->locvars[i].startpc = READ_VALUE(int); + p->locvars[i].endpc = READ_VALUE(int); + unpersist(info); /* ... proto str */ + copytstring(info->L, &p->locvars[i].varname); + lua_pop(info->L, 1); /* ... proto */ + poppath(info); + } + poppath(info); + + /* Read upvalue names. */ + pushpath(info, ".upvalnames"); + for (i = 0, n = p->sizeupvalues; i < n; ++i) { + pushpath(info, "[%d]", i); + unpersist(info); /* ... proto str */ + copytstring(info->L, &p->upvalues[i].name); + lua_pop(info->L, 1); /* ... proto */ + poppath(info); + } + poppath(info); + lua_pushvalue(info->L, -1); /* ... proto proto */ + + eris_assert(lua_type(info->L, -1) == LUA_TLIGHTUSERDATA); +} + +/** ======================================================================== */ + +static void +p_upval(Info *info) { /* ... obj */ + persist(info); /* ... obj */ +} + +static void +u_upval(Info *info) { /* ... */ + eris_checkstack(info->L, 2); + + /* Create the table we use to store the stack location to the upval (1+2), + * the value of the upval (3) and any references to the upvalue's value (4+). + * References are stored as two entries each, the actual closure holding the + * upvalue, and the index of the upvalue in that closure. */ + lua_createtable(info->L, 5, 0); /* ... tbl */ + registerobject(info); + unpersist(info); /* ... tbl obj */ + lua_rawseti(info->L, -2, UVTVAL); /* ... tbl */ + + eris_assert(lua_type(info->L, -1) == LUA_TTABLE); +} + +/** ======================================================================== */ + +/* For Lua closures we write the upvalue ID, which is usually the memory + * address at which it is stored. This is used to tell which upvalues are + * identical when unpersisting. */ +/* In either case we store the upvale *values*, i.e. the actual objects they + * point to. As in Pluto, we will restore any upvalues of Lua closures as + * closed as first, i.e. the upvalue will store the TValue itself. When + * loading a thread containing the upvalue (meaning it's the actual owner of + * the upvalue) we open it, i.e. we point it to the thread's upvalue list. + * For C closures, upvalues are always closed. */ +static void +p_closure(Info *info) { /* perms reftbl ... func */ + int nup; + eris_checkstack(info->L, 2); + switch (ttype(info->L->top - 1)) { + case LUA_TLCF: /* light C function */ + /* We cannot persist these, they have to be handled via the permtable. */ + eris_error(info, ERIS_ERR_CFUNC, lua_tocfunction(info->L, -1)); + return; /* not reached */ + case LUA_TCCL: /* C closure */ { /* perms reftbl ... ccl */ + CClosure *cl = clCvalue(info->L->top - 1); + /* Mark it as a C closure. */ + WRITE_VALUE(true, uint8_t); + /* Write the upvalue count first, since we have to know it when creating + * a new closure when unpersisting. */ + WRITE_VALUE(cl->nupvalues, uint8_t); + + /* We can only persist these if the underlying C function is in the + * permtable. So we try to persist it first as a light C function. If it + * isn't in the permtable that'll cause an error (in the case above). */ + lua_pushcfunction(info->L, lua_tocfunction(info->L, -1)); + /* perms reftbl ... ccl cfunc */ + persist(info); /* perms reftbl ... ccl cfunc */ + lua_pop(info->L, 1); /* perms reftbl ... ccl */ + + /* Persist the upvalues. Since for C closures all upvalues are always + * closed we can just write the actual values. */ + pushpath(info, ".upvalues"); + for (nup = 1; nup <= cl->nupvalues; ++nup) { + pushpath(info, "[%d]", nup); + lua_getupvalue(info->L, -1, nup); /* perms reftbl ... ccl obj */ + persist(info); /* perms reftbl ... ccl obj */ + lua_pop(info->L, 1); /* perms reftbl ... ccl */ + poppath(info); + } + poppath(info); + break; + } + case LUA_TLCL: /* Lua function */ { /* perms reftbl ... lcl */ + LClosure *cl = eris_clLvalue(info->L->top - 1); + /* Mark it as a Lua closure. */ + WRITE_VALUE(false, uint8_t); + /* Write the upvalue count first, since we have to know it when creating + * a new closure when unpersisting. */ + WRITE_VALUE(cl->nupvalues, uint8_t); + + /* Persist the function's prototype. Pass the proto as a parameter to + * p_proto so that it can access it and register it in the ref table. */ + pushpath(info, ".proto"); + lua_pushlightuserdata(info->L, cl->p); /* perms reftbl ... lcl proto */ + lua_pushvalue(info->L, -1); /* perms reftbl ... lcl proto proto */ + persist_keyed(info, LUA_TPROTO); /* perms reftbl ... lcl proto */ + lua_pop(info->L, 1); /* perms reftbl ... lcl */ + poppath(info); + + /* Persist the upvalues. We pretend to write these as their own type, + * to get proper identity preservation. We also pass them as a parameter + * to p_upval so it can register the upvalue in the reference table. */ + pushpath(info, ".upvalues"); + for (nup = 1; nup <= cl->nupvalues; ++nup) { + const char *name = lua_getupvalue(info->L, -1, nup); + /* perms reftbl ... lcl obj */ + pushpath(info, ".%s", name); + lua_pushlightuserdata(info->L, lua_upvalueid(info->L, -2, nup)); + /* perms reftbl ... lcl obj id */ + persist_keyed(info, LUA_TUPVAL); /* perms reftbl ... lcl obj */ + lua_pop(info->L, 1); /* perms reftble ... lcl */ + poppath(info); + } + poppath(info); + break; + } + default: + eris_error(info, ERIS_ERR_NOFUNC); + return; /* not reached */ + } +} + +static void +u_closure(Info *info) { /* ... */ + int nup; + bool isCClosure = READ_VALUE(uint8_t); + lu_byte nups = READ_VALUE(uint8_t); + if (isCClosure) { + lua_CFunction f; + + /* Reserve reference for the closure to avoid light C function or its + * perm table key going first. */ + const int reference = ++(info->refcount); + + /* nups is guaranteed to be >= 1, otherwise it'd be a light C function. */ + eris_checkstack(info->L, nups < 2 ? 2 : nups); + + /* Read the C function from the permanents table. */ + unpersist(info); /* ... cfunc */ + if (!lua_iscfunction(info->L, -1)) { + eris_error(info, ERIS_ERR_UCFUNC, kTypenames[lua_type(info->L, -1)]); + } + f = lua_tocfunction(info->L, -1); + if (!f) { + eris_error(info, ERIS_ERR_UCFUNCNULL); + } + lua_pop(info->L, 1); /* ... */ + + /* Now this is a little roundabout, but we want to create the closure + * before unpersisting the actual upvalues to avoid cycles. So we have to + * create it with all nil first, then fill the upvalues in afterwards. */ + for (nup = 1; nup <= nups; ++nup) { + lua_pushnil(info->L); /* ... nil[1] ... nil[nup] */ + } + lua_pushcclosure(info->L, f, nups); /* ... ccl */ + + /* Create the entry in the reftable. */ + lua_pushvalue(info->L, -1); /* perms reftbl ... ccl ccl */ + lua_rawseti(info->L, REFTIDX, reference); /* perms reftbl ... ccl */ + + /* Unpersist actual upvalues. */ + pushpath(info, ".upvalues"); + for (nup = 1; nup <= nups; ++nup) { + pushpath(info, "[%d]", nup); + unpersist(info); /* ... ccl obj */ + lua_setupvalue(info->L, -2, nup); /* ... ccl */ + poppath(info); + } + poppath(info); + } + else { + Closure *cl; + Proto *p; + + eris_checkstack(info->L, 4); + + /* Create closure and anchor it on the stack (avoid collection via GC). */ + cl = eris_newLclosure(info->L, nups); + eris_setclLvalue(info->L, info->L->top, cl); /* ... lcl */ + eris_incr_top(info->L); + + /* Preregister closure for handling of cycles (upvalues). */ + registerobject(info); + + /* Read prototype. In general, we create protos (and upvalues) before + * trying to read them and pass a pointer to the instance along to the + * unpersist function. This way the instance is safely hooked up to an + * object, so we don't have to worry about it getting GCed. */ + pushpath(info, ".proto"); + cl->l.p = eris_newproto(info->L); + /* Push the proto into which to unpersist as a parameter to u_proto. */ + lua_pushlightuserdata(info->L, cl->l.p); /* ... lcl nproto */ + unpersist(info); /* ... lcl nproto nproto/oproto */ + eris_assert(lua_type(info->L, -1) == LUA_TLIGHTUSERDATA); + /* The proto we have now may differ, if we already unpersisted it before. + * In that case we now have a reference to the originally unpersisted + * proto so we'll use that. */ + p = (Proto*)lua_touserdata(info->L, -1); + if (p != cl->l.p) { /* ... lcl nproto oproto */ + /* Just overwrite the old one, GC will clean this up. */ + cl->l.p = p; + } + lua_pop(info->L, 2); /* ... lcl */ + eris_assert(cl->l.p->sizeupvalues == nups); + poppath(info); + + /* Unpersist all upvalues. */ + pushpath(info, ".upvalues"); + for (nup = 1; nup <= nups; ++nup) { + UpVal **uv = &cl->l.upvals[nup - 1]; + /* Get the actual name of the upvalue, if possible. */ + if (p->upvalues[nup - 1].name) { + pushpath(info, "[%s]", getstr(p->upvalues[nup - 1].name)); + } + else { + pushpath(info, "[%d]", nup); + } + unpersist(info); /* ... lcl tbl */ + eris_assert(lua_type(info->L, -1) == LUA_TTABLE); + lua_rawgeti(info->L, -1, UVTOCL); /* ... lcl tbl olcl/nil */ + if (lua_isnil(info->L, -1)) { /* ... lcl tbl nil */ + lua_pop(info->L, 1); /* ... lcl tbl */ + lua_pushvalue(info->L, -2); /* ... lcl tbl lcl */ + lua_rawseti(info->L, -2, UVTOCL); /* ... lcl tbl */ + lua_pushinteger(info->L, nup); /* ... lcl tbl nup */ + lua_rawseti(info->L, -2, UVTONU); /* ... lcl tbl */ + *uv = eris_newupval(info->L); + } + else { /* ... lcl tbl olcl */ + LClosure *ocl; + int onup; + eris_assert(lua_type(info->L, -1) == LUA_TFUNCTION); + ocl = eris_clLvalue(info->L->top - 1); + lua_pop(info->L, 1); /* ... lcl tbl */ + lua_rawgeti(info->L, -1, UVTONU); /* ... lcl tbl onup */ + eris_assert(lua_type(info->L, -1) == LUA_TNUMBER); + onup = lua_tointeger(info->L, -1); + lua_pop(info->L, 1); /* ... lcl tbl */ + *uv = ocl->upvals[onup - 1]; + } + luaC_objbarrier(info->L, cl, *uv); + + /* Set the upvalue's actual value and add our reference to the upvalue to + * the list, for reference patching if we have to open the upvalue in + * u_thread. Either is only necessary if the upvalue is still closed. */ + if ((*uv)->v == &(*uv)->u.value) { + int i; + /* Always update the value of the upvalue's value for closed upvalues, + * even if we re-used one - if we had a cycle, it might have been + * incorrectly initialized to nil before (or rather, not yet set). */ + lua_rawgeti(info->L, -1, UVTVAL); /* ... lcl tbl obj */ + eris_setobj(info->L, &(*uv)->u.value, info->L->top - 1); + lua_pop(info->L, 1); /* ... lcl tbl */ + + lua_pushinteger(info->L, nup); /* ... lcl tbl nup */ + lua_pushvalue(info->L, -3); /* ... lcl tbl nup lcl */ + if (luaL_len(info->L, -3) >= UVTVAL) { + /* Got a valid sequence (value already set), insert at the end. */ + i = luaL_len(info->L, -3); + lua_rawseti(info->L, -3, i + 1); /* ... lcl tbl nup */ + lua_rawseti(info->L, -2, i + 2); /* ... lcl tbl */ + } + else { /* ... lcl tbl nup lcl */ + /* Find where to insert. This can happen if we have cycles, in which + * case the table is not fully initialized at this point, i.e. the + * value is not in it, yet (we work around that by always setting it, + * as seen above). */ + for (i = UVTREF;; i += 2) { + lua_rawgeti(info->L, -3, i); /* ... lcl tbl nup lcl lcl/nil */ + if (lua_isnil(info->L, -1)) { /* ... lcl tbl nup lcl nil */ + lua_pop(info->L, 1); /* ... lcl tbl nup lcl */ + lua_rawseti(info->L, -3, i); /* ... lcl tbl nup */ + lua_rawseti(info->L, -2, i + 1); /* ... lcl tbl */ + break; + } + else { + lua_pop(info->L, 1); /* ... lcl tbl nup lcl */ + } + } /* ... lcl tbl */ + } + } + + lua_pop(info->L, 1); /* ... lcl */ + poppath(info); + } + poppath(info); + + eris_barrierproto(info->L, p, cl); + p->cache = cl; /* save it in cache for reuse, see lvm.c:416 */ + } + + eris_assert(lua_type(info->L, -1) == LUA_TFUNCTION); +} + +/** ======================================================================== */ + +static void +p_thread(Info *info) { /* ... thread */ + lua_State* thread = lua_tothread(info->L, -1); + size_t level = 0, total = thread->top - thread->stack; + CallInfo *ci; + GCObject *uvi; + + eris_checkstack(info->L, 2); + + /* We cannot persist any running threads, because by definition we *are* that + * running thread. And we use the stack. So yeah, really not a good idea. */ + if (thread == info->L) { + eris_error(info, ERIS_ERR_THREAD); + return; /* not reached */ + } + + /* Persist the stack. Save the total size and used space first. */ + WRITE_VALUE(thread->stacksize, int); + WRITE_VALUE(total, size_t); + + /* The Lua stack looks like this: + * stack ... top ... stack_last + * Where stack <= top <= stack_last, and "top" actually being the first free + * element, i.e. there's nothing stored there. So we stop one below that. */ + pushpath(info, ".stack"); + lua_pushnil(info->L); /* ... thread nil */ + /* Since the thread's stack may be re-allocated in the meantime, we cannot + * use pointer arithmetic here (i.e. o = thread->stack; ...; ++o). Instead we + * have to keep track of our position in the stack directly (which we do for + * the path info anyway) and compute the actual address each time. + */ + for (; level < total; ++level) { + pushpath(info, "[%d]", level); + eris_setobj(info->L, info->L->top - 1, thread->stack + level); + /* ... thread obj */ + persist(info); /* ... thread obj */ + poppath(info); + } + lua_pop(info->L, 1); /* ... thread */ + poppath(info); + + /* If the thread isn't running this must be the default value, which is 1. */ + eris_assert(thread->nny == 1); + + /* Error jump info should only be set while thread is running. */ + eris_assert(thread->errorJmp == NULL); + + /* thread->oldpc always seems to be uninitialized, at least gdb always shows + * it as 0xbaadf00d when I set a breakpoint here. */ + + /* Write general information. */ + WRITE_VALUE(thread->status, uint8_t); + WRITE_VALUE(eris_savestackidx(thread, + eris_restorestack(thread, thread->errfunc)), size_t); + /* These are only used while a thread is being executed or can be deduced: + WRITE_VALUE(thread->nCcalls, uint16_t); + WRITE_VALUE(thread->allowhook, uint8_t); */ + + /* Hooks are not supported, bloody can of worms, those. + WRITE_VALUE(thread->hookmask, uint8_t); + WRITE_VALUE(thread->basehookcount, int); + WRITE_VALUE(thread->hookcount, int); */ + + if (thread->hook) { + /* TODO Warn that hooks are not persisted? */ + } + + /* Write call information (stack frames). In 5.2 CallInfo is stored in a + * linked list that originates in thead.base_ci. Upon initialization the + * thread.ci is set to thread.base_ci. During thread calls this is extended + * and always represents the tail of the callstack, though not necessarily of + * the linked list (which can be longer if the callstack was deeper earlier, + * but shrunk due to returns). */ + pushpath(info, ".callinfo"); + level = 0; + eris_assert(&thread->base_ci != thread->ci->next); + for (ci = &thread->base_ci; ci != thread->ci->next; ci = ci->next) { + pushpath(info, "[%d]", level++); + WRITE_VALUE(eris_savestackidx(thread, ci->func), size_t); + WRITE_VALUE(eris_savestackidx(thread, ci->top), size_t); + /* CallInfo.nresults is only set for actual functions */ + WRITE_VALUE(ttisfunction(ci->func) ? ci->nresults : 0, int16_t); + WRITE_VALUE(ci->callstatus, uint8_t); + /* CallInfo.extra is used in two contexts: if L->status == LUA_YIELD and + * CallInfo is the one stored as L->ci, in which case ci->extra refers to + * the original value of L->ci->func, and when we have a yieldable pcall + * (ci->callstatus & CIST_YPCALL) where ci->extra holds the stack level + * of the function being called (see lua_pcallk). We save the ci->extra + * for L->ci after the loop, because we won't know which one it is when + * unpersisting. */ + if (ci->callstatus & CIST_YPCALL) { + WRITE_VALUE(eris_savestackidx(thread, + eris_restorestack(thread, ci->extra)), size_t); + } + + eris_assert(eris_isLua(ci) || (ci->callstatus & CIST_TAIL) == 0); + + if (eris_isLua(ci)) { + StkId func = ci->func; + if (ci->callstatus & CIST_HOOKYIELD) { + /* Yielded from hook, mimic what resume does. */ + ci->func = restorestack(thread, ci->extra); + /* Also, store ci->func for unpersisting, + * as ci->extra won't be restored yet. */ + WRITE_VALUE(eris_savestackidx(thread, ci->func), size_t); + } + const LClosure *lcl = eris_ci_func(ci); /* Uses ci->func */ + ci->func = func; + WRITE_VALUE(eris_savestackidx(thread, ci->u.l.base), size_t); + WRITE_VALUE(ci->u.l.savedpc - lcl->p->code, size_t); + } + else { + WRITE_VALUE((ci->callstatus & (CIST_STAT | CIST_YIELDED)) + ? ci->u.c.status : 0, uint8_t); + + /* These are only used while a thread is being executed: + WRITE_VALUE(ci->u.c.old_errfunc, ptrdiff_t); + WRITE_VALUE(ci->u.c.old_allowhook, uint8_t); */ + + /* TODO Is this really right? Hooks may be a problem? */ + if (ci->callstatus & (CIST_YPCALL | CIST_YIELDED)) { + WRITE_VALUE(ci->u.c.ctx, int); + eris_assert(ci->u.c.k); + lua_pushcfunction(info->L, ci->u.c.k); /* ... thread func */ + persist(info); /* ... thread func/nil */ + lua_pop(info->L, 1); /* ... thread */ + } + } + + /* Write whether there's more to come. */ + WRITE_VALUE(ci->next == thread->ci->next, uint8_t); + + poppath(info); + } + /** See comment on ci->extra in loop. */ + if (thread->status == LUA_YIELD) { + WRITE_VALUE(eris_savestackidx(thread, + eris_restorestack(thread, thread->ci->extra)), size_t); + } + poppath(info); + + pushpath(info, ".openupval"); + lua_pushnil(info->L); /* ... thread nil */ + level = 0; + for (uvi = thread->openupval; + uvi != NULL; + uvi = eris_gch(uvi)->next) + { + UpVal *uv = eris_gco2uv(uvi); + pushpath(info, "[%d]", level++); + WRITE_VALUE(eris_savestackidx(thread, uv->v) + 1, size_t); + eris_setobj(info->L, info->L->top - 1, uv->v); /* ... thread obj */ + lua_pushlightuserdata(info->L, uv); /* ... thread obj id */ + persist_keyed(info, LUA_TUPVAL); /* ... thread obj */ + poppath(info); + } + WRITE_VALUE(0, size_t); + lua_pop(info->L, 1); /* ... thread */ + poppath(info); +} + +/* Used in u_thread to validate read stack positions. */ +#define validate(stackpos, inclmax) \ + if ((stackpos) < thread->stack || stackpos > (inclmax)) { \ + (stackpos) = thread->stack; \ + eris_error(info, ERIS_ERR_STACKBOUNDS); } + +/* I had so hoped to get by without any 'hacks', but I surrender. We mark the + * thread as incomplete to avoid the GC messing with it while we're building + * it. Otherwise it may try to shrink its stack. We do this by setting its + * stack field to null for every call that may trigger a GC run, since that + * field is what's used to determine whether threads should be shrunk. See + * lgc.c:699. Some of the locks could probably be joined (since nothing + * inbetween requires the stack field to be valid), but I prefer to keep the + * "invalid" blocks as small as possible to make it clearer. Also, locking and + * unlocking are really just variable assignments, so they're really cheap. */ +#define LOCK(L) (L->stack = NULL) +#define UNLOCK(L) (L->stack = stack) + +static void +u_thread(Info *info) { /* ... */ + lua_State* thread; + size_t level; + StkId stack, o; + + eris_checkstack(info->L, 3); + + thread = lua_newthread(info->L); /* ... thread */ + registerobject(info); + + /* Unpersist the stack. Read size first and adjust accordingly. */ + eris_reallocstack(thread, READ_VALUE(int)); + stack = thread->stack; /* After the realloc in case the address changes. */ + thread->top = thread->stack + READ_VALUE(size_t); + validate(thread->top, thread->stack_last); + + /* Read the elements one by one. */ + LOCK(thread); + pushpath(info, ".stack"); + UNLOCK(thread); + level = 0; + for (o = stack; o < thread->top; ++o) { + LOCK(thread); + pushpath(info, "[%d]", level++); + unpersist(info); /* ... thread obj */ + UNLOCK(thread); + eris_setobj(thread, o, info->L->top - 1); + lua_pop(info->L, 1); /* ... thread */ + LOCK(thread); + poppath(info); + UNLOCK(thread); + } + LOCK(thread); + poppath(info); + UNLOCK(thread); + + /* As in p_thread, just to make sure. */ + eris_assert(thread->nny == 1); + eris_assert(thread->errorJmp == NULL); + eris_assert(thread->hook == NULL); + + /* See comment in persist. */ + thread->oldpc = NULL; + + /* Read general information. */ + thread->status = READ_VALUE(uint8_t); + thread->errfunc = eris_savestack(thread, + eris_restorestackidx(thread, READ_VALUE(size_t))); + if (thread->errfunc) { + o = eris_restorestack(thread, thread->errfunc); + validate(o, thread->top); + if (eris_ttypenv(o) != LUA_TFUNCTION) { + eris_error(info, ERIS_ERR_THREADERRF); + } + } + /* These are only used while a thread is being executed or can be deduced: + thread->nCcalls = READ_VALUE(uint16_t); + thread->allowhook = READ_VALUE(uint8_t); */ + eris_assert(thread->allowhook == 1); + + /* Not supported. + thread->hookmask = READ_VALUE(uint8_t); + thread->basehookcount = READ_VALUE(int); + thread->hookcount = READ_VALUE(int); */ + + /* Read call information (stack frames). */ + LOCK(thread); + pushpath(info, ".callinfo"); + UNLOCK(thread); + thread->ci = &thread->base_ci; + level = 0; + for (;;) { + LOCK(thread); + pushpath(info, "[%d]", level++); + UNLOCK(thread); + thread->ci->func = eris_restorestackidx(thread, READ_VALUE(size_t)); + validate(thread->ci->func, thread->top - 1); + thread->ci->top = eris_restorestackidx(thread, READ_VALUE(size_t)); + validate(thread->ci->top, thread->stack_last); + thread->ci->nresults = READ_VALUE(int16_t); + thread->ci->callstatus = READ_VALUE(uint8_t); + /** See comment in p_thread. */ + if (thread->ci->callstatus & CIST_YPCALL) { + thread->ci->extra = eris_savestack(thread, + eris_restorestackidx(thread, READ_VALUE(size_t))); + o = eris_restorestack(thread, thread->ci->extra); + validate(o, thread->top); + if (eris_ttypenv(o) != LUA_TFUNCTION) { + eris_error(info, ERIS_ERR_THREADCI); + } + } + + if (eris_isLua(thread->ci)) { + StkId func = thread->ci->func; + if (thread->ci->callstatus & CIST_HOOKYIELD) { + /* See corresponding persist code */ + thread->ci->func = eris_restorestackidx(thread, READ_VALUE(size_t)); + } + LClosure *lcl = eris_ci_func(thread->ci); /* Uses ci->func */ + thread->ci->func = func; + thread->ci->u.l.base = eris_restorestackidx(thread, READ_VALUE(size_t)); + validate(thread->ci->u.l.base, thread->top); + thread->ci->u.l.savedpc = lcl->p->code + READ_VALUE(size_t); + if (thread->ci->u.l.savedpc < lcl->p->code || + thread->ci->u.l.savedpc > lcl->p->code + lcl->p->sizecode) + { + thread->ci->u.l.savedpc = lcl->p->code; /* Just to be safe. */ + eris_error(info, ERIS_ERR_THREADPC); + } + } + else { + thread->ci->u.c.status = READ_VALUE(uint8_t); + + /* These are only used while a thread is being executed: + thread->ci->u.c.old_errfunc = READ_VALUE(ptrdiff_t); + thread->ci->u.c.old_allowhook = READ_VALUE(uint8_t); */ + thread->ci->u.c.old_errfunc = 0; + thread->ci->u.c.old_allowhook = 0; + + /* TODO Is this really right? */ + if (thread->ci->callstatus & (CIST_YPCALL | CIST_YIELDED)) { + thread->ci->u.c.ctx = READ_VALUE(int); + LOCK(thread); + unpersist(info); /* ... thread func? */ + UNLOCK(thread); + if (lua_iscfunction(info->L, -1)) { /* ... thread func */ + thread->ci->u.c.k = lua_tocfunction(info->L, -1); + } + else { + eris_error(info, ERIS_ERR_THREADCTX); + return; /* not reached */ + } + lua_pop(info->L, 1); /* ... thread */ + } + else { + thread->ci->u.c.ctx = 0; + thread->ci->u.c.k = NULL; + } + } + LOCK(thread); + poppath(info); + UNLOCK(thread); + + /* Read in value for check for next iteration. */ + if (READ_VALUE(uint8_t)) { + break; + } + else { + thread->ci = eris_extendCI(thread); + } + } + if (thread->status == LUA_YIELD) { + thread->ci->extra = eris_savestack(thread, + eris_restorestackidx(thread, READ_VALUE(size_t))); + o = eris_restorestack(thread, thread->ci->extra); + validate(o, thread->top); + if (eris_ttypenv(o) != LUA_TFUNCTION) { + eris_error(info, ERIS_ERR_THREADCI); + } + } + LOCK(thread); + poppath(info); + UNLOCK(thread); + + /* Get from context: only zero for dead threads, otherwise one. */ + thread->nCcalls = thread->status != LUA_OK || lua_gettop(thread) != 0; + + /* Proceed to open upvalues. These upvalues will already exist due to the + * functions using them having been unpersisted (they'll usually be in the + * stack of the thread). For this reason we store all previous references to + * the upvalue in a table that is returned when we try to unpersist an + * upvalue, so that we can adjust these references in here. */ + LOCK(thread); + pushpath(info, ".openupval"); + UNLOCK(thread); + level = 0; + for (;;) { + UpVal *nuv; + StkId stk; + /* Get the position of the upvalue on the stack. As a special value we pass + * zero to indicate there are no more upvalues. */ + const size_t offset = READ_VALUE(size_t); + if (offset == 0) { + break; + } + LOCK(thread); + pushpath(info, "[%d]", level); + UNLOCK(thread); + stk = eris_restorestackidx(thread, offset - 1); + validate(stk, thread->top - 1); + LOCK(thread); + unpersist(info); /* ... thread tbl */ + UNLOCK(thread); + eris_assert(lua_type(info->L, -1) == LUA_TTABLE); + + /* Create the open upvalue either way. */ + LOCK(thread); + nuv = eris_findupval(thread, stk); + UNLOCK(thread); + + /* Then check if we need to patch some references. */ + lua_rawgeti(info->L, -1, UVTREF); /* ... thread tbl lcl/nil */ + if (!lua_isnil(info->L, -1)) { /* ... thread tbl lcl */ + int i, n; + eris_assert(lua_type(info->L, -1) == LUA_TFUNCTION); + /* Already exists, replace it. To do this we have to patch all the + * references to the already existing one, which we added to the table in + * u_closure. */ + lua_pop(info->L, 1); /* ... thread tbl */ + for (i = UVTREF, n = luaL_len(info->L, -1); i <= n; i += 2) { + LClosure *cl; + int nup; + lua_rawgeti(info->L, -1, i); /* ... thread tbl lcl */ + cl = eris_clLvalue(info->L->top - 1); + lua_pop(info->L, 1); /* ... thread tbl */ + lua_rawgeti(info->L, -1, i + 1); /* ... thread tbl nup */ + nup = lua_tointeger(info->L, -1); + lua_pop(info->L, 1); /* ... thread tbl */ + /* Open the upvalue by pointing to the stack and register in GC. */ + cl->upvals[nup - 1] = nuv; + luaC_objbarrier(info->L, cl, nuv); + } + } + else { /* ... thread tbl nil */ + eris_assert(lua_isnil(info->L, -1)); + lua_pop(info->L, 1); /* ... thread tbl */ + } + + /* Store open upvalue in table for future references. */ + LOCK(thread); + lua_pop(info->L, 1); /* ... thread */ + poppath(info); + UNLOCK(thread); + } + poppath(info); + + eris_assert(lua_type(info->L, -1) == LUA_TTHREAD); +} + +#undef UNLOCK +#undef LOCK + +#undef validate + +/* +** ============================================================================ +** Top-level delegator. +** ============================================================================ +*/ + +static void +persist_typed(Info *info, int type) { /* perms reftbl ... obj */ + eris_ifassert(const int top = lua_gettop(info->L)); + if (info->level >= info->maxComplexity) { + eris_error(info, ERIS_ERR_COMPLEXITY); + } + ++info->level; + + WRITE_VALUE(type, int); + switch(type) { + case LUA_TBOOLEAN: + p_boolean(info); + break; + case LUA_TLIGHTUSERDATA: + p_pointer(info); + break; + case LUA_TNUMBER: + p_number(info); + break; + case LUA_TSTRING: + p_string(info); + break; + case LUA_TTABLE: + p_table(info); + break; + case LUA_TFUNCTION: + p_closure(info); + break; + case LUA_TUSERDATA: + p_userdata(info); + break; + case LUA_TTHREAD: + p_thread(info); + break; + case LUA_TPROTO: + p_proto(info); + break; + case LUA_TUPVAL: + p_upval(info); + break; + default: + eris_error(info, ERIS_ERR_TYPEP, type); + } /* perms reftbl ... obj */ + + --info->level; + eris_assert(top == lua_gettop(info->L)); +} + +/* Second-level delegating persist function, used for cases when persisting + * data that's stored in the reftable with a key that is not the data itself, + * namely upvalues and protos. */ +static void +persist_keyed(Info *info, int type) { /* perms reftbl ... obj refkey */ + eris_checkstack(info->L, 2); + + /* Keep a copy of the key for pushing it to the reftable, if necessary. */ + lua_pushvalue(info->L, -1); /* perms reftbl ... obj refkey refkey */ + + /* If the object has already been written, write a reference to it. */ + lua_rawget(info->L, REFTIDX); /* perms reftbl ... obj refkey ref? */ + if (!lua_isnil(info->L, -1)) { /* perms reftbl ... obj refkey ref */ + const int reference = lua_tointeger(info->L, -1); + WRITE_VALUE(reference + ERIS_REFERENCE_OFFSET, int); + lua_pop(info->L, 2); /* perms reftbl ... obj */ + return; + } /* perms reftbl ... obj refkey nil */ + lua_pop(info->L, 1); /* perms reftbl ... obj refkey */ + + /* Copy the refkey for the perms check below. */ + lua_pushvalue(info->L, -1); /* perms reftbl ... obj refkey refkey */ + + /* Put the value in the reference table. This creates an entry pointing from + * the object (or its key) to the id the object is referenced by. */ + lua_pushinteger(info->L, ++(info->refcount)); + /* perms reftbl ... obj refkey refkey ref */ + lua_rawset(info->L, REFTIDX); /* perms reftbl ... obj refkey */ + + /* At this point, we'll give the permanents table a chance to play. */ + lua_gettable(info->L, PERMIDX); /* perms reftbl ... obj permkey? */ + if (!lua_isnil(info->L, -1)) { /* perms reftbl ... obj permkey */ + type = lua_type(info->L, -2); + /* Prepend permanent "type" so that we know it's a permtable key. This will + * trigger u_permanent when unpersisting. Also write the original type, so + * that we can verify what we get in the permtable when unpersisting is of + * the same kind we had when persisting. */ + WRITE_VALUE(ERIS_PERMANENT, int); + WRITE_VALUE(type, uint8_t); + persist(info); /* perms reftbl ... obj permkey */ + lua_pop(info->L, 1); /* perms reftbl ... obj */ + } + else { /* perms reftbl ... obj nil */ + /* No entry in the permtable for this object, persist it directly. */ + lua_pop(info->L, 1); /* perms reftbl ... obj */ + persist_typed(info, type); /* perms reftbl ... obj */ + } /* perms reftbl ... obj */ +} + +/* Top-level delegating persist function. */ +static void +persist(Info *info) { /* perms reftbl ... obj */ + /* Grab the object's type. */ + const int type = lua_type(info->L, -1); + + /* If the object is nil, only write its type. */ + if (type == LUA_TNIL) { + WRITE_VALUE(type, int); + } + /* Write simple values directly, because writing a "reference" would take up + * just as much space and we can save ourselves work this way. */ + else if (type == LUA_TBOOLEAN || + type == LUA_TLIGHTUSERDATA || + type == LUA_TNUMBER) + { + persist_typed(info, type); /* perms reftbl ... obj */ + } + /* For all non-simple values we keep a record in the reftable, so that we + * keep references alive across persisting and unpersisting an object. This + * has the nice side-effect of saving some space. */ + else { + eris_checkstack(info->L, 1); + lua_pushvalue(info->L, -1); /* perms reftbl ... obj obj */ + persist_keyed(info, type); /* perms reftbl ... obj */ + } +} + +/** ======================================================================== */ + +static void +u_permanent(Info *info) { /* perms reftbl ... */ + const int type = READ_VALUE(uint8_t); + /* Reserve reference to avoid the key going first. */ + const int reference = ++(info->refcount); + eris_checkstack(info->L, 1); + unpersist(info); /* perms reftbl ... permkey */ + lua_gettable(info->L, PERMIDX); /* perms reftbl ... obj? */ + if (lua_isnil(info->L, -1)) { /* perms reftbl ... nil */ + /* Since we may need permanent values to rebuild other structures, namely + * closures and threads, we cannot allow perms to fail unpersisting. */ + eris_error(info, ERIS_ERR_SPER_UPERMNIL); + } + else if (lua_type(info->L, -1) != type) { /* perms reftbl ... :( */ + /* For the same reason that we cannot allow nil we must also require the + * unpersisted value to be of the correct type. */ + const char *want = kTypenames[type]; + const char *have = kTypenames[lua_type(info->L, -1)]; + eris_error(info, ERIS_ERR_SPER_UPERM, want, have); + } /* perms reftbl ... obj */ + /* Create the entry in the reftable. */ + lua_pushvalue(info->L, -1); /* perms reftbl ... obj obj */ + lua_rawseti(info->L, REFTIDX, reference); /* perms reftbl ... obj */ +} + +static void +unpersist(Info *info) { /* perms reftbl ... */ + eris_ifassert(const int top = lua_gettop(info->L)); + if (info->level >= info->maxComplexity) { + eris_error(info, ERIS_ERR_COMPLEXITY); + } + ++info->level; + + eris_checkstack(info->L, 1); + { + const int typeOrReference = READ_VALUE(int); + if (typeOrReference > ERIS_REFERENCE_OFFSET) { + const int reference = typeOrReference - ERIS_REFERENCE_OFFSET; + lua_rawgeti(info->L, REFTIDX, reference); /* perms reftbl ud ... obj? */ + if (lua_isnil(info->L, -1)) { /* perms reftbl ud ... :( */ + eris_error(info, ERIS_ERR_REF, reference); + } /* perms reftbl ud ... obj */ + } + else { + const int type = typeOrReference; + switch (type) { + case LUA_TNIL: + lua_pushnil(info->L); + break; + case LUA_TBOOLEAN: + u_boolean(info); + break; + case LUA_TLIGHTUSERDATA: + u_pointer(info); + break; + case LUA_TNUMBER: + u_number(info); + break; + case LUA_TSTRING: + u_string(info); + break; + case LUA_TTABLE: + u_table(info); + break; + case LUA_TFUNCTION: + u_closure(info); + break; + case LUA_TUSERDATA: + u_userdata(info); + break; + case LUA_TTHREAD: + u_thread(info); + break; + case LUA_TPROTO: + u_proto(info); + break; + case LUA_TUPVAL: + u_upval(info); + break; + case ERIS_PERMANENT: + u_permanent(info); + break; + default: + eris_error(info, ERIS_ERR_TYPEU, type); + } /* perms reftbl ... obj? */ + } + } + + --info->level; + eris_assert(top + 1 == lua_gettop(info->L)); +} + +/* }======================================================================== */ + +/* +** {=========================================================================== +** Writer and reader implementation for library calls. +** ============================================================================ +*/ + +/* Implementation note: we use the MBuffer struct, but we don't use the built- + * in reallocation functions since we'll keep our working copy on the stack, to + * allow for proper collection if we have to throw an error. This is very much + * what the auxlib does with its buffer functionality. Which we don't use since + * we cannot guarantee stack balance inbetween calls to luaL_add*. */ + +static int +writer(lua_State *L, const void *p, size_t sz, void *ud) { + /* perms reftbl buff path? ... */ + const char *value = (const char*)p; + Mbuffer *buff = (Mbuffer*)ud; + const size_t size = eris_bufflen(buff); + const size_t capacity = eris_sizebuffer(buff); + if (capacity - size < sz) { + size_t newcapacity = capacity * 2; /* overflow checked below */ + if (newcapacity - size < sz) { + newcapacity = capacity + sz; /* overflow checked below */ + } + if (newcapacity <= capacity) { + /* Overflow in capacity, buffer size limit reached. */ + return 1; + } else { + char *newbuff; + eris_checkstack(L, 1); + newbuff = (char*)lua_newuserdata(L, newcapacity * sizeof(char)); + /* perms reftbl buff path? ... nbuff */ + memcpy(newbuff, eris_buffer(buff), eris_bufflen(buff)); + lua_replace(L, BUFFIDX); /* perms reftbl nbuff path? ... */ + eris_buffer(buff) = newbuff; + eris_sizebuffer(buff) = newcapacity; + } + } + memcpy(&eris_buffer(buff)[eris_bufflen(buff)], value, sz); + eris_bufflen(buff) += sz; + return 0; +} + +/** ======================================================================== */ + +/* Readonly, interface compatible with MBuffer macros. */ +typedef struct RBuffer { + const char *buffer; + size_t n; + size_t buffsize; +} RBuffer; + +static const char* +reader(lua_State *L, void *ud, size_t *sz) { + RBuffer *buff = (RBuffer*)ud; + (void) L; /* unused */ + if (eris_bufflen(buff) == 0) { + return NULL; + } + *sz = eris_bufflen(buff); + eris_bufflen(buff) = 0; + return eris_buffer(buff); +} + +/* }======================================================================== */ + +/* +** {=========================================================================== +** Library functions. +** ============================================================================ +*/ + +static void +p_header(Info *info) { + WRITE_RAW(kHeader, HEADER_LENGTH); + WRITE_VALUE(sizeof(lua_Number), uint8_t); + WRITE_VALUE(kHeaderNumber, lua_Number); + WRITE_VALUE(sizeof(int), uint8_t); + WRITE_VALUE(sizeof(size_t), uint8_t); +} + +static void +u_header(Info *info) { + char header[HEADER_LENGTH]; + uint8_t number_size; + READ_RAW(header, HEADER_LENGTH); + if (strncmp(kHeader, header, HEADER_LENGTH)) { + luaL_error(info->L, "invalid data"); + } + number_size = READ_VALUE(uint8_t); + if (number_size == 0) { + /* Old 64-bit versions of eris wrote '\0' and then three random bytes. */ + /* We skip them here for backwards compatibility. */ + char throw_away[3]; + READ_RAW(throw_away, 3); + + number_size = READ_VALUE(uint8_t); + } + if (number_size != sizeof(lua_Number)) { + luaL_error(info->L, "incompatible floating point type"); + } + /* In this case we really do want floating point equality. */ + if (READ_VALUE(lua_Number) != kHeaderNumber) { + luaL_error(info->L, "incompatible floating point representation"); + } + info->u.upi.sizeof_int = READ_VALUE(uint8_t); + info->u.upi.sizeof_size_t = READ_VALUE(uint8_t); +} + +static void +unchecked_persist(lua_State *L, lua_Writer writer, void *ud) { + Info info; /* perms buff rootobj */ + info.L = L; + info.level = 0; + info.refcount = 0; + info.maxComplexity = kMaxComplexity; + info.passIOToPersist = kPassIOToPersist; + info.generatePath = kGeneratePath; + info.u.pi.writer = writer; + info.u.pi.ud = ud; + info.u.pi.metafield = kPersistKey; + info.u.pi.writeDebugInfo = kWriteDebugInformation; + + eris_checkstack(L, 3); + + if (get_setting(L, (void*)&kSettingMaxComplexity)) { + /* perms buff rootobj value */ + info.maxComplexity = lua_tounsigned(L, -1); + lua_pop(L, 1); /* perms buff rootobj */ + } + if (get_setting(L, (void*)&kSettingGeneratePath)) { + /* perms buff rootobj value */ + info.generatePath = lua_toboolean(L, -1); + lua_pop(L, 1); /* perms buff rootobj */ + } + if (get_setting(L, (void*)&kSettingPassIOToPersist)) { + /* perms buff rootobj value */ + info.passIOToPersist = lua_toboolean(L, -1); + lua_pop(L, 1); /* perms buff rootobj */ + } + if (get_setting(L, (void*)&kSettingMetafield)) {/* perms buff rootobj value */ + info.u.pi.metafield = lua_tostring(L, -1); + lua_pop(L, 1); /* perms buff rootobj */ + } + if (get_setting(L, (void*)&kSettingWriteDebugInfo)) { + /* perms buff rootobj value */ + info.u.pi.writeDebugInfo = lua_toboolean(L, -1); + lua_pop(L, 1); /* perms buff rootobj */ + } + + lua_newtable(L); /* perms buff rootobj reftbl */ + lua_insert(L, REFTIDX); /* perms reftbl buff rootobj */ + if (info.generatePath) { + lua_newtable(L); /* perms reftbl buff rootobj path */ + lua_insert(L, PATHIDX); /* perms reftbl buff path rootobj */ + pushpath(&info, "root"); + } + + /* Populate perms table with Lua internals. */ + lua_pushvalue(L, PERMIDX); /* perms reftbl buff path? rootobj perms */ + populateperms(L, false); + lua_pop(L, 1); /* perms reftbl buff path? rootobj */ + + p_header(&info); + persist(&info); /* perms reftbl buff path? rootobj */ + + if (info.generatePath) { /* perms reftbl buff path rootobj */ + lua_remove(L, PATHIDX); /* perms reftbl buff rootobj */ + } /* perms reftbl buff rootobj */ + lua_remove(L, REFTIDX); /* perms buff rootobj */ +} + +static void +unchecked_unpersist(lua_State *L, lua_Reader reader, void *ud) {/* perms str? */ + Info info; + info.L = L; + info.level = 0; + info.refcount = 0; + info.maxComplexity = kMaxComplexity; + info.generatePath = kGeneratePath; + info.passIOToPersist = kPassIOToPersist; + eris_init(L, &info.u.upi.zio, reader, ud); + + eris_checkstack(L, 3); + + if (get_setting(L, (void*)&kSettingMaxComplexity)) { + /* perms buff rootobj value */ + info.maxComplexity = lua_tounsigned(L, -1); + lua_pop(L, 1); /* perms buff rootobj */ + } + if (get_setting(L, (void*)&kSettingGeneratePath)) { + /* perms buff? rootobj value */ + info.generatePath = lua_toboolean(L, -1); + lua_pop(L, 1); /* perms buff? rootobj */ + } + if (get_setting(L, (void*)&kSettingPassIOToPersist)) { /* perms str? value */ + info.passIOToPersist = lua_toboolean(L, -1); + lua_pop(L, 1); /* perms str? */ + } + + lua_newtable(L); /* perms str? reftbl */ + lua_insert(L, REFTIDX); /* perms reftbl str? */ + if (info.generatePath) { + /* Make sure the path is always at index 4, so that it's the same for + * persist and unpersist. */ + lua_pushnil(L); /* perms reftbl str? nil */ + lua_insert(L, BUFFIDX); /* perms reftbl nil str? */ + lua_newtable(L); /* perms reftbl nil str? path */ + lua_insert(L, PATHIDX); /* perms reftbl nil path str? */ + pushpath(&info, "root"); + } + + /* Populate perms table with Lua internals. */ + lua_pushvalue(L, PERMIDX); /* perms reftbl nil? path? str? perms */ + populateperms(L, true); + lua_pop(L, 1); /* perms reftbl nil? path? str? */ + + u_header(&info); + unpersist(&info); /* perms reftbl nil? path? str? rootobj */ + if (info.generatePath) { /* perms reftbl nil path str? rootobj */ + lua_remove(L, PATHIDX); /* perms reftbl nil str? rootobj */ + lua_remove(L, BUFFIDX); /* perms reftbl str? rootobj */ + } /* perms reftbl str? rootobj */ + lua_remove(L, REFTIDX); /* perms str? rootobj */ +} + +/** ======================================================================== */ + +static int +l_persist(lua_State *L) { /* perms? rootobj? ...? */ + Mbuffer buff; + + /* See if we have anything at all. */ + luaL_checkany(L, 1); + + /* If we only have one object we assume it is the root object and that there + * is no perms table, so we create an empty one for internal use. */ + if (lua_gettop(L) == 1) { /* rootobj */ + eris_checkstack(L, 1); + lua_newtable(L); /* rootobj perms */ + lua_insert(L, PERMIDX); /* perms rootobj */ + } + else { + luaL_checktype(L, 1, LUA_TTABLE); /* perms rootobj? ...? */ + luaL_checkany(L, 2); /* perms rootobj ...? */ + lua_settop(L, 2); /* perms rootobj */ + } + eris_checkstack(L, 1); + lua_pushnil(L); /* perms rootobj buff */ + lua_insert(L, 2); /* perms buff rootobj */ + + eris_initbuffer(L, &buff); + eris_bufflen(&buff) = 0; /* Not initialized by initbuffer... */ + + unchecked_persist(L, writer, &buff); /* perms buff rootobj */ + + /* Copy the buffer as the result string before removing it, to avoid the data + * being garbage collected. */ + lua_pushlstring(L, eris_buffer(&buff), eris_bufflen(&buff)); + /* perms buff rootobj str */ + + return 1; +} + +static int +l_unpersist(lua_State *L) { /* perms? str? ...? */ + RBuffer buff; + + /* See if we have anything at all. */ + luaL_checkany(L, 1); + + /* If we only have one object we assume it is the root object and that there + * is no perms table, so we create an empty one for internal use. */ + if (lua_gettop(L) == 1) { /* str? */ + eris_checkstack(L, 1); + lua_newtable(L); /* str? perms */ + lua_insert(L, PERMIDX); /* perms str? */ + } + else { + luaL_checktype(L, 1, LUA_TTABLE); /* perms str? ...? */ + } + eris_buffer(&buff) = luaL_checklstring(L, 2, &eris_bufflen(&buff)); + eris_sizebuffer(&buff) = eris_bufflen(&buff); /* perms str ...? */ + lua_settop(L, 2); /* perms str */ + + unchecked_unpersist(L, reader, &buff); /* perms str rootobj */ + + return 1; +} + +#define IS(s) strncmp(s, name, length < sizeof(s) ? length : sizeof(s)) == 0 + +static int +l_settings(lua_State *L) { /* name value? ...? */ + size_t length; + const char *name = luaL_checklstring(L, 1, &length); + if (lua_isnone(L, 2)) { /* name ...? */ + lua_settop(L, 1); /* name */ + /* Get the current setting value and return it. */ + if (IS(kSettingMetafield)) { + if (!get_setting(L, (void*)&kSettingMetafield)) { + lua_pushstring(L, kPersistKey); + } + } + else if (IS(kSettingPassIOToPersist)) { + if (!get_setting(L, (void*)&kSettingPassIOToPersist)) { + lua_pushboolean(L, kPassIOToPersist); + } + } + else if (IS(kSettingWriteDebugInfo)) { + if (!get_setting(L, (void*)&kSettingWriteDebugInfo)) { + lua_pushboolean(L, kWriteDebugInformation); + } + } + else if (IS(kSettingGeneratePath)) { + if (!get_setting(L, (void*)&kSettingGeneratePath)) { + lua_pushboolean(L, kGeneratePath); + } + } + else if (IS(kSettingMaxComplexity)) { + if (!get_setting(L, (void*)&kSettingMaxComplexity)) { + lua_pushunsigned(L, kMaxComplexity); + } + } + else { + return luaL_argerror(L, 1, "no such setting"); + } /* name value */ + return 1; + } + else { /* name value ...? */ + lua_settop(L, 2); /* name value */ + /* Set a new value for the setting. */ + if (IS(kSettingMetafield)) { + luaL_optstring(L, 2, NULL); + set_setting(L, (void*)&kSettingMetafield); + } + else if (IS(kSettingPassIOToPersist)) { + luaL_opt(L, checkboolean, 2, false); + set_setting(L, (void*)&kSettingPassIOToPersist); + } + else if (IS(kSettingWriteDebugInfo)) { + luaL_opt(L, checkboolean, 2, false); + set_setting(L, (void*)&kSettingWriteDebugInfo); + } + else if (IS(kSettingGeneratePath)) { + luaL_opt(L, checkboolean, 2, false); + set_setting(L, (void*)&kSettingGeneratePath); + } + else if (IS(kSettingMaxComplexity)) { + luaL_optunsigned(L, 2, 0); + set_setting(L, (void*)&kSettingMaxComplexity); + } + else { + return luaL_argerror(L, 1, "no such setting"); + } /* name */ + return 0; + } +} + +#undef IS + +/** ======================================================================== */ + +static luaL_Reg erislib[] = { + { "persist", l_persist }, + { "unpersist", l_unpersist }, + { "settings", l_settings }, + { NULL, NULL } +}; + +LUA_API int luaopen_eris(lua_State *L) { + luaL_newlib(L, erislib); + return 1; +} + +/* }======================================================================== */ + +/* +** {=========================================================================== +** Public API functions. +** ============================================================================ +*/ + +LUA_API void +eris_dump(lua_State *L, lua_Writer writer, void *ud) { /* perms? rootobj? */ + if (lua_gettop(L) > 2) { + luaL_error(L, "too many arguments"); + } + luaL_checktype(L, 1, LUA_TTABLE); /* perms rootobj? */ + luaL_checkany(L, 2); /* perms rootobj */ + lua_pushnil(L); /* perms rootobj nil */ + lua_insert(L, -2); /* perms nil rootobj */ + unchecked_persist(L, writer, ud); /* perms nil rootobj */ + lua_remove(L, -2); /* perms rootobj */ +} + +LUA_API void +eris_undump(lua_State *L, lua_Reader reader, void *ud) { /* perms? */ + if (lua_gettop(L) > 1) { + luaL_error(L, "too many arguments"); + } + luaL_checktype(L, 1, LUA_TTABLE); /* perms */ + unchecked_unpersist(L, reader, ud); /* perms rootobj */ +} + +/** ======================================================================== */ + +/* Lua internals that must never be serialized but are reachable from almost + * every object (every closure's _ENV upvalue is the globals table): the + * registry, the globals table and the main thread, keyed by fixed names. */ +static void +populateperms(lua_State *L, bool forUnpersist) { +#define ADD_PERM(key, push) \ + if (forUnpersist) { lua_pushstring(L, key); push; } \ + else { push; lua_pushstring(L, key); } \ + lua_rawset(L, -3) + ADD_PERM("__eris.registry", lua_pushvalue(L, LUA_REGISTRYINDEX)); + ADD_PERM("__eris.globals", lua_pushglobaltable(L)); + ADD_PERM("__eris.mainthread", lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_MAINTHREAD)); +#undef ADD_PERM +} + +LUA_API void +eris_persist(lua_State *L, int perms, int value) { /* ...? */ + perms = lua_absindex(L, perms); + value = lua_absindex(L, value); + eris_checkstack(L, 3); + lua_pushcfunction(L, l_persist); /* ... l_persist */ + lua_pushvalue(L, perms); /* ... l_persist perms */ + lua_pushvalue(L, value); /* ... l_persist perms rootobj */ + lua_call(L, 2, 1); /* ... str */ +} + +LUA_API void +eris_unpersist(lua_State *L, int perms, int value) { /* ... */ + perms = lua_absindex(L, perms); + value = lua_absindex(L, value); + eris_checkstack(L, 3); + lua_pushcfunction(L, l_unpersist); /* ... l_unpersist */ + lua_pushvalue(L, perms); /* ... l_unpersist perms */ + lua_pushvalue(L, value); /* ... l_unpersist perms str */ + lua_call(L, 2, 1); /* ... rootobj */ +} + +LUA_API void +eris_get_setting(lua_State *L, const char *name) { /* ... */ + eris_checkstack(L, 2); + lua_pushcfunction(L, l_settings); /* ... l_settings */ + lua_pushstring(L, name); /* ... l_settings name */ + lua_call(L, 1, 1); /* ... value */ +} + +LUA_API void +eris_set_setting(lua_State *L, const char *name, int value) { /* ... */ + value = lua_absindex(L, value); + eris_checkstack(L, 3); + lua_pushcfunction(L, l_settings); /* ... l_settings */ + lua_pushstring(L, name); /* ... l_settings name */ + lua_pushvalue(L, value); /* ... l_settings name value */ + lua_call(L, 2, 0); /* ... */ +} + +/* }======================================================================== */ + diff --git a/components/pico8/femto8/src/lua/eris.h b/components/pico8/femto8/src/lua/eris.h new file mode 100644 index 00000000..0779d0d3 --- /dev/null +++ b/components/pico8/femto8/src/lua/eris.h @@ -0,0 +1,153 @@ +/* +Eris - Heavy-duty persistence for Lua 5.2.4 - Based on Pluto +Copyright (c) 2013-2015 by Florian Nuecke. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +/* lua.h must be included before this file */ + +#ifndef ERIS_H +#define ERIS_H + +#define ERIS_VERSION_MAJOR "1" +#define ERIS_VERSION_MINOR "1" +#define ERIS_VERSION_NUM 101 +#define ERIS_VERSION_RELEASE "1" + +/* +** ================================================================== +** API +** ================================================================== +*/ + +/** + * This provides an interface to Eris' persist functionality for writing in + * an arbitrary way, using a writer. + * + * When called, the stack in 'L' must look like this: + * 1: perms:table + * 2: value:any + * + * 'writer' is the writer function used to store all data, 'ud' is passed to + * the writer function whenever it is called. + * + * [-0, +0, e] + */ +LUA_API void eris_dump(lua_State* L, lua_Writer writer, void* ud); + +/** + * This provides an interface to Eris' unpersist functionality for reading + * in an arbitrary way, using a reader. + * + * When called, the stack in 'L' must look like this: + * 1: perms:table + * + * 'reader' is the reader function used to read all data, 'ud' is passed to + * the reader function whenever it is called. + * + * The result of the operation will be pushed onto the stack. + * + * [-0, +1, e] + */ +LUA_API void eris_undump(lua_State* L, lua_Reader reader, void* ud); + +/** + * This is a stack-based alternative to eris_dump. + * + * It expects the perms table at the specified index 'perms' and the value to + * persist at the specified index 'value'. It will push the resulting string + * onto the stack on success. + * + * [-0, +1, e] + */ +LUA_API void eris_persist(lua_State* L, int perms, int value); + +/** + * This is a stack-based alternative to eris_undump. + * + * It expects the perms table at the specified index 'perms' and the string + * containing persisted data at the specified index 'value'. It will push the + * resulting value onto the stack on success. + * + * [-0, +1, e] + */ +LUA_API void eris_unpersist(lua_State* L, int perms, int value); + +/** + * Pushes the current value of a setting onto the stack. + * + * The name is the name of the setting to get the value for: + * - 'debug' whether to write debug information when persisting function + * prototypes (line numbers, local variable names, upvalue names). + * - 'maxrec' the maximum complexity of objects we support (the nesting level + * of tables, for example). This can be useful to avoid segmentation + * faults due to too deep recursion when working with user-provided + * data. + * - 'path' whether to generate a "path" used to indicate where in an object + * an error occurred. This adds considerable overhead and should + * only be used to debug errors as they appear. + * - 'spio' whether to pass IO objects along as light userdata to special + * persistence functions. When persisting this will pass along the + * lua_Writer and its void* in addition to the original object, when + * unpersisting it will pass along a ZIO*. + * - 'spkey' the name of the field in the metatable of tables and userdata + * used to control persistence (on/off or special persistence). + * + * If an unknown name is specified this will throw an error. + * + * [-0, +1, e] + */ +LUA_API void eris_get_setting(lua_State *L, const char *name); + +/** + * Changes the value of a setting to a value on the stack. + * + * For the available settings see eris_set_setting(). This will get the new + * value from the specified stack index 'value'. If the type does not match + * this will throw an error. Specify a nil value to reset the setting to its + * default value. + * + * [-0, +0, e] + */ +LUA_API void eris_set_setting(lua_State *L, const char *name, int value); + +/* +** ================================================================== +** Library installer +** ================================================================== +*/ + +/** + * This pushes a table with the two functions 'persist' and 'unpersist': + * persist([perms,] value) + * Where 'perms' is a table with "permanent" objects and 'value' is the + * value that should be persisted. Returns the string with persisted data. + * If only one value is given, the perms table is assumed to be empty. + * + * unpersist([perms,] value) + * Where 'perms' is a table with the inverse mapping as used when + * persisting the data via persist() and 'value' is the string with the + * persisted data returned by persist(). Returns the unpersisted value. + * If only one value is given, the perms table is assumed to be empty. + */ +LUA_API int luaopen_eris(lua_State* L); + +#endif + diff --git a/components/pico8/femto8/src/p8_audio.c b/components/pico8/femto8/src/p8_audio.c index 915939bb..7d9a2d9d 100644 --- a/components/pico8/femto8/src/p8_audio.c +++ b/components/pico8/femto8/src/p8_audio.c @@ -203,6 +203,30 @@ void audio_close() #endif } +#ifdef FEMTO8_ESPBOX +/* esp-box-emu save states: the playing channels and the music position */ +size_t audio_state_size(void) +{ + return sizeof(m_channels) + sizeof(m_music_state); +} + +void audio_state_save(void *dst) +{ + pthread_mutex_lock(&m_sound_queue_mutex); + memcpy(dst, m_channels, sizeof(m_channels)); + memcpy((uint8_t *)dst + sizeof(m_channels), &m_music_state, sizeof(m_music_state)); + pthread_mutex_unlock(&m_sound_queue_mutex); +} + +void audio_state_load(const void *src) +{ + pthread_mutex_lock(&m_sound_queue_mutex); + memcpy(m_channels, src, sizeof(m_channels)); + memcpy(&m_music_state, (const uint8_t *)src + sizeof(m_channels), sizeof(m_music_state)); + pthread_mutex_unlock(&m_sound_queue_mutex); +} +#endif + void audio_sound(int32_t index, int32_t channel, uint32_t start, uint32_t end) { soundcommand_t sound_command; diff --git a/components/pico8/femto8/src/p8_audio.h b/components/pico8/femto8/src/p8_audio.h index 6b1b3a3e..bd252b8f 100644 --- a/components/pico8/femto8/src/p8_audio.h +++ b/components/pico8/femto8/src/p8_audio.h @@ -21,6 +21,12 @@ void audio_init(); void audio_resume(); void audio_pause(); +#ifdef FEMTO8_ESPBOX +#include +size_t audio_state_size(void); +void audio_state_save(void *dst); +void audio_state_load(const void *src); +#endif void audio_close(); void audio_sound(int32_t index, int32_t channel, uint32_t start, uint32_t end); void audio_music(int32_t index, int32_t fade_ms, int32_t mask); diff --git a/components/pico8/femto8/src/p8_emu.c b/components/pico8/femto8/src/p8_emu.c index dae9fe1c..f13d41fa 100644 --- a/components/pico8/femto8/src/p8_emu.c +++ b/components/pico8/femto8/src/p8_emu.c @@ -887,6 +887,9 @@ static int p8_main_loop() time_debt += p8_elapsed_time() - elapsed; p8_flip(); +#ifdef FEMTO8_ESPBOX + p8_espbox_frame_boundary(); /* no cart code on the stack here */ +#endif if (updates_since_last_flip >= m_fps) { time_debt = 0; @@ -898,6 +901,9 @@ static int p8_main_loop() updates_since_last_flip = 0; } else { p8_post_flip(); +#ifdef FEMTO8_ESPBOX + p8_espbox_frame_boundary(); +#endif time_debt -= target_frame_time; } diff --git a/components/pico8/femto8/src/p8_lua.c b/components/pico8/femto8/src/p8_lua.c index 46660f1b..fdb80e78 100644 --- a/components/pico8/femto8/src/p8_lua.c +++ b/components/pico8/femto8/src/p8_lua.c @@ -81,6 +81,8 @@ void lua_register_functions(lua_State *L); #ifdef FEMTO8_ESPBOX #include "p8_lua_alloc.h" +#include "p8_state.h" +lua_State *p8_lua_state(void) { return L; } /* esp-box-emu: the interpreter's small objects come from pooled free lists * rather than the locked system heap (p8_lua_alloc.c) */ static int p8_lua_panic(lua_State *state) @@ -2613,6 +2615,9 @@ int lua_load_api() lua_pop(L, 1); } lua_setfield(L, LUA_REGISTRYINDEX, "__PICO8_SANDBOX"); +#ifdef FEMTO8_ESPBOX + p8_state_init(L); /* save states: the permanent objects, by name */ +#endif // Set debug hook to pump events every ~3000 instructions lua_sethook(L, lua_event_pump_hook, LUA_MASKCOUNT, 3000); diff --git a/components/pico8/include/pico8.hpp b/components/pico8/include/pico8.hpp index 714c2013..2150f875 100644 --- a/components/pico8/include/pico8.hpp +++ b/components/pico8/include/pico8.hpp @@ -20,7 +20,8 @@ void resume_pico8_tasks(); // failure); the cart then returns to the emulator menu bool pico8_quit_requested(); -// Save states are not supported; carts keep their own cartdata() files. +// Save states: PICO-8 RAM + the cart's Lua heap (serialized with Eris), +// taken at a frame boundary. Carts' own cartdata() files are separate. void load_pico8(std::string_view save_path, int save_slot); void save_pico8(std::string_view save_path, int save_slot); diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp index 17d28765..22ef38e7 100644 --- a/components/pico8/src/pico8.cpp +++ b/components/pico8/src/pico8.cpp @@ -18,6 +18,7 @@ #include "statistics.hpp" #include "platform/p8_espbox.h" #include "platform/p8_lua_alloc.h" +#include "platform/p8_state.h" #define PICO8_PROF_MAX_REPORT 8 extern "C" { @@ -72,6 +73,12 @@ namespace { std::atomic s_quit{false}; // the cart is over (or never started) std::atomic s_stopRequested{false}; // the emulator wants the cart gone std::atomic s_cartTaskDone{false}; + // a save/load requested from the menu, done by the cart task between frames + enum class StateOp { None, Save, Load }; + std::atomic s_stateOp{StateOp::None}; + std::atomic s_stateOpDone{false}; + std::atomic s_stateOpResult{0}; + std::string s_statePath; uint8_t* s_dataSnapshot = nullptr; TaskHandle_t s_cartTask = nullptr; @@ -236,8 +243,9 @@ extern "C" uint16_t p8_espbox_buttons(void) { } extern "C" void p8_espbox_pump(void) { - // the emulator menu holds the cart here (the Lua VM is at a safe point) - while (s_paused && !s_stopRequested) { + // the emulator menu holds the cart here (the Lua VM is at a safe point); + // a pending save/load lets it run on to the end of the frame first + while (s_paused && !s_stopRequested && s_stateOp == StateOp::None) { vTaskDelay(pdMS_TO_TICKS(10)); } if (s_stopRequested) { @@ -245,6 +253,35 @@ extern "C" void p8_espbox_pump(void) { } } +extern "C" void p8_espbox_frame_boundary(void) { + const StateOp op = s_stateOp; + if (op == StateOp::None) { + return; + } + s_stateOpResult = (op == StateOp::Save) ? p8_state_save(s_statePath.c_str()) : p8_state_load(s_statePath.c_str()); + s_stateOp = StateOp::None; + s_stateOpDone = true; +} + +// Ask the cart task to save/load at its next frame boundary and wait for it. +// Called from the emulator task while the menu has the cart paused. +static bool runStateOp(StateOp op, std::string_view path) { + if (!s_initialized || s_quit || path.empty()) { + return false; + } + s_statePath = std::string(path); + s_stateOpDone = false; + s_stateOp = op; + // a frame plus the file I/O; a cart stuck in its own pause menu never + // reaches the boundary, so give up eventually + if (!waitFor(s_stateOpDone, 15000)) { + fmt::print("[PICO8] {} state: the cart did not reach a frame boundary\n", op == StateOp::Save ? "save" : "load"); + s_stateOp = StateOp::None; + return false; + } + return s_stateOpResult == 0; +} + // ---- emulator API ----------------------------------------------------------- void init_pico8(const std::string& rom_filename, uint8_t* romdata, size_t rom_data_size) { @@ -414,12 +451,18 @@ void resume_pico8_tasks() { s_paused = false; } -void load_pico8(std::string_view, int) { - fmt::print("[PICO8] save states are not supported\n"); +void load_pico8(std::string_view save_path, int save_slot) { + if (save_slot < 0) { + return; + } + runStateOp(StateOp::Load, save_path); } -void save_pico8(std::string_view, int) { - fmt::print("[PICO8] save states are not supported\n"); +void save_pico8(std::string_view save_path, int save_slot) { + if (save_slot < 0) { + return; + } + runStateOp(StateOp::Save, save_path); } std::span get_pico8_video_buffer() { diff --git a/components/pico8/src/platform/p8_espbox.h b/components/pico8/src/platform/p8_espbox.h index 3b7b3f30..ceb0aee0 100644 --- a/components/pico8/src/platform/p8_espbox.h +++ b/components/pico8/src/platform/p8_espbox.h @@ -20,6 +20,10 @@ uint16_t p8_espbox_buttons(void); * it to stop. */ void p8_espbox_pump(void); +/* p8_main_loop(), between frames: the Lua stack holds no cart code, so this + * is where a save/load state requested from the emulator menu is done. */ +void p8_espbox_frame_boundary(void); + #ifdef __cplusplus } #endif diff --git a/components/pico8/src/platform/p8_state.c b/components/pico8/src/platform/p8_state.c new file mode 100644 index 00000000..70e5e4c8 --- /dev/null +++ b/components/pico8/src/platform/p8_state.c @@ -0,0 +1,238 @@ +/* Save states for femto8 on esp-box-emu. + * + * A state is PICO-8's RAM, the overlay, the frame counters, the audio + * channels and the cart's Lua heap. The heap is serialized with Eris (Lua + * 5.2's heavy-duty persistence, the approach fake-08 uses): everything the + * cart created or replaced in _G is persisted as a graph; the API functions + * and library tables that existed before the cart ran are "permanent" and + * referenced by name (p8_state_init builds that table right after the API is + * registered). Closures, upvalues, metatables and coroutines are persisted + * with the graph. + * + * Both operations must run while no cart code is executing -- between + * frames, from p8_espbox_frame_boundary() -- never from the Lua hook. + */ +#include "p8_state.h" + +#include +#include +#include +#include "esp_heap_caps.h" + +#include "lua.h" +#include "lauxlib.h" +#include "eris.h" +#include "p8_emu.h" +#include "p8_audio.h" + +#define STATE_MAGIC 0x31533850u /* "P8S1" */ +#define PERMS_KEY "__PICO8_PERMS" +#define UNPERMS_KEY "__PICO8_UNPERMS" +#define SANDBOX_KEY "__PICO8_SANDBOX" + +typedef struct { + uint32_t magic; + uint32_t frames; + uint32_t fps; + uint32_t audio_size; + uint32_t lua_size; +} state_header_t; + +lua_State *p8_lua_state(void); /* p8_lua.c */ + +/* perms[object] = "name" / "table.name", unperms the reverse; the sandbox + * (name -> original value) already exists for the _ENV fallback */ +void p8_state_init(lua_State *L) +{ + int top = lua_gettop(L); + lua_newtable(L); /* perms */ + int perms = lua_gettop(L); + lua_newtable(L); /* unperms */ + int unperms = lua_gettop(L); + lua_pushglobaltable(L); + int g = lua_gettop(L); + lua_pushnil(L); + while (lua_next(L, g) != 0) { /* key -2, value -1 */ + if (lua_type(L, -2) == LUA_TSTRING) { + int vt = lua_type(L, -1); + if (vt == LUA_TFUNCTION || vt == LUA_TTABLE || vt == LUA_TUSERDATA) { + /* the global itself */ + lua_pushvalue(L, -1); lua_pushvalue(L, -3); lua_rawset(L, perms); + lua_pushvalue(L, -2); lua_pushvalue(L, -2); lua_rawset(L, unperms); + } + if (vt == LUA_TTABLE) { + /* one level down: library functions a cart may have captured + * (local sub = string.sub) */ + const char *tname = lua_tostring(L, -2); + lua_pushnil(L); + while (lua_next(L, -2) != 0) { + if (lua_type(L, -2) == LUA_TSTRING && lua_type(L, -1) == LUA_TFUNCTION) { + lua_pushfstring(L, "%s.%s", tname, lua_tostring(L, -2)); + /* perms[func] = name */ + lua_pushvalue(L, -2); lua_pushvalue(L, -2); lua_rawset(L, perms); + /* unperms[name] = func */ + lua_pushvalue(L, -1); lua_pushvalue(L, -3); lua_rawset(L, unperms); + lua_pop(L, 1); + } + lua_pop(L, 1); + } + } + } + lua_pop(L, 1); + } + lua_pop(L, 1); /* globals */ + lua_setfield(L, LUA_REGISTRYINDEX, UNPERMS_KEY); + lua_setfield(L, LUA_REGISTRYINDEX, PERMS_KEY); + lua_settop(L, top); +} + +/* --- Lua side, run through pcall so an Eris error is reported, not fatal --- */ + +static int do_persist(lua_State *L) +{ + lua_getfield(L, LUA_REGISTRYINDEX, PERMS_KEY); + int perms = lua_gettop(L); + lua_newtable(L); /* what the cart created or replaced */ + int changed = lua_gettop(L); + lua_getfield(L, LUA_REGISTRYINDEX, SANDBOX_KEY); + int sandbox = lua_gettop(L); + lua_pushglobaltable(L); + int g = lua_gettop(L); + lua_pushnil(L); + while (lua_next(L, g) != 0) { + lua_pushvalue(L, -2); + lua_rawget(L, sandbox); + int same = lua_rawequal(L, -1, -2); + lua_pop(L, 1); + if (!same) { + lua_pushvalue(L, -2); lua_pushvalue(L, -2); lua_rawset(L, changed); + } + lua_pop(L, 1); + } + lua_pop(L, 2); /* globals, sandbox */ + eris_persist(L, perms, changed); /* pushes the blob */ + return 1; +} + +static int do_unpersist(lua_State *L) +{ + /* arg 1: the blob */ + lua_getfield(L, LUA_REGISTRYINDEX, UNPERMS_KEY); + int unperms = lua_gettop(L); + eris_unpersist(L, unperms, 1); /* pushes the table of globals */ + int restored = lua_gettop(L); + lua_getfield(L, LUA_REGISTRYINDEX, SANDBOX_KEY); + int sandbox = lua_gettop(L); + lua_pushglobaltable(L); + int g = lua_gettop(L); + /* drop every global the cart created since (not in the original set and + * not in the state): collect the keys first, then clear them */ + lua_newtable(L); + int stale = lua_gettop(L); + int n = 0; + lua_pushnil(L); + while (lua_next(L, g) != 0) { + lua_pushvalue(L, -2); lua_rawget(L, sandbox); + int original = !lua_isnil(L, -1); + lua_pop(L, 1); + lua_pushvalue(L, -2); lua_rawget(L, restored); + int in_state = !lua_isnil(L, -1); + lua_pop(L, 1); + if (!original && !in_state) { + lua_pushvalue(L, -2); lua_rawseti(L, stale, ++n); + } + lua_pop(L, 1); + } + for (int i = 1; i <= n; i++) { + lua_rawgeti(L, stale, i); lua_pushnil(L); lua_rawset(L, g); + } + /* originals the cart had replaced go back to the saved values; the + * state table carries both the replaced originals and the new globals */ + lua_pushnil(L); + while (lua_next(L, restored) != 0) { + lua_pushvalue(L, -2); lua_pushvalue(L, -2); lua_rawset(L, g); + lua_pop(L, 1); + } + return 0; +} + +int p8_state_save(const char *path) +{ + lua_State *L = p8_lua_state(); + if (!L || !m_memory) + return -1; + int top = lua_gettop(L); + lua_pushcfunction(L, do_persist); + if (lua_pcall(L, 0, 1, 0) != 0) { + printf("[PICO8] save state: %s\n", lua_tostring(L, -1)); + lua_settop(L, top); + return -1; + } + size_t blob_len = 0; + const char *blob = lua_tolstring(L, -1, &blob_len); + + int ret = -1; + FILE *f = fopen(path, "wb"); + if (f) { + state_header_t h = { STATE_MAGIC, m_frames, m_fps, (uint32_t)audio_state_size(), (uint32_t)blob_len }; + void *audio = malloc(h.audio_size); + if (audio) audio_state_save(audio); + ret = (fwrite(&h, sizeof h, 1, f) == 1 && + fwrite(m_memory, 1, MEMORY_SIZE, f) == MEMORY_SIZE && + fwrite(m_overlay_memory, 1, MEMORY_SCREEN_SIZE, f) == MEMORY_SCREEN_SIZE && + audio && fwrite(audio, 1, h.audio_size, f) == h.audio_size && + fwrite(blob, 1, blob_len, f) == blob_len) ? 0 : -1; + free(audio); + fclose(f); + } + printf("[PICO8] save state '%s': %s (lua %u B)\n", path, ret == 0 ? "ok" : "FAILED", (unsigned)blob_len); + lua_settop(L, top); + return ret; +} + +int p8_state_load(const char *path) +{ + lua_State *L = p8_lua_state(); + if (!L || !m_memory) + return -1; + FILE *f = fopen(path, "rb"); + if (!f) { + printf("[PICO8] load state: cannot open '%s'\n", path); + return -1; + } + state_header_t h; + int ret = -1; + char *blob = NULL; + void *audio = NULL; + uint8_t *mem = heap_caps_malloc(MEMORY_SIZE + MEMORY_SCREEN_SIZE, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (fread(&h, sizeof h, 1, f) == 1 && h.magic == STATE_MAGIC && h.audio_size == audio_state_size() && mem && + fread(mem, 1, MEMORY_SIZE + MEMORY_SCREEN_SIZE, f) == MEMORY_SIZE + MEMORY_SCREEN_SIZE && + (audio = malloc(h.audio_size)) && fread(audio, 1, h.audio_size, f) == h.audio_size && + (blob = heap_caps_malloc(h.lua_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)) && + fread(blob, 1, h.lua_size, f) == h.lua_size) { + /* the Lua heap first: if that fails nothing else has changed */ + int top = lua_gettop(L); + lua_pushcfunction(L, do_unpersist); + lua_pushlstring(L, blob, h.lua_size); + if (lua_pcall(L, 1, 0, 0) != 0) { + printf("[PICO8] load state: %s\n", lua_tostring(L, -1)); + } else { + memcpy(m_memory, mem, MEMORY_SIZE); + memcpy(m_overlay_memory, mem + MEMORY_SIZE, MEMORY_SCREEN_SIZE); + audio_state_load(audio); + m_frames = h.frames; + m_fps = h.fps; + lua_gc(L, LUA_GCCOLLECT, 0); /* the previous heap is garbage now */ + ret = 0; + } + lua_settop(L, top); + } else { + printf("[PICO8] load state: bad file '%s'\n", path); + } + free(blob); + free(audio); + free(mem); + fclose(f); + printf("[PICO8] load state '%s': %s\n", path, ret == 0 ? "ok" : "FAILED"); + return ret; +} diff --git a/components/pico8/src/platform/p8_state.h b/components/pico8/src/platform/p8_state.h new file mode 100644 index 00000000..57e36f9a --- /dev/null +++ b/components/pico8/src/platform/p8_state.h @@ -0,0 +1,18 @@ +#pragma once +/* esp-box-emu: save states for femto8 (see p8_state.c) */ +#include "lua.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* after the API is registered and before the cart runs: records the + * permanent objects (API functions, library tables) by name */ +void p8_state_init(lua_State *L); +/* only between frames (no cart code on the Lua stack); 0 on success */ +int p8_state_save(const char *path); +int p8_state_load(const char *path); + +#ifdef __cplusplus +} +#endif From af52db7cd3a9d0c913c99556701759bd438e0be9 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Wed, 7 Oct 2026 09:02:34 -0500 Subject: [PATCH 13/19] fix(pico8): no gamepad input reaches the cart while the emulator menu is open A save/load runs the cart for one frame with the menu up, and the button that closed the menu was still held on the first frame after resume. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/src/pico8.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp index 22ef38e7..1b0a537e 100644 --- a/components/pico8/src/pico8.cpp +++ b/components/pico8/src/pico8.cpp @@ -72,6 +72,9 @@ namespace { std::atomic s_paused{false}; std::atomic s_quit{false}; // the cart is over (or never started) std::atomic s_stopRequested{false}; // the emulator wants the cart gone + // after the menu closes, the pad is ignored until every button has been + // released once: the press that closed the menu must not reach the cart + std::atomic s_inputGate{false}; std::atomic s_cartTaskDone{false}; // a save/load requested from the menu, done by the cart task between frames enum class StateOp { None, Save, Load }; @@ -229,8 +232,19 @@ extern "C" void p8_espbox_frame_end(void) { } extern "C" uint16_t p8_espbox_buttons(void) { - // PICO-8: left right up down O X; pause opens PICO-8's own menu + // the emulator menu owns the pad while the cart is paused (a save/load + // runs the cart for one frame in that state) + if (s_paused) { + return 0; + } const GamepadState state = BoxEmu::get().gamepad_state(); + if (s_inputGate) { + if (state.buttons != 0) { + return 0; + } + s_inputGate = false; + } + // PICO-8: left right up down O X; pause opens PICO-8's own menu uint16_t mask = 0; if (state.left) mask |= BUTTON_MASK_LEFT; if (state.right) mask |= BUTTON_MASK_RIGHT; @@ -448,6 +462,7 @@ void resume_pico8_tasks() { box.push_frame(s_lastFrame); } audio_resume(); + s_inputGate = true; s_paused = false; } From 2cd8e60d644d065d290ac89fb9d0ca9def6c7f04 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Wed, 7 Oct 2026 09:21:15 -0500 Subject: [PATCH 14/19] docs(pico8): save states Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- README.md | 7 ++++--- components/pico8/VENDOR.md | 17 +++++++++++++++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e7c207e8..48da6133 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ that removes the frame-rate cap for maximum speed. | MSX 1 / 2 | [fmsx](https://fms.komkon.org/fMSX/) | β€” | D-Pad / A / B / Start / Select | | Doom | [prboom](https://prboom.sourceforge.net/) | β€” | Full speed with audio **and haptic feedback** | | Dark Forces | [The Force Engine](https://theforceengine.github.io/) (via [BSzili's Amiga port](https://github.com/BSzili/TheForceEngine/tree/amiga)) | β€” | Software renderer, iMuse sound effects and OPL3 music; see [Dark Forces setup](#dark-forces-setup) | -| PICO-8 | [femto8](https://github.com/benbaker76/femto8) | β€” | `.p8` and `.p8.png` carts; D-Pad, A/Y = O, B/X = X, START = PICO-8 pause menu; cartdata saves to `pico8/cdata/`; see [PICO-8 setup](#pico-8-setup) | +| PICO-8 | [femto8](https://github.com/benbaker76/femto8) | β€” | `.p8` and `.p8.png` carts; D-Pad, A/Y = O, B/X = X, START = PICO-8 pause menu; save states; cartdata saves to `pico8/cdata/`; see [PICO-8 setup](#pico-8-setup) | > 🧬 **Full-speed Genesis on the S3.** The Genesis core ships with a custom > **dual-core** modification of gwenesis that spreads the workload across both of @@ -271,8 +271,9 @@ same folder as `id.p8.png` / `id.p8`. What to expect: the Lua interpreter runs at roughly 1.3M instructions per second on the S3 (its heap lives in PSRAM), enough for carts of Celeste's weight at full speed, but CPU-heavy carts close to PICO-8's limit run at a -few frames per second. Save states are not available (carts' own -`cartdata()` saves are); there is no mouse or keyboard. +few frames per second. Save states work (the cart's Lua heap and PICO-8 +RAM are snapshotted between frames); carts' own `cartdata()` saves are kept +separately; there is no mouse or keyboard. ### metadata.csv format diff --git a/components/pico8/VENDOR.md b/components/pico8/VENDOR.md index 46ed1410..abe5b6c6 100644 --- a/components/pico8/VENDOR.md +++ b/components/pico8/VENDOR.md @@ -58,5 +58,18 @@ Measured on the BOX-3: the interpreter executes ~1.3M Lua instructions/s with its heap in PSRAM (GC ~1%, the drawing API ~5-15% of a frame), which runs Celeste at its full 30 fps but leaves CPU-heavy carts near PICO-8's limit (e.g. Cattle Crisis, Mossmoss) at a few fps. Known: Pico Ball shows a -blank screen in upstream femto8 as well; no save states (the Lua state cannot -be snapshotted) -- carts' own `cartdata()` saves work; no mouse/keyboard. +blank screen in upstream femto8 as well; no mouse/keyboard. + +## Save states + +`src/platform/p8_state.c`: PICO-8 RAM, the overlay, the frame counters, the +audio channels and the cart's Lua heap. The heap is serialized with **Eris** +(`femto8/src/lua/eris.c`, MIT, Florian Nuecke; the Lua 5.2.4 version as +carried in fake-08's z8lua, with the fixed-point number I/O and the +`populateperms` helper for this Lua). Everything the cart created or +replaced in `_G` is persisted as a graph; the API functions and library +tables recorded before the cart ran (`p8_state_init`) are permanents +referenced by name, as are the registry, `_G` and the main thread. The +menu's request is carried out by the cart task at its next frame boundary +(`p8_espbox_frame_boundary()` in `p8_main_loop`), where no cart code is on +the Lua stack; the cart's own `cartdata()` file is untouched. From af4745a74d515a1054dfd9d3ad734b875034e2ff Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Fri, 9 Oct 2026 09:03:11 -0500 Subject: [PATCH 15/19] fix(pico8): three present buffers; well-defined fix32 rotates (review) The video task keeps the frame pointer it dequeued for the whole LCD write and nothing signals completion, so with two buffers the cart could render into one still being scanned out; three buffers put the reuse two full frames out. fix32_rotl/rotr shifted a signed value, and by 32 for a rotate count of 0. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/femto8/src/lua/fix32.h | 8 ++++++-- components/pico8/src/pico8.cpp | 21 +++++++++++++++------ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/components/pico8/femto8/src/lua/fix32.h b/components/pico8/femto8/src/lua/fix32.h index 5c98a45d..f58012e1 100644 --- a/components/pico8/femto8/src/lua/fix32.h +++ b/components/pico8/femto8/src/lua/fix32.h @@ -108,13 +108,17 @@ static inline fix32_t fix32_lshr(fix32_t x, int y) { } static inline fix32_t fix32_rotl(fix32_t x, int y) { + /* on the unsigned pattern, and with the complementary count masked so a + * rotate by 0 does not shift by 32 (undefined) */ + uint32_t u = (uint32_t)x; y &= 0x1f; - return (x << y) | (fix32_t)((uint32_t)x >> (32 - y)); + return (fix32_t)((u << y) | (u >> ((32 - y) & 0x1f))); } static inline fix32_t fix32_rotr(fix32_t x, int y) { + uint32_t u = (uint32_t)x; y &= 0x1f; - return (fix32_t)((uint32_t)x >> y) | (x << (32 - y)); + return (fix32_t)((u >> y) | (u << ((32 - y) & 0x1f))); } /* Math functions */ diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp index 1b0a537e..f617eb7a 100644 --- a/components/pico8/src/pico8.cpp +++ b/components/pico8/src/pico8.cpp @@ -95,7 +95,13 @@ namespace { int16_t* s_audioStereo = nullptr; UBaseType_t s_emuTaskPrio = 1; - uint8_t* s_frames[2] = {nullptr, nullptr}; // 128x128 indices, in frame_buffer0 + // 128x128 index frames in frame_buffer0, rotated per frame. The video task + // keeps the pointer it dequeued for the whole LCD write (there is no + // completion signal back), so the cart must not render into that buffer + // again until the write is over: with three buffers the same buffer is + // reused two full frames later, well beyond one LCD write even at 60fps. + constexpr int NUM_FRAMES = 3; + uint8_t* s_frames[NUM_FRAMES] = {nullptr, nullptr, nullptr}; int s_frameIndex = 0; const uint8_t* s_lastFrame = nullptr; unsigned s_framesPresented = 0; @@ -223,7 +229,7 @@ extern "C" uint8_t* p8_espbox_frame_begin(void) { extern "C" void p8_espbox_frame_end(void) { const uint8_t* frame = s_frames[s_frameIndex]; - s_frameIndex ^= 1; + s_frameIndex = (s_frameIndex + 1) % NUM_FRAMES; s_lastFrame = frame; s_framesPresented++; if (!s_paused) { @@ -319,9 +325,10 @@ void init_pico8(const std::string& rom_filename, uint8_t* romdata, size_t rom_da auto& box = BoxEmu::get(); // two index frames in frame_buffer0 (it is far bigger than 2 x 16KB) - s_frames[0] = box.frame_buffer0(); - s_frames[1] = box.frame_buffer0() + FRAME_BYTES; - memset(s_frames[0], 0, 2 * FRAME_BYTES); + for (int i = 0; i < NUM_FRAMES; i++) { + s_frames[i] = box.frame_buffer0() + i * FRAME_BYTES; + } + memset(s_frames[0], 0, NUM_FRAMES * FRAME_BYTES); box.native_size(P8_W, P8_H); box.palette(m_colors, 32); @@ -526,7 +533,9 @@ void deinit_pico8() { heap_caps_free(s_audioMono); s_audioMono = nullptr; heap_caps_free(s_audioStereo); s_audioStereo = nullptr; s_lastFrame = nullptr; - s_frames[0] = s_frames[1] = nullptr; + for (int i = 0; i < NUM_FRAMES; i++) { + s_frames[i] = nullptr; + } // femto8 is gone: its statics can be put back for the next launch resetStatics(); From 2cb7f7da637a00923b55eacbf19126f16ec538ce Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Fri, 9 Oct 2026 09:13:09 -0500 Subject: [PATCH 16/19] fix(pico8): synchronize the audio task with cart shutdown (review) The audio task could pass its s_audioReady check and be preempted before render_sounds(); clearing the flag and sleeping did not cover that. It now re-checks the flag and renders under a mutex, and the cart task takes that mutex once after clearing the flag, before p8_shutdown() frees femto8's memory. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/src/pico8.cpp | 35 +++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp index f617eb7a..7061a189 100644 --- a/components/pico8/src/pico8.cpp +++ b/components/pico8/src/pico8.cpp @@ -37,6 +37,7 @@ extern uint32_t pico8_prof_gc_cycles, pico8_prof_gc_steps, pico8_prof_hooks; #include #include #include +#include #include #include @@ -90,6 +91,10 @@ namespace { TaskHandle_t s_audioTask = nullptr; std::atomic s_audioRun{false}; std::atomic s_audioReady{false}; // femto8's memory exists (between p8_init and p8_shutdown) + // held by the audio task around each render (which re-checks s_audioReady + // inside it); the cart task takes it once after clearing the flag, so no + // render is in flight when p8_shutdown() frees femto8's memory + SemaphoreHandle_t s_audioMutex = nullptr; std::atomic s_audioTaskDone{false}; int16_t* s_audioMono = nullptr; int16_t* s_audioStereo = nullptr; @@ -165,9 +170,13 @@ namespace { } } } - // the audio task must not touch femto8's memory once it is freed + // the audio task must not touch femto8's memory once it is freed: clear + // the flag, then wait out any render already past its check s_audioReady = false; - vTaskDelay(pdMS_TO_TICKS(20)); + if (s_audioMutex) { + xSemaphoreTake(s_audioMutex, portMAX_DELAY); + xSemaphoreGive(s_audioMutex); + } p8_shutdown(); s_quit = true; s_cartTaskDone = true; @@ -186,8 +195,17 @@ namespace { continue; } if (queued >= CHUNK_BYTES) { - // what femto8's SDL callback does, fed by hand - render_sounds(s_audioMono, AUDIO_CHUNK); + // what femto8's SDL callback does, fed by hand; the flag is checked + // again under the mutex the shutdown path synchronizes on + xSemaphoreTake(s_audioMutex, portMAX_DELAY); + const bool ready = s_audioReady; + if (ready) { + render_sounds(s_audioMono, AUDIO_CHUNK); + } + xSemaphoreGive(s_audioMutex); + if (!ready) { + continue; + } for (int i = 0; i < AUDIO_CHUNK; i++) { s_audioStereo[2 * i] = s_audioMono[i]; s_audioStereo[2 * i + 1] = s_audioMono[i]; @@ -332,11 +350,14 @@ void init_pico8(const std::string& rom_filename, uint8_t* romdata, size_t rom_da box.native_size(P8_W, P8_H); box.palette(m_colors, 32); + if (!s_audioMutex) { + s_audioMutex = xSemaphoreCreateMutex(); + } s_audioMono = (int16_t*)heap_caps_malloc(AUDIO_CHUNK * sizeof(int16_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); s_audioStereo = (int16_t*)heap_caps_malloc(AUDIO_CHUNK * 2 * sizeof(int16_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); s_cartStack = (StackType_t*)heap_caps_malloc(CART_TASK_STACK, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); s_cartTcb = (StaticTask_t*)heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); - if (!s_audioMono || !s_audioStereo || !s_cartStack || !s_cartTcb) { + if (!s_audioMono || !s_audioStereo || !s_cartStack || !s_cartTcb || !s_audioMutex) { fmt::print("[PICO8] ERROR: out of internal memory\n"); heap_caps_free(s_audioMono); s_audioMono = nullptr; heap_caps_free(s_audioStereo); s_audioStereo = nullptr; @@ -532,6 +553,10 @@ void deinit_pico8() { heap_caps_free(s_cartTcb); s_cartTcb = nullptr; heap_caps_free(s_audioMono); s_audioMono = nullptr; heap_caps_free(s_audioStereo); s_audioStereo = nullptr; + if (s_audioMutex) { + vSemaphoreDelete(s_audioMutex); + s_audioMutex = nullptr; + } s_lastFrame = nullptr; for (int i = 0; i < NUM_FRAMES; i++) { s_frames[i] = nullptr; From 6ce44994e8b63a2af0304ec22cd6aa58253e7c14 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Fri, 9 Oct 2026 09:26:03 -0500 Subject: [PATCH 17/19] fix(pico8): bounds-checked cart decompression; unsigned fix32 shifts (review) Both .p8.png code decompressors took the back-reference offset and length straight from the cart stream: the legacy one memcpy'd overlapping ranges, neither checked that the source lies inside the data produced so far or that the copy fits the output. A malformed cart now fails to load instead of reading before the buffer or writing past it. fix32's from_int / shl / abs shift the unsigned bit pattern (PICO-8 numbers wrap). Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- .../pico8/femto8/src/lexaloffle/p8_compress.c | 13 +++++++++++-- .../femto8/src/lexaloffle/pxa_compress_snippets.c | 6 ++++++ components/pico8/femto8/src/lua/fix32.h | 6 +++--- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/components/pico8/femto8/src/lexaloffle/p8_compress.c b/components/pico8/femto8/src/lexaloffle/p8_compress.c index abaf599e..f54dd2f3 100644 --- a/components/pico8/femto8/src/lexaloffle/p8_compress.c +++ b/components/pico8/femto8/src/lexaloffle/p8_compress.c @@ -111,8 +111,17 @@ int decompress_mini(uint8 *in_p, uint8 *out_p, int max_len) block_offset += val % 16; block_length = (val / 16) + 2; - memcpy(out, out - block_offset, block_length); - out += block_length; + /* the source must lie inside what has been produced so far and + * the copy inside the declared length; a shorter offset than the + * length is a repeating pattern, so expand byte by byte */ + if (block_offset <= 0 || block_offset > out - out_p || + block_length > (out_p + len) - out) + return 1; // corrupt data + while (block_length-- > 0) + { + *out = *(out - block_offset); + out++; + } } } diff --git a/components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c b/components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c index 4ccafdf1..45b126f0 100644 --- a/components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c +++ b/components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c @@ -213,6 +213,12 @@ int pxa_decompress(uint8 *in_p, uint8 *out_p, int max_len) { int block_len = getchain(BLOCK_LEN_CHAIN_BITS, 100000) + PXA_MIN_BLOCK_LEN; + // the source must be inside what has been produced, and the + // block must fit what is left of the output + if (block_offset > dest_pos || + block_len > raw_len - dest_pos || block_len > max_len - dest_pos) + return 0; // corrupt data + // copy // don't just memcpy because might be copying self for repeating pattern while (block_len > 0){ out_p[dest_pos] = out_p[dest_pos - block_offset]; diff --git a/components/pico8/femto8/src/lua/fix32.h b/components/pico8/femto8/src/lua/fix32.h index f58012e1..3acd4161 100644 --- a/components/pico8/femto8/src/lua/fix32.h +++ b/components/pico8/femto8/src/lua/fix32.h @@ -22,7 +22,7 @@ typedef int32_t fix32_t; #define FIX32_MIN ((fix32_t)0x80000001) /* not 0x80000000, per PICO-8 */ /* Construction */ -static inline fix32_t fix32_from_int(int x) { return (fix32_t)x << 16; } +static inline fix32_t fix32_from_int(int x) { return (fix32_t)((uint32_t)x << 16); } static inline fix32_t fix32_from_double(double d) { return (fix32_t)(int64_t)(d * 65536.0); } static inline fix32_t fix32_from_bits(int32_t b) { return b; } @@ -91,7 +91,7 @@ static inline fix32_t fix32_lshr(fix32_t x, int y); static inline fix32_t fix32_shl(fix32_t x, int y) { /* Negative y = lshr instead */ if (y < 0) return fix32_lshr(x, -y); - return y >= 32 ? 0 : x << y; + return y >= 32 ? 0 : (fix32_t)((uint32_t)x << y); } static inline fix32_t fix32_shr(fix32_t x, int y) { @@ -126,7 +126,7 @@ static inline fix32_t fix32_rotr(fix32_t x, int y) { /* PICO-8 0.2.3: abs(0x8000) should be 0x7fff.ffff */ static inline fix32_t fix32_abs(fix32_t a) { if (a >= 0) return a; - if ((a << 1) == 0) return ~a; /* 0x80000000 -> 0x7FFFFFFF */ + if ((uint32_t)a == 0x80000000u) return ~a; /* 0x80000000 -> 0x7FFFFFFF */ return -a; } From 23af3a2c2cf709fd648e8afd671253e2ee1038b2 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Fri, 9 Oct 2026 09:42:04 -0500 Subject: [PATCH 18/19] fix(pico8): input-bounded cart decompression; atomic frame publication (review) Both .p8.png code decompressors read the cart stream with no end check, so a cart declaring more output than its payload encodes read on past the decoded image. They now take the code section's length, every read past it fails the decode, and the legacy raw-text path is bounded as well. The last-frame pointer and the frame counter are written by the cart task and read by the emulator task; they are atomics now. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- .../pico8/femto8/src/lexaloffle/p8_compress.c | 8 +++-- .../pico8/femto8/src/lexaloffle/pico8.h | 6 ++-- .../src/lexaloffle/pxa_compress_snippets.c | 29 +++++++++++++++---- components/pico8/femto8/src/p8_parser.c | 4 ++- components/pico8/src/pico8.cpp | 15 ++++++---- 5 files changed, 45 insertions(+), 17 deletions(-) diff --git a/components/pico8/femto8/src/lexaloffle/p8_compress.c b/components/pico8/femto8/src/lexaloffle/p8_compress.c index f54dd2f3..73bfe7c9 100644 --- a/components/pico8/femto8/src/lexaloffle/p8_compress.c +++ b/components/pico8/femto8/src/lexaloffle/p8_compress.c @@ -52,13 +52,17 @@ typedef unsigned char uint8; char *literal = "^\n 0123456789abcdefghijklmnopqrstuvwxyz!#%(){}[]<>+=/*:;.,~_"; int literal_index[256]; // map literals to 0..LITERALS-1. 0 is reserved (not listed in literals string) -#define READ_VAL(val) {val = *in; in++;} -int decompress_mini(uint8 *in_p, uint8 *out_p, int max_len) +/* every read is bounded by the code section the caller hands in: a cart + * that declares more output than its payload encodes must fail, not read on + * past the decoded image */ +#define READ_VAL(val) {if (in >= in_end) return 1; val = *in; in++;} +int decompress_mini(uint8 *in_p, int in_len, uint8 *out_p, int max_len) { int block_offset; int block_length; int val; uint8 *in = in_p; + uint8 *in_end = in_p + (in_len > 0 ? in_len : 0); uint8 *out = out_p; int len; diff --git a/components/pico8/femto8/src/lexaloffle/pico8.h b/components/pico8/femto8/src/lexaloffle/pico8.h index a3139a68..9e8039c6 100644 --- a/components/pico8/femto8/src/lexaloffle/pico8.h +++ b/components/pico8/femto8/src/lexaloffle/pico8.h @@ -3,11 +3,11 @@ #include -int decompress_mini(uint8_t *in_p, uint8_t *out_p, int max_len); +int decompress_mini(uint8_t *in_p, int in_len, uint8_t *out_p, int max_len); int is_compressed_format_header(uint8_t *dat); // max_len should be 0x10000 (64k max code size) // out_p should allocate 0x10001 (includes null terminator) -int pico8_code_section_decompress(uint8_t *in_p, uint8_t *out_p, int max_len); -int pxa_decompress(uint8_t *in_p, uint8_t *out_p, int max_len); +int pico8_code_section_decompress(uint8_t *in_p, int in_len, uint8_t *out_p, int max_len); +int pxa_decompress(uint8_t *in_p, int in_len, uint8_t *out_p, int max_len); #endif diff --git a/components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c b/components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c index 45b126f0..3d2ebfbf 100644 --- a/components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c +++ b/components/pico8/femto8/src/lexaloffle/pxa_compress_snippets.c @@ -59,6 +59,8 @@ typedef unsigned char uint8; static int bit = 1; static int byte = 0; static int src_pos = 0; +static int src_len = 0; /* bytes available in src_buf; reads past it fail the decode */ +static int src_overrun = 0; //------------------------------------------------- @@ -72,6 +74,11 @@ static int getbit() { int ret; + if (src_pos >= src_len) + { + src_overrun = 1; + return 0; + } ret = (src_buf[src_pos] & bit) ? 1 : 0; bit <<= 1; if (bit == 256) @@ -160,7 +167,7 @@ static void init_literals_state(int *literal, int *literal_pos) #define RESTORE_VLIST_STATE() memcpy(literal, literal_backup, sizeof(literal)); memcpy(literal_pos, literal_pos_backup, sizeof(literal_pos)); -int pxa_decompress(uint8 *in_p, uint8 *out_p, int max_len) +int pxa_decompress(uint8 *in_p, int in_len, uint8 *out_p, int max_len) { int i; int literal[256]; @@ -171,6 +178,8 @@ int pxa_decompress(uint8 *in_p, uint8 *out_p, int max_len) byte = 0; src_buf = in_p; src_pos = 0; + src_len = in_len > 0 ? in_len : 0; + src_overrun = 0; init_literals_state(literal, literal_pos); @@ -186,8 +195,11 @@ int pxa_decompress(uint8 *in_p, uint8 *out_p, int max_len) // printf(" read raw_len: %d\n", raw_len); // printf(" read comp_len: %d\n", comp_len); + if (comp_len > src_len) return 0; // declares more input than the cart holds + while (src_pos < comp_len && dest_pos < raw_len && dest_pos < max_len) { + if (src_overrun) return 0; int block_type = getbit(); // printf("%d %d\n", src_pos, block_type); fflush(stdout); @@ -280,10 +292,17 @@ int is_compressed_format_header(uint8 *dat) // max_len should be 0x10000 (64k max code size) // out_p should allocate 0x10001 (includes null terminator) -int pico8_code_section_decompress(uint8 *in_p, uint8 *out_p, int max_len) +int pico8_code_section_decompress(uint8 *in_p, int in_len, uint8 *out_p, int max_len) { - if (is_compressed_format_header(in_p) == 0) { memcpy(out_p, in_p, 0x3d00); out_p[0x3d00] = '\0'; return 0; } // legacy: no header -> is raw text - if (is_compressed_format_header(in_p) == 1) return decompress_mini(in_p, out_p, max_len); - if (is_compressed_format_header(in_p) == 2) return pxa_decompress (in_p, out_p, max_len); + if (in_len < 8 || max_len < 1) return 1; + if (is_compressed_format_header(in_p) == 0) { + // legacy: no header -> is raw text (bounded by the section and the output) + int n = 0x3d00; + if (n > in_len) n = in_len; + if (n > max_len) n = max_len; + memcpy(out_p, in_p, n); out_p[n] = '\0'; return 0; + } + if (is_compressed_format_header(in_p) == 1) return decompress_mini(in_p, in_len, out_p, max_len); + if (is_compressed_format_header(in_p) == 2) return pxa_decompress (in_p, in_len, out_p, max_len); return 0; } diff --git a/components/pico8/femto8/src/p8_parser.c b/components/pico8/femto8/src/p8_parser.c index 0063682f..1d681584 100644 --- a/components/pico8/femto8/src/p8_parser.c +++ b/components/pico8/femto8/src/p8_parser.c @@ -667,7 +667,9 @@ int parse_png_ram(const char *file_name, uint8_t *buffer, int file_size, uint8_t } memcpy(memory, byte_buffer, CART_MEMORY_SIZE); { - pico8_code_section_decompress(byte_buffer + CART_MEMORY_SIZE, decompression_buffer, LUA_SCRIPT_SIZE - 1); + /* the code section is whatever the image holds past the cart memory */ + pico8_code_section_decompress(byte_buffer + CART_MEMORY_SIZE, (int)(PNG_WIDTH * PNG_HEIGHT) - CART_MEMORY_SIZE, + decompression_buffer, LUA_SCRIPT_SIZE - 1); if (lua_script) *lua_script = (const char *)decompression_buffer; } diff --git a/components/pico8/src/pico8.cpp b/components/pico8/src/pico8.cpp index 7061a189..a5cb7c3d 100644 --- a/components/pico8/src/pico8.cpp +++ b/components/pico8/src/pico8.cpp @@ -108,8 +108,10 @@ namespace { constexpr int NUM_FRAMES = 3; uint8_t* s_frames[NUM_FRAMES] = {nullptr, nullptr, nullptr}; int s_frameIndex = 0; - const uint8_t* s_lastFrame = nullptr; - unsigned s_framesPresented = 0; + // published by the cart task, read by the emulator task (statistics, + // resume, the pause screenshot) + std::atomic s_lastFrame{nullptr}; + std::atomic s_framesPresented{0}; unsigned s_lastPresented = 0; int64_t s_lastFrameUs = 0, s_lastReportUs = 0; unsigned s_framesAtReport = 0; @@ -486,8 +488,8 @@ void resume_pico8_tasks() { // the menu overwrote the screen and palette auto& box = BoxEmu::get(); box.palette(m_colors, 32); - if (s_lastFrame) { - box.push_frame(s_lastFrame); + if (const uint8_t* frame = s_lastFrame) { + box.push_frame(frame); } audio_resume(); s_inputGate = true; @@ -511,11 +513,12 @@ void save_pico8(std::string_view save_path, int save_slot) { std::span get_pico8_video_buffer() { // RGB565 copy of the last frame (for the pause screenshot) in frame_buffer1 uint16_t* dst = reinterpret_cast(BoxEmu::get().frame_buffer1()); - if (!s_lastFrame || !dst) { + const uint8_t* frame = s_lastFrame; + if (!frame || !dst) { return std::span(); } for (size_t i = 0; i < FRAME_BYTES; i++) { - dst[i] = m_colors[s_lastFrame[i] & 0x1f]; + dst[i] = m_colors[frame[i] & 0x1f]; } return std::span(reinterpret_cast(dst), FRAME_BYTES * sizeof(uint16_t)); } From aa50793337c36799edb7d78249638e195ebd3035 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Fri, 9 Oct 2026 11:47:25 -0500 Subject: [PATCH 19/19] fix(pico8): keep the Lua VM out of IRAM The 12KB it took came out of the internal SRAM every core shares: the largest free internal block at the menu fell from 100KB to 88KB, which pushed Genesis hot buffers to PSRAM (slower) and starved the pause menu (crash). It had not measurably helped PICO-8 either. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01AWhoGwibqcKDhcG17mjVT1 --- components/pico8/linker.lf | 5 ----- 1 file changed, 5 deletions(-) diff --git a/components/pico8/linker.lf b/components/pico8/linker.lf index a2a67e79..ce53322f 100644 --- a/components/pico8/linker.lf +++ b/components/pico8/linker.lf @@ -21,8 +21,3 @@ entries: # the emulator-side glue owns the reset (the .data snapshot, the lifecycle # flags) and must survive it: keep it in the default sections pico8 (default) - # the interpreter's hot loop and table/string access run from IRAM rather - # than through the flash cache (their statics still follow pico8_statics) - lvm (noflash_text) - ltable (noflash_text) - lstring (noflash_text)