Compare commits
96 Commits
4a4adeb3c8
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 2849ff8844 | |||
| 9f3089742a | |||
| b286a9bbcd | |||
| 6204e745ba | |||
| bbe0e48d23 | |||
| 79054080c0 | |||
| 81024c4c09 | |||
| 9068d96130 | |||
| 6f47543720 | |||
| 5a08384ae1 | |||
| 45d8fda0e4 | |||
| a9e664492f | |||
| 3c8b6cb2cc | |||
| 2b3abbe13b | |||
| 241a52b94a | |||
| 82c300b077 | |||
| 0f8b629e20 | |||
| 36f6ac65f2 | |||
| a25871a849 | |||
| 57766a9104 | |||
| 3770ae1645 | |||
| d73edb403f | |||
| b14196ff0d | |||
| 88903fee94 | |||
| 1e8311fc04 | |||
| 2b78370cb8 | |||
| 8f78bba9e9 | |||
| 41a4be678e | |||
| 8b2b4b7c3d | |||
| 1f3a29f89d | |||
| c4c93097cd | |||
| eedb7769e6 | |||
| 98db62a4bc | |||
| df48c8e500 | |||
| db9cc0f4c6 | |||
| a79ee429b4 | |||
| 6acfca6d48 | |||
| 1cd6f4cb72 | |||
| 3271e8c7d6 | |||
| 0bcde064af | |||
| 957980b3c5 | |||
| 03eb328d81 | |||
| e1716a741f | |||
| e24707c847 | |||
| 7c4b8c307f | |||
| 109318aeaf | |||
| 1f2657cea0 | |||
| 382c435bac | |||
| 130fe4ca5d | |||
| 31ba3fe127 | |||
| f68b31158f | |||
| 653ca9a72d | |||
| ba7857f4df | |||
| 23e617ea21 | |||
| cdf5a5229c | |||
| f841a35a53 | |||
| efd31237be | |||
| 6502822583 | |||
| a9e6f2b2a5 | |||
| 510a94b42c | |||
| d805be47ce | |||
| f9ea8e380a | |||
| 5cb05beb30 | |||
| 677768e6ab | |||
| ed6c951783 | |||
| 54254348b8 | |||
| 782fd07a8d | |||
| a8fd55cb38 | |||
| d7f515575a | |||
| bafbf2ec2f | |||
| 7415944e0a | |||
| 1ff990ff44 | |||
| 73e73d8772 | |||
| 6d876bb767 | |||
| 2be0fe9f06 | |||
| e1fb082927 | |||
| 65ca5ae4c4 | |||
| 2cea43dc70 | |||
| 44a0700800 | |||
| 1613a378f1 | |||
| deed98a27d | |||
| 9d0cb8fb46 | |||
| d8fe0f6923 | |||
| 581dbc2b3c | |||
| 7301d2ad76 | |||
| 3232a14d1d | |||
| 84c1f88d42 | |||
| 3695b10e4b | |||
| 6da02b25fa | |||
| 3bc544fba1 | |||
| 368d370f49 | |||
| bb29c0edef | |||
| 6edcf75a0c | |||
| 31cc186424 | |||
| 0e94c1fa6d | |||
| 6d9e2dd3e1 |
@@ -110,6 +110,28 @@ jobs:
|
||||
path: ./git-artifcats/Dusk
|
||||
if-no-files-found: error
|
||||
|
||||
build-gamecube-iso:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
- name: Set up Docker
|
||||
uses: docker/setup-docker-action@v5
|
||||
- name: Build GameCube ISO
|
||||
run: ./scripts/build-gamecube-iso-docker.sh
|
||||
- name: Copy output files.
|
||||
run: |
|
||||
mkdir -p ./git-artifcats/Dusk
|
||||
cp build-gamecube-iso/Dusk-NTSC-J.iso ./git-artifcats/Dusk/Dusk-NTSC-J.iso
|
||||
cp build-gamecube-iso/Dusk-NTSC-U.iso ./git-artifcats/Dusk/Dusk-NTSC-U.iso
|
||||
cp build-gamecube-iso/Dusk-PAL.iso ./git-artifcats/Dusk/Dusk-PAL.iso
|
||||
- name: Upload GameCube ISO
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: dusk-gamecube-iso
|
||||
path: ./git-artifcats/Dusk
|
||||
if-no-files-found: error
|
||||
|
||||
build-wii:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -122,12 +144,34 @@ jobs:
|
||||
- name: Copy output files.
|
||||
run: |
|
||||
mkdir -p ./git-artifcats/Dusk/apps/Dusk
|
||||
cp build-wii/Dusk.dol ./git-artifcats/Dusk/apps/Dusk/boot.dol
|
||||
cp build-wii/boot.dol ./git-artifcats/Dusk/apps/Dusk/boot.dol
|
||||
cp build-wii/dusk.dsk ./git-artifcats/Dusk/apps/Dusk/dusk.dsk
|
||||
cp docker/dolphin/meta.xml ./git-artifcats/Dusk/apps/Dusk/meta.xml
|
||||
cp build-wii/meta.xml ./git-artifcats/Dusk/apps/Dusk/meta.xml
|
||||
- name: Upload Wii binary
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: dusk-wii
|
||||
path: ./git-artifcats/Dusk
|
||||
if-no-files-found: error
|
||||
|
||||
build-wii-iso:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
- name: Set up Docker
|
||||
uses: docker/setup-docker-action@v5
|
||||
- name: Build Wii ISO
|
||||
run: ./scripts/build-wii-iso-docker.sh
|
||||
- name: Copy output files.
|
||||
run: |
|
||||
mkdir -p ./git-artifcats/Dusk
|
||||
cp build-wii-iso/Dusk-NTSC-J.iso ./git-artifcats/Dusk/Dusk-NTSC-J.iso
|
||||
cp build-wii-iso/Dusk-NTSC-U.iso ./git-artifcats/Dusk/Dusk-NTSC-U.iso
|
||||
cp build-wii-iso/Dusk-PAL.iso ./git-artifcats/Dusk/Dusk-PAL.iso
|
||||
- name: Upload Wii ISO
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: dusk-wii-iso
|
||||
path: ./git-artifcats/Dusk
|
||||
if-no-files-found: error
|
||||
+2
-1
@@ -105,4 +105,5 @@ yarn.lock
|
||||
/build2
|
||||
/build*
|
||||
/assets/test
|
||||
/tools_old
|
||||
/tools_old
|
||||
/assets/test.png
|
||||
+16
-1
@@ -9,11 +9,17 @@ 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)
|
||||
# [cmake] This is allowed only when policy CMP0079 is set to NEW.
|
||||
cmake_policy(SET CMP0079 NEW)
|
||||
# set(FETCHCONTENT_UPDATES_DISCONNECTED ON)
|
||||
|
||||
option(DUSK_BUILD_TESTS "Enable tests" OFF)
|
||||
|
||||
# Game identity — override these per-project
|
||||
set(DUSK_GAME_NAME "Dusk" CACHE STRING "Game display name")
|
||||
set(DUSK_GAME_AUTHOR "YouWish" 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")
|
||||
|
||||
# Prep cache
|
||||
set(DUSK_CACHE_TARGET "dusk-target")
|
||||
|
||||
@@ -70,10 +76,19 @@ else()
|
||||
set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||
endif()
|
||||
|
||||
if(NOT DEFINED DUSK_VERSION)
|
||||
string(TIMESTAMP DUSK_VERSION "debug-%y%m%d%H%M%S")
|
||||
endif()
|
||||
|
||||
# Definitions
|
||||
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
DUSK_TARGET_SYSTEM="${DUSK_TARGET_SYSTEM}"
|
||||
DUSK_GAME_NAME="${DUSK_GAME_NAME}"
|
||||
DUSK_GAME_AUTHOR="${DUSK_GAME_AUTHOR}"
|
||||
DUSK_GAME_SHORT_DESCRIPTION="${DUSK_GAME_SHORT_DESCRIPTION}"
|
||||
DUSK_GAME_LONG_DESCRIPTION="${DUSK_GAME_LONG_DESCRIPTION}"
|
||||
DUSK_VERSION="${DUSK_VERSION}"
|
||||
)
|
||||
|
||||
# Toolchains
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
var OverworldEntity = include('entities/OverworldEntity.js');
|
||||
|
||||
function CubeEntity() {
|
||||
OverworldEntity.call(this);
|
||||
|
||||
this.add(MESH);
|
||||
this.add(MATERIAL);
|
||||
}
|
||||
|
||||
CubeEntity.prototype = Object.create(OverworldEntity.prototype);
|
||||
CubeEntity.prototype.constructor = CubeEntity;
|
||||
|
||||
CubeEntity.prototype.update = function() {
|
||||
OverworldEntity.prototype.update.call(this);
|
||||
var speed = 3.0;
|
||||
var move = Input.axis2D(INPUT_ACTION_LEFT, INPUT_ACTION_RIGHT, INPUT_ACTION_UP, INPUT_ACTION_DOWN);
|
||||
this.position.position.x += move.x * speed * TIME.delta;
|
||||
this.position.position.z += move.y * speed * TIME.delta;
|
||||
this.material.setColor(Color.rainbow());
|
||||
};
|
||||
|
||||
module = CubeEntity;
|
||||
@@ -1,21 +0,0 @@
|
||||
function OverworldEntity() {
|
||||
Entity.call(this);
|
||||
|
||||
this.add(POSITION);
|
||||
}
|
||||
|
||||
OverworldEntity.prototype = Object.create(Entity.prototype);
|
||||
OverworldEntity.prototype.constructor = OverworldEntity;
|
||||
|
||||
OverworldEntity.prototype.update = function() {
|
||||
// var speed = 3.0;
|
||||
// var move = Input.axis2D(INPUT_ACTION_LEFT, INPUT_ACTION_RIGHT, INPUT_ACTION_UP, INPUT_ACTION_DOWN);
|
||||
// this.position.position.x += move.x * speed * TIME.delta;
|
||||
// this.position.position.z += move.y * speed * TIME.delta;
|
||||
}
|
||||
|
||||
OverworldEntity.prototype.dispose = function() {
|
||||
// Nothing to dispose
|
||||
}
|
||||
|
||||
module = OverworldEntity;
|
||||
+8
-76
@@ -1,77 +1,9 @@
|
||||
Console.visible = true;
|
||||
const platformNames = {
|
||||
[System.PLATFORM_LINUX]: 'Linux',
|
||||
[System.PLATFORM_KNULLI]: 'Knulli',
|
||||
[System.PLATFORM_PSP]: 'PSP',
|
||||
[System.PLATFORM_GAMECUBE]: 'GameCube',
|
||||
[System.PLATFORM_WII]: 'Wii',
|
||||
};
|
||||
|
||||
// Default input bindings.
|
||||
if (typeof PSP !== 'undefined') {
|
||||
Input.bind("up", INPUT_ACTION_UP);
|
||||
Input.bind("down", INPUT_ACTION_DOWN);
|
||||
Input.bind("left", INPUT_ACTION_LEFT);
|
||||
Input.bind("right", INPUT_ACTION_RIGHT);
|
||||
Input.bind("accept", INPUT_ACTION_ACCEPT);
|
||||
Input.bind("cancel", INPUT_ACTION_CANCEL);
|
||||
Input.bind("select", INPUT_ACTION_RAGEQUIT);
|
||||
Input.bind("lstick_up", INPUT_ACTION_UP);
|
||||
Input.bind("lstick_down", INPUT_ACTION_DOWN);
|
||||
Input.bind("lstick_left", INPUT_ACTION_LEFT);
|
||||
Input.bind("lstick_right", INPUT_ACTION_RIGHT);
|
||||
Input.bind("triangle", INPUT_ACTION_CONSOLE);
|
||||
|
||||
} else if (typeof DOLPHIN !== 'undefined') {
|
||||
Input.bind("up", INPUT_ACTION_UP);
|
||||
Input.bind("down", INPUT_ACTION_DOWN);
|
||||
Input.bind("left", INPUT_ACTION_LEFT);
|
||||
Input.bind("right", INPUT_ACTION_RIGHT);
|
||||
Input.bind("b", INPUT_ACTION_CANCEL);
|
||||
Input.bind("a", INPUT_ACTION_ACCEPT);
|
||||
Input.bind("z", INPUT_ACTION_CONSOLE);
|
||||
Input.bind("lstick_up", INPUT_ACTION_UP);
|
||||
Input.bind("lstick_down", INPUT_ACTION_DOWN);
|
||||
Input.bind("lstick_left", INPUT_ACTION_LEFT);
|
||||
Input.bind("lstick_right", INPUT_ACTION_RIGHT);
|
||||
|
||||
} else if (typeof LINUX !== 'undefined') {
|
||||
if (typeof INPUT_KEYBOARD !== 'undefined') {
|
||||
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("left", INPUT_ACTION_LEFT);
|
||||
Input.bind("right", INPUT_ACTION_RIGHT);
|
||||
Input.bind("up", INPUT_ACTION_UP);
|
||||
Input.bind("down", INPUT_ACTION_DOWN);
|
||||
|
||||
Input.bind("enter", INPUT_ACTION_ACCEPT);
|
||||
Input.bind("e", INPUT_ACTION_ACCEPT);
|
||||
|
||||
Input.bind("q", INPUT_ACTION_CANCEL);
|
||||
|
||||
Input.bind("escape", INPUT_ACTION_RAGEQUIT);
|
||||
Input.bind("`", INPUT_ACTION_CONSOLE);
|
||||
}
|
||||
|
||||
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_b", INPUT_ACTION_CANCEL);
|
||||
Input.bind("gamepad_back", INPUT_ACTION_RAGEQUIT);
|
||||
|
||||
Input.bind("gamepad_lstick_up", INPUT_ACTION_UP);
|
||||
Input.bind("gamepad_lstick_down", INPUT_ACTION_DOWN);
|
||||
Input.bind("gamepad_lstick_left", INPUT_ACTION_LEFT);
|
||||
Input.bind("gamepad_lstick_right", INPUT_ACTION_RIGHT);
|
||||
}
|
||||
|
||||
if (typeof INPUT_POINTER !== 'undefined') {
|
||||
Input.bind("mouse_x", INPUT_ACTION_POINTERX);
|
||||
Input.bind("mouse_y", INPUT_ACTION_POINTERY);
|
||||
}
|
||||
|
||||
} else {
|
||||
print("Unknown platform, no default input bindings set.");
|
||||
}
|
||||
|
||||
Scene.set('scenes/cube.js');
|
||||
Console.print('Platform: ' + (platformNames[System.platform] || 'Unknown'));
|
||||
@@ -1,32 +0,0 @@
|
||||
var CubeEntity = include('entities/CubeEntity.js');
|
||||
|
||||
function CubeScene() {
|
||||
this.cam = new Entity();
|
||||
this.cam.add(POSITION);
|
||||
this.cam.add(CAMERA);
|
||||
|
||||
this.cam.position.position = new Vec3(3, 3, 3);
|
||||
this.cam.position.lookAt(new Vec3(0, 0, 0));
|
||||
|
||||
this.cube = new CubeEntity();
|
||||
|
||||
this.spriteEnt = new Entity();
|
||||
this.spriteEnt.add(POSITION);
|
||||
this.spriteEnt.position.position = new Vec3(16, 16, 0);
|
||||
// this.spriteEnt.sprite.setTexture('ui/minogram.png');
|
||||
}
|
||||
|
||||
CubeScene.prototype = Object.create(Scene.prototype);
|
||||
CubeScene.prototype.constructor = CubeScene;
|
||||
|
||||
CubeScene.prototype.update = function() {
|
||||
this.cube.update();
|
||||
};
|
||||
|
||||
CubeScene.prototype.dispose = function() {
|
||||
this.cam.dispose();
|
||||
this.cube.dispose();
|
||||
this.spriteEnt.dispose();
|
||||
};
|
||||
|
||||
module = CubeScene;
|
||||
@@ -0,0 +1,58 @@
|
||||
Console.print('testscene.js is loaded');
|
||||
|
||||
module.exports = {
|
||||
test: function() {
|
||||
return 'Hello string';
|
||||
}
|
||||
}
|
||||
|
||||
// var scene = {
|
||||
// 'test': 'teststring'
|
||||
// };
|
||||
|
||||
// var assets = AssetBatch([
|
||||
// { path: 'test.png', type: Asset.TYPE_TEXTURE, format: Texture.FORMAT_RGBA }
|
||||
// ]);
|
||||
|
||||
// var cam;
|
||||
// var camPos;
|
||||
// var testEntity;
|
||||
// var testPos;
|
||||
// var testRenderable;
|
||||
// var texEntry;
|
||||
|
||||
// scene.init = function() {
|
||||
// assets.lock();
|
||||
// assets.onLoaded[0] = scene.loaded;
|
||||
// };
|
||||
|
||||
// scene.loaded = function() {
|
||||
// texEntry = assets.entry(0);
|
||||
|
||||
// // Camera at (3, 3, 3) looking at origin
|
||||
// cam = Entity.create();
|
||||
// camPos = cam.add(Component.POSITION);
|
||||
// cam.add(Component.CAMERA);
|
||||
// camPos.localPosition = new Vec3(3, 3, 3);
|
||||
// camPos.lookAt(new Vec3(0, 0, 0));
|
||||
|
||||
// // Test entity with textured quad at origin
|
||||
// testEntity = Entity.create();
|
||||
// testPos = testEntity.add(Component.POSITION);
|
||||
// testRenderable = testEntity.add(Component.RENDERABLE);
|
||||
|
||||
// testRenderable.texture = texEntry.texture;
|
||||
// testRenderable.sprites = [
|
||||
// [0, 0, 1, 1, 0, 1, 1, 0]
|
||||
// ];
|
||||
// testPos.localPosition = new Vec3(0, 0, 0);
|
||||
// }
|
||||
|
||||
// scene.dispose = function() {
|
||||
// Console.print('Scene Dispose');
|
||||
// Entity.dispose(cam);
|
||||
// Entity.dispose(testEntity);
|
||||
// assets.unlock();
|
||||
// };
|
||||
|
||||
// module.exports = scene;
|
||||
@@ -0,0 +1,6 @@
|
||||
module = {
|
||||
render() {
|
||||
Text.draw(0, 0, "Hello World");
|
||||
SpriteBatch.flush();
|
||||
}
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
# Copyright (c) 2026 Dominic Masters
|
||||
#
|
||||
#
|
||||
# This software is released under the MIT License.
|
||||
# https://opensource.org/licenses/MIT
|
||||
|
||||
|
||||
+46
-13
@@ -1,40 +1,73 @@
|
||||
# Target definitions
|
||||
# Build type: DOL (SD/USB via libfat) or ISO (DVD disc via libogc DVD driver)
|
||||
set(DUSK_DOLPHIN_BUILD_TYPE "DOL" CACHE STRING "Dolphin asset source: DOL (SD/USB) or ISO (DVD disc)")
|
||||
set_property(CACHE DUSK_DOLPHIN_BUILD_TYPE PROPERTY STRINGS "DOL" "ISO")
|
||||
|
||||
# Numeric tokens so #if DUSK_DOLPHIN_BUILD_TYPE == DOL works in C.
|
||||
# DUSK_DOLPHIN_BUILD_TYPE is passed without quotes so it expands to the identifier.
|
||||
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||
DUSK_DOLPHIN
|
||||
DUSK_INPUT_GAMEPAD
|
||||
DUSK_DISPLAY_WIDTH=640
|
||||
DUSK_DISPLAY_HEIGHT=480
|
||||
DUSK_THREAD_PTHREAD
|
||||
DOL=1
|
||||
ISO=2
|
||||
DUSK_DOLPHIN_BUILD_TYPE=${DUSK_DOLPHIN_BUILD_TYPE}
|
||||
)
|
||||
|
||||
# Custom compiler flags
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-rtti -fno-exceptions")
|
||||
|
||||
# Need PkgConfig
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(zip IMPORTED_TARGET libzip)
|
||||
|
||||
# Disable all warnings
|
||||
target_compile_options(${DUSK_LIBRARY_TARGET_NAME} PRIVATE -w)
|
||||
|
||||
# Custom flags for cglm
|
||||
set(CGLM_SHARED OFF CACHE BOOL "Build cglm shared" FORCE)
|
||||
set(CGLM_STATIC ON CACHE BOOL "Build cglm static" FORCE)
|
||||
# cglm: fetched at source level via Findcglm.cmake (FetchContent, headers only)
|
||||
find_package(cglm REQUIRED)
|
||||
|
||||
# Link libraries
|
||||
# Pre-create ZLIB::ZLIB so any downstream cmake module that resolves it
|
||||
# (FindZLIB, pkg-config IMPORTED_TARGET Requires processing) gets plain -lz
|
||||
# rather than an unresolvable IMPORTED target that the PPC linker rejects.
|
||||
if(NOT TARGET ZLIB::ZLIB)
|
||||
add_library(ZLIB::ZLIB INTERFACE IMPORTED GLOBAL)
|
||||
set_target_properties(ZLIB::ZLIB PROPERTIES INTERFACE_LINK_LIBRARIES "z")
|
||||
endif()
|
||||
|
||||
# Mark libzip as found so src/dusk/CMakeLists.txt skips Findlibzip.cmake.
|
||||
# Findlibzip.cmake calls find_package(ZLIB) which can recreate a broken
|
||||
# ZLIB::ZLIB IMPORTED target, bypassing the shim above.
|
||||
set(libzip_FOUND TRUE CACHE BOOL "libzip found (devkitpro portlibs)" FORCE)
|
||||
|
||||
# Locate zip.h in the devkitpro sysroot (respects CMAKE_FIND_ROOT_PATH).
|
||||
find_path(_dusk_zip_inc NAMES zip.h)
|
||||
if(_dusk_zip_inc)
|
||||
target_include_directories(${DUSK_LIBRARY_TARGET_NAME} PRIVATE "${_dusk_zip_inc}")
|
||||
endif()
|
||||
|
||||
# Link libraries.
|
||||
# zip/z/lzma use target_link_options (raw flags) to bypass cmake target
|
||||
# resolution — pkg-config-generated targets for these carry ZLIB::ZLIB in
|
||||
# INTERFACE_LINK_LIBRARIES which breaks the PPC link step.
|
||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
|
||||
cglm
|
||||
m
|
||||
fat
|
||||
PkgConfig::zip
|
||||
zip
|
||||
bz2
|
||||
zstd
|
||||
z
|
||||
lzma
|
||||
)
|
||||
|
||||
# Postbuild
|
||||
if(DUSK_DOLPHIN_BUILD_TYPE STREQUAL "ISO")
|
||||
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC DUSK_DOLPHIN_BUILD_ISO)
|
||||
else()
|
||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE fat)
|
||||
endif()
|
||||
|
||||
# Postbuild: ELF -> DOL
|
||||
set(DUSK_BINARY_TARGET_NAME_DOL "${DUSK_BUILD_DIR}/Dusk.dol")
|
||||
add_custom_command(TARGET ${DUSK_BINARY_TARGET_NAME} POST_BUILD
|
||||
COMMAND elf2dol
|
||||
"$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>"
|
||||
"${DUSK_BINARY_TARGET_NAME_DOL}"
|
||||
COMMENT "Generating ${DUSK_BINARY_TARGET_NAME_DOL} from ${DUSK_BINARY_TARGET_NAME}"
|
||||
)
|
||||
)
|
||||
|
||||
@@ -8,3 +8,17 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
|
||||
# bba
|
||||
)
|
||||
|
||||
# ISO post-build: produce NTSC-J, NTSC-U and PAL disc images
|
||||
if(DUSK_DOLPHIN_BUILD_TYPE STREQUAL "ISO")
|
||||
add_custom_command(TARGET ${DUSK_BINARY_TARGET_NAME} POST_BUILD
|
||||
COMMAND ${Python3_EXECUTABLE}
|
||||
"${CMAKE_SOURCE_DIR}/tools/makedolphiniso.py"
|
||||
"GCN"
|
||||
"${DUSK_BINARY_TARGET_NAME_DOL}"
|
||||
"${DUSK_ASSETS_ZIP}"
|
||||
"${DUSK_GAME_NAME}"
|
||||
"${DUSK_BUILD_DIR}"
|
||||
COMMENT "Building GameCube ISO images (NTSC-J, NTSC-U, PAL)"
|
||||
)
|
||||
endif()
|
||||
|
||||
@@ -34,6 +34,7 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||
DUSK_OPENGL
|
||||
DUSK_OPENGL_ES
|
||||
DUSK_LINUX
|
||||
DUSK_KNULLI
|
||||
DUSK_DISPLAY_SIZE_DYNAMIC
|
||||
DUSK_DISPLAY_WIDTH_DEFAULT=640
|
||||
DUSK_DISPLAY_HEIGHT_DEFAULT=480
|
||||
|
||||
@@ -26,6 +26,8 @@ target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||
# CURL::libcurl
|
||||
)
|
||||
|
||||
set(DUSK_BACKTRACE ON CACHE BOOL "Enable backtrace support for assert failures.")
|
||||
|
||||
# Define platform-specific macros.
|
||||
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||
DUSK_SDL2
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# Fixes some problems building JerryScript
|
||||
set(CMAKE_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
|
||||
set(CMAKE_RANLIB "$ENV{PSPDEV}/bin/psp-ranlib" CACHE FILEPATH "" FORCE)
|
||||
set(CMAKE_C_COMPILER_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
|
||||
@@ -8,9 +7,7 @@ set(CMAKE_C_ARCHIVE_APPEND "$ENV{PSPDEV}/bin/psp-ar q <TARGET> <LINK_FLAGS> <OBJ
|
||||
set(CMAKE_C_ARCHIVE_FINISH "$ENV{PSPDEV}/bin/psp-ranlib <TARGET>")
|
||||
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION OFF CACHE BOOL "" FORCE)
|
||||
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_C OFF CACHE BOOL "" FORCE)
|
||||
set(JERRY_LTO OFF CACHE BOOL "" FORCE)
|
||||
|
||||
find_package(jerryscript REQUIRED)
|
||||
find_package(SDL2 REQUIRED)
|
||||
find_package(OpenGL REQUIRED)
|
||||
target_link_libraries(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
||||
@@ -42,10 +39,6 @@ target_link_libraries(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
||||
pspnet_apctl
|
||||
psphttp
|
||||
pspssl
|
||||
|
||||
jerryscript::core
|
||||
jerryscript::ext
|
||||
jerryscript::port
|
||||
)
|
||||
|
||||
target_include_directories(${DUSK_BINARY_TARGET_NAME} PRIVATE
|
||||
|
||||
+23
-1
@@ -2,4 +2,26 @@ include(cmake/targets/dolphin.cmake)
|
||||
|
||||
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||
DUSK_WII
|
||||
)
|
||||
)
|
||||
|
||||
# Generate Homebrew Channel meta.xml from project identity variables
|
||||
string(TIMESTAMP DUSK_BUILD_DATE "%Y%m%d000000" UTC)
|
||||
configure_file(
|
||||
"${CMAKE_SOURCE_DIR}/docker/dolphin/meta.xml.in"
|
||||
"${DUSK_BUILD_DIR}/meta.xml"
|
||||
@ONLY
|
||||
)
|
||||
|
||||
# ISO post-build: produce NTSC-J, NTSC-U and PAL disc images
|
||||
if(DUSK_DOLPHIN_BUILD_TYPE STREQUAL "ISO")
|
||||
add_custom_command(TARGET ${DUSK_BINARY_TARGET_NAME} POST_BUILD
|
||||
COMMAND ${Python3_EXECUTABLE}
|
||||
"${CMAKE_SOURCE_DIR}/tools/makedolphiniso.py"
|
||||
"WII"
|
||||
"${DUSK_BINARY_TARGET_NAME_DOL}"
|
||||
"${DUSK_ASSETS_ZIP}"
|
||||
"${DUSK_GAME_NAME}"
|
||||
"${DUSK_BUILD_DIR}"
|
||||
COMMENT "Building Wii ISO images (NTSC-J, NTSC-U, PAL)"
|
||||
)
|
||||
endif()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
FROM devkitpro/devkitppc
|
||||
FROM ghcr.io/extremscorner/libogc2
|
||||
WORKDIR /workdir
|
||||
RUN apt update && \
|
||||
apt install -y python3 python3-pip python3-polib python3-pil python3-dotenv python3-pyqt5 python3-opengl && \
|
||||
dkp-pacman -S --needed --noconfirm gamecube-sdl2 ppc-liblzma ppc-libzip
|
||||
dkp-pacman -Syu --noconfirm && \
|
||||
apt install -y python3 python3-pip python3-polib python3-pil python3-dotenv python3-pyqt5 python3-opengl xorriso && \
|
||||
dkp-pacman -S --needed --noconfirm gamecube-sdl2 ppc-liblzma ppc-libzip libogc2 gamecube-tools ppc-libmad ppc-zlib-ng ppc-liblzma ppc-bzip2 ppc-zstd
|
||||
VOLUME ["/workdir"]
|
||||
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<app version="1">
|
||||
<name>Dusk</name>
|
||||
<version>1.00</version>
|
||||
<release_date></release_date>
|
||||
<coder>YouWish</coder>
|
||||
<short_description>Dusk game</short_description>
|
||||
<long_description>No description yet.</long_description>
|
||||
<ahb_access/>
|
||||
</app>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<app version="1">
|
||||
<name>@DUSK_GAME_NAME@</name>
|
||||
<version>@PROJECT_VERSION@</version>
|
||||
<release_date>@DUSK_BUILD_DATE@</release_date>
|
||||
<coder>@DUSK_GAME_AUTHOR@</coder>
|
||||
<short_description>@DUSK_GAME_SHORT_DESCRIPTION@</short_description>
|
||||
<long_description>@DUSK_GAME_LONG_DESCRIPTION@</long_description>
|
||||
<ahb_access/>
|
||||
</app>
|
||||
@@ -14,8 +14,8 @@ RUN apt-get install -y \
|
||||
python3-dotenv \
|
||||
python3-pyqt5 \
|
||||
python3-opengl \
|
||||
liblua5.3-dev \
|
||||
xz-utils \
|
||||
liblzma-dev \
|
||||
libbz2-dev \
|
||||
zlib1g-dev \
|
||||
libzip-dev \
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
#!/bin/bash
|
||||
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
||||
docker run --rm -v $(pwd):/workdir dusk-dolphin /bin/bash -c "./scripts/build-gamecube.sh"
|
||||
docker run --rm -v "$(pwd):/workdir" dusk-dolphin /bin/bash -c "./scripts/build-gamecube.sh"
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/bin/bash
|
||||
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
||||
docker run --rm -v "$(pwd):/workdir" dusk-dolphin /bin/bash -c "./scripts/build-gamecube-iso.sh"
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
if [ -z "$DEVKITPRO" ]; then
|
||||
echo "DEVKITPRO environment variable is not set. Please set it to the path of your DEVKITPRO installation."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p build-gamecube-iso
|
||||
cmake -S. -Bbuild-gamecube-iso \
|
||||
-DDUSK_TARGET_SYSTEM=gamecube \
|
||||
-DDUSK_DOLPHIN_BUILD_TYPE=ISO \
|
||||
-DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/GameCube.cmake"
|
||||
cd build-gamecube-iso
|
||||
make -j$(nproc) VERBOSE=1
|
||||
@@ -5,6 +5,10 @@ if [ -z "$DEVKITPRO" ]; then
|
||||
fi
|
||||
|
||||
mkdir -p build-gamecube
|
||||
cmake -S. -Bbuild-gamecube -DDUSK_TARGET_SYSTEM=gamecube -DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/GameCube.cmake"
|
||||
cmake -S. -Bbuild-gamecube \
|
||||
-DDUSK_TARGET_SYSTEM=gamecube \
|
||||
-DDUSK_DOLPHIN_BUILD_TYPE=DOL \
|
||||
-DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/GameCube.cmake" \
|
||||
-DDKP_OGC_PLATFORM_LIBRARY=libogc2
|
||||
cd build-gamecube
|
||||
make -j$(nproc) VERBOSE=1
|
||||
@@ -1,3 +1,3 @@
|
||||
#!/bin/bash
|
||||
docker build -t dusk-knulli -f docker/knulli/Dockerfile .
|
||||
docker run --rm -v $(pwd):/workdir dusk-knulli /bin/bash -c "./scripts/build-knulli.sh"
|
||||
docker run --rm -v "$(pwd):/workdir" dusk-knulli /bin/bash -c "./scripts/build-knulli.sh"
|
||||
@@ -1,3 +1,3 @@
|
||||
#!/bin/bash
|
||||
docker build -t dusk-linux -f docker/linux/Dockerfile .
|
||||
docker run --rm -v $(pwd):/workdir dusk-linux /bin/bash -c "./scripts/build-linux.sh"
|
||||
docker run --rm -v "$(pwd):/workdir" dusk-linux /bin/bash -c "./scripts/build-linux.sh"
|
||||
@@ -1,3 +1,3 @@
|
||||
#!/bin/bash
|
||||
docker build -t dusk-psp -f docker/psp/Dockerfile .
|
||||
docker run --rm -v $(pwd):/workdir dusk-psp /bin/bash -c "./scripts/build-psp.sh"
|
||||
docker run --rm -v "$(pwd):/workdir" dusk-psp /bin/bash -c "./scripts/build-psp.sh"
|
||||
@@ -1,3 +1,3 @@
|
||||
#!/bin/bash
|
||||
docker build -t dusk-vita -f docker/vita/Dockerfile .
|
||||
docker run --rm -v $(pwd):/workdir dusk-vita /bin/bash -c "./scripts/build-vita.sh"
|
||||
docker run --rm -v "$(pwd):/workdir" dusk-vita /bin/bash -c "./scripts/build-vita.sh"
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
#!/bin/bash
|
||||
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
||||
docker run --rm -v $(pwd):/workdir dusk-dolphin /bin/bash -c "./scripts/build-wii.sh"
|
||||
docker run --rm -v "$(pwd):/workdir" dusk-dolphin /bin/bash -c "./scripts/build-wii.sh"
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/bin/bash
|
||||
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
||||
docker run --rm -v "$(pwd):/workdir" dusk-dolphin /bin/bash -c "./scripts/build-wii-iso.sh"
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
if [ -z "$DEVKITPRO" ]; then
|
||||
echo "DEVKITPRO environment variable is not set. Please set it to the path of your DEVKITPRO installation."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p build-wii-iso
|
||||
cmake -S. -Bbuild-wii-iso \
|
||||
-DDUSK_TARGET_SYSTEM=wii \
|
||||
-DDUSK_DOLPHIN_BUILD_TYPE=ISO \
|
||||
-DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/Wii.cmake"
|
||||
cd build-wii-iso
|
||||
make -j$(nproc) VERBOSE=1
|
||||
@@ -5,6 +5,10 @@ if [ -z "$DEVKITPRO" ]; then
|
||||
fi
|
||||
|
||||
mkdir -p build-wii
|
||||
cmake -S. -Bbuild-wii -DDUSK_TARGET_SYSTEM=wii -DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/Wii.cmake"
|
||||
cmake -S. -Bbuild-wii \
|
||||
-DDUSK_TARGET_SYSTEM=wii \
|
||||
-DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/Wii.cmake" \
|
||||
-DDUSK_DOLPHIN_BUILD_TYPE=DOL
|
||||
cd build-wii
|
||||
make -j$(nproc) VERBOSE=1
|
||||
make -j$(nproc) VERBOSE=1
|
||||
mv Dusk.dol boot.dol
|
||||
@@ -1,3 +1,3 @@
|
||||
#!/bin/bash
|
||||
docker build -t dusk-linux -f docker/linux/Dockerfile .
|
||||
docker run --rm -v $(pwd):/workdir dusk-linux /bin/bash -c "./scripts/test-linux.sh"
|
||||
docker run --rm -v "$(pwd):/workdir" dusk-linux /bin/bash -c "./scripts/test-linux.sh"
|
||||
@@ -1,4 +1,6 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
rm -rf build-tests
|
||||
cmake -S . -B build-tests -DDUSK_BUILD_TESTS=ON -DDUSK_TARGET_SYSTEM=linux
|
||||
cmake --build build-tests -- -j$(nproc)
|
||||
ctest --output-on-failure --test-dir build-tests
|
||||
@@ -4,7 +4,6 @@
|
||||
# https://opensource.org/licenses/MIT
|
||||
|
||||
add_subdirectory(dusk)
|
||||
add_subdirectory(duskrpg)
|
||||
|
||||
if(DUSK_TARGET_SYSTEM STREQUAL "linux" OR DUSK_TARGET_SYSTEM STREQUAL "knulli")
|
||||
add_subdirectory(dusklinux)
|
||||
|
||||
@@ -41,6 +41,13 @@ if(NOT jerryscript_FOUND)
|
||||
)
|
||||
endif()
|
||||
|
||||
if(DUSK_BACKTRACE)
|
||||
target_link_options(${DUSK_LIBRARY_TARGET_NAME} PUBLIC -rdynamic)
|
||||
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
||||
DUSK_BACKTRACE
|
||||
)
|
||||
endif()
|
||||
|
||||
# Includes
|
||||
target_include_directories(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
@@ -54,8 +61,13 @@ target_sources(${DUSK_BINARY_TARGET_NAME}
|
||||
)
|
||||
|
||||
# Subdirs
|
||||
add_subdirectory(animation)
|
||||
add_subdirectory(event)
|
||||
add_subdirectory(assert)
|
||||
add_subdirectory(asset)
|
||||
add_subdirectory(cutscene)
|
||||
add_subdirectory(item)
|
||||
add_subdirectory(story)
|
||||
add_subdirectory(console)
|
||||
add_subdirectory(display)
|
||||
add_subdirectory(log)
|
||||
@@ -71,5 +83,7 @@ add_subdirectory(system)
|
||||
add_subdirectory(time)
|
||||
add_subdirectory(ui)
|
||||
add_subdirectory(network)
|
||||
add_subdirectory(overworld)
|
||||
add_subdirectory(save)
|
||||
add_subdirectory(util)
|
||||
add_subdirectory(thread)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Copyright (c) 2026 Dominic Masters
|
||||
#
|
||||
# This software is released under the MIT License.
|
||||
# https://opensource.org/licenses/MIT
|
||||
|
||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
easing.c
|
||||
animation.c
|
||||
)
|
||||
@@ -0,0 +1,52 @@
|
||||
// Copyright (c) 2026 Dominic Masters
|
||||
//
|
||||
// This software is released under the MIT License.
|
||||
// https://opensource.org/licenses/MIT
|
||||
|
||||
#include "animation.h"
|
||||
#include "assert/assert.h"
|
||||
#include "util/memory.h"
|
||||
#include "util/math.h"
|
||||
|
||||
void animationInit(
|
||||
animation_t *anim,
|
||||
keyframe_t *keyframes,
|
||||
uint16_t keyframeCount
|
||||
) {
|
||||
assertNotNull(anim, "Animation pointer cannot be null.");
|
||||
assertNotNull(keyframes, "Keyframes pointer cannot be null.");
|
||||
assertTrue(keyframeCount > 0, "Keyframe count must be more than 0.");
|
||||
|
||||
anim->keyframes = keyframes;
|
||||
anim->keyframeCount = keyframeCount;
|
||||
}
|
||||
|
||||
float_t animationGetValue(animation_t *anim, const float_t time) {
|
||||
assertNotNull(anim, "Animation pointer cannot be null.");
|
||||
assertNotNull(anim->keyframes, "Keyframes pointer cannot be null.");
|
||||
assertTrue(anim->keyframeCount > 0, "Keyframe count invalid.");
|
||||
assertTrue(time >= 0, "Time must be non-negative.");
|
||||
|
||||
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++;
|
||||
|
||||
if(current > last) {
|
||||
end = start;
|
||||
break;
|
||||
}
|
||||
} while(true);
|
||||
|
||||
float_t t = (time - start->time) / (end->time - start->time);
|
||||
return mathLerp(start->value, end->value, easingApply(start->easing, t));
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Copyright (c) 2026 Dominic Masters
|
||||
//
|
||||
// This software is released under the MIT License.
|
||||
// https://opensource.org/licenses/MIT
|
||||
|
||||
#pragma once
|
||||
#include "keyframe.h"
|
||||
|
||||
typedef struct {
|
||||
keyframe_t *keyframes;
|
||||
uint16_t keyframeCount;
|
||||
} animation_t;
|
||||
|
||||
/**
|
||||
* Initializes an 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 keyframeCount
|
||||
);
|
||||
|
||||
/**
|
||||
* Gets the value of the animation at a given time.
|
||||
*
|
||||
* @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.
|
||||
*/
|
||||
float_t animationGetValue(animation_t *anim, const float_t time);
|
||||
@@ -0,0 +1,111 @@
|
||||
// Copyright (c) 2026 Dominic Masters
|
||||
//
|
||||
// This software is released under the MIT License.
|
||||
// https://opensource.org/licenses/MIT
|
||||
|
||||
#include "easing.h"
|
||||
#include "assert/assert.h"
|
||||
#include "util/math.h"
|
||||
|
||||
const easingfn_t EASING_FUNCTIONS[EASING_COUNT] = {
|
||||
easingLinear,
|
||||
easingInSine,
|
||||
easingOutSine,
|
||||
easingInOutSine,
|
||||
easingInQuad,
|
||||
easingOutQuad,
|
||||
easingInOutQuad,
|
||||
easingInCubic,
|
||||
easingOutCubic,
|
||||
easingInOutCubic,
|
||||
easingInQuart,
|
||||
easingOutQuart,
|
||||
easingInOutQuart,
|
||||
easingInBack,
|
||||
easingOutBack,
|
||||
easingInOutBack,
|
||||
};
|
||||
|
||||
float_t easingApply(const easingtype_t type, const float_t t) {
|
||||
assertTrue(type < EASING_COUNT, "Invalid easing type");
|
||||
return EASING_FUNCTIONS[type](t);
|
||||
}
|
||||
|
||||
float_t easingLinear(const float_t t) {
|
||||
return t;
|
||||
}
|
||||
|
||||
float_t easingInSine(const float_t t) {
|
||||
return 1.0f - cosf(t * MATH_PI * 0.5f);
|
||||
}
|
||||
|
||||
float_t easingOutSine(const float_t t) {
|
||||
return sinf(t * MATH_PI * 0.5f);
|
||||
}
|
||||
|
||||
float_t easingInOutSine(const float_t t) {
|
||||
return -(cosf(MATH_PI * t) - 1.0f) * 0.5f;
|
||||
}
|
||||
|
||||
float_t easingInQuad(const float_t t) {
|
||||
return t * t;
|
||||
}
|
||||
|
||||
float_t easingOutQuad(const float_t t) {
|
||||
float_t u = 1.0f - t;
|
||||
return 1.0f - u * u;
|
||||
}
|
||||
|
||||
float_t easingInOutQuad(const float_t t) {
|
||||
if(t < 0.5f) return 2.0f * t * t;
|
||||
float_t u = -2.0f * t + 2.0f;
|
||||
return 1.0f - u * u * 0.5f;
|
||||
}
|
||||
|
||||
float_t easingInCubic(const float_t t) {
|
||||
return t * t * t;
|
||||
}
|
||||
|
||||
float_t easingOutCubic(const float_t t) {
|
||||
float_t u = 1.0f - t;
|
||||
return 1.0f - u * u * u;
|
||||
}
|
||||
|
||||
float_t easingInOutCubic(const float_t t) {
|
||||
if(t < 0.5f) return 4.0f * t * t * t;
|
||||
float_t u = -2.0f * t + 2.0f;
|
||||
return 1.0f - u * u * u * 0.5f;
|
||||
}
|
||||
|
||||
float_t easingInQuart(const float_t t) {
|
||||
return t * t * t * t;
|
||||
}
|
||||
|
||||
float_t easingOutQuart(const float_t t) {
|
||||
float_t u = 1.0f - t;
|
||||
return 1.0f - u * u * u * u;
|
||||
}
|
||||
|
||||
float_t easingInOutQuart(const float_t t) {
|
||||
if(t < 0.5f) return 8.0f * t * t * t * t;
|
||||
float_t u = -2.0f * t + 2.0f;
|
||||
return 1.0f - u * u * u * u * 0.5f;
|
||||
}
|
||||
|
||||
float_t easingInBack(const float_t t) {
|
||||
return EASING_C3 * t * t * t - EASING_C1 * t * t;
|
||||
}
|
||||
|
||||
float_t easingOutBack(const float_t t) {
|
||||
float_t u = t - 1.0f;
|
||||
return 1.0f + EASING_C3 * u * u * u + EASING_C1 * u * u;
|
||||
}
|
||||
|
||||
float_t easingInOutBack(const float_t t) {
|
||||
if(t < 0.5f) {
|
||||
float_t u = 2.0f * t;
|
||||
return u * u * ((EASING_C2 + 1.0f) * u - EASING_C2) * 0.5f;
|
||||
}
|
||||
float_t u = 2.0f * t - 2.0f;
|
||||
return (u * u * ((EASING_C2 + 1.0f) * u + EASING_C2) + 2.0f) * 0.5f;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Copyright (c) 2026 Dominic Masters
|
||||
//
|
||||
// This software is released under the MIT License.
|
||||
// https://opensource.org/licenses/MIT
|
||||
|
||||
#pragma once
|
||||
#include "dusk.h"
|
||||
|
||||
#define EASING_PI 3.14159265358979323846f
|
||||
#define EASING_C1 1.70158f
|
||||
#define EASING_C2 (EASING_C1 * 1.525f)
|
||||
#define EASING_C3 (EASING_C1 + 1.0f)
|
||||
|
||||
typedef enum {
|
||||
EASING_LINEAR,
|
||||
EASING_IN_SINE,
|
||||
EASING_OUT_SINE,
|
||||
EASING_IN_OUT_SINE,
|
||||
EASING_IN_QUAD,
|
||||
EASING_OUT_QUAD,
|
||||
EASING_IN_OUT_QUAD,
|
||||
EASING_IN_CUBIC,
|
||||
EASING_OUT_CUBIC,
|
||||
EASING_IN_OUT_CUBIC,
|
||||
EASING_IN_QUART,
|
||||
EASING_OUT_QUART,
|
||||
EASING_IN_OUT_QUART,
|
||||
EASING_IN_BACK,
|
||||
EASING_OUT_BACK,
|
||||
EASING_IN_OUT_BACK,
|
||||
|
||||
EASING_COUNT
|
||||
} easingtype_t;
|
||||
|
||||
typedef float_t (*easingfn_t)(const float_t t);
|
||||
|
||||
extern const easingfn_t EASING_FUNCTIONS[EASING_COUNT];
|
||||
|
||||
/**
|
||||
* Applies the specified easing function to t.
|
||||
*
|
||||
* @param type The easing type to apply.
|
||||
* @param t The input time, in the range [0, 1].
|
||||
* @return The eased value, in the range [0, 1].
|
||||
*/
|
||||
float_t easingApply(const easingtype_t type, const float_t t);
|
||||
|
||||
float_t easingLinear(const float_t t);
|
||||
float_t easingInSine(const float_t t);
|
||||
float_t easingOutSine(const float_t t);
|
||||
float_t easingInOutSine(const float_t t);
|
||||
float_t easingInQuad(const float_t t);
|
||||
float_t easingOutQuad(const float_t t);
|
||||
float_t easingInOutQuad(const float_t t);
|
||||
float_t easingInCubic(const float_t t);
|
||||
float_t easingOutCubic(const float_t t);
|
||||
float_t easingInOutCubic(const float_t t);
|
||||
float_t easingInQuart(const float_t t);
|
||||
float_t easingOutQuart(const float_t t);
|
||||
float_t easingInOutQuart(const float_t t);
|
||||
float_t easingInBack(const float_t t);
|
||||
float_t easingOutBack(const float_t t);
|
||||
float_t easingInOutBack(const float_t t);
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright (c) 2026 Dominic Masters
|
||||
//
|
||||
// This software is released under the MIT License.
|
||||
// https://opensource.org/licenses/MIT
|
||||
|
||||
#pragma once
|
||||
#include "easing.h"
|
||||
|
||||
typedef struct {
|
||||
float_t time;
|
||||
float_t value;
|
||||
easingtype_t easing;
|
||||
} keyframe_t;
|
||||
@@ -8,8 +8,19 @@
|
||||
#include "assert.h"
|
||||
#include "log/log.h"
|
||||
#include "util/string.h"
|
||||
#include "util/memory.h"
|
||||
|
||||
#ifdef DUSK_THREAD_PTHREAD
|
||||
pthread_t ASSERT_MAIN_THREAD_ID = 0;
|
||||
#endif
|
||||
|
||||
#ifndef DUSK_ASSERTIONS_FAKED
|
||||
void assertInit(void) {
|
||||
#ifdef DUSK_THREAD_PTHREAD
|
||||
ASSERT_MAIN_THREAD_ID = pthread_self();
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef DUSK_TEST_ASSERT
|
||||
void assertTrueImpl(
|
||||
const char *file,
|
||||
@@ -25,6 +36,25 @@
|
||||
);
|
||||
}
|
||||
#else
|
||||
#ifdef DUSK_BACKTRACE
|
||||
#include <execinfo.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
static void assertLogBacktrace(void) {
|
||||
void *frames[64];
|
||||
int count = backtrace(frames, 64);
|
||||
char **symbols = backtrace_symbols(frames, count);
|
||||
memoryTrack(symbols);
|
||||
logError("Stack trace:\n");
|
||||
if(symbols) {
|
||||
for(int i = 0; i < count; i++) {
|
||||
logError(" %s\n", symbols[i]);
|
||||
}
|
||||
memoryFree(symbols);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void assertTrueImpl(
|
||||
const char *file,
|
||||
const int32_t line,
|
||||
@@ -33,11 +63,14 @@
|
||||
) {
|
||||
if(x != true) {
|
||||
logError(
|
||||
"Assertion Failed in %s:%i\n\n%s\n",
|
||||
"Assertion Failed in %s:%i\n\n%s\n\n",
|
||||
file,
|
||||
line,
|
||||
message
|
||||
);
|
||||
#ifdef DUSK_BACKTRACE
|
||||
assertLogBacktrace();
|
||||
#endif
|
||||
abort();
|
||||
}
|
||||
}
|
||||
@@ -109,4 +142,29 @@
|
||||
) {
|
||||
assertTrueImpl(file, line, stringCompare(a, b) == 0, message);
|
||||
}
|
||||
#endif
|
||||
|
||||
void assertIsMainThreadImpl(
|
||||
const char *file,
|
||||
const int32_t line,
|
||||
const char *message
|
||||
) {
|
||||
#ifdef DUSK_THREAD_PTHREAD
|
||||
assertTrueImpl(
|
||||
file, line, pthread_self() == ASSERT_MAIN_THREAD_ID, message
|
||||
);
|
||||
#endif
|
||||
}
|
||||
|
||||
void assertNotMainThreadImpl(
|
||||
const char *file,
|
||||
const int32_t line,
|
||||
const char *message
|
||||
) {
|
||||
#ifdef DUSK_THREAD_PTHREAD
|
||||
assertTrueImpl(
|
||||
file, line, pthread_self() != ASSERT_MAIN_THREAD_ID, message
|
||||
);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -16,7 +16,18 @@
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef DUSK_THREAD_PTHREAD
|
||||
#include "thread/thread.h"
|
||||
extern pthread_t ASSERT_MAIN_THREAD_ID;
|
||||
#endif
|
||||
|
||||
#ifndef DUSK_ASSERTIONS_FAKED
|
||||
/**
|
||||
* Initializes the assert system. Must be the very first call in engine
|
||||
* startup.
|
||||
*/
|
||||
void assertInit(void);
|
||||
|
||||
/**
|
||||
* Assert a given value to be true.
|
||||
*
|
||||
@@ -121,6 +132,28 @@
|
||||
const char *message
|
||||
);
|
||||
|
||||
/**
|
||||
* Asserts that the current thread is the main thread.
|
||||
*
|
||||
* @param message Message to throw against assertion failure.
|
||||
*/
|
||||
void assertIsMainThreadImpl(
|
||||
const char *file,
|
||||
const int32_t line,
|
||||
const char *message
|
||||
);
|
||||
|
||||
/**
|
||||
* Asserts that the current thread is NOT the main thread.
|
||||
*
|
||||
* @param message Message to throw against assertion failure.
|
||||
*/
|
||||
void assertNotMainThreadImpl(
|
||||
const char *file,
|
||||
const int32_t line,
|
||||
const char *message
|
||||
);
|
||||
|
||||
/**
|
||||
* Asserts a given value to be true.
|
||||
*
|
||||
@@ -205,8 +238,28 @@
|
||||
#define assertStringEqual(a, b, message) \
|
||||
assertStringEqualImpl(__FILE__, __LINE__, a, b, message)
|
||||
|
||||
/**
|
||||
* Asserts that the current thread is the main thread.
|
||||
*
|
||||
* @param message Message to throw against assertion failure.
|
||||
*/
|
||||
#define assertIsMainThread(message) \
|
||||
assertIsMainThreadImpl(__FILE__, __LINE__, message)
|
||||
|
||||
/**
|
||||
* Asserts that the current thread is NOT the main thread.
|
||||
*
|
||||
* @param message Message to throw against assertion failure.
|
||||
*/
|
||||
#define assertNotMainThread(message) \
|
||||
assertNotMainThreadImpl(__FILE__, __LINE__, message)
|
||||
|
||||
#else
|
||||
// If assertions are faked, we define the macros to do nothing.
|
||||
#define assertInit() ((void)0)
|
||||
#define assertMainThreadInit() ((void)0)
|
||||
#define assertIsMainThread(message) ((void)0)
|
||||
#define assertNotMainThread(message) ((void)0)
|
||||
#define assertTrue(x, message) ((void)0)
|
||||
#define assertFalse(x, message) ((void)0)
|
||||
#define assertUnreachable(message) ((void)0)
|
||||
@@ -215,9 +268,13 @@
|
||||
#define assertDeprecated(message) ((void)0)
|
||||
#define assertStrLenMax(str, len, message) ((void)0)
|
||||
#define assertStrLenMin(str, len, message) ((void)0)
|
||||
#define assertStringEqual(a, b, message) ((void)0)
|
||||
#define assertIsMainThread(message) ((void)0)
|
||||
#define assertNotMainThread(message) ((void)0)
|
||||
|
||||
#endif
|
||||
|
||||
// Static Assertions
|
||||
#define assertStructSize(struct, size) \
|
||||
_Static_assert(sizeof(struct) == size, "Size of " #struct " must be " #size)
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
asset.c
|
||||
assetbatch.c
|
||||
assetfile.c
|
||||
)
|
||||
|
||||
|
||||
+400
-15
@@ -11,52 +11,437 @@
|
||||
#include "assert/assert.h"
|
||||
#include "engine/engine.h"
|
||||
#include "util/string.h"
|
||||
#include "console/console.h"
|
||||
#include <unistd.h>
|
||||
|
||||
asset_t ASSET;
|
||||
|
||||
errorret_t assetInit(void) {
|
||||
memoryZero(&ASSET, sizeof(asset_t));
|
||||
|
||||
|
||||
for(size_t i = 0; i < ASSET_LOADING_COUNT_MAX; i++) {
|
||||
threadMutexInit(&ASSET.loading[i].mutex);
|
||||
}
|
||||
|
||||
// assetInitPlatform must either define ASSET.zip or throw an error.
|
||||
errorChain(assetInitPlatform());
|
||||
assertNotNull(ASSET.zip, "Asset zip null without error.");
|
||||
threadInit(&ASSET.loadThread, assetUpdateAsync);
|
||||
threadStart(&ASSET.loadThread);
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
bool_t assetFileExists(const char_t *filename) {
|
||||
assertStrLenMax(filename, ASSET_FILE_PATH_MAX, "Filename too long.");
|
||||
assertStrLenMax(filename, ASSET_FILE_NAME_MAX, "Filename too long.");
|
||||
|
||||
zip_int64_t idx = zip_name_locate(ASSET.zip, filename, 0);
|
||||
if(idx < 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
errorret_t assetLoad(
|
||||
const char_t *filename,
|
||||
assetfileloader_t loader,
|
||||
void *params,
|
||||
void *output
|
||||
assetentry_t * assetGetEntry(
|
||||
const char_t *name,
|
||||
const assetloadertype_t type,
|
||||
assetloaderinput_t *input
|
||||
) {
|
||||
assertStrLenMax(filename, ASSET_FILE_PATH_MAX, "Filename too long.");
|
||||
assertNotNull(output, "Output pointer cannot be NULL.");
|
||||
assertNotNull(loader, "Asset file loader cannot be NULL.");
|
||||
// Is there an existing asset?
|
||||
assetentry_t *entry = ASSET.entries;
|
||||
do {
|
||||
if(entry->type == ASSET_LOADER_TYPE_NULL) {
|
||||
entry++;
|
||||
continue;
|
||||
}
|
||||
if(stringEquals(entry->name, name)) {
|
||||
assertTrue(entry->type == type, "Asset entry type mismatch.");
|
||||
return entry;
|
||||
}
|
||||
entry++;
|
||||
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||
|
||||
// We did not find one existing, Find first available slot.
|
||||
entry = ASSET.entries;
|
||||
do {
|
||||
if(entry->type != ASSET_LOADER_TYPE_NULL) {
|
||||
entry++;
|
||||
continue;
|
||||
}
|
||||
|
||||
assetfile_t file;
|
||||
errorChain(assetFileInit(&file, filename, params, output));
|
||||
errorChain(loader(&file));
|
||||
errorChain(assetFileDispose(&file));
|
||||
if(entry->state == ASSET_ENTRY_STATE_NOT_STARTED) {
|
||||
assetEntryInit(entry, name, type, input);
|
||||
return entry;
|
||||
}
|
||||
entry++;
|
||||
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||
|
||||
assertUnreachable("No available asset entry slots.");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
uint32_t assetGetEntriesOfType(
|
||||
assetentry_t **outEntries,
|
||||
const assetloadertype_t type
|
||||
) {
|
||||
assertNotNull(outEntries, "Output entries cannot be NULL.");
|
||||
|
||||
uint32_t count = 0;
|
||||
assetentry_t *entry = ASSET.entries;
|
||||
do {
|
||||
if(entry->type == type) {
|
||||
outEntries[count++] = entry;
|
||||
}
|
||||
entry++;
|
||||
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
errorret_t assetRequireLoaded(assetentry_t *entry) {
|
||||
assertNotNull(entry, "Entry cannot be NULL.");
|
||||
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
|
||||
assertIsMainThread("Currently only works on main thread.");
|
||||
|
||||
if(entry->state == ASSET_ENTRY_STATE_LOADED) {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
// Lock to prevent the reaper from collecting the entry mid-spin.
|
||||
assetEntryLock(entry);
|
||||
|
||||
while(entry->state != ASSET_ENTRY_STATE_LOADED) {
|
||||
usleep(1000);
|
||||
errorret_t ret = assetUpdate();
|
||||
if(errorIsNotOk(ret)) {
|
||||
assetEntryUnlock(entry);
|
||||
errorChain(ret);
|
||||
}
|
||||
}
|
||||
|
||||
assetEntryUnlock(entry);
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetRequireDisposed(assetentry_t *entry) {
|
||||
assertNotNull(entry, "Entry cannot be NULL.");
|
||||
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
|
||||
assertIsMainThread("Currently only works on main thread.");
|
||||
|
||||
if(entry->type == ASSET_LOADER_TYPE_NULL) {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
if(
|
||||
entry->state == ASSET_ENTRY_STATE_NOT_STARTED ||
|
||||
entry->state == ASSET_ENTRY_STATE_ERROR
|
||||
) {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
assertTrue(
|
||||
entry->refs.count == 0,
|
||||
"Cannot require disposal of an entry with active references."
|
||||
);
|
||||
|
||||
// Lock to prevent the reaper from collecting the entry mid-spin.
|
||||
assetEntryLock(entry);
|
||||
|
||||
while(entry->type != ASSET_LOADER_TYPE_NULL) {
|
||||
usleep(1000);
|
||||
errorret_t ret = assetUpdate();
|
||||
if(errorIsNotOk(ret)) {
|
||||
assetEntryUnlock(entry);
|
||||
errorChain(ret);
|
||||
}
|
||||
}
|
||||
|
||||
assetEntryUnlock(entry);
|
||||
errorOk();
|
||||
}
|
||||
|
||||
assetentry_t * assetLock(
|
||||
const char_t *name,
|
||||
const assetloadertype_t type,
|
||||
assetloaderinput_t *input
|
||||
) {
|
||||
assetentry_t *entry = assetGetEntry(name, type, input);
|
||||
assetEntryLock(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
void assetUnlock(const char_t *name) {
|
||||
assertNotNull(name, "Name cannot be NULL.");
|
||||
|
||||
assetentry_t *entry = ASSET.entries;
|
||||
do {
|
||||
if(entry->type != ASSET_LOADER_TYPE_NULL && stringEquals(entry->name, name)) {
|
||||
assetEntryUnlock(entry);
|
||||
return;
|
||||
}
|
||||
entry++;
|
||||
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||
|
||||
assertUnreachable("Asset entry not found for unlock.");
|
||||
}
|
||||
|
||||
void assetUnlockEntry(assetentry_t *entry) {
|
||||
assertNotNull(entry, "Entry cannot be NULL.");
|
||||
assetEntryUnlock(entry);
|
||||
}
|
||||
|
||||
errorret_t assetUpdate(void) {
|
||||
assertIsMainThread("assetUpdate must be called from the main thread.");
|
||||
|
||||
// Determine how many available loading slots we have.
|
||||
assetloading_t *availableLoading[ASSET_LOADING_COUNT_MAX];
|
||||
uint8_t availableLoadingCount = 0;
|
||||
assetloading_t *loading = ASSET.loading;
|
||||
assetentry_t *entry;
|
||||
|
||||
|
||||
do {
|
||||
// We only care about NULL entry references. Nothing async touches this so
|
||||
// it's fine to use raw here.
|
||||
if(loading->entry != NULL) {
|
||||
loading++;
|
||||
continue;
|
||||
}
|
||||
availableLoading[availableLoadingCount++] = loading;
|
||||
loading++;
|
||||
} while(loading < ASSET.loading + ASSET_LOADING_COUNT_MAX);
|
||||
|
||||
|
||||
// Now we can check for pending asset entries, we can't do anything if there
|
||||
// is no available slots though.
|
||||
if(availableLoadingCount > 0) {
|
||||
entry = ASSET.entries;
|
||||
do {
|
||||
// Is this asset "ready to start loading" ?
|
||||
if(entry->type == ASSET_LOADER_TYPE_NULL) {
|
||||
entry++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// We only care about assets not started.
|
||||
if(entry->state != ASSET_ENTRY_STATE_NOT_STARTED) {
|
||||
entry++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Pop a loading slot for this asset entry.
|
||||
loading = availableLoading[--availableLoadingCount];
|
||||
|
||||
// Start loading this asset.
|
||||
assetEntryStartLoading(entry, loading);
|
||||
entry++;
|
||||
|
||||
// Did we run out of loading slots?
|
||||
if(availableLoadingCount == 0) {
|
||||
break;
|
||||
}
|
||||
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||
}
|
||||
|
||||
// Now walk over all the loading slots and see what needs to be done.
|
||||
loading = ASSET.loading;
|
||||
do {
|
||||
// Is the loading slot in use? Entry can only be modified synchronously.
|
||||
if(loading->entry == NULL) {
|
||||
loading++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Lock the loading slot. This will prevent any async modifications.
|
||||
threadMutexLock(&loading->mutex);
|
||||
|
||||
// Check the state of the entry.
|
||||
switch(loading->entry->state) {
|
||||
// This thing is pending synchronous loading.
|
||||
case ASSET_ENTRY_STATE_PENDING_SYNC:
|
||||
loading->entry->state = ASSET_ENTRY_STATE_LOADING_SYNC;
|
||||
// Unlock before calling loadSync. The sync loader may re-enter
|
||||
// assetUpdate (e.g. a script loading another asset), and the async
|
||||
// thread never touches LOADING_SYNC entries, so this is safe.
|
||||
threadMutexUnlock(&loading->mutex);
|
||||
|
||||
errorret_t ret = (
|
||||
ASSET_LOADER_CALLBACKS[loading->type].loadSync(loading)
|
||||
);
|
||||
|
||||
// After a sync load, these are the only valid states.
|
||||
assertTrue(
|
||||
loading->entry->state == ASSET_ENTRY_STATE_LOADED ||
|
||||
loading->entry->state == ASSET_ENTRY_STATE_ERROR ||
|
||||
loading->entry->state == ASSET_ENTRY_STATE_PENDING_SYNC ||
|
||||
loading->entry->state == ASSET_ENTRY_STATE_PENDING_ASYNC,
|
||||
"Loader did not set entry state to loaded or error on finished load."
|
||||
);
|
||||
|
||||
if(errorIsNotOk(ret)) {
|
||||
errorCatch(errorPrint(ret));
|
||||
assertTrue(
|
||||
loading->entry->state == ASSET_ENTRY_STATE_ERROR,
|
||||
"Loader did not set entry state to error on failed load."
|
||||
);
|
||||
} else if(loading->entry->state == ASSET_ENTRY_STATE_LOADED) {
|
||||
eventInvoke(&loading->entry->onLoaded, loading->entry);
|
||||
}
|
||||
|
||||
loading++;
|
||||
break;
|
||||
|
||||
case ASSET_ENTRY_STATE_LOADING_SYNC:
|
||||
// A re-entrant assetUpdate call (e.g. from a script loading another
|
||||
// asset) will see this entry mid-sync-load. Skip it.
|
||||
threadMutexUnlock(&loading->mutex);
|
||||
loading++;
|
||||
continue;
|
||||
|
||||
// Done loading, we can just free it up.
|
||||
case ASSET_ENTRY_STATE_LOADED:
|
||||
loading->entry = NULL;
|
||||
threadMutexUnlock(&loading->mutex);
|
||||
loading++;
|
||||
break;
|
||||
|
||||
case ASSET_ENTRY_STATE_ERROR: {
|
||||
assetentry_t *errEntry = loading->entry;
|
||||
loading->entry = NULL;
|
||||
threadMutexUnlock(&loading->mutex);
|
||||
eventInvoke(&errEntry->onError, errEntry);
|
||||
errorThrow("Failed to load asset asynchronously.");
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
threadMutexUnlock(&loading->mutex);
|
||||
loading++;
|
||||
continue;
|
||||
}
|
||||
} while(loading < ASSET.loading + ASSET_LOADING_COUNT_MAX);
|
||||
|
||||
|
||||
// Reap unused entries.
|
||||
entry = ASSET.entries;
|
||||
do {
|
||||
if(entry->state != ASSET_ENTRY_STATE_LOADED) {
|
||||
entry++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if(entry->type == ASSET_LOADER_TYPE_NULL) {
|
||||
entry++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if(entry->refs.count > 0) {
|
||||
entry++;
|
||||
continue;
|
||||
}
|
||||
|
||||
consolePrint("Reaping asset %s", entry->name);
|
||||
errorChain(assetEntryDispose(entry));
|
||||
entry++;
|
||||
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
void assetUpdateAsync(thread_t *thread) {
|
||||
assertNotMainThread("assetUpdateAsync must not run on the main thread.");
|
||||
|
||||
while(!threadShouldStop(thread)) {
|
||||
// Walk over each asset
|
||||
assetloading_t *loading;
|
||||
loading = ASSET.loading;
|
||||
|
||||
do {
|
||||
threadMutexLock(&loading->mutex);
|
||||
|
||||
if(loading->entry == NULL) {
|
||||
threadMutexUnlock(&loading->mutex);
|
||||
loading++;
|
||||
continue;
|
||||
}
|
||||
|
||||
switch(loading->entry->state) {
|
||||
case ASSET_ENTRY_STATE_PENDING_ASYNC:
|
||||
loading->entry->state = ASSET_ENTRY_STATE_LOADING_ASYNC;
|
||||
assertNotNull(
|
||||
ASSET_LOADER_CALLBACKS[loading->type].loadAsync,
|
||||
"Loader does not support async loading."
|
||||
);
|
||||
errorret_t ret = (
|
||||
ASSET_LOADER_CALLBACKS[loading->type].loadAsync(loading)
|
||||
);
|
||||
|
||||
if(errorIsNotOk(ret)) {
|
||||
errorCatch(errorPrint(ret));
|
||||
assertTrue(
|
||||
loading->entry->state == ASSET_ENTRY_STATE_ERROR,
|
||||
"Loader did not set entry state to error on failed load."
|
||||
);
|
||||
}
|
||||
|
||||
threadMutexUnlock(&loading->mutex);
|
||||
loading++;
|
||||
break;
|
||||
|
||||
case ASSET_ENTRY_STATE_LOADING_ASYNC:
|
||||
assertUnreachable(
|
||||
"Entry is in a pending async state still?"
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
threadMutexUnlock(&loading->mutex);
|
||||
loading++;
|
||||
continue;
|
||||
}
|
||||
} while(loading < ASSET.loading + ASSET_LOADING_COUNT_MAX);
|
||||
|
||||
if(threadShouldStop(thread)) break;
|
||||
usleep(1000);
|
||||
}
|
||||
}
|
||||
|
||||
errorret_t assetDispose(void) {
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
threadStop(&ASSET.loadThread);
|
||||
|
||||
// Free any script read-buffers left behind by an in-flight async load
|
||||
// that was interrupted before the sync eval phase ran.
|
||||
for(size_t i = 0; i < ASSET_LOADING_COUNT_MAX; i++) {
|
||||
assetloading_t *loading = &ASSET.loading[i];
|
||||
if(
|
||||
loading->entry != NULL &&
|
||||
loading->type == ASSET_LOADER_TYPE_SCRIPT &&
|
||||
loading->loading.script.buffer != NULL
|
||||
) {
|
||||
memoryFree(loading->loading.script.buffer);
|
||||
loading->loading.script.buffer = NULL;
|
||||
}
|
||||
threadMutexDispose(&loading->mutex);
|
||||
}
|
||||
|
||||
// Dispose every non-null entry so type-specific dispose callbacks
|
||||
// (e.g. assetScriptDispose freeing jerry values) run before the
|
||||
// scripting engine is torn down.
|
||||
assetentry_t *entry = ASSET.entries;
|
||||
do {
|
||||
if(entry->type != ASSET_LOADER_TYPE_NULL) {
|
||||
errorChain(assetEntryDispose(entry));
|
||||
}
|
||||
entry++;
|
||||
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||
|
||||
// Cleanup zip file.
|
||||
if(ASSET.zip != NULL) {
|
||||
if(zip_close(ASSET.zip) != 0) {
|
||||
errorThrow("Failed to close asset zip archive.");
|
||||
}
|
||||
ASSET.zip = NULL;
|
||||
}
|
||||
|
||||
|
||||
errorChain(assetDisposePlatform());
|
||||
errorOk();
|
||||
}
|
||||
+101
-12
@@ -9,6 +9,9 @@
|
||||
#include "error/error.h"
|
||||
#include "asset/assetplatform.h"
|
||||
#include "assetfile.h"
|
||||
#include "thread/thread.h"
|
||||
#include "asset/loader/assetentry.h"
|
||||
#include "asset/loader/assetloading.h"
|
||||
|
||||
#ifndef assetInitPlatform
|
||||
#error "Platform must define assetInitPlatform function."
|
||||
@@ -20,15 +23,27 @@
|
||||
#define ASSET_FILE_NAME "dusk.dsk"
|
||||
#define ASSET_HEADER_SIZE 3
|
||||
|
||||
#define ASSET_LOADING_COUNT_MAX 4
|
||||
#define ASSET_ENTRY_COUNT_MAX 128
|
||||
|
||||
typedef struct asset_s {
|
||||
zip_t *zip;
|
||||
assetplatform_t platform;
|
||||
|
||||
// Background loading thread.
|
||||
thread_t loadThread;
|
||||
|
||||
// Assets that are mid loading.
|
||||
assetloading_t loading[ASSET_LOADING_COUNT_MAX];
|
||||
assetentry_t entries[ASSET_ENTRY_COUNT_MAX];
|
||||
} asset_t;
|
||||
|
||||
extern asset_t ASSET;
|
||||
|
||||
/**
|
||||
* Initializes the asset system.
|
||||
*
|
||||
* @return An error code if the asset system could not be initialized properly.
|
||||
*/
|
||||
errorret_t assetInit(void);
|
||||
|
||||
@@ -41,21 +56,95 @@ errorret_t assetInit(void);
|
||||
bool_t assetFileExists(const char_t *filename);
|
||||
|
||||
/**
|
||||
* Loads an asset by its filename,
|
||||
*
|
||||
* @param filename The filename of the asset to retrieve.
|
||||
* @param loader Loader to use for loading the asset file.
|
||||
* @param params Parameters to pass to the loader.
|
||||
* @param output The output pointer to store the loaded asset data.
|
||||
* @return An error code if the asset could not be loaded.
|
||||
* Gets, or creates, a new asset entry. Internal — prefer assetLock.
|
||||
*
|
||||
* @param name Filename of the asset.
|
||||
* @param type Type of the asset.
|
||||
* @param input Loader-specific parameters.
|
||||
*/
|
||||
errorret_t assetLoad(
|
||||
const char_t *filename,
|
||||
assetfileloader_t loader,
|
||||
void *params,
|
||||
void *output
|
||||
assetentry_t * assetGetEntry(
|
||||
const char_t *name,
|
||||
const assetloadertype_t type,
|
||||
assetloaderinput_t *input
|
||||
);
|
||||
|
||||
/**
|
||||
* Gets all asset entries of a given type.
|
||||
*
|
||||
* @param outEntries Output array to write the entries to.
|
||||
* @param type Type of the asset entries to get.
|
||||
* @return The number of entries written to outEntries.
|
||||
*/
|
||||
uint32_t assetGetEntriesOfType(
|
||||
assetentry_t **outEntries,
|
||||
const assetloadertype_t type
|
||||
);
|
||||
|
||||
/**
|
||||
* Gets, creates, and locks an asset entry. The asset will begin loading on
|
||||
* the next assetUpdate. Call assetUnlock when done to allow the entry to be
|
||||
* reclaimed.
|
||||
*
|
||||
* @param name Filename of the asset.
|
||||
* @param type Type of the asset.
|
||||
* @param input Loader-specific parameters.
|
||||
* @return The locked asset entry.
|
||||
*/
|
||||
assetentry_t * assetLock(
|
||||
const char_t *name,
|
||||
const assetloadertype_t type,
|
||||
assetloaderinput_t *input
|
||||
);
|
||||
|
||||
/**
|
||||
* Releases a lock on an asset entry by name. When all locks are released the
|
||||
* entry will be reclaimed at the start of the next assetUpdate.
|
||||
*
|
||||
* @param name Filename of the asset to unlock.
|
||||
*/
|
||||
void assetUnlock(const char_t *name);
|
||||
|
||||
/**
|
||||
* Releases a lock on an asset entry by pointer. When all locks are released
|
||||
* the entry will be reclaimed at the start of the next assetUpdate.
|
||||
*
|
||||
* @param entry The asset entry to unlock.
|
||||
*/
|
||||
void assetUnlockEntry(assetentry_t *entry);
|
||||
|
||||
/**
|
||||
* Requires an asset entry to be loaded. This will block until the asset entry
|
||||
* is fully loaded.
|
||||
*
|
||||
* @param entry The asset entry to require.
|
||||
* @return An error code if the asset entry could not be loaded properly.
|
||||
*/
|
||||
errorret_t assetRequireLoaded(assetentry_t *entry);
|
||||
|
||||
/**
|
||||
* Requires an asset entry to be disposed. This will block until the asset entry
|
||||
* is fully disposed.
|
||||
*
|
||||
* @param entry The asset entry to require disposal of.
|
||||
* @return An error code if the asset entry could not be disposed properly.
|
||||
*/
|
||||
errorret_t assetRequireDisposed(assetentry_t *entry);
|
||||
|
||||
/**
|
||||
* Updates the asset system.
|
||||
*
|
||||
* @return An error code if the asset system could not be updated properly.
|
||||
*/
|
||||
errorret_t assetUpdate(void);
|
||||
|
||||
/**
|
||||
* Starts the background asset loading thread. The thread runs assetUpdate
|
||||
* in a loop with a short sleep until stopped.
|
||||
*
|
||||
* @param thread The thread runner.
|
||||
*/
|
||||
void assetUpdateAsync(thread_t *thread);
|
||||
|
||||
/**
|
||||
* Disposes/cleans up the asset system.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "assetbatch.h"
|
||||
#include "asset.h"
|
||||
#include "assert/assert.h"
|
||||
#include "util/memory.h"
|
||||
#include <unistd.h>
|
||||
|
||||
/* ---- Per-entry event trampolines ----------------------------------------- */
|
||||
|
||||
static void assetBatchEntryOnLoadedCb(void *params, void *user) {
|
||||
assetentry_t *entry = (assetentry_t *)params;
|
||||
assetbatch_t *batch = (assetbatch_t *)user;
|
||||
|
||||
batch->loadedCount++;
|
||||
eventInvoke(&batch->onEntryLoaded, entry);
|
||||
|
||||
if((uint16_t)(batch->loadedCount + batch->errorCount) >= batch->count) {
|
||||
if(batch->errorCount == 0) {
|
||||
eventInvoke(&batch->onLoaded, batch);
|
||||
} else {
|
||||
eventInvoke(&batch->onError, batch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void assetBatchEntryOnErrorCb(void *params, void *user) {
|
||||
assetentry_t *entry = (assetentry_t *)params;
|
||||
assetbatch_t *batch = (assetbatch_t *)user;
|
||||
|
||||
batch->errorCount++;
|
||||
eventInvoke(&batch->onEntryError, entry);
|
||||
|
||||
if((uint16_t)(batch->loadedCount + batch->errorCount) >= batch->count) {
|
||||
eventInvoke(&batch->onError, batch);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- Public API ---------------------------------------------------------- */
|
||||
|
||||
void assetBatchInit(
|
||||
assetbatch_t *batch,
|
||||
const uint16_t count,
|
||||
const assetbatchdesc_t *descs
|
||||
) {
|
||||
assertNotNull(batch, "Batch cannot be NULL.");
|
||||
assertNotNull(descs, "Descs cannot be NULL.");
|
||||
assertTrue(count > 0, "Count must be greater than 0.");
|
||||
assertTrue(count <= ASSET_BATCH_COUNT_MAX, "Count exceeds ASSET_BATCH_COUNT_MAX.");
|
||||
|
||||
memoryZero(batch, sizeof(assetbatch_t));
|
||||
batch->count = count;
|
||||
|
||||
eventInit(
|
||||
&batch->onLoaded,
|
||||
batch->onLoadedCallbacks, batch->onLoadedUsers, ASSET_BATCH_EVENT_MAX
|
||||
);
|
||||
eventInit(
|
||||
&batch->onEntryLoaded,
|
||||
batch->onEntryLoadedCallbacks, batch->onEntryLoadedUsers, ASSET_BATCH_EVENT_MAX
|
||||
);
|
||||
eventInit(
|
||||
&batch->onError,
|
||||
batch->onErrorCallbacks, batch->onErrorUsers, ASSET_BATCH_EVENT_MAX
|
||||
);
|
||||
eventInit(
|
||||
&batch->onEntryError,
|
||||
batch->onEntryErrorCallbacks, batch->onEntryErrorUsers, ASSET_BATCH_EVENT_MAX
|
||||
);
|
||||
|
||||
for(uint16_t i = 0; i < count; i++) {
|
||||
batch->inputs[i] = descs[i].input;
|
||||
batch->entries[i] = assetLock(descs[i].path, descs[i].type, &batch->inputs[i]);
|
||||
|
||||
if(batch->entries[i]->state == ASSET_ENTRY_STATE_LOADED) {
|
||||
/* Already loaded (cached) — count it now, no subscription needed. */
|
||||
batch->loadedCount++;
|
||||
} else if(batch->entries[i]->state == ASSET_ENTRY_STATE_ERROR) {
|
||||
batch->errorCount++;
|
||||
} else {
|
||||
eventSubscribe(
|
||||
&batch->entries[i]->onLoaded, assetBatchEntryOnLoadedCb, batch
|
||||
);
|
||||
eventSubscribe(
|
||||
&batch->entries[i]->onError, assetBatchEntryOnErrorCb, batch
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void assetBatchLock(assetbatch_t *batch) {
|
||||
assertNotNull(batch, "Batch cannot be NULL.");
|
||||
for(uint16_t i = 0; i < batch->count; i++) {
|
||||
assetEntryLock(batch->entries[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void assetBatchUnlock(assetbatch_t *batch) {
|
||||
assertNotNull(batch, "Batch cannot be NULL.");
|
||||
for(uint16_t i = 0; i < batch->count; i++) {
|
||||
assetEntryUnlock(batch->entries[i]);
|
||||
}
|
||||
}
|
||||
|
||||
bool_t assetBatchIsLoaded(const assetbatch_t *batch) {
|
||||
assertNotNull(batch, "Batch cannot be NULL.");
|
||||
for(uint16_t i = 0; i < batch->count; i++) {
|
||||
if(batch->entries[i]->state != ASSET_ENTRY_STATE_LOADED) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool_t assetBatchHasError(const assetbatch_t *batch) {
|
||||
assertNotNull(batch, "Batch cannot be NULL.");
|
||||
for(uint16_t i = 0; i < batch->count; i++) {
|
||||
if(batch->entries[i]->state == ASSET_ENTRY_STATE_ERROR) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
errorret_t assetBatchRequireLoaded(assetbatch_t *batch) {
|
||||
assertNotNull(batch, "Batch cannot be NULL.");
|
||||
|
||||
bool_t allDone;
|
||||
do {
|
||||
allDone = true;
|
||||
for(uint16_t i = 0; i < batch->count; i++) {
|
||||
const assetentrystate_t state = batch->entries[i]->state;
|
||||
if(state == ASSET_ENTRY_STATE_ERROR) {
|
||||
errorThrow("Asset '%s' failed to load.", batch->entries[i]->name);
|
||||
}
|
||||
if(state != ASSET_ENTRY_STATE_LOADED) {
|
||||
allDone = false;
|
||||
}
|
||||
}
|
||||
if(!allDone) {
|
||||
usleep(1000);
|
||||
errorChain(assetUpdate());
|
||||
}
|
||||
} while(!allDone);
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
void assetBatchDispose(assetbatch_t *batch) {
|
||||
assertNotNull(batch, "Batch cannot be NULL.");
|
||||
for(uint16_t i = 0; i < batch->count; i++) {
|
||||
if(batch->entries[i]) {
|
||||
/* Unsubscribe while we still hold a lock so the entry is guaranteed live. */
|
||||
eventUnsubscribe(&batch->entries[i]->onLoaded, assetBatchEntryOnLoadedCb);
|
||||
eventUnsubscribe(&batch->entries[i]->onError, assetBatchEntryOnErrorCb);
|
||||
assetUnlockEntry(batch->entries[i]);
|
||||
}
|
||||
}
|
||||
memoryZero(batch, sizeof(assetbatch_t));
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "asset/loader/assetentry.h"
|
||||
#include "asset/loader/assetloader.h"
|
||||
#include "event/event.h"
|
||||
|
||||
#define ASSET_BATCH_COUNT_MAX 64
|
||||
#define ASSET_BATCH_EVENT_MAX 4
|
||||
|
||||
typedef struct {
|
||||
const char_t *path;
|
||||
assetloadertype_t type;
|
||||
assetloaderinput_t input;
|
||||
} assetbatchdesc_t;
|
||||
|
||||
typedef struct {
|
||||
assetentry_t *entries[ASSET_BATCH_COUNT_MAX];
|
||||
assetloaderinput_t inputs[ASSET_BATCH_COUNT_MAX];
|
||||
uint16_t count;
|
||||
uint16_t loadedCount;
|
||||
uint16_t errorCount;
|
||||
|
||||
/** Fires once when every entry has loaded successfully. params = assetbatch_t * */
|
||||
event_t onLoaded;
|
||||
eventcallback_t onLoadedCallbacks[ASSET_BATCH_EVENT_MAX];
|
||||
void *onLoadedUsers[ASSET_BATCH_EVENT_MAX];
|
||||
|
||||
/** Fires each time a single entry finishes loading. params = assetentry_t * */
|
||||
event_t onEntryLoaded;
|
||||
eventcallback_t onEntryLoadedCallbacks[ASSET_BATCH_EVENT_MAX];
|
||||
void *onEntryLoadedUsers[ASSET_BATCH_EVENT_MAX];
|
||||
|
||||
/** Fires once when all entries have finished (any with errors). params = assetbatch_t * */
|
||||
event_t onError;
|
||||
eventcallback_t onErrorCallbacks[ASSET_BATCH_EVENT_MAX];
|
||||
void *onErrorUsers[ASSET_BATCH_EVENT_MAX];
|
||||
|
||||
/** Fires each time a single entry errors. params = assetentry_t * */
|
||||
event_t onEntryError;
|
||||
eventcallback_t onEntryErrorCallbacks[ASSET_BATCH_EVENT_MAX];
|
||||
void *onEntryErrorUsers[ASSET_BATCH_EVENT_MAX];
|
||||
} assetbatch_t;
|
||||
|
||||
/**
|
||||
* Initialises the batch from an array of descriptors. Each entry is locked
|
||||
* and queued for loading immediately.
|
||||
*
|
||||
* @param batch Batch to initialise.
|
||||
* @param descs Array of entry descriptors (need not outlive this call).
|
||||
* @param count Number of descriptors (must be <= ASSET_BATCH_COUNT_MAX).
|
||||
*/
|
||||
void assetBatchInit(
|
||||
assetbatch_t *batch,
|
||||
uint16_t count,
|
||||
const assetbatchdesc_t *descs
|
||||
);
|
||||
|
||||
/**
|
||||
* Acquires one additional lock on every entry in the batch.
|
||||
*
|
||||
* @param batch Batch to lock.
|
||||
*/
|
||||
void assetBatchLock(assetbatch_t *batch);
|
||||
|
||||
/**
|
||||
* Releases one lock from every entry in the batch. When an entry's lock
|
||||
* count reaches zero it will be reaped on the next assetUpdate.
|
||||
*
|
||||
* @param batch Batch to unlock.
|
||||
*/
|
||||
void assetBatchUnlock(assetbatch_t *batch);
|
||||
|
||||
/**
|
||||
* Returns true if every entry in the batch has finished loading.
|
||||
*
|
||||
* @param batch Batch to query.
|
||||
*/
|
||||
bool_t assetBatchIsLoaded(const assetbatch_t *batch);
|
||||
|
||||
/**
|
||||
* Returns true if any entry in the batch is in an error state.
|
||||
*
|
||||
* @param batch Batch to query.
|
||||
*/
|
||||
bool_t assetBatchHasError(const assetbatch_t *batch);
|
||||
|
||||
/**
|
||||
* Blocks until every entry is loaded. Returns an error if any entry fails.
|
||||
*
|
||||
* @param batch Batch to wait on.
|
||||
*/
|
||||
errorret_t assetBatchRequireLoaded(assetbatch_t *batch);
|
||||
|
||||
/**
|
||||
* Releases the batch's lock on every entry and clears the batch. After this
|
||||
* call the batch struct may be reused with assetBatchInit.
|
||||
*
|
||||
* @param batch Batch to dispose.
|
||||
*/
|
||||
void assetBatchDispose(assetbatch_t *batch);
|
||||
@@ -16,9 +16,11 @@ errorret_t assetFileInit(
|
||||
void *params,
|
||||
void *output
|
||||
) {
|
||||
memoryZero(file, sizeof(assetfile_t));
|
||||
assertNotNull(file, "Asset file cannot be NULL.");
|
||||
assertStrLenMax(filename, ASSET_FILE_NAME_MAX, "Filename too long.");
|
||||
|
||||
file->filename = filename;
|
||||
memoryZero(file, sizeof(assetfile_t));
|
||||
memoryCopy(file->filename, filename, ASSET_FILE_NAME_MAX);
|
||||
file->params = params;
|
||||
file->output = output;
|
||||
|
||||
@@ -115,6 +117,48 @@ errorret_t assetFileDispose(assetfile_t *file) {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetFileReadEntire(
|
||||
assetfile_t *file,
|
||||
uint8_t **outBuffer,
|
||||
size_t *outSize
|
||||
) {
|
||||
assertNotNull(file, "Asset file cannot be NULL.");
|
||||
assertNotNull(outBuffer, "outBuffer cannot be NULL.");
|
||||
assertNotNull(outSize, "outSize cannot be NULL.");
|
||||
assertTrue(file->size > 0, "Asset file has no size; call assetFileInit first.");
|
||||
|
||||
// File should be closed currently.
|
||||
assertNull(file->zipFile, "Asset file must be closed before reading entire.");
|
||||
|
||||
// Open file
|
||||
errorret_t ret = assetFileOpen(file);
|
||||
if(errorIsNotOk(ret)) {
|
||||
errorChain(ret);
|
||||
}
|
||||
|
||||
// Set output.
|
||||
size_t size = (size_t)file->size;
|
||||
uint8_t *buffer = (uint8_t *)memoryAllocate(size);
|
||||
|
||||
// Read entire file.
|
||||
ret = assetFileRead(file, buffer, size);
|
||||
if(errorIsNotOk(ret)) {
|
||||
memoryFree(buffer);
|
||||
errorChain(ret);
|
||||
}
|
||||
|
||||
// Close the file.
|
||||
ret = assetFileClose(file);
|
||||
if(errorIsNotOk(ret)) {
|
||||
memoryFree(buffer);
|
||||
errorChain(ret);
|
||||
}
|
||||
|
||||
*outBuffer = buffer;
|
||||
*outSize = size;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
// Line Reader;
|
||||
void assetFileLineReaderInit(
|
||||
assetfilelinereader_t *reader,
|
||||
@@ -146,7 +190,9 @@ size_t assetFileLineReaderUnreadBytes(const assetfilelinereader_t *reader) {
|
||||
return reader->bufferEnd - reader->bufferStart;
|
||||
}
|
||||
|
||||
const uint8_t *assetFileLineReaderUnreadPtr(const assetfilelinereader_t *reader) {
|
||||
const uint8_t *assetFileLineReaderUnreadPtr(
|
||||
const assetfilelinereader_t *reader
|
||||
) {
|
||||
assertNotNull(reader, "Reader cannot be NULL.");
|
||||
assertNotNull(reader->readBuffer, "Read buffer cannot be NULL.");
|
||||
return reader->readBuffer + reader->bufferStart;
|
||||
@@ -177,11 +223,16 @@ static errorret_t assetFileLineReaderAppend(
|
||||
static void assetFileLineReaderTerminate(assetfilelinereader_t *reader) {
|
||||
assertNotNull(reader, "Reader cannot be NULL.");
|
||||
assertNotNull(reader->outBuffer, "Out buffer cannot be NULL.");
|
||||
assertTrue(reader->lineLength < reader->outBufferSize, "Line length exceeds out buffer.");
|
||||
assertTrue(
|
||||
reader->lineLength < reader->outBufferSize,
|
||||
"Line length exceeds out buffer."
|
||||
);
|
||||
reader->outBuffer[reader->lineLength] = '\0';
|
||||
}
|
||||
|
||||
static ssize_t assetFileLineReaderFindNewline(const assetfilelinereader_t *reader) {
|
||||
static ssize_t assetFileLineReaderFindNewline(
|
||||
const assetfilelinereader_t *reader
|
||||
) {
|
||||
size_t i;
|
||||
|
||||
assertNotNull(reader, "Reader cannot be NULL.");
|
||||
@@ -284,7 +335,10 @@ errorret_t assetFileLineReaderNext(assetfilelinereader_t *reader) {
|
||||
errorret_t ret;
|
||||
|
||||
/* strip CR in CRLF */
|
||||
if(chunkLength > 0 && reader->readBuffer[(size_t)newlineIndex - 1] == '\r') {
|
||||
if(
|
||||
chunkLength > 0 &&
|
||||
reader->readBuffer[(size_t)newlineIndex - 1] == '\r'
|
||||
) {
|
||||
chunkLength--;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,14 +9,15 @@
|
||||
#include "error/error.h"
|
||||
#include <zip.h>
|
||||
|
||||
#define ASSET_FILE_PATH_MAX FILENAME_MAX
|
||||
#define ASSET_FILE_NAME_MAX 48
|
||||
|
||||
typedef struct assetfile_s assetfile_t;
|
||||
|
||||
typedef errorret_t (*assetfileloader_t)(assetfile_t *file);
|
||||
|
||||
// Describes a file not yet loaded.
|
||||
typedef struct assetfile_s {
|
||||
const char_t *filename;
|
||||
char_t filename[ASSET_FILE_NAME_MAX];
|
||||
void *params;
|
||||
void *output;
|
||||
|
||||
@@ -85,12 +86,27 @@ errorret_t assetFileClose(assetfile_t *file);
|
||||
/**
|
||||
* Disposes the asset file structure, closing any open handles and zeroing
|
||||
* out the structure.
|
||||
*
|
||||
*
|
||||
* @param file The asset file to dispose.
|
||||
* @return An error code if the file could not be disposed properly.
|
||||
*/
|
||||
errorret_t assetFileDispose(assetfile_t *file);
|
||||
|
||||
/**
|
||||
* Reads the entire contents of the asset file into a newly allocated buffer.
|
||||
* The caller is responsible for freeing the buffer with memoryFree.
|
||||
*
|
||||
* @param file The asset file to read. Must be initialized but not open.
|
||||
* @param outBuffer Receives a pointer to the allocated buffer.
|
||||
* @param outSize Receives the number of bytes written to the buffer.
|
||||
* @return An error code if the file could not be read.
|
||||
*/
|
||||
errorret_t assetFileReadEntire(
|
||||
assetfile_t *file,
|
||||
uint8_t **outBuffer,
|
||||
size_t *outSize
|
||||
);
|
||||
|
||||
typedef struct {
|
||||
assetfile_t *file;
|
||||
uint8_t *readBuffer;
|
||||
|
||||
@@ -4,9 +4,15 @@
|
||||
# https://opensource.org/licenses/MIT
|
||||
|
||||
# Sources
|
||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
assetentry.c
|
||||
assetloader.c
|
||||
)
|
||||
|
||||
|
||||
# Subdirs
|
||||
add_subdirectory(display)
|
||||
add_subdirectory(locale)
|
||||
add_subdirectory(script)
|
||||
add_subdirectory(json)
|
||||
add_subdirectory(json)
|
||||
add_subdirectory(script)
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "assetentry.h"
|
||||
#include "assert/assert.h"
|
||||
#include "util/memory.h"
|
||||
#include "util/string.h"
|
||||
|
||||
void assetEntryInit(
|
||||
assetentry_t *entry,
|
||||
const char_t *name,
|
||||
const assetloadertype_t type,
|
||||
assetloaderinput_t *input
|
||||
) {
|
||||
assertNotNull(entry, "Entry cannot be NULL");
|
||||
assertStrLenMin(name, 1, "Name cannot be empty");
|
||||
assertStrLenMax(name, ASSET_FILE_NAME_MAX - 1, "Name too long");
|
||||
assertTrue(type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
|
||||
assertTrue(type < ASSET_LOADER_TYPE_COUNT, "Invalid loader type.");
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
|
||||
memoryZero(entry, sizeof(assetentry_t));
|
||||
stringCopy(entry->name, name, ASSET_FILE_NAME_MAX);
|
||||
entry->type = type;
|
||||
entry->state = ASSET_ENTRY_STATE_NOT_STARTED;
|
||||
if(input) {
|
||||
entry->inputData = *input;
|
||||
entry->input = &entry->inputData;
|
||||
} else {
|
||||
memoryZero(&entry->inputData, sizeof(assetloaderinput_t));
|
||||
entry->input = NULL;
|
||||
}
|
||||
refInit(&entry->refs, entry, NULL, NULL, NULL);
|
||||
|
||||
eventInit(
|
||||
&entry->onLoaded,
|
||||
entry->onLoadedCallbacks, entry->onLoadedUsers,
|
||||
ASSET_ENTRY_EVENT_MAX
|
||||
);
|
||||
eventInit(
|
||||
&entry->onUnloaded,
|
||||
entry->onUnloadedCallbacks, entry->onUnloadedUsers,
|
||||
ASSET_ENTRY_EVENT_MAX
|
||||
);
|
||||
eventInit(
|
||||
&entry->onError,
|
||||
entry->onErrorCallbacks, entry->onErrorUsers,
|
||||
ASSET_ENTRY_EVENT_MAX
|
||||
);
|
||||
}
|
||||
|
||||
void assetEntryLock(assetentry_t *entry) {
|
||||
assertNotNull(entry, "Entry cannot be NULL");
|
||||
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
|
||||
|
||||
refLock(&entry->refs);
|
||||
}
|
||||
|
||||
void assetEntryUnlock(assetentry_t *entry) {
|
||||
assertNotNull(entry, "Entry cannot be NULL");
|
||||
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
|
||||
|
||||
refUnlock(&entry->refs);
|
||||
}
|
||||
|
||||
void assetEntryStartLoading(
|
||||
assetentry_t *entry,
|
||||
assetloading_t *loading
|
||||
) {
|
||||
assertNotNull(entry, "Entry cannot be NULL");
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
|
||||
assertTrue(
|
||||
entry->state == ASSET_ENTRY_STATE_NOT_STARTED,
|
||||
"Can only start loading from NOT_STARTED state."
|
||||
);
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
|
||||
entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||
memoryZero(&loading->loading, sizeof(assetloaderloading_t));
|
||||
loading->type = entry->type;
|
||||
loading->entry = entry;
|
||||
// At this point the asset manager will manage this thing's loading
|
||||
}
|
||||
|
||||
errorret_t assetEntryDispose(assetentry_t *entry) {
|
||||
assertNotNull(entry, "Entry cannot be NULL");
|
||||
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
|
||||
assertTrue(entry->type < ASSET_LOADER_TYPE_COUNT, "Invalid loader type.");
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
assertTrue(
|
||||
entry->refs.count == 0,
|
||||
"Asset entry still refed at dispose time."
|
||||
);
|
||||
|
||||
eventInvoke(&entry->onUnloaded, entry);
|
||||
errorChain(ASSET_LOADER_CALLBACKS[entry->type].dispose(entry));
|
||||
memoryZero(entry, sizeof(assetentry_t));
|
||||
errorOk();
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "asset/loader/assetloading.h"
|
||||
#include "event/event.h"
|
||||
#include "util/ref.h"
|
||||
|
||||
typedef enum {
|
||||
ASSET_ENTRY_STATE_NOT_STARTED,
|
||||
ASSET_ENTRY_STATE_PENDING_ASYNC,
|
||||
ASSET_ENTRY_STATE_LOADING_ASYNC,
|
||||
ASSET_ENTRY_STATE_PENDING_SYNC,
|
||||
ASSET_ENTRY_STATE_LOADING_SYNC,
|
||||
ASSET_ENTRY_STATE_LOADED,
|
||||
ASSET_ENTRY_STATE_ERROR
|
||||
} assetentrystate_t;
|
||||
|
||||
/** Maximum number of subscribers for each per-entry event. */
|
||||
#define ASSET_ENTRY_EVENT_MAX 2
|
||||
|
||||
typedef struct assetentry_s assetentry_t;
|
||||
|
||||
struct assetentry_s {
|
||||
char_t name[ASSET_FILE_NAME_MAX];
|
||||
assetloadertype_t type;
|
||||
assetloaderoutput_t data;
|
||||
assetentrystate_t state;
|
||||
ref_t refs;
|
||||
assetloaderinput_t *input;
|
||||
assetloaderinput_t inputData;
|
||||
/**
|
||||
* Fired once when loading completes successfully (params = assetentry_t *).
|
||||
* Always invoked on the main thread.
|
||||
*/
|
||||
event_t onLoaded;
|
||||
eventcallback_t onLoadedCallbacks[ASSET_ENTRY_EVENT_MAX];
|
||||
void *onLoadedUsers[ASSET_ENTRY_EVENT_MAX];
|
||||
|
||||
/**
|
||||
* Fired once when the entry is disposed/reaped (params = assetentry_t *).
|
||||
* The asset data is still accessible when the callback runs.
|
||||
* Always invoked on the main thread.
|
||||
*/
|
||||
event_t onUnloaded;
|
||||
eventcallback_t onUnloadedCallbacks[ASSET_ENTRY_EVENT_MAX];
|
||||
void *onUnloadedUsers[ASSET_ENTRY_EVENT_MAX];
|
||||
|
||||
/**
|
||||
* Fired once when loading fails (params = assetentry_t *).
|
||||
* Always invoked on the main thread.
|
||||
*/
|
||||
event_t onError;
|
||||
eventcallback_t onErrorCallbacks[ASSET_ENTRY_EVENT_MAX];
|
||||
void *onErrorUsers[ASSET_ENTRY_EVENT_MAX];
|
||||
};
|
||||
|
||||
/**
|
||||
* Initializes an asset entry with the given name and type. This does not load
|
||||
* the asset.
|
||||
*
|
||||
* @param entry The asset entry to initialize.
|
||||
* @param name The name of the asset, used as a key for loading and caching.
|
||||
* @param type The type of asset this entry represents.
|
||||
* @param input Data that will be passed to the loader about how it should load.
|
||||
*/
|
||||
void assetEntryInit(
|
||||
assetentry_t *entry,
|
||||
const char_t *name,
|
||||
const assetloadertype_t type,
|
||||
assetloaderinput_t *input
|
||||
);
|
||||
|
||||
/**
|
||||
* Locks an asset entry, preventing it from being freed until it is unlocked.
|
||||
*
|
||||
* @param entry The asset entry to lock.
|
||||
*/
|
||||
void assetEntryLock(assetentry_t *entry);
|
||||
|
||||
/**
|
||||
* Unlocks an asset entry, allowing it to be freed if there are no more locks.
|
||||
*
|
||||
* @param entry The asset entry to unlock.
|
||||
*/
|
||||
void assetEntryUnlock(assetentry_t *entry);
|
||||
|
||||
/**
|
||||
* Starts loading the given asset entry using an assetloading slot. This will
|
||||
* be called by the asset manager when it deems it's a good time to begin the
|
||||
* loading of this asset entry.
|
||||
*
|
||||
* Currently we return the error but in future this will not be returned.
|
||||
*
|
||||
* @param entry The asset entry to start loading.
|
||||
* @param loading The assetloading slot to use for loading this asset entry.
|
||||
* @return Any error that occurs during loading.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
errorret_t assetEntryDispose(assetentry_t *entry);
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "assetloader.h"
|
||||
|
||||
assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = {
|
||||
[ASSET_LOADER_TYPE_NULL] = { 0 },
|
||||
|
||||
[ASSET_LOADER_TYPE_MESH] = {
|
||||
.loadSync = assetMeshLoaderSync,
|
||||
.loadAsync = assetMeshLoaderAsync,
|
||||
.dispose = assetMeshDispose
|
||||
},
|
||||
|
||||
[ASSET_LOADER_TYPE_TEXTURE] = {
|
||||
.loadSync = assetTextureLoaderSync,
|
||||
.loadAsync = assetTextureLoaderAsync,
|
||||
.dispose = assetTextureDispose
|
||||
},
|
||||
|
||||
[ASSET_LOADER_TYPE_TILESET] = {
|
||||
.loadSync = assetTilesetLoaderSync,
|
||||
.loadAsync = assetTilesetLoaderAsync,
|
||||
.dispose = assetTilesetDispose
|
||||
},
|
||||
|
||||
[ASSET_LOADER_TYPE_LOCALE] = {
|
||||
.loadSync = assetLocaleLoaderSync,
|
||||
.loadAsync = assetLocaleLoaderAsync,
|
||||
.dispose = assetLocaleDispose
|
||||
},
|
||||
|
||||
[ASSET_LOADER_TYPE_JSON] = {
|
||||
.loadSync = assetJsonLoaderSync,
|
||||
.loadAsync = assetJsonLoaderAsync,
|
||||
.dispose = assetJsonDispose
|
||||
},
|
||||
|
||||
[ASSET_LOADER_TYPE_SCRIPT] = {
|
||||
.loadSync = assetScriptLoaderSync,
|
||||
.loadAsync = assetScriptLoaderAsync,
|
||||
.dispose = assetScriptDispose
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "asset/loader/display/assetmeshloader.h"
|
||||
#include "asset/loader/display/assettextureloader.h"
|
||||
#include "asset/loader/display/assettilesetloader.h"
|
||||
#include "asset/loader/locale/assetlocaleloader.h"
|
||||
#include "asset/loader/json/assetjsonloader.h"
|
||||
#include "asset/loader/script/assetscriptloader.h"
|
||||
|
||||
typedef enum {
|
||||
ASSET_LOADER_TYPE_NULL,
|
||||
|
||||
ASSET_LOADER_TYPE_MESH,
|
||||
ASSET_LOADER_TYPE_TEXTURE,
|
||||
ASSET_LOADER_TYPE_TILESET,
|
||||
ASSET_LOADER_TYPE_LOCALE,
|
||||
ASSET_LOADER_TYPE_JSON,
|
||||
ASSET_LOADER_TYPE_SCRIPT,
|
||||
|
||||
ASSET_LOADER_TYPE_COUNT
|
||||
} assetloadertype_t;
|
||||
|
||||
typedef union {
|
||||
assetmeshloaderinput_t mesh;
|
||||
assettextureloaderinput_t texture;
|
||||
assettilesetloaderinput_t tileset;
|
||||
assetlocaleloaderinput_t locale;
|
||||
assetjsonloaderinput_t json;
|
||||
assetscriptloaderinput_t script;
|
||||
} assetloaderinput_t;
|
||||
|
||||
typedef union {
|
||||
assetmeshloaderloading_t mesh;
|
||||
assettextureloaderloading_t texture;
|
||||
assettilesetloaderloading_t tileset;
|
||||
assetlocaleloaderloading_t locale;
|
||||
assetjsonloaderloading_t json;
|
||||
assetscriptloaderloading_t script;
|
||||
} assetloaderloading_t;
|
||||
|
||||
typedef union {
|
||||
assetmeshoutput_t mesh;
|
||||
assettextureoutput_t texture;
|
||||
assettilesetoutput_t tileset;
|
||||
assetlocaleoutput_t locale;
|
||||
assetjsonoutput_t json;
|
||||
assetscriptoutput_t script;
|
||||
} assetloaderoutput_t;
|
||||
|
||||
typedef struct assetloading_s assetloading_t;
|
||||
typedef struct assetentry_s assetentry_t;
|
||||
|
||||
typedef errorret_t (assetloadersynccallback_t)(assetloading_t *loading);
|
||||
typedef errorret_t (assetloaderasynccallback_t)(assetloading_t *loading);
|
||||
typedef errorret_t (assetloaderdisposecallback_t)(assetentry_t *entry);
|
||||
|
||||
typedef struct {
|
||||
assetloadersynccallback_t *loadSync;
|
||||
assetloaderasynccallback_t *loadAsync;
|
||||
assetloaderdisposecallback_t *dispose;
|
||||
} assetloadercallbacks_t;
|
||||
|
||||
extern assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT];
|
||||
|
||||
/**
|
||||
* Shorthand method to both chain an error (against the loader state) and to
|
||||
* set the asset entry state to error.
|
||||
*
|
||||
* @param loading The asset loading slot.
|
||||
* @param ret The error return value to check and chain if it's an error.
|
||||
*/
|
||||
#define assetLoaderErrorChain(loading, _expr) {\
|
||||
errorret_t _alec = (_expr); \
|
||||
if(errorIsNotOk(_alec)) { \
|
||||
(loading)->entry->state = ASSET_ENTRY_STATE_ERROR; \
|
||||
errorChain(_alec); \
|
||||
} \
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorthand method to both throw an error (against the loader state) and to
|
||||
* set the asset entry state to error.
|
||||
*
|
||||
* @param loading The asset loading slot.
|
||||
* @param ... Format string and arguments for the error message.
|
||||
*/
|
||||
#define assetLoaderErrorThrow(loading, ...) {\
|
||||
loading->entry->state = ASSET_ENTRY_STATE_ERROR; \
|
||||
errorThrow(__VA_ARGS__); \
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "assetloader.h"
|
||||
#include "asset/assetfile.h"
|
||||
#include "thread/threadmutex.h"
|
||||
|
||||
typedef struct assetentry_s assetentry_t;
|
||||
|
||||
typedef struct assetloading_s {
|
||||
threadmutex_t mutex;
|
||||
assetloadertype_t type;
|
||||
assetentry_t *entry;
|
||||
assetloaderloading_t loading;
|
||||
} assetloading_t;
|
||||
|
||||
typedef errorret_t (assetloadingcallback_t)(assetloading_t *loading);
|
||||
|
||||
typedef struct {
|
||||
assetloadingcallback_t *loadSync;
|
||||
} assetloadingcallbacks_t;
|
||||
@@ -1,182 +1,174 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "asset/loader/display/assetmeshloader.h"
|
||||
#include "asset/asset.h"
|
||||
#include "assetmeshloader.h"
|
||||
#include "assert/assert.h"
|
||||
#include "util/endian.h"
|
||||
#include "util/memory.h"
|
||||
#include "asset/loader/assetloading.h"
|
||||
#include "asset/loader/assetentry.h"
|
||||
|
||||
errorret_t assetMeshLoader(assetfile_t *file) {
|
||||
assertNotNull(file, "Asset file cannot be null");
|
||||
|
||||
assetmeshoutput_t *output = (assetmeshoutput_t *)file->output;
|
||||
assertNotNull(output, "Output cannot be null");
|
||||
assertNotNull(output->outMesh, "Output mesh cannot be null");
|
||||
assertNotNull(output->outVertices, "Output vertices cannot be null");
|
||||
errorret_t assetMeshLoaderAsync(assetloading_t *loading) {
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
|
||||
// STL file loading
|
||||
errorChain(assetFileOpen(file));
|
||||
if(loading->loading.mesh.state != ASSET_MESH_LOADING_STATE_READ_FILE) {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
// Skip the 80 byte header
|
||||
errorChain(assetFileRead(file, NULL, 80));
|
||||
if(file->lastRead != 80) errorThrow("Failed to skip STL header");
|
||||
assetmeshoutput_t *out = &loading->entry->data.mesh;
|
||||
assetfile_t *file = &loading->loading.mesh.file;
|
||||
assetmeshinputaxis_t axis = loading->entry->inputData.mesh;
|
||||
|
||||
assetLoaderErrorChain(loading, assetFileInit(file, loading->entry->name, NULL, NULL));
|
||||
assetLoaderErrorChain(loading, assetFileOpen(file));
|
||||
|
||||
// Skip the 80-byte STL header.
|
||||
assetLoaderErrorChain(loading, assetFileRead(file, NULL, 80));
|
||||
if(file->lastRead != 80) {
|
||||
assetLoaderErrorThrow(loading, "Failed to skip STL header.");
|
||||
}
|
||||
|
||||
uint32_t triangleCount;
|
||||
errorChain(assetFileRead(file, &triangleCount, sizeof(uint32_t)));
|
||||
if(file->lastRead != sizeof(uint32_t)) errorThrow("Failed read tri count");
|
||||
// normalize
|
||||
assetLoaderErrorChain(loading, assetFileRead(file, &triangleCount, sizeof(uint32_t)));
|
||||
if(file->lastRead != sizeof(uint32_t)) {
|
||||
assetLoaderErrorThrow(loading, "Failed to read tri count");
|
||||
}
|
||||
triangleCount = endianLittleToHost32(triangleCount);
|
||||
|
||||
// Allocate mesh and vertex data
|
||||
errorret_t ret;
|
||||
meshvertex_t *verts = memoryAllocate(
|
||||
sizeof(meshvertex_t) * triangleCount * 3
|
||||
);
|
||||
*output->outVertices = verts;
|
||||
|
||||
// Read triangle data
|
||||
out->vertices = memoryAllocate(sizeof(meshvertex_t) * triangleCount * 3);
|
||||
meshvertex_t *verts = out->vertices;
|
||||
|
||||
errorret_t ret;
|
||||
for(uint32_t i = 0; i < triangleCount; i++) {
|
||||
assetmeshstltriangle_t triData;
|
||||
ret = assetFileRead(file, &triData, sizeof(triData));
|
||||
if(ret.code != ERROR_OK) {
|
||||
if(errorIsNotOk(ret)) {
|
||||
memoryFree(verts);
|
||||
errorChain(ret);
|
||||
out->vertices = NULL;
|
||||
assetLoaderErrorChain(loading, ret);
|
||||
}
|
||||
|
||||
if(file->lastRead != sizeof(triData)) {
|
||||
memoryFree(verts);
|
||||
errorThrow("Failed to read triangle data");
|
||||
out->vertices = NULL;
|
||||
assetLoaderErrorThrow(loading, "Failed to read triangle data");
|
||||
}
|
||||
|
||||
// Skip normals, we don't use them
|
||||
|
||||
// Fix endianess of of data
|
||||
for(uint8_t j = 0; j < 3; j++) {
|
||||
#if MESH_ENABLE_COLOR
|
||||
verts[i * 3 + j].color.r = (uint8_t)(endianLittleToHostFloat(
|
||||
triData.normal[0]
|
||||
) * 255.0f);
|
||||
verts[i * 3 + j].color.g = (uint8_t)(endianLittleToHostFloat(
|
||||
triData.normal[1]
|
||||
) * 255.0f);
|
||||
verts[i * 3 + j].color.b = (uint8_t)(endianLittleToHostFloat(
|
||||
triData.normal[2]
|
||||
) * 255.0f);
|
||||
verts[i * 3 + j].color.r = (
|
||||
(uint8_t)(endianLittleToHostFloat(triData.normal[0]) * 255.0f)
|
||||
);
|
||||
verts[i * 3 + j].color.g = (
|
||||
(uint8_t)(endianLittleToHostFloat(triData.normal[1]) * 255.0f)
|
||||
);
|
||||
verts[i * 3 + j].color.b = (
|
||||
(uint8_t)(endianLittleToHostFloat(triData.normal[2]) * 255.0f)
|
||||
);
|
||||
verts[i * 3 + j].color.a = 0xFF;
|
||||
#endif
|
||||
|
||||
verts[i * 3 + j].uv[0] = 0.0f; // No UV data in STL, just set to 0
|
||||
|
||||
verts[i * 3 + j].uv[0] = 0.0f;
|
||||
verts[i * 3 + j].uv[1] = 0.0f;
|
||||
|
||||
for(uint8_t k = 0; k < 3; k++) {
|
||||
verts[i * 3 + j].pos[k] = endianLittleToHostFloat(
|
||||
triData.positions[j][k]
|
||||
);
|
||||
verts[i * 3 + j].pos[k] = endianLittleToHostFloat(triData.positions[j][k]);
|
||||
}
|
||||
|
||||
switch(output->inputAxis) {
|
||||
case MESH_INPUT_AXIS_Z_UP:
|
||||
// Convert Z-Up to Y-Up
|
||||
{
|
||||
float_t temp = verts[i * 3 + j].pos[1];
|
||||
verts[i * 3 + j].pos[1] = verts[i * 3 + j].pos[2];
|
||||
verts[i * 3 + j].pos[2] = temp;
|
||||
}
|
||||
switch(axis) {
|
||||
case MESH_INPUT_AXIS_Z_UP: {
|
||||
float_t temp = verts[i * 3 + j].pos[1];
|
||||
verts[i * 3 + j].pos[1] = verts[i * 3 + j].pos[2];
|
||||
verts[i * 3 + j].pos[2] = temp;
|
||||
break;
|
||||
|
||||
case MESH_INPUT_AXIS_X_UP:
|
||||
// Convert X-Up to Y-Up
|
||||
{
|
||||
float_t temp = verts[i * 3 + j].pos[0];
|
||||
verts[i * 3 + j].pos[0] = verts[i * 3 + j].pos[1];
|
||||
verts[i * 3 + j].pos[1] = temp;
|
||||
}
|
||||
}
|
||||
case MESH_INPUT_AXIS_X_UP: {
|
||||
float_t temp = verts[i * 3 + j].pos[0];
|
||||
verts[i * 3 + j].pos[0] = verts[i * 3 + j].pos[1];
|
||||
verts[i * 3 + j].pos[1] = temp;
|
||||
break;
|
||||
|
||||
}
|
||||
case MESH_INPUT_AXIS_Y_DOWN:
|
||||
// Invert Y axis
|
||||
verts[i * 3 + j].pos[1] = -verts[i * 3 + j].pos[1];
|
||||
break;
|
||||
|
||||
case MESH_INPUT_AXIS_Z_DOWN:
|
||||
// Convert Z-Up to Y-Up and invert Y axis
|
||||
{
|
||||
float_t temp = verts[i * 3 + j].pos[1];
|
||||
verts[i * 3 + j].pos[1] = -verts[i * 3 + j].pos[2];
|
||||
verts[i * 3 + j].pos[2] = temp;
|
||||
}
|
||||
case MESH_INPUT_AXIS_Z_DOWN: {
|
||||
float_t temp = verts[i * 3 + j].pos[1];
|
||||
verts[i * 3 + j].pos[1] = -verts[i * 3 + j].pos[2];
|
||||
verts[i * 3 + j].pos[2] = temp;
|
||||
break;
|
||||
|
||||
case MESH_INPUT_AXIS_X_DOWN:
|
||||
// Convert X-Up to Y-Up and invert Y axis
|
||||
{
|
||||
float_t temp = verts[i * 3 + j].pos[0];
|
||||
verts[i * 3 + j].pos[0] = verts[i * 3 + j].pos[1];
|
||||
verts[i * 3 + j].pos[1] = -temp;
|
||||
}
|
||||
}
|
||||
case MESH_INPUT_AXIS_X_DOWN: {
|
||||
float_t temp = verts[i * 3 + j].pos[0];
|
||||
verts[i * 3 + j].pos[0] = verts[i * 3 + j].pos[1];
|
||||
verts[i * 3 + j].pos[1] = -temp;
|
||||
break;
|
||||
|
||||
}
|
||||
case MESH_INPUT_AXIS_Y_UP:
|
||||
default:
|
||||
// No covnersion possible / Needed
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finally, init mesh
|
||||
ret = meshInit(
|
||||
output->outMesh,
|
||||
MESH_PRIMITIVE_TYPE_TRIANGLES,
|
||||
triangleCount * 3,
|
||||
verts
|
||||
);
|
||||
if(ret.code != ERROR_OK) {
|
||||
memoryFree(verts);
|
||||
errorChain(ret);
|
||||
}
|
||||
|
||||
ret = assetFileClose(file);
|
||||
if(ret.code != ERROR_OK) {
|
||||
errorCatch(errorPrint(meshDispose(output->outMesh)));
|
||||
if(errorIsNotOk(ret)) {
|
||||
memoryFree(verts);
|
||||
errorChain(ret);
|
||||
out->vertices = NULL;
|
||||
assetLoaderErrorChain(loading, ret);
|
||||
}
|
||||
assetFileDispose(file);
|
||||
|
||||
loading->loading.mesh.triangleCount = triangleCount;
|
||||
loading->loading.mesh.state = ASSET_MESH_LOADING_STATE_CREATE_MESH;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetMeshLoadToOutput(
|
||||
const char_t *path,
|
||||
assetmeshoutput_t *output
|
||||
) {
|
||||
assertNotNull(path, "Path cannot be null");
|
||||
assertNotNull(output, "Output cannot be null");
|
||||
assertNotNull(output->outMesh, "Output mesh cannot be null");
|
||||
assertNotNull(output->outVertices, "Output vertices cannot be null");
|
||||
|
||||
return assetLoad(path, &assetMeshLoader, NULL, output);
|
||||
errorret_t assetMeshLoaderSync(assetloading_t *loading) {
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
assertTrue(loading->type == ASSET_LOADER_TYPE_MESH, "Invalid type.");
|
||||
|
||||
switch(loading->loading.mesh.state) {
|
||||
case ASSET_MESH_LOADING_STATE_INITIAL:
|
||||
loading->loading.mesh.state = ASSET_MESH_LOADING_STATE_READ_FILE;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||
errorOk();
|
||||
break;
|
||||
|
||||
case ASSET_MESH_LOADING_STATE_CREATE_MESH:
|
||||
break;
|
||||
|
||||
default:
|
||||
errorOk();
|
||||
}
|
||||
|
||||
assetmeshoutput_t *out = &loading->entry->data.mesh;
|
||||
assertNotNull(out->vertices, "Mesh vertices should have been loaded by now.");
|
||||
|
||||
errorret_t ret = meshInit(
|
||||
&out->mesh,
|
||||
MESH_PRIMITIVE_TYPE_TRIANGLES,
|
||||
loading->loading.mesh.triangleCount * 3,
|
||||
out->vertices
|
||||
);
|
||||
if(errorIsNotOk(ret)) {
|
||||
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
|
||||
memoryFree(out->vertices);
|
||||
out->vertices = NULL;
|
||||
assetLoaderErrorChain(loading, ret);
|
||||
}
|
||||
|
||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetMeshLoad(
|
||||
const char_t *path,
|
||||
mesh_t *outMesh,
|
||||
meshvertex_t **outVertices,
|
||||
const assetmeshinputaxis_t inputAxis
|
||||
) {
|
||||
assertNotNull(path, "Path cannot be null");
|
||||
assertNotNull(outMesh, "Output mesh cannot be null");
|
||||
assertNotNull(outVertices, "Output vertices cannot be null");
|
||||
|
||||
assetmeshoutput_t output = {
|
||||
outMesh,
|
||||
outVertices,
|
||||
inputAxis
|
||||
};
|
||||
return assetMeshLoadToOutput(path, &output);
|
||||
}
|
||||
errorret_t assetMeshDispose(assetentry_t *entry) {
|
||||
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||
assertTrue(entry->type == ASSET_LOADER_TYPE_MESH, "Invalid type.");
|
||||
errorChain(meshDispose(&entry->data.mesh.mesh));
|
||||
memoryFree(entry->data.mesh.vertices);
|
||||
errorOk();
|
||||
}
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "asset/asset.h"
|
||||
#include "asset/assetfile.h"
|
||||
#include "display/mesh/mesh.h"
|
||||
#include "assert/assert.h"
|
||||
|
||||
typedef struct assetloading_s assetloading_t;
|
||||
typedef struct assetentry_s assetentry_t;
|
||||
|
||||
typedef enum {
|
||||
MESH_INPUT_AXIS_Y_UP,// Default
|
||||
MESH_INPUT_AXIS_Y_UP,
|
||||
MESH_INPUT_AXIS_Z_UP,
|
||||
MESH_INPUT_AXIS_X_UP,
|
||||
|
||||
@@ -20,10 +23,24 @@ typedef enum {
|
||||
MESH_INPUT_AXIS_X_DOWN,
|
||||
} assetmeshinputaxis_t;
|
||||
|
||||
typedef assetmeshinputaxis_t assetmeshloaderinput_t;
|
||||
|
||||
typedef enum {
|
||||
ASSET_MESH_LOADING_STATE_INITIAL,
|
||||
ASSET_MESH_LOADING_STATE_READ_FILE,
|
||||
ASSET_MESH_LOADING_STATE_CREATE_MESH,
|
||||
ASSET_MESH_LOADING_STATE_DONE
|
||||
} assetmeshloadingstate_t;
|
||||
|
||||
typedef struct {
|
||||
mesh_t *outMesh;
|
||||
meshvertex_t **outVertices;
|
||||
assetmeshinputaxis_t inputAxis;
|
||||
assetfile_t file;
|
||||
assetmeshloadingstate_t state;
|
||||
uint32_t triangleCount;
|
||||
} assetmeshloaderloading_t;
|
||||
|
||||
typedef struct {
|
||||
mesh_t mesh;
|
||||
meshvertex_t *vertices;
|
||||
} assetmeshoutput_t;
|
||||
|
||||
#pragma pack(push, 1)
|
||||
@@ -36,26 +53,6 @@ typedef struct {
|
||||
|
||||
assertStructSize(assetmeshstltriangle_t, 50);
|
||||
|
||||
/**
|
||||
* Loader for mesh assets.
|
||||
*
|
||||
* @param file Asset file to load the mesh from.
|
||||
* @return Any error that occurs during loading.
|
||||
*/
|
||||
errorret_t assetMeshLoader(assetfile_t *file);
|
||||
|
||||
/**
|
||||
* Handler for mesh assets.
|
||||
*
|
||||
* @param file Asset file to load the mesh from.
|
||||
* @param outMesh Output mesh to load the data into.
|
||||
* @param outVertices Output pointer to the vertex data, used for cleanup.
|
||||
* @param inputAxis The axis orientation of the input mesh data.
|
||||
* @return Any error that occurs during loading.
|
||||
*/
|
||||
errorret_t assetMeshLoad(
|
||||
const char_t *path,
|
||||
mesh_t *outMesh,
|
||||
meshvertex_t **outVertices,
|
||||
const assetmeshinputaxis_t inputAxis
|
||||
);
|
||||
errorret_t assetMeshLoaderAsync(assetloading_t *loading);
|
||||
errorret_t assetMeshLoaderSync(assetloading_t *loading);
|
||||
errorret_t assetMeshDispose(assetentry_t *entry);
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
#include "stb_image.h"
|
||||
#include "log/log.h"
|
||||
#include "util/endian.h"
|
||||
#include "asset/loader/assetloading.h"
|
||||
#include "asset/loader/assetentry.h"
|
||||
|
||||
stbi_io_callbacks ASSET_TEXTURE_STB_CALLBACKS = {
|
||||
.read = assetTextureReader,
|
||||
@@ -25,7 +27,7 @@ int assetTextureReader(void *user, char *data, int size) {
|
||||
assertNotNull(file, "Asset file in stb_image callbacks cannot be NULL.");
|
||||
|
||||
errorret_t ret = assetFileRead(file, data, (size_t)size);
|
||||
if(ret.code != ERROR_OK) {
|
||||
if(errorIsNotOk(ret)) {
|
||||
errorCatch(errorPrint(ret));
|
||||
return -1;
|
||||
}
|
||||
@@ -38,7 +40,7 @@ void assetTextureSkipper(void *user, int n) {
|
||||
assertNotNull(file, "Asset file in stb_image callbacks cannot be NULL.");
|
||||
|
||||
errorret_t ret = assetFileRead(file, NULL, (size_t)n);
|
||||
if(ret.code != ERROR_OK) {
|
||||
if(errorIsNotOk(ret)) {
|
||||
errorCatch(errorPrint(ret));
|
||||
}
|
||||
}
|
||||
@@ -50,66 +52,118 @@ int assetTextureEOF(void *user) {
|
||||
return file->position >= file->size;
|
||||
}
|
||||
|
||||
errorret_t assetTextureLoader(assetfile_t *file) {
|
||||
assertNotNull(file, "Asset file cannot be NULL.");
|
||||
assertNotNull(file->params, "Asset file parameters cannot be NULL.");
|
||||
assertNotNull(file->output, "Asset file output cannot be NULL.");
|
||||
errorret_t assetTextureLoaderAsync(assetloading_t *loading) {
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
assertNotMainThread("Should be called from an async thread.");
|
||||
|
||||
assettextureloaderparams_t *p = (assettextureloaderparams_t*)file->params;
|
||||
assertNotNull(p, "Asset texture loader parameters cannot be NULL.");
|
||||
// Only care about loading pixels.
|
||||
if(loading->loading.texture.state != ASSET_TEXTURE_LOADING_STATE_LOAD_PIXELS){
|
||||
errorOk();
|
||||
}
|
||||
|
||||
// Init the file
|
||||
assertNull(
|
||||
loading->loading.texture.data, "Pixels already defined?"
|
||||
);
|
||||
|
||||
assetfile_t *file = &loading->loading.texture.file;
|
||||
assetLoaderErrorChain(loading, assetFileInit(
|
||||
file,
|
||||
loading->entry->name,
|
||||
NULL,
|
||||
&loading->entry->data.texture
|
||||
));
|
||||
assetLoaderErrorChain(loading, assetFileOpen(file));
|
||||
|
||||
// Determine channels
|
||||
int channelsDesired;
|
||||
switch(p->format) {
|
||||
switch(loading->entry->inputData.texture) {
|
||||
case TEXTURE_FORMAT_RGBA:
|
||||
channelsDesired = 4;
|
||||
break;
|
||||
|
||||
default:
|
||||
errorThrow("Bad texture format.");
|
||||
assetLoaderErrorThrow(loading, "Bad texture format.");
|
||||
}
|
||||
|
||||
int width, height, channels;
|
||||
errorChain(assetFileOpen(file));
|
||||
uint8_t *data = stbi_load_from_callbacks(
|
||||
// Load image pixels.
|
||||
loading->loading.texture.data = stbi_load_from_callbacks(
|
||||
&ASSET_TEXTURE_STB_CALLBACKS,
|
||||
file,
|
||||
&width,
|
||||
&height,
|
||||
&channels,
|
||||
&loading->loading.texture.width,
|
||||
&loading->loading.texture.height,
|
||||
&loading->loading.texture.channels,
|
||||
channelsDesired
|
||||
);
|
||||
errorChain(assetFileClose(file));
|
||||
|
||||
if(data == NULL) {
|
||||
// Close out the file.
|
||||
assetLoaderErrorChain(loading, assetFileClose(file));
|
||||
assetLoaderErrorChain(loading, assetFileDispose(file));
|
||||
|
||||
// Ensure we loaded correctly.
|
||||
if(loading->loading.texture.data == NULL) {
|
||||
const char_t *errorStr = stbi_failure_reason();
|
||||
errorThrow("Failed to load texture from file %s.", errorStr);
|
||||
assetLoaderErrorThrow(loading, "Failed to load texture from file %s.", errorStr);
|
||||
}
|
||||
|
||||
// Fixes a specific bug probably with Dolphin but for now just assuming endian
|
||||
if(!isHostLittleEndian()) {
|
||||
stbi__vertical_flip(data, width, height, channelsDesired);
|
||||
stbi__vertical_flip(
|
||||
loading->loading.texture.data,
|
||||
loading->loading.texture.width,
|
||||
loading->loading.texture.height,
|
||||
loading->loading.texture.channels
|
||||
);
|
||||
}
|
||||
|
||||
errorChain(textureInit(
|
||||
(texture_t*)file->output,
|
||||
(int32_t)width, (int32_t)height,
|
||||
p->format,
|
||||
(texturedata_t){
|
||||
.rgbaColors = (color_t*)data
|
||||
}
|
||||
));
|
||||
|
||||
stbi_image_free(data);
|
||||
loading->loading.texture.state = ASSET_TEXTURE_LOADING_STATE_CREATE_TEXTURE;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetTextureLoad(
|
||||
const char_t *path,
|
||||
texture_t *out,
|
||||
const textureformat_t format
|
||||
) {
|
||||
assettextureloaderparams_t params = {
|
||||
.format = format
|
||||
};
|
||||
return assetLoad(path, assetTextureLoader, ¶ms, out);
|
||||
errorret_t assetTextureLoaderSync(assetloading_t *loading) {
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
|
||||
switch(loading->loading.texture.state) {
|
||||
case ASSET_TEXTURE_LOADING_STATE_INITIAL:
|
||||
loading->loading.texture.state = ASSET_TEXTURE_LOADING_STATE_LOAD_PIXELS;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||
errorOk();
|
||||
break;
|
||||
|
||||
case ASSET_TEXTURE_LOADING_STATE_CREATE_TEXTURE:
|
||||
break;
|
||||
|
||||
default:
|
||||
errorOk();
|
||||
}
|
||||
|
||||
// Create the texture.
|
||||
assertNotNull(
|
||||
loading->loading.texture.data, "Pixels should have been loaded by now."
|
||||
);
|
||||
|
||||
assetLoaderErrorChain(loading, textureInit(
|
||||
(texture_t*)&loading->entry->data.texture,
|
||||
loading->loading.texture.width,
|
||||
loading->loading.texture.height,
|
||||
loading->entry->inputData.texture,
|
||||
(texturedata_t){
|
||||
.rgbaColors = (color_t*)loading->loading.texture.data
|
||||
}
|
||||
));
|
||||
|
||||
// Free the pixels.
|
||||
stbi_image_free(loading->loading.texture.data);
|
||||
|
||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetTextureDispose(assetentry_t *entry) {
|
||||
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
|
||||
return textureDispose(&entry->data.texture);
|
||||
}
|
||||
@@ -6,12 +6,29 @@
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "asset/asset.h"
|
||||
#include "asset/assetfile.h"
|
||||
#include "display/texture/texture.h"
|
||||
|
||||
typedef struct assetloading_s assetloading_t;
|
||||
typedef struct assetentry_s assetentry_t;
|
||||
typedef textureformat_t assettextureloaderinput_t;
|
||||
|
||||
typedef enum {
|
||||
ASSET_TEXTURE_LOADING_STATE_INITIAL,
|
||||
ASSET_TEXTURE_LOADING_STATE_LOAD_PIXELS,
|
||||
ASSET_TEXTURE_LOADING_STATE_CREATE_TEXTURE,
|
||||
ASSET_TEXTURE_LOADING_STATE_DONE
|
||||
} assettextureloadingstate_t;
|
||||
|
||||
typedef struct {
|
||||
textureformat_t format;
|
||||
} assettextureloaderparams_t;
|
||||
assetfile_t file;
|
||||
assettextureloadingstate_t state;
|
||||
|
||||
int channels, width, height;
|
||||
uint8_t *data;
|
||||
} assettextureloaderloading_t;
|
||||
|
||||
typedef texture_t assettextureoutput_t;
|
||||
|
||||
/**
|
||||
* STB image read callback for asset files.
|
||||
@@ -23,28 +40,42 @@ typedef struct {
|
||||
*/
|
||||
int assetTextureReader(void *user, char *data, int size);
|
||||
|
||||
/**
|
||||
* STB image skip callback for asset files.
|
||||
*
|
||||
* @param user User data passed to the callback, should be an assetfile_t*.
|
||||
* @param n Number of bytes to skip in the file.
|
||||
*/
|
||||
void assetTextureSkipper(void *user, int n);
|
||||
|
||||
/**
|
||||
* STB image EOF callback for asset files.
|
||||
*
|
||||
* @param user User data passed to the callback, should be an assetfile_t*.
|
||||
* @return Non-zero if end of file has been reached, zero otherwise.
|
||||
*/
|
||||
int assetTextureEOF(void *user);
|
||||
|
||||
/**
|
||||
* Handler for texture assets.
|
||||
* Synchronous loader for texture assets.
|
||||
*
|
||||
* @param file Asset file to load the texture from.
|
||||
* @return Any error that occurs during loading.
|
||||
* @param loading Loading information for the asset being loaded.
|
||||
* @return Error code indicating success or failure of the load operation.
|
||||
*/
|
||||
errorret_t assetTextureLoader(assetfile_t *file);
|
||||
errorret_t assetTextureLoaderAsync(assetloading_t *loading);
|
||||
|
||||
/**
|
||||
* Loads a texture from the specified path.
|
||||
* Synchronous loader for texture assets.
|
||||
*
|
||||
* @param path Path to the texture asset.
|
||||
* @param out Output texture to load into.
|
||||
* @param format Format of the texture to load.
|
||||
* @return Any error that occurs during loading.
|
||||
* @param loading Loading information for the asset being loaded.
|
||||
* @return Error code indicating success or failure of the load operation.
|
||||
*/
|
||||
errorret_t assetTextureLoad(
|
||||
const char_t *path,
|
||||
texture_t *out,
|
||||
const textureformat_t format
|
||||
);
|
||||
errorret_t assetTextureLoaderSync(assetloading_t *loading);
|
||||
|
||||
/**
|
||||
* Disposer for texture assets.
|
||||
*
|
||||
* @param entry Asset entry containing the texture to dispose.
|
||||
* @return Error code indicating success or failure of the dispose operation.
|
||||
*/
|
||||
errorret_t assetTextureDispose(assetentry_t *entry);
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
@@ -9,72 +9,111 @@
|
||||
#include "assert/assert.h"
|
||||
#include "util/memory.h"
|
||||
#include "util/endian.h"
|
||||
#include "asset/loader/assetloading.h"
|
||||
#include "asset/loader/assetentry.h"
|
||||
|
||||
errorret_t assetTilesetLoader(assetfile_t *file) {
|
||||
assertNotNull(file, "Asset file pointer for tileset loader is null.");
|
||||
errorret_t assetTilesetLoaderAsync(assetloading_t *loading) {
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
assertNotMainThread("Should be called from an async thread.");
|
||||
|
||||
tileset_t *out = (tileset_t *)file->output;
|
||||
assertNotNull(out, "Output pointer for tileset loader is null.");
|
||||
|
||||
uint8_t *entire = memoryAllocate(file->size);
|
||||
errorChain(assetFileOpen(file));
|
||||
errorChain(assetFileRead(file, entire, file->size));
|
||||
errorChain(assetFileClose(file));
|
||||
assertTrue(file->lastRead == file->size, "Failed to read entire file.");
|
||||
|
||||
|
||||
if(
|
||||
entire[0] != 'D' ||
|
||||
entire[1] != 'T' ||
|
||||
entire[2] != 'F'
|
||||
) {
|
||||
errorThrow("Invalid tileset header");
|
||||
if(loading->loading.tileset.state != ASSET_TILESET_LOADING_STATE_READ_FILE) {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
if(entire[3] != 0x00) {
|
||||
errorThrow("Unsupported tileset version");
|
||||
}
|
||||
assertNull(loading->loading.tileset.data, "Data already defined?");
|
||||
|
||||
// Fix endianness
|
||||
assetfile_t *file = &loading->loading.tileset.file;
|
||||
assetLoaderErrorChain(loading, assetFileInit(file, loading->entry->name, NULL, NULL));
|
||||
|
||||
out->tileWidth = endianLittleToHost16(*(uint16_t *)(entire + 4));
|
||||
out->tileHeight = endianLittleToHost16(*(uint16_t *)(entire + 6));
|
||||
out->columns = endianLittleToHost16(*(uint16_t *)(entire + 8));
|
||||
out->rows = endianLittleToHost16(*(uint16_t *)(entire + 10));
|
||||
// out->right = endianLittleToHost16(*(uint16_t *)(entire + 12));
|
||||
// out->bottom = endianLittleToHost16(*(uint16_t *)(entire + 14));
|
||||
|
||||
if(out->tileWidth == 0) {
|
||||
errorThrow("Tile width cannot be 0");
|
||||
}
|
||||
if(out->tileHeight == 0) {
|
||||
errorThrow("Tile height cannot be 0");
|
||||
}
|
||||
if(out->columns == 0) {
|
||||
errorThrow("Column count cannot be 0");
|
||||
}
|
||||
if(out->rows == 0) {
|
||||
errorThrow("Row count cannot be 0");
|
||||
}
|
||||
|
||||
out->uv[0] = endianLittleToHostFloat(*(float *)(entire + 16));
|
||||
out->uv[1] = endianLittleToHostFloat(*(float *)(entire + 20));
|
||||
|
||||
if(out->uv[1] < 0.0f || out->uv[1] > 1.0f) {
|
||||
errorThrow("Invalid v0 value in tileset");
|
||||
}
|
||||
|
||||
// Setup tileset
|
||||
out->tileCount = out->columns * out->rows;
|
||||
|
||||
memoryFree(entire);
|
||||
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));
|
||||
assertTrue(file->lastRead == file->size, "Failed to read entire tileset file.");
|
||||
|
||||
loading->loading.tileset.data = data;
|
||||
loading->loading.tileset.state = ASSET_TILESET_LOADING_STATE_PARSE;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetTilesetLoad(
|
||||
const char_t *path,
|
||||
tileset_t *out
|
||||
) {
|
||||
return assetLoad(path, assetTilesetLoader, NULL, out);
|
||||
}
|
||||
errorret_t assetTilesetLoaderSync(assetloading_t *loading) {
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
assertTrue(loading->type == ASSET_LOADER_TYPE_TILESET, "Invalid type.");
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
|
||||
switch(loading->loading.tileset.state) {
|
||||
case ASSET_TILESET_LOADING_STATE_INITIAL:
|
||||
loading->loading.tileset.state = ASSET_TILESET_LOADING_STATE_READ_FILE;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||
errorOk();
|
||||
break;
|
||||
|
||||
case ASSET_TILESET_LOADING_STATE_PARSE:
|
||||
break;
|
||||
|
||||
default:
|
||||
errorOk();
|
||||
}
|
||||
|
||||
uint8_t *data = loading->loading.tileset.data;
|
||||
assertNotNull(data, "Tileset data should have been loaded by now.");
|
||||
|
||||
tileset_t *out = &loading->entry->data.tileset;
|
||||
|
||||
if(data[0] != 'D' || data[1] != 'T' || data[2] != 'F') {
|
||||
memoryFree(data);
|
||||
assetLoaderErrorThrow(loading, "Invalid tileset header");
|
||||
}
|
||||
|
||||
if(data[3] != 0x00) {
|
||||
memoryFree(data);
|
||||
assetLoaderErrorThrow(loading, "Unsupported tileset version");
|
||||
}
|
||||
|
||||
out->tileWidth = endianLittleToHost16(*(uint16_t *)(data + 4));
|
||||
out->tileHeight = endianLittleToHost16(*(uint16_t *)(data + 6));
|
||||
out->columns = endianLittleToHost16(*(uint16_t *)(data + 8));
|
||||
out->rows = endianLittleToHost16(*(uint16_t *)(data + 10));
|
||||
|
||||
if(out->tileWidth == 0) {
|
||||
memoryFree(data);
|
||||
assetLoaderErrorThrow(loading, "Tile width cannot be 0");
|
||||
}
|
||||
if(out->tileHeight == 0) {
|
||||
memoryFree(data);
|
||||
assetLoaderErrorThrow(loading, "Tile height cannot be 0");
|
||||
}
|
||||
if(out->columns == 0) {
|
||||
memoryFree(data);
|
||||
assetLoaderErrorThrow(loading, "Column count cannot be 0");
|
||||
}
|
||||
if(out->rows == 0) {
|
||||
memoryFree(data);
|
||||
assetLoaderErrorThrow(loading, "Row count cannot be 0");
|
||||
}
|
||||
|
||||
out->uv[0] = endianLittleToHostFloat(*(float *)(data + 16));
|
||||
out->uv[1] = endianLittleToHostFloat(*(float *)(data + 20));
|
||||
|
||||
if(out->uv[1] < 0.0f || out->uv[1] > 1.0f) {
|
||||
memoryFree(data);
|
||||
assetLoaderErrorThrow(loading, "Invalid v0 value in tileset");
|
||||
}
|
||||
|
||||
out->tileCount = out->columns * out->rows;
|
||||
memoryFree(data);
|
||||
loading->loading.tileset.data = NULL;
|
||||
|
||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetTilesetDispose(assetentry_t *entry) {
|
||||
assertNotNull(entry, "Entry cannot be NULL");
|
||||
assertTrue(entry->type == ASSET_LOADER_TYPE_TILESET, "Invalid type.");
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
@@ -1,30 +1,60 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "asset/asset.h"
|
||||
#include "asset/assetfile.h"
|
||||
#include "display/texture/tileset.h"
|
||||
|
||||
/**
|
||||
* Handler for tileset assets.
|
||||
*
|
||||
* @param file Asset file to load the tileset from.
|
||||
* @return Any error that occurs during loading.
|
||||
*/
|
||||
errorret_t assetTilesetLoader(assetfile_t *file);
|
||||
typedef struct assetloading_s assetloading_t;
|
||||
typedef struct assetentry_s assetentry_t;
|
||||
|
||||
typedef struct {
|
||||
void *nothing;
|
||||
} assettilesetloaderinput_t;
|
||||
|
||||
typedef enum {
|
||||
ASSET_TILESET_LOADING_STATE_INITIAL,
|
||||
ASSET_TILESET_LOADING_STATE_READ_FILE,
|
||||
ASSET_TILESET_LOADING_STATE_PARSE,
|
||||
ASSET_TILESET_LOADING_STATE_DONE
|
||||
} assettilesetloadingstate_t;
|
||||
|
||||
typedef struct {
|
||||
assetfile_t file;
|
||||
assettilesetloadingstate_t state;
|
||||
|
||||
uint8_t *data;
|
||||
} assettilesetloaderloading_t;
|
||||
|
||||
typedef tileset_t assettilesetoutput_t;
|
||||
|
||||
/**
|
||||
* Loads a tileset from the specified path.
|
||||
*
|
||||
* @param path Path to the tileset asset.
|
||||
* @param out Output tileset to load into.
|
||||
* @return Any error that occurs during loading.
|
||||
* Asynchronous loader for tileset assets. Reads the raw DTF file bytes into
|
||||
* the loading buffer so the sync phase can parse without blocking the main
|
||||
* thread on I/O.
|
||||
*
|
||||
* @param loading Loading information for the asset being loaded.
|
||||
* @return Error code indicating success or failure of the load operation.
|
||||
*/
|
||||
errorret_t assetTilesetLoad(
|
||||
const char_t *path,
|
||||
tileset_t *out
|
||||
);
|
||||
errorret_t assetTilesetLoaderAsync(assetloading_t *loading);
|
||||
|
||||
/**
|
||||
* Synchronous loader for tileset assets. Parses the DTF binary previously
|
||||
* read by the async phase and populates the output tileset_t.
|
||||
*
|
||||
* @param loading Loading information for the asset being loaded.
|
||||
* @return Error code indicating success or failure of the load operation.
|
||||
*/
|
||||
errorret_t assetTilesetLoaderSync(assetloading_t *loading);
|
||||
|
||||
/**
|
||||
* Disposer for tileset assets.
|
||||
*
|
||||
* @param entry Asset entry containing the tileset to dispose.
|
||||
* @return Error code indicating success or failure of the dispose operation.
|
||||
*/
|
||||
errorret_t assetTilesetDispose(assetentry_t *entry);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
@@ -8,46 +8,86 @@
|
||||
#include "assetjsonloader.h"
|
||||
#include "util/memory.h"
|
||||
#include "assert/assert.h"
|
||||
#include "asset/loader/assetloading.h"
|
||||
#include "asset/loader/assetentry.h"
|
||||
|
||||
errorret_t assetJsonLoadFileToDoc(assetfile_t *file, yyjson_doc **outDoc) {
|
||||
assertNotNull(file, "Asset file pointer for JSON loader is null.");
|
||||
assertNotNull(outDoc, "Output pointer for JSON loader is null.");
|
||||
errorret_t assetJsonLoaderAsync(assetloading_t *loading) {
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
assertNotMainThread("Async loader should not be on main thread.");
|
||||
|
||||
if(file->size > ASSET_JSON_FILE_SIZE_MAX) {
|
||||
errorThrow("JSON exceeds maximum allowed size");
|
||||
if(loading->loading.json.state != ASSET_JSON_LOADING_STATE_READ_FILE) {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
// Create buffer
|
||||
uint8_t *buffer = memoryAllocate(file->size);
|
||||
assertNull(loading->loading.json.buffer, "Buffer already defined?");
|
||||
|
||||
errorChain(assetFileOpen(file));
|
||||
assetfile_t *file = &loading->loading.json.file;
|
||||
assetLoaderErrorChain(loading, assetFileInit(file, loading->entry->name, NULL, NULL));
|
||||
|
||||
// Read entire file
|
||||
errorChain(assetFileRead(file, buffer, file->size));
|
||||
if(file->size > ASSET_JSON_FILE_SIZE_MAX) {
|
||||
assetLoaderErrorThrow(loading, "JSON exceeds maximum allowed size");
|
||||
}
|
||||
|
||||
size_t fileSize = (size_t)file->size;
|
||||
uint8_t *buffer = memoryAllocate(fileSize);
|
||||
assetLoaderErrorChain(loading, assetFileOpen(file));
|
||||
assetLoaderErrorChain(loading, assetFileRead(file, buffer, fileSize));
|
||||
assertTrue(file->lastRead == file->size, "Failed to read entire JSON file.");
|
||||
assetLoaderErrorChain(loading, assetFileClose(file));
|
||||
assetLoaderErrorChain(loading, assetFileDispose(file));
|
||||
|
||||
errorChain(assetFileClose(file));
|
||||
|
||||
*outDoc = yyjson_read(
|
||||
buffer,
|
||||
file->size,
|
||||
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
|
||||
);
|
||||
memoryFree(buffer);
|
||||
|
||||
if(!*outDoc) errorThrow("Failed to parse JSON");
|
||||
loading->loading.json.buffer = buffer;
|
||||
loading->loading.json.size = fileSize;
|
||||
loading->loading.json.state = ASSET_JSON_LOADING_STATE_PARSE;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetJsonLoader(assetfile_t *file) {
|
||||
yyjson_doc **outDoc = (yyjson_doc **)file->output;
|
||||
assertNotNull(outDoc, "Output pointer for JSON loader is null.");
|
||||
return assetJsonLoadFileToDoc(file, outDoc);
|
||||
errorret_t assetJsonLoaderSync(assetloading_t *loading) {
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
assertTrue(loading->type == ASSET_LOADER_TYPE_JSON, "Invalid type.");
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
|
||||
switch(loading->loading.json.state) {
|
||||
case ASSET_JSON_LOADING_STATE_INITIAL:
|
||||
loading->loading.json.state = ASSET_JSON_LOADING_STATE_READ_FILE;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||
errorOk();
|
||||
break;
|
||||
|
||||
case ASSET_JSON_LOADING_STATE_PARSE:
|
||||
break;
|
||||
|
||||
default:
|
||||
errorOk();
|
||||
}
|
||||
|
||||
uint8_t *buffer = loading->loading.json.buffer;
|
||||
assertNotNull(buffer, "JSON buffer should have been loaded by now.");
|
||||
|
||||
loading->entry->data.json = yyjson_read(
|
||||
(char *)buffer,
|
||||
loading->loading.json.size,
|
||||
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
|
||||
);
|
||||
memoryFree(buffer);
|
||||
loading->loading.json.buffer = NULL;
|
||||
|
||||
if(!loading->entry->data.json) {
|
||||
assetLoaderErrorThrow(loading, "Failed to parse JSON");
|
||||
}
|
||||
|
||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetJsonLoad(
|
||||
const char_t *path,
|
||||
yyjson_doc **outDoc
|
||||
) {
|
||||
return assetLoad(path, assetJsonLoader, NULL, outDoc);
|
||||
}
|
||||
errorret_t assetJsonDispose(assetentry_t *entry) {
|
||||
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||
assertTrue(entry->type == ASSET_LOADER_TYPE_JSON, "Invalid type.");
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
|
||||
yyjson_doc_free(entry->data.json);
|
||||
entry->data.json = NULL;
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
@@ -1,45 +1,37 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "asset/asset.h"
|
||||
#include "asset/assetfile.h"
|
||||
#include "yyjson.h"
|
||||
|
||||
#define ASSET_JSON_FILE_SIZE_MAX 1024*256
|
||||
|
||||
typedef struct assetloading_s assetloading_t;
|
||||
typedef struct assetentry_s assetentry_t;
|
||||
|
||||
typedef struct { void *nothing; } assetjsonloaderinput_t;
|
||||
|
||||
typedef enum {
|
||||
ASSET_JSON_LOADING_STATE_INITIAL,
|
||||
ASSET_JSON_LOADING_STATE_READ_FILE,
|
||||
ASSET_JSON_LOADING_STATE_PARSE,
|
||||
ASSET_JSON_LOADING_STATE_DONE
|
||||
} assetjsonloadingstate_t;
|
||||
|
||||
typedef struct {
|
||||
void *nothing;
|
||||
} assetjsonloaderparams_t;
|
||||
assetfile_t file;
|
||||
assetjsonloadingstate_t state;
|
||||
uint8_t *buffer;
|
||||
size_t size;
|
||||
} assetjsonloaderloading_t;
|
||||
|
||||
/**
|
||||
* Loads a JSON document from the specified asset file.
|
||||
*
|
||||
* @param file Asset file to load the JSON document from.
|
||||
* @param outDoc Pointer to store the loaded JSON document.
|
||||
* @return Any error that occurs during loading.
|
||||
*/
|
||||
errorret_t assetJsonLoadFileToDoc(assetfile_t *file, yyjson_doc **outDoc);
|
||||
typedef yyjson_doc * assetjsonoutput_t;
|
||||
|
||||
/**
|
||||
* Handler for locale assets.
|
||||
*
|
||||
* @param file Asset file to load the locale from.
|
||||
* @return Any error that occurs during loading.
|
||||
*/
|
||||
errorret_t assetJsonLoader(assetfile_t *file);
|
||||
|
||||
/**
|
||||
* Loads a locale from the specified path.
|
||||
*
|
||||
* @param path Path to the locale asset.
|
||||
* @param outDoc Pointer to store the loaded JSON document.
|
||||
* @return Any error that occurs during loading.
|
||||
*/
|
||||
errorret_t assetJsonLoad(
|
||||
const char_t *path,
|
||||
yyjson_doc **outDoc
|
||||
);
|
||||
errorret_t assetJsonLoaderAsync(assetloading_t *loading);
|
||||
errorret_t assetJsonLoaderSync(assetloading_t *loading);
|
||||
errorret_t assetJsonDispose(assetentry_t *entry);
|
||||
|
||||
@@ -11,38 +11,65 @@
|
||||
#include "util/string.h"
|
||||
#include "assert/assert.h"
|
||||
|
||||
errorret_t assetLocaleFileInit(
|
||||
assetlocalefile_t *localeFile,
|
||||
const char_t *path
|
||||
) {
|
||||
assertNotNull(localeFile, "Locale file cannot be NULL.");
|
||||
assertNotNull(path, "Locale file path cannot be NULL.");
|
||||
|
||||
#include "asset/loader/assetloading.h"
|
||||
#include "asset/loader/assetentry.h"
|
||||
|
||||
errorret_t assetLocaleLoaderAsync(assetloading_t *loading) {
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
assertNotMainThread("Async loader should not be on main thread.");
|
||||
|
||||
if(loading->loading.locale.state != ASSET_LOCALE_LOADER_STATE_LOAD_HEADER) {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
assetlocalefile_t *localeFile = &loading->entry->data.locale;
|
||||
memoryZero(localeFile, sizeof(assetlocalefile_t));
|
||||
assetLoaderErrorChain(loading, assetFileInit(&localeFile->file, loading->entry->name, NULL, NULL));
|
||||
assetLoaderErrorChain(loading, assetFileOpen(&localeFile->file));
|
||||
|
||||
// Init the asset file.
|
||||
errorChain(assetFileInit(&localeFile->file, path, NULL, NULL));
|
||||
|
||||
// Open the file handle
|
||||
errorChain(assetFileOpen(&localeFile->file));
|
||||
|
||||
// Get the blank key, this is basically the header info for po files
|
||||
char_t buffer[1024];
|
||||
errorChain(assetLocaleGetString(localeFile, "", 0, buffer, sizeof(buffer)));
|
||||
errorChain(assetLocaleParseHeader(localeFile, buffer, sizeof(buffer)));
|
||||
assetLoaderErrorChain(loading, assetLocaleGetString(localeFile, "", 0, buffer, sizeof(buffer)));
|
||||
assetLoaderErrorChain(loading, assetLocaleParseHeader(localeFile, buffer, sizeof(buffer)));
|
||||
|
||||
loading->loading.locale.state = ASSET_LOCALE_LOADER_STATE_DONE;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetLocaleFileDispose(assetlocalefile_t *localeFile) {
|
||||
assertNotNull(localeFile, "Locale file cannot be NULL.");
|
||||
errorret_t assetLocaleLoaderSync(assetloading_t *loading) {
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
assertTrue(loading->type == ASSET_LOADER_TYPE_LOCALE, "Invalid type.");
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
|
||||
switch(loading->loading.locale.state) {
|
||||
case ASSET_LOCALE_LOADER_STATE_INITIAL:
|
||||
loading->loading.locale.state = ASSET_LOCALE_LOADER_STATE_LOAD_HEADER;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||
errorOk();
|
||||
break;
|
||||
|
||||
case ASSET_LOCALE_LOADER_STATE_DONE:
|
||||
break;
|
||||
|
||||
default:
|
||||
errorOk();
|
||||
}
|
||||
|
||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetLocaleDispose(assetentry_t *entry) {
|
||||
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||
assertTrue(entry->type == ASSET_LOADER_TYPE_LOCALE, "Invalid type.");
|
||||
assertIsMainThread("Must be called from the main thread.");
|
||||
|
||||
assetlocalefile_t *localeFile = &entry->data.locale;
|
||||
errorChain(assetFileClose(&localeFile->file));
|
||||
errorChain(assetFileDispose(&localeFile->file));
|
||||
|
||||
errorOk();
|
||||
return assetFileDispose(&localeFile->file);
|
||||
}
|
||||
|
||||
// These functions probably need some cleaning;
|
||||
errorret_t assetLocaleParseHeader(
|
||||
assetlocalefile_t *localeFile,
|
||||
char_t *headerBuffer,
|
||||
@@ -152,7 +179,7 @@ errorret_t assetLocaleParseHeader(
|
||||
|
||||
if(pluralIndex >= localeFile->pluralStateCount - 1) {
|
||||
errorThrow(
|
||||
"Too many plural conditions. Expected %d conditional clauses for nplurals=%d.",
|
||||
"Too many plural conditions. Expected %d clauses for nplurals=%d.",
|
||||
localeFile->pluralStateCount - 1,
|
||||
localeFile->pluralStateCount
|
||||
);
|
||||
@@ -307,16 +334,24 @@ errorret_t assetLocaleLineSkipBlanks(
|
||||
while(!reader->eof) {
|
||||
// Skip blank lines
|
||||
if(lineBuffer[0] == '\0') {
|
||||
errorChain(assetFileLineReaderNext(reader));
|
||||
errorret_t r = assetFileLineReaderNext(reader);
|
||||
if(errorIsNotOk(r)) {
|
||||
errorCatch(r);
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip comment lines
|
||||
if(lineBuffer[0] == '#') {
|
||||
errorChain(assetFileLineReaderNext(reader));
|
||||
errorret_t r = assetFileLineReaderNext(reader);
|
||||
if(errorIsNotOk(r)) {
|
||||
errorCatch(r);
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// Is line only spaces?
|
||||
size_t lineLength = strlen((char_t *)lineBuffer);
|
||||
size_t i;
|
||||
@@ -329,7 +364,11 @@ errorret_t assetLocaleLineSkipBlanks(
|
||||
}
|
||||
|
||||
if(onlySpaces) {
|
||||
errorChain(assetFileLineReaderNext(reader));
|
||||
errorret_t r = assetFileLineReaderNext(reader);
|
||||
if(errorIsNotOk(r)) {
|
||||
errorCatch(r);
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
@@ -365,10 +404,18 @@ errorret_t assetLocaleLineUnbuffer(
|
||||
|
||||
// Now start buffering lines out
|
||||
while(!reader->eof) {
|
||||
errorChain(assetFileLineReaderNext(reader));
|
||||
errorret_t r = assetFileLineReaderNext(reader);
|
||||
if(errorIsNotOk(r)) {
|
||||
errorCatch(r);
|
||||
break;
|
||||
}
|
||||
|
||||
// Skip blank lines
|
||||
errorChain(assetLocaleLineSkipBlanks(reader, lineBuffer));
|
||||
r = assetLocaleLineSkipBlanks(reader, lineBuffer);
|
||||
if(errorIsNotOk(r)) {
|
||||
errorCatch(r);
|
||||
break;
|
||||
}
|
||||
|
||||
// Skip starting spaces
|
||||
char_t *ptr = (char_t *)lineBuffer;
|
||||
@@ -593,7 +640,7 @@ errorret_t assetLocaleGetStringWithVA(
|
||||
tempBuffer,
|
||||
bufferSize
|
||||
);
|
||||
if(ret.code != ERROR_OK) {
|
||||
if(errorIsNotOk(ret)) {
|
||||
memoryFree(tempBuffer);
|
||||
return ret;
|
||||
}
|
||||
@@ -641,7 +688,7 @@ errorret_t assetLocaleGetStringWithArgs(
|
||||
format,
|
||||
bufferSize
|
||||
);
|
||||
if(ret.code != ERROR_OK) {
|
||||
if(errorIsNotOk(ret)) {
|
||||
memoryFree(format);
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,40 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "asset/asset.h"
|
||||
#include "asset/assetfile.h"
|
||||
|
||||
typedef struct assetloading_s assetloading_t;
|
||||
typedef struct assetentry_s assetentry_t;
|
||||
|
||||
/** Input passed to the locale loader — currently unused. */
|
||||
typedef struct { void *nothing; } assetlocaleloaderinput_t;
|
||||
|
||||
typedef enum {
|
||||
ASSET_LOCALE_LOADER_STATE_INITIAL,
|
||||
ASSET_LOCALE_LOADER_STATE_LOAD_HEADER,
|
||||
ASSET_LOCALE_LOADER_STATE_DONE
|
||||
} assetlocaleloaderstate_t;
|
||||
|
||||
/** Per-slot scratch data used while the locale file is loading. */
|
||||
typedef struct {
|
||||
assetlocaleloaderstate_t state;
|
||||
} assetlocaleloaderloading_t;
|
||||
|
||||
/** Maximum number of distinct plural forms a locale file may declare. */
|
||||
#define ASSET_LOCALE_FILE_PLURAL_FORM_COUNT 6
|
||||
|
||||
/**
|
||||
* Comparison operator used in a plural-form expression.
|
||||
*
|
||||
* Each condition in the plural-form header is evaluated as
|
||||
* `n <op> value`
|
||||
* where `n` is the runtime plural count.
|
||||
*/
|
||||
typedef enum {
|
||||
ASSET_LOCALE_PLURAL_OP_EQUAL,
|
||||
ASSET_LOCALE_PLURAL_OP_NOT_EQUAL,
|
||||
@@ -19,13 +44,24 @@ typedef enum {
|
||||
ASSET_LOCALE_PLURAL_OP_GREATER_EQUAL
|
||||
} assetlocalepluraloperation_t;
|
||||
|
||||
/**
|
||||
* Discriminator tag for a locale string argument.
|
||||
* @see assetlocalearg_t
|
||||
*/
|
||||
typedef enum {
|
||||
ASSET_LOCALE_ARG_STRING,
|
||||
ASSET_LOCALE_ARG_INT,
|
||||
ASSET_LOCALE_ARG_FLOAT
|
||||
} assetlocaleargtype_t;
|
||||
|
||||
/**
|
||||
* A single typed argument for locale string substitution.
|
||||
*
|
||||
* Used with @ref assetLocaleGetStringWithArgs to fill `%s`, `%d`, or `%f`
|
||||
* placeholders inside a translated string.
|
||||
*/
|
||||
typedef struct {
|
||||
/** Which union member is active. */
|
||||
assetlocaleargtype_t type;
|
||||
union {
|
||||
const char_t *stringValue;
|
||||
@@ -34,35 +70,81 @@ typedef struct {
|
||||
};
|
||||
} assetlocalearg_t;
|
||||
|
||||
/**
|
||||
* Runtime state for an open locale file.
|
||||
*
|
||||
* Loaded once by @ref assetLocaleLoaderSync and kept alive for the lifetime
|
||||
* of the asset entry. The plural-form fields are populated from the PO header
|
||||
* by @ref assetLocaleParseHeader.
|
||||
*
|
||||
* Plural evaluation works as a linear scan over `pluralStateCount - 1`
|
||||
* conditions; if none match, `pluralDefaultIndex` is returned.
|
||||
*/
|
||||
typedef struct {
|
||||
/** Underlying file handle used to rewind and re-read the PO data. */
|
||||
assetfile_t file;
|
||||
|
||||
/** Comparison operator for each conditional plural clause. */
|
||||
assetlocalepluraloperation_t pluralOps[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
|
||||
|
||||
/** Right-hand value for each conditional plural clause. */
|
||||
int32_t pluralValues[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
|
||||
|
||||
/** Form index returned when the corresponding condition is true. */
|
||||
int32_t pluralIndices[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
|
||||
|
||||
/** Total number of plural forms declared by `nplurals=`. */
|
||||
uint8_t pluralStateCount;
|
||||
|
||||
/** Form index used when no conditional clause matches. */
|
||||
uint8_t pluralDefaultIndex;
|
||||
} assetlocalefile_t;
|
||||
|
||||
/**
|
||||
* Initialize a locale asset file.
|
||||
*
|
||||
* @param localeFile The locale file to initialize.
|
||||
* @param path The path to the locale file.
|
||||
* @return An error code if a failure occurs.
|
||||
*/
|
||||
errorret_t assetLocaleFileInit(
|
||||
assetlocalefile_t *localeFile,
|
||||
const char_t *path
|
||||
);
|
||||
/** Convenience alias — the loaded output type of a locale asset entry. */
|
||||
typedef assetlocalefile_t assetlocaleoutput_t;
|
||||
|
||||
/**
|
||||
* Dispose of a locale asset file.
|
||||
*
|
||||
* @param localeFile The locale file to dispose of.
|
||||
* @return An error code if a failure occurs.
|
||||
* Asynchronous loader callback. Opens the locale file, reads the PO header,
|
||||
* and parses plural-form rules. 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 assetLocaleFileDispose(assetlocalefile_t *localeFile);
|
||||
errorret_t assetLocaleLoaderAsync(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 assetLocaleLoaderSync(assetloading_t *loading);
|
||||
|
||||
/**
|
||||
* Dispose callback. Closes the open file handle and zeros the locale data.
|
||||
*
|
||||
* @param entry The asset entry to dispose.
|
||||
* @return OK on success, error otherwise.
|
||||
*/
|
||||
errorret_t assetLocaleDispose(assetentry_t *entry);
|
||||
|
||||
/**
|
||||
* Parses the `Plural-Forms:` line from a PO header string and populates the
|
||||
* plural-form fields of `localeFile`. If no `Plural-Forms:` key is present
|
||||
* the function returns OK without modifying the struct.
|
||||
*
|
||||
* Supports the `nplurals=N; plural=(<expr>);` syntax where `<expr>` is a
|
||||
* chain of `n <op> value ? index : ...` ternary conditions ending with a
|
||||
* fallback index.
|
||||
*
|
||||
* @param localeFile Struct whose plural fields will be filled in.
|
||||
* @param headerBuffer The raw PO header string (msgstr of msgid "").
|
||||
* @param headerBufferSize Size of `headerBuffer` in bytes.
|
||||
* @return OK on success, error if the plural expression is malformed.
|
||||
*/
|
||||
errorret_t assetLocaleParseHeader(
|
||||
assetlocalefile_t *localeFile,
|
||||
char_t *headerBuffer,
|
||||
@@ -70,11 +152,29 @@ errorret_t assetLocaleParseHeader(
|
||||
);
|
||||
|
||||
/**
|
||||
* Skips blank lines and comment lines in the line reader.
|
||||
*
|
||||
* @param reader Line reader to read from.
|
||||
* @param lineBuffer Buffer to use for reading lines.
|
||||
* @return Any error that occurs during skipping.
|
||||
* Evaluates which plural form index to use for a given count.
|
||||
*
|
||||
* Walks the conditions stored in `file` in order; returns the index for the
|
||||
* first condition that matches `pluralCount`. Falls back to
|
||||
* `file->pluralDefaultIndex` if none match.
|
||||
*
|
||||
* @param file Locale file with parsed plural rules.
|
||||
* @param pluralCount The runtime count (e.g. number of items).
|
||||
* @return Zero-based plural form index.
|
||||
*/
|
||||
uint8_t assetLocaleEvaluatePlural(
|
||||
assetlocalefile_t *file,
|
||||
const int32_t pluralCount
|
||||
);
|
||||
|
||||
/**
|
||||
* Advances the line reader past blank lines, comment lines (starting with
|
||||
* `#`), and lines containing only spaces. Stops at the first content line or
|
||||
* end of file.
|
||||
*
|
||||
* @param reader Line reader positioned at the current line.
|
||||
* @param lineBuffer Output buffer that the reader writes each line into.
|
||||
* @return OK on success, error if reading fails.
|
||||
*/
|
||||
errorret_t assetLocaleLineSkipBlanks(
|
||||
assetfilelinereader_t *reader,
|
||||
@@ -82,16 +182,19 @@ errorret_t assetLocaleLineSkipBlanks(
|
||||
);
|
||||
|
||||
/**
|
||||
* Unbuffers a potentially multi-line quoted string from the line reader.
|
||||
*
|
||||
* This will read lines until it finds a line that starts with a quote, then
|
||||
* read until the closing quote.
|
||||
*
|
||||
* @param reader Line reader to read from.
|
||||
* @param lineBuffer Buffer to use for reading lines.
|
||||
* @param stringBuffer Buffer to write the unbuffered string to.
|
||||
* @param stringBufferSize Size of the string buffer.
|
||||
* @return Any error that occurs during unbuffering.
|
||||
* Reads a PO quoted string value from the current line and any immediately
|
||||
* following continuation lines that begin with `"`.
|
||||
*
|
||||
* Handles standard C escape sequences (`\n`, `\t`, `\\`, `\"`).
|
||||
*
|
||||
* @param reader Line reader positioned at the line containing the opening
|
||||
* quote (e.g. `msgstr "..."`).
|
||||
* @param lineBuffer Buffer the reader fills on each @ref assetFileLineReaderNext
|
||||
* call; also used to detect continuation lines.
|
||||
* @param stringBuffer Destination for the unescaped string content.
|
||||
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
|
||||
* @return OK on success, error if a quote or escape sequence is malformed or
|
||||
* the buffer would overflow.
|
||||
*/
|
||||
errorret_t assetLocaleLineUnbuffer(
|
||||
assetfilelinereader_t *reader,
|
||||
@@ -101,14 +204,19 @@ errorret_t assetLocaleLineUnbuffer(
|
||||
);
|
||||
|
||||
/**
|
||||
* Test function for locale asset loading.
|
||||
*
|
||||
* @param file Asset file to test loading from.
|
||||
* @param messageId The message ID to retrieve.
|
||||
* @param pluralCount Count for formulating the plural variant.
|
||||
* @param stringBuffer Buffer to write the retrieved string to.
|
||||
* @param stringBufferSize Size of the string buffer.
|
||||
* @return Any error that occurs during testing.
|
||||
* Looks up a translated string by message ID from the open locale file.
|
||||
*
|
||||
* 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 (`""` 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.
|
||||
* @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 assetLocaleGetString(
|
||||
assetlocalefile_t *file,
|
||||
@@ -119,15 +227,21 @@ errorret_t assetLocaleGetString(
|
||||
);
|
||||
|
||||
/**
|
||||
* Test function for locale asset loading with a variable argument list.
|
||||
*
|
||||
* @param file Asset file to test loading from.
|
||||
* @param messageId The message ID to retrieve.
|
||||
* @param pluralCount Count for formulating the plural variant.
|
||||
* @param buffer Buffer to write the retrieved string to.
|
||||
* @param bufferSize Size of the buffer.
|
||||
* @param ... Additional arguments for formatting the string.
|
||||
* @return Any error that occurs during testing.
|
||||
* Looks up a translated string and formats it with a `printf`-style variadic
|
||||
* argument list.
|
||||
*
|
||||
* Retrieves the raw format string via @ref assetLocaleGetString then applies
|
||||
* `vsnprintf` with the provided arguments.
|
||||
*
|
||||
* @param file Locale file to search. Must be open.
|
||||
* @param messageId PO message ID to find.
|
||||
* @param pluralCount Count used to select the plural form.
|
||||
* @param buffer Buffer to receive the formatted string.
|
||||
* @param bufferSize Capacity of `buffer` in bytes.
|
||||
* @param ... Format arguments matching the specifiers in the translated
|
||||
* string.
|
||||
* @return OK on success, error if the message is not found or formatting
|
||||
* fails.
|
||||
*/
|
||||
errorret_t assetLocaleGetStringWithVA(
|
||||
assetlocalefile_t *file,
|
||||
@@ -139,16 +253,22 @@ errorret_t assetLocaleGetStringWithVA(
|
||||
);
|
||||
|
||||
/**
|
||||
* Test function for locale asset loading with a list of arguments.
|
||||
*
|
||||
* @param file Asset file to test loading from.
|
||||
* @param messageId The message ID to retrieve.
|
||||
* @param pluralCount Count for formulating the plural variant.
|
||||
* @param buffer Buffer to write the retrieved string to.
|
||||
* @param bufferSize Size of the buffer.
|
||||
* @param args List of arguments for formatting the string.
|
||||
* @param argCount Number of arguments in the list.
|
||||
* @return Any error that occurs during testing.
|
||||
* Looks up a translated string and substitutes typed arguments into its
|
||||
* `%s`, `%d`, and `%f` placeholders.
|
||||
*
|
||||
* Unlike @ref assetLocaleGetStringWithVA this variant accepts an explicit
|
||||
* array of @ref assetlocalearg_t values, which is safer to use from
|
||||
* generated or scripted call sites.
|
||||
*
|
||||
* @param file Locale file to search. Must be open.
|
||||
* @param messageId PO message ID to find.
|
||||
* @param pluralCount Count used to select the plural form.
|
||||
* @param buffer Buffer to receive the formatted string.
|
||||
* @param bufferSize Capacity of `buffer` in bytes.
|
||||
* @param args Array of typed arguments; may be NULL when `argCount` is 0.
|
||||
* @param argCount Number of elements in `args`.
|
||||
* @return OK on success, error if the message is not found, an argument type
|
||||
* mismatches the specifier, or the buffer would overflow.
|
||||
*/
|
||||
errorret_t assetLocaleGetStringWithArgs(
|
||||
assetlocalefile_t *file,
|
||||
@@ -158,4 +278,4 @@ errorret_t assetLocaleGetStringWithArgs(
|
||||
const size_t bufferSize,
|
||||
const assetlocalearg_t *args,
|
||||
const size_t argCount
|
||||
);
|
||||
);
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
# 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
|
||||
assetscriptloader.c
|
||||
)
|
||||
)
|
||||
|
||||
@@ -6,87 +6,132 @@
|
||||
*/
|
||||
|
||||
#include "assetscriptloader.h"
|
||||
#include "asset/loader/assetloading.h"
|
||||
#include "asset/loader/assetentry.h"
|
||||
#include "asset/loader/assetloader.h"
|
||||
#include "script/module/require/modulerequire.h"
|
||||
#include "util/memory.h"
|
||||
#include "assert/assert.h"
|
||||
#include <stdlib.h>
|
||||
#include <zip.h>
|
||||
#include <jerryscript.h>
|
||||
|
||||
errorret_t assetScriptLoader(assetfile_t *file) {
|
||||
assertNotNull(file, "Asset file cannot be NULL");
|
||||
assertNull(file->zipFile, "Asset file zip handle must be NULL before open");
|
||||
assertNotNull(file->output, "Asset file output cannot be NULL");
|
||||
errorret_t assetScriptLoaderAsync(assetloading_t *loading) {
|
||||
assertNotNull(loading, "Loading cannot be NULL");
|
||||
assertNotMainThread("Async loader should not be on main thread.");
|
||||
|
||||
assetscript_t *script = (assetscript_t *)file->output;
|
||||
|
||||
errorChain(assetFileOpen(file));
|
||||
|
||||
// Accumulate full source into a dynamically grown buffer.
|
||||
size_t srcLen = 0;
|
||||
size_t capacity = ASSET_SCRIPT_CHUNK_SIZE;
|
||||
char_t *src = (char_t *)malloc(capacity + 1);
|
||||
if(!src) {
|
||||
assetFileClose(file);
|
||||
errorThrow("Out of memory reading script: %s", file->filename);
|
||||
if(loading->loading.script.state != ASSET_SCRIPT_LOADING_STATE_READ_FILE) {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
while(1) {
|
||||
if(srcLen + ASSET_SCRIPT_CHUNK_SIZE > capacity) {
|
||||
capacity = srcLen + ASSET_SCRIPT_CHUNK_SIZE;
|
||||
char_t *tmp = (char_t *)realloc(src, capacity + 1);
|
||||
if(!tmp) {
|
||||
free(src);
|
||||
assetFileClose(file);
|
||||
errorThrow("Out of memory reading script: %s", file->filename);
|
||||
}
|
||||
src = tmp;
|
||||
}
|
||||
zip_int64_t n = zip_fread(
|
||||
file->zipFile, src + srcLen, ASSET_SCRIPT_CHUNK_SIZE
|
||||
);
|
||||
if(n <= 0) break;
|
||||
srcLen += (size_t)n;
|
||||
assertNull(loading->loading.script.buffer, "Buffer already defined?");
|
||||
|
||||
assetfile_t *file = &loading->loading.script.file;
|
||||
assetLoaderErrorChain(
|
||||
loading, assetFileInit(file, loading->entry->name, NULL, NULL)
|
||||
);
|
||||
|
||||
uint8_t *buffer = NULL;
|
||||
size_t size = 0;
|
||||
assetLoaderErrorChain(loading, assetFileReadEntire(file, &buffer, &size));
|
||||
assetLoaderErrorChain(loading, assetFileDispose(file));
|
||||
|
||||
// Null-terminate for jerry_eval.
|
||||
memoryResize((void **)&buffer, size, size + 1);
|
||||
buffer[size] = '\0';
|
||||
|
||||
loading->loading.script.buffer = buffer;
|
||||
loading->loading.script.size = size;
|
||||
loading->loading.script.state = ASSET_SCRIPT_LOADING_STATE_EXEC;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
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.");
|
||||
|
||||
switch(loading->loading.script.state) {
|
||||
case ASSET_SCRIPT_LOADING_STATE_INITIAL:
|
||||
loading->loading.script.state = ASSET_SCRIPT_LOADING_STATE_READ_FILE;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||
errorOk();
|
||||
break;
|
||||
|
||||
case ASSET_SCRIPT_LOADING_STATE_EXEC:
|
||||
break;
|
||||
|
||||
default:
|
||||
errorOk();
|
||||
}
|
||||
src[srcLen] = '\0';
|
||||
|
||||
errorret_t closeRet = assetFileClose(file);
|
||||
// Get read buffer
|
||||
uint8_t *buffer = loading->loading.script.buffer;
|
||||
assertNotNull(buffer, "Script buffer should have been loaded by now.");
|
||||
|
||||
// Get the current global script realm
|
||||
jerry_value_t global = jerry_current_realm();
|
||||
|
||||
// Replace globalThis.module with a new `module = {}`
|
||||
jerry_value_t oldModule = jerry_object_get_sz(global, "module");
|
||||
|
||||
jerry_value_t module = jerry_object();
|
||||
jerry_object_set_sz(global, "module", module);
|
||||
|
||||
// Eval the script, we handle failure later down the code.
|
||||
jerry_value_t result = jerry_eval(
|
||||
(const jerry_char_t *)src,
|
||||
srcLen,
|
||||
buffer,
|
||||
loading->loading.script.size,
|
||||
JERRY_PARSE_NO_OPTS
|
||||
);
|
||||
free(src);
|
||||
|
||||
// Free the read buffer
|
||||
memoryFree(buffer);
|
||||
loading->loading.script.buffer = NULL;
|
||||
|
||||
// Restore globalThis.module
|
||||
jerry_object_set_sz(global, "module", oldModule);
|
||||
jerry_value_free(oldModule);
|
||||
jerry_value_free(global);
|
||||
|
||||
if(jerry_value_is_exception(result)) {
|
||||
jerry_value_t errVal = jerry_exception_value(result, false);
|
||||
jerry_value_t errStr = jerry_value_to_string(errVal);
|
||||
jerry_value_free(module);
|
||||
|
||||
loading->entry->data.script.exports = jerry_undefined();
|
||||
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
|
||||
|
||||
// Get error string
|
||||
char_t buf[256];
|
||||
jerry_size_t len = jerry_string_to_buffer(
|
||||
errStr, JERRY_ENCODING_UTF8, (jerry_char_t *)buf, sizeof(buf) - 1
|
||||
moduleBaseExceptionMessage(result, buf, sizeof(buf));
|
||||
jerry_value_free(result);
|
||||
assetLoaderErrorThrow(
|
||||
loading,
|
||||
"Script execution failed: %s: %s", loading->entry->name, buf
|
||||
);
|
||||
buf[len] = '\0';
|
||||
jerry_value_free(errStr);
|
||||
jerry_value_free(errVal);
|
||||
jerry_value_free(result);
|
||||
errorThrow("Script error in '%s': %s", file->filename, buf);
|
||||
}
|
||||
|
||||
// Get module.exports
|
||||
jerry_value_t exports = jerry_object_get_sz(module, "exports");
|
||||
jerry_value_free(result);
|
||||
jerry_value_free(module);
|
||||
|
||||
if(script->resultOut != NULL) {
|
||||
*(script->resultOut) = result;
|
||||
} else {
|
||||
jerry_value_free(result);
|
||||
}
|
||||
|
||||
return closeRet;
|
||||
// Store the exports.
|
||||
loading->entry->data.script.exports = exports;
|
||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t assetScriptLoad(
|
||||
const char_t *path,
|
||||
jerry_value_t *resultOut
|
||||
) {
|
||||
assertNotNull(path, "Script path cannot be NULL");
|
||||
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.");
|
||||
|
||||
assetscript_t scriptData;
|
||||
scriptData.resultOut = resultOut;
|
||||
|
||||
return assetLoad(path, assetScriptLoader, NULL, &scriptData);
|
||||
if(
|
||||
entry->data.script.exports != 0 &&
|
||||
!jerry_value_is_undefined(entry->data.script.exports)
|
||||
) {
|
||||
jerry_value_free(entry->data.script.exports);
|
||||
entry->data.script.exports = 0;
|
||||
}
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
@@ -6,33 +6,55 @@
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "asset/asset.h"
|
||||
#include "asset/assetfile.h"
|
||||
#include "script/scriptmodule.h"
|
||||
|
||||
#define ASSET_SCRIPT_CHUNK_SIZE 1024
|
||||
|
||||
typedef struct assetloading_s assetloading_t;
|
||||
typedef struct assetentry_s assetentry_t;
|
||||
|
||||
typedef struct {
|
||||
jerry_value_t *resultOut;
|
||||
} assetscript_t;
|
||||
void *nothing;
|
||||
} assetscriptloaderinput_t;
|
||||
|
||||
typedef scriptmodule_t assetscriptoutput_t;
|
||||
|
||||
typedef enum {
|
||||
ASSET_SCRIPT_LOADING_STATE_INITIAL,
|
||||
ASSET_SCRIPT_LOADING_STATE_READ_FILE,
|
||||
ASSET_SCRIPT_LOADING_STATE_EXEC,
|
||||
ASSET_SCRIPT_LOADING_STATE_DONE
|
||||
} assetscriptloadingstate_t;
|
||||
|
||||
typedef struct {
|
||||
assetfile_t file;
|
||||
assetscriptloadingstate_t state;
|
||||
uint8_t *buffer;
|
||||
size_t size;
|
||||
} assetscriptloaderloading_t;
|
||||
|
||||
/**
|
||||
* Handler for script assets. Reads the full source, evaluates it with
|
||||
* JerryScript, and optionally stores the result.
|
||||
*
|
||||
* @param file Asset file to load the script from.
|
||||
* @return Any error that occurs during loading.
|
||||
* Asynchronous loader for a script asset/module.
|
||||
*
|
||||
* @param loading The loading context.
|
||||
* @returns An error code and state.
|
||||
*/
|
||||
errorret_t assetScriptLoader(assetfile_t *file);
|
||||
errorret_t assetScriptLoaderAsync(assetloading_t *loading);
|
||||
|
||||
/**
|
||||
* Loads a script from the specified path.
|
||||
*
|
||||
* @param path Path to the script asset.
|
||||
* @param resultOut Optional out-parameter for the script return value.
|
||||
* Caller must call jerry_value_free() if non-NULL.
|
||||
* Pass NULL to discard the return value.
|
||||
* @return Any error that occurs during loading.
|
||||
* Synchronous loader for a script asset/module. This executes the script after
|
||||
* it has been loaded by the async loader.
|
||||
*
|
||||
* @param loading The loading context.
|
||||
* @returns An error code and state.
|
||||
*/
|
||||
errorret_t assetScriptLoad(
|
||||
const char_t *path,
|
||||
jerry_value_t *resultOut
|
||||
);
|
||||
errorret_t assetScriptLoaderSync(assetloading_t *loading);
|
||||
|
||||
/**
|
||||
* Disposes of a loaded script asset/module.
|
||||
*
|
||||
* @param entry The asset entry to dispose.
|
||||
* @returns An error code and state.
|
||||
*/
|
||||
errorret_t assetScriptDispose(assetentry_t *entry);
|
||||
|
||||
+4
-113
@@ -12,7 +12,6 @@
|
||||
#include "input/input.h"
|
||||
#include "log/log.h"
|
||||
#include "engine/engine.h"
|
||||
#include "script/scriptmanager.h"
|
||||
#include "display/shader/shaderunlit.h"
|
||||
#include "display/text/text.h"
|
||||
#include "display/spritebatch/spritebatch.h"
|
||||
@@ -23,10 +22,7 @@ void consoleInit(void) {
|
||||
memoryZero(&CONSOLE, sizeof(console_t));
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadInit(&CONSOLE.thread, consoleInputThread);
|
||||
threadMutexInit(&CONSOLE.execMutex);
|
||||
threadMutexInit(&CONSOLE.printMutex);
|
||||
threadStartRequest(&CONSOLE.thread);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -56,30 +52,6 @@ void consolePrint(const char_t *message, ...) {
|
||||
logDebug("%s\n", buffer);
|
||||
}
|
||||
|
||||
void consoleExec(const char_t *line) {
|
||||
assertNotNull(line, "line must not be NULL");
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadMutexLock(&CONSOLE.execMutex);
|
||||
#endif
|
||||
|
||||
assertTrue(
|
||||
CONSOLE.execBufferCount < CONSOLE_EXEC_BUFFER_MAX,
|
||||
"Console exec buffer is full"
|
||||
);
|
||||
|
||||
stringCopy(
|
||||
CONSOLE.execBuffer[CONSOLE.execBufferCount],
|
||||
line,
|
||||
CONSOLE_LINE_MAX
|
||||
);
|
||||
CONSOLE.execBufferCount++;
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadMutexUnlock(&CONSOLE.execMutex);
|
||||
#endif
|
||||
}
|
||||
|
||||
void consoleUpdate(void) {
|
||||
#ifdef DUSK_TIME_DYNAMIC
|
||||
if(TIME.dynamicUpdate) return;
|
||||
@@ -88,40 +60,6 @@ void consoleUpdate(void) {
|
||||
if(inputPressed(INPUT_ACTION_CONSOLE)) {
|
||||
CONSOLE.visible = !CONSOLE.visible;
|
||||
}
|
||||
|
||||
if(CONSOLE.execBufferCount == 0) return;
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadMutexLock(&CONSOLE.execMutex);
|
||||
#endif
|
||||
|
||||
char_t execBuffer[CONSOLE_EXEC_BUFFER_MAX][CONSOLE_LINE_MAX];
|
||||
uint32_t execBufferCount = CONSOLE.execBufferCount;
|
||||
memoryCopy(execBuffer, CONSOLE.execBuffer, sizeof(execBuffer));
|
||||
CONSOLE.execBufferCount = 0;
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadMutexUnlock(&CONSOLE.execMutex);
|
||||
#endif
|
||||
|
||||
for(uint32_t i = 0; i < execBufferCount; i++) {
|
||||
jerry_value_t result = 0;
|
||||
errorret_t err = scriptManagerExec(execBuffer[i], &result);
|
||||
if(err.code != ERROR_OK) {
|
||||
consolePrint("Error: %s", err.state->message);
|
||||
errorCatch(err);
|
||||
} else if(!jerry_value_is_undefined(result)) {
|
||||
jerry_value_t strVal = jerry_value_to_string(result);
|
||||
char_t buf[CONSOLE_LINE_MAX];
|
||||
jerry_size_t len = jerry_string_to_buffer(
|
||||
strVal, JERRY_ENCODING_UTF8, (jerry_char_t*)buf, sizeof(buf) - 1
|
||||
);
|
||||
buf[len] = '\0';
|
||||
jerry_value_free(strVal);
|
||||
consolePrint("%s", buf);
|
||||
}
|
||||
if(result != 0) jerry_value_free(result);
|
||||
}
|
||||
}
|
||||
|
||||
errorret_t consoleDraw(void) {
|
||||
@@ -129,64 +67,17 @@ errorret_t consoleDraw(void) {
|
||||
|
||||
for(uint32_t i = 0; i < CONSOLE_HISTORY_MAX; i++) {
|
||||
errorChain(textDraw(
|
||||
0, FONT_TILESET_DEFAULT.tileHeight * i,
|
||||
0, FONT_DEFAULT.tileset->tileHeight * i,
|
||||
CONSOLE.line[i],
|
||||
COLOR_WHITE,
|
||||
&FONT_TILESET_DEFAULT,
|
||||
&FONT_TEXTURE_DEFAULT
|
||||
&FONT_DEFAULT
|
||||
));
|
||||
}
|
||||
errorOk();
|
||||
return spriteBatchFlush();
|
||||
}
|
||||
|
||||
void consoleDispose(void) {
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadStop(&CONSOLE.thread);
|
||||
threadMutexDispose(&CONSOLE.execMutex);
|
||||
threadMutexDispose(&CONSOLE.printMutex);
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
void consoleInputThread(thread_t *thread) {
|
||||
assertNotNull(thread, "Thread cannot be NULL.");
|
||||
|
||||
char_t line[CONSOLE_LINE_MAX];
|
||||
|
||||
struct pollfd pfd = {
|
||||
.fd = STDIN_FILENO,
|
||||
.events = POLLIN
|
||||
};
|
||||
|
||||
while(!threadShouldStop(thread) && ENGINE.running) {
|
||||
int32_t rc = poll(&pfd, 1, CONSOLE_POSIX_POLL_RATE);
|
||||
|
||||
if(rc == 0) continue;
|
||||
if(rc < 0) {
|
||||
if(errno == EINTR) continue;
|
||||
assertUnreachable("poll() failed with unexpected error.");
|
||||
}
|
||||
|
||||
if(pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) break;
|
||||
if(!(pfd.revents & POLLIN)) {
|
||||
pfd.revents = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
if(!fgets(line, CONSOLE_LINE_MAX, stdin)) {
|
||||
if(feof(stdin)) break;
|
||||
clearerr(stdin);
|
||||
continue;
|
||||
}
|
||||
|
||||
size_t len = strlen(line);
|
||||
while(len && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
|
||||
line[--len] = '\0';
|
||||
}
|
||||
|
||||
if(len > 0) consoleExec(line);
|
||||
|
||||
pfd.revents = 0;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -21,12 +21,7 @@ typedef struct {
|
||||
char_t line[CONSOLE_HISTORY_MAX][CONSOLE_LINE_MAX];
|
||||
bool_t visible;
|
||||
|
||||
char_t execBuffer[CONSOLE_EXEC_BUFFER_MAX][CONSOLE_LINE_MAX];
|
||||
uint32_t execBufferCount;
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
thread_t thread;
|
||||
threadmutex_t execMutex;
|
||||
threadmutex_t printMutex;
|
||||
#endif
|
||||
} console_t;
|
||||
@@ -45,13 +40,6 @@ void consoleInit(void);
|
||||
*/
|
||||
void consolePrint(const char_t *message, ...);
|
||||
|
||||
/**
|
||||
* Queues a JS string for execution on the main thread. Thread-safe.
|
||||
*
|
||||
* @param line The JS source line to execute.
|
||||
*/
|
||||
void consoleExec(const char_t *line);
|
||||
|
||||
/**
|
||||
* Processes pending queued script lines. Call once per frame from main thread.
|
||||
*/
|
||||
@@ -67,13 +55,4 @@ errorret_t consoleDraw(void);
|
||||
/**
|
||||
* Disposes of the console.
|
||||
*/
|
||||
void consoleDispose(void);
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
/**
|
||||
* Input thread handler for POSIX stdin.
|
||||
*
|
||||
* @param thread The thread that is running.
|
||||
*/
|
||||
void consoleInputThread(thread_t *thread);
|
||||
#endif
|
||||
void consoleDispose(void);
|
||||
@@ -1,10 +1,9 @@
|
||||
# Copyright (c) 2025 Dominic Masters
|
||||
# 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
|
||||
game.c
|
||||
)
|
||||
cutscene.c
|
||||
)
|
||||
@@ -0,0 +1,96 @@
|
||||
// Copyright (c) 2026 Dominic Masters
|
||||
//
|
||||
// This software is released under the MIT License.
|
||||
// https://opensource.org/licenses/MIT
|
||||
|
||||
#include "cutscene.h"
|
||||
#include "assert/assert.h"
|
||||
#include "util/memory.h"
|
||||
#include "console/console.h"
|
||||
#include "time/time.h"
|
||||
|
||||
cutscene_t CUTSCENE;
|
||||
|
||||
errorret_t cutsceneInit(void) {
|
||||
memoryZero(&CUTSCENE, sizeof(cutscene_t));
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t cutsceneUpdate(void) {
|
||||
#ifdef DUSK_TIME_DYNAMIC
|
||||
if(TIME.dynamicUpdate) {
|
||||
errorOk();
|
||||
}
|
||||
#endif
|
||||
|
||||
if(!CUTSCENE.active) errorOk();
|
||||
|
||||
cutsceneevent_t *event = &CUTSCENE.events[CUTSCENE.eventCurrent];
|
||||
if(event->onUpdate) errorChain(event->onUpdate());
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t cutscenePlay(
|
||||
const cutsceneevent_t *events,
|
||||
const uint8_t eventCount
|
||||
) {
|
||||
assertNotNull(events, "Events cannot be null");
|
||||
assertTrue(eventCount > 0, "Event count must be greater than zero");
|
||||
assertTrue(
|
||||
eventCount <= CUTSCENE_EVENT_COUNT_MAX,
|
||||
"Event count exceeds CUTSCENE_EVENT_COUNT_MAX"
|
||||
);
|
||||
|
||||
if(CUTSCENE.active) {
|
||||
errorChain(cutsceneStop());
|
||||
}
|
||||
|
||||
memoryCopy(CUTSCENE.events, events, sizeof(cutsceneevent_t) * eventCount);
|
||||
CUTSCENE.eventCount = eventCount;
|
||||
CUTSCENE.eventCurrent = 0;
|
||||
CUTSCENE.active = true;
|
||||
|
||||
cutsceneevent_t *firstEvent = &CUTSCENE.events[0];
|
||||
if(firstEvent->onStart) errorChain(firstEvent->onStart());
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t cutsceneAdvance(void) {
|
||||
if(!CUTSCENE.active) errorOk();
|
||||
|
||||
cutsceneevent_t *currentEvent = &CUTSCENE.events[CUTSCENE.eventCurrent];
|
||||
if(currentEvent->onEnd) errorChain(currentEvent->onEnd());
|
||||
CUTSCENE.eventCurrent++;
|
||||
|
||||
if(CUTSCENE.eventCurrent >= CUTSCENE.eventCount) {
|
||||
if(CUTSCENE.onStop) errorChain(CUTSCENE.onStop());
|
||||
CUTSCENE.active = false;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
cutsceneevent_t *nextEvent = &CUTSCENE.events[CUTSCENE.eventCurrent];
|
||||
if(nextEvent->onStart) errorChain(nextEvent->onStart());
|
||||
consolePrint("Cutscene advance");
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t cutsceneStop(void) {
|
||||
if(!CUTSCENE.active) errorOk();
|
||||
|
||||
cutsceneevent_t *currentEvent = &CUTSCENE.events[CUTSCENE.eventCurrent];
|
||||
if(currentEvent->onEnd) errorChain(currentEvent->onEnd());
|
||||
|
||||
if(CUTSCENE.onStop) errorChain(CUTSCENE.onStop());
|
||||
|
||||
CUTSCENE.active = false;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t cutsceneDispose(void) {
|
||||
errorChain(cutsceneStop());
|
||||
errorOk();
|
||||
}
|
||||
|
||||
bool_t cutsceneIsActive(void) {
|
||||
return CUTSCENE.active;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// Copyright (c) 2026 Dominic Masters
|
||||
//
|
||||
// This software is released under the MIT License.
|
||||
// https://opensource.org/licenses/MIT
|
||||
|
||||
#pragma once
|
||||
#include "error/error.h"
|
||||
|
||||
#define CUTSCENE_EVENT_COUNT_MAX 16
|
||||
|
||||
typedef struct {
|
||||
errorret_t (*onStart)(void);
|
||||
errorret_t (*onEnd)(void);
|
||||
errorret_t (*onUpdate)(void);
|
||||
} cutsceneevent_t;
|
||||
|
||||
typedef struct {
|
||||
cutsceneevent_t events[CUTSCENE_EVENT_COUNT_MAX];
|
||||
uint8_t eventCount;
|
||||
uint8_t eventCurrent;
|
||||
errorret_t (*onStop)(void);
|
||||
bool_t active;
|
||||
} cutscene_t;
|
||||
|
||||
extern cutscene_t CUTSCENE;
|
||||
|
||||
/**
|
||||
* Initializes the cutscene manager.
|
||||
*
|
||||
* @return Any error state that happened.
|
||||
*/
|
||||
errorret_t cutsceneInit(void);
|
||||
|
||||
/**
|
||||
* Ticks the active cutscene event, calling its onUpdate callback.
|
||||
* Does nothing when no cutscene is playing.
|
||||
*
|
||||
* @return Any error state that happened.
|
||||
*/
|
||||
errorret_t cutsceneUpdate(void);
|
||||
|
||||
/**
|
||||
* Copies the given event array and begins playing from the first
|
||||
* event. If a cutscene is already playing it is stopped first.
|
||||
*
|
||||
* @param events Array of events to copy.
|
||||
* @param eventCount Number of events. Must be > 0 and
|
||||
* <= CUTSCENE_EVENT_COUNT_MAX.
|
||||
* @return Any error state that happened.
|
||||
*/
|
||||
errorret_t cutscenePlay(
|
||||
const cutsceneevent_t *events,
|
||||
const uint8_t eventCount
|
||||
);
|
||||
|
||||
/**
|
||||
* Ends the current event and starts the next one.
|
||||
* Marks the cutscene as inactive after the last event ends.
|
||||
* Does nothing when no cutscene is playing.
|
||||
*
|
||||
* @return Any error state that happened.
|
||||
*/
|
||||
errorret_t cutsceneAdvance(void);
|
||||
|
||||
/**
|
||||
* Ends the current event and stops the cutscene immediately.
|
||||
* Does nothing when no cutscene is playing.
|
||||
*
|
||||
* @return Any error state that happened.
|
||||
*/
|
||||
errorret_t cutsceneStop(void);
|
||||
|
||||
/**
|
||||
* Disposes of the cutscene manager, stopping any active cutscene.
|
||||
*
|
||||
* @return Any error state that happened.
|
||||
*/
|
||||
errorret_t cutsceneDispose(void);
|
||||
|
||||
/**
|
||||
* Returns whether a cutscene is currently playing.
|
||||
*
|
||||
* @return true if a cutscene is active.
|
||||
*/
|
||||
bool_t cutsceneIsActive(void);
|
||||
+11
-26
@@ -22,7 +22,7 @@
|
||||
#include "util/memory.h"
|
||||
#include "util/string.h"
|
||||
#include "asset/asset.h"
|
||||
#include "display/shader/shaderunlit.h"
|
||||
#include "display/shader/shaderlist.h"
|
||||
#include "time/time.h"
|
||||
|
||||
display_t DISPLAY = { 0 };
|
||||
@@ -33,6 +33,7 @@ errorret_t displayInit(void) {
|
||||
#ifdef displayPlatformInit
|
||||
errorChain(displayPlatformInit());
|
||||
#endif
|
||||
errorChain(displaySetState((displaystate_t){ .flags = 0 }));
|
||||
errorChain(textureInit(
|
||||
&TEXTURE_WHITE, 4, 4,
|
||||
TEXTURE_FORMAT_RGBA, (texturedata_t){ .rgbaColors = TEXTURE_WHITE_PIXELS }
|
||||
@@ -52,31 +53,8 @@ errorret_t displayInit(void) {
|
||||
errorChain(screenInit());
|
||||
|
||||
// Setup initial shader with default values
|
||||
mat4 view, proj, model;
|
||||
glm_lookat(
|
||||
(vec3){ 0.0f, 0.0f, 1.0f },
|
||||
(vec3){ 0.0f, 0.0f, 0.0f },
|
||||
(vec3){ 0.0f, 1.0f, 0.0f },
|
||||
view
|
||||
);
|
||||
|
||||
glm_perspective(
|
||||
glm_rad(45.0f),
|
||||
SCREEN.aspect,
|
||||
0.1f,
|
||||
100.0f,
|
||||
proj
|
||||
);
|
||||
|
||||
glm_mat4_identity(model);
|
||||
|
||||
errorChain(shaderInit(&SHADER_UNLIT, &SHADER_UNLIT_DEFINITION));
|
||||
errorChain(shaderBind(&SHADER_UNLIT));
|
||||
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_PROJECTION, proj));
|
||||
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_VIEW, view));
|
||||
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_MODEL, model));
|
||||
errorChain(shaderSetTexture(&SHADER_UNLIT, SHADER_UNLIT_TEXTURE, NULL));
|
||||
errorChain(shaderSetColor(&SHADER_UNLIT, SHADER_UNLIT_COLOR, COLOR_WHITE));
|
||||
errorChain(shaderListInit());
|
||||
|
||||
errorOk();
|
||||
}
|
||||
@@ -110,8 +88,15 @@ errorret_t displayUpdate(void) {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t displaySetState(displaystate_t state) {
|
||||
#ifdef displayPlatformSetState
|
||||
errorChain(displayPlatformSetState(state));
|
||||
#endif
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t displayDispose(void) {
|
||||
errorChain(shaderDispose(&SHADER_UNLIT));
|
||||
errorChain(shaderListDispose());
|
||||
errorChain(spriteBatchDispose());
|
||||
screenDispose();
|
||||
errorChain(textDispose());
|
||||
|
||||
@@ -40,15 +40,26 @@ extern display_t DISPLAY;
|
||||
|
||||
/**
|
||||
* Initializes the display system.
|
||||
* @return An errorret_t indicating success or failure.
|
||||
*/
|
||||
errorret_t displayInit(void);
|
||||
|
||||
/**
|
||||
* Tells the display system to actually draw the frame.
|
||||
* @return An errorret_t indicating success or failure.
|
||||
*/
|
||||
errorret_t displayUpdate(void);
|
||||
|
||||
/**
|
||||
* Sets the display state.
|
||||
*
|
||||
* @param state The state to set.
|
||||
* @return An errorret_t indicating success or failure.
|
||||
*/
|
||||
errorret_t displaySetState(displaystate_t state);
|
||||
|
||||
/**
|
||||
* Disposes of the display system.
|
||||
* @return An errorret_t indicating success or failure.
|
||||
*/
|
||||
errorret_t displayDispose(void);
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "dusk.h"
|
||||
|
||||
#define DISPLAY_STATE_FLAG_CULL (1 << 0)
|
||||
#define DISPLAY_STATE_FLAG_DEPTH_TEST (1 << 1)
|
||||
#define DISPLAY_STATE_FLAG_BLEND (1 << 2)
|
||||
|
||||
typedef struct {
|
||||
uint8_t flags;
|
||||
} displaystate_t;
|
||||
@@ -119,8 +119,12 @@ void capsuleBuffer(
|
||||
{
|
||||
const float_t yTop = cy + halfHeight;
|
||||
const float_t yBot = cy - halfHeight;
|
||||
const float_t vTop = 1.0f - (float_t)capRings / (float_t)(2 * capRings + 1);
|
||||
const float_t vBot = 1.0f - (float_t)(capRings + 1) / (float_t)(2 * capRings + 1);
|
||||
const float_t vTop = (
|
||||
1.0f - (float_t)capRings / (float_t)(2 * capRings + 1)
|
||||
);
|
||||
const float_t vBot = (
|
||||
1.0f - (float_t)(capRings + 1) / (float_t)(2 * capRings + 1)
|
||||
);
|
||||
|
||||
for(int32_t j = 0; j < sectors; j++) {
|
||||
const float_t t1 = (float_t)j * sectorStep;
|
||||
@@ -152,8 +156,12 @@ void capsuleBuffer(
|
||||
const float_t lxz1 = radius * cosf(phi1);
|
||||
const float_t lxz2 = radius * cosf(phi2);
|
||||
|
||||
const float_t v1 = 1.0f - (float_t)(capRings + 1 + i) / (float_t)(2 * capRings + 1);
|
||||
const float_t v2 = 1.0f - (float_t)(capRings + 1 + i + 1) / (float_t)(2 * capRings + 1);
|
||||
const float_t v1 = (
|
||||
1.0f - (float_t)(capRings + 1 + i) / (float_t)(2 * capRings + 1)
|
||||
);
|
||||
const float_t v2 = (
|
||||
1.0f - (float_t)(capRings + 1 + i + 1) / (float_t)(2 * capRings + 1)
|
||||
);
|
||||
|
||||
for(int32_t j = 0; j < sectors; j++) {
|
||||
const float_t t1 = (float_t)j * sectorStep;
|
||||
|
||||
@@ -28,7 +28,7 @@ errorret_t cubeInit();
|
||||
* Buffers a 3D axis-aligned cube into the provided vertex array.
|
||||
* Writes CUBE_VERTEX_COUNT vertices (6 faces x 6 vertices, CCW winding).
|
||||
*
|
||||
* @param vertices The vertex array to buffer into (must hold CUBE_VERTEX_COUNT).
|
||||
* @param vertices The vertex array to buffer into.
|
||||
* @param min The minimum XYZ corner of the cube.
|
||||
* @param max The maximum XYZ corner of the cube.
|
||||
* @param color The color applied to all vertices.
|
||||
|
||||
@@ -34,10 +34,14 @@ errorret_t meshFlush(
|
||||
#ifdef meshFlushPlatform
|
||||
assertNotNull(mesh, "Mesh cannot be NULL");
|
||||
assertTrue(vertexOffset >= 0, "Vertex offset must be non-negative.");
|
||||
assertTrue(vertexCount == -1 || vertexCount > 0, "Vertex count incorrect.");
|
||||
assertTrue(
|
||||
vertexCount == -1 || vertexCount > 0, "Vertex count incorrect."
|
||||
);
|
||||
|
||||
int32_t vertCount = meshGetVertexCount(mesh);
|
||||
assertTrue(vertexOffset < (vertCount - 1), "Need at least one vert to draw");
|
||||
assertTrue(
|
||||
vertexOffset < (vertCount - 1), "Need at least one vert to draw"
|
||||
);
|
||||
|
||||
int32_t drawCount = vertexCount;
|
||||
if(vertexCount == -1) {
|
||||
|
||||
@@ -9,12 +9,6 @@
|
||||
#include "display/mesh/mesh.h"
|
||||
#include "display/color.h"
|
||||
|
||||
/**
|
||||
* Vertex layout:
|
||||
* 2 triangular end-caps (3 verts each) = 6
|
||||
* 3 rectangular side faces (6 verts each) = 18
|
||||
* Total = 24
|
||||
*/
|
||||
#define TRIPRISM_VERTEX_COUNT 24
|
||||
#define TRIPRISM_PRIMITIVE_TYPE MESH_PRIMITIVE_TYPE_TRIANGLES
|
||||
|
||||
@@ -35,13 +29,13 @@ errorret_t triPrismInit();
|
||||
* the prism is extruded along the Z axis between minZ and maxZ.
|
||||
* Writes TRIPRISM_VERTEX_COUNT (24) vertices (CCW winding).
|
||||
*
|
||||
* @param vertices Vertex array to write into (must hold TRIPRISM_VERTEX_COUNT).
|
||||
* @param x0,y0 First triangle vertex (XY).
|
||||
* @param x1,y1 Second triangle vertex (XY).
|
||||
* @param x2,y2 Third triangle vertex (XY).
|
||||
* @param minZ Near Z extent of the prism.
|
||||
* @param maxZ Far Z extent of the prism.
|
||||
* @param color Color applied to all vertices.
|
||||
* @param vertices Vertex array to write into.
|
||||
* @param x0,y0 First triangle vertex (XY).
|
||||
* @param x1,y1 Second triangle vertex (XY).
|
||||
* @param x2,y2 Third triangle vertex (XY).
|
||||
* @param minZ Near Z extent of the prism.
|
||||
* @param maxZ Far Z extent of the prism.
|
||||
* @param color Color applied to all vertices.
|
||||
*/
|
||||
void triPrismBuffer(
|
||||
meshvertex_t *vertices,
|
||||
|
||||
@@ -7,5 +7,6 @@
|
||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
shader.c
|
||||
shaderlist.c
|
||||
shaderunlit.c
|
||||
)
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "shader.h"
|
||||
#include "shadermaterial.h"
|
||||
#include "assert/assert.h"
|
||||
#include "log/log.h"
|
||||
|
||||
shader_t *bound = NULL;
|
||||
|
||||
@@ -57,6 +58,7 @@ errorret_t shaderSetColor(
|
||||
) {
|
||||
assertNotNull(shader, "Shader cannot be null");
|
||||
assertStrLenMin(name, 1, "Uniform name cannot be empty");
|
||||
assertTrue(bound == shader, "Shader must be bound.");
|
||||
errorChain(shaderSetColorPlatform(shader, name, color));
|
||||
errorOk();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "shaderlist.h"
|
||||
#include "display/screen/screen.h"
|
||||
#include "assert/assert.h"
|
||||
|
||||
shaderlistdef_t SHADER_LIST_DEFS[SHADER_LIST_SHADER_COUNT] = {
|
||||
[SHADER_LIST_SHADER_UNLIT] = {
|
||||
.shader = &SHADER_UNLIT,
|
||||
.definition = &SHADER_UNLIT_DEFINITION
|
||||
},
|
||||
};
|
||||
|
||||
errorret_t shaderListInit() {
|
||||
mat4 view, proj, model;
|
||||
glm_lookat(
|
||||
(vec3){ 0.0f, 0.0f, 1.0f },
|
||||
(vec3){ 0.0f, 0.0f, 0.0f },
|
||||
(vec3){ 0.0f, 1.0f, 0.0f },
|
||||
view
|
||||
);
|
||||
|
||||
glm_perspective(
|
||||
glm_rad(45.0f),
|
||||
SCREEN.aspect,
|
||||
0.1f,
|
||||
100.0f,
|
||||
proj
|
||||
);
|
||||
|
||||
glm_mat4_identity(model);
|
||||
|
||||
for(shaderlistshader_t i = 0; i < SHADER_LIST_SHADER_COUNT; i++) {
|
||||
if(i == SHADER_LIST_SHADER_NULL) {
|
||||
continue;
|
||||
}
|
||||
|
||||
assertNotNull(
|
||||
SHADER_LIST_DEFS[i].shader, "Shader cannot be null"
|
||||
);
|
||||
assertNotNull(
|
||||
SHADER_LIST_DEFS[i].definition, "Shader definition cannot be null"
|
||||
);
|
||||
|
||||
errorChain(shaderInit(
|
||||
SHADER_LIST_DEFS[i].shader, SHADER_LIST_DEFS[i].definition
|
||||
));
|
||||
errorChain(shaderBind(SHADER_LIST_DEFS[i].shader));
|
||||
errorChain(shaderSetMatrix(
|
||||
SHADER_LIST_DEFS[i].shader, SHADER_UNLIT_PROJECTION, proj
|
||||
));
|
||||
errorChain(shaderSetMatrix(
|
||||
SHADER_LIST_DEFS[i].shader, SHADER_UNLIT_VIEW, view
|
||||
));
|
||||
errorChain(shaderSetMatrix(
|
||||
SHADER_LIST_DEFS[i].shader, SHADER_UNLIT_MODEL, model
|
||||
));
|
||||
errorChain(shaderSetTexture(
|
||||
SHADER_LIST_DEFS[i].shader, SHADER_UNLIT_TEXTURE, NULL
|
||||
));
|
||||
errorChain(shaderSetColor(
|
||||
SHADER_LIST_DEFS[i].shader, SHADER_UNLIT_COLOR, COLOR_WHITE
|
||||
));
|
||||
}
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t shaderListDispose(void) {
|
||||
for(shaderlistshader_t i = 0; i < SHADER_LIST_SHADER_COUNT; i++) {
|
||||
if(i == SHADER_LIST_SHADER_NULL) {
|
||||
continue;
|
||||
}
|
||||
|
||||
assertNotNull(
|
||||
SHADER_LIST_DEFS[i].shader, "Shader cannot be null"
|
||||
);
|
||||
|
||||
errorChain(shaderDispose(SHADER_LIST_DEFS[i].shader));
|
||||
}
|
||||
errorOk();
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "display/shader/shader.h"
|
||||
#include "display/shader/shaderunlit.h"
|
||||
|
||||
typedef enum {
|
||||
SHADER_LIST_SHADER_NULL,
|
||||
|
||||
SHADER_LIST_SHADER_UNLIT,
|
||||
|
||||
SHADER_LIST_SHADER_COUNT
|
||||
} shaderlistshader_t;
|
||||
|
||||
typedef struct {
|
||||
shader_t *shader;
|
||||
shaderdefinition_t *definition;
|
||||
} shaderlistdef_t;
|
||||
|
||||
extern shaderlistdef_t SHADER_LIST_DEFS[SHADER_LIST_SHADER_COUNT];
|
||||
|
||||
/**
|
||||
* Initializes all default shaders and uploads the initial view, projection,
|
||||
* and model matrices to each.
|
||||
*
|
||||
* @return Error state.
|
||||
*/
|
||||
errorret_t shaderListInit();
|
||||
|
||||
/**
|
||||
* Disposes all default shaders.
|
||||
*
|
||||
* @return Error state.
|
||||
*/
|
||||
errorret_t shaderListDispose(void);
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "display/shader/shaderunlit.h"
|
||||
#include "display/shader/shaderlist.h"
|
||||
|
||||
typedef union shadermaterial_u {
|
||||
shaderunlitmaterial_t unlit;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Copyright (c) 2025 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
@@ -8,13 +8,14 @@
|
||||
#include "spritebatch.h"
|
||||
#include "assert/assert.h"
|
||||
#include "util/memory.h"
|
||||
#include "util/math.h"
|
||||
#include "display/shader/shadermaterial.h"
|
||||
|
||||
meshvertex_t SPRITEBATCH_VERTICES[SPRITEBATCH_VERTEX_COUNT];
|
||||
spritebatch_t SPRITEBATCH;
|
||||
|
||||
errorret_t spriteBatchInit() {
|
||||
memoryZero(&SPRITEBATCH, sizeof(spritebatch_t));
|
||||
|
||||
errorChain(meshInit(
|
||||
&SPRITEBATCH.mesh,
|
||||
QUAD_PRIMITIVE_TYPE,
|
||||
@@ -24,63 +25,102 @@ errorret_t spriteBatchInit() {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t spriteBatchPush(
|
||||
const float_t minX,
|
||||
const float_t minY,
|
||||
const float_t maxX,
|
||||
const float_t maxY,
|
||||
#if MESH_ENABLE_COLOR
|
||||
const color_t color,
|
||||
#endif
|
||||
const float_t u0,
|
||||
const float_t v0,
|
||||
const float_t u1,
|
||||
const float_t v1
|
||||
errorret_t spriteBatchBuffer(
|
||||
const spritebatchsprite_t *sprites,
|
||||
const uint32_t count,
|
||||
shader_t *shader,
|
||||
const shadermaterial_t material
|
||||
) {
|
||||
return spriteBatchPush3D(
|
||||
(vec3){ minX, minY, 0 },
|
||||
(vec3){ maxX, maxY, 0 },
|
||||
#if MESH_ENABLE_COLOR
|
||||
color,
|
||||
#endif
|
||||
(vec2){ u0, v0 },
|
||||
(vec2){ u1, v1 }
|
||||
);
|
||||
}
|
||||
assertNotNull(sprites, "Sprites cannot be null");
|
||||
assertTrue(count > 0, "Count must be greater than zero");
|
||||
assertNotNull(shader, "Shader cannot be null");
|
||||
|
||||
errorret_t spriteBatchPush3D(
|
||||
const vec3 min,
|
||||
const vec3 max,
|
||||
#if MESH_ENABLE_COLOR
|
||||
const color_t color,
|
||||
#endif
|
||||
const vec2 uv0,
|
||||
const vec2 uv1
|
||||
) {
|
||||
// Need to flush?
|
||||
if(SPRITEBATCH.spriteCount >= SPRITEBATCH_SPRITES_MAX_PER_FLUSH) {
|
||||
// Did the shader or material data change?
|
||||
if(shader != SPRITEBATCH.shader) {
|
||||
errorChain(spriteBatchFlush());
|
||||
SPRITEBATCH.shader = shader;
|
||||
SPRITEBATCH.material = material;
|
||||
} else if(memoryCompare(
|
||||
&material, &SPRITEBATCH.material, sizeof(shadermaterial_t)
|
||||
) != 0) {
|
||||
// Did the material data change?
|
||||
errorChain(spriteBatchFlush());
|
||||
SPRITEBATCH.shader = shader;
|
||||
SPRITEBATCH.material = material;
|
||||
}
|
||||
|
||||
size_t vertexOffset = (
|
||||
SPRITEBATCH.spriteCount +
|
||||
(SPRITEBATCH.spriteFlush * SPRITEBATCH_SPRITES_MAX_PER_FLUSH)
|
||||
) * QUAD_VERTEX_COUNT;
|
||||
quadBuffer3D(
|
||||
&SPRITEBATCH_VERTICES[vertexOffset],
|
||||
min, max,
|
||||
uv0, uv1
|
||||
#if MESH_ENABLE_COLOR
|
||||
, color
|
||||
#endif
|
||||
);
|
||||
SPRITEBATCH.spriteCount++;
|
||||
// Buffer the vertices.
|
||||
for(uint32_t i = 0; i < count; i++ ){
|
||||
spritebatchsprite_t sprite = sprites[i];
|
||||
|
||||
meshvertex_t *v = &SPRITEBATCH_VERTICES[
|
||||
(SPRITEBATCH.spriteCount + (SPRITEBATCH.spriteFlush *
|
||||
SPRITEBATCH_SPRITES_MAX_PER_FLUSH)) * QUAD_VERTEX_COUNT
|
||||
];
|
||||
|
||||
// Buffer the quad
|
||||
v[0].pos[0] = sprite.min[0];
|
||||
v[0].pos[1] = sprite.min[1];
|
||||
v[0].pos[2] = sprite.min[2];
|
||||
|
||||
v[0].uv[0] = sprite.uvMin[0];
|
||||
v[0].uv[1] = sprite.uvMin[1];
|
||||
|
||||
|
||||
v[1].pos[0] = sprite.max[0];
|
||||
v[1].pos[1] = sprite.min[1];
|
||||
v[1].pos[2] = sprite.min[2];
|
||||
|
||||
v[1].uv[0] = sprite.uvMax[0];
|
||||
v[1].uv[1] = sprite.uvMin[1];
|
||||
|
||||
|
||||
v[2].pos[0] = sprite.max[0];
|
||||
v[2].pos[1] = sprite.max[1];
|
||||
v[2].pos[2] = sprite.max[2];
|
||||
|
||||
v[2].uv[0] = sprite.uvMax[0];
|
||||
v[2].uv[1] = sprite.uvMax[1];
|
||||
|
||||
|
||||
v[3].pos[0] = sprite.min[0];
|
||||
v[3].pos[1] = sprite.min[1];
|
||||
v[3].pos[2] = sprite.min[2];
|
||||
|
||||
v[3].uv[0] = sprite.uvMin[0];
|
||||
v[3].uv[1] = sprite.uvMin[1];
|
||||
|
||||
|
||||
v[4].pos[0] = sprite.max[0];
|
||||
v[4].pos[1] = sprite.max[1];
|
||||
v[4].pos[2] = sprite.max[2];
|
||||
|
||||
v[4].uv[0] = sprite.uvMax[0];
|
||||
v[4].uv[1] = sprite.uvMax[1];
|
||||
|
||||
|
||||
v[5].pos[0] = sprite.min[0];
|
||||
v[5].pos[1] = sprite.max[1];
|
||||
v[5].pos[2] = sprite.max[2];
|
||||
|
||||
v[5].uv[0] = sprite.uvMin[0];
|
||||
v[5].uv[1] = sprite.uvMax[1];
|
||||
|
||||
// Do we need to flush?
|
||||
SPRITEBATCH.spriteCount++;
|
||||
if(SPRITEBATCH.spriteCount >= SPRITEBATCH_SPRITES_MAX_PER_FLUSH) {
|
||||
errorChain(spriteBatchFlush());
|
||||
}
|
||||
}
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
void spriteBatchClear() {
|
||||
SPRITEBATCH.spriteCount = 0;
|
||||
SPRITEBATCH.spriteFlush = 0;
|
||||
SPRITEBATCH.shader = NULL;
|
||||
memoryZero(&SPRITEBATCH.material, sizeof(shadermaterial_t));
|
||||
}
|
||||
|
||||
errorret_t spriteBatchFlush() {
|
||||
@@ -93,6 +133,9 @@ errorret_t spriteBatchFlush() {
|
||||
SPRITEBATCH.spriteFlush * SPRITEBATCH_SPRITES_MAX_PER_FLUSH *
|
||||
QUAD_VERTEX_COUNT
|
||||
);
|
||||
|
||||
errorChain(shaderBind(SPRITEBATCH.shader));
|
||||
errorChain(shaderSetMaterial(SPRITEBATCH.shader, &SPRITEBATCH.material));
|
||||
errorChain(meshFlush(&SPRITEBATCH.mesh, vertexOffset, vertexCount));
|
||||
errorChain(meshDraw(&SPRITEBATCH.mesh, vertexOffset, vertexCount));
|
||||
|
||||
@@ -108,4 +151,4 @@ errorret_t spriteBatchFlush() {
|
||||
errorret_t spriteBatchDispose() {
|
||||
errorChain(meshDispose(&SPRITEBATCH.mesh));
|
||||
errorOk();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,107 +1,87 @@
|
||||
/**
|
||||
* Copyright (c) 2025 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "display/mesh/quad.h"
|
||||
#include "display/texture/texture.h"
|
||||
#include "display/shader/shadermaterial.h"
|
||||
|
||||
#define SPRITEBATCH_SPRITES_MAX 32
|
||||
#define SPRITEBATCH_VERTEX_COUNT (SPRITEBATCH_SPRITES_MAX * QUAD_VERTEX_COUNT)
|
||||
#define SPRITEBATCH_FLUSH_COUNT 4
|
||||
#define SPRITEBATCH_SPRITES_MAX 512
|
||||
#define SPRITEBATCH_VERTEX_COUNT (SPRITEBATCH_SPRITES_MAX * QUAD_VERTEX_COUNT)
|
||||
#define SPRITEBATCH_FLUSH_COUNT 16
|
||||
#define SPRITEBATCH_SPRITES_MAX_PER_FLUSH (\
|
||||
SPRITEBATCH_SPRITES_MAX / SPRITEBATCH_FLUSH_COUNT \
|
||||
)
|
||||
|
||||
typedef struct {
|
||||
vec3 min;
|
||||
vec3 max;
|
||||
vec2 uvMin;
|
||||
vec2 uvMax;
|
||||
} spritebatchsprite_t;
|
||||
|
||||
typedef struct {
|
||||
mesh_t mesh;
|
||||
int32_t spriteCount;
|
||||
int32_t spriteFlush;
|
||||
|
||||
shader_t *shader;
|
||||
shadermaterial_t material;
|
||||
} spritebatch_t;
|
||||
|
||||
// Have to define these seperately because of alignment in certain platforms.
|
||||
// Have to define these separately because of alignment on certain platforms.
|
||||
extern meshvertex_t SPRITEBATCH_VERTICES[SPRITEBATCH_VERTEX_COUNT];
|
||||
extern spritebatch_t SPRITEBATCH;
|
||||
|
||||
/**
|
||||
* Initializes a sprite batch.
|
||||
*
|
||||
* @param spriteBatch The sprite batch to initialize.
|
||||
* @return An error code indicating success or failure.
|
||||
* Initializes the global sprite batch and its internal mesh buffer.
|
||||
*
|
||||
* @return Error state.
|
||||
*/
|
||||
errorret_t spriteBatchInit();
|
||||
|
||||
/**
|
||||
* Pushes a sprite to the batch. This basically "queues" it to render (well
|
||||
* technically it is buffering the vertices to the mesh at the moment, but
|
||||
* that is likely to change when we switch to VAOs or VBOs or even Shader UBOs).
|
||||
*
|
||||
* Currently changing texture pointer will cause the buffer to flush but this is
|
||||
* also likely to change in the future.
|
||||
*
|
||||
* @param minX The minimum x coordinate of the sprite.
|
||||
* @param minY The minimum y coordinate of the sprite.
|
||||
* @param maxX The maximum x coordinate of the sprite.
|
||||
* @param maxY The maximum y coordinate of the sprite.
|
||||
* @param color The color to tint the sprite with.
|
||||
* @param u0 The texture coordinate for the top-left corner of the sprite.
|
||||
* @param v0 The texture coordinate for the top-left corner of the sprite.
|
||||
* @param u1 The texture coordinate for the bottom-right corner of the sprite.
|
||||
* @param v1 The texture coordinate for the bottom-right corner of the sprite.
|
||||
* @return An error code indicating success or failure.
|
||||
* Lowest-level buffer function. Writes sprites into the internal vertex buffer.
|
||||
* Flushes automatically when the per-flush capacity is reached. Does not
|
||||
* modify material state — call spriteBatchSetState or use a high-level push
|
||||
* function before buffering.
|
||||
*
|
||||
* @param sprites Pointer to the sprite array.
|
||||
* @param count Number of sprites to buffer.
|
||||
* @param shader Shader to use when flushing.
|
||||
* @param material Material information passed to the shader when flushing.
|
||||
* @return Error state.
|
||||
*/
|
||||
errorret_t spriteBatchPush(
|
||||
const float_t minX,
|
||||
const float_t minY,
|
||||
const float_t maxX,
|
||||
const float_t maxY,
|
||||
#if MESH_ENABLE_COLOR
|
||||
const color_t color,
|
||||
#endif
|
||||
const float_t u0,
|
||||
const float_t v0,
|
||||
const float_t u1,
|
||||
const float_t v1
|
||||
errorret_t spriteBatchBuffer(
|
||||
const spritebatchsprite_t *sprites,
|
||||
const uint32_t count,
|
||||
shader_t *shader,
|
||||
const shadermaterial_t material
|
||||
);
|
||||
|
||||
/**
|
||||
* Pushes a 3D sprite to the batch. This is like spriteBatchPush but takes
|
||||
* 3D coordinates instead of 2D.
|
||||
*
|
||||
* @param min The minimum (x,y,z) coordinate of the sprite.
|
||||
* @param max The maximum (x,y,z) coordinate of the sprite.
|
||||
* @param color The color to tint the sprite with.
|
||||
* @param uvMin The texture coordinate for the top-left corner of the sprite.
|
||||
* @param uvMax The texture coordinate for the bottom-right corner of the sprite
|
||||
* @return An error code indicating success or failure.
|
||||
*/
|
||||
errorret_t spriteBatchPush3D(
|
||||
const vec3 min,
|
||||
const vec3 max,
|
||||
#if MESH_ENABLE_COLOR
|
||||
const color_t color,
|
||||
#endif
|
||||
const vec2 uvMin,
|
||||
const vec2 uvMax
|
||||
);
|
||||
|
||||
/**
|
||||
* Clears the sprite batch. This will mean calling flush renders nothing.
|
||||
* Resets sprite and flush counters and clears the current material state.
|
||||
* Calling spriteBatchFlush after this renders nothing.
|
||||
*/
|
||||
void spriteBatchClear();
|
||||
|
||||
/**
|
||||
* Flushes the sprite batch, rendering all queued sprites.
|
||||
*
|
||||
* @return An error code indicating success or failure.
|
||||
* Uploads and draws all buffered sprites. If a material type has been set via
|
||||
* spriteBatchSetState or spriteBatchCheckState, the shader is bound and the
|
||||
* material is applied first. If matType is NULL the caller is responsible for
|
||||
* having the correct shader already bound. Does nothing if the buffer is empty.
|
||||
*
|
||||
* @return Error state.
|
||||
*/
|
||||
errorret_t spriteBatchFlush();
|
||||
|
||||
/**
|
||||
* Disposes of the sprite batch, freeing any allocated resources.
|
||||
*
|
||||
* @return An error code indicating success or failure.
|
||||
* Disposes of the sprite batch and frees its internal mesh buffer.
|
||||
*
|
||||
* @return Error state.
|
||||
*/
|
||||
errorret_t spriteBatchDispose();
|
||||
errorret_t spriteBatchDispose();
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "display/texture/texture.h"
|
||||
#include "display/texture/tileset.h"
|
||||
|
||||
typedef struct {
|
||||
texture_t *texture;
|
||||
tileset_t *tileset;
|
||||
} font_t;
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
@@ -9,121 +9,123 @@
|
||||
#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"
|
||||
|
||||
texture_t FONT_TEXTURE_DEFAULT;
|
||||
tileset_t FONT_TILESET_DEFAULT;
|
||||
font_t FONT_DEFAULT;
|
||||
|
||||
errorret_t textInit(void) {
|
||||
errorChain(assetTextureLoad(
|
||||
"ui/minogram.png", &FONT_TEXTURE_DEFAULT, TEXTURE_FORMAT_RGBA
|
||||
));
|
||||
errorChain(assetTilesetLoad("ui/minogram.dtf", &FONT_TILESET_DEFAULT));
|
||||
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(textureDispose(&FONT_TEXTURE_DEFAULT));
|
||||
FONT_DEFAULT.texture = NULL;
|
||||
FONT_DEFAULT.tileset = NULL;
|
||||
assetUnlock("ui/minogram.png");
|
||||
assetUnlock("ui/minogram.dtf");
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t textDrawChar(
|
||||
const float_t x,
|
||||
const float_t y,
|
||||
const char_t c,
|
||||
#if MESH_ENABLE_COLOR
|
||||
const color_t color,
|
||||
#endif
|
||||
const tileset_t *tileset,
|
||||
texture_t *texture
|
||||
spritebatchsprite_t textGetSprite(
|
||||
const vec2 pos, const char_t c, const font_t *font
|
||||
) {
|
||||
assertNotNull(font, "Font cannot be NULL");
|
||||
|
||||
// Change char from ASCII to a tile index.
|
||||
int32_t tileIndex = (int32_t)(c) - TEXT_CHAR_START;
|
||||
if(tileIndex < 0 || tileIndex >= tileset->tileCount) {
|
||||
if(tileIndex < 0 || tileIndex >= font->tileset->tileCount) {
|
||||
tileIndex = ((int32_t)'@') - TEXT_CHAR_START;
|
||||
}
|
||||
assertTrue(
|
||||
tileIndex >= 0 && tileIndex <= tileset->tileCount,
|
||||
tileIndex >= 0 && tileIndex <= font->tileset->tileCount,
|
||||
"Character is out of bounds for font tiles"
|
||||
);
|
||||
|
||||
// Create sprite.
|
||||
vec4 uv;
|
||||
tilesetTileGetUV(tileset, tileIndex, uv);
|
||||
tilesetTileGetUV(font->tileset, tileIndex, uv);
|
||||
|
||||
|
||||
errorChain(spriteBatchPush(
|
||||
// texture,
|
||||
x, y,
|
||||
x + tileset->tileWidth,
|
||||
y + tileset->tileHeight,
|
||||
#if MESH_ENABLE_COLOR
|
||||
color,
|
||||
#endif
|
||||
uv[0], uv[1], uv[2], uv[3]
|
||||
));
|
||||
errorOk();
|
||||
spritebatchsprite_t sprite;
|
||||
sprite.min[0] = pos[0];
|
||||
sprite.min[1] = pos[1];
|
||||
sprite.min[2] = 0.0f;
|
||||
sprite.max[0] = pos[0] + font->tileset->tileWidth;
|
||||
sprite.max[1] = pos[1] + font->tileset->tileHeight;
|
||||
sprite.max[2] = 0.0f;
|
||||
sprite.uvMin[0] = uv[0];
|
||||
sprite.uvMin[1] = uv[1];
|
||||
sprite.uvMax[0] = uv[2];
|
||||
sprite.uvMax[1] = uv[3];
|
||||
return sprite;
|
||||
}
|
||||
|
||||
|
||||
errorret_t textDraw(
|
||||
const float_t x,
|
||||
const float_t y,
|
||||
const char_t *text,
|
||||
const color_t color,
|
||||
const tileset_t *tileset,
|
||||
texture_t *texture
|
||||
font_t *font
|
||||
) {
|
||||
assertNotNull(text, "Text cannot be NULL");
|
||||
|
||||
spritebatchsprite_t sprite;
|
||||
shadermaterial_t material = {
|
||||
.unlit = {
|
||||
.color = color,
|
||||
.texture = font->texture
|
||||
}
|
||||
};
|
||||
|
||||
float_t posX = x;
|
||||
float_t posY = y;
|
||||
|
||||
errorChain(shaderSetTexture(&SHADER_UNLIT, SHADER_UNLIT_TEXTURE, texture));
|
||||
errorChain(shaderSetTexture(
|
||||
&SHADER_UNLIT, SHADER_UNLIT_TEXTURE, font->texture
|
||||
));
|
||||
|
||||
#if MESH_ENABLE_COLOR
|
||||
#else
|
||||
errorChain(shaderSetColor(&SHADER_UNLIT, SHADER_UNLIT_COLOR, color));
|
||||
#endif
|
||||
|
||||
// errorChain(spriteBatchPush(
|
||||
// // texture,
|
||||
// posX, posY,
|
||||
// posX + texture->width * 1, posY + texture->height * 1,
|
||||
// color,
|
||||
// 0.0f, 0.0f, 1.0f, 1.0f
|
||||
// ));
|
||||
// errorOk();
|
||||
|
||||
char_t c;
|
||||
int32_t i = 0;
|
||||
while((c = text[i++]) != '\0') {
|
||||
if(c == '\n') {
|
||||
posX = x;
|
||||
posY += tileset->tileHeight;
|
||||
posY += font->tileset->tileHeight;
|
||||
continue;
|
||||
}
|
||||
|
||||
if(c == ' ') {
|
||||
posX += tileset->tileWidth;
|
||||
posX += font->tileset->tileWidth;
|
||||
continue;
|
||||
}
|
||||
|
||||
errorChain(textDrawChar(
|
||||
posX, posY, c,
|
||||
#if MESH_ENABLE_COLOR
|
||||
color,
|
||||
#endif
|
||||
tileset, texture
|
||||
));
|
||||
posX += tileset->tileWidth;
|
||||
sprite = textGetSprite((vec2){posX, posY}, c, font);
|
||||
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
|
||||
posX += font->tileset->tileWidth;
|
||||
}
|
||||
errorOk();
|
||||
}
|
||||
|
||||
void textMeasure(
|
||||
const char_t *text,
|
||||
const tileset_t *tileset,
|
||||
const font_t *font,
|
||||
int32_t *outWidth,
|
||||
int32_t *outHeight
|
||||
) {
|
||||
@@ -132,28 +134,24 @@ void textMeasure(
|
||||
assertNotNull(outHeight, "Output height pointer cannot be NULL");
|
||||
|
||||
int32_t width = 0;
|
||||
int32_t height = tileset->tileHeight;
|
||||
int32_t height = font->tileset->tileHeight;
|
||||
int32_t lineWidth = 0;
|
||||
|
||||
char_t c;
|
||||
int32_t i = 0;
|
||||
while((c = text[i++]) != '\0') {
|
||||
if(c == '\n') {
|
||||
if(lineWidth > width) {
|
||||
width = lineWidth;
|
||||
}
|
||||
if(lineWidth > width) width = lineWidth;
|
||||
lineWidth = 0;
|
||||
height += tileset->tileHeight;
|
||||
height += font->tileset->tileHeight;
|
||||
continue;
|
||||
}
|
||||
|
||||
lineWidth += tileset->tileWidth;
|
||||
lineWidth += font->tileset->tileWidth;
|
||||
}
|
||||
|
||||
if(lineWidth > width) {
|
||||
width = lineWidth;
|
||||
}
|
||||
if(lineWidth > width) width = lineWidth;
|
||||
|
||||
*outWidth = width;
|
||||
*outHeight = height;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,65 +1,55 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "asset/asset.h"
|
||||
#include "display/texture/texture.h"
|
||||
#include "display/texture/tileset.h"
|
||||
#include "display/text/font.h"
|
||||
#include "display/spritebatch/spritebatch.h"
|
||||
|
||||
#define TEXT_CHAR_START '!'
|
||||
|
||||
extern texture_t FONT_TEXTURE_DEFAULT;
|
||||
extern tileset_t FONT_TILESET_DEFAULT;
|
||||
extern font_t FONT_DEFAULT;
|
||||
|
||||
/**
|
||||
* Initializes the text system.
|
||||
*
|
||||
*
|
||||
* @return Either an error or success result.
|
||||
*/
|
||||
errorret_t textInit(void);
|
||||
|
||||
/**
|
||||
* Disposes of the text system.
|
||||
*
|
||||
*
|
||||
* @return Either an error or success result.
|
||||
*/
|
||||
errorret_t textDispose(void);
|
||||
|
||||
/**
|
||||
* Draws a single character at the specified position.
|
||||
*
|
||||
* @param x The x-coordinate to draw the character at.
|
||||
* @param y The y-coordinate to draw the character at.
|
||||
* @param c The character to draw.
|
||||
* @param color The color to draw the character in.
|
||||
* @param tileset Font tileset to use for rendering.
|
||||
* @param texture Texture containing the font tileset image.
|
||||
* @return Either an error or success result.
|
||||
* Builds a sprite for a single character at the given position.
|
||||
*
|
||||
* @param pos The (x, y) position of the character in screen/world space.
|
||||
* @param c The character to build a sprite for.
|
||||
* @param font Font to use for tile lookup.
|
||||
* @return The populated sprite ready for spriteBatchBuffer.
|
||||
*/
|
||||
errorret_t textDrawChar(
|
||||
const float_t x,
|
||||
const float_t y,
|
||||
spritebatchsprite_t textGetSprite(
|
||||
const vec2 pos,
|
||||
const char_t c,
|
||||
#if MESH_ENABLE_COLOR
|
||||
const color_t color,
|
||||
#endif
|
||||
const tileset_t *tileset,
|
||||
texture_t *texture
|
||||
const font_t *font
|
||||
);
|
||||
|
||||
/**
|
||||
* Draws a string of text at the specified position.
|
||||
*
|
||||
*
|
||||
* @param x The x-coordinate to draw the text at.
|
||||
* @param y The y-coordinate to draw the text at.
|
||||
* @param text The null-terminated string of text to draw.
|
||||
* @param color The color to draw the text in.
|
||||
* @param tileset Font tileset to use for rendering.
|
||||
* @param texture Texture containing the font tileset image.
|
||||
* @param font Font to use for rendering.
|
||||
* @return Either an error or success result.
|
||||
*/
|
||||
errorret_t textDraw(
|
||||
@@ -67,21 +57,20 @@ errorret_t textDraw(
|
||||
const float_t y,
|
||||
const char_t *text,
|
||||
const color_t color,
|
||||
const tileset_t *tileset,
|
||||
texture_t *texture
|
||||
font_t *font
|
||||
);
|
||||
|
||||
/**
|
||||
* Measures the width and height of the given text string when rendered.
|
||||
*
|
||||
*
|
||||
* @param text The null-terminated string of text to measure.
|
||||
* @param tileset Font tileset to use for measurement.
|
||||
* @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.
|
||||
*/
|
||||
void textMeasure(
|
||||
const char_t *text,
|
||||
const tileset_t *tileset,
|
||||
const font_t *font,
|
||||
int32_t *outWidth,
|
||||
int32_t *outHeight
|
||||
);
|
||||
);
|
||||
|
||||
+2
-1
@@ -17,11 +17,12 @@
|
||||
#include <ctype.h>
|
||||
#include <stdarg.h>
|
||||
#include <float.h>
|
||||
#include <memory.h>
|
||||
#include <malloc.h>
|
||||
|
||||
#include <cglm/cglm.h>
|
||||
#include <cglm/types.h>
|
||||
#include <cglm/vec2.h>
|
||||
#include <jerryscript.h>
|
||||
|
||||
#include "duskplatform.h"
|
||||
|
||||
|
||||
+25
-24
@@ -12,35 +12,30 @@
|
||||
#include "locale/localemanager.h"
|
||||
#include "display/display.h"
|
||||
#include "scene/scene.h"
|
||||
#include "cutscene/cutscene.h"
|
||||
#include "asset/asset.h"
|
||||
#include "ui/ui.h"
|
||||
#include "script/scriptmanager.h"
|
||||
#include "ui/uitextbox.h"
|
||||
#include "assert/assert.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "entity/component/physics/entityphysics.h"
|
||||
#include "game/game.h"
|
||||
#include "physics/physicsmanager.h"
|
||||
#include "network/network.h"
|
||||
#include "system/system.h"
|
||||
#include "console/console.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;
|
||||
}
|
||||
#include "script/script.h"
|
||||
#include "item/backpack.h"
|
||||
#include "save/save.h"
|
||||
|
||||
engine_t ENGINE;
|
||||
|
||||
errorret_t engineInit(const int32_t argc, const char_t **argv) {
|
||||
assertInit();
|
||||
memoryZero(&ENGINE, sizeof(engine_t));
|
||||
ENGINE.running = true;
|
||||
ENGINE.argc = argc;
|
||||
ENGINE.argv = argv;
|
||||
ENGINE.version = DUSK_VERSION;
|
||||
|
||||
// Init systems. Order is important.
|
||||
errorChain(systemInit());
|
||||
@@ -48,19 +43,22 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
|
||||
consoleInit();
|
||||
errorChain(inputInit());
|
||||
errorChain(assetInit());
|
||||
// errorChain(saveInit());
|
||||
errorChain(localeManagerInit());
|
||||
errorChain(scriptManagerInit());
|
||||
errorChain(displayInit());
|
||||
errorChain(uiInit());
|
||||
errorChain(uiTextboxInit());
|
||||
errorChain(cutsceneInit());
|
||||
errorChain(sceneInit());
|
||||
entityManagerInit();
|
||||
backpackInit();
|
||||
physicsManagerInit();
|
||||
errorChain(networkInit());
|
||||
errorChain(gameInit());
|
||||
errorChain(scriptInit());
|
||||
|
||||
/* Run the init script. */
|
||||
consolePrint("Engine initialized");
|
||||
errorChain(scriptManagerExecFile("init.js", NULL));
|
||||
|
||||
errorChain(scriptExecFile("init.js"));
|
||||
|
||||
errorOk();
|
||||
}
|
||||
@@ -71,17 +69,17 @@ errorret_t engineUpdate(void) {
|
||||
timeUpdate();
|
||||
inputUpdate();
|
||||
consoleUpdate();
|
||||
entityManagerUpdate();
|
||||
uiUpdate();
|
||||
errorChain(uiTextboxUpdate());
|
||||
physicsManagerUpdate();
|
||||
errorChain(gameUpdate());
|
||||
errorChain(displayUpdate());
|
||||
errorChain(cutsceneUpdate());
|
||||
sceneUpdate();
|
||||
errorChain(assetUpdate());
|
||||
errorChain(scriptUpdate());
|
||||
|
||||
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
|
||||
|
||||
// Scene update occurs last because only after rendering would we want to do
|
||||
// scene switching, refer to sceneSet() for information.
|
||||
errorChain(sceneUpdate());
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
@@ -90,15 +88,18 @@ void engineExit(void) {
|
||||
}
|
||||
|
||||
errorret_t engineDispose(void) {
|
||||
uiTextboxDispose();
|
||||
cutsceneDispose();
|
||||
sceneDispose();
|
||||
errorChain(gameDispose());
|
||||
errorChain(networkDispose());
|
||||
entityManagerDispose();
|
||||
localeManagerDispose();
|
||||
uiDispose();
|
||||
consoleDispose();
|
||||
errorChain(displayDispose());
|
||||
// errorChain(saveDispose());
|
||||
errorChain(scriptDispose());
|
||||
errorChain(assetDispose());
|
||||
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ typedef struct {
|
||||
bool_t running;
|
||||
int32_t argc;
|
||||
const char_t **argv;
|
||||
const char_t *version;
|
||||
} engine_t;
|
||||
|
||||
extern engine_t ENGINE;
|
||||
@@ -35,4 +36,5 @@ errorret_t engineUpdate(void);
|
||||
/**
|
||||
* Shuts down the engine.
|
||||
*/
|
||||
errorret_t engineDispose(void);
|
||||
errorret_t engineDispose(void);
|
||||
|
||||
|
||||
@@ -12,12 +12,13 @@
|
||||
componentdefinition_t COMPONENT_DEFINITIONS[] = {
|
||||
[COMPONENT_TYPE_NULL] = { 0 },
|
||||
|
||||
#define X(enm, type, field, iMethod, dMethod) \
|
||||
#define X(enm, type, field, iMethod, dMethod, rMethod) \
|
||||
[COMPONENT_TYPE_##enm] = { \
|
||||
.enumName = #enm, \
|
||||
.name = #field, \
|
||||
.init = iMethod, \
|
||||
.dispose = dMethod \
|
||||
.dispose = dMethod, \
|
||||
.render = rMethod \
|
||||
},
|
||||
|
||||
#include "componentlist.h"
|
||||
@@ -87,7 +88,7 @@ entityid_t componentGetEntitiesWithComponent(
|
||||
componentid_t used = ENTITY_MANAGER.entitiesWithComponent[
|
||||
type * ENTITY_COUNT_MAX + i
|
||||
];
|
||||
if(used == 0xFF) continue;
|
||||
if(used == COMPONENT_ID_INVALID) continue;
|
||||
assertTrue(
|
||||
ENTITY_MANAGER.components[componentGetIndex(i, used)].type == type,
|
||||
"Component type mismatch in entitiesWithComponent lookup"
|
||||
@@ -101,7 +102,7 @@ entityid_t componentGetEntitiesWithComponent(
|
||||
"Component ID OOB in entitiesWithComponent lookup"
|
||||
);
|
||||
assertTrue(
|
||||
componentGetIndex(i, used) < ENTITY_COUNT_MAX * ENTITY_COMPONENT_COUNT_MAX,
|
||||
componentGetIndex(i,used) < ENTITY_COUNT_MAX*ENTITY_COMPONENT_COUNT_MAX,
|
||||
"Component index OOB in entitiesWithComponent lookup"
|
||||
);
|
||||
assertTrue(
|
||||
@@ -114,6 +115,19 @@ entityid_t componentGetEntitiesWithComponent(
|
||||
return written;
|
||||
}
|
||||
|
||||
errorret_t componentRenderAll(void) {
|
||||
for(entityid_t eid = 0; eid < ENTITY_COUNT_MAX; eid++) {
|
||||
if(!(ENTITY_MANAGER.entities[eid].state & ENTITY_STATE_ACTIVE)) continue;
|
||||
for(componentid_t cid = 0; cid < ENTITY_COMPONENT_COUNT_MAX; cid++) {
|
||||
component_t *cmp = &ENTITY_MANAGER.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
|
||||
|
||||
@@ -8,13 +8,13 @@
|
||||
#pragma once
|
||||
#include "entitybase.h"
|
||||
|
||||
#define X(enumName, type, field, init, dispose) \
|
||||
#define X(enumName, type, field, init, dispose, render) \
|
||||
// do nothing
|
||||
#include "componentlist.h"
|
||||
#undef X
|
||||
|
||||
typedef union {
|
||||
#define X(enumName, type, field, init, dispose) type field;
|
||||
#define X(enumName, type, field, init, dispose, render) type field;
|
||||
#include "componentlist.h"
|
||||
#undef X
|
||||
} componentdata_t;
|
||||
@@ -24,12 +24,13 @@ typedef struct {
|
||||
const char_t *name;
|
||||
void (*init)(const entityid_t, const componentid_t);
|
||||
void (*dispose)(const entityid_t, const componentid_t);
|
||||
errorret_t (*render)(const entityid_t, const componentid_t);
|
||||
} componentdefinition_t;
|
||||
|
||||
typedef enum {
|
||||
COMPONENT_TYPE_NULL,
|
||||
|
||||
#define X(enumName, type, field, init, dispose) \
|
||||
#define X(enumName, type, field, init, dispose, render) \
|
||||
COMPONENT_TYPE_##enumName,
|
||||
#include "componentlist.h"
|
||||
#undef X
|
||||
@@ -100,11 +101,20 @@ entityid_t componentGetEntitiesWithComponent(
|
||||
|
||||
/**
|
||||
* Disposes of a component for the entity with component ID.
|
||||
*
|
||||
*
|
||||
* @param entityId The entity ID.
|
||||
* @param componentId The component ID.
|
||||
*/
|
||||
void componentDispose(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
errorret_t componentRenderAll(void);
|
||||
@@ -5,4 +5,4 @@
|
||||
|
||||
add_subdirectory(display)
|
||||
add_subdirectory(physics)
|
||||
add_subdirectory(script)
|
||||
add_subdirectory(trigger)
|
||||
@@ -8,6 +8,5 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
entityposition.c
|
||||
entitycamera.c
|
||||
entitymesh.c
|
||||
entitymaterial.c
|
||||
entityrenderable.c
|
||||
)
|
||||
@@ -16,7 +16,7 @@ void entityCameraInit(const entityid_t ent, const componentid_t comp) {
|
||||
ent, comp, COMPONENT_TYPE_CAMERA
|
||||
);
|
||||
cam->nearClip = 0.1f;
|
||||
cam->farClip = 100.0f;
|
||||
cam->farClip = 5000.0f;
|
||||
cam->projType = ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE;
|
||||
cam->perspective.fov = glm_rad(45.0f);
|
||||
}
|
||||
@@ -66,28 +66,53 @@ entityid_t entityCameraGetCurrent(void) {
|
||||
entityid_t count = componentGetEntitiesWithComponent(
|
||||
COMPONENT_TYPE_CAMERA, camEnts, camComps
|
||||
);
|
||||
if(count == 0) return ENTITY_COUNT_MAX;
|
||||
if(count == 0) return ENTITY_ID_INVALID;
|
||||
return camEnts[0];
|
||||
}
|
||||
|
||||
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->transform[0][2];
|
||||
float_t fz = -pos->transform[2][2];
|
||||
// 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 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);
|
||||
}
|
||||
|
||||
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->transform[0][0];
|
||||
float_t rz = pos->transform[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;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user