63 Commits

Author SHA1 Message Date
YourWishes 7a858cc424 Add a real test suite for the save system (previously had none)
Covers save.c (device discovery/orchestration), savedevice.c (the
generic device state machine and platform dispatch), and the Linux
platform backend (path building, availability checks, JSON read/write,
corrupt/missing-file handling), plus saveslot.c/savesettings.c JSON
round-trips. 88 tests across 5 files, all run against the real Linux
filesystem backend sandboxed to a temp $HOME (there's no mockable
platform layer - the hooks are compile-time macros, not function
pointers).

Deliberately locks in two existing behaviors rather than working around
them: saveSaveSettings() is a permanent no-op because nothing anywhere
ever sets SAVE.settingsDirty = true, and saveUpdate() unconditionally
rewrites settings back out the moment a device is found regardless of
that same dirty flag. Both are pre-existing, not introduced here.

Does not cover the SAVE_DEVICE_DATA_RAW blob codec (PSP/GameCube/Wii
only) or GameCube's 2-device fallback chain - neither compiles into the
Linux host test build.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-30 12:33:20 -05:00
YourWishes c0292842a5 Fix stale include re-enabling test/item, fix dead sort-by-type coverage
test/item/test_inventory.c was disabled via a commented-out
add_subdirectory(item) with no explanation - the actual cause was a stale
"item/inventory.h" include left over from before the rpg/ reorg (real path
is rpg/item/inventory.h). The current inventory.h/.c API it tests hasn't
drifted; only the include path had rotted.

Also fixes a copy-paste bug in test_inventorySort: the "sort by type"
assertions were calling INVENTORY_SORT_BY_ID again instead of
INVENTORY_SORT_BY_TYPE, so inventorySortByType/Reverse had zero real
coverage. Asserts on type grouping only (not the tied FOOD-vs-FOOD order),
since the underlying sort() is qsort and not stable.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-30 12:33:00 -05:00
YourWishes 717902462b Fix fatal async asset load errors, remove unused event system
An async asset load failure crashed the whole game via errorThrow,
while the identical sync failure just logged and continued - a single
missing/corrupted asset could take down the process. assetUpdate now
handles the async error path the same way as sync (invoke onError,
keep running).

Also removes event.h/event.c and assetbatch, which existed only to
support multiple subscribers per asset event but had no real caller
that ever used more than one (assetbatch itself had zero callers
anywhere). Asset entries, uifullbox, and uiloading now use plain
single-callback + user-pointer fields instead of the generic
array-backed event_t.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-30 10:14:38 -05:00
YourWishes 1d73b9d224 Fix PSP asset loading: stale EBOOT.PBP packing, unreliable zip file reads
EBOOT.PBP packing was a POST_BUILD step with no dependency on the asset
pak, so an assets-only rebuild could silently leave a stale dusk.dsk
embedded. cmake/targets/psp.cmake now repacks EBOOT.PBP via a properly
tracked custom command depending on the executable, PARAM.SFO, and
dusk.dsk (and correctly embeds Dusk.prx rather than the raw ELF when
BUILD_PRX is on).

Separately, libzip's zip_source_filep_create (lazy seeked FILE* reads)
proved unreliable on real PSP hardware, corrupting reads of the embedded
PSAR (first EINVAL, then zlib data errors) even though the packaged data
was verified byte-perfect. assetInitPBP now reads the whole PSAR into
memory once and uses zip_source_buffer_create instead. Confirmed working
on real hardware.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-28 09:31:44 -05:00
YourWishes 51f262efa0 Wire keyboard into save naming, add fatal error overlay, cutscene keyboard item
- uimainmenu: removed the temporary keyboard test entry now that the
  keyboard has a real caller.
- uiselectsave: picking an empty save slot now opens the keyboard to
  name it (localized title "Enter game save file name"), writes the
  named slot to disk (mirroring the existing delete-confirm write
  pattern), and on a write failure opens the new fatal error overlay.
- uikeyboardopen_t gains a title override (NULL keeps the default
  "ENTER YOUR TEXT").
- New ui/overlay/uifatalerror: a minimal fullscreen, non-dismissible
  overlay (message + QUIT button, back disabled) for unrecoverable
  errors - a nicer alternative to a raw assert crash. Draws above
  everything else in the UI element list.
- New CUTSCENE_ITEM_TYPE_KEYBOARD cutscene item: opens the keyboard
  with an embedded uikeyboardopen_t, blocks the cutscene until it
  closes, then caches the entered text via a new general-purpose
  cutscenesystem_t.textCache (CUTSCENE_TEXT_CACHE_MAX, with get/set
  accessors) mirroring the existing entity/area/text-mini id caching
  pattern.
2026-08-28 08:29:07 -05:00
YourWishes a6e4e3f71f Add cancel confirmation, blinking cursor, custom keyboard icon glyphs
- uikeyboardopen_t gains cancelConfirm/cancelConfirmLabel, mirroring
  confirm/confirmLabel: cancelling (CANCEL button or back-with-nothing-
  left-to-delete) can now open an "are you sure?" dialog before closing.
- Added a blinking text-entry cursor, rendered as a separate label
  positioned at the end of the current text (accounting for newlines);
  it now stops at the last character rather than past it once maxLength
  is reached, matching uiKeyboardAppendChar's override-last-char
  behavior there.
- uibutton_t gains an `active` flag, independent of the focus-driven
  `highlighted` state, for a toggled-on indicator that survives focus
  moving elsewhere (used by the keyboard's CAPS/SHIFT keys).
- Added several custom icon glyphs to the default font by repurposing
  otherwise-blank/unused glyph slots (backtick, pipe, tilde, backslash,
  and the DEL trailing tile) - up arrows for Caps Lock/Shift, a return
  arrow for newline, a spacebar symbol, a left arrow for backspace, and
  a real underscore - replacing the keyboard's old text-abbreviation key
  labels ("CL"/"SL"/"NL"/"<") with single-glyph icons.
2026-08-27 22:17:00 -05:00
YourWishes 4387d223b9 Fullscreen keyboard dialog, nearest-cell vertical navigation, overwrite-at-max-length
- Keyboard dialog now fills the whole screen (no dimming backdrop); key
  cells use a fixed font-tile-based size instead of scaling to a
  percentage of the screen.
- uiMenuFocusSkipBlanks: UP/DOWN now search every non-blank cell strictly
  further in the pressed direction and land on the smallest combined
  row+column distance (ties favor the smaller column distance), instead
  of only scanning straight down the same column. Neither axis wraps
  during that search - only once the edge row is reached with nothing
  further to search does it fall back to wrapping to the opposite edge.
- Typing a new character while the keyboard's text is already at
  maxLength now overrides the last character instead of being ignored.
2026-08-27 21:14:19 -05:00
YourWishes 00bfaf6360 Fix cutscene/focus bugs found on PSP hardware, rework keyboard layout
Cutscene loader: a MODAL item's optionCount byte was read directly
inside an assertTrue() condition. On the PSP release build
(DUSK_ASSERTIONS_FAKED), assertTrue expands to a no-op and never
evaluates its argument, so that read - and the offset advance it was
responsible for - silently never happened, desyncing every item after
it in the stream. Moved the read out to its own statement and replaced
the assert with a real error throw, since this is untrusted file
content.

uifocus: fixed a wraparound bug in uiFocusMoveDirection - moving left/up
from position 0 truncated to uint8_t before the modulo wrap (0-1 => 255,
then 255 % cols), landing on the wrong column instead of the row's last
one. Only ever visible on a grid wider than a handful of columns, which
nothing but the new keyboard has.

Keyboard: merged uikeyboardqwerty into uikeyboard (only one layout
exists, so the split no longer earned its keep) and deleted the unused
numbers/symbols placeholder files. Reshaped the grid to a tighter 11x5
layout with per-mode key tables (unshifted/caps/shift) instead of
computing case transforms, and fixed the reserved NEWLINE/CONFIRM/CANCEL
slot indices to match. Added shift-symbols for digits and -/=, and
uimenu's directional navigation now skips blank filler cells (wrapping
around a row/column as if they weren't there) instead of landing on
them - a generic fix in uimenu.c, not keyboard-specific, since nothing
else uses blank cells.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 19:26:07 -05:00
YourWishes 709bd7be52 Add validation options and a full physical layout to the keyboard
uikeyboardopen_t grows: maxLength (auto-focuses confirm once full),
lineCount for multi-line entry with a NEWLINE key, trimmed/allowBlank
validation on confirm, and a second "are you sure" uiConfirm step.

Reworks uikeyboardqwerty from a packed flat list into a fixed 14x5 grid
shaped like a real keyboard - number row with -, =, ~ and backspace,
caps and shift (one-shot, XORed with caps for real-keyboard behavior),
and a bottom row with cancel/space/confirm in their normal corners.
Shorter rows are padded with invisible filler cells so every key lands
in its physical position; NEWLINE/CONFIRM/CANCEL are reserved slots
uikeyboard.c patches in conditionally, otherwise left as inert blanks.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-26 18:44:07 -05:00
YourWishes 80f4348e21 Implement on-screen keyboard dialog with QWERTY layout
Builds out uikeyboard/uikeyboardqwerty from placeholders into a working
controller-navigable text entry dialog: title/current-text labels, a flat
QWERTY key grid (letters, space, backspace), and confirm/cancel buttons in
one combined menu so d-pad navigation flows across all of it.

uikeyboardopen_t configures each dialog: onInput/onKeyPress callbacks,
optional cancel button, maxLength (auto-focuses confirm once full),
lineCount for multi-line entry (adds a NEWLINE key, reserves vertical
space up front), a second "are you sure" uiConfirm step, and
trimmed/allowBlank validation on confirm.

Back now deletes the last character first, falling through to close only
when cancel is allowed and the buffer is empty - this needed a general
cancel-intercept callback added to uifocusitem_t/uimenu_t
(uiMenuSetCancelCallback), since the focus system previously only
supported popping or fully swallowing back.

Wired a temporary "LOAD GAME (TEST)" entry into the main menu with
console-logging test callbacks for interactive testing; marked TODO for
removal once the keyboard is wired up somewhere real.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-26 15:26:57 -05:00
YourWishes e630827b34 Add runtime-loaded cutscene files, convert initial/main menu to use them
New ASSET_LOADER_TYPE_CUTSCENE (assetcutsceneloader.c) reads a versioned
binary .cts format decoded into a heap-allocated cutsceneitem_t array + a
string/data pool, both sized to the file's actual content rather than a
fixed capacity, so the shared assetloaderoutput_t union doesn't bloat for
every asset slot regardless of type. Authoring pipeline mirrors the chunk
asset pattern: assetsraw/cutscenes/*.jsonc (JSON plus // and /* */
comments) -> tools/asset/cutscene -> assets/cutscenes/*.cts.

cutsceneSystemSetOnComplete() lets the caller arm a native callback that
fires when a cutscene finishes normally, so a file (which can't store a
function pointer) can end plainly and still hand off to native code -
cutsceneRestart() preserves it across a retry loop rather than clearing it,
since a restart is the same logical run trying again.

The initial and main-menu start-game cutscenes are now loaded from files
instead of compiled in via the CUTSCENE(...) macro.

Fixed a real bug found while converting these: the sync loader read the
file's total size from assetfile_t.size to locate the trailing pool
region, but assetFileDispose() (called at the end of the async phase)
zeroes that whole struct first, so the size was always 0 and the pool
offset computation underflowed into an out-of-bounds read - intermittent
depending on heap layout. Fixed by saving the size before disposal; also
fixed the read-completeness assert being checked after that same zeroing
(a no-op 0 == 0 check).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 09:51:26 -05:00
YourWishes 106d9b0fc0 Move main menu start-game cutscene from ui panel to scene
The load-all-slots/no-device cutscene and its helper callbacks belong to
scene-level game flow, not the uimainmenu UI panel. Moved them into
scenemainmenu.c/h behind a new sceneMainMenuStartGame() entry point;
uimainmenu.c's Start Game handler now just calls that.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 20:30:33 -05:00
YourWishes 4a26f79945 Add uimenu disableBack flag, apply to main menu and all modal options
uifocusitem_t/uimenu_t gain a disableBack flag that makes back/cancel a
no-op while that item is focused, set via uiMenuSetDisableBack. Applied
centrally in uimodal.c so every modal with option buttons (confirm
dialogs, cutscene modals) must be dismissed by picking an option rather
than backing out, and to the main menu so it no longer bounces back to
the initial scene on cancel - replacing the suppressClosedSceneChange
hack entirely. Updated docs that described the now-unreachable
back/cancel dismissal path. Also adds
cutsceneSystemStartCutsceneAndGoToMarker for starting a cutscene
straight at a given marker instead of its first item.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 22:11:27 -05:00
YourWishes 1a199f6ce3 Add declarative cutscene items for save checks and marker-based modals
CUTSCENE_SAVE_DEVICE_CHECK and CUTSCENE_SAVE_LOAD_ALL_SLOTS wrap the
existing device-lookup/slot-load calls and jump straight to a
success/failure marker, and CUTSCENE_MODAL_OPTIONS_ONE/TWO do the same
for one/two-option modals, removing the need for a hand-written
goTo-only callback per use. Main menu's "Start Game" now runs a
cutscene (mirroring the initial scene's save-check flow) that loads all
slots before opening the load-game picker, retrying on error; the
initial scene's own device check is migrated onto the same items.
Backing out of the main menu now returns to the initial scene.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 20:29:57 -05:00
YourWishes ec59e77867 Moved files around 2026-08-23 10:14:39 -05:00
YourWishes cb28d2b611 Add save slot picker (uiselectsave/uisaveslot), fix focus stack reentrancy
uiselectsave is a Save/Load/Delete slot picker built on save/save.h's
SAVE_SLOT_COUNT: a scrolling list of framed uisaveslot_t rows (slot
number + file name, or an "Empty Slot" placeholder), navigated via the
same uimenu_t/focus-stack convention as every other menu. Load and
Delete modes add a trailing action row (switch to delete / cancel)
fixed below the scrollable area. Selecting a slot in Delete mode routes
through uiConfirmOpen before actually blanking the slot via
saveSlotInit + saveDeviceSlotWrite. uiScrollingEnsureVisible in
uiscrolling.c is now a real implementation instead of the earlier
placeholder.

Main menu collapses New Game/Load Game into a single Start Game entry
that opens uiselectsave in Load mode; backing out reopens the main
menu via uiselectsave's result callback.

Also fixes a real reentrancy bug in uiFocusPop: it invoked the popped
item's closed callback before decrementing UI_FOCUS.count, so a push
triggered from within that callback (e.g. reopening the main menu once
select-save reports no result) landed one slot past the true stack top
and got silently dropped, stranding the new item outside navigation.
Count is now decremented first.

Adds a uikeyboard placeholder widget, registered in uielementlist with
no behavior yet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 14:16:39 -05:00
YourWishes 27b6ddf5cb Rebuild uiconfirm on top of uimodal, add quit confirmation
uiconfirm no longer duplicates its own backdrop/frame/text/menu drawing
- it now just opens the shared uimodal_t with a Confirm/Cancel option
pair and translates the result back to a bool. uimodal itself gains an
optional title (NULL skips the title row entirely) so a title-less
confirm dialog doesn't reserve blank space.

Main menu's Quit option now opens a confirm dialog instead of exiting
immediately.

Drops es_MX.po/jp_JP.po locale files.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 22:41:06 -05:00
YourWishes 475c865e33 Move uimodal to ui/widget, make main menu its own scene
uimodal.c/.h now live in ui/widget alongside the other widgets rather
than ui/frame. The main menu now has a real scene (scene/mainmenu)
whose init just calls the new uiMainMenuOpen(), replacing the
SCENE.current-polling uiMainMenuUpdate with an explicit open call like
uiGameMenuOpen/uiBackpackOpen. Also renames the ui.main_menu.* locale
keys to main_menu.* and groups them under a Main Menu Scene heading in
en_US.po, alongside the existing Initial Scene keys.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 19:18:50 -05:00
YourWishes 0b4ba062bb Translate and word-wrap cutscene modal text
uiModalOpen now resolves title/message/option strings as locale
message IDs first, falling back to the literal string if no match is
found, and word-wraps the result to stay within the screen's scan
width via the new shared textWrap helper. sceneinitial.c's no-device
modal now uses locale keys instead of hardcoded English strings.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 18:53:47 -05:00
YourWishes 28f5e66662 Fix PSP memory stick availability check on real hardware
sceIoGetstat on a bare device root ("ms0:/") returns EINVAL on real
PSP hardware even when a memory stick is present - confirmed via a
diagnostic print during hardware testing. Switched to sceIoDopen/
sceIoDclose, the SDK's own documented way to probe a device root,
which real hardware handles correctly.

Also adds a temporary unconditional settings write once a save device
is selected, to confirm the write path itself works on hardware now
that availability detection is fixed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 17:22:24 -05:00
YourWishes e225a076f0 Add cutscene flow control and a scriptable modal dialog item
uimodal gains an onOpen hook and lets uiModalClose take a one-shot
callback, since options are now stored as raw (uncopied) string
pointers instead of a fixed char buffer.

New cutscene items:
- CUTSCENE_MODAL / CUTSCENE_MODAL_OPTIONS / CUTSCENE_MODAL_CLOSE: opens
  a message-only or option-driven uimodal. A message-only modal
  advances the cutscene immediately; one with options blocks
  indefinitely since only its option callback (or something it
  triggers) should decide what happens next.
- CUTSCENE_MARKER + cutsceneGoTo: a named, otherwise no-op position
  that execution can jump straight to from anywhere in the same
  cutscene (e.g. from a CUTSCENE_CALLBACK), matched by name rather
  than pointer identity.
- CUTSCENE_RESTART + cutsceneRestart: restarts the running cutscene
  from its first item, preserving its interact/interacted entities.
- CUTSCENE_SCENE: requests a scene switch via sceneSet as a cutscene
  step.
- CUTSCENE_PRINT: prints a line to the console as a cutscene step.

sceneinitial.c's boot-time save device check is rebuilt on top of
these: show a modal, kick off the async device search, then branch
via markers/goto to a retry/continue prompt depending on the result.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 14:35:41 -05:00
YourWishes 774c8ad0f8 Add uimodal dialog; uibutton reuses uilabel
uibutton now embeds a uilabel instead of drawing its text directly,
caching glyph sprites since a button's label never changes after
init. uimenu.c's item pointer in uiMenuDraw drops its unnecessary
const so uiButtonDraw can update the button's cache.

Also fixes remaining #include "ui/frame/uiframe.h" references left
over from uiframe's move to ui/widget/.

uimodal is a new generalized dialog (title + message + up to
UI_MODAL_OPTIONS_MAX option buttons) built the same way uiconfirm is,
but driven by a caller-supplied option list instead of a fixed
confirm/cancel pair.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 12:44:01 -05:00
YourWishes 52d1e7414d Convert debug UI overlays to uilabel
uiconsole, uifps, and uiplayerpos now render through uilabel instead
of calling textDraw per character every frame. Each owns its label(s)
plus backing text/sprite buffers and marks them dirty only when their
content or position actually changes. Also drops console.h's per-line
buffer from 512 to 128 chars, since the sprite cache backing each
console line label scales with it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 12:43:43 -05:00
YourWishes af4cb53e5f Simplify uilabel to caller-owned buffers
uilabel no longer owns fixed-size text/sprite arrays or copies text
internally - callers pass in their own buffers and write text
directly, then mark the label dirty. This drops SetText/GetText and
the textMax bound in favor of a single Rebuffer entry point, and lets
widgets like uibutton alias an existing (possibly immutable) label
string instead of duplicating it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 12:43:02 -05:00
YourWishes c019271e12 Add uilabel widget and chunked text buffering
textDraw now batches glyphs via a new textBuffer helper instead of
buffering one sprite at a time. Fixes spriteBatchBuffer dropping/
duplicating sprites when a single call spans multiple internal
flush batches, which surfaced as cut-off characters. Adds uilabel,
a widget that caches its glyph sprites and only rebuilds/rebuffers
them when its text or position actually changes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 09:18:35 -05:00
YourWishes 82ae2bce9d Add compressed combined save format for PSP and Dolphin
Memory sticks/cards don't suit N+1 separate save files the way Linux's
filesystem does, so add an opt-in SAVE_DEVICE_DATA_RAW mode: settings and
all save slots get serialized to JSON, concatenated, zlib-compressed, and
framed with a magic/version/checksum/generation header, then read/written
as a single blob through one combined platform hook instead of four.

- PSP and Dolphin's SD/NAND backends write via a temp file + atomic rename,
  so a crash mid-write can never leave a half-written save behind.
- GameCube memory cards have no rename or resize primitive, so they
  ping-pong between two fixed files instead, picking whichever is valid and
  has the higher generation counter on load.
- Linux is untouched (still four separate JSON files); saveslot.h/
  savesettings.h drop their now-unnecessary pack(1) now that nothing
  persists them as raw bytes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 21:28:56 -05:00
YourWishes 092e259a06 First pass of actual saving 2026-08-17 09:18:44 -05:00
YourWishes 08b4bbfe91 Added savestatus 2026-08-17 00:17:23 -05:00
YourWishes 560c51cf27 Drop default-skip behavior from savejson write macros
Only reads should fall back to a default when a key is missing; writes
should always emit the field so the saved JSON is a complete record.
2026-08-16 20:20:34 -05:00
YourWishes 674f86b18a Add JSON (de)serialization for save slots/settings and device write/read hooks
Introduces saveslot/savesettings structs with a shared savejson.h macro
toolkit (has/require/write/read per common type) for populating and
parsing yyjson objects, wires saveManager save/load calls through new
saveDevice slot/settings write/read entry points (still stubbed at the
device level), and drops the old binary-format scaffolding in favor of
JSON only.
2026-08-16 20:14:16 -05:00
YourWishes e3f10e0926 Fix GameCube memory card slot B detection and free-space check
CARD_Mount() alone reliably reports CARD_ERROR_NOCARD for a card physically
present in slot B - unlike slot A, which the IPL polls automatically at
boot, slot B needs an explicit CARD_Probe() first (the standard pattern in
every official devkitPro CARD sample). Also fixes
saveDeviceDolphinCardHasFreeSpace() treating CARD_GetDirectory()'s
CARD_ERROR_NOFILE (a totally empty card, not an actual error) as a hard
failure, which made any card with zero existing save files - slot B's in
this case, since slot A already had leftover test data on it - get
reported as full.

Confirmed via Dolphin with slot A disabled/slot B set to a memory card:
previously reported "no save device found", now correctly detects it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 16:49:18 -05:00
YourWishes d7223d7387 Add PSP/GameCube/Wii save-device availability checks
PSP checks memory-stick reachability via sceIoGetstat. GameCube gets two
devices (CARD_SLOTA/CARD_SLOTB), each mounted via CARD_Init/CARD_Mount and
checked for free space via CARD_GetDirectory/CARD_GetBlockCount. Wii picks
between three storage methods at compile time (DUSK_SAVE_WII_METHOD =
NAND/CARD/SD in wii.cmake, default NAND via ISFS) since real hardware
behavior for the default is unverified.

Also fixes two pre-existing bugs found while build/runtime-testing this
across PPSSPP and Dolphin: wrong libogc language macros in
systemGetLocaleDolphin, and a missing SYS_STDIO_Report(true) call that
silently swallowed all guest console output in Dolphin.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 16:20:28 -05:00
YourWishes 45331c2a60 First pass of save 2026-08-14 14:19:44 -05:00
YourWishes 33f50a2c69 Strip legacy save/settings systems for a unified savemanager rewrite; split uielement list out of uielement.c
Removes the per-platform save/savestream/autosave implementations, the settings UI frames, and the autosave overlay, replacing them with a savemanager.c/h + savefile.h/savedevice.h scaffold to build the new save system on top of. Also separates the concrete UI_ELEMENTS registration into uielementlist.h/.c so uielement.c only holds the generic per-element lifecycle logic.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 12:56:02 -05:00
YourWishes 6c8e4d5cbd Route remaining hardcoded UI strings through the locale system
Main menu buttons, the confirm dialog, battle menu/HUD text, backpack
tab labels, the loading/autosave indicators, and the settings tab
placeholders were all raw English literals bypassing translation.
Loads each through assetLocaleGetString like the rest of the UI, adding
new Init hooks for uibattlehud/uiautosave/uiloading where none existed,
and adds the corresponding message ids to en_US/es_MX/jp_JP.po.

Also widens the settings placeholder buffers to 64 bytes - the es_MX
and jp_JP translations overflowed the previous 32-byte size.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-10 09:12:57 -05:00
YourWishes 3b7215876a Move test battle setup out of uimainmenu into rpg/battle/testbattle
Keeps the temporary hardcoded-battle hook alongside the rest of the
battle module instead of the main menu UI, so the UI frame only
triggers it rather than owning battle setup code.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 16:28:00 -05:00
YourWishes c74f5890bd Remove event for input 2026-08-08 16:25:36 -05:00
YourWishes fbd3c71ba7 Move network code into its own dusknetwork module, gate behind DUSK_NETWORK
Splits the platform-agnostic network core out of dusk into a top-level
dusknetwork module, mirroring the duskgl/dusksdl2 pattern. Adds a
DUSK_NETWORK cmake option (default ON) so builds can exclude all
networking code, including the per-platform implementations.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 16:13:09 -05:00
YourWishes 128f9ab9d4 some random fixes 2026-08-08 01:18:07 -05:00
YourWishes 36fb359aa2 Finish animation update loop with loop/pingpong/reverse/stop flags, clean up keyframe sampling, add coverage
- animationUpdate now advances and resolves boundary crossings for
  ANIMATION_FLAG_LOOP, ANIMATION_FLAG_PINGPONG, ANIMATION_FLAG_REVERSE, and
  the STOP_BEGINNING/STOP_END flags, firing onLoop/onComplete appropriately;
  guards against LOOP+PINGPONG being set together and moves the
  duration-must-be-positive check into animationInit
- keyframeGetValue clamps to the last keyframe's value instead of dividing
  by zero once time reaches it, and its keyframe walk drops a branch that's
  unreachable after that clamp
- Adds test/animation/test_animation.c covering init, per-layer sampling,
  and the full animationUpdate flag matrix
2026-08-06 15:29:14 -05:00
YourWishes 1bd73d69fe Clamp keyframe interpolation to last value, add main menu scene/UI, battle HUD, and expanded test coverage
- keyframeGetValue now returns the last keyframe's value for times at or
  beyond it, fixes a missing util/math.h include, and asserts keyframes are
  sorted by time; adds test/animation/test_keyframe.c
- Adds mainmenu scene/UI and a battle HUD UI frame
- Adds save autosave-related fields and battle scene tweaks
- Adds headless test coverage for cutscenes, entities, and map areas
2026-08-06 12:58:07 -05:00
YourWishes fb48285143 Rebuild battle flow as an explicit state machine with cutscene hooks
Replace the one-fighter-at-a-time turn model with an OPENING/PRE_ROUND/
PLAYER_SELECTION/AI_SELECTION/MOVES_EXECUTING/POST_ROUND/ENDED state
machine and a per-fighter action queue, so actions are decided before any
of them execute (needed for speed-ordered resolution) and so a cutscene
can pause the battle, wait for a specific state, and force a fighter's
action -- enabling automated, fully-scripted, and partially-scripted
battles. Adds CUTSCENE_PAUSE_BATTLE plus CUTSCENE_BATTLE_WAIT_STATE and
CUTSCENE_BATTLE_FORCE_ACTION cutscene items, and generic onStateChanged/
onActionDecided callbacks on battle_t. Re-enables the long-dormant
test/rpg suite and adds test/rpg/battle covering the state machine and
the new cutscene hooks end-to-end.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 08:49:42 -05:00
YourWishes 3de50b8370 Lock in Chapter 1's literal opening scene
The village square at the mountain's foot, party roles established
(tank/paladin leader, ranged ranger, support mage, melee rogue), the
funds bicker, and the cowgirl teleporter's too-good-to-question,
one-way-only offer up the mountain - the innocent-sounding line that
seeds the whole chapter's central complication. Adds character stubs
for the three other party members and the teleporter, and confirms
the bubbly ranger as the first to abandon the mission.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 08:11:54 -05:00
YourWishes e61cbe25b7 Add three of the mentor's other former squadron members
Introduces Strider (a merc who protects those who can't afford real
protection, and has found genuine peace in it), Downes (retired to
farming and family, forced back into one last fight), and Egor (Royal
Guard, honor curdled into blind devotion, dies still certain of
himself). Together with the party leader, they give the same
mentor/same night four distinct answers to what honor means. Updates
themes and open questions accordingly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 06:54:49 -05:00
YourWishes 8395830be6 Introduce the Detective, kept deliberately thin by design
Reveals him as the presence following the party since Chapter 1 - a
king's agent who frees the protagonist from execution in early
Chapter 2, drops a small, cagey lead to the newly-dismissed party
leader, and then vanishes to chase other threads. Documents these
early Chapter 2 beats, notes culinary magic is now branded "the
forbidden magic" per the king's cover story, and updates open
questions/themes accordingly. His entry is intentionally sparse -
the character is meant to stay a mystery for as long as possible.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 23:47:50 -05:00
YourWishes 6e4ec2b9d8 Add the party leader's backstory and his mentor
Ties the party leader's rigid, orders-above-all sense of honor back
to a mentor he idolized as a young soldier - one who broke orders on
the night of the Great Explosion to keep his squadron out of the
massacre, then died in it. The party leader doesn't know why at the
time; his eventual realization that his mentor's disobedience was
itself the honorable act becomes his arc's throughline. Also notes
the rest of that squadron, now scattered, as a future plot thread.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 23:37:18 -05:00
YourWishes f501bb8e28 Detail the true events of the Great Explosion
Replaces the vague placeholder with the full account: the king's
personal, in-person purge of the culinary mages' hometown, the failed
hostage surrender, the town's collective final spell (built on a
shared folk song) that becomes the Great Explosion, and the
protagonist's survival via her mother's protective spell. Also adds
the king's official cover story (framing the mages as insurgents),
new characters (the Great Mage and the protagonist's mother), and
updates themes/open questions accordingly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 23:29:39 -05:00
YourWishes d07cd3397d Start documenting the story: premise, structure, and Chapter 1
Adds story.md covering the overarching premise (a prophecy caused by
the attempt to prevent it), the eight-movement story structure, the
Great Explosion backstory, core characters, and a detailed breakdown
of Chapter 1's opening - the bounty party's retrieval of the
protagonist, the mountain teleportation-logistics trap that splits
the party, and the confrontation with the king.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 23:16:46 -05:00
YourWishes e008fb108a Embed default font as a hard-coded bitmap instead of loading it as an asset
Moves FONT_DEFAULT and its init/dispose into their own font.h/font.c,
and rebuilds it from a static glyph bit array + a runtime-generated
texture/tileset rather than loading ui/minogram.png/.dtf through the
asset system. The engine now always has a usable font to render with,
even if asset loading fails. The now-unused minogram assets are removed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 22:37:22 -05:00
YourWishes 9aaffff7a8 Add autosave system with forced no-save-device prompt on failure
autoSaveQueue() is a single callable entry point for requesting an
autosave; autoSaveUpdate() pumps the queue each frame and, if the write
fails (e.g. no memory card), forces the existing no-card modal back
open and pauses world simulation until the player retries or accepts a
temporary session. A small overlay shows "SAVING" while a write is in
flight.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 22:05:43 -05:00
YourWishes 7357b4a5df Localize remaining hardcoded UI strings and persist language preference
Replaces the last hardcoded English strings (initial-scene modals, game
menu save status messages) with locale-loaded text, adds a shared
LOCALE_LIST so the settings dropdown and locale manager stay in sync,
and persists the chosen language into savemeta_t across all platforms.
Also fixes two message buffers that were too small for their longest
translations.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 21:39:24 -05:00
YourWishes 1ddc298a74 Only update overworld entities while the overworld scene is active
Entities (and the player's pause-to-open-game-menu handling with them)
previously kept updating every frame regardless of the active scene,
matching an existing TODO in rpgUpdate(). Gating the entity loop itself
means the game menu (and any other entity-driven input) naturally can't
trigger mid-battle or before the initial scene hands off to the
overworld, without needing a scene check at each individual call site.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 20:54:58 -05:00
YourWishes e2a9442aa6 Add initial boot scene to check/prompt for save data before overworld
A new SCENE_TYPE_INITIAL now runs before the overworld: it checks
save-device availability and existing save data, then shows one of two
new dedicated modals - "no save device found" (Retry / Continue Anyway)
or "no save data found, create one?" (Yes / No) - before handing off to
the overworld. Both modals are self-contained UI elements mirroring
uiconfirm.h's shape, registered like any other global UI element.

Choosing "Continue Anyway" marks the session temporary (SAVE.temporary,
folded into saveIsAvailable()) so saving stays disabled for the rest of
the session instead of silently retrying, and the game menu's Save
action now reports that distinctly instead of the generic "no device"
message.

Also removes rpg.c's leftover TEST block (unconditional player-name
stamp + save write on every boot) now that this real flow owns save
creation.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 20:53:01 -05:00
YourWishes aa0180571e Unify save system into one save.h/.c; diverge storage format per platform
Renames savefile_t to saveslot_t and folds last session's standalone
settings.h/.c module back in as savemeta_t, so there's one save system
(SAVE.slots[] + SAVE.meta) instead of two parallel ones - while letting
each platform pick its own physical format for the two concepts:

- Linux now writes human-editable JSON (slot0.json, settings.json, ...)
  via yyjson's mutable writer API, so players can hand-fix a bad setting.
- PSP folds meta into the same sceUtilitySavedata binary payload as its
  one save slot (SAVE_SLOT_COUNT_MAX=1 there - a future save picker will
  let players manage multiple named saves via the OS's own browser).
- GameCube consolidates the 3 per-slot memory card files and the separate
  settings file into one combined card file.

Also fixes two bugs surfaced while building this: the CRC finalize step
seeked to a hardcoded offset (only safe for one section per file, breaks
once meta+slots share a buffer), and save.c's async/sync dispatch left an
unconditional fallback call that doesn't exist on PSP-only platforms.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 18:35:06 -05:00
YourWishes 7f7be39230 Split device settings out of the per-slot save file
Deadzone (and future prefs like locale) now live in their own
settingsfile_t/settings.c, loaded eagerly at boot and saved immediately
on Apply, instead of inside savefile_t - a setting shouldn't reset or
diverge just because the player is on a different save slot, and this
also fixes settings changes not actually reaching disk until the next
full game Save.

PSP settings use a new plain sceIo path rather than sceUtilitySavedata,
since that dialog would flash its native icon on every settings tweak.
GameCube reuses the save system's existing memory card mount rather than
mounting it twice (settingsInit() now runs after saveInit()).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 13:54:15 -05:00
YourWishes 4d95415232 Move global item collected-state, deadzone, and story flags into save file
Adds three new pieces of save-file state, all following the same shape:
the save file is the single source of truth, not a separate live runtime
copy that gets synced in/out.

- globalitemstore.h/.c: per-global-entity-ID "collected" flags
  (savefile_t.globalItemCollected), so a global item entity's init
  callback can check whether it was already picked up in a prior session
  without needing to keep the entity itself alive to remember that.

- Gamepad deadzone: removed input_t.deadzone entirely. The setting UI and
  every platform's actual deadzone-applying code (inputGetDeadzoneDolphin/
  SDL2, previously hardcoded per-platform literals that the settings menu
  didn't actually affect) now read savefile_t.deadzone directly via
  saveGet(SAVE_ACTIVE_SLOT). Default lives in savefile.h
  (SAVE_DEADZONE_DEFAULT), stamped onto every slot in saveInit().

- Story flags: STORY_FLAG_VALUES (a live, codegen-initialized array) is
  replaced by savefile_t.storyFlags, read/written via the existing
  storyFlagGet()/storyFlagSet() call sites (now macros/functions over the
  active save file instead of a separate array). tools/story.py now
  generates STORY_FLAG_DEFAULTS (const) instead; storyFlagInitDefaults()
  stamps those onto a save the first time it's used (file->exists false),
  called from rpgInit().

Added SAVE_ACTIVE_SLOT (0) to savefile.h as the one shared "which slot is
actually being played" constant, replacing three different local/implicit
0s (uigamemenu.c, rpg.c, and now the settings/input call sites).

Verified round-trip on Linux (all three together in one save/load cycle);
both Linux and PSP build clean.
2026-08-04 11:10:44 -05:00
YourWishes 2cbd80a004 Check for existing save data before saving, confirm before creating new
uiGameMenuSave() now attempts a real load first (via the existing generic
saveLoad()/saveExists() primitives) instead of writing blind. If a save
already exists, it saves straight over it as before. If not, it prompts
via the existing uiConfirm dialog ("No save data found. Create a new
save?") before writing - this is exactly the flow GameCube needs (no
native OS save browser to lean on, unlike PSP), but implemented generically
so it also applies correctly on every other platform without any
platform-specific UI code: saveIsAvailable()/saveExists() already reflect
each platform's real state (e.g. Dolphin's memory-card presence and
existing-file checks), so the same logic just does the right thing
everywhere.

Verified the two branches directly on Linux (temporarily wiring the same
saveLoad -> check -> uiConfirmOpen sequence into rpgInit): with no save
file, saveExists() is false and the confirm dialog opens; with one already
written, it's true and the confirm dialog is correctly skipped. Not
verified via actual menu navigation (no input-injection tooling available
here) or on Dolphin (no devkitPPC toolchain in this environment).
2026-08-04 10:33:57 -05:00
YourWishes 9abf8101da PSP: save through the real sceUtilitySavedata API, not raw file I/O
Rewrote savepsp.c/savestreampsp.c to use sceUtilitySavedataInitStart/
Update/GetStatus/ShutdownStart instead of sceIoOpen/Read/Write, so PSP
saves get a proper OS-generated PARAM.SFO (title/savedataTitle/detail) and
show up correctly in the native save browser.

This dialog spans multiple frames and, per this project's prior experience
with the network config dialog, must be pumped non-blocking one step per
real engine frame rather than blocked on synchronously - a raw-sceGu
blocking loop already froze the app on real hardware for that dialog,
since pspGL owns the GU context. So save.h's saveWrite()/saveLoad() are
now callback-based (savecallback_t onComplete) instead of returning a
result directly, mirroring networkRequestConnection()'s shape, with a new
saveUpdate() (wired into engineUpdate()) pumping the active op each frame.
Linux/Dolphin behavior is unchanged - their fallback path in save.c still
completes synchronously, just via an immediate callback call instead of a
direct return.

Two real bugs found via PPSSPP testing (not just code review): SAVE/LOAD
modes show a confirm screen even for brand-new data, which blocks forever
headlessly - switched to AUTOSAVE/AUTOLOAD, which write/read silently and
generate the identical PARAM.SFO. And PPSSPP's dialog status goes straight
from QUIT to NONE without a separately observable FINISHED in between,
which the first version misread as "disappeared without a result" even on
a successful save - fixed by tracking whether QUIT was already seen.

Confirmed end-to-end in PPSSPP: write, dialog completes, PARAM.SFO +
encrypted save.bin appear on the virtual memory stick, and a subsequent
load decrypts/deserializes back to the exact original data. Not tested on
real PSP hardware.
2026-08-04 09:54:45 -05:00
YourWishes 24badd06a5 Add player name field to save file, save it out as a round-trip test
Adds savefile_t.playerName (SAVE_PLAYER_NAME_MAX) serialized via the
existing saveFileReadString/WriteString helpers, and stamps + saves it in
rpgInit() as a test that the save system now persists actual game data,
not just the header/version. Verified manually: written bytes end in
"Dusk\0" immediately after the version field, and loading it back returns
the same string.
2026-08-04 08:59:29 -05:00
YourWishes 7a03ef8eaf Re-enable save system, fix header/version stamping, handle missing media
- Fixed the actual reason saving never worked on any platform: saveWrite()
  never stamped file->header/file->version before serializing, so every
  written save file had a zeroed magic header and failed its own
  validation on the next load. Confirmed via a manual write/load round
  trip that this alone fully explains "saving doesn't work."
- Re-enabled saveInit()/saveDispose() in engine.c (previously commented out
  under "Temporarily disable save code").
- Added SAVE.available + saveIsAvailable(), refreshed by every real
  save/load/delete attempt. saveInit() no longer treats an unreachable
  save medium as fatal to booting - it logs and continues, since a missing
  memory card/stick shouldn't prevent playing.
- Hardened PSP's saveInitPSP() to actually detect a missing memory stick
  (sceIoGetstat on ms0:/) instead of assuming success, and fixed
  single-level sceIoMkdir to build the full PSP/SAVEDATA directory chain.
- Added busy-retry (CARD_ERROR_BUSY) and a not-mounted guard to Dolphin's
  live savestreamdolphin.c path, extending the same handling already
  backported into savedolphin.c.
- Added a "Save" entry to the game menu wired to saveWrite(0), showing a
  clear message on success, on failure, and when saveIsAvailable() is false.
2026-08-04 08:30:24 -05:00
YourWishes f3ea507313 Fixed save crash
Backported from branch ac2 (commit 85b61097) - CARD_Mount was being called
without CARD_Init first, leaving per-channel control blocks and the DSP
unlock sequence unset. On real Dolphin/hardware this surfaced as a hard
MMIO crash instead of a clean CARD_ERROR_* failure.

Co-Authored-By: Dominic Masters <dominic@domsplace.com>
2026-08-04 08:12:57 -05:00
YourWishes 4b0388a0e1 Chunk streaming concurrency, entity slot fix, and map-data-driven spawns
- Allow 2 chunks to be mid-load concurrently instead of 1 (MAP_CHUNK_LOAD_CONCURRENCY).
- Fix entitySetChunk silently losing track of an entity when its target chunk's
  entity slots are full - it now stays detached (and retries later) instead of
  claiming a chunk that never actually registered it.
- DCF format bumped to v5: chunks can now declare entity spawns (global/NPC via
  the existing entityglobal registry, or one-shot item pickups) and map area
  triggers, resolved via a new callback-ID registry (mapareagloballist.h)
  mirroring the entity one. rpg.c's hardcoded TEST entity/item/area spawns are
  gone - chunk_0_0_0.json now carries that data instead. The player is still
  bootstrapped in code since it isn't map-authored content.
2026-08-04 07:37:48 -05:00
YourWishes a84137b5ff del md 2026-08-04 06:58:03 -05:00
709 changed files with 27429 additions and 26567 deletions
-858
View File
@@ -1,858 +0,0 @@
# Dusk Code Check
A working checklist for walking through `src/dusk/` (the core, platform-
agnostic engine layer) one subsystem at a time and reviewing how it
actually looks today -- not just what it's supposed to do. Pairs with
`STATUS.md` (maturity snapshot) and `ROADMAP.md` (forward-looking work);
this doc is about auditing what's already there.
Each section below: **Purpose**, **Key files**, and a **Review status**
line to fill in as each system gets walked through (e.g. `Not started` /
`In progress` / `Reviewed 2026-08-01: <one-line finding>`).
First full pass completed 2026-08-01 (all 23 sections below reviewed).
See "Top cross-cutting findings" right after the index for the
highest-priority items across all of them before diving into any one
section -- this doc is long, don't make someone read all 23 to find
the load-bearing bugs.
Game-specific code lives in `src/duskrpg/` (not covered here) and
platform-specific implementations live in `src/dusk<platform>/` /
`src/duskgl/` / `src/dusksdl2/` (also not covered here) -- see `CLAUDE.md`
for the layer structure.
---
## Index
- [error](#error)
- [assert](#assert)
- [util](#util)
- [event](#event)
- [time](#time)
- [thread](#thread)
- [log](#log)
- [system](#system)
- [console](#console)
- [asset](#asset)
- [locale](#locale)
- [save](#save)
- [network](#network)
- [display](#display)
- [ui](#ui)
- [entity](#entity)
- [scene](#scene)
- [physics](#physics)
- [animation](#animation)
- [script](#script)
- [input](#input)
- [engine](#engine)
- [game](#game)
---
## Top cross-cutting findings
Ranked roughly by real-world impact, not by section order. Each links
to its full writeup below.
1. **Bounds/capacity checks that matter at runtime are `assert*` calls,
which compile to no-ops in release (`DUSK_ASSERTIONS_FAKED`, set
whenever `NDEBUG` is defined) -- confirmed by reading `assert.h`
directly.** This shows up in [entity](#entity) (`entitymanager.c`,
`component.c` -- reachable from JerryScript via `moduleentity.c`
with no return-value check) and [scene](#scene) (`sceneCreate`'s
pool-exhaustion path, reachable from `new Scene()`). Untrusted
script input can silently get back an invalid ID that later indexes
a fixed array out of bounds in a release build -- the exact
"validate untrusted data with errorThrow, not asserts" case
CLAUDE.md/project memory already calls out, just not applied here.
2. **FIXED 2026-08-01.** `util/ref.c`'s `refUnlock` decremented an
unsigned `count` guarded only by a tautological `count >= 0` assert
([util](#util)) -- a double-unlock silently underflowed to
`UINT32_MAX` instead of tripping an assert. This wasn't just a
`util/` nit: it's the lock/unlock primitive `asset/loader/assetentry.c`
builds on (see [asset](#asset)), so an over-unlocked asset entry
became permanently un-reapable rather than erroring loudly. Now
asserts `count > 0` before decrementing; the pointless
`count >= 0` check in `refLock` was removed too.
3. **`texture.c:42-52`'s `textureInit()` reads `texture->format` to
decide which `data` fields to validate *before* the struct is
zeroed a few lines later** ([display](#display)) -- it's validating
whatever stale value happened to be in the caller's (possibly
stack) memory, not the `format` parameter actually being requested.
4. **FIXED 2026-08-01 (confirmed real before fixing).** PSP's
`timeGetRealTimeZonePSP` returned hours; every other platform
(`timeGetRealTimeZoneLinux`/Dolphin) returns seconds, and
`timeEpochInit`/`timeEpochGetHours` etc. add the timezone value
directly to a Unix-epoch-seconds timestamp -- confirmed by reading
all three platform implementations plus `timeepoch.c` directly, not
just trusting the review agent's claim. The PSP function's own
comment even said "Return timezone offset in hours". Now divides by
`1000000.0` only (microseconds -> seconds), matching the other
platforms. See [time](#time).
5. **Discussed, not changed.** `consolePrint` aborts the process (via
`stringFormatVA`'s `assert(ret < destSize)`) instead of truncating
when a single debug line exceeds 511 bytes. This is a real, if rare,
crash risk (any format producing >511 bytes of runtime-variable
content -- a long path, a long error string -- takes the whole
process down over a debug print), but changing `stringFormatVA`
itself would affect every caller in the codebase, and a
console-local truncating rewrite is easy to do wrong (vsnprintf
directly, bypassing the project's string-utils convention) without
more time to get right. Left as-is pending a decision on which
fix shape is wanted. See [console](#console).
6. **FIXED 2026-08-01.** `thread.c`'s `threadHandler` signaled
`THREAD_STATE_STOPPED` before resetting `threadId = 0`, and
`threadStartRequest` wasn't synchronized against that reset -- a
real (if rare-window) race, not hypothetical: the test suite was
already working around it by re-calling `threadInit()` instead of
exercising true stop/start reuse. `threadId` is now reset inside the
same mutex-locked section before the STOPPED signal/unlock;
`test_thread_restart` now loops 20x on the same `thread_t` without
re-initializing, which would have caught the old race. See
[thread](#thread).
7. **FIXED 2026-08-01.** `tools/color.py` emitted invalid C float
literals (`0f`, `1f`, etc.) for any whole-number CSV channel --
confirmed by actually running the generator against `color.csv`
before and after. Was dormant only because `COLOR_*_3F`/`_4F` were
unreferenced anywhere in the repo; the first real use of a float
color variant wouldn't have compiled. Now routes channel values
through Python `float()` before interpolating (always stringifies
with a decimal point, e.g. `0.0`/`1.0`), and `test/display/test_color.c`
gained two tests that reference `COLOR_BLACK_3F`/`COLOR_WHITE_4F`/
`COLOR_RED_3B`/`COLOR_GRAY_3F` directly -- giving the previously-dead
generated macros real compile-time + value coverage instead of
silently bit-rotting again. See [display](#display).
8. **`assetModelLoaderAsync` is confirmed fully dead** -- model loading
is genuinely synchronous end-to-end (verified by tracing the state
machine, not just repeating STATUS.md's claim). See [asset](#asset).
9. **No cycle guard on prefab `extends` chains** in
`scenePrefabResolveAndApply` -- a self-referencing or A->B->A prefab
table is a stack-overflow crash from what looks like a harmless
typo in hand-authored data. See [scene](#scene).
10. **Untested-code hot spots worth prioritizing** if test investment
is on the table: `util/ref.c`/`random.c`/`crypt.c`/`endian.c`
(zero tests), `animation/easing.c` (13 of 16 functions untested),
`event/`, `console/`, `system/`, `log/`, `input/`, `engine/`,
`locale/`, `save/`, and most of `display/` (mesh, shader, texture,
tileset, text, screen, framebuffer) have no dedicated tests at
all.
Convention-only items (real, but lower stakes than the above): raw
stdlib string functions (`strlen`/`strchr`/`strstr`/etc.) show up
instead of `util/string.h` wrappers in `network/http/` and
`asset/loader/locale/assetlocaleloader.c` ([network](#network),
[asset](#asset)); several `display/mesh/` files use `//` header
comments and `/* */` inline comments where CLAUDE.md wants the
opposite ([display](#display)); `animation/`'s core files all use `//`
copyright headers instead of `/** */` ([animation](#animation)).
---
## error
**Purpose:** The engine's single error-handling convention. Every
fallible function returns `errorret_t`, built with `errorOk()` /
`errorThrow(fmt, ...)` / `errorChain(call)` and consumed with
`errorIsOk()`/`errorIsNotOk()`/`errorCatch()`. No `errno`, no raw error
codes anywhere else in the engine.
**Key files:** `error.c/h`.
**Review status:** Reviewed 2026-08-01. Solid, and tested unusually well
(`test/error/test_error.c` covers thread isolation and concurrent
throws, not just happy path). Two issues: `errorChainImpl` (error.c:86-91)
hand-rolls `snprintf`/`strlen` instead of `util/string.h`'s
`stringFormat`/`stringFormatVA` wrappers that `errorThrowImpl` uses one
function above it -- an inconsistency, not just a style nit, since
CLAUDE.md requires the wrappers everywhere. `errorThrowWithCode`
(error.h:100) is dead code -- zero call sites anywhere in `src/`/`test/`.
---
## assert
**Purpose:** Debug-time invariant checks -- `assertNotNull`, `assertTrue`,
`assertFalse`, `assertUnreachable`, `assertIsMainThread`. Distinct from
`error/`: asserts are for programmer mistakes/invariants, `errorret_t` is
for runtime-recoverable failures (see `CLAUDE.md`'s note on validating
untrusted data with `errorThrow` rather than asserting).
**Key files:** `assert.c/h`.
**Review status:** Reviewed 2026-08-01. Clean, no issues found. Impl
functions + macros wrapping `__FILE__`/`__LINE__` and a proper
`DUSK_ASSERTIONS_FAKED` no-op path for release builds;
`assertNotNullImpl` (assert.c:109-111) does a real "touch" dereference
after the null check as a belt-and-braces addition. Test coverage
exercises both success and `expect_assert_failure` failure paths for
every variant, including `assertDeprecated`/`assertIsMainThread`.
---
## util
**Purpose:** Small stand-alone helpers with no engine-state dependencies:
`array` (dynamic array), `crypt` (hashing/checksum), `endian` (byte-order
swap), `math` (clamp/lerp/pow2/etc.), `memory` (`memoryAllocate`/`Free`/
`Zero`/`Copy`/`Compare` -- the only allocator the rest of the engine is
allowed to call directly), `random`, `ref` (refcounted handle with
lock/unlock callbacks), `sort` (bubble sort used for one-time static list
ordering), `string` (`stringCopy`/`Compare`/`Format`/etc. -- required in
place of libc `str*` functions per `CLAUDE.md`).
**Key files:** `array.c/h`, `crypt.c/h`, `endian.c/h`, `math.c/h`,
`memory.c/h`, `random.c/h`, `ref.c/h`, `sort.c/h`, `string.c/h`.
**Review status:** Reviewed 2026-08-01. Several real issues, worst was
in `ref.c`: `refUnlock` (ref.c:37-39) decremented `count` (`uint32_t`)
guarded only by `assertTrue(ref->count >= 0, ...)` -- tautologically
always true on an unsigned type, so a double-unlock silently underflowed
to `UINT32_MAX` and kept invoking `onUnlock` instead of tripping an
assert (confirmed by reading ref.c directly). **Fixed 2026-08-01** --
`refUnlock` now asserts `count > 0` before decrementing; also fixed
`refInit`'s doc comment, which claimed a fresh ref starts at count 1
when the code has always started it at 0. Same tautological unsigned
`>= 0` assert remains in `memory.c:98` (lower stakes -- `memoryFree`'s
own counter, not a shared lock/unlock primitive other subsystems build
on -- left as-is). `memory.h:11` declares
`static size_t MEMORY_POINTERS_IN_USE = 0;` directly in the header --
confirmed present -- meaning every TU including it gets its own private
copy (only "works" because the accessors all live in memory.c).
`random.c`'s `randomInt` (confirmed, random.c:15-16) does
`rand() % (max - min)` with no `max > min` check (UB on `max <= min`),
and `srand()` is never called anywhere in the repo -- unseeded,
deterministic RNG. `sort.c:1` has `#include <stdlib.h>` before the
copyright header (confirmed). Test coverage: array/math/memory/sort/
string are thorough; `ref.c`, `random.c`, `crypt.c`, `endian.c` have
**zero** tests. `randomInt`/`randomFloat` also appear unused
engine-wide (dead code, not just untested).
---
## event
**Purpose:** Generic pub/sub primitive -- `event_t` wraps a caller-owned
array of `eventcallback_t`/user-pointer pairs; `eventInit`/`eventSubscribe`/
`eventInvoke`. Used for things like `uifullbox_t`'s transition-end
callback and `uiloading_t`'s show/hide callbacks. Per `STATUS.md`: "Clean,
small, finished", built to replace the old input system's callback
pattern.
**Key files:** `event.c/h`.
**Review status:** Reviewed 2026-08-01. Well-formed -- correctly uses
swap-with-last for O(1) unsubscribe, asserts on capacity overflow and
duplicate-subscribe, no dead code (`eventUnsubscribe` used in 3 other
files). No `errorret_t` needed here since these are programmer-error
assertions rather than runtime-data validation, consistent with
CLAUDE.md's assert-vs-error guidance. One gap: `test/event/` doesn't
exist -- zero unit coverage, including the capacity-exceeded and
double-subscribe assert paths.
---
## time
**Purpose:** Frame delta/elapsed time (`TIME.delta`, exposed to JS via
`moduleTime`) plus `timeepoch_t` wall-clock timestamps (used by
`uifps.c` for the FPS counter).
**Key files:** `time.c/h`, `timeepoch.c/h`.
**Review status:** Reviewed 2026-08-01. `time.c:52-56` unconditionally
formats an epoch string into a 256-byte stack buffer every single
`timeUpdate()` call purely to feed a commented-out `consolePrint` --
burns the leap-year/day-counting loop three times a frame for a
discarded value. `timeepoch.c`'s day-counting loops have no
handling/guard for negative epoch/timezone values (pre-1970). Test
coverage is solid for `time.c` (mocked ticks, boundary/backwards-time
cases) but `timeepoch.c`'s date math (leap year, rollover, format
specifiers) has no dedicated tests despite being the more bug-prone
half. The PSP-specific timezone unit bug flagged in the cross-cutting
findings (#4) was confirmed and fixed 2026-08-01 --
`timeGetRealTimeZonePSP` was returning hours where `timeepoch.c`
expects seconds.
---
## thread
**Purpose:** Thin cross-platform thread/mutex/thread-local wrappers.
Used by the asset system's background loading and the POSIX console's
input-polling thread.
**Key files:** `thread.c/h`, `threadmutex.c/h`, `threadlocal.h`.
**Review status:** Reviewed 2026-08-01. Conventions followed
throughout. Real race condition, **fixed 2026-08-01**: `threadHandler`
used to unlock `stateMutex` and signal `THREAD_STATE_STOPPED` *before*
resetting `thread->threadId = 0`, but `threadStartRequest` asserts
`threadId == 0` with no synchronization against that reset --
`threadStop()` immediately followed by `threadStart()` on the same
struct could intermittently trip the assert. Telling sign it was real,
not theoretical: `test/thread/test_thread.c` already re-called
`threadInit()` before restarting specifically "so threadId/state are
reset" -- the test suite was working around the bug rather than
exercising true reuse. `threadId` is now reset inside the same
mutex-locked section, before the signal/unlock; the test now loops
stop/start 20x on the same `thread_t` with no `threadInit()` in
between. Otherwise test coverage is good (real pthreads, try-lock
coordination, a 4-thread x 10k-iteration mutex contention test).
---
## log
**Purpose:** `logDebug`/`logError` -- the engine's only print/debug-output
path. Header-only declarations; each platform provides the actual
implementation (see `src/dusk<platform>/log/`).
**Key files:** `log.h` (declarations only, no `.c` in core).
**Review status:** Reviewed 2026-08-01. Clean 2-function API; all
three platform implementations (`dusklinux`, `duskpsp`, `duskdolphin`)
match the declared signatures with correct `va_copy` usage for the
dual stdout+file writes. Dolphin's `logError` correctly falls back to
raw VIDEO/console init when the framebuffer isn't ready yet and blocks
on a START-button dismiss loop; PSP writes to
`ms0:/PSP/GAME/Dusk/*.log`. No bugs found. No `test/log/` exists --
understandable for I/O/side-effect code, but zero coverage.
---
## system
**Purpose:** Very early engine init (`systemInit`), the
`systemplatform_t` enum (via the `systemplatformlist.h` X-macro pattern),
and native OS dialog boxes (`systemdialogtype_t`: render-blocking vs
tick-blocking).
**Key files:** `system.c/h`, `systemplatformlist.h`.
**Review status:** Reviewed 2026-08-01. X-macro platform enum and
compile-time `#error` guards for missing platform macros used
correctly; all three platforms define the required
`systemInitPlatform`/`systemGetActiveDialogTypePlatform`/
`systemGetCyclesPlatform`. Dead code confirmed: `systemPSPGetLanguage()`
(`duskpsp/system/systempsp.c:51`) and `systemGetLanguageDolphin()`
(`duskdolphin/system/systemdolphin.c:40`) are defined but never called
anywhere -- likely intended for locale wiring that hasn't landed. No
`test/system/` exists.
---
## console
**Purpose:** In-engine dev console: fixed-size scrollback
(`CONSOLE_HISTORY_MAX` lines x `CONSOLE_LINE_MAX` chars), `consolePrint`,
a `dirty` flag consumers (namely `ui/debug/uiconsole.c`) watch to know
when to rebuild their own cached representation. POSIX builds also poll
stdin on a background thread for interactive script execution.
**Key files:** `console.c/h`, `consoledefs.h`.
**Review status:** Reviewed 2026-08-01. Two real issues. `consolePrint`
(console.c:32-44) gets its length from `stringFormatVA(buffer,
CONSOLE_LINE_MAX, ...)`, and `stringFormatVA` (util/string.c:100)
**asserts** `ret < destSize` rather than truncating -- so any single
debug line over 511 bytes aborts the process instead of just getting
cut off, a harsh failure mode for a dev console. Separately,
`consoleUpdate`'s doc ("Processes pending queued script lines") and
`CONSOLE_EXEC_BUFFER_MAX` (consoledefs.h:12) describe a queued-script-
execution feature that doesn't exist -- `console_t` has no exec-queue
fields, `consoleUpdate` only toggles `visible`, and
`CONSOLE_EXEC_BUFFER_MAX` is unreferenced elsewhere (dead constant,
stale doc). No `test/console/` exists.
---
## asset
**Purpose:** The asset pipeline: `dusk.dsk` zip archive reading
(`assetfile.c/h`), lock/ref-counted entries (`asset/loader/assetentry.c/h`,
built on `util/ref.h`), batch loading (`assetbatch.c/h`), and the loader
registry (`asset/loader/assetloader.c/h`, plus one subfolder per loader
type: `dmf/` mesh+model, `display/` texture+tileset, `locale/`, `json/`,
`animation/`). See `CLAUDE.md`'s "Adding a new asset loader type" for the
extension pattern. Per `STATUS.md`: model loading's "async" path is
actually synchronous -- the one known stub in core.
**Key files:** `asset.c/h`, `assetfile.c/h`, `assetbatch.c/h`,
`loader/assetentry.c/h`, `loader/assetloader.c/h`.
**Review status:** Reviewed 2026-08-01. Core is well-structured and the
multi-pass reaper correctly handles parent/child dependency chains.
Found: `assetFileInit` (assetfile.c:29) has `if(!zip_stat(...) == 0)` --
precedence makes this `(!zip_stat(...)) == 0`, which happens to
evaluate correctly for zip's 0/nonzero convention but reads as broken
and should just be `zip_stat(...) != 0`. More seriously,
`assetEntryLock`/`Unlock` sit on top of `util/ref.c`'s confirmed
double-unlock underflow bug (see **util** above) -- an over-unlocked
asset entry silently becomes un-reapable forever instead of asserting.
**Confirmed via code-trace** (not just citing STATUS.md):
`assetModelLoaderAsync` (assetmodelloader.c:19-23) is genuinely dead --
`assetEntryStartLoading` unconditionally sets
`ASSET_ENTRY_STATE_PENDING_SYNC`, and `assetModelLoaderSync`'s state
machine never transitions to `PENDING_ASYNC` the way mesh/texture/
tileset/locale/json/animation all do, so model loading runs fully
synchronously via `assetRequireLoaded`'s busy-loop; grep confirms
`assetModelLoaderAsync` has no callers. `assetlocaleloader.c` uses raw
stdlib (`strstr`/`strncmp`/`strchr`/`strtol`/`atoi`) instead of
`util/string.h` wrappers throughout, and tests line-prefixes via
`memoryCompare(lineBuffer, "msgid", 5)` without confirming the reused
stack buffer actually holds 5 valid bytes at that point -- a short line
could spuriously prefix-match against stale buffer contents. Test
coverage: good breadth for entry lifecycle, tileset/JSON/animation
loaders, and locale parsing; no dedicated tests for mesh/model/texture
loader internals or `assetfile.c`'s line reader.
---
## locale
**Purpose:** Active-locale tracking (`LOCALE.locale`/`LOCALE.entry`) over
`.po`-derived locale assets loaded through the asset system. See
`assets/locale/en_US.po` -- per memory, currently placeholder/test
content, not real shipped game text.
**Key files:** `localemanager.c/h`, `localeinfo.h`.
**Review status:** Reviewed 2026-08-01. Clean, no bugs found --
correctly balances `assetEntryLock`/`Unlock` in both `SetLocale` and
`Dispose` (unlocks the old entry before adopting the new one). Minor
nit: `localeinfo.h` declares `static const localeinfo_t` globals
(`LOCALE_EN_US` etc.) directly in the header, so every including TU
gets its own duplicate copy -- harmless given how few TUs include it.
No `test/locale/` directory; `test/asset/test_assetlocale.c` tests the
loader, not `localemanager.c` itself.
---
## save
**Purpose:** Slot-based save data (`SAVE_FILE_COUNT_MAX` fixed slots),
yyjson documents persisted with size + CRC32 checksum. `saveLoad`/
`saveSave` read/write JSON fresh every call; callers own the returned
doc and must free it. Actual file I/O goes through platform stream hooks
(`saveplatform_t`, one impl per platform) -- core `save.c` must never
touch the filesystem directly. `savesettings.c/h` layers engine settings
(display/audio/input/general) on top. Per `CLAUDE.md`: "mature, but
undocumented" beyond the one paragraph there -- no tests.
**Key files:** `save.c/h`, `savefile.h`, `savestream.c/h`,
`savesettings.c/h`.
**Review status:** Reviewed 2026-08-01. Clean and convention-compliant
-- `save.c` genuinely never touches the filesystem directly (every I/O
path goes through `saveXxxPlatform` macros, all three platforms define
them), yyjson doc ownership is honored at every call site checked, and
CRC32 is validated before parsing with every error path freeing `buf`.
One real gap: `saveFileLoad`'s `memoryAllocate(file->size)`
(savestream.c:122) allocates straight from an on-disk size field with
no sanity bound before the allocation -- a corrupted/tampered save
could request an oversized allocation, worth a max-size guard given the
"never trust incoming data" principle (arguably applies to save files,
not just network packets). Confirmed no `test/save/` exists. `saveDelete`/
`saveExists`/`saveGet` are public API not yet called anywhere in the
repo -- likely just unconsumed so far, not truly dead.
---
## network
**Purpose:** Connection-state layer only (`networkstate_t`:
`DISCONNECTED`/`CONNECTING`/`CONNECTED`/`DISCONNECTING`) plus a one-off
HTTP client (`network/http/`: request/header/URL/thread/process split
across files). **Not** a multiplayer/replication protocol yet -- that's
`ROADMAP.md` items 8-17. Platform-specific connection polling (PSP's
`sceNetApctl`, GameCube/Wii's `if_config()`) lives under
`src/dusk<platform>/network/`. Has HTTP tests only (`test/network/http/`).
**Key files:** `network.c/h`, `networkinfo.c/h`, `http/networkhttp.c/h`,
`http/networkhttprequest.c/h`, `http/networkhttpthread.c/h`.
**Review status:** Reviewed 2026-08-01. Genuinely stays a thin
connection-state layer (grepped for "packet"/"replicat"/"multiplayer"/
"udp" -- no hits, no scope creep). The HTTP client correctly validates
untrusted server input with `errorThrow` rather than trusting it
(malformed status lines, oversized headers, bad `Content-Length`,
early-closed connections all throw) -- exactly what CLAUDE.md calls
out. `networkhttpthread.c`'s request handoff is actually correct
despite request fields being written outside the mutex: the final
`state = PENDING` write happens under the same mutex the worker
acquires, giving a valid release/acquire handoff (worth a comment, not
a bug). One recurring convention violation:
`networkhttpprocess.c`/`networkhttpurl.c` use raw stdlib
`strlen`/`strchr`/`strstr`/`strncasecmp`/`strcspn` instead of
`util/string.h` wrappers in several places -- `util/string.h` currently
has no direct substitute for `strchr`/`strstr`/`strcspn`, so this may
be a missing-utility gap rather than pure oversight. No leaks found
(request/response bodies freed exactly once via
`networkHttpRequestReset`, redirect loop frees the intermediate body).
Real test coverage exists: `test/network/http/test_networkhttp.c` runs
six tests against a fake loopback server (GET/POST/PUT, query encoding,
redirects, connection-refused), each asserting zero leaked allocations.
---
## display
**Purpose:** The engine's most mature, most-optimized subsystem --
platform-agnostic rendering built on top of `duskgl`/`duskdolphin`.
Subfolders: `mesh/` (primitive builders: cube/sphere/capsule/plane/
triprism/quad, plus the shared `meshvertex_t`/`mesh_t` API), `shader/`
(currently one material type, unlit), `spritebatch/` (the shared
`SPRITEBATCH_SPRITES_MAX`-capacity quad batcher everything 2D goes
through -- flushes on shader/material change), `texture/` (texture +
tileset + palette), `text/` (`font_t`/`FONT_DEFAULT`'s baked-in bitmap
glyphs, `textBuildSpriteCache`/`textDrawSpriteCache`'s build-once/
translate-per-frame pattern), `screen/` (scan-safe area), `framebuffer/`.
`color.csv` + `tools/color/csv/__main__.py` code-generate `color.h` --
never hand-edit the generated header.
**Key files:** `display.c/h`, `mesh/mesh.c/h`, `spritebatch/spritebatch.c/h`,
`spritebatch/spritebatchsprite.c/h`, `text/font.c/h`, `text/text.c/h`,
`texture/texture.c/h`, `texture/tileset.c/h`, `shader/shader.c/h`.
**Review status:** Reviewed 2026-08-01. "Most mature" oversold it
slightly -- real bugs found, several confirmed by direct read:
- **texture.c:42-52 (confirmed)** -- `textureInit()` branches on
`texture->format` to validate the incoming `data` union *before*
`memoryZero(texture, ...)` runs a few lines later, so it's reading
whatever stale/uninitialized value was already in the caller's
struct, not the `format` parameter actually being requested.
Validation is effectively checking garbage.
- `spritebatchsprite.c:20-25` -- `spriteBatchSpriteTilesetPosition`'s
zero-width/height early return zeroes `sprite.min`/`max` but leaves
`uvMin`/`uvMax` uninitialized (stack garbage); the existing
zero-size test doesn't check uv fields, so this isn't caught.
- `mesh.c:43` -- `meshFlush`'s offset assert (`vertexOffset <
vertCount - 1`) wrongly rejects a valid offset at the very last
vertex; off-by-one.
- `text.c:34-37` -- bounds assert uses `tileIndex <= tileCount`
(should be `<`), currently unreachable in practice since a preceding
clamp already guards it, but the assert itself is wrong.
- `framebuffer.c:23-28` -- `frameBufferBind(NULL)` recurses into
binding the backbuffer without `errorChain`, discarding any failure
and unconditionally returning `errorOk()`.
- `displayInit()`'s six static "SIMPLE" primitive meshes
(quad/cube/sphere/plane/capsule/triprism) are never disposed in
`displayDispose()` -- one VBO+VAO leaked per primitive on the
non-legacy GL path.
- **Confirmed and fixed 2026-08-01.** `tools/color.py` (not the
`tools/color/csv/__main__.py` path CLAUDE.md's doc comment names --
that's a stale path, only a `__pycache__/` remnant exists there; the
live script is `tools/color.py`) emitted invalid C float literals
for whole-number CSV channels (`0`, `1` -- every black/white/primary
color), e.g. `color3f(0f, 0f, 0f)`. Was harmless *only* because
`COLOR_*_3F`/`_4F` were never referenced anywhere in `src/`/`test/`
-- confirmed by actually running the generator before and after the
fix, not just reading the source. Now routes channel values through
Python `float()` first (always stringifies with a decimal point);
`test/display/test_color.c` gained tests referencing
`COLOR_BLACK_3F`/`COLOR_WHITE_4F`/`COLOR_RED_3B`/`COLOR_GRAY_3F`
directly so the previously-dead macros now have real compile-time +
value coverage.
- Style drift: `mesh.h` uses `//` header comments instead of `/** */`;
sphere/capsule/triprism use `/* */` block comments inside function
bodies where CLAUDE.md mandates `//`; every primitive builder's
JSDoc still documents a `@param color` that no longer exists in the
signature (leftover from before color moved out of `meshvertex_t`).
- The primitive `*Buffer()` flexible-geometry functions (sphereBuffer,
capsuleBuffer, etc.) are confirmed unused outside their own
`*Init()` -- only the fixed default mesh instances are actually
consumed (via `script/module/display/modulemesh.c`).
Test coverage: `test/display/` only registers `test_color.c` and
`test_spritebatchsprite.c` -- mesh/shader/texture/tileset/palette/text/
font/screen/framebuffer all have zero unit tests.
---
## ui
**Purpose:** Flat, static, singleton-driven widget framework -- no scene
graph. Top level is a compile-time X-macro registry
(`uielementlist.h`/`uielement.c/h`) of `{init, update, draw, dispose,
order}` tuples (screens: frame/confirm/settings/overlays/console/fps),
spliced with `duskrpg`'s own list. Composition below that is `uimenu_t`
(`widget/uimenu.c/h`) -- a flat tagged-union array of widgets laid out in
a simple row/column grid via the `MENU_*` authoring macros; no nesting.
Widgets: `uilabel`/`uiwidgetlabel` (cached glyph sprites, the pattern
every other widget's text now uses), `uibutton`, `uicheckbox`,
`uislider`, `uidropdown`, `uitab`, `uiscrolling` (empty placeholder).
`focus/` is the gamepad/keyboard directional-navigation stack (no mouse/
pointer hit-testing exists anywhere). `frame/` is the 9-slice box plus
the confirm dialog and settings screens. `overlay/` is fullscreen
fades/loading/crop bars. `debug/` is the FPS counter and dev console
renderer.
As of 2026-07-31: slider/tab/frame (`uiFrameDrawCached`)/duskrpg's
textbox all cache their sprite geometry instead of rebuilding it every
frame; console uses a fixed-size vertex buffer instead of alloc/free.
Still open: sprite-batch flushes are keyed on material/color, so
per-widget highlight-color changes still force a flush per widget (see
`ROADMAP.md` item 5 in the debt backlog). No JS bindings exist for UI
yet. `test/ui/`/`test/display/test_spritebatchsprite.c` cover the new
caching *logic* only -- nothing exercises real `uiXxxDraw()` calls, since
those need a live GL context (`FONT_DEFAULT`/`UI_FRAME` textures) this
repo's test binaries don't have.
**Key files:** `ui.c/h`, `uielement.c/h`, `focus/uifocus.c/h`,
`widget/uimenu.c/h`, `widget/uilabel.c/h`, `frame/uiframe.c/h`,
`debug/uiconsole.c/h`.
**Review status:** Reviewed 2026-07-31 (this session's sprite-caching
pass) -- see notes above; per-material flush granularity and hit-testing
still open.
---
## entity
**Purpose:** Fixed-size-array ECS. `entitymanager_t` owns
`ENTITY_COUNT_MAX` entities, each with up to `ENTITY_COMPONENT_COUNT_MAX`
components stored in a tagged union (`componentdata_t` -- flagged in
`PSP_OPTIMIZATION_PLAN.md` as the biggest PSP memory-waste candidate,
since every entity reserves space for every component type's largest
variant). `componentlist.h`'s `X()` macro auto-generates the component
enum/union/dispatch table from `entity/component/**`; engine-level
`entityprefablist.h` is an empty sentinel (real prefabs live in
`duskrpg/entity/entityprefablist.h`, resolved via
`entityPrefabResolveAndApply`). No JSON serialize/deserialize (removed by
design in favor of C-coded prefabs or JerryScript `Entity`/`Component`).
**Key files:** `entitymanager.c/h`, `entity.c/h`, `component.c/h`,
`componentlist.h`, `entityprefab.c/h`.
**Review status:** Reviewed 2026-08-01. Structurally sound (sentinel
prefab list, X-macro shape both match CLAUDE.md), but there's a real
security-relevant gap: **every capacity/bounds guard
(`entitymanager.c:35`, `entity.c:56`, `component.c:37-39,58-62,75-76,
140-141`) is an `assert*` call**, and `assert.h` compiles these to
`((void)0)` under `DUSK_ASSERTIONS_FAKED` (auto-set whenever `NDEBUG`
is defined -- confirmed by reading assert.h directly, this is a real
release-mode no-op, not a hypothetical). `moduleentity.c:30,67` create
entities/components from JerryScript with no return-value check, so a
script that exceeds `ENTITY_COUNT_MAX`/the per-entity component cap
silently gets back an invalid ID in release builds, which then indexes
fixed arrays out-of-bounds later. This directly contradicts the
project's own "untrusted-data limits need errorThrow, not asserts"
guidance -- and script input is about as untrusted as it gets. Minor:
`component.h:100`/`component.c:52` misplace the `*` in `void *
componentGetData(`. Dead code: `entityUpdateRemove`/
`entityDisposeRemove`/`entityDisposeAdd` have zero call sites.
---
## scene
**Purpose:** Same shape as `entity/` one level up -- `SCENE_COUNT_MAX`
fixed-count scenes, each an isolated entity-manager pool; engine-level
`sceneprefablist.h` is an empty sentinel (real prefabs in
`duskrpg/scene/`). As of the `Scene.set()` work (2026-07-31), JerryScript
can install a `{init, update, dispose}` module as the active scene via
`modulescene.c`'s `moduleSceneSetStatic`/`moduleSceneUpdateCurrent`/
`moduleSceneTeardownCurrent` (see `script` below) -- scene IDs are reused
from a small pool immediately after `sceneDestroy`, so don't assume a
freshly created scene has a "new" ID.
**Key files:** `scene.c/h`, `scenebase.h`, `sceneprefab.c/h`.
**Review status:** Reviewed 2026-08-01. Shares entity/'s assert-not-
errorThrow bounds gap (`sceneCreate` hits `assertUnreachable` then
falls through to `SCENE_ID_INVALID` on pool exhaustion in release --
reachable from `new Scene()` in JS). Additional finding:
`scenePrefabResolveAndApply`/`scenePrefabInit` (sceneprefab.c:31-54)
recurse through a prefab's `extends` chain with **no cycle guard** -- a
self-referencing or A→B→A prefab table causes unbounded recursion/
stack overflow from what's otherwise a one-typo mistake in a
hand-authored prefab list. No dead code, no use-after-free. Tests cover
create/destroy/isolation/update cadence well but have zero coverage for
pool exhaustion, `sceneRender()`, or `sceneprefab.c` (no prefab test
file exists at all).
---
## physics
**Purpose:** `physicsworld_t` step simulation over `physicsbodytype_t`
(static/dynamic/kinematic) and `physicshapetype_t` (cube/sphere/capsule/
plane/custom, plus mesh shapes via `physicsshapemesh.c/h`).
`triggersystem.c/h` layers trigger-volume enter/exit events on top. Per
`STATUS.md`: "mature, recently churned" -- a revert/re-disable of "old
ent code" suggests component wiring isn't fully settled yet. Well
tested (`test/physics/`).
**Key files:** `physicsworld.c/h`, `physicsbodytype.h`, `physicsshape.h`,
`physicsshapemesh.c/h`, `triggersystem.c/h`.
**Review status:** Reviewed 2026-08-01. `STATUS.md`'s "component
wiring isn't fully settled" caveat looks stale on closer look:
`physicsWorldStep`/`triggerSystemStep` are live-wired in `scene.c:89-90`
and `duskrpg`'s player prefab actively uses both PHYSICS and TRIGGER --
no `#if 0`/TODO/commented-out code found; the disable-then-revert in
history reads like a same-day whole-ECS revert, not something
physics-specific. Two real bugs found instead:
`physicsbodytype.h:23-27` documents kinematic bodies as capable of
being a player controller, but `physicsworld.c:124,166-167` only ever
writes `onGround` for the dynamic side of a collision pair -- a
kinematic controller's `onGround` is permanently false (latent today,
since the one existing player prefab uses DYNAMIC, not KINEMATIC).
`physicstest.c:213`'s barycentric interior-test branch has no guard
against a zero-area triangle (divide-by-zero/NaN risk in mesh-sphere
collision). Dead code: `physicsShapeMeshCreate` (mesh-terrain
collision) has zero production callers despite being well-tested in
isolation; `entityPhysicsGetShape`/`GetCollideMask` are unwired to the
JS module. Test depth is genuinely strong for what's implemented
(gravity convergence, dynamic-vs-dynamic separation, mask filtering,
mesh sphere/capsule resting) -- "well tested" is earned for the
features that exist, though the unused mesh-collision path and
missing trigger→JS bridge mean the subsystem's *integration* maturity
is a bit narrower than its test depth suggests.
---
## animation
**Purpose:** Keyframe + easing only -- no blend trees or state machines
yet. `keyframe_t`/`keyframeset_t` interpolate values over time via
`easing.c/h`'s easing functions; `animation.c/h` ties a keyframe set to
playback state. Per `STATUS.md`: terse commit history ("ANIM") suggests
still iterating.
**Key files:** `animation.c/h`, `easing.c/h`, `keyframe.c/h`,
`keyframeset.c/h`.
**Review status:** Reviewed 2026-08-01. All 8 core files use `//`
copyright headers instead of the required `/** */` block, inconsistent
with the correctly-formatted `entityanimation.{c,h}` next door. Math
checks out: all 16 easing functions satisfy f(0)=0/f(1)=1 with no
precision issues, and keyframe interpolation clamps (doesn't
extrapolate) outside the time range with no reachable divide-by-zero
-- though it doesn't validate that keyframe times are ascending. 15 of
16 `easing.h` declarations lack Javadoc. Biggest gap: **no
`test_easing.c` exists** -- only linear/in-quad get incidental coverage
via `test_keyframe.c`, so 13 of 16 easing functions are completely
untested. Dead code (test-only, unused by any `duskrpg` game code):
`keyframeSetGetValues`, `keyframeSetFireCallback`, `animationSetEvent`,
`entityAnimationSetKeyframes`/`GetValue`.
---
## script
**Purpose:** Embedded JerryScript integration. `scriptmanager.c/h` owns
the JerryScript context lifecycle and the exec/call helpers
(`scriptManagerExec`/`ExecFile`/`CallGlobal`/`CallValue`, the last two
sharing exception + promise-draining logic). `scriptproto.c/h` is the
`scriptproto_t` prototype-wrapping helper every module builds on.
`module/` holds each registered JS-facing module:
- `modulebase.h` -- the shared macro toolkit (`moduleBaseFunction`,
`moduleBaseRequireArgs`/`RequireString`/etc., `moduleBaseDefineProp`/
`Func`/`StaticFunc`, `moduleBaseSetWrappedPointer`, `moduleBaseThrowError`).
- `moduleplatform.h`, `entity/moduleentity.c/h` +
`entity/component/*` (generic `Component` plus typed Position/Physics/
Renderable wrappers via `modulecomponentlist.c/h`), `scene/modulescene.c/h`
(`Scene`, including `Scene.set()`), `display/modulemesh.c/h`,
`time/moduletime.c/h`, `require/modulerequire.c/h` (CommonJS-style
`require()`/`module.exports`, with a directory stack for relative
resolution -- `scriptManagerExecFile` now pushes its own file's
directory before exec so a top-level entry script's relative
`require()` calls resolve correctly).
- `modulelist.c/h` -- registers/disposes every module above in order;
`moduleListDispose()` is now actually called from
`scriptManagerDispose()` (was a latent bug -- it wasn't, until
2026-07-31).
Entry point convention: `assets/scripts/init.js` does
`require('./scenefile.js')` + `Scene.set(module)`. Has unit tests
(`test/script/`), including one that reads the real shipped
`overworldscene.js` off disk rather than an embedded copy.
**Key files:** `scriptmanager.c/h`, `scriptproto.c/h`,
`module/modulebase.h`, `module/modulelist.c/h`,
`module/require/modulerequire.c/h`, `module/scene/modulescene.c/h`.
**Review status:** Reviewed 2026-07-31 (this session's Scene.set() +
require()-dir-stack work) -- see notes above.
---
## input
**Purpose:** Bind-based input (`inputaction.c/h` maps
`INPUT_BIND_*` names to raw `inputbutton_t`s per platform), with a
configurable analog deadzone. Platform button/axis backends live under
`src/dusk<platform>/input/`; capability macros (`DUSK_INPUT_GAMEPAD`/
`KEYBOARD`/`POINTER`) gate what's available per target. Pointer axis
values are plumbed through (`DUSK_INPUT_POINTER`), but nothing in `ui/`
consumes them yet -- no hit-testing exists (see `ui` above).
**Key files:** `input.c/h`, `inputaction.c/h`, `inputbutton.c/h`.
**Review status:** Reviewed 2026-08-01. Clean and convention-compliant;
deadzone math (`inputDeadzone`, input.c:244) is correct and safe. One
naming nit: `inputBind`'s param is named `act` in input.h:216 while its
own doc comment calls it `action`. **Confirmed, not just cited from
STATUS.md**: pointer input is genuinely wired end-to-end, not a
dead-end at the platform layer -- SDL2's `inputUpdateSDL2` populates
`INPUT.platform.mouseX/Y`/scroll from `SDL_GetMouseState`,
`inputButtonGetValueSDL2` handles the pointer-axis cases, and
`duskrpg/input/inputbindmap.h` binds `mouse_x`/`mouse_y` to
`INPUT_BIND_POINTERX/Y`. The dead end is specifically at the
*consumption* layer: grepping `src/dusk/ui/` for those binds or any
pointer-axis read turns up nothing -- exactly as STATUS.md says, just
now confirmed rather than assumed. No tests exist for `input/`.
---
## engine
**Purpose:** Top-level init/update/dispose orchestration
(`engineInit`/`engineUpdate`/`engineDispose`) -- the thing `main.c` calls,
which in turn calls into every subsystem above plus `game/gameInit` etc.
`ENGINE.running`/`ENGINE.version` are the only bits of global state
outside the per-subsystem structs.
**Key files:** `engine.c/h`.
**Review status:** Reviewed 2026-08-01, confirmed by direct read of
`engineInit`/`engineDispose`. Init order is safe (time -> console ->
system -> input -> asset -> scriptManager -> save/saveSettings ->
locale -> display -> ui -> network -> scene -> game), with display
before UI and scriptManager before scene/game so JS `Entity`/`Scene`
wrappers exist before any script runs. `engineDispose` is **not** a
clean reverse of that order, though: `localeManagerDispose()` runs
*before* `uiDispose()`/`displayDispose()`, even though locale was
initialized *before* both -- correct reverse order would tear down
UI/display first, and as written there's a real risk of UI/display
teardown code touching already-freed locale data (e.g. any localized
string still held/logged during dispose). Separately, `void
engineExit(void)` (engine.c:95) is defined but **not declared in
engine.h**, and a repo-wide grep finds no caller anywhere -- dead,
unreachable, and in violation of the "every public function must be
declared in its header" rule. No tests exist for `engine/`.
---
## game
**Purpose:** Intentionally header-only in core -- just declares
`gameInit`/`gameUpdate`/`gameDispose`. The real implementation is
`src/duskrpg/game/game.c` (currently: runs `scripts/init.js` on init).
**Key files:** `game.h` (no `.c` in core).
**Review status:** Reviewed 2026-08-01. Confirmed: no `.c` file exists
in `src/dusk/game/` (only `game.h` + `CMakeLists.txt`) -- a pure
interface, as intended. The real `src/duskrpg/game/game.c`
implementation is a thin JS-bootstrap shim: `gameInit` just does
`errorChain(scriptManagerExecFile("scripts/init.js", NULL))`, while
`gameUpdate`/`gameDispose` are both empty (`errorOk()` only). Not a
bug -- consistent with the ongoing migration of game logic into JS --
but worth flagging as "not yet fleshed out" rather than broken if
anything is expected to happen there per-frame at the C layer. No
tests exist for this layer.
-71
View File
@@ -33,74 +33,3 @@ jobs:
libssl-dev
- name: Run tests
run: ./scripts/test-linux.sh
# Emulator smoke tests: boot the built disc/EBOOT for a fixed window and
# confirm the emulator doesn't crash. Not yet verified against a real
# runner (no CI run has exercised these) -- continue-on-error so a
# flaky/broken emulator step doesn't block the required Linux test job.
run-tests-gamecube-dolphin:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ghcr.io/extremscorner/libogc2:latest
steps:
- name: Install Node.js
run: apt-get update && apt-get install -y nodejs
- name: Checkout repository
uses: actions/checkout@v4
- name: Install additional dependencies
run: |
apt-get install -y \
python3-pip python3-polib python3-pil \
python3-dotenv python3-pyqt5 python3-opengl xorriso \
dolphin-emu xvfb
dkp-pacman -Syu --noconfirm
dkp-pacman -S --needed --noconfirm \
gamecube-sdl2 ppc-liblzma ppc-libzip \
gamecube-tools ppc-libmad ppc-zlib-ng ppc-bzip2 ppc-zstd
- name: Build GameCube ISO and boot it in Dolphin
run: ./scripts/test-gamecube-dolphin.sh
run-tests-wii-dolphin:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ghcr.io/extremscorner/libogc2:latest
steps:
- name: Install Node.js
run: apt-get update && apt-get install -y nodejs
- name: Checkout repository
uses: actions/checkout@v4
- name: Install additional dependencies
run: |
apt-get install -y \
python3-pip python3-polib python3-pil \
python3-dotenv python3-pyqt5 python3-opengl xorriso \
dolphin-emu xvfb
dkp-pacman -Syu --noconfirm
dkp-pacman -S --needed --noconfirm \
gamecube-sdl2 ppc-liblzma ppc-libzip \
gamecube-tools ppc-libmad ppc-zlib-ng ppc-bzip2 ppc-zstd
- name: Build Wii ISO and boot it in Dolphin
run: ./scripts/test-wii-dolphin.sh
run-tests-psp-ppsspp:
runs-on: ubuntu-latest
continue-on-error: true
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup pspdev
uses: ./.github/actions/setup-pspdev
- name: Install PPSSPPHeadless build dependencies
run: |
sudo apt-get update
sudo apt-get install -y git cmake ninja-build libsdl2-dev zlib1g-dev
- name: Build PPSSPPHeadless
run: |
git clone --recursive --depth 1 https://github.com/hrydgard/ppsspp.git /tmp/ppsspp
cmake -S /tmp/ppsspp -B /tmp/ppsspp/build -DCMAKE_BUILD_TYPE=Release
cmake --build /tmp/ppsspp/build --target PPSSPPHeadless -- -j$(nproc)
echo "PPSSPP_HEADLESS_BIN=/tmp/ppsspp/build/PPSSPPHeadless" >> "$GITHUB_ENV"
- name: Build PSP EBOOT and boot it in PPSSPPHeadless
run: ./scripts/test-psp-ppsspp.sh
-549
View File
@@ -1,549 +0,0 @@
# Dusk — Claude Code rules
See `STATUS.md` for a periodically-refreshed inventory of subsystem
maturity, test coverage gaps, and known open issues — check it before
assuming a subsystem is fully wired up or before picking a next task.
## File headers
Every C, H, and JS file starts with:
```c
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
```
JS files use `//` comment style instead.
---
## C conventions
### Types
Always use the project-defined aliases instead of bare C primitives:
| Use | Not |
|-----------|--------------|
| `bool_t` | `bool` |
| `int_t` | `int` |
| `float_t` | `float` |
| `char_t` | `char` |
Use `uint8_t`, `uint16_t`, `int32_t`, etc. for fixed-width integers.
All struct and enum types end in `_t` (`animation_t`, `errorret_t`, …).
### Naming
- **Functions** — snake_case, prefixed with their module:
`assetLock()`, `entityPositionInit()`, `moduleAssetBatchCtor()`
- **Struct fields** — camelCase: `keyframeCount`, `localPosition`
- **Macros / constants** — UPPER_SNAKE_CASE:
`ENTITY_ID_INVALID`, `ERROR_OK`, `COMPONENT_TYPE_COUNT`
- **Files** — snake_case matching the primary type: `entityposition.c`,
`moduleassetbatch.c`
### Header files (`.h`)
- Use `#pragma once` — no include guards.
- Declare every public function, `#define`, and `extern` global.
- Write a JSDoc block (`/** … */`) above every declaration explaining
purpose, `@param`s, and `@returns`.
- Only include headers that the `.h` file itself strictly requires for
the types it exposes. Move everything else to the `.c` file.
Do not use forward declarations as a workaround — use the real
include in the `.c` file instead.
### Implementation files (`.c`)
- Contain function bodies only; no declarations.
- Pull in whatever additional includes the implementation needs.
- Do not use `static` or `inline` on **functions**. Every function,
including internal helpers, must be declared in the matching `.h` and
defined in the `.c` file. Internal helpers belong near the bottom of
the `.c` file, not at the top with a `static` qualifier.
`static` and `inline` on functions are only appropriate when the
function body is written directly inside a `.h` file.
`static` on **variables** (file-scope state) is fine and expected.
### Formatting
- Hard-wrap all lines at **80 characters**.
### Error handling
Return `errorret_t` from fallible functions. Use these macros:
```c
errorOk(); // return success
errorThrow("msg %d", val); // return failure with message
errorChain(someCall()); // propagate failure, continue on success
errorIsOk(ret) / errorIsNotOk(ret) // test a result
errorCatch(ret); // handle + free an error
```
Never return raw error codes or use `errno` for in-engine errors.
### Memory
Use the project allocator — never raw `malloc`/`free`:
```c
memoryAllocate(size) // allocate
memoryFree(ptr) // free
memoryZero(dest, size) // zero a block
memoryCopy(dest, src, size) // copy
```
### Asserts
Prefer specific assert macros over bare `assert()`:
```c
assertNotNull(ptr, "msg");
assertTrue(cond, "msg");
assertFalse(cond, "msg");
assertUnreachable("msg");
assertIsMainThread("msg");
```
---
## Build system
Each subdirectory has its own `CMakeLists.txt` that adds sources with:
```cmake
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
myfile.c
)
```
Never add source files to the root `CMakeLists.txt` directly.
---
## Platform support
### Targets
Set `DUSK_TARGET_SYSTEM` at CMake configure time to select a platform:
| `DUSK_TARGET_SYSTEM` | Macro defined | Platform |
|----------------------|-------------------|------------------|
| `linux` | `DUSK_LINUX` | Linux desktop |
| `knulli` | `DUSK_KNULLI` | Knulli (handheld)|
| `psp` | `DUSK_PSP` | Sony PSP |
| `gamecube` | `DUSK_GAMECUBE` | Nintendo GameCube|
| `wii` | `DUSK_WII` | Nintendo Wii |
### Layer structure
```
src/dusk/ core, platform-agnostic game logic
src/duskgl/ OpenGL abstraction (Linux, Knulli, PSP)
src/dusksdl2/ SDL2 window + input (Linux, Knulli, PSP)
src/dusklinux/ Linux + Knulli platform impl
src/duskpsp/ PSP platform impl
src/duskdolphin/ GameCube / Wii platform impl (no SDL2/OpenGL)
```
Dolphin is the only target that bypasses SDL2 and OpenGL entirely —
it uses native GameCube/Wii rendering and input APIs.
### Platform guards
Use the compile-time macros for platform-specific code:
```c
#ifdef DUSK_PSP
// PSP-only path
#elif defined(DUSK_GAMECUBE) || defined(DUSK_WII)
// GameCube / Wii path
#else
// Generic / Linux fallback
#endif
```
Additional capability macros set per-target:
`DUSK_SDL2`, `DUSK_OPENGL`, `DUSK_OPENGL_ES`, `DUSK_OPENGL_LEGACY`,
`DUSK_INPUT_GAMEPAD`, `DUSK_INPUT_KEYBOARD`, `DUSK_INPUT_POINTER`,
`DUSK_PLATFORM_ENDIAN_BIG` / `DUSK_PLATFORM_ENDIAN_LITTLE`.
### Abstraction pattern
Platform-specific implementations are wired in via `#define` macros in
each platform's `displayplatform.h` / `inputplatform.h` etc., which
the core calls through. Functions that a platform does not support are
simply left undefined — the core guards calls with `#ifdef`.
### Adding platform-specific code
- Put it under `src/dusk<platform>/` in the matching subsystem folder.
- Gate any core call-site with the appropriate `#ifdef DUSK_<PLATFORM>`
or capability macro.
- Keep the `src/dusk/` core free of platform ifdefs — delegate through
the platform header macros instead.
---
## Adding a new asset loader type
1. Add an enum value to `assetloadertype_t` (before `_COUNT`) in
`src/dusk/asset/loader/assetloader.h`.
2. Add fields to the input/loading/output unions in `assetloader.h`.
3. Implement `assetXxxLoaderSync`, `assetXxxLoaderAsync`, and
`assetXxxDispose` in a new `src/dusk/asset/loader/xxx/` directory.
4. Register the three callbacks in `ASSET_LOADER_CALLBACKS[]` in
`src/dusk/asset/loader/assetloader.c`.
5. If user-facing, create a JS module (see below) and a `.d.ts` file.
---
## Adding a new entity component
1. Create `src/dusk/entity/component/<category>/entityMyComp.h/.c` with
struct `entityMyComp_t`, `entityMyCompInit()`, and optionally
`entityMyCompDispose()`, `entityMyCompRender()`.
2. Add the include to `src/dusk/entity/componentlist.h` header block
(or `src/duskrpg/entity/gamecomponentlist.h` for a game-specific
component, appended after the engine's inbuilt ones).
3. Add a row:
```c
X(MYCOMP, entityMyComp_t, myComp, entityMyCompInit, NULL, NULL)
```
Params are `(enumName, type, field, init, dispose, render)` — pass
`NULL` for any callback the component doesn't need. This
auto-generates the enum, union field, and definition entry.
4. If JS-facing, create the script module and `.d.ts` (see below).
Entities/components/scenes have no JSON serialize/deserialize path —
that was removed in favor of building scenes from C-coded prefabs
(below) or from JerryScript (`Entity`/`Component`/`Scene`, see
"Adding a new script (JS) module").
---
## Adding a new entity/scene prefab
Entity prefabs (`src/dusk/entity/entityprefab.h`) and scene prefabs
(`src/dusk/scene/sceneprefab.h`) follow the same pattern:
1. Write an apply function: `errorret_t entityPrefabXxxApply(mgr,
entityId)` (or `errorret_t scenePrefabXxxApply(sceneId)`), building
up the entity/scene with the normal component/entity APIs.
2. Add an entry to the sentinel-terminated `ENTITY_PREFABS[]` (in
`src/dusk/entity/entityprefablist.h`, or a game-specific list it
includes) or `SCENE_PREFABS[]`:
```c
{ .name = "MY_PREFAB", .extends = "", .apply = entityPrefabXxxApply }
```
`extends` names another prefab to apply first (recurses through
`entityPrefabResolveAndApply`/`scenePrefabResolveAndApply`), or `""`
for none. Do not add an enum or count field — the array is iterated
until `.name[0] == '\0'`.
3. `entityPrefabResolveAndApply`/`scenePrefabResolveAndApply` only
resolve names against the C-coded registry above — there is no JSON
asset fallback. Throws if no prefab with that name is registered.
---
## Adding a new cutscene item type
1. Create `src/duskrpg/cutscene/item/<category>/cutsceneMyItem.h/.c`
with a data struct (e.g. `cutscenemyitem_t`) and
`cutsceneMyItemStart(item, data)` / `cutsceneMyItemUpdate(item,
data)` (the latter returns `true` once the item has completed). Add
a matching `cutscenemyitemdata_t` runtime-data struct only if the
item needs per-run state across ticks (most don't).
2. Add `CUTSCENE_ITEM_TYPE_MY_ITEM` to the enum and a union member to
`cutsceneitem_t` (and `cutsceneitemdata_t` if it has runtime data) in
`src/duskrpg/cutscene/item/cutsceneitem.h`.
3. Register the `{ start, update }` pair in `CUTSCENE_ITEM_CALLBACKS[]`
in `cutsceneitem.c`.
4. Add an authoring macro to `src/duskrpg/cutscene/cutscene.h`:
```c
#define CUTSCENE_MY_ITEM(ARGS...) \
{ .type = CUTSCENE_ITEM_TYPE_MY_ITEM, .myItem = { ARGS } }
```
used inside a `CUTSCENE(NAME, SIZE, PAUSE_TYPE, ...)` block.
---
## Save system
Save data lives under `src/dusk/save/` (`save.h`/`savefile.h`/
`saveplatform.h`). Slots are fixed-count (`SAVE_FILE_COUNT_MAX`), each
holding a yyjson document persisted with its byte size and a CRC32
checksum. `saveLoad`/`saveSave` read/write the JSON fresh every call —
callers own the returned/passed `yyjson_doc`/`yyjson_mut_doc` and must
free it themselves. Actual file I/O goes through platform-specific
`saveplatform_t`/stream hooks (one implementation per platform under
`src/dusk<platform>/save/`) — do not add direct filesystem calls to the
core `save.c`, extend the platform stream hooks instead.
## Network system
`src/dusk/network/` (`network.h`) is a connection-state layer only — a
`networkstate_t` state machine (`DISCONNECTED`/`CONNECTING`/`CONNECTED`/
`DISCONNECTING`) plus an HTTP client (`network/http/`) used for one-off
requests. It is not a multiplayer/replication protocol — that layer
doesn't exist yet (see `ROADMAP.md` items on the socket server/client
and packet handlers). Platform-specific connection logic (e.g. PSP's
`sceNetApctl` polling, GameCube/Wii's `if_config()`) lives under
`src/dusk<platform>/network/`, wired through `networkplatform.h` macros
the same way display/input are. Whenever this eventually grows a
multiplayer protocol, apply `ROADMAP.md`'s principle: never trust
incoming packet data — validate defensively with `errorret_t`/
`errorThrow()`, not asserts.
## Adding a new script (JS) module
Dusk embeds JerryScript (`src/dusk/script/`, fetched via
`cmake/modules/Findjerryscript.cmake`). Today only `Entity`, the
generic `Component` wrapper, and `Scene` are registered (see
`src/dusk/script/module/modulelist.c`) — no per-component-type typed
wrappers exist yet (e.g. no `.position` on a `POSITION` component);
`entity.add(TYPE)`/`entity.getComponent(TYPE)` always return the
generic `Component`.
1. Create `src/dusk/script/module/<category>/moduleMyMod.h/.c`.
- Declare `extern scriptproto_t MODULE_MYMOD_PROTO;` in the header.
- Use `moduleBaseFunction(name)` to define JS-callable functions —
these are the one exception to "no `static` in `.c` files": the
macro itself expands to a `static jerry_value_t name(...)`
JerryScript external-handler trampoline, never called by name
from other C files, so it isn't declared in the `.h`.
- Register props/funcs in `moduleMyModInit()` with
`scriptProtoDefineProp` / `scriptProtoDefineFunc` /
`scriptProtoDefineStaticFunc`.
2. `#include` the header in
`src/dusk/script/module/modulelist.c` and call
`moduleMyModInit()` in `moduleListInit()` (and `Dispose` in
`moduleListDispose()`).
3. For a component module that adds a *typed* wrapper for a specific
component type, create
`src/dusk/script/module/entity/component/modulecomponentlist.c` (it
doesn't exist yet — the first such module creates it) so
`entity.add()` can return the typed wrapper instead of the generic
`Component`.
4. Create `types/<category>/mymod.d.ts` and add a
`/// <reference path="..." />` line to `types/index.d.ts`.
---
## Script module type declarations
Whenever a `src/dusk/script/module/**/*.c` file is created or modified,
check whether the corresponding `types/**/*.d.ts` needs updating and
apply any changes before finishing the task.
---
## JavaScript (asset scripts)
- Use `var` for module-level state; `const` for values that never
change.
- Always use semicolons.
- Scene objects are plain objects (`var scene = {}`) with assigned
methods.
- Export via `module.exports = scene`.
- Async scene init should use `async function` and `await`.
---
## Coding style
### ASCII only
Source files (`.c`, `.h`, `.js`) must contain only ASCII characters (U+0000U+007F).
Non-ASCII characters are banned even in comments and string literals.
Use ASCII-only substitutes instead:
- `--` or `-` instead of `` (em dash)
- `->` instead of `` (arrow)
- `x` or `*` instead of `×` (multiplication)
Only non-script asset files (e.g. `.po` locale files) may contain non-ASCII text.
### Indentation
2 spaces. No tabs.
### Keyword and operator spacing
No space between a keyword or function name and its opening parenthesis:
```c
if(!ptr) return;
for(uint8_t i = 0; i < count; i++) {
while(entry->state != DONE) {
switch(type) {
sizeof(assetbatch_t)
memoryZero(ptr, size)
```
Spaces around all binary operators and after every comma:
```c
pos->flags |= ENTITY_POSITION_FLAG_WORLD_DIRTY;
(size_t)end - (size_t)start
foo(a, b, c)
```
### Braces
Opening brace on the **same line** as the statement (K&R style) for all
constructs — functions, `if`, `else`, `for`, `while`, `switch`:
```c
void assetEntryLock(assetentry_t *entry) {
...
}
if(dirty) {
...
} else {
...
}
```
### Guard returns
Short guards go on one line with no braces:
```c
if(!ptr) return;
if(!b || !b->batch) return jerry_undefined();
if(!(flags & DIRTY)) return;
```
### Blank lines
- One blank line between functions; no blank line at the start or end of
a function body.
- One blank line between logical blocks inside a function body.
- No trailing blank lines at the end of a file.
### Pointer placement
`*` is attached to the variable name, not the type:
```c
assetentry_t *entry
const char_t *name
void *ptr
uint8_t *d = (uint8_t *)dest;
```
### Casts
Space between cast and operand:
```c
(assetbatch_t *)user
(uint8_t *)dest
(textureformat_t)v
```
### Return
No parentheses around the return value:
```c
return ptr;
return MEMORY_POINTERS_IN_USE;
```
### switch / case
`case` indented 2 spaces from `switch`; body indented 2 more from `case`:
```c
switch(type) {
case ASSET_LOADER_TYPE_TEXTURE:
descs[i].input.texture = (textureformat_t)v;
break;
default:
break;
}
```
### Multi-line function signatures
When parameters don't fit on one line, put each on its own line indented
2 spaces; the closing `) {` (definition) or `);` (declaration) goes on
its own line at column 0:
```c
void assetEntryInit(
assetentry_t *entry,
const char_t *name,
const assetloadertype_t type,
assetloaderinput_t *input
) {
errorret_t memoryCompare(
const void *a,
const void *b,
const size_t size
);
```
### Structs and enums
Anonymous inner struct or enum with a `typedef`, `_t` suffix, closing
brace and name on the same line:
```c
typedef struct {
errorcode_t code;
char_t *message;
} errorstate_t;
typedef enum {
ASSET_LOADER_TYPE_NULL,
ASSET_LOADER_TYPE_COUNT
} assetloadertype_t;
```
### Designated initialisers
Spaces inside braces; `.field = value`:
```c
jsassetentry_t e = { .entry = entry };
assetbatchloadedpend_t init = { .batch = batch };
```
### Ternary operator
Spaces around `?` and `:`:
```c
const float val = psx > 0.0f ? pt[0][0] / psx : 0.0f;
```
### const placement
`const` before the type, `*` attached to the variable:
```c
const char_t *name
const void *src
const size_t size
```
### Comments in `.c` files
- Do not use section dividers (`/* ---- ... ---- */`). Just let the
functions follow one another with a single blank line between them.
- Multi-line explanatory comments inside function bodies use `//` lines:
```c
// Script modules are freed; orphaned JS wrapper objects now get GC'd
// so their finalizers fire before assetDispose() checks ref counts.
jerry_heap_gc(JERRY_GC_PRESSURE_HIGH);
```
- Do not use `/* */` for inline or inline-block comments inside `.c`
function bodies.
### Comments in `.h` files
Every public declaration gets a Javadoc block (`/** … */`) with
`@param` and `@returns` where relevant. Keep it on the lines immediately
above the declaration with no blank line in between.
---
## Color system
Colors are defined in `src/dusk/display/color.csv` and code-generated
into a `color.h` header by `tools/color/csv/__main__.py`.
Each row in the CSV has `name,r,g,b,a` with channel values in `[0.0, 1.0]`.
The script emits four `#define` variants per color plus a bare alias:
```
COLOR_<NAME>_4B color4b(r8, g8, b8, a8) // default alias target
COLOR_<NAME>_3B color3b(r8, g8, b8)
COLOR_<NAME>_3F color3f(rf, gf, bf)
COLOR_<NAME>_4F color4f(rf, gf, bf, af)
COLOR_<NAME> COLOR_<NAME>_4B
```
`color_t` is `color4b_t` (four `uint8_t` channels).
To add a new color, append a row to `color.csv` and rebuild — do not
hand-edit the generated header.
---
## Tests
- Tests live in `test/` mirroring `src/dusk/` structure.
- Use cmocka; include `dusktest.h`.
- Test functions: `static void test_something(void **state)`.
- After each test, assert `memoryGetAllocatedCount() == 0` to catch
leaks.
- Build with `-DDUSK_BUILD_TESTS=ON`.
+7
View File
@@ -13,6 +13,7 @@ cmake_policy(SET CMP0079 NEW)
# set(FETCHCONTENT_UPDATES_DISCONNECTED ON)
option(DUSK_BUILD_TESTS "Enable tests" OFF)
option(DUSK_NETWORK "Enable network support" ON)
set(DUSK_GAME_NAME "Dusk" CACHE STRING "Game display name")
set(DUSK_GAME_AUTHOR "YourWishes" CACHE STRING "Game author / coder")
@@ -90,6 +91,12 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME}
DUSK_VERSION="${DUSK_VERSION}"
)
if(DUSK_NETWORK)
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_NETWORK
)
endif()
# Toolchains
include(cmake/targets/${DUSK_TARGET_SYSTEM}.cmake)
-260
View File
@@ -1,260 +0,0 @@
# PSP Optimization Plan
A survey of concrete memory and CPU (especially floating-point) optimization
opportunities for the PSP target, done 2026-07-31 on branch `ac2` at commit
`e61914ba` + this session's scripting work. Point-in-time findings, not a
substitute for reading the referenced source before acting on it.
## Why this exists
The PSP (Allegrex MIPS CPU, 222-333MHz, single core, 32-64MB main RAM, 2MB
eDRAM, 16KB I-cache / 16KB D-cache, no virtual memory or memory protection)
is the tightest-constrained target this engine ships to. Two rules guide
everything below, both already correctly applied in one place in this
codebase (`entityposition_t` caching its transform matrices instead of
recomputing them from position/rotation/scale every read — see "Already
correct" below):
- **Memory is finite and cannot be compacted.** No VM means a fragmented
heap after a few minutes of play can fail an allocation even with
"enough" total free bytes. Prefer static/pool allocation over
malloc/free churn; prefer trading memory for CPU only when the memory
cost is bounded and paid once.
- **CPU is finite and floating-point math is not free**, especially
trig/sqrt on the plain scalar FPU. Prefer caching a computed result
behind a dirty flag over recomputing it unconditionally; prefer
avoiding a sqrt via squared-distance comparison wherever only a
yes/no or ordering result is needed.
## Priority 1 — Entity/component memory: a union tax paid on every slot, times 4 scenes
**The single biggest finding.** `entitymanager_t` (`src/dusk/entity/entitymanager.h:11-15`)
is a flat, statically-sized struct:
```c
typedef struct entitymanager_t {
entity_t entities[ENTITY_COUNT_MAX]; // 64
component_t components[ENTITY_COUNT_MAX * ENTITY_COMPONENT_COUNT_MAX]; // 64*16 = 1024
componentid_t entitiesWithComponent[COMPONENT_TYPE_COUNT * ENTITY_COUNT_MAX];
} entitymanager_t;
```
`component_t` (`src/dusk/entity/component.h:69-72`) holds a **tagged union**
(`componentdata_t`) sized to its largest variant. That variant is
`entityrenderable_t`'s spritebatch payload (`entityrenderable.h:25-66`):
`spritebatchsprite_t sprites[64]` at 40 bytes each (`vec3 min + vec3 max +
vec2 uvMin + vec2 uvMax`) = **2560 bytes**, versus ~28-300 bytes for every
other component type (camera, physics, animation, position, trigger).
Because the union is embedded by value in a flat array — not behind a
pointer, not sparse — **every one of the 1024 component slots in every
entity manager costs ~2580 bytes, whether it holds a 28-byte camera or
nothing at all.** `1024 * 2580 ≈ 2.52MB` per `entitymanager_t`, confirmed
by the engine's own startup log every run: `Entity manager size: 2684992
bytes (2622.06 KB)`.
`scene_t` (`src/dusk/scene/scene.h:14-18`) embeds `entitymanager_t` by
value too, and `SCENE_COUNT_MAX = 4` (`scene/scenebase.h:11`) with
`SCENE_MANAGER` declared as a plain global (`scene/scene.c:20`) — so this
~2.52MB exists as static BSS from process start for **all 4 scene slots**,
used or not. **Total: ~10.1MB reserved permanently for entity storage
alone** — 16-31% of PSP main RAM — before a single texture, mesh, or audio
asset is loaded.
**Options to fix (roughly increasing effort/risk):**
1. Pull `entityrenderablespritebatch_t` out of the component union entirely
— store spritebatch entities via a pointer/handle into a separate,
smaller fixed pool sized to how many spritebatch-renderable entities
actually coexist (almost certainly far fewer than 64 per entity, and
far fewer entities need spritebatch at all vs. mesh/material
rendering). This alone would shrink the union's dominant variant from
~2560 bytes to whatever the next-largest variant is (~300 bytes,
`entitytrigger_t`) — an ~88% reduction, dropping the ~10.1MB down to
roughly ~1.2MB.
2. Reduce `SCENE_COUNT_MAX` from 4 if 4 concurrent scenes were never a
deliberate requirement (check with the project owner — this may just
be a round-number default nobody revisited), or make scene storage
pointer-based/lazily allocated so unused scene slots cost ~0 instead
of a full `entitymanager_t`.
3. Reduce `ENTITY_COMPONENT_COUNT_MAX` (16) if entities realistically use
far fewer distinct component types simultaneously — check actual
usage across `entityprefablist.h`/`gameprefablist.h` prefabs.
Do (1) first — it's the highest-leverage, most contained change (touches
`entityrenderable.h`'s data layout and its render/dispose paths, not the
general entity/component system), and re-measure via the same startup
log line before deciding whether (2)/(3) are still worth doing.
## Priority 2 — VFPU is completely unused; all vec/mat math is scalar
The PSP's Allegrex CPU has a **VFPU** (vector floating-point unit) capable
of fast SIMD-style 4-wide float ops and hardware-accelerated matrix
operations, exposed by pspsdk's `pspvfpu`/GU "Geometry Utility" (`gum_*`)
helpers. This engine links `pspvfpu` (`cmake/targets/psp.cmake`) but
**never calls into it** — confirmed via a zero-hit grep for
`vfpu|pspmath|gum_|vcst|gu_matrix` across `src/duskpsp/` and `src/duskgl/`.
All vector/matrix math instead goes through cglm (`glm_vec3_*`,
`glm_mat4_*`), which auto-detects SIMD only for x86 (`CGLM_SSE2`/`AVX`) or
ARM (`CGLM_NEON`) — neither applies to MIPS, and no `CGLM_*` macros are
set anywhere in this repo (confirmed zero hits). **Every `glm_mat4_mul`,
every position/rotation rebuild, every physics vector op runs on the
plain scalar MIPS FPU with the VFPU sitting idle.**
This is the single largest *available* CPU win identified in this survey
— larger than any specific hot-path fix below, because it's a multiplier
on all of them. Concretely: route `entityposition.c`'s matrix
rebuild/multiply path and `physicsworld.c`'s per-body vector math through
`pspvfpu`/`gum_*` on the PSP build specifically (behind `#ifdef DUSK_PSP`,
matching the project's existing platform-guard convention), while keeping
cglm as the portable fallback for Linux/Knulli/GameCube/Wii. This is a
genuinely large effort (new platform-specific math backend, careful
correctness verification since VFPU has its own quirks around
pipelining/hazards) — scope it as its own project, not a quick pass.
## Priority 3 — UI/spritebatch rebuilds and redraws every vertex, every frame
Already flagged in `STATUS.md`/`ROADMAP.md` (item 4/5) as a known open
issue; this session's research adds concrete numbers. `meshvertex_t`
(`display/mesh/meshvertex.h:14-17`) is `{ float uv[2]; float pos[3]; }` =
**20 bytes/vertex**, no packing. `SPRITEBATCH_SPRITES_MAX = 512`,
`SPRITEBATCH_FLUSH_COUNT = 16` → 32 sprites/flush = 192 vertices = **3,840
bytes rebuilt and redrawn per flush**, with a flush forced on every
shader/material change (`spritebatch.c:38-50`) and used unconditionally
by every widget except `uiconsole.c` (`uitab.c:56`, `uislider.c:183/199/231`,
final flush in `ui.c:51`). A UI screen with ~50-100 sprites and 2-3
material changes costs an estimated **8-15KB of vertex rebuild + GU
submission every single frame**, regardless of whether the UI changed
since the last frame.
Confirmed on the PSP legacy-GL path specifically: there's no GPU buffer
re-upload cost (`meshFlushGL` is a literal no-op comment: "we use the
glClientState stuff" — `meshgl.c:91-93`; `meshDrawGL` just points
`glVertexPointer` at the CPU-side array each call), so the real cost is
(a) the CPU-side per-sprite vertex rewrite every frame and (b) GU
re-transforming the full vertex stream from RAM on every draw with no
skip for unchanged geometry.
**Fix direction** (already captured in `ROADMAP.md`'s debt backlog item 5):
extend `uiconsole.c`'s cached-mesh, dirty-flag-gated rebuild pattern to
the rest of the widget tree. This plan adds one refinement: also consider
packing `meshvertex_t` down (next item) since it multiplies this cost.
## Priority 4 — All-float vertex format wastes bandwidth and T&L cost
`meshvertex_t` uses two `float` fields (20 bytes) for every mesh and
sprite vertex, mesh-wide, with no normal or per-vertex color (color is
already handled at the material level, so that part is already optimal).
GU natively supports fixed-point 16-bit positions/UVs
(`GU_VERTEX_16BIT`/`GU_TEXTURE_16BIT`), which would roughly halve
per-vertex size and the corresponding vertex-fetch/transform cost, at the
cost of position precision (fine for UI/sprite work and most world
geometry at this engine's scale; worth checking against the largest
world coordinates actually used before committing). Pair with Priority 3
so the packing benefit compounds with the dirty-tracking benefit instead
of just reducing the cost of a rebuild that still happens every frame.
## Priority 5 — Running gameplay logic in JerryScript has a real per-frame cost on PSP
This is new since last session's work, not a pre-existing issue: `assets/
scripts/overworldscene.js`'s `update()` is now called every frame via
`scriptManagerCallGlobal("update")` (wired into `engine.c`'s
`engineUpdate()`), replacing what used to be a direct `cosf`/`sinf` C
callback (`entityUpdateAdd`). Per call, `scriptManagerCallGlobal`
(`scriptmanager.c:91-144`) does: a global-object property lookup (key is
cached, but the `jerry_object_get` dispatch still runs), full JS
interpreter call dispatch (frame setup, argument marshaling) for what's a
two-line function, and an unconditional `jerry_value_is_promise` check
every call even though `update()` is synchronous. Inside, `Math.cos`/
`Math.sin` run as JS builtin calls rather than direct libm calls.
Additionally: this project's JerryScript fork is already patched to use
32-bit float internally (`JERRY_NUMBER_TYPE_FLOAT64=0`,
`Findjerryscript.cmake`) — a deliberate, already-correct optimization for
this exact concern — but the *public* engine API (`jerry_value_as_number()`)
still returns `double`, so every native↔JS boundary crossing (every
`moduleBaseArgFloat`, every `moduleBaseVec3ToObject`) still pays a
float→double→float round trip. Also note `JERRY_MATH` is off, so
`Math.sin`/`cos` fall through to whatever generic libm the platform
provides rather than JerryScript's own fdlibm implementation — worth
checking whether turning it on changes anything measurable on PSP.
**This is one `update()` call for one scene-level script today — cheap in
absolute terms.** It becomes a real problem only if the pattern scales:
giving many individual entities their own per-frame JS update callback
would multiply all of the above per entity. **Recommendation: keep
high-frequency, hot per-entity logic (movement, camera math, physics
response) in native C update callbacks (`entityUpdateAdd`, the existing
mechanism), and reserve JS for one-time setup, infrequent/event-driven
logic, and coarse-grained per-scene orchestration** — which is exactly
what `require()` and the typed component wrappers built this session are
suited for, not a per-entity-per-frame hot path. This is a design
guideline to apply going forward, not a regression to fix in the current
`overworldscene.js` (one scene-level `update()` call per frame is fine).
## Priority 6 — No pooling/arena allocator; plain malloc/free everywhere
`memoryAllocate`/`memoryFree` (`util/memory.c`) are direct `malloc`/`free`
passthroughs (`memoryAlign``memalign`, `memoryReallocate`/`memoryResize`
`realloc`), with the only extra behavior being a global allocation-count
tracker used solely for test leak detection. No pool, arena, free-list,
or size-class allocator exists anywhere.
This survey found **no rogue per-frame heap allocations** in the hot
paths checked (render dispatch in `entityrenderable.c`, all of
`physics/*.c`) — so this is not an active bug today. But it's a
structural risk for a no-VM platform over a long play session: any future
code that does frequent small alloc/free (dynamic lists, string
building, temp buffers) will fragment the 32-64MB heap with no OS-level
recovery mechanism. **Recommendation: before adding any new subsystem
that allocates/frees frequently at runtime (not just at load time),
default to a fixed-size pool or arena for it**, following the same
"static, bounded" philosophy already used for `ENTITY_COUNT_MAX`/
`SCENE_COUNT_MAX`/`ASSET_ENTRY_COUNT_MAX` elsewhere in the engine, rather
than reaching for `memoryAllocate` per-instance.
## Already correct — don't touch without new evidence
- **`entityposition_t`'s matrix caching** (the pattern the project owner
called out as the reason for writing this plan). Verified: a full
"dirty" recompute chain (decompose + rebuild local + rebuild world) is
~10 trig calls (`asinf`/`cosf`/`atan2f`) plus at most one 4x4 matrix
multiply, and `entityPositionEnsurePRS`/`EnsureLocal`/`EnsureWorld`
(`entityposition.c:596-669`) all early-return on a flag check, only
doing that work when something actually changed. The cache is correct
and clearly worth its ~128-byte-per-entity matrix storage cost.
- **Physics narrow-phase sqrt avoidance.** All three `sqrtf` call sites
in `physicstest.c`/`physicsshapemesh.c` already sit behind a
squared-distance early-reject and only compute the real (linear)
distance once, when actually needed for penetration depth — no further
"use squared distance instead" opportunity was found here.
- **No allocations in the render/physics hot loop** (Priority 6) — this
is good and worth preserving as new code is added to those files.
- **Asset decompression already runs off the main thread.** Assets are
DEFLATE-compressed (not stored) in `dusk.dsk`, so loading pays a real
CPU cost for decompression — but every `*LoaderAsync` function
(`asset/loader/*/*.c`) runs via `ASSET.loadThread`
(`assertNotMainThread` in `asset.c:365`), so this cost is already kept
off the main thread. Low priority to change; if load-time CPU cost
becomes a measured problem later, revisit stored-vs-compressed as a
build-time flag rather than assuming compression is free.
## Suggested approach
1. **Measure before changing.** None of the above have been profiled on
real PSP hardware in this pass — this is a source-level survey, not a
profile. Before investing in Priority 1 or 2 especially, confirm with
an actual PSP build/run (or at minimum the existing "Entity manager
size" startup log plus a frame-time counter) that these are the real
bottlenecks, not just the largest numbers on paper.
2. **Priority 1 first** — it's the most contained (one component's data
layout), has the clearest before/after metric (the startup log line),
and doesn't require new platform-specific code.
3. **Priority 3 next** (extend the console's dirty-tracking pattern to
the rest of the UI) — already scoped in `ROADMAP.md`, no new design
needed, just implementation.
4. **Priority 2 (VFPU) as a dedicated project**, not a quick pass — it's
the largest potential win but touches core math plumbing and needs
careful correctness verification on real hardware.
5. Treat Priority 5 as a standing design guideline for all future
scripting work, not a one-time fix.
-104
View File
@@ -1,104 +0,0 @@
# Dusk Roadmap
Tracking upcoming milestones for the engine. See `PSP_OPTIMIZATION_PLAN.md`
for a memory/CPU optimization survey specifically targeting the PSP build
(milestone 4 below is its Priority 3).
## Upcoming milestones
1. Add a very basic physics engine, moving away from the current
tile-based movement.
2. Give entities full freedom of movement (no longer locked to tile
grid positions).
3. Update entity interaction, triggers, chunk management, and other
systems that currently assume tile-based positioning so they work
with the new 3D positioning/movement code.
4. Investigate and fix poor UI rendering performance. First pass done
(2026-07-31): slider/tab/frame/textbox now cache their sprite
geometry instead of rebuilding it every frame, and the console's
vertex buffer is fixed-size instead of alloc/free churn (see
`STATUS.md`'s "UI rendering performance" note for detail). Still
open: per-widget material/color changes still force a sprite-batch
flush each time (color is per-material, not per-vertex), so a row of
alternating highlighted widgets still costs one draw call per
widget.
5. Create UI elements for displaying status indicators, e.g. network
connection state and save-in-progress.
6. Fully test saving end-to-end on all supported platforms.
7. Remove the tile system from chunks in favor of meshes, with
dynamic hitboxes per chunk loaded in from the chunk file data.
8. Create UI elements for network status: a connecting modal, an
error state, and a connected flag. Retire the test HTTP request
once these are in place.
9. Build the socket server and client implementation, including
handlers for the different packet types.
10. Add a dedicated multiplayer entity type, `clientplayer`, alongside
the existing `npc` and `player` types. Limit to 8 (defined
constant) for now.
11. Send and receive `clientplayer` position over the network.
12. Create a UI menu for creating a server and joining a server. For
now, join IPs are hard-coded (testing against a fixed IP of
10.0.0.94).
13. Create "handshake" packets. For now, just send the username,
enforced to be under 10 characters long.
14. Server tracks all players' positions and broadcasts them to all
connected clients.
15. Server sends disconnect packets for users who leave.
16. Server assigns each client a UUID; all clients know every other
client's UUID (used to reference them across position updates,
disconnect packets, etc).
17. Server notifies all clients (by UUID) when a user joins, leaves,
or is disconnected, so clients can spawn or remove the
corresponding `clientplayer` entity in the world.
## Infrastructure / debt backlog
Found during a full-codebase inventory pass (2026-07-30, see `STATUS.md`
for the full survey). These aren't new feature milestones so much as
loose ends worth closing, roughly in order of how cheap/safe they are to
fix:
1. Re-enable `test/item` (currently commented out in
`test/CMakeLists.txt`) -- confirm it still passes and turn it back on.
2. Restore `itemgive.c/h` in `src/duskrpg/item/CMakeLists.txt` -- the
textbox UI dependency it was waiting on (`ui/textbox/`) is already
back.
3. Decide the fate of the `vita` target: `scripts/build-vita.sh` and
`docker/vita/` reference `-DDUSK_TARGET_SYSTEM=vita`, but no
`cmake/targets/vita.cmake` exists, so the build is currently broken.
Either implement it or remove the dangling scripts/Dockerfile.
4. Per-PR CI build coverage for non-Linux targets: first pass added
2026-07-31 as `run-tests-gamecube-dolphin`/`run-tests-wii-dolphin`
(build the ISO, boot it in Dolphin under Xvfb) and
`run-tests-psp-ppsspp` (build the EBOOT, boot it in PPSSPPHeadless)
in `.github/workflows/test.yml`, plus matching
`scripts/test-*-dolphin.sh`/`scripts/test-psp-ppsspp.sh` (+ `-docker`
variants). Marked `continue-on-error: true` since none of these have
actually been exercised on a real runner yet -- verify they pass
before relying on them, and drop the flag once they do. Knulli still
has no per-PR coverage at all.
5. Milestone 4 above (poor UI rendering performance) has a first pass
in (2026-07-31, see `STATUS.md`) -- remaining concrete lead: sprite
batch flushes are keyed on shader+material (including tint color),
so per-widget color changes (e.g. focus highlight) still force a
flush per widget; moving tint to per-vertex color would let a whole
row of widgets batch into one draw call regardless of highlight
state.
6. Revisit the GameCube/Wii networking static-IP workaround in
`networkdolphin.c` -- it's standing in for an unresolved suspected
memory-corruption bug in `if_config()`'s DHCP path.
7. Decide whether the PSP dialog-based network connect UI needs to come
back -- it was removed entirely (not fixed) when the original
dialog-tearing bug proved hard to resolve.
8. Backfill unit tests for the biggest untested surfaces: `ui/` (whole
widget framework), `save/`, `script/` (JerryScript bindings), `event/`.
## Principles
- Never trust the network implicitly. Neither side (server or client)
should assume the other's packets are well-formed or benign --
validate all incoming packet data defensively, since either side
may send garbage or malicious data. Use `errorret_t` /
`errorThrow()` for these runtime checks, not assert macros --
asserts are debug-only and won't guard release builds against
malformed or malicious packet data.
-120
View File
@@ -1,120 +0,0 @@
# Dusk Engine - Status Snapshot
This is a point-in-time inventory of the codebase's maturity, test coverage,
and known gaps. It is not auto-maintained -- re-survey periodically (or
whenever picking a new roadmap milestone) rather than trusting it blindly.
See `ROADMAP.md` for the ordered feature milestones this status feeds into,
and `CLAUDE.md` for coding conventions.
Last surveyed: 2026-07-31, at commit `8f8fa8f8`.
## Core engine (`src/dusk/`)
| Subsystem | Maturity | Notes |
|------------|------------------------------------|-------|
| asset | Mature, fully wired | Model loading's "async" path is actually synchronous (`assetmodelloader.h`) -- only real stub found in core. |
| script | Mature for its current scope | Registered modules: `modulePlatform`, `moduleComponent`/`moduleComponentList` (typed Position/Physics/Renderable wrappers), `moduleEntity`, `moduleScene` (with `Scene.set()` module lifecycle), `moduleMesh`, `moduleTime`, `moduleRequire` (CommonJS-style `require()`/`module.exports`). Entry point is `scripts/init.js`, which does `require('./overworldscene.js')` + `Scene.set()`. Has unit tests (`test/script/`). |
| entity | Mature | Engine-level prefab lists are empty sentinels; all real prefabs live in `duskrpg`. |
| scene | Mature | Same prefab-delegation pattern as entity. No JSON serialize/deserialize (removed by design). |
| save | Mature, but undocumented | Slot-based, yyjson + CRC32, platform stream hooks. Not covered in `CLAUDE.md`, no tests. |
| network | Connection-state layer only | HTTP client + connection state machine; no multiplayer/replication protocol (expected -- that's roadmap items 8-17). Not covered in `CLAUDE.md`, has HTTP tests only. |
| physics | Mature, recently churned | Recent revert/re-disable of "old ent code" suggests component wiring around physics isn't fully settled. Well tested. |
| animation | Early/mid-stage | Keyframes + easing only, no blend trees or state machines. Terse commit history ("ANIM") suggests still iterating. |
| display | Most mature/battle-tested | Backbone of the engine; dominated by platform optimization commits. |
| ui | Actively churning, perf pass done | Widget framework has had features added and ripped out repeatedly (story/battle UI added then removed). No JS bindings yet (from-scratch surface if that's picked up). Sprite-cache pass landed for slider/tab/frame/textbox (see roadmap item 4 below); still no scripted pointer/hit-testing. Has unit tests for the new caching logic (`test/ui/`), but nothing exercises actual draw calls -- see below. |
| console | Small, finished for its scope | Fixed-size cached mesh (no more alloc/free churn), same pattern the rest of `ui/` now follows. |
| event | Clean, small, finished | Pub/sub, rebuilt to replace the old input system. |
| game | Intentionally header-only | Real implementation lives in `duskrpg/game/game.c`. |
### UI rendering performance (roadmap item 4)
First pass landed 2026-07-31: `uislider`/`uitab` now cache their non-text
quads (track/fill/markers, tab background) relative to origin and only
rebuild on state change, translating into position at draw time.
`uiframe.c` grew `uiFrameDrawCached()`, which skips rebuilding its 9-slice
sprites when x/y/width/height match the last call; wired into the
confirm dialog, settings panel, and textbox (each owns its own
`uiframecache_t`). `uitextbox` no longer does one `spriteBatchBuffer` call
per visible glyph -- it builds a per-page glyph cache once and slices a
prefix by scroll each frame. `uiconsole` dropped its alloc/free vertex
buffer for a fixed 512-glyph array. `uifps` skips its label rebuild when
the formatted FPS string hasn't changed.
Still open: every widget still issues its own `spriteBatchBuffer` call
per material/color, so a row of alternating highlighted/plain widgets
still forces a GPU flush per widget (color is applied via material, not
per-vertex) -- that's the next real win if PSP framerate is still an
issue. No scripted pointer/hit-testing exists either; input is still
100% gamepad/keyboard directional-focus (`ui/focus/`).
Test coverage caveat: `test/ui/` and `test/display/test_spritebatchsprite.c`
cover the new caching *logic* (geometry math, exercised by constructing
widget structs directly) but cannot exercise `uiXxxDraw()`/`uiFrameDraw()`
themselves -- those need `FONT_DEFAULT`/`UI_FRAME`'s GL texture, which
needs a live GL context this test binary doesn't have (confirmed: calling
`fontInitDefault()` in a test asserts in `texturegl.c`). This is true of
the whole rendering layer, not something newly introduced -- there's no
GL-backed test harness anywhere in the repo yet.
## Game layer (`src/duskrpg/`)
Actively maintained, not orphaned (despite an old "remove rpg" commit deep
in history) -- last touched the same day as this survey.
- **cutscene/** -- actively developed, matches `CLAUDE.md`'s documented
recipe exactly. 16 registered item types.
- **entity/, scene/** -- overworld player/camera/interactable components
and prefabs, active.
- **item/** -- `item.c`/`inventory.c`/`backpack.c` built via a working
`item.json` -> `itemdef.h` codegen pipeline. `itemgive.c/h` exist on
disk but are explicitly excluded from the CMake build pending textbox
UI restoration -- **that UI (`ui/textbox/`) is already restored**, so
this looks like an overdue follow-up, not a real blocker.
- **input/** -- headers only, no implementation. Contains the one
genuine TODO found in the whole `duskrpg` tree: `// TODO: Wiimote, USB
Keyboard, probably more.`
- **ui/** -- textbox restored and built; `uitestlabel.c/h` is an
intentional smoke-test scaffold, not dead code.
## Platform layers
| Platform | Status |
|--------------|--------|
| duskgl / dusksdl2 | Complete, shared by Linux/Knulli/PSP, no gaps found. |
| dusklinux | Complete, well-trodden. |
| duskpsp | Complete for current design. The historical dialog/tearing bug (see memory `project_psp_dialog_tearing` etc.) was **not fixed -- the dialog-based connect UI was removed entirely** (commit `d7982599`, "Simplified PSP network") in favor of a silent profile-based connect. Revisit if the dialog UX is still wanted. |
| duskdolphin (GameCube/Wii) | Functional, not a stub -- real GX-based display/mesh/shader/texture. Wii input uses only the GameCube `PAD_*` library; no WPAD/Wiimote support (`inputdolphin.h` has `#error "Wii not implemented"` gated behind macros that are never defined, so currently dormant, not a live build break). `networkdolphin.c` hardcodes a static IP as an explicit temporary workaround for a suspected DHCP-related memory-corruption bug in `if_config()` -- root cause still open. |
| vita | **Referenced by `scripts/build-vita.sh` and `docker/vita/` but no `cmake/targets/vita.cmake` exists** -- the build target is broken/unfinished at the CMake level. |
### CI coverage gap
`.github/workflows/test.yml` only builds+tests Linux, on PRs to `main`.
`build.yml` builds all other platforms (PSP, Knulli, GameCube, Wii +
ISO variants) but **only on tag push** (release time). Vita and Dolphin
aren't in CI at all. Net effect: regressions on 4+ platforms can land
silently until a release tag is cut.
## Test coverage gaps
Core `src/dusk/` subsystems with **zero** unit tests: `console`,
`engine`, `event`, `game`, `input`, `log`, `save`, `script` (+ all JS
module bindings), `system`, `ui` (entire widget framework).
`src/duskrpg/` has almost no test coverage: `test/item/test_inventory.c`
exists but **`add_subdirectory(item)` is commented out in
`test/CMakeLists.txt`**, so even that one test never runs. `cutscene`,
`entity`, `game`, `input`, `scene`, `ui` under `duskrpg` have no tests at
all.
No stale tests were found referencing deleted systems (old JSON
serialize/deserialize, old event/cutscene modules) -- the test suite is
internally consistent with current code, just incomplete in coverage.
## Build/tooling gaps worth knowing about
- `assetsraw/` -> `assets/` (chunk JSON -> `.dcf`) is a manual/editor-only
step (`tools.asset.chunk`), not part of the CMake build -- committed
`.dcf` files can silently drift from their raw source.
- Several Python tool packages exist but aren't wired into any build:
`tools/color/csv/`, `tools/asset/chunk_json/`, `tools/asset/dmf/`,
`tools/asset/tiles/`, `tools/input/csv/`. Some may be superseded by
`tools/color.py`/`tools/item.py`; worth a pass to confirm which are
live vs leftover.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+204
View File
@@ -5,11 +5,107 @@ msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=4; plural=(n==1 ? 0 : n==2 ? 1 : (n<7 ? 2 : 3));\n"
# Initial Scene
msgid "initial.checking_save.title"
msgstr "Checking for save data"
msgid "initial.checking_save.message"
msgstr "Please wait..."
msgid "initial.no_device.title"
msgstr "No Save Device Found"
msgid "initial.no_device.message"
msgstr "Could not find a save device, ensure it is connected and try again. You can continue, but progress will not be saved."
msgid "initial.no_device.retry"
msgstr "Try again"
msgid "initial.no_device.continue"
msgstr "Continue without saving"
# Main Menu Scene
msgid "main_menu.start_game"
msgstr "Start Game"
msgid "main_menu.options"
msgstr "Options"
msgid "main_menu.quit"
msgstr "Quit Game"
msgid "main_menu.quit_confirm"
msgstr "Are you sure you want to quit?"
msgid "main_menu.checking_save.title"
msgstr "Checking for save data"
msgid "main_menu.checking_save.message"
msgstr "Please wait..."
msgid "main_menu.no_device.title"
msgstr "No Save Device Found"
msgid "main_menu.no_device.message"
msgstr "Could not find a save device, ensure it is connected and try again. You can continue, but progress will not be saved."
msgid "main_menu.no_device.retry"
msgstr "Try again"
msgid "main_menu.no_device.continue"
msgstr "Continue without saving"
msgid "main_menu.save_load_error.title"
msgstr "Error"
msgid "main_menu.save_load_error.message"
msgstr "Failed to load save data. Please try again."
msgid "main_menu.save_load_error.retry"
msgstr "Try Again"
# Select Save Screen
msgid "ui.select_save.title"
msgstr "Select Save"
msgid "ui.select_save.empty"
msgstr "Empty Slot"
msgid "ui.select_save.slot_format"
msgstr "%s Lv.%d %s"
msgid "ui.select_save.delete_mode"
msgstr "Delete a Save"
msgid "ui.select_save.delete_confirm"
msgstr "Are you sure you want to delete this save?"
msgid "ui.select_save.name_title"
msgstr "Enter game save file name"
msgid "ui.save_slot.number_format"
msgstr "Slot %d"
#: ui/menu.c:10
msgid "ui.title"
msgstr ""
"Welcome"
msgid "save.linux.mkdirp_failed"
msgstr "Failed to create save directory, check the disk is not full or write-protected."
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.general"
msgstr "General"
@@ -56,6 +152,114 @@ msgstr "Items"
msgid "ui.game_menu.settings"
msgstr "Settings"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save"
msgstr "Save"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_success"
msgstr "Game saved."
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_cancelled"
msgstr "Save cancelled."
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_unavailable"
msgstr "Can't save - no save device found."
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_temporary"
msgstr "This session is temporary - no save device was found, so saving is disabled."
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_create_confirm"
msgstr "No save data found. Create a new save?"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_failed_format"
msgstr "Save failed: %s"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save_check_failed_format"
msgstr "Can't save: %s"
#: src/dusk/ui/frame/initial/uiinitialnocard.c
msgid "ui.initial.no_card.message"
msgstr "No save device found. You can continue, but\nprogress will not be saved."
#: src/dusk/ui/frame/initial/uiinitialnocard.c
msgid "ui.initial.no_card.retry"
msgstr "Retry"
#: src/dusk/ui/frame/initial/uiinitialnocard.c
msgid "ui.initial.no_card.continue"
msgstr "Continue Anyway"
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
msgid "ui.initial.create_save.message"
msgstr "No save data found. Create a new save?"
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
msgid "ui.initial.create_save.yes"
msgstr "Yes"
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
msgid "ui.initial.create_save.no"
msgstr "No"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.confirm"
msgstr "Confirm"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.cancel"
msgstr "Cancel"
#: src/dusk/ui/frame/battle/uibattlemenu.c
msgid "ui.battle.menu.attack"
msgstr "Attack"
#: src/dusk/ui/frame/battle/uibattlemenu.c
msgid "ui.battle.menu.flee"
msgstr "Flee"
#: src/dusk/ui/frame/battle/uibattlemenu.c
msgid "ui.battle.menu.target_format"
msgstr "Enemy %u (%u/%u HP)"
#: src/dusk/ui/frame/battle/uibattlehud.c
msgid "ui.battle.hud.hp_format"
msgstr "HP %u/%u"
#: src/dusk/ui/frame/battle/uibattlehud.c
msgid "ui.battle.hud.mp_format"
msgstr "MP %u/%u"
#: src/dusk/ui/frame/settings/uisettingsaudio.c
msgid "ui.settings.audio.placeholder"
msgstr "No audio settings yet"
#: src/dusk/ui/frame/settings/uisettingsdisplay.c
msgid "ui.settings.display.placeholder"
msgstr "No display settings yet"
#: src/dusk/ui/frame/settings/uisettingsinput.c
msgid "ui.settings.input.placeholder"
msgstr "No input settings yet"
#: src/dusk/ui/frame/backpack/uibackpack.c
msgid "ui.backpack.category_format"
msgstr "Category %u"
#: src/dusk/ui/overlay/uiloading.c
msgid "ui.loading.text"
msgstr "loading"
#: src/dusk/ui/overlay/uiautosave.c
msgid "ui.autosave.saving"
msgstr "SAVING"
msgid "item.potion.name"
msgstr "Potion"
-70
View File
@@ -1,70 +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/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"
-70
View File
@@ -1,70 +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/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 "リンゴ"
-9
View File
@@ -1,9 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Entry point run once at startup (see game.c). Swap which scene module
// gets passed to Scene.set() here to change what the game boots into.
var overworldScene = require('./overworldscene.js');
Scene.set(overworldScene);
-85
View File
@@ -1,85 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Radius must stay well outside the floor's footprint (a 20x20 plane has a
// corner-to-center distance of 10*sqrt(2) =~ 14.1) -- orbiting inside that
// puts parts of the floor's own geometry near/behind the camera's view
// direction, which the PSP's legacy GU pipeline can't clip properly and
// drops the whole triangle instead of clipping it.
var CAMERA_ORBIT_RADIUS = 18.0;
var CAMERA_ORBIT_HEIGHT = 10.0;
var CAMERA_ORBIT_SPEED = 0.5;
var cameraOrbitAngle = 0.0;
var cameraPosition = null;
// Orbits the camera around the world origin at a fixed radius/height/
// speed, always looking back at the origin. Called once up front (so the
// very first rendered frame is already positioned correctly) and then
// once per frame via update() below.
function updateCameraOrbit() {
cameraOrbitAngle += Time.delta * CAMERA_ORBIT_SPEED;
var eyeX = Math.cos(cameraOrbitAngle) * CAMERA_ORBIT_RADIUS;
var eyeY = CAMERA_ORBIT_HEIGHT;
var eyeZ = Math.sin(cameraOrbitAngle) * CAMERA_ORBIT_RADIUS;
cameraPosition.lookAt(eyeX, eyeY, eyeZ, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
module.exports = {
// Called once by Scene.set(), right after it creates and activates the
// scene this module owns.
init: function() {
// Camera, orbiting the origin (see updateCameraOrbit above).
var camera = new Entity();
cameraPosition = camera.add(POSITION);
camera.add(CAMERA);
updateCameraOrbit();
// Static ground plane. Physics ignores the entity's position
// component -- the shape's own normal/distance fully define the
// plane in world space.
var plane = new Entity();
var planePosition = plane.add(POSITION);
planePosition.setLocalPosition(-10.0, 0.0, -10.0);
planePosition.setLocalScale(20.0, 1.0, 20.0);
var planePhysics = plane.add(PHYSICS);
planePhysics.setBodyType(PHYSICS_BODY_STATIC);
planePhysics.setShape(PHYSICS_SHAPE_PLANE, 0.0, 1.0, 0.0, 0.0);
var planeRenderable = plane.add(RENDERABLE);
planeRenderable.setMesh(0, MESH_PLANE);
planeRenderable.setColor(128, 128, 128, 255);
// Player: dynamic capsule body, moved relative to the camera by
// PLAYER's own update callback (see entityplayer.c).
var player = new Entity();
var playerPosition = player.add(POSITION);
playerPosition.setLocalPosition(0.0, 2.0, 0.0);
var playerPhysics = player.add(PHYSICS);
playerPhysics.setShape(PHYSICS_SHAPE_CAPSULE, 0.5, 0.5);
var playerRenderable = player.add(RENDERABLE);
playerRenderable.setMesh(0, MESH_CAPSULE);
playerRenderable.setColor(0, 0, 255, 255);
player.add(PLAYER);
},
// Called once per engine frame while this module is the active scene
// (see Scene.set(), engineUpdate() -> moduleSceneUpdateCurrent()).
update: function() {
if(cameraPosition) updateCameraOrbit();
},
// Called once by Scene.set() when this module is replaced by another,
// right before the scene it owns is destroyed.
dispose: function() {
cameraPosition = null;
}
};
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

+22
View File
@@ -2179,5 +2179,27 @@
0
]
}
],
"entities": [
{
"type": "global",
"globalId": 3,
"pos": [8, 8, 1]
},
{
"type": "item",
"itemId": 1,
"quantity": 1,
"pos": [12, 2, 0]
}
],
"areas": [
{
"min": [11, 3, 0],
"max": [16, 9, 10],
"callbackId": 1,
"notify": 3,
"trigger": 6
}
]
}
+69
View File
@@ -0,0 +1,69 @@
{
"items": [
// Boot check: make sure a save device is available before handing off
// to the main menu.
{
"type": "MODAL",
"title": "initial.checking_save.title",
"message": "initial.checking_save.message"
},
{
"type": "WAIT",
"seconds": 0.2
},
{
"type": "SAVE_DEVICE_CHECK",
"successMarker": "CONTINUE",
"failureMarker": "NO_DEVICE"
},
// No save device found - offer to retry or continue without saving.
{
"type": "MARKER",
"name": "NO_DEVICE"
},
{
"type": "MODAL_CLOSE"
},
{
"type": "MODAL_OPTIONS_MARKERS",
"title": "initial.no_device.title",
"message": "initial.no_device.message",
"options": [
{
"text": "initial.no_device.retry",
"marker": "RETRY"
},
{
"text": "initial.no_device.continue",
"marker": "CONTINUE"
}
]
},
{
"type": "MARKER",
"name": "RETRY"
},
{
"type": "MODAL_CLOSE"
},
{
"type": "RESTART"
},
// Save device found (or continuing without one) - hand off to the
// main menu scene.
{
"type": "MARKER",
"name": "CONTINUE"
},
{
"type": "MODAL_CLOSE"
},
{
"type": "SCENE",
"sceneType": "MAIN_MENU"
}
]
}
@@ -0,0 +1,92 @@
{
"items": [
{
"type": "MODAL",
"title": "main_menu.checking_save.title",
"message": "main_menu.checking_save.message"
},
{
"type": "WAIT",
"seconds": 0.2
},
{
"type": "SAVE_DEVICE_CHECK",
"successMarker": "CONTINUE",
"failureMarker": "NO_DEVICE"
},
// No save device found - offer to retry or continue without saving.
{
"type": "MARKER",
"name": "NO_DEVICE"
},
{
"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": "RETRY"
},
{
"text": "main_menu.no_device.continue",
"marker": "CONTINUE"
}
]
},
// Retry
{
"type": "MARKER",
"name": "RETRY"
},
{
"type": "MODAL_CLOSE"
},
{
"type": "RESTART"
},
// Save device found - attempt to load all save slots.
{
"type": "MARKER",
"name": "CONTINUE"
},
{
"type": "MODAL_CLOSE"
},
{
"type": "SAVE_LOAD_ALL_SLOTS",
"successMarker": "LOADED",
"failureMarker": "LOAD_ERROR"
},
// 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": "RETRY"
}
]
},
{
"type": "MARKER",
"name": "LOADED"
}
]
}
-96
View File
@@ -1,96 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Turn things off we don't need
set(JERRY_CMDLINE OFF CACHE BOOL "" FORCE)
set(JERRY_EXT ON CACHE BOOL "" FORCE)
set(JERRY_DEBUGGER OFF CACHE BOOL "" FORCE)
set(JERRY_BUILTIN_DATE OFF CACHE BOOL "" FORCE)
set(ENABLE_LTO OFF CACHE BOOL "" FORCE)
# Fetch Jerry
include(FetchContent)
FetchContent_Declare(
jerryscript
GIT_REPOSITORY https://git.wish.moe/YourWishes/jerryscript
GIT_TAG float32-fix
)
FetchContent_MakeAvailable(jerryscript)
# Mark found
set(jerryscript_FOUND ON)
# Define targets
if(TARGET jerryscript-core)
set(JERRY_CORE_TARGET jerryscript-core)
elseif(TARGET jerry-core)
set(JERRY_CORE_TARGET jerry-core)
endif()
if(TARGET jerryscript-ext)
set(JERRY_EXT_TARGET jerryscript-ext)
elseif(TARGET jerry-ext)
set(JERRY_EXT_TARGET jerry-ext)
endif()
if(TARGET jerryscript-port-default)
set(JERRY_PORT_TARGET jerryscript-port-default)
elseif(TARGET jerry-port-default)
set(JERRY_PORT_TARGET jerry-port-default)
elseif(TARGET jerryscript-port)
set(JERRY_PORT_TARGET jerryscript-port)
elseif(TARGET jerry-port)
set(JERRY_PORT_TARGET jerry-port)
endif()
if(NOT JERRY_CORE_TARGET)
message(FATAL_ERROR "JerryScript core target not found")
endif()
if(NOT JERRY_EXT_TARGET)
message(FATAL_ERROR "JerryScript ext target not found")
endif()
if(NOT JERRY_PORT_TARGET)
message(FATAL_ERROR "JerryScript port target not found")
endif()
foreach(tgt IN ITEMS
${JERRY_CORE_TARGET}
${JERRY_EXT_TARGET}
${JERRY_PORT_TARGET}
)
if(TARGET ${tgt})
set_property(TARGET ${tgt} PROPERTY INTERPROCEDURAL_OPTIMIZATION OFF)
target_compile_definitions(${JERRY_CORE_TARGET} PRIVATE
JERRY_NUMBER_TYPE_FLOAT64=0
JERRY_BUILTIN_DATE=0
)
endif()
endforeach()
# Export include dirs through the targets
target_include_directories(${JERRY_CORE_TARGET} INTERFACE
${jerryscript_SOURCE_DIR}/jerry-core/include
)
target_include_directories(${JERRY_EXT_TARGET} INTERFACE
${jerryscript_SOURCE_DIR}/jerry-ext/include
)
target_include_directories(${JERRY_PORT_TARGET} INTERFACE
${jerryscript_SOURCE_DIR}/jerry-port/default/include
)
# Suppress JerryScript-only warning
if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
target_compile_options(${JERRY_CORE_TARGET} PRIVATE
-Wno-error
)
endif()
add_library(jerryscript::core ALIAS ${JERRY_CORE_TARGET})
add_library(jerryscript::ext ALIAS ${JERRY_EXT_TARGET})
add_library(jerryscript::port ALIAS ${JERRY_PORT_TARGET})
+1 -1
View File
@@ -6,7 +6,7 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
# Link libraries
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
bba
# bba
)
# ISO post-build: produce NTSC-J, NTSC-U and PAL disc images
+54 -5
View File
@@ -1,7 +1,3 @@
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
endif()
set(CMAKE_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
set(CMAKE_RANLIB "$ENV{PSPDEV}/bin/psp-ranlib" CACHE FILEPATH "" FORCE)
set(CMAKE_C_COMPILER_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
@@ -59,9 +55,33 @@ target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
DUSK_DISPLAY_WIDTH=480
DUSK_DISPLAY_HEIGHT=272
DUSK_THREAD_PTHREAD
DUSK_TIME_DYNAMIC
DUSK_DISPLAY_OVERSCAN=6
)
if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
DUSK_ASSERTIONS_FAKED
)
endif()
# Generate PARAM.SFO as a normal tracked build output (instead of letting
# create_pbp_file() auto-generate + delete it) so it can be reused below by
# a properly dependency-tracked EBOOT.PBP repack step.
set(DUSK_PSP_PARAM_SFO "${DUSK_BUILD_DIR}/PARAM.SFO")
add_custom_command(
OUTPUT "${DUSK_PSP_PARAM_SFO}"
COMMAND "$ENV{PSPDEV}/bin/mksfoex" "-d" "MEMSIZE=1" "-s" "APP_VER=01.00"
"${DUSK_BINARY_TARGET_NAME}" "${DUSK_PSP_PARAM_SFO}"
COMMENT "Generating PARAM.SFO for ${DUSK_BINARY_TARGET_NAME}"
VERBATIM
)
add_custom_target(DuskPspParamSfo DEPENDS "${DUSK_PSP_PARAM_SFO}")
# create_pbp_file()'s own POST_BUILD chain (below) also consumes
# DUSK_PSP_PARAM_SFO, so make sure it exists before that chain runs.
add_dependencies(${DUSK_BINARY_TARGET_NAME} DuskPspParamSfo)
# Postbuild, create .pbp file for PSP.
create_pbp_file(
TARGET "${DUSK_BINARY_TARGET_NAME}"
@@ -71,4 +91,33 @@ create_pbp_file(
TITLE "${DUSK_BINARY_TARGET_NAME}"
PSAR_PATH ${DUSK_ASSETS_ZIP}
VERSION 01.00
)
SFO_PATH "${DUSK_PSP_PARAM_SFO}"
OUTPUT_DIR "${DUSK_BUILD_DIR}"
)
# CreatePBP.cmake's pack-pbp step is a POST_BUILD command tied to the
# executable target, so it only reruns when the ELF itself relinks. That
# means regenerating dusk.dsk (assets) alone, without touching any C
# source, silently leaves EBOOT.PBP embedding a stale asset pak. Repack it
# here as a normal file-tracked custom command depending on both the
# executable and the asset zip, so EBOOT.PBP always reflects the current
# assets even when nothing else about the build changed.
set(DUSK_PSP_EBOOT "${DUSK_BUILD_DIR}/EBOOT.PBP")
if(BUILD_PRX)
set(DUSK_PSP_EXECUTABLE "$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>.prx")
else()
set(DUSK_PSP_EXECUTABLE "$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>")
endif()
add_custom_command(
OUTPUT "${DUSK_PSP_EBOOT}"
COMMAND "$ENV{PSPDEV}/bin/pack-pbp" "${DUSK_PSP_EBOOT}" "${DUSK_PSP_PARAM_SFO}"
"NULL" "NULL" "NULL" "NULL" "NULL"
"${DUSK_PSP_EXECUTABLE}" "${DUSK_ASSETS_ZIP}"
DEPENDS
"$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>"
"${DUSK_PSP_PARAM_SFO}"
"${DUSK_ASSETS_ZIP}"
COMMENT "Repacking EBOOT.PBP (tracks executable + asset pak freshness)"
VERBATIM
)
add_custom_target(DuskPspEbootRepack ALL DEPENDS "${DUSK_PSP_EBOOT}")
+88
View File
@@ -0,0 +1,88 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
if(NOT DEFINED ENV{VITASDK})
message(FATAL_ERROR "VITASDK environment variable is not set.")
endif()
include("$ENV{VITASDK}/share/vita.cmake" REQUIRED)
set(VITA_APP_NAME "Dusk")
set(VITA_TITLEID "DUSK00001")
set(VITA_VERSION "01.00")
find_package(SDL2 REQUIRED)
# Custom flags for cglm
set(CGLM_SHARED OFF CACHE BOOL "Build cglm shared" FORCE)
set(CGLM_STATIC ON CACHE BOOL "Build cglm static" FORCE)
find_package(cglm REQUIRED)
# Link libraries
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
${SDL2_LIBRARIES}
cglm
SDL2
SDL2main
zip
bz2
z
zstd
crypto
lzma
m
pthread
stdc++
vitaGL
mathneon
vitashark
kubridge_stub
SceAppMgr_stub
SceAudio_stub
SceCtrl_stub
SceCommonDialog_stub
SceDisplay_stub
SceKernelDmacMgr_stub
SceGxm_stub
SceShaccCg_stub
SceSysmodule_stub
ScePower_stub
SceTouch_stub
SceVshBridge_stub
SceIofilemgr_stub
SceShaccCgExt
libtaihen_stub.a
# SceKernel_stub
SceAppUtil_stub
SceHid_stub
SceRtc_stub
)
target_include_directories(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
${SDL2_INCLUDE_DIRS}
)
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_SDL2
DUSK_OPENGL
DUSK_VITA
DUSK_INPUT_GAMEPAD
DUSK_PLATFORM_ENDIAN_LITTLE
DUSK_OPENGL_LEGACY
DUSK_DISPLAY_WIDTH=960
DUSK_DISPLAY_HEIGHT=544
)
# Post-build: create SELF from the ELF binary (UNSAFE = homebrew, no signing)
vita_create_self(${DUSK_BINARY_TARGET_NAME}.self ${DUSK_BINARY_TARGET_NAME} UNSAFE)
# Post-build: package SELF + assets into a .vpk installable on the Vita
vita_create_vpk(${DUSK_BINARY_TARGET_NAME}.vpk ${VITA_TITLEID} ${DUSK_BINARY_TARGET_NAME}.self
VERSION ${VITA_VERSION}
NAME ${VITA_APP_NAME}
FILE ${DUSK_ASSETS_ZIP} dusk.dsk
)
+11
View File
@@ -4,6 +4,17 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_WII
)
# Wii save storage method - see src/duskdolphin/save/savedeviceplatform.h.
set(DUSK_SAVE_WII_METHOD "NAND" CACHE STRING
"Wii save storage: NAND (internal storage via ISFS), CARD (GameCube-\
compatible memory card emulation), or SD (SD card via libfat)"
)
set_property(CACHE DUSK_SAVE_WII_METHOD PROPERTY STRINGS "NAND" "CARD" "SD")
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_SAVE_WII_METHOD_${DUSK_SAVE_WII_METHOD}
)
# Generate Homebrew Channel meta.xml from project identity variables
string(TIMESTAMP DUSK_BUILD_DATE "%Y%m%d000000" UTC)
configure_file(
-7
View File
@@ -1,7 +0,0 @@
FROM ghcr.io/extremscorner/libogc2
WORKDIR /workdir
RUN apt update && \
dkp-pacman -Syu --noconfirm && \
apt install -y python3 python3-pip python3-polib python3-pil python3-dotenv python3-pyqt5 python3-opengl xorriso dolphin-emu xvfb && \
dkp-pacman -S --needed --noconfirm gamecube-sdl2 ppc-liblzma ppc-libzip libogc2 gamecube-tools ppc-libmad ppc-zlib-ng ppc-liblzma ppc-bzip2 ppc-zstd
VOLUME ["/workdir"]
-28
View File
@@ -1,28 +0,0 @@
FROM pspdev/pspdev:latest
WORKDIR /workdir
RUN apk add --no-cache \
python3 \
py3-pip \
py3-dotenv \
git \
cmake \
make \
g++ \
sdl2-dev \
zlib-dev \
linux-headers
# PPSSPP has no Alpine/Linux distro package -- build the "PPSSPPHeadless"
# target (the CLI/no-window build PPSSPP's own CI uses for automated runs)
# from source instead. The target name and exact CMake options have moved
# around across PPSSPP versions -- if this breaks, check
# https://github.com/hrydgard/ppsspp's CMakeLists.txt for the current name.
RUN git clone --recursive --depth 1 \
https://github.com/hrydgard/ppsspp.git /opt/ppsspp && \
cd /opt/ppsspp && \
cmake -B build -DCMAKE_BUILD_TYPE=Release && \
cmake --build build --target PPSSPPHeadless -- -j$(nproc) && \
cp build/PPSSPPHeadless /usr/local/bin/PPSSPPHeadless && \
rm -rf /opt/ppsspp
VOLUME ["/workdir"]
-3
View File
@@ -1,3 +0,0 @@
#!/bin/bash
docker build -t dusk-dolphin-test -f docker/dolphin-test/Dockerfile .
docker run --rm -v "$(pwd):/workdir" dusk-dolphin-test /bin/bash -c "./scripts/test-gamecube-dolphin.sh"
-45
View File
@@ -1,45 +0,0 @@
#!/bin/bash
set -e
if [ -z "$DEVKITPRO" ]; then
echo "DEVKITPRO environment variable is not set. Please set it to the path of your DEVKITPRO installation."
exit 1
fi
DOLPHIN_BIN="${DOLPHIN_BIN:-dolphin-emu}"
if ! command -v "$DOLPHIN_BIN" >/dev/null 2>&1; then
echo "$DOLPHIN_BIN not found. Install Dolphin Emulator (e.g. 'apt install dolphin-emu')"
echo "or set DOLPHIN_BIN to its path."
exit 1
fi
if ! command -v xvfb-run >/dev/null 2>&1; then
echo "xvfb-run not found. Install it (e.g. 'apt install xvfb') -- Dolphin's"
echo "Qt frontend needs a display even in batch mode."
exit 1
fi
./scripts/build-gamecube-iso.sh
DUSK_TEST_DOLPHIN_SECONDS="${DUSK_TEST_DOLPHIN_SECONDS:-20}"
ISO="build-gamecube-iso/Dusk-NTSC-U.iso"
echo "Booting $ISO in Dolphin for up to ${DUSK_TEST_DOLPHIN_SECONDS}s (batch mode, headless via Xvfb)..."
# Dolphin's batch mode (-b -e) runs the disc until told to stop -- there's
# no "the game exited cleanly" signal to wait for, so we bound it with
# timeout and treat "still running when the clock ran out" as success.
set +e
xvfb-run -a timeout "${DUSK_TEST_DOLPHIN_SECONDS}" "$DOLPHIN_BIN" -b -e "$ISO"
status=$?
set -e
# timeout returns 124 when it had to kill Dolphin after the duration
# elapsed -- that means the disc booted and kept running, the expected
# smoke-test-passed outcome, not a failure. Any other non-zero status
# means Dolphin crashed or refused to boot the disc.
if [ "$status" -ne 0 ] && [ "$status" -ne 124 ]; then
echo "Dolphin exited with unexpected status $status -- treating as a failure."
exit "$status"
fi
echo "GameCube smoke test passed (Dolphin ran $ISO for ${DUSK_TEST_DOLPHIN_SECONDS}s without crashing)."
-3
View File
@@ -1,3 +0,0 @@
#!/bin/bash
docker build -t dusk-psp-test -f docker/psp-test/Dockerfile .
docker run --rm -v "$(pwd):/workdir" dusk-psp-test /bin/bash -c "./scripts/test-psp-ppsspp.sh"
-42
View File
@@ -1,42 +0,0 @@
#!/bin/bash
set -e
if [ -z "$PSPDEV" ]; then
echo "PSPDEV environment variable is not set. Please set it to the path of your PSP development environment."
exit 1
fi
# PPSSPP doesn't ship a standard Linux package -- build its "PPSSPPHeadless"
# target from source (https://github.com/hrydgard/ppsspp) and either put it
# on PATH or point PPSSPP_HEADLESS_BIN at it. See docker/psp-test/Dockerfile
# for a from-scratch build.
PPSSPP_HEADLESS_BIN="${PPSSPP_HEADLESS_BIN:-PPSSPPHeadless}"
if ! command -v "$PPSSPP_HEADLESS_BIN" >/dev/null 2>&1; then
echo "$PPSSPP_HEADLESS_BIN not found. Build PPSSPP's 'PPSSPPHeadless' target"
echo "from source or set PPSSPP_HEADLESS_BIN to its path."
exit 1
fi
./scripts/build-psp.sh
DUSK_TEST_PPSSPP_SECONDS="${DUSK_TEST_PPSSPP_SECONDS:-20}"
EBOOT="build-psp/EBOOT.PBP"
echo "Booting $EBOOT in PPSSPPHeadless (timeout ${DUSK_TEST_PPSSPP_SECONDS}s)..."
# PPSSPPHeadless is purpose-built for automated/CI runs -- it renders
# without a window and is expected to exit on its own once --timeout
# elapses, unlike Dolphin's batch mode which has to be killed externally.
# Check `"$PPSSPP_HEADLESS_BIN" --help` if these flags don't match your
# PPSSPP checkout -- the headless CLI has changed across versions.
set +e
"$PPSSPP_HEADLESS_BIN" --timeout="${DUSK_TEST_PPSSPP_SECONDS}" "$EBOOT"
status=$?
set -e
if [ "$status" -ne 0 ]; then
echo "PPSSPPHeadless exited with status $status"
exit "$status"
fi
echo "PSP smoke test passed (PPSSPPHeadless ran EBOOT.PBP for ${DUSK_TEST_PPSSPP_SECONDS}s without crashing)."
-3
View File
@@ -1,3 +0,0 @@
#!/bin/bash
docker build -t dusk-dolphin-test -f docker/dolphin-test/Dockerfile .
docker run --rm -v "$(pwd):/workdir" dusk-dolphin-test /bin/bash -c "./scripts/test-wii-dolphin.sh"
-45
View File
@@ -1,45 +0,0 @@
#!/bin/bash
set -e
if [ -z "$DEVKITPRO" ]; then
echo "DEVKITPRO environment variable is not set. Please set it to the path of your DEVKITPRO installation."
exit 1
fi
DOLPHIN_BIN="${DOLPHIN_BIN:-dolphin-emu}"
if ! command -v "$DOLPHIN_BIN" >/dev/null 2>&1; then
echo "$DOLPHIN_BIN not found. Install Dolphin Emulator (e.g. 'apt install dolphin-emu')"
echo "or set DOLPHIN_BIN to its path."
exit 1
fi
if ! command -v xvfb-run >/dev/null 2>&1; then
echo "xvfb-run not found. Install it (e.g. 'apt install xvfb') -- Dolphin's"
echo "Qt frontend needs a display even in batch mode."
exit 1
fi
./scripts/build-wii-iso.sh
DUSK_TEST_DOLPHIN_SECONDS="${DUSK_TEST_DOLPHIN_SECONDS:-20}"
ISO="build-wii-iso/Dusk-NTSC-U.iso"
echo "Booting $ISO in Dolphin for up to ${DUSK_TEST_DOLPHIN_SECONDS}s (batch mode, headless via Xvfb)..."
# Dolphin's batch mode (-b -e) runs the disc until told to stop -- there's
# no "the game exited cleanly" signal to wait for, so we bound it with
# timeout and treat "still running when the clock ran out" as success.
set +e
xvfb-run -a timeout "${DUSK_TEST_DOLPHIN_SECONDS}" "$DOLPHIN_BIN" -b -e "$ISO"
status=$?
set -e
# timeout returns 124 when it had to kill Dolphin after the duration
# elapsed -- that means the disc booted and kept running, the expected
# smoke-test-passed outcome, not a failure. Any other non-zero status
# means Dolphin crashed or refused to boot the disc.
if [ "$status" -ne 0 ] && [ "$status" -ne 124 ]; then
echo "Dolphin exited with unexpected status $status -- treating as a failure."
exit "$status"
fi
echo "Wii smoke test passed (Dolphin ran $ISO for ${DUSK_TEST_DOLPHIN_SECONDS}s without crashing)."
+9 -1
View File
@@ -4,7 +4,10 @@
# https://opensource.org/licenses/MIT
add_subdirectory(dusk)
add_subdirectory(duskrpg)
if(DUSK_NETWORK)
add_subdirectory(dusknetwork)
endif()
if(DUSK_TARGET_SYSTEM STREQUAL "linux" OR DUSK_TARGET_SYSTEM STREQUAL "knulli")
add_subdirectory(dusklinux)
@@ -16,6 +19,11 @@ elseif(DUSK_TARGET_SYSTEM STREQUAL "psp")
add_subdirectory(dusksdl2)
add_subdirectory(duskgl)
elseif(DUSK_TARGET_SYSTEM STREQUAL "vita")
add_subdirectory(duskvita)
add_subdirectory(dusksdl2)
add_subdirectory(duskgl)
elseif(DUSK_TARGET_SYSTEM STREQUAL "wii" OR DUSK_TARGET_SYSTEM STREQUAL "gamecube")
add_subdirectory(duskdolphin)
+1 -15
View File
@@ -32,15 +32,6 @@ if(NOT yyjson_FOUND)
endif()
endif()
if(NOT jerryscript_FOUND)
find_package(jerryscript REQUIRED)
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
jerryscript::core
jerryscript::ext
jerryscript::port
)
endif()
if(DUSK_BACKTRACE)
target_link_options(${DUSK_LIBRARY_TARGET_NAME} PUBLIC -rdynamic)
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
@@ -62,25 +53,20 @@ target_sources(${DUSK_BINARY_TARGET_NAME}
# Subdirs
add_subdirectory(animation)
add_subdirectory(event)
add_subdirectory(assert)
add_subdirectory(asset)
add_subdirectory(console)
add_subdirectory(display)
add_subdirectory(entity)
add_subdirectory(log)
add_subdirectory(engine)
add_subdirectory(error)
add_subdirectory(game)
add_subdirectory(input)
add_subdirectory(locale)
add_subdirectory(rpg)
add_subdirectory(scene)
add_subdirectory(system)
add_subdirectory(time)
add_subdirectory(ui)
add_subdirectory(network)
add_subdirectory(physics)
add_subdirectory(save)
add_subdirectory(script)
add_subdirectory(util)
add_subdirectory(thread)
+1 -2
View File
@@ -6,7 +6,6 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
easing.c
keyframe.c
keyframeset.c
animation.c
keyframe.c
)
+109 -51
View File
@@ -5,70 +5,128 @@
#include "animation.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/math.h"
#include "time/time.h"
void animationInit(
animation_t *anim,
keyframe_t **tracks,
uint16_t *trackCounts,
uint16_t trackCount
keyframe_t *keyframes,
uint16_t *keyframeCounts,
const uint16_t layerCount
) {
assertNotNull(anim, "Animation pointer cannot be null.");
assertNotNull(keyframes, "Keyframes pointer cannot be null.");
assertNotNull(keyframeCounts, "Keyframe counts pointer cannot be null.");
assertTrue(layerCount > 0, "Layer count must be greater than zero.");
keyframeSetInit(
&anim->keyframes, tracks, trackCounts, NULL, NULL, trackCount, NULL
);
anim->time = 0.0f;
anim->speed = 1.0f;
anim->loop = false;
anim->playing = false;
anim->eventTime = 0.0f;
anim->eventCallback = NULL;
anim->eventUser = NULL;
memoryZero(anim, sizeof(animation_t));
anim->keyframes = keyframes;
anim->keyframeCounts = keyframeCounts;
anim->layerCount = layerCount;
// Determine duration
float_t duration = 0.0f;
for(uint16_t layer = 0; layer < layerCount; layer++) {
uint16_t keyframeCount = keyframeCounts[layer];
assertTrue(keyframeCount > 0, "Keyframe count invalid.");
keyframe_t *layerKeyframes = keyframes + layer * keyframeCount;
#ifdef DUSK_ASSERTIONS
// Check that the keyframes are sorted by time.
for(uint16_t i = 1; i < keyframeCount; i++) {
assertTrue(
layerKeyframes[i].time >= layerKeyframes[i - 1].time,
"Keyframes must be sorted by time."
);
}
#endif
keyframe_t *lastKeyframe = layerKeyframes + keyframeCount - 1;
duration = mathMax(duration, lastKeyframe->time);
}
assertTrue(duration > 0, "Animation duration must be greater than 0.");
anim->duration = duration;
}
void animationUpdate(animation_t *anim) {
float_t animationGetLayerValue(const animation_t *anim, const uint16_t layer) {
assertNotNull(anim, "Animation pointer cannot be null.");
if(!anim->playing) return;
assertTrue(layer < anim->layerCount, "Layer index out of bounds.");
float_t duration = keyframeSetGetDuration(&anim->keyframes);
float_t prevTime = anim->time;
anim->time += TIME.delta * anim->speed;
uint16_t keyframeCount = anim->keyframeCounts[layer];
keyframe_t *layerKeyframes = anim->keyframes + layer * keyframeCount;
return keyframeGetValue(layerKeyframes, keyframeCount, anim->time);
}
// Loops that overshoot duration wrap back into [0, duration) -- an event
// near the end must still be checked across that wrap, as two segments:
// (prevTime, duration] then [0, newTime].
bool_t wrapped = anim->loop && duration > 0.0f && anim->time >= duration;
void animationUpdate(
animation_t *anim,
const float_t deltaTime
) {
assertNotNull(anim, "Animation pointer cannot be null.");
assertTrue(deltaTime >= 0, "Delta time must be non-negative.");
if(anim->loop) {
if(duration > 0.0f) anim->time = mathModFloat(anim->time, duration);
} else if(anim->time >= duration) {
anim->time = duration;
anim->playing = false;
bool_t justCompleted = false;
if(!(anim->flags & ANIMATION_FLAG_INTERNAL_COMPLETED)) {
bool_t loop = (anim->flags & ANIMATION_FLAG_LOOP) != 0;
bool_t pingpong = (anim->flags & ANIMATION_FLAG_PINGPONG) != 0;
assertFalse(
loop && pingpong,
"Cannot set both ANIMATION_FLAG_LOOP and ANIMATION_FLAG_PINGPONG."
);
bool_t backward;
if(pingpong) {
backward = (anim->flags & ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD) != 0;
} else {
backward = (anim->flags & ANIMATION_FLAG_REVERSE) != 0;
}
// Resolve boundary crossings one at a time, so a single large deltaTime
// can correctly loop/pingpong across multiple boundaries in one call.
float_t remaining = deltaTime;
while(remaining > 0.0f) {
float_t toBoundary = (
backward ? anim->time : (anim->duration - anim->time)
);
if(remaining < toBoundary) {
anim->time += backward ? -remaining : remaining;
break;
}
remaining -= toBoundary;
anim->time = backward ? 0.0f : anim->duration;
bool_t stopHere;
if(backward) {
stopHere = (anim->flags & ANIMATION_FLAG_STOP_BEGINNING) != 0;
} else {
stopHere = (anim->flags & ANIMATION_FLAG_STOP_END) != 0;
}
if(stopHere) {
justCompleted = true;
break;
} else if(pingpong) {
backward = !backward;
if(backward) anim->flags |= ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD;
else anim->flags &= ~ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD;
} else if(loop) {
anim->time = backward ? anim->duration : 0.0f;
if(anim->onLoop) anim->onLoop(anim->user);
} else {
justCompleted = true;
break;
}
}
if(justCompleted) anim->flags |= ANIMATION_FLAG_INTERNAL_COMPLETED;
}
if(!anim->eventCallback) return;
// Call onUpdate for each layer.
for(uint16_t layer = 0; layer < anim->layerCount; layer++) {
float_t value = animationGetLayerValue(anim, layer);
if(anim->onUpdate) anim->onUpdate(layer, value, anim->user);
}
bool_t crossed = wrapped
? (prevTime < anim->eventTime || anim->time >= anim->eventTime)
: (prevTime < anim->eventTime && anim->time >= anim->eventTime);
if(crossed) anim->eventCallback(anim, anim->eventUser);
}
void animationSetEvent(
animation_t *anim,
const float_t time,
const animationeventcallback_t callback,
void *user
) {
assertNotNull(anim, "Animation pointer cannot be null.");
anim->eventTime = time;
anim->eventCallback = callback;
anim->eventUser = user;
}
float_t animationGetValue(animation_t *anim, const uint16_t trackIndex) {
assertNotNull(anim, "Animation pointer cannot be null.");
return keyframeSetGetValue(&anim->keyframes, trackIndex, anim->time);
}
if(justCompleted && anim->onComplete) anim->onComplete(anim->user);
}
+67 -75
View File
@@ -4,99 +4,91 @@
// https://opensource.org/licenses/MIT
#pragma once
#include "keyframeset.h"
#include "keyframe.h"
typedef struct animation_t animation_t;
#define ANIMATION_FLAG_LOOP (1 << 0)
#define ANIMATION_FLAG_REVERSE (1 << 1)
#define ANIMATION_FLAG_PINGPONG (1 << 2)
#define ANIMATION_FLAG_STOP_BEGINNING (1 << 3)
#define ANIMATION_FLAG_STOP_END (1 << 4)
/**
* Callback fired once when animationUpdate() advances time past
* eventTime (see animationSetEvent()).
*
* @param anim The animation whose event fired.
* @param user The user pointer passed to animationSetEvent().
*/
typedef void (*animationeventcallback_t)(animation_t *anim, void *user);
// Internal - tracks which direction a pingponging animation is currently
// travelling. Do not set this manually, it is managed by animationUpdate().
#define ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD (1 << 7)
typedef struct animation_t {
/** The animation's tracks/channels and their raw keyframe data. */
keyframeset_t keyframes;
// Internal - set once the animation has stopped advancing (see
// animationUpdate()). Do not set this manually. There is currently no way to
// restart a completed animation short of clearing this bit and resetting
// anim->time by hand.
#define ANIMATION_FLAG_INTERNAL_COMPLETED (1 << 6)
/** Current playback position, in seconds. */
typedef struct {
keyframe_t *keyframes;
uint16_t *keyframeCounts;
uint16_t layerCount;
float_t time;
float_t duration;
uint8_t flags;
/** Playback rate multiplier; 1.0 = normal speed. */
float_t speed;
/** True if animationUpdate() should wrap time back to 0 on reaching the
* final keyframe, rather than holding there and clearing playing. */
bool_t loop;
/** True while animationUpdate() should advance time each call. */
bool_t playing;
/** Time (seconds) at which eventCallback fires; see animationSetEvent(). */
float_t eventTime;
/** Callback fired once when time advances past eventTime, or NULL. */
animationeventcallback_t eventCallback;
/** User pointer passed to eventCallback unchanged. */
void *eventUser;
void *user;
void (*onUpdate)(const uint16_t layer, const float_t value, void *user);
void (*onComplete)(void *user);
void (*onLoop)(void *user);
} animation_t;
/**
* Initializes an animation: time 0, speed 1.0, not looping, not playing.
* See keyframeSetInit() -- tracks/trackCounts and the keyframe_t arrays
* they point to are not copied, and must outlive this animation.
* Initializes an animation with the given keyframes and layer count.
*
* @param anim The animation to initialize.
* @param tracks Array of trackCount keyframe_t arrays.
* @param trackCounts Array of trackCount keyframe counts, matching tracks.
* @param trackCount The number of tracks/channels in this animation.
* @param anim Pointer to the animation to initialize.
* @param keyframes Pointer to the array of keyframes for each layer.
* @param keyframeCount Number of keyframes in each layer.
* @param layerCount Number of layers in the animation.
*/
void animationInit(
animation_t *anim,
keyframe_t **tracks,
uint16_t *trackCounts,
uint16_t trackCount
keyframe_t *keyframes,
uint16_t *keyframeCounts,
const uint16_t layerCount
);
/**
* Advances an animation's time by TIME.delta * speed. No-op if not
* playing. Duration is the latest of every track's final keyframe time
* (see keyframeSetGetDuration()). If loop is set, time wraps back into
* [0, duration) on reaching it; otherwise time is clamped there and
* playing is cleared.
*
* If eventCallback is set, it fires once when this call advances time
* from at or before eventTime to after it (checked across the loop wrap
* point too, so an event near the end of a looping animation still fires
* every loop).
*
* @param anim The animation to update.
* Sets the current time of the animation, clamping it to the valid range.
* This will call the onUpdate callback but none of the other callbacks.
*
* @param anim Pointer to the animation to set the time for.
* @param time The new time to set for the animation.
*/
void animationUpdate(animation_t *anim);
void animationSetTime(animation_t *anim, const float_t time);
/**
* Sets (or clears, with callback NULL) the single time-triggered event
* fired by animationUpdate().
*
* @param anim The animation to set the event on.
* @param time The time, in seconds, at which callback fires.
* @param callback The callback to invoke, or NULL to clear any event.
* @param user Arbitrary pointer forwarded to callback unchanged.
* Gets the current value of a specific layer in the animation based on the
* current animation time.
*/
void animationSetEvent(
float_t animationGetLayerValue(const animation_t *anim, const uint16_t layer);
/**
* Updates the animation state based on the elapsed time. Advances anim->time
* by deltaTime (or against it, if ANIMATION_FLAG_REVERSE is set), then
* resolves whatever happens when it reaches the 0 or duration boundary:
*
* - ANIMATION_FLAG_PINGPONG: reflects off the boundary and continues playing
* in the opposite direction, forever, unless stopped (see below).
* - ANIMATION_FLAG_LOOP: wraps back around to the other boundary and keeps
* playing in the same direction, forever, unless stopped (see below).
* - ANIMATION_FLAG_STOP_BEGINNING / ANIMATION_FLAG_STOP_END: when the
* animation reaches that specific boundary, it clamps there and stops
* (firing onComplete) instead of looping/pingponging past it.
* - If none of the above apply at a boundary, the animation clamps there and
* stops, firing onComplete.
*
* onUpdate is called for every layer on every call. onLoop is called each
* time a loop wraps around. onComplete is called at most once, the moment
* the animation stops advancing.
*
* @param anim Pointer to the animation to update.
* @param deltaTime Time elapsed since the last update (in seconds).
*/
void animationUpdate(
animation_t *anim,
const float_t time,
const animationeventcallback_t callback,
void *user
);
/**
* Gets the value of one of the animation's tracks at its current
* playback time.
*
* @param anim The animation to get the value from.
* @param trackIndex The track to evaluate, in [0, trackCount).
* @return The interpolated value of that track at the current time.
*/
float_t animationGetValue(animation_t *anim, const uint16_t trackIndex);
const float_t deltaTime
);
+26 -24
View File
@@ -1,43 +1,45 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "keyframe.h"
#include "assert/assert.h"
#include "util/math.h"
float_t keyframeGetValue(
keyframe_t *keyframes,
const uint16_t keyframeCount,
const keyframe_t *keyframes,
const uint32_t keyframeCount,
const float_t time
) {
assertNotNull(keyframes, "Keyframes pointer cannot be null.");
assertTrue(keyframeCount > 0, "Keyframe count must be more than 0.");
assertTrue(time >= 0, "Time must be non-negative.");
#ifdef DUSK_ASSERTIONS
// Checks that the keyframes are sorted by time.
for(uint32_t i = 1; i < keyframeCount; i++) {
assertTrue(
keyframes[i].time >= keyframes[i - 1].time,
"Keyframes must be sorted by time."
);
}
#endif
keyframe_t *first = keyframes;
keyframe_t *last = keyframes + keyframeCount - 1;
// Clamp to the boundary keyframes' values directly rather than
// interpolating -- start == end at either boundary would otherwise
// divide by zero.
if(time <= first->time) return first->value;
keyframe_t *last = (keyframe_t *)(keyframes + keyframeCount - 1);
if(time >= last->time) return last->value;
keyframe_t *start = first;
keyframe_t *end;
keyframe_t *current = first;
do {
if(current->time > time) {
end = current;
break;
}
// Since time < last->time (checked above), current is guaranteed to stop
// at or before reaching last, so no separate end-of-array check is needed.
keyframe_t *current = (keyframe_t *)keyframes;
keyframe_t *start = current;
while(current->time <= time) {
start = current;
current++;
} while(true);
}
keyframe_t *end = current;
float_t t = (time - start->time) / (end->time - start->time);
return mathLerp(start->value, end->value, easingApply(start->easing, t));
}
}
+7 -7
View File
@@ -13,15 +13,15 @@ typedef struct {
} keyframe_t;
/**
* Gets the eased, interpolated value of a keyframe array at a given time.
*
* @param keyframes The keyframes to evaluate, ascending by time.
* @param keyframeCount The number of keyframes.
* Gets the value of a keyframe at a given time.
*
* @param keyframes The keyframes to get the value from.
* @param keyframeCount The number of keyframes in the array.
* @param time The time at which to get the value, in seconds.
* @return The interpolated value at the given time.
* @return The value of the keyframe at the given time.
*/
float_t keyframeGetValue(
keyframe_t *keyframes,
const uint16_t keyframeCount,
const keyframe_t *keyframes,
const uint32_t keyframeCount,
const float_t time
);
-76
View File
@@ -1,76 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include "keyframeset.h"
#include "assert/assert.h"
void keyframeSetInit(
keyframeset_t *set,
keyframe_t **tracks,
uint16_t *trackCounts,
keyframesetcallback_t *callbacks,
void **users,
uint16_t trackCount,
void *user
) {
assertNotNull(set, "Keyframe set pointer cannot be null.");
assertNotNull(tracks, "Tracks pointer cannot be null.");
assertNotNull(trackCounts, "Track counts pointer cannot be null.");
assertTrue(trackCount > 0, "Track count must be more than 0.");
set->tracks = tracks;
set->trackCounts = trackCounts;
set->trackCount = trackCount;
set->callbacks = callbacks;
set->users = users;
set->user = user;
}
float_t keyframeSetGetValue(
keyframeset_t *set,
const uint16_t trackIndex,
const float_t time
) {
assertNotNull(set, "Keyframe set pointer cannot be null.");
assertTrue(trackIndex < set->trackCount, "Track index out of bounds.");
return keyframeGetValue(
set->tracks[trackIndex], set->trackCounts[trackIndex], time
);
}
void keyframeSetGetValues(
keyframeset_t *set,
const float_t time,
float_t *outValues
) {
assertNotNull(set, "Keyframe set pointer cannot be null.");
assertNotNull(outValues, "Output values pointer cannot be null.");
for(uint16_t i = 0; i < set->trackCount; i++) {
outValues[i] = keyframeGetValue(set->tracks[i], set->trackCounts[i], time);
}
}
float_t keyframeSetGetDuration(keyframeset_t *set) {
assertNotNull(set, "Keyframe set pointer cannot be null.");
float_t duration = 0.0f;
for(uint16_t i = 0; i < set->trackCount; i++) {
float_t trackDuration = set->tracks[i][set->trackCounts[i] - 1].time;
if(trackDuration > duration) duration = trackDuration;
}
return duration;
}
void keyframeSetFireCallback(keyframeset_t *set, const uint16_t trackIndex) {
assertNotNull(set, "Keyframe set pointer cannot be null.");
assertTrue(trackIndex < set->trackCount, "Track index out of bounds.");
if(!set->callbacks || !set->callbacks[trackIndex]) return;
set->callbacks[trackIndex](
set, trackIndex, set->users ? set->users[trackIndex] : NULL
);
}
-116
View File
@@ -1,116 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#pragma once
#include "keyframe.h"
typedef struct keyframeset_t keyframeset_t;
/**
* Callback associated with one track of a keyframe set (see
* keyframeSetFireCallback()).
*
* @param set The keyframe set the track belongs to.
* @param trackIndex The track this callback is registered for.
* @param user The per-track user pointer passed to keyframeSetInit().
*/
typedef void (*keyframesetcallback_t)(
keyframeset_t *set,
const uint16_t trackIndex,
void *user
);
/**
* A group of N parallel keyframe tracks (e.g. one per animated channel --
* position.x/y/z, bone rotations, etc.) sharing a single timeline. Each
* track is independent: its own keyframe array and count, evaluated at
* whatever time is asked for.
*/
typedef struct keyframeset_t {
/** Caller-owned array of trackCount keyframe_t arrays. */
keyframe_t **tracks;
/** Caller-owned array of trackCount counts, one per entry in tracks. */
uint16_t *trackCounts;
uint16_t trackCount;
/** Caller-owned array of trackCount callbacks, one per track. Entries
* (or the whole array) may be NULL for tracks with no callback. */
keyframesetcallback_t *callbacks;
/** Caller-owned array of trackCount user pointers, one per track,
* passed to that track's callbacks[] entry. May be NULL. */
void **users;
/** Extra user data for the set as a whole, not tied to any one track. */
void *user;
} keyframeset_t;
/**
* Initializes a keyframe set. None of the passed-in arrays (or the
* keyframe_t arrays tracks points to) are copied -- they must outlive
* this keyframeset_t.
*
* @param set The keyframe set to initialize.
* @param tracks Array of trackCount keyframe_t arrays.
* @param trackCounts Array of trackCount keyframe counts, matching tracks.
* @param callbacks Array of trackCount callbacks, one per track, or NULL
* if no track has one.
* @param users Array of trackCount user pointers, matching callbacks, or
* NULL.
* @param trackCount The number of tracks.
* @param user Extra user data for the set as a whole; may be NULL.
*/
void keyframeSetInit(
keyframeset_t *set,
keyframe_t **tracks,
uint16_t *trackCounts,
keyframesetcallback_t *callbacks,
void **users,
uint16_t trackCount,
void *user
);
/**
* Gets the value of a single track at a given time.
*
* @param set The keyframe set to evaluate.
* @param trackIndex The track to evaluate, in [0, set->trackCount).
* @param time The time at which to get the value, in seconds.
* @return The interpolated value of that track at the given time.
*/
float_t keyframeSetGetValue(
keyframeset_t *set,
const uint16_t trackIndex,
const float_t time
);
/**
* Gets the value of every track at a given time.
*
* @param set The keyframe set to evaluate.
* @param time The time at which to get the values, in seconds.
* @param outValues Destination array of at least set->trackCount floats.
*/
void keyframeSetGetValues(
keyframeset_t *set,
const float_t time,
float_t *outValues
);
/**
* Gets the set's duration: the latest final-keyframe time across every
* track, i.e. how long it takes for every track to finish.
*
* @param set The keyframe set to measure.
* @return The set's duration, in seconds.
*/
float_t keyframeSetGetDuration(keyframeset_t *set);
/**
* Invokes a track's callback, if it (and its callbacks array) is set.
* No-op otherwise.
*
* @param set The keyframe set the track belongs to.
* @param trackIndex The track whose callback to invoke.
*/
void keyframeSetFireCallback(keyframeset_t *set, const uint16_t trackIndex);
+2 -7
View File
@@ -8,13 +8,6 @@
#pragma once
#include "dusk.h"
// Release-style CMake configs (Release, RelWithDebInfo, MinSizeRel) define
// NDEBUG automatically; fake assertions there rather than requiring every
// platform's CMakeLists to set DUSK_ASSERTIONS_FAKED itself.
#if defined(NDEBUG) && !defined(DUSK_ASSERTIONS_FAKED)
#define DUSK_ASSERTIONS_FAKED
#endif
#ifdef DUSK_TEST_ASSERT
#include <cmocka.h>
@@ -29,6 +22,8 @@
#endif
#ifndef DUSK_ASSERTIONS_FAKED
#define DUSK_ASSERTIONS 1
/**
* Initializes the assert system. Must be the very first call in engine
* startup.
-1
View File
@@ -7,7 +7,6 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
asset.c
assetbatch.c
assetfile.c
)
+5 -3
View File
@@ -322,7 +322,9 @@ errorret_t assetUpdate(void) {
} else if(loading->entry->state == ASSET_ENTRY_STATE_LOADED) {
assetentry_t *loadedEntry = loading->entry;
loading->entry = NULL;
eventInvoke(&loadedEntry->onLoaded, loadedEntry);
if(loadedEntry->onLoaded) {
loadedEntry->onLoaded(loadedEntry, loadedEntry->onLoadedUser);
}
}
loading++;
@@ -346,8 +348,8 @@ errorret_t assetUpdate(void) {
assetentry_t *errEntry = loading->entry;
loading->entry = NULL;
threadMutexUnlock(&loading->mutex);
eventInvoke(&errEntry->onError, errEntry);
errorThrow("Failed to load asset asynchronously.");
if(errEntry->onError) errEntry->onError(errEntry, errEntry->onErrorUser);
loading++;
break;
}
-165
View File
@@ -1,165 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "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);
}
}
-124
View File
@@ -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);
+23 -6
View File
@@ -87,13 +87,30 @@ errorret_t assetFileRead(
errorOk();
}
// I assume zip_fread takes buffer NULL for skipping?
zip_int64_t bytesRead = zip_fread(file->zipFile, buffer, bufferSize);
if(bytesRead < 0) {
errorThrow("Failed to read from asset file: %s", file->filename);
// Some zip_fread() implementations (seen on PSP) reject a single call
// asking for the entire (potentially large) file at once with EINVAL;
// the line reader above only ever asks for up to 1024 bytes per call and
// works fine, so read in bounded chunks here too.
size_t totalRead = 0;
uint8_t *dest = (uint8_t *)buffer;
while(totalRead < bufferSize) {
size_t chunkSize = mathMin(
bufferSize - totalRead, ASSET_FILE_READ_CHUNK_MAX
);
zip_int64_t bytesRead = zip_fread(
file->zipFile, dest + totalRead, chunkSize
);
if(bytesRead < 0) {
errorThrow(
"Failed to read from asset file: %s (%s)",
file->filename, zip_file_strerror(file->zipFile)
);
}
if(bytesRead == 0) break;
totalRead += (size_t)bytesRead;
}
file->position += bytesRead;
file->lastRead = bytesRead;
file->position += totalRead;
file->lastRead = totalRead;
errorOk();
}
+6
View File
@@ -11,6 +11,12 @@
#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 errorret_t (*assetfileloader_t)(assetfile_t *file);
+2 -1
View File
@@ -15,5 +15,6 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
add_subdirectory(display)
add_subdirectory(locale)
add_subdirectory(json)
add_subdirectory(chunk)
add_subdirectory(dmf)
add_subdirectory(animation)
add_subdirectory(cutscene)
@@ -1,234 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetanimationloader.h"
#include "util/memory.h"
#include "util/string.h"
#include "assert/assert.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
errorret_t assetAnimationLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Async loader should not be on main thread.");
if(
loading->loading.animation.state != ASSET_ANIMATION_LOADING_STATE_READ_FILE
) {
errorOk();
}
assertNull(loading->loading.animation.buffer, "Buffer already defined?");
assetfile_t *file = &loading->loading.animation.file;
assetLoaderErrorChain(
loading, assetFileInit(file, loading->entry->name, NULL, NULL)
);
if(file->size > ASSET_ANIMATION_FILE_SIZE_MAX) {
assetLoaderErrorThrow(
loading, "Animation JSON exceeds maximum allowed size"
);
}
uint8_t *buffer;
size_t size;
assetLoaderErrorChain(loading, assetFileReadEntire(file, &buffer, &size));
assetLoaderErrorChain(loading, assetFileDispose(file));
loading->loading.animation.buffer = buffer;
loading->loading.animation.size = size;
loading->loading.animation.state = ASSET_ANIMATION_LOADING_STATE_PARSE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetAnimationLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_ANIMATION, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.animation.state) {
case ASSET_ANIMATION_LOADING_STATE_INITIAL:
loading->loading.animation.state =
ASSET_ANIMATION_LOADING_STATE_READ_FILE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
errorOk();
break;
case ASSET_ANIMATION_LOADING_STATE_PARSE:
break;
default:
errorOk();
}
uint8_t *buffer = loading->loading.animation.buffer;
assertNotNull(buffer, "Animation buffer should have been loaded by now.");
yyjson_doc *doc = yyjson_read(
(char *)buffer,
loading->loading.animation.size,
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
);
memoryFree(buffer);
loading->loading.animation.buffer = NULL;
if(!doc) assetLoaderErrorThrow(loading, "Failed to parse animation JSON");
yyjson_val *root = yyjson_doc_get_root(doc);
yyjson_val *channelsVal = yyjson_obj_get(root, "channels");
if(!channelsVal || !yyjson_is_arr(channelsVal)) {
yyjson_doc_free(doc);
assetLoaderErrorThrow(loading, "Animation JSON missing 'channels' array");
}
uint16_t channelCount = (uint16_t)yyjson_arr_size(channelsVal);
if(channelCount == 0) {
yyjson_doc_free(doc);
assetLoaderErrorThrow(loading, "Animation must have at least one channel");
}
keyframe_t **tracks = memoryAllocate(channelCount * sizeof(keyframe_t *));
uint16_t *trackCounts = memoryAllocate(channelCount * sizeof(uint16_t));
size_t idx, max;
yyjson_val *channelJson;
uint16_t parsed = 0;
yyjson_arr_foreach(channelsVal, idx, max, channelJson) {
keyframe_t *keyframes;
uint16_t count;
errorret_t ret =
assetAnimationParseChannel(channelJson, &keyframes, &count);
if(errorIsNotOk(ret)) {
assetAnimationFreeChannels(tracks, parsed);
memoryFree(trackCounts);
yyjson_doc_free(doc);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorChain(ret);
}
tracks[idx] = keyframes;
trackCounts[idx] = count;
parsed++;
}
animationInit(
&loading->entry->data.animation, tracks, trackCounts, channelCount
);
yyjson_val *loopVal = yyjson_obj_get(root, "loop");
if(loopVal) loading->entry->data.animation.loop = yyjson_get_bool(loopVal);
yyjson_val *speedVal = yyjson_obj_get(root, "speed");
if(speedVal) {
loading->entry->data.animation.speed = (float_t)yyjson_get_num(speedVal);
}
yyjson_doc_free(doc);
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
errorret_t assetAnimationDispose(assetentry_t *entry) {
assertNotNull(entry, "Asset entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_ANIMATION, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
// A load that failed before animationInit() ran (e.g. a parse error)
// never populated these -- nothing to free in that case.
keyframeset_t *set = &entry->data.animation.keyframes;
if(set->tracks) {
assetAnimationFreeChannels(set->tracks, set->trackCount);
memoryFree(set->trackCounts);
set->tracks = NULL;
set->trackCounts = NULL;
set->trackCount = 0;
}
errorOk();
}
errorret_t assetAnimationParseEasing(
const char_t *name,
easingtype_t *outEasing
) {
if(stringEquals(name, "LINEAR")) *outEasing = EASING_LINEAR;
else if(stringEquals(name, "IN_SINE")) *outEasing = EASING_IN_SINE;
else if(stringEquals(name, "OUT_SINE")) *outEasing = EASING_OUT_SINE;
else if(stringEquals(name, "IN_OUT_SINE")) *outEasing = EASING_IN_OUT_SINE;
else if(stringEquals(name, "IN_QUAD")) *outEasing = EASING_IN_QUAD;
else if(stringEquals(name, "OUT_QUAD")) *outEasing = EASING_OUT_QUAD;
else if(stringEquals(name, "IN_OUT_QUAD")) *outEasing = EASING_IN_OUT_QUAD;
else if(stringEquals(name, "IN_CUBIC")) *outEasing = EASING_IN_CUBIC;
else if(stringEquals(name, "OUT_CUBIC")) *outEasing = EASING_OUT_CUBIC;
else if(stringEquals(name, "IN_OUT_CUBIC")) *outEasing = EASING_IN_OUT_CUBIC;
else if(stringEquals(name, "IN_QUART")) *outEasing = EASING_IN_QUART;
else if(stringEquals(name, "OUT_QUART")) *outEasing = EASING_OUT_QUART;
else if(stringEquals(name, "IN_OUT_QUART")) *outEasing = EASING_IN_OUT_QUART;
else if(stringEquals(name, "IN_BACK")) *outEasing = EASING_IN_BACK;
else if(stringEquals(name, "OUT_BACK")) *outEasing = EASING_OUT_BACK;
else if(stringEquals(name, "IN_OUT_BACK")) *outEasing = EASING_IN_OUT_BACK;
else errorThrow("Unknown easing type '%s'", name);
errorOk();
}
errorret_t assetAnimationParseChannel(
yyjson_val *channelJson,
keyframe_t **outKeyframes,
uint16_t *outCount
) {
if(!yyjson_is_arr(channelJson)) {
errorThrow("Animation channel must be an array");
}
size_t count = yyjson_arr_size(channelJson);
if(count == 0) {
errorThrow("Animation channel must have at least one keyframe");
}
keyframe_t *keyframes = memoryAllocate(count * sizeof(keyframe_t));
size_t idx, max;
yyjson_val *keyframeJson;
yyjson_arr_foreach(channelJson, idx, max, keyframeJson) {
yyjson_val *timeVal = yyjson_obj_get(keyframeJson, "time");
yyjson_val *valueVal = yyjson_obj_get(keyframeJson, "value");
if(!timeVal || !valueVal) {
memoryFree(keyframes);
errorThrow("Animation keyframe missing 'time' or 'value'");
}
keyframes[idx].time = (float_t)yyjson_get_num(timeVal);
keyframes[idx].value = (float_t)yyjson_get_num(valueVal);
yyjson_val *easingVal = yyjson_obj_get(keyframeJson, "easing");
if(!easingVal) {
keyframes[idx].easing = EASING_LINEAR;
continue;
}
errorret_t ret = assetAnimationParseEasing(
yyjson_get_str(easingVal), &keyframes[idx].easing
);
if(errorIsNotOk(ret)) {
memoryFree(keyframes);
errorChain(ret);
}
}
*outKeyframes = keyframes;
*outCount = (uint16_t)count;
errorOk();
}
void assetAnimationFreeChannels(keyframe_t **tracks, const uint16_t count) {
for(uint16_t i = 0; i < count; i++) memoryFree(tracks[i]);
memoryFree(tracks);
}
@@ -1,101 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "asset/assetfile.h"
#include "animation/animation.h"
#include "yyjson.h"
#define ASSET_ANIMATION_FILE_SIZE_MAX 1024*256
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
/**
* JSON animation file format:
* {
* "loop": false,
* "speed": 1.0,
* "channels": [
* [
* { "time": 0.0, "value": 0.0, "easing": "LINEAR" },
* { "time": 1.0, "value": 10.0 }
* ]
* ]
* }
*
* "loop" and "speed" are optional, defaulting to false and 1.0 (see
* animationInit()). "channels" is required and must have at least one
* entry; each entry is itself a non-empty array of keyframes, ascending
* by "time", sharing one timeline with every other channel (see
* keyframeset_t). Each keyframe requires "time" and "value"; "easing" is
* optional and defaults to "LINEAR" (see easingtype_t for the full set of
* names, e.g. "IN_QUAD", "OUT_BACK", "IN_OUT_CUBIC").
*/
typedef enum {
ASSET_ANIMATION_LOADING_STATE_INITIAL,
ASSET_ANIMATION_LOADING_STATE_READ_FILE,
ASSET_ANIMATION_LOADING_STATE_PARSE,
ASSET_ANIMATION_LOADING_STATE_DONE
} assetanimationloadingstate_t;
typedef struct {
assetfile_t file;
assetanimationloadingstate_t state;
uint8_t *buffer;
size_t size;
} assetanimationloaderloading_t;
typedef animation_t assetanimationoutput_t;
errorret_t assetAnimationLoaderAsync(assetloading_t *loading);
errorret_t assetAnimationLoaderSync(assetloading_t *loading);
errorret_t assetAnimationDispose(assetentry_t *entry);
/**
* Internal. Maps a JSON easing name (e.g. "IN_OUT_QUAD") to its
* easingtype_t.
*
* @param name The easing name to parse.
* @param outEasing Destination for the parsed easing type.
* @return Error state; fails if name doesn't match any easingtype_t.
*/
errorret_t assetAnimationParseEasing(
const char_t *name,
easingtype_t *outEasing
);
/**
* Internal. Parses one "channels" array entry into a heap-allocated
* keyframe_t array (memoryAllocate) -- freed later by
* assetAnimationFreeChannels() (on a parse failure) or
* assetAnimationDispose() (once loaded).
*
* @param channelJson The channel's JSON array of keyframe objects.
* @param outKeyframes Destination for the newly allocated keyframe array.
* @param outCount Destination for the number of keyframes parsed.
* @return Error state.
*/
errorret_t assetAnimationParseChannel(
yyjson_val *channelJson,
keyframe_t **outKeyframes,
uint16_t *outCount
);
/**
* Internal. Frees the first count entries of tracks (each a
* memoryAllocate'd keyframe_t array from assetAnimationParseChannel()),
* then frees tracks itself. Used both to unwind a partially-parsed
* channel list on failure and to free a fully-loaded animation's
* channels in assetAnimationDispose().
*
* @param tracks The channel array to free.
* @param count The number of entries in tracks to free.
*/
void assetAnimationFreeChannels(keyframe_t **tracks, const uint16_t count);
+1 -17
View File
@@ -35,22 +35,6 @@ void assetEntryInit(
entry->input = NULL;
}
refInit(&entry->refs, entry, NULL, NULL, NULL);
eventInit(
&entry->onLoaded,
entry->onLoadedCallbacks, entry->onLoadedUsers,
ASSET_ENTRY_EVENT_MAX
);
eventInit(
&entry->onUnloaded,
entry->onUnloadedCallbacks, entry->onUnloadedUsers,
ASSET_ENTRY_EVENT_MAX
);
eventInit(
&entry->onError,
entry->onErrorCallbacks, entry->onErrorUsers,
ASSET_ENTRY_EVENT_MAX
);
}
void assetEntryLock(assetentry_t *entry) {
@@ -97,7 +81,7 @@ errorret_t assetEntryDispose(assetentry_t *entry) {
"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));
memoryZero(entry, sizeof(assetentry_t));
errorOk();
+22 -20
View File
@@ -7,7 +7,6 @@
#pragma once
#include "asset/loader/assetloading.h"
#include "event/event.h"
#include "util/ref.h"
typedef enum {
@@ -20,11 +19,17 @@ typedef enum {
ASSET_ENTRY_STATE_ERROR
} assetentrystate_t;
/** Maximum number of subscribers for each per-entry event. */
#define ASSET_ENTRY_EVENT_MAX 2
typedef struct assetentry_s assetentry_t;
/**
* A single asset entry callback. Each entry supports at most one subscriber
* per event - a second assignment without clearing the first is a bug.
*
* @param entry The assetentry_t the event fired on.
* @param user The user pointer passed alongside the callback.
*/
typedef void (*assetentrycallback_t)(assetentry_t *entry, void *user);
struct assetentry_s {
char_t name[ASSET_FILE_NAME_MAX];
assetloadertype_t type;
@@ -33,30 +38,27 @@ struct assetentry_s {
ref_t refs;
assetloaderinput_t *input;
assetloaderinput_t inputData;
/**
* Fired once when loading completes successfully (params = assetentry_t *).
* Always invoked on the main thread.
*/
event_t onLoaded;
eventcallback_t onLoadedCallbacks[ASSET_ENTRY_EVENT_MAX];
void *onLoadedUsers[ASSET_ENTRY_EVENT_MAX];
/**
* Fired once when the entry is disposed/reaped (params = assetentry_t *).
* The asset data is still accessible when the callback runs.
* Fired once when loading completes successfully.
* Always invoked on the main thread.
*/
event_t onUnloaded;
eventcallback_t onUnloadedCallbacks[ASSET_ENTRY_EVENT_MAX];
void *onUnloadedUsers[ASSET_ENTRY_EVENT_MAX];
assetentrycallback_t onLoaded;
void *onLoadedUser;
/**
* 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.
*/
event_t onError;
eventcallback_t onErrorCallbacks[ASSET_ENTRY_EVENT_MAX];
void *onErrorUsers[ASSET_ENTRY_EVENT_MAX];
assetentrycallback_t onError;
void *onErrorUser;
};
/**
+10 -4
View File
@@ -46,9 +46,15 @@ assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = {
.dispose = assetJsonDispose
},
[ASSET_LOADER_TYPE_ANIMATION] = {
.loadSync = assetAnimationLoaderSync,
.loadAsync = assetAnimationLoaderAsync,
.dispose = assetAnimationDispose
[ASSET_LOADER_TYPE_CHUNK] = {
.loadSync = assetChunkLoaderSync,
.loadAsync = assetChunkLoaderAsync,
.dispose = assetChunkDispose
},
[ASSET_LOADER_TYPE_CUTSCENE] = {
.loadSync = assetCutsceneLoaderSync,
.loadAsync = assetCutsceneLoaderAsync,
.dispose = assetCutsceneDispose
},
};
+10 -4
View File
@@ -12,7 +12,8 @@
#include "asset/loader/display/assettilesetloader.h"
#include "asset/loader/locale/assetlocaleloader.h"
#include "asset/loader/json/assetjsonloader.h"
#include "asset/loader/animation/assetanimationloader.h"
#include "asset/loader/chunk/assetchunkloader.h"
#include "asset/loader/cutscene/assetcutsceneloader.h"
typedef enum {
ASSET_LOADER_TYPE_NULL,
@@ -23,7 +24,8 @@ typedef enum {
ASSET_LOADER_TYPE_TILESET,
ASSET_LOADER_TYPE_LOCALE,
ASSET_LOADER_TYPE_JSON,
ASSET_LOADER_TYPE_ANIMATION,
ASSET_LOADER_TYPE_CHUNK,
ASSET_LOADER_TYPE_CUTSCENE,
ASSET_LOADER_TYPE_COUNT
} assetloadertype_t;
@@ -35,7 +37,8 @@ typedef union {
assettilesetloaderloading_t tileset;
assetlocaleloaderloading_t locale;
assetjsonloaderloading_t json;
assetanimationloaderloading_t animation;
assetchunkloaderloading_t chunk;
assetcutsceneloaderloading_t cutscene;
} assetloaderloading_t;
typedef union {
@@ -45,7 +48,8 @@ typedef union {
assettilesetoutput_t tileset;
assetlocaleoutput_t locale;
assetjsonoutput_t json;
assetanimationoutput_t animation;
assetchunkoutput_t chunk;
assetcutsceneoutput_t cutscene;
} assetloaderoutput_t;
typedef union {
@@ -53,6 +57,8 @@ typedef union {
assettilesetloaderinput_t tileset;
assetlocaleloaderinput_t locale;
assetjsonloaderinput_t json;
assetchunkloaderinput_t chunk;
assetcutsceneloaderinput_t cutscene;
} assetloaderinput_t;
typedef struct assetloading_s assetloading_t;
@@ -3,7 +3,8 @@
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
assetanimationloader.c
assetchunkloader.c
)
@@ -0,0 +1,257 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetchunkloader.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/endian.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
#include "asset/loader/assetloader.h"
#include "asset/asset.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) {
assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Should be called from an async thread.");
if(loading->loading.chunk.state != ASSET_CHUNK_LOADING_STATE_READ_FILE) {
errorOk();
}
assertNull(loading->loading.chunk.data, "Data already defined?");
assetfile_t *file = &loading->loading.chunk.file;
assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL)
);
uint8_t *data = memoryAllocate(file->size);
assetLoaderErrorChain(loading, assetFileOpen(file));
assetLoaderErrorChain(loading, assetFileRead(file, data, file->size));
assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file));
assertTrue(
file->lastRead == file->size,
"Failed to read entire chunk file."
);
loading->loading.chunk.data = data;
loading->loading.chunk.state = ASSET_CHUNK_LOADING_STATE_PARSE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetChunkLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_CHUNK, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
assetchunkoutput_t *out = &loading->entry->data.chunk;
switch(loading->loading.chunk.state) {
case ASSET_CHUNK_LOADING_STATE_INITIAL:
loading->loading.chunk.state = ASSET_CHUNK_LOADING_STATE_READ_FILE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
errorOk();
case ASSET_CHUNK_LOADING_STATE_PARSE:
break;
case ASSET_CHUNK_LOADING_STATE_LOAD_MODELS:
while(loading->loading.chunk.modelIndex < out->meshCount) {
uint8_t m = loading->loading.chunk.modelIndex;
if(out->modelEntries[m] == NULL) {
out->modelEntries[m] = assetLock(
out->modelNames[m], ASSET_LOADER_TYPE_MODEL, NULL
);
assertNotNull(
out->modelEntries[m], "Failed to lock model."
);
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
if(out->modelEntries[m]->state == ASSET_ENTRY_STATE_ERROR) {
assetLoaderErrorThrow(
loading, "Model failed to load: %s", out->modelNames[m]
);
}
if(out->modelEntries[m]->state != ASSET_ENTRY_STATE_LOADED) {
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
loading->loading.chunk.modelIndex++;
}
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
default:
errorOk();
}
uint8_t *data = loading->loading.chunk.data;
assertNotNull(data, "Chunk data should have been loaded by now.");
if(data[0] != 'D' || data[1] != 'C' || data[2] != 'F') {
memoryFree(data);
assetLoaderErrorThrow(loading, "Invalid chunk file header");
}
uint32_t version = endianLittleToHost32(*(uint32_t *)(data + 4));
if(version != ASSET_CHUNK_FILE_VERSION) {
memoryFree(data);
assetLoaderErrorThrow(
loading, "Unsupported chunk file version %u", version
);
}
size_t offset = 8;
size_t tileSize = CHUNK_TILE_COUNT * sizeof(tile_t);
out->tiles = memoryAllocate(tileSize);
memoryCopy(out->tiles, data + offset, tileSize);
offset += tileSize;
for(size_t t = 0; t < CHUNK_TILE_COUNT; t++) {
uint32_t *shape = (uint32_t *)&out->tiles[t].shape;
*shape = endianLittleToHost32(*shape);
}
out->meshCount = data[offset];
offset += sizeof(uint8_t);
assertTrue(
out->meshCount <= CHUNK_MESH_COUNT_MAX,
"Chunk mesh count exceeds maximum."
);
for(uint8_t m = 0; m < out->meshCount; m++) {
uint8_t nameLen = 0;
while(
data[offset + nameLen] != '\0' &&
nameLen < CHUNK_MESH_NAME_MAX - 1
) {
nameLen++;
}
memoryCopy(out->modelNames[m], data + offset, nameLen);
out->modelNames[m][nameLen] = '\0';
offset += nameLen + 1;
memoryCopy(out->meshOffsets[m], data + offset, sizeof(vec3));
offset += sizeof(vec3);
out->meshOffsets[m][0] = endianLittleToHostFloat(out->meshOffsets[m][0]);
out->meshOffsets[m][1] = endianLittleToHostFloat(out->meshOffsets[m][1]);
out->meshOffsets[m][2] = endianLittleToHostFloat(out->meshOffsets[m][2]);
}
out->entitySpawnCount = data[offset];
offset += sizeof(uint8_t);
assertTrue(
out->entitySpawnCount <= CHUNK_ENTITY_SPAWN_COUNT_MAX,
"Chunk entity spawn count exceeds maximum."
);
for(uint8_t s = 0; s < out->entitySpawnCount; s++) {
chunkentityspawn_t *spawn = &out->entitySpawns[s];
spawn->kind = (chunkentityspawnkind_t)data[offset];
offset += sizeof(uint8_t);
uint16_t a;
memoryCopy(&a, data + offset, sizeof(uint16_t));
a = endianLittleToHost16(a);
offset += sizeof(uint16_t);
uint8_t b = data[offset];
offset += sizeof(uint8_t);
if(spawn->kind == CHUNK_ENTITY_SPAWN_KIND_ITEM) {
spawn->globalId = 0;
spawn->itemId = a;
spawn->itemQuantity = b;
} else {
spawn->globalId = a;
spawn->itemId = 0;
spawn->itemQuantity = 0;
}
spawn->position = assetChunkReadWorldPos(data, &offset);
}
out->areaSpawnCount = data[offset];
offset += sizeof(uint8_t);
assertTrue(
out->areaSpawnCount <= CHUNK_AREA_COUNT_MAX,
"Chunk area spawn count exceeds maximum."
);
for(uint8_t s = 0; s < out->areaSpawnCount; s++) {
chunkareaspawn_t *area = &out->areaSpawns[s];
area->min = assetChunkReadWorldPos(data, &offset);
area->max = assetChunkReadWorldPos(data, &offset);
uint16_t callbackId;
memoryCopy(&callbackId, data + offset, sizeof(uint16_t));
area->callbackId = endianLittleToHost16(callbackId);
offset += sizeof(uint16_t);
area->notify = data[offset];
offset += sizeof(uint8_t);
area->trigger = data[offset];
offset += sizeof(uint8_t);
}
memoryFree(data);
loading->loading.chunk.data = NULL;
if(out->meshCount == 0) {
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
loading->loading.chunk.state = ASSET_CHUNK_LOADING_STATE_LOAD_MODELS;
loading->loading.chunk.modelIndex = 0;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetChunkDispose(assetentry_t *entry) {
assertNotNull(entry, "Entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_CHUNK, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
assetchunkoutput_t *out = &entry->data.chunk;
if(out->tiles != NULL) {
memoryFree(out->tiles);
out->tiles = NULL;
}
for(uint8_t m = 0; m < out->meshCount; m++) {
if(out->modelEntries[m] == NULL) continue;
assetUnlockEntry(out->modelEntries[m]);
out->modelEntries[m] = NULL;
}
errorOk();
}
@@ -0,0 +1,97 @@
/**
* 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/overworld/chunk.h"
#define ASSET_CHUNK_FILE_VERSION 5
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
typedef struct {
void *nothing;
} assetchunkloaderinput_t;
typedef enum {
ASSET_CHUNK_LOADING_STATE_INITIAL,
ASSET_CHUNK_LOADING_STATE_READ_FILE,
ASSET_CHUNK_LOADING_STATE_PARSE,
ASSET_CHUNK_LOADING_STATE_LOAD_MODELS,
ASSET_CHUNK_LOADING_STATE_DONE
} assetchunkloadingstate_t;
typedef struct {
assetfile_t file;
assetchunkloadingstate_t state;
uint8_t *data;
uint8_t modelIndex;
} assetchunkloaderloading_t;
typedef enum {
CHUNK_ENTITY_SPAWN_KIND_GLOBAL,
CHUNK_ENTITY_SPAWN_KIND_ITEM
} chunkentityspawnkind_t;
typedef struct {
chunkentityspawnkind_t kind;
uint16_t globalId; // Valid when kind == CHUNK_ENTITY_SPAWN_KIND_GLOBAL.
uint16_t itemId; // Valid when kind == CHUNK_ENTITY_SPAWN_KIND_ITEM.
uint8_t itemQuantity; // Valid when kind == CHUNK_ENTITY_SPAWN_KIND_ITEM.
worldpos_t position;
} chunkentityspawn_t;
typedef struct {
worldpos_t min;
worldpos_t max;
uint16_t callbackId; // Index into MAP_AREA_CALLBACK_LIST.
uint8_t notify;
uint8_t trigger;
} chunkareaspawn_t;
typedef struct {
tile_t *tiles;
uint8_t meshCount;
char_t modelNames[CHUNK_MESH_COUNT_MAX][CHUNK_MESH_NAME_MAX];
vec3 meshOffsets[CHUNK_MESH_COUNT_MAX];
assetentry_t *modelEntries[CHUNK_MESH_COUNT_MAX];
uint8_t entitySpawnCount;
chunkentityspawn_t entitySpawns[CHUNK_ENTITY_SPAWN_COUNT_MAX];
uint8_t areaSpawnCount;
chunkareaspawn_t areaSpawns[CHUNK_AREA_COUNT_MAX];
} assetchunkoutput_t;
/**
* Asynchronous loader for chunk assets. Reads the raw DCF 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 assetChunkLoaderAsync(assetloading_t *loading);
/**
* Synchronous loader for chunk assets. Validates the DCF binary previously
* read by the async phase and populates the output assetchunkoutput_t with
* tile data and model paths.
*
* @param loading Loading information for the asset being loaded.
* @return Error code indicating success or failure of the load operation.
*/
errorret_t assetChunkLoaderSync(assetloading_t *loading);
/**
* Disposer for chunk assets.
*
* @param entry Asset entry containing the chunk data to dispose.
* @return Error code indicating success or failure of the dispose operation.
*/
errorret_t assetChunkDispose(assetentry_t *entry);
@@ -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
assetcutsceneloader.c
)
@@ -0,0 +1,467 @@
/**
* 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/endian.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
#include "asset/loader/assetloader.h"
#include "asset/asset.h"
// DCTS header: magic "DCTS" (4), version u32 LE (4), pauseType u8 (1),
// itemCount u8 (1), poolSize u16 LE (2) = 12 bytes.
#define ASSET_CUTSCENE_HEADER_SIZE 12
static uint8_t assetCutsceneReadU8(const uint8_t *data, size_t *offset) {
uint8_t value = data[*offset];
*offset += sizeof(uint8_t);
return value;
}
static uint16_t assetCutsceneReadU16(const uint8_t *data, size_t *offset) {
uint16_t value;
memoryCopy(&value, data + *offset, sizeof(uint16_t));
*offset += sizeof(uint16_t);
return endianLittleToHost16(value);
}
static uint32_t assetCutsceneReadU32(const uint8_t *data, size_t *offset) {
uint32_t value;
memoryCopy(&value, data + *offset, sizeof(uint32_t));
*offset += sizeof(uint32_t);
return endianLittleToHost32(value);
}
static float_t assetCutsceneReadFloat(const uint8_t *data, size_t *offset) {
float_t value;
memoryCopy(&value, data + *offset, sizeof(float_t));
*offset += sizeof(float_t);
return endianLittleToHostFloat(value);
}
static worldunit_t assetCutsceneReadWorldUnit(
const uint8_t *data,
size_t *offset
) {
uint16_t value = assetCutsceneReadU16(data, offset);
return (worldunit_t)value;
}
static worldpos_t assetCutsceneReadWorldPos(
const uint8_t *data,
size_t *offset
) {
worldpos_t pos;
pos.x = assetCutsceneReadWorldUnit(data, offset);
pos.y = assetCutsceneReadWorldUnit(data, offset);
pos.z = assetCutsceneReadWorldUnit(data, offset);
return pos;
}
// Copies a length-prefixed string directly into an item's own embedded
// char_t[destCapacity] field (CUTSCENE_TEXT_MAX_CHARS and friends) - these
// are never pool references, see the item-field inventory in the runtime
// cutscene file design.
static void assetCutsceneReadEmbeddedString(
const uint8_t *data,
size_t *offset,
char_t *dest,
const size_t destCapacity
) {
uint8_t len = assetCutsceneReadU8(data, offset);
assertTrue(len < destCapacity, "Cutscene string exceeds field capacity");
memoryCopy(dest, data + *offset, len);
dest[len] = '\0';
*offset += len;
}
// Resolves a u16 pool offset (read from the item stream) to a real pointer
// into the entry's own persistent pool allocation.
static const char_t * assetCutsceneReadPoolString(
const uint8_t *data,
size_t *offset,
const char_t *pool
) {
uint16_t poolOffset = assetCutsceneReadU16(data, offset);
return pool + poolOffset;
}
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.data, "Data already defined?");
assetfile_t *file = &loading->loading.cutscene.file;
assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL)
);
uint8_t *data = memoryAllocate(file->size);
assetLoaderErrorChain(loading, assetFileOpen(file));
assetLoaderErrorChain(loading, assetFileRead(file, data, file->size));
assertTrue(
file->lastRead == file->size,
"Failed to read entire cutscene file."
);
// Saved before assetFileDispose zeroes the whole assetfile_t struct
// (including .size) - the sync phase needs the file's total length to
// locate the pool region, which starts poolSize bytes before the end.
loading->loading.cutscene.dataSize = (size_t)file->size;
assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file));
loading->loading.cutscene.data = data;
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 *data = loading->loading.cutscene.data;
assertNotNull(data, "Cutscene data should have been loaded by now.");
size_t fileSize = loading->loading.cutscene.dataSize;
if(data[0] != 'D' || data[1] != 'C' || data[2] != 'T' || data[3] != 'S') {
memoryFree(data);
assetLoaderErrorThrow(loading, "Invalid cutscene file header");
}
size_t offset = 4;
uint32_t version = assetCutsceneReadU32(data, &offset);
if(version != ASSET_CUTSCENE_FILE_VERSION) {
memoryFree(data);
assetLoaderErrorThrow(
loading, "Unsupported cutscene file version %u", version
);
}
cutscenepause_t pauseType = (cutscenepause_t)assetCutsceneReadU8(data, &offset);
uint8_t itemCount = assetCutsceneReadU8(data, &offset);
uint16_t poolSize = assetCutsceneReadU16(data, &offset);
assertTrue(offset == ASSET_CUTSCENE_HEADER_SIZE, "Cutscene header size mismatch");
out->pool = poolSize > 0 ? memoryAllocate(poolSize) : NULL;
if(poolSize > 0) {
size_t poolStart = fileSize - (size_t)poolSize;
memoryCopy(out->pool, data + poolStart, poolSize);
}
const char_t *pool = out->pool;
out->items = memoryAllocate(itemCount * sizeof(cutsceneitem_t));
memoryZero(out->items, itemCount * sizeof(cutsceneitem_t));
for(uint8_t i = 0; i < itemCount; i++) {
cutsceneitem_t *item = &out->items[i];
item->type = (cutsceneitemtype_t)assetCutsceneReadU8(data, &offset);
switch(item->type) {
case CUTSCENE_ITEM_TYPE_TEXT:
assetCutsceneReadEmbeddedString(
data, &offset, item->text.text, CUTSCENE_TEXT_MAX_CHARS
);
break;
case CUTSCENE_ITEM_TYPE_TEXT_MINI:
assetCutsceneReadEmbeddedString(
data, &offset, item->textMini.text, CUTSCENE_TEXT_MINI_MAX_CHARS
);
item->textMini.position[0] = assetCutsceneReadFloat(data, &offset);
item->textMini.position[1] = assetCutsceneReadFloat(data, &offset);
item->textMini.position[2] = assetCutsceneReadFloat(data, &offset);
item->textMini.duration = assetCutsceneReadFloat(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE:
item->textMiniHide.index = assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_WAIT:
item->wait = assetCutsceneReadFloat(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT:
item->entityTeleport.entityIndex = assetCutsceneReadU8(data, &offset);
item->entityTeleport.target = assetCutsceneReadWorldPos(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO: {
item->entityWalkTo.entityIndex = assetCutsceneReadU8(data, &offset);
item->entityWalkTo.walkAround = assetCutsceneReadU8(data, &offset) != 0;
uint8_t count = assetCutsceneReadU8(data, &offset);
uint16_t poolOffset = assetCutsceneReadU16(data, &offset);
item->entityWalkTo.count = count;
item->entityWalkTo.positions = (const worldpos_t *)(pool + poolOffset);
break;
}
case CUTSCENE_ITEM_TYPE_FADE:
item->fade.from.r = assetCutsceneReadU8(data, &offset);
item->fade.from.g = assetCutsceneReadU8(data, &offset);
item->fade.from.b = assetCutsceneReadU8(data, &offset);
item->fade.from.a = assetCutsceneReadU8(data, &offset);
item->fade.to.r = assetCutsceneReadU8(data, &offset);
item->fade.to.g = assetCutsceneReadU8(data, &offset);
item->fade.to.b = assetCutsceneReadU8(data, &offset);
item->fade.to.a = assetCutsceneReadU8(data, &offset);
item->fade.duration = assetCutsceneReadFloat(data, &offset);
item->fade.easing = (easingtype_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_SET_PAUSE:
item->setPause = (cutscenepause_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ITEM_GIVE:
item->itemGive.item = (itemid_t)assetCutsceneReadU16(data, &offset);
item->itemGive.quantity = assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_REMOVE:
item->entityRemove.entityIndex = assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_ADD:
item->entityAdd.entityType = assetCutsceneReadU8(data, &offset);
item->entityAdd.position = assetCutsceneReadWorldPos(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_TURN:
item->entityTurn.entityIndex = assetCutsceneReadU8(data, &offset);
item->entityTurn.direction =
(entitydir_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY:
item->entityWalkToEntity.entityIndex =
assetCutsceneReadU8(data, &offset);
item->entityWalkToEntity.targetEntityIndex =
assetCutsceneReadU8(data, &offset);
item->entityWalkToEntity.offsetX =
assetCutsceneReadWorldUnit(data, &offset);
item->entityWalkToEntity.offsetY =
assetCutsceneReadWorldUnit(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE:
item->mapAreaRemove.areaId = assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT: {
uint8_t count = assetCutsceneReadU8(data, &offset);
uint16_t poolOffset = assetCutsceneReadU16(data, &offset);
assertTrue(
count <= CUTSCENE_MAP_AREA_WAIT_MAX,
"Cutscene map area wait count exceeds maximum"
);
item->mapAreaWait.count = count;
item->mapAreaWait.areaIds = (const uint8_t *)(pool + poolOffset);
break;
}
case CUTSCENE_ITEM_TYPE_START_BATTLE: {
item->startBattle.encounterType =
(battleencountertype_t)assetCutsceneReadU8(data, &offset);
item->startBattle.fleeAvailable =
assetCutsceneReadU8(data, &offset) != 0;
uint8_t enemyCount = assetCutsceneReadU8(data, &offset);
assertTrue(
enemyCount <= CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX,
"Cutscene battle enemy count exceeds maximum"
);
item->startBattle.enemyCount = enemyCount;
for(uint8_t e = 0; e < enemyCount; e++) {
cutscenestartbattleenemy_t *enemy = &item->startBattle.enemies[e];
enemy->stats.attack = assetCutsceneReadU16(data, &offset);
enemy->stats.defense = assetCutsceneReadU16(data, &offset);
enemy->stats.magic = assetCutsceneReadU16(data, &offset);
enemy->stats.speed = assetCutsceneReadU16(data, &offset);
enemy->stats.luck = assetCutsceneReadU16(data, &offset);
enemy->healthMax = assetCutsceneReadU16(data, &offset);
enemy->mpMax = assetCutsceneReadU16(data, &offset);
}
break;
}
case CUTSCENE_ITEM_TYPE_EMOJI:
item->emoji.entityIndex = assetCutsceneReadU8(data, &offset);
item->emoji.duration = assetCutsceneReadFloat(data, &offset);
item->emoji.emojiType = (uiemojitype_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_SHAKE:
item->shake.amount = assetCutsceneReadU8(data, &offset);
item->shake.duration = assetCutsceneReadFloat(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_BATTLE_WAIT_STATE:
item->battleWaitState.state =
(battlestate_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_BATTLE_FORCE_ACTION:
item->battleForceAction.fighterIndex = assetCutsceneReadU8(data, &offset);
item->battleForceAction.targetIndex = assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_MODAL: {
assetCutsceneReadEmbeddedString(
data, &offset, item->modal.title, CUTSCENE_MODAL_TITLE_MAX_CHARS
);
assetCutsceneReadEmbeddedString(
data, &offset, item->modal.message, CUTSCENE_MODAL_MESSAGE_MAX_CHARS
);
// v1 only supports the message-only form: MODAL and MODAL_OPTIONS
// share this same tag with no separate discriminator, and there is
// no native-callback registry yet to resolve an options callback.
// Read into a local first (not inline in the check below) - on a
// release build with DUSK_ASSERTIONS_FAKED, an assert's condition
// is never evaluated at all, so a byte-consuming call inside one
// would silently desync every item after it. This is untrusted
// file content anyway, so it gets a real error, not an assert.
uint8_t optionCount = assetCutsceneReadU8(data, &offset);
if(optionCount != 0) {
memoryFree(data);
memoryFree(out->items);
out->items = NULL;
if(out->pool != NULL) {
memoryFree(out->pool);
out->pool = NULL;
}
assetLoaderErrorThrow(
loading,
"Cutscene MODAL item with options is not supported in "
"file-based cutscenes yet - use MODAL_OPTIONS_MARKERS instead"
);
}
break;
}
case CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS: {
assetCutsceneReadEmbeddedString(
data, &offset, item->modalOptionsMarkers.title,
CUTSCENE_MODAL_TITLE_MAX_CHARS
);
assetCutsceneReadEmbeddedString(
data, &offset, item->modalOptionsMarkers.message,
CUTSCENE_MODAL_MESSAGE_MAX_CHARS
);
uint8_t optionCount = assetCutsceneReadU8(data, &offset);
assertTrue(
optionCount <= CUTSCENE_MODAL_OPTIONS_MARKERS_MAX,
"Cutscene modal option count exceeds maximum"
);
item->modalOptionsMarkers.optionCount = optionCount;
for(uint8_t o = 0; o < optionCount; o++) {
item->modalOptionsMarkers.options[o] =
assetCutsceneReadPoolString(data, &offset, pool);
item->modalOptionsMarkers.markers[o] =
assetCutsceneReadPoolString(data, &offset, pool);
}
break;
}
case CUTSCENE_ITEM_TYPE_MODAL_CLOSE:
case CUTSCENE_ITEM_TYPE_RESTART:
break;
case CUTSCENE_ITEM_TYPE_PRINT:
assetCutsceneReadEmbeddedString(
data, &offset, item->print.text, CUTSCENE_PRINT_MAX_CHARS
);
break;
case CUTSCENE_ITEM_TYPE_MARKER:
item->marker.name = assetCutsceneReadPoolString(data, &offset, pool);
break;
case CUTSCENE_ITEM_TYPE_SCENE:
item->sceneChange.type = (scenetype_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK:
item->saveDeviceCheck.successMarker =
assetCutsceneReadPoolString(data, &offset, pool);
item->saveDeviceCheck.failureMarker =
assetCutsceneReadPoolString(data, &offset, pool);
break;
case CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS:
item->saveLoadAllSlots.successMarker =
assetCutsceneReadPoolString(data, &offset, pool);
item->saveLoadAllSlots.failureMarker =
assetCutsceneReadPoolString(data, &offset, pool);
break;
default:
memoryFree(data);
memoryFree(out->items);
out->items = NULL;
if(out->pool != NULL) {
memoryFree(out->pool);
out->pool = NULL;
}
assetLoaderErrorThrow(
loading,
"Cutscene item type %u is not supported in file-based cutscenes "
"(item %u/%u, offset %u/%u, poolSize %u)",
(uint32_t)item->type, (uint32_t)i, (uint32_t)itemCount,
(uint32_t)offset, (uint32_t)fileSize, (uint32_t)poolSize
);
}
}
memoryFree(data);
loading->loading.cutscene.data = NULL;
out->cutscene.items = out->items;
out->cutscene.itemCount = itemCount;
out->cutscene.pause = pauseType;
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.");
assetcutsceneoutput_t *out = &entry->data.cutscene;
if(out->items != NULL) {
memoryFree(out->items);
out->items = NULL;
}
if(out->pool != NULL) {
memoryFree(out->pool);
out->pool = NULL;
}
errorOk();
}
@@ -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 "asset/assetfile.h"
#include "rpg/cutscene/cutscene.h"
#include "rpg/cutscene/item/cutsceneitem.h"
#define ASSET_CUTSCENE_FILE_VERSION 1
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 *data;
size_t dataSize;// Saved before assetFileDispose zeroes file.size.
} assetcutsceneloaderloading_t;
// Runtime-loaded cutscene: items/pool are heap-allocated to the file's
// actual declared sizes (not fixed-capacity), so an entry that never holds
// a cutscene costs nothing extra in the shared assetloaderoutput_t union -
// see assetchunkoutput_t.tiles for the same pattern.
typedef struct {
cutscene_t cutscene; // .items points at the items array below
cutsceneitem_t *items;
char_t *pool;
} assetcutsceneoutput_t;
/**
* Asynchronous loader for cutscene assets. Reads the raw DCTS 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. Validates the DCTS binary
* previously read by the async phase and decodes it into a heap-allocated
* cutsceneitem_t array + string/data 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);
@@ -127,6 +127,14 @@ errorret_t assetMeshLoaderSync(assetloading_t *loading) {
errorChain(ret);
}
#if defined(DUSK_OPENGL) && !defined(DUSK_OPENGL_LEGACY)
// VBO owns the data now; CPU copy is no longer needed. The platform
// mesh object itself still needs meshDispose later - tracked via
// out->meshInitialized, independent of the CPU buffer's lifetime.
memoryFree(out->vertices);
out->vertices = NULL;
#endif
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
+7 -18
View File
@@ -17,11 +17,9 @@ console_t CONSOLE;
void consoleInit(void) {
memoryZero(&CONSOLE, sizeof(console_t));
CONSOLE.visible = false;
#ifdef DUSK_CONSOLE_POSIX
threadMutexInit(&CONSOLE.printMutex);
#endif
// CONSOLE.visible = false;
CONSOLE.visible = true;
threadMutexInit(&CONSOLE.printMutex);
}
void consolePrint(const char_t *message, ...) {
@@ -32,21 +30,14 @@ void consolePrint(const char_t *message, ...) {
int32_t len = stringFormatVA(buffer, CONSOLE_LINE_MAX, message, args);
va_end(args);
#ifdef DUSK_CONSOLE_POSIX
threadMutexLock(&CONSOLE.printMutex);
#endif
threadMutexLock(&CONSOLE.printMutex);
memoryMove(
CONSOLE.line[0],
CONSOLE.line[1],
(CONSOLE_HISTORY_MAX - 1) * CONSOLE_LINE_MAX
);
memoryCopy(CONSOLE.line[CONSOLE_HISTORY_MAX - 1], buffer, len + 1);
CONSOLE.dirty = true;
#ifdef DUSK_CONSOLE_POSIX
threadMutexUnlock(&CONSOLE.printMutex);
#endif
threadMutexUnlock(&CONSOLE.printMutex);
logDebug("%s\n", buffer);
}
@@ -56,13 +47,11 @@ void consoleUpdate(void) {
if(TIME.dynamicUpdate) return;
#endif
if(inputPressed(INPUT_BIND_CONSOLE)) {
if(inputPressed(INPUT_ACTION_CONSOLE)) {
CONSOLE.visible = !CONSOLE.visible;
}
}
void consoleDispose(void) {
#ifdef DUSK_CONSOLE_POSIX
threadMutexDispose(&CONSOLE.printMutex);
#endif
threadMutexDispose(&CONSOLE.printMutex);
}
+5 -16
View File
@@ -6,29 +6,18 @@
*/
#pragma once
#include "consoledefs.h"
#include "error/error.h"
#include "dusk.h"
#include "thread/thread.h"
#ifdef DUSK_CONSOLE_POSIX
#include "thread/thread.h"
#include <poll.h>
#include <unistd.h>
#define CONSOLE_POSIX_POLL_RATE 75
#endif
#define CONSOLE_LINE_MAX 128
#define CONSOLE_HISTORY_MAX 16
#define CONSOLE_EXEC_BUFFER_MAX 32
typedef struct {
char_t line[CONSOLE_HISTORY_MAX][CONSOLE_LINE_MAX];
bool_t visible;
// Set whenever the history changes; consumers rendering the console
// (e.g. uiConsoleDraw) check and clear this to know when their own
// cached representation of the history needs rebuilding.
bool_t dirty;
#ifdef DUSK_CONSOLE_POSIX
threadmutex_t printMutex;
#endif
threadmutex_t printMutex;
} console_t;
extern console_t CONSOLE;
+8 -4
View File
@@ -33,13 +33,17 @@ errorret_t displayInit(void) {
#ifdef displayPlatformInit
errorChain(displayPlatformInit());
#endif
// Set initial state
errorChain(displaySetState((displaystate_t){ .flags = 0 }));
// Init the fixed textures
errorChain(textureInit(
&TEXTURE_WHITE, 4, 4,
&TEXTURE_WHITE, TEXTURE_FIXED_WIDTH, TEXTURE_FIXED_HEIGHT,
TEXTURE_FORMAT_RGBA, (texturedata_t){ .rgbaColors = TEXTURE_WHITE_PIXELS }
));
errorChain(textureInit(
&TEXTURE_TEST, 4, 4,
&TEXTURE_TEST, TEXTURE_FIXED_WIDTH, TEXTURE_FIXED_HEIGHT,
TEXTURE_FORMAT_RGBA, (texturedata_t){ .rgbaColors = TEXTURE_TEST_PIXELS }
));
@@ -50,14 +54,14 @@ errorret_t displayInit(void) {
errorChain(planeInit());
errorChain(capsuleInit());
errorChain(triPrismInit());
// Init the subsystems
errorChain(frameBufferInitBackBuffer());
errorChain(spriteBatchInit());
errorChain(textInit());
errorChain(screenInit());
// Setup initial shader with default values
errorChain(shaderListInit());
errorOk();
+2 -2
View File
@@ -12,8 +12,8 @@ mesh_t CUBE_MESH_SIMPLE;
meshvertex_t CUBE_MESH_SIMPLE_VERTICES[CUBE_VERTEX_COUNT];
errorret_t cubeInit() {
vec3 min = { -0.5f, -0.5f, -0.5f };
vec3 max = { 0.5f, 0.5f, 0.5f };
vec3 min = { 0.0f, 0.0f, 0.0f };
vec3 max = { 1.0f, 1.0f, 1.0f };
cubeBuffer(CUBE_MESH_SIMPLE_VERTICES, min, max);
errorChain(meshInit(
&CUBE_MESH_SIMPLE,
+1 -3
View File
@@ -17,9 +17,7 @@ extern mesh_t CUBE_MESH_SIMPLE;
extern meshvertex_t CUBE_MESH_SIMPLE_VERTICES[CUBE_VERTEX_COUNT];
/**
* Initializes the simple unit cube mesh, centered at (0,0,0), spanning
* (-0.5,-0.5,-0.5) to (0.5,0.5,0.5) -- matching the centered convention
* physics shapes and the sphere mesh use (position = center).
* Initializes the simple unit cube mesh (0,0,0) to (1,1,1).
*
* @return Error for initialization of the cube mesh.
*/
+7 -13
View File
@@ -59,8 +59,7 @@ void planeBuffer(
switch(axis) {
case PLANE_AXIS_XY: {
// Flat in XY at z = min[2]; spans X and Y.
// +Z normal: CCW when viewed from +Z (matches cube.c's front face).
/* Flat in XY at z = min[2]; spans X and Y. */
const float_t z = min[2];
PLANE_VERT(0, min[0], min[1], z, u0, v0)
PLANE_VERT(1, max[0], min[1], z, u1, v0)
@@ -72,24 +71,19 @@ void planeBuffer(
}
case PLANE_AXIS_XZ: {
// Flat in XZ at y = min[1]; spans X and Z.
// +Y normal: CCW when viewed from +Y (matches cube.c's top face).
// X and Z swap handedness relative to XY/YZ (right-hand rule with Y
// up), so the corner order here is deliberately not a straight copy
// of the XY/YZ pattern -- copying it as-is would flip this to -Y.
/* Flat in XZ at y = min[1]; spans X and Z. */
const float_t y = min[1];
PLANE_VERT(0, min[0], y, min[2], u0, v0)
PLANE_VERT(1, max[0], y, max[2], u1, v1)
PLANE_VERT(2, max[0], y, min[2], u1, v0)
PLANE_VERT(1, max[0], y, min[2], u1, v0)
PLANE_VERT(2, max[0], y, max[2], u1, v1)
PLANE_VERT(3, min[0], y, min[2], u0, v0)
PLANE_VERT(4, min[0], y, max[2], u0, v1)
PLANE_VERT(5, max[0], y, max[2], u1, v1)
PLANE_VERT(4, max[0], y, max[2], u1, v1)
PLANE_VERT(5, min[0], y, max[2], u0, v1)
break;
}
case PLANE_AXIS_YZ: {
// Flat in YZ at x = min[0]; spans Y and Z.
// +X normal: CCW when viewed from +X (matches cube.c's right face).
/* Flat in YZ at x = min[0]; spans Y and Z. */
const float_t x = min[0];
PLANE_VERT(0, x, min[1], min[2], u0, v0)
PLANE_VERT(1, x, max[1], min[2], u1, v0)
-1
View File
@@ -21,7 +21,6 @@ errorret_t shaderInit(shader_t *shader, const shaderdefinition_t *def) {
errorret_t shaderBind(shader_t *shader) {
assertNotNull(shader, "Shader cannot be null");
if(bound == shader) errorOk();
errorChain(shaderBindPlatform(shader));
bound = shader;
errorOk();
+1 -1
View File
@@ -76,7 +76,7 @@ errorret_t spriteBatchBuffer(
// Buffer to the mesh vertices.
spriteBatchBufferToMesh(
sprites, batchCount, v, batchCount * QUAD_VERTEX_COUNT
sprites + (count - remaining), batchCount, v, batchCount * QUAD_VERTEX_COUNT
);
SPRITEBATCH.spriteCount += batchCount;
remaining -= batchCount;
@@ -39,16 +39,3 @@ spritebatchsprite_t spriteBatchSpriteTilesetPosition(
sprite.uvMax[1] = uv[3];
return sprite;
}
spritebatchsprite_t spriteBatchSpriteTranslate(
const spritebatchsprite_t *sprite,
const float_t x,
const float_t y
) {
spritebatchsprite_t out = *sprite;
out.min[0] += x;
out.min[1] += y;
out.max[0] += x;
out.max[1] += y;
return out;
}
@@ -38,19 +38,3 @@ spritebatchsprite_t spriteBatchSpriteTilesetPosition(
const float_t width,
const float_t height
);
/**
* Returns a copy of sprite translated by (x, y). Used to reposition a
* sprite cached relative to origin (0,0) at draw time, instead of
* re-deriving its geometry from scratch every frame.
*
* @param sprite The cached sprite, relative to origin (0,0).
* @param x X offset to translate by.
* @param y Y offset to translate by.
* @returns The translated sprite.
*/
spritebatchsprite_t spriteBatchSpriteTranslate(
const spritebatchsprite_t *sprite,
const float_t x,
const float_t y
);
+1 -1
View File
@@ -6,6 +6,6 @@
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
font.c
text.c
font.c
)
+35 -8
View File
@@ -76,11 +76,23 @@ const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
{ 0x00, 0x22, 0x22, 0x14, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00 }, // Y
{ 0x00, 0x3E, 0x02, 0x04, 0x08, 0x10, 0x20, 0x3E, 0x00, 0x00 }, // Z
{ 0x00, 0x0C, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0C, 0x00, 0x00 }, // [
{ 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.
{ 0x00, 0x00, 0x08, 0x1F, 0x3F, 0x3F, 0x1F, 0x08, 0x00, 0x00 }, // FONT_ICON_BACKSPACE
{ 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)
{ 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 }, // ` (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.
{ 0x0C, 0x1E, 0x3F, 0x0C, 0x0C, 0x0C, 0x0C, 0x00, 0x0C, 0x00 }, // FONT_ICON_SHIFT
{ 0x00, 0x00, 0x00, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x00, 0x00 }, // a
{ 0x00, 0x20, 0x20, 0x3C, 0x22, 0x22, 0x22, 0x3C, 0x00, 0x00 }, // b
{ 0x00, 0x00, 0x00, 0x1C, 0x22, 0x20, 0x22, 0x1C, 0x00, 0x00 }, // c
@@ -108,14 +120,29 @@ const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
{ 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, 0x1E, 0x02, 0x1C }, // y
{ 0x00, 0x00, 0x00, 0x3E, 0x04, 0x08, 0x10, 0x3E, 0x00, 0x00 }, // z
{ 0x00, 0x04, 0x08, 0x08, 0x10, 0x08, 0x08, 0x04, 0x00, 0x00 }, // {
{ 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.
{ 0x02, 0x02, 0x02, 0x02, 0x0E, 0x1E, 0x08, 0x00, 0x00, 0x00 }, // FONT_ICON_NEWLINE
{ 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)
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // unused trailing tile
// Custom icon glyph, not a real tilde - a spacebar symbol for the
// keyboard's space key: an underscore with a tick at each end, like
// "|___|". Tilde was never drawn anyway, and was explicitly dropped
// from this virtual keyboard's own key set - see FONT_ICON_SPACE.
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x3F }, // FONT_ICON_SPACE
// 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.
{ 0x0C, 0x1E, 0x3F, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x00 }, // FONT_ICON_CAPSLOCK
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // unused trailing tile
};
errorret_t fontInitDefault(void) {
errorret_t fontDefaultInit(void) {
const int32_t width = (int32_t)mathNextPowTwo(
FONT_DEFAULT_COLUMNS * FONT_DEFAULT_TILE_WIDTH
);
@@ -160,7 +187,7 @@ errorret_t fontInitDefault(void) {
errorOk();
}
errorret_t fontDisposeDefault(void) {
errorret_t fontDefaultDispose(void) {
errorChain(textureDispose(&FONT_DEFAULT_TEXTURE));
FONT_DEFAULT.texture = NULL;
FONT_DEFAULT.tileset = NULL;
+50 -17
View File
@@ -16,9 +16,7 @@ typedef struct {
} font_t;
/**
* Pixel width/height of a single default-font glyph tile. Matches the
* glyph grid baked into the (now retired) ui/minogram.png + .dtf asset
* pair this data was extracted from.
* Pixel width/height of a single default-font glyph tile.
*/
#define FONT_DEFAULT_TILE_WIDTH 6
#define FONT_DEFAULT_TILE_HEIGHT 10
@@ -30,37 +28,72 @@ typedef struct {
/**
* Number of glyphs defined in FONT_DEFAULT_GLYPHS (FONT_DEFAULT_COLUMNS *
* 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)
/**
* Custom (non-ASCII-meaning) icon glyphs baked into FONT_DEFAULT_GLYPHS
* at otherwise-unused codepoints within the range this font covers -
* safe to use anywhere a char_t string is expected, e.g. a uibutton_t
* label. Kept below 128: char_t is a plain `char`, whose signedness
* varies by platform, so a codepoint of 128 or above isn't safely
* representable everywhere this engine targets.
*/
// Thick, solid, uninterrupted up arrow - Caps Lock. A trailing tile
// (char code 127/DEL) that was never a real character to begin with.
#define FONT_ICON_CAPSLOCK "\x7F"
// Same up arrow, but with a thinner and gapped shaft - Shift. Reuses
// the backtick's glyph slot: backtick was never drawn by this font
// anyway, and isn't a key this engine's virtual keyboard can type.
#define FONT_ICON_SHIFT "`"
// A "return" arrow (down then left, with a leftward arrowhead) - the
// keyboard's newline key. Reuses the pipe's glyph slot, for the same
// reason as FONT_ICON_SHIFT.
#define FONT_ICON_NEWLINE "|"
// An underscore with a tick at each end ("|___|") - the keyboard's
// space key. Reuses the tilde's glyph slot: tilde was never drawn by
// this font, and was explicitly dropped from this engine's virtual
// keyboard's own key set.
#define FONT_ICON_SPACE "~"
// Caps Lock's arrow rotated to point left - the keyboard's backspace
// key. Reuses the backslash's glyph slot, for the same reason as
// FONT_ICON_SHIFT/FONT_ICON_NEWLINE/FONT_ICON_SPACE. Last free reused
// slot below 128 - one more custom icon after this needs
// FONT_DEFAULT_COLUMNS/ROWS grown to make room.
#define FONT_ICON_BACKSPACE "\\"
extern font_t FONT_DEFAULT;
/**
* Hard coded bitmap data for the built-in default font, extracted
* pixel-for-pixel from the original ui/minogram.png glyph atlas (alpha
* >= 128 counts as set). Indexed [glyph][row], where glyph 0 corresponds
* to TEXT_CHAR_START ('!') and glyphs run consecutively through the
* printable ASCII range. Each row byte holds FONT_DEFAULT_TILE_WIDTH bit
* flags, one per pixel column: bit (FONT_DEFAULT_TILE_WIDTH - 1) is the
* leftmost pixel and bit 0 is the rightmost; 1 means the pixel is set,
* 0 means it is not.
* Hard coded bitmap data for the built-in default font. Indexed
* [glyph][row], where glyph 0 corresponds to TEXT_CHAR_START ('!') and
* glyphs run consecutively through the printable ASCII range. Each row
* byte holds FONT_DEFAULT_TILE_WIDTH bit flags, one per pixel column:
* bit (FONT_DEFAULT_TILE_WIDTH - 1) is the leftmost pixel and bit 0 is
* the rightmost; 1 means the pixel is set, 0 means it is not.
*/
extern const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
FONT_DEFAULT_TILE_HEIGHT
];
/**
* Builds the built-in default font (texture + tileset) directly from
* FONT_DEFAULT_GLYPHS, without going through the asset system.
* Builds the default font's texture + tileset directly from
* FONT_DEFAULT_GLYPHS, without going through the asset system - so the
* engine always has a usable font to render with regardless of whether
* asset loading (e.g. the packed .dsk archive) succeeds.
*
* @return Either an error or success result.
*/
errorret_t fontInitDefault(void);
errorret_t fontDefaultInit(void);
/**
* Disposes of the built-in default font created by fontInitDefault.
* Disposes of the default font created by fontDefaultInit().
*
* @return Either an error or success result.
*/
errorret_t fontDisposeDefault(void);
errorret_t fontDefaultDispose(void);
+115 -106
View File
@@ -12,12 +12,12 @@
#include "display/shader/shaderunlit.h"
errorret_t textInit(void) {
errorChain(fontInitDefault());
errorChain(fontDefaultInit());
errorOk();
}
errorret_t textDispose(void) {
errorChain(fontDisposeDefault());
errorChain(fontDefaultDispose());
errorOk();
}
@@ -54,6 +54,62 @@ spritebatchsprite_t textGetSprite(
return sprite;
}
int32_t textBuffer(
const float_t x,
const float_t y,
const char_t *text,
font_t *font,
spritebatchsprite_t *outSprites,
const int32_t maxSprites,
int32_t *charIndex,
float_t *posX,
float_t *posY
) {
assertNotNull(text, "Text cannot be NULL");
if(outSprites == NULL) {
int32_t count = 0;
char_t c;
int32_t i = 0;
while((c = text[i++]) != '\0') {
if(c != ' ' && c != '\n') count++;
}
return count;
}
assertNotNull(font, "Font cannot be NULL");
assertTrue(maxSprites > 0, "Max sprites must be greater than zero");
assertNotNull(posX, "Output posX cannot be NULL");
assertNotNull(posY, "Output posY cannot be NULL");
assertNotNull(charIndex, "Output charIndex cannot be NULL");
int32_t spriteIndex = 0;
char_t c;
for(;;) {
c = text[*charIndex];
if(c == '\0') break;
(*charIndex)++;
if(c == '\n') {
*posX = x;
*posY += font->tileset->tileHeight;
continue;
}
if(c == ' ') {
*posX += font->tileset->tileWidth;
continue;
}
outSprites[spriteIndex++] = textGetSprite((vec2){*posX, *posY}, c, font);
*posX += font->tileset->tileWidth;
if(spriteIndex >= maxSprites) break;
}
return spriteIndex;
}
errorret_t textDraw(
const float_t x,
const float_t y,
@@ -62,125 +118,37 @@ errorret_t textDraw(
font_t *font
) {
assertNotNull(text, "Text cannot be NULL");
int32_t length = strlen(text);
if(length == 0) errorOk();
if(font == NULL) font = &FONT_DEFAULT;
spritebatchsprite_t sprite;
shadermaterial_t material = {
.unlit = {
.color = color,
.texture = font->texture
}
};
spritebatchsprite_t sprites[32];
float_t posX = x;
float_t posY = y;
int32_t buffered = 0;
int32_t charIndex = 0;
do {
buffered = textBuffer(
x, y, text, font,
sprites,
sizeof(sprites) / sizeof(spritebatchsprite_t),
&charIndex, &posX, &posY
);
errorChain(spriteBatchBuffer(sprites, buffered, &SHADER_UNLIT, material));
} while(charIndex < length);
char_t c;
int32_t i = 0;
while((c = text[i++]) != '\0') {
if(c == '\n') {
posX = x;
posY += font->tileset->tileHeight;
continue;
}
if(c == ' ') {
posX += font->tileset->tileWidth;
continue;
}
sprite = textGetSprite((vec2){posX, posY}, c, font);
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
posX += font->tileset->tileWidth;
}
errorOk();
}
uint32_t textBuildSpriteCache(
const char_t *text,
const font_t *font,
spritebatchsprite_t *sprites,
const uint32_t spritesMax,
int32_t *outWidth,
int32_t *outHeight
) {
assertNotNull(text, "Text cannot be NULL");
assertNotNull(font, "Font cannot be NULL");
assertNotNull(sprites, "Sprites cannot be NULL");
assertNotNull(outWidth, "Output width cannot be NULL");
assertNotNull(outHeight, "Output height cannot be NULL");
uint32_t count = 0;
float_t posX = 0.0f;
float_t posY = 0.0f;
int32_t width = 0;
int32_t lineWidth = 0;
int32_t height = font->tileset->tileHeight;
char_t c;
int32_t i = 0;
while((c = text[i++]) != '\0') {
if(c == '\n') {
if(lineWidth > width) width = lineWidth;
lineWidth = 0;
posX = 0.0f;
posY += font->tileset->tileHeight;
height += font->tileset->tileHeight;
continue;
}
if(c == ' ') {
posX += font->tileset->tileWidth;
lineWidth += font->tileset->tileWidth;
continue;
}
assertTrue(count < spritesMax, "Text produces too many sprites");
sprites[count++] = textGetSprite((vec2){ posX, posY }, c, font);
posX += font->tileset->tileWidth;
lineWidth += font->tileset->tileWidth;
}
if(lineWidth > width) width = lineWidth;
*outWidth = width;
*outHeight = height;
return count;
}
errorret_t textDrawSpriteCache(
const spritebatchsprite_t *sprites,
const uint32_t spriteCount,
spritebatchsprite_t *scratch,
const float_t x,
const float_t y,
const color_t color,
texture_t *texture
) {
assertNotNull(scratch, "Scratch buffer cannot be NULL");
assertNotNull(texture, "Texture cannot be NULL");
if(spriteCount == 0) errorOk();
for(uint32_t i = 0; i < spriteCount; i++) {
scratch[i] = sprites[i];
scratch[i].min[0] += x;
scratch[i].min[1] += y;
scratch[i].max[0] += x;
scratch[i].max[1] += y;
}
shadermaterial_t material = {
.unlit = {
.color = color,
.texture = texture
}
};
errorChain(spriteBatchBuffer(scratch, spriteCount, &SHADER_UNLIT, material));
errorOk();
}
void textMeasure(
int32_t textMeasure(
const char_t *text,
const font_t *font,
int32_t *outWidth,
@@ -193,6 +161,7 @@ void textMeasure(
int32_t width = 0;
int32_t height = font->tileset->tileHeight;
int32_t lineWidth = 0;
int32_t spriteCount = 0;
char_t c;
int32_t i = 0;
@@ -205,10 +174,50 @@ void textMeasure(
}
lineWidth += font->tileset->tileWidth;
if(c != ' ') {
spriteCount++;
}
}
if(lineWidth > width) width = lineWidth;
*outWidth = width;
*outHeight = height;
return spriteCount;
}
void textWrap(char_t *text, const font_t *font, const float_t maxWidth) {
assertNotNull(text, "Text cannot be NULL");
assertNotNull(font, "Font cannot be NULL");
float_t fontWidth = (float_t)font->tileset->tileWidth;
if(fontWidth <= 0.0f) return;
int32_t charsPerLine = (int32_t)(maxWidth / fontWidth);
if(charsPerLine <= 0) return;
int32_t lineWidth = 0;
int32_t lastSpace = -1;
for(int32_t i = 0; text[i] != '\0'; i++) {
if(text[i] == '\n') {
lineWidth = 0;
lastSpace = -1;
continue;
}
if(text[i] == ' ') {
lastSpace = i;
}
lineWidth++;
if(lineWidth > charsPerLine && lastSpace != -1) {
text[lastSpace] = '\n';
lineWidth = i - lastSpace;
lastSpace = -1;
}
}
}
+47 -49
View File
@@ -40,6 +40,37 @@ spritebatchsprite_t textGetSprite(
const font_t *font
);
/**
* Buffers a string into sprites for rendering. If outSprites is NULL then
* the function will only return the count of sprites necessary for the buffer.
*
* posX and posY are updated whilst buffering characters, if you need to do
* buffering in sets then these will be reusable between buffer commands. Start
* by setting these to x and y initially.
*
* @param x The x-coordinate to start buffering the text at.
* @param y The y-coordinate to start buffering the text at.
* @param text The null-terminated string of text to buffer.
* @param font Font to use for rendering.
* @param outSprites Pointer to an array of spritebatchsprite_t.
* @param maxSprites The maximum number of sprites in outSprites.
* @param charIndex Pointer to an int32_t to store the character indexed.
* @param posX Pointer to a float_t to store the final x position.
* @param posY Pointer to a float_t to store the final y position.
* @return The count of sprites buffered.
*/
int32_t textBuffer(
const float_t x,
const float_t y,
const char_t *text,
font_t *font,
spritebatchsprite_t *outSprites,
const int32_t maxSprites,
int32_t *charIndex,
float_t *posX,
float_t *posY
);
/**
* Draws a string of text at the specified position.
*
@@ -58,54 +89,6 @@ errorret_t textDraw(
font_t *font
);
/**
* Builds a cache of sprites (glyph geometry + UVs, relative to origin
* 0,0) for a string of text. Callers that redraw the same text every
* frame (e.g. UI labels/widgets) should build this once and reuse it
* via textDrawSpriteCache, instead of re-deriving glyph geometry every
* frame the way textDraw does.
*
* @param text The null-terminated string to build sprites for.
* @param font Font to use for tile lookup.
* @param sprites Destination array to write sprites into.
* @param spritesMax Capacity of the sprites array.
* @param outWidth Pointer to store the measured width in pixels.
* @param outHeight Pointer to store the measured height in pixels.
* @return The number of sprites written.
*/
uint32_t textBuildSpriteCache(
const char_t *text,
const font_t *font,
spritebatchsprite_t *sprites,
const uint32_t spritesMax,
int32_t *outWidth,
int32_t *outHeight
);
/**
* Draws a previously-built sprite cache (see textBuildSpriteCache) at the
* given position in a single batched draw call.
*
* @param sprites Cached sprites, relative to origin 0,0.
* @param spriteCount Number of sprites in the cache.
* @param scratch Caller-owned scratch buffer, at least spriteCount
* entries, used to translate the cached sprites into position.
* @param x The x-coordinate to draw the text at.
* @param y The y-coordinate to draw the text at.
* @param color The color to draw the text in.
* @param texture The font's texture to sample glyphs from.
* @return Either an error or success result.
*/
errorret_t textDrawSpriteCache(
const spritebatchsprite_t *sprites,
const uint32_t spriteCount,
spritebatchsprite_t *scratch,
const float_t x,
const float_t y,
const color_t color,
texture_t *texture
);
/**
* Measures the width and height of the given text string when rendered.
*
@@ -113,10 +96,25 @@ errorret_t textDrawSpriteCache(
* @param font Font to use for measurement.
* @param outWidth Pointer to store the measured width in pixels.
* @param outHeight Pointer to store the measured height in pixels.
* @return The count of sprites that will be rendered for the given text.
*/
void textMeasure(
int32_t textMeasure(
const char_t *text,
const font_t *font,
int32_t *outWidth,
int32_t *outHeight
);
/**
* Word-wraps text in place for display at up to maxWidth pixels wide,
* by replacing the space nearest each overflow point with a newline.
* Length is unchanged - this only ever swaps existing spaces for
* newlines, never inserts characters - so it's always safe to call on a
* fixed-size buffer. A single word wider than maxWidth on its own is
* left unbroken.
*
* @param text Null-terminated, caller-owned buffer to wrap in place.
* @param font Font to measure character width with.
* @param maxWidth Maximum line width, in pixels.
*/
void textWrap(char_t *text, const font_t *font, const float_t maxWidth);
+2 -2
View File
@@ -12,7 +12,7 @@
#include "display/display.h"
texture_t TEXTURE_WHITE;
color_t TEXTURE_WHITE_PIXELS[4*4] = {
color_t TEXTURE_WHITE_PIXELS[TEXTURE_FIXED_WIDTH * TEXTURE_FIXED_HEIGHT] = {
COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE,
COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE,
COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE,
@@ -20,7 +20,7 @@ color_t TEXTURE_WHITE_PIXELS[4*4] = {
};
texture_t TEXTURE_TEST;
color_t TEXTURE_TEST_PIXELS[4*4] = {
color_t TEXTURE_TEST_PIXELS[TEXTURE_FIXED_WIDTH * TEXTURE_FIXED_HEIGHT] = {
COLOR_BLACK, COLOR_MAGENTA, COLOR_BLACK, COLOR_MAGENTA,
COLOR_MAGENTA, COLOR_BLACK, COLOR_MAGENTA, COLOR_BLACK,
COLOR_BLACK, COLOR_MAGENTA, COLOR_BLACK, COLOR_MAGENTA,
+5 -2
View File
@@ -17,6 +17,9 @@
#error "textureDisposePlatform should not be defined."
#endif
#define TEXTURE_FIXED_WIDTH 4
#define TEXTURE_FIXED_HEIGHT 4
typedef textureformatplatform_t textureformat_t;
typedef textureplatform_t texture_t;
@@ -29,9 +32,9 @@ typedef union texturedata_u {
} texturedata_t;
extern texture_t TEXTURE_WHITE;
extern color_t TEXTURE_WHITE_PIXELS[4*4];
extern color_t TEXTURE_WHITE_PIXELS[TEXTURE_FIXED_WIDTH * TEXTURE_FIXED_HEIGHT];
extern texture_t TEXTURE_TEST;
extern color_t TEXTURE_TEST_PIXELS[4*4];
extern color_t TEXTURE_TEST_PIXELS[TEXTURE_FIXED_WIDTH * TEXTURE_FIXED_HEIGHT];
/**
* Initializes a texture.
+25 -34
View File
@@ -10,20 +10,18 @@
#include "time/time.h"
#include "input/input.h"
#include "locale/localemanager.h"
#include "rpg/rpg.h"
#include "display/display.h"
#include "scene/scene.h"
#include "asset/asset.h"
#include "script/scriptmanager.h"
#include "script/module/scene/modulescene.h"
#include "ui/ui.h"
#include "assert/assert.h"
#include "network/network.h"
#include "game/game.h"
#ifdef DUSK_NETWORK
#include "network/network.h"
#endif
#include "system/system.h"
#include "console/console.h"
#include "save/save.h"
#include "save/savesettings.h"
#include "log/log.h"
#include "save/save.h"\
engine_t ENGINE;
@@ -41,15 +39,15 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
errorChain(systemInit());
errorChain(inputInit());
errorChain(assetInit());
errorChain(scriptManagerInit());
errorChain(saveInit());
errorChain(saveSettingsLoad());
errorChain(localeManagerInit());
errorChain(displayInit());
errorChain(uiInit());
errorChain(networkInit());
errorChain(rpgInit());
#ifdef DUSK_NETWORK
errorChain(networkInit());
#endif
errorChain(sceneInit());
errorChain(gameInit());
consolePrint("Engine initialized");
@@ -59,36 +57,28 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
consolePrint("Assertions real");
#endif
// sceneSet(SCENE_TYPE_OVERWORLD);
sceneSet(SCENE_TYPE_INITIAL);
errorOk();
}
errorret_t engineUpdate(void) {
// Order here is important.
errorChain(networkUpdate());
#ifdef DUSK_NETWORK
errorChain(networkUpdate());
#endif
errorChain(saveUpdate());
timeUpdate();
const systemdialogtype_t dialogType = systemGetActiveDialogType();
if(dialogType == SYSTEM_DIALOG_TYPE_NONE) {
inputUpdate();
consoleUpdate();
errorChain(gameUpdate());
errorChain(moduleSceneUpdateCurrent());
errorChain(sceneUpdate());
errorChain(assetUpdate());
errorChain(uiUpdate());
}
inputUpdate();
consoleUpdate();
errorChain(rpgUpdate());
errorChain(sceneUpdate());
errorChain(assetUpdate());
errorChain(uiUpdate());
// Render
errorChain(displayUpdate());
if(
dialogType == SYSTEM_DIALOG_TYPE_NONE &&
inputPressed(INPUT_BIND_RAGEQUIT)
) {
ENGINE.running = false;
}
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
errorOk();
}
@@ -97,15 +87,16 @@ void engineExit(void) {
}
errorret_t engineDispose(void) {
errorChain(gameDispose());
errorChain(sceneDispose());
errorChain(networkDispose());
#ifdef DUSK_NETWORK
errorChain(networkDispose());
#endif
errorChain(rpgDispose());
localeManagerDispose();
errorChain(uiDispose());
consoleDispose();
errorChain(displayDispose());
errorChain(saveDispose());
errorChain(scriptManagerDispose());
errorChain(assetDispose());
errorOk();
+1
View File
@@ -37,3 +37,4 @@ errorret_t engineUpdate(void);
* Shuts down the engine.
*/
errorret_t engineDispose(void);
-16
View File
@@ -1,16 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
entity.c
entitymanager.c
component.c
entityprefab.c
)
# Subdirs
add_subdirectory(component)
-152
View File
@@ -1,152 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entitymanager.h"
#include "assert/assert.h"
#include "util/memory.h"
componentdefinition_t COMPONENT_DEFINITIONS[] = {
[COMPONENT_TYPE_NULL] = { 0 },
#define X(enm, type, field, iMethod, dMethod, rMethod) \
[COMPONENT_TYPE_##enm] = { \
.enumName = #enm, \
.name = #field, \
.init = iMethod, \
.dispose = dMethod, \
.render = rMethod \
},
#include "componentlist.h"
#undef X
[COMPONENT_TYPE_COUNT] = { 0 }
};
void componentInit(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const componenttype_t type
) {
assertNotNull(mgr, "Entity manager cannot be null");
assertTrue(entityId < ENTITY_COUNT_MAX, "Entity ID OOB");
assertTrue(componentId < ENTITY_COMPONENT_COUNT_MAX, "Component ID OOB");
assertTrue(type < COMPONENT_TYPE_COUNT, "Component type OOB");
assertTrue(type != COMPONENT_TYPE_NULL, "Cannot initialize null component");
componentindex_t index = componentGetIndex(entityId, componentId);
component_t *cmp = &mgr->components[index];
memoryZero(cmp, sizeof(component_t));
cmp->type = type;
if(COMPONENT_DEFINITIONS[type].init) {
COMPONENT_DEFINITIONS[type].init(mgr, entityId, componentId);
}
}
void * componentGetData(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const componenttype_t type
) {
assertNotNull(mgr, "Entity manager cannot be null");
assertTrue(entityId < ENTITY_COUNT_MAX, "Entity ID OOB");
assertTrue(componentId < ENTITY_COMPONENT_COUNT_MAX, "Component ID OOB");
assertTrue(type < COMPONENT_TYPE_COUNT, "Component type OOB");
assertTrue(type != COMPONENT_TYPE_NULL, "Cannot get data of null component");
componentindex_t index = componentGetIndex(entityId, componentId);
component_t *cmp = &mgr->components[index];
assertTrue(cmp->type == type, "Component type mismatch");
return &cmp->data;
}
componentindex_t componentGetIndex(
const entityid_t entityId,
const componentid_t componentId
) {
assertTrue(entityId < ENTITY_COUNT_MAX, "Entity ID OOB");
assertTrue(componentId < ENTITY_COMPONENT_COUNT_MAX, "Component ID OOB");
return (entityId * ENTITY_COMPONENT_COUNT_MAX) + componentId;
}
entityid_t componentGetEntitiesWithComponent(
entitymanager_t *mgr,
const componenttype_t type,
entityid_t outEntities[ENTITY_COUNT_MAX],
componentid_t outComponents[ENTITY_COUNT_MAX]
) {
assertNotNull(mgr, "Entity manager cannot be null");
assertTrue(type < COMPONENT_TYPE_COUNT, "Component type OOB");
assertTrue(type != COMPONENT_TYPE_NULL, "Cannot check NULL type");
assertNotNull(outEntities, "Output entities array cannot be null");
assertNotNull(outComponents, "Output components array cannot be null");
entityid_t written = 0;
for(entityid_t i = 0; i < ENTITY_COUNT_MAX; i++) {
componentid_t used = mgr->entitiesWithComponent[
type * ENTITY_COUNT_MAX + i
];
if(used == COMPONENT_ID_INVALID) continue;
assertTrue(
mgr->components[componentGetIndex(i, used)].type == type,
"Component type mismatch in entitiesWithComponent lookup"
);
assertTrue(
(mgr->entities[i].state & ENTITY_STATE_ACTIVE) != 0,
"Inactive entity in entitiesWithComponent lookup"
);
assertTrue(
used < ENTITY_COMPONENT_COUNT_MAX,
"Component ID OOB in entitiesWithComponent lookup"
);
assertTrue(
componentGetIndex(i,used) < ENTITY_COUNT_MAX*ENTITY_COMPONENT_COUNT_MAX,
"Component index OOB in entitiesWithComponent lookup"
);
outComponents[written] = used;
outEntities[written++] = i;
}
return written;
}
errorret_t componentRenderAll(entitymanager_t *mgr) {
assertNotNull(mgr, "Entity manager cannot be null");
for(entityid_t eid = 0; eid < ENTITY_COUNT_MAX; eid++) {
if(!(mgr->entities[eid].state & ENTITY_STATE_ACTIVE)) continue;
for(componentid_t cid = 0; cid < ENTITY_COMPONENT_COUNT_MAX; cid++) {
component_t *cmp = &mgr->components[componentGetIndex(eid, cid)];
if(cmp->type == COMPONENT_TYPE_NULL) continue;
if(!COMPONENT_DEFINITIONS[cmp->type].render) continue;
errorChain(COMPONENT_DEFINITIONS[cmp->type].render(mgr, eid, cid));
}
}
errorOk();
}
void componentDispose(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
assertNotNull(mgr, "Entity manager cannot be null");
assertTrue(entityId < ENTITY_COUNT_MAX, "Entity ID OOB");
assertTrue(componentId < ENTITY_COMPONENT_COUNT_MAX, "Component ID OOB");
componentindex_t index = componentGetIndex(entityId, componentId);
component_t *cmp = &mgr->components[index];
if(cmp->type == COMPONENT_TYPE_NULL) return;
if(COMPONENT_DEFINITIONS[cmp->type].dispose) {
COMPONENT_DEFINITIONS[cmp->type].dispose(mgr, entityId, componentId);
}
cmp->type = COMPONENT_TYPE_NULL;
}
-157
View File
@@ -1,157 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entitybase.h"
#include "error/error.h"
#define X(enumName, type, field, init, dispose, render) \
// do nothing
#include "componentlist.h"
#undef X
typedef union {
#define X(enumName, type, field, init, dispose, render) type field;
#include "componentlist.h"
#undef X
} componentdata_t;
/**
* Callback signature for a component's init/dispose hooks.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
*/
typedef void (*componentcallback_t)(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Callback signature for a component's render hook.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @return Error state.
*/
typedef errorret_t (*componentcallbackerror_t)(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
typedef struct {
const char_t *enumName;
const char_t *name;
componentcallback_t init;
componentcallback_t dispose;
componentcallbackerror_t render;
} componentdefinition_t;
typedef enum {
COMPONENT_TYPE_NULL,
#define X(enumName, type, field, init, dispose, render) \
COMPONENT_TYPE_##enumName,
#include "componentlist.h"
#undef X
COMPONENT_TYPE_COUNT
} componenttype_t;
typedef struct {
componenttype_t type;
componentdata_t data;
} component_t;
extern componentdefinition_t COMPONENT_DEFINITIONS[];
/**
* Initializes a component of the given type for the entity with component ID.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param type The type of the component to initialize.
*/
void componentInit(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const componenttype_t type
);
/**
* Gets the pointer to the data of a component for the entity with component ID.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param type The type of the component to get, only used for assertion.
* @return A pointer to the component data.
*/
void * componentGetData(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const componenttype_t type
);
/**
* Gets the index of a component for the entity with component ID.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @return The index of the component in the component array.
*/
componentindex_t componentGetIndex(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Gets the entity IDs of all entities with a component of the given type.
*
* @param mgr The entity manager to search.
* @param type The type of the component to get entities for.
* @param outEntities An array to write the entity IDs to, must be at least
* ENTITY_COUNT_MAX in size.
* @param outComponents An array to write the component IDs to.
* @return The number of entity IDs written to outEntities.
*/
entityid_t componentGetEntitiesWithComponent(
entitymanager_t *mgr,
const componenttype_t type,
entityid_t outEntities[ENTITY_COUNT_MAX],
componentid_t outComponents[ENTITY_COUNT_MAX]
);
/**
* Disposes of a component for the entity with component ID.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
*/
void componentDispose(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Calls the render callback on every active component that defines one.
* Iterates all active entities and all their component slots. No-op for
* components whose definition has render == NULL.
*
* @param mgr The entity manager to render.
* @return Error state.
*/
errorret_t componentRenderAll(entitymanager_t *mgr);
-10
View File
@@ -1,10 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Subdirs
add_subdirectory(display)
add_subdirectory(physics)
add_subdirectory(trigger)
add_subdirectory(animation)
@@ -1,114 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entityanimation.h"
#include "entity/entitymanager.h"
#include "util/memory.h"
void entityAnimationInit(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityanimation_t *animComp = entityAnimationGet(mgr, entityId, componentId);
memoryZero(animComp, sizeof(entityanimation_t));
entityUpdateAdd(mgr, entityId, entityAnimationUpdate, componentId, NULL);
}
entityanimation_t *entityAnimationGet(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_ANIMATION
);
}
void entityAnimationSetKeyframes(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
keyframe_t **channelTracks,
uint16_t *channelTrackCounts,
const uint16_t channelCount
) {
entityanimation_t *animComp = entityAnimationGet(mgr, entityId, componentId);
animationInit(
&animComp->anim, channelTracks, channelTrackCounts, channelCount
);
}
void entityAnimationPlay(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityanimation_t *animComp = entityAnimationGet(mgr, entityId, componentId);
animComp->anim.time = 0.0f;
animComp->anim.playing = true;
}
void entityAnimationStop(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityanimation_t *animComp = entityAnimationGet(mgr, entityId, componentId);
animComp->anim.playing = false;
}
bool_t entityAnimationIsPlaying(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityanimation_t *animComp = entityAnimationGet(mgr, entityId, componentId);
return animComp->anim.playing;
}
void entityAnimationSetLoop(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const bool_t loop
) {
entityanimation_t *animComp = entityAnimationGet(mgr, entityId, componentId);
animComp->anim.loop = loop;
}
void entityAnimationSetSpeed(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const float_t speed
) {
entityanimation_t *animComp = entityAnimationGet(mgr, entityId, componentId);
animComp->anim.speed = speed;
}
float_t entityAnimationGetValue(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const uint16_t channelIndex
) {
entityanimation_t *animComp = entityAnimationGet(mgr, entityId, componentId);
return animationGetValue(&animComp->anim, channelIndex);
}
void entityAnimationUpdate(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
void *user
) {
entityanimation_t *animComp = entityAnimationGet(mgr, entityId, componentId);
animationUpdate(&animComp->anim);
}
@@ -1,176 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
#include "animation/animation.h"
typedef struct {
animation_t anim;
} entityanimation_t;
/**
* Initializes the animation component: no keyframes set, and registers
* entityAnimationUpdate as an update callback. Call
* entityAnimationSetKeyframes() before entityAnimationPlay().
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
*/
void entityAnimationInit(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Gets the underlying animation structure (temporarily) for the given
* entity. Prefer the dedicated getters/setters where possible.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @return The animation component data for the given entity and
* component ID.
*/
entityanimation_t *entityAnimationGet(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Sets the entity's keyframes, stopped, at speed 1.0, non-looping. See
* keyframeSetInit() -- channelTracks/channelTrackCounts and the
* keyframe_t arrays they point to are not copied, and must outlive this
* component (e.g. static/const arrays owned by the caller).
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param channelTracks Array of channelCount keyframe_t arrays -- one per
* animated channel (e.g. position.x/y/z), sharing this animation's
* timeline.
* @param channelTrackCounts Array of channelCount keyframe counts,
* matching channelTracks.
* @param channelCount The number of channels.
*/
void entityAnimationSetKeyframes(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
keyframe_t **channelTracks,
uint16_t *channelTrackCounts,
const uint16_t channelCount
);
/**
* Starts (or restarts) playback from time 0.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
*/
void entityAnimationPlay(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Stops playback without resetting the current time.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
*/
void entityAnimationStop(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Checks whether the animation is currently playing.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @return True if playing.
*/
bool_t entityAnimationIsPlaying(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Sets whether the animation loops on reaching its final keyframe, rather
* than stopping there.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param loop True to loop, false to stop at the end.
*/
void entityAnimationSetLoop(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const bool_t loop
);
/**
* Sets the animation's playback rate multiplier.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param speed The new playback rate; 1.0 = normal speed.
*/
void entityAnimationSetSpeed(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const float_t speed
);
/**
* Evaluates one of the animation's channels at its current playback
* time, regardless of whether it's currently playing.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param channelIndex The channel to evaluate, in [0, channelCount) as
* passed to entityAnimationSetKeyframes().
* @return That channel's value at the current time.
*/
float_t entityAnimationGetValue(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const uint16_t channelIndex
);
/**
* Per-tick update for the animation component: calls animationUpdate()
* (a no-op if not playing). Registered automatically as an update
* callback by entityAnimationInit.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param user Unused.
*/
void entityAnimationUpdate(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
void *user
);
@@ -1,140 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entity/entitymanager.h"
#include "entity/entity.h"
#include "entity/component/display/entityposition.h"
#include "display/screen/screen.h"
void entityCameraInit(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entitycamera_t *cam = (entitycamera_t *)componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_CAMERA
);
cam->nearClip = 0.1f;
cam->farClip = 5000.0f;
cam->projType = ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE;
cam->perspective.fov = glm_rad(45.0f);
}
void entityCameraGetProjection(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
mat4 out
) {
entitycamera_t *cam = (entitycamera_t *)componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_CAMERA
);
if(
cam->projType == ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE ||
cam->projType == ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE_FLIPPED
) {
glm_mat4_identity(out);
glm_perspective(
cam->perspective.fov,
SCREEN.aspect,
cam->nearClip,
cam->farClip,
out
);
if(cam->projType == ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE_FLIPPED) {
out[1][1] *= -1.0f;
}
} else if(cam->projType == ENTITY_CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC) {
glm_mat4_identity(out);
glm_ortho(
cam->orthographic.left,
cam->orthographic.right,
cam->orthographic.top,
cam->orthographic.bottom,
cam->nearClip,
cam->farClip,
out
);
}
}
entityid_t entityCameraGetCurrent(entitymanager_t *mgr) {
entityid_t camEnts[ENTITY_COUNT_MAX];
componentid_t camComps[ENTITY_COUNT_MAX];
entityid_t count = componentGetEntitiesWithComponent(
mgr, COMPONENT_TYPE_CAMERA, camEnts, camComps
);
if(count == 0) return ENTITY_ID_INVALID;
return camEnts[0];
}
void entityCameraGetForward(
entitymanager_t *mgr,
const entityid_t entityId,
vec2 out
) {
componentid_t posComp = entityGetComponent(
mgr, entityId, COMPONENT_TYPE_POSITION
);
mat4 transform;
entityPositionGetTransform(mgr, entityId, posComp, transform);
// transform is an object->world matrix; column 2 is the entity's local Z
// axis expressed in world space. Cameras look down their local -Z.
float_t fx = -transform[2][0];
float_t fz = -transform[2][2];
float_t len = sqrtf(fx * fx + fz * fz);
if(len > 1e-6f) { fx /= len; fz /= len; }
out[0] = fx;
out[1] = fz;
}
void entityCameraGetRight(
entitymanager_t *mgr,
const entityid_t entityId,
vec2 out
) {
componentid_t posComp = entityGetComponent(
mgr, entityId, COMPONENT_TYPE_POSITION
);
mat4 transform;
entityPositionGetTransform(mgr, entityId, posComp, transform);
// transform is an object->world matrix; column 0 is the entity's local X
// (right) axis expressed in world space.
float_t rx = transform[0][0];
float_t rz = transform[0][2];
float_t len = sqrtf(rx * rx + rz * rz);
if(len > 1e-6f) { rx /= len; rz /= len; }
out[0] = rx;
out[1] = rz;
}
void entityCameraLookAtPixelPerfect(
entitymanager_t *mgr,
const entityid_t ent,
const componentid_t posComp,
const componentid_t camComp,
const vec3 point,
const vec3 eyeOffset,
const float_t scale
) {
entitycamera_t *cam = (entitycamera_t *)componentGetData(
mgr, ent, camComp, COMPONENT_TYPE_CAMERA
);
float_t dist = (
(float_t)SCREEN.height / (2.0f * scale * tanf(cam->perspective.fov * 0.5f))
);
vec3 eye = {
point[0] + eyeOffset[0],
point[1] + dist + eyeOffset[1],
point[2] + eyeOffset[2]
};
vec3 up = { 0.0f, 0.0f, -1.0f };
entityPositionLookAt(mgr, ent, posComp, eye, (float_t *)point, up);
}
@@ -1,122 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
#include "error/error.h"
typedef enum {
ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE,
ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE_FLIPPED,
ENTITY_CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC
} entitycameraprojectiontype_t;
typedef struct {
union {
struct {
float_t fov;
} perspective;
struct {
float_t left;
float_t right;
float_t top;
float_t bottom;
} orthographic;
};
float_t nearClip;
float_t farClip;
entitycameraprojectiontype_t projType;
} entitycamera_t;
/**
* Initializes an entity camera component.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
*/
void entityCameraInit(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Renders out the projection matrix for the given camera.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param out The output projection matrix.
*/
void entityCameraGetProjection(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
mat4 out
);
/**
* Returns the entity ID of the first active camera, or ENTITY_ID_INVALID if
* none are active.
*
* @param mgr The entity manager to search.
*/
entityid_t entityCameraGetCurrent(entitymanager_t *mgr);
/**
* Gets the camera's horizontal forward direction (XZ plane) from its
* position component. Automatically finds the position component on the
* entity.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The camera entity ID.
* @param out Output vec2: {forwardX, forwardZ} normalized.
*/
void entityCameraGetForward(
entitymanager_t *mgr,
const entityid_t entityId,
vec2 out
);
/**
* Gets the camera's horizontal right direction (XZ plane) from its position
* component. Automatically finds the position component on the entity.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The camera entity ID.
* @param out Output vec2: {rightX, rightZ} normalized.
*/
void entityCameraGetRight(
entitymanager_t *mgr,
const entityid_t entityId,
vec2 out
);
/**
* Positions the camera to look at a 3D point at a pixel-perfect distance
* derived from the camera's FOV and screen height.
*
* @param mgr The entity manager that owns the entity.
* @param ent The camera entity ID.
* @param posComp The position component ID.
* @param camComp The camera component ID.
* @param point World position to look at.
* @param eyeOffset Offset added to the eye position only (not the target).
* @param scale Pixels per world unit. 1.0 = pixel perfect, 2.0 = 2px per unit.
*/
void entityCameraLookAtPixelPerfect(
entitymanager_t *mgr,
const entityid_t ent,
const componentid_t posComp,
const componentid_t camComp,
const vec3 point,
const vec3 eyeOffset,
const float_t scale
);
@@ -1,669 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entity/entitymanager.h"
#include "assert/assert.h"
void entityPositionInit(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
pos->flags = 0;
pos->parentEntityId = ENTITY_ID_INVALID;
pos->parentComponentId = COMPONENT_ID_INVALID;
pos->childCount = 0;
glm_vec3_zero(pos->position);
glm_vec3_zero(pos->rotation);
glm_vec3_one(pos->scale);
glm_mat4_identity(pos->localTransform);
glm_mat4_identity(pos->worldTransform);
}
void entityPositionLookAt(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 eye,
vec3 target,
vec3 up
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
// glm_lookat() produces a view matrix (world -> eye space). Every other
// setter treats localTransform as this entity's placement in world space
// (eye -> world), so invert it here to keep that meaning consistent --
// callers that need a view matrix (e.g. scene rendering) invert it back.
mat4 view;
glm_lookat(eye, target, up, view);
glm_mat4_inv(view, pos->localTransform);
// localTransform is now authoritative; PRS cache is stale.
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_PRS_DIRTY)
& ~(ENTITY_POSITION_FLAG_ROTATION_DIRTY |
ENTITY_POSITION_FLAG_POSITION_DIRTY);
entityPositionMarkDirty(mgr, pos);
}
void entityPositionGetTransform(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
mat4 dest
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsureWorld(mgr, pos);
glm_mat4_copy(
pos->parentEntityId == ENTITY_ID_INVALID
? pos->localTransform : pos->worldTransform,
dest
);
}
void entityPositionGetLocalTransform(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
mat4 dest
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsureLocal(pos);
glm_mat4_copy(pos->localTransform, dest);
}
void entityPositionGetLocalPosition(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsurePRS(pos);
glm_vec3_copy(pos->position, dest);
}
void entityPositionGetWorldPosition(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
if(pos->parentEntityId == ENTITY_ID_INVALID) {
entityPositionEnsurePRS(pos);
glm_vec3_copy(pos->position, dest);
return;
}
entityPositionEnsureWorld(mgr, pos);
dest[0] = pos->worldTransform[3][0];
dest[1] = pos->worldTransform[3][1];
dest[2] = pos->worldTransform[3][2];
}
void entityPositionSetWorldPosition(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 position
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
if(pos->parentEntityId == ENTITY_ID_INVALID) {
glm_vec3_copy(position, pos->position);
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_POSITION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(mgr, pos);
return;
}
entityposition_t *parent = componentGetData(
mgr, pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsureWorld(mgr, parent);
mat4 invParent;
glm_mat4_inv(parent->worldTransform, invParent);
vec3 localPos;
glm_mat4_mulv3(invParent, position, 1.0f, localPos);
glm_vec3_copy(localPos, pos->position);
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_POSITION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(mgr, pos);
}
void entityPositionSetLocalPosition(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 position
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
glm_vec3_copy(position, pos->position);
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_POSITION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(mgr, pos);
}
void entityPositionGetLocalRotation(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsurePRS(pos);
glm_vec3_copy(pos->rotation, dest);
}
void entityPositionGetWorldRotation(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
if(pos->parentEntityId == ENTITY_ID_INVALID) {
entityPositionEnsurePRS(pos);
glm_vec3_copy(pos->rotation, dest);
return;
}
entityPositionEnsureWorld(mgr, pos);
const float_t (*wt)[4] = pos->worldTransform;
const float_t sx = sqrtf(
wt[0][0]*wt[0][0] + wt[0][1]*wt[0][1] + wt[0][2]*wt[0][2]
);
const float_t sy = sqrtf(
wt[1][0]*wt[1][0] + wt[1][1]*wt[1][1] + wt[1][2]*wt[1][2]
);
const float_t sz = sqrtf(
wt[2][0]*wt[2][0] + wt[2][1]*wt[2][1] + wt[2][2]*wt[2][2]
);
const float_t r00 = sx > 0.0f ? wt[0][0]/sx : 0.0f;
const float_t r10 = sy > 0.0f ? wt[1][0]/sy : 0.0f;
const float_t r20 = sz > 0.0f ? wt[2][0]/sz : 0.0f;
const float_t r01 = sx > 0.0f ? wt[0][1]/sx : 0.0f;
const float_t r11 = sy > 0.0f ? wt[1][1]/sy : 0.0f;
const float_t r21 = sz > 0.0f ? wt[2][1]/sz : 0.0f;
const float_t r22 = sz > 0.0f ? wt[2][2]/sz : 0.0f;
const float_t sinBeta = glm_clamp(r20, -1.0f, 1.0f);
dest[1] = asinf(sinBeta);
const float_t cosBeta = cosf(dest[1]);
if(fabsf(cosBeta) > 1e-6f) {
dest[0] = atan2f(-r21, r22);
dest[2] = atan2f(-r10, r00);
} else {
dest[2] = 0.0f;
dest[0] = (sinBeta > 0.0f) ? atan2f(r01, r11) : -atan2f(r01, r11);
}
}
void entityPositionSetLocalRotation(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 rotation
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
glm_vec3_copy(rotation, pos->rotation);
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(mgr, pos);
}
void entityPositionSetWorldRotation(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 rotation
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
if(pos->parentEntityId == ENTITY_ID_INVALID) {
glm_vec3_copy(rotation, pos->rotation);
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(mgr, pos);
return;
}
entityposition_t *parent = componentGetData(
mgr, pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsureWorld(mgr, parent);
// Build target world rotation matrix (unit scale) from XYZ euler.
const float_t c0 = cosf(rotation[0]), s0 = sinf(rotation[0]);
const float_t c1 = cosf(rotation[1]), s1 = sinf(rotation[1]);
const float_t c2 = cosf(rotation[2]), s2 = sinf(rotation[2]);
const float_t s0s1 = s0*s1, c0s1 = c0*s1;
// Named wr[col_stored][row_stored] matching cglm column-major layout.
const float_t wr00 = c1*c2;
const float_t wr01 = c0*s2 + s0s1*c2;
const float_t wr02 = s0*s2 - c0s1*c2;
const float_t wr10 = -c1*s2;
const float_t wr11 = c0*c2 - s0s1*s2;
const float_t wr12 = s0*c2 + c0s1*s2;
const float_t wr20 = s1;
const float_t wr21 = -s0*c1;
const float_t wr22 = c0*c1;
// Normalize parent world columns to extract pure rotation.
const float_t (*pt)[4] = parent->worldTransform;
const float_t psx = sqrtf(
pt[0][0]*pt[0][0] + pt[0][1]*pt[0][1] + pt[0][2]*pt[0][2]
);
const float_t psy = sqrtf(
pt[1][0]*pt[1][0] + pt[1][1]*pt[1][1] + pt[1][2]*pt[1][2]
);
const float_t psz = sqrtf(
pt[2][0]*pt[2][0] + pt[2][1]*pt[2][1] + pt[2][2]*pt[2][2]
);
const float_t pr00 = psx > 0.f ? pt[0][0]/psx : 0.f;
const float_t pr01 = psx > 0.f ? pt[0][1]/psx : 0.f;
const float_t pr02 = psx > 0.f ? pt[0][2]/psx : 0.f;
const float_t pr10 = psy > 0.f ? pt[1][0]/psy : 0.f;
const float_t pr11 = psy > 0.f ? pt[1][1]/psy : 0.f;
const float_t pr12 = psy > 0.f ? pt[1][2]/psy : 0.f;
const float_t pr20 = psz > 0.f ? pt[2][0]/psz : 0.f;
const float_t pr21 = psz > 0.f ? pt[2][1]/psz : 0.f;
const float_t pr22 = psz > 0.f ? pt[2][2]/psz : 0.f;
// local_R = parent_R^T * world_R (R^-1 == R^T for orthogonal matrices).
// Compute only the 7 entries of the local rotation matrix needed for XYZ
// euler extraction (stored column-major: [col][row] = math [row][col]).
// sinBeta = stored[2][0] = math[0][2]
// r21/r22 = stored[2][1..2] = math[1..2][2]
// r10/r00 = stored[1][0], stored[0][0] = math[0][1], math[0][0]
// gimbal = stored[0][1], stored[1][1] = math[1][0], math[1][1]
const float_t lr00 = pr00*wr00 + pr01*wr10 + pr02*wr20; // math[0][0]
const float_t lr10 = pr00*wr01 + pr01*wr11 + pr02*wr21; // math[0][1]
const float_t lr20 = pr00*wr02 + pr01*wr12 + pr02*wr22; // [0][2] -> sinBeta
const float_t lr01 = pr10*wr00 + pr11*wr10 + pr12*wr20; // math[1][0]
const float_t lr11 = pr10*wr01 + pr11*wr11 + pr12*wr21; // math[1][1]
const float_t lr21 = pr10*wr02 + pr11*wr12 + pr12*wr22; // [1][2] -> r21
const float_t lr22 = pr20*wr02 + pr21*wr12 + pr22*wr22; // [2][2] -> r22
const float_t sinBeta = glm_clamp(lr20, -1.0f, 1.0f);
pos->rotation[1] = asinf(sinBeta);
const float_t cosBeta = cosf(pos->rotation[1]);
if(fabsf(cosBeta) > 1e-6f) {
pos->rotation[0] = atan2f(-lr21, lr22);
pos->rotation[2] = atan2f(-lr10, lr00);
} else {
pos->rotation[2] = 0.0f;
pos->rotation[0] = (sinBeta > 0.0f)
? atan2f(lr01, lr11) : -atan2f(lr01, lr11);
}
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(mgr, pos);
}
void entityPositionGetLocalScale(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsurePRS(pos);
glm_vec3_copy(pos->scale, dest);
}
void entityPositionGetWorldScale(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
if(pos->parentEntityId == ENTITY_ID_INVALID) {
entityPositionEnsurePRS(pos);
glm_vec3_copy(pos->scale, dest);
return;
}
entityPositionEnsureWorld(mgr, pos);
const float_t (*wt)[4] = pos->worldTransform;
dest[0] = sqrtf(wt[0][0]*wt[0][0] + wt[0][1]*wt[0][1] + wt[0][2]*wt[0][2]);
dest[1] = sqrtf(wt[1][0]*wt[1][0] + wt[1][1]*wt[1][1] + wt[1][2]*wt[1][2]);
dest[2] = sqrtf(wt[2][0]*wt[2][0] + wt[2][1]*wt[2][1] + wt[2][2]*wt[2][2]);
}
void entityPositionSetLocalScale(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 scale
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
glm_vec3_copy(scale, pos->scale);
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(mgr, pos);
}
void entityPositionSetWorldScale(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 scale
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
if(pos->parentEntityId == ENTITY_ID_INVALID) {
glm_vec3_copy(scale, pos->scale);
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(mgr, pos);
return;
}
entityposition_t *parent = componentGetData(
mgr, pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsureWorld(mgr, parent);
const float_t (*pt)[4] = parent->worldTransform;
const float_t psx = sqrtf(
pt[0][0]*pt[0][0] + pt[0][1]*pt[0][1] + pt[0][2]*pt[0][2]
);
const float_t psy = sqrtf(
pt[1][0]*pt[1][0] + pt[1][1]*pt[1][1] + pt[1][2]*pt[1][2]
);
const float_t psz = sqrtf(
pt[2][0]*pt[2][0] + pt[2][1]*pt[2][1] + pt[2][2]*pt[2][2]
);
pos->scale[0] = psx > 0.0f ? scale[0] / psx : scale[0];
pos->scale[1] = psy > 0.0f ? scale[1] / psy : scale[1];
pos->scale[2] = psz > 0.0f ? scale[2] / psz : scale[2];
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(mgr, pos);
}
void entityPositionSetParent(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const entityid_t parentEntityId,
const componentid_t parentComponentId
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
// Remove from old parent's child list.
if(pos->parentEntityId != ENTITY_ID_INVALID) {
entityposition_t *oldParent = componentGetData(
mgr, pos->parentEntityId, pos->parentComponentId,
COMPONENT_TYPE_POSITION
);
for(uint8_t i = 0; i < oldParent->childCount; i++) {
if(
oldParent->childEntityIds[i] == entityId &&
oldParent->childComponentIds[i] == componentId
) {
oldParent->childCount--;
for(uint8_t j = i; j < oldParent->childCount; j++) {
oldParent->childEntityIds[j] = oldParent->childEntityIds[j + 1];
oldParent->childComponentIds[j] = oldParent->childComponentIds[j + 1];
}
break;
}
}
}
pos->parentEntityId = parentEntityId;
pos->parentComponentId = parentComponentId;
// Register with new parent.
if(parentEntityId != ENTITY_ID_INVALID) {
entityposition_t *parent = componentGetData(
mgr, parentEntityId, parentComponentId, COMPONENT_TYPE_POSITION
);
if(parent->childCount < ENTITY_POSITION_CHILDREN_MAX) {
parent->childEntityIds[parent->childCount] = entityId;
parent->childComponentIds[parent->childCount] = componentId;
parent->childCount++;
}
}
entityPositionMarkDirty(mgr, pos);
}
entityid_t entityPositionGetParent(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityposition_t *pos = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
return pos->parentEntityId;
}
entityposition_t *entityPositionGet(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_POSITION
);
}
void entityPositionRebuild(entitymanager_t *mgr, entityposition_t *pos) {
pos->flags = (
pos->flags |
ENTITY_POSITION_FLAG_ROTATION_DIRTY |
ENTITY_POSITION_FLAG_POSITION_DIRTY
) & ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(mgr, pos);
}
void entityPositionMarkDirty(entitymanager_t *mgr, entityposition_t *pos) {
if(pos->flags & ENTITY_POSITION_FLAG_WORLD_DIRTY) return;
pos->flags |= ENTITY_POSITION_FLAG_WORLD_DIRTY;
for(uint8_t i = 0; i < pos->childCount; i++) {
entityposition_t *child = componentGetData(
mgr, pos->childEntityIds[i], pos->childComponentIds[i],
COMPONENT_TYPE_POSITION
);
entityPositionMarkDirty(mgr, child);
}
}
void entityPositionDisposeDeep(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityposition_t *pos = entityPositionGet(mgr, entityId, componentId);
// Detach from parent so the parent's child list stays consistent.
if(pos->parentEntityId != ENTITY_ID_INVALID) {
entityPositionSetParent(
mgr, entityId, componentId, ENTITY_ID_INVALID, COMPONENT_ID_INVALID
);
}
// Copy the child list before disposing self (entityDispose invalidates
// pos).
uint8_t childCount = pos->childCount;
entityid_t childEntityIds[ENTITY_POSITION_CHILDREN_MAX];
componentid_t childComponentIds[ENTITY_POSITION_CHILDREN_MAX];
for(uint8_t i = 0; i < childCount; i++) {
childEntityIds[i] = pos->childEntityIds[i];
childComponentIds[i] = pos->childComponentIds[i];
// Sever child's parent link so it won't try to modify our disposed
// data.
entityposition_t *child = entityPositionGet(
mgr, childEntityIds[i], childComponentIds[i]
);
child->parentEntityId = ENTITY_ID_INVALID;
child->parentComponentId = COMPONENT_ID_INVALID;
}
entityDispose(mgr, entityId);
for(uint8_t i = 0; i < childCount; i++) {
entityPositionDisposeDeep(mgr, childEntityIds[i], childComponentIds[i]);
}
}
void entityPositionDecompose(entityposition_t *pos) {
// Translation: column 3
pos->position[0] = pos->localTransform[3][0];
pos->position[1] = pos->localTransform[3][1];
pos->position[2] = pos->localTransform[3][2];
// Scale: length of each basis column (xyz only)
pos->scale[0] = sqrtf(
pos->localTransform[0][0] * pos->localTransform[0][0] +
pos->localTransform[0][1] * pos->localTransform[0][1] +
pos->localTransform[0][2] * pos->localTransform[0][2]
);
pos->scale[1] = sqrtf(
pos->localTransform[1][0] * pos->localTransform[1][0] +
pos->localTransform[1][1] * pos->localTransform[1][1] +
pos->localTransform[1][2] * pos->localTransform[1][2]
);
pos->scale[2] = sqrtf(
pos->localTransform[2][0] * pos->localTransform[2][0] +
pos->localTransform[2][1] * pos->localTransform[2][1] +
pos->localTransform[2][2] * pos->localTransform[2][2]
);
// Normalize columns to isolate the rotation matrix (no mat4 needed).
const float_t invS0 = pos->scale[0] > 0.0f ? 1.0f / pos->scale[0] : 0.0f;
const float_t invS1 = pos->scale[1] > 0.0f ? 1.0f / pos->scale[1] : 0.0f;
const float_t invS2 = pos->scale[2] > 0.0f ? 1.0f / pos->scale[2] : 0.0f;
const float_t r00 = pos->localTransform[0][0] * invS0;
const float_t r01 = pos->localTransform[0][1] * invS0;
const float_t r02 = pos->localTransform[0][2] * invS0;
const float_t r10 = pos->localTransform[1][0] * invS1;
const float_t r11 = pos->localTransform[1][1] * invS1;
const float_t r20 = pos->localTransform[2][0] * invS2;
const float_t r21 = pos->localTransform[2][1] * invS2;
const float_t r22 = pos->localTransform[2][2] * invS2;
// Extract XYZ euler angles (R = Rx * Ry * Rz, column-major)
const float_t sinBeta = glm_clamp(r20, -1.0f, 1.0f);
pos->rotation[1] = asinf(sinBeta);
const float_t cosBeta = cosf(pos->rotation[1]);
if(fabsf(cosBeta) > 1e-6f) {
pos->rotation[0] = atan2f(-r21, r22);
pos->rotation[2] = atan2f(-r10, r00);
} else {
// Gimbal lock: pin Z to 0, recover X.
pos->rotation[2] = 0.0f;
pos->rotation[0] = (sinBeta > 0.0f)
? atan2f(r01, r11)
: -atan2f(r01, r11);
}
}
void entityPositionEnsurePRS(entityposition_t *pos) {
if(!(pos->flags & ENTITY_POSITION_FLAG_PRS_DIRTY)) return;
entityPositionDecompose(pos);
pos->flags &= ~ENTITY_POSITION_FLAG_PRS_DIRTY;
}
void entityPositionEnsureLocal(entityposition_t *pos) {
const uint8_t dirty = pos->flags & (
ENTITY_POSITION_FLAG_ROTATION_DIRTY | ENTITY_POSITION_FLAG_POSITION_DIRTY
);
if(!dirty) return;
if(dirty & ENTITY_POSITION_FLAG_ROTATION_DIRTY) {
// Rotation or scale changed: rebuild cols 0-2 analytically (XYZ euler).
const float_t c0 = cosf(pos->rotation[0]), s0 = sinf(pos->rotation[0]);
const float_t c1 = cosf(pos->rotation[1]), s1 = sinf(pos->rotation[1]);
const float_t c2 = cosf(pos->rotation[2]), s2 = sinf(pos->rotation[2]);
const float_t s0s1 = s0 * s1;
const float_t c0s1 = c0 * s1;
pos->localTransform[0][0] = c1 * c2 * pos->scale[0];
pos->localTransform[0][1] = (c0 * s2 + s0s1 * c2) * pos->scale[0];
pos->localTransform[0][2] = (s0 * s2 - c0s1 * c2) * pos->scale[0];
pos->localTransform[0][3] = 0.0f;
pos->localTransform[1][0] = -c1 * s2 * pos->scale[1];
pos->localTransform[1][1] = (c0 * c2 - s0s1 * s2) * pos->scale[1];
pos->localTransform[1][2] = (s0 * c2 + c0s1 * s2) * pos->scale[1];
pos->localTransform[1][3] = 0.0f;
pos->localTransform[2][0] = s1 * pos->scale[2];
pos->localTransform[2][1] = -s0 * c1 * pos->scale[2];
pos->localTransform[2][2] = c0 * c1 * pos->scale[2];
pos->localTransform[2][3] = 0.0f;
}
if(dirty & ENTITY_POSITION_FLAG_POSITION_DIRTY) {
// Only position changed: update column 3 only (no trig needed).
pos->localTransform[3][0] = pos->position[0];
pos->localTransform[3][1] = pos->position[1];
pos->localTransform[3][2] = pos->position[2];
pos->localTransform[3][3] = 1.0f;
}
pos->flags &= ~(
ENTITY_POSITION_FLAG_ROTATION_DIRTY | ENTITY_POSITION_FLAG_POSITION_DIRTY
);
}
void entityPositionEnsureWorld(entitymanager_t *mgr, entityposition_t *pos) {
if(!(pos->flags & ENTITY_POSITION_FLAG_WORLD_DIRTY)) return;
entityPositionEnsureLocal(pos);
if(pos->parentEntityId != ENTITY_ID_INVALID) {
// Parented: world = parent.world x local. worldTransform must be
// written because children (and this node's getters) read it.
entityposition_t *parent = componentGetData(
mgr, pos->parentEntityId, pos->parentComponentId,
COMPONENT_TYPE_POSITION
);
entityPositionEnsureWorld(mgr, parent);
glm_mat4_mul(
parent->worldTransform, pos->localTransform, pos->worldTransform
);
} else if(pos->childCount > 0) {
// Parentless root with children: children need a valid worldTransform
// to multiply against, but world == local, so just copy.
glm_mat4_copy(pos->localTransform, pos->worldTransform);
}
// Parentless leaf: world == local. Getters read localTransform directly;
// no copy needed.
pos->flags &= ~ENTITY_POSITION_FLAG_WORLD_DIRTY;
}
@@ -1,460 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
#include "error/error.h"
/** Maximum number of child position components this node can track. */
#define ENTITY_POSITION_CHILDREN_MAX 8
/**
* PRS cache is stale. localTransform was written directly (e.g. lookAt) and
* position/rotation/scale need to be decomposed before they can be read.
*/
#define ENTITY_POSITION_FLAG_PRS_DIRTY (1 << 0)
/**
* Columns 0-2 of localTransform are stale. Rotation or scale changed; the
* basis vectors need to be rebuilt analytically before the matrix can be used.
* Does not imply column 3 (translation) is stale.
*/
#define ENTITY_POSITION_FLAG_ROTATION_DIRTY (1 << 1)
/**
* Column 3 of localTransform is stale. Position changed; only the
* translation column needs to be written. Does not imply columns 0-2 are
* stale.
*/
#define ENTITY_POSITION_FLAG_POSITION_DIRTY (1 << 2)
/**
* worldTransform is stale. Either the local matrix changed or an ancestor
* moved; worldTransform must be recomputed before world data can be read.
*/
#define ENTITY_POSITION_FLAG_WORLD_DIRTY (1 << 3)
typedef struct {
/*
* Hot fields - flag checks, parent/child traversal (markDirty, ensureWorld)
* only touch these. Kept at the front so they share the first cache line.
*/
/** ENTITY_POSITION_FLAG_* bitmask; describes which caches are stale. */
uint8_t flags;
/** Entity ID of the parent node, or ENTITY_ID_INVALID if none. */
entityid_t parentEntityId;
/** Component ID of the parent position, or COMPONENT_ID_INVALID if none. */
componentid_t parentComponentId;
/** Number of currently registered children. */
uint8_t childCount;
/** Entity IDs of child nodes. */
entityid_t childEntityIds[ENTITY_POSITION_CHILDREN_MAX];
/** Component IDs of child position components. */
componentid_t childComponentIds[ENTITY_POSITION_CHILDREN_MAX];
/*
* Warm fields - read/written by PRS getters/setters.
* Accessed more often than the matrices but less often than flags.
*/
/** Cached local position (XYZ). Stale when PRS_DIRTY is set. */
vec3 position;
/** Cached local rotation (XYZ euler, radians). Stale when PRS_DIRTY. */
vec3 rotation;
/** Cached local scale (XYZ). Stale when PRS_DIRTY is set. */
vec3 scale;
/*
* Cold fields - only touched when actually rebuilding transforms.
*/
/** Local transform matrix, rebuilt lazily from position/rotation/scale. */
mat4 localTransform;
/** World transform matrix, recomputed lazily from the parent chain. */
mat4 worldTransform;
} entityposition_t;
/**
* Initializes the entity position component, setting identity transforms and
* zeroing all parent/child state.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
*/
void entityPositionInit(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Positions and orients the entity at eye, facing target. Stores this as
* the entity's normal world-space placement (consistent with every other
* setter), not as a view matrix -- invert entityPositionGetTransform()'s
* result to get a view matrix for rendering.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param eye The eye/camera position.
* @param target The target point to look at.
* @param up The up vector.
*/
void entityPositionLookAt(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 eye,
vec3 target,
vec3 up
);
/**
* Gets the world-space transform matrix, recomputing it lazily if dirty.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param dest Destination matrix.
*/
void entityPositionGetTransform(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
mat4 dest
);
/**
* Gets the local transform matrix (does not include parent transforms).
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param dest Destination matrix.
*/
void entityPositionGetLocalTransform(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
mat4 dest
);
/**
* Gets the cached local position (XYZ). Decomposes localTransform into PRS
* first if ENTITY_POSITION_FLAG_PRS_DIRTY is set; never triggers a matrix
* rebuild or world-transform update.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param dest Destination vector.
*/
void entityPositionGetLocalPosition(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
);
/**
* Gets the world-space position. For parentless entities this is the same as
* the local position.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param dest Destination vector.
*/
void entityPositionGetWorldPosition(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
);
/**
* Sets the world-space position. For parentless entities this is equivalent
* to entityPositionSetLocalPosition. For parented entities the position is
* converted to local space via the inverted parent world transform.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param position The desired world-space position.
*/
void entityPositionSetWorldPosition(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 position
);
/**
* Sets the local position, marks localTransform and worldTransform (self +
* descendants) dirty.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param position The new local position.
*/
void entityPositionSetLocalPosition(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 position
);
/**
* Gets the cached local euler rotation (XYZ, radians). Decomposes
* localTransform first if ENTITY_POSITION_FLAG_PRS_DIRTY is set.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param dest Destination vector.
*/
void entityPositionGetLocalRotation(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
);
/**
* Gets the world-space euler rotation (XYZ, radians) by decomposing the
* world transform. For parentless entities this is the same as local
* rotation.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param dest Destination vector.
*/
void entityPositionGetWorldRotation(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
);
/**
* Sets the local euler rotation (XYZ, radians) and marks transforms dirty.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param rotation The new local rotation.
*/
void entityPositionSetLocalRotation(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 rotation
);
/**
* Sets the world-space euler rotation (XYZ, radians). For parentless
* entities this is equivalent to entityPositionSetLocalRotation. For
* parented entities the rotation is converted to local space by removing
* the parent world rotation.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param rotation The desired world-space euler rotation.
*/
void entityPositionSetWorldRotation(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 rotation
);
/**
* Gets the cached local scale. Decomposes localTransform first if
* ENTITY_POSITION_FLAG_PRS_DIRTY is set.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param dest Destination vector.
*/
void entityPositionGetLocalScale(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
);
/**
* Gets the world-space scale by extracting column lengths from the world
* transform. For parentless entities this is the same as local scale.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param dest Destination vector.
*/
void entityPositionGetWorldScale(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
);
/**
* Sets the local scale and marks transforms dirty.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param scale The new local scale.
*/
void entityPositionSetLocalScale(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 scale
);
/**
* Sets the world-space scale. For parentless entities this is equivalent to
* entityPositionSetLocalScale. For parented entities the scale is converted
* to local space by dividing by the parent world scale (assumes no shear).
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @param scale The desired world-space scale.
*/
void entityPositionSetWorldScale(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 scale
);
/**
* Sets the parent of this entity's position component.
* Pass ENTITY_ID_INVALID / COMPONENT_ID_INVALID to detach from any parent.
*
* @param mgr The entity manager that owns both entities.
* @param entityId The child entity ID.
* @param componentId The child component ID.
* @param parentEntityId The parent entity ID.
* @param parentComponentId The parent component ID.
*/
void entityPositionSetParent(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const entityid_t parentEntityId,
const componentid_t parentComponentId
);
/**
* Gets the entity ID of this position component's parent.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @return The parent entity ID, or ENTITY_ID_INVALID if unparented.
*/
entityid_t entityPositionGetParent(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Returns a direct pointer to the entity position component data.
* After modifying localTransform directly, call entityPositionMarkDirty() to
* set ENTITY_POSITION_FLAG_WORLD_DIRTY on self and descendants. After
* modifying PRS directly, call entityPositionRebuild() instead.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity ID.
* @param componentId The component ID.
* @return Pointer to the component data.
*/
entityposition_t *entityPositionGet(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Signals that the PRS cache was modified externally. Sets both
* ENTITY_POSITION_FLAG_ROTATION_DIRTY and ENTITY_POSITION_FLAG_POSITION_DIRTY
* so all of localTransform is rebuilt lazily on the next read, clears
* ENTITY_POSITION_FLAG_PRS_DIRTY, propagates ENTITY_POSITION_FLAG_WORLD_DIRTY
* to self and all descendants.
*
* @param mgr The entity manager that owns pos and its descendants.
* @param pos The position component whose PRS was modified.
*/
void entityPositionRebuild(entitymanager_t *mgr, entityposition_t *pos);
/**
* Sets ENTITY_POSITION_FLAG_WORLD_DIRTY on this node and all descendants,
* indicating that worldTransform must be recomputed before it is read.
* Call this after modifying localTransform directly.
*
* @param mgr The entity manager that owns pos and its descendants.
* @param pos The position component to mark dirty.
*/
void entityPositionMarkDirty(entitymanager_t *mgr, entityposition_t *pos);
/**
* Disposes this entity and all of its position-component descendants
* recursively. Detaches from any parent before destroying.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The root entity ID.
* @param componentId The root position component ID.
*/
void entityPositionDisposeDeep(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Decomposes the local transform matrix back into the position, rotation
* (XYZ euler, radians), and scale cache fields.
*
* @param pos The position component to decompose.
*/
void entityPositionDecompose(entityposition_t *pos);
/**
* Internal. Decomposes localTransform into the PRS cache if
* ENTITY_POSITION_FLAG_PRS_DIRTY is set.
*
* @param pos The position component to update.
*/
void entityPositionEnsurePRS(entityposition_t *pos);
/**
* Internal. Rebuilds localTransform from the PRS cache, touching only the
* columns flagged as stale (ROTATION_DIRTY and/or POSITION_DIRTY).
*
* @param pos The position component to update.
*/
void entityPositionEnsureLocal(entityposition_t *pos);
/**
* Internal. Recomputes worldTransform from the parent chain if
* ENTITY_POSITION_FLAG_WORLD_DIRTY is set.
*
* @param mgr The entity manager that owns pos and its ancestors.
* @param pos The position component to update.
*/
void entityPositionEnsureWorld(entitymanager_t *mgr, entityposition_t *pos);
@@ -1,192 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entityrenderable.h"
#include "entity/entitymanager.h"
#include "display/shader/shadermaterial.h"
#include "display/shader/shaderunlit.h"
#include "display/display.h"
#include "display/mesh/cube.h"
#include "util/memory.h"
#include "assert/assert.h"
void entityRenderableInit(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityrenderable_t *r = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
memoryZero(r, sizeof(entityrenderable_t));
r->type = ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL;
r->data.material.shaderType = SHADER_LIST_SHADER_UNLIT;
r->data.material.material.unlit.color = COLOR_WHITE;
r->data.material.meshes[0] = &CUBE_MESH_SIMPLE;
r->data.material.meshOffsets[0] = 0;
r->data.material.meshCounts[0] = -1;
r->data.material.meshCount = 1;
r->data.material.state.flags = DISPLAY_STATE_FLAG_DEPTH_TEST;
}
void entityRenderableDispose(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
}
void entityRenderableSetType(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const entityrenderabletype_t type
) {
entityrenderable_t *r = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
r->type = type;
}
void entityRenderableSetPriority(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const int8_t priority
) {
entityrenderable_t *r = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
r->priority = priority;
}
void entityRenderableSetColor(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const color_t color
) {
entityrenderable_t *r = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
assertTrue(
r->type == ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL,
"Renderable must be ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL to set color"
);
r->data.material.material.unlit.color = color;
}
void entityRenderableSetMesh(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const uint8_t slot,
mesh_t *mesh
) {
assertNotNull(mesh, "Mesh cannot be null");
assertTrue(slot < ENTITY_RENDERABLE_MESHES_MAX, "Mesh slot out of bounds");
entityrenderable_t *r = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
assertTrue(
r->type == ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL,
"Renderable must be ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL to set a mesh"
);
r->data.material.meshes[slot] = mesh;
r->data.material.meshOffsets[slot] = 0;
r->data.material.meshCounts[slot] = -1;
if(slot >= r->data.material.meshCount) {
r->data.material.meshCount = slot + 1;
}
}
void entityRenderableSetDraw(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
errorret_t (*draw)(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
void *user
),
void *user
) {
assertNotNull(draw, "Draw callback cannot be null");
entityrenderable_t *r = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
r->type = ENTITY_RENDERABLE_TYPE_CUSTOM;
r->data.custom.draw = draw;
r->data.custom.drawUser = user;
}
errorret_t entityRenderableDraw(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityrenderable_t *r = componentGetData(
mgr, entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
switch(r->type) {
case ENTITY_RENDERABLE_TYPE_SPRITEBATCH:
return entityRenderableDrawSpritebatch(&r->data.spritebatch);
case ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL:
return entityRenderableDrawMaterial(&r->data.material);
case ENTITY_RENDERABLE_TYPE_CUSTOM:
return entityRenderableDrawCustom(
mgr, entityId, componentId, &r->data.custom
);
default:
assertUnreachable("Invalid renderable type");
}
}
errorret_t entityRenderableDrawSpritebatch(
const entityrenderablespritebatch_t *sb
) {
if(sb->spriteCount == 0) errorOk();
errorChain(displaySetState((displaystate_t){
.flags = DISPLAY_STATE_FLAG_BLEND
}));
spriteBatchClear();
shadermaterial_t mat;
memoryZero(&mat, sizeof(shadermaterial_t));
mat.unlit.texture = sb->texture;
mat.unlit.color = COLOR_WHITE;
errorChain(spriteBatchBuffer(
sb->sprites, sb->spriteCount,
SHADER_LIST_DEFS[SHADER_LIST_SHADER_UNLIT].shader, mat
));
return spriteBatchFlush();
}
errorret_t entityRenderableDrawMaterial(const entityrenderablematerial_t *m) {
errorChain(displaySetState(m->state));
shader_t *shader = SHADER_LIST_DEFS[m->shaderType].shader;
assertNotNull(shader, "Shader cannot be null for material type");
errorChain(shaderBind(shader));
errorChain(shaderSetMaterial(shader, &m->material));
for(uint8_t i = 0; i < m->meshCount; i++) {
errorChain(meshDraw(m->meshes[i], m->meshOffsets[i], m->meshCounts[i]));
}
errorOk();
}
errorret_t entityRenderableDrawCustom(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const entityrenderablecustom_t *custom
) {
return custom->draw(mgr, entityId, componentId, custom->drawUser);
}
@@ -1,234 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
#include "display/mesh/mesh.h"
#include "display/shader/shadermaterial.h"
#include "display/spritebatch/spritebatch.h"
#include "display/displaystate.h"
#include "error/error.h"
#define ENTITY_RENDERABLE_SPRITEBATCH_SPRITES_MAX 64
#define ENTITY_RENDERABLE_MESHES_MAX 8
typedef enum {
ENTITY_RENDERABLE_TYPE_CUSTOM = 0,
ENTITY_RENDERABLE_TYPE_SPRITEBATCH,
ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL,
} entityrenderabletype_t;
typedef struct {
spritebatchsprite_t sprites[ENTITY_RENDERABLE_SPRITEBATCH_SPRITES_MAX];
uint32_t spriteCount;
texture_t *texture;
} entityrenderablespritebatch_t;
typedef struct {
mesh_t *meshes[ENTITY_RENDERABLE_MESHES_MAX];
int32_t meshOffsets[ENTITY_RENDERABLE_MESHES_MAX];
int32_t meshCounts[ENTITY_RENDERABLE_MESHES_MAX];
uint8_t meshCount;
shaderlistshader_t shaderType;
shadermaterial_t material;
displaystate_t state;
} entityrenderablematerial_t;
typedef struct {
errorret_t (*draw)(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
void *user
);
void *drawUser;
} entityrenderablecustom_t;
typedef union entityrenderabledata_u {
entityrenderablespritebatch_t spritebatch;
entityrenderablematerial_t material;
entityrenderablecustom_t custom;
} entityrenderabledata_t;
typedef struct {
entityrenderabletype_t type;
entityrenderabledata_t data;
/**
* Render priority. 0 = auto (derived from type/flags). Higher values
* render later (on top of lower values). Range: [-128..127] with 0 auto.
*/
int8_t priority;
} entityrenderable_t;
/**
* Initializes the entity renderable component. Defaults to
* ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL with the unlit shader, a white
* cube, and depth-test enabled.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity to initialize the component for.
* @param componentId The renderable component of the entity.
*/
void entityRenderableInit(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Disposes the entity renderable component.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity to dispose the component for.
* @param componentId The renderable component of the entity.
*/
void entityRenderableDispose(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Sets the rendering type for the renderable component. Resets
* type-specific data to zero.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity to configure.
* @param componentId The renderable component.
* @param type The rendering type to use.
*/
void entityRenderableSetType(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const entityrenderabletype_t type
);
/**
* Sets the render priority. 0 = auto (derived from type/flags). Higher
* values render later (on top). Use non-zero to force ordering.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity to configure.
* @param componentId The renderable component.
* @param priority The priority value, or 0 for auto.
*/
void entityRenderableSetPriority(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const int8_t priority
);
/**
* Sets the unlit material color. Only meaningful when the renderable is
* (or defaults to) ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL -- asserts
* otherwise.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity to configure.
* @param componentId The renderable component.
* @param color The color to tint the material with.
*/
void entityRenderableSetColor(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const color_t color
);
/**
* Sets one of the material renderable's meshes, drawn in full (no offset/
* count override). Only meaningful when the renderable is (or defaults
* to) ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL -- asserts otherwise.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity to configure.
* @param componentId The renderable component.
* @param slot Index into the material's meshes array (0 to
* ENTITY_RENDERABLE_MESHES_MAX - 1).
* @param mesh The mesh to draw in that slot.
*/
void entityRenderableSetMesh(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const uint8_t slot,
mesh_t *mesh
);
/**
* Sets the draw callback, switching the type to
* ENTITY_RENDERABLE_TYPE_CUSTOM.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity to configure.
* @param componentId The renderable component of the entity.
* @param draw The draw callback to assign.
* @param user Userdata passed to the callback.
*/
void entityRenderableSetDraw(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
errorret_t (*draw)(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
void *user
),
void *user
);
/**
* Draws the entity using its renderable component data.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity to draw.
* @param componentId The renderable component of the entity.
* @return Any error state that happened.
*/
errorret_t entityRenderableDraw(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
);
/**
* Internal. Draws a spritebatch-type renderable.
*
* @param sb The spritebatch data to draw.
* @return Error state.
*/
errorret_t entityRenderableDrawSpritebatch(
const entityrenderablespritebatch_t *sb
);
/**
* Internal. Draws a shader-material-type renderable.
*
* @param m The material data to draw.
* @return Error state.
*/
errorret_t entityRenderableDrawMaterial(const entityrenderablematerial_t *m);
/**
* Internal. Invokes a custom-type renderable's draw callback.
*
* @param mgr The entity manager that owns the entity.
* @param entityId The entity being drawn.
* @param componentId The renderable component of the entity.
* @param custom The custom draw data.
* @return Error state.
*/
errorret_t entityRenderableDrawCustom(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const entityrenderablecustom_t *custom
);
@@ -1,135 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entityphysics.h"
#include "entity/entitymanager.h"
#include "util/memory.h"
void entityPhysicsInit(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityphysics_t *phys = entityPhysicsGet(mgr, entityId, componentId);
memoryZero(phys, sizeof(entityphysics_t));
// Default to cube
phys->type = PHYSICS_BODY_DYNAMIC;
phys->shape.type = PHYSICS_SHAPE_CUBE;
phys->shape.data.cube.halfExtents[0] = 0.5f;
phys->shape.data.cube.halfExtents[1] = 0.5f;
phys->shape.data.cube.halfExtents[2] = 0.5f;
phys->gravityScale = 1.0f;
phys->onGround = false;
phys->collideMask = 0x1;
}
entityphysics_t *entityPhysicsGet(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(mgr, entityId, componentId, COMPONENT_TYPE_PHYSICS);
}
void entityPhysicsSetShape(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const physicsshape_t shape
) {
entityphysics_t *phys = entityPhysicsGet(mgr, entityId, componentId);
phys->shape = shape;
}
physicsshape_t entityPhysicsGetShape(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityphysics_t *phys = entityPhysicsGet(mgr, entityId, componentId);
return phys->shape;
}
void entityPhysicsGetVelocity(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
) {
entityphysics_t *phys = entityPhysicsGet(mgr, entityId, componentId);
glm_vec3_copy(phys->velocity, dest);
}
void entityPhysicsSetVelocity(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 velocity
) {
entityphysics_t *phys = entityPhysicsGet(mgr, entityId, componentId);
glm_vec3_copy(velocity, phys->velocity);
}
void entityPhysicsApplyImpulse(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
vec3 impulse
) {
entityphysics_t *phys = entityPhysicsGet(mgr, entityId, componentId);
if(phys->type == PHYSICS_BODY_STATIC) return;
glm_vec3_add(phys->velocity, impulse, phys->velocity);
}
bool_t entityPhysicsIsOnGround(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityphysics_t *phys = entityPhysicsGet(mgr, entityId, componentId);
return phys->onGround;
}
void entityPhysicsSetBodyType(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const physicsbodytype_t type
) {
entityphysics_t *phys = entityPhysicsGet(mgr, entityId, componentId);
phys->type = type;
}
physicsbodytype_t entityPhysicsGetBodyType(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityphysics_t *phys = entityPhysicsGet(mgr, entityId, componentId);
return phys->type;
}
void entityPhysicsSetCollideMask(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId,
const uint32_t mask
) {
entityphysics_t *phys = entityPhysicsGet(mgr, entityId, componentId);
phys->collideMask = mask;
}
uint32_t entityPhysicsGetCollideMask(
entitymanager_t *mgr,
const entityid_t entityId,
const componentid_t componentId
) {
entityphysics_t *phys = entityPhysicsGet(mgr, entityId, componentId);
return phys->collideMask;
}

Some files were not shown because too many files have changed in this diff Show More