4 Commits
Author SHA1 Message Date
YourWishes 5184064a26 w 2026-07-12 10:10:05 -05:00
YourWishes 6a43363539 Optimized 2026-07-11 23:51:39 -05:00
YourWishes b9195fbbad Script ezy 2026-07-11 22:29:57 -05:00
YourWishes f715ad2176 Nuke it all 2026-07-11 20:37:28 -05:00
859 changed files with 10552 additions and 44620 deletions

No files matched your search

+1 -2
View File
@@ -91,7 +91,7 @@ assets/borrowed
/archive0
/archive1
/archive
# /archive
__pycache__
@@ -107,4 +107,3 @@ yarn.lock
/assets/test
/tools_old
/assets/test.png
/assets/audio/boa.mp3
+15 -57
View File
@@ -8,22 +8,16 @@ cmake_minimum_required(VERSION 3.13)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_MODULE_PATH
${CMAKE_MODULE_PATH}
${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules
)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)
cmake_policy(SET CMP0079 NEW)
# set(FETCHCONTENT_UPDATES_DISCONNECTED ON)
option(DUSK_BUILD_TESTS "Enable tests" OFF)
option(DUSK_NETWORK "Enable network support" ON)
set(DUSK_GAME_NAME "Dusk" CACHE STRING "Game display name")
set(DUSK_GAME_AUTHOR "YourWishes" CACHE STRING "Game author / coder")
set(DUSK_GAME_SHORT_DESCRIPTION "Dusk game" CACHE STRING "One-line description")
set(DUSK_GAME_LONG_DESCRIPTION
"No description yet." CACHE STRING "Full description"
)
set(DUSK_GAME_LONG_DESCRIPTION "No description yet." CACHE STRING "Full description")
# Prep cache
set(DUSK_CACHE_TARGET "dusk-target")
@@ -37,19 +31,13 @@ set(DUSK_TEMP_DIR "${DUSK_BUILD_DIR}/temp")
set(DUSK_TOOLS_DIR "${DUSK_ROOT_DIR}/tools")
set(DUSK_DATA_DIR "${DUSK_ROOT_DIR}/data")
set(DUSK_ASSETS_DIR "${DUSK_ROOT_DIR}/assets")
set(DUSK_BUILT_ASSETS_DIR "${DUSK_BUILD_DIR}/built_assets"
CACHE INTERNAL ${DUSK_CACHE_TARGET}
)
set(DUSK_BUILT_ASSETS_DIR "${DUSK_BUILD_DIR}/built_assets" CACHE INTERNAL ${DUSK_CACHE_TARGET})
set(DUSK_GENERATED_HEADERS_DIR "${DUSK_BUILD_DIR}/generated")
set(DUSK_BUILD_BINARY ${DUSK_BUILD_DIR}/Dusk
CACHE INTERNAL ${DUSK_CACHE_TARGET}
)
set(DUSK_BUILD_BINARY ${DUSK_BUILD_DIR}/Dusk CACHE INTERNAL ${DUSK_CACHE_TARGET})
set(DUSK_ASSETS "" CACHE INTERNAL ${DUSK_CACHE_TARGET})
set(DUSK_LIBRARY_TARGET_NAME "DuskCore" CACHE INTERNAL ${DUSK_CACHE_TARGET})
set(DUSK_BINARY_TARGET_NAME "Dusk" CACHE INTERNAL ${DUSK_CACHE_TARGET})
set(DUSK_ASSETS_ZIP "${DUSK_BUILD_DIR}/dusk.dsk"
CACHE INTERNAL ${DUSK_CACHE_TARGET}
)
set(DUSK_ASSETS_ZIP "${DUSK_BUILD_DIR}/dusk.dsk" CACHE INTERNAL ${DUSK_CACHE_TARGET})
if(NOT DEFINED DUSK_TARGET_SYSTEM)
set(DUSK_TARGET_SYSTEM "linux")
@@ -84,9 +72,7 @@ if(DUSK_BUILD_TESTS)
${DUSK_LIBRARY_TARGET_NAME}
)
else()
set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}"
CACHE INTERNAL ${DUSK_CACHE_TARGET}
)
set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}" CACHE INTERNAL ${DUSK_CACHE_TARGET})
endif()
if(NOT DEFINED DUSK_VERSION)
@@ -104,12 +90,6 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME}
DUSK_VERSION="${DUSK_VERSION}"
)
if(DUSK_NETWORK)
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_NETWORK
)
endif()
# Toolchains
include(cmake/targets/${DUSK_TARGET_SYSTEM}.cmake)
@@ -135,38 +115,16 @@ if(DUSK_BUILD_TESTS)
add_subdirectory(test)
endif()
# Build assets. Runs unconditionally on every build (rather than being
# gated behind a custom_command's file-level DEPENDS list) because
# CONFIGURE_DEPENDS globs only pick up added/removed files on the next
# CMake configure, so that approach could miss/lag a rebuild behind an
# asset edit. tools.asset.pack itself decides whether anything actually
# changed (see its manifest check) and no-ops quickly when nothing did,
# so this stays cheap on a build where assets are untouched.
#
# A .ds script under assets/ is compiled to .dsb by duskscriptcc as part of
# packing, so dusk.dsk only ever carries bytecode. duskscriptcc is a host
# tool, only built when target_system is the build host (linux/knulli, see
# src/CMakeLists.txt) - a cross-compiled console target has no duskscriptcc
# of its own to depend on or pass down, so it can only pack assets with no
# .ds in them until something sets up a host-built duskscriptcc for it too.
if(DUSK_TARGET_SYSTEM STREQUAL "linux" OR DUSK_TARGET_SYSTEM STREQUAL "knulli")
set(DUSK_ASSET_PACK_DUSKSCRIPTCC_ARGS --duskscriptcc "$<TARGET_FILE:duskscriptcc>")
set(DUSK_ASSET_PACK_DEPENDS duskscriptcc)
else()
set(DUSK_ASSET_PACK_DUSKSCRIPTCC_ARGS "")
set(DUSK_ASSET_PACK_DEPENDS "")
endif()
add_custom_target(DUSK_ASSETS_BUILT ALL
# Build assets
file(GLOB_RECURSE DUSK_ASSET_FILES CONFIGURE_DEPENDS "${DUSK_ASSETS_DIR}/*")
add_custom_command(
OUTPUT "${DUSK_ASSETS_ZIP}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${DUSK_ASSETS_DIR}"
COMMAND ${Python3_EXECUTABLE} -m tools.asset.pack
--input "${DUSK_ASSETS_DIR}"
--output "${DUSK_ASSETS_ZIP}"
${DUSK_ASSET_PACK_DUSKSCRIPTCC_ARGS}
WORKING_DIRECTORY "${DUSK_ROOT_DIR}"
BYPRODUCTS "${DUSK_ASSETS_ZIP}"
DEPENDS ${DUSK_ASSET_PACK_DEPENDS}
COMMENT "Packing assets into dusk.dsk"
COMMAND ${CMAKE_COMMAND} -E rm -f "${DUSK_ASSETS_ZIP}"
COMMAND ${CMAKE_COMMAND} -E tar "cf" "${DUSK_ASSETS_ZIP}" --format=zip -- .
WORKING_DIRECTORY "${DUSK_ASSETS_DIR}"
DEPENDS ${DUSK_ASSET_FILES}
VERBATIM
)
add_custom_target(DUSK_ASSETS_BUILT DEPENDS "${DUSK_ASSETS_ZIP}")
add_dependencies(${DUSK_LIBRARY_TARGET_NAME} DUSK_ASSETS_BUILT)
+6 -8
View File
@@ -1,5 +1,6 @@
# Dusk
RPG Game Project, small and able to run on a PSP.
# Documentation
- [Scripting](docs/SCRIPTING.md) — writing gameplay logic in JavaScript.
- [UI](docs/UI.md) — building buttons/menus/etc from engine/game C code.
# Building
Each build target has different requirements. You can take a look at the git
@@ -9,18 +10,15 @@ following packages, depending on your system;
Fedora;
```
sudo dnf install git make gcc cmake python python-polib python3-pillow python3-dotenv python3-numpy python-qt5 python3-pyopengl SDL2-devel zlib-devel libzip-devel bzip2-devel openssl-devel lzma-sdk-devel xz xz-devel lua-devel libmad-devel
sudo dnf install git make gcc cmake python python-polib python3-pillow python3-dotenv python3-numpy python-qt5 python3-pyopengl SDL2-devel zlib-devel libzip-devel bzip2-devel openssl-devel lzma-sdk-devel xz xz-devel lua-devel
```
`libmad-devel` (used for MP3 decoding) is GPL-licensed and ships in the
[RPM Fusion](https://rpmfusion.org/) free repository rather than Fedora's
base repos - make sure RPM Fusion is enabled first.
Ubuntu;
```
sudo apt-get install git build-essential gcc python python-polib python3-pillow python3-dotenv python3-numpy python3-pyqt5 python3-opengl libmad0-dev
sudo apt-get install git build-essential gcc python python-polib python3-pillow python3-dotenv python3-numpy python3-pyqt5 python3-opengl
```
Arch Linux;
```
sudo pacman -S git base-devel gcc python python-polib python-pillow python-dotenv python-numpy python-pyqt5 python-opengl libmad
sudo pacman -S git base-devel gcc python python-polib python-pillow python-dotenv python-numpy python-pyqt5 python-opengl
```
+47
View File
@@ -0,0 +1,47 @@
var Actions;
var camera, cameraPosition;
var cube, cubePosition, cubeRenderable, cubeMesh;
var ground, groundPosition, groundRenderable;
// init() is called via scriptManagerCallGlobal(), which pumps the asset
// system + job queue until any promise it returns settles - so it's safe
// to await include() here even though this runs before the main loop.
async function init() {
Actions = await include("input.js");
camera = new Entity();
cameraPosition = camera.add(POSITION);
camera.add(CAMERA);
cameraPosition.position = new Vec3(3, 3, -6);
cameraPosition.lookAt(new Vec3(0, 0, 0));
cube = new Entity();
cubePosition = cube.add(POSITION);
cubeRenderable = cube.add(RENDERABLE);
cubeMesh = Mesh.createCube();
cubeRenderable.mesh = cubeMesh;
cubeRenderable.color = Color.red();
ground = new Entity();
groundPosition = ground.add(POSITION);
groundRenderable = ground.add(RENDERABLE);
groundRenderable.mesh = Mesh.createCube();
groundRenderable.color = Color.dark_gray();
}
// Runs every frame (including dynamic/interpolation frames) - use for
// smooth, purely presentational animation.
function update() {
cubePosition.rotation.y += TIME.delta * 1.5;
cubePosition.rotation.x += TIME.delta * 0.7;
}
// Runs once per fixed timestep only - use for gameplay logic that should
// be deterministic and independent of display refresh rate.
function fixedUpdate() {
}
function deinit() {
cube.dispose();
camera.dispose();
}
-20
View File
@@ -1,20 +0,0 @@
// Entry point, run once by the engine after every other system is ready.
var camera = entityAdd();
var cameraPosition = entityAddComponent(camera, COMPONENT_TYPE_POSITION);
entityAddComponent(camera, COMPONENT_TYPE_CAMERA);
entityPositionLookAt(camera, cameraPosition, 3, 3, 3, 0, 0, 0);
var cube = entityAdd();
var cubePosition = entityAddComponent(cube, COMPONENT_TYPE_POSITION);
var cubeRenderable = entityAddComponent(cube, COMPONENT_TYPE_RENDERABLE);
entityRenderableSetMesh(cube, cubeRenderable, "cube");
entityPositionSetLocalPosition(cube, cubePosition, 0, 0, 0);
var plane = entityAdd();
var planePosition = entityAddComponent(plane, COMPONENT_TYPE_POSITION);
var planeRenderable = entityAddComponent(plane, COMPONENT_TYPE_RENDERABLE);
entityRenderableSetMesh(plane, planeRenderable, "plane");
entityPositionSetLocalPosition(plane, planePosition, 0, 0, 0);
consolePrint("Camera, cube and plane created");
+27
View File
@@ -0,0 +1,27 @@
// Binds physical buttons to abstract actions, then exports the action
// constants so other scripts don't need to know raw INPUT_ACTION_* names.
Input.bind("w", INPUT_ACTION_UP);
Input.bind("s", INPUT_ACTION_DOWN);
Input.bind("a", INPUT_ACTION_LEFT);
Input.bind("d", INPUT_ACTION_RIGHT);
Input.bind("space", INPUT_ACTION_ACCEPT);
Input.bind("escape", INPUT_ACTION_RAGEQUIT);
if(typeof INPUT_GAMEPAD !== "undefined") {
Input.bind("gamepad_up", INPUT_ACTION_UP);
Input.bind("gamepad_down", INPUT_ACTION_DOWN);
Input.bind("gamepad_left", INPUT_ACTION_LEFT);
Input.bind("gamepad_right", INPUT_ACTION_RIGHT);
Input.bind("gamepad_a", INPUT_ACTION_ACCEPT);
Input.bind("gamepad_start", INPUT_ACTION_RAGEQUIT);
}
module = {
UP: INPUT_ACTION_UP,
DOWN: INPUT_ACTION_DOWN,
LEFT: INPUT_ACTION_LEFT,
RIGHT: INPUT_ACTION_RIGHT,
ACCEPT: INPUT_ACTION_ACCEPT,
CANCEL: INPUT_ACTION_CANCEL,
RAGEQUIT: INPUT_ACTION_RAGEQUIT
};
+2 -289
View File
@@ -1,289 +1,2 @@
msgid ""
msgstr ""
"Project-Id-Version: ExampleApp 1.0\n"
"Language: en\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=4; plural=(n==1 ? 0 : n==2 ? 1 : (n<7 ? 2 : 3));\n"
# Initial Scene
msgid "initial.checking_save.title"
msgstr "Checking for save data"
msgid "initial.checking_save.message"
msgstr "Please wait..."
msgid "initial.no_device.title"
msgstr "No Save Device Found"
msgid "initial.no_device.message"
msgstr "Could not find a save device, ensure it is connected and try again. You can continue, but progress will not be saved."
msgid "initial.no_device.retry"
msgstr "Try again"
msgid "initial.no_device.continue"
msgstr "Continue without saving"
# Main Menu Scene
msgid "main_menu.start_game"
msgstr "Start Game"
msgid "main_menu.options"
msgstr "Options"
msgid "main_menu.quit"
msgstr "Quit Game"
msgid "main_menu.quit_confirm"
msgstr "Are you sure you want to quit?"
msgid "main_menu.checking_save.title"
msgstr "Checking for save data"
msgid "main_menu.checking_save.message"
msgstr "Please wait..."
msgid "main_menu.no_device.title"
msgstr "No Save Device Found"
msgid "main_menu.no_device.message"
msgstr "Could not find a save device, ensure it is connected and try again. You can continue, but progress will not be saved."
msgid "main_menu.no_device.retry"
msgstr "Try again"
msgid "main_menu.no_device.continue"
msgstr "Continue without saving"
msgid "main_menu.save_load_error.title"
msgstr "Error"
msgid "main_menu.save_load_error.message"
msgstr "Failed to load save data. Please try again."
msgid "main_menu.save_load_error.retry"
msgstr "Try Again"
# Select Save Screen
msgid "ui.select_save.title"
msgstr "Select Save"
msgid "ui.select_save.empty"
msgstr "Empty Slot"
msgid "ui.select_save.corrupt"
msgstr "Corrupted Save"
msgid "ui.select_save.corrupt_warning"
msgstr "This save file is corrupted and could not be loaded. Please contact support if this issue persists."
msgid "ui.select_save.slot_format"
msgstr "%s Lv.%d %s"
msgid "ui.select_save.delete_mode"
msgstr "Delete a Save"
msgid "ui.select_save.delete_confirm"
msgstr "Are you sure you want to delete this save?"
msgid "ui.select_save.name_title"
msgstr "Enter game save file name"
msgid "ui.save_slot.number_format"
msgstr "Slot %d"
#: ui/menu.c:10
msgid "ui.title"
msgstr ""
"Welcome"
msgid "save.linux.mkdirp_failed"
msgstr "Failed to create save directory, check the disk is not full or write-protected."
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.general"
msgstr "General"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.input"
msgstr "Input"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.display"
msgstr "Display"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.audio"
msgstr "Audio"
msgid "ui.settings.input.deadzone"
msgstr "Deadzone"
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
msgid "ui.settings.general.language"
msgstr "Language"
msgid "ui.settings.general.language_detail"
msgstr "Takes effect after restarting the application."
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.apply"
msgstr "Apply"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.discard_changes"
msgstr "Discard unsaved changes?"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.characters"
msgstr "Characters"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.items"
msgstr "Items"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.settings"
msgstr "Settings"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save"
msgstr "Save"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_success"
msgstr "Game saved."
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_cancelled"
msgstr "Save cancelled."
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_unavailable"
msgstr "Can't save - no save device found."
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_temporary"
msgstr "This session is temporary - no save device was found, so saving is disabled."
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_create_confirm"
msgstr "No save data found. Create a new save?"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_failed_format"
msgstr "Save failed: %s"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_check_failed_format"
msgstr "Can't save: %s"
#: src/dusk/ui/frame/initial/uiinitialnocard.c
msgid "ui.initial.no_card.message"
msgstr "No save device found. You can continue, but\nprogress will not be saved."
#: src/dusk/ui/frame/initial/uiinitialnocard.c
msgid "ui.initial.no_card.retry"
msgstr "Retry"
#: src/dusk/ui/frame/initial/uiinitialnocard.c
msgid "ui.initial.no_card.continue"
msgstr "Continue Anyway"
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
msgid "ui.initial.create_save.message"
msgstr "No save data found. Create a new save?"
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
msgid "ui.initial.create_save.yes"
msgstr "Yes"
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
msgid "ui.initial.create_save.no"
msgstr "No"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.confirm"
msgstr "Confirm"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.cancel"
msgstr "Cancel"
#: src/dusk/ui/frame/battle/uibattlemenu.c
msgid "ui.battle.menu.attack"
msgstr "Attack"
#: src/dusk/ui/frame/battle/uibattlemenu.c
msgid "ui.battle.menu.flee"
msgstr "Flee"
#: src/dusk/ui/frame/battle/uibattlemenu.c
msgid "ui.battle.menu.target_format"
msgstr "Enemy %u (%u/%u HP)"
#: src/dusk/ui/frame/battle/uibattlehud.c
msgid "ui.battle.hud.hp_format"
msgstr "HP %u/%u"
#: src/dusk/ui/frame/battle/uibattlehud.c
msgid "ui.battle.hud.mp_format"
msgstr "MP %u/%u"
#: src/dusk/ui/frame/settings/uisettingsaudio.c
msgid "ui.settings.audio.placeholder"
msgstr "No audio settings yet"
#: src/dusk/ui/frame/settings/uisettingsdisplay.c
msgid "ui.settings.display.placeholder"
msgstr "No display settings yet"
#: src/dusk/ui/frame/settings/uisettingsinput.c
msgid "ui.settings.input.placeholder"
msgstr "No input settings yet"
#: src/dusk/ui/frame/backpack/uibackpack.c
msgid "ui.backpack.category_format"
msgstr "Category %u"
#: src/dusk/ui/overlay/uiloading.c
msgid "ui.loading.text"
msgstr "loading"
#: src/dusk/ui/overlay/uiautosave.c
msgid "ui.autosave.saving"
msgstr "SAVING"
#
# Items
#
msgid "item.potion.name"
msgstr "Potion"
msgid "item.potato.name"
msgstr "Potato"
msgid "item.apple.name"
msgstr "Apple"
#
# Moves
#
msgid "move.fire.name"
msgstr "Fire"
msgid "move.slash.name"
msgstr "Slash"
msgid "test.string"
msgstr "This is a test string"
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

+96
View File
@@ -0,0 +1,96 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Turn things off we don't need
set(JERRY_CMDLINE OFF CACHE BOOL "" FORCE)
set(JERRY_EXT ON CACHE BOOL "" FORCE)
set(JERRY_DEBUGGER OFF CACHE BOOL "" FORCE)
set(JERRY_BUILTIN_DATE OFF CACHE BOOL "" FORCE)
set(ENABLE_LTO OFF CACHE BOOL "" FORCE)
# Fetch Jerry
include(FetchContent)
FetchContent_Declare(
jerryscript
GIT_REPOSITORY https://git.wish.moe/YourWishes/jerryscript
GIT_TAG float32-fix
)
FetchContent_MakeAvailable(jerryscript)
# Mark found
set(jerryscript_FOUND ON)
# Define targets
if(TARGET jerryscript-core)
set(JERRY_CORE_TARGET jerryscript-core)
elseif(TARGET jerry-core)
set(JERRY_CORE_TARGET jerry-core)
endif()
if(TARGET jerryscript-ext)
set(JERRY_EXT_TARGET jerryscript-ext)
elseif(TARGET jerry-ext)
set(JERRY_EXT_TARGET jerry-ext)
endif()
if(TARGET jerryscript-port-default)
set(JERRY_PORT_TARGET jerryscript-port-default)
elseif(TARGET jerry-port-default)
set(JERRY_PORT_TARGET jerry-port-default)
elseif(TARGET jerryscript-port)
set(JERRY_PORT_TARGET jerryscript-port)
elseif(TARGET jerry-port)
set(JERRY_PORT_TARGET jerry-port)
endif()
if(NOT JERRY_CORE_TARGET)
message(FATAL_ERROR "JerryScript core target not found")
endif()
if(NOT JERRY_EXT_TARGET)
message(FATAL_ERROR "JerryScript ext target not found")
endif()
if(NOT JERRY_PORT_TARGET)
message(FATAL_ERROR "JerryScript port target not found")
endif()
foreach(tgt IN ITEMS
${JERRY_CORE_TARGET}
${JERRY_EXT_TARGET}
${JERRY_PORT_TARGET}
)
if(TARGET ${tgt})
set_property(TARGET ${tgt} PROPERTY INTERPROCEDURAL_OPTIMIZATION OFF)
target_compile_definitions(${JERRY_CORE_TARGET} PRIVATE
JERRY_NUMBER_TYPE_FLOAT64=0
JERRY_BUILTIN_DATE=0
)
endif()
endforeach()
# Export include dirs through the targets
target_include_directories(${JERRY_CORE_TARGET} INTERFACE
${jerryscript_SOURCE_DIR}/jerry-core/include
)
target_include_directories(${JERRY_EXT_TARGET} INTERFACE
${jerryscript_SOURCE_DIR}/jerry-ext/include
)
target_include_directories(${JERRY_PORT_TARGET} INTERFACE
${jerryscript_SOURCE_DIR}/jerry-port/default/include
)
# Suppress JerryScript-only warning
if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
target_compile_options(${JERRY_CORE_TARGET} PRIVATE
-Wno-error
)
endif()
add_library(jerryscript::core ALIAS ${JERRY_CORE_TARGET})
add_library(jerryscript::ext ALIAS ${JERRY_EXT_TARGET})
add_library(jerryscript::port ALIAS ${JERRY_PORT_TARGET})
-32
View File
@@ -1,32 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# NOTE: libmad itself is GPL-licensed (see https://www.underbit.com/products/mad/),
# not MIT like the rest of this project. Any binary linking it must comply
# with the GPL - a deliberate tradeoff accepted for MP3 decode correctness
# (see audiostreammp3decodersw.c's own comment on why minimp3 wasn't enough).
find_path(LIBMAD_INCLUDE_DIR NAMES mad.h)
mark_as_advanced(LIBMAD_INCLUDE_DIR)
find_library(LIBMAD_LIBRARY NAMES mad)
mark_as_advanced(LIBMAD_LIBRARY)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
libmad
REQUIRED_VARS
LIBMAD_LIBRARY
LIBMAD_INCLUDE_DIR
)
if(libmad_FOUND AND NOT TARGET libmad::mad)
add_library(libmad::mad UNKNOWN IMPORTED)
set_target_properties(libmad::mad
PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${LIBMAD_INCLUDE_DIR}
IMPORTED_LOCATION ${LIBMAD_LIBRARY}
)
endif()
-2
View File
@@ -61,8 +61,6 @@ target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
zstd
z
lzma
asnd
mad
)
if(DUSK_DOLPHIN_BUILD_TYPE STREQUAL "ISO")
+1
View File
@@ -43,4 +43,5 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_INPUT_POINTER
DUSK_INPUT_GAMEPAD
DUSK_TIME_DYNAMIC
DUSK_THREAD_PTHREAD
)
-1
View File
@@ -27,7 +27,6 @@ target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
)
set(DUSK_BACKTRACE ON CACHE BOOL "Enable backtrace support for assert failures.")
set(DUSK_TRACK_MEMORY ON CACHE BOOL "Track memoryAllocate() call sites to help find memory leaks.")
# Define platform-specific macros.
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
-60
View File
@@ -30,7 +30,6 @@ target_link_libraries(${DUSK_BINARY_TARGET_NAME} PUBLIC
pspgu
pspaudio
pspaudiolib
pspmp3
psputility
pspvfpu
pspvram
@@ -60,42 +59,12 @@ target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
DUSK_DISPLAY_OVERSCAN=6
)
# logDebug()/logError() additionally write every call to a file on the
# Memory Stick (ms0:/PSP/GAME/Dusk/*.log) - a real, measured source of
# per-call hitching (fopen+write+fclose every log line), not just a
# theoretical cost. Default off so a normal build doesn't pay it; opt in
# with -DDUSK_PSP_LOG_FILE=ON when the log file itself is actually needed
# (e.g. no way to see stdout on real hardware).
set(DUSK_PSP_LOG_FILE OFF CACHE BOOL "Also write PSP debug/error logs to ms0:/PSP/GAME/Dusk/*.log (slow - Memory Stick I/O per call).")
if(DUSK_PSP_LOG_FILE)
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
DUSK_PSP_LOG_FILE
)
endif()
if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
DUSK_ASSERTIONS_FAKED
)
endif()
# Generate PARAM.SFO as a normal tracked build output (instead of letting
# create_pbp_file() auto-generate + delete it) so it can be reused below by
# a properly dependency-tracked EBOOT.PBP repack step.
set(DUSK_PSP_PARAM_SFO "${DUSK_BUILD_DIR}/PARAM.SFO")
add_custom_command(
OUTPUT "${DUSK_PSP_PARAM_SFO}"
COMMAND "$ENV{PSPDEV}/bin/mksfoex" "-d" "MEMSIZE=1" "-s" "APP_VER=01.00"
"${DUSK_BINARY_TARGET_NAME}" "${DUSK_PSP_PARAM_SFO}"
COMMENT "Generating PARAM.SFO for ${DUSK_BINARY_TARGET_NAME}"
VERBATIM
)
add_custom_target(DuskPspParamSfo DEPENDS "${DUSK_PSP_PARAM_SFO}")
# create_pbp_file()'s own POST_BUILD chain (below) also consumes
# DUSK_PSP_PARAM_SFO, so make sure it exists before that chain runs.
add_dependencies(${DUSK_BINARY_TARGET_NAME} DuskPspParamSfo)
# Postbuild, create .pbp file for PSP.
create_pbp_file(
TARGET "${DUSK_BINARY_TARGET_NAME}"
@@ -105,33 +74,4 @@ create_pbp_file(
TITLE "${DUSK_BINARY_TARGET_NAME}"
PSAR_PATH ${DUSK_ASSETS_ZIP}
VERSION 01.00
SFO_PATH "${DUSK_PSP_PARAM_SFO}"
OUTPUT_DIR "${DUSK_BUILD_DIR}"
)
# CreatePBP.cmake's pack-pbp step is a POST_BUILD command tied to the
# executable target, so it only reruns when the ELF itself relinks. That
# means regenerating dusk.dsk (assets) alone, without touching any C
# source, silently leaves EBOOT.PBP embedding a stale asset pak. Repack it
# here as a normal file-tracked custom command depending on both the
# executable and the asset zip, so EBOOT.PBP always reflects the current
# assets even when nothing else about the build changed.
set(DUSK_PSP_EBOOT "${DUSK_BUILD_DIR}/EBOOT.PBP")
if(BUILD_PRX)
set(DUSK_PSP_EXECUTABLE "$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>.prx")
else()
set(DUSK_PSP_EXECUTABLE "$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>")
endif()
add_custom_command(
OUTPUT "${DUSK_PSP_EBOOT}"
COMMAND "$ENV{PSPDEV}/bin/pack-pbp" "${DUSK_PSP_EBOOT}" "${DUSK_PSP_PARAM_SFO}"
"NULL" "NULL" "NULL" "NULL" "NULL"
"${DUSK_PSP_EXECUTABLE}" "${DUSK_ASSETS_ZIP}"
DEPENDS
"$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>"
"${DUSK_PSP_PARAM_SFO}"
"${DUSK_ASSETS_ZIP}"
COMMENT "Repacking EBOOT.PBP (tracks executable + asset pak freshness)"
VERBATIM
)
add_custom_target(DuskPspEbootRepack ALL DEPENDS "${DUSK_PSP_EBOOT}")
+1
View File
@@ -75,6 +75,7 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_OPENGL_LEGACY
DUSK_DISPLAY_WIDTH=960
DUSK_DISPLAY_HEIGHT=544
DUSK_THREAD_PTHREAD
)
# Post-build: create SELF from the ELF binary (UNSAFE = homebrew, no signing)
-11
View File
@@ -4,17 +4,6 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_WII
)
# Wii save storage method - see src/duskdolphin/save/savedeviceplatform.h.
set(DUSK_SAVE_WII_METHOD "SD" CACHE STRING
"Wii save storage: NAND (internal storage via ISFS), CARD (GameCube-\
compatible memory card emulation), or SD (SD card via libfat)"
)
set_property(CACHE DUSK_SAVE_WII_METHOD PROPERTY STRINGS "NAND" "CARD" "SD")
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_SAVE_WII_METHOD_${DUSK_SAVE_WII_METHOD}
)
# Generate Homebrew Channel meta.xml from project identity variables
string(TIMESTAMP DUSK_BUILD_DATE "%Y%m%d000000" UTC)
configure_file(
+379
View File
@@ -0,0 +1,379 @@
# Scripting
Dusk embeds [JerryScript](https://github.com/jerryscript-project/jerryscript) to
drive gameplay logic from JavaScript. The engine itself (rendering, physics,
asset loading, entity storage) is all C; scripts sit on top and manipulate that
state through a small set of bound objects.
This document covers the JS-facing scripting API. **UI (buttons, sliders,
menus, etc.) is not exposed to scripts** — it's a separate, C-only API. See
[UI.md](UI.md) if you're building screens/menus from engine/game C code.
## Lifecycle
On startup, `engineInit()` loads and evaluates `assets/engine.js` as the main
script, then calls the global `init()` function if one is defined. From then
on, every engine tick calls (in order):
1. `fixedUpdate()` — once per fixed timestep. Use this for gameplay logic that
must be deterministic and independent of display refresh rate (movement,
physics-adjacent input handling, etc). Skipped on interpolation/dynamic
frames when the build has variable-timestep rendering enabled.
2. `update()` — once per rendered frame, including interpolation frames. Use
this for smooth, purely presentational animation (nothing that needs to be
deterministic).
On shutdown, `deinit()` is called once.
All four hooks (`init`, `update`, `fixedUpdate`, `deinit`) are **optional** —
if a script doesn't define one, the engine simply skips it, no error.
```js
function update() {
cubePosition.rotation.y += TIME.delta * 1.5;
}
```
### `async init()` and `include()`
`init` (or any of the other hooks) can be declared `async` and use `await`
freely, including awaiting `include()` (see below), even though the engine
calls these functions synchronously from C with no external JS event loop.
When a hook returns a pending `Promise`, the engine keeps driving the asset
system and JerryScript's job queue until that promise settles before
continuing — so by the time e.g. `init()` "returns" from the engine's point of
view, everything it awaited has actually finished.
```js
async function init() {
Actions = await include("input.js");
// ...
}
```
If the awaited work throws/rejects, it surfaces as a C-level error.
## Loading other scripts: `include(path)`
```js
var Actions = await include("input.js");
```
`include(path)` always returns a `Promise`. The named file is loaded and
evaluated once no matter how many times (or from how many different scripts)
you `include()` it — later calls for the same path are handed the same
in-flight/resolved promise rather than re-running the file.
The included script communicates its result back by assigning to the bare
global `module`:
```js
// input.js
Input.bind("w", INPUT_ACTION_UP);
// ...
module = {
UP: INPUT_ACTION_UP,
DOWN: INPUT_ACTION_DOWN,
// ...
};
```
Whatever `input.js` assigns to `module` becomes the resolved value of the
promise `include("input.js")` returned — that's what `Actions` ends up being
in the example above. If the included script throws, the promise rejects
instead.
## Full example
This is the actual shipped example content (`assets/engine.js` +
`assets/input.js`):
```js
// input.js — binds physical buttons to abstract actions, then exports the
// action constants so other scripts don't need to know raw INPUT_ACTION_* names.
Input.bind("w", INPUT_ACTION_UP);
Input.bind("s", INPUT_ACTION_DOWN);
Input.bind("a", INPUT_ACTION_LEFT);
Input.bind("d", INPUT_ACTION_RIGHT);
Input.bind("space", INPUT_ACTION_ACCEPT);
Input.bind("escape", INPUT_ACTION_RAGEQUIT);
if(typeof INPUT_GAMEPAD !== "undefined") {
Input.bind("gamepad_up", INPUT_ACTION_UP);
Input.bind("gamepad_down", INPUT_ACTION_DOWN);
Input.bind("gamepad_left", INPUT_ACTION_LEFT);
Input.bind("gamepad_right", INPUT_ACTION_RIGHT);
Input.bind("gamepad_a", INPUT_ACTION_ACCEPT);
Input.bind("gamepad_start", INPUT_ACTION_RAGEQUIT);
}
module = {
UP: INPUT_ACTION_UP,
DOWN: INPUT_ACTION_DOWN,
LEFT: INPUT_ACTION_LEFT,
RIGHT: INPUT_ACTION_RIGHT,
ACCEPT: INPUT_ACTION_ACCEPT,
CANCEL: INPUT_ACTION_CANCEL,
RAGEQUIT: INPUT_ACTION_RAGEQUIT
};
```
```js
// engine.js
var Actions;
var camera, cameraPosition;
var cube, cubePosition, cubeRenderable, cubeMesh;
async function init() {
Actions = await include("input.js");
camera = new Entity();
cameraPosition = camera.add(POSITION);
camera.add(CAMERA);
cameraPosition.position = new Vec3(3, 3, -6);
cameraPosition.lookAt(new Vec3(0, 0, 0));
cube = new Entity();
cubePosition = cube.add(POSITION);
cubeRenderable = cube.add(RENDERABLE);
cubeMesh = Mesh.createCube();
cubeRenderable.mesh = cubeMesh;
cubeRenderable.color = Color.red();
}
function update() {
cubePosition.rotation.y += TIME.delta * 1.5;
cubePosition.rotation.x += TIME.delta * 0.7;
}
function fixedUpdate() {
var move = 3.0 * TIME.delta;
if(Input.isDown(Actions.LEFT)) cubePosition.position.x -= move;
if(Input.isDown(Actions.RIGHT)) cubePosition.position.x += move;
if(Input.isDown(Actions.UP)) cubePosition.position.z += move;
if(Input.isDown(Actions.DOWN)) cubePosition.position.z -= move;
if(Input.pressed(Actions.ACCEPT)) cubePosition.position = new Vec3(0, 0, 0);
}
function deinit() {
cube.dispose();
camera.dispose();
}
```
## API reference
### `TIME`
Plain global object, live getters (read fresh engine state every access, not
snapshotted):
| Property | Type | Description |
|---|---|---|
| `TIME.delta` | number | Seconds since the last frame. |
| `TIME.time` | number | Total elapsed engine time, in seconds. |
### `PLATFORM`
A single global string constant — the compile-time target name, e.g.
`"linux"`, `"psp"`, `"vita"`, `"dolphin"`. Individual platform builds may
inject additional platform-specific globals via their own
`modulePlatformPlatform()` hook; those aren't documented here since they vary
per target.
### `Input`
Static namespace (not constructible — there's no `new Input()`).
| Method | Description |
|---|---|
| `Input.bind(buttonName, action)` | Binds a physical button/key (string, e.g. `"w"`, `"space"`, `"gamepad_up"`) to an abstract `INPUT_ACTION_*` constant. Many buttons can bind to the same action. Throws on an empty/unrecognized button name or invalid action. |
| `Input.isDown(action)` → boolean | Is the action currently held. |
| `Input.pressed(action)` → boolean | Action transitioned to down this frame. |
| `Input.released(action)` → boolean | Action transitioned to up this frame. |
| `Input.getValue(action)` → number | Current analog value for the action. |
| `Input.axis(negAction, posAction)` → number | Combined axis value from two opposing actions. |
| `Input.axis2D(negX, posX, negY, posY)` → `Vec2` | Combined 2D axis from four actions. |
Global `INPUT_ACTION_*` constants (names are stable API; treat the numeric
values as opaque/build-specific): `INPUT_ACTION_UP`, `INPUT_ACTION_DOWN`,
`INPUT_ACTION_LEFT`, `INPUT_ACTION_RIGHT`, `INPUT_ACTION_ACCEPT`,
`INPUT_ACTION_CANCEL`, `INPUT_ACTION_PAUSE`, `INPUT_ACTION_RAGEQUIT`,
`INPUT_ACTION_CONSOLE`, `INPUT_ACTION_POINTERX`, `INPUT_ACTION_POINTERY`.
Conditionally-defined boolean globals reflecting build capability — only
present at all if the corresponding input method is compiled in, so
feature-test with `typeof`, don't assume they exist:
`INPUT_KEYBOARD`, `INPUT_GAMEPAD`, `INPUT_POINTER`, `INPUT_TOUCH`.
### `Vec2` / `Vec3` / `Vec4`
`new Vec2(x?, y?)`, `new Vec3(x?, y?, z?)`, `new Vec4(x?, y?, z?, w?)` — all
components optional, default `0`.
Common instance surface across all three: `.dot(other)`, `.length()`,
`.lengthSq()`, `.normalize()`, `.negate()`, `.add(other)`, `.sub(other)`,
`.scale(n)`, `.lerp(other, t)` — each of `add`/`sub`/`scale`/`negate`/
`normalize`/`lerp` returns a **new** vector (non-mutating). `Vec3` additionally
has `.cross(other)` and `.distance(other)`; `Vec2` has `.distance(other)` too;
`Vec4` has neither `.cross()` nor `.distance()`.
`Vec4` also has UV aliases over the same four floats: `.u0` (= `.x`), `.v0`
(= `.y`), `.u1` (= `.z`), `.v1` (= `.w`) — handy for texture-rect style code.
All three have `.x`/`.y`(/`.z`/`.w`) get/set properties and a `.toString()`
like `"Vec3(1, 2, 3)"`.
**"Vec3Ref" — live references.** Several engine properties (entity
`position`/`rotation`/`scale`, physics `velocity`, a mesh vertex's `position`)
return a vector-*like* object instead of a plain `Vec3`. It has the identical
`.x`/`.y`/`.z` surface, but reads/writes go straight into the underlying
native buffer — writing `.x` on `entity.position.position` immediately moves
the entity, no separate assignment needed. Anywhere the API expects a `Vec3`
argument, a Vec3Ref works too. You never construct one directly; you only
ever receive them from properties like the ones above.
### `Mat4`
`new Mat4()` — always constructs identity; no other constructor form.
| Member | Description |
|---|---|
| `.mul(other)` → `Mat4` | `this * other`. |
| `.transpose()` → `Mat4` | |
| `.inverse()` → `Mat4` | |
| `.determinant()` → number | |
| `.mulVec3(vec3, w?)` → `Vec3` | `w` defaults to `1.0` (point); pass `0` for a direction. |
| `.mulVec4(vec4)` → `Vec4` | |
| `.translate(vec3)` → `Mat4` | Non-mutating — returns a translated copy. |
| `.scale(vec3)` → `Mat4` | Non-mutating — returns a scaled copy. |
| `Mat4.identity()` → `Mat4` | Static. |
| `Mat4.perspective(fov, aspect, near, far)` → `Mat4` | Static, all 4 args required. |
| `Mat4.lookAt(eye, center, up)` → `Mat4` | Static, all 3 args required `Vec3`s. |
### `Color`
`new Color(r?, g?, b?, a?)` — each an int `0..255`, default `255` (so
`new Color()` is opaque white). Properties `.r`/`.g`/`.b`/`.a` get/set.
Named factories, each a zero-arg static returning a new opaque `Color`
(alpha `255` unless noted): `Color.black()`, `Color.white()`, `Color.red()`,
`Color.green()`, `Color.blue()`, `Color.yellow()`, `Color.cyan()`,
`Color.magenta()`, `Color.transparent()` (alpha 0), `Color.transparent_white()`
(alpha 0), `Color.transparent_black()` (alpha 0), `Color.gray()`,
`Color.light_gray()`, `Color.dark_gray()`, `Color.orange()`, `Color.purple()`,
`Color.brown()`, `Color.pink()`, `Color.lime()`, `Color.navy()`,
`Color.teal()`, `Color.cornflower_blue()`.
`Color.rainbow(t?, speed?)` → `Color` — `t` defaults to `TIME.time * 4.0`;
produces a shifting rainbow color, useful for debug visuals.
### `Mesh`
`new Mesh(vertexCount)` — allocates an uninitialized CPU-side vertex buffer
(not yet uploaded to the GPU).
| Member | Description |
|---|---|
| `.vertices` | Array of vertex wrappers, each with a `.position` (Vec3Ref, writes straight into that vertex). |
| `.vertexCount` | Read-only. |
| `.flush()` | Uploads to the GPU. First call initializes the GPU mesh; later calls re-upload the current vertex data — call this after editing `.vertices[i].position`. |
| `.dispose()` | Frees GPU + CPU resources. |
Static engine-owned singletons (read-only, not something you dispose):
`Mesh.DEFAULT_CUBE`, `Mesh.DEFAULT_QUAD`, `Mesh.DEFAULT_SPHERE`,
`Mesh.DEFAULT_PLANE`, `Mesh.DEFAULT_CAPSULE`, `Mesh.DEFAULT_TRIPRISM`.
Static factories (each builds and uploads a brand-new `Mesh`):
| Factory | Notes |
|---|---|
| `Mesh.createCube(min?, max?)` | Both `Vec3`, default `(-0.5,-0.5,-0.5)`..`(0.5,0.5,0.5)`. |
| `Mesh.createQuad(minX?, minY?, maxX?, maxY?)` | Default `-0.5..0.5` both axes; UV fixed `0,0`–`1,1`. |
| `Mesh.createSphere(radius?, stacks?, sectors?)` | `radius` default `0.5`. |
| `Mesh.createPlane(width?, height?)` | Defaults `1.0`/`1.0`; XZ-aligned, centered at origin. |
| `Mesh.createCapsule(radius?, halfHeight?, capRings?, sectors?)` | Defaults `0.5`, `0.5`. |
| `Mesh.createTriPrism(x0, y0, x1, y1, x2, y2, minZ, maxZ)` | All 8 args required — a triangular cross-section extruded along Z. |
### `Entity` and components
```js
var e = new Entity();
var pos = e.add(POSITION);
```
`new Entity()` allocates an entity. `.id` is the read-only numeric engine ID.
`.add(TYPE)` adds a component and returns its wrapper (`TYPE` is one of the
constants below). `.dispose()` removes the entity and all its components.
Component-type constants: `POSITION`, `CAMERA`, `RENDERABLE`, `PHYSICS`,
`TRIGGER`. Each entity also exposes a lowercase getter that returns the
existing wrapper if the component is present, or `undefined` if not (it does
**not** add the component — use `.add()` for that): `entity.position`,
`entity.camera`, `entity.renderable`, `entity.physics`, `entity.trigger`.
#### `entity.add(POSITION)` → position component
| Member | Description |
|---|---|
| `.position` | Vec3Ref. Writing rebuilds the transform automatically. |
| `.rotation` | Vec3Ref, Euler angles. Same rebuild-on-write behavior. |
| `.scale` | Vec3Ref. Same rebuild-on-write behavior. |
| `.parent` | Get/set another position-component wrapper, or `null` to clear parenting. |
| `.lookAt(target, up?)` | `target` a `Vec3`; `up` defaults to `(0,1,0)`. |
#### `entity.add(CAMERA)` → camera component
| Member | Description |
|---|---|
| `.zNear` / `.zFar` | Numbers. |
| `.fov` | Only meaningful when `projectionType` is `CAMERA_TYPE_PERSPECTIVE`; otherwise get returns `undefined` and set is a no-op. |
| `.projectionType` | `CAMERA_TYPE_PERSPECTIVE` or `CAMERA_TYPE_ORTHOGRAPHIC`. |
| `.orthoTop` / `.orthoBottom` / `.orthoLeft` / `.orthoRight` | Only meaningful in orthographic mode, same undefined/no-op rule otherwise. |
#### `entity.add(RENDERABLE)` → renderable component
| Member | Description |
|---|---|
| `.type` | `ENTITY_RENDERABLE_TYPE_MATERIAL`, `_SPRITEBATCH`, or `_CALLBACK`. |
| `.mesh` | Get/set a `Mesh` instance or a `Mesh.DEFAULT_*` singleton. |
| `.color` | Get/set a `Color` instance (throws if given something else). |
| `.addSprite({ min?, max?, uvMin?, uvMax? })` | Adds a sprite to this renderable's sprite batch; all fields optional, default zero. |
| `.clearSprites()` | Clears the sprite batch. |
| `.setCallback(fn?)` | Switches to `ENTITY_RENDERABLE_TYPE_CALLBACK` and calls `fn()` on every render of this entity. Omit/pass non-function to clear. Exceptions inside `fn` surface as a C error. |
#### `entity.add(PHYSICS)` → physics component
| Member | Description |
|---|---|
| `.velocity` | Vec3Ref, plain (no rebuild-on-write). |
| `.onGround` | Read-only boolean. |
| `.bodyType` | `PHYSICS_BODY_STATIC`, `PHYSICS_BODY_DYNAMIC`, `PHYSICS_BODY_KINEMATIC`. |
| `.applyImpulse(vec3)` | Adds to velocity. No-op on static bodies. |
| `.setShapeCube(halfExtents)` | `halfExtents` a `Vec3`. |
| `.setShapeSphere(radius)` | Number. |
| `.setShapeCapsule(radius, halfHeight)` | Two numbers. |
| `.setShapePlane(normal, distance)` | `Vec3` + number. |
Shape-type constants (for reading `.type` on the underlying shape, not for
`.bodyType`): `PHYSICS_SHAPE_CUBE`, `PHYSICS_SHAPE_SPHERE`,
`PHYSICS_SHAPE_CAPSULE`, `PHYSICS_SHAPE_PLANE`.
#### `entity.add(TRIGGER)` → trigger component
| Member | Description |
|---|---|
| `.min` / `.max` | Plain `Vec3` values (copies, not live refs). |
| `.setBounds(min, max)` | Sets both at once. |
| `.contains(point)` → boolean | `point` a `Vec3`. |
## Not yet available to scripts
The following C modules exist and are fully implemented, but aren't currently
wired into script registration (`moduleRegister()` in
`src/dusk/script/module/module.h`), so none of these globals exist in a
script today: `Screen`, `SpriteBatch`, `Text`, `Scene`, `Easing`, `Console`,
`Engine`. If you need one of these from a script, it needs to be registered
in `moduleRegister()` first — see the existing entries there and the modules
under `src/dusk/script/module/` for the pattern to follow.
+255
View File
@@ -0,0 +1,255 @@
# UI
Dusk's UI system (buttons, checkboxes, sliders, dropdowns, tabs, menus, focus
navigation) is a **C-only API**. It is not exposed to JerryScript — see
[SCRIPTING.md](SCRIPTING.md) for what scripts *can* touch. If you need a
script to open/react to a menu, wire it through a C callback or a game-side
flag scripts can poll; there's no bridge for this today.
## Mental model
There is no retained-mode UI tree, no automatic dispatch, no scissor/clip-rect
API. Every widget is a plain struct you own (usually as a global or
scene-owned variable). You call its `xxxInit(...)` once, then call its
`xxxDraw(widget, x, y)` yourself, every frame you want it visible, at whatever
screen position you choose. Nothing draws itself automatically except three
fixed system overlays (overscan bars, debug console, FPS counter) — see
[System overlays](#system-overlays-automatic) below.
### Where UI rendering happens in the frame
- `uiInit()` / `uiDispose()` run once, at engine startup/shutdown.
- `uiUpdate()` runs once per tick (drives focus-navigation input handling).
- `uiRender()` runs once per frame, called from inside `sceneRender()` — i.e.
**after** the active scene's own 3D/game-world rendering, using an
orthographic screen-space projection. Your own widget `xxxDraw()` calls
should happen around the same point — typically from your scene's render
callback, after world content, so UI draws on top.
## Widgets
Every widget follows the same shape: `xxxInit(widget, ...)` zeroes the struct
and sets its fields; `xxxDraw(const widget*, x, y) -> errorret_t` draws it at
that screen position.
> **Init before Draw.** `uislider_t`, `uidropdown_t`, and `uitab_t` cache
> their label's measured width/height at `Init` time (an optimization —
> label text doesn't change after that point). Calling `Draw` before `Init`,
> or mutating `->label` directly instead of re-initializing, leaves stale
> layout. `uibutton_t`/`uicheckbox_t` don't have this restriction.
### Button
```c
void uiButtonInit(uibutton_t *button, const char_t *label);
bool_t uiButtonIsHighlighted(const uibutton_t *button);
void uiButtonSetHighlighted(uibutton_t *button, bool_t highlighted);
errorret_t uiButtonDraw(const uibutton_t *button, float_t x, float_t y);
```
Draws `label` in red when highlighted, white otherwise.
### Checkbox
```c
void uiCheckboxInit(uicheckbox_t *checkbox, const char_t *label);
bool_t uiCheckboxIsChecked(const uicheckbox_t *checkbox);
void uiCheckboxSetChecked(uicheckbox_t *checkbox, bool_t checked);
void uiCheckboxToggle(uicheckbox_t *checkbox);
bool_t uiCheckboxIsHighlighted(const uicheckbox_t *checkbox);
void uiCheckboxSetHighlighted(uicheckbox_t *checkbox, bool_t highlighted);
errorret_t uiCheckboxDraw(const uicheckbox_t *checkbox, float_t x, float_t y);
```
Draws `"Y "`/`"N "` then the label.
### Slider
```c
typedef union { float_t f; int32_t i; } uislidervalue_t;
void uiSliderInitFloat(uislider_t*, const char_t *label,
float_t value, float_t min, float_t max, float_t step);
void uiSliderInitInt(uislider_t*, const char_t *label,
int32_t value, int32_t min, int32_t max, int32_t step);
float_t uiSliderGetFloat(const uislider_t*); // works for either type
int32_t uiSliderGetInt(const uislider_t*); // asserts type == INT
void uiSliderSetFloat(uislider_t*, float_t value); // asserts type == FLOAT, clamps
void uiSliderSetInt(uislider_t*, int32_t value); // asserts type == INT, clamps
void uiSliderStepUp(uislider_t*); // wraps to min past max
void uiSliderStepDown(uislider_t*); // wraps to max past min
float_t uiSliderGetRatio(const uislider_t*); // normalized 0..1
int32_t uiSliderGetStepCount(const uislider_t*); // 0 for float sliders
bool_t uiSliderIsHighlighted(const uislider_t*);
void uiSliderSetHighlighted(uislider_t*, bool_t highlighted);
errorret_t uiSliderDraw(const uislider_t*, float_t x, float_t y);
```
Draws label, a track, a fill proportional to the current ratio, discrete step
markers if it's an int slider with fewer than 10 steps, then the value as
text.
### Dropdown
```c
void uiDropdownInit(uidropdown_t *dropdown, const char_t *label,
const char_t *const *options, uint8_t optionCount,
uint8_t selectedIndex);
uint8_t uiDropdownGetSelectedIndex(const uidropdown_t *dropdown);
const char_t *uiDropdownGetSelectedOption(const uidropdown_t *dropdown);
void uiDropdownSetSelectedIndex(uidropdown_t *dropdown, uint8_t index);
void uiDropdownStepNext(uidropdown_t *dropdown); // wraps
void uiDropdownStepPrev(uidropdown_t *dropdown); // wraps
bool_t uiDropdownIsHighlighted(const uidropdown_t *dropdown);
void uiDropdownSetHighlighted(uidropdown_t *dropdown, bool_t highlighted);
errorret_t uiDropdownDraw(const uidropdown_t *dropdown, float_t x, float_t y);
```
`options` is a caller-owned array of strings that must outlive the dropdown
(it isn't copied). Draws `label` then `"< Option >"`.
### Tab
```c
void uiTabInit(uitab_t *tab, const char_t *label);
bool_t uiTabIsActive(const uitab_t *tab);
void uiTabSetActive(uitab_t *tab, bool_t active);
errorret_t uiTabDraw(const uitab_t *tab, float_t x, float_t y);
```
Draws a background box sized to the label (green if active, red if inactive)
with the label on top.
## Menus: assembling widgets into a navigable list
`uimenu_t` is the one aggregate widget — it owns an array of items (labels,
spacers, and any of the widgets above), lays them out in a grid, and wires
keyboard/gamepad navigation via the focus system for you.
```c
typedef enum {
UI_MENU_WIDGET_TYPE_NONE, UI_MENU_WIDGET_TYPE_LABEL,
UI_MENU_WIDGET_TYPE_SPACER, UI_MENU_WIDGET_TYPE_CHECKBOX,
UI_MENU_WIDGET_TYPE_BUTTON, UI_MENU_WIDGET_TYPE_TAB,
UI_MENU_WIDGET_TYPE_SLIDER, UI_MENU_WIDGET_TYPE_DROPDOWN,
} uimenuwidgettype_t;
void uiMenuInit(uimenu_t *menu, uimenuselectedcallback_t selected,
uimenuclosedcallback_t closed, uimenuchangedcallback_t changed);
void uiMenuSetItems(uimenu_t *menu, const uimenuitem_t *items,
uint8_t itemCount, uint8_t columns);
void uiMenuSetPosition(uimenu_t *menu, uint8_t x, uint8_t y); // focus cursor cell, not pixels
void uiMenuOpen(uimenu_t *menu); // pushes onto the focus stack
void uiMenuClose(uimenu_t *menu); // pops it
bool_t uiMenuIsActive(const uimenu_t *menu);
errorret_t uiMenuDraw(const uimenu_t *menu, float_t x, float_t y,
float_t width, float_t height);
```
- `selected(menu, index, item)` fires when the player presses accept on an item.
- `changed(menu, index, item)` fires when the highlighted item changes.
- `closed(menu)` fires when the menu is popped off the focus stack.
- LEFT/RIGHT on a highlighted slider/checkbox/dropdown adjusts its value in
place instead of moving focus off it (handled internally).
### Building a menu with the `MENU_*` macros
`uimenu.h` provides macros that cut the boilerplate of filling in a
`uimenuitem_t` array. They expand into statements using local variables named
`menu`, `menuIndex`, and `menuCapacity`, so use them together, inside one
function, starting with `MENU_BEGIN` and ending with `MENU_END`:
```c
static uimenuitem_t optionsItems[8];
static uimenu_t optionsMenu;
static const char_t *qualityOptions[] = { "Low", "Medium", "High" };
static void onOptionsSelected(
const uimenu_t *menu, const uint8_t index, const uimenuitem_t *item
) {
if(index == 4) uiMenuClose(&optionsMenu); // "Back" button
}
static void onOptionsClosed(const uimenu_t *menu) {
// e.g. return to the previous screen
}
void optionsMenuBuild(void) {
MENU_BEGIN(&optionsMenu, optionsItems, onOptionsSelected, onOptionsClosed, NULL);
MENU_LABEL("Options");
MENU_CHECKBOX("Fullscreen");
MENU_SLIDER_FLOAT("Volume", 0.8f, 0.0f, 1.0f, 0.05f);
MENU_DROPDOWN("Quality", qualityOptions, 3, 1);
MENU_BUTTON("Back");
MENU_END(optionsItems, 1);
}
// Once, when the menu screen becomes active:
uiMenuOpen(&optionsMenu);
// Every frame the menu should be visible:
uiMenuDraw(&optionsMenu, 20.0f, 20.0f, 200.0f, 100.0f);
// When leaving the menu screen:
uiMenuClose(&optionsMenu);
```
`MENU_LABEL`/`MENU_SPACER` force a row break and aren't focusable/selectable.
Every other `MENU_*` macro calls the matching widget's own `Init` for you.
> This example is constructed directly from the widget/menu API surface (all
> function and macro signatures above are verified against the source), but
> there's currently no real menu-building call site anywhere else in the
> engine to cross-check the *pattern* against — treat it as a starting point,
> not a copy of shipped code.
## Focus system: navigation underneath `uimenu`
If you're building a custom widget that needs keyboard/gamepad navigation
without going through `uimenu`, use `ui/focus/uifocus.h` directly. `uimenu`
is implemented entirely in terms of this API, so it's a reasonable reference.
```c
uifocusitem_t * uiFocusPush(
uint8_t cols, uint8_t rows,
uifocusitemcallback_t selected, // fires on accept
uifocusitemcallback_t changed, // fires on cursor move (and once immediately)
uifocusitemcallback_t closed, // fires on pop
uifocusitemdirectioncallback_t direction, // optional pre-empt of a direction press; NULL for default grid movement
void *user
);
void uiFocusPop(void);
void uiFocusPopItem(uifocusitem_t *item);
void uiFocusSetPosition(uifocusitem_t *item, uint8_t x, uint8_t y); // wraps
void uiFocusMoveDirection(uifocusitem_t *item, uifocusdirection_t dir);
```
`uiFocusUpdate()` runs automatically from `uiUpdate()` every tick — you don't
call it yourself. It reads `INPUT_ACTION_ACCEPT` (fires `selected`),
`INPUT_ACTION_CANCEL` (pops the stack), and the four directional actions
(with hold-to-repeat timing) to move the cursor within the topmost pushed
item. Only the topmost stack entry (max depth 8) receives input at a time —
opening a submenu means pushing a new focus item on top; closing it pops back
to the parent.
There's no separate "is this widget focused" query — "focused" is expressed
as the pushed item's current `(x, y)` cursor cell matching a given slot, which
is exactly how `uimenu`'s `changed` callback decides which item to highlight.
## System overlays (automatic)
Three small overlays are wired into a fixed internal list and draw themselves
every frame with no call needed from game code:
- **Overscan bars** (`ui/overlay/uicrop.h`) — draws opaque bars over the
screen area outside `SCREEN.scanX/scanY/scanWidth/scanHeight` (the
overscan-safe viewport). A no-op on platforms/configs where the scan area
already equals the full viewport. `UI_CROP.color` (default black) is the
only thing you'd normally touch here.
- **Debug console** (`ui/debug/uiconsole.h`) — draws console history when
visible.
- **FPS counter** (`ui/debug/uifps.h`) — draws a live FPS/frame-time readout.
None of these have a scissor/clip-rect equivalent for your own widgets —
there is no clipping API in this UI system; everything draws unclipped at
whatever position you give it.
-159
View File
@@ -1,159 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
"use strict";
// ChunkTerrain - JS port of the terrain-quad generation performed by
// tools/asset/chunk/__main__.py (build_terrain_verts / _tile_quad /
// _RAMP_CORNERS) so the editor's 3D preview can show the same geometry the
// Python compiler will bake into the chunk's terrain mesh, without waiting
// for a compile pass. Vertex layout matches DMF: interleaved [u, v, x, y, z].
const ChunkTerrain = (() => {
const CHUNK_WIDTH = 16;
const CHUNK_HEIGHT = 16;
const CHUNK_DEPTH = 4;
const TILE_COUNT = CHUNK_WIDTH * CHUNK_HEIGHT * CHUNK_DEPTH;
// World-space Z distance of one Z-layer/story, in world-float space.
// Must match WORLD_LAYER_HEIGHT in src/dusk/rpg/overworld/worldpos.h.
const WORLD_LAYER_HEIGHT = Math.SQRT1_2;
const TILE_SHAPE_NULL = 0;
const TILE_SHAPE_GROUND = 1;
const TILE_SHAPE_RAMP_NORTH = 2;
const TILE_SHAPE_RAMP_EAST = 3;
const TILE_SHAPE_RAMP_SOUTH = 4;
const TILE_SHAPE_RAMP_WEST = 5;
const TILE_SHAPE_RAMP_NORTHEAST = 6;
const TILE_SHAPE_RAMP_NORTHWEST = 7;
const TILE_SHAPE_RAMP_SOUTHEAST = 8;
const TILE_SHAPE_RAMP_SOUTHWEST = 9;
const TILE_SHAPE_RAMP_NORTHEAST_INNER = 10;
const TILE_SHAPE_RAMP_NORTHWEST_INNER = 11;
const TILE_SHAPE_RAMP_SOUTHEAST_INNER = 12;
const TILE_SHAPE_RAMP_SOUTHWEST_INNER = 13;
// Per-shape corner heights as [sw, se, ne, nw] offsets from tile base Z.
// NORTH=+Y, EAST=+X. Cardinal ramps: low face at 0, high face at 1.
// Diagonal outer-corner ramps: only the named corner raised, rest at 0.
// Diagonal inner-corner ramps: only the corner opposite the named one is
// lowered to 0, the rest (including the named corner) stay raised at 1.
const RAMP_CORNERS = {
[TILE_SHAPE_GROUND]: [0.0, 0.0, 0.0, 0.0],
[TILE_SHAPE_RAMP_NORTH]: [0.0, 0.0, 1.0, 1.0],
[TILE_SHAPE_RAMP_SOUTH]: [1.0, 1.0, 0.0, 0.0],
[TILE_SHAPE_RAMP_EAST]: [0.0, 1.0, 1.0, 0.0],
[TILE_SHAPE_RAMP_WEST]: [1.0, 0.0, 0.0, 1.0],
[TILE_SHAPE_RAMP_NORTHEAST]: [0.0, 0.0, 1.0, 0.0],
[TILE_SHAPE_RAMP_NORTHWEST]: [0.0, 0.0, 0.0, 1.0],
[TILE_SHAPE_RAMP_SOUTHEAST]: [0.0, 1.0, 0.0, 0.0],
[TILE_SHAPE_RAMP_SOUTHWEST]: [1.0, 0.0, 0.0, 0.0],
[TILE_SHAPE_RAMP_NORTHEAST_INNER]: [0.0, 1.0, 1.0, 1.0],
[TILE_SHAPE_RAMP_NORTHWEST_INNER]: [1.0, 0.0, 1.0, 1.0],
[TILE_SHAPE_RAMP_SOUTHEAST_INNER]: [1.0, 1.0, 1.0, 0.0],
[TILE_SHAPE_RAMP_SOUTHWEST_INNER]: [1.0, 1.0, 0.0, 1.0],
};
function tileIndex(x, y, z) {
return x + y * CHUNK_WIDTH + z * CHUNK_WIDTH * CHUNK_HEIGHT;
}
// Six vertices (2 CCW triangles) for a quad with per-corner Z heights.
// Corner order: SW=(fx,fy), SE=(fx+1,fy), NE=(fx+1,fy+1), NW=(fx,fy+1).
function pushTileQuad(out, u0, u1, v0, v1, fx, fy, swZ, seZ, neZ, nwZ) {
out.push(
u0, v0, fx, fy, swZ,
u1, v0, fx + 1, fy, seZ,
u1, v1, fx + 1, fy + 1, neZ,
u0, v0, fx, fy, swZ,
u1, v1, fx + 1, fy + 1, neZ,
u0, v1, fx, fy + 1, nwZ,
);
}
// Generate terrain quads for every non-null tile in a flat tiles array
// (length TILE_COUNT, indexed via tileIndex). Returns a Float32Array of
// interleaved [u, v, x, y, z] vertices, matching DMF.VERTEX_FLOATS.
function buildTerrainVerts(tiles) {
const out = [];
for(let z = 0; z < CHUNK_DEPTH; z++) {
for(let y = 0; y < CHUNK_HEIGHT; y++) {
for(let x = 0; x < CHUNK_WIDTH; x++) {
const type = tiles[tileIndex(x, y, z)] || TILE_SHAPE_NULL;
const corners = RAMP_CORNERS[type];
if(!corners) continue;
const u0 = x / CHUNK_WIDTH;
const u1 = (x + 1) / CHUNK_WIDTH;
const v0 = y / CHUNK_HEIGHT;
const v1 = (y + 1) / CHUNK_HEIGHT;
const [sw, se, ne, nw] = corners;
pushTileQuad(
out, u0, u1, v0, v1, x, y,
(z + sw) * WORLD_LAYER_HEIGHT,
(z + se) * WORLD_LAYER_HEIGHT,
(z + ne) * WORLD_LAYER_HEIGHT,
(z + nw) * WORLD_LAYER_HEIGHT
);
}
}
}
return new Float32Array(out);
}
// Four edges (SW-SE, SE-NE, NE-NW, NW-SW) of a tile's quad as line
// segments, lifted slightly above the terrain surface to avoid
// z-fighting - same corner-height convention as pushTileQuad().
function pushTileGridLines(out, fx, fy, swZ, seZ, neZ, nwZ) {
const eps = 0.01;
const sw = [fx, fy, swZ + eps];
const se = [fx + 1, fy, seZ + eps];
const ne = [fx + 1, fy + 1, neZ + eps];
const nw = [fx, fy + 1, nwZ + eps];
const edges = [sw, se, se, ne, ne, nw, nw, sw];
for(const [x, y, z] of edges) out.push(0, 0, x, y, z);
}
// Generate grid-outline line segments for every non-null tile, following
// the same per-corner heights as buildTerrainVerts() so lines hug ramps
// instead of cutting through them. Returns a Float32Array of interleaved
// [u, v, x, y, z] vertices meant to be drawn with gl.LINES (pairs).
function buildGridLines(tiles) {
const out = [];
for(let z = 0; z < CHUNK_DEPTH; z++) {
for(let y = 0; y < CHUNK_HEIGHT; y++) {
for(let x = 0; x < CHUNK_WIDTH; x++) {
const type = tiles[tileIndex(x, y, z)] || TILE_SHAPE_NULL;
const corners = RAMP_CORNERS[type];
if(!corners) continue;
const [sw, se, ne, nw] = corners;
pushTileGridLines(
out, x, y,
(z + sw) * WORLD_LAYER_HEIGHT,
(z + se) * WORLD_LAYER_HEIGHT,
(z + ne) * WORLD_LAYER_HEIGHT,
(z + nw) * WORLD_LAYER_HEIGHT
);
}
}
}
return new Float32Array(out);
}
return Object.freeze({
CHUNK_WIDTH, CHUNK_HEIGHT, CHUNK_DEPTH, TILE_COUNT, WORLD_LAYER_HEIGHT,
TILE_SHAPE_NULL, TILE_SHAPE_GROUND,
TILE_SHAPE_RAMP_NORTH, TILE_SHAPE_RAMP_EAST,
TILE_SHAPE_RAMP_SOUTH, TILE_SHAPE_RAMP_WEST,
TILE_SHAPE_RAMP_NORTHEAST, TILE_SHAPE_RAMP_NORTHWEST,
TILE_SHAPE_RAMP_SOUTHEAST, TILE_SHAPE_RAMP_SOUTHWEST,
TILE_SHAPE_RAMP_NORTHEAST_INNER, TILE_SHAPE_RAMP_NORTHWEST_INNER,
TILE_SHAPE_RAMP_SOUTHEAST_INNER, TILE_SHAPE_RAMP_SOUTHWEST_INNER,
RAMP_CORNERS, tileIndex, buildTerrainVerts, buildGridLines,
});
})();
-64
View File
@@ -1,64 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
"use strict";
// DMF - Dusk Mesh Format
//
// Header (12 bytes):
// [0-3] "DMF\0" magic
// [4-7] uint32 version (little-endian)
// [8-11] uint32 vertCount (little-endian)
//
// Followed by vertCount vertices, each 20 bytes:
// [0-7] float32[2] uv (little-endian)
// [8-19] float32[3] pos (little-endian)
const DMF = (() => {
const MAGIC = [0x44, 0x4d, 0x46, 0x00]; // "DMF\0"
const VERSION = 1;
const HEADER_SIZE = 12;
const VERTEX_FLOATS = 5; // uv[2] + pos[3]
const VERTEX_SIZE = VERTEX_FLOATS * 4;
// Decode a DMF ArrayBuffer into { version, vertexCount, floats }, where
// floats is a Float32Array of tightly interleaved [u, v, x, y, z] per
// vertex - ready to hand straight to gl.bufferData().
function decode(buffer) {
const bytes = new Uint8Array(buffer);
const view = new DataView(buffer);
if(bytes.length < HEADER_SIZE) throw new Error("File too small to be a valid DMF");
if(
bytes[0] !== MAGIC[0] || bytes[1] !== MAGIC[1] ||
bytes[2] !== MAGIC[2] || bytes[3] !== MAGIC[3]
) {
throw new Error("Invalid DMF magic bytes - not a DMF file");
}
const version = view.getUint32(4, true);
if(version !== VERSION) {
throw new Error(`Unsupported DMF version: ${version}`);
}
const vertexCount = view.getUint32(8, true);
const expected = HEADER_SIZE + vertexCount * VERTEX_SIZE;
if(bytes.length < expected) {
throw new Error(`DMF vertex data truncated (expected ${expected} bytes, got ${bytes.length})`);
}
const floats = new Float32Array(vertexCount * VERTEX_FLOATS);
for(let i = 0; i < floats.length; i++) {
floats[i] = view.getFloat32(HEADER_SIZE + i * 4, true);
}
return { version, vertexCount, floats };
}
return Object.freeze({
decode,
VERSION, HEADER_SIZE, VERTEX_FLOATS, VERTEX_SIZE,
});
})();
-6
View File
@@ -1,6 +0,0 @@
<div class="row">
<div class="col-12">
<h1>Dusk Map Editor</h1>
<p class="text-muted">Browse and edit project assets.</p>
</div>
</div>
-92
View File
@@ -1,92 +0,0 @@
<link rel="stylesheet" href="/map/map.css">
<div class="row g-3">
<div class="col-12">
<div class="d-flex flex-wrap align-items-end gap-2 mb-2">
<div>
<label class="form-label mb-0">X</label>
<input type="number" id="coordX" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<div>
<label class="form-label mb-0">Y</label>
<input type="number" id="coordY" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<div>
<label class="form-label mb-0">Z</label>
<input type="number" id="coordZ" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<button id="btnLoad" type="button" class="btn btn-sm btn-secondary">Load</button>
<div class="dropdown">
<button
class="btn btn-sm btn-outline-secondary dropdown-toggle"
type="button" data-bs-toggle="dropdown"
>Browse</button>
<ul class="dropdown-menu" id="chunkBrowseList"></ul>
</div>
<div class="dpad" title="Navigate to the neighboring chunk">
<button type="button" class="btn btn-sm btn-outline-secondary dpad-n" id="navN" title="North (+Y)">N</button>
<button type="button" class="btn btn-sm btn-outline-secondary dpad-w" id="navW" title="West (-X)">W</button>
<button type="button" class="btn btn-sm btn-outline-secondary dpad-e" id="navE" title="East (+X)">E</button>
<button type="button" class="btn btn-sm btn-outline-secondary dpad-s" id="navS" title="South (-Y)">S</button>
</div>
<div class="d-flex flex-column gap-1">
<button type="button" class="btn btn-sm btn-outline-secondary" id="navUp" title="Up (+Z)">Up</button>
<button type="button" class="btn btn-sm btn-outline-secondary" id="navDown" title="Down (-Z)">Down</button>
</div>
<button id="btnSave" type="button" class="btn btn-sm btn-primary ms-auto">
Save &amp; Compile
</button>
</div>
<div id="statusLine" class="small text-muted mb-2">&nbsp;</div>
</div>
<div class="col-12 col-lg-6">
<div class="d-flex align-items-center gap-2 mb-2">
<label class="form-label mb-0">Z-Level</label>
<button type="button" class="btn btn-sm btn-outline-secondary" id="zLevelDown">-</button>
<input type="range" id="zLevel" class="form-range" style="width:150px" min="0" max="3" value="0">
<button type="button" class="btn btn-sm btn-outline-secondary" id="zLevelUp">+</button>
<span id="zLevelLabel">0</span>
</div>
<div class="d-flex gap-3">
<div id="toolPalette" class="tile-palette"></div>
<div id="tilePalette" class="tile-palette"></div>
<canvas id="gridCanvas" class="border tile-grid" width="512" height="512"></canvas>
</div>
<h5 class="mt-3">Meshes</h5>
<ul id="meshList" class="list-group mb-2"></ul>
<div class="d-flex gap-2 align-items-end flex-wrap">
<div style="min-width:220px">
<label class="form-label mb-0">Model</label>
<select id="meshPicker" class="form-select form-select-sm"></select>
</div>
<div>
<label class="form-label mb-0">X</label>
<input id="meshX" type="number" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<div>
<label class="form-label mb-0">Y</label>
<input id="meshY" type="number" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<div>
<label class="form-label mb-0">Z</label>
<input id="meshZ" type="number" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<button id="btnAddMesh" type="button" class="btn btn-sm btn-outline-primary">Add</button>
</div>
</div>
<div class="col-12 col-lg-6">
<p class="small text-muted mb-2">Preview (scroll to zoom)</p>
<canvas id="previewCanvas" class="border" width="512" height="512"></canvas>
</div>
</div>
<script src="/common/dmf.js"></script>
<script src="/common/chunkterrain.js"></script>
<script src="/map/renderer.js"></script>
<script src="/map/map.js"></script>
-65
View File
@@ -1,65 +0,0 @@
/* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
.tile-palette {
display: flex;
flex-direction: column;
flex-wrap: wrap;
gap: 6px;
max-height: 600px;
}
.tile-swatch {
position: relative;
width: 32px;
height: 32px;
border: 2px solid transparent;
border-radius: 4px;
cursor: pointer;
padding: 0;
}
.tile-swatch.active {
border-color: #fff;
}
.tile-swatch-icon {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
}
.dpad {
display: grid;
grid-template-columns: repeat(3, 2rem);
grid-template-rows: repeat(3, 2rem);
grid-template-areas:
". n ."
"w . e"
". s .";
gap: 2px;
}
.dpad-n { grid-area: n; }
.dpad-w { grid-area: w; }
.dpad-e { grid-area: e; }
.dpad-s { grid-area: s; }
.dpad button { padding: 0; }
.tile-grid {
image-rendering: pixelated;
cursor: crosshair;
touch-action: none;
max-width: 100%;
height: auto;
}
#previewCanvas {
width: 100%;
aspect-ratio: 1 / 1;
height: auto;
}
-920
View File
@@ -1,920 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
"use strict";
(() => {
const SHAPES = [
{ type: ChunkTerrain.TILE_SHAPE_NULL, name: "Erase", color: "#20232a" },
{ type: ChunkTerrain.TILE_SHAPE_GROUND, name: "Ground", color: "#4caf50" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_NORTH, name: "Ramp North", color: "#2196f3" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_EAST, name: "Ramp East", color: "#03a9f4" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_SOUTH, name: "Ramp South", color: "#00bcd4" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_WEST, name: "Ramp West", color: "#009688" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_NORTHEAST, name: "Ramp NE", color: "#ff9800" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_NORTHWEST, name: "Ramp NW", color: "#ff5722" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_SOUTHEAST, name: "Ramp SE", color: "#9c27b0" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_SOUTHWEST, name: "Ramp SW", color: "#e91e63" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_NORTHEAST_INNER, name: "Ramp NE Inner", color: "#795548" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_NORTHWEST_INNER, name: "Ramp NW Inner", color: "#607d8b" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_SOUTHEAST_INNER, name: "Ramp SE Inner", color: "#8bc34a" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_SOUTHWEST_INNER, name: "Ramp SW Inner", color: "#ffc107" },
];
const SHAPE_COLORS = Object.fromEntries(SHAPES.map((s) => [s.type, s.color]));
// Arrow direction per ramp, in canvas/screen space: north is up (dy < 0),
// east is right (dx > 0) - matches renderGrid()'s north-is-up convention.
const SHAPE_DIRECTIONS = {
[ChunkTerrain.TILE_SHAPE_RAMP_NORTH]: { dx: 0, dy: -1 },
[ChunkTerrain.TILE_SHAPE_RAMP_SOUTH]: { dx: 0, dy: 1 },
[ChunkTerrain.TILE_SHAPE_RAMP_EAST]: { dx: 1, dy: 0 },
[ChunkTerrain.TILE_SHAPE_RAMP_WEST]: { dx: -1, dy: 0 },
[ChunkTerrain.TILE_SHAPE_RAMP_NORTHEAST]: { dx: 1, dy: -1 },
[ChunkTerrain.TILE_SHAPE_RAMP_NORTHWEST]: { dx: -1, dy: -1 },
[ChunkTerrain.TILE_SHAPE_RAMP_SOUTHEAST]: { dx: 1, dy: 1 },
[ChunkTerrain.TILE_SHAPE_RAMP_SOUTHWEST]: { dx: -1, dy: 1 },
[ChunkTerrain.TILE_SHAPE_RAMP_NORTHEAST_INNER]: { dx: 1, dy: -1 },
[ChunkTerrain.TILE_SHAPE_RAMP_NORTHWEST_INNER]: { dx: -1, dy: -1 },
[ChunkTerrain.TILE_SHAPE_RAMP_SOUTHEAST_INNER]: { dx: 1, dy: 1 },
[ChunkTerrain.TILE_SHAPE_RAMP_SOUTHWEST_INNER]: { dx: -1, dy: 1 },
};
const INNER_CORNER_SHAPES = new Set([
ChunkTerrain.TILE_SHAPE_RAMP_NORTHEAST_INNER,
ChunkTerrain.TILE_SHAPE_RAMP_NORTHWEST_INNER,
ChunkTerrain.TILE_SHAPE_RAMP_SOUTHEAST_INNER,
ChunkTerrain.TILE_SHAPE_RAMP_SOUTHWEST_INNER,
]);
// Draws a single-headed arrow from (tailX, tailY) to (tipX, tipY).
function drawArrowSegment(ctx, tailX, tailY, tipX, tipY, size) {
ctx.strokeStyle = "#ffffff";
ctx.fillStyle = "#ffffff";
ctx.lineWidth = Math.max(1, size * 0.08);
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(tailX, tailY);
ctx.lineTo(tipX, tipY);
ctx.stroke();
const headLen = size * 0.18;
const angle = Math.atan2(tipY - tailY, tipX - tailX);
const leftAngle = angle + Math.PI * 0.8;
const rightAngle = angle - Math.PI * 0.8;
ctx.beginPath();
ctx.moveTo(tipX, tipY);
ctx.lineTo(tipX + Math.cos(leftAngle) * headLen, tipY + Math.sin(leftAngle) * headLen);
ctx.lineTo(tipX + Math.cos(rightAngle) * headLen, tipY + Math.sin(rightAngle) * headLen);
ctx.closePath();
ctx.fill();
}
// Draws an arrow centered at (cx, cy) pointing toward the ramp's high
// side, so ramp direction is visible at a glance on both the palette
// swatches and the tile grid. Used for cardinal ramps and outer-corner
// ramps (a single raised corner).
function drawArrow(ctx, cx, cy, size, dx, dy) {
const mag = Math.hypot(dx, dy) || 1;
const ux = dx / mag, uy = dy / mag;
const len = size * 0.32;
drawArrowSegment(ctx, cx - ux * len, cy - uy * len, cx + ux * len, cy + uy * len, size);
}
// Draws a plain right-angle bracket - two line segments meeting at 90
// degrees at the tile's corner, one running along each of the two edges
// adjacent to it - so inner-corner ramps (three corners raised, one
// dropped) read as "the adjacent sides meeting in a 90-degree corner",
// distinct from the single diagonal arrow used for outer-corner ramps.
function drawCornerBracket(ctx, cx, cy, size, dx, dy) {
const cornerDist = size * 0.42;
const armLen = size * 0.34;
const cornerX = cx + dx * cornerDist;
const cornerY = cy + dy * cornerDist;
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = Math.max(1, size * 0.08);
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(cornerX - dx * armLen, cornerY);
ctx.lineTo(cornerX, cornerY);
ctx.lineTo(cornerX, cornerY - dy * armLen);
ctx.stroke();
}
// Draws the direction icon for a ramp tile `type` in a `size`x`size` area
// centered at (cx, cy): a diagonal arrow for cardinal/outer-corner ramps,
// or a right-angle bracket for inner-corner ramps. No-op for shapes with
// no direction (ground, erase).
function drawShapeIcon(ctx, cx, cy, size, type) {
const dir = SHAPE_DIRECTIONS[type];
if(!dir) return;
if(INNER_CORNER_SHAPES.has(type)) {
drawCornerBracket(ctx, cx, cy, size, dir.dx, dir.dy);
} else {
drawArrow(ctx, cx, cy, size, dir.dx, dir.dy);
}
}
// Draws a small pencil icon centered in a `size`x`size` canvas.
function drawPencilIcon(ctx, size) {
ctx.save();
ctx.translate(size / 2, size / 2);
ctx.rotate(-Math.PI / 4);
const shaftW = size * 0.18;
const shaftH = size * 0.62;
ctx.fillStyle = "#e0e0e0";
ctx.fillRect(-shaftW / 2, shaftH * 0.28, shaftW, shaftH * 0.22);
ctx.fillStyle = "#f0c419";
ctx.fillRect(-shaftW / 2, -shaftH * 0.5, shaftW, shaftH * 0.78);
ctx.fillStyle = "#8d6e63";
ctx.beginPath();
ctx.moveTo(-shaftW / 2, -shaftH * 0.5);
ctx.lineTo(shaftW / 2, -shaftH * 0.5);
ctx.lineTo(0, -shaftH * 0.5 - shaftW);
ctx.closePath();
ctx.fill();
ctx.restore();
}
// Draws a small paint bucket icon centered in a `size`x`size` canvas.
function drawBucketIcon(ctx, size) {
ctx.save();
ctx.translate(size / 2, size / 2);
const w = size * 0.5, h = size * 0.34;
ctx.strokeStyle = "#e0e0e0";
ctx.lineWidth = Math.max(1, size * 0.06);
ctx.beginPath();
ctx.arc(0, -h * 0.4, w * 0.4, Math.PI, 0);
ctx.stroke();
ctx.fillStyle = "#03a9f4";
ctx.beginPath();
ctx.moveTo(-w / 2, -h * 0.2);
ctx.lineTo(w / 2, -h * 0.2);
ctx.lineTo(w * 0.32, h * 0.6);
ctx.lineTo(-w * 0.32, h * 0.6);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.arc(-w * 0.55, h * 0.75, size * 0.06, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
const TOOLS = [
{ id: "pencil", name: "Pencil", draw: drawPencilIcon },
{ id: "bucket", name: "Paint Bucket", draw: drawBucketIcon },
];
let coord = { x: 0, y: 0, z: 0 };
let tiles = new Int32Array(ChunkTerrain.TILE_COUNT);
let meshes = [];
let chunkExists = false;
let currentZLevel = 0;
let selectedShape = ChunkTerrain.TILE_SHAPE_GROUND;
let zoomWorldH = 20;
let dirty = false;
let hoverTile = null;
let activeTool = "pencil";
let mapRenderer = null;
let terrainMesh = null;
let gridLinesMesh = null;
let terrainTexturePromise = null;
let modelIndex = null;
let neighborChunks = [];
const modelCache = new Map();
const UNDO_LIMIT = 100;
let undoStack = [];
function markDirty() {
dirty = true;
}
function snapshotState() {
return {
tiles: tiles.slice(),
meshes: meshes.map((m) => ({ file: m.file, pos: m.pos.slice() })),
};
}
function pushUndo() {
undoStack.push(snapshotState());
if(undoStack.length > UNDO_LIMIT) undoStack.shift();
}
function undo() {
if(!undoStack.length) return;
const snap = undoStack.pop();
tiles = snap.tiles;
meshes = snap.meshes;
dirty = true;
renderGrid();
renderMeshList();
renderPreview();
updateStatus("Undid last change.");
}
// Returns true if it's OK to proceed (no unsaved changes, or the user
// confirmed discarding them).
function confirmDiscardIfDirty() {
if(!dirty) return true;
return window.confirm("You have unsaved changes to this chunk. Discard them?");
}
function statusLine() {
return document.getElementById("statusLine");
}
function updateStatus(msg, isError) {
const el = statusLine();
el.textContent = msg;
el.classList.toggle("text-danger", !!isError);
el.classList.toggle("text-muted", !isError);
}
async function apiReadJson(path) {
const res = await fetch(`/api/read?path=${encodeURIComponent(path)}`);
const data = await res.json();
return { ok: res.ok, data };
}
async function apiWrite(path, content) {
return fetch(`/api/write?path=${encodeURIComponent(path)}`, {
method: "POST",
body: JSON.stringify({ content }),
});
}
async function apiDelete(path) {
return fetch(`/api/delete?path=${encodeURIComponent(path)}`, { method: "POST" });
}
async function apiCompileChunk(x, y, z) {
const res = await fetch(`/api/compile-chunk?x=${x}&y=${y}&z=${z}`, { method: "POST" });
return res.json();
}
async function apiLs(path) {
const res = await fetch(`/api/ls?path=${encodeURIComponent(path)}`);
return res.json();
}
async function apiFind(path, ext) {
const res = await fetch(`/api/find?path=${encodeURIComponent(path)}&ext=${encodeURIComponent(ext)}`);
return res.json();
}
function base64ToBuffer(base64) {
const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
return bytes.buffer;
}
async function loadImageTexture(assetPath) {
const { ok, data } = await apiReadJson(assetPath);
if(!ok || data.error) return null;
const blob = new Blob([base64ToBuffer(data.content)], { type: "image/png" });
const bitmap = await createImageBitmap(blob);
return mapRenderer.createTextureFromImage(bitmap);
}
async function readDmfVertices(assetPath) {
const { ok, data } = await apiReadJson(assetPath);
if(!ok || data.error) throw new Error(`Failed to read ${assetPath}`);
return DMF.decode(base64ToBuffer(data.content)).floats;
}
async function ensureModelIndex() {
if(modelIndex) return modelIndex;
const res = await apiFind("assets/models", ".json");
modelIndex = new Map();
for(const file of res.files || []) {
const base = file.split("/").pop().replace(/\.json$/, "");
modelIndex.set(base, file);
}
return modelIndex;
}
// Scales a mesh's stored [x, y, z] offset for preview, matching the
// Z scaling mapChunkLoaded() applies at runtime (chunk.meshOffsets[m][2]
// * WORLD_LAYER_HEIGHT) - x/y stay 1:1 since only Z is height-scaled.
function scaledMeshOffset(pos) {
return [pos[0], pos[1], pos[2] * ChunkTerrain.WORLD_LAYER_HEIGHT];
}
// Resolves a chunk mesh entry's bare filename (e.g. "house_5_3.dmf") to
// its model JSON by basename, mirroring find_model() in
// tools/asset/chunk/__main__.py - the chunk JSON only ever stores a bare
// filename, not a path.
async function resolveModelForMeshFile(file) {
await ensureModelIndex();
const base = file.replace(/\.[^.]+$/, "");
const rel = modelIndex.get(base);
if(!rel) return null;
const modelPath = `assets/models/${rel}`;
if(modelCache.has(modelPath)) return modelCache.get(modelPath);
const promise = (async () => {
const { ok, data } = await apiReadJson(modelPath);
if(!ok || data.error) throw new Error(`Failed to read model ${modelPath}`);
const modelDef = JSON.parse(data.content);
const meshFloats = await readDmfVertices(`assets/${modelDef.mesh}`);
const mesh = mapRenderer.createMesh(meshFloats);
const texture = modelDef.texture ? await loadImageTexture(`assets/${modelDef.texture}`) : null;
const colorBytes = modelDef.color || [255, 255, 255, 255];
const color = colorBytes.map((c) => c / 255);
return { mesh, texture, color };
})();
modelCache.set(modelPath, promise);
return promise;
}
const MAP_NAME = "overworld";
function chunkPaths(x, y, z) {
return {
raw: `assetsraw/maps/${MAP_NAME}/chunks/chunk_${x}_${y}_${z}.json`,
dcf: `assets/maps/${MAP_NAME}/chunks/${x}_${y}_${z}.dcf`,
terrainDmf: `assets/maps/${MAP_NAME}/meshes/chunks/chunk_${x}_${y}_${z}_0.dmf`,
terrainModel: `assets/maps/${MAP_NAME}/models/chunks/chunk_${x}_${y}_${z}_0.json`,
};
}
// Loads the 8 same-Z neighbors around `coord` (read-only, for context in
// the 3D preview) and pre-builds their render data so renderPreview()
// doesn't have to rebuild GL buffers on every paint stroke.
async function loadNeighborChunks() {
const offsets = [];
for(let dy = -1; dy <= 1; dy++) {
for(let dx = -1; dx <= 1; dx++) {
if(dx || dy) offsets.push({ dx, dy });
}
}
const results = await Promise.all(offsets.map(async ({ dx, dy }) => {
const nx = coord.x + dx, ny = coord.y + dy, nz = coord.z;
const { ok, data } = await apiReadJson(chunkPaths(nx, ny, nz).raw);
if(!ok || data.error) return null;
const json = JSON.parse(data.content);
const neighborTiles = new Int32Array(ChunkTerrain.TILE_COUNT);
for(const t of json.tiles || []) {
const [tx, ty, tz] = t.pos;
neighborTiles[ChunkTerrain.tileIndex(tx, ty, tz)] = t.type;
}
const neighborMeshes = (json.meshes || []).map((m) => ({ file: m.file, pos: m.pos || [0, 0, 0] }));
const floats = ChunkTerrain.buildTerrainVerts(neighborTiles);
const terrain = floats.length ? { mesh: mapRenderer.createMesh(floats) } : null;
const models = [];
for(const m of neighborMeshes) {
try {
const resolved = await resolveModelForMeshFile(m.file);
if(resolved) models.push({ ...resolved, offset: scaledMeshOffset(m.pos) });
} catch(e) {
console.warn("Failed to load neighbor mesh preview", m.file, e);
}
}
return {
offset: [dx * ChunkTerrain.CHUNK_WIDTH, dy * ChunkTerrain.CHUNK_HEIGHT, 0],
terrain,
models,
};
}));
neighborChunks = results.filter(Boolean);
}
async function loadChunk(x, y, z) {
coord = { x, y, z };
tiles = new Int32Array(ChunkTerrain.TILE_COUNT);
meshes = [];
chunkExists = false;
const { ok, data } = await apiReadJson(chunkPaths(x, y, z).raw);
if(ok && !data.error) {
chunkExists = true;
const json = JSON.parse(data.content);
for(const t of json.tiles || []) {
const [tx, ty, tz] = t.pos;
tiles[ChunkTerrain.tileIndex(tx, ty, tz)] = t.type;
}
meshes = (json.meshes || []).map((m) => ({ file: m.file, pos: m.pos || [0, 0, 0] }));
}
await loadNeighborChunks();
dirty = false;
undoStack = [];
renderGrid();
renderMeshList();
renderPreview();
updateStatus(chunkExists
? `Loaded chunk_${x}_${y}_${z}.json`
: `New (empty) chunk at ${x}, ${y}, ${z} - paint a tile and save to create it.`);
}
async function saveChunk() {
const tilesArr = [];
for(let z = 0; z < ChunkTerrain.CHUNK_DEPTH; z++) {
for(let y = 0; y < ChunkTerrain.CHUNK_HEIGHT; y++) {
for(let x = 0; x < ChunkTerrain.CHUNK_WIDTH; x++) {
const type = tiles[ChunkTerrain.tileIndex(x, y, z)];
if(type && type !== ChunkTerrain.TILE_SHAPE_NULL) {
tilesArr.push({ pos: [x, y, z], type, tile: 0 });
}
}
}
}
const paths = chunkPaths(coord.x, coord.y, coord.z);
if(tilesArr.length === 0 && meshes.length === 0) {
await Promise.all(Object.values(paths).map((p) => apiDelete(p)));
chunkExists = false;
dirty = false;
updateStatus(`Chunk ${coord.x}, ${coord.y}, ${coord.z} is empty - deleted.`);
return;
}
const json = { tiles: tilesArr, meshes: meshes.map((m) => ({ file: m.file, pos: m.pos })) };
await apiWrite(paths.raw, JSON.stringify(json, null, 2));
chunkExists = true;
dirty = false;
updateStatus("Saved. Compiling...");
const result = await apiCompileChunk(coord.x, coord.y, coord.z);
if(result.ok) {
updateStatus(`Compiled OK.\n${result.stdout}`);
} else {
updateStatus(`Compile FAILED (code ${result.returncode}):\n${result.stderr}`, true);
}
}
function buildPalette() {
const el = document.getElementById("tilePalette");
el.innerHTML = "";
for(const s of SHAPES) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "tile-swatch" + (s.type === selectedShape ? " active" : "");
btn.style.background = s.color;
btn.title = s.name;
btn.addEventListener("click", () => {
selectedShape = s.type;
buildPalette();
});
if(SHAPE_DIRECTIONS[s.type]) {
const icon = document.createElement("canvas");
icon.width = 32;
icon.height = 32;
icon.className = "tile-swatch-icon";
drawShapeIcon(icon.getContext("2d"), 16, 16, 32, s.type);
btn.appendChild(icon);
}
el.appendChild(btn);
}
}
function buildToolPalette() {
const el = document.getElementById("toolPalette");
el.innerHTML = "";
for(const tool of TOOLS) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "tile-swatch" + (tool.id === activeTool ? " active" : "");
btn.style.background = "#2a2d33";
btn.title = tool.name;
btn.addEventListener("click", () => {
activeTool = tool.id;
buildToolPalette();
});
const icon = document.createElement("canvas");
icon.width = 32;
icon.height = 32;
icon.className = "tile-swatch-icon";
tool.draw(icon.getContext("2d"), 32);
btn.appendChild(icon);
el.appendChild(btn);
}
}
function canvasToTile(e, canvas) {
const rect = canvas.getBoundingClientRect();
const cell = canvas.width / ChunkTerrain.CHUNK_WIDTH;
const px = (e.clientX - rect.left) * (canvas.width / rect.width);
const py = (e.clientY - rect.top) * (canvas.height / rect.height);
const x = Math.floor(px / cell);
const yFromTop = Math.floor(py / cell);
const y = ChunkTerrain.CHUNK_HEIGHT - 1 - yFromTop;
if(x < 0 || x >= ChunkTerrain.CHUNK_WIDTH || y < 0 || y >= ChunkTerrain.CHUNK_HEIGHT) return null;
return { x, y };
}
function renderGrid() {
const canvas = document.getElementById("gridCanvas");
const ctx = canvas.getContext("2d");
const cell = canvas.width / ChunkTerrain.CHUNK_WIDTH;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(let y = 0; y < ChunkTerrain.CHUNK_HEIGHT; y++) {
for(let x = 0; x < ChunkTerrain.CHUNK_WIDTH; x++) {
const type = tiles[ChunkTerrain.tileIndex(x, y, currentZLevel)];
const sy = (ChunkTerrain.CHUNK_HEIGHT - 1 - y) * cell;
ctx.fillStyle = SHAPE_COLORS[type] || "#15171b";
ctx.fillRect(x * cell, sy, cell, cell);
ctx.strokeStyle = "rgba(255, 255, 255, 0.25)";
ctx.strokeRect(x * cell, sy, cell, cell);
drawShapeIcon(ctx, x * cell + cell / 2, sy + cell / 2, cell, type);
}
}
ctx.fillStyle = "#ffffff";
for(const m of meshes) {
const [mx, my, mz] = m.pos;
if(Math.round(mz) !== currentZLevel) continue;
const sy = (ChunkTerrain.CHUNK_HEIGHT - 1 - my) * cell;
ctx.beginPath();
ctx.arc(mx * cell + cell / 2, sy + cell / 2, cell * 0.3, 0, Math.PI * 2);
ctx.fill();
}
if(hoverTile) {
const sy = (ChunkTerrain.CHUNK_HEIGHT - 1 - hoverTile.y) * cell;
ctx.strokeStyle = "#ffeb3b";
ctx.lineWidth = 2;
ctx.strokeRect(hoverTile.x * cell + 1, sy + 1, cell - 2, cell - 2);
}
}
function hitTestMesh(e, canvas) {
const rect = canvas.getBoundingClientRect();
const cell = canvas.width / ChunkTerrain.CHUNK_WIDTH;
const px = (e.clientX - rect.left) * (canvas.width / rect.width);
const py = (e.clientY - rect.top) * (canvas.height / rect.height);
let closest = -1;
let closestDist = cell * 0.5;
meshes.forEach((m, i) => {
const [mx, my, mz] = m.pos;
if(Math.round(mz) !== currentZLevel) return;
const cx = mx * cell + cell / 2;
const cy = (ChunkTerrain.CHUNK_HEIGHT - 1 - my) * cell + cell / 2;
const dist = Math.hypot(px - cx, py - cy);
if(dist < closestDist) { closestDist = dist; closest = i; }
});
return closest;
}
function moveMeshTo(e, index) {
const canvas = document.getElementById("gridCanvas");
const t = canvasToTile(e, canvas);
if(!t) return;
meshes[index].pos[0] = t.x;
meshes[index].pos[1] = t.y;
markDirty();
renderGrid();
renderMeshList();
renderPreview();
}
function paintAt(e) {
const canvas = document.getElementById("gridCanvas");
const t = canvasToTile(e, canvas);
if(!t) return;
tiles[ChunkTerrain.tileIndex(t.x, t.y, currentZLevel)] = selectedShape;
markDirty();
renderGrid();
renderPreview();
}
// 4-connected flood fill of same-type tiles at the current Z-level,
// starting from (startX, startY), replacing them with selectedShape.
function floodFill(startX, startY) {
const targetType = tiles[ChunkTerrain.tileIndex(startX, startY, currentZLevel)];
if(targetType === selectedShape) return;
const stack = [[startX, startY]];
const visited = new Set();
while(stack.length) {
const [x, y] = stack.pop();
const key = `${x},${y}`;
if(visited.has(key)) continue;
if(x < 0 || x >= ChunkTerrain.CHUNK_WIDTH || y < 0 || y >= ChunkTerrain.CHUNK_HEIGHT) continue;
visited.add(key);
const idx = ChunkTerrain.tileIndex(x, y, currentZLevel);
if(tiles[idx] !== targetType) continue;
tiles[idx] = selectedShape;
stack.push([x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]);
}
}
function fillAt(e) {
const canvas = document.getElementById("gridCanvas");
const t = canvasToTile(e, canvas);
if(!t) return;
pushUndo();
floodFill(t.x, t.y);
markDirty();
renderGrid();
renderPreview();
}
function rebuildTerrainMesh() {
const floats = ChunkTerrain.buildTerrainVerts(tiles);
terrainMesh = floats.length ? mapRenderer.createMesh(floats) : null;
const lineFloats = ChunkTerrain.buildGridLines(tiles);
gridLinesMesh = lineFloats.length ? mapRenderer.createMesh(lineFloats) : null;
}
// Keeps the preview canvas's backing-store resolution matched to its
// actual displayed CSS size (times devicePixelRatio) - the canvas
// otherwise stays at its fixed width/height attributes (512x512) while
// CSS stretches it to fill the column, which upscales and blurs the
// WebGL output on wider or high-DPI screens.
function resizePreviewCanvas() {
const canvas = document.getElementById("previewCanvas");
const dpr = window.devicePixelRatio || 1;
const displayWidth = Math.max(1, Math.round(canvas.clientWidth * dpr));
const displayHeight = Math.max(1, Math.round(canvas.clientHeight * dpr));
if(canvas.width !== displayWidth || canvas.height !== displayHeight) {
canvas.width = displayWidth;
canvas.height = displayHeight;
}
}
async function renderPreview() {
if(!mapRenderer) return;
resizePreviewCanvas();
rebuildTerrainMesh();
const models = [];
for(const m of meshes) {
try {
const resolved = await resolveModelForMeshFile(m.file);
if(resolved) models.push({ ...resolved, offset: scaledMeshOffset(m.pos) });
} catch(e) {
console.warn("Failed to load mesh preview", m.file, e);
}
}
let terrainTexture = null;
if(terrainMesh || neighborChunks.some((n) => n.terrain)) {
if(!terrainTexturePromise) terrainTexturePromise = loadImageTexture("assets/tiles.png");
terrainTexture = await terrainTexturePromise;
}
const neighbors = neighborChunks.map((n) => ({
offset: n.offset,
terrain: n.terrain ? { mesh: n.terrain.mesh, texture: terrainTexture } : null,
models: n.models,
}));
const zLevelHeight = currentZLevel * ChunkTerrain.WORLD_LAYER_HEIGHT;
mapRenderer.render({
target: [ChunkTerrain.CHUNK_WIDTH / 2, ChunkTerrain.CHUNK_HEIGHT / 2, zLevelHeight],
worldH: zoomWorldH,
terrain: terrainMesh ? { mesh: terrainMesh, texture: terrainTexture } : null,
gridLines: gridLinesMesh ? { mesh: gridLinesMesh } : null,
models,
neighbors,
highlight: hoverTile ? { x: hoverTile.x, y: hoverTile.y, z: zLevelHeight } : null,
});
}
function renderMeshList() {
const ul = document.getElementById("meshList");
ul.innerHTML = "";
meshes.forEach((m, i) => {
const li = document.createElement("li");
li.className = "list-group-item d-flex align-items-center gap-2 flex-wrap";
const label = document.createElement("span");
label.className = "me-auto";
label.textContent = m.file;
li.appendChild(label);
["X", "Y", "Z"].forEach((axis, axisIndex) => {
const input = document.createElement("input");
input.type = "number";
input.className = "form-control form-control-sm";
input.style.width = "5rem";
input.title = axis;
input.value = m.pos[axisIndex];
input.addEventListener("change", () => {
pushUndo();
m.pos[axisIndex] = parseFloat(input.value) || 0;
markDirty();
renderGrid();
renderPreview();
});
li.appendChild(input);
});
const btn = document.createElement("button");
btn.type = "button";
btn.className = "btn btn-sm btn-outline-danger";
btn.textContent = "Remove";
btn.addEventListener("click", () => {
pushUndo();
meshes.splice(i, 1);
markDirty();
renderMeshList();
renderGrid();
renderPreview();
});
li.appendChild(btn);
ul.appendChild(li);
});
}
async function buildMeshPicker() {
await ensureModelIndex();
const select = document.getElementById("meshPicker");
select.innerHTML = "";
for(const [base, rel] of [...modelIndex.entries()].sort()) {
const opt = document.createElement("option");
opt.value = base;
opt.textContent = rel;
select.appendChild(opt);
}
}
async function buildChunkBrowseList() {
const list = document.getElementById("chunkBrowseList");
list.innerHTML = "";
const res = await apiLs(`assetsraw/maps/${MAP_NAME}/chunks`);
for(const entry of res.entries || []) {
const m = entry.name.match(/^chunk_(-?\d+)_(-?\d+)_(-?\d+)\.json$/);
if(!m) continue;
const [, x, y, z] = m;
const li = document.createElement("li");
const a = document.createElement("a");
a.className = "dropdown-item";
a.href = "#";
a.textContent = `${x}, ${y}, ${z}`;
a.addEventListener("click", (e) => {
e.preventDefault();
goToChunk(parseInt(x, 10), parseInt(y, 10), parseInt(z, 10));
});
li.appendChild(a);
list.appendChild(li);
}
}
function setCoordInputs(x, y, z) {
document.getElementById("coordX").value = x;
document.getElementById("coordY").value = y;
document.getElementById("coordZ").value = z;
}
function goToChunk(x, y, z) {
if(!confirmDiscardIfDirty()) return;
setCoordInputs(x, y, z);
loadChunk(x, y, z);
}
function bindEvents() {
const gridCanvas = document.getElementById("gridCanvas");
let painting = false;
let draggingMeshIndex = -1;
gridCanvas.addEventListener("mousedown", (e) => {
if(activeTool === "bucket") {
fillAt(e);
return;
}
const hit = hitTestMesh(e, gridCanvas);
pushUndo();
if(hit !== -1) {
draggingMeshIndex = hit;
return;
}
painting = true;
paintAt(e);
});
window.addEventListener("mouseup", () => { painting = false; draggingMeshIndex = -1; });
gridCanvas.addEventListener("mousemove", (e) => {
hoverTile = canvasToTile(e, gridCanvas);
if(draggingMeshIndex !== -1) { moveMeshTo(e, draggingMeshIndex); return; }
if(painting) { paintAt(e); return; }
renderGrid();
renderPreview();
});
gridCanvas.addEventListener("mouseleave", () => {
hoverTile = null;
renderGrid();
renderPreview();
});
function setZLevel(z) {
currentZLevel = Math.max(0, Math.min(ChunkTerrain.CHUNK_DEPTH - 1, z));
document.getElementById("zLevel").value = currentZLevel;
document.getElementById("zLevelLabel").textContent = currentZLevel;
renderGrid();
renderPreview();
}
document.getElementById("zLevel").addEventListener("input", (e) => {
setZLevel(parseInt(e.target.value, 10));
});
document.getElementById("zLevelDown").addEventListener("click", () => setZLevel(currentZLevel - 1));
document.getElementById("zLevelUp").addEventListener("click", () => setZLevel(currentZLevel + 1));
document.getElementById("btnLoad").addEventListener("click", () => {
const x = parseInt(document.getElementById("coordX").value, 10) || 0;
const y = parseInt(document.getElementById("coordY").value, 10) || 0;
const z = parseInt(document.getElementById("coordZ").value, 10) || 0;
goToChunk(x, y, z);
});
// NORTH=+Y, EAST=+X (matches tile-shape convention used by the tile
// grid and tools/asset/chunk/__main__.py).
document.getElementById("navN").addEventListener("click", () => goToChunk(coord.x, coord.y + 1, coord.z));
document.getElementById("navS").addEventListener("click", () => goToChunk(coord.x, coord.y - 1, coord.z));
document.getElementById("navE").addEventListener("click", () => goToChunk(coord.x + 1, coord.y, coord.z));
document.getElementById("navW").addEventListener("click", () => goToChunk(coord.x - 1, coord.y, coord.z));
document.getElementById("navUp").addEventListener("click", () => goToChunk(coord.x, coord.y, coord.z + 1));
document.getElementById("navDown").addEventListener("click", () => goToChunk(coord.x, coord.y, coord.z - 1));
function runSave() {
saveChunk().catch((e) => updateStatus(`Save failed: ${e.message}`, true));
}
document.getElementById("btnSave").addEventListener("click", runSave);
document.getElementById("btnAddMesh").addEventListener("click", () => {
const base = document.getElementById("meshPicker").value;
if(!base) return;
const pos = [
parseFloat(document.getElementById("meshX").value) || 0,
parseFloat(document.getElementById("meshY").value) || 0,
parseFloat(document.getElementById("meshZ").value) || 0,
];
pushUndo();
meshes.push({ file: `${base}.dmf`, pos });
markDirty();
renderMeshList();
renderGrid();
renderPreview();
});
document.getElementById("previewCanvas").addEventListener("wheel", (e) => {
e.preventDefault();
zoomWorldH = Math.min(60, Math.max(4, zoomWorldH + Math.sign(e.deltaY)));
renderPreview();
}, { passive: false });
window.addEventListener("resize", () => renderPreview());
window.addEventListener("keydown", (e) => {
if(!(e.ctrlKey || e.metaKey)) return;
const key = e.key.toLowerCase();
if(key === "z") {
e.preventDefault();
undo();
} else if(key === "s") {
e.preventDefault();
runSave();
}
});
}
document.addEventListener("DOMContentLoaded", async () => {
buildPalette();
buildToolPalette();
mapRenderer = MapRenderer.create(document.getElementById("previewCanvas"));
bindEvents();
await Promise.all([buildChunkBrowseList(), buildMeshPicker()]);
await loadChunk(coord.x, coord.y, coord.z);
});
})();
-298
View File
@@ -1,298 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
"use strict";
// MapRenderer - a minimal, dependency-free WebGL renderer for the chunk
// preview pane. The camera formula is ported 1:1 from
// src/dusk/scene/overworld/sceneoverworld.c (lines 62-81) so the preview
// approximates the game's own fixed-angle 3rd-person camera: the eye sits
// worldH units "behind" the target along Y and a proportional distance
// "above" along Z, always looking at the target, up = (0, 1, 0).
//
// The material model mirrors SHADER_UNLIT: a texture sampler multiplied by
// a flat RGBA tint, with a 1x1 white fallback texture standing in for
// untextured models.
const MapRenderer = (() => {
const VERT_SRC = `
attribute vec2 aUV;
attribute vec3 aPos;
uniform mat4 uModel;
uniform mat4 uView;
uniform mat4 uProjection;
varying vec2 vUV;
void main() {
vUV = aUV;
gl_Position = uProjection * uView * uModel * vec4(aPos, 1.0);
}
`;
const FRAG_SRC = `
precision mediump float;
varying vec2 vUV;
uniform sampler2D uTexture;
uniform vec4 uColor;
void main() {
gl_FragColor = texture2D(uTexture, vUV) * uColor;
}
`;
function mat4Identity(out) {
out.fill(0);
out[0] = out[5] = out[10] = out[15] = 1;
return out;
}
function mat4Translation(out, v) {
mat4Identity(out);
out[12] = v[0];
out[13] = v[1];
out[14] = v[2];
return out;
}
function mat4Perspective(out, fovy, aspect, near, far) {
const f = 1.0 / Math.tan(fovy / 2);
out.fill(0);
out[0] = f / aspect;
out[5] = f;
out[10] = (far + near) / (near - far);
out[11] = -1;
out[14] = (2 * far * near) / (near - far);
return out;
}
function vec3Sub(a, b) {
return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
}
function vec3Cross(a, b) {
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
}
function vec3Normalize(a) {
const len = Math.hypot(a[0], a[1], a[2]) || 1;
return [a[0] / len, a[1] / len, a[2] / len];
}
function mat4LookAt(out, eye, center, up) {
const zAxis = vec3Normalize(vec3Sub(eye, center));
const xAxis = vec3Normalize(vec3Cross(up, zAxis));
const yAxis = vec3Cross(zAxis, xAxis);
out[0] = xAxis[0]; out[1] = yAxis[0]; out[2] = zAxis[0]; out[3] = 0;
out[4] = xAxis[1]; out[5] = yAxis[1]; out[6] = zAxis[1]; out[7] = 0;
out[8] = xAxis[2]; out[9] = yAxis[2]; out[10] = zAxis[2]; out[11] = 0;
out[12] = -(xAxis[0] * eye[0] + xAxis[1] * eye[1] + xAxis[2] * eye[2]);
out[13] = -(yAxis[0] * eye[0] + yAxis[1] * eye[1] + yAxis[2] * eye[2]);
out[14] = -(zAxis[0] * eye[0] + zAxis[1] * eye[1] + zAxis[2] * eye[2]);
out[15] = 1;
return out;
}
// Ported from sceneoverworld.c:62-81. Returns { eye, view }.
function computeCamera(target, worldH) {
const fov = Math.PI / 4; // glm_rad(45.0f)
const zDist = (worldH * 0.5) / Math.tan(fov * 0.5);
const offset = -worldH;
const eye = [target[0], target[1] + offset, target[2] + zDist];
const view = mat4LookAt(new Float32Array(16), eye, target, [0, 1, 0]);
return { eye, view, fov };
}
function compileShader(gl, type, src) {
const shader = gl.createShader(type);
gl.shaderSource(shader, src);
gl.compileShader(shader);
if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
const info = gl.getShaderInfoLog(shader);
gl.deleteShader(shader);
throw new Error(`Shader compile failed: ${info}`);
}
return shader;
}
function create(canvas) {
const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
if(!gl) throw new Error("WebGL is not available in this browser");
const program = gl.createProgram();
gl.attachShader(program, compileShader(gl, gl.VERTEX_SHADER, VERT_SRC));
gl.attachShader(program, compileShader(gl, gl.FRAGMENT_SHADER, FRAG_SRC));
gl.linkProgram(program);
if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error(`Program link failed: ${gl.getProgramInfoLog(program)}`);
}
const attribs = {
aUV: gl.getAttribLocation(program, "aUV"),
aPos: gl.getAttribLocation(program, "aPos"),
};
const uniforms = {
uModel: gl.getUniformLocation(program, "uModel"),
uView: gl.getUniformLocation(program, "uView"),
uProjection: gl.getUniformLocation(program, "uProjection"),
uTexture: gl.getUniformLocation(program, "uTexture"),
uColor: gl.getUniformLocation(program, "uColor"),
};
const whiteTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, whiteTexture);
gl.texImage2D(
gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,
new Uint8Array([255, 255, 255, 255]),
);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
// Terrain/mesh winding isn't guaranteed consistent relative to this
// preview's fixed camera angle, so backface culling stays off - this
// is an authoring preview, not a performance-sensitive renderer, and
// an invisible mesh is a worse failure mode than a visible backface.
// Uploads interleaved [u, v, x, y, z] float data (DMF/terrain layout)
// into a GL buffer. Returns { buffer, vertexCount }.
function createMesh(floats) {
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, floats, gl.STATIC_DRAW);
return { buffer, vertexCount: floats.length / 5 };
}
function createTextureFromImage(image) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return texture;
}
function drawMesh(mesh, model, texture, color, depthWrite, mode) {
gl.depthMask(depthWrite !== false);
gl.bindBuffer(gl.ARRAY_BUFFER, mesh.buffer);
gl.enableVertexAttribArray(attribs.aUV);
gl.vertexAttribPointer(attribs.aUV, 2, gl.FLOAT, false, 20, 0);
gl.enableVertexAttribArray(attribs.aPos);
gl.vertexAttribPointer(attribs.aPos, 3, gl.FLOAT, false, 20, 8);
gl.uniformMatrix4fv(uniforms.uModel, false, model);
gl.uniform4f(uniforms.uColor, color[0], color[1], color[2], color[3]);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture || whiteTexture);
gl.uniform1i(uniforms.uTexture, 0);
gl.drawArrays(mode || gl.TRIANGLES, 0, mesh.vertexCount);
}
// Builds a 4-vertex outline of the tile at (x, y, z), lifted slightly
// to avoid z-fighting with the terrain surface beneath it.
function buildHighlightMesh(x, y, z) {
const eps = 0.02;
return createMesh(new Float32Array([
0, 0, x, y, z + eps,
0, 0, x + 1, y, z + eps,
0, 0, x + 1, y + 1, z + eps,
0, 0, x, y + 1, z + eps,
]));
}
// Neighboring chunks are drawn dimmer and semi-transparent, so they
// read as context rather than part of the chunk being edited.
const NEIGHBOR_ALPHA = 0.35;
const NEIGHBOR_DARKEN = 0.5;
// scene = {
// target: [x, y, z], worldH: number,
// terrain: { mesh, texture } | null,
// gridLines: { mesh } | null,
// models: [{ mesh, texture, color: [r,g,b,a in 0..1], offset: [x,y,z] }],
// neighbors: [{
// offset: [x,y,z],
// terrain: { mesh, texture } | null,
// models: [{ mesh, texture, color, offset }],
// }],
// highlight: { x, y, z } | null,
// }
function render(scene) {
const width = canvas.width, height = canvas.height;
gl.viewport(0, 0, width, height);
gl.clearColor(0.16, 0.18, 0.22, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.useProgram(program);
gl.depthMask(true);
const { view, fov } = computeCamera(scene.target, scene.worldH);
const projection = mat4Perspective(new Float32Array(16), fov, width / height, 0.1, 1000);
gl.uniformMatrix4fv(uniforms.uProjection, false, projection);
gl.uniformMatrix4fv(uniforms.uView, false, view);
const identity = mat4Identity(new Float32Array(16));
if(scene.terrain) {
drawMesh(scene.terrain.mesh, identity, scene.terrain.texture, [1, 1, 1, 1], true);
}
if(scene.gridLines) {
drawMesh(scene.gridLines.mesh, identity, null, [0, 0, 0, 0.35], false, gl.LINES);
}
for(const model of scene.models) {
const modelMatrix = mat4Translation(new Float32Array(16), model.offset);
drawMesh(model.mesh, modelMatrix, model.texture, model.color, true);
}
for(const neighbor of scene.neighbors || []) {
if(neighbor.terrain) {
const modelMatrix = mat4Translation(new Float32Array(16), neighbor.offset);
drawMesh(
neighbor.terrain.mesh, modelMatrix, neighbor.terrain.texture,
[NEIGHBOR_DARKEN, NEIGHBOR_DARKEN, NEIGHBOR_DARKEN, NEIGHBOR_ALPHA], false,
);
}
for(const model of neighbor.models) {
const worldOffset = [
neighbor.offset[0] + model.offset[0],
neighbor.offset[1] + model.offset[1],
neighbor.offset[2] + model.offset[2],
];
const modelMatrix = mat4Translation(new Float32Array(16), worldOffset);
const color = [
model.color[0] * NEIGHBOR_DARKEN,
model.color[1] * NEIGHBOR_DARKEN,
model.color[2] * NEIGHBOR_DARKEN,
model.color[3] * NEIGHBOR_ALPHA,
];
drawMesh(model.mesh, modelMatrix, model.texture, color, false);
}
}
if(scene.highlight) {
const { x, y, z } = scene.highlight;
const highlightMesh = buildHighlightMesh(x, y, z);
drawMesh(highlightMesh, identity, null, [1, 0.92, 0.23, 1], false, gl.LINE_LOOP);
}
}
return { gl, createMesh, createTextureFromImage, render };
}
return Object.freeze({ create, computeCamera });
})();
-23
View File
@@ -1,23 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dusk Map Editor</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-expand navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="/">Dusk Map Editor</a>
<ul class="navbar-nav flex-row">
<li class="nav-item">
<a class="nav-link" href="/map">Map Editor</a>
</li>
</ul>
</div>
</nav>
<div id="editor" class="container-fluid py-3"></div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
-298
View File
@@ -1,298 +0,0 @@
"""
Map Editor HTTP Server
Serves editor/client/public/ as static files with smart routing:
/ -> index.html
/page -> page.html or page/index.html
/index -> index.html
API endpoints (all paths relative to project root):
GET /api/ls?path=<dir> directory listing
GET /api/read?path=<file> file contents
GET /api/find?path=<dir>&ext=<.json> recursive file listing by extension
POST /api/write?path=<file> write file (JSON body: {"content":"..."})
POST /api/mkdir?path=<dir> create directory
POST /api/delete?path=<file> delete a file
POST /api/compile-chunk?x=&y=&z= recompile a chunk JSON to .dcf
"""
import os
import re
import sys
import json
import mimetypes
import subprocess
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs, unquote
from pathlib import Path
CHUNK_COORD_RE = re.compile(r"^-?\d+$")
PORT = 3000
SCRIPT_DIR = Path(__file__).parent.resolve()
PUBLIC_DIR = SCRIPT_DIR.parent / "client" / "public"
PROJECT_ROOT = SCRIPT_DIR.parent.parent.resolve()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
path = unquote(parsed.path)
if path.startswith("/api/"):
params = parse_qs(parsed.query)
if path == "/api/ls":
self.api_ls(params)
elif path == "/api/read":
self.api_read(params)
elif path == "/api/find":
self.api_find(params)
else:
self.send_error(404)
else:
self.serve_static(path)
def do_POST(self):
parsed = urlparse(self.path)
params = parse_qs(parsed.query)
if parsed.path == "/api/write":
self.api_write(params)
elif parsed.path == "/api/mkdir":
self.api_mkdir(params)
elif parsed.path == "/api/delete":
self.api_delete(params)
elif parsed.path == "/api/compile-chunk":
self.api_compile_chunk(params)
else:
self.send_error(404)
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
def resolve_project_path(self, rel):
rel = rel.lstrip("/")
target = (PROJECT_ROOT / rel).resolve()
if not str(target).startswith(str(PROJECT_ROOT)):
return None
return target
def send_json(self, data, code=200):
body = json.dumps(data, indent=2).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", len(body))
self.end_headers()
self.wfile.write(body)
def read_body(self):
length = int(self.headers.get("Content-Length", 0))
return self.rfile.read(length)
# ------------------------------------------------------------------
# API handlers
# ------------------------------------------------------------------
def api_ls(self, params):
rel = params.get("path", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
if not target.exists():
self.send_json({"error": "path not found"}, 404)
return
if not target.is_dir():
self.send_json({"error": "not a directory"}, 400)
return
entries = []
for entry in sorted(target.iterdir(), key=lambda e: (e.is_file(), e.name)):
entries.append({
"name": entry.name,
"type": "dir" if entry.is_dir() else "file",
"size": entry.stat().st_size if entry.is_file() else None,
})
self.send_json({
"path": str(target.relative_to(PROJECT_ROOT)),
"entries": entries,
})
def api_read(self, params):
rel = params.get("path", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
if not target.exists():
self.send_json({"error": "file not found"}, 404)
return
if not target.is_file():
self.send_json({"error": "not a file"}, 400)
return
try:
content = target.read_text(encoding="utf-8")
self.send_json({
"path": str(target.relative_to(PROJECT_ROOT)),
"content": content,
})
except UnicodeDecodeError:
import base64
content = base64.b64encode(target.read_bytes()).decode("ascii")
self.send_json({
"path": str(target.relative_to(PROJECT_ROOT)),
"content": content,
"encoding": "base64",
})
def api_write(self, params):
rel = params.get("path", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
body = self.read_body()
try:
data = json.loads(body)
content = data.get("content", "")
except (json.JSONDecodeError, UnicodeDecodeError):
content = body.decode("utf-8")
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
self.send_json({"ok": True, "path": str(target.relative_to(PROJECT_ROOT))})
def api_mkdir(self, params):
rel = params.get("path", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
target.mkdir(parents=True, exist_ok=True)
self.send_json({"ok": True, "path": str(target.relative_to(PROJECT_ROOT))})
def api_delete(self, params):
rel = params.get("path", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
if target.is_file():
target.unlink()
self.send_json({"ok": True, "path": str(target.relative_to(PROJECT_ROOT))})
def api_find(self, params):
rel = params.get("path", [""])[0]
ext = params.get("ext", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
if not target.is_dir():
self.send_json({"error": "not a directory"}, 400)
return
pattern = f"*{ext}" if ext else "*"
paths = sorted(
str(p.relative_to(target)).replace(os.sep, "/")
for p in target.rglob(pattern)
if p.is_file()
)
self.send_json({"path": str(target.relative_to(PROJECT_ROOT)), "files": paths})
def api_compile_chunk(self, params):
x = params.get("x", [""])[0]
y = params.get("y", [""])[0]
z = params.get("z", [""])[0]
if not (CHUNK_COORD_RE.match(x) and CHUNK_COORD_RE.match(y) and CHUNK_COORD_RE.match(z)):
self.send_json({"error": "invalid chunk coordinates"}, 400)
return
json_path = (
PROJECT_ROOT / "assetsraw" / "maps" / "overworld" / "chunks"
/ f"chunk_{x}_{y}_{z}.json"
)
if not json_path.is_file():
self.send_json({"error": "chunk json not found"}, 404)
return
result = subprocess.run(
[sys.executable, "-m", "tools.asset.chunk", str(json_path)],
cwd=str(PROJECT_ROOT),
capture_output=True,
text=True,
)
self.send_json({
"ok": result.returncode == 0,
"returncode": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr,
})
# ------------------------------------------------------------------
# Static file serving
# ------------------------------------------------------------------
def serve_static(self, path):
clean = path.lstrip("/")
candidates = []
if clean == "" or clean == "index" or clean == "index.html":
candidates = ["index.html"]
else:
candidates.append(clean)
if "." not in Path(clean).name:
candidates.append(clean + ".html")
candidates.append(clean + "/index.html")
for candidate in candidates:
file_path = PUBLIC_DIR / candidate
if file_path.is_file():
self.serve_file(file_path)
return
self.send_error(404)
def serve_file(self, file_path):
mime, _ = mimetypes.guess_type(str(file_path))
mime = mime or "application/octet-stream"
template = PUBLIC_DIR / "template.html"
if (
mime == "text/html"
and file_path.name != "template.html"
and template.is_file()
):
fragment = file_path.read_text(encoding="utf-8")
shell = template.read_text(encoding="utf-8")
marker = shell.find('id="editor"')
if marker == -1:
content = shell.encode("utf-8")
else:
tag_end = shell.index(">", marker) + 1
close_idx = shell.index("</div>", tag_end)
content = (shell[:tag_end] + fragment + shell[close_idx:]).encode("utf-8")
else:
content = file_path.read_bytes()
self.send_response(200)
self.send_header("Content-Type", mime)
self.send_header("Content-Length", len(content))
self.end_headers()
self.wfile.write(content)
def log_message(self, fmt, *args):
print(f" {self.address_string()} {fmt % args}")
if __name__ == "__main__":
print(f"Map Editor")
print(f" http://localhost:{PORT}")
print(f" public : {PUBLIC_DIR}")
print(f" project: {PROJECT_ROOT}")
server = HTTPServer(("", PORT), Handler)
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nStopped.")
-4
View File
@@ -1,4 +0,0 @@
#!/usr/bin/env bash
set -e
cd "$(dirname "$0")"
python3 server/server.py
+1 -17
View File
@@ -5,22 +5,10 @@
add_subdirectory(dusk)
if(DUSK_NETWORK)
add_subdirectory(dusknetwork)
endif()
if(DUSK_TARGET_SYSTEM STREQUAL "linux" OR DUSK_TARGET_SYSTEM STREQUAL "knulli")
# The duskscript runtime itself lives in src/dusk/script, added
# unconditionally of platform there since it is plain, portable C; this is
# just the duskscriptcc compiler, a host tool only built on the dev machine.
add_subdirectory(duskscriptcc)
endif()
if(DUSK_TARGET_SYSTEM STREQUAL "linux" OR DUSK_TARGET_SYSTEM STREQUAL "knulli")
add_subdirectory(dusklinux)
add_subdirectory(dusksdl2)
add_subdirectory(duskgl)
add_subdirectory(duskmad)
elseif(DUSK_TARGET_SYSTEM STREQUAL "psp")
add_subdirectory(duskpsp)
@@ -32,11 +20,7 @@ elseif(DUSK_TARGET_SYSTEM STREQUAL "vita")
add_subdirectory(dusksdl2)
add_subdirectory(duskgl)
elseif(
DUSK_TARGET_SYSTEM STREQUAL "wii" OR
DUSK_TARGET_SYSTEM STREQUAL "gamecube"
)
elseif(DUSK_TARGET_SYSTEM STREQUAL "wii" OR DUSK_TARGET_SYSTEM STREQUAL "gamecube")
add_subdirectory(duskdolphin)
add_subdirectory(duskmad)
endif()
+15 -23
View File
@@ -14,21 +14,12 @@ if(NOT libzip_FOUND)
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC zip)
endif()
# assetdsk.c calls crc32() directly (to verify dusk.dsk archive checksums).
# find_package(libzip) above already resolves ZLIB as a side effect, so
# ZLIB_FOUND may already be true without ZLIB::ZLIB having been linked to
# our target - link it unconditionally rather than guarding on ZLIB_FOUND.
find_package(ZLIB REQUIRED)
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC ZLIB::ZLIB)
if(NOT stb_image_FOUND)
find_package(stb REQUIRED)
if(STB_IMAGE_FOUND)
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC stb_image)
else()
message(FATAL_ERROR
"stb_image not found. Please ensure stb is correctly fetched."
)
message(FATAL_ERROR "stb_image not found. Please ensure stb is correctly fetched.")
endif()
endif()
@@ -37,12 +28,19 @@ if(NOT yyjson_FOUND)
if(yyjson_FOUND)
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC yyjson::yyjson)
else()
message(FATAL_ERROR
"yyjson not found. Please ensure yyjson is correctly fetched."
)
message(FATAL_ERROR "yyjson not found. Please ensure yyjson is correctly fetched.")
endif()
endif()
if(NOT jerryscript_FOUND)
find_package(jerryscript REQUIRED)
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
jerryscript::core
jerryscript::ext
jerryscript::port
)
endif()
if(DUSK_BACKTRACE)
target_link_options(${DUSK_LIBRARY_TARGET_NAME} PUBLIC -rdynamic)
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
@@ -50,12 +48,6 @@ if(DUSK_BACKTRACE)
)
endif()
if(DUSK_TRACK_MEMORY)
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_TRACK_MEMORY
)
endif()
# Includes
target_include_directories(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
@@ -72,20 +64,20 @@ target_sources(${DUSK_BINARY_TARGET_NAME}
add_subdirectory(animation)
add_subdirectory(assert)
add_subdirectory(asset)
add_subdirectory(audio)
add_subdirectory(console)
add_subdirectory(display)
add_subdirectory(entity)
add_subdirectory(log)
add_subdirectory(engine)
add_subdirectory(entity)
add_subdirectory(error)
add_subdirectory(input)
add_subdirectory(locale)
add_subdirectory(perf)
add_subdirectory(physics)
add_subdirectory(scene)
add_subdirectory(script)
add_subdirectory(system)
add_subdirectory(time)
add_subdirectory(save)
add_subdirectory(ui)
add_subdirectory(network)
add_subdirectory(util)
add_subdirectory(thread)
-1
View File
@@ -7,5 +7,4 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
easing.c
animation.c
keyframe.c
)
+23 -103
View File
@@ -11,122 +11,42 @@
void animationInit(
animation_t *anim,
keyframe_t *keyframes,
uint16_t *keyframeCounts,
const uint16_t layerCount
uint16_t keyframeCount
) {
assertNotNull(anim, "Animation pointer cannot be null.");
assertNotNull(keyframes, "Keyframes pointer cannot be null.");
assertNotNull(keyframeCounts, "Keyframe counts pointer cannot be null.");
assertTrue(layerCount > 0, "Layer count must be greater than zero.");
assertTrue(keyframeCount > 0, "Keyframe count must be more than 0.");
memoryZero(anim, sizeof(animation_t));
anim->keyframes = keyframes;
anim->keyframeCounts = keyframeCounts;
anim->layerCount = layerCount;
// Determine duration
float_t duration = 0.0f;
for(uint16_t layer = 0; layer < layerCount; layer++) {
uint16_t keyframeCount = keyframeCounts[layer];
assertTrue(keyframeCount > 0, "Keyframe count invalid.");
keyframe_t *layerKeyframes = keyframes + layer * keyframeCount;
#ifdef DUSK_ASSERTIONS
// Check that the keyframes are sorted by time.
for(uint16_t i = 1; i < keyframeCount; i++) {
assertTrue(
layerKeyframes[i].time >= layerKeyframes[i - 1].time,
"Keyframes must be sorted by time."
);
}
#endif
keyframe_t *lastKeyframe = layerKeyframes + keyframeCount - 1;
duration = mathMax(duration, lastKeyframe->time);
}
assertTrue(duration > 0, "Animation duration must be greater than 0.");
anim->duration = duration;
anim->keyframeCount = keyframeCount;
}
float_t animationGetLayerValue(const animation_t *anim, const uint16_t layer) {
float_t animationGetValue(animation_t *anim, const float_t time) {
assertNotNull(anim, "Animation pointer cannot be null.");
assertTrue(layer < anim->layerCount, "Layer index out of bounds.");
assertNotNull(anim->keyframes, "Keyframes pointer cannot be null.");
assertTrue(anim->keyframeCount > 0, "Keyframe count invalid.");
assertTrue(time >= 0, "Time must be non-negative.");
uint16_t keyframeCount = anim->keyframeCounts[layer];
keyframe_t *layerKeyframes = anim->keyframes + layer * keyframeCount;
return keyframeGetValue(layerKeyframes, keyframeCount, anim->time);
}
void animationUpdate(
animation_t *anim,
const float_t deltaTime
) {
assertNotNull(anim, "Animation pointer cannot be null.");
assertTrue(deltaTime >= 0, "Delta time must be non-negative.");
bool_t justCompleted = false;
if(!(anim->flags & ANIMATION_FLAG_INTERNAL_COMPLETED)) {
bool_t loop = (anim->flags & ANIMATION_FLAG_LOOP) != 0;
bool_t pingpong = (anim->flags & ANIMATION_FLAG_PINGPONG) != 0;
assertFalse(
loop && pingpong,
"Cannot set both ANIMATION_FLAG_LOOP and ANIMATION_FLAG_PINGPONG."
);
bool_t backward;
if(pingpong) {
backward = (anim->flags & ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD) != 0;
} else {
backward = (anim->flags & ANIMATION_FLAG_REVERSE) != 0;
}
// Resolve boundary crossings one at a time, so a single large deltaTime
// can correctly loop/pingpong across multiple boundaries in one call.
float_t remaining = deltaTime;
while(remaining > 0.0f) {
float_t toBoundary = (
backward ? anim->time : (anim->duration - anim->time)
);
if(remaining < toBoundary) {
anim->time += backward ? -remaining : remaining;
keyframe_t *start;
keyframe_t *end;
keyframe_t *last = anim->keyframes + anim->keyframeCount - 1;
keyframe_t *current = anim->keyframes;
start = current;
do {
if(current->time > time) {
end = current;
break;
}
start = current;
current++;
remaining -= toBoundary;
anim->time = backward ? 0.0f : anim->duration;
bool_t stopHere;
if(backward) {
stopHere = (anim->flags & ANIMATION_FLAG_STOP_BEGINNING) != 0;
} else {
stopHere = (anim->flags & ANIMATION_FLAG_STOP_END) != 0;
}
if(stopHere) {
justCompleted = true;
break;
} else if(pingpong) {
backward = !backward;
if(backward) anim->flags |= ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD;
else anim->flags &= ~ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD;
} else if(loop) {
anim->time = backward ? anim->duration : 0.0f;
if(anim->onLoop) anim->onLoop(anim->user);
} else {
justCompleted = true;
if(current > last) {
end = start;
break;
}
}
if(justCompleted) anim->flags |= ANIMATION_FLAG_INTERNAL_COMPLETED;
}
// Call onUpdate for each layer.
for(uint16_t layer = 0; layer < anim->layerCount; layer++) {
float_t value = animationGetLayerValue(anim, layer);
if(anim->onUpdate) anim->onUpdate(layer, value, anim->user);
}
} while(true);
if(justCompleted && anim->onComplete) anim->onComplete(anim->user);
float_t t = (time - start->time) / (end->time - start->time);
return mathLerp(start->value, end->value, easingApply(start->easing, t));
}
+11 -71
View File
@@ -6,89 +6,29 @@
#pragma once
#include "keyframe.h"
#define ANIMATION_FLAG_LOOP (1 << 0)
#define ANIMATION_FLAG_REVERSE (1 << 1)
#define ANIMATION_FLAG_PINGPONG (1 << 2)
#define ANIMATION_FLAG_STOP_BEGINNING (1 << 3)
#define ANIMATION_FLAG_STOP_END (1 << 4)
// Internal - tracks which direction a pingponging animation is currently
// travelling. Do not set this manually, it is managed by animationUpdate().
#define ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD (1 << 7)
// Internal - set once the animation has stopped advancing (see
// animationUpdate()). Do not set this manually. There is currently no way to
// restart a completed animation short of clearing this bit and resetting
// anim->time by hand.
#define ANIMATION_FLAG_INTERNAL_COMPLETED (1 << 6)
typedef struct {
keyframe_t *keyframes;
uint16_t *keyframeCounts;
uint16_t layerCount;
float_t time;
float_t duration;
uint8_t flags;
void *user;
void (*onUpdate)(const uint16_t layer, const float_t value, void *user);
void (*onComplete)(void *user);
void (*onLoop)(void *user);
uint16_t keyframeCount;
} animation_t;
/**
* Initializes an animation with the given keyframes and layer count.
* Initializes an animation.
*
* @param anim Pointer to the animation to initialize.
* @param keyframes Pointer to the array of keyframes for each layer.
* @param keyframeCount Number of keyframes in each layer.
* @param layerCount Number of layers in the animation.
* @param anim The animation to initialize.
* @param keyframes The keyframes to use for the animation.
* @param keyframeCount The number of keyframes in the animation.
*/
void animationInit(
animation_t *anim,
keyframe_t *keyframes,
uint16_t *keyframeCounts,
const uint16_t layerCount
uint16_t keyframeCount
);
/**
* Sets the current time of the animation, clamping it to the valid range.
* This will call the onUpdate callback but none of the other callbacks.
* Gets the value of the animation at a given time.
*
* @param anim Pointer to the animation to set the time for.
* @param time The new time to set for the animation.
* @param anim The animation to get the value from.
* @param time The time at which to get the value, in seconds.
* @return The value of the animation at the given time.
*/
void animationSetTime(animation_t *anim, const float_t time);
/**
* Gets the current value of a specific layer in the animation based on the
* current animation time.
*/
float_t animationGetLayerValue(const animation_t *anim, const uint16_t layer);
/**
* Updates the animation state based on the elapsed time. Advances anim->time
* by deltaTime (or against it, if ANIMATION_FLAG_REVERSE is set), then
* resolves whatever happens when it reaches the 0 or duration boundary:
*
* - ANIMATION_FLAG_PINGPONG: reflects off the boundary and continues playing
* in the opposite direction, forever, unless stopped (see below).
* - ANIMATION_FLAG_LOOP: wraps back around to the other boundary and keeps
* playing in the same direction, forever, unless stopped (see below).
* - ANIMATION_FLAG_STOP_BEGINNING / ANIMATION_FLAG_STOP_END: when the
* animation reaches that specific boundary, it clamps there and stops
* (firing onComplete) instead of looping/pingponging past it.
* - If none of the above apply at a boundary, the animation clamps there and
* stops, firing onComplete.
*
* onUpdate is called for every layer on every call. onLoop is called each
* time a loop wraps around. onComplete is called at most once, the moment
* the animation stops advancing.
*
* @param anim Pointer to the animation to update.
* @param deltaTime Time elapsed since the last update (in seconds).
*/
void animationUpdate(
animation_t *anim,
const float_t deltaTime
);
float_t animationGetValue(animation_t *anim, const float_t time);
+3 -4
View File
@@ -5,7 +5,6 @@
#include "easing.h"
#include "assert/assert.h"
#include "util/math.h"
const easingfn_t EASING_FUNCTIONS[EASING_COUNT] = {
easingLinear,
@@ -36,15 +35,15 @@ float_t easingLinear(const float_t t) {
}
float_t easingInSine(const float_t t) {
return 1.0f - cosf(t * MATH_PI * 0.5f);
return 1.0f - cosf(t * EASING_PI * 0.5f);
}
float_t easingOutSine(const float_t t) {
return sinf(t * MATH_PI * 0.5f);
return sinf(t * EASING_PI * 0.5f);
}
float_t easingInOutSine(const float_t t) {
return -(cosf(MATH_PI * t) - 1.0f) * 0.5f;
return -(cosf(EASING_PI * t) - 1.0f) * 0.5f;
}
float_t easingInQuad(const float_t t) {
-45
View File
@@ -1,45 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "keyframe.h"
#include "assert/assert.h"
#include "util/math.h"
float_t keyframeGetValue(
const keyframe_t *keyframes,
const uint32_t keyframeCount,
const float_t time
) {
assertNotNull(keyframes, "Keyframes pointer cannot be null.");
assertTrue(keyframeCount > 0, "Keyframe count must be more than 0.");
assertTrue(time >= 0, "Time must be non-negative.");
#ifdef DUSK_ASSERTIONS
// Checks that the keyframes are sorted by time.
for(uint32_t i = 1; i < keyframeCount; i++) {
assertTrue(
keyframes[i].time >= keyframes[i - 1].time,
"Keyframes must be sorted by time."
);
}
#endif
keyframe_t *last = (keyframe_t *)(keyframes + keyframeCount - 1);
if(time >= last->time) return last->value;
// Since time < last->time (checked above), current is guaranteed to stop
// at or before reaching last, so no separate end-of-array check is needed.
keyframe_t *current = (keyframe_t *)keyframes;
keyframe_t *start = current;
while(current->time <= time) {
start = current;
current++;
}
keyframe_t *end = current;
float_t t = (time - start->time) / (end->time - start->time);
return mathLerp(start->value, end->value, easingApply(start->easing, t));
}
-14
View File
@@ -11,17 +11,3 @@ typedef struct {
float_t value;
easingtype_t easing;
} keyframe_t;
/**
* Gets the value of a keyframe at a given time.
*
* @param keyframes The keyframes to get the value from.
* @param keyframeCount The number of keyframes in the array.
* @param time The time at which to get the value, in seconds.
* @return The value of the keyframe at the given time.
*/
float_t keyframeGetValue(
const keyframe_t *keyframes,
const uint32_t keyframeCount,
const float_t time
);
-2
View File
@@ -22,8 +22,6 @@
#endif
#ifndef DUSK_ASSERTIONS_FAKED
#define DUSK_ASSERTIONS 1
/**
* Initializes the assert system. Must be the very first call in engine
* startup.
-1
View File
@@ -7,7 +7,6 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
asset.c
assetdsk.c
assetfile.c
)
+4 -25
View File
@@ -19,8 +19,6 @@ asset_t ASSET;
errorret_t assetInit(void) {
memoryZero(&ASSET, sizeof(asset_t));
threadMutexInit(&ASSET.zipLock);
for(size_t i = 0; i < ASSET_LOADING_COUNT_MAX; i++) {
threadMutexInit(&ASSET.loading[i].mutex);
}
@@ -37,10 +35,9 @@ errorret_t assetInit(void) {
bool_t assetFileExists(const char_t *filename) {
assertStrLenMax(filename, ASSET_FILE_NAME_MAX, "Filename too long.");
threadMutexLock(&ASSET.zipLock);
bool_t found = zip_name_locate(ASSET.zip, filename, 0) >= 0;
threadMutexUnlock(&ASSET.zipLock);
return found;
zip_int64_t idx = zip_name_locate(ASSET.zip, filename, 0);
if(idx < 0) return false;
return true;
}
assetentry_t * assetGetEntry(
@@ -120,15 +117,6 @@ errorret_t assetRequireLoaded(assetentry_t *entry) {
assetEntryLock(entry);
while(entry->state != ASSET_ENTRY_STATE_LOADED) {
// A failed load transitions to ERROR, not LOADED - without this check
// this loop spins forever on any load failure (assetUpdate() itself
// still returns OK, since a single asset failing isn't meant to halt
// the whole update loop - see its ASSET_ENTRY_STATE_ERROR handling).
if(entry->state == ASSET_ENTRY_STATE_ERROR) {
assetEntryUnlock(entry);
errorThrow("Failed to load asset: %s", entry->name);
}
usleep(1000);
errorret_t ret = assetUpdate();
if(errorIsNotOk(ret)) {
@@ -332,11 +320,7 @@ errorret_t assetUpdate(void) {
"Loader did not set entry state to error on failed load."
);
} else if(loading->entry->state == ASSET_ENTRY_STATE_LOADED) {
assetentry_t *loadedEntry = loading->entry;
loading->entry = NULL;
if(loadedEntry->onLoaded) {
loadedEntry->onLoaded(loadedEntry, loadedEntry->onLoadedUser);
}
}
loading++;
@@ -357,13 +341,9 @@ errorret_t assetUpdate(void) {
break;
case ASSET_ENTRY_STATE_ERROR: {
assetentry_t *errEntry = loading->entry;
loading->entry = NULL;
threadMutexUnlock(&loading->mutex);
if(errEntry->onError) {
errEntry->onError(errEntry, errEntry->onErrorUser);
}
loading++;
errorThrow("Failed to load asset asynchronously.");
break;
}
@@ -450,6 +430,5 @@ errorret_t assetDispose(void) {
}
errorChain(assetDisposePlatform());
threadMutexDispose(&ASSET.zipLock);
errorOk();
}
+1 -31
View File
@@ -23,43 +23,13 @@
#define ASSET_FILE_NAME "dusk.dsk"
#define ASSET_HEADER_SIZE 3
#define ASSET_LOADING_COUNT_MAX 10
#define ASSET_LOADING_COUNT_MAX 16
#define ASSET_ENTRY_COUNT_MAX 64
#define ASSET_BASE_DIRECTORY_MAX 256
typedef struct asset_s {
// The dusk.dsk archive - a single uncompressed (ZIP_STORED) zip, so
// every entry gets the reliable repeated seeking/re-opening that
// libzip only supports reliably for uncompressed entries (locale
// strings, MP3 loop restarts, etc.).
zip_t *zip;
// Directory dusk.dsk was actually found/opened in (on PSP, the directory
// EBOOT.PBP lives in, since dusk.dsk is embedded inside it rather than a
// loose file) - populated by each platform's own assetInitXxx() once it
// locates the file. Save devices that persist to a real filesystem path
// (Linux, PSP, Wii SD) use this as their base directory instead of a
// separate hardcoded location, so saves live next to wherever the game
// itself was actually launched from rather than some unrelated fixed
// path. Not meaningful for devices with no filesystem-path concept at
// all (GameCube/Wii memory card, Wii NAND's ISFS namespace).
char_t baseDirectory[ASSET_BASE_DIRECTORY_MAX];
assetplatform_t platform;
// Guards every libzip call against ASSET.zip (zip_fopen,
// zip_fread, zip_fclose, zip_fseek, zip_stat, zip_name_locate - see
// assetfile.c/assetFileExists). libzip is documented as not thread-safe,
// and this asset system genuinely calls it from multiple real threads at
// once (main thread, the background load thread below, and - on
// platforms that stream PCM from an asset on their own thread, like PSP
// - an audio feeder thread too). Confirmed necessary on real PSP
// hardware: without this lock, concurrent zip_fopen/zip_fread calls from
// different threads corrupted reads (EINVAL, then zlib data errors) once
// dusk.dsk stopped being read entirely into memory up front.
threadmutex_t zipLock;
// Background loading thread.
thread_t loadThread;
-165
View File
@@ -1,165 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetdsk.h"
#include "util/memory.h"
#include "util/endian.h"
#include "assert/assert.h"
#include <zlib.h>
errorret_t assetDskParseHeader(
const uint8_t *bytes,
const size_t bytesSize,
assetdskheader_t *outHeader
) {
assertNotNull(bytes, "Bytes cannot be NULL.");
assertNotNull(outHeader, "Out header cannot be NULL.");
if(bytesSize < ASSET_DSK_HEADER_SIZE) {
errorThrow("dusk.dsk header is truncated.");
}
if(memoryCompare(bytes, ASSET_DSK_MAGIC, ASSET_DSK_MAGIC_SIZE) != 0) {
errorThrow("dusk.dsk has an invalid magic header.");
}
// Every field is a little-endian uint32_t regardless of host - convert
// to host order (a no-op on little-endian hosts, a real byteswap on
// Dolphin's big-endian PowerPC).
uint32_t fields[3];
memoryCopy(fields, bytes + ASSET_DSK_MAGIC_SIZE, sizeof(fields));
for(uint8_t i = 0; i < 3; i++) {
fields[i] = endianLittleToHost32(fields[i]);
}
const uint32_t version = fields[0];
if(version != ASSET_DSK_VERSION) {
errorThrow("dusk.dsk has an unsupported version: %u", version);
}
outHeader->size = fields[1];
outHeader->checksum = fields[2];
errorOk();
}
errorret_t assetDskOpenFromPath(
const char_t *path,
zip_t **outZip
) {
errorChain(assetDskOpenFromPathRange(path, 0, SIZE_MAX, outZip));
errorOk();
}
errorret_t assetDskOpenFromPathRange(
const char_t *path,
const size_t baseOffset,
const size_t baseSize,
zip_t **outZip
) {
assertNotNull(path, "Path cannot be NULL.");
assertNotNull(outZip, "Out zip cannot be NULL.");
*outZip = NULL;
FILE *headerFile = fopen(path, "rb");
if(headerFile == NULL) {
errorThrow("Failed to open dusk.dsk: %s", path);
}
if(fseek(headerFile, (long) baseOffset, SEEK_SET) != 0) {
fclose(headerFile);
errorThrow("Failed to seek to dusk.dsk range in file: %s", path);
}
uint8_t headerBytes[ASSET_DSK_HEADER_SIZE];
size_t headerRead = fread(headerBytes, 1, sizeof(headerBytes), headerFile);
fclose(headerFile);
if(headerRead != sizeof(headerBytes)) {
errorThrow("Failed to read dusk.dsk header: %s", path);
}
assetdskheader_t header;
errorChain(assetDskParseHeader(headerBytes, sizeof(headerBytes), &header));
if((size_t) ASSET_DSK_HEADER_SIZE + header.size > baseSize) {
errorThrow("dusk.dsk header describes a range beyond its containing file.");
}
zip_error_t zipError;
zip_error_init(&zipError);
zip_source_t *source = zip_source_file_create(
path,
(zip_uint64_t) (baseOffset + ASSET_DSK_HEADER_SIZE),
(zip_int64_t) header.size,
&zipError
);
if(source == NULL) {
errorThrow(
"Failed to create dusk.dsk source: %s", zip_error_strerror(&zipError)
);
}
*outZip = zip_open_from_source(source, ZIP_RDONLY, &zipError);
if(*outZip == NULL) {
zip_source_free(source);
errorThrow(
"Failed to open dusk.dsk archive: %s", zip_error_strerror(&zipError)
);
}
errorOk();
}
errorret_t assetDskOpenFromBuffer(
uint8_t *buffer,
const size_t bufferSize,
zip_t **outZip
) {
assertNotNull(buffer, "Buffer cannot be NULL.");
assertNotNull(outZip, "Out zip cannot be NULL.");
*outZip = NULL;
assetdskheader_t header;
errorChain(assetDskParseHeader(buffer, bufferSize, &header));
if((size_t) ASSET_DSK_HEADER_SIZE + header.size > bufferSize) {
errorThrow("dusk.dsk header describes a range beyond the buffer.");
}
uint8_t *data = buffer + ASSET_DSK_HEADER_SIZE;
uint32_t checksum = (uint32_t) crc32(0L, data, (uInt) header.size);
if(checksum != header.checksum) {
errorThrow("dusk.dsk archive failed checksum verification.");
}
zip_error_t zipError;
zip_error_init(&zipError);
// freep=0 - this is a non-owning window into the same caller-owned
// buffer, not an independent allocation libzip should free.
zip_source_t *source = zip_source_buffer_create(
data, header.size, 0, &zipError
);
if(source == NULL) {
errorThrow(
"Failed to create dusk.dsk source: %s", zip_error_strerror(&zipError)
);
}
*outZip = zip_open_from_source(source, ZIP_RDONLY, &zipError);
if(*outZip == NULL) {
zip_source_free(source);
errorThrow(
"Failed to open dusk.dsk archive: %s", zip_error_strerror(&zipError)
);
}
errorOk();
}
-120
View File
@@ -1,120 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include <zip.h>
// "DSK2" - distinct from a plain zip's "PK\x03\x04" so a stray plain zip
// never gets misread as a valid dusk.dsk.
#define ASSET_DSK_MAGIC_SIZE 4
#define ASSET_DSK_MAGIC "DSK"
#define ASSET_DSK_VERSION 2
// Magic + version + size + checksum
#define ASSET_DSK_HEADER_SIZE ( \
ASSET_DSK_MAGIC_SIZE + \
sizeof(uint32_t) + \
sizeof(uint32_t) + \
sizeof(uint32_t) \
)
/**
* Parsed dusk.dsk (DSK2 format) header. dusk.dsk is a single uncompressed
* (ZIP_STORED) zip archive (see tools/asset/pack) rather than DEFLATEd -
* the bulk of what's packed (audio, images) is already compressed at the
* file level, so DEFLATE-ing the whole archive on top buys negligible
* space for real CPU cost, and every entry gets the reliable repeated
* seeking/re-opening that libzip only supports for uncompressed entries
* (locale line-by-line reads, MP3 loop restarts, etc.) instead of just a
* hand-picked subset of files.
*/
typedef struct {
uint32_t size;
uint32_t checksum;
} assetdskheader_t;
/**
* Parses a DSK2 header from a raw byte buffer (at least
* ASSET_DSK_HEADER_SIZE bytes), validating the magic/version and
* byte-swapping the little-endian fields to host order.
*
* @param bytes Buffer containing the header (and beyond).
* @param bytesSize Number of bytes available at `bytes`.
* @param outHeader Filled with the parsed header on success.
* @return OK on success, error if too short, bad magic, or unsupported version.
*/
errorret_t assetDskParseHeader(
const uint8_t *bytes,
const size_t bytesSize,
assetdskheader_t *outHeader
);
/**
* Opens the dusk.dsk archive given a filesystem path, using a lazy/
* windowed file-backed zip source - no more memory used than the
* existing per-platform small read buffers, matching the memory
* characteristics of a plain zip_open() on the whole file. The checksum
* is intentionally not verified here since doing so would require
* reading the whole (potentially large) archive just to compute it.
*
* See assetDskOpenFromPathRange() for the case where the DSK2 blob isn't
* the whole file (e.g. embedded inside another container).
*
* @param path Filesystem path to the dusk.dsk file.
* @param outZip Set to the opened archive on success.
* @return OK on success, error if the file is missing, too short, has a
* bad header, or the archive fails to open.
*/
errorret_t assetDskOpenFromPath(
const char_t *path,
zip_t **outZip
);
/**
* Same as assetDskOpenFromPath(), but the DSK2 blob doesn't start at the
* beginning of `path` - it's a byte range embedded inside a larger
* container file (e.g. the PSAR region of an EBOOT.PBP). Every offset the
* header describes is relative to `baseOffset`; `baseSize` bounds them
* (the size of the embedded blob, not the whole container file) - pass
* SIZE_MAX to skip that check when the caller doesn't know/care.
*
* @param path Filesystem path to the container file.
* @param baseOffset Byte offset within `path` where the DSK2 blob starts.
* @param baseSize Number of bytes available at `baseOffset`.
* @param outZip Set to the opened archive on success.
* @return OK on success, error if the file is missing, too short, has a
* bad header, or the archive fails to open.
*/
errorret_t assetDskOpenFromPathRange(
const char_t *path,
const size_t baseOffset,
const size_t baseSize,
zip_t **outZip
);
/**
* Opens the dusk.dsk archive already fully resident in memory (e.g. a
* PSAR embedded in an EBOOT.PBP, or an ISO-embedded file already read via
* DVD_ReadAbs - platforms that already buffer the whole file for reasons
* unrelated to this format). The returned archive doesn't take ownership
* of `buffer` (it's opened as a non-owning sub-range of it) - the caller
* remains responsible for freeing it, and must keep it alive for as long
* as the archive stays open. Verifies the checksum, since the bytes are
* already resident.
*
* @param buffer The whole dusk.dsk file's bytes.
* @param bufferSize Number of bytes at `buffer`.
* @param outZip Set to the opened archive on success.
* @return OK on success, error if too short, has a bad header/checksum, or
* the archive fails to open.
*/
errorret_t assetDskOpenFromBuffer(
uint8_t *buffer,
const size_t bufferSize,
zip_t **outZip
);
+13 -69
View File
@@ -24,11 +24,9 @@ errorret_t assetFileInit(
file->params = params;
file->output = output;
// Stat the file
zip_stat_init(&file->stat);
threadMutexLock(&ASSET.zipLock);
int statResult = zip_stat(ASSET.zip, filename, 0, &file->stat);
threadMutexUnlock(&ASSET.zipLock);
if(statResult != 0) {
if(!zip_stat(ASSET.zip, filename, 0, &file->stat) == 0) {
errorThrow("Failed to stat asset file: %s", filename);
}
@@ -49,25 +47,6 @@ errorret_t assetFileRewind(assetfile_t *file) {
errorOk();
}
// Prefer seeking within the still-open handle over closing and
// re-opening it. Repeatedly closing/re-opening the same compressed zip
// entry (once per rewind - e.g. once per locale string lookup) was
// confirmed unreliable on at least one platform's zip backend, silently
// skipping ranges of the decompressed content on some re-opens after
// the first. A real seek avoids that failure mode entirely, with no
// extra memory cost over the close+reopen fallback.
threadMutexLock(&ASSET.zipLock);
bool_t seekable = zip_file_is_seekable(file->zipFile);
int seekResult = seekable ? zip_fseek(file->zipFile, 0, SEEK_SET) : -1;
threadMutexUnlock(&ASSET.zipLock);
if(seekable) {
if(seekResult != 0) {
errorThrow("Failed to seek asset file: %s", file->filename);
}
file->position = 0;
errorOk();
}
errorChain(assetFileClose(file));
errorChain(assetFileOpen(file));
errorOk();
@@ -76,11 +55,10 @@ errorret_t assetFileRewind(assetfile_t *file) {
errorret_t assetFileOpen(assetfile_t *file) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(file->filename, "Asset file filename cannot be NULL.");
assertNotNull(ASSET.zip, "Asset zip cannot be NULL.");
assertNull(file->zipFile, "Asset file already open.");
threadMutexLock(&ASSET.zipLock);
file->zipFile = zip_fopen(ASSET.zip, file->filename, 0);
threadMutexUnlock(&ASSET.zipLock);
if(file->zipFile == NULL) {
errorThrow("Failed to open asset file: %s", file->filename);
}
@@ -101,52 +79,21 @@ errorret_t assetFileRead(
uint8_t tempBuffer[256];
while(bytesRemaining > 0) {
size_t chunkSize = mathMin(bytesRemaining, sizeof(tempBuffer));
// The recursive call below already advances file->position by
// chunkSize (the non-NULL branch does this itself) - do not also
// advance it here, or every skip ends up double-counted.
errorChain(assetFileRead(file, tempBuffer, chunkSize));
file->position += chunkSize;
bytesRemaining -= chunkSize;
}
file->lastRead = bufferSize;
errorOk();
}
// Some zip_fread() implementations (seen on PSP) reject a single call
// asking for the entire (potentially large) file at once with EINVAL;
// the line reader above only ever asks for up to 1024 bytes per call and
// works fine, so read in bounded chunks here too.
size_t totalRead = 0;
uint8_t *dest = (uint8_t *)buffer;
while(totalRead < bufferSize) {
size_t chunkSize = mathMin(
bufferSize - totalRead, ASSET_FILE_READ_CHUNK_MAX
);
threadMutexLock(&ASSET.zipLock);
zip_int64_t bytesRead = zip_fread(
file->zipFile, dest + totalRead, chunkSize
);
errorret_t readError = errorOkImpl();
// I assume zip_fread takes buffer NULL for skipping?
zip_int64_t bytesRead = zip_fread(file->zipFile, buffer, bufferSize);
if(bytesRead < 0) {
// Built (not thrown) while still holding the lock, so
// zip_file_strerror() reads the just-failed zipFile's error state
// before another thread can touch it - errorThrow() itself isn't
// used here since it returns immediately, which would leave
// ASSET.zipLock held forever.
readError = errorThrowImpl(
&ERROR_STATE, ERROR_NOT_OK, __FILE__, __func__, __LINE__,
"Failed to read from asset file: %s (%s)",
file->filename, zip_file_strerror(file->zipFile)
);
errorThrow("Failed to read from asset file: %s", file->filename);
}
threadMutexUnlock(&ASSET.zipLock);
if(errorIsNotOk(readError)) {
errorChain(readError);
}
if(bytesRead == 0) break;
totalRead += (size_t)bytesRead;
}
file->position += totalRead;
file->lastRead = totalRead;
file->position += bytesRead;
file->lastRead = bytesRead;
errorOk();
}
@@ -154,10 +101,7 @@ errorret_t assetFileClose(assetfile_t *file) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(file->zipFile, "Asset file must be opened before closing.");
threadMutexLock(&ASSET.zipLock);
int closeResult = zip_fclose(file->zipFile);
threadMutexUnlock(&ASSET.zipLock);
if(closeResult != 0) {
if(zip_fclose(file->zipFile) != 0) {
errorThrow("Failed to close asset file: %s", file->filename);
}
file->zipFile = NULL;
@@ -257,7 +201,7 @@ const uint8_t *assetFileLineReaderUnreadPtr(
return reader->readBuffer + reader->bufferStart;
}
errorret_t assetFileLineReaderAppend(
static errorret_t assetFileLineReaderAppend(
assetfilelinereader_t *reader,
const uint8_t *src,
size_t srcLength
@@ -279,7 +223,7 @@ errorret_t assetFileLineReaderAppend(
errorOk();
}
void assetFileLineReaderTerminate(assetfilelinereader_t *reader) {
static void assetFileLineReaderTerminate(assetfilelinereader_t *reader) {
assertNotNull(reader, "Reader cannot be NULL.");
assertNotNull(reader->outBuffer, "Out buffer cannot be NULL.");
assertTrue(
@@ -289,7 +233,7 @@ void assetFileLineReaderTerminate(assetfilelinereader_t *reader) {
reader->outBuffer[reader->lineLength] = '\0';
}
ssize_t assetFileLineReaderFindNewline(
static ssize_t assetFileLineReaderFindNewline(
const assetfilelinereader_t *reader
) {
size_t i;
+1 -64
View File
@@ -9,13 +9,7 @@
#include "error/error.h"
#include <zip.h>
#define ASSET_FILE_NAME_MAX 128
// Max bytes requested per zip_fread() call in assetFileRead(). Some
// zip_fread() implementations (seen on PSP) reject a single call asking
// for very large amounts of data at once; the locale line reader has
// always used 1024-byte reads successfully, so that's the proven-safe cap.
#define ASSET_FILE_READ_CHUNK_MAX 1024
#define ASSET_FILE_NAME_MAX 48
typedef struct assetfile_s assetfile_t;
@@ -150,63 +144,6 @@ void assetFileLineReaderInit(
const size_t outBufferSize
);
/**
* Returns the number of bytes still unread in the line reader's read buffer.
*
* @param reader The line reader to check.
* @return Number of unread bytes remaining in the read buffer.
*/
size_t assetFileLineReaderUnreadBytes(const assetfilelinereader_t *reader);
/**
* Returns a pointer to the first unread byte in the line reader's read
* buffer.
*
* @param reader The line reader to check.
* @return Pointer to the first unread byte.
*/
const uint8_t *assetFileLineReaderUnreadPtr(
const assetfilelinereader_t *reader
);
/**
* Appends src to the line reader's current line buffer, growing lineLength.
*
* @param reader The line reader whose out buffer to append to.
* @param src Bytes to append.
* @param srcLength Number of bytes in src.
* @return Error state if any (the line would exceed the output buffer).
*/
errorret_t assetFileLineReaderAppend(
assetfilelinereader_t *reader,
const uint8_t *src,
size_t srcLength
);
/**
* Null-terminates the line reader's current line buffer at lineLength.
*
* @param reader The line reader whose out buffer to terminate.
*/
void assetFileLineReaderTerminate(assetfilelinereader_t *reader);
/**
* Searches the line reader's unread buffered bytes for a newline character.
*
* @param reader The line reader to search.
* @return The index of the newline within readBuffer, or -1 if not found.
*/
ssize_t assetFileLineReaderFindNewline(const assetfilelinereader_t *reader);
/**
* Refills the line reader's read buffer from the underlying file once its
* buffered bytes are fully consumed. A no-op once the file is at EOF.
*
* @param reader The line reader to refill.
* @return Error state if any.
*/
errorret_t assetFileLineReaderFill(assetfilelinereader_t *reader);
/**
* Reads the next line from the asset file into the line buffer. The line
* buffer is null-terminated and does not include the newline character.
+1 -2
View File
@@ -16,5 +16,4 @@ add_subdirectory(display)
add_subdirectory(locale)
add_subdirectory(json)
add_subdirectory(dmf)
add_subdirectory(wav)
add_subdirectory(mp3)
add_subdirectory(script)
-1
View File
@@ -81,7 +81,6 @@ errorret_t assetEntryDispose(assetentry_t *entry) {
"Asset entry still refed at dispose time."
);
if(entry->onUnloaded) entry->onUnloaded(entry, entry->onUnloadedUser);
errorChain(ASSET_LOADER_CALLBACKS[entry->type].dispose(entry));
memoryZero(entry, sizeof(assetentry_t));
errorOk();
-31
View File
@@ -21,15 +21,6 @@ typedef enum {
typedef struct assetentry_s assetentry_t;
/**
* A single asset entry callback. Each entry supports at most one subscriber
* per event - a second assignment without clearing the first is a bug.
*
* @param entry The assetentry_t the event fired on.
* @param user The user pointer passed alongside the callback.
*/
typedef void (*assetentrycallback_t)(assetentry_t *entry, void *user);
struct assetentry_s {
char_t name[ASSET_FILE_NAME_MAX];
assetloadertype_t type;
@@ -38,27 +29,6 @@ struct assetentry_s {
ref_t refs;
assetloaderinput_t *input;
assetloaderinput_t inputData;
/**
* Fired once when loading completes successfully.
* Always invoked on the main thread.
*/
assetentrycallback_t onLoaded;
void *onLoadedUser;
/**
* Fired once when the entry is disposed/reaped. The asset data is still
* accessible when the callback runs. Always invoked on the main thread.
*/
assetentrycallback_t onUnloaded;
void *onUnloadedUser;
/**
* Fired once when loading fails.
* Always invoked on the main thread.
*/
assetentrycallback_t onError;
void *onErrorUser;
};
/**
@@ -106,7 +76,6 @@ void assetEntryStartLoading(assetentry_t *entry, assetloading_t *loading);
/**
* Disposes an asset entry, freeing any resources it holds.
* Fires the onUnloaded event before releasing asset data.
*
* @param entry The asset entry to dispose.
* @return Any error that occurs during disposal.
+3 -10
View File
@@ -46,15 +46,8 @@ assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = {
.dispose = assetJsonDispose
},
[ASSET_LOADER_TYPE_WAV] = {
.loadSync = assetWavLoaderSync,
.loadAsync = assetWavLoaderAsync,
.dispose = assetWavDispose
},
[ASSET_LOADER_TYPE_MP3] = {
.loadSync = assetMp3LoaderSync,
.loadAsync = assetMp3LoaderAsync,
.dispose = assetMp3Dispose
[ASSET_LOADER_TYPE_SCRIPT] = {
.loadSync = assetScriptLoaderSync,
.dispose = assetScriptDispose
},
};
+22 -10
View File
@@ -12,8 +12,7 @@
#include "asset/loader/display/assettilesetloader.h"
#include "asset/loader/locale/assetlocaleloader.h"
#include "asset/loader/json/assetjsonloader.h"
#include "asset/loader/wav/assetwavloader.h"
#include "asset/loader/mp3/assetmp3loader.h"
#include "asset/loader/script/assetscriptloader.h"
typedef enum {
ASSET_LOADER_TYPE_NULL,
@@ -24,8 +23,7 @@ typedef enum {
ASSET_LOADER_TYPE_TILESET,
ASSET_LOADER_TYPE_LOCALE,
ASSET_LOADER_TYPE_JSON,
ASSET_LOADER_TYPE_WAV,
ASSET_LOADER_TYPE_MP3,
ASSET_LOADER_TYPE_SCRIPT,
ASSET_LOADER_TYPE_COUNT
} assetloadertype_t;
@@ -37,8 +35,6 @@ typedef union {
assettilesetloaderloading_t tileset;
assetlocaleloaderloading_t locale;
assetjsonloaderloading_t json;
assetwavloaderloading_t wav;
assetmp3loaderloading_t mp3;
} assetloaderloading_t;
typedef union {
@@ -48,8 +44,7 @@ typedef union {
assettilesetoutput_t tileset;
assetlocaleoutput_t locale;
assetjsonoutput_t json;
assetwavoutput_t wav;
assetmp3output_t mp3;
assetscriptoutput_t script;
} assetloaderoutput_t;
typedef union {
@@ -57,8 +52,6 @@ typedef union {
assettilesetloaderinput_t tileset;
assetlocaleloaderinput_t locale;
assetjsonloaderinput_t json;
assetwavloaderinput_t wav;
assetmp3loaderinput_t mp3;
} assetloaderinput_t;
typedef struct assetloading_s assetloading_t;
@@ -91,6 +84,25 @@ extern assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT];
} \
}
/**
* Like @ref assetLoaderErrorChain, but also frees `_ptr` (via memoryFree)
* before chaining the error if `_expr` failed. Use this for any loader step
* that runs after a buffer has already been allocated, so a later I/O
* failure doesn't leak it.
*
* @param loading The asset loading slot.
* @param _ptr A heap pointer to free if `_expr` fails.
* @param _expr The error return value to check and chain if it's an error.
*/
#define assetLoaderErrorChainFree(loading, _ptr, _expr) {\
errorret_t _alecf = (_expr); \
if(errorIsNotOk(_alecf)) { \
memoryFree(_ptr); \
(loading)->entry->state = ASSET_ENTRY_STATE_ERROR; \
errorChain(_alecf); \
} \
}
/**
* Shorthand method to both throw an error (against the loader state) and to
* set the asset entry state to error.
@@ -27,11 +27,12 @@ errorret_t assetTilesetLoaderAsync(assetloading_t *loading) {
assetFileInit(file, loading->entry->name, NULL, NULL)
);
uint8_t *data = memoryAllocate(file->size);
assetLoaderErrorChain(loading, assetFileOpen(file));
assetLoaderErrorChain(loading, assetFileRead(file, data, file->size));
assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file));
uint8_t *data = memoryAllocate(file->size);
assetLoaderErrorChainFree(loading, data, assetFileRead(file, data, file->size));
assetLoaderErrorChainFree(loading, data, assetFileClose(file));
assetLoaderErrorChainFree(loading, data, assetFileDispose(file));
assertTrue(
file->lastRead == file->size,
"Failed to read entire tileset file."
@@ -102,6 +103,11 @@ errorret_t assetTilesetLoaderSync(assetloading_t *loading) {
out->uv[0] = endianLittleToHostFloat(*(float *)(data + 16));
out->uv[1] = endianLittleToHostFloat(*(float *)(data + 20));
if(out->uv[0] < 0.0f || out->uv[0] > 1.0f) {
memoryFree(data);
assetLoaderErrorThrow(loading, "Invalid u0 value in tileset");
}
if(out->uv[1] < 0.0f || out->uv[1] > 1.0f) {
memoryFree(data);
assetLoaderErrorThrow(loading, "Invalid v0 value in tileset");
+5 -4
View File
@@ -27,11 +27,12 @@ errorret_t assetMeshLoaderAsync(assetloading_t *loading) {
assetFileInit(file, loading->entry->name, NULL, NULL)
);
uint8_t *raw = memoryAllocate(file->size);
assetLoaderErrorChain(loading, assetFileOpen(file));
assetLoaderErrorChain(loading, assetFileRead(file, raw, file->size));
assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file));
uint8_t *raw = memoryAllocate(file->size);
assetLoaderErrorChainFree(loading, raw, assetFileRead(file, raw, file->size));
assetLoaderErrorChainFree(loading, raw, assetFileClose(file));
assetLoaderErrorChainFree(loading, raw, assetFileDispose(file));
assertTrue(file->lastRead == file->size, "Failed to read entire DMF file.");
if(raw[0] != 'D' || raw[1] != 'M' || raw[2] != 'F') {
+1 -2
View File
@@ -115,8 +115,7 @@ errorret_t assetModelLoaderSync(assetloading_t *loading) {
assetUnlockEntry(jsonEntry);
// Lock and load the mesh sub-asset.
assetentry_t *meshEntry =
assetLock(meshName, ASSET_LOADER_TYPE_MESH, NULL);
assetentry_t *meshEntry = assetLock(meshName, ASSET_LOADER_TYPE_MESH, NULL);
ret = assetRequireLoaded(meshEntry);
if(errorIsNotOk(ret)) {
assetUnlockEntry(meshEntry);
+5 -4
View File
@@ -32,13 +32,14 @@ errorret_t assetJsonLoaderAsync(assetloading_t *loading) {
assetLoaderErrorThrow(loading, "JSON exceeds maximum allowed size");
}
assetLoaderErrorChain(loading, assetFileOpen(file));
size_t fileSize = (size_t)file->size;
uint8_t *buffer = memoryAllocate(fileSize);
assetLoaderErrorChain(loading, assetFileOpen(file));
assetLoaderErrorChain(loading, assetFileRead(file, buffer, fileSize));
assetLoaderErrorChainFree(loading, buffer, assetFileRead(file, buffer, fileSize));
assertTrue(file->lastRead == file->size, "Failed to read entire JSON file.");
assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file));
assetLoaderErrorChainFree(loading, buffer, assetFileClose(file));
assetLoaderErrorChainFree(loading, buffer, assetFileDispose(file));
loading->loading.json.buffer = buffer;
loading->loading.json.size = fileSize;
+30 -129
View File
@@ -30,8 +30,8 @@ errorret_t assetLocaleLoaderAsync(assetloading_t *loading) {
assetLoaderErrorChain(loading, assetFileOpen(&localeFile->file));
char_t buffer[1024];
assetLoaderErrorChain(loading, assetLocaleGetHeader(
localeFile, buffer, sizeof(buffer)
assetLoaderErrorChain(loading, assetLocaleGetString(
localeFile, "", 0, buffer, sizeof(buffer)
));
assetLoaderErrorChain(loading, assetLocaleParseHeader(
localeFile, buffer, sizeof(buffer)
@@ -71,12 +71,6 @@ errorret_t assetLocaleDispose(assetentry_t *entry) {
assertIsMainThread("Must be called from the main thread.");
assetlocalefile_t *localeFile = &entry->data.locale;
if(localeFile->cache != NULL) {
memoryFree(localeFile->cache);
localeFile->cache = NULL;
}
errorChain(assetFileClose(&localeFile->file));
return assetFileDispose(&localeFile->file);
}
@@ -476,94 +470,7 @@ errorret_t assetLocaleLineUnbuffer(
errorOk();
}
errorret_t assetLocaleCacheFind(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralCount,
char_t *stringBuffer,
const size_t stringBufferSize,
bool_t *outHit
) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(messageId, "Message ID cannot be NULL.");
assertNotNull(outHit, "outHit cannot be NULL.");
assertStrLenMin(messageId, 1, "Message ID cannot be empty.");
*outHit = false;
if(file->cache == NULL) errorOk();
assetlocalecache_t *cache = file->cache;
for(uint8_t i = 0; i < ASSET_LOCALE_CACHE_COUNT; i++) {
assetlocalecacheentry_t *entry = &cache->entries[i];
if(entry->messageId[0] == '\0') break;// unused tail - nothing further
if(entry->pluralCount != pluralCount) continue;
if(!stringEquals(entry->messageId, messageId)) continue;
// Move to the front of the LRU order (a no-op when already there).
if(i > 0) {
assetlocalecacheentry_t hit = *entry;
memoryMove(
&cache->entries[1], &cache->entries[0],
i * sizeof(assetlocalecacheentry_t)
);
cache->entries[0] = hit;
}
size_t len = strlen(cache->entries[0].value);
if(len >= stringBufferSize) errorThrow("String buffer overflow");
memoryCopy(stringBuffer, cache->entries[0].value, len + 1);
*outHit = true;
errorOk();
}
errorOk();
}
void assetLocaleCacheInsert(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralCount,
const char_t *value
) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(messageId, "Message ID cannot be NULL.");
assertNotNull(value, "Value cannot be NULL.");
assertStrLenMin(messageId, 1, "Message ID cannot be empty.");
// Caching is a pure optimization - a message ID or value too long for a
// fixed cache slot is just never cached, not an error.
if(strlen(messageId) >= ASSET_LOCALE_CACHE_KEY_MAX) return;
if(strlen(value) >= ASSET_LOCALE_CACHE_VALUE_MAX) return;
if(file->cache == NULL) {
file->cache =
(assetlocalecache_t *)memoryAllocate(sizeof(assetlocalecache_t));
memoryZero(file->cache, sizeof(assetlocalecache_t));
}
// Shift every entry down one slot, dropping the least-recently-used one
// off the end, to make room for the new entry at the front. This assumes
// messageId is never already present elsewhere in the cache, which holds
// as long as callers only insert after a confirmed assetLocaleCacheFind
// miss (a hit would have returned before reaching this point).
memoryMove(
&file->cache->entries[1], &file->cache->entries[0],
(ASSET_LOCALE_CACHE_COUNT - 1) * sizeof(assetlocalecacheentry_t)
);
assetlocalecacheentry_t *entry = &file->cache->entries[0];
stringCopy(entry->messageId, messageId, ASSET_LOCALE_CACHE_KEY_MAX);
entry->pluralCount = pluralCount;
stringCopy(entry->value, value, ASSET_LOCALE_CACHE_VALUE_MAX);
}
// Shared by assetLocaleGetString (external callers, messageId required
// non-empty) and assetLocaleGetHeader (messageId "", the PO format's own
// sentinel for its header entry - see assetLocaleGetHeader). Caching is
// skipped entirely for an empty messageId: assetLocaleCacheFind/Insert
// both reject one outright (same guard as assetLocaleGetString's own),
// and it's a one-shot boot-time read anyway, not worth caching.
errorret_t assetLocaleGetStringLookup(
errorret_t assetLocaleGetString(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralCount,
@@ -576,12 +483,21 @@ errorret_t assetLocaleGetStringLookup(
assertNotNull(stringBuffer, "String buffer cannot be NULL.");
assertTrue(stringBufferSize > 0, "String buffer size must be > 0");
bool_t cacheHit = false;
if(messageId[0] != '\0') {
errorChain(assetLocaleCacheFind(
file, messageId, pluralCount, stringBuffer, stringBufferSize, &cacheHit
));
if(cacheHit) errorOk();
// Check the cache before rewinding/rescanning the whole file.
for(uint8_t i = 0; i < ASSET_LOCALE_STRING_CACHE_SIZE; i++) {
assetlocalecacheentry_t *entry = &file->stringCache[i];
if(
!entry->valid ||
entry->pluralCount != pluralCount ||
stringCompare(messageId, entry->messageId) != 0
) continue;
size_t valueLen = strlen(entry->value);
if(valueLen >= stringBufferSize) {
errorThrow("String buffer overflow");
}
memoryCopy(stringBuffer, entry->value, valueLen + 1);
errorOk();
}
assetfilelinereader_t reader;
@@ -727,38 +643,23 @@ errorret_t assetLocaleGetStringLookup(
errorThrow("Failed to find msgstr for message ID: %s", messageId);
}
if(messageId[0] != '\0') {
assetLocaleCacheInsert(file, messageId, pluralCount, stringBuffer);
// Cache the resolved string for future lookups, if it fits.
if(
strlen(messageId) < ASSET_LOCALE_CACHE_MESSAGE_ID_MAX &&
strlen(stringBuffer) < ASSET_LOCALE_CACHE_VALUE_MAX
) {
assetlocalecacheentry_t *entry = &file->stringCache[file->stringCacheNext];
stringCopy(entry->messageId, messageId, sizeof(entry->messageId) - 1);
stringCopy(entry->value, stringBuffer, sizeof(entry->value) - 1);
entry->pluralCount = pluralCount;
entry->valid = true;
file->stringCacheNext =
(file->stringCacheNext + 1) % ASSET_LOCALE_STRING_CACHE_SIZE;
}
errorOk();
}
errorret_t assetLocaleGetString(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralCount,
char_t *stringBuffer,
const size_t stringBufferSize
) {
assertNotNull(messageId, "Message ID cannot be NULL.");
assertStrLenMin(messageId, 1, "Message ID cannot be empty.");
return assetLocaleGetStringLookup(
file, messageId, pluralCount, stringBuffer, stringBufferSize
);
}
errorret_t assetLocaleGetHeader(
assetlocalefile_t *file,
char_t *stringBuffer,
const size_t stringBufferSize
) {
return assetLocaleGetStringLookup(
file, "", 0, stringBuffer, stringBufferSize
);
}
errorret_t assetLocaleGetStringWithVA(
assetlocalefile_t *file,
const char_t *messageId,
+31 -148
View File
@@ -28,6 +28,27 @@ typedef struct {
/** Maximum number of distinct plural forms a locale file may declare. */
#define ASSET_LOCALE_FILE_PLURAL_FORM_COUNT 6
/** Max distinct resolved strings cached per open locale file. */
#define ASSET_LOCALE_STRING_CACHE_SIZE 16
/** Max message ID length (incl. null terminator) storable in the cache. */
#define ASSET_LOCALE_CACHE_MESSAGE_ID_MAX 128
/** Max resolved string length (incl. null terminator) storable in the cache. */
#define ASSET_LOCALE_CACHE_VALUE_MAX 256
/**
* A single cached (messageId, pluralCount) -> resolved string lookup, used by
* @ref assetLocaleGetString to avoid rescanning the whole PO file for
* repeated lookups of the same message.
*/
typedef struct {
bool_t valid;
char_t messageId[ASSET_LOCALE_CACHE_MESSAGE_ID_MAX];
int32_t pluralCount;
char_t value[ASSET_LOCALE_CACHE_VALUE_MAX];
} assetlocalecacheentry_t;
/**
* Comparison operator used in a plural-form expression.
*
@@ -70,41 +91,6 @@ typedef struct {
};
} assetlocalearg_t;
/** Number of recently resolved strings @ref assetlocalecache_t remembers. */
#define ASSET_LOCALE_CACHE_COUNT 128
/** Max length (excluding null terminator) of a cacheable message ID. */
#define ASSET_LOCALE_CACHE_KEY_MAX 64
/** Max length (excluding null terminator) of a cacheable resolved string. */
#define ASSET_LOCALE_CACHE_VALUE_MAX 256
/** One (messageId, pluralCount) -> resolved string cache slot. */
typedef struct {
char_t messageId[ASSET_LOCALE_CACHE_KEY_MAX];
int32_t pluralCount;
char_t value[ASSET_LOCALE_CACHE_VALUE_MAX];
} assetlocalecacheentry_t;
/**
* Fixed-size move-to-front LRU cache of recently resolved locale strings.
* assetLocaleGetString() re-scans and re-decompresses the whole PO file on
* every miss, which is expensive to repeat for strings a screen fetches
* every time it opens (menu labels, etc) - this cache lets identical
* (messageId, pluralCount) lookups skip that entirely.
*
* Lazily allocated on the first cache insert (see assetlocalefile_t.cache)
* so locale entries that are never queried, or a file that's disposed
* before anything is cached, never pay for it.
*/
typedef struct {
/**
* Entries ordered most-recently-used first. An entry with
* messageId[0] == '\0' (and every entry after it) is unused.
*/
assetlocalecacheentry_t entries[ASSET_LOCALE_CACHE_COUNT];
} assetlocalecache_t;
/**
* Runtime state for an open locale file.
*
@@ -134,15 +120,11 @@ typedef struct {
/** Form index used when no conditional clause matches. */
uint8_t pluralDefaultIndex;
/**
* Recently resolved string cache, or NULL if nothing has been cached yet.
* Heap-allocated rather than embedded because assetlocalefile_t lives
* inside the shared assetloaderoutput_t union alongside every other
* asset type - embedding a 128-entry cache there would size that union
* (and therefore every one of the ASSET_ENTRY_COUNT_MAX asset slots,
* regardless of what type of asset occupies it) up by the same amount.
*/
assetlocalecache_t *cache;
/** Ring buffer of recently resolved (messageId, pluralCount) lookups. */
assetlocalecacheentry_t stringCache[ASSET_LOCALE_STRING_CACHE_SIZE];
/** Next slot in @ref stringCache to overwrite. */
uint8_t stringCacheNext;
} assetlocalefile_t;
/** Convenience alias - the loaded output type of a locale asset entry. */
@@ -248,93 +230,15 @@ errorret_t assetLocaleLineUnbuffer(
const size_t stringBufferSize
);
/**
* Searches a locale file's cache for a previously resolved
* (messageId, pluralCount) pair.
*
* On a hit, copies the cached value into `stringBuffer` (erroring if it
* doesn't fit, same contract as @ref assetLocaleGetString) and moves the
* entry to the front of the cache's move-to-front LRU order. On a miss,
* `stringBuffer` is left untouched.
*
* @param file Locale file whose cache to search. Its cache may be NULL
* (nothing cached yet), which is treated as a miss.
* @param messageId Message ID to look up.
* @param pluralCount Plural count the original lookup used.
* @param stringBuffer Destination buffer, filled only on a hit.
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
* @param outHit Set to true on a cache hit, false on a miss.
* @return OK on success (hit or miss), error if a hit's cached value does
* not fit `stringBuffer`.
*/
errorret_t assetLocaleCacheFind(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralCount,
char_t *stringBuffer,
const size_t stringBufferSize,
bool_t *outHit
);
/**
* Records a resolved (messageId, pluralCount) -> value string at the front
* of the cache's move-to-front LRU order, evicting the least-recently-used
* entry if the cache is already full. Lazily allocates the cache (see
* assetlocalefile_t.cache) on the first call.
*
* Caching is a pure optimization: if `messageId` or `value` is too long to
* fit the cache's fixed-size slots, this silently does nothing rather than
* erroring or growing the cache.
*
* @param file Locale file whose cache to insert into.
* @param messageId Message ID that was looked up.
* @param pluralCount Plural count the lookup was made with.
* @param value Resolved string to cache.
*/
void assetLocaleCacheInsert(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralCount,
const char_t *value
);
/**
* Shared lookup core behind assetLocaleGetString and assetLocaleGetHeader:
* checks the file's cache first (see @ref assetLocaleCacheFind; skipped
* entirely for an empty messageId, since the cache rejects one), on a
* miss rewinds the file and scans from the beginning, then caches the
* result (see @ref assetLocaleCacheInsert, same empty-messageId skip)
* before returning. For plural entries (`msgid_plural`) the
* `pluralCount` is evaluated against the loaded plural rules to select
* the correct `msgstr[N]` form.
*
* Unlike assetLocaleGetString, messageId may be `""` here (see
* assetLocaleGetHeader) - this is the shared implementation both of
* them delegate to, not a public entry point of its own in practice.
*
* @param file Locale file to search. Must be open.
* @param messageId PO message ID to find, or `""` for the header entry.
* @param pluralCount Count used to select the plural form (ignored for
* singular entries).
* @param stringBuffer Buffer to receive the translated string.
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
* @return OK on success, error if the message ID is not found or I/O fails.
*/
errorret_t assetLocaleGetStringLookup(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralCount,
char_t *stringBuffer,
const size_t stringBufferSize
);
/**
* Looks up a translated string by message ID from the open locale file.
* See @ref assetLocaleGetStringLookup for the lookup/caching mechanics.
*
* Rewinds the file and scans from the beginning on every call. For plural
* entries (`msgid_plural`) the `pluralCount` is evaluated against the loaded
* plural rules to select the correct `msgstr[N]` form.
*
* @param file Locale file to search. Must be open.
* @param messageId PO message ID to find. Must be non-empty - use
* @ref assetLocaleGetHeader to read the header entry.
* @param messageId PO message ID to find (`""` retrieves the header entry).
* @param pluralCount Count used to select the plural form (ignored for
* singular entries).
* @param stringBuffer Buffer to receive the translated string.
@@ -349,27 +253,6 @@ errorret_t assetLocaleGetString(
const size_t stringBufferSize
);
/**
* Reads the PO file's header entry (the `msgid ""` block every PO file
* starts with, holding metadata like the plural-forms rule) - see @ref
* assetLocaleParseHeader, its caller. A dedicated function rather than
* calling assetLocaleGetString(file, "", ...) since messageId "" is a
* PO-format-internal sentinel, not a real (untrusted) caller-supplied
* message ID, so it doesn't go through assetLocaleGetString's normal
* non-empty validation.
*
* @param file Locale file to search. Must be open.
* @param stringBuffer Buffer to receive the raw header block.
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
* @return OK on success, error if the header entry is missing or I/O
* fails.
*/
errorret_t assetLocaleGetHeader(
assetlocalefile_t *file,
char_t *stringBuffer,
const size_t stringBufferSize
);
/**
* Looks up a translated string and formats it with a `printf`-style variadic
* argument list.
-255
View File
@@ -1,255 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetmp3loader.h"
#include "util/memory.h"
#include "util/math.h"
#include "assert/assert.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
// How far into the file (after any ID3v2 tag) assetMp3ParseHeader() will
// search for the first valid MPEG frame sync. Real encoders write it
// within the first handful of bytes; this is a generous sane upper bound
// (matching assetwavloader.c's own approach to bounding a stack buffer)
// rather than a real expectation of needing that much.
#define ASSET_MP3_HEADER_SEARCH_MAX 8192
// MPEG-1 Layer III bitrates (kbps), indexed by the header's 4-bit bitrate
// index. Index 0 ("free format") and 15 (reserved) aren't supported.
static const uint16_t ASSET_MP3_BITRATE_MPEG1_L3[16] = {
0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0
};
// MPEG-2/2.5 Layer III bitrates (kbps) - a different table from MPEG-1's.
static const uint16_t ASSET_MP3_BITRATE_MPEG2_L3[16] = {
0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0
};
static const uint32_t ASSET_MP3_SAMPLE_RATE_MPEG1[4] = {
44100, 48000, 32000, 0
};
static const uint32_t ASSET_MP3_SAMPLE_RATE_MPEG2[4] = {
22050, 24000, 16000, 0
};
static const uint32_t ASSET_MP3_SAMPLE_RATE_MPEG25[4] = {
11025, 12000, 8000, 0
};
errorret_t assetMp3LoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Async loader should not be on main thread.");
if(loading->loading.mp3.state != ASSET_MP3_LOADER_STATE_READ_HEADER) {
errorOk();
}
assetmp3file_t *mp3File = &loading->entry->data.mp3;
memoryZero(mp3File, sizeof(assetmp3file_t));
assetfile_t file;
assetLoaderErrorChain(loading, assetFileInit(
&file, loading->entry->name, NULL, NULL
));
assetLoaderErrorChain(loading, assetFileOpen(&file));
assetLoaderErrorChain(loading, assetMp3ParseHeader(&file, mp3File));
assetLoaderErrorChain(loading, assetFileClose(&file));
assetLoaderErrorChain(loading, assetFileDispose(&file));
loading->loading.mp3.state = ASSET_MP3_LOADER_STATE_DONE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetMp3LoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_MP3, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.mp3.state) {
case ASSET_MP3_LOADER_STATE_INITIAL:
loading->loading.mp3.state = ASSET_MP3_LOADER_STATE_READ_HEADER;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
errorOk();
break;
case ASSET_MP3_LOADER_STATE_DONE:
break;
default:
errorOk();
}
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
errorret_t assetMp3Dispose(assetentry_t *entry) {
assertNotNull(entry, "Asset entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_MP3, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
errorOk();
}
errorret_t assetMp3ParseHeader(assetfile_t *file, assetmp3file_t *mp3File) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(mp3File, "Mp3 file cannot be NULL.");
memoryZero(mp3File, sizeof(assetmp3file_t));
// Skip a leading ID3v2 tag if present: "ID3" + version(2) + flags(1) + a
// 4-byte syncsafe (7 usable bits/byte) size covering everything after
// this 10-byte header.
uint8_t id3Header[10];
errorChain(assetFileRead(file, id3Header, sizeof(id3Header)));
size_t searchBase;
if(memoryCompare(id3Header, "ID3", 3) == 0) {
const uint32_t tagSize = (
((uint32_t) (id3Header[6] & 0x7F) << 21) |
((uint32_t) (id3Header[7] & 0x7F) << 14) |
((uint32_t) (id3Header[8] & 0x7F) << 7) |
((uint32_t) (id3Header[9] & 0x7F))
);
errorChain(assetFileRead(file, NULL, tagSize));
searchBase = sizeof(id3Header) + tagSize;
} else {
// No ID3v2 tag - rewind the probe bytes just consumed so the frame
// sync search below starts from the true beginning of the file.
errorChain(assetFileRewind(file));
searchBase = 0;
}
const size_t searchWindowSize = mathMin(
(size_t) ASSET_MP3_HEADER_SEARCH_MAX,
(size_t) file->size > searchBase ? (size_t) file->size - searchBase : 0
);
if(searchWindowSize < 4) {
errorThrow(
"MP3 file is too short to contain a frame header: %s", file->filename
);
}
uint8_t *window = (uint8_t *) memoryAllocate(searchWindowSize);
errorret_t readRet = assetFileRead(file, window, searchWindowSize);
if(errorIsNotOk(readRet)) {
memoryFree(window);
errorChain(readRet);
}
bool_t found = false;
size_t frameIndex = 0;
for(size_t i = 0; i + 4 <= searchWindowSize; i++) {
if(window[i] != 0xFF || (window[i + 1] & 0xE0) != 0xE0) continue;
const uint8_t versionBits = (window[i + 1] >> 3) & 0x3;
const uint8_t layerBits = (window[i + 1] >> 1) & 0x3;
// reserved version, or not Layer III
if(versionBits == 1 || layerBits != 1) continue;
const uint8_t bitrateIndex = (window[i + 2] >> 4) & 0xF;
const uint8_t sampleRateIndex = (window[i + 2] >> 2) & 0x3;
if(
bitrateIndex == 0 || bitrateIndex == 15 || sampleRateIndex == 3
) continue;
const uint8_t channelMode = (window[i + 3] >> 6) & 0x3;
const bool_t isMpeg1 = versionBits == 3;
mp3File->bitrateKbps = isMpeg1
? ASSET_MP3_BITRATE_MPEG1_L3[bitrateIndex]
: ASSET_MP3_BITRATE_MPEG2_L3[bitrateIndex];
mp3File->sampleRate = isMpeg1
? ASSET_MP3_SAMPLE_RATE_MPEG1[sampleRateIndex]
: (versionBits == 2
? ASSET_MP3_SAMPLE_RATE_MPEG2[sampleRateIndex]
: ASSET_MP3_SAMPLE_RATE_MPEG25[sampleRateIndex]);
mp3File->samplesPerFrame = isMpeg1 ? 1152 : 576;
mp3File->channels = channelMode == 3 ? 1 : 2;
// A Xing/Info header, if present, sits right after the side info -
// whose size depends on MPEG version and channel mode - immediately
// following the 4-byte header (plus a 2-byte CRC, if the protection
// bit says one follows).
const bool_t hasCrc = (window[i + 1] & 0x1) == 0;
const size_t sideInfoSize = isMpeg1
? (mp3File->channels == 1 ? 17 : 32)
: (mp3File->channels == 1 ? 9 : 17);
const size_t xingOffset = i + 4 + (hasCrc ? 2 : 0) + sideInfoSize;
if(
xingOffset + 8 <= searchWindowSize &&
(
memoryCompare(window + xingOffset, "Xing", 4) == 0 ||
memoryCompare(window + xingOffset, "Info", 4) == 0
)
) {
const uint8_t *flagsBytes = window + xingOffset + 4;
const uint32_t flags = (
((uint32_t) flagsBytes[0] << 24) | ((uint32_t) flagsBytes[1] << 16) |
((uint32_t) flagsBytes[2] << 8) | (uint32_t) flagsBytes[3]
);
if((flags & 0x1) != 0 && xingOffset + 12 <= searchWindowSize) {
const uint8_t *framesBytes = window + xingOffset + 8;
const uint32_t xingFrameCount = (
((uint32_t) framesBytes[0] << 24) |
((uint32_t) framesBytes[1] << 16) |
((uint32_t) framesBytes[2] << 8) |
(uint32_t) framesBytes[3]
);
// The Xing/Info header's frame count includes the header's own
// frame (this one, at `i`) - which libmad (and sceMp3) will
// attempt to decode like any other, but which doesn't contribute a
// real decodable frame of audio the way every other one does.
// Confirmed against a real LAME-encoded file: its Xing header
// declared 40 frames, but decoding actually produced exactly 39
// frames' worth of real PCM - without this -1, playback would
// permanently stall one frame short of the declared total (audible
// as "never loops"), since real decode output can never catch up
// to an overstated total.
if(xingFrameCount > 0) {
mp3File->totalFrames =
(size_t) (xingFrameCount - 1) * mp3File->samplesPerFrame;
}
}
}
frameIndex = i;
found = true;
break;
}
memoryFree(window);
if(!found) {
errorThrow(
"MP3 file has no valid MPEG-1/2/2.5 Layer III frame within the first "
"%u bytes: %s",
(uint32_t) searchWindowSize, file->filename
);
}
mp3File->dataOffset = searchBase + frameIndex;
mp3File->dataSize = (size_t) file->size - mp3File->dataOffset;
// No Xing/Info header found - estimate assuming constant bitrate (the
// common case when one's genuinely absent; a real VBR file without one
// is rare and will just get an approximate duration/loop point instead
// of an exact one).
if(mp3File->totalFrames == 0) {
const float_t durationSeconds = (
((float_t) mp3File->dataSize * 8.0f) /
((float_t) mp3File->bitrateKbps * 1000.0f)
);
mp3File->totalFrames =
(size_t) (durationSeconds * (float_t) mp3File->sampleRate);
}
errorOk();
}
-113
View File
@@ -1,113 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "asset/assetfile.h"
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
typedef struct { void *nothing; } assetmp3loaderinput_t;
typedef enum {
ASSET_MP3_LOADER_STATE_INITIAL,
ASSET_MP3_LOADER_STATE_READ_HEADER,
ASSET_MP3_LOADER_STATE_DONE
} assetmp3loaderstate_t;
typedef struct {
assetmp3loaderstate_t state;
} assetmp3loaderloading_t;
/**
* Parsed metadata for an MP3 asset - deliberately just enough to configure
* a decoder and know the clip's total length, not anything about its
* actual compressed content (which is read/decoded on demand at playback
* time - see audiostreammp3.c). Only MPEG-1/2/2.5 Layer III ("MP3" in the
* everyday sense) is supported; Layers I/II are rejected.
*/
typedef struct {
uint32_t sampleRate;
uint8_t channels;
// 1152 for MPEG-1, 576 for MPEG-2/2.5 - how many PCM samples (per
// channel) one compressed MPEG frame decodes to.
uint16_t samplesPerFrame;
// The first frame's bitrate, in kbps. Used only as a fallback duration
// estimate (assuming CBR) when no Xing/Info header is found - see
// assetMp3ParseHeader()'s own comment.
uint32_t bitrateKbps;
// Byte offset (from the start of the file) of the first real MPEG
// frame, i.e. right after any leading ID3v2 tag.
size_t dataOffset;
// Bytes of compressed MPEG data, from dataOffset to the end of the file.
size_t dataSize;
// Decoded PCM frame count for the whole clip - exact if a Xing/Info
// header was found (the common case for anything encoded with a modern
// tool), otherwise estimated from bitrateKbps/dataSize assuming CBR (see
// assetMp3ParseHeader()'s own comment) - unlike assetwavfile_t.dataSize,
// MP3 has no header field that gives this directly.
size_t totalFrames;
} assetmp3file_t;
typedef assetmp3file_t assetmp3output_t;
/**
* Async (background-thread) half of the MP3 loader - opens the asset file,
* parses its header (see assetMp3ParseHeader()), and closes it again. Never
* buffers the compressed MPEG data itself; that's read on demand at
* playback time by audiostreammp3.c via its own independent file handle.
*
* @param loading The asset loading slot.
* @return Error indicating success or failure.
*/
errorret_t assetMp3LoaderAsync(assetloading_t *loading);
/**
* Sync (main-thread) half of the MP3 loader - a simple state machine that
* schedules the async header parse and marks the entry loaded once it's
* done, mirroring assetWavLoaderSync()'s shape exactly.
*
* @param loading The asset loading slot.
* @return Error indicating success or failure.
*/
errorret_t assetMp3LoaderSync(assetloading_t *loading);
/**
* Disposes an MP3 asset entry. A no-op - an assetmp3file_t owns no heap
* allocations, and playback streams open their own independent file
* handles (see audiostreammp3.c).
*
* @param entry The asset entry to dispose.
* @return Error indicating success or failure.
*/
errorret_t assetMp3Dispose(assetentry_t *entry);
/**
* Parses an MP3 file's metadata from an already-opened asset file
* positioned at its very start: skips a leading ID3v2 tag if present,
* scans forward for the first valid MPEG-1/2/2.5 Layer III frame header
* (rejecting anything else - other layers, or no valid frame found within
* a sane search window), and checks that frame for a Xing/Info header
* (found in the vast majority of real-world MP3s, VBR or CBR) to get an
* exact total-frame count; falls back to a CBR estimate from the first
* frame's bitrate and the file's remaining size if absent.
*
* Never reads more than a bounded lookahead window into memory - the bulk
* of the file (the actual compressed audio, following the parsed frame's
* position) is left untouched, exactly like assetWavParseHeader().
*
* @param file Asset file to parse, positioned at offset 0.
* @param mp3File Filled with the parsed metadata on success.
* @return Error indicating success or failure.
*/
errorret_t assetMp3ParseHeader(assetfile_t *file, assetmp3file_t *mp3File);
@@ -5,5 +5,5 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
assetmp3loader.c
assetscriptloader.c
)
@@ -0,0 +1,115 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetscriptloader.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
static void assetScriptSettleWithError(
assetscriptoutput_t *output,
const char_t *message
) {
jerry_value_t errVal = jerry_string_sz(message);
jerry_value_t rejectResult = jerry_promise_reject(output->promise, errVal);
jerry_value_free(rejectResult);
jerry_value_free(errVal);
}
errorret_t assetScriptLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_SCRIPT, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
assetentry_t *entry = loading->entry;
assetscriptoutput_t *output = &entry->data.script;
assertTrue(
output->promise != 0,
"Script entry has no promise - was it requested via include()?"
);
assetfile_t file;
uint8_t *buffer = NULL;
size_t size = 0;
errorret_t err = assetFileInit(&file, entry->name, NULL, NULL);
if(errorIsOk(err)) err = assetFileReadEntire(&file, &buffer, &size);
if(errorIsOk(err)) err = assetFileDispose(&file);
if(errorIsNotOk(err)) {
assetScriptSettleWithError(output, err.state->message);
entry->state = ASSET_ENTRY_STATE_ERROR;
errorChain(err);
}
char_t *src = (char_t *)memoryAllocate(size + 1);
memoryCopy(src, buffer, size);
src[size] = '\0';
memoryFree(buffer);
// Scripts export their public API by assigning to the global `module`.
// Swap it out around the eval so this doesn't clobber a caller's own
// in-flight include() of a different file.
jerry_value_t global = jerry_current_realm();
jerry_value_t moduleKey = jerry_string_sz("module");
jerry_value_t prevModule = jerry_object_get(global, moduleKey);
jerry_value_t undef = jerry_undefined();
jerry_object_set(global, moduleKey, undef);
jerry_value_free(undef);
jerry_value_t evalResult = jerry_eval(
(const jerry_char_t *)src, size, JERRY_PARSE_NO_OPTS
);
memoryFree(src);
if(jerry_value_is_exception(evalResult)) {
jerry_value_t errVal = jerry_exception_value(evalResult, false);
jerry_value_t rejectResult = jerry_promise_reject(output->promise, errVal);
jerry_value_free(rejectResult);
jerry_value_free(errVal);
jerry_value_free(evalResult);
jerry_value_t moduleVal = jerry_object_get(global, moduleKey);
jerry_value_free(moduleVal);
jerry_object_set(global, moduleKey, prevModule);
jerry_value_free(prevModule);
jerry_value_free(moduleKey);
jerry_value_free(global);
entry->state = ASSET_ENTRY_STATE_ERROR;
errorThrow("Script error in '%s'", entry->name);
}
jerry_value_free(evalResult);
jerry_value_t moduleVal = jerry_object_get(global, moduleKey);
jerry_object_set(global, moduleKey, prevModule);
jerry_value_free(prevModule);
jerry_value_free(moduleKey);
jerry_value_free(global);
jerry_value_t resolveResult = jerry_promise_resolve(output->promise, moduleVal);
jerry_value_free(resolveResult);
jerry_value_free(moduleVal);
entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
errorret_t assetScriptDispose(assetentry_t *entry) {
assertNotNull(entry, "Asset entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_SCRIPT, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
assetscriptoutput_t *output = &entry->data.script;
if(output->promise != 0) {
jerry_value_free(output->promise);
output->promise = 0;
}
errorOk();
}
@@ -0,0 +1,45 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/assetfile.h"
#include <jerryscript.h>
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
/**
* Output data for a script asset entry. The promise is created once, the
* first time a script requests this file (see moduleIncludeInclude), and is
* owned by the entry for its lifetime - every subsequent request for the
* same file is handed a copy of this same promise instead of starting a
* second load. It is resolved (with the script's exported `module` value)
* or rejected (with the JS exception) exactly once, the moment the entry
* transitions to ASSET_ENTRY_STATE_LOADED or ASSET_ENTRY_STATE_ERROR.
*/
typedef struct {
jerry_value_t promise;
} assetscriptoutput_t;
/**
* Loads and evaluates a script asset synchronously (reads the whole file
* from the archive, then runs it) and resolves/rejects the entry's promise
* with the outcome. Scripts are small and read instantly, so there is no
* async (background-thread) phase - this is the only loader function.
*
* @param loading The asset loading slot.
* @return An error if reading failed, or errorOk() (a script exception is
* reported via promise rejection, not a returned error).
*/
errorret_t assetScriptLoaderSync(assetloading_t *loading);
/**
* Releases the promise reference held by a script asset entry.
*
* @param entry The asset entry to dispose.
*/
errorret_t assetScriptDispose(assetentry_t *entry);
-181
View File
@@ -1,181 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetwavloader.h"
#include "util/memory.h"
#include "util/endian.h"
#include "assert/assert.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
// "RIFF" + chunkSize + "WAVE", before any sub-chunks begin.
#define ASSET_WAV_RIFF_HEADER_SIZE 12
// A sub-chunk header is a 4-byte id followed by a 4-byte little-endian size.
#define ASSET_WAV_CHUNK_HEADER_SIZE 8
#define ASSET_WAV_FMT_CHUNK_SIZE_MIN 16
// Sane upper bound for a stack buffer - real fmt chunks (PCM or otherwise)
// never come close to this; anything bigger is treated as malformed.
#define ASSET_WAV_FMT_CHUNK_SIZE_MAX 64
errorret_t assetWavLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Async loader should not be on main thread.");
if(loading->loading.wav.state != ASSET_WAV_LOADER_STATE_READ_HEADER) {
errorOk();
}
assetwavfile_t *wavFile = &loading->entry->data.wav;
memoryZero(wavFile, sizeof(assetwavfile_t));
assetfile_t file;
assetLoaderErrorChain(loading, assetFileInit(
&file, loading->entry->name, NULL, NULL
));
assetLoaderErrorChain(loading, assetFileOpen(&file));
assetLoaderErrorChain(loading, assetWavParseHeader(&file, wavFile));
assetLoaderErrorChain(loading, assetFileClose(&file));
assetLoaderErrorChain(loading, assetFileDispose(&file));
loading->loading.wav.state = ASSET_WAV_LOADER_STATE_DONE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetWavLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_WAV, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.wav.state) {
case ASSET_WAV_LOADER_STATE_INITIAL:
loading->loading.wav.state = ASSET_WAV_LOADER_STATE_READ_HEADER;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
errorOk();
break;
case ASSET_WAV_LOADER_STATE_DONE:
break;
default:
errorOk();
}
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
errorret_t assetWavDispose(assetentry_t *entry) {
assertNotNull(entry, "Asset entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_WAV, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
errorOk();
}
errorret_t assetWavParseHeader(
assetfile_t *file,
assetwavfile_t *wavFile
) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(wavFile, "Wav file cannot be NULL.");
uint8_t riffHeader[ASSET_WAV_RIFF_HEADER_SIZE];
errorChain(assetFileRead(file, riffHeader, sizeof(riffHeader)));
if(memoryCompare(riffHeader, "RIFF", 4) != 0) {
errorThrow("WAV file has an invalid RIFF header: %s", file->filename);
}
if(memoryCompare(riffHeader + 8, "WAVE", 4) != 0) {
errorThrow("WAV file has an invalid WAVE header: %s", file->filename);
}
bool_t foundFormat = false;
bool_t foundData = false;
uint16_t audioFormat = 0;
// Walk the chunk list, reading only chunk headers (and the small "fmt "
// body) - every other chunk, "data"'s sample bytes included, is skipped
// via a NULL-buffer read rather than buffered into memory. Stops as soon
// as "data" is found; nothing after it matters here.
while(!foundData && (size_t) file->position < (size_t) file->size) {
uint8_t chunkHeader[ASSET_WAV_CHUNK_HEADER_SIZE];
errorChain(assetFileRead(file, chunkHeader, sizeof(chunkHeader)));
uint32_t chunkSizeLE;
memoryCopy(&chunkSizeLE, chunkHeader + 4, sizeof(chunkSizeLE));
const uint32_t chunkSize = endianLittleToHost32(chunkSizeLE);
// Chunks are padded to an even total size - the pad byte (if any)
// isn't included in chunkSize but still needs to be skipped over.
const uint32_t chunkSizePadded = chunkSize + (chunkSize % 2);
if(memoryCompare(chunkHeader, "fmt ", 4) == 0) {
if(
chunkSize < ASSET_WAV_FMT_CHUNK_SIZE_MIN ||
chunkSize > ASSET_WAV_FMT_CHUNK_SIZE_MAX
) {
errorThrow("WAV 'fmt ' chunk has an unsupported size: %u", chunkSize);
}
uint8_t fmtBuffer[ASSET_WAV_FMT_CHUNK_SIZE_MAX];
errorChain(assetFileRead(file, fmtBuffer, chunkSize));
if(chunkSize % 2 != 0) {
errorChain(assetFileRead(file, NULL, 1));
}
uint16_t u16;
uint32_t u32;
memoryCopy(&u16, fmtBuffer + 0, sizeof(u16));
audioFormat = endianLittleToHost16(u16);
memoryCopy(&u16, fmtBuffer + 2, sizeof(u16));
wavFile->channels = (uint8_t) endianLittleToHost16(u16);
memoryCopy(&u32, fmtBuffer + 4, sizeof(u32));
wavFile->sampleRate = endianLittleToHost32(u32);
memoryCopy(&u16, fmtBuffer + 14, sizeof(u16));
wavFile->bitsPerSample = (uint8_t) endianLittleToHost16(u16);
foundFormat = true;
} else if(memoryCompare(chunkHeader, "data", 4) == 0) {
wavFile->dataOffset = (size_t) file->position;
wavFile->dataSize = chunkSize;
foundData = true;
} else {
errorChain(assetFileRead(file, NULL, chunkSizePadded));
}
}
if(!foundFormat) {
errorThrow("WAV file is missing its 'fmt ' chunk: %s", file->filename);
}
if(!foundData) {
errorThrow("WAV file is missing its 'data' chunk: %s", file->filename);
}
if(audioFormat != 1) {
errorThrow(
"Unsupported WAV audio format: %u (only PCM is supported): %s",
audioFormat, file->filename
);
}
if(wavFile->bitsPerSample != 16 && wavFile->bitsPerSample != 24) {
errorThrow(
"Unsupported WAV bits per sample: %u (only 16/24-bit is supported): %s",
wavFile->bitsPerSample, file->filename
);
}
if(wavFile->channels == 0) {
errorThrow("WAV file declares 0 channels: %s", file->filename);
}
errorOk();
}
-117
View File
@@ -1,117 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/assetfile.h"
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
/** Input passed to the wav loader - currently unused. */
typedef struct { void *nothing; } assetwavloaderinput_t;
typedef enum {
ASSET_WAV_LOADER_STATE_INITIAL,
ASSET_WAV_LOADER_STATE_READ_HEADER,
ASSET_WAV_LOADER_STATE_DONE
} assetwavloaderstate_t;
/** Per-slot scratch data used while the wav file is loading. */
typedef struct {
assetwavloaderstate_t state;
} assetwavloaderloading_t;
/**
* Parsed metadata for a WAV asset - only the RIFF/WAVE/fmt/data chunk
* headers are ever read; the PCM sample data itself is never loaded here
* (see @ref assetWavParseHeader). Playback reads sample data directly
* from the archive on demand instead - see audiostreampcm.h.
*/
typedef struct {
/** Sample rate of the PCM data, in Hz. */
uint32_t sampleRate;
/** Number of interleaved channels in the PCM data. */
uint8_t channels;
/**
* Bits per sample of the *source* file data - 16 or 24 (see
* assetWavParseHeader). Playback always reads 16-bit samples out via
* audioStreamPcmRead() regardless of this - a 24-bit source is
* truncated to 16-bit there, since none of this project's audio
* backends (PSP/Dolphin hardware, SDL2 on Linux) accept anything wider.
*/
uint8_t bitsPerSample;
/** Byte offset from the start of the file to the first PCM sample. */
size_t dataOffset;
/** Size of the PCM data, in bytes. */
size_t dataSize;
} assetwavfile_t;
/** Convenience alias - the loaded output type of a wav asset entry. */
typedef assetwavfile_t assetwavoutput_t;
/**
* Asynchronous loader callback. Opens the WAV file and reads just enough of
* it to locate and parse the `fmt ` chunk and locate (not read) the `data`
* chunk - see @ref assetWavParseHeader. All I/O happens here so the main
* thread is not blocked. Sets entry state to `ASSET_ENTRY_STATE_PENDING_SYNC`
* on success or `ASSET_ENTRY_STATE_ERROR` on failure.
*
* @param loading The loading slot for this asset entry.
* @return OK on success, error otherwise.
*/
errorret_t assetWavLoaderAsync(assetloading_t *loading);
/**
* Synchronous loader callback. Confirms the async phase completed and marks
* the entry as `ASSET_ENTRY_STATE_LOADED`.
*
* @param loading The loading slot for this asset entry.
* @return OK on success, error otherwise.
*/
errorret_t assetWavLoaderSync(assetloading_t *loading);
/**
* Dispose callback. The wav asset owns no allocations of its own (its data
* chunk is read directly from the archive by whichever streams are playing
* it, each through their own handle - see audiostreampcm.h), so this is
* currently a no-op beyond the standard asserts.
*
* @param entry The asset entry to dispose.
* @return OK on success, error otherwise.
*/
errorret_t assetWavDispose(assetentry_t *entry);
/**
* Parses a RIFF/WAVE file's chunk structure from an already-open asset
* file, reading only chunk headers (and the small `fmt ` chunk body) -
* every other chunk, including `data`'s actual sample bytes, is skipped
* over via `assetFileRead(file, NULL, size)` rather than read into memory,
* so this never buffers the (potentially large) PCM payload.
*
* Stops as soon as the `data` chunk header is found, recording its file
* offset and declared size in `wavFile` without reading any of its bytes -
* the file is left positioned at the start of the PCM data.
*
* Only PCM (audio format 1), 16- or 24-bit-per-sample WAV data is
* supported - see audiostreampcm.h's audioStreamPcmRead() for how a
* 24-bit source gets truncated to the 16-bit output every platform
* backend expects. Requires the `fmt ` chunk to appear before `data`, per
* the WAV spec's recommended ordering.
*
* @param file An open asset file, positioned at the start of the WAV data.
* @param wavFile Struct whose fields will be filled in.
* @return OK on success, error if the file is malformed or an unsupported
* format.
*/
errorret_t assetWavParseHeader(
assetfile_t *file,
assetwavfile_t *wavFile
);
-14
View File
@@ -1,14 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
audio.c
)
# Subdirs
add_subdirectory(mixer)
add_subdirectory(stream)
-73
View File
@@ -1,73 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "audio.h"
#include "audio/mixer/audiomixer.h"
#include "util/memory.h"
#include "assert/assert.h"
audio_t AUDIO;
errorret_t audioInit() {
memoryZero(&AUDIO, sizeof(audio_t));
errorChain(audioPlatformInit());
errorChain(audioMixerInit());
errorOk();
}
audiostream_t * audioAquireStream(assetentry_t *asset) {
assertNotNull(asset, "Asset cannot be NULL.");
// Same check audioStreamInit() makes - see its own comment on why this
// is an assert (a programmer error, not untrusted data). Checking here
// too catches the mistake as early as possible, before any stream slot
// is handed out for it.
assertTrue(
audioStreamTypeForAssetType(asset->type) != AUDIO_STREAM_TYPE_NULL,
"Unsupported asset type for an audio stream."
);
for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) {
audiostream_t *stream = &AUDIO.streams[i];
if(stream->type == AUDIO_STREAM_TYPE_NULL) {
return stream;
}
}
return NULL;
}
errorret_t audioUpdateEarly() {
errorChain(audioPlatformUpdate());
errorChain(audioMixerUpdateEarly());
for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) {
audiostream_t *stream = &AUDIO.streams[i];
errorChain(audioStreamUpdate(stream));
}
errorOk();
}
errorret_t audioUpdateLate() {
errorChain(audioMixerUpdateLate());
errorOk();
}
errorret_t audioDispose() {
for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) {
audiostream_t *stream = &AUDIO.streams[i];
errorChain(audioStreamDispose(stream));
}
errorChain(audioMixerDispose());
errorChain(audioPlatformDispose());
errorOk();
}
-77
View File
@@ -1,77 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#include "audio/stream/audiostream.h"
#include "audio/audioplatform.h"
#ifndef audioPlatformInit
#error "audioPlatformInit is not defined"
#endif
#ifndef audioPlatformUpdate
#error "audioPlatformUpdate is not defined"
#endif
#ifndef audioPlatformDispose
#error "audioPlatformDispose is not defined"
#endif
typedef struct {
audiostream_t streams[AUDIO_STREAMS_MAX];
} audio_t;
extern audio_t AUDIO;
/**
* Initializes the audio subsystem.
*
* @return Error indicating success or failure of the operation.
*/
errorret_t audioInit();
/**
* Aquires an available audio stream for playing the given asset. Can return
* NULL if there is no available stream slot.
*
* The returned stream is not yet configured to play `asset` - call
* audioStreamInit(stream, asset) next.
*
* @param asset The asset the caller intends to play - validated eagerly so
* an unsupported asset type is caught here rather than only
* once audioStreamInit() is called.
* @return Pointer to an available audio stream, or NULL if none are free.
*/
audiostream_t * audioAquireStream(assetentry_t *asset);
/**
* Updates the audio subsystem, updating every active stream. Should be
* called once per frame, before rendering - keeps stream buffering/decode
* work off the render thread's critical path (see duskmad's MP3 decode
* ring for why this matters).
*
* @return Error indicating success or failure of the operation.
*/
errorret_t audioUpdateEarly();
/**
* Updates the audio subsystem's end-of-frame work - currently just starting
* whatever the audio mixer queued this frame (see
* audioMixerUpdateLate()'s own comment). Should be called once per frame,
* after rendering.
*
* @return Error indicating success or failure of the operation.
*/
errorret_t audioUpdateLate();
/**
* Disposes the audio subsystem, stopping and disposing every active stream.
*
* @return Error indicating success or failure of the operation.
*/
errorret_t audioDispose();
-199
View File
@@ -1,199 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "audiomixer.h"
#include "audio/stream/audiostream.h"
#include "util/memory.h"
#include "util/string.h"
#include "assert/assert.h"
audiomixer_t AUDIO_MIXER;
errorret_t audioMixerInit() {
memoryZero(&AUDIO_MIXER, sizeof(audiomixer_t));
audiomixerchannel_t channel = 0;
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
AUDIO_MIXER.channels[channel].fade = 1.0f;
// -1 means "no fade in progress" - see its own comment; zero-init
// would otherwise look like an active fade at time 0.
AUDIO_MIXER.channels[channel].fadeTime = -1.0f;
channel++;
}
errorOk();
}
errorret_t audioMixerUpdateEarly() {
audiomixerchannel_t channel = 0;
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
// One channel's error (e.g. a failed asset load) must not stop every
// other channel from being updated this frame - caught and logged
// rather than propagated, same as audioStream*IsFinished()'s own
// per-stream error handling.
errorret_t ret = audioMixerChannelUpdateEarly(
channel, &AUDIO_MIXER.channels[channel]
);
if(errorIsNotOk(ret)) errorCatch(errorPrint(ret));
channel++;
}
errorOk();
}
errorret_t audioMixerUpdateLate() {
audiomixerchannel_t channel = 0;
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
errorret_t ret =
audioMixerChannelUpdateLate(&AUDIO_MIXER.channels[channel]);
if(errorIsNotOk(ret)) errorCatch(errorPrint(ret));
channel++;
}
errorOk();
}
void audioMixerPlay(
const char_t *file,
const audiomixerchannel_t channel,
const float_t volume,
const float_t pan
) {
audioMixerQueuePlay(file, channel, volume, pan, false, 0, -1.0f, 0.0f);
}
void audioMixerPlayLooped(
const char_t *file,
const audiomixerchannel_t channel,
const float_t volume,
const float_t pan,
const uint8_t loopCount,
const float_t loopStart,
const float_t loopTo
) {
audioMixerQueuePlay(
file, channel, volume, pan, true, loopCount, loopStart, loopTo
);
}
void audioMixerQueuePlay(
const char_t *file,
const audiomixerchannel_t channel,
const float_t volume,
const float_t pan,
const bool_t looping,
const uint8_t loopCount,
const float_t loopStart,
const float_t loopTo
) {
assertStrLenMin(file, 1, "File is required, to stop use audioMixerStop");
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
assertTrue(volume > 0.0f && volume <= 1.0f, "Volume is out of range");
assertTrue(
pan >= AUDIO_STREAM_LEFT && pan <= AUDIO_STREAM_RIGHT,
"Pan is out of range"
);
assertTrue(
!looping || loopStart < 0.0f || loopTo < loopStart,
"Loop points incorrect"
);
audiomixercommand_t *command = &AUDIO_MIXER.channels[channel].pending;
command->command = AUDIO_MIXER_COMMAND_PLAY;
stringCopy(command->file, file, AUDIO_PATH_MAX);
command->volume = volume;
command->pan = pan;
command->looping = looping;
command->loopCount = loopCount;
command->loopStart = loopStart;
command->loopTo = loopTo;
}
void audioMixerStop(const audiomixerchannel_t channel) {
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
AUDIO_MIXER.channels[channel].pending.command = AUDIO_MIXER_COMMAND_STOP;
}
void audioMixerPause(const audiomixerchannel_t channel) {
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
if(stream != NULL) audioStreamPause(stream);
}
void audioMixerResume(const audiomixerchannel_t channel) {
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
if(stream != NULL) audioStreamPlay(stream);
}
void audioMixerSetPan(const audiomixerchannel_t channel, const float_t pan) {
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
assertTrue(
pan >= AUDIO_STREAM_LEFT && pan <= AUDIO_STREAM_RIGHT,
"Pan is out of range"
);
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
if(stream != NULL) audioStreamSetDirectionality(stream, pan);
}
void audioMixerSetLoop(
const audiomixerchannel_t channel,
const bool_t looping,
const uint8_t loopCount,
const float_t loopStart,
const float_t loopTo
) {
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
assertTrue(
!looping || loopStart < 0.0f || loopTo < loopStart,
"Loop points incorrect"
);
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
if(stream == NULL) return;
audioStreamSetLooping(stream, looping);
if(looping) {
audioStreamSetLoopPoints(stream, loopStart, loopTo);
audioStreamSetLoopLimit(stream, loopCount);
}
}
void audioMixerFadeTo(
const audiomixerchannel_t channel,
const float_t from,
const float_t to,
const float_t duration,
const easingtype_t easing
) {
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
audioMixerChannelFadeTo(
&AUDIO_MIXER.channels[channel], from, to, duration, easing
);
}
bool_t audioMixerIsFading(const audiomixerchannel_t channel) {
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
return audioMixerChannelIsFading(&AUDIO_MIXER.channels[channel]);
}
errorret_t audioMixerDispose() {
audiomixerchannel_t channel = 0;
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
errorChain(audioMixerChannelStopStream(&AUDIO_MIXER.channels[channel]));
channel++;
}
errorOk();
}
-204
View File
@@ -1,204 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "audio/mixer/audiomixerchannel.h"
typedef struct {
audiomixerchannelstate_t channels[AUDIO_MIXER_CHANNEL_COUNT];
} audiomixer_t;
extern audiomixer_t AUDIO_MIXER;
/**
* Initializes the audio mixer.
*/
errorret_t audioMixerInit();
/**
* Updates the audio mixer, called before rendering (the start of the
* frame) - see audioMixerChannelUpdateEarly()'s own comment, run for every
* channel.
*/
errorret_t audioMixerUpdateEarly();
/**
* Updates the audio mixer, called at the end of each frame - see
* audioMixerChannelUpdateLate()'s own comment, run for every channel.
*/
errorret_t audioMixerUpdateLate();
/**
* Same as audioMixerPlayLooped() but with no looping.
*
* @param file File to be played.
* @param channel Channel you want to play this sound on.
* @param volume Volume of the sound, from 0.0 (silent) to 1.0 (loudest).
* @param pan Stereo panning of the sound, from AUDIO_STREAM_LEFT to
* AUDIO_STREAM_RIGHT.
*/
void audioMixerPlay(
const char_t *file,
const audiomixerchannel_t channel,
const float_t volume,
const float_t pan
);
/**
* Queues a sound to be played on the next audio mixer update, which occurs at
* the end of each frame.
*
* Mixer channels can only hold one voice (audio stream) at a time. If you try
* to queue multiple sounds on the same channel only the last one will be played
* and will stop any actively playing on that channel currently.
*
* Volume is also mixed based on the channel, so supplying volume 1.0 is then
* multiplied by the channel's volume, e.g. 0.5*1.0 = 0.5.
*
* @param file File to be played.
* @param channel Channel you want to play this sound on.
* @param volume Volume of the sound, from 0.0 (silent) to 1.0 (loudest).
* @param pan Stereo panning of the sound, from AUDIO_STREAM_LEFT to
* AUDIO_STREAM_RIGHT.
* @param loopCount How many times to loop the sound, 0 for infinite looping.
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
* the whole stream (the default).
* @param loopTo Where the loop segment starts, in seconds.
*/
void audioMixerPlayLooped(
const char_t *file,
const audiomixerchannel_t channel,
const float_t volume,
const float_t pan,
const uint8_t loopCount,
const float_t loopStart,
const float_t loopTo
);
/**
* Shared implementation behind audioMixerPlay()/audioMixerPlayLooped() -
* queues an AUDIO_MIXER_COMMAND_PLAY for the given channel, to be loaded at
* the end of this frame and started at the start of the next (see
* audioMixerUpdateLate()/audioMixerUpdateEarly()).
*
* @param file File to be played.
* @param channel Channel you want to play this sound on.
* @param volume Volume of the sound, from 0.0 (silent) to 1.0 (loudest).
* @param pan Stereo panning of the sound, from AUDIO_STREAM_LEFT to
* AUDIO_STREAM_RIGHT.
* @param looping Whether the stream should loop once it finishes.
* @param loopCount How many times to loop the sound, 0 for infinite looping.
* Ignored unless looping is true.
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
* the whole stream. Ignored unless looping is true.
* @param loopTo Where the loop segment starts, in seconds. Ignored unless
* looping is true.
*/
void audioMixerQueuePlay(
const char_t *file,
const audiomixerchannel_t channel,
const float_t volume,
const float_t pan,
const bool_t looping,
const uint8_t loopCount,
const float_t loopStart,
const float_t loopTo
);
/**
* Stops playing sound on the given channel.
*
* @param channel Channel to stop.
*/
void audioMixerStop(const audiomixerchannel_t channel);
/**
* Pauses the given channel's currently playing stream, if any - a safe
* no-op if the channel isn't playing anything. Playback position is
* retained, so audioMixerResume() continues from the same point.
*
* @param channel Channel to pause.
*/
void audioMixerPause(const audiomixerchannel_t channel);
/**
* Resumes the given channel's currently paused stream, if any - a safe
* no-op if the channel isn't playing anything.
*
* @param channel Channel to resume.
*/
void audioMixerResume(const audiomixerchannel_t channel);
/**
* Sets the stereo panning of the given channel's currently playing stream,
* if any - a safe no-op if the channel isn't playing anything. Only
* affects what's playing right now; a later audioMixerPlay()/
* audioMixerPlayLooped() call on this channel uses its own `pan` argument
* instead.
*
* @param channel Channel to update.
* @param pan Stereo panning, from AUDIO_STREAM_LEFT to AUDIO_STREAM_RIGHT.
*/
void audioMixerSetPan(const audiomixerchannel_t channel, const float_t pan);
/**
* Sets the looping behaviour of the given channel's currently playing
* stream, if any - a safe no-op if the channel isn't playing anything.
* Only affects what's playing right now; a later audioMixerPlay()/
* audioMixerPlayLooped() call on this channel uses its own loop arguments
* instead.
*
* @param channel Channel to update.
* @param looping Whether the stream should loop.
* @param loopCount How many times to loop, 0 for infinite. Ignored unless
* looping is true.
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
* the whole stream. Ignored unless looping is true.
* @param loopTo Where the loop segment starts, in seconds. Ignored unless
* looping is true.
*/
void audioMixerSetLoop(
const audiomixerchannel_t channel,
const bool_t looping,
const uint8_t loopCount,
const float_t loopStart,
const float_t loopTo
);
/**
* Starts fading the given channel from `from` to `to` over `duration`
* seconds, eased by `easing` - see audioMixerChannelFadeTo()'s own
* comment. Continues running (advanced every audioMixerUpdateEarly()) even
* if the channel isn't currently playing anything.
*
* @param channel Channel to fade.
* @param from Starting fade value, from 0.0 (silent) to 1.0 (loudest).
* @param to Ending fade value, from 0.0 (silent) to 1.0 (loudest).
* @param duration How long the fade takes, in seconds.
* @param easing Easing curve to apply to the fade's progress.
*/
void audioMixerFadeTo(
const audiomixerchannel_t channel,
const float_t from,
const float_t to,
const float_t duration,
const easingtype_t easing
);
/**
* Whether the given channel currently has a fade in progress (started via
* audioMixerFadeTo() and not yet finished).
*
* @param channel Channel to check.
* @return true if a fade is still in progress.
*/
bool_t audioMixerIsFading(const audiomixerchannel_t channel);
/**
* Disposes the audio mixer.
*/
errorret_t audioMixerDispose();
-223
View File
@@ -1,223 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "audiomixerchannel.h"
#include "asset/asset.h"
#include "audio/audio.h"
#include "audio/stream/audiostream.h"
#include "audio/stream/audiostreamtype.h"
#include "save/save.h"
#include "time/time.h"
#include "util/math.h"
#include "assert/assert.h"
errorret_t audioMixerChannelStopStream(audiomixerchannelstate_t *state) {
assertNotNull(state, "State cannot be NULL.");
if(state->stream == NULL) errorOk();
errorChain(audioStreamDispose(state->stream));
state->stream = NULL;
errorOk();
}
void audioMixerChannelFadeTo(
audiomixerchannelstate_t *state,
const float_t from,
const float_t to,
const float_t duration,
const easingtype_t easing
) {
assertNotNull(state, "State cannot be NULL.");
state->fade = from;
state->fadeFrom = from;
state->fadeTo = to;
state->fadeDuration = duration;
state->fadeEasing = easing;
// A non-positive duration finishes instantly - marked inactive right
// away (fadeTime < 0) rather than left at 0 to progress next frame,
// since there's nothing left to progress.
if(duration <= 0.0f) {
state->fade = to;
state->fadeTime = -1.0f;
} else {
state->fadeTime = 0.0f;
}
}
bool_t audioMixerChannelIsFading(const audiomixerchannelstate_t *state) {
assertNotNull(state, "State cannot be NULL.");
return state->fadeTime >= 0.0f;
}
void audioMixerChannelApplyVolume(
const audiomixerchannel_t channel,
audiomixerchannelstate_t *state
) {
assertNotNull(state, "State cannot be NULL.");
if(state->stream == NULL) return;
// Advances any in-progress fade before it's read below - see
// audioMixerChannelFadeTo()'s own comment on fadeTime's meaning.
if(state->fadeTime >= 0.0f) {
state->fadeTime += TIME.delta;
const float_t t = mathClamp(
state->fadeTime / state->fadeDuration, 0.0f, 1.0f
);
state->fade = state->fadeFrom +
(state->fadeTo - state->fadeFrom) * easingApply(state->fadeEasing, t);
if(state->fadeTime >= state->fadeDuration) {
state->fade = state->fadeTo;
state->fadeTime = -1.0f;
}
}
// state->fade and both SAVE.settings volumes have no setter - written
// directly by callers - so this is the only place any of them ever gets
// validated, rather than at the point they're set.
assertTrue(
state->fade >= 0.0f && state->fade <= 1.0f,
"Channel fade is out of range."
);
assertTrue(
SAVE.settings.audioChannelVolume[channel] >= 0.0f &&
SAVE.settings.audioChannelVolume[channel] <= 1.0f,
"Channel volume is out of range."
);
assertTrue(
SAVE.settings.audioMasterVolume >= 0.0f &&
SAVE.settings.audioMasterVolume <= 1.0f,
"Master volume is out of range."
);
// Final computed volume.
float_t volume = (
state->baseVolume *
state->fade *
SAVE.settings.audioChannelVolume[channel] *
SAVE.settings.audioMasterVolume
);
audioStreamSetVolume(state->stream, volume);
}
errorret_t audioMixerChannelUpdateEarly(
const audiomixerchannel_t channel,
audiomixerchannelstate_t *state
) {
assertNotNull(state, "State cannot be NULL.");
audiomixercommand_t *command = &state->pending;
if(command->command == AUDIO_MIXER_COMMAND_STOP) {
errorChain(audioMixerChannelStopStream(state));
command->command = AUDIO_MIXER_COMMAND_NONE;
audioMixerChannelApplyVolume(channel, state);
errorOk();
}
if(
command->command != AUDIO_MIXER_COMMAND_PLAY ||
command->loadingAsset == NULL
) {
// A PLAY command with no loadingAsset yet (command->loadingAsset ==
// NULL) was queued too late for the audioMixerChannelUpdateLate() that
// just ran immediately before this call to have locked it - the only
// way that happens is a command queued outside the normal per-frame
// cycle, e.g. during engine startup before any
// audioMixerChannelUpdateLate() has run yet. Left alone (still
// AUDIO_MIXER_COMMAND_PLAY) rather than treated as an error: the very
// next audioMixerChannelUpdateLate() will lock it, and the frame after
// that will reach here and apply it normally.
audioMixerChannelApplyVolume(channel, state);
errorOk();
}
// Blocks here if audioMixerChannelUpdateLate()'s load (kicked off at the
// end of the previous frame) hasn't finished yet - see this function's
// own doc comment on why that's accepted for now.
errorret_t loadRet = assetRequireLoaded(command->loadingAsset);
if(errorIsNotOk(loadRet)) {
assetUnlockEntry(command->loadingAsset);
command->loadingAsset = NULL;
command->command = AUDIO_MIXER_COMMAND_NONE;
errorChain(loadRet);
}
errorChain(audioMixerChannelStopStream(state));
audiostream_t *stream = audioAquireStream(command->loadingAsset);
assertNotNull(stream, "No free audio stream slots available.");
errorret_t initRet = audioStreamInit(stream, command->loadingAsset);
// The stream holds its own lock on the asset once initialized (or, on
// failure, audioStreamInit() has already released it itself) - either
// way this call's own lock is no longer needed.
assetUnlockEntry(command->loadingAsset);
command->loadingAsset = NULL;
command->command = AUDIO_MIXER_COMMAND_NONE;
errorChain(initRet);
// Forwards to this channel's own onLoop/onEnd (persistent across every
// play on this channel) rather than this one stream instance's own -
// see audiomixerchannelstate_t.onLoop's own comment.
stream->user = state;
stream->onLoop = audioMixerChannelOnStreamLoop;
stream->onEnd = audioMixerChannelOnStreamEnd;
audioStreamSetDirectionality(stream, command->pan);
if(command->looping) {
audioStreamSetLooping(stream, true);
audioStreamSetLoopPoints(stream, command->loopStart, command->loopTo);
audioStreamSetLoopLimit(stream, command->loopCount);
}
audioStreamPlay(stream);
state->stream = stream;
state->baseVolume = command->volume;
audioMixerChannelApplyVolume(channel, state);
errorOk();
}
errorret_t audioMixerChannelUpdateLate(audiomixerchannelstate_t *state) {
assertNotNull(state, "State cannot be NULL.");
audiomixercommand_t *command = &state->pending;
if(command->command != AUDIO_MIXER_COMMAND_PLAY) errorOk();
assetloadertype_t assetType = audioStreamAssetTypeForPath(command->file);
assertTrue(
assetType != ASSET_LOADER_TYPE_NULL, "Unsupported audio file extension."
);
// Begins loading now - kicked off at the end of this frame so it has
// until the start of the next (audioMixerChannelUpdateEarly()) to finish
// before that has to block on it.
command->loadingAsset = assetLock(command->file, assetType, NULL);
errorOk();
}
void audioMixerChannelOnStreamLoop(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
audiomixerchannelstate_t *state = (audiomixerchannelstate_t *) stream->user;
if(state->onLoop != NULL) state->onLoop(state);
}
void audioMixerChannelOnStreamEnd(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
audiomixerchannelstate_t *state = (audiomixerchannelstate_t *) stream->user;
if(state->onEnd != NULL) state->onEnd(state);
}
-241
View File
@@ -1,241 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#include "error/error.h"
#include "animation/easing.h"
// Forward-declared rather than including asset/asset.h - this header only
// ever needs a pointer to it, and pulling in the full asset module here
// risks an include cycle for anything that reaches this header via a
// cutscene item (cutscene.h -> cutsceneitem.h -> the audio cutscene items
// -> this header -> asset/asset.h, mid-parse). audiomixerchannel.c itself
// still includes the full header.
typedef struct assetentry_s assetentry_t;
typedef struct audiostream_s audiostream_t;
#define AUDIO_PATH_MAX 256
typedef enum {
AUDIO_MIXER_CHANNEL_BGM_0,
AUDIO_MIXER_CHANNEL_VOICE_0,
AUDIO_MIXER_CHANNEL_VOICE_1,
AUDIO_MIXER_CHANNEL_SFX_0,
AUDIO_MIXER_CHANNEL_SFX_1,
AUDIO_MIXER_CHANNEL_SFX_2,
AUDIO_MIXER_CHANNEL_SFX_3,
AUDIO_MIXER_CHANNEL_COUNT
} audiomixerchannel_t;
typedef enum {
AUDIO_MIXER_COMMAND_NONE,
AUDIO_MIXER_COMMAND_PLAY,
AUDIO_MIXER_COMMAND_STOP
} audiomixercommandtype_t;
typedef struct {
// What audioMixerChannelUpdateEarly() should do to this channel at the
// start of the next frame - AUDIO_MIXER_COMMAND_NONE if nothing's
// queued. Set by audioMixerPlay()/audioMixerPlayLooped()/
// audioMixerStop(); queuing a new command on a channel replaces, rather
// than stacks on top of, whatever was already queued for it this frame -
// only the most recent survives.
audiomixercommandtype_t command;
// AUDIO_MIXER_COMMAND_PLAY only, below.
char_t file[AUDIO_PATH_MAX];
float_t volume;
float_t pan;
bool_t looping;
uint8_t loopCount;
float_t loopStart;
float_t loopTo;
// Set by audioMixerChannelUpdateLate() (the end of the frame this PLAY
// command was queued on), once it locks the requested file and kicks off
// its load. audioMixerChannelUpdateEarly() (the start of the next frame)
// blocks on this being fully loaded before actually starting playback -
// see its own comment. NULL except in that in-between window.
assetentry_t *loadingAsset;
} audiomixercommand_t;
typedef struct audiomixerchannelstate_s audiomixerchannelstate_t;
typedef struct audiomixerchannelstate_s {
// Queued action for the next audioMixerChannelUpdateEarly() to apply.
audiomixercommand_t pending;
// This channel's currently playing stream, or NULL if nothing is -
// acquired from AUDIO.streams by audioMixerChannelUpdateEarly() when it
// applies an AUDIO_MIXER_COMMAND_PLAY, disposed the same way on
// AUDIO_MIXER_COMMAND_STOP or before a new AUDIO_MIXER_COMMAND_PLAY
// replaces it.
audiostream_t *stream;
// The per-sound volume `stream` was last started with (the `volume`
// argument to whichever audioMixerPlay()/audioMixerPlayLooped() call
// started it) - combined with this channel's fade, its own volume
// (SAVE.settings.audioChannelVolume) and the mixer's master volume
// (SAVE.settings.audioMasterVolume), every frame, to get the volume
// actually passed to audioStreamSetVolume(). Meaningless while `stream`
// is NULL.
float_t baseVolume;
// This channel's own fade multiplier, from 0.0 (fully faded out) to 1.0
// (no fade applied, the default) - transient runtime state, unlike the
// channel/master volumes below (which are persisted user preferences).
// No setter - write it directly; audioMixerChannelApplyVolume() asserts
// it's in range the next time it reads it, rather than validating at the
// point it's set.
float_t fade;
// Fade transition state, set by audioMixerChannelFadeTo() and advanced
// every frame by audioMixerChannelApplyVolume(), before it reads `fade`
// to compute the mixed volume. fadeTime < 0 means no fade is in progress
// (audioMixerChannelIsFading() is just `fadeTime >= 0`) - audioMixerInit()
// explicitly sets this to -1.0f, since zero-initializing it would
// otherwise look like an active fade at time 0.
float_t fadeFrom;
float_t fadeTo;
float_t fadeDuration;
float_t fadeTime;
easingtype_t fadeEasing;
// Arbitrary caller data, handed back as-is to onLoop/onEnd below - never
// read or written by the mixer itself. NULL by default.
void *user;
// Fired (from the main thread - safe to do arbitrary work, same
// guarantee as audiostream_t's own onLoop/onEnd) whenever this channel's
// currently playing stream loops, or reaches its natural end (including
// hitting its loop limit - see audioStreamSetLoopLimit()) and stops.
// Wired onto every stream this channel starts via
// audioMixerChannelOnStreamLoop()/OnStreamEnd() - not called directly by
// anything else. No setter - write these fields directly; NULL (the
// default) means not notified. Unlike `stream`/`pending`, these persist
// across every play on this channel, not just one.
void (*onLoop)(audiomixerchannelstate_t *state);
void (*onEnd)(audiomixerchannelstate_t *state);
} audiomixerchannelstate_t;
/**
* Stops and disposes the given channel's currently playing stream, if any -
* a safe no-op if the channel is already idle. Shared by
* audioMixerChannelUpdateEarly() (AUDIO_MIXER_COMMAND_STOP, and replacing a
* channel's stream before a new AUDIO_MIXER_COMMAND_PLAY starts) and
* audioMixerDispose().
*
* @param state The channel state to stop.
*/
errorret_t audioMixerChannelStopStream(audiomixerchannelstate_t *state);
/**
* Computes the given channel's actual playback volume - its currently
* playing sound's own volume (baseVolume), this channel's fade, this
* channel's own volume (SAVE.settings.audioChannelVolume[channel]) and the
* mixer's master volume (SAVE.settings.audioMasterVolume) - and applies it
* via audioStreamSetVolume(). Asserts fade and both save-settings volumes
* are each within [0.0, 1.0] - the only validation any of them ever gets,
* since none of them have a setter. A safe no-op if the channel isn't
* playing anything. Called every audioMixerChannelUpdateEarly(), not just
* when a PLAY command starts a new stream - see its own comment.
*
* @param channel Which channel `state` is, to index
* SAVE.settings.audioChannelVolume with.
* @param state The channel state to update.
*/
void audioMixerChannelApplyVolume(
const audiomixerchannel_t channel,
audiomixerchannelstate_t *state
);
/**
* Starts fading the given channel's `fade` multiplier from `from` to `to`
* over `duration` seconds, eased by `easing` - snaps `fade` to `from`
* immediately, then audioMixerChannelApplyVolume() advances it every frame
* from here on. A `duration` of 0 or less snaps straight to `to` and marks
* the fade as already finished (audioMixerChannelIsFading() returns
* false on the very next call).
*
* @param state The channel state to fade.
* @param from Starting fade value, from 0.0 (silent) to 1.0 (loudest).
* @param to Ending fade value, from 0.0 (silent) to 1.0 (loudest).
* @param duration How long the fade takes, in seconds.
* @param easing Easing curve to apply to the fade's progress.
*/
void audioMixerChannelFadeTo(
audiomixerchannelstate_t *state,
const float_t from,
const float_t to,
const float_t duration,
const easingtype_t easing
);
/**
* Whether the given channel currently has a fade in progress (started via
* audioMixerChannelFadeTo() and not yet finished).
*
* @param state The channel state to check.
* @return true if a fade is still in progress.
*/
bool_t audioMixerChannelIsFading(const audiomixerchannelstate_t *state);
/**
* Updates a single mixer channel, called before rendering (the start of
* the frame): applies whatever command (play, stop - including everything
* a play carries, pan/looping) audioMixerChannelUpdateLate() queued for
* loading at the end of the previous frame. If that load hasn't finished
* yet, this blocks (via assetRequireLoaded()) until it has - a deliberate
* stall for now rather than skipping a frame, since there's currently no
* way to only partially apply a channel's command. Also recomputes and
* reapplies this channel's mixed volume (see
* audioMixerChannelApplyVolume()) every time, regardless of whether a
* command was queued this frame, so a live change to this channel's fade,
* its own volume, or the master volume takes effect on whatever's already
* playing too.
*
* @param channel Which channel `state` is - see
* audioMixerChannelApplyVolume()'s own comment.
* @param state The channel state to update.
*/
errorret_t audioMixerChannelUpdateEarly(
const audiomixerchannel_t channel,
audiomixerchannelstate_t *state
);
/**
* Updates a single mixer channel, called at the end of each frame, once
* every other system has had a chance to queue a command via
* audioMixerPlay()/audioMixerPlayLooped()/audioMixerStop(). For a queued
* AUDIO_MIXER_COMMAND_PLAY, locks its file and begins loading it (see
* assetLock()) - giving it from now until the next
* audioMixerChannelUpdateEarly() to finish before that has to block on it.
* Actually starting/stopping playback happens there, not here.
*
* @param state The channel state to update.
*/
errorret_t audioMixerChannelUpdateLate(audiomixerchannelstate_t *state);
/**
* Trampoline wired onto every stream a channel starts (as that stream's
* onLoop) - forwards to the channel's own onLoop (see
* audiomixerchannelstate_t.onLoop's own comment) via stream->user, which
* audioMixerChannelUpdateEarly() points at the channel's own state.
*
* @param stream The stream that looped.
*/
void audioMixerChannelOnStreamLoop(audiostream_t *stream);
/**
* Same as audioMixerChannelOnStreamLoop() but wired onto onEnd, forwarding
* to the channel's own onEnd.
*
* @param stream The stream that ended.
*/
void audioMixerChannelOnStreamEnd(audiostream_t *stream);
-312
View File
@@ -1,312 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "audiostream.h"
#include "assert/assert.h"
#include "util/math.h"
errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset) {
assertNotNull(stream, "Stream cannot be NULL.");
assertNotNull(asset, "Asset cannot be NULL.");
assertTrue(
asset->state == ASSET_ENTRY_STATE_LOADED,
"Asset must be loaded before it can back an audio stream."
);
// A caller passing an asset type that can't back an audio stream is a
// programmer error, not something that can happen from untrusted data, so
// this is an assert rather than an errorThrow (see
// feedback_assert_vs_error convention).
assertTrue(
audioStreamTypeForAssetType(asset->type) != AUDIO_STREAM_TYPE_NULL,
"Unsupported asset type for an audio stream."
);
stream->state = 0;
stream->volume = 1.0f;
stream->directionality = AUDIO_STREAM_CENTER;
stream->loopStart = -1;
stream->loopTo = 0;
stream->duration = 0;
stream->startFrame = 0;
stream->seeking = false;
stream->user = NULL;
stream->onLoop = NULL;
stream->onEnd = NULL;
stream->loopCount = 0;
stream->lastLoopCount = 0;
stream->loopLimit = 0;
stream->loopRestartCount = 0;
// Locked for as long as the stream is in use (see audiostream_t.asset's
// own comment) - released in audioStreamDispose().
stream->asset = asset;
assetEntryLock(asset);
// Type-specific setup (audioStreamPcmInit() / audioStreamMp3Init())
// determines stream->type, sets stream->sampleRate/channels, and asks
// the platform implementation to set up its state.
errorret_t ret = asset->type == ASSET_LOADER_TYPE_MP3
? audioStreamMp3Init(stream)
: audioStreamPcmInit(stream);
if(errorIsNotOk(ret)) {
assetEntryUnlock(asset);
stream->asset = NULL;
errorChain(ret);
}
errorOk();
}
size_t audioStreamGetTotalFrames(const audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
return stream->type == AUDIO_STREAM_TYPE_MP3
? audioStreamMp3GetTotalFrames(stream)
: audioStreamPcmGetTotalFrames(stream);
}
errorret_t audioStreamSeek(audiostream_t *stream, const size_t frame) {
assertNotNull(stream, "Stream cannot be NULL.");
errorChain(
stream->type == AUDIO_STREAM_TYPE_MP3
? audioStreamMp3Seek(stream, frame)
: audioStreamPcmSeek(stream, frame)
);
errorOk();
}
errorret_t audioStreamRead(
audiostream_t *stream,
int16_t *buffer,
const size_t frameCount,
size_t *outFramesRead
) {
assertNotNull(stream, "Stream cannot be NULL.");
errorChain(
stream->type == AUDIO_STREAM_TYPE_MP3
? audioStreamMp3Read(stream, buffer, frameCount, outFramesRead)
: audioStreamPcmRead(stream, buffer, frameCount, outFramesRead)
);
errorOk();
}
void audioStreamPlay(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
stream->state |= AUDIO_STREAM_STATE_PLAYING;
}
void audioStreamPause(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
stream->state &= ~AUDIO_STREAM_STATE_PLAYING;
}
void audioStreamSetPosition(audiostream_t *stream, const float_t position) {
assertNotNull(stream, "Stream cannot be NULL.");
// Wrap into [0, duration).
float_t t = position;
while(t < 0) t += stream->duration;
while(t >= stream->duration) t -= stream->duration;
stream->startFrame = (size_t) (t * stream->sampleRate);
stream->seeking = true;
// Force the next audioStreamUpdate() to re-buffer from startFrame instead
// of continuing whatever was already buffered - see the platform Buffer()
// implementations for how each one applies startFrame; PSP is the one
// exception (see audioStreamSetPosition's own doc comment).
stream->state &= ~AUDIO_STREAM_STATE_BUFFERED;
}
void audioStreamSetLoopPoints(
audiostream_t *stream,
const float_t loopStart,
const float_t loopTo
) {
assertNotNull(stream, "Stream cannot be NULL.");
assertTrue(
loopStart < 0 || loopTo < loopStart,
"loopTo must be before loopStart."
);
stream->loopStart = loopStart;
stream->loopTo = loopTo;
}
void audioStreamGetPanFactors(
const audiostream_t *stream,
float_t *outLeft,
float_t *outRight
) {
assertNotNull(stream, "Stream cannot be NULL.");
assertNotNull(outLeft, "outLeft cannot be NULL.");
assertNotNull(outRight, "outRight cannot be NULL.");
// directionality is already a pan factor in AUDIO_STREAM_LEFT..RIGHT
// (-1.0..1.0) - assertTrue'd here rather than clamped, since a caller
// passing something outside that range is a programmer error (see
// audioStreamSetDirectionality()'s own assert).
const float_t pan = stream->directionality;
*outLeft = pan > 0 ? (1.0f - pan) : 1.0f;
*outRight = pan < 0 ? (1.0f + pan) : 1.0f;
}
size_t audioStreamComputeEndFrame(
const audiostream_t *stream,
const size_t startFrame,
const size_t totalFrames
) {
assertNotNull(stream, "Stream cannot be NULL.");
size_t endFrame = totalFrames;
if((stream->state & AUDIO_STREAM_STATE_LOOPING) && stream->loopStart >= 0) {
endFrame = mathMin(
(size_t) (stream->loopStart * stream->sampleRate), totalFrames
);
}
if(startFrame >= endFrame) endFrame = totalFrames;
return endFrame;
}
void audioStreamSetVolume(audiostream_t *stream, const float_t volume) {
assertNotNull(stream, "Stream cannot be NULL.");
assertTrue(volume >= 0.0f && volume <= 1.0f, "Volume is out of range.");
stream->volume = volume;
// TODO: Do I need to update the device output? PSP may require this
}
void audioStreamSetDirectionality(
audiostream_t *stream,
const float_t directionality
) {
assertNotNull(stream, "Stream cannot be NULL.");
assertTrue(
directionality >= AUDIO_STREAM_LEFT && directionality <= AUDIO_STREAM_RIGHT,
"Directionality is out of range."
);
stream->directionality = directionality;
// TODO: Need to update internal decoder?
}
void audioStreamSetLooping(audiostream_t *stream, const bool_t looping) {
assertNotNull(stream, "Stream cannot be NULL.");
if(looping) {
stream->state |= AUDIO_STREAM_STATE_LOOPING;
} else {
stream->state &= ~AUDIO_STREAM_STATE_LOOPING;
}
}
void audioStreamSetLoopLimit(audiostream_t *stream, const uint32_t loopLimit) {
assertNotNull(stream, "Stream cannot be NULL.");
stream->loopLimit = loopLimit;
stream->loopRestartCount = 0;
}
errorret_t audioStreamUpdate(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
if(stream->type == AUDIO_STREAM_TYPE_NULL) {
errorOk();
}
// Some platforms (PSP) loop entirely on their own background thread for
// gaplessness and can only safely notify onLoop by incrementing this
// counter from there, rather than calling onLoop directly off the main
// thread - see loopCount's own comment. Firing it here, unconditionally,
// catches up to the latest count in one call even if multiple loops
// happened between two Update() calls.
if(stream->loopCount != stream->lastLoopCount) {
stream->lastLoopCount = stream->loopCount;
if(stream->onLoop != NULL) {
stream->onLoop(stream);
}
}
// TODO: Once streamed (rather than fully in-memory) sources exist, this is
// where new data would be decoded/read in and re-buffered as playback
// consumes it.
// Checked in this order (finished-check before needs-buffering) so that a
// loop restart falls straight through into re-buffering within this same
// call, instead of leaving BUFFERED cleared for the caller to notice and
// act on next frame - that extra frame of latency was audible as a gap
// at every loop boundary.
if(
(stream->state & AUDIO_STREAM_STATE_PLAYING) &&
(stream->state & AUDIO_STREAM_STATE_BUFFERED) &&
audioStreamPlatformIsFinished(stream)
) {
// A limit of 0 means unlimited; otherwise this pass's restart only goes
// ahead while fewer than loopLimit restarts have already happened -
// once it's reached, fall through to the same stop/onEnd path as a
// non-looping stream instead of restarting again.
const bool_t loopLimitReached = stream->loopLimit > 0 &&
stream->loopRestartCount >= stream->loopLimit;
if((stream->state & AUDIO_STREAM_STATE_LOOPING) && !loopLimitReached) {
stream->state &= ~AUDIO_STREAM_STATE_BUFFERED;
stream->loopRestartCount++;
// Resume from loopTo rather than the very start of the buffer - only
// matters for platforms that reach this generic restart path at all
// (Linux and Dolphin, both of which re-buffer per pass and report
// "finished" at every loop boundary); PSP loops entirely on its own
// read-ahead ring instead (see loopRestartCount's own comment).
stream->startFrame = (size_t) (stream->loopTo * stream->sampleRate);
if(stream->onLoop != NULL) {
stream->onLoop(stream);
}
} else {
stream->state &=
~(AUDIO_STREAM_STATE_PLAYING | AUDIO_STREAM_STATE_BUFFERED);
if(stream->onEnd != NULL) {
stream->onEnd(stream);
}
}
}
if(
(stream->state & AUDIO_STREAM_STATE_PLAYING) &&
!(stream->state & AUDIO_STREAM_STATE_BUFFERED)
) {
errorChain(audioStreamPlatformBuffer(stream));
stream->state |= AUDIO_STREAM_STATE_BUFFERED;
}
errorOk();
}
errorret_t audioStreamDispose(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
if(stream->type != AUDIO_STREAM_TYPE_NULL) {
errorChain(audioStreamPlatformDispose(stream));
}
if(stream->type == AUDIO_STREAM_TYPE_PCM) {
errorChain(audioStreamPcmDispose(stream));
} else if(stream->type == AUDIO_STREAM_TYPE_MP3) {
errorChain(audioStreamMp3Dispose(stream));
}
if(stream->asset != NULL) {
assetEntryUnlock(stream->asset);
stream->asset = NULL;
}
stream->type = AUDIO_STREAM_TYPE_NULL;
errorOk();
}
-360
View File
@@ -1,360 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "audio/stream/audiostreamtype.h"
#include "audio/stream/audiostreampcm.h"
#include "audio/stream/audiostreammp3.h"
#include "audio/audiostreamplatform.h"
#include "asset/loader/assetentry.h"
#ifndef audioStreamPlatformInit
#error "audioStreamPlatformInit is not defined"
#endif
#ifndef audioStreamPlatformDispose
#error "audioStreamPlatformDispose is not defined"
#endif
#ifndef audioStreamPlatformBuffer
#error "audioStreamPlatformBuffer is not defined"
#endif
#ifndef audioStreamPlatformIsFinished
#error "audioStreamPlatformIsFinished is not defined"
#endif
#define AUDIO_STREAMS_MAX 8
#define AUDIO_STREAM_STATE_PLAYING (1 << 0)
#define AUDIO_STREAM_STATE_LOOPING (1 << 1)
#define AUDIO_STREAM_STATE_BUFFERED (1 << 2)
#define AUDIO_STREAM_CENTER 0.0f
#define AUDIO_STREAM_LEFT -1.0f
#define AUDIO_STREAM_RIGHT 1.0f
typedef struct audiostream_s audiostream_t;
typedef struct audiostream_s {
// Used for aquiring new data.
audistreamtype_t type;
// What state the stream is in. volatile: PSP's output thread reads
// AUDIO_STREAM_STATE_PLAYING directly to honor a pause promptly instead
// of only reacting once the main thread's own per-frame gate notices -
// see audioStreamPSPThreadFeed()'s own comment.
volatile uint8_t state;
// The asset backing this stream's data (e.g. a WAV file) - determines
// `type` (see audioStreamInit()) and is read from on demand by the
// type-specific module (e.g. audiostreampcm.h) rather than ever being
// fully decoded into memory up front. The stream holds its own lock on
// this entry (assetEntryLock()/assetEntryUnlock()) for as long as it's
// in use, independent of whatever lock(s) the caller that requested
// playback may also be holding.
assetentry_t *asset;
// Loudness, from 0.0 (silent) to 1.0 (loudest).
float_t volume;
// In stereo space, where do we send the audio - from AUDIO_STREAM_LEFT
// (-1.0) to AUDIO_STREAM_RIGHT (1.0), AUDIO_STREAM_CENTER (0.0) by
// default.
// TODO: Can we use a 3D vector + Pro Logic II?
float_t directionality;
// In seconds, where the loop segment ends and playback jumps back to
// loopTo - -1 (the default) means "at the end of the stream", i.e. loop
// the whole buffer. Set via audioStreamSetLoopPoints().
float_t loopStart;
// In seconds, where a loop jumps back to once it reaches loopStart.
// Defaults to 0 (start of stream). Set via audioStreamSetLoopPoints().
float_t loopTo;
// Cached duration of the stream in seconds.
float_t duration;
// Frame offset the next platform Buffer() call should start playback
// from - set by audioStreamSetPosition() (an explicit seek) and by
// audioStreamUpdate() itself (to loopTo's frame offset, for platforms
// that re-enter Buffer() on every loop restart rather than looping
// natively). Each platform's Buffer()-invoking entry point must read and
// reset this to 0 synchronously, in the same call that decided to
// (re)buffer - not later/asynchronously (e.g. from a feeder thread),
// since audioStreamUpdate() may already have moved on to something else
// that touches this field by the time an async reader gets to it.
size_t startFrame;
// True when startFrame came from an explicit audioStreamSetPosition()
// seek rather than a natural loop restart. Platforms whose Buffer() call
// can leave previously-queued audio still playing underneath the new
// pass (currently just Linux's SDL queue, kept deliberately overlapping
// across a loop restart to avoid a gap) need this to tell "jump now,
// discarding whatever's still playing" (seek) apart from "let the old
// tail keep playing while the new pass queues underneath it" (loop
// restart) - both look identical as just "a pending startFrame"
// otherwise. Consumed (reset to false) the same way as startFrame.
bool_t seeking;
// Callbacks
void *user;
void (*onLoop)(audiostream_t *stream);
void (*onEnd)(audiostream_t *stream);
// Incremented by platform code (from whatever thread/context it runs in)
// each time a loop happens, instead of calling onLoop directly - onLoop
// may do arbitrary, possibly-slow work (console printing, game logic),
// which is only safe to run from the main thread inside audioStreamUpdate().
// Calling it straight from a real-time audio thread risks starving the
// hardware buffer if it takes too long - confirmed as the real cause of
// a loud crackle on PSP once its feeder thread called onLoop inline.
volatile uint32_t loopCount;
// audioStreamUpdate()'s own record of the last loopCount it fired
// onLoop for - only ever touched from the main thread.
uint32_t lastLoopCount;
// Maximum number of times this stream is allowed to loop before stopping
// (firing onEnd) instead of restarting again - 0 (the default) means loop
// forever. Has no effect unless looping is also enabled via
// audioStreamSetLooping(). Set via audioStreamSetLoopLimit().
uint32_t loopLimit;
// How many loop restarts this stream has already committed to - compared
// against loopLimit each time a restart is considered, then incremented
// if it goes ahead; reset to 0 by audioStreamSetLoopLimit(). Distinct
// from loopCount (which tracks when a loop becomes audible, purely for
// onLoop notification, and is PSP-only) - this counts decided restarts,
// main-thread-only on every platform (PSP decides whether to loop from
// its own read-ahead ring, itself driven from the main thread via
// audioStreamPSPIsFinished() - see its own comment).
uint32_t loopRestartCount;
// PCM format of the stream's decoded output - read identically by every
// platform backend regardless of stream type (PCM decodes straight
// through; MP3 decodes to this same format), so it lives here rather
// than duplicated in both audiostreampcm_t and audiostreammp3_t. Set by
// whichever type-specific Init function runs (audioStreamPcmInit() /
// audioStreamMp3Init()).
uint32_t sampleRate;
uint8_t channels;
// Stream type specific data.
union {
audiostreampcm_t pcm;
audiostreammp3_t mp3;
};
// Platform-specific playback state (e.g. SDL2 device, PSP channel, ASND
// voice). Defined by each platform's audiostreamplatform.h.
audiostreamplatform_t platform;
} audiostream_t;
/**
* Initializes an audio stream to play the given asset, determining the
* stream's type from the asset's loader type (e.g. a WAV asset becomes an
* AUDIO_STREAM_TYPE_PCM stream) and dispatching to that type's own setup
* (e.g. audioStreamPcmInit()). Does not begin playback; call
* audioStreamPlay() once this returns.
*
* The stream takes its own lock on `asset` (see audiostream_t.asset's own
* comment), released by audioStreamDispose() - the asset must already be
* loaded (ASSET_ENTRY_STATE_LOADED) when this is called.
*
* @param stream The audio stream to initialize.
* @param asset The loaded asset to play - its type must be one this
* function supports (ASSET_LOADER_TYPE_WAV or
* ASSET_LOADER_TYPE_MP3).
* @return Error indicating success or failure.
*/
errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset);
/**
* Returns the total number of decoded PCM frames (one sample per channel)
* available in the stream's underlying data, regardless of its type -
* dispatches to audioStreamPcmGetTotalFrames() or
* audioStreamMp3GetTotalFrames(). Platform backends should use this rather
* than a type-specific function directly, so they don't need to know or
* care which type they're driving.
*
* @param stream The audio stream to query.
* @return The total number of frames available.
*/
size_t audioStreamGetTotalFrames(const audiostream_t *stream);
/**
* Seeks the stream's decode position to the given frame offset, regardless
* of its type - dispatches to audioStreamPcmSeek() or audioStreamMp3Seek().
*
* @param stream The audio stream to seek.
* @param frame Frame offset to seek to, relative to the start of the
* stream's decoded data.
* @return Error indicating success or failure.
*/
errorret_t audioStreamSeek(audiostream_t *stream, const size_t frame);
/**
* Reads up to frameCount frames of decoded PCM sample data from the
* stream's current position, regardless of its type - dispatches to
* audioStreamPcmRead() or audioStreamMp3Read(). See either for the exact
* short-read-at-end-of-stream contract, which is identical for both.
*
* @param stream The audio stream to read from.
* @param buffer Destination buffer, sized for at least frameCount frames.
* @param frameCount Maximum number of frames to read.
* @param outFramesRead Set to the number of frames actually read.
* @return Error indicating success or failure.
*/
errorret_t audioStreamRead(
audiostream_t *stream,
int16_t *buffer,
const size_t frameCount,
size_t *outFramesRead
);
/**
* Begins or resumes playback of the given audio stream.
*
* @param stream The audio stream to play.
*/
void audioStreamPlay(audiostream_t *stream);
/**
* Pauses playback of the given audio stream. Playback position is retained,
* so audioStreamPlay() resumes from the same point.
*
* @param stream The audio stream to pause.
*/
void audioStreamPause(audiostream_t *stream);
/**
* Seeks the given audio stream to the given position, in seconds, wrapping
* into range if the position is outside [0, duration). Takes effect on the
* next audioStreamUpdate() call for platforms that re-buffer per frame
* (e.g. Linux); on PSP, which manages an entire playback pass on its own
* feeder thread once started, a seek only takes effect the next time the
* stream begins playing from a stopped state, not instantaneously mid-pass.
*
* @param stream The audio stream to seek.
* @param position The new playback position, in seconds.
*/
void audioStreamSetPosition(audiostream_t *stream, const float_t position);
/**
* Sets the loop region for the given audio stream: once playback reaches
* loopStart, it jumps back to loopTo instead of continuing (or stopping,
* if not looping). Has no effect unless looping is also enabled via
* audioStreamSetLooping().
*
* @param stream The audio stream to update.
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
* the whole stream (the default).
* @param loopTo Where the loop segment starts, in seconds.
*/
void audioStreamSetLoopPoints(
audiostream_t *stream,
const float_t loopStart,
const float_t loopTo
);
/**
* Computes normalized left/right pan factors (0..1) for the given audio
* stream's directionality. Callers multiply these by their own
* platform-specific base volume representation.
*
* @param stream The audio stream to read directionality from.
* @param outLeft Set to the left channel's pan factor.
* @param outRight Set to the right channel's pan factor.
*/
void audioStreamGetPanFactors(
const audiostream_t *stream,
float_t *outLeft,
float_t *outRight
);
/**
* Computes the stop frame for a playback pass starting at startFrame: the
* current loop segment's end (stream->loopStart, converted to frames and
* clamped to totalFrames) if looping is enabled and a loop start is set,
* or totalFrames itself otherwise - including when startFrame has already
* reached or passed the computed loop end (e.g. a seek landing in an
* outro past the loop point), in which case this pass plays out to the
* true end of the stream once instead of only the loop segment.
*
* @param stream The audio stream to compute this for.
* @param startFrame This pass's starting frame offset.
* @param totalFrames The stream's total decoded frame count
* (audioStreamGetTotalFrames()).
* @return This pass's stop frame offset.
*/
size_t audioStreamComputeEndFrame(
const audiostream_t *stream,
const size_t startFrame,
const size_t totalFrames
);
/**
* Sets the playback volume of the given audio stream.
*
* @param stream The audio stream to update.
* @param volume The new volume, from 0.0 (silent) to 1.0 (loudest).
*/
void audioStreamSetVolume(audiostream_t *stream, const float_t volume);
/**
* Sets the stereo directionality (panning) of the given audio stream.
*
* @param stream The audio stream to update.
* @param directionality The new panning value, from AUDIO_STREAM_LEFT to
* AUDIO_STREAM_RIGHT.
*/
void audioStreamSetDirectionality(
audiostream_t *stream,
const float_t directionality
);
/**
* Sets whether the given audio stream loops back to loopTo (or the start
* of the buffer, by default - see audioStreamSetLoopPoints()) when it
* reaches loopStart (or the end of the buffer), rather than stopping and
* firing onEnd.
*
* @param stream The audio stream to update.
* @param looping Whether the stream should loop.
*/
void audioStreamSetLooping(audiostream_t *stream, const bool_t looping);
/**
* Sets the maximum number of times the given audio stream is allowed to
* loop before stopping (firing onEnd) instead of restarting again. Has no
* effect unless looping is also enabled via audioStreamSetLooping(). Resets
* the stream's current loop-restart progress back to 0, so the stream gets
* the full count from this call onward.
*
* @param stream The audio stream to update.
* @param loopLimit Maximum number of loop restarts, or 0 (the default) to
* loop forever.
*/
void audioStreamSetLoopLimit(audiostream_t *stream, const uint32_t loopLimit);
/**
* Updates the given audio stream, decoding new data and advancing playback
* as needed. Should be called every frame for every active stream.
*
* @param stream The audio stream to update.
* @return Error indicating success or failure.
*/
errorret_t audioStreamUpdate(audiostream_t *stream);
/**
* Disposes the audio stream, stopping playback and releasing any resources
* associated with it.
*
* @param stream The audio stream to dispose.
* @return Error indicating success or failure.
*/
errorret_t audioStreamDispose(audiostream_t *stream);
-167
View File
@@ -1,167 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "audiostreammp3.h"
#include "audiostream.h"
#include "assert/assert.h"
#include "util/math.h"
#include "util/memory.h"
errorret_t audioStreamMp3Init(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
assertNotNull(stream->asset, "Stream must have an asset assigned.");
assertTrue(
stream->asset->type == ASSET_LOADER_TYPE_MP3,
"Asset is not an MP3 file."
);
const assetmp3file_t *mp3 = &stream->asset->data.mp3;
stream->type = AUDIO_STREAM_TYPE_MP3;
stream->sampleRate = mp3->sampleRate;
stream->channels = mp3->channels;
stream->duration = (float_t) mp3->totalFrames / (float_t) mp3->sampleRate;
stream->mp3.pendingFrames = 0;
stream->mp3.pendingPosition = 0;
stream->mp3.position = 0;
stream->mp3.totalFrames = mp3->totalFrames;
// Each stream opens its own independent handle to the same underlying
// asset file - see audiostreampcm.c's audioStreamPcmInit() for why.
errorChain(assetFileInit(
&stream->mp3.file, stream->asset->name, NULL, NULL
));
errorChain(assetFileOpen(&stream->mp3.file));
errorChain(assetFileRead(&stream->mp3.file, NULL, mp3->dataOffset));
errorChain(audioStreamMp3DecoderInit(stream));
errorChain(audioStreamPlatformInit(stream));
errorOk();
}
errorret_t audioStreamMp3Dispose(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
errorChain(audioStreamMp3DecoderDispose(stream));
errorChain(assetFileClose(&stream->mp3.file));
errorChain(assetFileDispose(&stream->mp3.file));
errorOk();
}
size_t audioStreamMp3GetTotalFrames(const audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
return stream->mp3.totalFrames;
}
errorret_t audioStreamMp3Seek(audiostream_t *stream, const size_t frame) {
assertNotNull(stream, "Stream cannot be NULL.");
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
if(frame == stream->mp3.position) {
errorOk();
}
// Every seek - forward or backward - restarts decoding from the very
// start of the compressed stream and discards frames until reaching the
// target; see this file's own header comment for why MP3 has no cheaper
// option, unlike audioStreamPcmSeek()'s direct byte-offset seek.
errorChain(audioStreamMp3DecoderRewind(stream));
stream->mp3.position = 0;
stream->mp3.pendingFrames = 0;
stream->mp3.pendingPosition = 0;
const size_t channels = stream->channels;
int16_t discard[AUDIO_MP3_MAX_SAMPLES_PER_FRAME];
while(stream->mp3.position < frame) {
size_t decodedFrames = 0;
errorChain(
audioStreamMp3DecoderDecodeFrame(stream, discard, &decodedFrames)
);
if(decodedFrames == 0) {
// Ran out of stream before reaching the target - clamp rather than
// erroring, same tolerance audioStreamPcmRead() has for a
// shorter-than-declared asset.
break;
}
const size_t framesNeeded = frame - stream->mp3.position;
if(decodedFrames <= framesNeeded) {
stream->mp3.position += decodedFrames;
continue;
}
// This frame overshoots the target - keep the excess as pending so
// the next Read() starts exactly at `frame` instead of skipping past
// it.
const size_t keepFrames = decodedFrames - framesNeeded;
memoryMove(
discard, discard + (framesNeeded * channels),
keepFrames * channels * sizeof(int16_t)
);
memoryCopy(
stream->mp3.pending, discard, keepFrames * channels * sizeof(int16_t)
);
stream->mp3.pendingFrames = keepFrames;
stream->mp3.pendingPosition = 0;
stream->mp3.position = frame;
}
errorOk();
}
errorret_t audioStreamMp3Read(
audiostream_t *stream,
int16_t *buffer,
const size_t frameCount,
size_t *outFramesRead
) {
assertNotNull(stream, "Stream cannot be NULL.");
assertNotNull(buffer, "Buffer cannot be NULL.");
assertNotNull(outFramesRead, "outFramesRead cannot be NULL.");
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
const size_t channels = stream->channels;
size_t framesWritten = 0;
while(framesWritten < frameCount) {
if(stream->mp3.pendingPosition >= stream->mp3.pendingFrames) {
size_t decodedFrames = 0;
errorChain(audioStreamMp3DecoderDecodeFrame(
stream, stream->mp3.pending, &decodedFrames
));
stream->mp3.pendingFrames = decodedFrames;
stream->mp3.pendingPosition = 0;
if(decodedFrames == 0) break; // Genuine end of stream.
}
const size_t framesAvailable =
stream->mp3.pendingFrames - stream->mp3.pendingPosition;
const size_t framesToCopy =
mathMin(frameCount - framesWritten, framesAvailable);
memoryCopy(
buffer + (framesWritten * channels),
stream->mp3.pending + (stream->mp3.pendingPosition * channels),
framesToCopy * channels * sizeof(int16_t)
);
stream->mp3.pendingPosition += framesToCopy;
framesWritten += framesToCopy;
}
stream->mp3.position += framesWritten;
*outFramesRead = framesWritten;
errorOk();
}
-140
View File
@@ -1,140 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "asset/assetfile.h"
#include "audio/audiostreammp3decoder.h"
typedef struct audiostream_s audiostream_t;
// How many interleaved PCM samples (not frames - samples, i.e. frames *
// channels) a single audioStreamMp3DecoderDecodeFrame() call is ever
// allowed to produce. Sizes the pending-sample buffer below, which every
// decoder backend writes directly into - this must be sized to the
// largest of them, not just "one MPEG frame":
// - libmad (software, Linux/Dolphin): always exactly one frame, 1152
// samples/channel for MPEG-1 Layer III, doubled here for stereo.
// - sceMp3 (hardware, PSP): its own pcmBuf is provisioned at double that
// (see AUDIO_MP3_PSP_PCM_BUF_SIZE) - i.e. sceMp3Decode() can
// legitimately hand back more than one frame's worth in a single call.
// Sizing this for only one frame silently overflowed stream->mp3.pending
// on real hardware whenever that happened - confirmed as the cause of
// very intermittent audio corruption/clicking, since it only bit when
// sceMp3 actually returned the larger amount.
// So this covers the larger (PSP) case; libmad's decode is safely well
// within it.
#define AUDIO_MP3_MAX_SAMPLES_PER_FRAME (1152 * 2 * 2)
typedef struct {
// This stream's own private handle into its asset's underlying file -
// see audiostreampcm_t.file's own comment for why this isn't shared
// across streams playing the same asset. Holds compressed MP3 bytes;
// the decoder backend (audiostreammp3decoder.h) reads from it directly.
assetfile_t file;
// Opaque per-platform decoder state - a reserved sceMp3 handle plus its
// buffers on PSP, or libmad's mad_stream/mad_frame/mad_synth state plus a
// sliding compressed-byte window on the libmad-based software backend
// (Linux/Dolphin). Defined by whichever audiostreammp3decoder.h is
// actually visible when this file is compiled - see that header's own
// comment.
audiostreammp3decoder_t decoder;
// One decoded MPEG frame's worth of PCM, held here across Read() calls
// since a frame (576 or 1152 samples/channel) rarely lines up exactly
// with whatever frameCount a caller asks for. pendingPosition marks how
// many of the first pendingFrames frames have already been consumed.
int16_t pending[AUDIO_MP3_MAX_SAMPLES_PER_FRAME];
size_t pendingFrames;
size_t pendingPosition;
// Current logical PCM frame position, relative to the start of the
// decoded stream - decoding is push-forward-only (see
// audioStreamMp3Seek()'s own comment on why a backward seek re-decodes
// from the start rather than truly random-accessing).
size_t position;
// Total decoded PCM frame count for the whole clip - copied from the
// asset's parsed metadata at Init (see assetmp3file_t.totalFrames),
// exact if a Xing/Info header was present, otherwise an estimate.
size_t totalFrames;
} audiostreammp3_t;
/**
* Configures the given MP3 audio stream from its already-assigned asset
* (see audiostream_t.asset - set by audioStreamInit(), which is what
* should be calling this, not application code directly): opens this
* stream's own private file handle onto the asset's compressed MPEG data,
* and initializes the platform decoder backend
* (audioStreamMp3DecoderInit()).
*
* Must be called after stream->asset is set and before audioStreamPlay().
*
* @param stream The audio stream to configure.
* @return Error indicating success or failure.
*/
errorret_t audioStreamMp3Init(audiostream_t *stream);
/**
* Disposes the given MP3 audio stream's decoder backend and private file
* handle.
*
* @param stream The audio stream to dispose.
* @return Error indicating success or failure.
*/
errorret_t audioStreamMp3Dispose(audiostream_t *stream);
/**
* Returns the total number of frames (one sample per channel) available in
* the stream's underlying MP3 data - see assetmp3file_t.totalFrames's own
* comment on why this is sometimes an estimate rather than an exact count,
* unlike audioStreamPcmGetTotalFrames().
*
* @param stream The audio stream to query. Must be AUDIO_STREAM_TYPE_MP3.
* @return The total number of frames available.
*/
size_t audioStreamMp3GetTotalFrames(const audiostream_t *stream);
/**
* Seeks the stream's decode position to the given frame offset. Unlike
* audioStreamPcmSeek(), this is never cheap: MPEG frames aren't
* independently decodable (each one's bit reservoir can depend on data
* carried over from prior frames), so there's no equivalent of PCM's
* direct byte-offset seek - every call, forward or backward, rewinds the
* decoder to the very start of the compressed stream and decodes (and
* discards) frames until reaching the target. Acceptable for this engine's
* actual use (looping background music, where loopTo is typically near
* the start anyway), but a real, non-constant cost for a seek deep into a
* long track.
*
* @param stream The audio stream to seek. Must be AUDIO_STREAM_TYPE_MP3.
* @param frame Frame offset to seek to, relative to the start of the
* decoded stream.
* @return Error indicating success or failure.
*/
errorret_t audioStreamMp3Seek(audiostream_t *stream, const size_t frame);
/**
* Reads up to frameCount frames of PCM sample data from the stream's
* current position, advancing it by however many frames were actually
* read. Reads fewer than frameCount (down to zero) once the underlying
* MP3 data is exhausted, rather than erroring - same contract as
* audioStreamPcmRead().
*
* @param stream The audio stream to read from. Must be AUDIO_STREAM_TYPE_MP3.
* @param buffer Destination buffer, sized for at least frameCount frames.
* @param frameCount Maximum number of frames to read.
* @param outFramesRead Set to the number of frames actually read.
* @return Error indicating success or failure.
*/
errorret_t audioStreamMp3Read(
audiostream_t *stream,
int16_t *buffer,
const size_t frameCount,
size_t *outFramesRead
);
-179
View File
@@ -1,179 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "audiostreampcm.h"
#include "audiostream.h"
#include "assert/assert.h"
#include "util/math.h"
#include "util/memory.h"
#include "util/endian.h"
errorret_t audioStreamPcmInit(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
assertNotNull(stream->asset, "Stream must have an asset assigned.");
assertTrue(
stream->asset->type == ASSET_LOADER_TYPE_WAV,
"Asset is not a WAV file."
);
assetwavfile_t *wav = &stream->asset->data.wav;
stream->type = AUDIO_STREAM_TYPE_PCM;
stream->sampleRate = wav->sampleRate;
stream->channels = wav->channels;
stream->duration = (
(float_t) audioStreamPcmGetTotalFrames(stream) /
(float_t) wav->sampleRate
);
// Each stream opens its own independent handle to the same underlying
// asset file, rather than sharing a single handle on the asset entry -
// multiple streams playing the same asset concurrently (e.g. two
// simultaneous plays of the same sound effect) would otherwise fight
// over one shared read position. This isn't the final answer for that
// (a shared decode/cache layer would scale better than N independent
// decompression streams of the same data), but it's a correct one for
// now - a problem to revisit once it actually matters.
errorChain(assetFileInit(
&stream->pcm.file, stream->asset->name, NULL, NULL
));
errorChain(assetFileOpen(&stream->pcm.file));
errorChain(assetFileRead(&stream->pcm.file, NULL, wav->dataOffset));
errorChain(audioStreamPlatformInit(stream));
errorOk();
}
errorret_t audioStreamPcmDispose(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
errorChain(assetFileClose(&stream->pcm.file));
errorChain(assetFileDispose(&stream->pcm.file));
errorOk();
}
size_t audioStreamPcmGetTotalFrames(const audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL.");
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
const assetwavfile_t *wav = &stream->asset->data.wav;
const size_t sourceFrameSize = (
stream->channels * (wav->bitsPerSample / 8)
);
return wav->dataSize / sourceFrameSize;
}
errorret_t audioStreamPcmSeek(audiostream_t *stream, const size_t frame) {
assertNotNull(stream, "Stream cannot be NULL.");
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
assetwavfile_t *wav = &stream->asset->data.wav;
const size_t sourceFrameSize = (
stream->channels * (wav->bitsPerSample / 8)
);
const size_t targetByte = wav->dataOffset + (frame * sourceFrameSize);
assertTrue(
frame * sourceFrameSize <= wav->dataSize,
"Seek frame is beyond the end of the PCM data."
);
const size_t currentByte = (size_t) stream->pcm.file.position;
if(targetByte < currentByte) {
// A rewind is needed to move the read cursor earlier once it's
// already advanced past a point - assetFileRewind() takes the cheap
// in-place seek path since every dusk.dsk entry is stored
// uncompressed.
errorChain(assetFileRewind(&stream->pcm.file));
errorChain(assetFileRead(&stream->pcm.file, NULL, targetByte));
} else if(targetByte > currentByte) {
errorChain(assetFileRead(
&stream->pcm.file, NULL, targetByte - currentByte
));
}
errorOk();
}
errorret_t audioStreamPcmRead(
audiostream_t *stream,
int16_t *buffer,
const size_t frameCount,
size_t *outFramesRead
) {
assertNotNull(stream, "Stream cannot be NULL.");
assertNotNull(buffer, "Buffer cannot be NULL.");
assertNotNull(outFramesRead, "outFramesRead cannot be NULL.");
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
assetwavfile_t *wav = &stream->asset->data.wav;
const size_t channels = stream->channels;
const size_t sourceSampleBytes = wav->bitsPerSample / 8;
const size_t sourceFrameSize = channels * sourceSampleBytes;
const size_t dataEndByte = wav->dataOffset + wav->dataSize;
const size_t currentByte = (size_t) stream->pcm.file.position;
const size_t bytesAvailable = (
currentByte < dataEndByte ? dataEndByte - currentByte : 0
);
const size_t framesAvailable = bytesAvailable / sourceFrameSize;
const size_t framesToRead = mathMin(frameCount, framesAvailable);
if(framesToRead == 0) {
*outFramesRead = 0;
errorOk();
}
if(sourceSampleBytes == sizeof(int16_t)) {
// Output format already matches the source in width, but WAV samples
// are always little-endian per the format spec regardless of host -
// read straight through, then fix up byte order in place. A no-op on
// every little-endian platform (endianLittleToHost16() compiles down
// to returning its argument unchanged there) - only actually swaps
// anything on a big-endian host (Dolphin/GameCube/Wii).
errorChain(assetFileRead(
&stream->pcm.file, buffer, framesToRead * sourceFrameSize
));
const size_t sampleCount = framesToRead * channels;
for(size_t i = 0; i < sampleCount; i++) {
buffer[i] = (int16_t) endianLittleToHost16((uint16_t) buffer[i]);
}
} else {
// 24-bit source (the only other width assetWavParseHeader() accepts) -
// read the raw 3-byte samples into a scratch buffer, then truncate
// each down to 16-bit, since none of PSP/Dolphin's audio hardware (or
// SDL2 on Linux) accepts anything wider - see assetwavfile_t's own
// comment on bitsPerSample.
assertTrue(sourceSampleBytes == 3, "Unsupported PCM sample width.");
const size_t rawBytes = framesToRead * sourceFrameSize;
uint8_t *raw = memoryAllocate(rawBytes);
errorret_t ret = assetFileRead(&stream->pcm.file, raw, rawBytes);
if(errorIsNotOk(ret)) {
memoryFree(raw);
errorChain(ret);
}
// 24-bit PCM samples are little-endian two's complement - the top two
// bytes of each (indices 1 and 2) already form that same value
// truncated to 16-bit (equivalent to an arithmetic right-shift by 8
// bits, which preserves the sign correctly since byte 2 carries it).
const size_t sampleCount = framesToRead * channels;
for(size_t i = 0; i < sampleCount; i++) {
const uint8_t *sample = raw + (i * 3);
buffer[i] = (int16_t) (sample[1] | (sample[2] << 8));
}
memoryFree(raw);
}
*outFramesRead = framesToRead;
errorOk();
}
-96
View File
@@ -1,96 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "asset/assetfile.h"
typedef struct audiostream_s audiostream_t;
typedef struct {
// This stream's own private handle into its asset's underlying file -
// deliberately not shared with any other stream reading the same asset
// (see audioStreamPcmInit's own comment for why). Its read cursor is
// what audioStreamPcmRead()/audioStreamPcmSeek() operate on.
assetfile_t file;
} audiostreampcm_t;
/**
* Configures the given PCM audio stream from its already-assigned asset
* (see audiostream_t.asset - set by audioStreamInit(), which is what
* should be calling this, not application code directly) rather than
* taking raw decoded data: sampleRate/channels/duration are read from the
* asset's parsed WAV header, and a private file handle is opened for
* reading sample data on demand as playback consumes it (see
* audioStreamPcmRead()) - the PCM data itself is never read into memory
* all at once, so this works the same regardless of how long the
* underlying clip is.
*
* Must be called after stream->asset is set and before audioStreamPlay().
*
* @param stream The audio stream to configure.
* @return Error indicating success or failure.
*/
errorret_t audioStreamPcmInit(audiostream_t *stream);
/**
* Disposes the given PCM audio stream's own private file handle.
*
* @param stream The audio stream to dispose.
* @return Error indicating success or failure.
*/
errorret_t audioStreamPcmDispose(audiostream_t *stream);
/**
* Returns the total number of frames (one sample per channel) available
* in the stream's underlying PCM data - NOT simply the asset's declared
* byte size divided by a 16-bit frame size, since the source data isn't
* always 16-bit even though audioStreamPcmRead() always produces 16-bit
* output (see assetwavfile_t.bitsPerSample). Platform backends should use
* this rather than computing frame counts from dataSize themselves.
*
* @param stream The audio stream to query. Must be AUDIO_STREAM_TYPE_PCM.
* @return The total number of frames available.
*/
size_t audioStreamPcmGetTotalFrames(const audiostream_t *stream);
/**
* Seeks the stream's private read cursor to the given frame offset
* (relative to the start of the PCM data - the same units as
* audiostream_t's startFrame/loopStart/loopTo, once converted from
* seconds). Seeking backward re-reads from the start of the underlying
* asset file (see assetFileRewind()), which is a cheap in-place seek
* since every dusk.dsk entry is stored uncompressed.
*
* @param stream The audio stream to seek. Must be AUDIO_STREAM_TYPE_PCM.
* @param frame Frame offset to seek to, relative to the start of the PCM
* data.
* @return Error indicating success or failure.
*/
errorret_t audioStreamPcmSeek(audiostream_t *stream, const size_t frame);
/**
* Reads up to frameCount frames of PCM sample data from the stream's
* current read position, advancing it by however many frames were
* actually read. Reads fewer than frameCount (down to zero) once the
* underlying asset's PCM data is exhausted, rather than erroring - it's
* up to the caller (platform code, which already knows about loop points)
* to request no more than what it wants read from within the current
* loop segment or the true end of the clip.
*
* @param stream The audio stream to read from. Must be AUDIO_STREAM_TYPE_PCM.
* @param buffer Destination buffer, sized for at least frameCount frames.
* @param frameCount Maximum number of frames to read.
* @param outFramesRead Set to the number of frames actually read.
* @return Error indicating success or failure.
*/
errorret_t audioStreamPcmRead(
audiostream_t *stream,
int16_t *buffer,
const size_t frameCount,
size_t *outFramesRead
);
-50
View File
@@ -1,50 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "audiostreamtype.h"
#include "util/string.h"
const audiostreamassettypeinfo_t
AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[ASSET_LOADER_TYPE_COUNT] = {
[ASSET_LOADER_TYPE_WAV] = {
.type = AUDIO_STREAM_TYPE_PCM, .extension = ".wav"
},
[ASSET_LOADER_TYPE_MP3] = {
.type = AUDIO_STREAM_TYPE_MP3, .extension = ".mp3"
}
};
assetloadertype_t audioStreamAssetTypeForPath(const char_t *path) {
for(assetloadertype_t i = 0; i < ASSET_LOADER_TYPE_COUNT; i++) {
const char_t *extension = AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[i].extension;
if(extension != NULL && stringEndsWithCaseInsensitive(path, extension)) {
return i;
}
}
return ASSET_LOADER_TYPE_NULL;
}
audistreamtype_t audioStreamTypeForAssetType(
const assetloadertype_t assetType
) {
return AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[assetType].type;
}
assetloadertype_t audioStreamAssetTypeForStreamType(
const audistreamtype_t streamType
) {
if(streamType == AUDIO_STREAM_TYPE_NULL) return ASSET_LOADER_TYPE_NULL;
for(assetloadertype_t i = 0; i < ASSET_LOADER_TYPE_COUNT; i++) {
if(AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[i].type == streamType) {
return i;
}
}
return ASSET_LOADER_TYPE_NULL;
}
-71
View File
@@ -1,71 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#include "asset/loader/assetloader.h"
typedef enum {
AUDIO_STREAM_TYPE_NULL,
AUDIO_STREAM_TYPE_PCM,
AUDIO_STREAM_TYPE_MP3,
AUDIO_STREAM_TYPE_COUNT
} audistreamtype_t;
typedef struct {
// The audistreamtype_t an audio stream backed by this asset type should
// become - AUDIO_STREAM_TYPE_NULL (the zero-initialized default) for any
// asset type that can't back an audio stream.
audistreamtype_t type;
// This asset type's file extension, including the leading '.' (e.g.
// ".wav"). NULL for any asset type that can't back an audio stream.
const char_t *extension;
} audiostreamassettypeinfo_t;
// Maps an assetloadertype_t to the info describing the audio stream it
// backs. Indexed directly by assetentry_t.type; see audioStreamInit()'s own
// use of this for the canonical "is this asset type supported" check. Use
// the functions below rather than indexing this directly, except where
// you already have an assetloadertype_t in hand.
extern const audiostreamassettypeinfo_t
AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[ASSET_LOADER_TYPE_COUNT];
/**
* Determines which asset loader type a file path's extension corresponds
* to, by matching it against AUDIO_STREAM_TYPE_FOR_ASSET_TYPE's own
* extensions (case-insensitively).
*
* @param path The file path to inspect, e.g. "audio/boa.mp3".
* @return The matching assetloadertype_t, or ASSET_LOADER_TYPE_NULL if the
* path's extension doesn't match any audio asset type.
*/
assetloadertype_t audioStreamAssetTypeForPath(const char_t *path);
/**
* Looks up the audistreamtype_t an audio stream backed by the given asset
* type should become.
*
* @param assetType The asset loader type to look up.
* @return The matching audistreamtype_t, or AUDIO_STREAM_TYPE_NULL if
* assetType can't back an audio stream.
*/
audistreamtype_t audioStreamTypeForAssetType(const assetloadertype_t assetType);
/**
* Looks up which asset loader type backs audio streams of the given type -
* the reverse of audioStreamTypeForAssetType(). Scans
* AUDIO_STREAM_TYPE_FOR_ASSET_TYPE for the first entry whose type matches,
* since it isn't itself indexed by audistreamtype_t.
*
* @param streamType The audio stream type to look up.
* @return The matching assetloadertype_t, or ASSET_LOADER_TYPE_NULL if
* streamType is AUDIO_STREAM_TYPE_NULL or otherwise unmapped.
*/
assetloadertype_t audioStreamAssetTypeForStreamType(
const audistreamtype_t streamType
);
+11 -1
View File
@@ -18,8 +18,10 @@ console_t CONSOLE;
void consoleInit(void) {
memoryZero(&CONSOLE, sizeof(console_t));
CONSOLE.visible = false;
// CONSOLE.visible = true;
#ifdef DUSK_CONSOLE_POSIX
threadMutexInit(&CONSOLE.printMutex);
#endif
}
void consolePrint(const char_t *message, ...) {
@@ -30,14 +32,20 @@ void consolePrint(const char_t *message, ...) {
int32_t len = stringFormatVA(buffer, CONSOLE_LINE_MAX, message, args);
va_end(args);
#ifdef DUSK_CONSOLE_POSIX
threadMutexLock(&CONSOLE.printMutex);
#endif
memoryMove(
CONSOLE.line[0],
CONSOLE.line[1],
(CONSOLE_HISTORY_MAX - 1) * CONSOLE_LINE_MAX
);
memoryCopy(CONSOLE.line[CONSOLE_HISTORY_MAX - 1], buffer, len + 1);
#ifdef DUSK_CONSOLE_POSIX
threadMutexUnlock(&CONSOLE.printMutex);
#endif
logDebug("%s\n", buffer);
}
@@ -53,5 +61,7 @@ void consoleUpdate(void) {
}
void consoleDispose(void) {
#ifdef DUSK_CONSOLE_POSIX
threadMutexDispose(&CONSOLE.printMutex);
#endif
}
+10 -4
View File
@@ -6,18 +6,24 @@
*/
#pragma once
#include "consoledefs.h"
#include "error/error.h"
#include "dusk.h"
#include "thread/thread.h"
#define CONSOLE_LINE_MAX 128
#define CONSOLE_HISTORY_MAX 16
#define CONSOLE_EXEC_BUFFER_MAX 32
#ifdef DUSK_CONSOLE_POSIX
#include "thread/thread.h"
#include <poll.h>
#include <unistd.h>
#define CONSOLE_POSIX_POLL_RATE 75
#endif
typedef struct {
char_t line[CONSOLE_HISTORY_MAX][CONSOLE_LINE_MAX];
bool_t visible;
#ifdef DUSK_CONSOLE_POSIX
threadmutex_t printMutex;
#endif
} console_t;
extern console_t CONSOLE;
@@ -7,7 +7,6 @@
#pragma once
#include "core/scriptcore.h"
#include "builtin/scriptbuiltin.h"
SCRIPT_NATIVE(scriptBSplit);
#define CONSOLE_LINE_MAX 512
#define CONSOLE_HISTORY_MAX 16
#define CONSOLE_EXEC_BUFFER_MAX 32
+7 -9
View File
@@ -7,7 +7,7 @@
#include "display/display.h"
#include "display/framebuffer/framebuffer.h"
#include "entity/entity.h"
#include "scene/scene.h"
#include "entity/entityrender.h"
#include "display/spritebatch/spritebatch.h"
#include "display/mesh/quad.h"
@@ -17,6 +17,7 @@
#include "display/mesh/capsule.h"
#include "display/mesh/triprism.h"
#include "display/screen/screen.h"
#include "ui/ui.h"
#include "display/text/text.h"
#include "assert/assert.h"
#include "util/memory.h"
@@ -33,17 +34,13 @@ errorret_t displayInit(void) {
#ifdef displayPlatformInit
errorChain(displayPlatformInit());
#endif
// Set initial state
errorChain(displaySetState((displaystate_t){ .flags = 0 }));
// Init the fixed textures
errorChain(textureInit(
&TEXTURE_WHITE, TEXTURE_FIXED_WIDTH, TEXTURE_FIXED_HEIGHT,
&TEXTURE_WHITE, 4, 4,
TEXTURE_FORMAT_RGBA, (texturedata_t){ .rgbaColors = TEXTURE_WHITE_PIXELS }
));
errorChain(textureInit(
&TEXTURE_TEST, TEXTURE_FIXED_WIDTH, TEXTURE_FIXED_HEIGHT,
&TEXTURE_TEST, 4, 4,
TEXTURE_FORMAT_RGBA, (texturedata_t){ .rgbaColors = TEXTURE_TEST_PIXELS }
));
@@ -55,13 +52,13 @@ errorret_t displayInit(void) {
errorChain(capsuleInit());
errorChain(triPrismInit());
// Init the subsystems
errorChain(frameBufferInitBackBuffer());
errorChain(spriteBatchInit());
errorChain(textInit());
errorChain(screenInit());
// Setup initial shader with default values
errorChain(shaderListInit());
errorOk();
@@ -76,13 +73,14 @@ errorret_t displayUpdate(void) {
spriteBatchClear();
errorChain(frameBufferBind(NULL));
// Bind screen and render the entity world
// Bind screen and render scene
errorChain(screenBind());
frameBufferClear(
FRAMEBUFFER_CLEAR_COLOR | FRAMEBUFFER_CLEAR_DEPTH,
SCREEN.background
);
errorChain(sceneRender());
errorChain(entityRenderAll());
// Finish up
+6 -12
View File
@@ -73,33 +73,27 @@ void sphereBuffer(
const float_t u1 = (float_t)j / (float_t)sectors;
const float_t u2 = (float_t)(j + 1) / (float_t)sectors;
vertices[vi].pos[0] = center[0] + x11;
vertices[vi].pos[1] = center[1] + y1;
vertices[vi].pos[0] = center[0] + x11; vertices[vi].pos[1] = center[1] + y1;
vertices[vi].pos[2] = center[2] + z11;
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v1; vi++;
vertices[vi].pos[0] = center[0] + x21;
vertices[vi].pos[1] = center[1] + y2;
vertices[vi].pos[0] = center[0] + x21; vertices[vi].pos[1] = center[1] + y2;
vertices[vi].pos[2] = center[2] + z21;
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++;
vertices[vi].pos[0] = center[0] + x12;
vertices[vi].pos[1] = center[1] + y1;
vertices[vi].pos[0] = center[0] + x12; vertices[vi].pos[1] = center[1] + y1;
vertices[vi].pos[2] = center[2] + z12;
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++;
vertices[vi].pos[0] = center[0] + x12;
vertices[vi].pos[1] = center[1] + y1;
vertices[vi].pos[0] = center[0] + x12; vertices[vi].pos[1] = center[1] + y1;
vertices[vi].pos[2] = center[2] + z12;
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++;
vertices[vi].pos[0] = center[0] + x21;
vertices[vi].pos[1] = center[1] + y2;
vertices[vi].pos[0] = center[0] + x21; vertices[vi].pos[1] = center[1] + y2;
vertices[vi].pos[2] = center[2] + z21;
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++;
vertices[vi].pos[0] = center[0] + x22;
vertices[vi].pos[1] = center[1] + y2;
vertices[vi].pos[0] = center[0] + x22; vertices[vi].pos[1] = center[1] + y2;
vertices[vi].pos[2] = center[2] + z22;
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v2; vi++;
}
+1 -2
View File
@@ -76,8 +76,7 @@ errorret_t spriteBatchBuffer(
// Buffer to the mesh vertices.
spriteBatchBufferToMesh(
sprites + (count - remaining), batchCount, v,
batchCount * QUAD_VERTEX_COUNT
sprites, batchCount, v, batchCount * QUAD_VERTEX_COUNT
);
SPRITEBATCH.spriteCount += batchCount;
remaining -= batchCount;
-1
View File
@@ -7,5 +7,4 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
text.c
font.c
)
-205
View File
@@ -1,205 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "font.h"
#include "util/memory.h"
#include "util/math.h"
#include "display/color.h"
font_t FONT_DEFAULT;
static texture_t FONT_DEFAULT_TEXTURE;
static tileset_t FONT_DEFAULT_TILESET;
const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
FONT_DEFAULT_TILE_HEIGHT
] = {
{ 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x10, 0x00, 0x00 }, // !
{ 0x00, 0x14, 0x14, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // "
{ 0x00, 0x14, 0x14, 0x3E, 0x14, 0x3E, 0x14, 0x14, 0x00, 0x00 }, // #
{ 0x00, 0x08, 0x1E, 0x28, 0x1C, 0x0A, 0x3C, 0x08, 0x00, 0x00 }, // $
{ 0x00, 0x00, 0x22, 0x24, 0x08, 0x12, 0x22, 0x00, 0x00, 0x00 }, // %
{ 0x00, 0x08, 0x14, 0x14, 0x1A, 0x24, 0x24, 0x1A, 0x00, 0x00 }, // &
{ 0x00, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // '
{ 0x00, 0x04, 0x08, 0x08, 0x08, 0x08, 0x08, 0x04, 0x00, 0x00 }, // (
{ 0x00, 0x10, 0x08, 0x08, 0x08, 0x08, 0x08, 0x10, 0x00, 0x00 }, // )
{ 0x00, 0x00, 0x08, 0x2A, 0x1C, 0x2A, 0x08, 0x00, 0x00, 0x00 }, // *
{ 0x00, 0x00, 0x08, 0x08, 0x3E, 0x08, 0x08, 0x00, 0x00, 0x00 }, // +
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x20, 0x00 }, // ,
{ 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00 }, // -
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00 }, // .
{ 0x00, 0x04, 0x04, 0x08, 0x08, 0x08, 0x10, 0x10, 0x00, 0x00 }, // /
{ 0x00, 0x1C, 0x22, 0x26, 0x2A, 0x32, 0x22, 0x1C, 0x00, 0x00 }, // 0
{ 0x00, 0x08, 0x18, 0x08, 0x08, 0x08, 0x08, 0x3E, 0x00, 0x00 }, // 1
{ 0x00, 0x1C, 0x22, 0x02, 0x04, 0x08, 0x10, 0x3E, 0x00, 0x00 }, // 2
{ 0x00, 0x1C, 0x22, 0x02, 0x0C, 0x02, 0x22, 0x1C, 0x00, 0x00 }, // 3
{ 0x00, 0x22, 0x22, 0x22, 0x3E, 0x02, 0x02, 0x02, 0x00, 0x00 }, // 4
{ 0x00, 0x3E, 0x20, 0x20, 0x3C, 0x02, 0x22, 0x1C, 0x00, 0x00 }, // 5
{ 0x00, 0x1C, 0x20, 0x20, 0x3C, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // 6
{ 0x00, 0x3E, 0x02, 0x02, 0x04, 0x08, 0x08, 0x08, 0x00, 0x00 }, // 7
{ 0x00, 0x1C, 0x22, 0x22, 0x1C, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // 8
{ 0x00, 0x1C, 0x22, 0x22, 0x1E, 0x02, 0x22, 0x1C, 0x00, 0x00 }, // 9
{ 0x00, 0x00, 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00 }, // :
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // ;
{ 0x00, 0x04, 0x08, 0x10, 0x20, 0x10, 0x08, 0x04, 0x00, 0x00 }, // <
{ 0x00, 0x00, 0x00, 0x3E, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x00 }, // =
{ 0x00, 0x10, 0x08, 0x04, 0x02, 0x04, 0x08, 0x10, 0x00, 0x00 }, // >
{ 0x00, 0x1C, 0x22, 0x02, 0x04, 0x08, 0x00, 0x08, 0x00, 0x00 }, // ?
{ 0x00, 0x1C, 0x26, 0x2A, 0x2A, 0x26, 0x20, 0x1C, 0x00, 0x00 }, // @
{ 0x00, 0x1C, 0x22, 0x22, 0x22, 0x3E, 0x22, 0x22, 0x00, 0x00 }, // A
{ 0x00, 0x3C, 0x22, 0x22, 0x3C, 0x22, 0x22, 0x3C, 0x00, 0x00 }, // B
{ 0x00, 0x1C, 0x22, 0x20, 0x20, 0x20, 0x22, 0x1C, 0x00, 0x00 }, // C
{ 0x00, 0x3C, 0x22, 0x22, 0x22, 0x22, 0x22, 0x3C, 0x00, 0x00 }, // D
{ 0x00, 0x3E, 0x20, 0x20, 0x3C, 0x20, 0x20, 0x3E, 0x00, 0x00 }, // E
{ 0x00, 0x3E, 0x20, 0x20, 0x3C, 0x20, 0x20, 0x20, 0x00, 0x00 }, // F
{ 0x00, 0x1C, 0x22, 0x20, 0x2E, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // G
{ 0x00, 0x22, 0x22, 0x22, 0x3E, 0x22, 0x22, 0x22, 0x00, 0x00 }, // H
{ 0x00, 0x3E, 0x08, 0x08, 0x08, 0x08, 0x08, 0x3E, 0x00, 0x00 }, // I
{ 0x00, 0x02, 0x02, 0x02, 0x02, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // J
{ 0x00, 0x22, 0x24, 0x28, 0x30, 0x28, 0x24, 0x22, 0x00, 0x00 }, // K
{ 0x00, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3E, 0x00, 0x00 }, // L
{ 0x00, 0x22, 0x36, 0x2A, 0x22, 0x22, 0x22, 0x22, 0x00, 0x00 }, // M
{ 0x00, 0x22, 0x22, 0x32, 0x2A, 0x26, 0x22, 0x22, 0x00, 0x00 }, // N
{ 0x00, 0x1C, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // O
{ 0x00, 0x3C, 0x22, 0x22, 0x3C, 0x20, 0x20, 0x20, 0x00, 0x00 }, // P
{ 0x00, 0x1C, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1C, 0x06, 0x00 }, // Q
{ 0x00, 0x3C, 0x22, 0x22, 0x3C, 0x22, 0x22, 0x22, 0x00, 0x00 }, // R
{ 0x00, 0x1C, 0x22, 0x20, 0x1C, 0x02, 0x22, 0x1C, 0x00, 0x00 }, // S
{ 0x00, 0x3E, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00 }, // T
{ 0x00, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // U
{ 0x00, 0x22, 0x22, 0x22, 0x22, 0x14, 0x14, 0x08, 0x00, 0x00 }, // V
{ 0x00, 0x22, 0x22, 0x22, 0x22, 0x2A, 0x36, 0x22, 0x00, 0x00 }, // W
{ 0x00, 0x22, 0x22, 0x14, 0x08, 0x14, 0x22, 0x22, 0x00, 0x00 }, // X
{ 0x00, 0x22, 0x22, 0x14, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00 }, // Y
{ 0x00, 0x3E, 0x02, 0x04, 0x08, 0x10, 0x20, 0x3E, 0x00, 0x00 }, // Z
{ 0x00, 0x0C, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0C, 0x00, 0x00 }, // [
// Custom icon glyph, not a real backslash - a backspace symbol: Caps
// Lock's up arrow (see FONT_ICON_CAPSLOCK) rotated 270 degrees to
// point left instead, adapted to this font's fixed 6x10 tile (each of
// Caps Lock's row widths becomes a column height here, centered
// vertically). Backslash was never drawn anyway, and isn't a key this
// virtual keyboard can type - see FONT_ICON_BACKSPACE.
// FONT_ICON_BACKSPACE
{ 0x00, 0x00, 0x08, 0x1F, 0x3F, 0x3F, 0x1F, 0x08, 0x00, 0x00 },
{ 0x00, 0x18, 0x08, 0x08, 0x08, 0x08, 0x08, 0x18, 0x00, 0x00 }, // ]
// ^ (not drawn in source font)
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E }, // _
// Custom icon glyph, not a real backtick - an up arrow for Shift, same
// head as Caps Lock's (see FONT_ICON_CAPSLOCK) but with a shaft 2px
// thinner, plus one empty row near the bottom of it, so it reads as a
// lighter/broken version of Caps Lock's thicker uninterrupted one.
// Backtick was never drawn anyway, and isn't a key this virtual
// keyboard can type - see FONT_ICON_SHIFT.
// FONT_ICON_SHIFT
{ 0x0C, 0x1E, 0x3F, 0x0C, 0x0C, 0x0C, 0x0C, 0x00, 0x0C, 0x00 },
{ 0x00, 0x00, 0x00, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x00, 0x00 }, // a
{ 0x00, 0x20, 0x20, 0x3C, 0x22, 0x22, 0x22, 0x3C, 0x00, 0x00 }, // b
{ 0x00, 0x00, 0x00, 0x1C, 0x22, 0x20, 0x22, 0x1C, 0x00, 0x00 }, // c
{ 0x00, 0x02, 0x02, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x00, 0x00 }, // d
{ 0x00, 0x00, 0x00, 0x1C, 0x22, 0x3E, 0x20, 0x1C, 0x00, 0x00 }, // e
{ 0x00, 0x0C, 0x12, 0x10, 0x3C, 0x10, 0x10, 0x10, 0x00, 0x00 }, // f
{ 0x00, 0x00, 0x00, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x02, 0x1C }, // g
{ 0x00, 0x20, 0x20, 0x3C, 0x22, 0x22, 0x22, 0x22, 0x00, 0x00 }, // h
{ 0x00, 0x08, 0x00, 0x18, 0x08, 0x08, 0x08, 0x3E, 0x00, 0x00 }, // i
{ 0x00, 0x02, 0x00, 0x06, 0x02, 0x02, 0x02, 0x02, 0x22, 0x1C }, // j
{ 0x00, 0x20, 0x20, 0x22, 0x24, 0x38, 0x24, 0x22, 0x00, 0x00 }, // k
{ 0x00, 0x30, 0x10, 0x10, 0x10, 0x10, 0x10, 0x0E, 0x00, 0x00 }, // l
{ 0x00, 0x00, 0x00, 0x3C, 0x2A, 0x2A, 0x2A, 0x2A, 0x00, 0x00 }, // m
{ 0x00, 0x00, 0x00, 0x3C, 0x22, 0x22, 0x22, 0x22, 0x00, 0x00 }, // n
{ 0x00, 0x00, 0x00, 0x1C, 0x22, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // o
{ 0x00, 0x00, 0x00, 0x3C, 0x22, 0x22, 0x22, 0x3C, 0x20, 0x20 }, // p
{ 0x00, 0x00, 0x00, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x02, 0x02 }, // q
{ 0x00, 0x00, 0x00, 0x2C, 0x32, 0x20, 0x20, 0x20, 0x00, 0x00 }, // r
{ 0x00, 0x00, 0x00, 0x1E, 0x20, 0x1C, 0x02, 0x3C, 0x00, 0x00 }, // s
{ 0x00, 0x10, 0x10, 0x3C, 0x10, 0x10, 0x10, 0x0E, 0x00, 0x00 }, // t
{ 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, 0x1E, 0x00, 0x00 }, // u
{ 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x14, 0x08, 0x00, 0x00 }, // v
{ 0x00, 0x00, 0x00, 0x22, 0x22, 0x2A, 0x2A, 0x14, 0x00, 0x00 }, // w
{ 0x00, 0x00, 0x00, 0x22, 0x14, 0x08, 0x14, 0x22, 0x00, 0x00 }, // x
{ 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, 0x1E, 0x02, 0x1C }, // y
{ 0x00, 0x00, 0x00, 0x3E, 0x04, 0x08, 0x10, 0x3E, 0x00, 0x00 }, // z
{ 0x00, 0x04, 0x08, 0x08, 0x10, 0x08, 0x08, 0x04, 0x00, 0x00 }, // {
// Custom icon glyph, not a real pipe - a "return" arrow for the
// keyboard's newline key: a vertical riser down the right side that
// hooks left into a leftward-pointing arrowhead, i.e. "<-|" rotated
// into an L. Pipe was never drawn anyway, and isn't a key this
// virtual keyboard can type - see FONT_ICON_NEWLINE.
// FONT_ICON_NEWLINE
{ 0x02, 0x02, 0x02, 0x02, 0x0E, 0x1E, 0x08, 0x00, 0x00, 0x00 },
{ 0x00, 0x10, 0x08, 0x08, 0x04, 0x08, 0x08, 0x10, 0x00, 0x00 }, // }
// Custom icon glyph, not a real tilde - a spacebar symbol for the
// keyboard's space key: an underscore with a tick at each end, like
// "|___|". Tilde was never drawn anyway, and was explicitly dropped
// from this virtual keyboard's own key set - see FONT_ICON_SPACE.
// FONT_ICON_SPACE
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x3F },
// Custom icon glyph, not a real ASCII character - a thick, solid,
// uninterrupted up arrow for Caps Lock (contrast FONT_ICON_SHIFT's
// same head but a thinner, gapped shaft). Assigned to char code 127
// (DEL) since that codepoint is never legitimately typed text and
// (unlike 128+) is still a positive value regardless of whether this
// platform's plain `char` is signed - see FONT_ICON_CAPSLOCK.
// FONT_ICON_CAPSLOCK
{ 0x0C, 0x1E, 0x3F, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x00 },
// unused trailing tile
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
};
errorret_t fontDefaultInit(void) {
const int32_t width = (int32_t)mathNextPowTwo(
FONT_DEFAULT_COLUMNS * FONT_DEFAULT_TILE_WIDTH
);
const int32_t height = (int32_t)mathNextPowTwo(
FONT_DEFAULT_ROWS * FONT_DEFAULT_TILE_HEIGHT
);
color_t *pixels = memoryAllocate(sizeof(color_t) * width * height);
memoryZero(pixels, sizeof(color_t) * width * height);
for(uint16_t i = 0; i < FONT_DEFAULT_TILE_COUNT; i++) {
const uint16_t tileX = (i % FONT_DEFAULT_COLUMNS) * FONT_DEFAULT_TILE_WIDTH;
const uint16_t tileY =
(i / FONT_DEFAULT_COLUMNS) * FONT_DEFAULT_TILE_HEIGHT;
for(uint8_t row = 0; row < FONT_DEFAULT_TILE_HEIGHT; row++) {
const uint8_t bits = FONT_DEFAULT_GLYPHS[i][row];
for(uint8_t col = 0; col < FONT_DEFAULT_TILE_WIDTH; col++) {
if(!((bits >> (FONT_DEFAULT_TILE_WIDTH - 1 - col)) & 1)) continue;
pixels[((tileY + row) * width) + (tileX + col)] = COLOR_WHITE;
}
}
}
FONT_DEFAULT_TILESET.tileWidth = FONT_DEFAULT_TILE_WIDTH;
FONT_DEFAULT_TILESET.tileHeight = FONT_DEFAULT_TILE_HEIGHT;
FONT_DEFAULT_TILESET.columns = FONT_DEFAULT_COLUMNS;
FONT_DEFAULT_TILESET.rows = FONT_DEFAULT_ROWS;
FONT_DEFAULT_TILESET.tileCount = FONT_DEFAULT_TILE_COUNT;
FONT_DEFAULT_TILESET.uv[0] =
(float_t)FONT_DEFAULT_TILE_WIDTH / (float_t)width;
FONT_DEFAULT_TILESET.uv[1] =
(float_t)FONT_DEFAULT_TILE_HEIGHT / (float_t)height;
const texturedata_t data = { .rgbaColors = pixels };
errorret_t textureResult = textureInit(
&FONT_DEFAULT_TEXTURE, width, height, TEXTURE_FORMAT_RGBA, data
);
memoryFree(pixels);
errorChain(textureResult);
FONT_DEFAULT.texture = &FONT_DEFAULT_TEXTURE;
FONT_DEFAULT.tileset = &FONT_DEFAULT_TILESET;
errorOk();
}
errorret_t fontDefaultDispose(void) {
errorChain(textureDispose(&FONT_DEFAULT_TEXTURE));
FONT_DEFAULT.texture = NULL;
FONT_DEFAULT.tileset = NULL;
errorOk();
}
-84
View File
@@ -6,7 +6,6 @@
*/
#pragma once
#include "error/error.h"
#include "display/texture/texture.h"
#include "display/texture/tileset.h"
@@ -14,86 +13,3 @@ typedef struct {
texture_t *texture;
tileset_t *tileset;
} font_t;
/**
* Pixel width/height of a single default-font glyph tile.
*/
#define FONT_DEFAULT_TILE_WIDTH 6
#define FONT_DEFAULT_TILE_HEIGHT 10
/** Grid layout of the generated default-font texture, in tiles. */
#define FONT_DEFAULT_COLUMNS 16
#define FONT_DEFAULT_ROWS 6
/**
* Number of glyphs defined in FONT_DEFAULT_GLYPHS (FONT_DEFAULT_COLUMNS *
* FONT_DEFAULT_ROWS), covering the printable ASCII range starting at
* TEXT_CHAR_START ('!'), one custom icon glyph in a trailing unused tile
* (see FONT_ICON_CAPSLOCK), plus one more genuinely unused trailing tile.
* FONT_ICON_SHIFT/FONT_ICON_NEWLINE reuse existing-but-blank slots within
* the printable range instead of more trailing tiles - see their own
* comments.
*/
#define FONT_DEFAULT_TILE_COUNT (FONT_DEFAULT_COLUMNS * FONT_DEFAULT_ROWS)
/**
* Custom (non-ASCII-meaning) icon glyphs baked into FONT_DEFAULT_GLYPHS
* at otherwise-unused codepoints within the range this font covers -
* safe to use anywhere a char_t string is expected, e.g. a uibutton_t
* label. Kept below 128: char_t is a plain `char`, whose signedness
* varies by platform, so a codepoint of 128 or above isn't safely
* representable everywhere this engine targets.
*/
// Thick, solid, uninterrupted up arrow - Caps Lock. A trailing tile
// (char code 127/DEL) that was never a real character to begin with.
#define FONT_ICON_CAPSLOCK "\x7F"
// Same up arrow, but with a thinner and gapped shaft - Shift. Reuses
// the backtick's glyph slot: backtick was never drawn by this font
// anyway, and isn't a key this engine's virtual keyboard can type.
#define FONT_ICON_SHIFT "`"
// A "return" arrow (down then left, with a leftward arrowhead) - the
// keyboard's newline key. Reuses the pipe's glyph slot, for the same
// reason as FONT_ICON_SHIFT.
#define FONT_ICON_NEWLINE "|"
// An underscore with a tick at each end ("|___|") - the keyboard's
// space key. Reuses the tilde's glyph slot: tilde was never drawn by
// this font, and was explicitly dropped from this engine's virtual
// keyboard's own key set.
#define FONT_ICON_SPACE "~"
// Caps Lock's arrow rotated to point left - the keyboard's backspace
// key. Reuses the backslash's glyph slot, for the same reason as
// FONT_ICON_SHIFT/FONT_ICON_NEWLINE/FONT_ICON_SPACE. Last free reused
// slot below 128 - one more custom icon after this needs
// FONT_DEFAULT_COLUMNS/ROWS grown to make room.
#define FONT_ICON_BACKSPACE "\\"
extern font_t FONT_DEFAULT;
/**
* Hard coded bitmap data for the built-in default font. Indexed
* [glyph][row], where glyph 0 corresponds to TEXT_CHAR_START ('!') and
* glyphs run consecutively through the printable ASCII range. Each row
* byte holds FONT_DEFAULT_TILE_WIDTH bit flags, one per pixel column:
* bit (FONT_DEFAULT_TILE_WIDTH - 1) is the leftmost pixel and bit 0 is
* the rightmost; 1 means the pixel is set, 0 means it is not.
*/
extern const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
FONT_DEFAULT_TILE_HEIGHT
];
/**
* Builds the default font's texture + tileset directly from
* FONT_DEFAULT_GLYPHS, without going through the asset system - so the
* engine always has a usable font to render with regardless of whether
* asset loading (e.g. the packed .dsk archive) succeeds.
*
* @return Either an error or success result.
*/
errorret_t fontDefaultInit(void);
/**
* Disposes of the default font created by fontDefaultInit().
*
* @return Either an error or success result.
*/
errorret_t fontDefaultDispose(void);
+42 -115
View File
@@ -9,15 +9,34 @@
#include "assert/assert.h"
#include "util/memory.h"
#include "display/spritebatch/spritebatch.h"
#include "asset/asset.h"
#include "asset/loader/display/assettextureloader.h"
#include "asset/loader/display/assettilesetloader.h"
#include "display/shader/shaderunlit.h"
font_t FONT_DEFAULT;
errorret_t textInit(void) {
errorChain(fontDefaultInit());
assetloaderinput_t input = { .texture = TEXTURE_FORMAT_RGBA };
assetentry_t *entryTexture = assetLock(
"ui/minogram.png", ASSET_LOADER_TYPE_TEXTURE, &input
);
assetentry_t *entryTileset = assetLock(
"ui/minogram.dtf", ASSET_LOADER_TYPE_TILESET, NULL
);
errorChain(assetRequireLoaded(entryTexture));
errorChain(assetRequireLoaded(entryTileset));
FONT_DEFAULT.texture = &entryTexture->data.texture;
FONT_DEFAULT.tileset = &entryTileset->data.tileset;
errorOk();
}
errorret_t textDispose(void) {
errorChain(fontDefaultDispose());
FONT_DEFAULT.texture = NULL;
FONT_DEFAULT.tileset = NULL;
assetUnlock("ui/minogram.png");
assetUnlock("ui/minogram.dtf");
errorOk();
}
@@ -32,7 +51,7 @@ spritebatchsprite_t textGetSprite(
tileIndex = ((int32_t)'@') - TEXT_CHAR_START;
}
assertTrue(
tileIndex >= 0 && tileIndex <= font->tileset->tileCount,
tileIndex >= 0 && tileIndex < font->tileset->tileCount,
"Character is out of bounds for font tiles"
);
@@ -54,62 +73,6 @@ spritebatchsprite_t textGetSprite(
return sprite;
}
int32_t textBuffer(
const float_t x,
const float_t y,
const char_t *text,
font_t *font,
spritebatchsprite_t *outSprites,
const int32_t maxSprites,
int32_t *charIndex,
float_t *posX,
float_t *posY
) {
assertNotNull(text, "Text cannot be NULL");
if(outSprites == NULL) {
int32_t count = 0;
char_t c;
int32_t i = 0;
while((c = text[i++]) != '\0') {
if(c != ' ' && c != '\n') count++;
}
return count;
}
assertNotNull(font, "Font cannot be NULL");
assertTrue(maxSprites > 0, "Max sprites must be greater than zero");
assertNotNull(posX, "Output posX cannot be NULL");
assertNotNull(posY, "Output posY cannot be NULL");
assertNotNull(charIndex, "Output charIndex cannot be NULL");
int32_t spriteIndex = 0;
char_t c;
for(;;) {
c = text[*charIndex];
if(c == '\0') break;
(*charIndex)++;
if(c == '\n') {
*posX = x;
*posY += font->tileset->tileHeight;
continue;
}
if(c == ' ') {
*posX += font->tileset->tileWidth;
continue;
}
outSprites[spriteIndex++] = textGetSprite((vec2){*posX, *posY}, c, font);
*posX += font->tileset->tileWidth;
if(spriteIndex >= maxSprites) break;
}
return spriteIndex;
}
errorret_t textDraw(
const float_t x,
const float_t y,
@@ -118,11 +81,10 @@ errorret_t textDraw(
font_t *font
) {
assertNotNull(text, "Text cannot be NULL");
int32_t length = strlen(text);
if(length == 0) errorOk();
if(font == NULL) font = &FONT_DEFAULT;
spritebatchsprite_t sprite;
shadermaterial_t material = {
.unlit = {
.color = color,
@@ -130,25 +92,31 @@ errorret_t textDraw(
}
};
spritebatchsprite_t sprites[32];
float_t posX = x;
float_t posY = y;
int32_t buffered = 0;
int32_t charIndex = 0;
do {
buffered = textBuffer(
x, y, text, font,
sprites,
sizeof(sprites) / sizeof(spritebatchsprite_t),
&charIndex, &posX, &posY
);
errorChain(spriteBatchBuffer(sprites, buffered, &SHADER_UNLIT, material));
} while(charIndex < length);
char_t c;
int32_t i = 0;
while((c = text[i++]) != '\0') {
if(c == '\n') {
posX = x;
posY += font->tileset->tileHeight;
continue;
}
if(c == ' ') {
posX += font->tileset->tileWidth;
continue;
}
sprite = textGetSprite((vec2){posX, posY}, c, font);
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
posX += font->tileset->tileWidth;
}
errorOk();
}
int32_t textMeasure(
void textMeasure(
const char_t *text,
const font_t *font,
int32_t *outWidth,
@@ -161,7 +129,6 @@ int32_t textMeasure(
int32_t width = 0;
int32_t height = font->tileset->tileHeight;
int32_t lineWidth = 0;
int32_t spriteCount = 0;
char_t c;
int32_t i = 0;
@@ -174,50 +141,10 @@ int32_t textMeasure(
}
lineWidth += font->tileset->tileWidth;
if(c != ' ') {
spriteCount++;
}
}
if(lineWidth > width) width = lineWidth;
*outWidth = width;
*outHeight = height;
return spriteCount;
}
void textWrap(char_t *text, const font_t *font, const float_t maxWidth) {
assertNotNull(text, "Text cannot be NULL");
assertNotNull(font, "Font cannot be NULL");
float_t fontWidth = (float_t)font->tileset->tileWidth;
if(fontWidth <= 0.0f) return;
int32_t charsPerLine = (int32_t)(maxWidth / fontWidth);
if(charsPerLine <= 0) return;
int32_t lineWidth = 0;
int32_t lastSpace = -1;
for(int32_t i = 0; text[i] != '\0'; i++) {
if(text[i] == '\n') {
lineWidth = 0;
lastSpace = -1;
continue;
}
if(text[i] == ' ') {
lastSpace = i;
}
lineWidth++;
if(lineWidth > charsPerLine && lastSpace != -1) {
text[lastSpace] = '\n';
lineWidth = i - lastSpace;
lastSpace = -1;
}
}
}
+3 -47
View File
@@ -12,6 +12,8 @@
#define TEXT_CHAR_START '!'
extern font_t FONT_DEFAULT;
/**
* Initializes the text system.
*
@@ -40,37 +42,6 @@ spritebatchsprite_t textGetSprite(
const font_t *font
);
/**
* Buffers a string into sprites for rendering. If outSprites is NULL then
* the function will only return the count of sprites necessary for the buffer.
*
* posX and posY are updated whilst buffering characters, if you need to do
* buffering in sets then these will be reusable between buffer commands. Start
* by setting these to x and y initially.
*
* @param x The x-coordinate to start buffering the text at.
* @param y The y-coordinate to start buffering the text at.
* @param text The null-terminated string of text to buffer.
* @param font Font to use for rendering.
* @param outSprites Pointer to an array of spritebatchsprite_t.
* @param maxSprites The maximum number of sprites in outSprites.
* @param charIndex Pointer to an int32_t to store the character indexed.
* @param posX Pointer to a float_t to store the final x position.
* @param posY Pointer to a float_t to store the final y position.
* @return The count of sprites buffered.
*/
int32_t textBuffer(
const float_t x,
const float_t y,
const char_t *text,
font_t *font,
spritebatchsprite_t *outSprites,
const int32_t maxSprites,
int32_t *charIndex,
float_t *posX,
float_t *posY
);
/**
* Draws a string of text at the specified position.
*
@@ -96,25 +67,10 @@ errorret_t textDraw(
* @param font Font to use for measurement.
* @param outWidth Pointer to store the measured width in pixels.
* @param outHeight Pointer to store the measured height in pixels.
* @return The count of sprites that will be rendered for the given text.
*/
int32_t textMeasure(
void textMeasure(
const char_t *text,
const font_t *font,
int32_t *outWidth,
int32_t *outHeight
);
/**
* Word-wraps text in place for display at up to maxWidth pixels wide,
* by replacing the space nearest each overflow point with a newline.
* Length is unchanged - this only ever swaps existing spaces for
* newlines, never inserts characters - so it's always safe to call on a
* fixed-size buffer. A single word wider than maxWidth on its own is
* left unbroken.
*
* @param text Null-terminated, caller-owned buffer to wrap in place.
* @param font Font to measure character width with.
* @param maxWidth Maximum line width, in pixels.
*/
void textWrap(char_t *text, const font_t *font, const float_t maxWidth);
+2 -2
View File
@@ -12,7 +12,7 @@
#include "display/display.h"
texture_t TEXTURE_WHITE;
color_t TEXTURE_WHITE_PIXELS[TEXTURE_FIXED_WIDTH * TEXTURE_FIXED_HEIGHT] = {
color_t TEXTURE_WHITE_PIXELS[4*4] = {
COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE,
COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE,
COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE,
@@ -20,7 +20,7 @@ color_t TEXTURE_WHITE_PIXELS[TEXTURE_FIXED_WIDTH * TEXTURE_FIXED_HEIGHT] = {
};
texture_t TEXTURE_TEST;
color_t TEXTURE_TEST_PIXELS[TEXTURE_FIXED_WIDTH * TEXTURE_FIXED_HEIGHT] = {
color_t TEXTURE_TEST_PIXELS[4*4] = {
COLOR_BLACK, COLOR_MAGENTA, COLOR_BLACK, COLOR_MAGENTA,
COLOR_MAGENTA, COLOR_BLACK, COLOR_MAGENTA, COLOR_BLACK,
COLOR_BLACK, COLOR_MAGENTA, COLOR_BLACK, COLOR_MAGENTA,
+2 -5
View File
@@ -17,9 +17,6 @@
#error "textureDisposePlatform should not be defined."
#endif
#define TEXTURE_FIXED_WIDTH 4
#define TEXTURE_FIXED_HEIGHT 4
typedef textureformatplatform_t textureformat_t;
typedef textureplatform_t texture_t;
@@ -32,9 +29,9 @@ typedef union texturedata_u {
} texturedata_t;
extern texture_t TEXTURE_WHITE;
extern color_t TEXTURE_WHITE_PIXELS[TEXTURE_FIXED_WIDTH * TEXTURE_FIXED_HEIGHT];
extern color_t TEXTURE_WHITE_PIXELS[4*4];
extern texture_t TEXTURE_TEST;
extern color_t TEXTURE_TEST_PIXELS[TEXTURE_FIXED_WIDTH * TEXTURE_FIXED_HEIGHT];
extern color_t TEXTURE_TEST_PIXELS[4*4];
/**
* Initializes a texture.
+49 -35
View File
@@ -7,23 +7,30 @@
#include "engine.h"
#include "util/memory.h"
#include "perf/perf.h"
#include "time/time.h"
#include "input/input.h"
#include "locale/localemanager.h"
#include "display/display.h"
#include "entity/entity.h"
#include "scene/scene.h"
#include "asset/asset.h"
#include "ui/ui.h"
#include "assert/assert.h"
#ifdef DUSK_NETWORK
#include "network/network.h"
#endif
#include "script/script.h"
#include "entity/entitymanager.h"
#include "physics/physicsmanager.h"
#include "script/scriptmanager.h"
#include "network/network.h"
#include "system/system.h"
#include "console/console.h"
#include "save/save.h"
#include "audio/audio.h"
#include "audio/mixer/audiomixer.h"
double jerry_port_current_time(void) {
dusktimeepoch_t epoch = timeGetEpoch();
return epoch.time * 1000.0;
}
int32_t jerry_port_local_tza(double unix_ms) {
(void) unix_ms;
return 0;
}
engine_t ENGINE;
@@ -36,27 +43,22 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
ENGINE.version = DUSK_VERSION;
// Init systems. Order is important.
perfInit();
timeInit();
consoleInit();
errorChain(systemInit());
errorChain(inputInit());
errorChain(assetInit());
errorChain(saveInit());
errorChain(localeManagerInit());
errorChain(scriptManagerInit());
errorChain(displayInit());
errorChain(audioInit());
errorChain(uiInit());
entityManagerInit();
#ifdef DUSK_NETWORK
physicsManagerInit();
errorChain(networkInit());
#endif
errorChain(scriptInit());
errorChain(sceneInit());
// Runs once every other system is ready, so init.ds can use any of them.
scripterror_t scriptInitError;
if(scriptRuntimeRunFile(SCRIPT.runtime, "init.dsb", false, &scriptInitError) != SCRIPT_OK) {
errorThrow("init.ds failed: %s", scriptInitError.message);
}
errorChain(scriptManagerExecFile("engine.js", NULL));
errorChain(scriptManagerCallGlobal("init"));
consolePrint("Engine initialized");
@@ -71,20 +73,31 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
errorret_t engineUpdate(void) {
// Order here is important.
#ifdef DUSK_NETWORK
errorChain(networkUpdate());
#endif
errorChain(saveUpdate());
timeUpdate();
inputUpdate();
consoleUpdate();
errorChain(audioUpdateEarly());
physicsManagerUpdate();
// Fixed-step logic: runs once per DUSK_TIME_STEP tick. On platforms
// without dynamic timing every frame is a fixed step; on platforms with
// it, dynamic (interpolation) frames are skipped.
#ifdef DUSK_TIME_DYNAMIC
if(!TIME.dynamicUpdate) {
#endif
entityManagerFixedUpdate();
errorChain(scriptManagerCallGlobal("fixedUpdate"));
#ifdef DUSK_TIME_DYNAMIC
}
#endif
errorChain(sceneUpdate());
errorChain(scriptManagerCallGlobal("update"));
errorChain(assetUpdate());
entityManagerUpdate();
errorChain(uiUpdate());
// Render
errorChain(displayUpdate());
errorChain(audioUpdateLate());
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
errorOk();
}
@@ -94,20 +107,21 @@ void engineExit(void) {
}
errorret_t engineDispose(void) {
errorChain(scriptDispose());
entityManagerDispose();
#ifdef DUSK_NETWORK
errorChain(scriptManagerCallGlobal("deinit"));
errorChain(sceneDispose());
errorChain(networkDispose());
#endif
entityManagerDispose();
localeManagerDispose();
errorChain(audioDispose());
errorChain(uiDispose());
consoleDispose();
errorChain(displayDispose());
errorChain(saveDispose());
errorChain(assetDispose());
perfDispose();
memoryCheckUnfreed();
// Must run before scriptManagerDispose(): asset entries (e.g. loaded
// scripts) hold jerry_value_t references (promises) that need to be
// released via their loader's dispose callback before jerry_cleanup()
// runs, which fatally asserts if anything is still held.
errorChain(assetDispose());
errorChain(scriptManagerDispose());
errorOk();
}
+2 -1
View File
@@ -7,8 +7,9 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
entity.c
entityrender.c
entitymanager.c
component.c
entityrender.c
)
# Subdirs
+24 -22
View File
@@ -5,20 +5,20 @@
* https://opensource.org/licenses/MIT
*/
#include "entity.h"
#include "entitymanager.h"
#include "assert/assert.h"
#include "util/memory.h"
componentdefinition_t COMPONENT_DEFINITIONS[] = {
[COMPONENT_TYPE_NULL] = { 0 },
#define X(enm, type, field, iMethod, dMethod, rMethod) \
#define X(enm, type, field, iMethod, dMethod, fMethod) \
[COMPONENT_TYPE_##enm] = { \
.enumName = #enm, \
.name = #field, \
.init = iMethod, \
.dispose = dMethod, \
.render = rMethod \
.fixedUpdate = fMethod \
},
#include "componentlist.h"
@@ -38,7 +38,7 @@ void componentInit(
assertTrue(type != COMPONENT_TYPE_NULL, "Cannot initialize null component");
componentindex_t index = componentGetIndex(entityId, componentId);
component_t *cmp = &COMPONENTS[index];
component_t *cmp = &ENTITY_MANAGER.components[index];
memoryZero(cmp, sizeof(component_t));
cmp->type = type;
@@ -58,7 +58,7 @@ void * componentGetData(
assertTrue(type != COMPONENT_TYPE_NULL, "Cannot get data of null component");
componentindex_t index = componentGetIndex(entityId, componentId);
component_t *cmp = &COMPONENTS[index];
component_t *cmp = &ENTITY_MANAGER.components[index];
assertTrue(cmp->type == type, "Component type mismatch");
return &cmp->data;
@@ -85,16 +85,16 @@ entityid_t componentGetEntitiesWithComponent(
entityid_t written = 0;
for(entityid_t i = 0; i < ENTITY_COUNT_MAX; i++) {
componentid_t used = ENTITIES_WITH_COMPONENT[
componentid_t used = ENTITY_MANAGER.entitiesWithComponent[
type * ENTITY_COUNT_MAX + i
];
if(used == COMPONENT_ID_INVALID) continue;
assertTrue(
COMPONENTS[componentGetIndex(i, used)].type == type,
ENTITY_MANAGER.components[componentGetIndex(i, used)].type == type,
"Component type mismatch in entitiesWithComponent lookup"
);
assertTrue(
(ENTITIES[i].state & ENTITY_STATE_ACTIVE) != 0,
(ENTITY_MANAGER.entities[i].state & ENTITY_STATE_ACTIVE) != 0,
"Inactive entity in entitiesWithComponent lookup"
);
assertTrue(
@@ -111,19 +111,6 @@ entityid_t componentGetEntitiesWithComponent(
return written;
}
errorret_t componentRenderAll(void) {
for(entityid_t eid = 0; eid < ENTITY_COUNT_MAX; eid++) {
if(!(ENTITIES[eid].state & ENTITY_STATE_ACTIVE)) continue;
for(componentid_t cid = 0; cid < ENTITY_COMPONENT_COUNT_MAX; cid++) {
component_t *cmp = &COMPONENTS[componentGetIndex(eid, cid)];
if(cmp->type == COMPONENT_TYPE_NULL) continue;
if(!COMPONENT_DEFINITIONS[cmp->type].render) continue;
errorChain(COMPONENT_DEFINITIONS[cmp->type].render(eid, cid));
}
}
errorOk();
}
void componentDispose(
const entityid_t entityId,
const componentid_t componentId
@@ -132,7 +119,7 @@ void componentDispose(
assertTrue(componentId < ENTITY_COMPONENT_COUNT_MAX, "Component ID OOB");
componentindex_t index = componentGetIndex(entityId, componentId);
component_t *cmp = &COMPONENTS[index];
component_t *cmp = &ENTITY_MANAGER.components[index];
if(cmp->type == COMPONENT_TYPE_NULL) return;
if(COMPONENT_DEFINITIONS[cmp->type].dispose) {
@@ -141,3 +128,18 @@ void componentDispose(
cmp->type = COMPONENT_TYPE_NULL;
}
void componentFixedUpdateAll(void) {
for(entityid_t e = 0; e < ENTITY_COUNT_MAX; e++) {
if((ENTITY_MANAGER.entities[e].state & ENTITY_STATE_ACTIVE) == 0) continue;
for(componentid_t c = 0; c < ENTITY_COMPONENT_COUNT_MAX; c++) {
componentindex_t index = componentGetIndex(e, c);
componenttype_t type = ENTITY_MANAGER.components[index].type;
if(type == COMPONENT_TYPE_NULL) continue;
if(COMPONENT_DEFINITIONS[type].fixedUpdate) {
COMPONENT_DEFINITIONS[type].fixedUpdate(e, c);
}
}
}
}
+9 -36
View File
@@ -7,54 +7,30 @@
#pragma once
#include "entitybase.h"
#include "error/error.h"
#define X(enumName, type, field, init, dispose, render) \
#define X(enumName, type, field, init, dispose, fixedUpdate) \
// do nothing
#include "componentlist.h"
#undef X
typedef union {
#define X(enumName, type, field, init, dispose, render) type field;
#define X(enumName, type, field, init, dispose, fixedUpdate) type field;
#include "componentlist.h"
#undef X
} componentdata_t;
/**
* Callback signature for a component's init/dispose hooks.
*
* @param entityId The entity ID.
* @param componentId The component ID.
*/
typedef void (*componentcallback_t)(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Callback signature for a component's render hook.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @return Error state.
*/
typedef errorret_t (*componentcallbackerror_t)(
const entityid_t entityId,
const componentid_t componentId
);
typedef struct {
const char_t *enumName;
const char_t *name;
componentcallback_t init;
componentcallback_t dispose;
componentcallbackerror_t render;
void (*init)(const entityid_t, const componentid_t);
void (*dispose)(const entityid_t, const componentid_t);
void (*fixedUpdate)(const entityid_t, const componentid_t);
} componentdefinition_t;
typedef enum {
COMPONENT_TYPE_NULL,
#define X(enumName, type, field, init, dispose, render) \
#define X(enumName, type, field, init, dispose, fixedUpdate) \
COMPONENT_TYPE_##enumName,
#include "componentlist.h"
#undef X
@@ -135,10 +111,7 @@ void componentDispose(
);
/**
* Calls the render callback on every active component that defines one.
* Iterates all active entities and all their component slots. No-op for
* components whose definition has render == NULL.
*
* @return Error state.
* Calls fixedUpdate on every active component that defines one. Intended to
* be called once per fixed timestep - see entityManagerFixedUpdate().
*/
errorret_t componentRenderAll(void);
void componentFixedUpdateAll(void);
+1 -2
View File
@@ -3,8 +3,7 @@
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Subdirs
add_subdirectory(display)
add_subdirectory(physics)
add_subdirectory(script)
add_subdirectory(trigger)
add_subdirectory(animation)
@@ -1,10 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
entityanimation.c
)
@@ -1,111 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entityanimation.h"
#include "entity/entity.h"
#include "util/memory.h"
#include "time/time.h"
void entityAnimationInit(
const entityid_t entityId,
const componentid_t componentId
) {
entityanimation_t *animComp = entityAnimationGet(entityId, componentId);
memoryZero(animComp, sizeof(entityanimation_t));
animComp->speed = 1.0f;
entityUpdateAdd(entityId, entityAnimationUpdate, componentId, NULL);
}
entityanimation_t *entityAnimationGet(
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(
entityId, componentId, COMPONENT_TYPE_ANIMATION
);
}
void entityAnimationSetKeyframes(
const entityid_t entityId,
const componentid_t componentId,
keyframe_t *keyframes,
uint16_t *keyframeCounts,
const uint16_t layerCount
) {
entityanimation_t *animComp = entityAnimationGet(entityId, componentId);
animationInit(&animComp->anim, keyframes, keyframeCounts, layerCount);
animComp->speed = 1.0f;
animComp->playing = false;
}
void entityAnimationPlay(
const entityid_t entityId,
const componentid_t componentId
) {
entityanimation_t *animComp = entityAnimationGet(entityId, componentId);
animComp->anim.time = 0.0f;
// Clear the internal completed latch so a previously-finished
// (non-looping) animation can actually advance again.
animComp->anim.flags &= ~ANIMATION_FLAG_INTERNAL_COMPLETED;
animComp->playing = true;
}
void entityAnimationStop(
const entityid_t entityId,
const componentid_t componentId
) {
entityanimation_t *animComp = entityAnimationGet(entityId, componentId);
animComp->playing = false;
}
bool_t entityAnimationIsPlaying(
const entityid_t entityId,
const componentid_t componentId
) {
entityanimation_t *animComp = entityAnimationGet(entityId, componentId);
return animComp->playing;
}
void entityAnimationSetLoop(
const entityid_t entityId,
const componentid_t componentId,
const bool_t loop
) {
entityanimation_t *animComp = entityAnimationGet(entityId, componentId);
if(loop) animComp->anim.flags |= ANIMATION_FLAG_LOOP;
else animComp->anim.flags &= ~ANIMATION_FLAG_LOOP;
}
void entityAnimationSetSpeed(
const entityid_t entityId,
const componentid_t componentId,
const float_t speed
) {
entityanimation_t *animComp = entityAnimationGet(entityId, componentId);
animComp->speed = speed;
}
float_t entityAnimationGetValue(
const entityid_t entityId,
const componentid_t componentId,
const uint16_t channelIndex
) {
entityanimation_t *animComp = entityAnimationGet(entityId, componentId);
return animationGetLayerValue(&animComp->anim, channelIndex);
}
void entityAnimationUpdate(
const entityid_t entityId,
const componentid_t componentId,
void *user
) {
entityanimation_t *animComp = entityAnimationGet(entityId, componentId);
if(!animComp->playing) return;
animationUpdate(&animComp->anim, TIME.delta * animComp->speed);
}
@@ -1,171 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
#include "animation/animation.h"
typedef struct {
animation_t anim;
/**
* Playback rate multiplier; 1.0 = normal speed. This branch's
* animation_t has no speed field of its own (animationUpdate() just
* takes a deltaTime), so the multiplier is tracked here and applied to
* TIME.delta before calling animationUpdate() each tick.
*/
float_t speed;
/**
* True while entityAnimationUpdate() should advance anim's time each
* tick. This branch's animation_t has no playing field of its own --
* advancing is purely a function of whether animationUpdate() is
* called -- so playback gating lives here instead.
*/
bool_t playing;
} entityanimation_t;
/**
* Initializes the animation component: no keyframes set, and registers
* entityAnimationUpdate as an update callback. Call
* entityAnimationSetKeyframes() before entityAnimationPlay().
*
* @param entityId The entity ID.
* @param componentId The component ID.
*/
void entityAnimationInit(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Gets the underlying animation structure (temporarily) for the given
* entity. Prefer the dedicated getters/setters where possible.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @return The animation component data for the given entity and
* component ID.
*/
entityanimation_t *entityAnimationGet(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Sets the entity's keyframes, stopped, at speed 1.0, non-looping. See
* animationInit() -- keyframes/keyframeCounts and the keyframe_t data
* they point to are not copied, and must outlive this component (e.g.
* static/const arrays owned by the caller).
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param keyframes Flat array of keyframe_t, one contiguous run per layer
* (layer's run length is keyframeCounts[layer]) -- see animationInit().
* @param keyframeCounts Array of layerCount keyframe counts, matching the
* per-layer runs in keyframes.
* @param layerCount The number of layers/channels.
*/
void entityAnimationSetKeyframes(
const entityid_t entityId,
const componentid_t componentId,
keyframe_t *keyframes,
uint16_t *keyframeCounts,
const uint16_t layerCount
);
/**
* Starts (or restarts) playback from time 0.
*
* @param entityId The entity ID.
* @param componentId The component ID.
*/
void entityAnimationPlay(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Stops playback without resetting the current time.
*
* @param entityId The entity ID.
* @param componentId The component ID.
*/
void entityAnimationStop(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Checks whether the animation is currently playing.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @return True if playing.
*/
bool_t entityAnimationIsPlaying(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Sets whether the animation loops on reaching its final keyframe, rather
* than stopping there.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param loop True to loop, false to stop at the end.
*/
void entityAnimationSetLoop(
const entityid_t entityId,
const componentid_t componentId,
const bool_t loop
);
/**
* Sets the animation's playback rate multiplier.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param speed The new playback rate; 1.0 = normal speed.
*/
void entityAnimationSetSpeed(
const entityid_t entityId,
const componentid_t componentId,
const float_t speed
);
/**
* Evaluates one of the animation's channels at its current playback
* time, regardless of whether it's currently playing.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param channelIndex The channel to evaluate, in [0, channelCount) as
* passed to entityAnimationSetKeyframes().
* @return That channel's value at the current time.
*/
float_t entityAnimationGetValue(
const entityid_t entityId,
const componentid_t componentId,
const uint16_t channelIndex
);
/**
* Per-tick update for the animation component: calls animationUpdate()
* (a no-op if not playing). Registered automatically as an update
* callback by entityAnimationInit.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param user Unused.
*/
void entityAnimationUpdate(
const entityid_t entityId,
const componentid_t componentId,
void *user
);
@@ -5,30 +5,29 @@
* https://opensource.org/licenses/MIT
*/
#include "entity/entitymanager.h"
#include "entity/entity.h"
#include "entity/component/display/entityposition.h"
#include "display/framebuffer/framebuffer.h"
#include "display/screen/screen.h"
void entityCameraInit(
const entityid_t entityId,
const componentid_t componentId
) {
void entityCameraInit(const entityid_t ent, const componentid_t comp) {
entitycamera_t *cam = (entitycamera_t *)componentGetData(
entityId, componentId, COMPONENT_TYPE_CAMERA
ent, comp, COMPONENT_TYPE_CAMERA
);
cam->nearClip = 0.1f;
cam->farClip = 5000.0f;
cam->farClip = 100.0f;
cam->projType = ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE;
cam->perspective.fov = glm_rad(45.0f);
}
void entityCameraGetProjection(
const entityid_t entityId,
const componentid_t componentId,
const entityid_t ent,
const componentid_t comp,
mat4 out
) {
entitycamera_t *cam = (entitycamera_t *)componentGetData(
entityId, componentId, COMPONENT_TYPE_CAMERA
ent, comp, COMPONENT_TYPE_CAMERA
);
if(
@@ -67,68 +66,31 @@ entityid_t entityCameraGetCurrent(void) {
entityid_t count = componentGetEntitiesWithComponent(
COMPONENT_TYPE_CAMERA, camEnts, camComps
);
if(count == 0) return ENTITY_ID_INVALID;
if(count == 0) return ENTITY_COUNT_MAX;
return camEnts[0];
}
void entityCameraGetForward(
const entityid_t entityId,
vec2 out
) {
componentid_t posComp = entityGetComponent(
entityId, COMPONENT_TYPE_POSITION
);
mat4 transform;
entityPositionGetTransform(entityId, posComp, transform);
// transform is an object->world matrix; column 2 is the entity's local Z
// axis expressed in world space. Cameras look down their local -Z.
float_t fx = -transform[2][0];
float_t fz = -transform[2][2];
void entityCameraGetForward(const entityid_t entityId, vec2 out) {
componentid_t posComp = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
entityposition_t *pos = entityPositionGet(entityId, posComp);
// View matrix column layout: M[col][row],
// forward = {-M[0][2], -M[1][2], -M[2][2]}
float_t fx = -pos->worldTransform[0][2];
float_t fz = -pos->worldTransform[2][2];
float_t len = sqrtf(fx * fx + fz * fz);
if(len > 1e-6f) { fx /= len; fz /= len; }
out[0] = fx;
out[1] = fz;
}
void entityCameraGetRight(
const entityid_t entityId,
vec2 out
) {
componentid_t posComp = entityGetComponent(
entityId, COMPONENT_TYPE_POSITION
);
mat4 transform;
entityPositionGetTransform(entityId, posComp, transform);
// transform is an object->world matrix; column 0 is the entity's local X
// (right) axis expressed in world space.
float_t rx = transform[0][0];
float_t rz = transform[0][2];
void entityCameraGetRight(const entityid_t entityId, vec2 out) {
componentid_t posComp = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
entityposition_t *pos = entityPositionGet(entityId, posComp);
// View matrix column layout: right = {M[0][0], M[1][0], M[2][0]}
float_t rx = pos->worldTransform[0][0];
float_t rz = pos->worldTransform[2][0];
float_t len = sqrtf(rx * rx + rz * rz);
if(len > 1e-6f) { rx /= len; rz /= len; }
out[0] = rx;
out[1] = rz;
}
void entityCameraLookAtPixelPerfect(
const entityid_t ent,
const componentid_t posComp,
const componentid_t camComp,
const vec3 point,
const vec3 eyeOffset,
const float_t scale
) {
entitycamera_t *cam = (entitycamera_t *)componentGetData(
ent, camComp, COMPONENT_TYPE_CAMERA
);
float_t dist = (
(float_t)SCREEN.height / (2.0f * scale * tanf(cam->perspective.fov * 0.5f))
);
vec3 eye = {
point[0] + eyeOffset[0],
point[1] + dist + eyeOffset[1],
point[2] + eyeOffset[2]
};
vec3 up = { 0.0f, 0.0f, -1.0f };
entityPositionLookAt(ent, posComp, eye, (float_t *)point, up);
}
Loaded 100 of 859 files, more files were not shown because too many files have changed in this diff. Show more