Compare commits
81
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5cf81aa238 | ||
|
|
b3623c84a5 | ||
|
|
45c1f9004b | ||
|
|
845a395ff1 | ||
|
|
f63653c307 | ||
|
|
5b523c68a7 | ||
|
|
03efbe0681 | ||
|
|
cebd3d81e7 | ||
|
|
de53bebeb8 | ||
|
|
6ccaedd48f | ||
|
|
707856fcf2 | ||
|
|
3c3dc35e1d | ||
|
|
f9820bd226 | ||
|
|
fe2ef92ef3 | ||
|
|
9364768397 | ||
|
|
9c28d5a3b7 | ||
|
|
d5078b978c | ||
|
|
d49594d3fb | ||
|
|
619ce932f9 | ||
|
|
b564d0b1c1 | ||
|
|
fc1fc9f170 | ||
|
|
fd5bcfae90 | ||
|
|
3ee0a53688 | ||
|
|
62c081ecf2 | ||
|
|
d9beb647c1 | ||
|
|
f8f8a80a21 | ||
|
|
ac8023d50f | ||
|
|
769f2f5702 | ||
|
|
2f6839bcc4 | ||
|
|
d37109f5f7 | ||
|
|
15bd9fc43c | ||
|
|
8049e90853 | ||
|
|
e47a2c3e5c | ||
|
|
9512c22e1f | ||
|
|
8a77001016 | ||
|
|
9b0214ee55 | ||
|
|
7ad735552a | ||
|
|
ea35472ef8 | ||
|
|
50c5621d8a | ||
|
|
da275cfd52 | ||
|
|
0f4ee5d965 | ||
|
|
af8c0f5ccd | ||
|
|
8ea370a1d1 | ||
|
|
fcf0de72af | ||
|
|
320c5e6ce5 | ||
|
|
7a858cc424 | ||
|
|
c0292842a5 | ||
|
|
717902462b | ||
|
|
1d73b9d224 | ||
|
|
51f262efa0 | ||
|
|
a6e4e3f71f | ||
|
|
4387d223b9 | ||
|
|
00bfaf6360 | ||
|
|
709bd7be52 | ||
|
|
80f4348e21 | ||
|
|
e630827b34 | ||
|
|
106d9b0fc0 | ||
|
|
4a26f79945 | ||
|
|
1a199f6ce3 | ||
|
|
ec59e77867 | ||
|
|
cb28d2b611 | ||
|
|
27b6ddf5cb | ||
|
|
475c865e33 | ||
|
|
0b4ba062bb | ||
|
|
28f5e66662 | ||
|
|
e225a076f0 | ||
|
|
774c8ad0f8 | ||
|
|
52d1e7414d | ||
|
|
af4cb53e5f | ||
|
|
c019271e12 | ||
|
|
82ae2bce9d | ||
|
|
092e259a06 | ||
|
|
08b4bbfe91 | ||
|
|
560c51cf27 | ||
|
|
674f86b18a | ||
|
|
e3f10e0926 | ||
|
|
d7223d7387 | ||
|
|
45331c2a60 | ||
|
|
33f50a2c69 | ||
|
|
6c8e4d5cbd | ||
|
|
3b7215876a |
No files matched your search
@@ -107,3 +107,4 @@ yarn.lock
|
|||||||
/assets/test
|
/assets/test
|
||||||
/tools_old
|
/tools_old
|
||||||
/assets/test.png
|
/assets/test.png
|
||||||
|
/assets/audio/boa.mp3
|
||||||
+33
-15
@@ -8,7 +8,10 @@ cmake_minimum_required(VERSION 3.13)
|
|||||||
|
|
||||||
set(CMAKE_C_STANDARD 11)
|
set(CMAKE_C_STANDARD 11)
|
||||||
set(CMAKE_C_STANDARD_REQUIRED ON)
|
set(CMAKE_C_STANDARD_REQUIRED ON)
|
||||||
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)
|
set(CMAKE_MODULE_PATH
|
||||||
|
${CMAKE_MODULE_PATH}
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules
|
||||||
|
)
|
||||||
cmake_policy(SET CMP0079 NEW)
|
cmake_policy(SET CMP0079 NEW)
|
||||||
# set(FETCHCONTENT_UPDATES_DISCONNECTED ON)
|
# set(FETCHCONTENT_UPDATES_DISCONNECTED ON)
|
||||||
|
|
||||||
@@ -18,7 +21,9 @@ option(DUSK_NETWORK "Enable network support" ON)
|
|||||||
set(DUSK_GAME_NAME "Dusk" CACHE STRING "Game display name")
|
set(DUSK_GAME_NAME "Dusk" CACHE STRING "Game display name")
|
||||||
set(DUSK_GAME_AUTHOR "YourWishes" CACHE STRING "Game author / coder")
|
set(DUSK_GAME_AUTHOR "YourWishes" CACHE STRING "Game author / coder")
|
||||||
set(DUSK_GAME_SHORT_DESCRIPTION "Dusk game" CACHE STRING "One-line description")
|
set(DUSK_GAME_SHORT_DESCRIPTION "Dusk game" CACHE STRING "One-line description")
|
||||||
set(DUSK_GAME_LONG_DESCRIPTION "No description yet." CACHE STRING "Full description")
|
set(DUSK_GAME_LONG_DESCRIPTION
|
||||||
|
"No description yet." CACHE STRING "Full description"
|
||||||
|
)
|
||||||
|
|
||||||
# Prep cache
|
# Prep cache
|
||||||
set(DUSK_CACHE_TARGET "dusk-target")
|
set(DUSK_CACHE_TARGET "dusk-target")
|
||||||
@@ -32,13 +37,19 @@ set(DUSK_TEMP_DIR "${DUSK_BUILD_DIR}/temp")
|
|||||||
set(DUSK_TOOLS_DIR "${DUSK_ROOT_DIR}/tools")
|
set(DUSK_TOOLS_DIR "${DUSK_ROOT_DIR}/tools")
|
||||||
set(DUSK_DATA_DIR "${DUSK_ROOT_DIR}/data")
|
set(DUSK_DATA_DIR "${DUSK_ROOT_DIR}/data")
|
||||||
set(DUSK_ASSETS_DIR "${DUSK_ROOT_DIR}/assets")
|
set(DUSK_ASSETS_DIR "${DUSK_ROOT_DIR}/assets")
|
||||||
set(DUSK_BUILT_ASSETS_DIR "${DUSK_BUILD_DIR}/built_assets" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
set(DUSK_BUILT_ASSETS_DIR "${DUSK_BUILD_DIR}/built_assets"
|
||||||
|
CACHE INTERNAL ${DUSK_CACHE_TARGET}
|
||||||
|
)
|
||||||
set(DUSK_GENERATED_HEADERS_DIR "${DUSK_BUILD_DIR}/generated")
|
set(DUSK_GENERATED_HEADERS_DIR "${DUSK_BUILD_DIR}/generated")
|
||||||
set(DUSK_BUILD_BINARY ${DUSK_BUILD_DIR}/Dusk CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
set(DUSK_BUILD_BINARY ${DUSK_BUILD_DIR}/Dusk
|
||||||
|
CACHE INTERNAL ${DUSK_CACHE_TARGET}
|
||||||
|
)
|
||||||
set(DUSK_ASSETS "" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
set(DUSK_ASSETS "" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||||
set(DUSK_LIBRARY_TARGET_NAME "DuskCore" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
set(DUSK_LIBRARY_TARGET_NAME "DuskCore" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||||
set(DUSK_BINARY_TARGET_NAME "Dusk" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
set(DUSK_BINARY_TARGET_NAME "Dusk" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||||
set(DUSK_ASSETS_ZIP "${DUSK_BUILD_DIR}/dusk.dsk" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
set(DUSK_ASSETS_ZIP "${DUSK_BUILD_DIR}/dusk.dsk"
|
||||||
|
CACHE INTERNAL ${DUSK_CACHE_TARGET}
|
||||||
|
)
|
||||||
|
|
||||||
if(NOT DEFINED DUSK_TARGET_SYSTEM)
|
if(NOT DEFINED DUSK_TARGET_SYSTEM)
|
||||||
set(DUSK_TARGET_SYSTEM "linux")
|
set(DUSK_TARGET_SYSTEM "linux")
|
||||||
@@ -73,7 +84,9 @@ if(DUSK_BUILD_TESTS)
|
|||||||
${DUSK_LIBRARY_TARGET_NAME}
|
${DUSK_LIBRARY_TARGET_NAME}
|
||||||
)
|
)
|
||||||
else()
|
else()
|
||||||
set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}"
|
||||||
|
CACHE INTERNAL ${DUSK_CACHE_TARGET}
|
||||||
|
)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
if(NOT DEFINED DUSK_VERSION)
|
if(NOT DEFINED DUSK_VERSION)
|
||||||
@@ -122,16 +135,21 @@ if(DUSK_BUILD_TESTS)
|
|||||||
add_subdirectory(test)
|
add_subdirectory(test)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
# Build assets
|
# Build assets. Runs unconditionally on every build (rather than being
|
||||||
file(GLOB_RECURSE DUSK_ASSET_FILES CONFIGURE_DEPENDS "${DUSK_ASSETS_DIR}/*")
|
# gated behind a custom_command's file-level DEPENDS list) because
|
||||||
add_custom_command(
|
# CONFIGURE_DEPENDS globs only pick up added/removed files on the next
|
||||||
OUTPUT "${DUSK_ASSETS_ZIP}"
|
# CMake configure, so that approach could miss/lag a rebuild behind an
|
||||||
|
# asset edit. tools.asset.pack itself decides whether anything actually
|
||||||
|
# changed (see its manifest check) and no-ops quickly when nothing did,
|
||||||
|
# so this stays cheap on a build where assets are untouched.
|
||||||
|
add_custom_target(DUSK_ASSETS_BUILT ALL
|
||||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${DUSK_ASSETS_DIR}"
|
COMMAND ${CMAKE_COMMAND} -E make_directory "${DUSK_ASSETS_DIR}"
|
||||||
COMMAND ${CMAKE_COMMAND} -E rm -f "${DUSK_ASSETS_ZIP}"
|
COMMAND ${Python3_EXECUTABLE} -m tools.asset.pack
|
||||||
COMMAND ${CMAKE_COMMAND} -E tar "cf" "${DUSK_ASSETS_ZIP}" --format=zip -- .
|
--input "${DUSK_ASSETS_DIR}"
|
||||||
WORKING_DIRECTORY "${DUSK_ASSETS_DIR}"
|
--output "${DUSK_ASSETS_ZIP}"
|
||||||
DEPENDS ${DUSK_ASSET_FILES}
|
WORKING_DIRECTORY "${DUSK_ROOT_DIR}"
|
||||||
|
BYPRODUCTS "${DUSK_ASSETS_ZIP}"
|
||||||
|
COMMENT "Packing assets into dusk.dsk"
|
||||||
VERBATIM
|
VERBATIM
|
||||||
)
|
)
|
||||||
add_custom_target(DUSK_ASSETS_BUILT DEPENDS "${DUSK_ASSETS_ZIP}")
|
|
||||||
add_dependencies(${DUSK_LIBRARY_TARGET_NAME} DUSK_ASSETS_BUILT)
|
add_dependencies(${DUSK_LIBRARY_TARGET_NAME} DUSK_ASSETS_BUILT)
|
||||||
@@ -9,15 +9,18 @@ following packages, depending on your system;
|
|||||||
|
|
||||||
Fedora;
|
Fedora;
|
||||||
```
|
```
|
||||||
sudo dnf install git make gcc cmake python python-polib python3-pillow python3-dotenv python3-numpy python-qt5 python3-pyopengl SDL2-devel zlib-devel libzip-devel bzip2-devel openssl-devel lzma-sdk-devel xz xz-devel lua-devel
|
sudo dnf install git make gcc cmake python python-polib python3-pillow python3-dotenv python3-numpy python-qt5 python3-pyopengl SDL2-devel zlib-devel libzip-devel bzip2-devel openssl-devel lzma-sdk-devel xz xz-devel lua-devel libmad-devel
|
||||||
```
|
```
|
||||||
|
`libmad-devel` (used for MP3 decoding) is GPL-licensed and ships in the
|
||||||
|
[RPM Fusion](https://rpmfusion.org/) free repository rather than Fedora's
|
||||||
|
base repos - make sure RPM Fusion is enabled first.
|
||||||
|
|
||||||
Ubuntu;
|
Ubuntu;
|
||||||
```
|
```
|
||||||
sudo apt-get install git build-essential gcc python python-polib python3-pillow python3-dotenv python3-numpy python3-pyqt5 python3-opengl
|
sudo apt-get install git build-essential gcc python python-polib python3-pillow python3-dotenv python3-numpy python3-pyqt5 python3-opengl libmad0-dev
|
||||||
```
|
```
|
||||||
|
|
||||||
Arch Linux;
|
Arch Linux;
|
||||||
```
|
```
|
||||||
sudo pacman -S git base-devel gcc python python-polib python-pillow python-dotenv python-numpy python-pyqt5 python-opengl
|
sudo pacman -S git base-devel gcc python python-polib python-pillow python-dotenv python-numpy python-pyqt5 python-opengl libmad
|
||||||
```
|
```
|
||||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,68 @@
|
|||||||
|
{
|
||||||
|
"items": [
|
||||||
|
// First thing, try and find a save device, used for settings and what not.
|
||||||
|
{
|
||||||
|
"type": "MODAL",
|
||||||
|
"title": "initial.checking_save.title",
|
||||||
|
"message": "initial.checking_save.message"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "WAIT",
|
||||||
|
"seconds": 0.2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "SAVE_DEVICE_CHECK",
|
||||||
|
"successMarker": "CONTINUE",
|
||||||
|
"failureMarker": "SAVE_DEVICE_NOT_FOUND"
|
||||||
|
},
|
||||||
|
|
||||||
|
// No save device found
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "SAVE_DEVICE_NOT_FOUND"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "MODAL_CLOSE"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "MODAL_OPTIONS_MARKERS",
|
||||||
|
"title": "initial.no_device.title",
|
||||||
|
"message": "initial.no_device.message",
|
||||||
|
"options": [
|
||||||
|
{
|
||||||
|
"text": "initial.no_device.retry",
|
||||||
|
"marker": "SAVE_DEVICE_RETRY"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "initial.no_device.continue",
|
||||||
|
"marker": "CONTINUE"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
// Save device not found, user to retry, just close modal and loop
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "SAVE_DEVICE_RETRY"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "MODAL_CLOSE"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "RESTART"
|
||||||
|
},
|
||||||
|
|
||||||
|
// Save device found (or continuing without one)
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "CONTINUE"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "MODAL_CLOSE"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "CUTSCENE",
|
||||||
|
"name": "main_menu"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
{
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "MAIN_MENU_IDLE"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "UI_SHOW",
|
||||||
|
"name": "main_menu"
|
||||||
|
},
|
||||||
|
|
||||||
|
// Options button goes here - no options screen yet, so this is just
|
||||||
|
// an alias landing right back on the idle loop below.
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "OPTIONS"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "IDLE"
|
||||||
|
},
|
||||||
|
|
||||||
|
// New Game button goes here.
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "NEW_GAME"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "MODAL",
|
||||||
|
"title": "main_menu.checking_save.title",
|
||||||
|
"message": "main_menu.checking_save.message"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "WAIT",
|
||||||
|
"seconds": 0.2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "SAVE_DEVICE_CHECK",
|
||||||
|
"successMarker": "SAVE_DEVICE_FOUND",
|
||||||
|
"failureMarker": "SAVE_DEVICE_NOT_FOUND"
|
||||||
|
},
|
||||||
|
|
||||||
|
// Save device not found
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "SAVE_DEVICE_NOT_FOUND"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "MODAL_CLOSE"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "MODAL_OPTIONS_MARKERS",
|
||||||
|
"title": "main_menu.no_device.title",
|
||||||
|
"message": "main_menu.no_device.message",
|
||||||
|
"options": [
|
||||||
|
{
|
||||||
|
"text": "main_menu.no_device.retry",
|
||||||
|
"marker": "NEW_GAME"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "main_menu.no_device.continue",
|
||||||
|
"marker": "SAVE_DEVICE_FOUND"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
// Save data failed to load (e.g. corrupt/unreadable) - only option is
|
||||||
|
// to retry, no "continue without saving" here since we already know a
|
||||||
|
// device is present.
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "LOAD_ERROR"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "MODAL_OPTIONS_MARKERS",
|
||||||
|
"title": "main_menu.save_load_error.title",
|
||||||
|
"message": "main_menu.save_load_error.message",
|
||||||
|
"options": [
|
||||||
|
{
|
||||||
|
"text": "main_menu.save_load_error.retry",
|
||||||
|
"marker": "NEW_GAME"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
// Quit Game button goes here. Cancelling jumps back to
|
||||||
|
// MAIN_MENU_IDLE; confirming falls through to QUIT_GAME, which
|
||||||
|
// ends the process directly.
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "QUIT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "MODAL_OPTIONS_MARKERS",
|
||||||
|
"title": "main_menu.quit_confirm",
|
||||||
|
"options": [
|
||||||
|
{
|
||||||
|
"text": "ui.confirm.confirm",
|
||||||
|
"marker": "QUIT_CONFIRMED"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "ui.confirm.cancel",
|
||||||
|
"marker": "MAIN_MENU_IDLE"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "QUIT_CONFIRMED"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "QUIT_GAME"
|
||||||
|
},
|
||||||
|
|
||||||
|
// main menu just listens for cutscene ending to show the select save modal
|
||||||
|
// so we have that here.
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "SAVE_DEVICE_FOUND"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "MODAL_CLOSE"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "SAVE_LOAD_ALL_SLOTS",
|
||||||
|
"successMarker": "LOADED",
|
||||||
|
"failureMarker": "LOAD_ERROR"
|
||||||
|
},
|
||||||
|
|
||||||
|
// Must be the very last item - falling off the end here is what
|
||||||
|
// completes the cutscene and fires uiMainMenuOpenSelectSave (see
|
||||||
|
// cutsceneSystemSetOnComplete in ui/screen/mainmenu/uimainmenu.c).
|
||||||
|
// Placing this anywhere earlier would fall through into whatever
|
||||||
|
// comes next instead (e.g. the QUIT block, if placed just before it).
|
||||||
|
{
|
||||||
|
"type": "MARKER",
|
||||||
|
"name": "LOADED"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -5,11 +5,107 @@ msgstr ""
|
|||||||
"Content-Type: text/plain; charset=UTF-8\n"
|
"Content-Type: text/plain; charset=UTF-8\n"
|
||||||
"Plural-Forms: nplurals=4; plural=(n==1 ? 0 : n==2 ? 1 : (n<7 ? 2 : 3));\n"
|
"Plural-Forms: nplurals=4; plural=(n==1 ? 0 : n==2 ? 1 : (n<7 ? 2 : 3));\n"
|
||||||
|
|
||||||
|
# Initial Scene
|
||||||
|
msgid "initial.checking_save.title"
|
||||||
|
msgstr "Checking for save data"
|
||||||
|
|
||||||
|
msgid "initial.checking_save.message"
|
||||||
|
msgstr "Please wait..."
|
||||||
|
|
||||||
|
msgid "initial.no_device.title"
|
||||||
|
msgstr "No Save Device Found"
|
||||||
|
|
||||||
|
msgid "initial.no_device.message"
|
||||||
|
msgstr "Could not find a save device, ensure it is connected and try again. You can continue, but progress will not be saved."
|
||||||
|
|
||||||
|
msgid "initial.no_device.retry"
|
||||||
|
msgstr "Try again"
|
||||||
|
|
||||||
|
msgid "initial.no_device.continue"
|
||||||
|
msgstr "Continue without saving"
|
||||||
|
|
||||||
|
|
||||||
|
# Main Menu Scene
|
||||||
|
msgid "main_menu.start_game"
|
||||||
|
msgstr "Start Game"
|
||||||
|
|
||||||
|
msgid "main_menu.options"
|
||||||
|
msgstr "Options"
|
||||||
|
|
||||||
|
msgid "main_menu.quit"
|
||||||
|
msgstr "Quit Game"
|
||||||
|
|
||||||
|
msgid "main_menu.quit_confirm"
|
||||||
|
msgstr "Are you sure you want to quit?"
|
||||||
|
|
||||||
|
msgid "main_menu.checking_save.title"
|
||||||
|
msgstr "Checking for save data"
|
||||||
|
|
||||||
|
msgid "main_menu.checking_save.message"
|
||||||
|
msgstr "Please wait..."
|
||||||
|
|
||||||
|
msgid "main_menu.no_device.title"
|
||||||
|
msgstr "No Save Device Found"
|
||||||
|
|
||||||
|
msgid "main_menu.no_device.message"
|
||||||
|
msgstr "Could not find a save device, ensure it is connected and try again. You can continue, but progress will not be saved."
|
||||||
|
|
||||||
|
msgid "main_menu.no_device.retry"
|
||||||
|
msgstr "Try again"
|
||||||
|
|
||||||
|
msgid "main_menu.no_device.continue"
|
||||||
|
msgstr "Continue without saving"
|
||||||
|
|
||||||
|
msgid "main_menu.save_load_error.title"
|
||||||
|
msgstr "Error"
|
||||||
|
|
||||||
|
msgid "main_menu.save_load_error.message"
|
||||||
|
msgstr "Failed to load save data. Please try again."
|
||||||
|
|
||||||
|
msgid "main_menu.save_load_error.retry"
|
||||||
|
msgstr "Try Again"
|
||||||
|
|
||||||
|
|
||||||
|
# Select Save Screen
|
||||||
|
msgid "ui.select_save.title"
|
||||||
|
msgstr "Select Save"
|
||||||
|
|
||||||
|
msgid "ui.select_save.empty"
|
||||||
|
msgstr "Empty Slot"
|
||||||
|
|
||||||
|
msgid "ui.select_save.slot_format"
|
||||||
|
msgstr "%s Lv.%d %s"
|
||||||
|
|
||||||
|
msgid "ui.select_save.delete_mode"
|
||||||
|
msgstr "Delete a Save"
|
||||||
|
|
||||||
|
msgid "ui.select_save.delete_confirm"
|
||||||
|
msgstr "Are you sure you want to delete this save?"
|
||||||
|
|
||||||
|
msgid "ui.select_save.name_title"
|
||||||
|
msgstr "Enter game save file name"
|
||||||
|
|
||||||
|
msgid "ui.save_slot.number_format"
|
||||||
|
msgstr "Slot %d"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#: ui/menu.c:10
|
#: ui/menu.c:10
|
||||||
msgid "ui.title"
|
msgid "ui.title"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
"Welcome"
|
"Welcome"
|
||||||
|
|
||||||
|
msgid "save.linux.mkdirp_failed"
|
||||||
|
msgstr "Failed to create save directory, check the disk is not full or write-protected."
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
msgid "ui.settings.tabs.general"
|
msgid "ui.settings.tabs.general"
|
||||||
msgstr "General"
|
msgstr "General"
|
||||||
@@ -112,6 +208,58 @@ msgstr "Yes"
|
|||||||
msgid "ui.initial.create_save.no"
|
msgid "ui.initial.create_save.no"
|
||||||
msgstr "No"
|
msgstr "No"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/uiconfirm.c
|
||||||
|
msgid "ui.confirm.confirm"
|
||||||
|
msgstr "Confirm"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/uiconfirm.c
|
||||||
|
msgid "ui.confirm.cancel"
|
||||||
|
msgstr "Cancel"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/battle/uibattlemenu.c
|
||||||
|
msgid "ui.battle.menu.attack"
|
||||||
|
msgstr "Attack"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/battle/uibattlemenu.c
|
||||||
|
msgid "ui.battle.menu.flee"
|
||||||
|
msgstr "Flee"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/battle/uibattlemenu.c
|
||||||
|
msgid "ui.battle.menu.target_format"
|
||||||
|
msgstr "Enemy %u (%u/%u HP)"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/battle/uibattlehud.c
|
||||||
|
msgid "ui.battle.hud.hp_format"
|
||||||
|
msgstr "HP %u/%u"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/battle/uibattlehud.c
|
||||||
|
msgid "ui.battle.hud.mp_format"
|
||||||
|
msgstr "MP %u/%u"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettingsaudio.c
|
||||||
|
msgid "ui.settings.audio.placeholder"
|
||||||
|
msgstr "No audio settings yet"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettingsdisplay.c
|
||||||
|
msgid "ui.settings.display.placeholder"
|
||||||
|
msgstr "No display settings yet"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettingsinput.c
|
||||||
|
msgid "ui.settings.input.placeholder"
|
||||||
|
msgstr "No input settings yet"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/backpack/uibackpack.c
|
||||||
|
msgid "ui.backpack.category_format"
|
||||||
|
msgstr "Category %u"
|
||||||
|
|
||||||
|
#: src/dusk/ui/overlay/uiloading.c
|
||||||
|
msgid "ui.loading.text"
|
||||||
|
msgstr "loading"
|
||||||
|
|
||||||
|
#: src/dusk/ui/overlay/uiautosave.c
|
||||||
|
msgid "ui.autosave.saving"
|
||||||
|
msgstr "SAVING"
|
||||||
|
|
||||||
msgid "item.potion.name"
|
msgid "item.potion.name"
|
||||||
msgstr "Potion"
|
msgstr "Potion"
|
||||||
|
|
||||||
|
|||||||
@@ -1,126 +0,0 @@
|
|||||||
msgid ""
|
|
||||||
msgstr ""
|
|
||||||
"Project-Id-Version: ExampleApp 1.0\n"
|
|
||||||
"Language: es\n"
|
|
||||||
"Content-Type: text/plain; charset=UTF-8\n"
|
|
||||||
"Plural-Forms: nplurals=2; plural=(n==1 ? 0 : 1);\n"
|
|
||||||
|
|
||||||
#: ui/menu.c:10
|
|
||||||
msgid "ui.title"
|
|
||||||
msgstr ""
|
|
||||||
"Bienvenido"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
|
||||||
msgid "ui.settings.tabs.general"
|
|
||||||
msgstr "General"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
|
||||||
msgid "ui.settings.tabs.input"
|
|
||||||
msgstr "Entrada"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
|
||||||
msgid "ui.settings.tabs.display"
|
|
||||||
msgstr "Pantalla"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
|
||||||
msgid "ui.settings.tabs.audio"
|
|
||||||
msgstr "Audio"
|
|
||||||
|
|
||||||
msgid "ui.settings.input.deadzone"
|
|
||||||
msgstr "Deadzone"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
|
|
||||||
msgid "ui.settings.general.language"
|
|
||||||
msgstr "Idioma"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
|
|
||||||
msgid "ui.settings.general.language_detail"
|
|
||||||
msgstr "Se aplica después de reiniciar la aplicación."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
|
||||||
msgid "ui.settings.apply"
|
|
||||||
msgstr "Aplicar"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/uiconfirm.c
|
|
||||||
msgid "ui.confirm.discard_changes"
|
|
||||||
msgstr "¿Descartar los cambios no guardados?"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.characters"
|
|
||||||
msgstr "Personajes"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.items"
|
|
||||||
msgstr "Objetos"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.settings"
|
|
||||||
msgstr "Configuración"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save"
|
|
||||||
msgstr "Guardar"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_success"
|
|
||||||
msgstr "Partida guardada."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_cancelled"
|
|
||||||
msgstr "Guardado cancelado."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_unavailable"
|
|
||||||
msgstr "No se puede guardar: no se encontró ningún dispositivo de guardado."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_temporary"
|
|
||||||
msgstr "Esta sesión es temporal - no se encontró ningún dispositivo de guardado, por lo que guardar está deshabilitado."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_create_confirm"
|
|
||||||
msgstr "No se encontraron datos guardados. ¿Crear una partida nueva?"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_failed_format"
|
|
||||||
msgstr "Error al guardar: %s"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_check_failed_format"
|
|
||||||
msgstr "No se puede guardar: %s"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialnocard.c
|
|
||||||
msgid "ui.initial.no_card.message"
|
|
||||||
msgstr "No se encontró ningún dispositivo de guardado. Puedes continuar, pero\nel progreso no se guardará."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialnocard.c
|
|
||||||
msgid "ui.initial.no_card.retry"
|
|
||||||
msgstr "Reintentar"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialnocard.c
|
|
||||||
msgid "ui.initial.no_card.continue"
|
|
||||||
msgstr "Continuar de todos modos"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
|
|
||||||
msgid "ui.initial.create_save.message"
|
|
||||||
msgstr "No se encontraron datos guardados. ¿Crear una partida nueva?"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
|
|
||||||
msgid "ui.initial.create_save.yes"
|
|
||||||
msgstr "Sí"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
|
|
||||||
msgid "ui.initial.create_save.no"
|
|
||||||
msgstr "No"
|
|
||||||
|
|
||||||
#: src/dusk/rpg/item/item.json
|
|
||||||
msgid "item.potion.name"
|
|
||||||
msgstr "Poción"
|
|
||||||
|
|
||||||
#: src/dusk/rpg/item/item.json
|
|
||||||
msgid "item.potato.name"
|
|
||||||
msgstr "Papa"
|
|
||||||
|
|
||||||
#: src/dusk/rpg/item/item.json
|
|
||||||
msgid "item.apple.name"
|
|
||||||
msgstr "Manzana"
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
msgid ""
|
|
||||||
msgstr ""
|
|
||||||
"Project-Id-Version: ExampleApp 1.0\n"
|
|
||||||
"Language: ja\n"
|
|
||||||
"Content-Type: text/plain; charset=UTF-8\n"
|
|
||||||
"Plural-Forms: nplurals=1; plural=(0);\n"
|
|
||||||
|
|
||||||
#: ui/menu.c:10
|
|
||||||
msgid "ui.title"
|
|
||||||
msgstr ""
|
|
||||||
"歓迎"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
|
||||||
msgid "ui.settings.tabs.general"
|
|
||||||
msgstr "一般"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
|
||||||
msgid "ui.settings.tabs.input"
|
|
||||||
msgstr "入力"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
|
||||||
msgid "ui.settings.tabs.display"
|
|
||||||
msgstr "表示"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
|
||||||
msgid "ui.settings.tabs.audio"
|
|
||||||
msgstr "オーディオ"
|
|
||||||
|
|
||||||
msgid "ui.settings.input.deadzone"
|
|
||||||
msgstr "デッドゾーン"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
|
|
||||||
msgid "ui.settings.general.language"
|
|
||||||
msgstr "言語"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
|
|
||||||
msgid "ui.settings.general.language_detail"
|
|
||||||
msgstr "アプリケーションを再起動すると適用されます。"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
|
||||||
msgid "ui.settings.apply"
|
|
||||||
msgstr "適用"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/uiconfirm.c
|
|
||||||
msgid "ui.confirm.discard_changes"
|
|
||||||
msgstr "未保存の変更を破棄しますか?"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.characters"
|
|
||||||
msgstr "キャラクター"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.items"
|
|
||||||
msgstr "アイテム"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.settings"
|
|
||||||
msgstr "設定"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save"
|
|
||||||
msgstr "セーブ"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_success"
|
|
||||||
msgstr "セーブしました。"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_cancelled"
|
|
||||||
msgstr "セーブをキャンセルしました。"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_unavailable"
|
|
||||||
msgstr "セーブできません - セーブデバイスが見つかりません。"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_temporary"
|
|
||||||
msgstr "このセッションは一時的です - セーブデバイスが見つからなかったため、セーブは無効になっています。"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_create_confirm"
|
|
||||||
msgstr "セーブデータが見つかりません。新しいセーブを作成しますか?"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_failed_format"
|
|
||||||
msgstr "セーブに失敗しました: %s"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_check_failed_format"
|
|
||||||
msgstr "セーブできません: %s"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialnocard.c
|
|
||||||
msgid "ui.initial.no_card.message"
|
|
||||||
msgstr "セーブデバイスが見つかりません。続行できますが、\n進行状況は保存されません。"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialnocard.c
|
|
||||||
msgid "ui.initial.no_card.retry"
|
|
||||||
msgstr "再試行"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialnocard.c
|
|
||||||
msgid "ui.initial.no_card.continue"
|
|
||||||
msgstr "続行する"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
|
|
||||||
msgid "ui.initial.create_save.message"
|
|
||||||
msgstr "セーブデータが見つかりません。新しいセーブを作成しますか?"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
|
|
||||||
msgid "ui.initial.create_save.yes"
|
|
||||||
msgstr "はい"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
|
|
||||||
msgid "ui.initial.create_save.no"
|
|
||||||
msgstr "いいえ"
|
|
||||||
|
|
||||||
#: src/dusk/rpg/item/item.json
|
|
||||||
msgid "item.potion.name"
|
|
||||||
msgstr "ポーション"
|
|
||||||
|
|
||||||
#: src/dusk/rpg/item/item.json
|
|
||||||
msgid "item.potato.name"
|
|
||||||
msgstr "ジャガイモ"
|
|
||||||
|
|
||||||
#: src/dusk/rpg/item/item.json
|
|
||||||
msgid "item.apple.name"
|
|
||||||
msgstr "リンゴ"
|
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Copyright (c) 2026 Dominic Masters
|
||||||
|
#
|
||||||
|
# This software is released under the MIT License.
|
||||||
|
# https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
|
# NOTE: libmad itself is GPL-licensed (see https://www.underbit.com/products/mad/),
|
||||||
|
# not MIT like the rest of this project. Any binary linking it must comply
|
||||||
|
# with the GPL - a deliberate tradeoff accepted for MP3 decode correctness
|
||||||
|
# (see audiostreammp3decodersw.c's own comment on why minimp3 wasn't enough).
|
||||||
|
|
||||||
|
find_path(LIBMAD_INCLUDE_DIR NAMES mad.h)
|
||||||
|
mark_as_advanced(LIBMAD_INCLUDE_DIR)
|
||||||
|
|
||||||
|
find_library(LIBMAD_LIBRARY NAMES mad)
|
||||||
|
mark_as_advanced(LIBMAD_LIBRARY)
|
||||||
|
|
||||||
|
include(FindPackageHandleStandardArgs)
|
||||||
|
find_package_handle_standard_args(
|
||||||
|
libmad
|
||||||
|
REQUIRED_VARS
|
||||||
|
LIBMAD_LIBRARY
|
||||||
|
LIBMAD_INCLUDE_DIR
|
||||||
|
)
|
||||||
|
|
||||||
|
if(libmad_FOUND AND NOT TARGET libmad::mad)
|
||||||
|
add_library(libmad::mad UNKNOWN IMPORTED)
|
||||||
|
set_target_properties(libmad::mad
|
||||||
|
PROPERTIES
|
||||||
|
INTERFACE_INCLUDE_DIRECTORIES ${LIBMAD_INCLUDE_DIR}
|
||||||
|
IMPORTED_LOCATION ${LIBMAD_LIBRARY}
|
||||||
|
)
|
||||||
|
endif()
|
||||||
@@ -61,6 +61,8 @@ target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
|
|||||||
zstd
|
zstd
|
||||||
z
|
z
|
||||||
lzma
|
lzma
|
||||||
|
asnd
|
||||||
|
mad
|
||||||
)
|
)
|
||||||
|
|
||||||
if(DUSK_DOLPHIN_BUILD_TYPE STREQUAL "ISO")
|
if(DUSK_DOLPHIN_BUILD_TYPE STREQUAL "ISO")
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ target_link_libraries(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
|||||||
pspgu
|
pspgu
|
||||||
pspaudio
|
pspaudio
|
||||||
pspaudiolib
|
pspaudiolib
|
||||||
|
pspmp3
|
||||||
psputility
|
psputility
|
||||||
pspvfpu
|
pspvfpu
|
||||||
pspvram
|
pspvram
|
||||||
@@ -65,6 +66,23 @@ if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
|
|||||||
)
|
)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
# Generate PARAM.SFO as a normal tracked build output (instead of letting
|
||||||
|
# create_pbp_file() auto-generate + delete it) so it can be reused below by
|
||||||
|
# a properly dependency-tracked EBOOT.PBP repack step.
|
||||||
|
set(DUSK_PSP_PARAM_SFO "${DUSK_BUILD_DIR}/PARAM.SFO")
|
||||||
|
add_custom_command(
|
||||||
|
OUTPUT "${DUSK_PSP_PARAM_SFO}"
|
||||||
|
COMMAND "$ENV{PSPDEV}/bin/mksfoex" "-d" "MEMSIZE=1" "-s" "APP_VER=01.00"
|
||||||
|
"${DUSK_BINARY_TARGET_NAME}" "${DUSK_PSP_PARAM_SFO}"
|
||||||
|
COMMENT "Generating PARAM.SFO for ${DUSK_BINARY_TARGET_NAME}"
|
||||||
|
VERBATIM
|
||||||
|
)
|
||||||
|
add_custom_target(DuskPspParamSfo DEPENDS "${DUSK_PSP_PARAM_SFO}")
|
||||||
|
|
||||||
|
# create_pbp_file()'s own POST_BUILD chain (below) also consumes
|
||||||
|
# DUSK_PSP_PARAM_SFO, so make sure it exists before that chain runs.
|
||||||
|
add_dependencies(${DUSK_BINARY_TARGET_NAME} DuskPspParamSfo)
|
||||||
|
|
||||||
# Postbuild, create .pbp file for PSP.
|
# Postbuild, create .pbp file for PSP.
|
||||||
create_pbp_file(
|
create_pbp_file(
|
||||||
TARGET "${DUSK_BINARY_TARGET_NAME}"
|
TARGET "${DUSK_BINARY_TARGET_NAME}"
|
||||||
@@ -74,4 +92,33 @@ create_pbp_file(
|
|||||||
TITLE "${DUSK_BINARY_TARGET_NAME}"
|
TITLE "${DUSK_BINARY_TARGET_NAME}"
|
||||||
PSAR_PATH ${DUSK_ASSETS_ZIP}
|
PSAR_PATH ${DUSK_ASSETS_ZIP}
|
||||||
VERSION 01.00
|
VERSION 01.00
|
||||||
|
SFO_PATH "${DUSK_PSP_PARAM_SFO}"
|
||||||
|
OUTPUT_DIR "${DUSK_BUILD_DIR}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# CreatePBP.cmake's pack-pbp step is a POST_BUILD command tied to the
|
||||||
|
# executable target, so it only reruns when the ELF itself relinks. That
|
||||||
|
# means regenerating dusk.dsk (assets) alone, without touching any C
|
||||||
|
# source, silently leaves EBOOT.PBP embedding a stale asset pak. Repack it
|
||||||
|
# here as a normal file-tracked custom command depending on both the
|
||||||
|
# executable and the asset zip, so EBOOT.PBP always reflects the current
|
||||||
|
# assets even when nothing else about the build changed.
|
||||||
|
set(DUSK_PSP_EBOOT "${DUSK_BUILD_DIR}/EBOOT.PBP")
|
||||||
|
if(BUILD_PRX)
|
||||||
|
set(DUSK_PSP_EXECUTABLE "$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>.prx")
|
||||||
|
else()
|
||||||
|
set(DUSK_PSP_EXECUTABLE "$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>")
|
||||||
|
endif()
|
||||||
|
add_custom_command(
|
||||||
|
OUTPUT "${DUSK_PSP_EBOOT}"
|
||||||
|
COMMAND "$ENV{PSPDEV}/bin/pack-pbp" "${DUSK_PSP_EBOOT}" "${DUSK_PSP_PARAM_SFO}"
|
||||||
|
"NULL" "NULL" "NULL" "NULL" "NULL"
|
||||||
|
"${DUSK_PSP_EXECUTABLE}" "${DUSK_ASSETS_ZIP}"
|
||||||
|
DEPENDS
|
||||||
|
"$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>"
|
||||||
|
"${DUSK_PSP_PARAM_SFO}"
|
||||||
|
"${DUSK_ASSETS_ZIP}"
|
||||||
|
COMMENT "Repacking EBOOT.PBP (tracks executable + asset pak freshness)"
|
||||||
|
VERBATIM
|
||||||
|
)
|
||||||
|
add_custom_target(DuskPspEbootRepack ALL DEPENDS "${DUSK_PSP_EBOOT}")
|
||||||
@@ -4,6 +4,17 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
|||||||
DUSK_WII
|
DUSK_WII
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Wii save storage method - see src/duskdolphin/save/savedeviceplatform.h.
|
||||||
|
set(DUSK_SAVE_WII_METHOD "SD" CACHE STRING
|
||||||
|
"Wii save storage: NAND (internal storage via ISFS), CARD (GameCube-\
|
||||||
|
compatible memory card emulation), or SD (SD card via libfat)"
|
||||||
|
)
|
||||||
|
set_property(CACHE DUSK_SAVE_WII_METHOD PROPERTY STRINGS "NAND" "CARD" "SD")
|
||||||
|
|
||||||
|
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||||
|
DUSK_SAVE_WII_METHOD_${DUSK_SAVE_WII_METHOD}
|
||||||
|
)
|
||||||
|
|
||||||
# Generate Homebrew Channel meta.xml from project identity variables
|
# Generate Homebrew Channel meta.xml from project identity variables
|
||||||
string(TIMESTAMP DUSK_BUILD_DATE "%Y%m%d000000" UTC)
|
string(TIMESTAMP DUSK_BUILD_DATE "%Y%m%d000000" UTC)
|
||||||
configure_file(
|
configure_file(
|
||||||
|
|||||||
+6
-1
@@ -13,6 +13,7 @@ if(DUSK_TARGET_SYSTEM STREQUAL "linux" OR DUSK_TARGET_SYSTEM STREQUAL "knulli")
|
|||||||
add_subdirectory(dusklinux)
|
add_subdirectory(dusklinux)
|
||||||
add_subdirectory(dusksdl2)
|
add_subdirectory(dusksdl2)
|
||||||
add_subdirectory(duskgl)
|
add_subdirectory(duskgl)
|
||||||
|
add_subdirectory(duskmad)
|
||||||
|
|
||||||
elseif(DUSK_TARGET_SYSTEM STREQUAL "psp")
|
elseif(DUSK_TARGET_SYSTEM STREQUAL "psp")
|
||||||
add_subdirectory(duskpsp)
|
add_subdirectory(duskpsp)
|
||||||
@@ -24,7 +25,11 @@ elseif(DUSK_TARGET_SYSTEM STREQUAL "vita")
|
|||||||
add_subdirectory(dusksdl2)
|
add_subdirectory(dusksdl2)
|
||||||
add_subdirectory(duskgl)
|
add_subdirectory(duskgl)
|
||||||
|
|
||||||
elseif(DUSK_TARGET_SYSTEM STREQUAL "wii" OR DUSK_TARGET_SYSTEM STREQUAL "gamecube")
|
elseif(
|
||||||
|
DUSK_TARGET_SYSTEM STREQUAL "wii" OR
|
||||||
|
DUSK_TARGET_SYSTEM STREQUAL "gamecube"
|
||||||
|
)
|
||||||
add_subdirectory(duskdolphin)
|
add_subdirectory(duskdolphin)
|
||||||
|
add_subdirectory(duskmad)
|
||||||
|
|
||||||
endif()
|
endif()
|
||||||
+14
-3
@@ -14,12 +14,21 @@ if(NOT libzip_FOUND)
|
|||||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC zip)
|
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC zip)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
# assetdsk.c calls crc32() directly (to verify dusk.dsk archive checksums).
|
||||||
|
# find_package(libzip) above already resolves ZLIB as a side effect, so
|
||||||
|
# ZLIB_FOUND may already be true without ZLIB::ZLIB having been linked to
|
||||||
|
# our target - link it unconditionally rather than guarding on ZLIB_FOUND.
|
||||||
|
find_package(ZLIB REQUIRED)
|
||||||
|
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC ZLIB::ZLIB)
|
||||||
|
|
||||||
if(NOT stb_image_FOUND)
|
if(NOT stb_image_FOUND)
|
||||||
find_package(stb REQUIRED)
|
find_package(stb REQUIRED)
|
||||||
if(STB_IMAGE_FOUND)
|
if(STB_IMAGE_FOUND)
|
||||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC stb_image)
|
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC stb_image)
|
||||||
else()
|
else()
|
||||||
message(FATAL_ERROR "stb_image not found. Please ensure stb is correctly fetched.")
|
message(FATAL_ERROR
|
||||||
|
"stb_image not found. Please ensure stb is correctly fetched."
|
||||||
|
)
|
||||||
endif()
|
endif()
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
@@ -28,7 +37,9 @@ if(NOT yyjson_FOUND)
|
|||||||
if(yyjson_FOUND)
|
if(yyjson_FOUND)
|
||||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC yyjson::yyjson)
|
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC yyjson::yyjson)
|
||||||
else()
|
else()
|
||||||
message(FATAL_ERROR "yyjson not found. Please ensure yyjson is correctly fetched.")
|
message(FATAL_ERROR
|
||||||
|
"yyjson not found. Please ensure yyjson is correctly fetched."
|
||||||
|
)
|
||||||
endif()
|
endif()
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
@@ -53,9 +64,9 @@ target_sources(${DUSK_BINARY_TARGET_NAME}
|
|||||||
|
|
||||||
# Subdirs
|
# Subdirs
|
||||||
add_subdirectory(animation)
|
add_subdirectory(animation)
|
||||||
add_subdirectory(event)
|
|
||||||
add_subdirectory(assert)
|
add_subdirectory(assert)
|
||||||
add_subdirectory(asset)
|
add_subdirectory(asset)
|
||||||
|
add_subdirectory(audio)
|
||||||
add_subdirectory(console)
|
add_subdirectory(console)
|
||||||
add_subdirectory(display)
|
add_subdirectory(display)
|
||||||
add_subdirectory(log)
|
add_subdirectory(log)
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
// Copyright (c) 2026 Dominic Masters
|
/**
|
||||||
//
|
* Copyright (c) 2026 Dominic Masters
|
||||||
// This software is released under the MIT License.
|
*
|
||||||
// https://opensource.org/licenses/MIT
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
#include "animation.h"
|
#include "animation.h"
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
@@ -14,9 +16,9 @@ void animationInit(
|
|||||||
uint16_t *keyframeCounts,
|
uint16_t *keyframeCounts,
|
||||||
const uint16_t layerCount
|
const uint16_t layerCount
|
||||||
) {
|
) {
|
||||||
assertNotNull(anim, "Animation pointer cannot be null.");
|
assertNotNull(anim, "Animation pointer cannot be NULL.");
|
||||||
assertNotNull(keyframes, "Keyframes pointer cannot be null.");
|
assertNotNull(keyframes, "Keyframes pointer cannot be NULL.");
|
||||||
assertNotNull(keyframeCounts, "Keyframe counts pointer cannot be null.");
|
assertNotNull(keyframeCounts, "Keyframe counts pointer cannot be NULL.");
|
||||||
assertTrue(layerCount > 0, "Layer count must be greater than zero.");
|
assertTrue(layerCount > 0, "Layer count must be greater than zero.");
|
||||||
|
|
||||||
memoryZero(anim, sizeof(animation_t));
|
memoryZero(anim, sizeof(animation_t));
|
||||||
@@ -49,7 +51,7 @@ void animationInit(
|
|||||||
}
|
}
|
||||||
|
|
||||||
float_t animationGetLayerValue(const animation_t *anim, const uint16_t layer) {
|
float_t animationGetLayerValue(const animation_t *anim, const uint16_t layer) {
|
||||||
assertNotNull(anim, "Animation pointer cannot be null.");
|
assertNotNull(anim, "Animation pointer cannot be NULL.");
|
||||||
assertTrue(layer < anim->layerCount, "Layer index out of bounds.");
|
assertTrue(layer < anim->layerCount, "Layer index out of bounds.");
|
||||||
|
|
||||||
uint16_t keyframeCount = anim->keyframeCounts[layer];
|
uint16_t keyframeCount = anim->keyframeCounts[layer];
|
||||||
@@ -61,7 +63,7 @@ void animationUpdate(
|
|||||||
animation_t *anim,
|
animation_t *anim,
|
||||||
const float_t deltaTime
|
const float_t deltaTime
|
||||||
) {
|
) {
|
||||||
assertNotNull(anim, "Animation pointer cannot be null.");
|
assertNotNull(anim, "Animation pointer cannot be NULL.");
|
||||||
assertTrue(deltaTime >= 0, "Delta time must be non-negative.");
|
assertTrue(deltaTime >= 0, "Delta time must be non-negative.");
|
||||||
|
|
||||||
bool_t justCompleted = false;
|
bool_t justCompleted = false;
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
// Copyright (c) 2026 Dominic Masters
|
/**
|
||||||
//
|
* Copyright (c) 2026 Dominic Masters
|
||||||
// This software is released under the MIT License.
|
*
|
||||||
// https://opensource.org/licenses/MIT
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "keyframe.h"
|
#include "keyframe.h"
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
// Copyright (c) 2026 Dominic Masters
|
/**
|
||||||
//
|
* Copyright (c) 2026 Dominic Masters
|
||||||
// This software is released under the MIT License.
|
*
|
||||||
// https://opensource.org/licenses/MIT
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
#include "easing.h"
|
#include "easing.h"
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
|
|||||||
+123
-4
@@ -1,7 +1,9 @@
|
|||||||
// Copyright (c) 2026 Dominic Masters
|
/**
|
||||||
//
|
* Copyright (c) 2026 Dominic Masters
|
||||||
// This software is released under the MIT License.
|
*
|
||||||
// https://opensource.org/licenses/MIT
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "dusk.h"
|
#include "dusk.h"
|
||||||
@@ -45,19 +47,136 @@ extern const easingfn_t EASING_FUNCTIONS[EASING_COUNT];
|
|||||||
*/
|
*/
|
||||||
float_t easingApply(const easingtype_t type, const float_t t);
|
float_t easingApply(const easingtype_t type, const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* No easing - returns t unchanged.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, equal to t.
|
||||||
|
*/
|
||||||
float_t easingLinear(const float_t t);
|
float_t easingLinear(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sinusoidal easing in: starts slow, accelerates to the end.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingInSine(const float_t t);
|
float_t easingInSine(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sinusoidal easing out: starts fast, decelerates to the end.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingOutSine(const float_t t);
|
float_t easingOutSine(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sinusoidal easing in and out: slow at both ends, fastest in
|
||||||
|
* the middle.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingInOutSine(const float_t t);
|
float_t easingInOutSine(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Quadratic easing in: starts slow, accelerates to the end.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingInQuad(const float_t t);
|
float_t easingInQuad(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Quadratic easing out: starts fast, decelerates to the end.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingOutQuad(const float_t t);
|
float_t easingOutQuad(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Quadratic easing in and out: slow at both ends, fastest in the
|
||||||
|
* middle.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingInOutQuad(const float_t t);
|
float_t easingInOutQuad(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cubic easing in: starts slow, accelerates to the end.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingInCubic(const float_t t);
|
float_t easingInCubic(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cubic easing out: starts fast, decelerates to the end.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingOutCubic(const float_t t);
|
float_t easingOutCubic(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cubic easing in and out: slow at both ends, fastest in the
|
||||||
|
* middle.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingInOutCubic(const float_t t);
|
float_t easingInOutCubic(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Quartic easing in: starts slow, accelerates to the end.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingInQuart(const float_t t);
|
float_t easingInQuart(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Quartic easing out: starts fast, decelerates to the end.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingOutQuart(const float_t t);
|
float_t easingOutQuart(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Quartic easing in and out: slow at both ends, fastest in the
|
||||||
|
* middle.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, in the range [0, 1].
|
||||||
|
*/
|
||||||
float_t easingInOutQuart(const float_t t);
|
float_t easingInOutQuart(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Back easing in: overshoots backwards before moving to the end.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, which may fall below 0.
|
||||||
|
*/
|
||||||
float_t easingInBack(const float_t t);
|
float_t easingInBack(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Back easing out: overshoots past the end before settling on it.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, which may rise above 1.
|
||||||
|
*/
|
||||||
float_t easingOutBack(const float_t t);
|
float_t easingOutBack(const float_t t);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Back easing in and out: overshoots backwards at the start and
|
||||||
|
* past the end before settling on it.
|
||||||
|
*
|
||||||
|
* @param t The input time, in the range [0, 1].
|
||||||
|
* @return The eased value, which may fall below 0 or rise above 1.
|
||||||
|
*/
|
||||||
float_t easingInOutBack(const float_t t);
|
float_t easingInOutBack(const float_t t);
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ float_t keyframeGetValue(
|
|||||||
const uint32_t keyframeCount,
|
const uint32_t keyframeCount,
|
||||||
const float_t time
|
const float_t time
|
||||||
) {
|
) {
|
||||||
assertNotNull(keyframes, "Keyframes pointer cannot be null.");
|
assertNotNull(keyframes, "Keyframes pointer cannot be NULL.");
|
||||||
assertTrue(keyframeCount > 0, "Keyframe count must be more than 0.");
|
assertTrue(keyframeCount > 0, "Keyframe count must be more than 0.");
|
||||||
assertTrue(time >= 0, "Time must be non-negative.");
|
assertTrue(time >= 0, "Time must be non-negative.");
|
||||||
#ifdef DUSK_ASSERTIONS
|
#ifdef DUSK_ASSERTIONS
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
// Copyright (c) 2026 Dominic Masters
|
/**
|
||||||
//
|
* Copyright (c) 2026 Dominic Masters
|
||||||
// This software is released under the MIT License.
|
*
|
||||||
// https://opensource.org/licenses/MIT
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "easing.h"
|
#include "easing.h"
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
PUBLIC
|
PUBLIC
|
||||||
asset.c
|
asset.c
|
||||||
assetbatch.c
|
assetdsk.c
|
||||||
assetfile.c
|
assetfile.c
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+37
-10
@@ -19,13 +19,17 @@ asset_t ASSET;
|
|||||||
errorret_t assetInit(void) {
|
errorret_t assetInit(void) {
|
||||||
memoryZero(&ASSET, sizeof(asset_t));
|
memoryZero(&ASSET, sizeof(asset_t));
|
||||||
|
|
||||||
|
threadMutexInit(&ASSET.zipLock);
|
||||||
|
|
||||||
for(size_t i = 0; i < ASSET_LOADING_COUNT_MAX; i++) {
|
for(size_t i = 0; i < ASSET_LOADING_COUNT_MAX; i++) {
|
||||||
threadMutexInit(&ASSET.loading[i].mutex);
|
threadMutexInit(&ASSET.loading[i].mutex);
|
||||||
}
|
}
|
||||||
|
|
||||||
// assetInitPlatform must either define ASSET.zip or throw an error.
|
// assetInitPlatform must either define both ASSET.zip/ASSET.zipStored or
|
||||||
|
// throw an error.
|
||||||
errorChain(assetInitPlatform());
|
errorChain(assetInitPlatform());
|
||||||
assertNotNull(ASSET.zip, "Asset zip null without error.");
|
assertNotNull(ASSET.zip, "Asset zip NULL without error.");
|
||||||
|
assertNotNull(ASSET.zipStored, "Asset stored zip NULL without error.");
|
||||||
threadInit(&ASSET.loadThread, assetUpdateAsync);
|
threadInit(&ASSET.loadThread, assetUpdateAsync);
|
||||||
threadStart(&ASSET.loadThread);
|
threadStart(&ASSET.loadThread);
|
||||||
|
|
||||||
@@ -35,9 +39,12 @@ errorret_t assetInit(void) {
|
|||||||
bool_t assetFileExists(const char_t *filename) {
|
bool_t assetFileExists(const char_t *filename) {
|
||||||
assertStrLenMax(filename, ASSET_FILE_NAME_MAX, "Filename too long.");
|
assertStrLenMax(filename, ASSET_FILE_NAME_MAX, "Filename too long.");
|
||||||
|
|
||||||
zip_int64_t idx = zip_name_locate(ASSET.zip, filename, 0);
|
threadMutexLock(&ASSET.zipLock);
|
||||||
if(idx < 0) return false;
|
bool_t found =
|
||||||
return true;
|
zip_name_locate(ASSET.zip, filename, 0) >= 0 ||
|
||||||
|
zip_name_locate(ASSET.zipStored, filename, 0) >= 0;
|
||||||
|
threadMutexUnlock(&ASSET.zipLock);
|
||||||
|
return found;
|
||||||
}
|
}
|
||||||
|
|
||||||
assetentry_t * assetGetEntry(
|
assetentry_t * assetGetEntry(
|
||||||
@@ -117,6 +124,15 @@ errorret_t assetRequireLoaded(assetentry_t *entry) {
|
|||||||
assetEntryLock(entry);
|
assetEntryLock(entry);
|
||||||
|
|
||||||
while(entry->state != ASSET_ENTRY_STATE_LOADED) {
|
while(entry->state != ASSET_ENTRY_STATE_LOADED) {
|
||||||
|
// A failed load transitions to ERROR, not LOADED - without this check
|
||||||
|
// this loop spins forever on any load failure (assetUpdate() itself
|
||||||
|
// still returns OK, since a single asset failing isn't meant to halt
|
||||||
|
// the whole update loop - see its ASSET_ENTRY_STATE_ERROR handling).
|
||||||
|
if(entry->state == ASSET_ENTRY_STATE_ERROR) {
|
||||||
|
assetEntryUnlock(entry);
|
||||||
|
errorThrow("Failed to load asset: %s", entry->name);
|
||||||
|
}
|
||||||
|
|
||||||
usleep(1000);
|
usleep(1000);
|
||||||
errorret_t ret = assetUpdate();
|
errorret_t ret = assetUpdate();
|
||||||
if(errorIsNotOk(ret)) {
|
if(errorIsNotOk(ret)) {
|
||||||
@@ -322,7 +338,9 @@ errorret_t assetUpdate(void) {
|
|||||||
} else if(loading->entry->state == ASSET_ENTRY_STATE_LOADED) {
|
} else if(loading->entry->state == ASSET_ENTRY_STATE_LOADED) {
|
||||||
assetentry_t *loadedEntry = loading->entry;
|
assetentry_t *loadedEntry = loading->entry;
|
||||||
loading->entry = NULL;
|
loading->entry = NULL;
|
||||||
eventInvoke(&loadedEntry->onLoaded, loadedEntry);
|
if(loadedEntry->onLoaded) {
|
||||||
|
loadedEntry->onLoaded(loadedEntry, loadedEntry->onLoadedUser);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
loading++;
|
loading++;
|
||||||
@@ -346,8 +364,10 @@ errorret_t assetUpdate(void) {
|
|||||||
assetentry_t *errEntry = loading->entry;
|
assetentry_t *errEntry = loading->entry;
|
||||||
loading->entry = NULL;
|
loading->entry = NULL;
|
||||||
threadMutexUnlock(&loading->mutex);
|
threadMutexUnlock(&loading->mutex);
|
||||||
eventInvoke(&errEntry->onError, errEntry);
|
if(errEntry->onError) {
|
||||||
errorThrow("Failed to load asset asynchronously.");
|
errEntry->onError(errEntry, errEntry->onErrorUser);
|
||||||
|
}
|
||||||
|
loading++;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -425,14 +445,21 @@ errorret_t assetDispose(void) {
|
|||||||
|
|
||||||
errorChain(assetReapUnused());
|
errorChain(assetReapUnused());
|
||||||
|
|
||||||
// Cleanup zip file.
|
// Cleanup zip files.
|
||||||
if(ASSET.zip != NULL) {
|
if(ASSET.zip != NULL) {
|
||||||
if(zip_close(ASSET.zip) != 0) {
|
if(zip_close(ASSET.zip) != 0) {
|
||||||
errorThrow("Failed to close asset zip archive.");
|
errorThrow("Failed to close compressed asset zip archive.");
|
||||||
}
|
}
|
||||||
ASSET.zip = NULL;
|
ASSET.zip = NULL;
|
||||||
}
|
}
|
||||||
|
if(ASSET.zipStored != NULL) {
|
||||||
|
if(zip_close(ASSET.zipStored) != 0) {
|
||||||
|
errorThrow("Failed to close stored asset zip archive.");
|
||||||
|
}
|
||||||
|
ASSET.zipStored = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
errorChain(assetDisposePlatform());
|
errorChain(assetDisposePlatform());
|
||||||
|
threadMutexDispose(&ASSET.zipLock);
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
@@ -26,10 +26,44 @@
|
|||||||
#define ASSET_LOADING_COUNT_MAX 10
|
#define ASSET_LOADING_COUNT_MAX 10
|
||||||
#define ASSET_ENTRY_COUNT_MAX 64
|
#define ASSET_ENTRY_COUNT_MAX 64
|
||||||
|
|
||||||
|
#define ASSET_BASE_DIRECTORY_MAX 256
|
||||||
|
|
||||||
typedef struct asset_s {
|
typedef struct asset_s {
|
||||||
|
// Compressed (DEFLATE) archive - expected to hold the bulk of a game's
|
||||||
|
// binary assets. Looked up first by assetFileInit().
|
||||||
zip_t *zip;
|
zip_t *zip;
|
||||||
|
|
||||||
|
// Stored (uncompressed) archive - expected to hold small files that need
|
||||||
|
// reliable repeated seeking/re-opening (e.g. locale strings), which
|
||||||
|
// libzip only supports reliably for uncompressed entries. Looked up by
|
||||||
|
// assetFileInit() only if the name isn't found in `zip`.
|
||||||
|
zip_t *zipStored;
|
||||||
|
|
||||||
|
// Directory dusk.dsk was actually found/opened in (on PSP, the directory
|
||||||
|
// EBOOT.PBP lives in, since dusk.dsk is embedded inside it rather than a
|
||||||
|
// loose file) - populated by each platform's own assetInitXxx() once it
|
||||||
|
// locates the file. Save devices that persist to a real filesystem path
|
||||||
|
// (Linux, PSP, Wii SD) use this as their base directory instead of a
|
||||||
|
// separate hardcoded location, so saves live next to wherever the game
|
||||||
|
// itself was actually launched from rather than some unrelated fixed
|
||||||
|
// path. Not meaningful for devices with no filesystem-path concept at
|
||||||
|
// all (GameCube/Wii memory card, Wii NAND's ISFS namespace).
|
||||||
|
char_t baseDirectory[ASSET_BASE_DIRECTORY_MAX];
|
||||||
|
|
||||||
assetplatform_t platform;
|
assetplatform_t platform;
|
||||||
|
|
||||||
|
// Guards every libzip call against ASSET.zip/ASSET.zipStored (zip_fopen,
|
||||||
|
// zip_fread, zip_fclose, zip_fseek, zip_stat, zip_name_locate - see
|
||||||
|
// assetfile.c/assetFileExists). libzip is documented as not thread-safe,
|
||||||
|
// and this asset system genuinely calls it from multiple real threads at
|
||||||
|
// once (main thread, the background load thread below, and - on
|
||||||
|
// platforms that stream PCM from an asset on their own thread, like PSP
|
||||||
|
// - an audio feeder thread too). Confirmed necessary on real PSP
|
||||||
|
// hardware: without this lock, concurrent zip_fopen/zip_fread calls from
|
||||||
|
// different threads corrupted reads (EINVAL, then zlib data errors) once
|
||||||
|
// dusk.dsk stopped being read entirely into memory up front.
|
||||||
|
threadmutex_t zipLock;
|
||||||
|
|
||||||
// Background loading thread.
|
// Background loading thread.
|
||||||
thread_t loadThread;
|
thread_t loadThread;
|
||||||
|
|
||||||
|
|||||||
@@ -1,165 +0,0 @@
|
|||||||
/**
|
|
||||||
* 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>
|
|
||||||
|
|
||||||
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 live.
|
|
||||||
eventUnsubscribe(&batch->entries[i]->onLoaded, assetBatchEntryOnLoadedCb);
|
|
||||||
eventUnsubscribe(&batch->entries[i]->onError, assetBatchEntryOnErrorCb);
|
|
||||||
assetUnlockEntry(batch->entries[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
memoryZero(batch, sizeof(assetbatch_t));
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
/**
|
|
||||||
* 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 loaded. 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 loads. params = assetentry_t * */
|
|
||||||
event_t onEntryLoaded;
|
|
||||||
eventcallback_t onEntryLoadedCallbacks[ASSET_BATCH_EVENT_MAX];
|
|
||||||
void *onEntryLoadedUsers[ASSET_BATCH_EVENT_MAX];
|
|
||||||
|
|
||||||
/** Fires when all entries finish (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);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Event trampoline invoked when a batch entry finishes loading.
|
|
||||||
* Increments the loaded counter and fires batch-level events.
|
|
||||||
*
|
|
||||||
* @param params The loaded assetentry_t pointer.
|
|
||||||
* @param user The owning assetbatch_t pointer.
|
|
||||||
*/
|
|
||||||
void assetBatchEntryOnLoadedCb(void *params, void *user);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Event trampoline invoked when a batch entry fails to load.
|
|
||||||
* Increments the error counter and fires batch-level events.
|
|
||||||
*
|
|
||||||
* @param params The errored assetentry_t pointer.
|
|
||||||
* @param user The owning assetbatch_t pointer.
|
|
||||||
*/
|
|
||||||
void assetBatchEntryOnErrorCb(void *params, void *user);
|
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "assetdsk.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include "util/endian.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include <zlib.h>
|
||||||
|
|
||||||
|
errorret_t assetDskParseHeader(
|
||||||
|
const uint8_t *bytes,
|
||||||
|
const size_t bytesSize,
|
||||||
|
assetdskheader_t *outHeader
|
||||||
|
) {
|
||||||
|
assertNotNull(bytes, "Bytes cannot be NULL.");
|
||||||
|
assertNotNull(outHeader, "Out header cannot be NULL.");
|
||||||
|
|
||||||
|
if(bytesSize < ASSET_DSK_HEADER_SIZE) {
|
||||||
|
errorThrow("dusk.dsk header is truncated.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if(memoryCompare(bytes, ASSET_DSK_MAGIC, ASSET_DSK_MAGIC_SIZE) != 0) {
|
||||||
|
errorThrow("dusk.dsk has an invalid magic header.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every field is a little-endian uint32_t regardless of host - convert
|
||||||
|
// to host order (a no-op on little-endian hosts, a real byteswap on
|
||||||
|
// Dolphin's big-endian PowerPC).
|
||||||
|
uint32_t fields[7];
|
||||||
|
memoryCopy(fields, bytes + ASSET_DSK_MAGIC_SIZE, sizeof(fields));
|
||||||
|
for(uint8_t i = 0; i < 7; i++) {
|
||||||
|
fields[i] = endianLittleToHost32(fields[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint32_t version = fields[0];
|
||||||
|
if(version != ASSET_DSK_VERSION) {
|
||||||
|
errorThrow("dusk.dsk has an unsupported version: %u", version);
|
||||||
|
}
|
||||||
|
|
||||||
|
outHeader->compressedOffset = fields[1];
|
||||||
|
outHeader->compressedSize = fields[2];
|
||||||
|
outHeader->compressedChecksum = fields[3];
|
||||||
|
outHeader->storedOffset = fields[4];
|
||||||
|
outHeader->storedSize = fields[5];
|
||||||
|
outHeader->storedChecksum = fields[6];
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetDskOpenFromPath(
|
||||||
|
const char_t *path,
|
||||||
|
zip_t **outCompressed,
|
||||||
|
zip_t **outStored
|
||||||
|
) {
|
||||||
|
errorChain(assetDskOpenFromPathRange(
|
||||||
|
path, 0, SIZE_MAX, outCompressed, outStored
|
||||||
|
));
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetDskOpenFromPathRange(
|
||||||
|
const char_t *path,
|
||||||
|
const size_t baseOffset,
|
||||||
|
const size_t baseSize,
|
||||||
|
zip_t **outCompressed,
|
||||||
|
zip_t **outStored
|
||||||
|
) {
|
||||||
|
assertNotNull(path, "Path cannot be NULL.");
|
||||||
|
assertNotNull(outCompressed, "Out compressed cannot be NULL.");
|
||||||
|
assertNotNull(outStored, "Out stored cannot be NULL.");
|
||||||
|
|
||||||
|
*outCompressed = NULL;
|
||||||
|
*outStored = NULL;
|
||||||
|
|
||||||
|
FILE *headerFile = fopen(path, "rb");
|
||||||
|
if(headerFile == NULL) {
|
||||||
|
errorThrow("Failed to open dusk.dsk: %s", path);
|
||||||
|
}
|
||||||
|
|
||||||
|
if(fseek(headerFile, (long) baseOffset, SEEK_SET) != 0) {
|
||||||
|
fclose(headerFile);
|
||||||
|
errorThrow("Failed to seek to dusk.dsk range in file: %s", path);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t headerBytes[ASSET_DSK_HEADER_SIZE];
|
||||||
|
size_t headerRead = fread(headerBytes, 1, sizeof(headerBytes), headerFile);
|
||||||
|
fclose(headerFile);
|
||||||
|
if(headerRead != sizeof(headerBytes)) {
|
||||||
|
errorThrow("Failed to read dusk.dsk header: %s", path);
|
||||||
|
}
|
||||||
|
|
||||||
|
assetdskheader_t header;
|
||||||
|
errorChain(assetDskParseHeader(headerBytes, sizeof(headerBytes), &header));
|
||||||
|
|
||||||
|
if(
|
||||||
|
(size_t) header.compressedOffset + header.compressedSize > baseSize ||
|
||||||
|
(size_t) header.storedOffset + header.storedSize > baseSize
|
||||||
|
) {
|
||||||
|
errorThrow("dusk.dsk header describes ranges beyond its containing file.");
|
||||||
|
}
|
||||||
|
|
||||||
|
zip_error_t zipError;
|
||||||
|
zip_error_init(&zipError);
|
||||||
|
|
||||||
|
zip_source_t *compressedSource = zip_source_file_create(
|
||||||
|
path,
|
||||||
|
(zip_uint64_t) (baseOffset + header.compressedOffset),
|
||||||
|
(zip_int64_t) header.compressedSize,
|
||||||
|
&zipError
|
||||||
|
);
|
||||||
|
if(compressedSource == NULL) {
|
||||||
|
errorThrow(
|
||||||
|
"Failed to create compressed dusk.dsk source: %s",
|
||||||
|
zip_error_strerror(&zipError)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
*outCompressed =
|
||||||
|
zip_open_from_source(compressedSource, ZIP_RDONLY, &zipError);
|
||||||
|
if(*outCompressed == NULL) {
|
||||||
|
zip_source_free(compressedSource);
|
||||||
|
errorThrow(
|
||||||
|
"Failed to open compressed dusk.dsk archive: %s",
|
||||||
|
zip_error_strerror(&zipError)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
zip_source_t *storedSource = zip_source_file_create(
|
||||||
|
path,
|
||||||
|
(zip_uint64_t) (baseOffset + header.storedOffset),
|
||||||
|
(zip_int64_t) header.storedSize,
|
||||||
|
&zipError
|
||||||
|
);
|
||||||
|
if(storedSource == NULL) {
|
||||||
|
zip_close(*outCompressed);
|
||||||
|
*outCompressed = NULL;
|
||||||
|
errorThrow(
|
||||||
|
"Failed to create stored dusk.dsk source: %s",
|
||||||
|
zip_error_strerror(&zipError)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
*outStored = zip_open_from_source(storedSource, ZIP_RDONLY, &zipError);
|
||||||
|
if(*outStored == NULL) {
|
||||||
|
zip_source_free(storedSource);
|
||||||
|
zip_close(*outCompressed);
|
||||||
|
*outCompressed = NULL;
|
||||||
|
errorThrow(
|
||||||
|
"Failed to open stored dusk.dsk archive: %s",
|
||||||
|
zip_error_strerror(&zipError)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The stored archive is small by convention, so verifying its checksum
|
||||||
|
// here (one extra small read) is cheap; the compressed archive isn't
|
||||||
|
// checked since it's meant to be read lazily/on-demand from here on.
|
||||||
|
uint8_t *storedBytes = (uint8_t *) memoryAllocate(header.storedSize);
|
||||||
|
FILE *storedFile = fopen(path, "rb");
|
||||||
|
if(storedFile == NULL) {
|
||||||
|
memoryFree(storedBytes);
|
||||||
|
zip_close(*outStored);
|
||||||
|
zip_close(*outCompressed);
|
||||||
|
*outStored = NULL;
|
||||||
|
*outCompressed = NULL;
|
||||||
|
errorThrow(
|
||||||
|
"Failed to re-open dusk.dsk to verify stored checksum: %s", path
|
||||||
|
);
|
||||||
|
}
|
||||||
|
fseek(storedFile, (long) (baseOffset + header.storedOffset), SEEK_SET);
|
||||||
|
size_t storedRead = fread(storedBytes, 1, header.storedSize, storedFile);
|
||||||
|
fclose(storedFile);
|
||||||
|
if(storedRead != header.storedSize) {
|
||||||
|
memoryFree(storedBytes);
|
||||||
|
zip_close(*outStored);
|
||||||
|
zip_close(*outCompressed);
|
||||||
|
*outStored = NULL;
|
||||||
|
*outCompressed = NULL;
|
||||||
|
errorThrow(
|
||||||
|
"Failed to read dusk.dsk stored archive to verify checksum: %s", path
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t checksum =
|
||||||
|
(uint32_t) crc32(0L, storedBytes, (uInt) header.storedSize);
|
||||||
|
memoryFree(storedBytes);
|
||||||
|
if(checksum != header.storedChecksum) {
|
||||||
|
zip_close(*outStored);
|
||||||
|
zip_close(*outCompressed);
|
||||||
|
*outStored = NULL;
|
||||||
|
*outCompressed = NULL;
|
||||||
|
errorThrow(
|
||||||
|
"dusk.dsk stored archive failed checksum verification: %s", path
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetDskOpenFromBuffer(
|
||||||
|
uint8_t *buffer,
|
||||||
|
const size_t bufferSize,
|
||||||
|
zip_t **outCompressed,
|
||||||
|
zip_t **outStored
|
||||||
|
) {
|
||||||
|
assertNotNull(buffer, "Buffer cannot be NULL.");
|
||||||
|
assertNotNull(outCompressed, "Out compressed cannot be NULL.");
|
||||||
|
assertNotNull(outStored, "Out stored cannot be NULL.");
|
||||||
|
|
||||||
|
*outCompressed = NULL;
|
||||||
|
*outStored = NULL;
|
||||||
|
|
||||||
|
assetdskheader_t header;
|
||||||
|
errorChain(assetDskParseHeader(buffer, bufferSize, &header));
|
||||||
|
|
||||||
|
if(
|
||||||
|
(size_t) header.compressedOffset + header.compressedSize > bufferSize ||
|
||||||
|
(size_t) header.storedOffset + header.storedSize > bufferSize
|
||||||
|
) {
|
||||||
|
errorThrow("dusk.dsk header describes ranges beyond the buffer.");
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t compressedChecksum = (uint32_t) crc32(
|
||||||
|
0L, buffer + header.compressedOffset, (uInt) header.compressedSize
|
||||||
|
);
|
||||||
|
if(compressedChecksum != header.compressedChecksum) {
|
||||||
|
errorThrow("dusk.dsk compressed archive failed checksum verification.");
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t storedChecksum = (uint32_t) crc32(
|
||||||
|
0L, buffer + header.storedOffset, (uInt) header.storedSize
|
||||||
|
);
|
||||||
|
if(storedChecksum != header.storedChecksum) {
|
||||||
|
errorThrow("dusk.dsk stored archive failed checksum verification.");
|
||||||
|
}
|
||||||
|
|
||||||
|
zip_error_t zipError;
|
||||||
|
zip_error_init(&zipError);
|
||||||
|
|
||||||
|
// freep=0 for both - they're non-owning windows into the same caller-owned
|
||||||
|
// buffer, not independent allocations libzip should free.
|
||||||
|
zip_source_t *compressedSource = zip_source_buffer_create(
|
||||||
|
buffer + header.compressedOffset, header.compressedSize, 0, &zipError
|
||||||
|
);
|
||||||
|
if(compressedSource == NULL) {
|
||||||
|
errorThrow(
|
||||||
|
"Failed to create compressed dusk.dsk source: %s",
|
||||||
|
zip_error_strerror(&zipError)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
*outCompressed =
|
||||||
|
zip_open_from_source(compressedSource, ZIP_RDONLY, &zipError);
|
||||||
|
if(*outCompressed == NULL) {
|
||||||
|
zip_source_free(compressedSource);
|
||||||
|
errorThrow(
|
||||||
|
"Failed to open compressed dusk.dsk archive: %s",
|
||||||
|
zip_error_strerror(&zipError)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
zip_source_t *storedSource = zip_source_buffer_create(
|
||||||
|
buffer + header.storedOffset, header.storedSize, 0, &zipError
|
||||||
|
);
|
||||||
|
if(storedSource == NULL) {
|
||||||
|
zip_close(*outCompressed);
|
||||||
|
*outCompressed = NULL;
|
||||||
|
errorThrow(
|
||||||
|
"Failed to create stored dusk.dsk source: %s",
|
||||||
|
zip_error_strerror(&zipError)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
*outStored = zip_open_from_source(storedSource, ZIP_RDONLY, &zipError);
|
||||||
|
if(*outStored == NULL) {
|
||||||
|
zip_source_free(storedSource);
|
||||||
|
zip_close(*outCompressed);
|
||||||
|
*outCompressed = NULL;
|
||||||
|
errorThrow(
|
||||||
|
"Failed to open stored dusk.dsk archive: %s",
|
||||||
|
zip_error_strerror(&zipError)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "error/error.h"
|
||||||
|
#include <zip.h>
|
||||||
|
|
||||||
|
// "DSK2" - distinct from a plain zip's "PK\x03\x04" so a stray plain zip
|
||||||
|
// never gets misread as a valid dusk.dsk.
|
||||||
|
#define ASSET_DSK_MAGIC_SIZE 4
|
||||||
|
#define ASSET_DSK_MAGIC "DSK2"
|
||||||
|
#define ASSET_DSK_VERSION 1
|
||||||
|
|
||||||
|
// magic(4) + version(4) + compressedOffset(4) + compressedSize(4) +
|
||||||
|
// compressedChecksum(4) + storedOffset(4) + storedSize(4) +
|
||||||
|
// storedChecksum(4), all little-endian regardless of host - see
|
||||||
|
// assetDskParseHeader.
|
||||||
|
#define ASSET_DSK_HEADER_SIZE 32
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parsed dusk.dsk (DSK2 format) header. dusk.dsk is two independent, back
|
||||||
|
* to back zip archives (see tools/asset/pack) rather than a single plain
|
||||||
|
* zip: a "compressed" one (DEFLATE, expected to hold the bulk of a game's
|
||||||
|
* binary assets, opened lazily/on-demand) and a "stored" one (uncompressed,
|
||||||
|
* expected to hold small files - locale strings, config - that need
|
||||||
|
* reliable repeated seeking/re-opening, which libzip only supports for
|
||||||
|
* uncompressed entries).
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint32_t compressedOffset;
|
||||||
|
uint32_t compressedSize;
|
||||||
|
uint32_t compressedChecksum;
|
||||||
|
uint32_t storedOffset;
|
||||||
|
uint32_t storedSize;
|
||||||
|
uint32_t storedChecksum;
|
||||||
|
} assetdskheader_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a DSK2 header from a raw byte buffer (at least
|
||||||
|
* ASSET_DSK_HEADER_SIZE bytes), validating the magic/version and
|
||||||
|
* byte-swapping the little-endian fields to host order.
|
||||||
|
*
|
||||||
|
* @param bytes Buffer containing the header (and beyond).
|
||||||
|
* @param bytesSize Number of bytes available at `bytes`.
|
||||||
|
* @param outHeader Filled with the parsed header on success.
|
||||||
|
* @return OK on success, error if too short, bad magic, or unsupported version.
|
||||||
|
*/
|
||||||
|
errorret_t assetDskParseHeader(
|
||||||
|
const uint8_t *bytes,
|
||||||
|
const size_t bytesSize,
|
||||||
|
assetdskheader_t *outHeader
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens both archives of a dusk.dsk file given a filesystem path, using
|
||||||
|
* lazy/windowed file-backed zip sources - no more memory used than the
|
||||||
|
* existing per-platform small read buffers, matching the memory
|
||||||
|
* characteristics of a plain zip_open() on the whole file. Verifies the
|
||||||
|
* (small, by convention) stored archive's checksum; the compressed
|
||||||
|
* archive's checksum is intentionally not verified here since doing so
|
||||||
|
* would require reading the bulk of the game's assets just to compute it.
|
||||||
|
*
|
||||||
|
* See assetDskOpenFromPathRange() for the case where the DSK2 blob isn't
|
||||||
|
* the whole file (e.g. embedded inside another container).
|
||||||
|
*
|
||||||
|
* @param path Filesystem path to the dusk.dsk file.
|
||||||
|
* @param outCompressed Set to the opened compressed archive on success.
|
||||||
|
* @param outStored Set to the opened stored archive on success.
|
||||||
|
* @return OK on success, error if the file is missing, too short, has a
|
||||||
|
* bad header, or either archive fails to open/verify.
|
||||||
|
*/
|
||||||
|
errorret_t assetDskOpenFromPath(
|
||||||
|
const char_t *path,
|
||||||
|
zip_t **outCompressed,
|
||||||
|
zip_t **outStored
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same as assetDskOpenFromPath(), but the DSK2 blob doesn't start at the
|
||||||
|
* beginning of `path` - it's a byte range embedded inside a larger
|
||||||
|
* container file (e.g. the PSAR region of an EBOOT.PBP). Every offset the
|
||||||
|
* header describes is relative to `baseOffset`; `baseSize` bounds them
|
||||||
|
* (the size of the embedded blob, not the whole container file) - pass
|
||||||
|
* SIZE_MAX to skip that check when the caller doesn't know/care.
|
||||||
|
*
|
||||||
|
* @param path Filesystem path to the container file.
|
||||||
|
* @param baseOffset Byte offset within `path` where the DSK2 blob starts.
|
||||||
|
* @param baseSize Number of bytes available at `baseOffset`.
|
||||||
|
* @param outCompressed Set to the opened compressed archive on success.
|
||||||
|
* @param outStored Set to the opened stored archive on success.
|
||||||
|
* @return OK on success, error if the file is missing, too short, has a
|
||||||
|
* bad header, or either archive fails to open/verify.
|
||||||
|
*/
|
||||||
|
errorret_t assetDskOpenFromPathRange(
|
||||||
|
const char_t *path,
|
||||||
|
const size_t baseOffset,
|
||||||
|
const size_t baseSize,
|
||||||
|
zip_t **outCompressed,
|
||||||
|
zip_t **outStored
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens both archives of a dusk.dsk file already fully resident in memory
|
||||||
|
* (e.g. a PSAR embedded in an EBOOT.PBP, or an ISO-embedded file already
|
||||||
|
* read via DVD_ReadAbs - platforms that already buffer the whole file for
|
||||||
|
* reasons unrelated to this format). Neither archive takes ownership of
|
||||||
|
* `buffer` (both are opened as non-owning sub-ranges of it) - the caller
|
||||||
|
* remains responsible for freeing it, and must keep it alive for as long
|
||||||
|
* as either archive stays open. Verifies both archives' checksums, since
|
||||||
|
* the bytes are already resident.
|
||||||
|
*
|
||||||
|
* @param buffer The whole dusk.dsk file's bytes.
|
||||||
|
* @param bufferSize Number of bytes at `buffer`.
|
||||||
|
* @param outCompressed Set to the opened compressed archive on success.
|
||||||
|
* @param outStored Set to the opened stored archive on success.
|
||||||
|
* @return OK on success, error if too short, has a bad header/checksum, or
|
||||||
|
* either archive fails to open.
|
||||||
|
*/
|
||||||
|
errorret_t assetDskOpenFromBuffer(
|
||||||
|
uint8_t *buffer,
|
||||||
|
const size_t bufferSize,
|
||||||
|
zip_t **outCompressed,
|
||||||
|
zip_t **outStored
|
||||||
|
);
|
||||||
+90
-28
@@ -24,9 +24,20 @@ errorret_t assetFileInit(
|
|||||||
file->params = params;
|
file->params = params;
|
||||||
file->output = output;
|
file->output = output;
|
||||||
|
|
||||||
// Stat the file
|
// Stat the file, trying the compressed archive first and falling back to
|
||||||
|
// the stored one - remember which matched so assetFileOpen opens it from
|
||||||
|
// the right archive.
|
||||||
zip_stat_init(&file->stat);
|
zip_stat_init(&file->stat);
|
||||||
if(!zip_stat(ASSET.zip, filename, 0, &file->stat) == 0) {
|
threadMutexLock(&ASSET.zipLock);
|
||||||
|
if(zip_stat(ASSET.zip, filename, 0, &file->stat) == 0) {
|
||||||
|
file->sourceZip = ASSET.zip;
|
||||||
|
} else if(zip_stat(ASSET.zipStored, filename, 0, &file->stat) == 0) {
|
||||||
|
file->sourceZip = ASSET.zipStored;
|
||||||
|
} else {
|
||||||
|
file->sourceZip = NULL;
|
||||||
|
}
|
||||||
|
threadMutexUnlock(&ASSET.zipLock);
|
||||||
|
if(file->sourceZip == NULL) {
|
||||||
errorThrow("Failed to stat asset file: %s", filename);
|
errorThrow("Failed to stat asset file: %s", filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,6 +58,25 @@ errorret_t assetFileRewind(assetfile_t *file) {
|
|||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Prefer seeking within the still-open handle over closing and
|
||||||
|
// re-opening it. Repeatedly closing/re-opening the same compressed zip
|
||||||
|
// entry (once per rewind - e.g. once per locale string lookup) was
|
||||||
|
// confirmed unreliable on at least one platform's zip backend, silently
|
||||||
|
// skipping ranges of the decompressed content on some re-opens after
|
||||||
|
// the first. A real seek avoids that failure mode entirely, with no
|
||||||
|
// extra memory cost over the close+reopen fallback.
|
||||||
|
threadMutexLock(&ASSET.zipLock);
|
||||||
|
bool_t seekable = zip_file_is_seekable(file->zipFile);
|
||||||
|
int seekResult = seekable ? zip_fseek(file->zipFile, 0, SEEK_SET) : -1;
|
||||||
|
threadMutexUnlock(&ASSET.zipLock);
|
||||||
|
if(seekable) {
|
||||||
|
if(seekResult != 0) {
|
||||||
|
errorThrow("Failed to seek asset file: %s", file->filename);
|
||||||
|
}
|
||||||
|
file->position = 0;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
errorChain(assetFileClose(file));
|
errorChain(assetFileClose(file));
|
||||||
errorChain(assetFileOpen(file));
|
errorChain(assetFileOpen(file));
|
||||||
errorOk();
|
errorOk();
|
||||||
@@ -55,10 +85,12 @@ errorret_t assetFileRewind(assetfile_t *file) {
|
|||||||
errorret_t assetFileOpen(assetfile_t *file) {
|
errorret_t assetFileOpen(assetfile_t *file) {
|
||||||
assertNotNull(file, "Asset file cannot be NULL.");
|
assertNotNull(file, "Asset file cannot be NULL.");
|
||||||
assertNotNull(file->filename, "Asset file filename cannot be NULL.");
|
assertNotNull(file->filename, "Asset file filename cannot be NULL.");
|
||||||
assertNotNull(ASSET.zip, "Asset zip cannot be NULL.");
|
assertNotNull(file->sourceZip, "Asset file must be inited before opening.");
|
||||||
assertNull(file->zipFile, "Asset file already open.");
|
assertNull(file->zipFile, "Asset file already open.");
|
||||||
|
|
||||||
file->zipFile = zip_fopen(ASSET.zip, file->filename, 0);
|
threadMutexLock(&ASSET.zipLock);
|
||||||
|
file->zipFile = zip_fopen(file->sourceZip, file->filename, 0);
|
||||||
|
threadMutexUnlock(&ASSET.zipLock);
|
||||||
if(file->zipFile == NULL) {
|
if(file->zipFile == NULL) {
|
||||||
errorThrow("Failed to open asset file: %s", file->filename);
|
errorThrow("Failed to open asset file: %s", file->filename);
|
||||||
}
|
}
|
||||||
@@ -79,21 +111,52 @@ errorret_t assetFileRead(
|
|||||||
uint8_t tempBuffer[256];
|
uint8_t tempBuffer[256];
|
||||||
while(bytesRemaining > 0) {
|
while(bytesRemaining > 0) {
|
||||||
size_t chunkSize = mathMin(bytesRemaining, sizeof(tempBuffer));
|
size_t chunkSize = mathMin(bytesRemaining, sizeof(tempBuffer));
|
||||||
|
// The recursive call below already advances file->position by
|
||||||
|
// chunkSize (the non-NULL branch does this itself) - do not also
|
||||||
|
// advance it here, or every skip ends up double-counted.
|
||||||
errorChain(assetFileRead(file, tempBuffer, chunkSize));
|
errorChain(assetFileRead(file, tempBuffer, chunkSize));
|
||||||
file->position += chunkSize;
|
|
||||||
bytesRemaining -= chunkSize;
|
bytesRemaining -= chunkSize;
|
||||||
}
|
}
|
||||||
file->lastRead = bufferSize;
|
file->lastRead = bufferSize;
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
// I assume zip_fread takes buffer NULL for skipping?
|
// Some zip_fread() implementations (seen on PSP) reject a single call
|
||||||
zip_int64_t bytesRead = zip_fread(file->zipFile, buffer, bufferSize);
|
// asking for the entire (potentially large) file at once with EINVAL;
|
||||||
if(bytesRead < 0) {
|
// the line reader above only ever asks for up to 1024 bytes per call and
|
||||||
errorThrow("Failed to read from asset file: %s", file->filename);
|
// works fine, so read in bounded chunks here too.
|
||||||
|
size_t totalRead = 0;
|
||||||
|
uint8_t *dest = (uint8_t *)buffer;
|
||||||
|
while(totalRead < bufferSize) {
|
||||||
|
size_t chunkSize = mathMin(
|
||||||
|
bufferSize - totalRead, ASSET_FILE_READ_CHUNK_MAX
|
||||||
|
);
|
||||||
|
threadMutexLock(&ASSET.zipLock);
|
||||||
|
zip_int64_t bytesRead = zip_fread(
|
||||||
|
file->zipFile, dest + totalRead, chunkSize
|
||||||
|
);
|
||||||
|
errorret_t readError = errorOkImpl();
|
||||||
|
if(bytesRead < 0) {
|
||||||
|
// Built (not thrown) while still holding the lock, so
|
||||||
|
// zip_file_strerror() reads the just-failed zipFile's error state
|
||||||
|
// before another thread can touch it - errorThrow() itself isn't
|
||||||
|
// used here since it returns immediately, which would leave
|
||||||
|
// ASSET.zipLock held forever.
|
||||||
|
readError = errorThrowImpl(
|
||||||
|
&ERROR_STATE, ERROR_NOT_OK, __FILE__, __func__, __LINE__,
|
||||||
|
"Failed to read from asset file: %s (%s)",
|
||||||
|
file->filename, zip_file_strerror(file->zipFile)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
threadMutexUnlock(&ASSET.zipLock);
|
||||||
|
if(errorIsNotOk(readError)) {
|
||||||
|
errorChain(readError);
|
||||||
|
}
|
||||||
|
if(bytesRead == 0) break;
|
||||||
|
totalRead += (size_t)bytesRead;
|
||||||
}
|
}
|
||||||
file->position += bytesRead;
|
file->position += totalRead;
|
||||||
file->lastRead = bytesRead;
|
file->lastRead = totalRead;
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,7 +164,10 @@ errorret_t assetFileClose(assetfile_t *file) {
|
|||||||
assertNotNull(file, "Asset file cannot be NULL.");
|
assertNotNull(file, "Asset file cannot be NULL.");
|
||||||
assertNotNull(file->zipFile, "Asset file must be opened before closing.");
|
assertNotNull(file->zipFile, "Asset file must be opened before closing.");
|
||||||
|
|
||||||
if(zip_fclose(file->zipFile) != 0) {
|
threadMutexLock(&ASSET.zipLock);
|
||||||
|
int closeResult = zip_fclose(file->zipFile);
|
||||||
|
threadMutexUnlock(&ASSET.zipLock);
|
||||||
|
if(closeResult != 0) {
|
||||||
errorThrow("Failed to close asset file: %s", file->filename);
|
errorThrow("Failed to close asset file: %s", file->filename);
|
||||||
}
|
}
|
||||||
file->zipFile = NULL;
|
file->zipFile = NULL;
|
||||||
@@ -201,7 +267,7 @@ const uint8_t *assetFileLineReaderUnreadPtr(
|
|||||||
return reader->readBuffer + reader->bufferStart;
|
return reader->readBuffer + reader->bufferStart;
|
||||||
}
|
}
|
||||||
|
|
||||||
static errorret_t assetFileLineReaderAppend(
|
errorret_t assetFileLineReaderAppend(
|
||||||
assetfilelinereader_t *reader,
|
assetfilelinereader_t *reader,
|
||||||
const uint8_t *src,
|
const uint8_t *src,
|
||||||
size_t srcLength
|
size_t srcLength
|
||||||
@@ -213,7 +279,7 @@ static errorret_t assetFileLineReaderAppend(
|
|||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
/* reserve room for optional NUL terminator */
|
// reserve room for optional NUL terminator
|
||||||
if(reader->lineLength + srcLength >= reader->outBufferSize) {
|
if(reader->lineLength + srcLength >= reader->outBufferSize) {
|
||||||
errorThrow("Line length exceeds output buffer size.");
|
errorThrow("Line length exceeds output buffer size.");
|
||||||
}
|
}
|
||||||
@@ -223,7 +289,7 @@ static errorret_t assetFileLineReaderAppend(
|
|||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
static void assetFileLineReaderTerminate(assetfilelinereader_t *reader) {
|
void assetFileLineReaderTerminate(assetfilelinereader_t *reader) {
|
||||||
assertNotNull(reader, "Reader cannot be NULL.");
|
assertNotNull(reader, "Reader cannot be NULL.");
|
||||||
assertNotNull(reader->outBuffer, "Out buffer cannot be NULL.");
|
assertNotNull(reader->outBuffer, "Out buffer cannot be NULL.");
|
||||||
assertTrue(
|
assertTrue(
|
||||||
@@ -233,7 +299,7 @@ static void assetFileLineReaderTerminate(assetfilelinereader_t *reader) {
|
|||||||
reader->outBuffer[reader->lineLength] = '\0';
|
reader->outBuffer[reader->lineLength] = '\0';
|
||||||
}
|
}
|
||||||
|
|
||||||
static ssize_t assetFileLineReaderFindNewline(
|
ssize_t assetFileLineReaderFindNewline(
|
||||||
const assetfilelinereader_t *reader
|
const assetfilelinereader_t *reader
|
||||||
) {
|
) {
|
||||||
size_t i;
|
size_t i;
|
||||||
@@ -262,7 +328,7 @@ errorret_t assetFileLineReaderFill(assetfilelinereader_t *reader) {
|
|||||||
|
|
||||||
size_t unreadBytes = assetFileLineReaderUnreadBytes(reader);
|
size_t unreadBytes = assetFileLineReaderUnreadBytes(reader);
|
||||||
|
|
||||||
/* If buffer is fully consumed, refill from start. */
|
// If buffer is fully consumed, refill from start.
|
||||||
if(unreadBytes == 0) {
|
if(unreadBytes == 0) {
|
||||||
reader->bufferStart = 0;
|
reader->bufferStart = 0;
|
||||||
reader->bufferEnd = 0;
|
reader->bufferEnd = 0;
|
||||||
@@ -283,18 +349,14 @@ errorret_t assetFileLineReaderFill(assetfilelinereader_t *reader) {
|
|||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
// There are unread bytes left but no newline in them.
|
||||||
* There are unread bytes left but no newline in them.
|
// If bufferStart > 0, slide unread bytes to front so we can read more.
|
||||||
* If bufferStart > 0, slide unread bytes to front so we can read more.
|
// This only happens when necessary to make space.
|
||||||
* This only happens when necessary to make space.
|
|
||||||
*/
|
|
||||||
if(reader->bufferEnd == reader->readBufferSize) {
|
if(reader->bufferEnd == reader->readBufferSize) {
|
||||||
if(reader->bufferStart == 0) {
|
if(reader->bufferStart == 0) {
|
||||||
/*
|
// Entire read buffer is unread and contains no newline.
|
||||||
* Entire read buffer is unread and contains no newline.
|
// Caller must have a large enough outBuffer to accumulate across fills,
|
||||||
* Caller must have a large enough outBuffer to accumulate across fills,
|
// so we consume these bytes into outBuffer before refilling.
|
||||||
* so we consume these bytes into outBuffer before refilling.
|
|
||||||
*/
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,7 +399,7 @@ errorret_t assetFileLineReaderNext(assetfilelinereader_t *reader) {
|
|||||||
size_t chunkLength = (size_t)newlineIndex - reader->bufferStart;
|
size_t chunkLength = (size_t)newlineIndex - reader->bufferStart;
|
||||||
errorret_t ret;
|
errorret_t ret;
|
||||||
|
|
||||||
/* strip CR in CRLF */
|
// strip CR in CRLF
|
||||||
if(
|
if(
|
||||||
chunkLength > 0 &&
|
chunkLength > 0 &&
|
||||||
reader->readBuffer[(size_t)newlineIndex - 1] == '\r'
|
reader->readBuffer[(size_t)newlineIndex - 1] == '\r'
|
||||||
|
|||||||
@@ -11,6 +11,12 @@
|
|||||||
|
|
||||||
#define ASSET_FILE_NAME_MAX 48
|
#define ASSET_FILE_NAME_MAX 48
|
||||||
|
|
||||||
|
// Max bytes requested per zip_fread() call in assetFileRead(). Some
|
||||||
|
// zip_fread() implementations (seen on PSP) reject a single call asking
|
||||||
|
// for very large amounts of data at once; the locale line reader has
|
||||||
|
// always used 1024-byte reads successfully, so that's the proven-safe cap.
|
||||||
|
#define ASSET_FILE_READ_CHUNK_MAX 1024
|
||||||
|
|
||||||
typedef struct assetfile_s assetfile_t;
|
typedef struct assetfile_s assetfile_t;
|
||||||
|
|
||||||
typedef errorret_t (*assetfileloader_t)(assetfile_t *file);
|
typedef errorret_t (*assetfileloader_t)(assetfile_t *file);
|
||||||
@@ -26,6 +32,11 @@ typedef struct assetfile_s {
|
|||||||
zip_int64_t position;
|
zip_int64_t position;
|
||||||
zip_int64_t lastRead;
|
zip_int64_t lastRead;
|
||||||
zip_file_t *zipFile;
|
zip_file_t *zipFile;
|
||||||
|
|
||||||
|
// The archive this file was found in (ASSET.zip or ASSET.zipStored),
|
||||||
|
// set by assetFileInit and used by assetFileOpen so lookups fall back
|
||||||
|
// correctly between the two dusk.dsk archives.
|
||||||
|
zip_t *sourceZip;
|
||||||
} assetfile_t;
|
} assetfile_t;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -144,6 +155,63 @@ void assetFileLineReaderInit(
|
|||||||
const size_t outBufferSize
|
const size_t outBufferSize
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the number of bytes still unread in the line reader's read buffer.
|
||||||
|
*
|
||||||
|
* @param reader The line reader to check.
|
||||||
|
* @return Number of unread bytes remaining in the read buffer.
|
||||||
|
*/
|
||||||
|
size_t assetFileLineReaderUnreadBytes(const assetfilelinereader_t *reader);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a pointer to the first unread byte in the line reader's read
|
||||||
|
* buffer.
|
||||||
|
*
|
||||||
|
* @param reader The line reader to check.
|
||||||
|
* @return Pointer to the first unread byte.
|
||||||
|
*/
|
||||||
|
const uint8_t *assetFileLineReaderUnreadPtr(
|
||||||
|
const assetfilelinereader_t *reader
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Appends src to the line reader's current line buffer, growing lineLength.
|
||||||
|
*
|
||||||
|
* @param reader The line reader whose out buffer to append to.
|
||||||
|
* @param src Bytes to append.
|
||||||
|
* @param srcLength Number of bytes in src.
|
||||||
|
* @return Error state if any (the line would exceed the output buffer).
|
||||||
|
*/
|
||||||
|
errorret_t assetFileLineReaderAppend(
|
||||||
|
assetfilelinereader_t *reader,
|
||||||
|
const uint8_t *src,
|
||||||
|
size_t srcLength
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Null-terminates the line reader's current line buffer at lineLength.
|
||||||
|
*
|
||||||
|
* @param reader The line reader whose out buffer to terminate.
|
||||||
|
*/
|
||||||
|
void assetFileLineReaderTerminate(assetfilelinereader_t *reader);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Searches the line reader's unread buffered bytes for a newline character.
|
||||||
|
*
|
||||||
|
* @param reader The line reader to search.
|
||||||
|
* @return The index of the newline within readBuffer, or -1 if not found.
|
||||||
|
*/
|
||||||
|
ssize_t assetFileLineReaderFindNewline(const assetfilelinereader_t *reader);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Refills the line reader's read buffer from the underlying file once its
|
||||||
|
* buffered bytes are fully consumed. A no-op once the file is at EOF.
|
||||||
|
*
|
||||||
|
* @param reader The line reader to refill.
|
||||||
|
* @return Error state if any.
|
||||||
|
*/
|
||||||
|
errorret_t assetFileLineReaderFill(assetfilelinereader_t *reader);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reads the next line from the asset file into the line buffer. The line
|
* Reads the next line from the asset file into the line buffer. The line
|
||||||
* buffer is null-terminated and does not include the newline character.
|
* buffer is null-terminated and does not include the newline character.
|
||||||
|
|||||||
@@ -17,3 +17,6 @@ add_subdirectory(locale)
|
|||||||
add_subdirectory(json)
|
add_subdirectory(json)
|
||||||
add_subdirectory(chunk)
|
add_subdirectory(chunk)
|
||||||
add_subdirectory(dmf)
|
add_subdirectory(dmf)
|
||||||
|
add_subdirectory(cutscene)
|
||||||
|
add_subdirectory(wav)
|
||||||
|
add_subdirectory(mp3)
|
||||||
@@ -35,22 +35,6 @@ void assetEntryInit(
|
|||||||
entry->input = NULL;
|
entry->input = NULL;
|
||||||
}
|
}
|
||||||
refInit(&entry->refs, entry, NULL, NULL, 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) {
|
void assetEntryLock(assetentry_t *entry) {
|
||||||
@@ -97,7 +81,7 @@ errorret_t assetEntryDispose(assetentry_t *entry) {
|
|||||||
"Asset entry still refed at dispose time."
|
"Asset entry still refed at dispose time."
|
||||||
);
|
);
|
||||||
|
|
||||||
eventInvoke(&entry->onUnloaded, entry);
|
if(entry->onUnloaded) entry->onUnloaded(entry, entry->onUnloadedUser);
|
||||||
errorChain(ASSET_LOADER_CALLBACKS[entry->type].dispose(entry));
|
errorChain(ASSET_LOADER_CALLBACKS[entry->type].dispose(entry));
|
||||||
memoryZero(entry, sizeof(assetentry_t));
|
memoryZero(entry, sizeof(assetentry_t));
|
||||||
errorOk();
|
errorOk();
|
||||||
|
|||||||
@@ -7,7 +7,6 @@
|
|||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "asset/loader/assetloading.h"
|
#include "asset/loader/assetloading.h"
|
||||||
#include "event/event.h"
|
|
||||||
#include "util/ref.h"
|
#include "util/ref.h"
|
||||||
|
|
||||||
typedef enum {
|
typedef enum {
|
||||||
@@ -20,11 +19,17 @@ typedef enum {
|
|||||||
ASSET_ENTRY_STATE_ERROR
|
ASSET_ENTRY_STATE_ERROR
|
||||||
} assetentrystate_t;
|
} assetentrystate_t;
|
||||||
|
|
||||||
/** Maximum number of subscribers for each per-entry event. */
|
|
||||||
#define ASSET_ENTRY_EVENT_MAX 2
|
|
||||||
|
|
||||||
typedef struct assetentry_s assetentry_t;
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A single asset entry callback. Each entry supports at most one subscriber
|
||||||
|
* per event - a second assignment without clearing the first is a bug.
|
||||||
|
*
|
||||||
|
* @param entry The assetentry_t the event fired on.
|
||||||
|
* @param user The user pointer passed alongside the callback.
|
||||||
|
*/
|
||||||
|
typedef void (*assetentrycallback_t)(assetentry_t *entry, void *user);
|
||||||
|
|
||||||
struct assetentry_s {
|
struct assetentry_s {
|
||||||
char_t name[ASSET_FILE_NAME_MAX];
|
char_t name[ASSET_FILE_NAME_MAX];
|
||||||
assetloadertype_t type;
|
assetloadertype_t type;
|
||||||
@@ -33,30 +38,27 @@ struct assetentry_s {
|
|||||||
ref_t refs;
|
ref_t refs;
|
||||||
assetloaderinput_t *input;
|
assetloaderinput_t *input;
|
||||||
assetloaderinput_t inputData;
|
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 *).
|
* Fired once when loading completes successfully.
|
||||||
* The asset data is still accessible when the callback runs.
|
|
||||||
* Always invoked on the main thread.
|
* Always invoked on the main thread.
|
||||||
*/
|
*/
|
||||||
event_t onUnloaded;
|
assetentrycallback_t onLoaded;
|
||||||
eventcallback_t onUnloadedCallbacks[ASSET_ENTRY_EVENT_MAX];
|
void *onLoadedUser;
|
||||||
void *onUnloadedUsers[ASSET_ENTRY_EVENT_MAX];
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fired once when loading fails (params = assetentry_t *).
|
* Fired once when the entry is disposed/reaped. The asset data is still
|
||||||
|
* accessible when the callback runs. Always invoked on the main thread.
|
||||||
|
*/
|
||||||
|
assetentrycallback_t onUnloaded;
|
||||||
|
void *onUnloadedUser;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fired once when loading fails.
|
||||||
* Always invoked on the main thread.
|
* Always invoked on the main thread.
|
||||||
*/
|
*/
|
||||||
event_t onError;
|
assetentrycallback_t onError;
|
||||||
eventcallback_t onErrorCallbacks[ASSET_ENTRY_EVENT_MAX];
|
void *onErrorUser;
|
||||||
void *onErrorUsers[ASSET_ENTRY_EVENT_MAX];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -51,4 +51,22 @@ assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = {
|
|||||||
.loadAsync = assetChunkLoaderAsync,
|
.loadAsync = assetChunkLoaderAsync,
|
||||||
.dispose = assetChunkDispose
|
.dispose = assetChunkDispose
|
||||||
},
|
},
|
||||||
|
|
||||||
|
[ASSET_LOADER_TYPE_CUTSCENE] = {
|
||||||
|
.loadSync = assetCutsceneLoaderSync,
|
||||||
|
.loadAsync = assetCutsceneLoaderAsync,
|
||||||
|
.dispose = assetCutsceneDispose
|
||||||
|
},
|
||||||
|
|
||||||
|
[ASSET_LOADER_TYPE_WAV] = {
|
||||||
|
.loadSync = assetWavLoaderSync,
|
||||||
|
.loadAsync = assetWavLoaderAsync,
|
||||||
|
.dispose = assetWavDispose
|
||||||
|
},
|
||||||
|
|
||||||
|
[ASSET_LOADER_TYPE_MP3] = {
|
||||||
|
.loadSync = assetMp3LoaderSync,
|
||||||
|
.loadAsync = assetMp3LoaderAsync,
|
||||||
|
.dispose = assetMp3Dispose
|
||||||
|
},
|
||||||
};
|
};
|
||||||
@@ -13,6 +13,9 @@
|
|||||||
#include "asset/loader/locale/assetlocaleloader.h"
|
#include "asset/loader/locale/assetlocaleloader.h"
|
||||||
#include "asset/loader/json/assetjsonloader.h"
|
#include "asset/loader/json/assetjsonloader.h"
|
||||||
#include "asset/loader/chunk/assetchunkloader.h"
|
#include "asset/loader/chunk/assetchunkloader.h"
|
||||||
|
#include "asset/loader/cutscene/assetcutsceneloader.h"
|
||||||
|
#include "asset/loader/wav/assetwavloader.h"
|
||||||
|
#include "asset/loader/mp3/assetmp3loader.h"
|
||||||
|
|
||||||
typedef enum {
|
typedef enum {
|
||||||
ASSET_LOADER_TYPE_NULL,
|
ASSET_LOADER_TYPE_NULL,
|
||||||
@@ -24,6 +27,9 @@ typedef enum {
|
|||||||
ASSET_LOADER_TYPE_LOCALE,
|
ASSET_LOADER_TYPE_LOCALE,
|
||||||
ASSET_LOADER_TYPE_JSON,
|
ASSET_LOADER_TYPE_JSON,
|
||||||
ASSET_LOADER_TYPE_CHUNK,
|
ASSET_LOADER_TYPE_CHUNK,
|
||||||
|
ASSET_LOADER_TYPE_CUTSCENE,
|
||||||
|
ASSET_LOADER_TYPE_WAV,
|
||||||
|
ASSET_LOADER_TYPE_MP3,
|
||||||
|
|
||||||
ASSET_LOADER_TYPE_COUNT
|
ASSET_LOADER_TYPE_COUNT
|
||||||
} assetloadertype_t;
|
} assetloadertype_t;
|
||||||
@@ -36,6 +42,9 @@ typedef union {
|
|||||||
assetlocaleloaderloading_t locale;
|
assetlocaleloaderloading_t locale;
|
||||||
assetjsonloaderloading_t json;
|
assetjsonloaderloading_t json;
|
||||||
assetchunkloaderloading_t chunk;
|
assetchunkloaderloading_t chunk;
|
||||||
|
assetcutsceneloaderloading_t cutscene;
|
||||||
|
assetwavloaderloading_t wav;
|
||||||
|
assetmp3loaderloading_t mp3;
|
||||||
} assetloaderloading_t;
|
} assetloaderloading_t;
|
||||||
|
|
||||||
typedef union {
|
typedef union {
|
||||||
@@ -46,6 +55,9 @@ typedef union {
|
|||||||
assetlocaleoutput_t locale;
|
assetlocaleoutput_t locale;
|
||||||
assetjsonoutput_t json;
|
assetjsonoutput_t json;
|
||||||
assetchunkoutput_t chunk;
|
assetchunkoutput_t chunk;
|
||||||
|
assetcutsceneoutput_t cutscene;
|
||||||
|
assetwavoutput_t wav;
|
||||||
|
assetmp3output_t mp3;
|
||||||
} assetloaderoutput_t;
|
} assetloaderoutput_t;
|
||||||
|
|
||||||
typedef union {
|
typedef union {
|
||||||
@@ -54,6 +66,9 @@ typedef union {
|
|||||||
assetlocaleloaderinput_t locale;
|
assetlocaleloaderinput_t locale;
|
||||||
assetjsonloaderinput_t json;
|
assetjsonloaderinput_t json;
|
||||||
assetchunkloaderinput_t chunk;
|
assetchunkloaderinput_t chunk;
|
||||||
|
assetcutsceneloaderinput_t cutscene;
|
||||||
|
assetwavloaderinput_t wav;
|
||||||
|
assetmp3loaderinput_t mp3;
|
||||||
} assetloaderinput_t;
|
} assetloaderinput_t;
|
||||||
|
|
||||||
typedef struct assetloading_s assetloading_t;
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
|||||||
@@ -13,26 +13,7 @@
|
|||||||
#include "asset/loader/assetentry.h"
|
#include "asset/loader/assetentry.h"
|
||||||
#include "asset/loader/assetloader.h"
|
#include "asset/loader/assetloader.h"
|
||||||
#include "asset/asset.h"
|
#include "asset/asset.h"
|
||||||
|
#include "rpg/overworld/worldpos.h"
|
||||||
// Reads a little-endian int16 from a potentially-unaligned offset into a
|
|
||||||
// worldunit_t, advancing *offset past it.
|
|
||||||
static worldunit_t assetChunkReadWorldUnit(
|
|
||||||
const uint8_t *data,
|
|
||||||
size_t *offset
|
|
||||||
) {
|
|
||||||
int16_t value;
|
|
||||||
memoryCopy(&value, data + *offset, sizeof(int16_t));
|
|
||||||
*offset += sizeof(int16_t);
|
|
||||||
return (worldunit_t)endianLittleToHost16((uint16_t)value);
|
|
||||||
}
|
|
||||||
|
|
||||||
static worldpos_t assetChunkReadWorldPos(const uint8_t *data, size_t *offset) {
|
|
||||||
worldpos_t pos;
|
|
||||||
pos.x = assetChunkReadWorldUnit(data, offset);
|
|
||||||
pos.y = assetChunkReadWorldUnit(data, offset);
|
|
||||||
pos.z = assetChunkReadWorldUnit(data, offset);
|
|
||||||
return pos;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetChunkLoaderAsync(assetloading_t *loading) {
|
errorret_t assetChunkLoaderAsync(assetloading_t *loading) {
|
||||||
assertNotNull(loading, "Loading cannot be NULL");
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
@@ -196,7 +177,7 @@ errorret_t assetChunkLoaderSync(assetloading_t *loading) {
|
|||||||
spawn->itemQuantity = 0;
|
spawn->itemQuantity = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
spawn->position = assetChunkReadWorldPos(data, &offset);
|
spawn->position = worldPosReadLE(data, &offset);
|
||||||
}
|
}
|
||||||
|
|
||||||
out->areaSpawnCount = data[offset];
|
out->areaSpawnCount = data[offset];
|
||||||
@@ -208,8 +189,8 @@ errorret_t assetChunkLoaderSync(assetloading_t *loading) {
|
|||||||
|
|
||||||
for(uint8_t s = 0; s < out->areaSpawnCount; s++) {
|
for(uint8_t s = 0; s < out->areaSpawnCount; s++) {
|
||||||
chunkareaspawn_t *area = &out->areaSpawns[s];
|
chunkareaspawn_t *area = &out->areaSpawns[s];
|
||||||
area->min = assetChunkReadWorldPos(data, &offset);
|
area->min = worldPosReadLE(data, &offset);
|
||||||
area->max = assetChunkReadWorldPos(data, &offset);
|
area->max = worldPosReadLE(data, &offset);
|
||||||
|
|
||||||
uint16_t callbackId;
|
uint16_t callbackId;
|
||||||
memoryCopy(&callbackId, data + offset, sizeof(uint16_t));
|
memoryCopy(&callbackId, data + offset, sizeof(uint16_t));
|
||||||
|
|||||||
+1
-2
@@ -5,6 +5,5 @@
|
|||||||
|
|
||||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
PUBLIC
|
PUBLIC
|
||||||
uiinitialnocard.c
|
assetcutsceneloader.c
|
||||||
uiinitialcreatesave.c
|
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "assetcutsceneloader.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include "util/string.h"
|
||||||
|
#include "asset/loader/assetloading.h"
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
#include "asset/loader/assetloader.h"
|
||||||
|
#include "asset/asset.h"
|
||||||
|
#include "rpg/cutscene/item/json/cutscenejsonpauseflags.h"
|
||||||
|
|
||||||
|
errorret_t assetCutsceneParseItem(
|
||||||
|
assetloading_t *loading,
|
||||||
|
yyjson_val *itemObj,
|
||||||
|
cutsceneitem_t *item,
|
||||||
|
uint8_t *pool,
|
||||||
|
size_t *poolOffset,
|
||||||
|
const uint8_t index
|
||||||
|
) {
|
||||||
|
if(!yyjson_is_obj(itemObj)) {
|
||||||
|
assetLoaderErrorThrow(
|
||||||
|
loading,
|
||||||
|
"Cutscene item %u is not an object",
|
||||||
|
(uint32_t)index
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const char_t *typeName = yyjson_get_str(yyjson_obj_get(itemObj, "type"));
|
||||||
|
if(!cutsceneItemLookupType(typeName, &item->type)) {
|
||||||
|
assetLoaderErrorThrow(
|
||||||
|
loading,
|
||||||
|
"Cutscene item %u: missing/unsupported item type %s",
|
||||||
|
(uint32_t)index,
|
||||||
|
typeName
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
cutsceneitemloadcallback_t *load = CUTSCENE_ITEM_CALLBACKS[item->type].load;
|
||||||
|
if(load == NULL) {
|
||||||
|
assetLoaderErrorThrow(
|
||||||
|
loading, "Cutscene item %u: unhandled item type %u", (uint32_t)index,
|
||||||
|
(uint32_t)item->type
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t result = load(itemObj, item, pool, poolOffset);
|
||||||
|
if(errorIsNotOk(result)) {
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
|
||||||
|
errorChain(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t assetCutsceneComputePoolSize(yyjson_val *itemsArr) {
|
||||||
|
size_t size = 0;
|
||||||
|
yyjson_arr_iter iter = yyjson_arr_iter_with(itemsArr);
|
||||||
|
yyjson_val *itemVal;
|
||||||
|
while((itemVal = yyjson_arr_iter_next(&iter)) != NULL) {
|
||||||
|
const char_t *typeName = yyjson_get_str(yyjson_obj_get(itemVal, "type"));
|
||||||
|
cutsceneitemtype_t type;
|
||||||
|
if(!cutsceneItemLookupType(typeName, &type)) continue;
|
||||||
|
|
||||||
|
cutsceneitempoolsizecallback_t *poolSize =
|
||||||
|
CUTSCENE_ITEM_CALLBACKS[type].poolSize;
|
||||||
|
if(poolSize == NULL) continue;
|
||||||
|
|
||||||
|
size = cutsceneJsonPoolAlign(size) + poolSize(itemVal);
|
||||||
|
}
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetCutsceneFreeParsed(assetcutsceneoutput_t *out) {
|
||||||
|
if(out->items != NULL) {
|
||||||
|
memoryFree(out->items);
|
||||||
|
out->items = NULL;
|
||||||
|
}
|
||||||
|
if(out->pool != NULL) {
|
||||||
|
memoryFree(out->pool);
|
||||||
|
out->pool = NULL;
|
||||||
|
}
|
||||||
|
if(out->doc != NULL) {
|
||||||
|
yyjson_doc_free(out->doc);
|
||||||
|
out->doc = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetCutsceneLoaderAsync(assetloading_t *loading) {
|
||||||
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertNotMainThread("Should be called from an async thread.");
|
||||||
|
|
||||||
|
if(
|
||||||
|
loading->loading.cutscene.state != ASSET_CUTSCENE_LOADING_STATE_READ_FILE
|
||||||
|
) {
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
assertNull(loading->loading.cutscene.buffer, "Buffer already defined?");
|
||||||
|
|
||||||
|
assetfile_t *file = &loading->loading.cutscene.file;
|
||||||
|
assetLoaderErrorChain(loading,
|
||||||
|
assetFileInit(file, loading->entry->name, NULL, NULL)
|
||||||
|
);
|
||||||
|
|
||||||
|
if(file->size > ASSET_CUTSCENE_FILE_SIZE_MAX) {
|
||||||
|
assetLoaderErrorThrow(
|
||||||
|
loading, "Cutscene 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 cutscene file."
|
||||||
|
);
|
||||||
|
assetLoaderErrorChain(loading, assetFileClose(file));
|
||||||
|
assetLoaderErrorChain(loading, assetFileDispose(file));
|
||||||
|
|
||||||
|
loading->loading.cutscene.buffer = buffer;
|
||||||
|
loading->loading.cutscene.size = fileSize;
|
||||||
|
loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_PARSE;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetCutsceneLoaderSync(assetloading_t *loading) {
|
||||||
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertTrue(loading->type == ASSET_LOADER_TYPE_CUTSCENE, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
if(loading->loading.cutscene.state == ASSET_CUTSCENE_LOADING_STATE_INITIAL) {
|
||||||
|
loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_READ_FILE;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
assetcutsceneoutput_t *out = &loading->entry->data.cutscene;
|
||||||
|
uint8_t *buffer = loading->loading.cutscene.buffer;
|
||||||
|
assertNotNull(buffer, "Cutscene data should have been loaded by now.");
|
||||||
|
size_t bufferSize = loading->loading.cutscene.size;
|
||||||
|
|
||||||
|
yyjson_doc *doc = yyjson_read(
|
||||||
|
(char *)buffer, bufferSize,
|
||||||
|
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
|
||||||
|
);
|
||||||
|
memoryFree(buffer);
|
||||||
|
loading->loading.cutscene.buffer = NULL;
|
||||||
|
|
||||||
|
if(doc == NULL) {
|
||||||
|
assetLoaderErrorThrow(loading, "Failed to parse cutscene JSON");
|
||||||
|
}
|
||||||
|
out->doc = doc;
|
||||||
|
|
||||||
|
yyjson_val *root = yyjson_doc_get_root(doc);
|
||||||
|
yyjson_val *itemsArr = yyjson_obj_get(root, "items");
|
||||||
|
if(!yyjson_is_arr(itemsArr)) {
|
||||||
|
assetCutsceneFreeParsed(out);
|
||||||
|
assetLoaderErrorThrow(loading, "Cutscene JSON is missing an 'items' array");
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t itemCount = yyjson_arr_size(itemsArr);
|
||||||
|
if(itemCount > UINT8_MAX) {
|
||||||
|
assetCutsceneFreeParsed(out);
|
||||||
|
assetLoaderErrorThrow(loading, "Cutscene has more than 255 items");
|
||||||
|
}
|
||||||
|
|
||||||
|
cutscenepause_t pause = CUTSCENE_PAUSE_DEFAULT;
|
||||||
|
yyjson_val *pauseArr = yyjson_obj_get(root, "pause");
|
||||||
|
if(yyjson_is_arr(pauseArr)) {
|
||||||
|
if(!cutsceneJsonParsePauseFlags(pauseArr, &pause)) {
|
||||||
|
assetCutsceneFreeParsed(out);
|
||||||
|
assetLoaderErrorThrow(
|
||||||
|
loading, "Cutscene JSON has an invalid 'pause' flag"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out->items = memoryAllocate(itemCount * sizeof(cutsceneitem_t));
|
||||||
|
memoryZero(out->items, itemCount * sizeof(cutsceneitem_t));
|
||||||
|
|
||||||
|
size_t poolSize = assetCutsceneComputePoolSize(itemsArr);
|
||||||
|
out->pool = poolSize > 0 ? memoryAllocate(poolSize) : NULL;
|
||||||
|
|
||||||
|
size_t poolOffset = 0;
|
||||||
|
yyjson_arr_iter itemIter = yyjson_arr_iter_with(itemsArr);
|
||||||
|
yyjson_val *itemVal;
|
||||||
|
uint8_t index = 0;
|
||||||
|
while((itemVal = yyjson_arr_iter_next(&itemIter)) != NULL) {
|
||||||
|
errorret_t itemResult = assetCutsceneParseItem(
|
||||||
|
loading, itemVal, &out->items[index], out->pool, &poolOffset, index
|
||||||
|
);
|
||||||
|
if(errorIsNotOk(itemResult)) {
|
||||||
|
assetCutsceneFreeParsed(out);
|
||||||
|
errorChain(itemResult);
|
||||||
|
}
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
out->cutscene.items = out->items;
|
||||||
|
out->cutscene.itemCount = (uint8_t)itemCount;
|
||||||
|
out->cutscene.pause = pause;
|
||||||
|
out->cutscene.dataSize = 0;
|
||||||
|
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetCutsceneDispose(assetentry_t *entry) {
|
||||||
|
assertNotNull(entry, "Entry cannot be NULL");
|
||||||
|
assertTrue(entry->type == ASSET_LOADER_TYPE_CUTSCENE, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
assetCutsceneFreeParsed(&entry->data.cutscene);
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
@@ -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/assetfile.h"
|
||||||
|
#include "rpg/cutscene/cutscene.h"
|
||||||
|
#include "rpg/cutscene/item/cutsceneitem.h"
|
||||||
|
#include "rpg/cutscene/item/json/cutscenejsonpool.h"
|
||||||
|
#include "yyjson.h"
|
||||||
|
|
||||||
|
#define ASSET_CUTSCENE_FILE_SIZE_MAX (1024 * 64)
|
||||||
|
|
||||||
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
void *nothing;
|
||||||
|
} assetcutsceneloaderinput_t;
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_CUTSCENE_LOADING_STATE_INITIAL,
|
||||||
|
ASSET_CUTSCENE_LOADING_STATE_READ_FILE,
|
||||||
|
ASSET_CUTSCENE_LOADING_STATE_PARSE
|
||||||
|
} assetcutsceneloadingstate_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
assetfile_t file;
|
||||||
|
assetcutsceneloadingstate_t state;
|
||||||
|
uint8_t *buffer;
|
||||||
|
size_t size;
|
||||||
|
} assetcutsceneloaderloading_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
cutscene_t cutscene;
|
||||||
|
cutsceneitem_t *items;
|
||||||
|
uint8_t *pool;
|
||||||
|
yyjson_doc *doc;
|
||||||
|
} assetcutsceneoutput_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses one cutscene item object into item, writing any pool-backed
|
||||||
|
* array data (entityWalkTo positions, mapAreaWait areaIds) into pool at
|
||||||
|
* *poolOffset and advancing it. Every field/enum name is validated as
|
||||||
|
* real (untrusted, authored) file content - failures are real errors, not
|
||||||
|
* asserts. Dispatches to the matching type's Load callback (see
|
||||||
|
* CUTSCENE_ITEM_CALLBACKS in rpg/cutscene/item/cutsceneitem.h) - the
|
||||||
|
* per-type parsing logic itself lives there now, colocated with that
|
||||||
|
* type's runtime behavior.
|
||||||
|
*
|
||||||
|
* @param loading Loading information for the asset being loaded.
|
||||||
|
* @param itemObj The item's JSON object.
|
||||||
|
* @param item Destination item, already zeroed by the caller.
|
||||||
|
* @param pool Base pointer of the entry's pool allocation (may be NULL if
|
||||||
|
* assetCutsceneComputePoolSize returned 0).
|
||||||
|
* @param poolOffset In/out cursor into pool.
|
||||||
|
* @param index Index of this item within the cutscene, for error messages.
|
||||||
|
* @return Error code indicating success or failure of the parse.
|
||||||
|
*/
|
||||||
|
errorret_t assetCutsceneParseItem(
|
||||||
|
assetloading_t *loading,
|
||||||
|
yyjson_val *itemObj,
|
||||||
|
cutsceneitem_t *item,
|
||||||
|
uint8_t *pool,
|
||||||
|
size_t *poolOffset,
|
||||||
|
const uint8_t index
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Frees whatever of out->items/out->pool/out->doc is currently non-NULL
|
||||||
|
* and clears them - shared by both the normal disposer and every parse
|
||||||
|
* failure path's cleanup.
|
||||||
|
*
|
||||||
|
* @param out The output to free.
|
||||||
|
*/
|
||||||
|
void assetCutsceneFreeParsed(assetcutsceneoutput_t *out);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asynchronous loader for cutscene assets. Reads the raw JSONC 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 assetCutsceneLoaderAsync(assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Synchronous loader for cutscene assets. Parses the JSONC previously read
|
||||||
|
* by the async phase into a heap-allocated cutsceneitem_t array + pool.
|
||||||
|
*
|
||||||
|
* @param loading Loading information for the asset being loaded.
|
||||||
|
* @return Error code indicating success or failure of the load operation.
|
||||||
|
*/
|
||||||
|
errorret_t assetCutsceneLoaderSync(assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposer for cutscene assets.
|
||||||
|
*
|
||||||
|
* @param entry Asset entry containing the cutscene data to dispose.
|
||||||
|
* @return Error code indicating success or failure of the dispose operation.
|
||||||
|
*/
|
||||||
|
errorret_t assetCutsceneDispose(assetentry_t *entry);
|
||||||
@@ -62,7 +62,7 @@ errorret_t assetModelLoaderSync(assetloading_t *loading) {
|
|||||||
|
|
||||||
// Parse required mesh path.
|
// Parse required mesh path.
|
||||||
yyjson_val *meshVal = yyjson_obj_get(root, "mesh");
|
yyjson_val *meshVal = yyjson_obj_get(root, "mesh");
|
||||||
if(!meshVal || !yyjson_is_str(meshVal)) {
|
if(meshVal == NULL || !yyjson_is_str(meshVal)) {
|
||||||
assetUnlockEntry(jsonEntry);
|
assetUnlockEntry(jsonEntry);
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
|
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
|
||||||
errorThrow("Model JSON missing 'mesh' string");
|
errorThrow("Model JSON missing 'mesh' string");
|
||||||
@@ -115,7 +115,8 @@ errorret_t assetModelLoaderSync(assetloading_t *loading) {
|
|||||||
assetUnlockEntry(jsonEntry);
|
assetUnlockEntry(jsonEntry);
|
||||||
|
|
||||||
// Lock and load the mesh sub-asset.
|
// Lock and load the mesh sub-asset.
|
||||||
assetentry_t *meshEntry = assetLock(meshName, ASSET_LOADER_TYPE_MESH, NULL);
|
assetentry_t *meshEntry =
|
||||||
|
assetLock(meshName, ASSET_LOADER_TYPE_MESH, NULL);
|
||||||
ret = assetRequireLoaded(meshEntry);
|
ret = assetRequireLoaded(meshEntry);
|
||||||
if(errorIsNotOk(ret)) {
|
if(errorIsNotOk(ret)) {
|
||||||
assetUnlockEntry(meshEntry);
|
assetUnlockEntry(meshEntry);
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ typedef struct {
|
|||||||
* on the main thread; this callback is never reached.
|
* on the main thread; this callback is never reached.
|
||||||
*
|
*
|
||||||
* @param loading Loading information for the asset being loaded.
|
* @param loading Loading information for the asset being loaded.
|
||||||
* @returns Always success.
|
* @return Always success.
|
||||||
*/
|
*/
|
||||||
errorret_t assetModelLoaderAsync(assetloading_t *loading);
|
errorret_t assetModelLoaderAsync(assetloading_t *loading);
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ errorret_t assetModelLoaderAsync(assetloading_t *loading);
|
|||||||
* within ASSET_LOADING_COUNT_MAX slot limits.
|
* within ASSET_LOADING_COUNT_MAX slot limits.
|
||||||
*
|
*
|
||||||
* @param loading Loading information for the asset being loaded.
|
* @param loading Loading information for the asset being loaded.
|
||||||
* @returns Error code indicating success or failure.
|
* @return Error code indicating success or failure.
|
||||||
*/
|
*/
|
||||||
errorret_t assetModelLoaderSync(assetloading_t *loading);
|
errorret_t assetModelLoaderSync(assetloading_t *loading);
|
||||||
|
|
||||||
@@ -53,6 +53,6 @@ errorret_t assetModelLoaderSync(assetloading_t *loading);
|
|||||||
* sub-asset entries.
|
* sub-asset entries.
|
||||||
*
|
*
|
||||||
* @param entry Asset entry containing the model to dispose.
|
* @param entry Asset entry containing the model to dispose.
|
||||||
* @returns Error code indicating success or failure.
|
* @return Error code indicating success or failure.
|
||||||
*/
|
*/
|
||||||
errorret_t assetModelDispose(assetentry_t *entry);
|
errorret_t assetModelDispose(assetentry_t *entry);
|
||||||
@@ -77,7 +77,7 @@ errorret_t assetJsonLoaderSync(assetloading_t *loading) {
|
|||||||
memoryFree(buffer);
|
memoryFree(buffer);
|
||||||
loading->loading.json.buffer = NULL;
|
loading->loading.json.buffer = NULL;
|
||||||
|
|
||||||
if(!loading->entry->data.json) {
|
if(loading->entry->data.json == NULL) {
|
||||||
assetLoaderErrorThrow(loading, "Failed to parse JSON");
|
assetLoaderErrorThrow(loading, "Failed to parse JSON");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -41,6 +41,32 @@ typedef struct {
|
|||||||
|
|
||||||
typedef yyjson_doc * assetjsonoutput_t;
|
typedef yyjson_doc * assetjsonoutput_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asynchronous loader callback. Opens the JSON file and reads the whole of
|
||||||
|
* it into a heap buffer, so the main thread is not blocked on I/O. The
|
||||||
|
* buffer is parsed later, on the main thread, by assetJsonLoaderSync. Sets
|
||||||
|
* the entry state to `ASSET_ENTRY_STATE_PENDING_SYNC` on success.
|
||||||
|
*
|
||||||
|
* @param loading The loading slot for this asset entry.
|
||||||
|
* @return OK on success, error otherwise.
|
||||||
|
*/
|
||||||
errorret_t assetJsonLoaderAsync(assetloading_t *loading);
|
errorret_t assetJsonLoaderAsync(assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Synchronous loader callback. Drives the load state machine: on the first
|
||||||
|
* call it queues the async read, and once that has completed it parses the
|
||||||
|
* buffer into a `yyjson_doc` (comments and trailing commas allowed), frees
|
||||||
|
* the buffer and marks the entry `ASSET_ENTRY_STATE_LOADED`.
|
||||||
|
*
|
||||||
|
* @param loading The loading slot for this asset entry.
|
||||||
|
* @return OK on success, error otherwise.
|
||||||
|
*/
|
||||||
errorret_t assetJsonLoaderSync(assetloading_t *loading);
|
errorret_t assetJsonLoaderSync(assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dispose callback. Frees the parsed `yyjson_doc` held by the entry.
|
||||||
|
*
|
||||||
|
* @param entry The asset entry to dispose.
|
||||||
|
* @return OK on success, error otherwise.
|
||||||
|
*/
|
||||||
errorret_t assetJsonDispose(assetentry_t *entry);
|
errorret_t assetJsonDispose(assetentry_t *entry);
|
||||||
@@ -30,8 +30,8 @@ errorret_t assetLocaleLoaderAsync(assetloading_t *loading) {
|
|||||||
assetLoaderErrorChain(loading, assetFileOpen(&localeFile->file));
|
assetLoaderErrorChain(loading, assetFileOpen(&localeFile->file));
|
||||||
|
|
||||||
char_t buffer[1024];
|
char_t buffer[1024];
|
||||||
assetLoaderErrorChain(loading, assetLocaleGetString(
|
assetLoaderErrorChain(loading, assetLocaleGetHeader(
|
||||||
localeFile, "", 0, buffer, sizeof(buffer)
|
localeFile, buffer, sizeof(buffer)
|
||||||
));
|
));
|
||||||
assetLoaderErrorChain(loading, assetLocaleParseHeader(
|
assetLoaderErrorChain(loading, assetLocaleParseHeader(
|
||||||
localeFile, buffer, sizeof(buffer)
|
localeFile, buffer, sizeof(buffer)
|
||||||
@@ -71,6 +71,12 @@ errorret_t assetLocaleDispose(assetentry_t *entry) {
|
|||||||
assertIsMainThread("Must be called from the main thread.");
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
assetlocalefile_t *localeFile = &entry->data.locale;
|
assetlocalefile_t *localeFile = &entry->data.locale;
|
||||||
|
|
||||||
|
if(localeFile->cache != NULL) {
|
||||||
|
memoryFree(localeFile->cache);
|
||||||
|
localeFile->cache = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
errorChain(assetFileClose(&localeFile->file));
|
errorChain(assetFileClose(&localeFile->file));
|
||||||
return assetFileDispose(&localeFile->file);
|
return assetFileDispose(&localeFile->file);
|
||||||
}
|
}
|
||||||
@@ -87,7 +93,7 @@ errorret_t assetLocaleParseHeader(
|
|||||||
|
|
||||||
// Find "Plural-Forms: " line and parse out plural form info
|
// Find "Plural-Forms: " line and parse out plural form info
|
||||||
char_t *pluralFormsLine = strstr(headerBuffer, "Plural-Forms:");
|
char_t *pluralFormsLine = strstr(headerBuffer, "Plural-Forms:");
|
||||||
if(!pluralFormsLine) {
|
if(pluralFormsLine == NULL) {
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,7 +101,7 @@ errorret_t assetLocaleParseHeader(
|
|||||||
|
|
||||||
// Expect nplurals
|
// Expect nplurals
|
||||||
char_t *npluralsStr = strstr(pluralFormsLine, "nplurals=");
|
char_t *npluralsStr = strstr(pluralFormsLine, "nplurals=");
|
||||||
if(!npluralsStr) {
|
if(npluralsStr == NULL) {
|
||||||
errorThrow("Failed to find nplurals in Plural-Forms header.");
|
errorThrow("Failed to find nplurals in Plural-Forms header.");
|
||||||
}
|
}
|
||||||
npluralsStr += strlen("nplurals=");
|
npluralsStr += strlen("nplurals=");
|
||||||
@@ -114,7 +120,7 @@ errorret_t assetLocaleParseHeader(
|
|||||||
|
|
||||||
// Expect plural=
|
// Expect plural=
|
||||||
char_t *pluralStr = strstr(pluralFormsLine, "plural=");
|
char_t *pluralStr = strstr(pluralFormsLine, "plural=");
|
||||||
if(!pluralStr) {
|
if(pluralStr == NULL) {
|
||||||
errorThrow("Failed to find plural in Plural-Forms header.");
|
errorThrow("Failed to find plural in Plural-Forms header.");
|
||||||
}
|
}
|
||||||
pluralStr += strlen("plural=");
|
pluralStr += strlen("plural=");
|
||||||
@@ -122,7 +128,7 @@ errorret_t assetLocaleParseHeader(
|
|||||||
// Expect ( [expressions] )
|
// Expect ( [expressions] )
|
||||||
char_t *openParen = strchr(pluralStr, '(');
|
char_t *openParen = strchr(pluralStr, '(');
|
||||||
char_t *closeParen = strrchr(pluralStr, ')');
|
char_t *closeParen = strrchr(pluralStr, ')');
|
||||||
if(!openParen || !closeParen || closeParen < openParen) {
|
if(openParen == NULL || closeParen == NULL || closeParen < openParen) {
|
||||||
errorThrow("Failed to find plural expression in Plural-Forms header.");
|
errorThrow("Failed to find plural expression in Plural-Forms header.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -393,12 +399,12 @@ errorret_t assetLocaleLineUnbuffer(
|
|||||||
|
|
||||||
// At the point this funciton is called, we are looking for an opening quote.
|
// At the point this funciton is called, we are looking for an opening quote.
|
||||||
char_t *start = strchr((char_t *)lineBuffer, '"');
|
char_t *start = strchr((char_t *)lineBuffer, '"');
|
||||||
if(!start) {
|
if(start == NULL) {
|
||||||
errorThrow("Expected open (0) \"");
|
errorThrow("Expected open (0) \"");
|
||||||
}
|
}
|
||||||
|
|
||||||
char *end = strchr(start + 1, '"');
|
char *end = strchr(start + 1, '"');
|
||||||
if(!end) {
|
if(end == NULL) {
|
||||||
errorThrow("Expected close (0) \"");
|
errorThrow("Expected close (0) \"");
|
||||||
}
|
}
|
||||||
*end = '\0';
|
*end = '\0';
|
||||||
@@ -470,7 +476,94 @@ errorret_t assetLocaleLineUnbuffer(
|
|||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetLocaleGetString(
|
errorret_t assetLocaleCacheFind(
|
||||||
|
assetlocalefile_t *file,
|
||||||
|
const char_t *messageId,
|
||||||
|
const int32_t pluralCount,
|
||||||
|
char_t *stringBuffer,
|
||||||
|
const size_t stringBufferSize,
|
||||||
|
bool_t *outHit
|
||||||
|
) {
|
||||||
|
assertNotNull(file, "Asset file cannot be NULL.");
|
||||||
|
assertNotNull(messageId, "Message ID cannot be NULL.");
|
||||||
|
assertNotNull(outHit, "outHit cannot be NULL.");
|
||||||
|
assertStrLenMin(messageId, 1, "Message ID cannot be empty.");
|
||||||
|
|
||||||
|
*outHit = false;
|
||||||
|
if(file->cache == NULL) errorOk();
|
||||||
|
|
||||||
|
assetlocalecache_t *cache = file->cache;
|
||||||
|
for(uint8_t i = 0; i < ASSET_LOCALE_CACHE_COUNT; i++) {
|
||||||
|
assetlocalecacheentry_t *entry = &cache->entries[i];
|
||||||
|
if(entry->messageId[0] == '\0') break;// unused tail - nothing further
|
||||||
|
if(entry->pluralCount != pluralCount) continue;
|
||||||
|
if(!stringEquals(entry->messageId, messageId)) continue;
|
||||||
|
|
||||||
|
// Move to the front of the LRU order (a no-op when already there).
|
||||||
|
if(i > 0) {
|
||||||
|
assetlocalecacheentry_t hit = *entry;
|
||||||
|
memoryMove(
|
||||||
|
&cache->entries[1], &cache->entries[0],
|
||||||
|
i * sizeof(assetlocalecacheentry_t)
|
||||||
|
);
|
||||||
|
cache->entries[0] = hit;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t len = strlen(cache->entries[0].value);
|
||||||
|
if(len >= stringBufferSize) errorThrow("String buffer overflow");
|
||||||
|
memoryCopy(stringBuffer, cache->entries[0].value, len + 1);
|
||||||
|
*outHit = true;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetLocaleCacheInsert(
|
||||||
|
assetlocalefile_t *file,
|
||||||
|
const char_t *messageId,
|
||||||
|
const int32_t pluralCount,
|
||||||
|
const char_t *value
|
||||||
|
) {
|
||||||
|
assertNotNull(file, "Asset file cannot be NULL.");
|
||||||
|
assertNotNull(messageId, "Message ID cannot be NULL.");
|
||||||
|
assertNotNull(value, "Value cannot be NULL.");
|
||||||
|
assertStrLenMin(messageId, 1, "Message ID cannot be empty.");
|
||||||
|
|
||||||
|
// Caching is a pure optimization - a message ID or value too long for a
|
||||||
|
// fixed cache slot is just never cached, not an error.
|
||||||
|
if(strlen(messageId) >= ASSET_LOCALE_CACHE_KEY_MAX) return;
|
||||||
|
if(strlen(value) >= ASSET_LOCALE_CACHE_VALUE_MAX) return;
|
||||||
|
|
||||||
|
if(file->cache == NULL) {
|
||||||
|
file->cache =
|
||||||
|
(assetlocalecache_t *)memoryAllocate(sizeof(assetlocalecache_t));
|
||||||
|
memoryZero(file->cache, sizeof(assetlocalecache_t));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shift every entry down one slot, dropping the least-recently-used one
|
||||||
|
// off the end, to make room for the new entry at the front. This assumes
|
||||||
|
// messageId is never already present elsewhere in the cache, which holds
|
||||||
|
// as long as callers only insert after a confirmed assetLocaleCacheFind
|
||||||
|
// miss (a hit would have returned before reaching this point).
|
||||||
|
memoryMove(
|
||||||
|
&file->cache->entries[1], &file->cache->entries[0],
|
||||||
|
(ASSET_LOCALE_CACHE_COUNT - 1) * sizeof(assetlocalecacheentry_t)
|
||||||
|
);
|
||||||
|
|
||||||
|
assetlocalecacheentry_t *entry = &file->cache->entries[0];
|
||||||
|
stringCopy(entry->messageId, messageId, ASSET_LOCALE_CACHE_KEY_MAX);
|
||||||
|
entry->pluralCount = pluralCount;
|
||||||
|
stringCopy(entry->value, value, ASSET_LOCALE_CACHE_VALUE_MAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shared by assetLocaleGetString (external callers, messageId required
|
||||||
|
// non-empty) and assetLocaleGetHeader (messageId "", the PO format's own
|
||||||
|
// sentinel for its header entry - see assetLocaleGetHeader). Caching is
|
||||||
|
// skipped entirely for an empty messageId: assetLocaleCacheFind/Insert
|
||||||
|
// both reject one outright (same guard as assetLocaleGetString's own),
|
||||||
|
// and it's a one-shot boot-time read anyway, not worth caching.
|
||||||
|
errorret_t assetLocaleGetStringLookup(
|
||||||
assetlocalefile_t *file,
|
assetlocalefile_t *file,
|
||||||
const char_t *messageId,
|
const char_t *messageId,
|
||||||
const int32_t pluralCount,
|
const int32_t pluralCount,
|
||||||
@@ -482,6 +575,15 @@ errorret_t assetLocaleGetString(
|
|||||||
assertTrue(pluralCount >= 0, "Plural index cannot be negative.");
|
assertTrue(pluralCount >= 0, "Plural index cannot be negative.");
|
||||||
assertNotNull(stringBuffer, "String buffer cannot be NULL.");
|
assertNotNull(stringBuffer, "String buffer cannot be NULL.");
|
||||||
assertTrue(stringBufferSize > 0, "String buffer size must be > 0");
|
assertTrue(stringBufferSize > 0, "String buffer size must be > 0");
|
||||||
|
|
||||||
|
bool_t cacheHit = false;
|
||||||
|
if(messageId[0] != '\0') {
|
||||||
|
errorChain(assetLocaleCacheFind(
|
||||||
|
file, messageId, pluralCount, stringBuffer, stringBufferSize, &cacheHit
|
||||||
|
));
|
||||||
|
if(cacheHit) errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
assetfilelinereader_t reader;
|
assetfilelinereader_t reader;
|
||||||
|
|
||||||
bool_t msgidFound = false, msgidPluralFound = false, msgstrFound = false;
|
bool_t msgidFound = false, msgidPluralFound = false, msgstrFound = false;
|
||||||
@@ -588,7 +690,7 @@ errorret_t assetLocaleGetString(
|
|||||||
|
|
||||||
// Parse until ]
|
// Parse until ]
|
||||||
char *end = strchr(ptr, ']');
|
char *end = strchr(ptr, ']');
|
||||||
if(!end) {
|
if(end == NULL) {
|
||||||
errorThrow("Expected ] for plural form, found: %s", lineBuffer);
|
errorThrow("Expected ] for plural form, found: %s", lineBuffer);
|
||||||
}
|
}
|
||||||
*end = '\0';
|
*end = '\0';
|
||||||
@@ -625,9 +727,38 @@ errorret_t assetLocaleGetString(
|
|||||||
errorThrow("Failed to find msgstr for message ID: %s", messageId);
|
errorThrow("Failed to find msgstr for message ID: %s", messageId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(messageId[0] != '\0') {
|
||||||
|
assetLocaleCacheInsert(file, messageId, pluralCount, stringBuffer);
|
||||||
|
}
|
||||||
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
errorret_t assetLocaleGetString(
|
||||||
|
assetlocalefile_t *file,
|
||||||
|
const char_t *messageId,
|
||||||
|
const int32_t pluralCount,
|
||||||
|
char_t *stringBuffer,
|
||||||
|
const size_t stringBufferSize
|
||||||
|
) {
|
||||||
|
assertNotNull(messageId, "Message ID cannot be NULL.");
|
||||||
|
assertStrLenMin(messageId, 1, "Message ID cannot be empty.");
|
||||||
|
|
||||||
|
return assetLocaleGetStringLookup(
|
||||||
|
file, messageId, pluralCount, stringBuffer, stringBufferSize
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetLocaleGetHeader(
|
||||||
|
assetlocalefile_t *file,
|
||||||
|
char_t *stringBuffer,
|
||||||
|
const size_t stringBufferSize
|
||||||
|
) {
|
||||||
|
return assetLocaleGetStringLookup(
|
||||||
|
file, "", 0, stringBuffer, stringBufferSize
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
errorret_t assetLocaleGetStringWithVA(
|
errorret_t assetLocaleGetStringWithVA(
|
||||||
assetlocalefile_t *file,
|
assetlocalefile_t *file,
|
||||||
const char_t *messageId,
|
const char_t *messageId,
|
||||||
@@ -723,7 +854,7 @@ errorret_t assetLocaleGetStringWithArgs(
|
|||||||
|
|
||||||
inIndex++;
|
inIndex++;
|
||||||
|
|
||||||
/* Escaped percent */
|
// Escaped percent
|
||||||
if(format[inIndex] == '%') {
|
if(format[inIndex] == '%') {
|
||||||
if(outIndex + 1 >= bufferSize) {
|
if(outIndex + 1 >= bufferSize) {
|
||||||
memoryFree(format);
|
memoryFree(format);
|
||||||
@@ -749,7 +880,7 @@ errorret_t assetLocaleGetStringWithArgs(
|
|||||||
|
|
||||||
specBuffer[specLength++] = '%';
|
specBuffer[specLength++] = '%';
|
||||||
|
|
||||||
/* Allow flags / width / precision */
|
// Allow flags / width / precision
|
||||||
while(format[inIndex] != '\0') {
|
while(format[inIndex] != '\0') {
|
||||||
char_t ch = format[inIndex];
|
char_t ch = format[inIndex];
|
||||||
|
|
||||||
|
|||||||
@@ -70,6 +70,41 @@ typedef struct {
|
|||||||
};
|
};
|
||||||
} assetlocalearg_t;
|
} assetlocalearg_t;
|
||||||
|
|
||||||
|
/** Number of recently resolved strings @ref assetlocalecache_t remembers. */
|
||||||
|
#define ASSET_LOCALE_CACHE_COUNT 128
|
||||||
|
|
||||||
|
/** Max length (excluding null terminator) of a cacheable message ID. */
|
||||||
|
#define ASSET_LOCALE_CACHE_KEY_MAX 64
|
||||||
|
|
||||||
|
/** Max length (excluding null terminator) of a cacheable resolved string. */
|
||||||
|
#define ASSET_LOCALE_CACHE_VALUE_MAX 256
|
||||||
|
|
||||||
|
/** One (messageId, pluralCount) -> resolved string cache slot. */
|
||||||
|
typedef struct {
|
||||||
|
char_t messageId[ASSET_LOCALE_CACHE_KEY_MAX];
|
||||||
|
int32_t pluralCount;
|
||||||
|
char_t value[ASSET_LOCALE_CACHE_VALUE_MAX];
|
||||||
|
} assetlocalecacheentry_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fixed-size move-to-front LRU cache of recently resolved locale strings.
|
||||||
|
* assetLocaleGetString() re-scans and re-decompresses the whole PO file on
|
||||||
|
* every miss, which is expensive to repeat for strings a screen fetches
|
||||||
|
* every time it opens (menu labels, etc) - this cache lets identical
|
||||||
|
* (messageId, pluralCount) lookups skip that entirely.
|
||||||
|
*
|
||||||
|
* Lazily allocated on the first cache insert (see assetlocalefile_t.cache)
|
||||||
|
* so locale entries that are never queried, or a file that's disposed
|
||||||
|
* before anything is cached, never pay for it.
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
/**
|
||||||
|
* Entries ordered most-recently-used first. An entry with
|
||||||
|
* messageId[0] == '\0' (and every entry after it) is unused.
|
||||||
|
*/
|
||||||
|
assetlocalecacheentry_t entries[ASSET_LOCALE_CACHE_COUNT];
|
||||||
|
} assetlocalecache_t;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Runtime state for an open locale file.
|
* Runtime state for an open locale file.
|
||||||
*
|
*
|
||||||
@@ -98,6 +133,16 @@ typedef struct {
|
|||||||
|
|
||||||
/** Form index used when no conditional clause matches. */
|
/** Form index used when no conditional clause matches. */
|
||||||
uint8_t pluralDefaultIndex;
|
uint8_t pluralDefaultIndex;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recently resolved string cache, or NULL if nothing has been cached yet.
|
||||||
|
* Heap-allocated rather than embedded because assetlocalefile_t lives
|
||||||
|
* inside the shared assetloaderoutput_t union alongside every other
|
||||||
|
* asset type - embedding a 128-entry cache there would size that union
|
||||||
|
* (and therefore every one of the ASSET_ENTRY_COUNT_MAX asset slots,
|
||||||
|
* regardless of what type of asset occupies it) up by the same amount.
|
||||||
|
*/
|
||||||
|
assetlocalecache_t *cache;
|
||||||
} assetlocalefile_t;
|
} assetlocalefile_t;
|
||||||
|
|
||||||
/** Convenience alias - the loaded output type of a locale asset entry. */
|
/** Convenience alias - the loaded output type of a locale asset entry. */
|
||||||
@@ -204,14 +249,92 @@ errorret_t assetLocaleLineUnbuffer(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Looks up a translated string by message ID from the open locale file.
|
* Searches a locale file's cache for a previously resolved
|
||||||
|
* (messageId, pluralCount) pair.
|
||||||
*
|
*
|
||||||
* Rewinds the file and scans from the beginning on every call. For plural
|
* On a hit, copies the cached value into `stringBuffer` (erroring if it
|
||||||
* entries (`msgid_plural`) the `pluralCount` is evaluated against the loaded
|
* doesn't fit, same contract as @ref assetLocaleGetString) and moves the
|
||||||
* plural rules to select the correct `msgstr[N]` form.
|
* entry to the front of the cache's move-to-front LRU order. On a miss,
|
||||||
|
* `stringBuffer` is left untouched.
|
||||||
|
*
|
||||||
|
* @param file Locale file whose cache to search. Its cache may be NULL
|
||||||
|
* (nothing cached yet), which is treated as a miss.
|
||||||
|
* @param messageId Message ID to look up.
|
||||||
|
* @param pluralCount Plural count the original lookup used.
|
||||||
|
* @param stringBuffer Destination buffer, filled only on a hit.
|
||||||
|
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
|
||||||
|
* @param outHit Set to true on a cache hit, false on a miss.
|
||||||
|
* @return OK on success (hit or miss), error if a hit's cached value does
|
||||||
|
* not fit `stringBuffer`.
|
||||||
|
*/
|
||||||
|
errorret_t assetLocaleCacheFind(
|
||||||
|
assetlocalefile_t *file,
|
||||||
|
const char_t *messageId,
|
||||||
|
const int32_t pluralCount,
|
||||||
|
char_t *stringBuffer,
|
||||||
|
const size_t stringBufferSize,
|
||||||
|
bool_t *outHit
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records a resolved (messageId, pluralCount) -> value string at the front
|
||||||
|
* of the cache's move-to-front LRU order, evicting the least-recently-used
|
||||||
|
* entry if the cache is already full. Lazily allocates the cache (see
|
||||||
|
* assetlocalefile_t.cache) on the first call.
|
||||||
|
*
|
||||||
|
* Caching is a pure optimization: if `messageId` or `value` is too long to
|
||||||
|
* fit the cache's fixed-size slots, this silently does nothing rather than
|
||||||
|
* erroring or growing the cache.
|
||||||
|
*
|
||||||
|
* @param file Locale file whose cache to insert into.
|
||||||
|
* @param messageId Message ID that was looked up.
|
||||||
|
* @param pluralCount Plural count the lookup was made with.
|
||||||
|
* @param value Resolved string to cache.
|
||||||
|
*/
|
||||||
|
void assetLocaleCacheInsert(
|
||||||
|
assetlocalefile_t *file,
|
||||||
|
const char_t *messageId,
|
||||||
|
const int32_t pluralCount,
|
||||||
|
const char_t *value
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared lookup core behind assetLocaleGetString and assetLocaleGetHeader:
|
||||||
|
* checks the file's cache first (see @ref assetLocaleCacheFind; skipped
|
||||||
|
* entirely for an empty messageId, since the cache rejects one), on a
|
||||||
|
* miss rewinds the file and scans from the beginning, then caches the
|
||||||
|
* result (see @ref assetLocaleCacheInsert, same empty-messageId skip)
|
||||||
|
* before returning. For plural entries (`msgid_plural`) the
|
||||||
|
* `pluralCount` is evaluated against the loaded plural rules to select
|
||||||
|
* the correct `msgstr[N]` form.
|
||||||
|
*
|
||||||
|
* Unlike assetLocaleGetString, messageId may be `""` here (see
|
||||||
|
* assetLocaleGetHeader) - this is the shared implementation both of
|
||||||
|
* them delegate to, not a public entry point of its own in practice.
|
||||||
*
|
*
|
||||||
* @param file Locale file to search. Must be open.
|
* @param file Locale file to search. Must be open.
|
||||||
* @param messageId PO message ID to find (`""` retrieves the header entry).
|
* @param messageId PO message ID to find, or `""` for the header entry.
|
||||||
|
* @param pluralCount Count used to select the plural form (ignored for
|
||||||
|
* singular entries).
|
||||||
|
* @param stringBuffer Buffer to receive the translated string.
|
||||||
|
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
|
||||||
|
* @return OK on success, error if the message ID is not found or I/O fails.
|
||||||
|
*/
|
||||||
|
errorret_t assetLocaleGetStringLookup(
|
||||||
|
assetlocalefile_t *file,
|
||||||
|
const char_t *messageId,
|
||||||
|
const int32_t pluralCount,
|
||||||
|
char_t *stringBuffer,
|
||||||
|
const size_t stringBufferSize
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Looks up a translated string by message ID from the open locale file.
|
||||||
|
* See @ref assetLocaleGetStringLookup for the lookup/caching mechanics.
|
||||||
|
*
|
||||||
|
* @param file Locale file to search. Must be open.
|
||||||
|
* @param messageId PO message ID to find. Must be non-empty - use
|
||||||
|
* @ref assetLocaleGetHeader to read the header entry.
|
||||||
* @param pluralCount Count used to select the plural form (ignored for
|
* @param pluralCount Count used to select the plural form (ignored for
|
||||||
* singular entries).
|
* singular entries).
|
||||||
* @param stringBuffer Buffer to receive the translated string.
|
* @param stringBuffer Buffer to receive the translated string.
|
||||||
@@ -226,6 +349,27 @@ errorret_t assetLocaleGetString(
|
|||||||
const size_t stringBufferSize
|
const size_t stringBufferSize
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads the PO file's header entry (the `msgid ""` block every PO file
|
||||||
|
* starts with, holding metadata like the plural-forms rule) - see @ref
|
||||||
|
* assetLocaleParseHeader, its caller. A dedicated function rather than
|
||||||
|
* calling assetLocaleGetString(file, "", ...) since messageId "" is a
|
||||||
|
* PO-format-internal sentinel, not a real (untrusted) caller-supplied
|
||||||
|
* message ID, so it doesn't go through assetLocaleGetString's normal
|
||||||
|
* non-empty validation.
|
||||||
|
*
|
||||||
|
* @param file Locale file to search. Must be open.
|
||||||
|
* @param stringBuffer Buffer to receive the raw header block.
|
||||||
|
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
|
||||||
|
* @return OK on success, error if the header entry is missing or I/O
|
||||||
|
* fails.
|
||||||
|
*/
|
||||||
|
errorret_t assetLocaleGetHeader(
|
||||||
|
assetlocalefile_t *file,
|
||||||
|
char_t *stringBuffer,
|
||||||
|
const size_t stringBufferSize
|
||||||
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Looks up a translated string and formats it with a `printf`-style variadic
|
* Looks up a translated string and formats it with a `printf`-style variadic
|
||||||
* argument list.
|
* argument list.
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# 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
|
||||||
|
assetmp3loader.c
|
||||||
|
)
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "assetmp3loader.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include "util/math.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include "asset/loader/assetloading.h"
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
|
||||||
|
// How far into the file (after any ID3v2 tag) assetMp3ParseHeader() will
|
||||||
|
// search for the first valid MPEG frame sync. Real encoders write it
|
||||||
|
// within the first handful of bytes; this is a generous sane upper bound
|
||||||
|
// (matching assetwavloader.c's own approach to bounding a stack buffer)
|
||||||
|
// rather than a real expectation of needing that much.
|
||||||
|
#define ASSET_MP3_HEADER_SEARCH_MAX 8192
|
||||||
|
|
||||||
|
// MPEG-1 Layer III bitrates (kbps), indexed by the header's 4-bit bitrate
|
||||||
|
// index. Index 0 ("free format") and 15 (reserved) aren't supported.
|
||||||
|
static const uint16_t ASSET_MP3_BITRATE_MPEG1_L3[16] = {
|
||||||
|
0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0
|
||||||
|
};
|
||||||
|
|
||||||
|
// MPEG-2/2.5 Layer III bitrates (kbps) - a different table from MPEG-1's.
|
||||||
|
static const uint16_t ASSET_MP3_BITRATE_MPEG2_L3[16] = {
|
||||||
|
0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0
|
||||||
|
};
|
||||||
|
|
||||||
|
static const uint32_t ASSET_MP3_SAMPLE_RATE_MPEG1[4] = {
|
||||||
|
44100, 48000, 32000, 0
|
||||||
|
};
|
||||||
|
static const uint32_t ASSET_MP3_SAMPLE_RATE_MPEG2[4] = {
|
||||||
|
22050, 24000, 16000, 0
|
||||||
|
};
|
||||||
|
static const uint32_t ASSET_MP3_SAMPLE_RATE_MPEG25[4] = {
|
||||||
|
11025, 12000, 8000, 0
|
||||||
|
};
|
||||||
|
|
||||||
|
errorret_t assetMp3LoaderAsync(assetloading_t *loading) {
|
||||||
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertNotMainThread("Async loader should not be on main thread.");
|
||||||
|
|
||||||
|
if(loading->loading.mp3.state != ASSET_MP3_LOADER_STATE_READ_HEADER) {
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
assetmp3file_t *mp3File = &loading->entry->data.mp3;
|
||||||
|
memoryZero(mp3File, sizeof(assetmp3file_t));
|
||||||
|
|
||||||
|
assetfile_t file;
|
||||||
|
assetLoaderErrorChain(loading, assetFileInit(
|
||||||
|
&file, loading->entry->name, NULL, NULL
|
||||||
|
));
|
||||||
|
assetLoaderErrorChain(loading, assetFileOpen(&file));
|
||||||
|
assetLoaderErrorChain(loading, assetMp3ParseHeader(&file, mp3File));
|
||||||
|
assetLoaderErrorChain(loading, assetFileClose(&file));
|
||||||
|
assetLoaderErrorChain(loading, assetFileDispose(&file));
|
||||||
|
|
||||||
|
loading->loading.mp3.state = ASSET_MP3_LOADER_STATE_DONE;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetMp3LoaderSync(assetloading_t *loading) {
|
||||||
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertTrue(loading->type == ASSET_LOADER_TYPE_MP3, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
switch(loading->loading.mp3.state) {
|
||||||
|
case ASSET_MP3_LOADER_STATE_INITIAL:
|
||||||
|
loading->loading.mp3.state = ASSET_MP3_LOADER_STATE_READ_HEADER;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||||
|
errorOk();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ASSET_MP3_LOADER_STATE_DONE:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetMp3Dispose(assetentry_t *entry) {
|
||||||
|
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||||
|
assertTrue(entry->type == ASSET_LOADER_TYPE_MP3, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetMp3ParseHeader(assetfile_t *file, assetmp3file_t *mp3File) {
|
||||||
|
assertNotNull(file, "Asset file cannot be NULL.");
|
||||||
|
assertNotNull(mp3File, "Mp3 file cannot be NULL.");
|
||||||
|
|
||||||
|
memoryZero(mp3File, sizeof(assetmp3file_t));
|
||||||
|
|
||||||
|
// Skip a leading ID3v2 tag if present: "ID3" + version(2) + flags(1) + a
|
||||||
|
// 4-byte syncsafe (7 usable bits/byte) size covering everything after
|
||||||
|
// this 10-byte header.
|
||||||
|
uint8_t id3Header[10];
|
||||||
|
errorChain(assetFileRead(file, id3Header, sizeof(id3Header)));
|
||||||
|
|
||||||
|
size_t searchBase;
|
||||||
|
if(memoryCompare(id3Header, "ID3", 3) == 0) {
|
||||||
|
const uint32_t tagSize = (
|
||||||
|
((uint32_t) (id3Header[6] & 0x7F) << 21) |
|
||||||
|
((uint32_t) (id3Header[7] & 0x7F) << 14) |
|
||||||
|
((uint32_t) (id3Header[8] & 0x7F) << 7) |
|
||||||
|
((uint32_t) (id3Header[9] & 0x7F))
|
||||||
|
);
|
||||||
|
errorChain(assetFileRead(file, NULL, tagSize));
|
||||||
|
searchBase = sizeof(id3Header) + tagSize;
|
||||||
|
} else {
|
||||||
|
// No ID3v2 tag - rewind the probe bytes just consumed so the frame
|
||||||
|
// sync search below starts from the true beginning of the file.
|
||||||
|
errorChain(assetFileRewind(file));
|
||||||
|
searchBase = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const size_t searchWindowSize = mathMin(
|
||||||
|
(size_t) ASSET_MP3_HEADER_SEARCH_MAX,
|
||||||
|
(size_t) file->size > searchBase ? (size_t) file->size - searchBase : 0
|
||||||
|
);
|
||||||
|
if(searchWindowSize < 4) {
|
||||||
|
errorThrow(
|
||||||
|
"MP3 file is too short to contain a frame header: %s", file->filename
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t *window = (uint8_t *) memoryAllocate(searchWindowSize);
|
||||||
|
errorret_t readRet = assetFileRead(file, window, searchWindowSize);
|
||||||
|
if(errorIsNotOk(readRet)) {
|
||||||
|
memoryFree(window);
|
||||||
|
errorChain(readRet);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool_t found = false;
|
||||||
|
size_t frameIndex = 0;
|
||||||
|
|
||||||
|
for(size_t i = 0; i + 4 <= searchWindowSize; i++) {
|
||||||
|
if(window[i] != 0xFF || (window[i + 1] & 0xE0) != 0xE0) continue;
|
||||||
|
|
||||||
|
const uint8_t versionBits = (window[i + 1] >> 3) & 0x3;
|
||||||
|
const uint8_t layerBits = (window[i + 1] >> 1) & 0x3;
|
||||||
|
// reserved version, or not Layer III
|
||||||
|
if(versionBits == 1 || layerBits != 1) continue;
|
||||||
|
|
||||||
|
const uint8_t bitrateIndex = (window[i + 2] >> 4) & 0xF;
|
||||||
|
const uint8_t sampleRateIndex = (window[i + 2] >> 2) & 0x3;
|
||||||
|
if(
|
||||||
|
bitrateIndex == 0 || bitrateIndex == 15 || sampleRateIndex == 3
|
||||||
|
) continue;
|
||||||
|
|
||||||
|
const uint8_t channelMode = (window[i + 3] >> 6) & 0x3;
|
||||||
|
const bool_t isMpeg1 = versionBits == 3;
|
||||||
|
|
||||||
|
mp3File->bitrateKbps = isMpeg1
|
||||||
|
? ASSET_MP3_BITRATE_MPEG1_L3[bitrateIndex]
|
||||||
|
: ASSET_MP3_BITRATE_MPEG2_L3[bitrateIndex];
|
||||||
|
mp3File->sampleRate = isMpeg1
|
||||||
|
? ASSET_MP3_SAMPLE_RATE_MPEG1[sampleRateIndex]
|
||||||
|
: (versionBits == 2
|
||||||
|
? ASSET_MP3_SAMPLE_RATE_MPEG2[sampleRateIndex]
|
||||||
|
: ASSET_MP3_SAMPLE_RATE_MPEG25[sampleRateIndex]);
|
||||||
|
mp3File->samplesPerFrame = isMpeg1 ? 1152 : 576;
|
||||||
|
mp3File->channels = channelMode == 3 ? 1 : 2;
|
||||||
|
|
||||||
|
// A Xing/Info header, if present, sits right after the side info -
|
||||||
|
// whose size depends on MPEG version and channel mode - immediately
|
||||||
|
// following the 4-byte header (plus a 2-byte CRC, if the protection
|
||||||
|
// bit says one follows).
|
||||||
|
const bool_t hasCrc = (window[i + 1] & 0x1) == 0;
|
||||||
|
const size_t sideInfoSize = isMpeg1
|
||||||
|
? (mp3File->channels == 1 ? 17 : 32)
|
||||||
|
: (mp3File->channels == 1 ? 9 : 17);
|
||||||
|
const size_t xingOffset = i + 4 + (hasCrc ? 2 : 0) + sideInfoSize;
|
||||||
|
|
||||||
|
if(
|
||||||
|
xingOffset + 8 <= searchWindowSize &&
|
||||||
|
(
|
||||||
|
memoryCompare(window + xingOffset, "Xing", 4) == 0 ||
|
||||||
|
memoryCompare(window + xingOffset, "Info", 4) == 0
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
const uint8_t *flagsBytes = window + xingOffset + 4;
|
||||||
|
const uint32_t flags = (
|
||||||
|
((uint32_t) flagsBytes[0] << 24) | ((uint32_t) flagsBytes[1] << 16) |
|
||||||
|
((uint32_t) flagsBytes[2] << 8) | (uint32_t) flagsBytes[3]
|
||||||
|
);
|
||||||
|
if((flags & 0x1) != 0 && xingOffset + 12 <= searchWindowSize) {
|
||||||
|
const uint8_t *framesBytes = window + xingOffset + 8;
|
||||||
|
const uint32_t xingFrameCount = (
|
||||||
|
((uint32_t) framesBytes[0] << 24) |
|
||||||
|
((uint32_t) framesBytes[1] << 16) |
|
||||||
|
((uint32_t) framesBytes[2] << 8) |
|
||||||
|
(uint32_t) framesBytes[3]
|
||||||
|
);
|
||||||
|
// The Xing/Info header's frame count includes the header's own
|
||||||
|
// frame (this one, at `i`) - which libmad (and sceMp3) will
|
||||||
|
// attempt to decode like any other, but which doesn't contribute a
|
||||||
|
// real decodable frame of audio the way every other one does.
|
||||||
|
// Confirmed against a real LAME-encoded file: its Xing header
|
||||||
|
// declared 40 frames, but decoding actually produced exactly 39
|
||||||
|
// frames' worth of real PCM - without this -1, playback would
|
||||||
|
// permanently stall one frame short of the declared total (audible
|
||||||
|
// as "never loops"), since real decode output can never catch up
|
||||||
|
// to an overstated total.
|
||||||
|
if(xingFrameCount > 0) {
|
||||||
|
mp3File->totalFrames =
|
||||||
|
(size_t) (xingFrameCount - 1) * mp3File->samplesPerFrame;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
frameIndex = i;
|
||||||
|
found = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
memoryFree(window);
|
||||||
|
|
||||||
|
if(!found) {
|
||||||
|
errorThrow(
|
||||||
|
"MP3 file has no valid MPEG-1/2/2.5 Layer III frame within the first "
|
||||||
|
"%u bytes: %s",
|
||||||
|
(uint32_t) searchWindowSize, file->filename
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
mp3File->dataOffset = searchBase + frameIndex;
|
||||||
|
mp3File->dataSize = (size_t) file->size - mp3File->dataOffset;
|
||||||
|
|
||||||
|
// No Xing/Info header found - estimate assuming constant bitrate (the
|
||||||
|
// common case when one's genuinely absent; a real VBR file without one
|
||||||
|
// is rare and will just get an approximate duration/loop point instead
|
||||||
|
// of an exact one).
|
||||||
|
if(mp3File->totalFrames == 0) {
|
||||||
|
const float_t durationSeconds = (
|
||||||
|
((float_t) mp3File->dataSize * 8.0f) /
|
||||||
|
((float_t) mp3File->bitrateKbps * 1000.0f)
|
||||||
|
);
|
||||||
|
mp3File->totalFrames =
|
||||||
|
(size_t) (durationSeconds * (float_t) mp3File->sampleRate);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "error/error.h"
|
||||||
|
#include "asset/assetfile.h"
|
||||||
|
|
||||||
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
typedef struct { void *nothing; } assetmp3loaderinput_t;
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_MP3_LOADER_STATE_INITIAL,
|
||||||
|
ASSET_MP3_LOADER_STATE_READ_HEADER,
|
||||||
|
ASSET_MP3_LOADER_STATE_DONE
|
||||||
|
} assetmp3loaderstate_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
assetmp3loaderstate_t state;
|
||||||
|
} assetmp3loaderloading_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parsed metadata for an MP3 asset - deliberately just enough to configure
|
||||||
|
* a decoder and know the clip's total length, not anything about its
|
||||||
|
* actual compressed content (which is read/decoded on demand at playback
|
||||||
|
* time - see audiostreammp3.c). Only MPEG-1/2/2.5 Layer III ("MP3" in the
|
||||||
|
* everyday sense) is supported; Layers I/II are rejected.
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint32_t sampleRate;
|
||||||
|
uint8_t channels;
|
||||||
|
|
||||||
|
// 1152 for MPEG-1, 576 for MPEG-2/2.5 - how many PCM samples (per
|
||||||
|
// channel) one compressed MPEG frame decodes to.
|
||||||
|
uint16_t samplesPerFrame;
|
||||||
|
|
||||||
|
// The first frame's bitrate, in kbps. Used only as a fallback duration
|
||||||
|
// estimate (assuming CBR) when no Xing/Info header is found - see
|
||||||
|
// assetMp3ParseHeader()'s own comment.
|
||||||
|
uint32_t bitrateKbps;
|
||||||
|
|
||||||
|
// Byte offset (from the start of the file) of the first real MPEG
|
||||||
|
// frame, i.e. right after any leading ID3v2 tag.
|
||||||
|
size_t dataOffset;
|
||||||
|
|
||||||
|
// Bytes of compressed MPEG data, from dataOffset to the end of the file.
|
||||||
|
size_t dataSize;
|
||||||
|
|
||||||
|
// Decoded PCM frame count for the whole clip - exact if a Xing/Info
|
||||||
|
// header was found (the common case for anything encoded with a modern
|
||||||
|
// tool), otherwise estimated from bitrateKbps/dataSize assuming CBR (see
|
||||||
|
// assetMp3ParseHeader()'s own comment) - unlike assetwavfile_t.dataSize,
|
||||||
|
// MP3 has no header field that gives this directly.
|
||||||
|
size_t totalFrames;
|
||||||
|
} assetmp3file_t;
|
||||||
|
|
||||||
|
typedef assetmp3file_t assetmp3output_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Async (background-thread) half of the MP3 loader - opens the asset file,
|
||||||
|
* parses its header (see assetMp3ParseHeader()), and closes it again. Never
|
||||||
|
* buffers the compressed MPEG data itself; that's read on demand at
|
||||||
|
* playback time by audiostreammp3.c via its own independent file handle.
|
||||||
|
*
|
||||||
|
* @param loading The asset loading slot.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t assetMp3LoaderAsync(assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sync (main-thread) half of the MP3 loader - a simple state machine that
|
||||||
|
* schedules the async header parse and marks the entry loaded once it's
|
||||||
|
* done, mirroring assetWavLoaderSync()'s shape exactly.
|
||||||
|
*
|
||||||
|
* @param loading The asset loading slot.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t assetMp3LoaderSync(assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposes an MP3 asset entry. A no-op - an assetmp3file_t owns no heap
|
||||||
|
* allocations, and playback streams open their own independent file
|
||||||
|
* handles (see audiostreammp3.c).
|
||||||
|
*
|
||||||
|
* @param entry The asset entry to dispose.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t assetMp3Dispose(assetentry_t *entry);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses an MP3 file's metadata from an already-opened asset file
|
||||||
|
* positioned at its very start: skips a leading ID3v2 tag if present,
|
||||||
|
* scans forward for the first valid MPEG-1/2/2.5 Layer III frame header
|
||||||
|
* (rejecting anything else - other layers, or no valid frame found within
|
||||||
|
* a sane search window), and checks that frame for a Xing/Info header
|
||||||
|
* (found in the vast majority of real-world MP3s, VBR or CBR) to get an
|
||||||
|
* exact total-frame count; falls back to a CBR estimate from the first
|
||||||
|
* frame's bitrate and the file's remaining size if absent.
|
||||||
|
*
|
||||||
|
* Never reads more than a bounded lookahead window into memory - the bulk
|
||||||
|
* of the file (the actual compressed audio, following the parsed frame's
|
||||||
|
* position) is left untouched, exactly like assetWavParseHeader().
|
||||||
|
*
|
||||||
|
* @param file Asset file to parse, positioned at offset 0.
|
||||||
|
* @param mp3File Filled with the parsed metadata on success.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t assetMp3ParseHeader(assetfile_t *file, assetmp3file_t *mp3File);
|
||||||
@@ -6,6 +6,5 @@
|
|||||||
# Sources
|
# Sources
|
||||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
PUBLIC
|
PUBLIC
|
||||||
savevita.c
|
assetwavloader.c
|
||||||
savestreamvita.c
|
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "assetwavloader.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include "util/endian.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include "asset/loader/assetloading.h"
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
|
||||||
|
// "RIFF" + chunkSize + "WAVE", before any sub-chunks begin.
|
||||||
|
#define ASSET_WAV_RIFF_HEADER_SIZE 12
|
||||||
|
|
||||||
|
// A sub-chunk header is a 4-byte id followed by a 4-byte little-endian size.
|
||||||
|
#define ASSET_WAV_CHUNK_HEADER_SIZE 8
|
||||||
|
|
||||||
|
#define ASSET_WAV_FMT_CHUNK_SIZE_MIN 16
|
||||||
|
// Sane upper bound for a stack buffer - real fmt chunks (PCM or otherwise)
|
||||||
|
// never come close to this; anything bigger is treated as malformed.
|
||||||
|
#define ASSET_WAV_FMT_CHUNK_SIZE_MAX 64
|
||||||
|
|
||||||
|
errorret_t assetWavLoaderAsync(assetloading_t *loading) {
|
||||||
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertNotMainThread("Async loader should not be on main thread.");
|
||||||
|
|
||||||
|
if(loading->loading.wav.state != ASSET_WAV_LOADER_STATE_READ_HEADER) {
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
assetwavfile_t *wavFile = &loading->entry->data.wav;
|
||||||
|
memoryZero(wavFile, sizeof(assetwavfile_t));
|
||||||
|
|
||||||
|
assetfile_t file;
|
||||||
|
assetLoaderErrorChain(loading, assetFileInit(
|
||||||
|
&file, loading->entry->name, NULL, NULL
|
||||||
|
));
|
||||||
|
assetLoaderErrorChain(loading, assetFileOpen(&file));
|
||||||
|
assetLoaderErrorChain(loading, assetWavParseHeader(&file, wavFile));
|
||||||
|
assetLoaderErrorChain(loading, assetFileClose(&file));
|
||||||
|
assetLoaderErrorChain(loading, assetFileDispose(&file));
|
||||||
|
|
||||||
|
loading->loading.wav.state = ASSET_WAV_LOADER_STATE_DONE;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetWavLoaderSync(assetloading_t *loading) {
|
||||||
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertTrue(loading->type == ASSET_LOADER_TYPE_WAV, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
switch(loading->loading.wav.state) {
|
||||||
|
case ASSET_WAV_LOADER_STATE_INITIAL:
|
||||||
|
loading->loading.wav.state = ASSET_WAV_LOADER_STATE_READ_HEADER;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||||
|
errorOk();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ASSET_WAV_LOADER_STATE_DONE:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetWavDispose(assetentry_t *entry) {
|
||||||
|
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||||
|
assertTrue(entry->type == ASSET_LOADER_TYPE_WAV, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetWavParseHeader(
|
||||||
|
assetfile_t *file,
|
||||||
|
assetwavfile_t *wavFile
|
||||||
|
) {
|
||||||
|
assertNotNull(file, "Asset file cannot be NULL.");
|
||||||
|
assertNotNull(wavFile, "Wav file cannot be NULL.");
|
||||||
|
|
||||||
|
uint8_t riffHeader[ASSET_WAV_RIFF_HEADER_SIZE];
|
||||||
|
errorChain(assetFileRead(file, riffHeader, sizeof(riffHeader)));
|
||||||
|
|
||||||
|
if(memoryCompare(riffHeader, "RIFF", 4) != 0) {
|
||||||
|
errorThrow("WAV file has an invalid RIFF header: %s", file->filename);
|
||||||
|
}
|
||||||
|
if(memoryCompare(riffHeader + 8, "WAVE", 4) != 0) {
|
||||||
|
errorThrow("WAV file has an invalid WAVE header: %s", file->filename);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool_t foundFormat = false;
|
||||||
|
bool_t foundData = false;
|
||||||
|
uint16_t audioFormat = 0;
|
||||||
|
|
||||||
|
// Walk the chunk list, reading only chunk headers (and the small "fmt "
|
||||||
|
// body) - every other chunk, "data"'s sample bytes included, is skipped
|
||||||
|
// via a NULL-buffer read rather than buffered into memory. Stops as soon
|
||||||
|
// as "data" is found; nothing after it matters here.
|
||||||
|
while(!foundData && (size_t) file->position < (size_t) file->size) {
|
||||||
|
uint8_t chunkHeader[ASSET_WAV_CHUNK_HEADER_SIZE];
|
||||||
|
errorChain(assetFileRead(file, chunkHeader, sizeof(chunkHeader)));
|
||||||
|
|
||||||
|
uint32_t chunkSizeLE;
|
||||||
|
memoryCopy(&chunkSizeLE, chunkHeader + 4, sizeof(chunkSizeLE));
|
||||||
|
const uint32_t chunkSize = endianLittleToHost32(chunkSizeLE);
|
||||||
|
|
||||||
|
// Chunks are padded to an even total size - the pad byte (if any)
|
||||||
|
// isn't included in chunkSize but still needs to be skipped over.
|
||||||
|
const uint32_t chunkSizePadded = chunkSize + (chunkSize % 2);
|
||||||
|
|
||||||
|
if(memoryCompare(chunkHeader, "fmt ", 4) == 0) {
|
||||||
|
if(
|
||||||
|
chunkSize < ASSET_WAV_FMT_CHUNK_SIZE_MIN ||
|
||||||
|
chunkSize > ASSET_WAV_FMT_CHUNK_SIZE_MAX
|
||||||
|
) {
|
||||||
|
errorThrow("WAV 'fmt ' chunk has an unsupported size: %u", chunkSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t fmtBuffer[ASSET_WAV_FMT_CHUNK_SIZE_MAX];
|
||||||
|
errorChain(assetFileRead(file, fmtBuffer, chunkSize));
|
||||||
|
if(chunkSize % 2 != 0) {
|
||||||
|
errorChain(assetFileRead(file, NULL, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t u16;
|
||||||
|
uint32_t u32;
|
||||||
|
|
||||||
|
memoryCopy(&u16, fmtBuffer + 0, sizeof(u16));
|
||||||
|
audioFormat = endianLittleToHost16(u16);
|
||||||
|
|
||||||
|
memoryCopy(&u16, fmtBuffer + 2, sizeof(u16));
|
||||||
|
wavFile->channels = (uint8_t) endianLittleToHost16(u16);
|
||||||
|
|
||||||
|
memoryCopy(&u32, fmtBuffer + 4, sizeof(u32));
|
||||||
|
wavFile->sampleRate = endianLittleToHost32(u32);
|
||||||
|
|
||||||
|
memoryCopy(&u16, fmtBuffer + 14, sizeof(u16));
|
||||||
|
wavFile->bitsPerSample = (uint8_t) endianLittleToHost16(u16);
|
||||||
|
|
||||||
|
foundFormat = true;
|
||||||
|
} else if(memoryCompare(chunkHeader, "data", 4) == 0) {
|
||||||
|
wavFile->dataOffset = (size_t) file->position;
|
||||||
|
wavFile->dataSize = chunkSize;
|
||||||
|
foundData = true;
|
||||||
|
} else {
|
||||||
|
errorChain(assetFileRead(file, NULL, chunkSizePadded));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(!foundFormat) {
|
||||||
|
errorThrow("WAV file is missing its 'fmt ' chunk: %s", file->filename);
|
||||||
|
}
|
||||||
|
if(!foundData) {
|
||||||
|
errorThrow("WAV file is missing its 'data' chunk: %s", file->filename);
|
||||||
|
}
|
||||||
|
if(audioFormat != 1) {
|
||||||
|
errorThrow(
|
||||||
|
"Unsupported WAV audio format: %u (only PCM is supported): %s",
|
||||||
|
audioFormat, file->filename
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if(wavFile->bitsPerSample != 16 && wavFile->bitsPerSample != 24) {
|
||||||
|
errorThrow(
|
||||||
|
"Unsupported WAV bits per sample: %u (only 16/24-bit is supported): %s",
|
||||||
|
wavFile->bitsPerSample, file->filename
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if(wavFile->channels == 0) {
|
||||||
|
errorThrow("WAV file declares 0 channels: %s", file->filename);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "asset/assetfile.h"
|
||||||
|
|
||||||
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
/** Input passed to the wav loader - currently unused. */
|
||||||
|
typedef struct { void *nothing; } assetwavloaderinput_t;
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_WAV_LOADER_STATE_INITIAL,
|
||||||
|
ASSET_WAV_LOADER_STATE_READ_HEADER,
|
||||||
|
ASSET_WAV_LOADER_STATE_DONE
|
||||||
|
} assetwavloaderstate_t;
|
||||||
|
|
||||||
|
/** Per-slot scratch data used while the wav file is loading. */
|
||||||
|
typedef struct {
|
||||||
|
assetwavloaderstate_t state;
|
||||||
|
} assetwavloaderloading_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parsed metadata for a WAV asset - only the RIFF/WAVE/fmt/data chunk
|
||||||
|
* headers are ever read; the PCM sample data itself is never loaded here
|
||||||
|
* (see @ref assetWavParseHeader). Playback reads sample data directly
|
||||||
|
* from the archive on demand instead - see audiostreampcm.h.
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
/** Sample rate of the PCM data, in Hz. */
|
||||||
|
uint32_t sampleRate;
|
||||||
|
|
||||||
|
/** Number of interleaved channels in the PCM data. */
|
||||||
|
uint8_t channels;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bits per sample of the *source* file data - 16 or 24 (see
|
||||||
|
* assetWavParseHeader). Playback always reads 16-bit samples out via
|
||||||
|
* audioStreamPcmRead() regardless of this - a 24-bit source is
|
||||||
|
* truncated to 16-bit there, since none of this project's audio
|
||||||
|
* backends (PSP/Dolphin hardware, SDL2 on Linux) accept anything wider.
|
||||||
|
*/
|
||||||
|
uint8_t bitsPerSample;
|
||||||
|
|
||||||
|
/** Byte offset from the start of the file to the first PCM sample. */
|
||||||
|
size_t dataOffset;
|
||||||
|
|
||||||
|
/** Size of the PCM data, in bytes. */
|
||||||
|
size_t dataSize;
|
||||||
|
} assetwavfile_t;
|
||||||
|
|
||||||
|
/** Convenience alias - the loaded output type of a wav asset entry. */
|
||||||
|
typedef assetwavfile_t assetwavoutput_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asynchronous loader callback. Opens the WAV file and reads just enough of
|
||||||
|
* it to locate and parse the `fmt ` chunk and locate (not read) the `data`
|
||||||
|
* chunk - see @ref assetWavParseHeader. All I/O happens here so the main
|
||||||
|
* thread is not blocked. Sets entry state to `ASSET_ENTRY_STATE_PENDING_SYNC`
|
||||||
|
* on success or `ASSET_ENTRY_STATE_ERROR` on failure.
|
||||||
|
*
|
||||||
|
* @param loading The loading slot for this asset entry.
|
||||||
|
* @return OK on success, error otherwise.
|
||||||
|
*/
|
||||||
|
errorret_t assetWavLoaderAsync(assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Synchronous loader callback. Confirms the async phase completed and marks
|
||||||
|
* the entry as `ASSET_ENTRY_STATE_LOADED`.
|
||||||
|
*
|
||||||
|
* @param loading The loading slot for this asset entry.
|
||||||
|
* @return OK on success, error otherwise.
|
||||||
|
*/
|
||||||
|
errorret_t assetWavLoaderSync(assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dispose callback. The wav asset owns no allocations of its own (its data
|
||||||
|
* chunk is read directly from the archive by whichever streams are playing
|
||||||
|
* it, each through their own handle - see audiostreampcm.h), so this is
|
||||||
|
* currently a no-op beyond the standard asserts.
|
||||||
|
*
|
||||||
|
* @param entry The asset entry to dispose.
|
||||||
|
* @return OK on success, error otherwise.
|
||||||
|
*/
|
||||||
|
errorret_t assetWavDispose(assetentry_t *entry);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a RIFF/WAVE file's chunk structure from an already-open asset
|
||||||
|
* file, reading only chunk headers (and the small `fmt ` chunk body) -
|
||||||
|
* every other chunk, including `data`'s actual sample bytes, is skipped
|
||||||
|
* over via `assetFileRead(file, NULL, size)` rather than read into memory,
|
||||||
|
* so this never buffers the (potentially large) PCM payload.
|
||||||
|
*
|
||||||
|
* Stops as soon as the `data` chunk header is found, recording its file
|
||||||
|
* offset and declared size in `wavFile` without reading any of its bytes -
|
||||||
|
* the file is left positioned at the start of the PCM data.
|
||||||
|
*
|
||||||
|
* Only PCM (audio format 1), 16- or 24-bit-per-sample WAV data is
|
||||||
|
* supported - see audiostreampcm.h's audioStreamPcmRead() for how a
|
||||||
|
* 24-bit source gets truncated to the 16-bit output every platform
|
||||||
|
* backend expects. Requires the `fmt ` chunk to appear before `data`, per
|
||||||
|
* the WAV spec's recommended ordering.
|
||||||
|
*
|
||||||
|
* @param file An open asset file, positioned at the start of the WAV data.
|
||||||
|
* @param wavFile Struct whose fields will be filled in.
|
||||||
|
* @return OK on success, error if the file is malformed or an unsupported
|
||||||
|
* format.
|
||||||
|
*/
|
||||||
|
errorret_t assetWavParseHeader(
|
||||||
|
assetfile_t *file,
|
||||||
|
assetwavfile_t *wavFile
|
||||||
|
);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# Copyright (c) 2026 Dominic Masters
|
||||||
|
#
|
||||||
|
# This software is released under the MIT License.
|
||||||
|
# https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
|
# Sources
|
||||||
|
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
|
PUBLIC
|
||||||
|
audio.c
|
||||||
|
)
|
||||||
|
|
||||||
|
# Subdirs
|
||||||
|
add_subdirectory(mixer)
|
||||||
|
add_subdirectory(stream)
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "audio.h"
|
||||||
|
#include "audio/mixer/audiomixer.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
|
||||||
|
audio_t AUDIO;
|
||||||
|
|
||||||
|
errorret_t audioInit() {
|
||||||
|
memoryZero(&AUDIO, sizeof(audio_t));
|
||||||
|
|
||||||
|
errorChain(audioPlatformInit());
|
||||||
|
errorChain(audioMixerInit());
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
audiostream_t * audioAquireStream(assetentry_t *asset) {
|
||||||
|
assertNotNull(asset, "Asset cannot be NULL.");
|
||||||
|
// Same check audioStreamInit() makes - see its own comment on why this
|
||||||
|
// is an assert (a programmer error, not untrusted data). Checking here
|
||||||
|
// too catches the mistake as early as possible, before any stream slot
|
||||||
|
// is handed out for it.
|
||||||
|
assertTrue(
|
||||||
|
audioStreamTypeForAssetType(asset->type) != AUDIO_STREAM_TYPE_NULL,
|
||||||
|
"Unsupported asset type for an audio stream."
|
||||||
|
);
|
||||||
|
|
||||||
|
for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) {
|
||||||
|
audiostream_t *stream = &AUDIO.streams[i];
|
||||||
|
if(stream->type == AUDIO_STREAM_TYPE_NULL) {
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioUpdateEarly() {
|
||||||
|
errorChain(audioPlatformUpdate());
|
||||||
|
errorChain(audioMixerUpdateEarly());
|
||||||
|
|
||||||
|
for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) {
|
||||||
|
audiostream_t *stream = &AUDIO.streams[i];
|
||||||
|
errorChain(audioStreamUpdate(stream));
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioUpdateLate() {
|
||||||
|
errorChain(audioMixerUpdateLate());
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioDispose() {
|
||||||
|
for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) {
|
||||||
|
audiostream_t *stream = &AUDIO.streams[i];
|
||||||
|
errorChain(audioStreamDispose(stream));
|
||||||
|
}
|
||||||
|
|
||||||
|
errorChain(audioMixerDispose());
|
||||||
|
errorChain(audioPlatformDispose());
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "dusk.h"
|
||||||
|
#include "audio/stream/audiostream.h"
|
||||||
|
#include "audio/audioplatform.h"
|
||||||
|
|
||||||
|
#ifndef audioPlatformInit
|
||||||
|
#error "audioPlatformInit is not defined"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef audioPlatformUpdate
|
||||||
|
#error "audioPlatformUpdate is not defined"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef audioPlatformDispose
|
||||||
|
#error "audioPlatformDispose is not defined"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
audiostream_t streams[AUDIO_STREAMS_MAX];
|
||||||
|
} audio_t;
|
||||||
|
|
||||||
|
extern audio_t AUDIO;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes the audio subsystem.
|
||||||
|
*
|
||||||
|
* @return Error indicating success or failure of the operation.
|
||||||
|
*/
|
||||||
|
errorret_t audioInit();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aquires an available audio stream for playing the given asset. Can return
|
||||||
|
* NULL if there is no available stream slot.
|
||||||
|
*
|
||||||
|
* The returned stream is not yet configured to play `asset` - call
|
||||||
|
* audioStreamInit(stream, asset) next.
|
||||||
|
*
|
||||||
|
* @param asset The asset the caller intends to play - validated eagerly so
|
||||||
|
* an unsupported asset type is caught here rather than only
|
||||||
|
* once audioStreamInit() is called.
|
||||||
|
* @return Pointer to an available audio stream, or NULL if none are free.
|
||||||
|
*/
|
||||||
|
audiostream_t * audioAquireStream(assetentry_t *asset);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the audio subsystem, updating every active stream. Should be
|
||||||
|
* called once per frame, before rendering - keeps stream buffering/decode
|
||||||
|
* work off the render thread's critical path (see duskmad's MP3 decode
|
||||||
|
* ring for why this matters).
|
||||||
|
*
|
||||||
|
* @return Error indicating success or failure of the operation.
|
||||||
|
*/
|
||||||
|
errorret_t audioUpdateEarly();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the audio subsystem's end-of-frame work - currently just starting
|
||||||
|
* whatever the audio mixer queued this frame (see
|
||||||
|
* audioMixerUpdateLate()'s own comment). Should be called once per frame,
|
||||||
|
* after rendering.
|
||||||
|
*
|
||||||
|
* @return Error indicating success or failure of the operation.
|
||||||
|
*/
|
||||||
|
errorret_t audioUpdateLate();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposes the audio subsystem, stopping and disposing every active stream.
|
||||||
|
*
|
||||||
|
* @return Error indicating success or failure of the operation.
|
||||||
|
*/
|
||||||
|
errorret_t audioDispose();
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# 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
|
||||||
|
audiomixer.c
|
||||||
|
audiomixerchannel.c
|
||||||
|
)
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "audiomixer.h"
|
||||||
|
#include "audio/stream/audiostream.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include "util/string.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
|
||||||
|
audiomixer_t AUDIO_MIXER;
|
||||||
|
|
||||||
|
errorret_t audioMixerInit() {
|
||||||
|
memoryZero(&AUDIO_MIXER, sizeof(audiomixer_t));
|
||||||
|
|
||||||
|
audiomixerchannel_t channel = 0;
|
||||||
|
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
|
||||||
|
AUDIO_MIXER.channels[channel].fade = 1.0f;
|
||||||
|
// -1 means "no fade in progress" - see its own comment; zero-init
|
||||||
|
// would otherwise look like an active fade at time 0.
|
||||||
|
AUDIO_MIXER.channels[channel].fadeTime = -1.0f;
|
||||||
|
channel++;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioMixerUpdateEarly() {
|
||||||
|
audiomixerchannel_t channel = 0;
|
||||||
|
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
|
||||||
|
// One channel's error (e.g. a failed asset load) must not stop every
|
||||||
|
// other channel from being updated this frame - caught and logged
|
||||||
|
// rather than propagated, same as audioStream*IsFinished()'s own
|
||||||
|
// per-stream error handling.
|
||||||
|
errorret_t ret = audioMixerChannelUpdateEarly(
|
||||||
|
channel, &AUDIO_MIXER.channels[channel]
|
||||||
|
);
|
||||||
|
if(errorIsNotOk(ret)) errorCatch(errorPrint(ret));
|
||||||
|
channel++;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioMixerUpdateLate() {
|
||||||
|
audiomixerchannel_t channel = 0;
|
||||||
|
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
|
||||||
|
errorret_t ret =
|
||||||
|
audioMixerChannelUpdateLate(&AUDIO_MIXER.channels[channel]);
|
||||||
|
if(errorIsNotOk(ret)) errorCatch(errorPrint(ret));
|
||||||
|
channel++;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerPlay(
|
||||||
|
const char_t *file,
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
const float_t volume,
|
||||||
|
const float_t pan
|
||||||
|
) {
|
||||||
|
audioMixerQueuePlay(file, channel, volume, pan, false, 0, -1.0f, 0.0f);
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerPlayLooped(
|
||||||
|
const char_t *file,
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
const float_t volume,
|
||||||
|
const float_t pan,
|
||||||
|
const uint8_t loopCount,
|
||||||
|
const float_t loopStart,
|
||||||
|
const float_t loopTo
|
||||||
|
) {
|
||||||
|
audioMixerQueuePlay(
|
||||||
|
file, channel, volume, pan, true, loopCount, loopStart, loopTo
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerQueuePlay(
|
||||||
|
const char_t *file,
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
const float_t volume,
|
||||||
|
const float_t pan,
|
||||||
|
const bool_t looping,
|
||||||
|
const uint8_t loopCount,
|
||||||
|
const float_t loopStart,
|
||||||
|
const float_t loopTo
|
||||||
|
) {
|
||||||
|
assertStrLenMin(file, 1, "File is required, to stop use audioMixerStop");
|
||||||
|
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
||||||
|
assertTrue(volume > 0.0f && volume <= 1.0f, "Volume is out of range");
|
||||||
|
assertTrue(
|
||||||
|
pan >= AUDIO_STREAM_LEFT && pan <= AUDIO_STREAM_RIGHT,
|
||||||
|
"Pan is out of range"
|
||||||
|
);
|
||||||
|
assertTrue(
|
||||||
|
!looping || loopStart < 0.0f || loopTo < loopStart,
|
||||||
|
"Loop points incorrect"
|
||||||
|
);
|
||||||
|
|
||||||
|
audiomixercommand_t *command = &AUDIO_MIXER.channels[channel].pending;
|
||||||
|
|
||||||
|
command->command = AUDIO_MIXER_COMMAND_PLAY;
|
||||||
|
stringCopy(command->file, file, AUDIO_PATH_MAX);
|
||||||
|
command->volume = volume;
|
||||||
|
command->pan = pan;
|
||||||
|
command->looping = looping;
|
||||||
|
command->loopCount = loopCount;
|
||||||
|
command->loopStart = loopStart;
|
||||||
|
command->loopTo = loopTo;
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerStop(const audiomixerchannel_t channel) {
|
||||||
|
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
||||||
|
|
||||||
|
AUDIO_MIXER.channels[channel].pending.command = AUDIO_MIXER_COMMAND_STOP;
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerPause(const audiomixerchannel_t channel) {
|
||||||
|
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
||||||
|
|
||||||
|
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
|
||||||
|
if(stream != NULL) audioStreamPause(stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerResume(const audiomixerchannel_t channel) {
|
||||||
|
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
||||||
|
|
||||||
|
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
|
||||||
|
if(stream != NULL) audioStreamPlay(stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerSetPan(const audiomixerchannel_t channel, const float_t pan) {
|
||||||
|
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
||||||
|
assertTrue(
|
||||||
|
pan >= AUDIO_STREAM_LEFT && pan <= AUDIO_STREAM_RIGHT,
|
||||||
|
"Pan is out of range"
|
||||||
|
);
|
||||||
|
|
||||||
|
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
|
||||||
|
if(stream != NULL) audioStreamSetDirectionality(stream, pan);
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerSetLoop(
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
const bool_t looping,
|
||||||
|
const uint8_t loopCount,
|
||||||
|
const float_t loopStart,
|
||||||
|
const float_t loopTo
|
||||||
|
) {
|
||||||
|
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
||||||
|
assertTrue(
|
||||||
|
!looping || loopStart < 0.0f || loopTo < loopStart,
|
||||||
|
"Loop points incorrect"
|
||||||
|
);
|
||||||
|
|
||||||
|
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
|
||||||
|
if(stream == NULL) return;
|
||||||
|
|
||||||
|
audioStreamSetLooping(stream, looping);
|
||||||
|
if(looping) {
|
||||||
|
audioStreamSetLoopPoints(stream, loopStart, loopTo);
|
||||||
|
audioStreamSetLoopLimit(stream, loopCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerFadeTo(
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
const float_t from,
|
||||||
|
const float_t to,
|
||||||
|
const float_t duration,
|
||||||
|
const easingtype_t easing
|
||||||
|
) {
|
||||||
|
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
||||||
|
|
||||||
|
audioMixerChannelFadeTo(
|
||||||
|
&AUDIO_MIXER.channels[channel], from, to, duration, easing
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool_t audioMixerIsFading(const audiomixerchannel_t channel) {
|
||||||
|
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
||||||
|
|
||||||
|
return audioMixerChannelIsFading(&AUDIO_MIXER.channels[channel]);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioMixerDispose() {
|
||||||
|
audiomixerchannel_t channel = 0;
|
||||||
|
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
|
||||||
|
errorChain(audioMixerChannelStopStream(&AUDIO_MIXER.channels[channel]));
|
||||||
|
channel++;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "audio/mixer/audiomixerchannel.h"
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
audiomixerchannelstate_t channels[AUDIO_MIXER_CHANNEL_COUNT];
|
||||||
|
} audiomixer_t;
|
||||||
|
|
||||||
|
extern audiomixer_t AUDIO_MIXER;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes the audio mixer.
|
||||||
|
*/
|
||||||
|
errorret_t audioMixerInit();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the audio mixer, called before rendering (the start of the
|
||||||
|
* frame) - see audioMixerChannelUpdateEarly()'s own comment, run for every
|
||||||
|
* channel.
|
||||||
|
*/
|
||||||
|
errorret_t audioMixerUpdateEarly();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the audio mixer, called at the end of each frame - see
|
||||||
|
* audioMixerChannelUpdateLate()'s own comment, run for every channel.
|
||||||
|
*/
|
||||||
|
errorret_t audioMixerUpdateLate();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same as audioMixerPlayLooped() but with no looping.
|
||||||
|
*
|
||||||
|
* @param file File to be played.
|
||||||
|
* @param channel Channel you want to play this sound on.
|
||||||
|
* @param volume Volume of the sound, from 0.0 (silent) to 1.0 (loudest).
|
||||||
|
* @param pan Stereo panning of the sound, from AUDIO_STREAM_LEFT to
|
||||||
|
* AUDIO_STREAM_RIGHT.
|
||||||
|
*/
|
||||||
|
void audioMixerPlay(
|
||||||
|
const char_t *file,
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
const float_t volume,
|
||||||
|
const float_t pan
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queues a sound to be played on the next audio mixer update, which occurs at
|
||||||
|
* the end of each frame.
|
||||||
|
*
|
||||||
|
* Mixer channels can only hold one voice (audio stream) at a time. If you try
|
||||||
|
* to queue multiple sounds on the same channel only the last one will be played
|
||||||
|
* and will stop any actively playing on that channel currently.
|
||||||
|
*
|
||||||
|
* Volume is also mixed based on the channel, so supplying volume 1.0 is then
|
||||||
|
* multiplied by the channel's volume, e.g. 0.5*1.0 = 0.5.
|
||||||
|
*
|
||||||
|
* @param file File to be played.
|
||||||
|
* @param channel Channel you want to play this sound on.
|
||||||
|
* @param volume Volume of the sound, from 0.0 (silent) to 1.0 (loudest).
|
||||||
|
* @param pan Stereo panning of the sound, from AUDIO_STREAM_LEFT to
|
||||||
|
* AUDIO_STREAM_RIGHT.
|
||||||
|
* @param loopCount How many times to loop the sound, 0 for infinite looping.
|
||||||
|
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
|
||||||
|
* the whole stream (the default).
|
||||||
|
* @param loopTo Where the loop segment starts, in seconds.
|
||||||
|
*/
|
||||||
|
void audioMixerPlayLooped(
|
||||||
|
const char_t *file,
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
const float_t volume,
|
||||||
|
const float_t pan,
|
||||||
|
const uint8_t loopCount,
|
||||||
|
const float_t loopStart,
|
||||||
|
const float_t loopTo
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared implementation behind audioMixerPlay()/audioMixerPlayLooped() -
|
||||||
|
* queues an AUDIO_MIXER_COMMAND_PLAY for the given channel, to be loaded at
|
||||||
|
* the end of this frame and started at the start of the next (see
|
||||||
|
* audioMixerUpdateLate()/audioMixerUpdateEarly()).
|
||||||
|
*
|
||||||
|
* @param file File to be played.
|
||||||
|
* @param channel Channel you want to play this sound on.
|
||||||
|
* @param volume Volume of the sound, from 0.0 (silent) to 1.0 (loudest).
|
||||||
|
* @param pan Stereo panning of the sound, from AUDIO_STREAM_LEFT to
|
||||||
|
* AUDIO_STREAM_RIGHT.
|
||||||
|
* @param looping Whether the stream should loop once it finishes.
|
||||||
|
* @param loopCount How many times to loop the sound, 0 for infinite looping.
|
||||||
|
* Ignored unless looping is true.
|
||||||
|
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
|
||||||
|
* the whole stream. Ignored unless looping is true.
|
||||||
|
* @param loopTo Where the loop segment starts, in seconds. Ignored unless
|
||||||
|
* looping is true.
|
||||||
|
*/
|
||||||
|
void audioMixerQueuePlay(
|
||||||
|
const char_t *file,
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
const float_t volume,
|
||||||
|
const float_t pan,
|
||||||
|
const bool_t looping,
|
||||||
|
const uint8_t loopCount,
|
||||||
|
const float_t loopStart,
|
||||||
|
const float_t loopTo
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stops playing sound on the given channel.
|
||||||
|
*
|
||||||
|
* @param channel Channel to stop.
|
||||||
|
*/
|
||||||
|
void audioMixerStop(const audiomixerchannel_t channel);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pauses the given channel's currently playing stream, if any - a safe
|
||||||
|
* no-op if the channel isn't playing anything. Playback position is
|
||||||
|
* retained, so audioMixerResume() continues from the same point.
|
||||||
|
*
|
||||||
|
* @param channel Channel to pause.
|
||||||
|
*/
|
||||||
|
void audioMixerPause(const audiomixerchannel_t channel);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resumes the given channel's currently paused stream, if any - a safe
|
||||||
|
* no-op if the channel isn't playing anything.
|
||||||
|
*
|
||||||
|
* @param channel Channel to resume.
|
||||||
|
*/
|
||||||
|
void audioMixerResume(const audiomixerchannel_t channel);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the stereo panning of the given channel's currently playing stream,
|
||||||
|
* if any - a safe no-op if the channel isn't playing anything. Only
|
||||||
|
* affects what's playing right now; a later audioMixerPlay()/
|
||||||
|
* audioMixerPlayLooped() call on this channel uses its own `pan` argument
|
||||||
|
* instead.
|
||||||
|
*
|
||||||
|
* @param channel Channel to update.
|
||||||
|
* @param pan Stereo panning, from AUDIO_STREAM_LEFT to AUDIO_STREAM_RIGHT.
|
||||||
|
*/
|
||||||
|
void audioMixerSetPan(const audiomixerchannel_t channel, const float_t pan);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the looping behaviour of the given channel's currently playing
|
||||||
|
* stream, if any - a safe no-op if the channel isn't playing anything.
|
||||||
|
* Only affects what's playing right now; a later audioMixerPlay()/
|
||||||
|
* audioMixerPlayLooped() call on this channel uses its own loop arguments
|
||||||
|
* instead.
|
||||||
|
*
|
||||||
|
* @param channel Channel to update.
|
||||||
|
* @param looping Whether the stream should loop.
|
||||||
|
* @param loopCount How many times to loop, 0 for infinite. Ignored unless
|
||||||
|
* looping is true.
|
||||||
|
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
|
||||||
|
* the whole stream. Ignored unless looping is true.
|
||||||
|
* @param loopTo Where the loop segment starts, in seconds. Ignored unless
|
||||||
|
* looping is true.
|
||||||
|
*/
|
||||||
|
void audioMixerSetLoop(
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
const bool_t looping,
|
||||||
|
const uint8_t loopCount,
|
||||||
|
const float_t loopStart,
|
||||||
|
const float_t loopTo
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts fading the given channel from `from` to `to` over `duration`
|
||||||
|
* seconds, eased by `easing` - see audioMixerChannelFadeTo()'s own
|
||||||
|
* comment. Continues running (advanced every audioMixerUpdateEarly()) even
|
||||||
|
* if the channel isn't currently playing anything.
|
||||||
|
*
|
||||||
|
* @param channel Channel to fade.
|
||||||
|
* @param from Starting fade value, from 0.0 (silent) to 1.0 (loudest).
|
||||||
|
* @param to Ending fade value, from 0.0 (silent) to 1.0 (loudest).
|
||||||
|
* @param duration How long the fade takes, in seconds.
|
||||||
|
* @param easing Easing curve to apply to the fade's progress.
|
||||||
|
*/
|
||||||
|
void audioMixerFadeTo(
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
const float_t from,
|
||||||
|
const float_t to,
|
||||||
|
const float_t duration,
|
||||||
|
const easingtype_t easing
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the given channel currently has a fade in progress (started via
|
||||||
|
* audioMixerFadeTo() and not yet finished).
|
||||||
|
*
|
||||||
|
* @param channel Channel to check.
|
||||||
|
* @return true if a fade is still in progress.
|
||||||
|
*/
|
||||||
|
bool_t audioMixerIsFading(const audiomixerchannel_t channel);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposes the audio mixer.
|
||||||
|
*/
|
||||||
|
errorret_t audioMixerDispose();
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "audiomixerchannel.h"
|
||||||
|
#include "asset/asset.h"
|
||||||
|
#include "audio/audio.h"
|
||||||
|
#include "audio/stream/audiostream.h"
|
||||||
|
#include "audio/stream/audiostreamtype.h"
|
||||||
|
#include "save/save.h"
|
||||||
|
#include "time/time.h"
|
||||||
|
#include "util/math.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
|
||||||
|
errorret_t audioMixerChannelStopStream(audiomixerchannelstate_t *state) {
|
||||||
|
assertNotNull(state, "State cannot be NULL.");
|
||||||
|
|
||||||
|
if(state->stream == NULL) errorOk();
|
||||||
|
|
||||||
|
errorChain(audioStreamDispose(state->stream));
|
||||||
|
state->stream = NULL;
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerChannelFadeTo(
|
||||||
|
audiomixerchannelstate_t *state,
|
||||||
|
const float_t from,
|
||||||
|
const float_t to,
|
||||||
|
const float_t duration,
|
||||||
|
const easingtype_t easing
|
||||||
|
) {
|
||||||
|
assertNotNull(state, "State cannot be NULL.");
|
||||||
|
|
||||||
|
state->fade = from;
|
||||||
|
state->fadeFrom = from;
|
||||||
|
state->fadeTo = to;
|
||||||
|
state->fadeDuration = duration;
|
||||||
|
state->fadeEasing = easing;
|
||||||
|
// A non-positive duration finishes instantly - marked inactive right
|
||||||
|
// away (fadeTime < 0) rather than left at 0 to progress next frame,
|
||||||
|
// since there's nothing left to progress.
|
||||||
|
if(duration <= 0.0f) {
|
||||||
|
state->fade = to;
|
||||||
|
state->fadeTime = -1.0f;
|
||||||
|
} else {
|
||||||
|
state->fadeTime = 0.0f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool_t audioMixerChannelIsFading(const audiomixerchannelstate_t *state) {
|
||||||
|
assertNotNull(state, "State cannot be NULL.");
|
||||||
|
|
||||||
|
return state->fadeTime >= 0.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerChannelApplyVolume(
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
audiomixerchannelstate_t *state
|
||||||
|
) {
|
||||||
|
assertNotNull(state, "State cannot be NULL.");
|
||||||
|
|
||||||
|
if(state->stream == NULL) return;
|
||||||
|
|
||||||
|
// Advances any in-progress fade before it's read below - see
|
||||||
|
// audioMixerChannelFadeTo()'s own comment on fadeTime's meaning.
|
||||||
|
if(state->fadeTime >= 0.0f) {
|
||||||
|
state->fadeTime += TIME.delta;
|
||||||
|
const float_t t = mathClamp(
|
||||||
|
state->fadeTime / state->fadeDuration, 0.0f, 1.0f
|
||||||
|
);
|
||||||
|
state->fade = state->fadeFrom +
|
||||||
|
(state->fadeTo - state->fadeFrom) * easingApply(state->fadeEasing, t);
|
||||||
|
if(state->fadeTime >= state->fadeDuration) {
|
||||||
|
state->fade = state->fadeTo;
|
||||||
|
state->fadeTime = -1.0f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// state->fade and both SAVE.settings volumes have no setter - written
|
||||||
|
// directly by callers - so this is the only place any of them ever gets
|
||||||
|
// validated, rather than at the point they're set.
|
||||||
|
assertTrue(
|
||||||
|
state->fade >= 0.0f && state->fade <= 1.0f,
|
||||||
|
"Channel fade is out of range."
|
||||||
|
);
|
||||||
|
assertTrue(
|
||||||
|
SAVE.settings.audioChannelVolume[channel] >= 0.0f &&
|
||||||
|
SAVE.settings.audioChannelVolume[channel] <= 1.0f,
|
||||||
|
"Channel volume is out of range."
|
||||||
|
);
|
||||||
|
assertTrue(
|
||||||
|
SAVE.settings.audioMasterVolume >= 0.0f &&
|
||||||
|
SAVE.settings.audioMasterVolume <= 1.0f,
|
||||||
|
"Master volume is out of range."
|
||||||
|
);
|
||||||
|
|
||||||
|
// Final computed volume.
|
||||||
|
float_t volume = (
|
||||||
|
state->baseVolume *
|
||||||
|
state->fade *
|
||||||
|
SAVE.settings.audioChannelVolume[channel] *
|
||||||
|
SAVE.settings.audioMasterVolume
|
||||||
|
);
|
||||||
|
audioStreamSetVolume(state->stream, volume);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioMixerChannelUpdateEarly(
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
audiomixerchannelstate_t *state
|
||||||
|
) {
|
||||||
|
assertNotNull(state, "State cannot be NULL.");
|
||||||
|
|
||||||
|
audiomixercommand_t *command = &state->pending;
|
||||||
|
|
||||||
|
if(command->command == AUDIO_MIXER_COMMAND_STOP) {
|
||||||
|
errorChain(audioMixerChannelStopStream(state));
|
||||||
|
command->command = AUDIO_MIXER_COMMAND_NONE;
|
||||||
|
audioMixerChannelApplyVolume(channel, state);
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(
|
||||||
|
command->command != AUDIO_MIXER_COMMAND_PLAY ||
|
||||||
|
command->loadingAsset == NULL
|
||||||
|
) {
|
||||||
|
// A PLAY command with no loadingAsset yet (command->loadingAsset ==
|
||||||
|
// NULL) was queued too late for the audioMixerChannelUpdateLate() that
|
||||||
|
// just ran immediately before this call to have locked it - the only
|
||||||
|
// way that happens is a command queued outside the normal per-frame
|
||||||
|
// cycle, e.g. during engine startup before any
|
||||||
|
// audioMixerChannelUpdateLate() has run yet. Left alone (still
|
||||||
|
// AUDIO_MIXER_COMMAND_PLAY) rather than treated as an error: the very
|
||||||
|
// next audioMixerChannelUpdateLate() will lock it, and the frame after
|
||||||
|
// that will reach here and apply it normally.
|
||||||
|
audioMixerChannelApplyVolume(channel, state);
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Blocks here if audioMixerChannelUpdateLate()'s load (kicked off at the
|
||||||
|
// end of the previous frame) hasn't finished yet - see this function's
|
||||||
|
// own doc comment on why that's accepted for now.
|
||||||
|
errorret_t loadRet = assetRequireLoaded(command->loadingAsset);
|
||||||
|
if(errorIsNotOk(loadRet)) {
|
||||||
|
assetUnlockEntry(command->loadingAsset);
|
||||||
|
command->loadingAsset = NULL;
|
||||||
|
command->command = AUDIO_MIXER_COMMAND_NONE;
|
||||||
|
errorChain(loadRet);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorChain(audioMixerChannelStopStream(state));
|
||||||
|
|
||||||
|
audiostream_t *stream = audioAquireStream(command->loadingAsset);
|
||||||
|
assertNotNull(stream, "No free audio stream slots available.");
|
||||||
|
|
||||||
|
errorret_t initRet = audioStreamInit(stream, command->loadingAsset);
|
||||||
|
// The stream holds its own lock on the asset once initialized (or, on
|
||||||
|
// failure, audioStreamInit() has already released it itself) - either
|
||||||
|
// way this call's own lock is no longer needed.
|
||||||
|
assetUnlockEntry(command->loadingAsset);
|
||||||
|
command->loadingAsset = NULL;
|
||||||
|
command->command = AUDIO_MIXER_COMMAND_NONE;
|
||||||
|
errorChain(initRet);
|
||||||
|
|
||||||
|
// Forwards to this channel's own onLoop/onEnd (persistent across every
|
||||||
|
// play on this channel) rather than this one stream instance's own -
|
||||||
|
// see audiomixerchannelstate_t.onLoop's own comment.
|
||||||
|
stream->user = state;
|
||||||
|
stream->onLoop = audioMixerChannelOnStreamLoop;
|
||||||
|
stream->onEnd = audioMixerChannelOnStreamEnd;
|
||||||
|
|
||||||
|
audioStreamSetDirectionality(stream, command->pan);
|
||||||
|
if(command->looping) {
|
||||||
|
audioStreamSetLooping(stream, true);
|
||||||
|
audioStreamSetLoopPoints(stream, command->loopStart, command->loopTo);
|
||||||
|
audioStreamSetLoopLimit(stream, command->loopCount);
|
||||||
|
}
|
||||||
|
audioStreamPlay(stream);
|
||||||
|
|
||||||
|
state->stream = stream;
|
||||||
|
state->baseVolume = command->volume;
|
||||||
|
|
||||||
|
audioMixerChannelApplyVolume(channel, state);
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioMixerChannelUpdateLate(audiomixerchannelstate_t *state) {
|
||||||
|
assertNotNull(state, "State cannot be NULL.");
|
||||||
|
|
||||||
|
audiomixercommand_t *command = &state->pending;
|
||||||
|
|
||||||
|
if(command->command != AUDIO_MIXER_COMMAND_PLAY) errorOk();
|
||||||
|
|
||||||
|
assetloadertype_t assetType = audioStreamAssetTypeForPath(command->file);
|
||||||
|
assertTrue(
|
||||||
|
assetType != ASSET_LOADER_TYPE_NULL, "Unsupported audio file extension."
|
||||||
|
);
|
||||||
|
|
||||||
|
// Begins loading now - kicked off at the end of this frame so it has
|
||||||
|
// until the start of the next (audioMixerChannelUpdateEarly()) to finish
|
||||||
|
// before that has to block on it.
|
||||||
|
command->loadingAsset = assetLock(command->file, assetType, NULL);
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerChannelOnStreamLoop(audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
|
||||||
|
audiomixerchannelstate_t *state = (audiomixerchannelstate_t *) stream->user;
|
||||||
|
if(state->onLoop != NULL) state->onLoop(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioMixerChannelOnStreamEnd(audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
|
||||||
|
audiomixerchannelstate_t *state = (audiomixerchannelstate_t *) stream->user;
|
||||||
|
if(state->onEnd != NULL) state->onEnd(state);
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "dusk.h"
|
||||||
|
#include "error/error.h"
|
||||||
|
#include "animation/easing.h"
|
||||||
|
|
||||||
|
// Forward-declared rather than including asset/asset.h - this header only
|
||||||
|
// ever needs a pointer to it, and pulling in the full asset module here
|
||||||
|
// creates a real include cycle for anything that reaches this header via
|
||||||
|
// asset/loader/cutscene/assetcutsceneloader.h (asset.h -> ... ->
|
||||||
|
// assetloader.h -> assetcutsceneloader.h -> cutscene.h -> cutsceneitem.h
|
||||||
|
// -> the audio cutscene items -> this header -> asset/asset.h again,
|
||||||
|
// mid-parse). audiomixerchannel.c itself still includes the full header.
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
typedef struct audiostream_s audiostream_t;
|
||||||
|
|
||||||
|
#define AUDIO_PATH_MAX 256
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
AUDIO_MIXER_CHANNEL_BGM_0,
|
||||||
|
AUDIO_MIXER_CHANNEL_VOICE_0,
|
||||||
|
AUDIO_MIXER_CHANNEL_VOICE_1,
|
||||||
|
AUDIO_MIXER_CHANNEL_SFX_0,
|
||||||
|
AUDIO_MIXER_CHANNEL_SFX_1,
|
||||||
|
AUDIO_MIXER_CHANNEL_SFX_2,
|
||||||
|
AUDIO_MIXER_CHANNEL_SFX_3,
|
||||||
|
AUDIO_MIXER_CHANNEL_COUNT
|
||||||
|
} audiomixerchannel_t;
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
AUDIO_MIXER_COMMAND_NONE,
|
||||||
|
AUDIO_MIXER_COMMAND_PLAY,
|
||||||
|
AUDIO_MIXER_COMMAND_STOP
|
||||||
|
} audiomixercommandtype_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
// What audioMixerChannelUpdateEarly() should do to this channel at the
|
||||||
|
// start of the next frame - AUDIO_MIXER_COMMAND_NONE if nothing's
|
||||||
|
// queued. Set by audioMixerPlay()/audioMixerPlayLooped()/
|
||||||
|
// audioMixerStop(); queuing a new command on a channel replaces, rather
|
||||||
|
// than stacks on top of, whatever was already queued for it this frame -
|
||||||
|
// only the most recent survives.
|
||||||
|
audiomixercommandtype_t command;
|
||||||
|
|
||||||
|
// AUDIO_MIXER_COMMAND_PLAY only, below.
|
||||||
|
char_t file[AUDIO_PATH_MAX];
|
||||||
|
float_t volume;
|
||||||
|
float_t pan;
|
||||||
|
bool_t looping;
|
||||||
|
uint8_t loopCount;
|
||||||
|
float_t loopStart;
|
||||||
|
float_t loopTo;
|
||||||
|
|
||||||
|
// Set by audioMixerChannelUpdateLate() (the end of the frame this PLAY
|
||||||
|
// command was queued on), once it locks the requested file and kicks off
|
||||||
|
// its load. audioMixerChannelUpdateEarly() (the start of the next frame)
|
||||||
|
// blocks on this being fully loaded before actually starting playback -
|
||||||
|
// see its own comment. NULL except in that in-between window.
|
||||||
|
assetentry_t *loadingAsset;
|
||||||
|
} audiomixercommand_t;
|
||||||
|
|
||||||
|
typedef struct audiomixerchannelstate_s audiomixerchannelstate_t;
|
||||||
|
|
||||||
|
typedef struct audiomixerchannelstate_s {
|
||||||
|
// Queued action for the next audioMixerChannelUpdateEarly() to apply.
|
||||||
|
audiomixercommand_t pending;
|
||||||
|
|
||||||
|
// This channel's currently playing stream, or NULL if nothing is -
|
||||||
|
// acquired from AUDIO.streams by audioMixerChannelUpdateEarly() when it
|
||||||
|
// applies an AUDIO_MIXER_COMMAND_PLAY, disposed the same way on
|
||||||
|
// AUDIO_MIXER_COMMAND_STOP or before a new AUDIO_MIXER_COMMAND_PLAY
|
||||||
|
// replaces it.
|
||||||
|
audiostream_t *stream;
|
||||||
|
|
||||||
|
// The per-sound volume `stream` was last started with (the `volume`
|
||||||
|
// argument to whichever audioMixerPlay()/audioMixerPlayLooped() call
|
||||||
|
// started it) - combined with this channel's fade, its own volume
|
||||||
|
// (SAVE.settings.audioChannelVolume) and the mixer's master volume
|
||||||
|
// (SAVE.settings.audioMasterVolume), every frame, to get the volume
|
||||||
|
// actually passed to audioStreamSetVolume(). Meaningless while `stream`
|
||||||
|
// is NULL.
|
||||||
|
float_t baseVolume;
|
||||||
|
|
||||||
|
// This channel's own fade multiplier, from 0.0 (fully faded out) to 1.0
|
||||||
|
// (no fade applied, the default) - transient runtime state, unlike the
|
||||||
|
// channel/master volumes below (which are persisted user preferences).
|
||||||
|
// No setter - write it directly; audioMixerChannelApplyVolume() asserts
|
||||||
|
// it's in range the next time it reads it, rather than validating at the
|
||||||
|
// point it's set.
|
||||||
|
float_t fade;
|
||||||
|
|
||||||
|
// Fade transition state, set by audioMixerChannelFadeTo() and advanced
|
||||||
|
// every frame by audioMixerChannelApplyVolume(), before it reads `fade`
|
||||||
|
// to compute the mixed volume. fadeTime < 0 means no fade is in progress
|
||||||
|
// (audioMixerChannelIsFading() is just `fadeTime >= 0`) - audioMixerInit()
|
||||||
|
// explicitly sets this to -1.0f, since zero-initializing it would
|
||||||
|
// otherwise look like an active fade at time 0.
|
||||||
|
float_t fadeFrom;
|
||||||
|
float_t fadeTo;
|
||||||
|
float_t fadeDuration;
|
||||||
|
float_t fadeTime;
|
||||||
|
easingtype_t fadeEasing;
|
||||||
|
|
||||||
|
// Arbitrary caller data, handed back as-is to onLoop/onEnd below - never
|
||||||
|
// read or written by the mixer itself. NULL by default.
|
||||||
|
void *user;
|
||||||
|
|
||||||
|
// Fired (from the main thread - safe to do arbitrary work, same
|
||||||
|
// guarantee as audiostream_t's own onLoop/onEnd) whenever this channel's
|
||||||
|
// currently playing stream loops, or reaches its natural end (including
|
||||||
|
// hitting its loop limit - see audioStreamSetLoopLimit()) and stops.
|
||||||
|
// Wired onto every stream this channel starts via
|
||||||
|
// audioMixerChannelOnStreamLoop()/OnStreamEnd() - not called directly by
|
||||||
|
// anything else. No setter - write these fields directly; NULL (the
|
||||||
|
// default) means not notified. Unlike `stream`/`pending`, these persist
|
||||||
|
// across every play on this channel, not just one.
|
||||||
|
void (*onLoop)(audiomixerchannelstate_t *state);
|
||||||
|
void (*onEnd)(audiomixerchannelstate_t *state);
|
||||||
|
} audiomixerchannelstate_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stops and disposes the given channel's currently playing stream, if any -
|
||||||
|
* a safe no-op if the channel is already idle. Shared by
|
||||||
|
* audioMixerChannelUpdateEarly() (AUDIO_MIXER_COMMAND_STOP, and replacing a
|
||||||
|
* channel's stream before a new AUDIO_MIXER_COMMAND_PLAY starts) and
|
||||||
|
* audioMixerDispose().
|
||||||
|
*
|
||||||
|
* @param state The channel state to stop.
|
||||||
|
*/
|
||||||
|
errorret_t audioMixerChannelStopStream(audiomixerchannelstate_t *state);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computes the given channel's actual playback volume - its currently
|
||||||
|
* playing sound's own volume (baseVolume), this channel's fade, this
|
||||||
|
* channel's own volume (SAVE.settings.audioChannelVolume[channel]) and the
|
||||||
|
* mixer's master volume (SAVE.settings.audioMasterVolume) - and applies it
|
||||||
|
* via audioStreamSetVolume(). Asserts fade and both save-settings volumes
|
||||||
|
* are each within [0.0, 1.0] - the only validation any of them ever gets,
|
||||||
|
* since none of them have a setter. A safe no-op if the channel isn't
|
||||||
|
* playing anything. Called every audioMixerChannelUpdateEarly(), not just
|
||||||
|
* when a PLAY command starts a new stream - see its own comment.
|
||||||
|
*
|
||||||
|
* @param channel Which channel `state` is, to index
|
||||||
|
* SAVE.settings.audioChannelVolume with.
|
||||||
|
* @param state The channel state to update.
|
||||||
|
*/
|
||||||
|
void audioMixerChannelApplyVolume(
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
audiomixerchannelstate_t *state
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts fading the given channel's `fade` multiplier from `from` to `to`
|
||||||
|
* over `duration` seconds, eased by `easing` - snaps `fade` to `from`
|
||||||
|
* immediately, then audioMixerChannelApplyVolume() advances it every frame
|
||||||
|
* from here on. A `duration` of 0 or less snaps straight to `to` and marks
|
||||||
|
* the fade as already finished (audioMixerChannelIsFading() returns
|
||||||
|
* false on the very next call).
|
||||||
|
*
|
||||||
|
* @param state The channel state to fade.
|
||||||
|
* @param from Starting fade value, from 0.0 (silent) to 1.0 (loudest).
|
||||||
|
* @param to Ending fade value, from 0.0 (silent) to 1.0 (loudest).
|
||||||
|
* @param duration How long the fade takes, in seconds.
|
||||||
|
* @param easing Easing curve to apply to the fade's progress.
|
||||||
|
*/
|
||||||
|
void audioMixerChannelFadeTo(
|
||||||
|
audiomixerchannelstate_t *state,
|
||||||
|
const float_t from,
|
||||||
|
const float_t to,
|
||||||
|
const float_t duration,
|
||||||
|
const easingtype_t easing
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the given channel currently has a fade in progress (started via
|
||||||
|
* audioMixerChannelFadeTo() and not yet finished).
|
||||||
|
*
|
||||||
|
* @param state The channel state to check.
|
||||||
|
* @return true if a fade is still in progress.
|
||||||
|
*/
|
||||||
|
bool_t audioMixerChannelIsFading(const audiomixerchannelstate_t *state);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates a single mixer channel, called before rendering (the start of
|
||||||
|
* the frame): applies whatever command (play, stop - including everything
|
||||||
|
* a play carries, pan/looping) audioMixerChannelUpdateLate() queued for
|
||||||
|
* loading at the end of the previous frame. If that load hasn't finished
|
||||||
|
* yet, this blocks (via assetRequireLoaded()) until it has - a deliberate
|
||||||
|
* stall for now rather than skipping a frame, since there's currently no
|
||||||
|
* way to only partially apply a channel's command. Also recomputes and
|
||||||
|
* reapplies this channel's mixed volume (see
|
||||||
|
* audioMixerChannelApplyVolume()) every time, regardless of whether a
|
||||||
|
* command was queued this frame, so a live change to this channel's fade,
|
||||||
|
* its own volume, or the master volume takes effect on whatever's already
|
||||||
|
* playing too.
|
||||||
|
*
|
||||||
|
* @param channel Which channel `state` is - see
|
||||||
|
* audioMixerChannelApplyVolume()'s own comment.
|
||||||
|
* @param state The channel state to update.
|
||||||
|
*/
|
||||||
|
errorret_t audioMixerChannelUpdateEarly(
|
||||||
|
const audiomixerchannel_t channel,
|
||||||
|
audiomixerchannelstate_t *state
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates a single mixer channel, called at the end of each frame, once
|
||||||
|
* every other system has had a chance to queue a command via
|
||||||
|
* audioMixerPlay()/audioMixerPlayLooped()/audioMixerStop(). For a queued
|
||||||
|
* AUDIO_MIXER_COMMAND_PLAY, locks its file and begins loading it (see
|
||||||
|
* assetLock()) - giving it from now until the next
|
||||||
|
* audioMixerChannelUpdateEarly() to finish before that has to block on it.
|
||||||
|
* Actually starting/stopping playback happens there, not here.
|
||||||
|
*
|
||||||
|
* @param state The channel state to update.
|
||||||
|
*/
|
||||||
|
errorret_t audioMixerChannelUpdateLate(audiomixerchannelstate_t *state);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trampoline wired onto every stream a channel starts (as that stream's
|
||||||
|
* onLoop) - forwards to the channel's own onLoop (see
|
||||||
|
* audiomixerchannelstate_t.onLoop's own comment) via stream->user, which
|
||||||
|
* audioMixerChannelUpdateEarly() points at the channel's own state.
|
||||||
|
*
|
||||||
|
* @param stream The stream that looped.
|
||||||
|
*/
|
||||||
|
void audioMixerChannelOnStreamLoop(audiostream_t *stream);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same as audioMixerChannelOnStreamLoop() but wired onto onEnd, forwarding
|
||||||
|
* to the channel's own onEnd.
|
||||||
|
*
|
||||||
|
* @param stream The stream that ended.
|
||||||
|
*/
|
||||||
|
void audioMixerChannelOnStreamEnd(audiostream_t *stream);
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# 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
|
||||||
|
audiostream.c
|
||||||
|
audiostreampcm.c
|
||||||
|
audiostreammp3.c
|
||||||
|
audiostreamtype.c
|
||||||
|
)
|
||||||
@@ -0,0 +1,312 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "audiostream.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include "util/math.h"
|
||||||
|
|
||||||
|
errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertNotNull(asset, "Asset cannot be NULL.");
|
||||||
|
assertTrue(
|
||||||
|
asset->state == ASSET_ENTRY_STATE_LOADED,
|
||||||
|
"Asset must be loaded before it can back an audio stream."
|
||||||
|
);
|
||||||
|
// A caller passing an asset type that can't back an audio stream is a
|
||||||
|
// programmer error, not something that can happen from untrusted data, so
|
||||||
|
// this is an assert rather than an errorThrow (see
|
||||||
|
// feedback_assert_vs_error convention).
|
||||||
|
assertTrue(
|
||||||
|
audioStreamTypeForAssetType(asset->type) != AUDIO_STREAM_TYPE_NULL,
|
||||||
|
"Unsupported asset type for an audio stream."
|
||||||
|
);
|
||||||
|
|
||||||
|
stream->state = 0;
|
||||||
|
stream->volume = 1.0f;
|
||||||
|
stream->directionality = AUDIO_STREAM_CENTER;
|
||||||
|
stream->loopStart = -1;
|
||||||
|
stream->loopTo = 0;
|
||||||
|
stream->duration = 0;
|
||||||
|
stream->startFrame = 0;
|
||||||
|
stream->seeking = false;
|
||||||
|
stream->user = NULL;
|
||||||
|
stream->onLoop = NULL;
|
||||||
|
stream->onEnd = NULL;
|
||||||
|
stream->loopCount = 0;
|
||||||
|
stream->lastLoopCount = 0;
|
||||||
|
stream->loopLimit = 0;
|
||||||
|
stream->loopRestartCount = 0;
|
||||||
|
|
||||||
|
// Locked for as long as the stream is in use (see audiostream_t.asset's
|
||||||
|
// own comment) - released in audioStreamDispose().
|
||||||
|
stream->asset = asset;
|
||||||
|
assetEntryLock(asset);
|
||||||
|
|
||||||
|
// Type-specific setup (audioStreamPcmInit() / audioStreamMp3Init())
|
||||||
|
// determines stream->type, sets stream->sampleRate/channels, and asks
|
||||||
|
// the platform implementation to set up its state.
|
||||||
|
errorret_t ret = asset->type == ASSET_LOADER_TYPE_MP3
|
||||||
|
? audioStreamMp3Init(stream)
|
||||||
|
: audioStreamPcmInit(stream);
|
||||||
|
if(errorIsNotOk(ret)) {
|
||||||
|
assetEntryUnlock(asset);
|
||||||
|
stream->asset = NULL;
|
||||||
|
errorChain(ret);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t audioStreamGetTotalFrames(const audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
|
||||||
|
return stream->type == AUDIO_STREAM_TYPE_MP3
|
||||||
|
? audioStreamMp3GetTotalFrames(stream)
|
||||||
|
: audioStreamPcmGetTotalFrames(stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioStreamSeek(audiostream_t *stream, const size_t frame) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
|
||||||
|
errorChain(
|
||||||
|
stream->type == AUDIO_STREAM_TYPE_MP3
|
||||||
|
? audioStreamMp3Seek(stream, frame)
|
||||||
|
: audioStreamPcmSeek(stream, frame)
|
||||||
|
);
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioStreamRead(
|
||||||
|
audiostream_t *stream,
|
||||||
|
int16_t *buffer,
|
||||||
|
const size_t frameCount,
|
||||||
|
size_t *outFramesRead
|
||||||
|
) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
|
||||||
|
errorChain(
|
||||||
|
stream->type == AUDIO_STREAM_TYPE_MP3
|
||||||
|
? audioStreamMp3Read(stream, buffer, frameCount, outFramesRead)
|
||||||
|
: audioStreamPcmRead(stream, buffer, frameCount, outFramesRead)
|
||||||
|
);
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioStreamPlay(audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
stream->state |= AUDIO_STREAM_STATE_PLAYING;
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioStreamPause(audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
stream->state &= ~AUDIO_STREAM_STATE_PLAYING;
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioStreamSetPosition(audiostream_t *stream, const float_t position) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
|
||||||
|
// Wrap into [0, duration).
|
||||||
|
float_t t = position;
|
||||||
|
while(t < 0) t += stream->duration;
|
||||||
|
while(t >= stream->duration) t -= stream->duration;
|
||||||
|
|
||||||
|
stream->startFrame = (size_t) (t * stream->sampleRate);
|
||||||
|
stream->seeking = true;
|
||||||
|
|
||||||
|
// Force the next audioStreamUpdate() to re-buffer from startFrame instead
|
||||||
|
// of continuing whatever was already buffered - see the platform Buffer()
|
||||||
|
// implementations for how each one applies startFrame; PSP is the one
|
||||||
|
// exception (see audioStreamSetPosition's own doc comment).
|
||||||
|
stream->state &= ~AUDIO_STREAM_STATE_BUFFERED;
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioStreamSetLoopPoints(
|
||||||
|
audiostream_t *stream,
|
||||||
|
const float_t loopStart,
|
||||||
|
const float_t loopTo
|
||||||
|
) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertTrue(
|
||||||
|
loopStart < 0 || loopTo < loopStart,
|
||||||
|
"loopTo must be before loopStart."
|
||||||
|
);
|
||||||
|
|
||||||
|
stream->loopStart = loopStart;
|
||||||
|
stream->loopTo = loopTo;
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioStreamGetPanFactors(
|
||||||
|
const audiostream_t *stream,
|
||||||
|
float_t *outLeft,
|
||||||
|
float_t *outRight
|
||||||
|
) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertNotNull(outLeft, "outLeft cannot be NULL.");
|
||||||
|
assertNotNull(outRight, "outRight cannot be NULL.");
|
||||||
|
|
||||||
|
// directionality is already a pan factor in AUDIO_STREAM_LEFT..RIGHT
|
||||||
|
// (-1.0..1.0) - assertTrue'd here rather than clamped, since a caller
|
||||||
|
// passing something outside that range is a programmer error (see
|
||||||
|
// audioStreamSetDirectionality()'s own assert).
|
||||||
|
const float_t pan = stream->directionality;
|
||||||
|
|
||||||
|
*outLeft = pan > 0 ? (1.0f - pan) : 1.0f;
|
||||||
|
*outRight = pan < 0 ? (1.0f + pan) : 1.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t audioStreamComputeEndFrame(
|
||||||
|
const audiostream_t *stream,
|
||||||
|
const size_t startFrame,
|
||||||
|
const size_t totalFrames
|
||||||
|
) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
|
||||||
|
size_t endFrame = totalFrames;
|
||||||
|
if((stream->state & AUDIO_STREAM_STATE_LOOPING) && stream->loopStart >= 0) {
|
||||||
|
endFrame = mathMin(
|
||||||
|
(size_t) (stream->loopStart * stream->sampleRate), totalFrames
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if(startFrame >= endFrame) endFrame = totalFrames;
|
||||||
|
|
||||||
|
return endFrame;
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioStreamSetVolume(audiostream_t *stream, const float_t volume) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertTrue(volume >= 0.0f && volume <= 1.0f, "Volume is out of range.");
|
||||||
|
stream->volume = volume;
|
||||||
|
// TODO: Do I need to update the device output? PSP may require this
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioStreamSetDirectionality(
|
||||||
|
audiostream_t *stream,
|
||||||
|
const float_t directionality
|
||||||
|
) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertTrue(
|
||||||
|
directionality >= AUDIO_STREAM_LEFT && directionality <= AUDIO_STREAM_RIGHT,
|
||||||
|
"Directionality is out of range."
|
||||||
|
);
|
||||||
|
stream->directionality = directionality;
|
||||||
|
// TODO: Need to update internal decoder?
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioStreamSetLooping(audiostream_t *stream, const bool_t looping) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
|
||||||
|
if(looping) {
|
||||||
|
stream->state |= AUDIO_STREAM_STATE_LOOPING;
|
||||||
|
} else {
|
||||||
|
stream->state &= ~AUDIO_STREAM_STATE_LOOPING;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void audioStreamSetLoopLimit(audiostream_t *stream, const uint32_t loopLimit) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
stream->loopLimit = loopLimit;
|
||||||
|
stream->loopRestartCount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioStreamUpdate(audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
|
||||||
|
if(stream->type == AUDIO_STREAM_TYPE_NULL) {
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Some platforms (PSP) loop entirely on their own background thread for
|
||||||
|
// gaplessness and can only safely notify onLoop by incrementing this
|
||||||
|
// counter from there, rather than calling onLoop directly off the main
|
||||||
|
// thread - see loopCount's own comment. Firing it here, unconditionally,
|
||||||
|
// catches up to the latest count in one call even if multiple loops
|
||||||
|
// happened between two Update() calls.
|
||||||
|
if(stream->loopCount != stream->lastLoopCount) {
|
||||||
|
stream->lastLoopCount = stream->loopCount;
|
||||||
|
|
||||||
|
if(stream->onLoop != NULL) {
|
||||||
|
stream->onLoop(stream);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Once streamed (rather than fully in-memory) sources exist, this is
|
||||||
|
// where new data would be decoded/read in and re-buffered as playback
|
||||||
|
// consumes it.
|
||||||
|
// Checked in this order (finished-check before needs-buffering) so that a
|
||||||
|
// loop restart falls straight through into re-buffering within this same
|
||||||
|
// call, instead of leaving BUFFERED cleared for the caller to notice and
|
||||||
|
// act on next frame - that extra frame of latency was audible as a gap
|
||||||
|
// at every loop boundary.
|
||||||
|
if(
|
||||||
|
(stream->state & AUDIO_STREAM_STATE_PLAYING) &&
|
||||||
|
(stream->state & AUDIO_STREAM_STATE_BUFFERED) &&
|
||||||
|
audioStreamPlatformIsFinished(stream)
|
||||||
|
) {
|
||||||
|
// A limit of 0 means unlimited; otherwise this pass's restart only goes
|
||||||
|
// ahead while fewer than loopLimit restarts have already happened -
|
||||||
|
// once it's reached, fall through to the same stop/onEnd path as a
|
||||||
|
// non-looping stream instead of restarting again.
|
||||||
|
const bool_t loopLimitReached = stream->loopLimit > 0 &&
|
||||||
|
stream->loopRestartCount >= stream->loopLimit;
|
||||||
|
|
||||||
|
if((stream->state & AUDIO_STREAM_STATE_LOOPING) && !loopLimitReached) {
|
||||||
|
stream->state &= ~AUDIO_STREAM_STATE_BUFFERED;
|
||||||
|
stream->loopRestartCount++;
|
||||||
|
|
||||||
|
// Resume from loopTo rather than the very start of the buffer - only
|
||||||
|
// matters for platforms that reach this generic restart path at all
|
||||||
|
// (Linux and Dolphin, both of which re-buffer per pass and report
|
||||||
|
// "finished" at every loop boundary); PSP loops entirely on its own
|
||||||
|
// read-ahead ring instead (see loopRestartCount's own comment).
|
||||||
|
stream->startFrame = (size_t) (stream->loopTo * stream->sampleRate);
|
||||||
|
|
||||||
|
if(stream->onLoop != NULL) {
|
||||||
|
stream->onLoop(stream);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
stream->state &=
|
||||||
|
~(AUDIO_STREAM_STATE_PLAYING | AUDIO_STREAM_STATE_BUFFERED);
|
||||||
|
|
||||||
|
if(stream->onEnd != NULL) {
|
||||||
|
stream->onEnd(stream);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(
|
||||||
|
(stream->state & AUDIO_STREAM_STATE_PLAYING) &&
|
||||||
|
!(stream->state & AUDIO_STREAM_STATE_BUFFERED)
|
||||||
|
) {
|
||||||
|
errorChain(audioStreamPlatformBuffer(stream));
|
||||||
|
stream->state |= AUDIO_STREAM_STATE_BUFFERED;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioStreamDispose(audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
|
||||||
|
if(stream->type != AUDIO_STREAM_TYPE_NULL) {
|
||||||
|
errorChain(audioStreamPlatformDispose(stream));
|
||||||
|
}
|
||||||
|
|
||||||
|
if(stream->type == AUDIO_STREAM_TYPE_PCM) {
|
||||||
|
errorChain(audioStreamPcmDispose(stream));
|
||||||
|
} else if(stream->type == AUDIO_STREAM_TYPE_MP3) {
|
||||||
|
errorChain(audioStreamMp3Dispose(stream));
|
||||||
|
}
|
||||||
|
|
||||||
|
if(stream->asset != NULL) {
|
||||||
|
assetEntryUnlock(stream->asset);
|
||||||
|
stream->asset = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
stream->type = AUDIO_STREAM_TYPE_NULL;
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
@@ -0,0 +1,360 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "audio/stream/audiostreamtype.h"
|
||||||
|
#include "audio/stream/audiostreampcm.h"
|
||||||
|
#include "audio/stream/audiostreammp3.h"
|
||||||
|
#include "audio/audiostreamplatform.h"
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
|
||||||
|
#ifndef audioStreamPlatformInit
|
||||||
|
#error "audioStreamPlatformInit is not defined"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef audioStreamPlatformDispose
|
||||||
|
#error "audioStreamPlatformDispose is not defined"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef audioStreamPlatformBuffer
|
||||||
|
#error "audioStreamPlatformBuffer is not defined"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef audioStreamPlatformIsFinished
|
||||||
|
#error "audioStreamPlatformIsFinished is not defined"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define AUDIO_STREAMS_MAX 8
|
||||||
|
#define AUDIO_STREAM_STATE_PLAYING (1 << 0)
|
||||||
|
#define AUDIO_STREAM_STATE_LOOPING (1 << 1)
|
||||||
|
#define AUDIO_STREAM_STATE_BUFFERED (1 << 2)
|
||||||
|
#define AUDIO_STREAM_CENTER 0.0f
|
||||||
|
#define AUDIO_STREAM_LEFT -1.0f
|
||||||
|
#define AUDIO_STREAM_RIGHT 1.0f
|
||||||
|
|
||||||
|
typedef struct audiostream_s audiostream_t;
|
||||||
|
|
||||||
|
typedef struct audiostream_s {
|
||||||
|
// Used for aquiring new data.
|
||||||
|
audistreamtype_t type;
|
||||||
|
|
||||||
|
// What state the stream is in. volatile: PSP's output thread reads
|
||||||
|
// AUDIO_STREAM_STATE_PLAYING directly to honor a pause promptly instead
|
||||||
|
// of only reacting once the main thread's own per-frame gate notices -
|
||||||
|
// see audioStreamPSPThreadFeed()'s own comment.
|
||||||
|
volatile uint8_t state;
|
||||||
|
|
||||||
|
// The asset backing this stream's data (e.g. a WAV file) - determines
|
||||||
|
// `type` (see audioStreamInit()) and is read from on demand by the
|
||||||
|
// type-specific module (e.g. audiostreampcm.h) rather than ever being
|
||||||
|
// fully decoded into memory up front. The stream holds its own lock on
|
||||||
|
// this entry (assetEntryLock()/assetEntryUnlock()) for as long as it's
|
||||||
|
// in use, independent of whatever lock(s) the caller that requested
|
||||||
|
// playback may also be holding.
|
||||||
|
assetentry_t *asset;
|
||||||
|
|
||||||
|
// Loudness, from 0.0 (silent) to 1.0 (loudest).
|
||||||
|
float_t volume;
|
||||||
|
|
||||||
|
// In stereo space, where do we send the audio - from AUDIO_STREAM_LEFT
|
||||||
|
// (-1.0) to AUDIO_STREAM_RIGHT (1.0), AUDIO_STREAM_CENTER (0.0) by
|
||||||
|
// default.
|
||||||
|
// TODO: Can we use a 3D vector + Pro Logic II?
|
||||||
|
float_t directionality;
|
||||||
|
|
||||||
|
// In seconds, where the loop segment ends and playback jumps back to
|
||||||
|
// loopTo - -1 (the default) means "at the end of the stream", i.e. loop
|
||||||
|
// the whole buffer. Set via audioStreamSetLoopPoints().
|
||||||
|
float_t loopStart;
|
||||||
|
|
||||||
|
// In seconds, where a loop jumps back to once it reaches loopStart.
|
||||||
|
// Defaults to 0 (start of stream). Set via audioStreamSetLoopPoints().
|
||||||
|
float_t loopTo;
|
||||||
|
|
||||||
|
// Cached duration of the stream in seconds.
|
||||||
|
float_t duration;
|
||||||
|
|
||||||
|
// Frame offset the next platform Buffer() call should start playback
|
||||||
|
// from - set by audioStreamSetPosition() (an explicit seek) and by
|
||||||
|
// audioStreamUpdate() itself (to loopTo's frame offset, for platforms
|
||||||
|
// that re-enter Buffer() on every loop restart rather than looping
|
||||||
|
// natively). Each platform's Buffer()-invoking entry point must read and
|
||||||
|
// reset this to 0 synchronously, in the same call that decided to
|
||||||
|
// (re)buffer - not later/asynchronously (e.g. from a feeder thread),
|
||||||
|
// since audioStreamUpdate() may already have moved on to something else
|
||||||
|
// that touches this field by the time an async reader gets to it.
|
||||||
|
size_t startFrame;
|
||||||
|
|
||||||
|
// True when startFrame came from an explicit audioStreamSetPosition()
|
||||||
|
// seek rather than a natural loop restart. Platforms whose Buffer() call
|
||||||
|
// can leave previously-queued audio still playing underneath the new
|
||||||
|
// pass (currently just Linux's SDL queue, kept deliberately overlapping
|
||||||
|
// across a loop restart to avoid a gap) need this to tell "jump now,
|
||||||
|
// discarding whatever's still playing" (seek) apart from "let the old
|
||||||
|
// tail keep playing while the new pass queues underneath it" (loop
|
||||||
|
// restart) - both look identical as just "a pending startFrame"
|
||||||
|
// otherwise. Consumed (reset to false) the same way as startFrame.
|
||||||
|
bool_t seeking;
|
||||||
|
|
||||||
|
// Callbacks
|
||||||
|
void *user;
|
||||||
|
void (*onLoop)(audiostream_t *stream);
|
||||||
|
void (*onEnd)(audiostream_t *stream);
|
||||||
|
|
||||||
|
// Incremented by platform code (from whatever thread/context it runs in)
|
||||||
|
// each time a loop happens, instead of calling onLoop directly - onLoop
|
||||||
|
// may do arbitrary, possibly-slow work (console printing, game logic),
|
||||||
|
// which is only safe to run from the main thread inside audioStreamUpdate().
|
||||||
|
// Calling it straight from a real-time audio thread risks starving the
|
||||||
|
// hardware buffer if it takes too long - confirmed as the real cause of
|
||||||
|
// a loud crackle on PSP once its feeder thread called onLoop inline.
|
||||||
|
volatile uint32_t loopCount;
|
||||||
|
|
||||||
|
// audioStreamUpdate()'s own record of the last loopCount it fired
|
||||||
|
// onLoop for - only ever touched from the main thread.
|
||||||
|
uint32_t lastLoopCount;
|
||||||
|
|
||||||
|
// Maximum number of times this stream is allowed to loop before stopping
|
||||||
|
// (firing onEnd) instead of restarting again - 0 (the default) means loop
|
||||||
|
// forever. Has no effect unless looping is also enabled via
|
||||||
|
// audioStreamSetLooping(). Set via audioStreamSetLoopLimit().
|
||||||
|
uint32_t loopLimit;
|
||||||
|
|
||||||
|
// How many loop restarts this stream has already committed to - compared
|
||||||
|
// against loopLimit each time a restart is considered, then incremented
|
||||||
|
// if it goes ahead; reset to 0 by audioStreamSetLoopLimit(). Distinct
|
||||||
|
// from loopCount (which tracks when a loop becomes audible, purely for
|
||||||
|
// onLoop notification, and is PSP-only) - this counts decided restarts,
|
||||||
|
// main-thread-only on every platform (PSP decides whether to loop from
|
||||||
|
// its own read-ahead ring, itself driven from the main thread via
|
||||||
|
// audioStreamPSPIsFinished() - see its own comment).
|
||||||
|
uint32_t loopRestartCount;
|
||||||
|
|
||||||
|
// PCM format of the stream's decoded output - read identically by every
|
||||||
|
// platform backend regardless of stream type (PCM decodes straight
|
||||||
|
// through; MP3 decodes to this same format), so it lives here rather
|
||||||
|
// than duplicated in both audiostreampcm_t and audiostreammp3_t. Set by
|
||||||
|
// whichever type-specific Init function runs (audioStreamPcmInit() /
|
||||||
|
// audioStreamMp3Init()).
|
||||||
|
uint32_t sampleRate;
|
||||||
|
uint8_t channels;
|
||||||
|
|
||||||
|
// Stream type specific data.
|
||||||
|
union {
|
||||||
|
audiostreampcm_t pcm;
|
||||||
|
audiostreammp3_t mp3;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Platform-specific playback state (e.g. SDL2 device, PSP channel, ASND
|
||||||
|
// voice). Defined by each platform's audiostreamplatform.h.
|
||||||
|
audiostreamplatform_t platform;
|
||||||
|
} audiostream_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes an audio stream to play the given asset, determining the
|
||||||
|
* stream's type from the asset's loader type (e.g. a WAV asset becomes an
|
||||||
|
* AUDIO_STREAM_TYPE_PCM stream) and dispatching to that type's own setup
|
||||||
|
* (e.g. audioStreamPcmInit()). Does not begin playback; call
|
||||||
|
* audioStreamPlay() once this returns.
|
||||||
|
*
|
||||||
|
* The stream takes its own lock on `asset` (see audiostream_t.asset's own
|
||||||
|
* comment), released by audioStreamDispose() - the asset must already be
|
||||||
|
* loaded (ASSET_ENTRY_STATE_LOADED) when this is called.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to initialize.
|
||||||
|
* @param asset The loaded asset to play - its type must be one this
|
||||||
|
* function supports (ASSET_LOADER_TYPE_WAV or
|
||||||
|
* ASSET_LOADER_TYPE_MP3).
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the total number of decoded PCM frames (one sample per channel)
|
||||||
|
* available in the stream's underlying data, regardless of its type -
|
||||||
|
* dispatches to audioStreamPcmGetTotalFrames() or
|
||||||
|
* audioStreamMp3GetTotalFrames(). Platform backends should use this rather
|
||||||
|
* than a type-specific function directly, so they don't need to know or
|
||||||
|
* care which type they're driving.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to query.
|
||||||
|
* @return The total number of frames available.
|
||||||
|
*/
|
||||||
|
size_t audioStreamGetTotalFrames(const audiostream_t *stream);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seeks the stream's decode position to the given frame offset, regardless
|
||||||
|
* of its type - dispatches to audioStreamPcmSeek() or audioStreamMp3Seek().
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to seek.
|
||||||
|
* @param frame Frame offset to seek to, relative to the start of the
|
||||||
|
* stream's decoded data.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamSeek(audiostream_t *stream, const size_t frame);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads up to frameCount frames of decoded PCM sample data from the
|
||||||
|
* stream's current position, regardless of its type - dispatches to
|
||||||
|
* audioStreamPcmRead() or audioStreamMp3Read(). See either for the exact
|
||||||
|
* short-read-at-end-of-stream contract, which is identical for both.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to read from.
|
||||||
|
* @param buffer Destination buffer, sized for at least frameCount frames.
|
||||||
|
* @param frameCount Maximum number of frames to read.
|
||||||
|
* @param outFramesRead Set to the number of frames actually read.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamRead(
|
||||||
|
audiostream_t *stream,
|
||||||
|
int16_t *buffer,
|
||||||
|
const size_t frameCount,
|
||||||
|
size_t *outFramesRead
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Begins or resumes playback of the given audio stream.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to play.
|
||||||
|
*/
|
||||||
|
void audioStreamPlay(audiostream_t *stream);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pauses playback of the given audio stream. Playback position is retained,
|
||||||
|
* so audioStreamPlay() resumes from the same point.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to pause.
|
||||||
|
*/
|
||||||
|
void audioStreamPause(audiostream_t *stream);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seeks the given audio stream to the given position, in seconds, wrapping
|
||||||
|
* into range if the position is outside [0, duration). Takes effect on the
|
||||||
|
* next audioStreamUpdate() call for platforms that re-buffer per frame
|
||||||
|
* (e.g. Linux); on PSP, which manages an entire playback pass on its own
|
||||||
|
* feeder thread once started, a seek only takes effect the next time the
|
||||||
|
* stream begins playing from a stopped state, not instantaneously mid-pass.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to seek.
|
||||||
|
* @param position The new playback position, in seconds.
|
||||||
|
*/
|
||||||
|
void audioStreamSetPosition(audiostream_t *stream, const float_t position);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the loop region for the given audio stream: once playback reaches
|
||||||
|
* loopStart, it jumps back to loopTo instead of continuing (or stopping,
|
||||||
|
* if not looping). Has no effect unless looping is also enabled via
|
||||||
|
* audioStreamSetLooping().
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to update.
|
||||||
|
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
|
||||||
|
* the whole stream (the default).
|
||||||
|
* @param loopTo Where the loop segment starts, in seconds.
|
||||||
|
*/
|
||||||
|
void audioStreamSetLoopPoints(
|
||||||
|
audiostream_t *stream,
|
||||||
|
const float_t loopStart,
|
||||||
|
const float_t loopTo
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computes normalized left/right pan factors (0..1) for the given audio
|
||||||
|
* stream's directionality. Callers multiply these by their own
|
||||||
|
* platform-specific base volume representation.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to read directionality from.
|
||||||
|
* @param outLeft Set to the left channel's pan factor.
|
||||||
|
* @param outRight Set to the right channel's pan factor.
|
||||||
|
*/
|
||||||
|
void audioStreamGetPanFactors(
|
||||||
|
const audiostream_t *stream,
|
||||||
|
float_t *outLeft,
|
||||||
|
float_t *outRight
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computes the stop frame for a playback pass starting at startFrame: the
|
||||||
|
* current loop segment's end (stream->loopStart, converted to frames and
|
||||||
|
* clamped to totalFrames) if looping is enabled and a loop start is set,
|
||||||
|
* or totalFrames itself otherwise - including when startFrame has already
|
||||||
|
* reached or passed the computed loop end (e.g. a seek landing in an
|
||||||
|
* outro past the loop point), in which case this pass plays out to the
|
||||||
|
* true end of the stream once instead of only the loop segment.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to compute this for.
|
||||||
|
* @param startFrame This pass's starting frame offset.
|
||||||
|
* @param totalFrames The stream's total decoded frame count
|
||||||
|
* (audioStreamGetTotalFrames()).
|
||||||
|
* @return This pass's stop frame offset.
|
||||||
|
*/
|
||||||
|
size_t audioStreamComputeEndFrame(
|
||||||
|
const audiostream_t *stream,
|
||||||
|
const size_t startFrame,
|
||||||
|
const size_t totalFrames
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the playback volume of the given audio stream.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to update.
|
||||||
|
* @param volume The new volume, from 0.0 (silent) to 1.0 (loudest).
|
||||||
|
*/
|
||||||
|
void audioStreamSetVolume(audiostream_t *stream, const float_t volume);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the stereo directionality (panning) of the given audio stream.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to update.
|
||||||
|
* @param directionality The new panning value, from AUDIO_STREAM_LEFT to
|
||||||
|
* AUDIO_STREAM_RIGHT.
|
||||||
|
*/
|
||||||
|
void audioStreamSetDirectionality(
|
||||||
|
audiostream_t *stream,
|
||||||
|
const float_t directionality
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets whether the given audio stream loops back to loopTo (or the start
|
||||||
|
* of the buffer, by default - see audioStreamSetLoopPoints()) when it
|
||||||
|
* reaches loopStart (or the end of the buffer), rather than stopping and
|
||||||
|
* firing onEnd.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to update.
|
||||||
|
* @param looping Whether the stream should loop.
|
||||||
|
*/
|
||||||
|
void audioStreamSetLooping(audiostream_t *stream, const bool_t looping);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the maximum number of times the given audio stream is allowed to
|
||||||
|
* loop before stopping (firing onEnd) instead of restarting again. Has no
|
||||||
|
* effect unless looping is also enabled via audioStreamSetLooping(). Resets
|
||||||
|
* the stream's current loop-restart progress back to 0, so the stream gets
|
||||||
|
* the full count from this call onward.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to update.
|
||||||
|
* @param loopLimit Maximum number of loop restarts, or 0 (the default) to
|
||||||
|
* loop forever.
|
||||||
|
*/
|
||||||
|
void audioStreamSetLoopLimit(audiostream_t *stream, const uint32_t loopLimit);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the given audio stream, decoding new data and advancing playback
|
||||||
|
* as needed. Should be called every frame for every active stream.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to update.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamUpdate(audiostream_t *stream);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposes the audio stream, stopping playback and releasing any resources
|
||||||
|
* associated with it.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to dispose.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamDispose(audiostream_t *stream);
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "audiostreammp3.h"
|
||||||
|
#include "audiostream.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include "util/math.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
|
||||||
|
errorret_t audioStreamMp3Init(audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertNotNull(stream->asset, "Stream must have an asset assigned.");
|
||||||
|
assertTrue(
|
||||||
|
stream->asset->type == ASSET_LOADER_TYPE_MP3,
|
||||||
|
"Asset is not an MP3 file."
|
||||||
|
);
|
||||||
|
|
||||||
|
const assetmp3file_t *mp3 = &stream->asset->data.mp3;
|
||||||
|
|
||||||
|
stream->type = AUDIO_STREAM_TYPE_MP3;
|
||||||
|
stream->sampleRate = mp3->sampleRate;
|
||||||
|
stream->channels = mp3->channels;
|
||||||
|
stream->duration = (float_t) mp3->totalFrames / (float_t) mp3->sampleRate;
|
||||||
|
|
||||||
|
stream->mp3.pendingFrames = 0;
|
||||||
|
stream->mp3.pendingPosition = 0;
|
||||||
|
stream->mp3.position = 0;
|
||||||
|
stream->mp3.totalFrames = mp3->totalFrames;
|
||||||
|
|
||||||
|
// Each stream opens its own independent handle to the same underlying
|
||||||
|
// asset file - see audiostreampcm.c's audioStreamPcmInit() for why.
|
||||||
|
errorChain(assetFileInit(
|
||||||
|
&stream->mp3.file, stream->asset->name, NULL, NULL
|
||||||
|
));
|
||||||
|
errorChain(assetFileOpen(&stream->mp3.file));
|
||||||
|
errorChain(assetFileRead(&stream->mp3.file, NULL, mp3->dataOffset));
|
||||||
|
|
||||||
|
errorChain(audioStreamMp3DecoderInit(stream));
|
||||||
|
|
||||||
|
errorChain(audioStreamPlatformInit(stream));
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioStreamMp3Dispose(audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
|
||||||
|
|
||||||
|
errorChain(audioStreamMp3DecoderDispose(stream));
|
||||||
|
errorChain(assetFileClose(&stream->mp3.file));
|
||||||
|
errorChain(assetFileDispose(&stream->mp3.file));
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t audioStreamMp3GetTotalFrames(const audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
|
||||||
|
|
||||||
|
return stream->mp3.totalFrames;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioStreamMp3Seek(audiostream_t *stream, const size_t frame) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
|
||||||
|
|
||||||
|
if(frame == stream->mp3.position) {
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every seek - forward or backward - restarts decoding from the very
|
||||||
|
// start of the compressed stream and discards frames until reaching the
|
||||||
|
// target; see this file's own header comment for why MP3 has no cheaper
|
||||||
|
// option, unlike audioStreamPcmSeek()'s direct byte-offset seek.
|
||||||
|
errorChain(audioStreamMp3DecoderRewind(stream));
|
||||||
|
stream->mp3.position = 0;
|
||||||
|
stream->mp3.pendingFrames = 0;
|
||||||
|
stream->mp3.pendingPosition = 0;
|
||||||
|
|
||||||
|
const size_t channels = stream->channels;
|
||||||
|
int16_t discard[AUDIO_MP3_MAX_SAMPLES_PER_FRAME];
|
||||||
|
|
||||||
|
while(stream->mp3.position < frame) {
|
||||||
|
size_t decodedFrames = 0;
|
||||||
|
errorChain(
|
||||||
|
audioStreamMp3DecoderDecodeFrame(stream, discard, &decodedFrames)
|
||||||
|
);
|
||||||
|
if(decodedFrames == 0) {
|
||||||
|
// Ran out of stream before reaching the target - clamp rather than
|
||||||
|
// erroring, same tolerance audioStreamPcmRead() has for a
|
||||||
|
// shorter-than-declared asset.
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const size_t framesNeeded = frame - stream->mp3.position;
|
||||||
|
if(decodedFrames <= framesNeeded) {
|
||||||
|
stream->mp3.position += decodedFrames;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// This frame overshoots the target - keep the excess as pending so
|
||||||
|
// the next Read() starts exactly at `frame` instead of skipping past
|
||||||
|
// it.
|
||||||
|
const size_t keepFrames = decodedFrames - framesNeeded;
|
||||||
|
memoryMove(
|
||||||
|
discard, discard + (framesNeeded * channels),
|
||||||
|
keepFrames * channels * sizeof(int16_t)
|
||||||
|
);
|
||||||
|
memoryCopy(
|
||||||
|
stream->mp3.pending, discard, keepFrames * channels * sizeof(int16_t)
|
||||||
|
);
|
||||||
|
stream->mp3.pendingFrames = keepFrames;
|
||||||
|
stream->mp3.pendingPosition = 0;
|
||||||
|
stream->mp3.position = frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioStreamMp3Read(
|
||||||
|
audiostream_t *stream,
|
||||||
|
int16_t *buffer,
|
||||||
|
const size_t frameCount,
|
||||||
|
size_t *outFramesRead
|
||||||
|
) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertNotNull(buffer, "Buffer cannot be NULL.");
|
||||||
|
assertNotNull(outFramesRead, "outFramesRead cannot be NULL.");
|
||||||
|
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
|
||||||
|
|
||||||
|
const size_t channels = stream->channels;
|
||||||
|
size_t framesWritten = 0;
|
||||||
|
|
||||||
|
while(framesWritten < frameCount) {
|
||||||
|
if(stream->mp3.pendingPosition >= stream->mp3.pendingFrames) {
|
||||||
|
size_t decodedFrames = 0;
|
||||||
|
errorChain(audioStreamMp3DecoderDecodeFrame(
|
||||||
|
stream, stream->mp3.pending, &decodedFrames
|
||||||
|
));
|
||||||
|
stream->mp3.pendingFrames = decodedFrames;
|
||||||
|
stream->mp3.pendingPosition = 0;
|
||||||
|
if(decodedFrames == 0) break; // Genuine end of stream.
|
||||||
|
}
|
||||||
|
|
||||||
|
const size_t framesAvailable =
|
||||||
|
stream->mp3.pendingFrames - stream->mp3.pendingPosition;
|
||||||
|
const size_t framesToCopy =
|
||||||
|
mathMin(frameCount - framesWritten, framesAvailable);
|
||||||
|
|
||||||
|
memoryCopy(
|
||||||
|
buffer + (framesWritten * channels),
|
||||||
|
stream->mp3.pending + (stream->mp3.pendingPosition * channels),
|
||||||
|
framesToCopy * channels * sizeof(int16_t)
|
||||||
|
);
|
||||||
|
|
||||||
|
stream->mp3.pendingPosition += framesToCopy;
|
||||||
|
framesWritten += framesToCopy;
|
||||||
|
}
|
||||||
|
|
||||||
|
stream->mp3.position += framesWritten;
|
||||||
|
*outFramesRead = framesWritten;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "error/error.h"
|
||||||
|
#include "asset/assetfile.h"
|
||||||
|
#include "audio/audiostreammp3decoder.h"
|
||||||
|
|
||||||
|
typedef struct audiostream_s audiostream_t;
|
||||||
|
|
||||||
|
// How many interleaved PCM samples (not frames - samples, i.e. frames *
|
||||||
|
// channels) a single audioStreamMp3DecoderDecodeFrame() call is ever
|
||||||
|
// allowed to produce. Sizes the pending-sample buffer below, which every
|
||||||
|
// decoder backend writes directly into - this must be sized to the
|
||||||
|
// largest of them, not just "one MPEG frame":
|
||||||
|
// - libmad (software, Linux/Dolphin): always exactly one frame, 1152
|
||||||
|
// samples/channel for MPEG-1 Layer III, doubled here for stereo.
|
||||||
|
// - sceMp3 (hardware, PSP): its own pcmBuf is provisioned at double that
|
||||||
|
// (see AUDIO_MP3_PSP_PCM_BUF_SIZE) - i.e. sceMp3Decode() can
|
||||||
|
// legitimately hand back more than one frame's worth in a single call.
|
||||||
|
// Sizing this for only one frame silently overflowed stream->mp3.pending
|
||||||
|
// on real hardware whenever that happened - confirmed as the cause of
|
||||||
|
// very intermittent audio corruption/clicking, since it only bit when
|
||||||
|
// sceMp3 actually returned the larger amount.
|
||||||
|
// So this covers the larger (PSP) case; libmad's decode is safely well
|
||||||
|
// within it.
|
||||||
|
#define AUDIO_MP3_MAX_SAMPLES_PER_FRAME (1152 * 2 * 2)
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
// This stream's own private handle into its asset's underlying file -
|
||||||
|
// see audiostreampcm_t.file's own comment for why this isn't shared
|
||||||
|
// across streams playing the same asset. Holds compressed MP3 bytes;
|
||||||
|
// the decoder backend (audiostreammp3decoder.h) reads from it directly.
|
||||||
|
assetfile_t file;
|
||||||
|
|
||||||
|
// Opaque per-platform decoder state - a reserved sceMp3 handle plus its
|
||||||
|
// buffers on PSP, or libmad's mad_stream/mad_frame/mad_synth state plus a
|
||||||
|
// sliding compressed-byte window on the libmad-based software backend
|
||||||
|
// (Linux/Dolphin). Defined by whichever audiostreammp3decoder.h is
|
||||||
|
// actually visible when this file is compiled - see that header's own
|
||||||
|
// comment.
|
||||||
|
audiostreammp3decoder_t decoder;
|
||||||
|
|
||||||
|
// One decoded MPEG frame's worth of PCM, held here across Read() calls
|
||||||
|
// since a frame (576 or 1152 samples/channel) rarely lines up exactly
|
||||||
|
// with whatever frameCount a caller asks for. pendingPosition marks how
|
||||||
|
// many of the first pendingFrames frames have already been consumed.
|
||||||
|
int16_t pending[AUDIO_MP3_MAX_SAMPLES_PER_FRAME];
|
||||||
|
size_t pendingFrames;
|
||||||
|
size_t pendingPosition;
|
||||||
|
|
||||||
|
// Current logical PCM frame position, relative to the start of the
|
||||||
|
// decoded stream - decoding is push-forward-only (see
|
||||||
|
// audioStreamMp3Seek()'s own comment on why a backward seek re-decodes
|
||||||
|
// from the start rather than truly random-accessing).
|
||||||
|
size_t position;
|
||||||
|
|
||||||
|
// Total decoded PCM frame count for the whole clip - copied from the
|
||||||
|
// asset's parsed metadata at Init (see assetmp3file_t.totalFrames),
|
||||||
|
// exact if a Xing/Info header was present, otherwise an estimate.
|
||||||
|
size_t totalFrames;
|
||||||
|
} audiostreammp3_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configures the given MP3 audio stream from its already-assigned asset
|
||||||
|
* (see audiostream_t.asset - set by audioStreamInit(), which is what
|
||||||
|
* should be calling this, not application code directly): opens this
|
||||||
|
* stream's own private file handle onto the asset's compressed MPEG data,
|
||||||
|
* and initializes the platform decoder backend
|
||||||
|
* (audioStreamMp3DecoderInit()).
|
||||||
|
*
|
||||||
|
* Must be called after stream->asset is set and before audioStreamPlay().
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to configure.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamMp3Init(audiostream_t *stream);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposes the given MP3 audio stream's decoder backend and private file
|
||||||
|
* handle.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to dispose.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamMp3Dispose(audiostream_t *stream);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the total number of frames (one sample per channel) available in
|
||||||
|
* the stream's underlying MP3 data - see assetmp3file_t.totalFrames's own
|
||||||
|
* comment on why this is sometimes an estimate rather than an exact count,
|
||||||
|
* unlike audioStreamPcmGetTotalFrames().
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to query. Must be AUDIO_STREAM_TYPE_MP3.
|
||||||
|
* @return The total number of frames available.
|
||||||
|
*/
|
||||||
|
size_t audioStreamMp3GetTotalFrames(const audiostream_t *stream);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seeks the stream's decode position to the given frame offset. Unlike
|
||||||
|
* audioStreamPcmSeek(), this is never cheap: MPEG frames aren't
|
||||||
|
* independently decodable (each one's bit reservoir can depend on data
|
||||||
|
* carried over from prior frames), so there's no equivalent of PCM's
|
||||||
|
* direct byte-offset seek - every call, forward or backward, rewinds the
|
||||||
|
* decoder to the very start of the compressed stream and decodes (and
|
||||||
|
* discards) frames until reaching the target. Acceptable for this engine's
|
||||||
|
* actual use (looping background music, where loopTo is typically near
|
||||||
|
* the start anyway), but a real, non-constant cost for a seek deep into a
|
||||||
|
* long track.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to seek. Must be AUDIO_STREAM_TYPE_MP3.
|
||||||
|
* @param frame Frame offset to seek to, relative to the start of the
|
||||||
|
* decoded stream.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamMp3Seek(audiostream_t *stream, const size_t frame);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads up to frameCount frames of PCM sample data from the stream's
|
||||||
|
* current position, advancing it by however many frames were actually
|
||||||
|
* read. Reads fewer than frameCount (down to zero) once the underlying
|
||||||
|
* MP3 data is exhausted, rather than erroring - same contract as
|
||||||
|
* audioStreamPcmRead().
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to read from. Must be AUDIO_STREAM_TYPE_MP3.
|
||||||
|
* @param buffer Destination buffer, sized for at least frameCount frames.
|
||||||
|
* @param frameCount Maximum number of frames to read.
|
||||||
|
* @param outFramesRead Set to the number of frames actually read.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamMp3Read(
|
||||||
|
audiostream_t *stream,
|
||||||
|
int16_t *buffer,
|
||||||
|
const size_t frameCount,
|
||||||
|
size_t *outFramesRead
|
||||||
|
);
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "audiostreampcm.h"
|
||||||
|
#include "audiostream.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include "util/math.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include "util/endian.h"
|
||||||
|
|
||||||
|
errorret_t audioStreamPcmInit(audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertNotNull(stream->asset, "Stream must have an asset assigned.");
|
||||||
|
assertTrue(
|
||||||
|
stream->asset->type == ASSET_LOADER_TYPE_WAV,
|
||||||
|
"Asset is not a WAV file."
|
||||||
|
);
|
||||||
|
|
||||||
|
assetwavfile_t *wav = &stream->asset->data.wav;
|
||||||
|
|
||||||
|
stream->type = AUDIO_STREAM_TYPE_PCM;
|
||||||
|
stream->sampleRate = wav->sampleRate;
|
||||||
|
stream->channels = wav->channels;
|
||||||
|
stream->duration = (
|
||||||
|
(float_t) audioStreamPcmGetTotalFrames(stream) /
|
||||||
|
(float_t) wav->sampleRate
|
||||||
|
);
|
||||||
|
|
||||||
|
// Each stream opens its own independent handle to the same underlying
|
||||||
|
// asset file, rather than sharing a single handle on the asset entry -
|
||||||
|
// multiple streams playing the same asset concurrently (e.g. two
|
||||||
|
// simultaneous plays of the same sound effect) would otherwise fight
|
||||||
|
// over one shared read position. This isn't the final answer for that
|
||||||
|
// (a shared decode/cache layer would scale better than N independent
|
||||||
|
// decompression streams of the same data), but it's a correct one for
|
||||||
|
// now - a problem to revisit once it actually matters.
|
||||||
|
errorChain(assetFileInit(
|
||||||
|
&stream->pcm.file, stream->asset->name, NULL, NULL
|
||||||
|
));
|
||||||
|
errorChain(assetFileOpen(&stream->pcm.file));
|
||||||
|
errorChain(assetFileRead(&stream->pcm.file, NULL, wav->dataOffset));
|
||||||
|
|
||||||
|
errorChain(audioStreamPlatformInit(stream));
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioStreamPcmDispose(audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
|
||||||
|
|
||||||
|
errorChain(assetFileClose(&stream->pcm.file));
|
||||||
|
errorChain(assetFileDispose(&stream->pcm.file));
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t audioStreamPcmGetTotalFrames(const audiostream_t *stream) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
|
||||||
|
|
||||||
|
const assetwavfile_t *wav = &stream->asset->data.wav;
|
||||||
|
const size_t sourceFrameSize = (
|
||||||
|
stream->channels * (wav->bitsPerSample / 8)
|
||||||
|
);
|
||||||
|
return wav->dataSize / sourceFrameSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioStreamPcmSeek(audiostream_t *stream, const size_t frame) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
|
||||||
|
|
||||||
|
assetwavfile_t *wav = &stream->asset->data.wav;
|
||||||
|
const size_t sourceFrameSize = (
|
||||||
|
stream->channels * (wav->bitsPerSample / 8)
|
||||||
|
);
|
||||||
|
const size_t targetByte = wav->dataOffset + (frame * sourceFrameSize);
|
||||||
|
|
||||||
|
assertTrue(
|
||||||
|
frame * sourceFrameSize <= wav->dataSize,
|
||||||
|
"Seek frame is beyond the end of the PCM data."
|
||||||
|
);
|
||||||
|
|
||||||
|
const size_t currentByte = (size_t) stream->pcm.file.position;
|
||||||
|
if(targetByte < currentByte) {
|
||||||
|
// Only a full rewind can move a read cursor earlier once it's already
|
||||||
|
// advanced past a point - a compressed archive entry can't be decoded
|
||||||
|
// backward. See this function's own doc comment for the performance
|
||||||
|
// implications of a deep loopTo.
|
||||||
|
errorChain(assetFileRewind(&stream->pcm.file));
|
||||||
|
errorChain(assetFileRead(&stream->pcm.file, NULL, targetByte));
|
||||||
|
} else if(targetByte > currentByte) {
|
||||||
|
errorChain(assetFileRead(
|
||||||
|
&stream->pcm.file, NULL, targetByte - currentByte
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t audioStreamPcmRead(
|
||||||
|
audiostream_t *stream,
|
||||||
|
int16_t *buffer,
|
||||||
|
const size_t frameCount,
|
||||||
|
size_t *outFramesRead
|
||||||
|
) {
|
||||||
|
assertNotNull(stream, "Stream cannot be NULL.");
|
||||||
|
assertNotNull(buffer, "Buffer cannot be NULL.");
|
||||||
|
assertNotNull(outFramesRead, "outFramesRead cannot be NULL.");
|
||||||
|
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
|
||||||
|
|
||||||
|
assetwavfile_t *wav = &stream->asset->data.wav;
|
||||||
|
const size_t channels = stream->channels;
|
||||||
|
const size_t sourceSampleBytes = wav->bitsPerSample / 8;
|
||||||
|
const size_t sourceFrameSize = channels * sourceSampleBytes;
|
||||||
|
const size_t dataEndByte = wav->dataOffset + wav->dataSize;
|
||||||
|
const size_t currentByte = (size_t) stream->pcm.file.position;
|
||||||
|
|
||||||
|
const size_t bytesAvailable = (
|
||||||
|
currentByte < dataEndByte ? dataEndByte - currentByte : 0
|
||||||
|
);
|
||||||
|
const size_t framesAvailable = bytesAvailable / sourceFrameSize;
|
||||||
|
const size_t framesToRead = mathMin(frameCount, framesAvailable);
|
||||||
|
|
||||||
|
if(framesToRead == 0) {
|
||||||
|
*outFramesRead = 0;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(sourceSampleBytes == sizeof(int16_t)) {
|
||||||
|
// Output format already matches the source in width, but WAV samples
|
||||||
|
// are always little-endian per the format spec regardless of host -
|
||||||
|
// read straight through, then fix up byte order in place. A no-op on
|
||||||
|
// every little-endian platform (endianLittleToHost16() compiles down
|
||||||
|
// to returning its argument unchanged there) - only actually swaps
|
||||||
|
// anything on a big-endian host (Dolphin/GameCube/Wii).
|
||||||
|
errorChain(assetFileRead(
|
||||||
|
&stream->pcm.file, buffer, framesToRead * sourceFrameSize
|
||||||
|
));
|
||||||
|
const size_t sampleCount = framesToRead * channels;
|
||||||
|
for(size_t i = 0; i < sampleCount; i++) {
|
||||||
|
buffer[i] = (int16_t) endianLittleToHost16((uint16_t) buffer[i]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 24-bit source (the only other width assetWavParseHeader() accepts) -
|
||||||
|
// read the raw 3-byte samples into a scratch buffer, then truncate
|
||||||
|
// each down to 16-bit, since none of PSP/Dolphin's audio hardware (or
|
||||||
|
// SDL2 on Linux) accepts anything wider - see assetwavfile_t's own
|
||||||
|
// comment on bitsPerSample.
|
||||||
|
assertTrue(sourceSampleBytes == 3, "Unsupported PCM sample width.");
|
||||||
|
|
||||||
|
const size_t rawBytes = framesToRead * sourceFrameSize;
|
||||||
|
uint8_t *raw = memoryAllocate(rawBytes);
|
||||||
|
errorret_t ret = assetFileRead(&stream->pcm.file, raw, rawBytes);
|
||||||
|
if(errorIsNotOk(ret)) {
|
||||||
|
memoryFree(raw);
|
||||||
|
errorChain(ret);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 24-bit PCM samples are little-endian two's complement - the top two
|
||||||
|
// bytes of each (indices 1 and 2) already form that same value
|
||||||
|
// truncated to 16-bit (equivalent to an arithmetic right-shift by 8
|
||||||
|
// bits, which preserves the sign correctly since byte 2 carries it).
|
||||||
|
const size_t sampleCount = framesToRead * channels;
|
||||||
|
for(size_t i = 0; i < sampleCount; i++) {
|
||||||
|
const uint8_t *sample = raw + (i * 3);
|
||||||
|
buffer[i] = (int16_t) (sample[1] | (sample[2] << 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
memoryFree(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
*outFramesRead = framesToRead;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "error/error.h"
|
||||||
|
#include "asset/assetfile.h"
|
||||||
|
|
||||||
|
typedef struct audiostream_s audiostream_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
// This stream's own private handle into its asset's underlying file -
|
||||||
|
// deliberately not shared with any other stream reading the same asset
|
||||||
|
// (see audioStreamPcmInit's own comment for why). Its read cursor is
|
||||||
|
// what audioStreamPcmRead()/audioStreamPcmSeek() operate on.
|
||||||
|
assetfile_t file;
|
||||||
|
} audiostreampcm_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configures the given PCM audio stream from its already-assigned asset
|
||||||
|
* (see audiostream_t.asset - set by audioStreamInit(), which is what
|
||||||
|
* should be calling this, not application code directly) rather than
|
||||||
|
* taking raw decoded data: sampleRate/channels/duration are read from the
|
||||||
|
* asset's parsed WAV header, and a private file handle is opened for
|
||||||
|
* reading sample data on demand as playback consumes it (see
|
||||||
|
* audioStreamPcmRead()) - the PCM data itself is never read into memory
|
||||||
|
* all at once, so this works the same regardless of how long the
|
||||||
|
* underlying clip is.
|
||||||
|
*
|
||||||
|
* Must be called after stream->asset is set and before audioStreamPlay().
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to configure.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamPcmInit(audiostream_t *stream);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposes the given PCM audio stream's own private file handle.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to dispose.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamPcmDispose(audiostream_t *stream);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the total number of frames (one sample per channel) available
|
||||||
|
* in the stream's underlying PCM data - NOT simply the asset's declared
|
||||||
|
* byte size divided by a 16-bit frame size, since the source data isn't
|
||||||
|
* always 16-bit even though audioStreamPcmRead() always produces 16-bit
|
||||||
|
* output (see assetwavfile_t.bitsPerSample). Platform backends should use
|
||||||
|
* this rather than computing frame counts from dataSize themselves.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to query. Must be AUDIO_STREAM_TYPE_PCM.
|
||||||
|
* @return The total number of frames available.
|
||||||
|
*/
|
||||||
|
size_t audioStreamPcmGetTotalFrames(const audiostream_t *stream);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seeks the stream's private read cursor to the given frame offset
|
||||||
|
* (relative to the start of the PCM data - the same units as
|
||||||
|
* audiostream_t's startFrame/loopStart/loopTo, once converted from
|
||||||
|
* seconds). Seeking backward re-reads from the start of the underlying
|
||||||
|
* asset file (see assetFileRewind()) since a compressed archive entry can
|
||||||
|
* only be decoded forward - this makes a loop with a deep loopTo more
|
||||||
|
* expensive to restart than one near the start, which is a real
|
||||||
|
* performance caveat, not just a theoretical one, for anything backed by
|
||||||
|
* a compressed (not stored) asset archive entry.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to seek. Must be AUDIO_STREAM_TYPE_PCM.
|
||||||
|
* @param frame Frame offset to seek to, relative to the start of the PCM
|
||||||
|
* data.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamPcmSeek(audiostream_t *stream, const size_t frame);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads up to frameCount frames of PCM sample data from the stream's
|
||||||
|
* current read position, advancing it by however many frames were
|
||||||
|
* actually read. Reads fewer than frameCount (down to zero) once the
|
||||||
|
* underlying asset's PCM data is exhausted, rather than erroring - it's
|
||||||
|
* up to the caller (platform code, which already knows about loop points)
|
||||||
|
* to request no more than what it wants read from within the current
|
||||||
|
* loop segment or the true end of the clip.
|
||||||
|
*
|
||||||
|
* @param stream The audio stream to read from. Must be AUDIO_STREAM_TYPE_PCM.
|
||||||
|
* @param buffer Destination buffer, sized for at least frameCount frames.
|
||||||
|
* @param frameCount Maximum number of frames to read.
|
||||||
|
* @param outFramesRead Set to the number of frames actually read.
|
||||||
|
* @return Error indicating success or failure.
|
||||||
|
*/
|
||||||
|
errorret_t audioStreamPcmRead(
|
||||||
|
audiostream_t *stream,
|
||||||
|
int16_t *buffer,
|
||||||
|
const size_t frameCount,
|
||||||
|
size_t *outFramesRead
|
||||||
|
);
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "audiostreamtype.h"
|
||||||
|
#include "util/string.h"
|
||||||
|
|
||||||
|
const audiostreamassettypeinfo_t
|
||||||
|
AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[ASSET_LOADER_TYPE_COUNT] = {
|
||||||
|
[ASSET_LOADER_TYPE_WAV] = {
|
||||||
|
.type = AUDIO_STREAM_TYPE_PCM, .extension = ".wav"
|
||||||
|
},
|
||||||
|
[ASSET_LOADER_TYPE_MP3] = {
|
||||||
|
.type = AUDIO_STREAM_TYPE_MP3, .extension = ".mp3"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
assetloadertype_t audioStreamAssetTypeForPath(const char_t *path) {
|
||||||
|
for(assetloadertype_t i = 0; i < ASSET_LOADER_TYPE_COUNT; i++) {
|
||||||
|
const char_t *extension = AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[i].extension;
|
||||||
|
if(extension != NULL && stringEndsWithCaseInsensitive(path, extension)) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ASSET_LOADER_TYPE_NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
audistreamtype_t audioStreamTypeForAssetType(
|
||||||
|
const assetloadertype_t assetType
|
||||||
|
) {
|
||||||
|
return AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[assetType].type;
|
||||||
|
}
|
||||||
|
|
||||||
|
assetloadertype_t audioStreamAssetTypeForStreamType(
|
||||||
|
const audistreamtype_t streamType
|
||||||
|
) {
|
||||||
|
if(streamType == AUDIO_STREAM_TYPE_NULL) return ASSET_LOADER_TYPE_NULL;
|
||||||
|
|
||||||
|
for(assetloadertype_t i = 0; i < ASSET_LOADER_TYPE_COUNT; i++) {
|
||||||
|
if(AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[i].type == streamType) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ASSET_LOADER_TYPE_NULL;
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "dusk.h"
|
||||||
|
#include "asset/loader/assetloader.h"
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
AUDIO_STREAM_TYPE_NULL,
|
||||||
|
AUDIO_STREAM_TYPE_PCM,
|
||||||
|
AUDIO_STREAM_TYPE_MP3,
|
||||||
|
AUDIO_STREAM_TYPE_COUNT
|
||||||
|
} audistreamtype_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
// The audistreamtype_t an audio stream backed by this asset type should
|
||||||
|
// become - AUDIO_STREAM_TYPE_NULL (the zero-initialized default) for any
|
||||||
|
// asset type that can't back an audio stream.
|
||||||
|
audistreamtype_t type;
|
||||||
|
|
||||||
|
// This asset type's file extension, including the leading '.' (e.g.
|
||||||
|
// ".wav"). NULL for any asset type that can't back an audio stream.
|
||||||
|
const char_t *extension;
|
||||||
|
} audiostreamassettypeinfo_t;
|
||||||
|
|
||||||
|
// Maps an assetloadertype_t to the info describing the audio stream it
|
||||||
|
// backs. Indexed directly by assetentry_t.type; see audioStreamInit()'s own
|
||||||
|
// use of this for the canonical "is this asset type supported" check. Use
|
||||||
|
// the functions below rather than indexing this directly, except where
|
||||||
|
// you already have an assetloadertype_t in hand.
|
||||||
|
extern const audiostreamassettypeinfo_t
|
||||||
|
AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[ASSET_LOADER_TYPE_COUNT];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determines which asset loader type a file path's extension corresponds
|
||||||
|
* to, by matching it against AUDIO_STREAM_TYPE_FOR_ASSET_TYPE's own
|
||||||
|
* extensions (case-insensitively).
|
||||||
|
*
|
||||||
|
* @param path The file path to inspect, e.g. "audio/boa.mp3".
|
||||||
|
* @return The matching assetloadertype_t, or ASSET_LOADER_TYPE_NULL if the
|
||||||
|
* path's extension doesn't match any audio asset type.
|
||||||
|
*/
|
||||||
|
assetloadertype_t audioStreamAssetTypeForPath(const char_t *path);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Looks up the audistreamtype_t an audio stream backed by the given asset
|
||||||
|
* type should become.
|
||||||
|
*
|
||||||
|
* @param assetType The asset loader type to look up.
|
||||||
|
* @return The matching audistreamtype_t, or AUDIO_STREAM_TYPE_NULL if
|
||||||
|
* assetType can't back an audio stream.
|
||||||
|
*/
|
||||||
|
audistreamtype_t audioStreamTypeForAssetType(const assetloadertype_t assetType);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Looks up which asset loader type backs audio streams of the given type -
|
||||||
|
* the reverse of audioStreamTypeForAssetType(). Scans
|
||||||
|
* AUDIO_STREAM_TYPE_FOR_ASSET_TYPE for the first entry whose type matches,
|
||||||
|
* since it isn't itself indexed by audistreamtype_t.
|
||||||
|
*
|
||||||
|
* @param streamType The audio stream type to look up.
|
||||||
|
* @return The matching assetloadertype_t, or ASSET_LOADER_TYPE_NULL if
|
||||||
|
* streamType is AUDIO_STREAM_TYPE_NULL or otherwise unmapped.
|
||||||
|
*/
|
||||||
|
assetloadertype_t audioStreamAssetTypeForStreamType(
|
||||||
|
const audistreamtype_t streamType
|
||||||
|
);
|
||||||
@@ -18,6 +18,7 @@ console_t CONSOLE;
|
|||||||
void consoleInit(void) {
|
void consoleInit(void) {
|
||||||
memoryZero(&CONSOLE, sizeof(console_t));
|
memoryZero(&CONSOLE, sizeof(console_t));
|
||||||
CONSOLE.visible = false;
|
CONSOLE.visible = false;
|
||||||
|
// CONSOLE.visible = true;
|
||||||
threadMutexInit(&CONSOLE.printMutex);
|
threadMutexInit(&CONSOLE.printMutex);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
#include "dusk.h"
|
#include "dusk.h"
|
||||||
#include "thread/thread.h"
|
#include "thread/thread.h"
|
||||||
|
|
||||||
#define CONSOLE_LINE_MAX 512
|
#define CONSOLE_LINE_MAX 128
|
||||||
#define CONSOLE_HISTORY_MAX 16
|
#define CONSOLE_HISTORY_MAX 16
|
||||||
#define CONSOLE_EXEC_BUFFER_MAX 32
|
#define CONSOLE_EXEC_BUFFER_MAX 32
|
||||||
|
|
||||||
|
|||||||
@@ -55,8 +55,8 @@ void capsuleBuffer(
|
|||||||
vertices[vi].uv[1] = (v); \
|
vertices[vi].uv[1] = (v); \
|
||||||
vi++;
|
vi++;
|
||||||
|
|
||||||
/* ---- Top hemisphere ---- */
|
// ---- Top hemisphere ----
|
||||||
/* phi ranges from PI/2 (top pole) down to 0 (equator). */
|
// phi ranges from PI/2 (top pole) down to 0 (equator).
|
||||||
const float_t capStep = (float_t)GLM_PI_2 / (float_t)capRings;
|
const float_t capStep = (float_t)GLM_PI_2 / (float_t)capRings;
|
||||||
for(int32_t i = 0; i < capRings; i++) {
|
for(int32_t i = 0; i < capRings; i++) {
|
||||||
const float_t phi1 = (float_t)GLM_PI_2 - (float_t)i * capStep;
|
const float_t phi1 = (float_t)GLM_PI_2 - (float_t)i * capStep;
|
||||||
@@ -67,8 +67,8 @@ void capsuleBuffer(
|
|||||||
const float_t lxz1 = radius * cosf(phi1);
|
const float_t lxz1 = radius * cosf(phi1);
|
||||||
const float_t lxz2 = radius * cosf(phi2);
|
const float_t lxz2 = radius * cosf(phi2);
|
||||||
|
|
||||||
/* UV: top cap occupies v in [0.5 + halfHeightFrac .. 1.0]: we use a
|
// UV: top cap occupies v in [0.5 + halfHeightFrac .. 1.0]: we use a
|
||||||
* simple per-band normalisation against the full height. */
|
// simple per-band normalisation against the full height.
|
||||||
const float_t v1 = 1.0f - (float_t)i / (float_t)(2 * capRings + 1);
|
const float_t v1 = 1.0f - (float_t)i / (float_t)(2 * capRings + 1);
|
||||||
const float_t v2 = 1.0f - (float_t)(i + 1) / (float_t)(2 * capRings + 1);
|
const float_t v2 = 1.0f - (float_t)(i + 1) / (float_t)(2 * capRings + 1);
|
||||||
|
|
||||||
@@ -97,7 +97,7 @@ void capsuleBuffer(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---- Cylindrical body ---- */
|
// ---- Cylindrical body ----
|
||||||
{
|
{
|
||||||
const float_t yTop = cy + halfHeight;
|
const float_t yTop = cy + halfHeight;
|
||||||
const float_t yBot = cy - halfHeight;
|
const float_t yBot = cy - halfHeight;
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
// Copyright (c) 2026 Dominic Masters
|
/**
|
||||||
//
|
* Copyright (c) 2026 Dominic Masters
|
||||||
// This software is released under the MIT License.
|
*
|
||||||
// https://opensource.org/licenses/MIT
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "display/display.h"
|
#include "display/display.h"
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ void planeBuffer(
|
|||||||
|
|
||||||
switch(axis) {
|
switch(axis) {
|
||||||
case PLANE_AXIS_XY: {
|
case PLANE_AXIS_XY: {
|
||||||
/* Flat in XY at z = min[2]; spans X and Y. */
|
// Flat in XY at z = min[2]; spans X and Y.
|
||||||
const float_t z = min[2];
|
const float_t z = min[2];
|
||||||
PLANE_VERT(0, min[0], min[1], z, u0, v0)
|
PLANE_VERT(0, min[0], min[1], z, u0, v0)
|
||||||
PLANE_VERT(1, max[0], min[1], z, u1, v0)
|
PLANE_VERT(1, max[0], min[1], z, u1, v0)
|
||||||
@@ -71,7 +71,7 @@ void planeBuffer(
|
|||||||
}
|
}
|
||||||
|
|
||||||
case PLANE_AXIS_XZ: {
|
case PLANE_AXIS_XZ: {
|
||||||
/* Flat in XZ at y = min[1]; spans X and Z. */
|
// Flat in XZ at y = min[1]; spans X and Z.
|
||||||
const float_t y = min[1];
|
const float_t y = min[1];
|
||||||
PLANE_VERT(0, min[0], y, min[2], u0, v0)
|
PLANE_VERT(0, min[0], y, min[2], u0, v0)
|
||||||
PLANE_VERT(1, max[0], y, min[2], u1, v0)
|
PLANE_VERT(1, max[0], y, min[2], u1, v0)
|
||||||
@@ -83,7 +83,7 @@ void planeBuffer(
|
|||||||
}
|
}
|
||||||
|
|
||||||
case PLANE_AXIS_YZ: {
|
case PLANE_AXIS_YZ: {
|
||||||
/* Flat in YZ at x = min[0]; spans Y and Z. */
|
// Flat in YZ at x = min[0]; spans Y and Z.
|
||||||
const float_t x = min[0];
|
const float_t x = min[0];
|
||||||
PLANE_VERT(0, x, min[1], min[2], u0, v0)
|
PLANE_VERT(0, x, min[1], min[2], u0, v0)
|
||||||
PLANE_VERT(1, x, max[1], min[2], u1, v0)
|
PLANE_VERT(1, x, max[1], min[2], u1, v0)
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ void sphereBuffer(
|
|||||||
int32_t vi = 0;
|
int32_t vi = 0;
|
||||||
|
|
||||||
for(int32_t i = 0; i < stacks; i++) {
|
for(int32_t i = 0; i < stacks; i++) {
|
||||||
/* Latitude angles: top of band -> bottom of band */
|
// Latitude angles: top of band -> bottom of band
|
||||||
const float_t phi1 = (float_t)GLM_PI_2 - (float_t)i * stackStep;
|
const float_t phi1 = (float_t)GLM_PI_2 - (float_t)i * stackStep;
|
||||||
const float_t phi2 = (float_t)GLM_PI_2 - (float_t)(i + 1) * stackStep;
|
const float_t phi2 = (float_t)GLM_PI_2 - (float_t)(i + 1) * stackStep;
|
||||||
|
|
||||||
@@ -73,27 +73,33 @@ void sphereBuffer(
|
|||||||
const float_t u1 = (float_t)j / (float_t)sectors;
|
const float_t u1 = (float_t)j / (float_t)sectors;
|
||||||
const float_t u2 = (float_t)(j + 1) / (float_t)sectors;
|
const float_t u2 = (float_t)(j + 1) / (float_t)sectors;
|
||||||
|
|
||||||
vertices[vi].pos[0] = center[0] + x11; vertices[vi].pos[1] = center[1] + y1;
|
vertices[vi].pos[0] = center[0] + x11;
|
||||||
|
vertices[vi].pos[1] = center[1] + y1;
|
||||||
vertices[vi].pos[2] = center[2] + z11;
|
vertices[vi].pos[2] = center[2] + z11;
|
||||||
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v1; vi++;
|
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v1; vi++;
|
||||||
|
|
||||||
vertices[vi].pos[0] = center[0] + x21; vertices[vi].pos[1] = center[1] + y2;
|
vertices[vi].pos[0] = center[0] + x21;
|
||||||
|
vertices[vi].pos[1] = center[1] + y2;
|
||||||
vertices[vi].pos[2] = center[2] + z21;
|
vertices[vi].pos[2] = center[2] + z21;
|
||||||
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++;
|
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++;
|
||||||
|
|
||||||
vertices[vi].pos[0] = center[0] + x12; vertices[vi].pos[1] = center[1] + y1;
|
vertices[vi].pos[0] = center[0] + x12;
|
||||||
|
vertices[vi].pos[1] = center[1] + y1;
|
||||||
vertices[vi].pos[2] = center[2] + z12;
|
vertices[vi].pos[2] = center[2] + z12;
|
||||||
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++;
|
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++;
|
||||||
|
|
||||||
vertices[vi].pos[0] = center[0] + x12; vertices[vi].pos[1] = center[1] + y1;
|
vertices[vi].pos[0] = center[0] + x12;
|
||||||
|
vertices[vi].pos[1] = center[1] + y1;
|
||||||
vertices[vi].pos[2] = center[2] + z12;
|
vertices[vi].pos[2] = center[2] + z12;
|
||||||
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++;
|
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++;
|
||||||
|
|
||||||
vertices[vi].pos[0] = center[0] + x21; vertices[vi].pos[1] = center[1] + y2;
|
vertices[vi].pos[0] = center[0] + x21;
|
||||||
|
vertices[vi].pos[1] = center[1] + y2;
|
||||||
vertices[vi].pos[2] = center[2] + z21;
|
vertices[vi].pos[2] = center[2] + z21;
|
||||||
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++;
|
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++;
|
||||||
|
|
||||||
vertices[vi].pos[0] = center[0] + x22; vertices[vi].pos[1] = center[1] + y2;
|
vertices[vi].pos[0] = center[0] + x22;
|
||||||
|
vertices[vi].pos[1] = center[1] + y2;
|
||||||
vertices[vi].pos[2] = center[2] + z22;
|
vertices[vi].pos[2] = center[2] + z22;
|
||||||
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v2; vi++;
|
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v2; vi++;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,17 +47,17 @@ void triPrismBuffer(
|
|||||||
vertices[vi].uv[1] = (v); \
|
vertices[vi].uv[1] = (v); \
|
||||||
vi++;
|
vi++;
|
||||||
|
|
||||||
/* --- Front face (z = maxZ), CCW from +Z --- */
|
// --- Front face (z = maxZ), CCW from +Z ---
|
||||||
PRISM_VERT(x0, y0, maxZ, 0.0f, 0.0f)
|
PRISM_VERT(x0, y0, maxZ, 0.0f, 0.0f)
|
||||||
PRISM_VERT(x1, y1, maxZ, 1.0f, 0.0f)
|
PRISM_VERT(x1, y1, maxZ, 1.0f, 0.0f)
|
||||||
PRISM_VERT(x2, y2, maxZ, 0.5f, 1.0f)
|
PRISM_VERT(x2, y2, maxZ, 0.5f, 1.0f)
|
||||||
|
|
||||||
/* --- Back face (z = minZ), CCW from -Z (reverse winding) --- */
|
// --- Back face (z = minZ), CCW from -Z (reverse winding) ---
|
||||||
PRISM_VERT(x2, y2, minZ, 0.5f, 1.0f)
|
PRISM_VERT(x2, y2, minZ, 0.5f, 1.0f)
|
||||||
PRISM_VERT(x1, y1, minZ, 1.0f, 0.0f)
|
PRISM_VERT(x1, y1, minZ, 1.0f, 0.0f)
|
||||||
PRISM_VERT(x0, y0, minZ, 0.0f, 0.0f)
|
PRISM_VERT(x0, y0, minZ, 0.0f, 0.0f)
|
||||||
|
|
||||||
/* --- Side face 0: edge p0->p1 --- */
|
// --- Side face 0: edge p0->p1 ---
|
||||||
PRISM_VERT(x0, y0, minZ, 0.0f, 0.0f)
|
PRISM_VERT(x0, y0, minZ, 0.0f, 0.0f)
|
||||||
PRISM_VERT(x1, y1, minZ, 1.0f, 0.0f)
|
PRISM_VERT(x1, y1, minZ, 1.0f, 0.0f)
|
||||||
PRISM_VERT(x1, y1, maxZ, 1.0f, 1.0f)
|
PRISM_VERT(x1, y1, maxZ, 1.0f, 1.0f)
|
||||||
@@ -66,7 +66,7 @@ void triPrismBuffer(
|
|||||||
PRISM_VERT(x1, y1, maxZ, 1.0f, 1.0f)
|
PRISM_VERT(x1, y1, maxZ, 1.0f, 1.0f)
|
||||||
PRISM_VERT(x0, y0, maxZ, 0.0f, 1.0f)
|
PRISM_VERT(x0, y0, maxZ, 0.0f, 1.0f)
|
||||||
|
|
||||||
/* --- Side face 1: edge p1->p2 --- */
|
// --- Side face 1: edge p1->p2 ---
|
||||||
PRISM_VERT(x1, y1, minZ, 0.0f, 0.0f)
|
PRISM_VERT(x1, y1, minZ, 0.0f, 0.0f)
|
||||||
PRISM_VERT(x2, y2, minZ, 1.0f, 0.0f)
|
PRISM_VERT(x2, y2, minZ, 1.0f, 0.0f)
|
||||||
PRISM_VERT(x2, y2, maxZ, 1.0f, 1.0f)
|
PRISM_VERT(x2, y2, maxZ, 1.0f, 1.0f)
|
||||||
@@ -75,7 +75,7 @@ void triPrismBuffer(
|
|||||||
PRISM_VERT(x2, y2, maxZ, 1.0f, 1.0f)
|
PRISM_VERT(x2, y2, maxZ, 1.0f, 1.0f)
|
||||||
PRISM_VERT(x1, y1, maxZ, 0.0f, 1.0f)
|
PRISM_VERT(x1, y1, maxZ, 0.0f, 1.0f)
|
||||||
|
|
||||||
/* --- Side face 2: edge p2->p0 --- */
|
// --- Side face 2: edge p2->p0 ---
|
||||||
PRISM_VERT(x2, y2, minZ, 0.0f, 0.0f)
|
PRISM_VERT(x2, y2, minZ, 0.0f, 0.0f)
|
||||||
PRISM_VERT(x0, y0, minZ, 1.0f, 0.0f)
|
PRISM_VERT(x0, y0, minZ, 1.0f, 0.0f)
|
||||||
PRISM_VERT(x0, y0, maxZ, 1.0f, 1.0f)
|
PRISM_VERT(x0, y0, maxZ, 1.0f, 1.0f)
|
||||||
|
|||||||
@@ -13,14 +13,14 @@
|
|||||||
shader_t *bound = NULL;
|
shader_t *bound = NULL;
|
||||||
|
|
||||||
errorret_t shaderInit(shader_t *shader, const shaderdefinition_t *def) {
|
errorret_t shaderInit(shader_t *shader, const shaderdefinition_t *def) {
|
||||||
assertNotNull(shader, "Shader cannot be null");
|
assertNotNull(shader, "Shader cannot be NULL");
|
||||||
errorChain(shaderInitPlatform(shader, def));
|
errorChain(shaderInitPlatform(shader, def));
|
||||||
bound = NULL;
|
bound = NULL;
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t shaderBind(shader_t *shader) {
|
errorret_t shaderBind(shader_t *shader) {
|
||||||
assertNotNull(shader, "Shader cannot be null");
|
assertNotNull(shader, "Shader cannot be NULL");
|
||||||
errorChain(shaderBindPlatform(shader));
|
errorChain(shaderBindPlatform(shader));
|
||||||
bound = shader;
|
bound = shader;
|
||||||
errorOk();
|
errorOk();
|
||||||
@@ -31,9 +31,9 @@ errorret_t shaderSetMatrix(
|
|||||||
const char_t *name,
|
const char_t *name,
|
||||||
mat4 matrix
|
mat4 matrix
|
||||||
) {
|
) {
|
||||||
assertNotNull(shader, "Shader cannot be null");
|
assertNotNull(shader, "Shader cannot be NULL");
|
||||||
assertStrLenMin(name, 1, "Uniform name cannot be empty");
|
assertStrLenMin(name, 1, "Uniform name cannot be empty");
|
||||||
assertNotNull(matrix, "Matrix cannot be null");
|
assertNotNull(matrix, "Matrix cannot be NULL");
|
||||||
assertTrue(bound == shader, "Shader must be bound.");
|
assertTrue(bound == shader, "Shader must be bound.");
|
||||||
errorChain(shaderSetMatrixPlatform(shader, name, matrix));
|
errorChain(shaderSetMatrixPlatform(shader, name, matrix));
|
||||||
errorOk();
|
errorOk();
|
||||||
@@ -44,7 +44,7 @@ errorret_t shaderSetTexture(
|
|||||||
const char_t *name,
|
const char_t *name,
|
||||||
texture_t *texture
|
texture_t *texture
|
||||||
) {
|
) {
|
||||||
assertNotNull(shader, "Shader cannot be null");
|
assertNotNull(shader, "Shader cannot be NULL");
|
||||||
assertStrLenMin(name, 1, "Uniform name cannot be empty");
|
assertStrLenMin(name, 1, "Uniform name cannot be empty");
|
||||||
assertTrue(bound == shader, "Shader must be bound.");
|
assertTrue(bound == shader, "Shader must be bound.");
|
||||||
errorChain(shaderSetTexturePlatform(shader, name, texture));
|
errorChain(shaderSetTexturePlatform(shader, name, texture));
|
||||||
@@ -56,7 +56,7 @@ errorret_t shaderSetColor(
|
|||||||
const char_t *name,
|
const char_t *name,
|
||||||
color_t color
|
color_t color
|
||||||
) {
|
) {
|
||||||
assertNotNull(shader, "Shader cannot be null");
|
assertNotNull(shader, "Shader cannot be NULL");
|
||||||
assertStrLenMin(name, 1, "Uniform name cannot be empty");
|
assertStrLenMin(name, 1, "Uniform name cannot be empty");
|
||||||
assertTrue(bound == shader, "Shader must be bound.");
|
assertTrue(bound == shader, "Shader must be bound.");
|
||||||
errorChain(shaderSetColorPlatform(shader, name, color));
|
errorChain(shaderSetColorPlatform(shader, name, color));
|
||||||
@@ -67,16 +67,16 @@ errorret_t shaderSetMaterial(
|
|||||||
shader_t *shader,
|
shader_t *shader,
|
||||||
const shadermaterial_t *material
|
const shadermaterial_t *material
|
||||||
) {
|
) {
|
||||||
assertNotNull(shader, "Shader cannot be null");
|
assertNotNull(shader, "Shader cannot be NULL");
|
||||||
assertNotNull(material, "Material cannot be null");
|
assertNotNull(material, "Material cannot be NULL");
|
||||||
assertTrue(bound == shader, "Shader must be bound.");
|
assertTrue(bound == shader, "Shader must be bound.");
|
||||||
assertNotNull(shader->definition, "Shader definition cannot be null");
|
assertNotNull(shader->definition, "Shader definition cannot be NULL");
|
||||||
assertNotNull(shader->definition->setMaterial, "Def lacks setMaterial");
|
assertNotNull(shader->definition->setMaterial, "Def lacks setMaterial");
|
||||||
return shader->definition->setMaterial(shader, material);
|
return shader->definition->setMaterial(shader, material);
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t shaderDispose(shader_t *shader) {
|
errorret_t shaderDispose(shader_t *shader) {
|
||||||
assertNotNull(shader, "Shader cannot be null");
|
assertNotNull(shader, "Shader cannot be NULL");
|
||||||
bound = NULL;
|
bound = NULL;
|
||||||
errorChain(shaderDisposePlatform(shader));
|
errorChain(shaderDisposePlatform(shader));
|
||||||
errorOk();
|
errorOk();
|
||||||
|
|||||||
@@ -41,10 +41,10 @@ errorret_t shaderListInit() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
assertNotNull(
|
assertNotNull(
|
||||||
SHADER_LIST_DEFS[i].shader, "Shader cannot be null"
|
SHADER_LIST_DEFS[i].shader, "Shader cannot be NULL"
|
||||||
);
|
);
|
||||||
assertNotNull(
|
assertNotNull(
|
||||||
SHADER_LIST_DEFS[i].definition, "Shader definition cannot be null"
|
SHADER_LIST_DEFS[i].definition, "Shader definition cannot be NULL"
|
||||||
);
|
);
|
||||||
|
|
||||||
errorChain(shaderInit(
|
errorChain(shaderInit(
|
||||||
@@ -78,7 +78,7 @@ errorret_t shaderListDispose(void) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
assertNotNull(
|
assertNotNull(
|
||||||
SHADER_LIST_DEFS[i].shader, "Shader cannot be null"
|
SHADER_LIST_DEFS[i].shader, "Shader cannot be NULL"
|
||||||
);
|
);
|
||||||
|
|
||||||
errorChain(shaderDispose(SHADER_LIST_DEFS[i].shader));
|
errorChain(shaderDispose(SHADER_LIST_DEFS[i].shader));
|
||||||
|
|||||||
@@ -31,9 +31,9 @@ errorret_t spriteBatchBuffer(
|
|||||||
shader_t *shader,
|
shader_t *shader,
|
||||||
const shadermaterial_t material
|
const shadermaterial_t material
|
||||||
) {
|
) {
|
||||||
assertNotNull(sprites, "Sprites cannot be null");
|
assertNotNull(sprites, "Sprites cannot be NULL");
|
||||||
assertTrue(count > 0, "Count must be greater than zero");
|
assertTrue(count > 0, "Count must be greater than zero");
|
||||||
assertNotNull(shader, "Shader cannot be null");
|
assertNotNull(shader, "Shader cannot be NULL");
|
||||||
|
|
||||||
// Did the shader or material data change?
|
// Did the shader or material data change?
|
||||||
if(shader != SPRITEBATCH.shader) {
|
if(shader != SPRITEBATCH.shader) {
|
||||||
@@ -76,7 +76,8 @@ errorret_t spriteBatchBuffer(
|
|||||||
|
|
||||||
// Buffer to the mesh vertices.
|
// Buffer to the mesh vertices.
|
||||||
spriteBatchBufferToMesh(
|
spriteBatchBufferToMesh(
|
||||||
sprites, batchCount, v, batchCount * QUAD_VERTEX_COUNT
|
sprites + (count - remaining), batchCount, v,
|
||||||
|
batchCount * QUAD_VERTEX_COUNT
|
||||||
);
|
);
|
||||||
SPRITEBATCH.spriteCount += batchCount;
|
SPRITEBATCH.spriteCount += batchCount;
|
||||||
remaining -= batchCount;
|
remaining -= batchCount;
|
||||||
@@ -91,9 +92,9 @@ void spriteBatchBufferToMesh(
|
|||||||
meshvertex_t *vertices,
|
meshvertex_t *vertices,
|
||||||
const uint32_t verticesSize
|
const uint32_t verticesSize
|
||||||
) {
|
) {
|
||||||
assertNotNull(sprites, "Sprites cannot be null");
|
assertNotNull(sprites, "Sprites cannot be NULL");
|
||||||
assertTrue(count > 0, "Count must be greater than zero");
|
assertTrue(count > 0, "Count must be greater than zero");
|
||||||
assertNotNull(vertices, "Vertices cannot be null");
|
assertNotNull(vertices, "Vertices cannot be NULL");
|
||||||
assertTrue(
|
assertTrue(
|
||||||
verticesSize >= count * QUAD_VERTEX_COUNT, "Vertices array too small"
|
verticesSize >= count * QUAD_VERTEX_COUNT, "Vertices array too small"
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ typedef struct {
|
|||||||
* @param y Screen y position of the sprite's top-left corner.
|
* @param y Screen y position of the sprite's top-left corner.
|
||||||
* @param width Width of the sprite in screen space.
|
* @param width Width of the sprite in screen space.
|
||||||
* @param height Height of the sprite in screen space.
|
* @param height Height of the sprite in screen space.
|
||||||
* @returns The populated sprite.
|
* @return The populated sprite.
|
||||||
*/
|
*/
|
||||||
spritebatchsprite_t spriteBatchSpriteTilesetPosition(
|
spritebatchsprite_t spriteBatchSpriteTilesetPosition(
|
||||||
const tileset_t *tileset,
|
const tileset_t *tileset,
|
||||||
|
|||||||
@@ -76,11 +76,26 @@ const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
|
|||||||
{ 0x00, 0x22, 0x22, 0x14, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00 }, // Y
|
{ 0x00, 0x22, 0x22, 0x14, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00 }, // Y
|
||||||
{ 0x00, 0x3E, 0x02, 0x04, 0x08, 0x10, 0x20, 0x3E, 0x00, 0x00 }, // Z
|
{ 0x00, 0x3E, 0x02, 0x04, 0x08, 0x10, 0x20, 0x3E, 0x00, 0x00 }, // Z
|
||||||
{ 0x00, 0x0C, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0C, 0x00, 0x00 }, // [
|
{ 0x00, 0x0C, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0C, 0x00, 0x00 }, // [
|
||||||
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // backslash (not drawn in source font)
|
// Custom icon glyph, not a real backslash - a backspace symbol: Caps
|
||||||
|
// Lock's up arrow (see FONT_ICON_CAPSLOCK) rotated 270 degrees to
|
||||||
|
// point left instead, adapted to this font's fixed 6x10 tile (each of
|
||||||
|
// Caps Lock's row widths becomes a column height here, centered
|
||||||
|
// vertically). Backslash was never drawn anyway, and isn't a key this
|
||||||
|
// virtual keyboard can type - see FONT_ICON_BACKSPACE.
|
||||||
|
// FONT_ICON_BACKSPACE
|
||||||
|
{ 0x00, 0x00, 0x08, 0x1F, 0x3F, 0x3F, 0x1F, 0x08, 0x00, 0x00 },
|
||||||
{ 0x00, 0x18, 0x08, 0x08, 0x08, 0x08, 0x08, 0x18, 0x00, 0x00 }, // ]
|
{ 0x00, 0x18, 0x08, 0x08, 0x08, 0x08, 0x08, 0x18, 0x00, 0x00 }, // ]
|
||||||
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // ^ (not drawn in source font)
|
// ^ (not drawn in source font)
|
||||||
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // _ (not drawn in source font)
|
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
|
||||||
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // ` (not drawn in source font)
|
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E }, // _
|
||||||
|
// Custom icon glyph, not a real backtick - an up arrow for Shift, same
|
||||||
|
// head as Caps Lock's (see FONT_ICON_CAPSLOCK) but with a shaft 2px
|
||||||
|
// thinner, plus one empty row near the bottom of it, so it reads as a
|
||||||
|
// lighter/broken version of Caps Lock's thicker uninterrupted one.
|
||||||
|
// Backtick was never drawn anyway, and isn't a key this virtual
|
||||||
|
// keyboard can type - see FONT_ICON_SHIFT.
|
||||||
|
// FONT_ICON_SHIFT
|
||||||
|
{ 0x0C, 0x1E, 0x3F, 0x0C, 0x0C, 0x0C, 0x0C, 0x00, 0x0C, 0x00 },
|
||||||
{ 0x00, 0x00, 0x00, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x00, 0x00 }, // a
|
{ 0x00, 0x00, 0x00, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x00, 0x00 }, // a
|
||||||
{ 0x00, 0x20, 0x20, 0x3C, 0x22, 0x22, 0x22, 0x3C, 0x00, 0x00 }, // b
|
{ 0x00, 0x20, 0x20, 0x3C, 0x22, 0x22, 0x22, 0x3C, 0x00, 0x00 }, // b
|
||||||
{ 0x00, 0x00, 0x00, 0x1C, 0x22, 0x20, 0x22, 0x1C, 0x00, 0x00 }, // c
|
{ 0x00, 0x00, 0x00, 0x1C, 0x22, 0x20, 0x22, 0x1C, 0x00, 0x00 }, // c
|
||||||
@@ -108,11 +123,30 @@ const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
|
|||||||
{ 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, 0x1E, 0x02, 0x1C }, // y
|
{ 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, 0x1E, 0x02, 0x1C }, // y
|
||||||
{ 0x00, 0x00, 0x00, 0x3E, 0x04, 0x08, 0x10, 0x3E, 0x00, 0x00 }, // z
|
{ 0x00, 0x00, 0x00, 0x3E, 0x04, 0x08, 0x10, 0x3E, 0x00, 0x00 }, // z
|
||||||
{ 0x00, 0x04, 0x08, 0x08, 0x10, 0x08, 0x08, 0x04, 0x00, 0x00 }, // {
|
{ 0x00, 0x04, 0x08, 0x08, 0x10, 0x08, 0x08, 0x04, 0x00, 0x00 }, // {
|
||||||
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // | (not drawn in source font)
|
// Custom icon glyph, not a real pipe - a "return" arrow for the
|
||||||
|
// keyboard's newline key: a vertical riser down the right side that
|
||||||
|
// hooks left into a leftward-pointing arrowhead, i.e. "<-|" rotated
|
||||||
|
// into an L. Pipe was never drawn anyway, and isn't a key this
|
||||||
|
// virtual keyboard can type - see FONT_ICON_NEWLINE.
|
||||||
|
// FONT_ICON_NEWLINE
|
||||||
|
{ 0x02, 0x02, 0x02, 0x02, 0x0E, 0x1E, 0x08, 0x00, 0x00, 0x00 },
|
||||||
{ 0x00, 0x10, 0x08, 0x08, 0x04, 0x08, 0x08, 0x10, 0x00, 0x00 }, // }
|
{ 0x00, 0x10, 0x08, 0x08, 0x04, 0x08, 0x08, 0x10, 0x00, 0x00 }, // }
|
||||||
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // ~ (not drawn in source font)
|
// Custom icon glyph, not a real tilde - a spacebar symbol for the
|
||||||
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // unused trailing tile
|
// keyboard's space key: an underscore with a tick at each end, like
|
||||||
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // unused trailing tile
|
// "|___|". Tilde was never drawn anyway, and was explicitly dropped
|
||||||
|
// from this virtual keyboard's own key set - see FONT_ICON_SPACE.
|
||||||
|
// FONT_ICON_SPACE
|
||||||
|
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x3F },
|
||||||
|
// Custom icon glyph, not a real ASCII character - a thick, solid,
|
||||||
|
// uninterrupted up arrow for Caps Lock (contrast FONT_ICON_SHIFT's
|
||||||
|
// same head but a thinner, gapped shaft). Assigned to char code 127
|
||||||
|
// (DEL) since that codepoint is never legitimately typed text and
|
||||||
|
// (unlike 128+) is still a positive value regardless of whether this
|
||||||
|
// platform's plain `char` is signed - see FONT_ICON_CAPSLOCK.
|
||||||
|
// FONT_ICON_CAPSLOCK
|
||||||
|
{ 0x0C, 0x1E, 0x3F, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x00 },
|
||||||
|
// unused trailing tile
|
||||||
|
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
|
||||||
};
|
};
|
||||||
|
|
||||||
errorret_t fontDefaultInit(void) {
|
errorret_t fontDefaultInit(void) {
|
||||||
@@ -128,7 +162,8 @@ errorret_t fontDefaultInit(void) {
|
|||||||
|
|
||||||
for(uint16_t i = 0; i < FONT_DEFAULT_TILE_COUNT; i++) {
|
for(uint16_t i = 0; i < FONT_DEFAULT_TILE_COUNT; i++) {
|
||||||
const uint16_t tileX = (i % FONT_DEFAULT_COLUMNS) * FONT_DEFAULT_TILE_WIDTH;
|
const uint16_t tileX = (i % FONT_DEFAULT_COLUMNS) * FONT_DEFAULT_TILE_WIDTH;
|
||||||
const uint16_t tileY = (i / FONT_DEFAULT_COLUMNS) * FONT_DEFAULT_TILE_HEIGHT;
|
const uint16_t tileY =
|
||||||
|
(i / FONT_DEFAULT_COLUMNS) * FONT_DEFAULT_TILE_HEIGHT;
|
||||||
|
|
||||||
for(uint8_t row = 0; row < FONT_DEFAULT_TILE_HEIGHT; row++) {
|
for(uint8_t row = 0; row < FONT_DEFAULT_TILE_HEIGHT; row++) {
|
||||||
const uint8_t bits = FONT_DEFAULT_GLYPHS[i][row];
|
const uint8_t bits = FONT_DEFAULT_GLYPHS[i][row];
|
||||||
@@ -145,8 +180,10 @@ errorret_t fontDefaultInit(void) {
|
|||||||
FONT_DEFAULT_TILESET.columns = FONT_DEFAULT_COLUMNS;
|
FONT_DEFAULT_TILESET.columns = FONT_DEFAULT_COLUMNS;
|
||||||
FONT_DEFAULT_TILESET.rows = FONT_DEFAULT_ROWS;
|
FONT_DEFAULT_TILESET.rows = FONT_DEFAULT_ROWS;
|
||||||
FONT_DEFAULT_TILESET.tileCount = FONT_DEFAULT_TILE_COUNT;
|
FONT_DEFAULT_TILESET.tileCount = FONT_DEFAULT_TILE_COUNT;
|
||||||
FONT_DEFAULT_TILESET.uv[0] = (float_t)FONT_DEFAULT_TILE_WIDTH / (float_t)width;
|
FONT_DEFAULT_TILESET.uv[0] =
|
||||||
FONT_DEFAULT_TILESET.uv[1] = (float_t)FONT_DEFAULT_TILE_HEIGHT / (float_t)height;
|
(float_t)FONT_DEFAULT_TILE_WIDTH / (float_t)width;
|
||||||
|
FONT_DEFAULT_TILESET.uv[1] =
|
||||||
|
(float_t)FONT_DEFAULT_TILE_HEIGHT / (float_t)height;
|
||||||
|
|
||||||
const texturedata_t data = { .rgbaColors = pixels };
|
const texturedata_t data = { .rgbaColors = pixels };
|
||||||
errorret_t textureResult = textureInit(
|
errorret_t textureResult = textureInit(
|
||||||
|
|||||||
@@ -28,10 +28,45 @@ typedef struct {
|
|||||||
/**
|
/**
|
||||||
* Number of glyphs defined in FONT_DEFAULT_GLYPHS (FONT_DEFAULT_COLUMNS *
|
* Number of glyphs defined in FONT_DEFAULT_GLYPHS (FONT_DEFAULT_COLUMNS *
|
||||||
* FONT_DEFAULT_ROWS), covering the printable ASCII range starting at
|
* FONT_DEFAULT_ROWS), covering the printable ASCII range starting at
|
||||||
* TEXT_CHAR_START ('!') plus a couple of unused trailing tiles.
|
* TEXT_CHAR_START ('!'), one custom icon glyph in a trailing unused tile
|
||||||
|
* (see FONT_ICON_CAPSLOCK), plus one more genuinely unused trailing tile.
|
||||||
|
* FONT_ICON_SHIFT/FONT_ICON_NEWLINE reuse existing-but-blank slots within
|
||||||
|
* the printable range instead of more trailing tiles - see their own
|
||||||
|
* comments.
|
||||||
*/
|
*/
|
||||||
#define FONT_DEFAULT_TILE_COUNT (FONT_DEFAULT_COLUMNS * FONT_DEFAULT_ROWS)
|
#define FONT_DEFAULT_TILE_COUNT (FONT_DEFAULT_COLUMNS * FONT_DEFAULT_ROWS)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom (non-ASCII-meaning) icon glyphs baked into FONT_DEFAULT_GLYPHS
|
||||||
|
* at otherwise-unused codepoints within the range this font covers -
|
||||||
|
* safe to use anywhere a char_t string is expected, e.g. a uibutton_t
|
||||||
|
* label. Kept below 128: char_t is a plain `char`, whose signedness
|
||||||
|
* varies by platform, so a codepoint of 128 or above isn't safely
|
||||||
|
* representable everywhere this engine targets.
|
||||||
|
*/
|
||||||
|
// Thick, solid, uninterrupted up arrow - Caps Lock. A trailing tile
|
||||||
|
// (char code 127/DEL) that was never a real character to begin with.
|
||||||
|
#define FONT_ICON_CAPSLOCK "\x7F"
|
||||||
|
// Same up arrow, but with a thinner and gapped shaft - Shift. Reuses
|
||||||
|
// the backtick's glyph slot: backtick was never drawn by this font
|
||||||
|
// anyway, and isn't a key this engine's virtual keyboard can type.
|
||||||
|
#define FONT_ICON_SHIFT "`"
|
||||||
|
// A "return" arrow (down then left, with a leftward arrowhead) - the
|
||||||
|
// keyboard's newline key. Reuses the pipe's glyph slot, for the same
|
||||||
|
// reason as FONT_ICON_SHIFT.
|
||||||
|
#define FONT_ICON_NEWLINE "|"
|
||||||
|
// An underscore with a tick at each end ("|___|") - the keyboard's
|
||||||
|
// space key. Reuses the tilde's glyph slot: tilde was never drawn by
|
||||||
|
// this font, and was explicitly dropped from this engine's virtual
|
||||||
|
// keyboard's own key set.
|
||||||
|
#define FONT_ICON_SPACE "~"
|
||||||
|
// Caps Lock's arrow rotated to point left - the keyboard's backspace
|
||||||
|
// key. Reuses the backslash's glyph slot, for the same reason as
|
||||||
|
// FONT_ICON_SHIFT/FONT_ICON_NEWLINE/FONT_ICON_SPACE. Last free reused
|
||||||
|
// slot below 128 - one more custom icon after this needs
|
||||||
|
// FONT_DEFAULT_COLUMNS/ROWS grown to make room.
|
||||||
|
#define FONT_ICON_BACKSPACE "\\"
|
||||||
|
|
||||||
extern font_t FONT_DEFAULT;
|
extern font_t FONT_DEFAULT;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+112
-20
@@ -54,6 +54,62 @@ spritebatchsprite_t textGetSprite(
|
|||||||
return sprite;
|
return sprite;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int32_t textBuffer(
|
||||||
|
const float_t x,
|
||||||
|
const float_t y,
|
||||||
|
const char_t *text,
|
||||||
|
font_t *font,
|
||||||
|
spritebatchsprite_t *outSprites,
|
||||||
|
const int32_t maxSprites,
|
||||||
|
int32_t *charIndex,
|
||||||
|
float_t *posX,
|
||||||
|
float_t *posY
|
||||||
|
) {
|
||||||
|
assertNotNull(text, "Text cannot be NULL");
|
||||||
|
|
||||||
|
if(outSprites == NULL) {
|
||||||
|
int32_t count = 0;
|
||||||
|
char_t c;
|
||||||
|
int32_t i = 0;
|
||||||
|
while((c = text[i++]) != '\0') {
|
||||||
|
if(c != ' ' && c != '\n') count++;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
assertNotNull(font, "Font cannot be NULL");
|
||||||
|
assertTrue(maxSprites > 0, "Max sprites must be greater than zero");
|
||||||
|
assertNotNull(posX, "Output posX cannot be NULL");
|
||||||
|
assertNotNull(posY, "Output posY cannot be NULL");
|
||||||
|
assertNotNull(charIndex, "Output charIndex cannot be NULL");
|
||||||
|
|
||||||
|
int32_t spriteIndex = 0;
|
||||||
|
char_t c;
|
||||||
|
for(;;) {
|
||||||
|
c = text[*charIndex];
|
||||||
|
if(c == '\0') break;
|
||||||
|
(*charIndex)++;
|
||||||
|
|
||||||
|
if(c == '\n') {
|
||||||
|
*posX = x;
|
||||||
|
*posY += font->tileset->tileHeight;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(c == ' ') {
|
||||||
|
*posX += font->tileset->tileWidth;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
outSprites[spriteIndex++] = textGetSprite((vec2){*posX, *posY}, c, font);
|
||||||
|
*posX += font->tileset->tileWidth;
|
||||||
|
|
||||||
|
if(spriteIndex >= maxSprites) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return spriteIndex;
|
||||||
|
}
|
||||||
|
|
||||||
errorret_t textDraw(
|
errorret_t textDraw(
|
||||||
const float_t x,
|
const float_t x,
|
||||||
const float_t y,
|
const float_t y,
|
||||||
@@ -62,10 +118,11 @@ errorret_t textDraw(
|
|||||||
font_t *font
|
font_t *font
|
||||||
) {
|
) {
|
||||||
assertNotNull(text, "Text cannot be NULL");
|
assertNotNull(text, "Text cannot be NULL");
|
||||||
|
int32_t length = strlen(text);
|
||||||
|
if(length == 0) errorOk();
|
||||||
|
|
||||||
if(font == NULL) font = &FONT_DEFAULT;
|
if(font == NULL) font = &FONT_DEFAULT;
|
||||||
|
|
||||||
spritebatchsprite_t sprite;
|
|
||||||
shadermaterial_t material = {
|
shadermaterial_t material = {
|
||||||
.unlit = {
|
.unlit = {
|
||||||
.color = color,
|
.color = color,
|
||||||
@@ -73,31 +130,25 @@ errorret_t textDraw(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
spritebatchsprite_t sprites[32];
|
||||||
float_t posX = x;
|
float_t posX = x;
|
||||||
float_t posY = y;
|
float_t posY = y;
|
||||||
|
int32_t buffered = 0;
|
||||||
|
int32_t charIndex = 0;
|
||||||
|
do {
|
||||||
|
buffered = textBuffer(
|
||||||
|
x, y, text, font,
|
||||||
|
sprites,
|
||||||
|
sizeof(sprites) / sizeof(spritebatchsprite_t),
|
||||||
|
&charIndex, &posX, &posY
|
||||||
|
);
|
||||||
|
errorChain(spriteBatchBuffer(sprites, buffered, &SHADER_UNLIT, material));
|
||||||
|
} while(charIndex < length);
|
||||||
|
|
||||||
char_t c;
|
|
||||||
int32_t i = 0;
|
|
||||||
while((c = text[i++]) != '\0') {
|
|
||||||
if(c == '\n') {
|
|
||||||
posX = x;
|
|
||||||
posY += font->tileset->tileHeight;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(c == ' ') {
|
|
||||||
posX += font->tileset->tileWidth;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
sprite = textGetSprite((vec2){posX, posY}, c, font);
|
|
||||||
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
|
|
||||||
posX += font->tileset->tileWidth;
|
|
||||||
}
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
void textMeasure(
|
int32_t textMeasure(
|
||||||
const char_t *text,
|
const char_t *text,
|
||||||
const font_t *font,
|
const font_t *font,
|
||||||
int32_t *outWidth,
|
int32_t *outWidth,
|
||||||
@@ -110,6 +161,7 @@ void textMeasure(
|
|||||||
int32_t width = 0;
|
int32_t width = 0;
|
||||||
int32_t height = font->tileset->tileHeight;
|
int32_t height = font->tileset->tileHeight;
|
||||||
int32_t lineWidth = 0;
|
int32_t lineWidth = 0;
|
||||||
|
int32_t spriteCount = 0;
|
||||||
|
|
||||||
char_t c;
|
char_t c;
|
||||||
int32_t i = 0;
|
int32_t i = 0;
|
||||||
@@ -122,10 +174,50 @@ void textMeasure(
|
|||||||
}
|
}
|
||||||
|
|
||||||
lineWidth += font->tileset->tileWidth;
|
lineWidth += font->tileset->tileWidth;
|
||||||
|
|
||||||
|
if(c != ' ') {
|
||||||
|
spriteCount++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(lineWidth > width) width = lineWidth;
|
if(lineWidth > width) width = lineWidth;
|
||||||
|
|
||||||
*outWidth = width;
|
*outWidth = width;
|
||||||
*outHeight = height;
|
*outHeight = height;
|
||||||
|
|
||||||
|
return spriteCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
void textWrap(char_t *text, const font_t *font, const float_t maxWidth) {
|
||||||
|
assertNotNull(text, "Text cannot be NULL");
|
||||||
|
assertNotNull(font, "Font cannot be NULL");
|
||||||
|
|
||||||
|
float_t fontWidth = (float_t)font->tileset->tileWidth;
|
||||||
|
if(fontWidth <= 0.0f) return;
|
||||||
|
|
||||||
|
int32_t charsPerLine = (int32_t)(maxWidth / fontWidth);
|
||||||
|
if(charsPerLine <= 0) return;
|
||||||
|
|
||||||
|
int32_t lineWidth = 0;
|
||||||
|
int32_t lastSpace = -1;
|
||||||
|
|
||||||
|
for(int32_t i = 0; text[i] != '\0'; i++) {
|
||||||
|
if(text[i] == '\n') {
|
||||||
|
lineWidth = 0;
|
||||||
|
lastSpace = -1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(text[i] == ' ') {
|
||||||
|
lastSpace = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
lineWidth++;
|
||||||
|
|
||||||
|
if(lineWidth > charsPerLine && lastSpace != -1) {
|
||||||
|
text[lastSpace] = '\n';
|
||||||
|
lineWidth = i - lastSpace;
|
||||||
|
lastSpace = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -40,6 +40,37 @@ spritebatchsprite_t textGetSprite(
|
|||||||
const font_t *font
|
const font_t *font
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Buffers a string into sprites for rendering. If outSprites is NULL then
|
||||||
|
* the function will only return the count of sprites necessary for the buffer.
|
||||||
|
*
|
||||||
|
* posX and posY are updated whilst buffering characters, if you need to do
|
||||||
|
* buffering in sets then these will be reusable between buffer commands. Start
|
||||||
|
* by setting these to x and y initially.
|
||||||
|
*
|
||||||
|
* @param x The x-coordinate to start buffering the text at.
|
||||||
|
* @param y The y-coordinate to start buffering the text at.
|
||||||
|
* @param text The null-terminated string of text to buffer.
|
||||||
|
* @param font Font to use for rendering.
|
||||||
|
* @param outSprites Pointer to an array of spritebatchsprite_t.
|
||||||
|
* @param maxSprites The maximum number of sprites in outSprites.
|
||||||
|
* @param charIndex Pointer to an int32_t to store the character indexed.
|
||||||
|
* @param posX Pointer to a float_t to store the final x position.
|
||||||
|
* @param posY Pointer to a float_t to store the final y position.
|
||||||
|
* @return The count of sprites buffered.
|
||||||
|
*/
|
||||||
|
int32_t textBuffer(
|
||||||
|
const float_t x,
|
||||||
|
const float_t y,
|
||||||
|
const char_t *text,
|
||||||
|
font_t *font,
|
||||||
|
spritebatchsprite_t *outSprites,
|
||||||
|
const int32_t maxSprites,
|
||||||
|
int32_t *charIndex,
|
||||||
|
float_t *posX,
|
||||||
|
float_t *posY
|
||||||
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Draws a string of text at the specified position.
|
* Draws a string of text at the specified position.
|
||||||
*
|
*
|
||||||
@@ -65,10 +96,25 @@ errorret_t textDraw(
|
|||||||
* @param font Font to use for measurement.
|
* @param font Font to use for measurement.
|
||||||
* @param outWidth Pointer to store the measured width in pixels.
|
* @param outWidth Pointer to store the measured width in pixels.
|
||||||
* @param outHeight Pointer to store the measured height in pixels.
|
* @param outHeight Pointer to store the measured height in pixels.
|
||||||
|
* @return The count of sprites that will be rendered for the given text.
|
||||||
*/
|
*/
|
||||||
void textMeasure(
|
int32_t textMeasure(
|
||||||
const char_t *text,
|
const char_t *text,
|
||||||
const font_t *font,
|
const font_t *font,
|
||||||
int32_t *outWidth,
|
int32_t *outWidth,
|
||||||
int32_t *outHeight
|
int32_t *outHeight
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Word-wraps text in place for display at up to maxWidth pixels wide,
|
||||||
|
* by replacing the space nearest each overflow point with a newline.
|
||||||
|
* Length is unchanged - this only ever swaps existing spaces for
|
||||||
|
* newlines, never inserts characters - so it's always safe to call on a
|
||||||
|
* fixed-size buffer. A single word wider than maxWidth on its own is
|
||||||
|
* left unbroken.
|
||||||
|
*
|
||||||
|
* @param text Null-terminated, caller-owned buffer to wrap in place.
|
||||||
|
* @param font Font to measure character width with.
|
||||||
|
* @param maxWidth Maximum line width, in pixels.
|
||||||
|
*/
|
||||||
|
void textWrap(char_t *text, const font_t *font, const float_t maxWidth);
|
||||||
@@ -22,7 +22,8 @@
|
|||||||
#include "system/system.h"
|
#include "system/system.h"
|
||||||
#include "console/console.h"
|
#include "console/console.h"
|
||||||
#include "save/save.h"
|
#include "save/save.h"
|
||||||
#include "save/autosave.h"
|
#include "audio/audio.h"
|
||||||
|
#include "audio/mixer/audiomixer.h"
|
||||||
|
|
||||||
engine_t ENGINE;
|
engine_t ENGINE;
|
||||||
|
|
||||||
@@ -43,6 +44,7 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
|
|||||||
errorChain(saveInit());
|
errorChain(saveInit());
|
||||||
errorChain(localeManagerInit());
|
errorChain(localeManagerInit());
|
||||||
errorChain(displayInit());
|
errorChain(displayInit());
|
||||||
|
errorChain(audioInit());
|
||||||
errorChain(uiInit());
|
errorChain(uiInit());
|
||||||
errorChain(rpgInit());
|
errorChain(rpgInit());
|
||||||
#ifdef DUSK_NETWORK
|
#ifdef DUSK_NETWORK
|
||||||
@@ -69,10 +71,10 @@ errorret_t engineUpdate(void) {
|
|||||||
errorChain(networkUpdate());
|
errorChain(networkUpdate());
|
||||||
#endif
|
#endif
|
||||||
errorChain(saveUpdate());
|
errorChain(saveUpdate());
|
||||||
autoSaveUpdate();
|
|
||||||
timeUpdate();
|
timeUpdate();
|
||||||
inputUpdate();
|
inputUpdate();
|
||||||
consoleUpdate();
|
consoleUpdate();
|
||||||
|
errorChain(audioUpdateEarly());
|
||||||
errorChain(rpgUpdate());
|
errorChain(rpgUpdate());
|
||||||
errorChain(sceneUpdate());
|
errorChain(sceneUpdate());
|
||||||
errorChain(assetUpdate());
|
errorChain(assetUpdate());
|
||||||
@@ -80,6 +82,7 @@ errorret_t engineUpdate(void) {
|
|||||||
|
|
||||||
// Render
|
// Render
|
||||||
errorChain(displayUpdate());
|
errorChain(displayUpdate());
|
||||||
|
errorChain(audioUpdateLate());
|
||||||
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
|
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
@@ -96,6 +99,7 @@ errorret_t engineDispose(void) {
|
|||||||
errorChain(rpgDispose());
|
errorChain(rpgDispose());
|
||||||
localeManagerDispose();
|
localeManagerDispose();
|
||||||
errorChain(uiDispose());
|
errorChain(uiDispose());
|
||||||
|
errorChain(audioDispose());
|
||||||
consoleDispose();
|
consoleDispose();
|
||||||
errorChain(displayDispose());
|
errorChain(displayDispose());
|
||||||
errorChain(saveDispose());
|
errorChain(saveDispose());
|
||||||
|
|||||||
@@ -1,76 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "event.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
#include "util/memory.h"
|
|
||||||
|
|
||||||
void eventInit(
|
|
||||||
event_t *event,
|
|
||||||
eventcallback_t *callbacks,
|
|
||||||
void **users,
|
|
||||||
size_t size
|
|
||||||
) {
|
|
||||||
assertNotNull(event, "event must not be NULL");
|
|
||||||
assertNotNull((void *)callbacks, "callbacks must not be NULL");
|
|
||||||
assertTrue(size > 0, "size must be greater than 0");
|
|
||||||
|
|
||||||
event->callbacks = callbacks;
|
|
||||||
event->users = users;
|
|
||||||
event->size = size;
|
|
||||||
event->count = 0;
|
|
||||||
memoryZero(callbacks, sizeof(eventcallback_t) * size);
|
|
||||||
if(users) memoryZero(users, sizeof(void *) * size);
|
|
||||||
}
|
|
||||||
|
|
||||||
void eventSubscribe(event_t *event, eventcallback_t callback, void *user) {
|
|
||||||
assertNotNull(event, "event must not be NULL");
|
|
||||||
assertNotNull(callback, "callback must not be NULL");
|
|
||||||
|
|
||||||
// Ensure callback isn't already susbcribed
|
|
||||||
for(uint32_t i = 0; i < event->count; i++) {
|
|
||||||
if(event->callbacks[i] != callback) continue;
|
|
||||||
assertUnreachable("Callback already registered, cannot subscribe twice.");
|
|
||||||
}
|
|
||||||
|
|
||||||
assertTrue(event->count < event->size, "event subscriber capacity exceeded");
|
|
||||||
|
|
||||||
event->callbacks[event->count] = callback;
|
|
||||||
if(user) {
|
|
||||||
assertNotNull(event->users, "Cannot add user pointer.");
|
|
||||||
event->users[event->count] = user;
|
|
||||||
}
|
|
||||||
event->count++;
|
|
||||||
}
|
|
||||||
|
|
||||||
void eventUnsubscribe(event_t *event, eventcallback_t callback) {
|
|
||||||
assertNotNull(event, "event must not be NULL");
|
|
||||||
assertNotNull(callback, "callback must not be NULL");
|
|
||||||
|
|
||||||
for(uint32_t i = 0; i < event->count; i++) {
|
|
||||||
if(event->callbacks[i] != callback) continue;
|
|
||||||
|
|
||||||
uint32_t last = event->count - 1;
|
|
||||||
if(i != last) {
|
|
||||||
event->callbacks[i] = event->callbacks[last];
|
|
||||||
if(event->users) event->users[i] = event->users[last];
|
|
||||||
}
|
|
||||||
event->callbacks[last] = NULL;
|
|
||||||
if(event->users) event->users[last] = NULL;
|
|
||||||
event->count--;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void eventInvoke(const event_t *event, void *params) {
|
|
||||||
assertNotNull(event, "event must not be NULL");
|
|
||||||
|
|
||||||
for(uint32_t i = 0; i < event->count; i++) {
|
|
||||||
void *u = event->users ? event->users[i] : NULL;
|
|
||||||
event->callbacks[i](params, u);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include "dusk.h"
|
|
||||||
|
|
||||||
typedef void (*eventcallback_t)(void *params, void *user);
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
eventcallback_t *callbacks;
|
|
||||||
void **users;
|
|
||||||
size_t size;
|
|
||||||
uint32_t count;
|
|
||||||
} event_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes an event, binding it to the provided backing arrays and clearing
|
|
||||||
* all subscribers. May also be called to reset an event (re-clears subscribers
|
|
||||||
* without changing the backing arrays or size).
|
|
||||||
*
|
|
||||||
* @param event The event to initialize.
|
|
||||||
* @param callbacks Caller-owned array of at least `size` callback slots.
|
|
||||||
* @param users Array of user pointers, matching each callback, or NULL.
|
|
||||||
* @param size Capacity of both arrays, must match.
|
|
||||||
*/
|
|
||||||
void eventInit(
|
|
||||||
event_t *event,
|
|
||||||
eventcallback_t *callbacks,
|
|
||||||
void **users,
|
|
||||||
size_t size
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Subscribes a callback to an event. The callback is invoked with params and
|
|
||||||
* the provided user pointer each time the event fires. The same (callback,
|
|
||||||
* user) pair may only be subscribed once.
|
|
||||||
*
|
|
||||||
* @param event The event to subscribe to.
|
|
||||||
* @param callback The function to call when the event fires.
|
|
||||||
* @param user Arbitrary pointer forwarded to the callback unchanged.
|
|
||||||
*/
|
|
||||||
void eventSubscribe(event_t *event, eventcallback_t callback, void *user);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes a previously subscribed (callback, user) pair. Does nothing if the
|
|
||||||
* pair is not currently subscribed.
|
|
||||||
*
|
|
||||||
* @param event The event to unsubscribe from.
|
|
||||||
* @param callback The callback that was passed to eventSubscribe.
|
|
||||||
*/
|
|
||||||
void eventUnsubscribe(event_t *event, eventcallback_t callback);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invokes all subscribed callbacks, passing params and each subscriber's user
|
|
||||||
* pointer.
|
|
||||||
*
|
|
||||||
* @param event The event to invoke.
|
|
||||||
* @param params Arbitrary pointer forwarded to every callback unchanged.
|
|
||||||
*/
|
|
||||||
void eventInvoke(const event_t *event, void *params);
|
|
||||||
@@ -11,7 +11,6 @@
|
|||||||
#include "util/string.h"
|
#include "util/string.h"
|
||||||
#include "util/math.h"
|
#include "util/math.h"
|
||||||
#include "time/time.h"
|
#include "time/time.h"
|
||||||
#include "event/event.h"
|
|
||||||
|
|
||||||
input_t INPUT;
|
input_t INPUT;
|
||||||
|
|
||||||
@@ -153,7 +152,7 @@ float_t inputGetLastValue(const inputaction_t action) {
|
|||||||
const inputaction_t negY, const inputaction_t posY,
|
const inputaction_t negY, const inputaction_t posY,
|
||||||
vec2 result
|
vec2 result
|
||||||
) {
|
) {
|
||||||
assertNotNull(result, "Result vector cannot be null");
|
assertNotNull(result, "Result vector cannot be NULL");
|
||||||
result[0] = inputAxisDynamic(negX, posX);
|
result[0] = inputAxisDynamic(negX, posX);
|
||||||
result[1] = inputAxisDynamic(negY, posY);
|
result[1] = inputAxisDynamic(negY, posY);
|
||||||
}
|
}
|
||||||
@@ -163,7 +162,7 @@ float_t inputGetLastValue(const inputaction_t action) {
|
|||||||
const inputaction_t negY, const inputaction_t posY,
|
const inputaction_t negY, const inputaction_t posY,
|
||||||
vec2 result
|
vec2 result
|
||||||
) {
|
) {
|
||||||
assertNotNull(result, "Result vector cannot be null");
|
assertNotNull(result, "Result vector cannot be NULL");
|
||||||
float_t x = inputAxisDynamic(negX, posX);
|
float_t x = inputAxisDynamic(negX, posX);
|
||||||
float_t y = inputAxisDynamic(negY, posY);
|
float_t y = inputAxisDynamic(negY, posY);
|
||||||
float_t mag = sqrtf(x * x + y * y);
|
float_t mag = sqrtf(x * x + y * y);
|
||||||
@@ -209,7 +208,7 @@ void inputAxis2D(
|
|||||||
const inputaction_t negY, const inputaction_t posY,
|
const inputaction_t negY, const inputaction_t posY,
|
||||||
vec2 result
|
vec2 result
|
||||||
) {
|
) {
|
||||||
assertNotNull(result, "Result vector cannot be null");
|
assertNotNull(result, "Result vector cannot be NULL");
|
||||||
result[0] = inputAxis(negX, posX);
|
result[0] = inputAxis(negX, posX);
|
||||||
result[1] = inputAxis(negY, posY);
|
result[1] = inputAxis(negY, posY);
|
||||||
}
|
}
|
||||||
@@ -219,7 +218,7 @@ void inputAngle2D(
|
|||||||
const inputaction_t negY, const inputaction_t posY,
|
const inputaction_t negY, const inputaction_t posY,
|
||||||
vec2 result
|
vec2 result
|
||||||
) {
|
) {
|
||||||
assertNotNull(result, "Result vector cannot be null");
|
assertNotNull(result, "Result vector cannot be NULL");
|
||||||
float_t x = inputAxis(negX, posX);
|
float_t x = inputAxis(negX, posX);
|
||||||
float_t y = inputAxis(negY, posY);
|
float_t y = inputAxis(negY, posY);
|
||||||
float_t mag = sqrtf(x * x + y * y);
|
float_t mag = sqrtf(x * x + y * y);
|
||||||
|
|||||||
@@ -13,17 +13,31 @@ typedef struct {
|
|||||||
const char_t *file;
|
const char_t *file;
|
||||||
} localeinfo_t;
|
} localeinfo_t;
|
||||||
|
|
||||||
static const localeinfo_t LOCALE_EN_US = {
|
static const localeinfo_t LOCALE_INFO_EN_US = {
|
||||||
.name = "en-US",
|
.name = "en-US",
|
||||||
.file = "locale/en_US.po",
|
.file = "locale/en_US.po",
|
||||||
};
|
};
|
||||||
|
|
||||||
static const localeinfo_t LOCALE_JP_JP = {
|
static const localeinfo_t LOCALE_INFO_JP_JP = {
|
||||||
.name = "ja-JP",
|
.name = "ja-JP",
|
||||||
.file = "locale/jp_JP.po",
|
.file = "locale/jp_JP.po",
|
||||||
};
|
};
|
||||||
|
|
||||||
static const localeinfo_t LOCALE_ES_MX = {
|
static const localeinfo_t LOCALE_INFO_ES_MX = {
|
||||||
.name = "es-MX",
|
.name = "es-MX",
|
||||||
.file = "locale/es_MX.po",
|
.file = "locale/es_MX.po",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
static const localeinfo_t * const LOCALE_INFO_LIST[] = {
|
||||||
|
&LOCALE_INFO_EN_US,
|
||||||
|
&LOCALE_INFO_JP_JP,
|
||||||
|
&LOCALE_INFO_ES_MX
|
||||||
|
};
|
||||||
|
|
||||||
|
#define LOCALE_INFO_LIST_COUNT ( \
|
||||||
|
sizeof(LOCALE_INFO_LIST) / sizeof(LOCALE_INFO_LIST[0]) \
|
||||||
|
)
|
||||||
|
|
||||||
|
#define LOCALE_DEFAULT LOCALE_INFO_EN_US
|
||||||
|
|
||||||
|
// EOF
|
||||||
@@ -9,40 +9,23 @@
|
|||||||
#include "util/memory.h"
|
#include "util/memory.h"
|
||||||
#include "util/string.h"
|
#include "util/string.h"
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
#include "save/save.h"
|
#include "ui/ui.h"
|
||||||
|
#include "system/system.h"
|
||||||
|
#include "console/console.h"
|
||||||
|
|
||||||
localemanager_t LOCALE;
|
localemanager_t LOCALE;
|
||||||
|
|
||||||
const localeinfo_t * const LOCALE_LIST[LOCALE_LIST_COUNT] = {
|
|
||||||
&LOCALE_EN_US,
|
|
||||||
&LOCALE_JP_JP,
|
|
||||||
&LOCALE_ES_MX
|
|
||||||
};
|
|
||||||
|
|
||||||
errorret_t localeManagerInit() {
|
errorret_t localeManagerInit() {
|
||||||
memoryZero(&LOCALE, sizeof(localemanager_t));
|
memoryZero(&LOCALE, sizeof(localemanager_t));
|
||||||
// saveInit() runs before this (see engine.c) and, on most platforms,
|
|
||||||
// has already loaded a persisted language choice into savemeta_t by
|
// TODO: Set locale based on system locale.
|
||||||
// this point - see localeManagerGetByIndex().
|
const localeinfo_t *locale = systemGetLocale();
|
||||||
errorChain(localeManagerSetLocale(
|
errorChain(localeManagerSetLocale(locale));
|
||||||
localeManagerGetByIndex(saveGetMeta()->language)
|
consolePrint("Locale set to: %s", locale->name);
|
||||||
));
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
uint8_t localeManagerGetIndex(const localeinfo_t *locale) {
|
|
||||||
assertNotNull(locale, "Locale cannot be NULL");
|
|
||||||
for(uint8_t i = 0; i < LOCALE_LIST_COUNT; i++) {
|
|
||||||
if(stringCompare(LOCALE_LIST[i]->file, locale->file) == 0) return i;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
const localeinfo_t * localeManagerGetByIndex(const uint8_t index) {
|
|
||||||
if(index >= LOCALE_LIST_COUNT) return LOCALE_LIST[0];
|
|
||||||
return LOCALE_LIST[index];
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t localeManagerSetLocale(const localeinfo_t *locale) {
|
errorret_t localeManagerSetLocale(const localeinfo_t *locale) {
|
||||||
assertNotNull(locale, "Locale cannot be NULL");
|
assertNotNull(locale, "Locale cannot be NULL");
|
||||||
|
|
||||||
@@ -56,6 +39,9 @@ errorret_t localeManagerSetLocale(const localeinfo_t *locale) {
|
|||||||
assetEntryLock(LOCALE.entry);
|
assetEntryLock(LOCALE.entry);
|
||||||
errorChain(assetRequireLoaded(LOCALE.entry));
|
errorChain(assetRequireLoaded(LOCALE.entry));
|
||||||
|
|
||||||
|
// TODO : Trigger UI update.
|
||||||
|
errorChain(uiUpdateTranslations());
|
||||||
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "error/error.h"
|
#include "error/error.h"
|
||||||
#include "localemanager.h"
|
#include "locale/localemanager.h"
|
||||||
#include "locale/localeinfo.h"
|
#include "locale/localeinfo.h"
|
||||||
#include "asset/asset.h"
|
#include "asset/asset.h"
|
||||||
|
|
||||||
@@ -18,15 +18,6 @@ typedef struct {
|
|||||||
|
|
||||||
extern localemanager_t LOCALE;
|
extern localemanager_t LOCALE;
|
||||||
|
|
||||||
/**
|
|
||||||
* Every locale the game supports, in a fixed, stable order - index into
|
|
||||||
* this array is what gets persisted as savemeta_t.language (see
|
|
||||||
* save/savemeta.h), so the order here must never change once shipped
|
|
||||||
* (only append new locales at the end).
|
|
||||||
*/
|
|
||||||
#define LOCALE_LIST_COUNT 3
|
|
||||||
extern const localeinfo_t * const LOCALE_LIST[LOCALE_LIST_COUNT];
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize the locale system.
|
* Initialize the locale system.
|
||||||
*
|
*
|
||||||
@@ -43,34 +34,43 @@ errorret_t localeManagerInit();
|
|||||||
errorret_t localeManagerSetLocale(const localeinfo_t *locale);
|
errorret_t localeManagerSetLocale(const localeinfo_t *locale);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Finds the LOCALE_LIST index matching the given locale's file, by
|
* Get a localized string for the given message ID verbatim, with no
|
||||||
* content rather than pointer identity (localeinfo_t instances are
|
* printf-style formatting applied - use this (rather than
|
||||||
* declared `static const` in a header, so the same locale gets a
|
* localeManagerGetText with no variadic args) whenever the raw string
|
||||||
* distinct pointer in every translation unit that references it).
|
* is displayed as-is, or cached to be formatted later (e.g. a
|
||||||
*
|
* "_format" message ID whose %-specifiers are filled in by the caller
|
||||||
* @param locale The locale to find.
|
* itself via stringFormat once the actual values are known). Passing a
|
||||||
* @return The matching index in LOCALE_LIST, or 0 if not found.
|
* "_format" string through localeManagerGetText/GetTextArgs instead
|
||||||
*/
|
* would consume it immediately as a format string with zero args,
|
||||||
uint8_t localeManagerGetIndex(const localeinfo_t *locale);
|
* which is wrong for this use, and would also mishandle any literal
|
||||||
|
* '%' in a plain display string.
|
||||||
/**
|
|
||||||
* Gets the locale at the given LOCALE_LIST index, clamping to index 0
|
|
||||||
* (LOCALE_EN_US) if out of range - e.g. a save file's persisted language
|
|
||||||
* index from a future build with more locales than this one supports.
|
|
||||||
*
|
|
||||||
* @param index The index to look up.
|
|
||||||
* @return The locale at that index, or LOCALE_LIST[0] if out of range.
|
|
||||||
*/
|
|
||||||
const localeinfo_t * localeManagerGetByIndex(const uint8_t index);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get a localized string for the given message ID.
|
|
||||||
*
|
*
|
||||||
* @param id The message ID to retrieve.
|
* @param id The message ID to retrieve.
|
||||||
* @param buffer Buffer to write the retrieved string to.
|
* @param buffer Buffer to write the retrieved string to.
|
||||||
* @param bufferSize Size of the buffer.
|
* @param bufferSize Size of the buffer.
|
||||||
* @param plural Plural index to retrieve.
|
* @param plural Plural index to retrieve.
|
||||||
* @param ... Additional arguments for formatting the string.
|
* @return An error code if a failure occurs.
|
||||||
|
*/
|
||||||
|
#define localeManagerGetString(id, buffer, bufferSize, plural) \
|
||||||
|
assetLocaleGetString( \
|
||||||
|
&LOCALE.entry->data.locale, \
|
||||||
|
id, \
|
||||||
|
plural, \
|
||||||
|
buffer, \
|
||||||
|
bufferSize \
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a localized string for the given message ID, formatted
|
||||||
|
* printf-style with the given variadic arguments.
|
||||||
|
*
|
||||||
|
* @param id The message ID to retrieve.
|
||||||
|
* @param buffer Buffer to write the retrieved string to.
|
||||||
|
* @param bufferSize Size of the buffer.
|
||||||
|
* @param plural Plural index to retrieve.
|
||||||
|
* @param ... Arguments for formatting the string - must not be empty,
|
||||||
|
* since the retrieved string is always run through vsnprintf; see
|
||||||
|
* localeManagerGetString for a message ID with no format args at all.
|
||||||
* @return An error code if a failure occurs.
|
* @return An error code if a failure occurs.
|
||||||
*/
|
*/
|
||||||
#define localeManagerGetText(id, buffer, bufferSize, plural, ...) \
|
#define localeManagerGetText(id, buffer, bufferSize, plural, ...) \
|
||||||
|
|||||||
@@ -10,3 +10,6 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
|||||||
battlefighter.c
|
battlefighter.c
|
||||||
party.c
|
party.c
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Subdirs
|
||||||
|
add_subdirectory(testbattle)
|
||||||
@@ -214,7 +214,9 @@ void battleMoveTeamFirst(const battlefighterteam_t team) {
|
|||||||
sorted[count++] = BATTLE.executionOrder[i];
|
sorted[count++] = BATTLE.executionOrder[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
memoryCopy(BATTLE.executionOrder, sorted, sizeof(uint8_t) * BATTLE.executionCount);
|
memoryCopy(
|
||||||
|
BATTLE.executionOrder, sorted, sizeof(uint8_t) * BATTLE.executionCount
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
battlefighter_t *battleAIChooseTarget(const battlefighter_t *fighter) {
|
battlefighter_t *battleAIChooseTarget(const battlefighter_t *fighter) {
|
||||||
|
|||||||
@@ -82,6 +82,6 @@ void battleFighterInit(
|
|||||||
* is not dead).
|
* is not dead).
|
||||||
*
|
*
|
||||||
* @param fighter Pointer to the fighter to check.
|
* @param fighter Pointer to the fighter to check.
|
||||||
* @returns True if the fighter can act.
|
* @return True if the fighter can act.
|
||||||
*/
|
*/
|
||||||
bool_t battleFighterIsAlive(const battlefighter_t *fighter);
|
bool_t battleFighterIsAlive(const battlefighter_t *fighter);
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# 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
|
||||||
|
testbattle.c
|
||||||
|
)
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "testbattle.h"
|
||||||
|
#include "rpg/battle/battle.h"
|
||||||
|
#include "scene/scene.h"
|
||||||
|
|
||||||
|
void testBattleStart(void) {
|
||||||
|
battleInit();
|
||||||
|
|
||||||
|
const battlefighterstats_t allyOneStats =
|
||||||
|
{ .attack = 10, .defense = 5, .magic = 0, .speed = 10, .luck = 0 };
|
||||||
|
const battlefighterstats_t allyTwoStats =
|
||||||
|
{ .attack = 8, .defense = 4, .magic = 0, .speed = 8, .luck = 0 };
|
||||||
|
const battlefighterstats_t enemyOneStats =
|
||||||
|
{ .attack = 6, .defense = 3, .magic = 0, .speed = 6, .luck = 0 };
|
||||||
|
const battlefighterstats_t enemyTwoStats =
|
||||||
|
{ .attack = 7, .defense = 3, .magic = 0, .speed = 5, .luck = 0 };
|
||||||
|
|
||||||
|
battleAddFighter(
|
||||||
|
BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER,
|
||||||
|
allyOneStats, 30, 10
|
||||||
|
);
|
||||||
|
battleAddFighter(
|
||||||
|
BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER,
|
||||||
|
allyTwoStats, 25, 10
|
||||||
|
);
|
||||||
|
battleAddFighter(
|
||||||
|
BATTLE_FIGHTER_TEAM_ENEMY, BATTLE_FIGHTER_CONTROLLER_AI,
|
||||||
|
enemyOneStats, 20, 5
|
||||||
|
);
|
||||||
|
battleAddFighter(
|
||||||
|
BATTLE_FIGHTER_TEAM_ENEMY, BATTLE_FIGHTER_CONTROLLER_AI,
|
||||||
|
enemyTwoStats, 20, 5
|
||||||
|
);
|
||||||
|
|
||||||
|
battleStart(BATTLE_ENCOUNTER_REGULAR, true);
|
||||||
|
sceneSet(SCENE_TYPE_BATTLE);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "error/error.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TEMPORARY test hook: sets up a hardcoded mock battle and switches to the
|
||||||
|
* battle scene, so the battle scene (camera/fighters/HUD) can be seen and
|
||||||
|
* played without a real encounter trigger yet.
|
||||||
|
*/
|
||||||
|
void testBattleStart(void);
|
||||||
@@ -53,6 +53,36 @@ typedef struct cutscene_s {
|
|||||||
#define CUTSCENE_WAIT(WAIT) \
|
#define CUTSCENE_WAIT(WAIT) \
|
||||||
{ .type = CUTSCENE_ITEM_TYPE_WAIT, .wait = WAIT }
|
{ .type = CUTSCENE_ITEM_TYPE_WAIT, .wait = WAIT }
|
||||||
|
|
||||||
|
// A named, otherwise no-op position in the item list that cutsceneGoTo
|
||||||
|
// can jump execution straight to. NAME is matched with stringEquals,
|
||||||
|
// not pointer identity, so it's safe to use separate string literals
|
||||||
|
// with the same contents at the marker and at each call site.
|
||||||
|
#define CUTSCENE_MARKER(NAME) \
|
||||||
|
{ .type = CUTSCENE_ITEM_TYPE_MARKER, .marker = { .name = NAME } }
|
||||||
|
|
||||||
|
// Restarts the currently running cutscene from its first item,
|
||||||
|
// preserving whatever interact/interacted entities triggered it.
|
||||||
|
#define CUTSCENE_RESTART() \
|
||||||
|
{ .type = CUTSCENE_ITEM_TYPE_RESTART }
|
||||||
|
|
||||||
|
// Blocks the cutscene here indefinitely - it never completes on its own,
|
||||||
|
// only cutsceneGoTo (called externally, e.g. from a UI callback) can move
|
||||||
|
// execution past it.
|
||||||
|
#define CUTSCENE_IDLE() \
|
||||||
|
{ .type = CUTSCENE_ITEM_TYPE_IDLE }
|
||||||
|
|
||||||
|
// Opens a full-screen UI panel (e.g. the main menu) declaratively, then
|
||||||
|
// immediately continues on to whatever follows this item.
|
||||||
|
#define CUTSCENE_UI_SHOW(SCREEN) \
|
||||||
|
{ .type = CUTSCENE_ITEM_TYPE_UI_SHOW, .uiShow = { .screen = SCREEN } }
|
||||||
|
|
||||||
|
// Requests a switch to a different SCENE_TYPE via sceneSet, then
|
||||||
|
// immediately continues on to whatever follows this item - the switch
|
||||||
|
// itself doesn't happen until the next sceneUpdate() tick, so it does
|
||||||
|
// not take effect this frame.
|
||||||
|
#define CUTSCENE_SCENE(TYPE) \
|
||||||
|
{ .type = CUTSCENE_ITEM_TYPE_SCENE, .sceneChange = { .type = TYPE } }
|
||||||
|
|
||||||
#define CUTSCENE_CUTSCENE(CUTSCENE) \
|
#define CUTSCENE_CUTSCENE(CUTSCENE) \
|
||||||
{ \
|
{ \
|
||||||
.type = CUTSCENE_ITEM_TYPE_CUTSCENE, \
|
.type = CUTSCENE_ITEM_TYPE_CUTSCENE, \
|
||||||
@@ -62,6 +92,124 @@ typedef struct cutscene_s {
|
|||||||
#define CUTSCENE_CALLBACK(CALLBACK) \
|
#define CUTSCENE_CALLBACK(CALLBACK) \
|
||||||
{ .type = CUTSCENE_ITEM_TYPE_CALLBACK, .callback = CALLBACK }
|
{ .type = CUTSCENE_ITEM_TYPE_CALLBACK, .callback = CALLBACK }
|
||||||
|
|
||||||
|
#define CUTSCENE_PRINT(TEXT) \
|
||||||
|
{ .type = CUTSCENE_ITEM_TYPE_PRINT, .print = { .text = TEXT } }
|
||||||
|
|
||||||
|
// Shows a message-only modal (no option buttons) and immediately
|
||||||
|
// continues on to whatever follows this item - it does not wait for
|
||||||
|
// the dialog to be dismissed. Script the rest of the interaction (e.g.
|
||||||
|
// CUTSCENE_CALLBACK to kick off work, CUTSCENE_WAIT, then
|
||||||
|
// CUTSCENE_MODAL_CLOSE) as later items in the same cutscene.
|
||||||
|
// TITLE and MESSAGE are each displayed as-is unless they match a
|
||||||
|
// locale message ID, in which case the translated string is shown
|
||||||
|
// instead - see uiModalLocalize.
|
||||||
|
#define CUTSCENE_MODAL(TITLE, MESSAGE) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_MODAL, \
|
||||||
|
.modal = { .title = TITLE, .message = MESSAGE } \
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shows a modal with option buttons and immediately continues on, same
|
||||||
|
// as CUTSCENE_MODAL - it does not block waiting for a selection.
|
||||||
|
// Back/cancel input is disabled while it's open (see
|
||||||
|
// uiMenuSetDisableBack), so it must be dismissed by picking one; CALLBACK
|
||||||
|
// then fires with the selected option index once the dialog closes.
|
||||||
|
// Option labels are passed as trailing arguments, e.g.
|
||||||
|
// CUTSCENE_MODAL_OPTIONS(title, message, callback, "Retry", "Cancel") -
|
||||||
|
// their strings are not copied by this item, so they must stay valid
|
||||||
|
// until the modal opens (string literals are fine). Like TITLE and
|
||||||
|
// MESSAGE, each option is translated if it matches a locale message ID.
|
||||||
|
#define CUTSCENE_MODAL_OPTIONS(TITLE, MESSAGE, CALLBACK, ...) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_MODAL, \
|
||||||
|
.modal = { \
|
||||||
|
.title = TITLE, .message = MESSAGE, \
|
||||||
|
.options = (const char_t *[]){ __VA_ARGS__ }, \
|
||||||
|
.optionCount = (uint8_t)( \
|
||||||
|
sizeof((const char_t *[]){ __VA_ARGS__ }) / sizeof(const char_t *) \
|
||||||
|
), \
|
||||||
|
.callback = CALLBACK \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same as CUTSCENE_MODAL_OPTIONS, but fixed to exactly one option and
|
||||||
|
// MARKER1 to jump straight to via cutsceneGoTo once it's selected - no
|
||||||
|
// callback function to write. Does not fall through to whatever follows
|
||||||
|
// this item, so MARKER1 must be scripted elsewhere in the same cutscene.
|
||||||
|
#define CUTSCENE_MODAL_OPTIONS_ONE(TITLE, MESSAGE, OPTION1, MARKER1) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS, \
|
||||||
|
.modalOptionsMarkers = { \
|
||||||
|
.title = TITLE, .message = MESSAGE, \
|
||||||
|
.options = { OPTION1 }, \
|
||||||
|
.markers = { MARKER1 }, \
|
||||||
|
.optionCount = 1 \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same as CUTSCENE_MODAL_OPTIONS, but fixed to exactly two options,
|
||||||
|
// jumping straight to OPTION1_MARKER or OPTION2_MARKER via cutsceneGoTo
|
||||||
|
// once the corresponding option is selected - no callback function to
|
||||||
|
// write. Does not fall through to whatever follows this item, so both
|
||||||
|
// markers must be scripted elsewhere in the same cutscene.
|
||||||
|
#define CUTSCENE_MODAL_OPTIONS_TWO( \
|
||||||
|
TITLE, MESSAGE, OPTION1, OPTION1_MARKER, OPTION2, OPTION2_MARKER \
|
||||||
|
) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS, \
|
||||||
|
.modalOptionsMarkers = { \
|
||||||
|
.title = TITLE, .message = MESSAGE, \
|
||||||
|
.options = { OPTION1, OPTION2 }, \
|
||||||
|
.markers = { OPTION1_MARKER, OPTION2_MARKER }, \
|
||||||
|
.optionCount = 2 \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
// Closes the currently open modal (if any). Useful when a modal was
|
||||||
|
// opened outside of a blocking CUTSCENE_MODAL item (e.g. directly via
|
||||||
|
// uiModalOpen) and this cutscene just needs to dismiss it and continue
|
||||||
|
// on to whatever follows this item in the sequence.
|
||||||
|
#define CUTSCENE_MODAL_CLOSE() \
|
||||||
|
{ .type = CUTSCENE_ITEM_TYPE_MODAL_CLOSE }
|
||||||
|
|
||||||
|
// Opens the on-screen keyboard and blocks the cutscene until it closes,
|
||||||
|
// then caches whatever was typed - see cutsceneSystemGetTextCache to
|
||||||
|
// read it back afterwards. __VA_ARGS__ are uikeyboardopen_t designated
|
||||||
|
// initializers, e.g. CUTSCENE_KEYBOARD(.cancel = true, .maxLength = 8).
|
||||||
|
#define CUTSCENE_KEYBOARD(...) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_KEYBOARD, \
|
||||||
|
.keyboard = { .open = { __VA_ARGS__ } } \
|
||||||
|
}
|
||||||
|
|
||||||
|
// (Re)requests an available save device and jumps straight to
|
||||||
|
// SUCCESS_MARKER or FAILURE_MARKER once it resolves, same as a
|
||||||
|
// CUTSCENE_MODAL_OPTIONS callback - it does not fall through to
|
||||||
|
// whatever follows this item, so both markers must be scripted
|
||||||
|
// elsewhere in the same cutscene.
|
||||||
|
#define CUTSCENE_SAVE_DEVICE_CHECK(SUCCESS_MARKER, FAILURE_MARKER) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK, \
|
||||||
|
.saveDeviceCheck = { \
|
||||||
|
.successMarker = SUCCESS_MARKER, \
|
||||||
|
.failureMarker = FAILURE_MARKER \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
// (Re)loads every save slot via saveLoadAllSlots() and jumps straight to
|
||||||
|
// SUCCESS_MARKER or FAILURE_MARKER once it resolves, same shape as
|
||||||
|
// CUTSCENE_SAVE_DEVICE_CHECK - it does not fall through to whatever
|
||||||
|
// follows this item, so both markers must be scripted elsewhere in the
|
||||||
|
// same cutscene.
|
||||||
|
#define CUTSCENE_SAVE_LOAD_ALL_SLOTS(SUCCESS_MARKER, FAILURE_MARKER) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS, \
|
||||||
|
.saveLoadAllSlots = { \
|
||||||
|
.successMarker = SUCCESS_MARKER, \
|
||||||
|
.failureMarker = FAILURE_MARKER \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
#define CUTSCENE_ENTITY_WALK_TO(ENTITY_INDEX, X, Y, Z) \
|
#define CUTSCENE_ENTITY_WALK_TO(ENTITY_INDEX, X, Y, Z) \
|
||||||
{ \
|
{ \
|
||||||
.type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO, \
|
.type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO, \
|
||||||
@@ -252,3 +400,114 @@ typedef struct cutscene_s {
|
|||||||
), \
|
), \
|
||||||
CUTSCENE_MAP_AREA_WAIT(CUTSCENE_AREA_LAST_CREATED), \
|
CUTSCENE_MAP_AREA_WAIT(CUTSCENE_AREA_LAST_CREATED), \
|
||||||
CUTSCENE_MAP_AREA_REMOVE(CUTSCENE_AREA_LAST_CREATED)
|
CUTSCENE_MAP_AREA_REMOVE(CUTSCENE_AREA_LAST_CREATED)
|
||||||
|
|
||||||
|
// Longhand - every audioMixerQueuePlay() parameter. See
|
||||||
|
// CUTSCENE_AUDIO_PLAY_SIMPLE/CUTSCENE_AUDIO_PLAY_LOOPED below for the
|
||||||
|
// shorthands.
|
||||||
|
#define CUTSCENE_AUDIO_PLAY( \
|
||||||
|
FILE, CHANNEL, VOLUME, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
|
||||||
|
) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_AUDIO_PLAY, \
|
||||||
|
.audioPlay = { \
|
||||||
|
.file = FILE, \
|
||||||
|
.channel = CHANNEL, \
|
||||||
|
.volume = VOLUME, \
|
||||||
|
.pan = PAN, \
|
||||||
|
.looping = LOOPING, \
|
||||||
|
.loopCount = LOOP_COUNT, \
|
||||||
|
.loopStart = LOOP_START, \
|
||||||
|
.loopTo = LOOP_TO \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shorthand: play FILE on CHANNEL once, full volume, centered (0.0f, same
|
||||||
|
// as AUDIO_STREAM_CENTER), no loop.
|
||||||
|
#define CUTSCENE_AUDIO_PLAY_SIMPLE(FILE, CHANNEL) \
|
||||||
|
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, false, 0, -1.0f, 0.0f)
|
||||||
|
|
||||||
|
// Shorthand: play FILE on CHANNEL looping the whole clip forever, full
|
||||||
|
// volume, centered (0.0f, same as AUDIO_STREAM_CENTER).
|
||||||
|
#define CUTSCENE_AUDIO_PLAY_LOOPED(FILE, CHANNEL) \
|
||||||
|
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, true, 0, -1.0f, 0.0f)
|
||||||
|
|
||||||
|
#define CUTSCENE_AUDIO_STOP(CHANNEL) \
|
||||||
|
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_STOP, .audioStopChannel = CHANNEL }
|
||||||
|
|
||||||
|
#define CUTSCENE_AUDIO_PAUSE(CHANNEL) \
|
||||||
|
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_PAUSE, .audioPauseChannel = CHANNEL }
|
||||||
|
|
||||||
|
#define CUTSCENE_AUDIO_RESUME(CHANNEL) \
|
||||||
|
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_RESUME, .audioResumeChannel = CHANNEL }
|
||||||
|
|
||||||
|
// Longhand - starts CHANNEL fading from FROM to TO over DURATION seconds,
|
||||||
|
// eased by EASING. Doesn't wait for it - pair with
|
||||||
|
// CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) to block until it finishes. See
|
||||||
|
// CUTSCENE_AUDIO_FADE_OUT/CUTSCENE_AUDIO_FADE_IN below for the shorthands;
|
||||||
|
// use this directly for a custom range, e.g.
|
||||||
|
// CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.3f, 5.0f, EASING_LINEAR) to fade
|
||||||
|
// down to "playing quietly" rather than silent.
|
||||||
|
#define CUTSCENE_AUDIO_FADE(CHANNEL, FROM, TO, DURATION, EASING) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_AUDIO_FADE, \
|
||||||
|
.audioFade = { \
|
||||||
|
.channel = CHANNEL, \
|
||||||
|
.from = FROM, \
|
||||||
|
.to = TO, \
|
||||||
|
.duration = DURATION, \
|
||||||
|
.easing = EASING \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shorthand: fade CHANNEL from full volume to silent over DURATION seconds.
|
||||||
|
#define CUTSCENE_AUDIO_FADE_OUT(CHANNEL, DURATION) \
|
||||||
|
CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.0f, DURATION, EASING_LINEAR)
|
||||||
|
|
||||||
|
// Shorthand: fade CHANNEL from silent to full volume over DURATION seconds.
|
||||||
|
#define CUTSCENE_AUDIO_FADE_IN(CHANNEL, DURATION) \
|
||||||
|
CUTSCENE_AUDIO_FADE(CHANNEL, 0.0f, 1.0f, DURATION, EASING_LINEAR)
|
||||||
|
|
||||||
|
// Waits until CHANNEL's fade (started elsewhere by CUTSCENE_AUDIO_FADE)
|
||||||
|
// has finished - a no-op wait if CHANNEL isn't fading.
|
||||||
|
#define CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_AUDIO_FADE_WAIT, \
|
||||||
|
.audioFadeWaitChannel = CHANNEL \
|
||||||
|
}
|
||||||
|
|
||||||
|
#define CUTSCENE_AUDIO_SET_PAN(CHANNEL, PAN) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN, \
|
||||||
|
.audioSetPan = { .channel = CHANNEL, .pan = PAN } \
|
||||||
|
}
|
||||||
|
|
||||||
|
#define CUTSCENE_AUDIO_SET_LOOP( \
|
||||||
|
CHANNEL, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
|
||||||
|
) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP, \
|
||||||
|
.audioSetLoop = { \
|
||||||
|
.channel = CHANNEL, \
|
||||||
|
.looping = LOOPING, \
|
||||||
|
.loopCount = LOOP_COUNT, \
|
||||||
|
.loopStart = LOOP_START, \
|
||||||
|
.loopTo = LOOP_TO \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
// Combined form of CUTSCENE_AUDIO_SET_PAN + CUTSCENE_AUDIO_SET_LOOP, for
|
||||||
|
// setting both at once rather than as two separate items.
|
||||||
|
#define CUTSCENE_AUDIO_SET( \
|
||||||
|
CHANNEL, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
|
||||||
|
) \
|
||||||
|
{ \
|
||||||
|
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET, \
|
||||||
|
.audioSet = { \
|
||||||
|
.channel = CHANNEL, \
|
||||||
|
.pan = PAN, \
|
||||||
|
.looping = LOOPING, \
|
||||||
|
.loopCount = LOOP_COUNT, \
|
||||||
|
.loopStart = LOOP_START, \
|
||||||
|
.loopTo = LOOP_TO \
|
||||||
|
} \
|
||||||
|
}
|
||||||
@@ -8,7 +8,10 @@
|
|||||||
#include "cutscenesystem.h"
|
#include "cutscenesystem.h"
|
||||||
#include "rpg/entity/entity.h"
|
#include "rpg/entity/entity.h"
|
||||||
#include "util/memory.h"
|
#include "util/memory.h"
|
||||||
|
#include "util/string.h"
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
|
#include "asset/asset.h"
|
||||||
|
#include "ui/overlay/uifatalerror.h"
|
||||||
|
|
||||||
cutscenesystem_t CUTSCENE_SYSTEM;
|
cutscenesystem_t CUTSCENE_SYSTEM;
|
||||||
|
|
||||||
@@ -16,11 +19,7 @@ void cutsceneSystemInit() {
|
|||||||
memoryZero(&CUTSCENE_SYSTEM, sizeof(cutscenesystem_t));
|
memoryZero(&CUTSCENE_SYSTEM, sizeof(cutscenesystem_t));
|
||||||
}
|
}
|
||||||
|
|
||||||
void cutsceneSystemStartCutscene(const cutscene_t *cutscene) {
|
void cutsceneSystemPrepare(
|
||||||
cutsceneSystemStartCutsceneWith(cutscene, NULL, NULL);
|
|
||||||
}
|
|
||||||
|
|
||||||
void cutsceneSystemStartCutsceneWith(
|
|
||||||
const cutscene_t *cutscene,
|
const cutscene_t *cutscene,
|
||||||
entity_t *interact,
|
entity_t *interact,
|
||||||
entity_t *interacted
|
entity_t *interacted
|
||||||
@@ -38,10 +37,64 @@ void cutsceneSystemStartCutsceneWith(
|
|||||||
CUTSCENE_SYSTEM.entityLastRef = NULL;
|
CUTSCENE_SYSTEM.entityLastRef = NULL;
|
||||||
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_LAST_CREATED;
|
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_LAST_CREATED;
|
||||||
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
|
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
|
||||||
|
CUTSCENE_SYSTEM.textCache[0] = '\0';
|
||||||
CUTSCENE_SYSTEM.currentItem = 0xFF;// Set to 0xFF so Next wraps to 0.
|
CUTSCENE_SYSTEM.currentItem = 0xFF;// Set to 0xFF so Next wraps to 0.
|
||||||
|
CUTSCENE_SYSTEM.onComplete = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
void cutsceneSystemStartCutscene(const cutscene_t *cutscene) {
|
||||||
|
cutsceneSystemStartCutsceneWith(cutscene, NULL, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
void cutsceneSystemStartCutsceneWith(
|
||||||
|
const cutscene_t *cutscene,
|
||||||
|
entity_t *interact,
|
||||||
|
entity_t *interacted
|
||||||
|
) {
|
||||||
|
cutsceneSystemPrepare(cutscene, interact, interacted);
|
||||||
cutsceneSystemNext();
|
cutsceneSystemNext();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void cutsceneSystemStartCutsceneAndGoToMarker(
|
||||||
|
const cutscene_t *cutscene,
|
||||||
|
const char_t *marker
|
||||||
|
) {
|
||||||
|
cutsceneSystemPrepare(cutscene, NULL, NULL);
|
||||||
|
cutsceneGoTo(marker);
|
||||||
|
}
|
||||||
|
|
||||||
|
void cutsceneSystemLoad(const char_t *file) {
|
||||||
|
char_t path[ASSET_FILE_NAME_MAX];
|
||||||
|
stringFormat(path, sizeof(path), "cutscenes/%s", file);
|
||||||
|
|
||||||
|
assetentry_t *entry = assetLock(path, ASSET_LOADER_TYPE_CUTSCENE, NULL);
|
||||||
|
errorret_t result = assetRequireLoaded(entry);
|
||||||
|
if(errorIsNotOk(result)) {
|
||||||
|
errorCatch(errorPrint(result));
|
||||||
|
uiFatalErrorOpen(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
cutsceneSystemStartCutscene(&entry->data.cutscene.cutscene);
|
||||||
|
}
|
||||||
|
|
||||||
|
void cutsceneRestart(void) {
|
||||||
|
assertNotNull(
|
||||||
|
CUTSCENE_SYSTEM.scene, "cutsceneRestart called with no cutscene running"
|
||||||
|
);
|
||||||
|
|
||||||
|
// A restart is the same logical run trying again (e.g. retrying a failed
|
||||||
|
// save-device check), not a fresh unrelated start, so it should not
|
||||||
|
// silently drop a completion callback the caller already armed.
|
||||||
|
cutscenecallback_t onComplete = CUTSCENE_SYSTEM.onComplete;
|
||||||
|
cutsceneSystemStartCutsceneWith(
|
||||||
|
CUTSCENE_SYSTEM.scene,
|
||||||
|
CUTSCENE_SYSTEM.entityInteract,
|
||||||
|
CUTSCENE_SYSTEM.entityInteracted
|
||||||
|
);
|
||||||
|
CUTSCENE_SYSTEM.onComplete = onComplete;
|
||||||
|
}
|
||||||
|
|
||||||
void cutsceneSystemUpdate() {
|
void cutsceneSystemUpdate() {
|
||||||
if(CUTSCENE_SYSTEM.scene == NULL) return;
|
if(CUTSCENE_SYSTEM.scene == NULL) return;
|
||||||
|
|
||||||
@@ -58,6 +111,13 @@ void cutsceneSystemNext() {
|
|||||||
if(
|
if(
|
||||||
CUTSCENE_SYSTEM.currentItem >= CUTSCENE_SYSTEM.scene->itemCount
|
CUTSCENE_SYSTEM.currentItem >= CUTSCENE_SYSTEM.scene->itemCount
|
||||||
) {
|
) {
|
||||||
|
// Saved and cleared before firing so a callback that immediately
|
||||||
|
// starts another cutscene (or sets its own onComplete) isn't clobbered
|
||||||
|
// by this function's own cleanup running after it - same reentrancy
|
||||||
|
// hazard as uiFocusPop, see src/dusk/ui/focus/uifocus.c.
|
||||||
|
cutscenecallback_t onComplete = CUTSCENE_SYSTEM.onComplete;
|
||||||
|
void *userData = CUTSCENE_SYSTEM.userData;
|
||||||
|
|
||||||
CUTSCENE_SYSTEM.scene = NULL;
|
CUTSCENE_SYSTEM.scene = NULL;
|
||||||
CUTSCENE_SYSTEM.currentItem = 0xFF;
|
CUTSCENE_SYSTEM.currentItem = 0xFF;
|
||||||
CUTSCENE_SYSTEM.pause = CUTSCENE_PAUSE_NONE;
|
CUTSCENE_SYSTEM.pause = CUTSCENE_PAUSE_NONE;
|
||||||
@@ -66,16 +126,49 @@ void cutsceneSystemNext() {
|
|||||||
CUTSCENE_SYSTEM.entityLastCreated = NULL;
|
CUTSCENE_SYSTEM.entityLastCreated = NULL;
|
||||||
CUTSCENE_SYSTEM.entityLastRef = NULL;
|
CUTSCENE_SYSTEM.entityLastRef = NULL;
|
||||||
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_LAST_CREATED;
|
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_LAST_CREATED;
|
||||||
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
|
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
|
||||||
|
CUTSCENE_SYSTEM.textCache[0] = '\0';
|
||||||
|
CUTSCENE_SYSTEM.onComplete = NULL;
|
||||||
|
|
||||||
|
if(onComplete != NULL) onComplete(userData);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start item.
|
// Start item.
|
||||||
const cutsceneitem_t *item = cutsceneSystemGetCurrentItem();
|
const cutsceneitem_t *item = cutsceneSystemGetCurrentItem();
|
||||||
memset(&CUTSCENE_SYSTEM.data, 0, sizeof(CUTSCENE_SYSTEM.data));
|
memoryZero(&CUTSCENE_SYSTEM.data, sizeof(CUTSCENE_SYSTEM.data));
|
||||||
cutsceneItemStart(item, &CUTSCENE_SYSTEM.data);
|
cutsceneItemStart(item, &CUTSCENE_SYSTEM.data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void cutsceneSystemSetOnComplete(cutscenecallback_t onComplete) {
|
||||||
|
assertNotNull(
|
||||||
|
CUTSCENE_SYSTEM.scene,
|
||||||
|
"cutsceneSystemSetOnComplete called with no cutscene running"
|
||||||
|
);
|
||||||
|
CUTSCENE_SYSTEM.onComplete = onComplete;
|
||||||
|
}
|
||||||
|
|
||||||
|
void cutsceneGoTo(const char_t *name) {
|
||||||
|
assertNotNull(
|
||||||
|
CUTSCENE_SYSTEM.scene, "cutsceneGoTo called with no cutscene running"
|
||||||
|
);
|
||||||
|
|
||||||
|
for(uint8_t i = 0; i < CUTSCENE_SYSTEM.scene->itemCount; i++) {
|
||||||
|
const cutsceneitem_t *item = &CUTSCENE_SYSTEM.scene->items[i];
|
||||||
|
if(
|
||||||
|
item->type == CUTSCENE_ITEM_TYPE_MARKER &&
|
||||||
|
stringEquals(item->marker.name, name)
|
||||||
|
) {
|
||||||
|
CUTSCENE_SYSTEM.currentItem = i;
|
||||||
|
memoryZero(&CUTSCENE_SYSTEM.data, sizeof(CUTSCENE_SYSTEM.data));
|
||||||
|
cutsceneItemStart(item, &CUTSCENE_SYSTEM.data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(false, "cutsceneGoTo: no marker found with that name");
|
||||||
|
}
|
||||||
|
|
||||||
const cutsceneitem_t * cutsceneSystemGetCurrentItem() {
|
const cutsceneitem_t * cutsceneSystemGetCurrentItem() {
|
||||||
if(CUTSCENE_SYSTEM.scene == NULL) return NULL;
|
if(CUTSCENE_SYSTEM.scene == NULL) return NULL;
|
||||||
|
|
||||||
@@ -144,6 +237,16 @@ uint8_t cutsceneSystemGetTextMiniId(const uint8_t index) {
|
|||||||
return index;
|
return index;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const char_t * cutsceneSystemGetTextCache(void) {
|
||||||
|
return CUTSCENE_SYSTEM.textCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
void cutsceneSystemSetTextCache(const char_t *text) {
|
||||||
|
stringCopy(
|
||||||
|
CUTSCENE_SYSTEM.textCache, text, CUTSCENE_TEXT_CACHE_MAX - 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
void cutsceneSystemDispose() {
|
void cutsceneSystemDispose() {
|
||||||
CUTSCENE_SYSTEM.scene = NULL;
|
CUTSCENE_SYSTEM.scene = NULL;
|
||||||
CUTSCENE_SYSTEM.currentItem = 0xFF;
|
CUTSCENE_SYSTEM.currentItem = 0xFF;
|
||||||
@@ -154,4 +257,6 @@ void cutsceneSystemDispose() {
|
|||||||
CUTSCENE_SYSTEM.entityLastRef = NULL;
|
CUTSCENE_SYSTEM.entityLastRef = NULL;
|
||||||
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_LAST_CREATED;
|
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_LAST_CREATED;
|
||||||
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
|
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
|
||||||
|
CUTSCENE_SYSTEM.textCache[0] = '\0';
|
||||||
|
CUTSCENE_SYSTEM.onComplete = NULL;
|
||||||
}
|
}
|
||||||
@@ -21,6 +21,11 @@ typedef struct entity_s entity_t;
|
|||||||
// cutscene_t.dataSize.
|
// cutscene_t.dataSize.
|
||||||
#define CUTSCENE_SYSTEM_SIZE_MAX 8192
|
#define CUTSCENE_SYSTEM_SIZE_MAX 8192
|
||||||
|
|
||||||
|
// Size of CUTSCENE_SYSTEM.textCache - keep >= UI_KEYBOARD_TEXT_MAX (see
|
||||||
|
// ui/dialog/keyboard/uikeyboard.h) so text entered via a
|
||||||
|
// CUTSCENE_ITEM_TYPE_KEYBOARD item is never truncated caching it here.
|
||||||
|
#define CUTSCENE_TEXT_CACHE_MAX 64
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
const cutscene_t *scene;
|
const cutscene_t *scene;
|
||||||
uint8_t currentItem;
|
uint8_t currentItem;
|
||||||
@@ -32,12 +37,21 @@ typedef struct {
|
|||||||
uint8_t areaLastCreated;
|
uint8_t areaLastCreated;
|
||||||
uint8_t textMiniLastCreated;
|
uint8_t textMiniLastCreated;
|
||||||
|
|
||||||
|
// Free-form text cache, e.g. holding whatever was last typed via a
|
||||||
|
// CUTSCENE_ITEM_TYPE_KEYBOARD item - see cutsceneSystemGetTextCache/
|
||||||
|
// cutsceneSystemSetTextCache. Not tied to any one item type; any item
|
||||||
|
// may read or write it.
|
||||||
|
char_t textCache[CUTSCENE_TEXT_CACHE_MAX];
|
||||||
|
|
||||||
// Data (used by the current item).
|
// Data (used by the current item).
|
||||||
cutsceneitemdata_t data;
|
cutsceneitemdata_t data;
|
||||||
|
|
||||||
// Custom user data for the running cutscene, sized per-scene by
|
// Custom user data for the running cutscene, sized per-scene by
|
||||||
// cutscene_t.dataSize.
|
// cutscene_t.dataSize.
|
||||||
uint8_t userData[CUTSCENE_SYSTEM_SIZE_MAX];
|
uint8_t userData[CUTSCENE_SYSTEM_SIZE_MAX];
|
||||||
|
|
||||||
|
// See cutsceneSystemSetOnComplete.
|
||||||
|
cutscenecallback_t onComplete;
|
||||||
} cutscenesystem_t;
|
} cutscenesystem_t;
|
||||||
|
|
||||||
extern cutscenesystem_t CUTSCENE_SYSTEM;
|
extern cutscenesystem_t CUTSCENE_SYSTEM;
|
||||||
@@ -67,6 +81,63 @@ void cutsceneSystemStartCutsceneWith(
|
|||||||
entity_t *interacted
|
entity_t *interacted
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts a cutscene with no bound entities, jumping straight to the
|
||||||
|
* CUTSCENE_MARKER item with the given name instead of running from the
|
||||||
|
* first item - as if cutsceneGoTo(marker) had been called immediately
|
||||||
|
* after cutsceneSystemStartCutscene. Asserts if no marker with that
|
||||||
|
* name exists in the cutscene.
|
||||||
|
*
|
||||||
|
* @param cutscene Pointer to the cutscene to start.
|
||||||
|
* @param marker Marker name to jump to, matched with stringEquals.
|
||||||
|
*/
|
||||||
|
void cutsceneSystemStartCutsceneAndGoToMarker(
|
||||||
|
const cutscene_t *cutscene,
|
||||||
|
const char_t *marker
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Locks, loads and immediately starts a cutscene asset by file name,
|
||||||
|
* e.g. cutsceneSystemLoad("main_menu.jsonc") loads and starts
|
||||||
|
* assets/cutscenes/main_menu.jsonc - same lock/assetRequireLoaded/start
|
||||||
|
* sequence as sceneInitialInit's INITIAL_CUTSCENE_ENTRY. The entry is
|
||||||
|
* locked forever (never unlocked), same lifetime convention as
|
||||||
|
* LOCALE.entry - it's fine to call this again later for the same file,
|
||||||
|
* it'll just resolve to the same already-loaded entry. Opens the fatal
|
||||||
|
* error overlay (see uiFatalErrorOpen) instead of starting anything if
|
||||||
|
* the asset fails to load.
|
||||||
|
*
|
||||||
|
* @param file Cutscene file name (with .jsonc extension), relative to
|
||||||
|
* assets/cutscenes/.
|
||||||
|
*/
|
||||||
|
void cutsceneSystemLoad(const char_t *file);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restarts the currently running cutscene from its first item,
|
||||||
|
* preserving whatever interact/interacted entities triggered it.
|
||||||
|
* Asserts if no cutscene is running.
|
||||||
|
*/
|
||||||
|
void cutsceneRestart(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets a native callback to fire once when the currently running cutscene
|
||||||
|
* finishes by running off the end of its item list. A fresh
|
||||||
|
* cutsceneSystemStartCutscene* call clears any previously set callback, so
|
||||||
|
* call this again after starting a new cutscene to arm it - but
|
||||||
|
* cutsceneRestart() preserves whatever was armed, since a restart (e.g.
|
||||||
|
* retrying a failed check) is the same logical run trying again, not a new
|
||||||
|
* one. Invoked with CUTSCENE_SYSTEM.userData, same as CUTSCENE_CALLBACK.
|
||||||
|
*
|
||||||
|
* Exists so a runtime-loaded cutscene file (which can't store a native
|
||||||
|
* function pointer) can still hand off to native code once it's done,
|
||||||
|
* without needing a whole name->function registry: the file just ends
|
||||||
|
* normally, and whoever started it supplies what happens next.
|
||||||
|
*
|
||||||
|
* @param onComplete Callback to fire on natural completion. May be NULL
|
||||||
|
* to clear a previously set one.
|
||||||
|
*/
|
||||||
|
void cutsceneSystemSetOnComplete(cutscenecallback_t onComplete);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolves a raw entity index (or sentinel) to an entity pointer.
|
* Resolves a raw entity index (or sentinel) to an entity pointer.
|
||||||
* Handles CUTSCENE_ENTITY_INTERACT, CUTSCENE_ENTITY_INTERACTED,
|
* Handles CUTSCENE_ENTITY_INTERACT, CUTSCENE_ENTITY_INTERACTED,
|
||||||
@@ -75,7 +146,7 @@ void cutsceneSystemStartCutsceneWith(
|
|||||||
* Asserts the resolved entity is within bounds.
|
* Asserts the resolved entity is within bounds.
|
||||||
*
|
*
|
||||||
* @param entityIndex Raw entity index or sentinel value.
|
* @param entityIndex Raw entity index or sentinel value.
|
||||||
* @returns Pointer to the resolved entity.
|
* @return Pointer to the resolved entity.
|
||||||
*/
|
*/
|
||||||
entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex);
|
entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex);
|
||||||
|
|
||||||
@@ -84,7 +155,7 @@ entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex);
|
|||||||
* a concrete map area ID.
|
* a concrete map area ID.
|
||||||
*
|
*
|
||||||
* @param areaId Raw map area ID or sentinel value.
|
* @param areaId Raw map area ID or sentinel value.
|
||||||
* @returns The resolved map area ID.
|
* @return The resolved map area ID.
|
||||||
*/
|
*/
|
||||||
uint8_t cutsceneSystemGetAreaId(const uint8_t areaId);
|
uint8_t cutsceneSystemGetAreaId(const uint8_t areaId);
|
||||||
|
|
||||||
@@ -93,15 +164,48 @@ uint8_t cutsceneSystemGetAreaId(const uint8_t areaId);
|
|||||||
* sentinel) to a concrete UI_TEXTBOX_MINI_LIST slot index.
|
* sentinel) to a concrete UI_TEXTBOX_MINI_LIST slot index.
|
||||||
*
|
*
|
||||||
* @param index Raw slot index or sentinel value.
|
* @param index Raw slot index or sentinel value.
|
||||||
* @returns The resolved slot index.
|
* @return The resolved slot index.
|
||||||
*/
|
*/
|
||||||
uint8_t cutsceneSystemGetTextMiniId(const uint8_t index);
|
uint8_t cutsceneSystemGetTextMiniId(const uint8_t index);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns CUTSCENE_SYSTEM.textCache - whatever was last written there via
|
||||||
|
* cutsceneSystemSetTextCache (e.g. by a CUTSCENE_ITEM_TYPE_KEYBOARD item
|
||||||
|
* once its keyboard closes). Empty ("") if nothing has been cached yet
|
||||||
|
* for the running cutscene.
|
||||||
|
*
|
||||||
|
* @return The cached text.
|
||||||
|
*/
|
||||||
|
const char_t * cutsceneSystemGetTextCache(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Overwrites CUTSCENE_SYSTEM.textCache with a copy of text. Any item may
|
||||||
|
* call this - it isn't tied to any one item type - so later items can
|
||||||
|
* read back whatever the caller wants to pass along, up to
|
||||||
|
* CUTSCENE_TEXT_CACHE_MAX - 1 characters.
|
||||||
|
*
|
||||||
|
* @param text The text to cache; copied internally, safe to be
|
||||||
|
* transient. Must not exceed CUTSCENE_TEXT_CACHE_MAX - 1 characters.
|
||||||
|
*/
|
||||||
|
void cutsceneSystemSetTextCache(const char_t *text);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Advance to the next item in the cutscene.
|
* Advance to the next item in the cutscene.
|
||||||
*/
|
*/
|
||||||
void cutsceneSystemNext();
|
void cutsceneSystemNext();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Jumps the running cutscene directly to the CUTSCENE_MARKER item with
|
||||||
|
* the given name and starts it immediately, as if cutsceneSystemNext()
|
||||||
|
* had advanced straight to it. Intended to be called from within
|
||||||
|
* another item's start/update (e.g. a CUTSCENE_CALLBACK) to implement
|
||||||
|
* flow control. Asserts if no cutscene is running or no marker with
|
||||||
|
* that name exists in it.
|
||||||
|
*
|
||||||
|
* @param name Marker name to search for, matched with stringEquals.
|
||||||
|
*/
|
||||||
|
void cutsceneGoTo(const char_t *name);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update the cutscene system for one frame.
|
* Update the cutscene system for one frame.
|
||||||
*/
|
*/
|
||||||
|
|||||||
Loaded 100 of 520 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user