54 Commits

Author SHA1 Message Date
YourWishes b639bc6c4f Reimplement the archived UI widget stack on the new element-tree system
The old widget system (archive/dusk/ui/) depended on infrastructure this
rewrite deleted -- a static X-macro element list, a 9-slice UI_FRAME, and
a global gamepad/keyboard focus stack -- so everything below is rebuilt
on top of the new native uielement_t pool + parent/child tree instead,
gamepad/keyboard-only (no mouse support exists in the input system).

New JS widgets (assets/scripts/), all pure composites of Label/Rectangle
following the Button.js pattern: Checkbox, Tab, Slider, Dropdown. Slider/
Dropdown expose a directionInput(dx, dy) hook so a menu can hand them
LEFT/RIGHT before falling back to cursor movement.

New Menu.js replaces the old global uifocus_t stack: a small push/pop
stack of Menu instances where only the topmost consumes CANCEL/ACCEPT/
direction input each tick (needed for nested modals -- a Settings
sub-page menu plus a "discard changes?" Confirm can be open at once).
Held-direction repeat timing matches the old 0.5s delay / 0.1s repeat.

New overlay composites (added via a new UI.addOverlay()/UI.removeOverlay(),
always drawn/updated after normal roots): FpsCounter, ConsoleOverlay
(one Label per console history line, driven directly rather than via
add() since History (16) exceeds the 8-children-per-element cap), Crop
(letterbox/pillarbox bars), and Fullbox (a reusable tweened full-screen
fade covering both the old fullbox and transition effects -- reuses
shared instances rather than allocate-and-dispose, since disposing an
element from inside its own render() callback risks the same JerryScript
refcount corruption hit earlier in this rewrite).

New Confirm.js (Yes/No dialog) and Settings.js (+ SettingsGeneral/
SettingsInput sub-pages) built on Menu. Display/Audio settings pages are
intentionally not ported -- neither had a real backing engine system
even in the old code. Frame is a flat Rectangle for now, not real 9-slice
(a genuinely bigger native lift, deliberately deferred).

Small native binding additions needed by the above, each with its own
unit test: Time.renderDelta, Console.lineCount/getLine/visible/
consumeDirty, a new Screen module, a new Locale module, Input.deadzone,
a new Save module, and Label.color (was missing entirely). Also fixes
a real gap from the UI.addOverlay() work: uiElementDispose() wasn't
removing disposed elements from the new overlay root array, which would
have left dangling ids behind.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 09:05:11 -05:00
YourWishes 7ee04c78cd Rebuild UI as a scriptable element tree, archive the old system
The old UI system (X-macro static element list, hand-authored C
screens/widgets/focus stack) is archived under archive/ rather than
deleted, since it's a useful reference during the rewrite.

New native UI element pool (src/dusk/ui): a flat UI_ELEMENTS[128] pool
of tagged-union elements (Label, Rectangle, Scripted), a real
persistent parent/child tree (children[8] per element, cycle- and
capacity-checked uiElementSetParent), always-fresh worldX/worldY
(cheap enough to recompute on every read, no dirty-flag cache needed),
and cascading dispose. Rendering stays manual/immediate: a scripted
element with no render() override auto-renders its children by
default, but overriding render() takes full control (an override must
call renderChildren() itself to opt back in) -- this is deliberately
preserved end to end via a render()-shadow trampoline so overriding
render() always keeps working the same way regardless of how a node
is reached.

New scripting layer (src/dusk/script/module/ui): UIElement/Label/
Rectangle JS classes (Label/Rectangle share UIElement's prototype via
manual chaining, not JS `extends`), exposing x/y/worldX/worldY/parent/
add()/remove()/render()/renderChildren()/dispose(). UI.add()/
UI.remove() manage top-level render roots, mutually exclusive with
being someone's child.

Also: Scene gains a lateUpdate() hook (called once per frame after
every other update, for things like camera-follow that need to react
to where everything else ended up); several duskrpg call sites
(cutscene items, entityinteractable, entityplayer) that depended on
the now-archived RPG textbox are stubbed to console output instead of
a dialogue box, pending the new UI reaching that far.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 11:13:23 -05:00
YourWishes 7b58addf7e Prepping UI overhaul 2026-08-11 23:33:29 -05:00
YourWishes ae52be591b Add Input/InputBind/InputButton JS bindings, move default binds to JS
Adds a new script module exposing Input.bind/value/lastValue/isDown/
wasDown/pressed/released, InputBind.* (the inputbind_t action enum),
and InputButton.* (every named button in the compiled platform's
INPUT_BUTTON_DATA table, e.g. InputButton.SELECT on PSP).

Renames the PLATFORM global to Platform.current for consistency with
Time/Console/Input.

Uppercases every INPUT_BUTTON_DATA .name across inputlinux.c/
inputpsp.c/inputdolphin.c to match the InputButton.* JS constants
(inputButtonGetByName was already case-insensitive, so this doesn't
change matching behavior).

Moves the default key/button-to-action bindings out of
src/duskrpg/input/inputbindmap.h (deleted) and into
assets/scripts/input.js, branching on Platform.current instead of the
old per-platform #ifdefs. Wired in via require('./input.js') from
init.js.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-11 16:03:32 -05:00
YourWishes 93ab7690ba Add asset/event test coverage, fix caching-breaking eventSubscribe bug
Adds missing test coverage for the asset pipeline's binary loaders
(mesh/model/texture), assetfile.c, and assetbatch.c, plus a new
test/event suite for the shared event primitive.

Found and fixed two real bugs while writing this:
- assetFileRead's NULL-buffer skip path double-counted file->position,
  which could trip stb_image's EOF check early on images that skip
  bytes mid-decode.
- eventSubscribe/eventUnsubscribe matched only on the callback pointer
  instead of the (callback, user) pair the docs already promised, so
  two independent consumers of the same cached asset (e.g. two
  assetbatch_t's) would abort. Covered by dedicated caching tests in
  both test_assetbatch.c and test_assetmodelloader.c.

Also drops test_overworldscene.c, broken by the in-progress
overworldscene.js/init.js export-contract rewrite.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-11 14:34:51 -05:00
YourWishes 68c3f88181 Build on PSP 2026-08-11 13:11:22 -05:00
YourWishes 830864aa8a Gating network behind compile flag 2026-08-11 12:52:38 -05:00
YourWishes 5f34cb34b2 Add a thin declarative API for defining script methods/properties
scriptvalue.h/.c holds the scriptvalue_t tagged-union type and its
JS<->C decode/encode helpers; scriptdef.h/.c holds the declarative
scriptfuncdef_t/scriptpropdef_t definitions, the binding registry,
and the JerryScript trampolines. Lets a module declare its JS-facing
methods/properties/globals as typed data instead of hand-writing
argument-checking boilerplate per method. Framework only for now --
no existing module has been migrated onto it yet.
2026-08-03 19:36:08 -05:00
YourWishes b9d2fe60fd Split overworldscene.js's player/plane/camera into their own classes
Extracts Player (extends Entity), TestPlane, and PlayerCamera into
their own files; the camera now tracks the player's live position
at a fixed offset instead of orbiting the world origin over time.
Updates test_overworldscene.c to match the new entity order and to
build an in-memory zip fixture, since overworldscene.js now
require()s these sibling files and require() always resolves
through ASSET.zip.
2026-08-03 19:35:54 -05:00
YourWishes 06bc4fcd55 .MD remove 2026-08-03 14:35:30 -05:00
YourWishes 42cb84b610 Extract player entity setup into a Player class
Moves the capsule/physics/renderable/PLAYER setup out of
overworldscene.js's inline init() into assets/scripts/Player.js so the
scene module just instantiates it.
2026-08-02 21:06:31 -05:00
YourWishes f8607d114c Add UDP socket client/server multiplayer protocol
Implements the multiplayer transport layer from ROADMAP.md: UUID-based
client identity, a reliable-packet channel over UDP, handshake/ack/
ping/disconnect/player-joined/player-left/player-state packet types,
and split online (networked) vs offline (in-process singleplayer)
server modes wired into the engine's update/dispose loop.
2026-08-02 21:06:23 -05:00
YourWishes 56230dd340 Fix ref-count underflow, PSP timezone units, thread restart race, color codegen
- util/ref.c: refUnlock's assert(count >= 0) on an unsigned count was
  tautological, so a double-unlock silently underflowed to UINT32_MAX
  instead of asserting. Now asserts count > 0 before decrementing.
- duskpsp/time/timepsp.c: timeGetRealTimeZonePSP returned hours while
  every other platform (and timeepoch.c's math) expects seconds.
- thread.c: threadHandler reset threadId outside the mutex, after
  signaling STOPPED, letting a caller's immediate threadStart() race
  threadStartRequest()'s "thread id not 0" assert. threadId is now
  reset inside the same locked section.
- tools/color.py: whole-number CSV channels (0, 1) produced invalid C
  float literals (0f, 1f) for the generated COLOR_*_3F/_4F macros.
  Route through float() so they always stringify with a decimal point.

Also adds .claude/code-check.md: a full review pass over every
subsystem in src/dusk/, with the above (plus several other findings
not yet acted on) written up in detail.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 15:02:17 -05:00
YourWishes df9fdf26c8 Refresh STATUS.md/ROADMAP.md for the Scene.set()/UI caching/CI work
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 13:53:06 -05:00
YourWishes 8f8fa8f8d1 Scene.set() JS lifecycle, UI sprite caching, emulator test scripts
- Add Scene.set(module) so JerryScript can switch scenes via
  require()'d {init, update, dispose} modules; wire it into
  engineUpdate() and rework overworldscene.js/init.js to the new shape.
- Fix scriptManagerExecFile() never pushing its own file's directory
  onto the require() dir stack, breaking relative require() calls from
  a top-level entry script (e.g. init.js -> ./overworldscene.js).
- Cache sprite geometry across frames for uislider/uitab/uiframe
  (dialogs/textbox/settings) and give uitextbox a per-page glyph cache
  instead of one spriteBatchBuffer call per visible character. uiconsole
  drops its alloc/free vertex buffer for a fixed-size one. uifps skips
  rebuilding its label when the text hasn't changed.
- Add PSP_OPTIMIZATION_PLAN.md and a handful of UI/spritebatch unit
  tests covering the new caching logic.
- Add Dolphin/PPSSPP emulator smoke-test scripts (+ Docker variants and
  CI jobs) for GameCube/Wii/PSP.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 13:21:57 -05:00
YourWishes 07f98c119a Script stuff 2026-07-31 09:40:53 -05:00
YourWishes d49194fc4d Embed font into binary 2026-07-30 15:18:07 -05:00
YourWishes e61914bad4 Finish JerryScript Entity/Scene wiring; remove JSON serialize/deserialize
Register Entity, the generic Component wrapper, and Scene as JerryScript
classes (modulelist.c ties them together, plus their .d.ts stubs), so
scenes/entities can be built from script going forward instead of the
JSON scene format.

With scripting now the intended authoring path, drop the JSON
serialize/deserialize machinery entirely: componentdefinition_t's
serialize/deserialize callbacks, every component's *Serialize/
*Deserialize function, entitySerialize/entityDeserialize,
sceneSerialize/sceneDeserialize, and the "prefabs/<name>.json"/
"scenes/<name>.json" asset fallback in entityPrefabResolveAndApply/
scenePrefabResolveAndApply (C-coded prefabs only now). physicsshape.c
and its test are removed outright since they only existed for this.
game.c's test scene now comes from the existing overworldSceneCreate()
C builder instead of loading the now-deleted assets/scenes/test.json.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 11:19:08 -05:00
YourWishes 015d90519f WIP: start JerryScript integration (core engine + Component wrapper)
Ports the core scripting engine (scriptmanager, scriptproto, modulebase,
moduleplatform) and a generic Component JS wrapper from the old we-ball
branch, adapted to the current entitymanager_t/multi-scene architecture.

Not yet buildable: moduleentity.c, modulescene, modulelist.h/.c, and the
CMakeLists.txt for the new module subdirectories are still missing, and
engine.c isn't wired up yet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 09:06:34 -05:00
YourWishes 7b4f0abfb8 Cutscene progress 2026-07-24 15:57:13 -05:00
YourWishes 0667a44e14 Restored cutscene code 2026-07-23 09:15:47 -05:00
YourWishes 0852b8463b ANIM 2026-07-21 18:55:23 -05:00
YourWishes 1436fda858 Some animation work 2026-07-21 09:29:14 -05:00
YourWishes 0826908068 First round of animation improvements 2026-07-20 16:07:38 -05:00
YourWishes 7ceb9e571d Scene prefabs 2026-07-20 15:11:38 -05:00
YourWishes 38c2f6b6f9 Add prefab support 2026-07-20 14:44:14 -05:00
YourWishes b9f06fef7a Add area and flag on physics 2026-07-20 12:31:14 -05:00
YourWishes 373f1c1010 test 2026-07-19 22:12:53 -05:00
YourWishes e80d693d85 More ui optimization 2026-07-19 17:39:38 -05:00
YourWishes ef60ddf6a8 UI Optim 2026-07-19 17:31:29 -05:00
YourWishes de0ff2e263 Fix collide issue on PSP 2026-07-19 14:51:57 -05:00
YourWishes 13a435e9c1 Test 2026-07-19 14:05:46 -05:00
YourWishes 725338cd5a Game code start 2026-07-19 11:49:13 -05:00
YourWishes acd14f46a8 Optimize PSP slightly 2026-07-19 11:15:22 -05:00
YourWishes ef78f023ed yeah whatever 2026-07-18 23:07:45 -05:00
YourWishes 85b6109792 Fixed save crash 2026-07-18 21:17:24 -05:00
YourWishes 6c5738c863 Testing physics 2026-07-18 20:53:22 -05:00
YourWishes 1174e471f6 Time fixes 2026-07-18 20:31:42 -05:00
YourWishes a618ff46fe Physics 2026-07-18 20:01:44 -05:00
YourWishes 1fa5cd316e Restore ECS 2026-07-18 19:05:51 -05:00
YourWishes 11e5d37563 Cleanup more. 2026-07-18 17:38:25 -05:00
YourWishes 9f86c20129 remove rpg 2026-07-18 17:15:45 -05:00
YourWishes 8fb1c9fb42 physics and rendering fixes 2026-07-17 21:06:21 -05:00
YourWishes 5f08337726 physics stuff 2026-07-17 19:07:32 -05:00
YourWishes 0bc80d5df3 Roadmap and physics 2026-07-17 13:09:58 -05:00
YourWishes 2432443ea6 Cleaned settings a bit 2026-07-17 09:11:19 -05:00
YourWishes fa138971e7 Console optimized slightly for rendering 2026-07-16 23:52:47 -05:00
YourWishes d7982599d1 Simplified PSP network 2026-07-16 22:55:47 -05:00
YourWishes f16c80aa0f Fixed PSP rendering 2026-07-16 21:20:49 -05:00
YourWishes ef5adf8274 PSP Network connect 2026-07-16 20:09:39 -05:00
YourWishes 2ffc65b1b1 Network conn and disconn 2026-07-16 19:32:44 -05:00
YourWishes d4a17bd98d Net 2026-07-16 19:08:32 -05:00
YourWishes dcf5f434c5 Remove vita for now 2026-07-16 15:50:19 -05:00
YourWishes 78cd973a33 Remove story and battle stuff 2026-07-16 15:37:55 -05:00
682 changed files with 39461 additions and 7295 deletions
+71
View File
@@ -33,3 +33,74 @@ 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
+12 -1
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_NETWORKING "Enable networking support" OFF)
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_NETWORKING)
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_NETWORKING
)
endif()
# Toolchains
include(cmake/targets/${DUSK_TARGET_SYSTEM}.cmake)
@@ -116,7 +123,11 @@ if(DUSK_BUILD_TESTS)
endif()
# Build assets
file(GLOB_RECURSE DUSK_ASSET_FILES CONFIGURE_DEPENDS "${DUSK_ASSETS_DIR}/*")
# Deliberately not CONFIGURE_DEPENDS: that reruns the full CMake configure
# step (which invalidates generated headers and forces a huge rebuild) on
# every single asset edit. Re-run cmake manually when assets are added or
# removed.
file(GLOB_RECURSE DUSK_ASSET_FILES "${DUSK_ASSETS_DIR}/*")
add_custom_command(
OUTPUT "${DUSK_ASSETS_ZIP}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${DUSK_ASSETS_DIR}"
+2 -3
View File
@@ -1,6 +1,5 @@
# Documentation
- [Scripting](docs/SCRIPTING.md) — writing gameplay logic in JavaScript.
- [UI](docs/UI.md) — building buttons/menus/etc from engine/game C code.
# Dusk
RPG Game Project, small and able to run on a PSP.
# Building
Each build target has different requirements. You can take a look at the git
+18
View File
@@ -0,0 +1,18 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
add_subdirectory(debug)
add_subdirectory(frame)
add_subdirectory(focus)
add_subdirectory(overlay)
add_subdirectory(transition)
add_subdirectory(widget)
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
ui.c
uielement.c
)
+138
View File
@@ -0,0 +1,138 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uiconsole.h"
#include "assert/assert.h"
#include "console/console.h"
#include "display/screen/screen.h"
#include "display/text/text.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
#include "display/mesh/mesh.h"
#include "util/memory.h"
typedef struct {
mesh_t mesh;
bool_t built;
meshvertex_t vertices[UI_CONSOLE_CACHE_VERTEX_MAX];
int32_t vertexCount;
int32_t cachedScanX;
int32_t cachedScanY;
} uiconsolecache_t;
uiconsolecache_t UI_CONSOLE_CACHE;
errorret_t uiConsoleDraw(void) {
if(!CONSOLE.visible) errorOk();
if(
CONSOLE.dirty ||
UI_CONSOLE_CACHE.cachedScanX != SCREEN.scanX ||
UI_CONSOLE_CACHE.cachedScanY != SCREEN.scanY
) {
errorChain(uiConsoleRebuild());
}
if(UI_CONSOLE_CACHE.vertexCount == 0) errorOk();
shadermaterial_t material = {
.unlit = {
.color = COLOR_RED,
.texture = FONT_DEFAULT.texture
}
};
errorChain(shaderBind(&SHADER_UNLIT));
errorChain(shaderSetMaterial(&SHADER_UNLIT, &material));
return meshDraw(&UI_CONSOLE_CACHE.mesh, 0, UI_CONSOLE_CACHE.vertexCount);
}
errorret_t uiConsoleRebuild(void) {
int32_t spriteCount = 0;
for(uint32_t i = 0; i < CONSOLE_HISTORY_MAX; i++) {
char_t c;
int32_t j = 0;
while((c = CONSOLE.line[i][j++]) != '\0') {
if(c != ' ' && c != '\n') spriteCount++;
}
}
assertTrue(
spriteCount <= UI_CONSOLE_CACHE_GLYPH_MAX,
"Console history exceeds fixed cache capacity"
);
const int32_t vertexCount = spriteCount * QUAD_VERTEX_COUNT;
UI_CONSOLE_CACHE.vertexCount = vertexCount;
if(vertexCount > 0) {
const float_t lineH = (float_t)FONT_DEFAULT.tileset->tileHeight;
const float_t charW = (float_t)FONT_DEFAULT.tileset->tileWidth;
int32_t index = 0;
int32_t row = 0;
for(uint32_t i = 0; i < CONSOLE_HISTORY_MAX; i++) {
float_t posX = (float_t)SCREEN.scanX;
float_t posY = (float_t)SCREEN.scanY + lineH * (float_t)row;
char_t c;
int32_t j = 0;
while((c = CONSOLE.line[i][j++]) != '\0') {
if(c == '\n') {
posX = (float_t)SCREEN.scanX;
posY += lineH;
row++;
continue;
}
if(c == ' ') {
posX += charW;
continue;
}
const spritebatchsprite_t sprite = textGetSprite(
(vec2){ posX, posY }, c, &FONT_DEFAULT
);
spriteBatchBufferToMesh(
&sprite, 1,
&UI_CONSOLE_CACHE.vertices[index], QUAD_VERTEX_COUNT
);
index += QUAD_VERTEX_COUNT;
posX += charW;
}
row++;
}
if(!UI_CONSOLE_CACHE.built) {
errorChain(meshInit(
&UI_CONSOLE_CACHE.mesh,
QUAD_PRIMITIVE_TYPE,
UI_CONSOLE_CACHE_VERTEX_MAX,
UI_CONSOLE_CACHE.vertices
));
UI_CONSOLE_CACHE.built = true;
} else {
errorChain(meshFlush(&UI_CONSOLE_CACHE.mesh, 0, vertexCount));
}
}
UI_CONSOLE_CACHE.cachedScanX = SCREEN.scanX;
UI_CONSOLE_CACHE.cachedScanY = SCREEN.scanY;
CONSOLE.dirty = false;
errorOk();
}
errorret_t uiConsoleDispose(void) {
if(UI_CONSOLE_CACHE.built) {
errorChain(meshDispose(&UI_CONSOLE_CACHE.mesh));
}
memoryZero(&UI_CONSOLE_CACHE, sizeof(uiconsolecache_t));
errorOk();
}
+48
View File
@@ -0,0 +1,48 @@
/**
* 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 "display/mesh/quad.h"
// Fixed capacity for the console's cached glyph mesh, in glyphs -- the
// mesh/vertex buffer is sized to this once and never grown/shrunk, so
// history producing more non-space characters than this asserts (see
// uiConsoleRebuild) instead of reallocating.
#define UI_CONSOLE_CACHE_GLYPH_MAX 512
#define UI_CONSOLE_CACHE_VERTEX_MAX (\
UI_CONSOLE_CACHE_GLYPH_MAX * QUAD_VERTEX_COUNT \
)
/**
* Renders the console history into the scan-safe area, drawing a mesh
* that is only rebuilt when the history changes or the scan-safe origin
* moves, rather than rebuffering vertices every frame. No-ops when the
* console is not visible.
*
* @return Any error that occurs.
*/
errorret_t uiConsoleDraw(void);
/**
* Rebuilds the cached mesh for the console's current history and
* scan-safe origin. Called automatically by uiConsoleDraw() whenever
* needed; only needs calling directly to force an immediate rebuild.
* The underlying vertex buffer is a fixed-size array (see
* UI_CONSOLE_CACHE_VERTEX_MAX) -- asserts if the history produces more
* glyphs than that capacity, rather than growing it.
*
* @return Any error that occurs.
*/
errorret_t uiConsoleRebuild(void);
/**
* Frees the mesh and vertex buffer built up by uiConsoleDraw().
*
* @return Any error that occurs.
*/
errorret_t uiConsoleDispose(void);
@@ -7,13 +7,21 @@
#include "uifps.h"
#include "time/time.h"
#include "display/spritebatch/spritebatch.h"
#include "util/string.h"
#include "display/text/text.h"
#include "display/screen/screen.h"
#include "engine/engine.h"
uifps_t UIFPS;
errorret_t uiFPSInit() {
uiLabelInit(&UIFPS.fpsLabel, &FONT_DEFAULT);
uiLabelInit(&UIFPS.versionLabel, &FONT_DEFAULT);
uiLabelSetText(&UIFPS.versionLabel, ENGINE.version);
uiLabelSetColor(&UIFPS.versionLabel, color(255, 255, 255, 128));
errorOk();
}
errorret_t uiFPSDraw() {
char_t fpsText[32];
@@ -50,26 +58,21 @@ errorret_t uiFPSDraw() {
textColor = COLOR_RED;
}
errorChain(textDraw(
(float_t)SCREEN.scanX,
(float_t)SCREEN.scanY,
fpsText, textColor,
&FONT_DEFAULT
));
errorChain(spriteBatchFlush());
// ENGINE.version and FONT_DEFAULT never change after boot; measure once.
static int32_t versionWidth = -1, versionHeight = 0;
if(versionWidth < 0) {
textMeasure(ENGINE.version, &FONT_DEFAULT, &versionWidth, &versionHeight);
uiLabelSetColor(&UIFPS.fpsLabel, textColor);
if(stringCompare(fpsText, UIFPS.fpsLabel.text) != 0) {
uiLabelSetText(&UIFPS.fpsLabel, fpsText);
}
errorChain(textDraw(
(float_t)(SCREEN.scanX + SCREEN.scanWidth - versionWidth),
(float_t)(SCREEN.scanY + SCREEN.scanHeight - versionHeight),
ENGINE.version,
color(255, 255, 255, 128),
&FONT_DEFAULT
errorChain(uiLabelDraw(
&UIFPS.fpsLabel, (float_t)SCREEN.scanX, (float_t)SCREEN.scanY
));
return spriteBatchFlush();
int32_t versionWidth, versionHeight;
uiLabelGetSize(&UIFPS.versionLabel, &versionWidth, &versionHeight);
errorChain(uiLabelDraw(
&UIFPS.versionLabel,
(float_t)(SCREEN.scanX + SCREEN.scanWidth - versionWidth),
(float_t)(SCREEN.scanY + SCREEN.scanHeight - versionHeight)
));
errorOk();
}
@@ -8,14 +8,24 @@
#pragma once
#include "error/error.h"
#include "time/timeepoch.h"
#include "ui/widget/uilabel.h"
typedef struct {
dusktimeepoch_t lastTick;
float_t fpsAverage;
uilabel_t fpsLabel;
uilabel_t versionLabel;
} uifps_t;
extern uifps_t UIFPS;
/**
* Initializes the FPS counter, caching the (static) version label.
*
* @return Any error that occurs.
*/
errorret_t uiFPSInit();
/**
* Draws the FPS counter on the screen, and also does the update (for now).
*
@@ -12,11 +12,11 @@
#include "time/time.h"
const uifocusdirmap_t UI_FOCUS_DIR_MAP[] = {
{ INPUT_ACTION_UP, UI_FOCUS_DIRECTION_UP, 0, -1 },
{ INPUT_ACTION_DOWN, UI_FOCUS_DIRECTION_DOWN, 0, 1 },
{ INPUT_ACTION_LEFT, UI_FOCUS_DIRECTION_LEFT, -1, 0 },
{ INPUT_ACTION_RIGHT, UI_FOCUS_DIRECTION_RIGHT, 1, 0 },
{ INPUT_ACTION_NULL, UI_FOCUS_DIRECTION_NONE, 0, 0 },
{ INPUT_BIND_UP, UI_FOCUS_DIRECTION_UP, 0, -1 },
{ INPUT_BIND_DOWN, UI_FOCUS_DIRECTION_DOWN, 0, 1 },
{ INPUT_BIND_LEFT, UI_FOCUS_DIRECTION_LEFT, -1, 0 },
{ INPUT_BIND_RIGHT, UI_FOCUS_DIRECTION_RIGHT, 1, 0 },
{ INPUT_BIND_NULL, UI_FOCUS_DIRECTION_NONE, 0, 0 },
};
uifocus_t UI_FOCUS;
@@ -108,7 +108,7 @@ void uiFocusMoveDirection(
) {
for(
const uifocusdirmap_t *m = UI_FOCUS_DIR_MAP;
m->action != INPUT_ACTION_NULL;
m->action != INPUT_BIND_NULL;
m++
) {
if(m->direction != dir) continue;
@@ -142,19 +142,19 @@ void uiFocusUpdate(void) {
uifocusitem_t *item = &UI_FOCUS.items[UI_FOCUS.count - 1];
if(inputPressed(INPUT_ACTION_ACCEPT)) {
if(inputPressed(INPUT_BIND_ACCEPT)) {
if(item->selected != NULL) item->selected(item);
return;
}
if(inputPressed(INPUT_ACTION_CANCEL)) {
if(inputPressed(INPUT_BIND_CANCEL)) {
uiFocusPop();
return;
}
for(
const uifocusdirmap_t *m = UI_FOCUS_DIR_MAP;
m->action != INPUT_ACTION_NULL;
m->action != INPUT_BIND_NULL;
m++
) {
if(!inputPressed(m->action)) continue;
@@ -167,7 +167,7 @@ void uiFocusUpdate(void) {
bool_t held = false;
for(
const uifocusdirmap_t *m = UI_FOCUS_DIR_MAP;
m->action != INPUT_ACTION_NULL;
m->action != INPUT_BIND_NULL;
m++
) {
if(m->direction != UI_FOCUS.direction) continue;
@@ -23,7 +23,7 @@
#define UI_FOCUS_HOLD_REPEAT 0.1f
typedef struct {
inputaction_t action;
inputbind_t action;
uifocusdirection_t direction;
int8_t dx;
int8_t dy;
@@ -31,7 +31,7 @@ typedef struct {
/**
* Mapping of input actions to focus directions, terminated by an
* entry with action == INPUT_ACTION_NULL.
* entry with action == INPUT_BIND_NULL.
*/
extern const uifocusdirmap_t UI_FOCUS_DIR_MAP[];
+12
View File
@@ -0,0 +1,12 @@
# 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
uiframe.c
uiconfirm.c
)
add_subdirectory(settings)
@@ -0,0 +1,13 @@
# 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
uisettings.c
uisettingsgeneral.c
uisettingsinput.c
uisettingsdisplay.c
uisettingsaudio.c
)
+248
View File
@@ -0,0 +1,248 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uisettings.h"
#include "uisettingsgeneral.h"
#include "uisettingsinput.h"
#include "uisettingsdisplay.h"
#include "uisettingsaudio.h"
#include "ui/frame/uiframe.h"
#include "ui/frame/uiconfirm.h"
#include "util/memory.h"
#include "display/text/text.h"
#include "display/screen/screen.h"
#include "assert/assert.h"
#include "locale/localemanager.h"
#include "asset/loader/locale/assetlocaleloader.h"
uisettings_t UI_SETTINGS;
uisettingstabdef_t UI_SETTINGS_TAB_DEFS[UI_SETTINGS_TAB_COUNT] = {
{
.localeId = "ui.settings.tabs.general",
.init = uiSettingsGeneralInit,
.menu = (uimenu_t *)&UI_SETTINGS.data,
.load = uiSettingsGeneralLoad,
.apply = uiSettingsGeneralApply,
.hasChanges = uiSettingsGeneralHasChanges
},
{
.localeId = "ui.settings.tabs.input",
.init = uiSettingsInputInit,
.menu = (uimenu_t *)&UI_SETTINGS.data,
.load = uiSettingsInputLoad,
.apply = uiSettingsInputApply,
.hasChanges = uiSettingsInputHasChanges
},
{
.localeId = "ui.settings.tabs.display",
.init = uiSettingsDisplayInit,
.menu = (uimenu_t *)&UI_SETTINGS.data,
.load = uiSettingsDisplayLoad,
.apply = uiSettingsDisplayApply,
.hasChanges = uiSettingsDisplayHasChanges
},
{
.localeId = "ui.settings.tabs.audio",
.init = uiSettingsAudioInit,
.menu = (uimenu_t *)&UI_SETTINGS.data,
.load = uiSettingsAudioLoad,
.apply = uiSettingsAudioApply,
.hasChanges = uiSettingsAudioHasChanges
}
};
static uisettingstabdef_t UI_SETTINGS_TOP_DEF = {
.menu = &UI_SETTINGS.tabsMenu,
.load = uiSettingsLoad,
.hasChanges = uiSettingsHasChanges
};
static uisettingstabdef_t *UI_SETTINGS_PENDING_DISCARD = NULL;
static uisettingstabdef_t *UI_SETTINGS_ACTIVE_TAB = NULL;
errorret_t uiSettingsActivateTab(uisettingstabdef_t *def) {
if(def == UI_SETTINGS_ACTIVE_TAB) errorOk();
errorChain(def->init(&UI_SETTINGS.data));
def->menu->user = def;
def->load();
UI_SETTINGS_ACTIVE_TAB = def;
errorOk();
}
void uiSettingsTabChanged(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
if(index >= UI_SETTINGS_TAB_COUNT) return;
errorCatch(uiSettingsActivateTab(&UI_SETTINGS_TAB_DEFS[index]));
}
void uiSettingsTabSelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
if(index >= UI_SETTINGS_TAB_COUNT) return;
uisettingstabdef_t *def = &UI_SETTINGS_TAB_DEFS[index];
errorCatch(uiSettingsActivateTab(def));
uiMenuOpen(def->menu);
}
errorret_t uiSettingsInit(void) {
memoryZero(&UI_SETTINGS, sizeof(uisettings_t));
UI_SETTINGS_ACTIVE_TAB = NULL;
for(uint8_t i = 0; i < UI_SETTINGS_TAB_COUNT; i++) {
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
UI_SETTINGS_TAB_DEFS[i].localeId,
0,
UI_SETTINGS.tabLabels[i],
UI_SETTINGS_TAB_LABEL_MAX
));
}
MENU_BEGIN(
&UI_SETTINGS.tabsMenu, UI_SETTINGS.tabs, uiSettingsTabSelected,
uiSettingsDiscardMenuClosed, uiSettingsTabChanged
);
for(uint8_t i = 0; i < UI_SETTINGS_TAB_COUNT; i++) {
MENU_TAB(UI_SETTINGS.tabLabels[i]);
}
MENU_END(UI_SETTINGS.tabs, menuIndex);
UI_SETTINGS.tabsMenu.user = &UI_SETTINGS_TOP_DEF;
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
"ui.settings.apply",
0,
UI_SETTINGS.applyLabel,
UI_SETTINGS_APPLY_LABEL_MAX
));
errorChain(uiSettingsActivateTab(&UI_SETTINGS_TAB_DEFS[0]));
errorOk();
}
errorret_t uiSettingsDraw(void) {
if(!uiMenuIsActive(&UI_SETTINGS.tabsMenu)) errorOk();
const float_t width = SCREEN.width;
const float_t height = SCREEN.height;
const float_t x = (float_t)SCREEN.scanX +
((float_t)SCREEN.scanWidth - width) * 0.5f;
const float_t y = (float_t)SCREEN.scanY +
((float_t)SCREEN.scanHeight - height) * 0.5f;
errorChain(uiFrameDrawCached(&UI_SETTINGS.frameCache, x, y, width, height));
const float_t contentX = x + UI_FRAME_START_X;
const float_t contentY = y + UI_FRAME_START_Y;
const float_t contentWidth = width - (UI_FRAME_START_X * 2);
const float_t contentHeight = height - (UI_FRAME_START_Y * 2);
errorChain(uiMenuDraw(
&UI_SETTINGS.tabsMenu,
contentX,
contentY,
contentWidth,
contentHeight
));
const float_t tabsRowHeight = (float_t)FONT_DEFAULT.tileset->tileHeight;
const float_t pageY = contentY + tabsRowHeight + UI_FRAME_PADDING_Y;
const float_t pageHeight = contentHeight - tabsRowHeight - UI_FRAME_PADDING_Y;
if(UI_SETTINGS_ACTIVE_TAB != NULL) {
errorChain(uiMenuDraw(
UI_SETTINGS_ACTIVE_TAB->menu, contentX, pageY, contentWidth, pageHeight
));
}
errorOk();
}
errorret_t uiSettingsUpdate(void) {
if(!UI_SETTINGS_PENDING_DISCARD) errorOk();
uisettingstabdef_t *def = UI_SETTINGS_PENDING_DISCARD;
UI_SETTINGS_PENDING_DISCARD = NULL;
return uiSettingsDiscardUpdate(def);
}
bool_t uiSettingsIsOpen(void) {
return uiMenuIsActive(&UI_SETTINGS.tabsMenu);
}
void uiSettingsOpen() {
uiSettingsLoad();
uiMenuOpen(&UI_SETTINGS.tabsMenu);
}
void uiSettingsClose() {
uiMenuClose(&UI_SETTINGS.tabsMenu);
}
errorret_t uiSettingsDispose(void) {
errorOk();
}
void uiSettingsLoad(void) {
if(UI_SETTINGS_ACTIVE_TAB != NULL) UI_SETTINGS_ACTIVE_TAB->load();
}
void uiSettingsApply(void) {
if(UI_SETTINGS_ACTIVE_TAB != NULL) UI_SETTINGS_ACTIVE_TAB->apply();
}
bool_t uiSettingsHasChanges(void) {
return UI_SETTINGS_ACTIVE_TAB != NULL && UI_SETTINGS_ACTIVE_TAB->hasChanges();
}
void uiSettingsDiscardMenuClosed(const uimenu_t *menu) {
uisettingstabdef_t *def = (uisettingstabdef_t *)menu->user;
if(def->hasChanges()) UI_SETTINGS_PENDING_DISCARD = def;
}
errorret_t uiSettingsDiscardUpdate(uisettingstabdef_t *def) {
#define UI_SETTINGS_DISCARD_TEXT_MAX 128
char_t text[UI_SETTINGS_DISCARD_TEXT_MAX];
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
"ui.confirm.discard_changes",
0,
text,
UI_SETTINGS_DISCARD_TEXT_MAX
));
#undef UI_SETTINGS_DISCARD_TEXT_MAX
uiConfirmOpen(text, uiSettingsDiscardConfirmResult, def);
errorOk();
}
void uiSettingsDiscardConfirmResult(const bool_t result, void *user) {
uisettingstabdef_t *def = (uisettingstabdef_t *)user;
if(!result) {
uiMenuOpen(def->menu);
return;
}
def->load();
}
+135
View File
@@ -0,0 +1,135 @@
/**
* 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 "ui/widget/uimenu.h"
#include "ui/frame/uiframe.h"
#include "uisettingsdata.h"
#define UI_SETTINGS_TAB_COUNT 4
#define UI_SETTINGS_TAB_LABEL_MAX 32
#define UI_SETTINGS_APPLY_LABEL_MAX 32
typedef struct {
const char_t *localeId;
errorret_t (*init)(uisettingsdata_t *data);
uimenu_t *menu;
void (*load)(void);
void (*apply)(void);
bool_t (*hasChanges)(void);
} uisettingstabdef_t;
typedef struct {
uimenu_t tabsMenu;
uimenuitem_t tabs[UI_SETTINGS_TAB_COUNT];
char_t tabLabels[UI_SETTINGS_TAB_COUNT][UI_SETTINGS_TAB_LABEL_MAX];
char_t applyLabel[UI_SETTINGS_APPLY_LABEL_MAX];
uisettingsdata_t data;
uiframecache_t frameCache;
} uisettings_t;
extern uisettings_t UI_SETTINGS;
extern uisettingstabdef_t UI_SETTINGS_TAB_DEFS[UI_SETTINGS_TAB_COUNT];
/**
* Menu closed callback that flags a pending discard-changes
* confirmation if the menu's settings page/panel reports unsaved
* changes. Pass this directly as a settings page menu's closed
* callback. The pending def is picked up by uiSettingsUpdate on the
* next tick.
*
* @param menu The menu that was just closed.
*/
void uiSettingsDiscardMenuClosed(const uimenu_t *menu);
/**
* Shows the discard-changes confirmation dialog for def. Called once
* by uiSettingsUpdate when uiSettingsDiscardMenuClosed has flagged a
* pending def.
*
* @param def The tab/panel def to show the confirmation for.
* @return Any error that occurs.
*/
errorret_t uiSettingsDiscardUpdate(uisettingstabdef_t *def);
/**
* Callback passed to uiConfirmOpen by uiSettingsDiscardUpdate. Reopens
* the menu if the user chose to keep editing, otherwise reloads the
* widgets back to the actual engine values.
*
* @param result True if the user confirmed discarding changes, false
* to keep editing.
* @param user The uisettingstabdef_t* this confirmation belongs to.
*/
void uiSettingsDiscardConfirmResult(const bool_t result, void *user);
/**
* Initializes the settings panel and all of its category pages.
*
* @return Any error that occurs.
*/
errorret_t uiSettingsInit(void);
/**
* Draws the settings panel. No-op when not visible.
*
* @return Any error that occurs.
*/
errorret_t uiSettingsDraw(void);
/**
* Updates the settings panel. Shows a discard-changes confirmation if
* the panel was just closed with unsaved changes.
*
* @return Any error that occurs.
*/
errorret_t uiSettingsUpdate(void);
/**
* Returns true when the settings panel is currently open.
*
* @returns True if open.
*/
bool_t uiSettingsIsOpen(void);
/**
* Opens the settings panel. No-op when already open.
*/
void uiSettingsOpen();
/**
* Closes the settings panel. No-op when already closed.
*/
void uiSettingsClose();
/**
* Disposes of the settings panel.
*
* @return Any error that occurs.
*/
errorret_t uiSettingsDispose(void);
/**
* Loads every category page's widgets from the current engine settings.
* Called automatically by uiSettingsOpen.
*/
void uiSettingsLoad(void);
/**
* Applies every category page's widget values to the engine settings.
* Called automatically when a page's own Apply button is pressed.
*/
void uiSettingsApply(void);
/**
* Returns whether any category page has a widget value that differs
* from what was loaded.
*
* @returns True if there are unsaved changes.
*/
bool_t uiSettingsHasChanges(void);
@@ -0,0 +1,47 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uisettingsaudio.h"
#include "uisettings.h"
#include "assert/assert.h"
#include "util/memory.h"
void uiSettingsAudioSelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
if(index != UI_SETTINGS_AUDIO_INDEX_APPLY) return;
uiSettingsAudioApply();
}
errorret_t uiSettingsAudioInit(uisettingsdata_t *data) {
uisettingsaudio_t *audio = &data->audio;
memoryZero(audio, sizeof(uisettingsaudio_t));
MENU_BEGIN(
&audio->menu, audio->items,
uiSettingsAudioSelected, uiSettingsDiscardMenuClosed, NULL
);
MENU_LABEL("No audio settings yet");
MENU_BUTTON(UI_SETTINGS.applyLabel);
MENU_END(audio->items, 1);
errorOk();
}
void uiSettingsAudioLoad(void) {
}
void uiSettingsAudioApply(void) {
uiMenuClose(&UI_SETTINGS.data.audio.menu);
}
bool_t uiSettingsAudioHasChanges(void) {
return false;
}
@@ -0,0 +1,36 @@
/**
* 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 "uisettingsdata.h"
/**
* Initializes the audio settings page into the shared settings data
* union.
*
* @param data The shared settings data union to initialize into.
* @return Any error that occurs.
*/
errorret_t uiSettingsAudioInit(uisettingsdata_t *data);
/**
* Loads the page's widgets from the current engine audio settings.
*/
void uiSettingsAudioLoad(void);
/**
* Applies the page's widget values to the engine audio settings.
*/
void uiSettingsAudioApply(void);
/**
* Returns whether any widget's value differs from what was loaded.
*
* @returns True if there are unsaved changes.
*/
bool_t uiSettingsAudioHasChanges(void);
@@ -0,0 +1,67 @@
/**
* 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 "ui/widget/uimenu.h"
#define UI_SETTINGS_GENERAL_ITEM_COUNT 3
#define UI_SETTINGS_GENERAL_INDEX_LANGUAGE 0
#define UI_SETTINGS_GENERAL_INDEX_LANGUAGE_DETAIL 1
#define UI_SETTINGS_GENERAL_INDEX_APPLY 2
#define UI_SETTINGS_GENERAL_LOCALE_COUNT 3
#define UI_SETTINGS_GENERAL_LABEL_MAX 32
#define UI_SETTINGS_GENERAL_INFO_MAX 64
typedef struct {
uimenu_t menu;
uimenuitem_t items[UI_SETTINGS_GENERAL_ITEM_COUNT];
const char_t *localeNames[UI_SETTINGS_GENERAL_LOCALE_COUNT];
char_t languageLabel[UI_SETTINGS_GENERAL_LABEL_MAX];
char_t labelInfo[UI_SETTINGS_GENERAL_INFO_MAX];
} uisettingsgeneral_t;
#define UI_SETTINGS_INPUT_ITEM_COUNT 2
#define UI_SETTINGS_INPUT_LABEL_MAX 32
#define UI_SETTINGS_INPUT_INDEX_DEADZONE 0
#define UI_SETTINGS_INPUT_INDEX_APPLY 1
typedef struct {
uimenu_t menu;
uimenuitem_t items[UI_SETTINGS_INPUT_ITEM_COUNT];
char_t deadzoneLabel[UI_SETTINGS_INPUT_LABEL_MAX];
} uisettingsinput_t;
#define UI_SETTINGS_DISPLAY_ITEM_COUNT 2
#define UI_SETTINGS_DISPLAY_INDEX_APPLY 1
typedef struct {
uimenu_t menu;
uimenuitem_t items[UI_SETTINGS_DISPLAY_ITEM_COUNT];
} uisettingsdisplay_t;
#define UI_SETTINGS_AUDIO_ITEM_COUNT 2
#define UI_SETTINGS_AUDIO_INDEX_APPLY 1
typedef struct {
uimenu_t menu;
uimenuitem_t items[UI_SETTINGS_AUDIO_ITEM_COUNT];
} uisettingsaudio_t;
/**
* Shared, overlapping storage for every settings tab's page data. Only
* one member is ever live at a time -- the active tab's Init writes
* into it, overwriting whatever the previously active tab left there.
* This trades simultaneous access to every tab for a memory footprint
* of only the single largest page.
*/
typedef union {
uisettingsgeneral_t general;
uisettingsinput_t input;
uisettingsdisplay_t display;
uisettingsaudio_t audio;
} uisettingsdata_t;
@@ -0,0 +1,47 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uisettingsdisplay.h"
#include "uisettings.h"
#include "assert/assert.h"
#include "util/memory.h"
void uiSettingsDisplaySelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
if(index != UI_SETTINGS_DISPLAY_INDEX_APPLY) return;
uiSettingsDisplayApply();
}
errorret_t uiSettingsDisplayInit(uisettingsdata_t *data) {
uisettingsdisplay_t *display = &data->display;
memoryZero(display, sizeof(uisettingsdisplay_t));
MENU_BEGIN(
&display->menu, display->items,
uiSettingsDisplaySelected, uiSettingsDiscardMenuClosed, NULL
);
MENU_LABEL("No display settings yet");
MENU_BUTTON(UI_SETTINGS.applyLabel);
MENU_END(display->items, 1);
errorOk();
}
void uiSettingsDisplayLoad(void) {
}
void uiSettingsDisplayApply(void) {
uiMenuClose(&UI_SETTINGS.data.display.menu);
}
bool_t uiSettingsDisplayHasChanges(void) {
return false;
}
@@ -0,0 +1,36 @@
/**
* 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 "uisettingsdata.h"
/**
* Initializes the display settings page into the shared settings data
* union.
*
* @param data The shared settings data union to initialize into.
* @return Any error that occurs.
*/
errorret_t uiSettingsDisplayInit(uisettingsdata_t *data);
/**
* Loads the page's widgets from the current engine display settings.
*/
void uiSettingsDisplayLoad(void);
/**
* Applies the page's widget values to the engine display settings.
*/
void uiSettingsDisplayApply(void);
/**
* Returns whether any widget's value differs from what was loaded.
*
* @returns True if there are unsaved changes.
*/
bool_t uiSettingsDisplayHasChanges(void);
@@ -0,0 +1,117 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uisettingsgeneral.h"
#include "uisettings.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "locale/localemanager.h"
#include "locale/localeinfo.h"
#include "asset/loader/locale/assetlocaleloader.h"
static const localeinfo_t *const UI_SETTINGS_GENERAL_LOCALES[
UI_SETTINGS_GENERAL_LOCALE_COUNT
] = {
&LOCALE_EN_US,
&LOCALE_JP_JP,
&LOCALE_ES_MX
};
void uiSettingsGeneralSelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
switch(index) {
case UI_SETTINGS_GENERAL_INDEX_APPLY:
uiSettingsGeneralApply();
break;
default:
break;
}
}
errorret_t uiSettingsGeneralInit(uisettingsdata_t *data) {
uisettingsgeneral_t *general = &data->general;
memoryZero(general, sizeof(uisettingsgeneral_t));
for(uint8_t i = 0; i < UI_SETTINGS_GENERAL_LOCALE_COUNT; i++) {
general->localeNames[i] = UI_SETTINGS_GENERAL_LOCALES[i]->name;
}
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
"ui.settings.general.language",
0,
general->languageLabel,
UI_SETTINGS_GENERAL_LABEL_MAX
));
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
"ui.settings.general.language_detail",
0,
general->labelInfo,
UI_SETTINGS_GENERAL_INFO_MAX
));
MENU_BEGIN(
&general->menu, general->items,
uiSettingsGeneralSelected, uiSettingsDiscardMenuClosed, NULL
);
MENU_DROPDOWN(
general->languageLabel, general->localeNames,
UI_SETTINGS_GENERAL_LOCALE_COUNT, 0
);
MENU_LABEL(general->labelInfo);
MENU_BUTTON(UI_SETTINGS.applyLabel);
MENU_END(general->items, 1);
errorOk();
}
void uiSettingsGeneralLoad(void) {
uisettingsgeneral_t *general = &UI_SETTINGS.data.general;
uint8_t index = 0;
for(uint8_t i = 0; i < UI_SETTINGS_GENERAL_LOCALE_COUNT; i++) {
if(stringCompare(LOCALE.locale->file, UI_SETTINGS_GENERAL_LOCALES[i]->file) != 0) {
continue;
}
index = i;
break;
}
uiDropdownSetSelectedIndex(
&general->items[UI_SETTINGS_GENERAL_INDEX_LANGUAGE].dropdown, index
);
}
void uiSettingsGeneralApply(void) {
uisettingsgeneral_t *general = &UI_SETTINGS.data.general;
uint8_t index = uiDropdownGetSelectedIndex(
&general->items[UI_SETTINGS_GENERAL_INDEX_LANGUAGE].dropdown
);
errorCatch(localeManagerSetLocale(UI_SETTINGS_GENERAL_LOCALES[index]));
uiMenuClose(&general->menu);
}
bool_t uiSettingsGeneralHasChanges(void) {
uisettingsgeneral_t *general = &UI_SETTINGS.data.general;
uint8_t index = uiDropdownGetSelectedIndex(
&general->items[UI_SETTINGS_GENERAL_INDEX_LANGUAGE].dropdown
);
return stringCompare(
LOCALE.locale->file, UI_SETTINGS_GENERAL_LOCALES[index]->file
) != 0;
}
@@ -0,0 +1,36 @@
/**
* 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 "uisettingsdata.h"
/**
* Initializes the general settings page into the shared settings data
* union.
*
* @param data The shared settings data union to initialize into.
* @return Any error that occurs.
*/
errorret_t uiSettingsGeneralInit(uisettingsdata_t *data);
/**
* Loads the page's widgets from the current engine general settings.
*/
void uiSettingsGeneralLoad(void);
/**
* Applies the page's widget values to the engine general settings.
*/
void uiSettingsGeneralApply(void);
/**
* Returns whether any widget's value differs from what was loaded.
*
* @returns True if there are unsaved changes.
*/
bool_t uiSettingsGeneralHasChanges(void);
@@ -0,0 +1,82 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uisettingsinput.h"
#include "uisettings.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "locale/localemanager.h"
#include "asset/loader/locale/assetlocaleloader.h"
#include "input/input.h"
#include "save/savesettings.h"
void uiSettingsInputSelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
if(index != UI_SETTINGS_INPUT_INDEX_APPLY) return;
uiSettingsInputApply();
}
errorret_t uiSettingsInputInit(uisettingsdata_t *data) {
uisettingsinput_t *input = &data->input;
memoryZero(input, sizeof(uisettingsinput_t));
MENU_BEGIN(
&input->menu, input->items,
uiSettingsInputSelected, uiSettingsDiscardMenuClosed, NULL
);
#ifdef DUSK_INPUT_GAMEPAD
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
"ui.settings.input.deadzone",
0,
input->deadzoneLabel,
UI_SETTINGS_INPUT_LABEL_MAX
));
MENU_SLIDER_FLOAT(
input->deadzoneLabel, INPUT_DEADZONE_DEFAULT, 0.0f, 1.0f, 0.05f
);
#else
MENU_LABEL("No input settings yet");
#endif
MENU_BUTTON(UI_SETTINGS.applyLabel);
MENU_END(input->items, 1);
errorOk();
}
void uiSettingsInputLoad(void) {
#ifdef DUSK_INPUT_GAMEPAD
uiSliderSetFloat(
&UI_SETTINGS.data.input.items[UI_SETTINGS_INPUT_INDEX_DEADZONE].slider,
INPUT.deadzone
);
#endif
}
void uiSettingsInputApply(void) {
#ifdef DUSK_INPUT_GAMEPAD
INPUT.deadzone = uiSliderGetFloat(
&UI_SETTINGS.data.input.items[UI_SETTINGS_INPUT_INDEX_DEADZONE].slider
);
#endif
errorCatch(errorPrint(saveSettingsWrite()));
uiMenuClose(&UI_SETTINGS.data.input.menu);
}
bool_t uiSettingsInputHasChanges(void) {
#ifdef DUSK_INPUT_GAMEPAD
if(uiSliderGetFloat(
&UI_SETTINGS.data.input.items[UI_SETTINGS_INPUT_INDEX_DEADZONE].slider
) != INPUT.deadzone) return true;
#endif
return false;
}
@@ -0,0 +1,36 @@
/**
* 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 "uisettingsdata.h"
/**
* Initializes the input settings page into the shared settings data
* union.
*
* @param data The shared settings data union to initialize into.
* @return Any error that occurs.
*/
errorret_t uiSettingsInputInit(uisettingsdata_t *data);
/**
* Loads the page's widgets from the current engine input settings.
*/
void uiSettingsInputLoad(void);
/**
* Applies the page's widget values to the engine input settings.
*/
void uiSettingsInputApply(void);
/**
* Returns whether any widget's value differs from what was loaded.
*
* @returns True if there are unsaved changes.
*/
bool_t uiSettingsInputHasChanges(void);
+126
View File
@@ -0,0 +1,126 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uiconfirm.h"
#include "uiframe.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/math.h"
#include "display/screen/screen.h"
#include "display/text/text.h"
#include "display/color.h"
#include "display/spritebatch/spritebatch.h"
#include "display/texture/texture.h"
#include "display/shader/shaderunlit.h"
#define UI_CONFIRM_BACKDROP_COLOR color4b(0, 0, 0, 160)
uiconfirm_t UI_CONFIRM;
void uiConfirmSelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
UI_CONFIRM.result = index == UI_CONFIRM_INDEX_CONFIRM;
uiConfirmClose();
}
void uiConfirmClosed(const uimenu_t *menu) {
if(UI_CONFIRM.callback != NULL) {
UI_CONFIRM.callback(UI_CONFIRM.result, UI_CONFIRM.user);
}
}
errorret_t uiConfirmInit(void) {
memoryZero(&UI_CONFIRM, sizeof(uiconfirm_t));
uiLabelInit(&UI_CONFIRM.textLabel, &FONT_DEFAULT);
MENU_BEGIN(
&UI_CONFIRM.menu, UI_CONFIRM.items, uiConfirmSelected, uiConfirmClosed, NULL
);
MENU_BUTTON("Confirm");
MENU_BUTTON("Cancel");
MENU_END(UI_CONFIRM.items, menuIndex);
errorOk();
}
errorret_t uiConfirmDraw(void) {
if(!uiMenuIsActive(&UI_CONFIRM.menu)) errorOk();
spritebatchsprite_t backdropSprite = {
.min = { 0.0f, 0.0f, 0.0f },
.max = { (float_t)SCREEN.width, (float_t)SCREEN.height, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
shadermaterial_t backdropMaterial = {
.unlit = {
.color = UI_CONFIRM_BACKDROP_COLOR,
.texture = &TEXTURE_WHITE
}
};
errorChain(
spriteBatchBuffer(&backdropSprite, 1, &SHADER_UNLIT, backdropMaterial)
);
int32_t textW, textH;
uiLabelGetSize(&UI_CONFIRM.textLabel, &textW, &textH);
float_t rowHeight = (float_t)FONT_DEFAULT.tileset->tileHeight;
float_t width = mathMax(
(float_t)textW + (UI_FRAME_START_X * 2), UI_CONFIRM_MIN_WIDTH
);
float_t height = (UI_FRAME_START_Y * 2) + rowHeight + UI_FRAME_PADDING_Y +
rowHeight;
float_t x = (float_t)SCREEN.scanX + ((float_t)SCREEN.scanWidth - width) * 0.5f;
float_t y = (float_t)SCREEN.scanY + ((float_t)SCREEN.scanHeight - height) * 0.5f;
errorChain(uiFrameDrawCached(&UI_CONFIRM.frameCache, x, y, width, height));
float_t contentX = x + UI_FRAME_START_X;
float_t contentY = y + UI_FRAME_START_Y;
float_t contentWidth = width - (UI_FRAME_START_X * 2);
errorChain(uiLabelDraw(&UI_CONFIRM.textLabel, contentX, contentY));
float_t buttonsY = contentY + rowHeight + UI_FRAME_PADDING_Y;
errorChain(uiMenuDraw(&UI_CONFIRM.menu, contentX, buttonsY, contentWidth, rowHeight));
errorOk();
}
bool_t uiConfirmIsOpen(void) {
return uiMenuIsActive(&UI_CONFIRM.menu);
}
bool_t uiConfirmGetResult(void) {
return UI_CONFIRM.result;
}
void uiConfirmOpen(
const char_t *question,
uiconfirmcallback_t callback,
void *user
) {
assertNotNull(question, "Question cannot be NULL");
uiLabelSetText(&UI_CONFIRM.textLabel, question);
UI_CONFIRM.callback = callback;
UI_CONFIRM.user = user;
UI_CONFIRM.result = false;
uiMenuOpen(&UI_CONFIRM.menu);
}
void uiConfirmClose(void) {
uiMenuClose(&UI_CONFIRM.menu);
}
errorret_t uiConfirmDispose(void) {
errorOk();
}
+96
View File
@@ -0,0 +1,96 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "ui/widget/uimenu.h"
#include "ui/widget/uilabel.h"
#include "ui/frame/uiframe.h"
#define UI_CONFIRM_MIN_WIDTH 160.0f
#define UI_CONFIRM_INDEX_CONFIRM 0
#define UI_CONFIRM_INDEX_CANCEL 1
#define UI_CONFIRM_ITEM_COUNT 2
/**
* Callback invoked once a confirm dialog is dismissed.
*
* @param result True if Confirm was selected, false if Cancel was
* selected or the dialog was backed out of.
* @param user Arbitrary pointer passed to uiConfirmOpen.
*/
typedef void (*uiconfirmcallback_t)(const bool_t result, void *user);
typedef struct {
uilabel_t textLabel;
uimenu_t menu;
uimenuitem_t items[UI_CONFIRM_ITEM_COUNT];
uiconfirmcallback_t callback;
void *user;
bool_t result;
uiframecache_t frameCache;
} uiconfirm_t;
extern uiconfirm_t UI_CONFIRM;
/**
* Initializes the confirm dialog.
*
* @return Any error that occurs.
*/
errorret_t uiConfirmInit(void);
/**
* Draws the confirm dialog: a semi-transparent black backdrop covering
* the whole screen, then its own centered frame with the question text
* and Confirm/Cancel buttons. No-op when not open.
*
* @return Any error that occurs.
*/
errorret_t uiConfirmDraw(void);
/**
* Returns true when the confirm dialog is currently open.
*
* @returns True if open.
*/
bool_t uiConfirmIsOpen(void);
/**
* Returns the result of the most recently dismissed confirm dialog.
*
* @returns True if Confirm was selected, false otherwise.
*/
bool_t uiConfirmGetResult(void);
/**
* Opens the confirm dialog with the given question text. callback is
* invoked exactly once with the result, whether the dialog was
* dismissed by selecting a button or by pressing cancel/back.
*
* @param question Display text; copied internally, safe to be transient.
* @param callback Called with the result once the dialog closes. May be
* NULL.
* @param user Arbitrary pointer passed through to callback.
*/
void uiConfirmOpen(
const char_t *question,
uiconfirmcallback_t callback,
void *user
);
/**
* Closes the confirm dialog. No-op when already closed.
*/
void uiConfirmClose(void);
/**
* Disposes of the confirm dialog.
*
* @return Any error that occurs.
*/
errorret_t uiConfirmDispose(void);
+161
View File
@@ -0,0 +1,161 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uiframe.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "display/texture/texture.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
#include "display/color.h"
uiframe_t UI_FRAME;
errorret_t uiFrameInit(void) {
memoryZero(&UI_FRAME, sizeof(uiframe_t));
// Init texture.
color_t border = color4b(0, 50, 255, 255);
color_t center = color4b(0, 100, 220, 240);
for(uint8_t y = 0; y < UI_FRAME_TEXTURE_HEIGHT_POW2; y++) {
for(uint8_t x = 0; x < UI_FRAME_TEXTURE_WIDTH_POW2; x++) {
color_t c;
if(x >= UI_FRAME_TEXTURE_WIDTH || y >= UI_FRAME_TEXTURE_HEIGHT) {
c = COLOR_TRANSPARENT;
} else if(
y < UI_FRAME_TILE_HEIGHT || y >= UI_FRAME_TILE_HEIGHT * 2 ||
x < UI_FRAME_TILE_WIDTH || x >= UI_FRAME_TILE_WIDTH * 2
) {
c = border;
} else {
c = center;
}
UI_FRAME.pixels[y * UI_FRAME_TEXTURE_WIDTH_POW2 + x] = c;
}
}
errorChain(textureInit(
&UI_FRAME.texture,
UI_FRAME_TEXTURE_WIDTH_POW2, UI_FRAME_TEXTURE_HEIGHT_POW2,
TEXTURE_FORMAT_RGBA,
(texturedata_t){ .rgbaColors = UI_FRAME.pixels }
));
UI_FRAME.tileset.tileWidth = UI_FRAME_TILE_WIDTH;
UI_FRAME.tileset.tileHeight = UI_FRAME_TILE_HEIGHT;
UI_FRAME.tileset.columns = 3;
UI_FRAME.tileset.rows = 3;
UI_FRAME.tileset.tileCount = 9;
UI_FRAME.tileset.uv[0] =
(float_t)UI_FRAME_TILE_WIDTH / UI_FRAME_TEXTURE_WIDTH_POW2;
UI_FRAME.tileset.uv[1] =
(float_t)UI_FRAME_TILE_HEIGHT / UI_FRAME_TEXTURE_HEIGHT_POW2;
errorOk();
}
errorret_t uiFrameDraw(
const float_t x,
const float_t y,
const float_t width,
const float_t height
) {
shadermaterial_t material = {
.unlit = {
.color = COLOR_WHITE,
.texture = &UI_FRAME.texture
}
};
spritebatchsprite_t sprites[9];
uiFrameBuildSprites(sprites, x, y, width, height);
return spriteBatchBuffer(sprites, 9, &SHADER_UNLIT, material);
}
void uiFrameBuildSprites(
spritebatchsprite_t sprites[9],
const float_t x,
const float_t y,
const float_t width,
const float_t height
) {
float_t tileW = (float_t)UI_FRAME_BORDER_WIDTH;
float_t tileH = (float_t)UI_FRAME_BORDER_HEIGHT;
sprites[0] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 0, 0,
x, y, tileW, tileH
);
sprites[1] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 1, 0,
x + tileW, y, width - (tileW * 2.0f), tileH
);
sprites[2] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 2, 0,
x + width - tileW, y, tileW, tileH
);
sprites[3] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 0, 1,
x, y + tileH, tileW, height - (tileH * 2.0f)
);
sprites[4] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 1, 1,
x + tileW, y + tileH,
width - (tileW * 2.0f), height - (tileH * 2.0f)
);
sprites[5] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 2, 1,
x + width - tileW, y + tileH, tileW, height - (tileH * 2.0f)
);
sprites[6] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 0, 2,
x, y + height - tileH, tileW, tileH
);
sprites[7] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 1, 2,
x + tileW, y + height - tileH, width - (tileW * 2.0f), tileH
);
sprites[8] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 2, 2,
x + width - tileW, y + height - tileH, tileW, tileH
);
}
errorret_t uiFrameDrawCached(
uiframecache_t *cache,
const float_t x,
const float_t y,
const float_t width,
const float_t height
) {
assertNotNull(cache, "Frame cache cannot be NULL");
if(
!cache->built ||
cache->lastX != x || cache->lastY != y ||
cache->lastWidth != width || cache->lastHeight != height
) {
uiFrameBuildSprites(cache->sprites, x, y, width, height);
cache->lastX = x;
cache->lastY = y;
cache->lastWidth = width;
cache->lastHeight = height;
cache->built = true;
}
shadermaterial_t material = {
.unlit = {
.color = COLOR_WHITE,
.texture = &UI_FRAME.texture
}
};
return spriteBatchBuffer(cache->sprites, 9, &SHADER_UNLIT, material);
}
errorret_t uiFrameDispose(void) {
return textureDispose(&UI_FRAME.texture);
}
+122
View File
@@ -0,0 +1,122 @@
/**
* 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 "display/texture/texture.h"
#include "display/texture/tileset.h"
#include "display/spritebatch/spritebatchsprite.h"
#define UI_FRAME_BORDER_WIDTH 6
#define UI_FRAME_BORDER_HEIGHT 6
#define UI_FRAME_PADDING_X 2
#define UI_FRAME_PADDING_Y 2
#define UI_FRAME_START_X (UI_FRAME_BORDER_WIDTH + UI_FRAME_PADDING_X)
#define UI_FRAME_START_Y (UI_FRAME_BORDER_HEIGHT + UI_FRAME_PADDING_Y)
#define UI_FRAME_TILE_WIDTH 1
#define UI_FRAME_TILE_HEIGHT 1
#define UI_FRAME_TEXTURE_WIDTH (UI_FRAME_TILE_WIDTH * 3)
#define UI_FRAME_TEXTURE_HEIGHT (UI_FRAME_TILE_HEIGHT * 3)
#define UI_FRAME_TEXTURE_WIDTH_POW2 4
#define UI_FRAME_TEXTURE_HEIGHT_POW2 4
typedef struct {
tileset_t tileset;
texture_t texture;
color_t pixels[UI_FRAME_BORDER_WIDTH * UI_FRAME_BORDER_HEIGHT];
} uiframe_t;
extern uiframe_t UI_FRAME;
/**
* Initializes the global UI_FRAME: builds the dummy texture and
* configures the tileset. Call once after displayInit().
*
* @return Any error that occurs.
*/
errorret_t uiFrameInit(void);
/**
* Draws UI_FRAME using 9-slice rendering from its 3x3 tileset.
* Pushes quads to the sprite batch without flushing.
*
* @param x Screen x position.
* @param y Screen y position.
* @param width Total width of the frame.
* @param height Total height of the frame.
* @return Any error that occurs.
*/
errorret_t uiFrameDraw(
const float_t x,
const float_t y,
const float_t width,
const float_t height
);
/**
* Builds the 9 sprites for a 9-slice frame at the given rect. Used
* internally by uiFrameDraw and uiFrameDrawCached -- call directly only
* if you need the raw sprites instead of buffering them.
*
* @param sprites Destination array of exactly 9 sprites.
* @param x Screen x position.
* @param y Screen y position.
* @param width Total width of the frame.
* @param height Total height of the frame.
*/
void uiFrameBuildSprites(
spritebatchsprite_t sprites[9],
const float_t x,
const float_t y,
const float_t width,
const float_t height
);
/**
* A frame's cached 9-slice sprites, plus the rect they were built for.
* Owned by whichever widget/screen draws a frame repeatedly (dialogs,
* textboxes, settings panels) so uiFrameDrawCached can skip rebuilding
* the sprites when the rect hasn't moved since the last draw.
*/
typedef struct {
spritebatchsprite_t sprites[9];
bool_t built;
float_t lastX;
float_t lastY;
float_t lastWidth;
float_t lastHeight;
} uiframecache_t;
/**
* Draws a 9-slice frame using a caller-owned cache, only rebuilding the
* sprites (via uiFrameBuildSprites) when x/y/width/height differ from
* the last call -- unlike uiFrameDraw, which rebuilds unconditionally
* every time. Prefer this for frames redrawn every frame at a fixed or
* rarely-changing rect (dialogs, panels); use plain uiFrameDraw for
* genuinely one-off or per-frame-varying rects.
*
* @param cache Caller-owned cache, zero-initialized before first use.
* @param x Screen x position.
* @param y Screen y position.
* @param width Total width of the frame.
* @param height Total height of the frame.
* @return Any error that occurs.
*/
errorret_t uiFrameDrawCached(
uiframecache_t *cache,
const float_t x,
const float_t y,
const float_t width,
const float_t height
);
/**
* Disposes of the global UI_FRAME, releasing its GPU texture.
*
* @return Any error that occurs.
*/
errorret_t uiFrameDispose(void);
+11
View File
@@ -0,0 +1,11 @@
# 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
uicrop.c
uifullbox.c
uiloading.c
)
@@ -85,5 +85,5 @@ errorret_t uiCropDraw(void) {
}
};
errorChain(spriteBatchBuffer(sprites, count, &SHADER_UNLIT, material));
return spriteBatchFlush();
errorOk();
}
+122
View File
@@ -0,0 +1,122 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uifullbox.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "time/time.h"
#include "display/screen/screen.h"
#include "display/texture/texture.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
uifullbox_t UI_FULLBOX_UNDER;
uifullbox_t UI_FULLBOX_OVER;
void uiFullboxInit(uifullbox_t *fullbox) {
assertNotNull(fullbox, "fullbox must not be NULL");
memoryZero(fullbox, sizeof(uifullbox_t));
eventInit(
&fullbox->onTransitionEnd,
fullbox->onTransitionEndCallbacks,
fullbox->onTransitionEndUsers,
4
);
}
void uiFullboxUpdate(uifullbox_t *fullbox, float_t delta) {
assertNotNull(fullbox, "fullbox must not be NULL");
if(fullbox->duration <= 0.0f || fullbox->time >= fullbox->duration) return;
fullbox->time += delta;
if(fullbox->time >= fullbox->duration) {
fullbox->time = fullbox->duration;
eventInvoke(&fullbox->onTransitionEnd, fullbox);
}
}
static color_t uiFullboxGetColor(const uifullbox_t *fullbox) {
if(fullbox->duration <= 0.0f || fullbox->time >= fullbox->duration) {
return fullbox->toColor;
}
float_t t = easingApply(fullbox->easing, fullbox->time / fullbox->duration);
return color4b(
(uint8_t)((float_t)fullbox->fromColor.r +
((float_t)fullbox->toColor.r - (float_t)fullbox->fromColor.r) * t),
(uint8_t)((float_t)fullbox->fromColor.g +
((float_t)fullbox->toColor.g - (float_t)fullbox->fromColor.g) * t),
(uint8_t)((float_t)fullbox->fromColor.b +
((float_t)fullbox->toColor.b - (float_t)fullbox->fromColor.b) * t),
(uint8_t)((float_t)fullbox->fromColor.a +
((float_t)fullbox->toColor.a - (float_t)fullbox->fromColor.a) * t)
);
}
errorret_t uiFullboxDraw(uifullbox_t *fullbox) {
assertNotNull(fullbox, "fullbox must not be NULL");
color_t color = uiFullboxGetColor(fullbox);
if(color.a == 0) errorOk();
spritebatchsprite_t sprite = {
.min = { 0.0f, 0.0f, 0.0f },
.max = { (float_t)SCREEN.width, (float_t)SCREEN.height, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
shadermaterial_t material = {
.unlit = {
.color = color,
.texture = &TEXTURE_WHITE
}
};
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
errorOk();
}
void uiFullboxTransition(
uifullbox_t *fullbox,
color_t from,
color_t to,
float_t duration,
easingtype_t easing
) {
assertNotNull(fullbox, "fullbox must not be NULL");
fullbox->fromColor = from;
fullbox->toColor = to;
fullbox->duration = duration;
fullbox->time = 0.0f;
fullbox->easing = easing;
}
errorret_t uiFullboxUnderInit(void) {
uiFullboxInit(&UI_FULLBOX_UNDER);
errorOk();
}
errorret_t uiFullboxUnderUpdate(void) {
uiFullboxUpdate(&UI_FULLBOX_UNDER, TIME.delta);
errorOk();
}
errorret_t uiFullboxUnderDraw(void) {
return uiFullboxDraw(&UI_FULLBOX_UNDER);
}
errorret_t uiFullboxOverInit(void) {
uiFullboxInit(&UI_FULLBOX_OVER);
errorOk();
}
errorret_t uiFullboxOverUpdate(void) {
uiFullboxUpdate(&UI_FULLBOX_OVER, TIME.delta);
errorOk();
}
errorret_t uiFullboxOverDraw(void) {
return uiFullboxDraw(&UI_FULLBOX_OVER);
}
+109
View File
@@ -0,0 +1,109 @@
/**
* 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 "display/color.h"
#include "animation/easing.h"
#include "event/event.h"
typedef struct {
color_t fromColor;
color_t toColor;
float_t duration;
float_t time;
easingtype_t easing;
eventcallback_t onTransitionEndCallbacks[4];
void *onTransitionEndUsers[4];
event_t onTransitionEnd;
} uifullbox_t;
extern uifullbox_t UI_FULLBOX_UNDER;
extern uifullbox_t UI_FULLBOX_OVER;
/**
* Initializes a fullbox, zeroing all fields.
*
* @param fullbox The fullbox to initialize.
*/
void uiFullboxInit(uifullbox_t *fullbox);
/**
* Advances the fullbox transition. Fires onTransitionEnd once when the
* transition completes. Safe to call when no transition is running.
*
* @param fullbox The fullbox to update.
* @param delta Seconds elapsed since last update.
*/
void uiFullboxUpdate(uifullbox_t *fullbox, float_t delta);
/**
* Renders the fullbox. Skipped entirely when the current alpha is zero.
*
* @param fullbox The fullbox to draw.
* @return Any error that occurs.
*/
errorret_t uiFullboxDraw(uifullbox_t *fullbox);
/**
* Begins a color transition.
*
* @param fullbox The fullbox to transition.
* @param from Start color.
* @param to End color.
* @param duration Transition duration in seconds.
* @param easing Easing function to apply.
*/
void uiFullboxTransition(
uifullbox_t *fullbox,
color_t from,
color_t to,
float_t duration,
easingtype_t easing
);
/**
* Init function for UI_FULLBOX_UNDER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxUnderInit(void);
/**
* Update function for UI_FULLBOX_UNDER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxUnderUpdate(void);
/**
* Draw function for UI_FULLBOX_UNDER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxUnderDraw(void);
/**
* Init function for UI_FULLBOX_OVER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxOverInit(void);
/**
* Update function for UI_FULLBOX_OVER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxOverUpdate(void);
/**
* Draw function for UI_FULLBOX_OVER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxOverDraw(void);
+111
View File
@@ -0,0 +1,111 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uiloading.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "time/time.h"
#include "display/text/text.h"
#include "display/screen/screen.h"
#include "uifullbox.h"
#define UI_LOADING_TEXT "loading"
uiloading_t UI_LOADING;
errorret_t uiLoadingInit(void) {
memoryZero(&UI_LOADING, sizeof(uiloading_t));
uiLabelInit(&UI_LOADING.textLabel, &FONT_DEFAULT);
uiLabelSetText(&UI_LOADING.textLabel, UI_LOADING_TEXT);
eventInit(
&UI_LOADING.onTransitionEnd,
UI_LOADING.onTransitionEndCallbacks,
UI_LOADING.onTransitionEndUsers,
4
);
errorOk();
}
errorret_t uiLoadingUpdate(void) {
if(UI_LOADING.duration > 0.0f && UI_LOADING.time < UI_LOADING.duration) {
UI_LOADING.time += TIME.delta;
if(UI_LOADING.time >= UI_LOADING.duration) {
UI_LOADING.time = UI_LOADING.duration;
eventInvoke(&UI_LOADING.onTransitionEnd, &UI_LOADING);
}
}
errorOk();
}
errorret_t uiLoadingDraw(void) {
float_t alpha;
if(UI_LOADING.duration <= 0.0f || UI_LOADING.time >= UI_LOADING.duration) {
alpha = UI_LOADING.toAlpha;
} else {
float_t t = UI_LOADING.time / UI_LOADING.duration;
alpha = UI_LOADING.fromAlpha +
(UI_LOADING.toAlpha - UI_LOADING.fromAlpha) * t;
}
if(alpha <= 0.0f) errorOk();
int32_t textW, textH;
uiLabelGetSize(&UI_LOADING.textLabel, &textW, &textH);
float_t x = (float_t)(SCREEN.scanX + SCREEN.scanWidth) -
(float_t)textW - UI_LOADING_MARGIN;
float_t y = (float_t)(SCREEN.scanY + SCREEN.scanHeight) -
(float_t)textH - UI_LOADING_MARGIN;
color_t color = COLOR_WHITE;
color.a = (uint8_t)(alpha * 255.0f);
uiLabelSetColor(&UI_LOADING.textLabel, color);
errorChain(uiLabelDraw(&UI_LOADING.textLabel, x, y));
errorOk();
}
static void uiLoadingTransition(
const float_t from,
const float_t to,
const eventcallback_t callback,
void *user
) {
UI_LOADING.fromAlpha = from;
UI_LOADING.toAlpha = to;
UI_LOADING.duration = UI_LOADING_FADE_DURATION;
UI_LOADING.time = 0.0f;
eventInit(
&UI_LOADING.onTransitionEnd,
UI_LOADING.onTransitionEndCallbacks,
UI_LOADING.onTransitionEndUsers,
4
);
if(callback) eventSubscribe(&UI_LOADING.onTransitionEnd, callback, user);
}
void uiLoadingShow(eventcallback_t callback, void *user) {
uiLoadingTransition(0.0f, 1.0f, callback, user);
uiFullboxTransition(
&UI_FULLBOX_OVER,
COLOR_TRANSPARENT_BLACK,
COLOR_BLACK,
UI_LOADING_FADE_DURATION,
EASING_LINEAR
);
}
void uiLoadingHide(eventcallback_t callback, void *user) {
uiLoadingTransition(1.0f, 0.0f, callback, user);
uiFullboxTransition(
&UI_FULLBOX_OVER,
COLOR_BLACK,
COLOR_TRANSPARENT_BLACK,
UI_LOADING_FADE_DURATION,
EASING_LINEAR
);
}
+65
View File
@@ -0,0 +1,65 @@
/**
* 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 "event/event.h"
#include "ui/widget/uilabel.h"
#define UI_LOADING_FADE_DURATION 0.5f
#define UI_LOADING_MARGIN 8.0f
typedef struct {
float_t fromAlpha;
float_t toAlpha;
float_t duration;
float_t time;
eventcallback_t onTransitionEndCallbacks[4];
void *onTransitionEndUsers[4];
event_t onTransitionEnd;
uilabel_t textLabel;
} uiloading_t;
extern uiloading_t UI_LOADING;
/**
* Initializes the loading indicator.
*
* @return Any error that occurs.
*/
errorret_t uiLoadingInit(void);
/**
* Advances the loading indicator fade transition. Fires onTransitionEnd once
* when the transition completes.
*
* @return Any error that occurs.
*/
errorret_t uiLoadingUpdate(void);
/**
* Draws the loading indicator. No-op when fully transparent.
*
* @return Error state.
*/
errorret_t uiLoadingDraw(void);
/**
* Fades the loading indicator in. Invokes callback when fully visible.
*
* @param callback Called when the fade-in completes. May be NULL.
* @param user Forwarded to the callback unchanged.
*/
void uiLoadingShow(eventcallback_t callback, void *user);
/**
* Fades the loading indicator out. Invokes callback when fully hidden.
*
* @param callback Called when the fade-out completes. May be NULL.
* @param user Forwarded to the callback unchanged.
*/
void uiLoadingHide(eventcallback_t callback, void *user);
+10
View File
@@ -0,0 +1,10 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
uitransition.c
uitransitionfade.c
)
+81
View File
@@ -0,0 +1,81 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uitransition.h"
#include "uitransitionfade.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "time/time.h"
#include "util/math.h"
uitransition_t UI_TRANSITION;
uitransitiondrawfunc_t UI_TRANSITION_TYPE_DRAW[UI_TRANSITION_TYPE_COUNT] = {
[UI_TRANSITION_TYPE_FADE] = uiTransitionFadeDraw
};
errorret_t uiTransitionInit(void) {
memoryZero(&UI_TRANSITION, sizeof(uitransition_t));
// uiTransitionStart((uitransitionstartparams_t){
// .duration = 5.0f,
// .type = UI_TRANSITION_TYPE_FADE,
// .params = {
// .fade = {
// .easing = EASING_OUT_QUART,
// .fromColor = COLOR_TRANSPARENT_BLACK,
// .toColor = COLOR_BLACK
// }
// },
// .finished = NULL,
// .user = NULL
// });
errorOk();
}
errorret_t uiTransitionUpdate(void) {
// Update time.
float_t newTime = UI_TRANSITION.data.time + TIME.delta;
UI_TRANSITION.data.time = mathClamp(
newTime,
0.0f,
UI_TRANSITION.data.duration
);
UI_TRANSITION.data.t = (
(UI_TRANSITION.data.duration <= 0.0f) ?
1.0f :
(UI_TRANSITION.data.time / UI_TRANSITION.data.duration)
);
if(UI_TRANSITION.data.t >= 1.0f && UI_TRANSITION.finished) {
UI_TRANSITION.finished(UI_TRANSITION.user);
}
errorOk();
}
errorret_t uiTransitionDraw(void) {
uitransitiondrawfunc_t draw = UI_TRANSITION_TYPE_DRAW[UI_TRANSITION.type];
if(!draw) errorOk();
return draw(&UI_TRANSITION.data);
}
void uiTransitionStart(const uitransitionstartparams_t info) {
assertTrue(info.type > UI_TRANSITION_TYPE_NULL, "Invalid type");
assertTrue(info.type < UI_TRANSITION_TYPE_COUNT, "Invalid type");
assertTrue(info.duration >= 0.0f, "Duration must be non-negative");
memoryZero(&UI_TRANSITION, sizeof(uitransition_t));
UI_TRANSITION.data.duration = info.duration;
UI_TRANSITION.type = info.type;
UI_TRANSITION.data.params = info.params;
UI_TRANSITION.finished = info.finished;
UI_TRANSITION.user = info.user;
}
+74
View File
@@ -0,0 +1,74 @@
/**
* 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 "display/color.h"
#include "animation/easing.h"
#include "uitransitiondata.h"
typedef void (*uitransitioncallback_t)(void *user);
typedef enum {
UI_TRANSITION_TYPE_NULL,
UI_TRANSITION_TYPE_FADE,
UI_TRANSITION_TYPE_COUNT
} uitransitiontype_t;
extern uitransitiondrawfunc_t UI_TRANSITION_TYPE_DRAW[UI_TRANSITION_TYPE_COUNT];
typedef struct {
uitransitiondata_t data;
uitransitiontype_t type;
uitransitioncallback_t finished;
void *user;
} uitransition_t;
extern uitransition_t UI_TRANSITION;
/**
* Initializes the transition overlay, zeroing all fields and wiring the
* onTransitionEnd event.
*
* @return Any error that occurs.
*/
errorret_t uiTransitionInit(void);
/**
* Advances the transition. Fires onTransitionEnd once when it completes.
* Safe to call when no transition is running.
*
* @return Any error that occurs.
*/
errorret_t uiTransitionUpdate(void);
/**
* Renders the transition overlay. Skipped entirely when the current alpha
* is zero.
*
* @return Any error that occurs.
*/
errorret_t uiTransitionDraw(void);
typedef struct {
float_t duration;
uitransitiontype_t type;
uitransitionparams_t params;
uitransitioncallback_t finished;
void *user;
} uitransitionstartparams_t;
/**
* Starts a transition described by an info struct.
*
* @param info Transition parameters.
*/
void uiTransitionStart(const uitransitionstartparams_t info);
@@ -0,0 +1,23 @@
/**
* 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 "uitransitionfade.h"
typedef union uitransitionparams_u {
uitransitionfade_t fade;
} uitransitionparams_t;
typedef struct uitransitiondata_s {
float_t time;
float_t duration;
float_t t;
uitransitionparams_t params;
} uitransitiondata_t;
typedef errorret_t (*uitransitiondrawfunc_t)(const uitransitiondata_t *data);
@@ -0,0 +1,56 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uitransition.h"
#include "assert/assert.h"
#include "display/screen/screen.h"
#include "display/texture/texture.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
errorret_t uiTransitionFadeDraw(const uitransitiondata_t *data) {
assertNotNull(data, "data must not be NULL");
float_t e = easingApply(data->params.fade.easing, data->t);
float_t r = (float_t)(
data->params.fade.toColor.r - data->params.fade.fromColor.r
) * e;
float_t g = (float_t)(
data->params.fade.toColor.g - data->params.fade.fromColor.g
) * e;
float_t b = (float_t)(
data->params.fade.toColor.b - data->params.fade.fromColor.b
) * e;
float_t a = (float_t)(
data->params.fade.toColor.a - data->params.fade.fromColor.a
) * e;
color_t color = color4b(
data->params.fade.fromColor.r + (uint8_t)r,
data->params.fade.fromColor.g + (uint8_t)g,
data->params.fade.fromColor.b + (uint8_t)b,
data->params.fade.fromColor.a + (uint8_t)a
);
if(color.a == 0) errorOk();
spritebatchsprite_t sprite = {
.min = { 0.0f, 0.0f, 0.0f },
.max = { (float_t)SCREEN.width, (float_t)SCREEN.height, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
shadermaterial_t material = {
.unlit = {
.color = color,
.texture = NULL
}
};
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
errorOk();
}
@@ -0,0 +1,29 @@
/**
* 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 "display/color.h"
#include "animation/easing.h"
typedef struct uitransitiondata_s uitransitiondata_t;
typedef struct {
color_t fromColor;
color_t toColor;
easingtype_t easing;
} uitransitionfade_t;
/**
* Renders a full-screen color overlay interpolated between fade->fromColor
* and fade->toColor using fade->easing. t is the raw normalized progress
* in [0, 1] before easing is applied. No-op when the resulting alpha is zero.
*
* @param fade The fade parameters.
* @return Any error that occurs.
*/
errorret_t uiTransitionFadeDraw(const uitransitiondata_t *fade);
+62
View File
@@ -0,0 +1,62 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "ui.h"
#include "util/memory.h"
#include "assert/assert.h"
#include "display/spritebatch/spritebatch.h"
#include "display/screen/screen.h"
#include "ui/uielement.h"
#include "ui/focus/uifocus.h"
ui_t UI;
errorret_t uiInit(void) {
memoryZero(&UI, sizeof(ui_t));
uiFocusInit();
uiElementsSort();
uielement_t *element = &UI_ELEMENTS[0];
while(!uiElementIsNull(element)) {
errorChain(uiElementInit(element));
element++;
}
errorOk();
}
errorret_t uiUpdate(void) {
uiFocusUpdate();
uielement_t *element = &UI_ELEMENTS[0];
while(!uiElementIsNull(element)) {
errorChain(uiElementUpdate(element));
element++;
}
errorOk();
}
errorret_t uiRender(void) {
const uielement_t *element = &UI_ELEMENTS[0];
while(!uiElementIsNull(element)) {
errorChain(uiElementDraw(element));
element++;
}
errorChain(spriteBatchFlush());
errorOk();
}
errorret_t uiDispose(void) {
uielement_t *element = &UI_ELEMENTS[0];
while(!uiElementIsNull(element)) {
errorChain(uiElementDispose(element));
element++;
}
errorOk();
}
+41
View File
@@ -0,0 +1,41 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
typedef struct {
void *nothing;
} ui_t;
extern ui_t UI;
/**
* Initializes the UI system.
*/
errorret_t uiInit(void);
/**
* Updates the UI system.
*
* @return Any error that occurs.
*/
errorret_t uiUpdate(void);
/**
* Renders the UI system.
*
* @return Any error that occurs.
*/
errorret_t uiRender(void);
/**
* Disposes of the UI system.
*
* @return Any error that occurs.
*/
errorret_t uiDispose(void);
+86
View File
@@ -0,0 +1,86 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uielement.h"
#include "assert/assert.h"
#include "util/sort.h"
#include "ui/frame/uiframe.h"
#include "ui/debug/uifps.h"
#include "engine/engine.h"
#include "ui/overlay/uifullbox.h"
#include "ui/overlay/uiloading.h"
#include "ui/overlay/uicrop.h"
#include "ui/transition/uitransition.h"
#include "ui/debug/uiconsole.h"
#include "ui/frame/uiconfirm.h"
// Priming pass: X does nothing here, so this only exists to process any
// #include directives nested in uielementlist.h/ui/uielementgame.h at
// file scope (each such header's own #pragma once makes it a no-op on
// the real pass below, which happens inside UI_ELEMENTS[]'s braces,
// where a raw #include of a declaration would be invalid).
#define X(initFn, updateFn, drawFn, disposeFn, order) // do nothing
#include "uielementlist.h"
#undef X
uielement_t UI_ELEMENTS[] = {
#define X(initFn, updateFn, drawFn, disposeFn, elementOrder) \
{ \
.init = initFn, .update = updateFn, .draw = drawFn, \
.dispose = disposeFn, .order = elementOrder \
},
#include "uielementlist.h"
#undef X
{ 0 } // Null terminator
};
bool_t uiElementIsNull(const uielement_t *element) {
return element->init == NULL &&
element->update == NULL &&
element->draw == NULL &&
element->dispose == NULL;
}
int_t uiElementCompareOrder(const void *a, const void *b) {
const uielement_t *elementA = (const uielement_t *)a;
const uielement_t *elementB = (const uielement_t *)b;
if(elementA->order < elementB->order) return -1;
if(elementA->order > elementB->order) return 1;
return 0;
}
void uiElementsSort(void) {
// The trailing null terminator is always the last static entry -- sort
// everything before it, and leave it in place.
const size_t count = (sizeof(UI_ELEMENTS) / sizeof(UI_ELEMENTS[0])) - 1;
sortBubble(UI_ELEMENTS, count, sizeof(uielement_t), uiElementCompareOrder);
}
errorret_t uiElementInit(uielement_t *element) {
assertNotNull(element, "element must not be NULL");
if(element->init != NULL) errorChain(element->init());
errorOk();
}
errorret_t uiElementUpdate(uielement_t *element) {
assertNotNull(element, "element must not be NULL");
if(element->update != NULL) errorChain(element->update());
errorOk();
}
errorret_t uiElementDraw(const uielement_t *element) {
assertNotNull(element, "element must not be NULL");
if(element->draw != NULL) errorChain(element->draw());
errorOk();
}
errorret_t uiElementDispose(uielement_t *element) {
assertNotNull(element, "element must not be NULL");
if(element->dispose != NULL) errorChain(element->dispose());
errorOk();
}
+84
View File
@@ -0,0 +1,84 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
// Built-in order tiers. Lower values update/render first; ties preserve
// their relative UI_ELEMENTS declaration order (uiElementsSort uses a
// stable sort). Game-specific elements can use any int32_t value -- these
// are just the ones the engine itself relies on.
#define UI_ELEMENT_ORDER_DEFAULT 0
#define UI_ELEMENT_ORDER_DEBUG 1000
typedef struct {
errorret_t (*init)();
errorret_t (*update)();
errorret_t (*draw)();
errorret_t (*dispose)();
int32_t order;
} uielement_t;
extern uielement_t UI_ELEMENTS[];
/**
* Returns true when all four callbacks on the element are NULL,
* which marks the end of the UI_ELEMENTS array.
*
* @param element The element to test.
* @returns True if the element is the null terminator.
*/
bool_t uiElementIsNull(const uielement_t *element);
/**
* Compares two elements by their .order field, ascending. Matches
* sortcompare_t, for use with the project's sort utilities.
*
* @param a First uielement_t to compare.
* @param b Second uielement_t to compare.
* @return Negative if a < b, zero if a == b, positive if a > b.
*/
int_t uiElementCompareOrder(const void *a, const void *b);
/**
* Stably sorts UI_ELEMENTS in place by .order, ascending. The trailing
* null terminator is never moved. Called once by uiInit -- element order
* is static after that, so there's no need to re-sort every frame.
*/
void uiElementsSort(void);
/**
* Initializes a UI element, invoking its init callback if set.
*
* @param element The element to initialize.
* @return Any error that occurs.
*/
errorret_t uiElementInit(uielement_t *element);
/**
* Updates a UI element, calling its update callback if set.
*
* @param element The element to update.
* @return Any error that occurs.
*/
errorret_t uiElementUpdate(uielement_t *element);
/**
* Draws a UI element, calling its draw callback if set.
*
* @param element The element to render.
* @return Any error that occurs.
*/
errorret_t uiElementDraw(const uielement_t *element);
/**
* Disposes of a UI element, invoking its dispose callback if set.
*
* @param element The element to dispose.
* @return Any error that occurs.
*/
errorret_t uiElementDispose(uielement_t *element);
+47
View File
@@ -0,0 +1,47 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
// X(init, update, draw, dispose, order) -- pass NULL for any callback the
// element doesn't need. order controls update/draw sequence (lower first,
// see UI_ELEMENT_ORDER_* in uielement.h); ties preserve declaration order.
// See uielement.c for how this expands.
X(uiFrameInit, NULL, NULL, uiFrameDispose, UI_ELEMENT_ORDER_DEFAULT)
// Fullbox under: above scene, below system UI.
X(
uiFullboxUnderInit, uiFullboxUnderUpdate, uiFullboxUnderDraw, NULL,
UI_ELEMENT_ORDER_DEFAULT
)
// Text stuffs
X(uiConfirmInit, NULL, uiConfirmDraw, uiConfirmDispose, UI_ELEMENT_ORDER_DEFAULT)
X(
uiTransitionInit, uiTransitionUpdate, uiTransitionDraw, NULL,
UI_ELEMENT_ORDER_DEFAULT
)
// Fullbox over: above absolutely everything (except debug).
X(
uiFullboxOverInit, uiFullboxOverUpdate, uiFullboxOverDraw, NULL,
UI_ELEMENT_ORDER_DEFAULT
)
X(
uiLoadingInit, uiLoadingUpdate, uiLoadingDraw, NULL,
UI_ELEMENT_ORDER_DEFAULT
)
X(uiCropInit, NULL, uiCropDraw, NULL, UI_ELEMENT_ORDER_DEFAULT)
// Debug items -- always last.
X(NULL, NULL, uiConsoleDraw, uiConsoleDispose, UI_ELEMENT_ORDER_DEBUG)
X(uiFPSInit, NULL, uiFPSDraw, NULL, UI_ELEMENT_ORDER_DEBUG)
// Game-specific UI elements (duskrpg)
#include "ui/uielementgame.h"
+17
View File
@@ -0,0 +1,17 @@
# 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
uibutton.c
uicheckbox.c
uitab.c
uislider.c
uidropdown.c
uiscrolling.c
uimenu.c
uilabel.c
uiwidgetlabel.c
)
@@ -7,15 +7,15 @@
#include "uibutton.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "display/text/text.h"
#include "display/color.h"
void uiButtonInit(uibutton_t *button, const char_t *label) {
assertNotNull(button, "Button cannot be NULL");
assertNotNull(label, "Label cannot be NULL");
memoryZero(button, sizeof(uibutton_t));
button->label = label;
uiWidgetLabelInit(&button->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&button->label, label);
button->highlighted = false;
}
bool_t uiButtonIsHighlighted(const uibutton_t *button) {
@@ -26,6 +26,9 @@ bool_t uiButtonIsHighlighted(const uibutton_t *button) {
void uiButtonSetHighlighted(uibutton_t *button, const bool_t highlighted) {
assertNotNull(button, "Button cannot be NULL");
button->highlighted = highlighted;
uiWidgetLabelSetColor(
&button->label, highlighted ? COLOR_RED : COLOR_WHITE
);
}
errorret_t uiButtonDraw(
@@ -34,10 +37,6 @@ errorret_t uiButtonDraw(
const float_t y
) {
assertNotNull(button, "Button cannot be NULL");
errorChain(textDraw(
x, y, button->label,
button->highlighted ? COLOR_RED : COLOR_WHITE,
&FONT_DEFAULT
));
errorChain(uiWidgetLabelDraw(&button->label, x, y));
errorOk();
}
@@ -7,9 +7,10 @@
#pragma once
#include "error/error.h"
#include "ui/widget/uiwidgetlabel.h"
typedef struct {
const char_t *label;
uiwidgetlabel_t label;
bool_t highlighted;
} uibutton_t;
@@ -7,6 +7,7 @@
#include "uicheckbox.h"
#include "util/memory.h"
#include "util/string.h"
#include "display/text/text.h"
#include "display/color.h"
@@ -15,7 +16,9 @@ void uiCheckboxInit(
const char_t *label
) {
memoryZero(checkbox, sizeof(uicheckbox_t));
checkbox->label = label;
checkbox->rawLabel = label;
uiWidgetLabelInit(&checkbox->label, &FONT_DEFAULT);
uiCheckboxRebuildLabel(checkbox);
}
bool_t uiCheckboxIsChecked(const uicheckbox_t *checkbox) {
@@ -24,6 +27,7 @@ bool_t uiCheckboxIsChecked(const uicheckbox_t *checkbox) {
void uiCheckboxSetChecked(uicheckbox_t *checkbox, const bool_t checked) {
checkbox->checked = checked;
uiCheckboxRebuildLabel(checkbox);
}
void uiCheckboxToggle(uicheckbox_t *checkbox) {
@@ -36,6 +40,9 @@ bool_t uiCheckboxIsHighlighted(const uicheckbox_t *checkbox) {
void uiCheckboxSetHighlighted(uicheckbox_t *checkbox, const bool_t highlighted) {
checkbox->highlighted = highlighted;
uiWidgetLabelSetColor(
&checkbox->label, highlighted ? COLOR_RED : COLOR_WHITE
);
}
errorret_t uiCheckboxDraw(
@@ -43,15 +50,15 @@ errorret_t uiCheckboxDraw(
const float_t x,
const float_t y
) {
color_t color = checkbox->highlighted ? COLOR_RED : COLOR_WHITE;
const char_t *mark = checkbox->checked ? "Y " : "N ";
errorChain(textDraw(x, y, mark, color, &FONT_DEFAULT));
int32_t markW, markH;
textMeasure(mark, &FONT_DEFAULT, &markW, &markH);
errorChain(textDraw(
x + (float_t)markW, y, checkbox->label, color, &FONT_DEFAULT
));
errorChain(uiWidgetLabelDraw(&checkbox->label, x, y));
errorOk();
}
void uiCheckboxRebuildLabel(uicheckbox_t *checkbox) {
char_t combined[UI_WIDGET_LABEL_TEXT_MAX];
stringFormat(
combined, UI_WIDGET_LABEL_TEXT_MAX - 1, "%s %s",
checkbox->checked ? "Y" : "N", checkbox->rawLabel
);
uiWidgetLabelSetText(&checkbox->label, combined);
}
@@ -7,9 +7,11 @@
#pragma once
#include "error/error.h"
#include "ui/widget/uiwidgetlabel.h"
typedef struct uicheckbox_s {
const char_t *label;
const char_t *rawLabel;
uiwidgetlabel_t label;
bool_t checked;
bool_t highlighted;
} uicheckbox_t;
@@ -77,3 +79,12 @@ errorret_t uiCheckboxDraw(
const float_t x,
const float_t y
);
/**
* Rebuilds the checkbox's cached label ("Y "/"N " mark plus rawLabel)
* from its current checked state. Called internally whenever checked
* changes.
*
* @param checkbox The checkbox to update.
*/
void uiCheckboxRebuildLabel(uicheckbox_t *checkbox);
@@ -25,13 +25,13 @@ void uiDropdownInit(
assertTrue(optionCount > 0, "Dropdown must have at least one option");
memoryZero(dropdown, sizeof(uidropdown_t));
dropdown->label = label;
uiWidgetLabelInit(&dropdown->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&dropdown->label, label);
uiWidgetLabelInit(&dropdown->value, &FONT_DEFAULT);
dropdown->options = options;
dropdown->optionCount = optionCount;
dropdown->selectedIndex = selectedIndex < optionCount ? selectedIndex : 0;
textMeasure(
label, &FONT_DEFAULT, &dropdown->labelWidth, &dropdown->labelHeight
);
uiDropdownRebuildValue(dropdown);
}
uint8_t uiDropdownGetSelectedIndex(const uidropdown_t *dropdown) {
@@ -48,18 +48,21 @@ void uiDropdownSetSelectedIndex(uidropdown_t *dropdown, const uint8_t index) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
assertTrue(index < dropdown->optionCount, "Dropdown index out of range");
dropdown->selectedIndex = index;
uiDropdownRebuildValue(dropdown);
}
void uiDropdownStepNext(uidropdown_t *dropdown) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
dropdown->selectedIndex =
(dropdown->selectedIndex + 1) % dropdown->optionCount;
uiDropdownRebuildValue(dropdown);
}
void uiDropdownStepPrev(uidropdown_t *dropdown) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
dropdown->selectedIndex = dropdown->selectedIndex == 0 ?
dropdown->optionCount - 1 : dropdown->selectedIndex - 1;
uiDropdownRebuildValue(dropdown);
}
bool_t uiDropdownIsHighlighted(const uidropdown_t *dropdown) {
@@ -73,6 +76,9 @@ void uiDropdownSetHighlighted(
) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
dropdown->highlighted = highlighted;
color_t color = highlighted ? COLOR_RED : COLOR_WHITE;
uiWidgetLabelSetColor(&dropdown->label, color);
uiWidgetLabelSetColor(&dropdown->value, color);
}
errorret_t uiDropdownDraw(
@@ -82,20 +88,23 @@ errorret_t uiDropdownDraw(
) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
color_t color = dropdown->highlighted ? COLOR_RED : COLOR_WHITE;
errorChain(uiWidgetLabelDraw(&dropdown->label, x, y));
errorChain(textDraw(x, y, dropdown->label, color, &FONT_DEFAULT));
int32_t labelW, labelH;
uiWidgetLabelGetSize(&dropdown->label, &labelW, &labelH);
char_t valueText[UI_DROPDOWN_VALUE_TEXT_MAX];
stringFormat(
valueText, UI_DROPDOWN_VALUE_TEXT_MAX - 1, "< %s >",
uiDropdownGetSelectedOption(dropdown)
);
errorChain(textDraw(
x + (float_t)dropdown->labelWidth + UI_DROPDOWN_GAP, y, valueText, color,
&FONT_DEFAULT
errorChain(uiWidgetLabelDraw(
&dropdown->value, x + (float_t)labelW + UI_DROPDOWN_GAP, y
));
errorOk();
}
void uiDropdownRebuildValue(uidropdown_t *dropdown) {
char_t valueText[UI_WIDGET_LABEL_TEXT_MAX];
stringFormat(
valueText, UI_WIDGET_LABEL_TEXT_MAX - 1, "< %s >",
uiDropdownGetSelectedOption(dropdown)
);
uiWidgetLabelSetText(&dropdown->value, valueText);
}
@@ -7,18 +7,17 @@
#pragma once
#include "error/error.h"
#include "ui/widget/uiwidgetlabel.h"
#define UI_DROPDOWN_GAP 4.0f
#define UI_DROPDOWN_VALUE_TEXT_MAX 64
typedef struct {
const char_t *label;
uiwidgetlabel_t label;
uiwidgetlabel_t value;
const char_t *const *options;
uint8_t optionCount;
uint8_t selectedIndex;
bool_t highlighted;
int32_t labelWidth;
int32_t labelHeight;
} uidropdown_t;
/**
@@ -113,3 +112,12 @@ errorret_t uiDropdownDraw(
const float_t x,
const float_t y
);
/**
* Rebuilds the dropdown's cached value label ("< option >") from its
* current selectedIndex. Called internally whenever selectedIndex
* changes.
*
* @param dropdown The dropdown to update.
*/
void uiDropdownRebuildValue(uidropdown_t *dropdown);
+70
View File
@@ -0,0 +1,70 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uilabel.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "display/text/text.h"
void uiLabelInit(uilabel_t *label, font_t *font) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(font, "Font cannot be NULL");
memoryZero(label, sizeof(uilabel_t));
label->font = font;
label->color = COLOR_WHITE;
}
void uiLabelSetText(uilabel_t *label, const char_t *text) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(text, "Text cannot be NULL");
assertStrLenMax(text, UI_LABEL_TEXT_MAX, "Label text too long");
stringCopy(label->text, text, UI_LABEL_TEXT_MAX);
label->spriteCount = textBuildSpriteCache(
label->text, label->font, label->sprites, UI_LABEL_SPRITE_COUNT_MAX,
&label->width, &label->height
);
}
void uiLabelSetColor(uilabel_t *label, const color_t color) {
assertNotNull(label, "Label cannot be NULL");
label->color = color;
}
void uiLabelGetSize(
const uilabel_t *label,
int32_t *outWidth,
int32_t *outHeight
) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(outWidth, "Output width cannot be NULL");
assertNotNull(outHeight, "Output height cannot be NULL");
*outWidth = label->width;
*outHeight = label->height;
}
errorret_t uiLabelDraw(
const uilabel_t *label,
const float_t x,
const float_t y
) {
assertNotNull(label, "Label cannot be NULL");
if(label->spriteCount == 0) errorOk();
// Cached sprites are relative to (0,0); textDrawSpriteCache translates
// into the requested screen position here instead of in
// uiLabelSetText, so a label can be repositioned every frame without
// rebuilding the (much more expensive) glyph/UV cache.
spritebatchsprite_t scratch[UI_LABEL_SPRITE_COUNT_MAX];
errorChain(textDrawSpriteCache(
label->sprites, label->spriteCount, scratch, x, y, label->color,
label->font->texture
));
errorOk();
}
+85
View File
@@ -0,0 +1,85 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "display/text/font.h"
#include "display/spritebatch/spritebatchsprite.h"
#include "display/color.h"
#define UI_LABEL_TEXT_MAX 256
#define UI_LABEL_SPRITE_COUNT_MAX UI_LABEL_TEXT_MAX
typedef struct {
char_t text[UI_LABEL_TEXT_MAX];
color_t color;
font_t *font;
spritebatchsprite_t sprites[UI_LABEL_SPRITE_COUNT_MAX];
uint32_t spriteCount;
int32_t width;
int32_t height;
} uilabel_t;
/**
* Initializes a label, defaulting to white text and no text set.
*
* @param label The label to initialize.
* @param font Font to use for rendering. Must outlive the label.
*/
void uiLabelInit(uilabel_t *label, font_t *font);
/**
* Sets the label's text, rebuilding its cached sprites (glyph lookup, UV,
* and layout) immediately. This is the only way the sprite cache gets
* rebuilt -- uiLabelDraw never recomputes it, so call this whenever the
* text changes rather than once up front and expecting it to stay in sync.
*
* @param label The label to update.
* @param text Null-terminated string to display. Must be shorter than
* UI_LABEL_TEXT_MAX.
*/
void uiLabelSetText(uilabel_t *label, const char_t *text);
/**
* Sets the label's tint color. Cheap -- doesn't touch the sprite cache,
* since color is applied via the draw material, not baked into sprites.
*
* @param label The label to update.
* @param color The new tint color.
*/
void uiLabelSetColor(uilabel_t *label, const color_t color);
/**
* Gets the measured size (in pixels) of the label's current text, cached
* from the last uiLabelSetText call.
*
* @param label The label to query.
* @param outWidth Pointer to store the width.
* @param outHeight Pointer to store the height.
*/
void uiLabelGetSize(
const uilabel_t *label,
int32_t *outWidth,
int32_t *outHeight
);
/**
* Draws the label's cached sprites at the given screen position in a
* single batched buffer call. Does not recompute glyph layout -- call
* uiLabelSetText first whenever the text changes.
*
* @param label The label to draw.
* @param x Screen x position.
* @param y Screen y position.
* @return Any error that occurs.
*/
errorret_t uiLabelDraw(
const uilabel_t *label,
const float_t x,
const float_t y
);
@@ -10,6 +10,7 @@
#include "util/memory.h"
#include "display/text/text.h"
#include "display/color.h"
#include "ui/widget/uiwidgetlabel.h"
#include "ui/widget/uibutton.h"
#include "ui/widget/uitab.h"
#include "ui/widget/uislider.h"
@@ -102,12 +103,8 @@ errorret_t uiMenuDraw(
if(item->type == UI_MENU_WIDGET_TYPE_LABEL) {
if(col > 0) { row++; col = 0; }
errorChain(textDraw(
x,
y + (float_t)row * rowHeight,
item->label,
COLOR_WHITE,
&FONT_DEFAULT
errorChain(uiWidgetLabelDraw(
&item->label, x, y + (float_t)row * rowHeight
));
row++;
continue;
@@ -274,6 +271,13 @@ uint8_t uiMenuFocusSlotToIndex(const uimenu_t *menu, const uint8_t slot) {
return 0xFF;
}
void uiMenuLabelInit(uimenuitem_t *item, const char_t *text) {
assertNotNull(item, "Item cannot be NULL");
assertNotNull(text, "Text cannot be NULL");
uiWidgetLabelInit(&item->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&item->label, text);
}
void uiMenuItemSetHighlighted(uimenuitem_t *item, const bool_t highlighted) {
if(item->type == UI_MENU_WIDGET_TYPE_CHECKBOX) {
uiCheckboxSetHighlighted(&item->checkbox, highlighted);
@@ -8,14 +8,13 @@
#pragma once
#include "error/error.h"
#include "ui/focus/uifocus.h"
#include "ui/widget/uiwidgetlabel.h"
#include "ui/widget/uibutton.h"
#include "ui/widget/uicheckbox.h"
#include "ui/widget/uitab.h"
#include "ui/widget/uislider.h"
#include "ui/widget/uidropdown.h"
#define UI_MENU_LABEL_MAX UI_CHECKBOX_LABEL_MAX
typedef struct uimenu_s uimenu_t;
typedef enum {
@@ -32,7 +31,7 @@ typedef enum {
typedef struct {
uimenuwidgettype_t type;
union {
char_t *label;
uiwidgetlabel_t label;
uicheckbox_t checkbox;
uibutton_t button;
uitab_t tab;
@@ -178,6 +177,15 @@ uint8_t uiMenuFocusSlotToIndex(const uimenu_t *menu, const uint8_t slot);
*/
void uiMenuItemSetHighlighted(uimenuitem_t *item, const bool_t highlighted);
/**
* Initializes a menu item as a standalone label, caching its text.
* Used internally by the MENU_LABEL helper macro.
*
* @param item The item to initialize.
* @param text Display text.
*/
void uiMenuLabelInit(uimenuitem_t *item, const char_t *text);
/**
* Internal focus callback - forwards selection to the menu's selected handler.
*
@@ -227,7 +235,7 @@ bool_t uiMenuFocusDirection(
#define MENU_LABEL(text) \
assertTrue(menuIndex < menuCapacity, "Menu item count exceeds capacity"); \
menu->items[menuIndex].type = UI_MENU_WIDGET_TYPE_LABEL; \
menu->items[menuIndex].label = text; \
uiMenuLabelInit(&menu->items[menuIndex], text); \
++menuIndex
#define MENU_SPACER() \
@@ -30,13 +30,16 @@ void uiSliderInitFloat(
assertTrue(step > 0.0f, "Slider step must be greater than zero");
memoryZero(slider, sizeof(uislider_t));
slider->label = label;
uiWidgetLabelInit(&slider->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&slider->label, label);
uiWidgetLabelInit(&slider->valueLabel, &FONT_DEFAULT);
slider->type = UI_SLIDER_TYPE_FLOAT;
slider->min.f = min;
slider->max.f = max;
slider->step.f = step;
slider->value.f = mathClamp(value, min, max);
textMeasure(label, &FONT_DEFAULT, &slider->labelWidth, &slider->labelHeight);
uiSliderRebuildValueLabel(slider);
uiSliderRebuildGeometry(slider);
}
void uiSliderInitInt(
@@ -53,13 +56,16 @@ void uiSliderInitInt(
assertTrue(step > 0, "Slider step must be greater than zero");
memoryZero(slider, sizeof(uislider_t));
slider->label = label;
uiWidgetLabelInit(&slider->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&slider->label, label);
uiWidgetLabelInit(&slider->valueLabel, &FONT_DEFAULT);
slider->type = UI_SLIDER_TYPE_INT;
slider->min.i = min;
slider->max.i = max;
slider->step.i = step;
slider->value.i = mathClamp(value, min, max);
textMeasure(label, &FONT_DEFAULT, &slider->labelWidth, &slider->labelHeight);
uiSliderRebuildValueLabel(slider);
uiSliderRebuildGeometry(slider);
}
float_t uiSliderGetFloat(const uislider_t *slider) {
@@ -82,6 +88,8 @@ void uiSliderSetFloat(uislider_t *slider, const float_t value) {
slider->type == UI_SLIDER_TYPE_FLOAT, "Slider is not a float slider"
);
slider->value.f = mathClamp(value, slider->min.f, slider->max.f);
uiSliderRebuildValueLabel(slider);
uiSliderRebuildGeometry(slider);
}
void uiSliderSetInt(uislider_t *slider, const int32_t value) {
@@ -90,6 +98,8 @@ void uiSliderSetInt(uislider_t *slider, const int32_t value) {
slider->type == UI_SLIDER_TYPE_INT, "Slider is not an int slider"
);
slider->value.i = mathClamp(value, slider->min.i, slider->max.i);
uiSliderRebuildValueLabel(slider);
uiSliderRebuildGeometry(slider);
}
void uiSliderStepUp(uislider_t *slider) {
@@ -140,6 +150,9 @@ bool_t uiSliderIsHighlighted(const uislider_t *slider) {
void uiSliderSetHighlighted(uislider_t *slider, const bool_t highlighted) {
assertNotNull(slider, "Slider cannot be NULL");
slider->highlighted = highlighted;
color_t color = highlighted ? COLOR_RED : COLOR_WHITE;
uiWidgetLabelSetColor(&slider->label, color);
uiWidgetLabelSetColor(&slider->valueLabel, color);
}
errorret_t uiSliderDraw(
@@ -149,42 +162,97 @@ errorret_t uiSliderDraw(
) {
assertNotNull(slider, "Slider cannot be NULL");
color_t color = slider->highlighted ? COLOR_RED : COLOR_WHITE;
errorChain(uiWidgetLabelDraw(&slider->label, x, y));
errorChain(textDraw(x, y, slider->label, color, &FONT_DEFAULT));
float_t trackX = x + (float_t)slider->labelWidth + UI_SLIDER_GAP;
float_t trackY = y + ((float_t)slider->labelHeight - UI_SLIDER_TRACK_HEIGHT) * 0.5f;
spritebatchsprite_t trackSprite = {
.min = { trackX, trackY, 0.0f },
.max = { trackX + UI_SLIDER_TRACK_WIDTH, trackY + UI_SLIDER_TRACK_HEIGHT, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
shadermaterial_t trackMaterial = {
.unlit = {
.color = COLOR_DARK_GRAY,
.texture = &TEXTURE_WHITE
}
};
errorChain(spriteBatchBuffer(&trackSprite, 1, &SHADER_UNLIT, trackMaterial));
spritebatchsprite_t track = spriteBatchSpriteTranslate(
&slider->cachedTrack, x, y
);
errorChain(spriteBatchBuffer(&track, 1, &SHADER_UNLIT, trackMaterial));
if(slider->cachedFillVisible) {
shadermaterial_t fillMaterial = {
.unlit = {
.color = slider->highlighted ? COLOR_RED : COLOR_WHITE,
.texture = &TEXTURE_WHITE
}
};
spritebatchsprite_t fill = spriteBatchSpriteTranslate(
&slider->cachedFill, x, y
);
errorChain(spriteBatchBuffer(&fill, 1, &SHADER_UNLIT, fillMaterial));
}
if(slider->cachedMarkerCount > 0) {
spritebatchsprite_t markers[UI_SLIDER_STEP_MARKERS_MAX];
for(int32_t i = 0; i < slider->cachedMarkerCount; i++) {
markers[i] = spriteBatchSpriteTranslate(&slider->cachedMarkers[i], x, y);
}
shadermaterial_t markerMaterial = {
.unlit = {
.color = COLOR_WHITE,
.texture = &TEXTURE_WHITE
}
};
errorChain(spriteBatchBuffer(
markers, slider->cachedMarkerCount, &SHADER_UNLIT, markerMaterial
));
}
errorChain(uiWidgetLabelDraw(
&slider->valueLabel,
x + slider->cachedTrack.max[0] + UI_SLIDER_GAP,
y
));
errorOk();
}
void uiSliderRebuildValueLabel(uislider_t *slider) {
char_t valueText[UI_WIDGET_LABEL_TEXT_MAX];
if(slider->type == UI_SLIDER_TYPE_INT) {
stringFormat(
valueText, UI_WIDGET_LABEL_TEXT_MAX - 1, "%d", slider->value.i
);
} else {
stringFormat(
valueText, UI_WIDGET_LABEL_TEXT_MAX - 1, "%.2f", slider->value.f
);
}
uiWidgetLabelSetText(&slider->valueLabel, valueText);
}
void uiSliderRebuildGeometry(uislider_t *slider) {
int32_t labelW, labelH;
uiWidgetLabelGetSize(&slider->label, &labelW, &labelH);
float_t trackX = (float_t)labelW + UI_SLIDER_GAP;
float_t trackY = ((float_t)labelH - UI_SLIDER_TRACK_HEIGHT) * 0.5f;
slider->cachedTrack = (spritebatchsprite_t){
.min = { trackX, trackY, 0.0f },
.max = {
trackX + UI_SLIDER_TRACK_WIDTH, trackY + UI_SLIDER_TRACK_HEIGHT, 0.0f
},
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
float_t fillWidth = UI_SLIDER_TRACK_WIDTH * uiSliderGetRatio(slider);
if(fillWidth > 0.0f) {
spritebatchsprite_t fillSprite = {
slider->cachedFillVisible = fillWidth > 0.0f;
if(slider->cachedFillVisible) {
slider->cachedFill = (spritebatchsprite_t){
.min = { trackX, trackY, 0.0f },
.max = { trackX + fillWidth, trackY + UI_SLIDER_TRACK_HEIGHT, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
shadermaterial_t fillMaterial = {
.unlit = {
.color = color,
.texture = &TEXTURE_WHITE
}
};
errorChain(spriteBatchBuffer(&fillSprite, 1, &SHADER_UNLIT, fillMaterial));
}
int32_t stepCount = uiSliderGetStepCount(slider);
@@ -192,7 +260,7 @@ errorret_t uiSliderDraw(
for(int32_t i = 0; i <= stepCount; i++) {
float_t markerX = trackX +
UI_SLIDER_TRACK_WIDTH * (float_t)i / (float_t)stepCount;
spritebatchsprite_t markerSprite = {
slider->cachedMarkers[i] = (spritebatchsprite_t){
.min = {
markerX - UI_SLIDER_STEP_MARKER_WIDTH * 0.5f,
trackY - UI_SLIDER_STEP_MARKER_OVERHANG,
@@ -206,33 +274,9 @@ errorret_t uiSliderDraw(
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
shadermaterial_t markerMaterial = {
.unlit = {
.color = COLOR_WHITE,
.texture = &TEXTURE_WHITE
}
};
errorChain(
spriteBatchBuffer(&markerSprite, 1, &SHADER_UNLIT, markerMaterial)
);
}
}
char_t valueText[UI_SLIDER_VALUE_TEXT_MAX];
if(slider->type == UI_SLIDER_TYPE_INT) {
stringFormat(
valueText, UI_SLIDER_VALUE_TEXT_MAX - 1, "%d", slider->value.i
);
slider->cachedMarkerCount = stepCount + 1;
} else {
stringFormat(
valueText, UI_SLIDER_VALUE_TEXT_MAX - 1, "%.2f", slider->value.f
);
slider->cachedMarkerCount = 0;
}
errorChain(textDraw(
trackX + UI_SLIDER_TRACK_WIDTH + UI_SLIDER_GAP, y,
valueText, color, &FONT_DEFAULT
));
errorOk();
}
@@ -7,13 +7,14 @@
#pragma once
#include "error/error.h"
#include "ui/widget/uiwidgetlabel.h"
#include "display/spritebatch/spritebatchsprite.h"
#define UI_SLIDER_TRACK_WIDTH 80.0f
#define UI_SLIDER_TRACK_HEIGHT 4.0f
#define UI_SLIDER_STEP_MARKER_WIDTH 2.0f
#define UI_SLIDER_STEP_MARKER_OVERHANG 1.0f
#define UI_SLIDER_GAP 4.0f
#define UI_SLIDER_VALUE_TEXT_MAX 16
/**
* Number of discrete steps below which an int slider renders individual
@@ -34,15 +35,24 @@ typedef union {
} uislidervalue_t;
typedef struct {
const char_t *label;
uiwidgetlabel_t label;
uiwidgetlabel_t valueLabel;
uislidertype_t type;
uislidervalue_t value;
uislidervalue_t min;
uislidervalue_t max;
uislidervalue_t step;
bool_t highlighted;
int32_t labelWidth;
int32_t labelHeight;
// Track/fill/marker geometry, cached relative to origin (0,0) and only
// rebuilt when the value or step configuration changes (see
// uiSliderRebuildGeometry) -- uiSliderDraw just translates these into
// position instead of re-deriving them every frame.
spritebatchsprite_t cachedTrack;
spritebatchsprite_t cachedFill;
bool_t cachedFillVisible;
spritebatchsprite_t cachedMarkers[UI_SLIDER_STEP_MARKERS_MAX];
int32_t cachedMarkerCount;
} uislider_t;
/**
@@ -185,3 +195,21 @@ errorret_t uiSliderDraw(
const float_t x,
const float_t y
);
/**
* Rebuilds the slider's cached value label from its current value.
* Called internally whenever value changes.
*
* @param slider The slider to update.
*/
void uiSliderRebuildValueLabel(uislider_t *slider);
/**
* Rebuilds the slider's cached track/fill/marker geometry (relative to
* origin (0,0)) from its current label size, value, and step
* configuration. Called internally on init and whenever the value
* changes -- uiSliderDraw never recomputes this itself.
*
* @param slider The slider to update.
*/
void uiSliderRebuildGeometry(uislider_t *slider);
@@ -7,7 +7,6 @@
#include "uitab.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "display/text/text.h"
#include "display/color.h"
#include "display/spritebatch/spritebatch.h"
@@ -17,9 +16,10 @@
void uiTabInit(uitab_t *tab, const char_t *label) {
assertNotNull(tab, "Tab cannot be NULL");
assertNotNull(label, "Label cannot be NULL");
memoryZero(tab, sizeof(uitab_t));
tab->label = label;
textMeasure(label, &FONT_DEFAULT, &tab->labelWidth, &tab->labelHeight);
uiWidgetLabelInit(&tab->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&tab->label, label);
tab->active = false;
uiTabRebuildBackground(tab);
}
bool_t uiTabIsActive(const uitab_t *tab) {
@@ -39,12 +39,9 @@ errorret_t uiTabDraw(
) {
assertNotNull(tab, "Tab cannot be NULL");
spritebatchsprite_t sprite = {
.min = { x, y, 0.0f },
.max = { x + (float_t)tab->labelWidth, y + (float_t)tab->labelHeight, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
spritebatchsprite_t sprite = spriteBatchSpriteTranslate(
&tab->cachedBackground, x, y
);
shadermaterial_t material = {
.unlit = {
.color = tab->active ? COLOR_GREEN : COLOR_RED,
@@ -52,9 +49,21 @@ errorret_t uiTabDraw(
}
};
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
errorChain(spriteBatchFlush());
errorChain(textDraw(x, y, tab->label, COLOR_WHITE, &FONT_DEFAULT));
errorChain(uiWidgetLabelDraw(&tab->label, x, y));
errorOk();
}
void uiTabRebuildBackground(uitab_t *tab) {
assertNotNull(tab, "Tab cannot be NULL");
int32_t labelW, labelH;
uiWidgetLabelGetSize(&tab->label, &labelW, &labelH);
tab->cachedBackground = (spritebatchsprite_t){
.min = { 0.0f, 0.0f, 0.0f },
.max = { (float_t)labelW, (float_t)labelH, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
}
@@ -7,12 +7,17 @@
#pragma once
#include "error/error.h"
#include "ui/widget/uiwidgetlabel.h"
#include "display/spritebatch/spritebatchsprite.h"
typedef struct {
const char_t *label;
uiwidgetlabel_t label;
bool_t active;
int32_t labelWidth;
int32_t labelHeight;
// Background quad, cached relative to origin (0,0) from the label's
// size at init -- uiTabDraw only translates this into position, since
// active/inactive only changes the material color, not the geometry.
spritebatchsprite_t cachedBackground;
} uitab_t;
/**
@@ -53,3 +58,13 @@ errorret_t uiTabDraw(
const float_t x,
const float_t y
);
/**
* Rebuilds the tab's cached background quad (relative to origin (0,0))
* from its current label size. Called internally by uiTabInit -- the
* background's geometry never changes afterwards, since the tab has no
* API to change its label text.
*
* @param tab The tab to update.
*/
void uiTabRebuildBackground(uitab_t *tab);
+66
View File
@@ -0,0 +1,66 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uiwidgetlabel.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "display/text/text.h"
void uiWidgetLabelInit(uiwidgetlabel_t *label, font_t *font) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(font, "Font cannot be NULL");
memoryZero(label, sizeof(uiwidgetlabel_t));
label->font = font;
label->color = COLOR_WHITE;
}
void uiWidgetLabelSetText(uiwidgetlabel_t *label, const char_t *text) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(text, "Text cannot be NULL");
assertStrLenMax(text, UI_WIDGET_LABEL_TEXT_MAX, "Label text too long");
stringCopy(label->text, text, UI_WIDGET_LABEL_TEXT_MAX);
label->spriteCount = textBuildSpriteCache(
label->text, label->font, label->sprites,
UI_WIDGET_LABEL_SPRITE_COUNT_MAX, &label->width, &label->height
);
}
void uiWidgetLabelSetColor(uiwidgetlabel_t *label, const color_t color) {
assertNotNull(label, "Label cannot be NULL");
label->color = color;
}
void uiWidgetLabelGetSize(
const uiwidgetlabel_t *label,
int32_t *outWidth,
int32_t *outHeight
) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(outWidth, "Output width cannot be NULL");
assertNotNull(outHeight, "Output height cannot be NULL");
*outWidth = label->width;
*outHeight = label->height;
}
errorret_t uiWidgetLabelDraw(
const uiwidgetlabel_t *label,
const float_t x,
const float_t y
) {
assertNotNull(label, "Label cannot be NULL");
if(label->spriteCount == 0) errorOk();
spritebatchsprite_t scratch[UI_WIDGET_LABEL_SPRITE_COUNT_MAX];
errorChain(textDrawSpriteCache(
label->sprites, label->spriteCount, scratch, x, y, label->color,
label->font->texture
));
errorOk();
}
+90
View File
@@ -0,0 +1,90 @@
/**
* 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 "display/text/font.h"
#include "display/spritebatch/spritebatchsprite.h"
#include "display/color.h"
// A cached, cheap-to-redraw label sized for embedding directly inside
// small widgets (buttons, checkboxes, sliders, ...) rather than
// referencing text by pointer and re-deriving glyph geometry every
// frame. Capacity is intentionally much smaller than uilabel_t's -- it
// gets embedded by value in every widget instance (and inside
// uimenuitem_t's union, which is often arrayed), so keeping it small
// matters on memory-constrained targets. See uilabel_t for the
// general-purpose, larger-capacity equivalent.
#define UI_WIDGET_LABEL_TEXT_MAX 64
#define UI_WIDGET_LABEL_SPRITE_COUNT_MAX UI_WIDGET_LABEL_TEXT_MAX
typedef struct {
char_t text[UI_WIDGET_LABEL_TEXT_MAX];
color_t color;
font_t *font;
spritebatchsprite_t sprites[UI_WIDGET_LABEL_SPRITE_COUNT_MAX];
uint32_t spriteCount;
int32_t width;
int32_t height;
} uiwidgetlabel_t;
/**
* Initializes a widget label, defaulting to white text and no text set.
*
* @param label The label to initialize.
* @param font Font to use for rendering. Must outlive the label.
*/
void uiWidgetLabelInit(uiwidgetlabel_t *label, font_t *font);
/**
* Sets the label's text, rebuilding its cached sprites immediately.
* Call this whenever the displayed text changes -- uiWidgetLabelDraw
* never recomputes it.
*
* @param label The label to update.
* @param text Null-terminated string to display. Must be shorter than
* UI_WIDGET_LABEL_TEXT_MAX.
*/
void uiWidgetLabelSetText(uiwidgetlabel_t *label, const char_t *text);
/**
* Sets the label's tint color. Cheap -- doesn't touch the sprite cache.
*
* @param label The label to update.
* @param color The new tint color.
*/
void uiWidgetLabelSetColor(uiwidgetlabel_t *label, const color_t color);
/**
* Gets the measured size (in pixels) of the label's current text, cached
* from the last uiWidgetLabelSetText call.
*
* @param label The label to query.
* @param outWidth Pointer to store the width.
* @param outHeight Pointer to store the height.
*/
void uiWidgetLabelGetSize(
const uiwidgetlabel_t *label,
int32_t *outWidth,
int32_t *outHeight
);
/**
* Draws the label's cached sprites at the given screen position in a
* single batched buffer call. Does not recompute glyph layout.
*
* @param label The label to draw.
* @param x Screen x position.
* @param y Screen y position.
* @return Any error that occurs.
*/
errorret_t uiWidgetLabelDraw(
const uiwidgetlabel_t *label,
const float_t x,
const float_t y
);
+10
View File
@@ -0,0 +1,10 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
uitextbox.c
uitextboxmain.c
)
+276
View File
@@ -0,0 +1,276 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uitextbox.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "time/time.h"
#include "display/text/text.h"
#include "display/color.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
#include "ui/frame/uiframe.h"
void uiTextboxInit(
uitextbox_t *box,
char_t *text,
const uint32_t maxLength,
uitextboxline_t *lines,
const uint32_t linesMax
) {
assertNotNull(box, "Textbox cannot be NULL");
assertNotNull(text, "Text buffer cannot be NULL");
assertTrue(maxLength >= 1, "maxLength must be at least 1");
assertNotNull(lines, "Lines buffer cannot be NULL");
assertTrue(linesMax >= 1, "linesMax must be at least 1");
memoryZero(box, sizeof(uitextbox_t));
box->text = text;
box->maxLength = maxLength;
box->lines = lines;
box->linesMax = linesMax;
box->glyphsBuiltForPage = -1;
}
void uiTextboxSetText(uitextbox_t *box, const char_t *text) {
assertNotNull(box, "Textbox cannot be NULL");
assertNotNull(text, "Text cannot be NULL");
stringCopy(box->text, text, box->maxLength);
box->currentPage = 0;
box->scroll = 0;
box->layoutWidth = 0.0f;
box->layoutHeight = 0.0f;
box->glyphsBuiltForPage = -1;
}
void uiTextboxBuildLayout(
uitextbox_t *box,
const float_t width,
const float_t height
) {
assertNotNull(box, "Textbox cannot be NULL");
box->glyphsBuiltForPage = -1;
box->layoutWidth = width;
box->layoutHeight = height;
box->lineCount = 0;
box->pageCount = 1;
float_t fontW = (float_t)FONT_DEFAULT.tileset->tileWidth;
float_t fontH = (float_t)FONT_DEFAULT.tileset->tileHeight;
if(fontW <= 0.0f || fontH <= 0.0f) return;
box->charsPerLine = (int32_t)(width / fontW);
box->linesPerPage = (int32_t)(height / (fontH + UI_TEXTBOX_LINE_SPACING));
if(box->linesPerPage > UI_TEXTBOX_LINES_PER_PAGE_MAX) {
box->linesPerPage = UI_TEXTBOX_LINES_PER_PAGE_MAX;
}
if(box->charsPerLine <= 0 || box->linesPerPage <= 0) return;
if(box->text[0] == '\0') return;
char_t *src = box->text;
int32_t i = 0;
while(src[i] != '\0' && box->lineCount < (int32_t)box->linesMax) {
if(src[i] == '\t') {
i++;
int32_t rem = box->lineCount % box->linesPerPage;
int32_t pad = rem > 0 ? box->linesPerPage - rem : 0;
while(pad > 0 && box->lineCount < (int32_t)box->linesMax) {
box->lines[box->lineCount].start = i;
box->lines[box->lineCount].count = 0;
box->lineCount++;
pad--;
}
continue;
}
int32_t lineStart = i;
int32_t lineWidth = 0;
while(src[i] != '\0') {
char_t c = src[i];
if(c == '\n') { i++; break; }
if(c == '\t') break;
if(c == ' ') {
int32_t wordLen = 0;
int32_t j = i + 1;
while(
src[j] != ' ' && src[j] != '\n' &&
src[j] != '\t' && src[j] != '\0'
) {
wordLen++;
j++;
}
if(lineWidth > 0 && lineWidth + 1 + wordLen > box->charsPerLine) {
i++;
break;
}
lineWidth++;
i++;
} else {
if(lineWidth >= box->charsPerLine) break;
lineWidth++;
i++;
}
}
box->lines[box->lineCount].start = lineStart;
box->lines[box->lineCount].count = lineWidth;
box->lineCount++;
}
if(box->lineCount == 0) {
box->pageCount = 1;
} else {
box->pageCount =
(box->lineCount + box->linesPerPage - 1) / box->linesPerPage;
}
}
errorret_t uiTextboxUpdate(uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
#ifdef DUSK_TIME_DYNAMIC
if(TIME.dynamicUpdate) errorOk();
#endif
if(!uiTextboxPageIsComplete(box)) {
box->scroll += UI_TEXTBOX_SCROLL_CHARS_PER_TICK;
}
errorOk();
}
errorret_t uiTextboxDraw(
uitextbox_t *box,
const float_t x,
const float_t y,
const float_t width,
const float_t height
) {
assertNotNull(box, "Textbox cannot be NULL");
float_t startX = (float_t)UI_FRAME_START_X;
float_t startY = (float_t)UI_FRAME_START_Y;
float_t contentX = x + startX;
float_t contentY = y + startY;
float_t contentW = width - 2.0f * startX;
float_t contentH = height - 2.0f * startY;
if(contentW != box->layoutWidth || contentH != box->layoutHeight) {
uiTextboxBuildLayout(box, contentW, contentH);
}
errorChain(uiFrameDrawCached(&box->frameCache, x, y, width, height));
if(box->lineCount == 0 || box->text[0] == '\0') errorOk();
if(box->glyphsBuiltForPage != box->currentPage) {
uiTextboxBuildPageGlyphs(box);
}
if(box->glyphCount == 0) errorOk();
int32_t visibleCount = 0;
while(
visibleCount < box->glyphCount &&
box->glyphs[visibleCount].revealAt <= box->scroll
) visibleCount++;
if(visibleCount == 0) errorOk();
spritebatchsprite_t scratch[UI_TEXTBOX_PAGE_GLYPHS_MAX];
for(int32_t i = 0; i < visibleCount; i++) {
scratch[i] = spriteBatchSpriteTranslate(
&box->glyphs[i].sprite, contentX, contentY
);
}
shadermaterial_t material = {
.unlit = {
.color = COLOR_WHITE,
.texture = FONT_DEFAULT.texture
}
};
errorChain(spriteBatchBuffer(scratch, visibleCount, &SHADER_UNLIT, material));
errorOk();
}
void uiTextboxBuildPageGlyphs(uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
box->glyphCount = 0;
int32_t pageFirst = box->currentPage * box->linesPerPage;
int32_t pageLast = pageFirst + box->linesPerPage;
if(pageLast > box->lineCount) pageLast = box->lineCount;
float_t fontW = (float_t)FONT_DEFAULT.tileset->tileWidth;
float_t fontH = (float_t)FONT_DEFAULT.tileset->tileHeight;
int32_t consumed = 0;
for(int32_t li = pageFirst; li < pageLast; li++) {
uitextboxline_t *line = &box->lines[li];
float_t lineY =
(float_t)(li - pageFirst) * (fontH + UI_TEXTBOX_LINE_SPACING);
for(int32_t ci = 0; ci < line->count; ci++) {
consumed++;
char_t c = box->text[line->start + ci];
if(c == ' ') continue;
assertTrue(
box->glyphCount < UI_TEXTBOX_PAGE_GLYPHS_MAX,
"Textbox page produces too many glyphs"
);
uitextboxglyph_t *glyph = &box->glyphs[box->glyphCount++];
glyph->sprite = textGetSprite(
(vec2){ (float_t)ci * fontW, lineY }, c, &FONT_DEFAULT
);
glyph->revealAt = consumed;
}
}
box->glyphsBuiltForPage = box->currentPage;
}
int32_t uiTextboxGetPageCharCount(const uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
int32_t first = box->currentPage * box->linesPerPage;
int32_t last = first + box->linesPerPage;
if(last > box->lineCount) last = box->lineCount;
int32_t total = 0;
for(int32_t i = first; i < last; i++) {
total += box->lines[i].count;
}
return total;
}
bool_t uiTextboxPageIsComplete(const uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
return box->scroll >= uiTextboxGetPageCharCount(box);
}
bool_t uiTextboxHasNextPage(const uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
return box->currentPage + 1 < box->pageCount;
}
void uiTextboxNextPage(uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
if(!uiTextboxHasNextPage(box)) return;
box->currentPage++;
box->scroll = 0;
}
+175
View File
@@ -0,0 +1,175 @@
/**
* 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 "ui/frame/uiframe.h"
#include "display/spritebatch/spritebatchsprite.h"
#define UI_TEXTBOX_LINES_PER_PAGE_MAX 4
#define UI_TEXTBOX_SCROLL_CHARS_PER_TICK 1
#define UI_TEXTBOX_LINE_SPACING 0.0f
// Fixed capacity for a page's cached glyph sprites (see uitextboxglyph_t).
// Sized generously above UI_TEXTBOX_LINES_PER_PAGE_MAX worth of glyphs at
// typical textbox widths; uiTextboxBuildPageGlyphs asserts if a page
// somehow produces more than this.
#define UI_TEXTBOX_PAGE_GLYPHS_MAX 512
typedef struct {
int32_t start;
int32_t count;
} uitextboxline_t;
// A single visible glyph's cached sprite (relative to the textbox's
// content origin, i.e. (0,0)) plus the scroll value at/after which it
// becomes visible -- lets uiTextboxDraw turn the typewriter scroll into
// a simple prefix-count instead of recomputing glyph geometry every
// frame.
typedef struct {
spritebatchsprite_t sprite;
int32_t revealAt;
} uitextboxglyph_t;
typedef struct {
char_t *text;
uint32_t maxLength;
uitextboxline_t *lines;
uint32_t linesMax;
int32_t lineCount;
int32_t charsPerLine;
int32_t linesPerPage;
int32_t pageCount;
// last dimensions used for layout; rebuild triggers when these change
float_t layoutWidth;
float_t layoutHeight;
int32_t currentPage;
int32_t scroll;
// Cached glyph sprites for the current page (see uitextboxglyph_t),
// rebuilt only when currentPage no longer matches
// glyphsBuiltForPage -- not every frame/scroll tick.
uitextboxglyph_t glyphs[UI_TEXTBOX_PAGE_GLYPHS_MAX];
int32_t glyphCount;
int32_t glyphsBuiltForPage;
uiframecache_t frameCache;
} uitextbox_t;
/**
* Initializes a textbox, zeroing all state and binding it to caller-owned
* text and line storage.
*
* @param box The textbox to initialize.
* @param text Caller-owned buffer the textbox copies its text into.
* @param maxLength Capacity of text, in characters.
* @param lines Caller-owned buffer the textbox lays lines out into.
* @param linesMax Capacity of lines, in entries.
*/
void uiTextboxInit(
uitextbox_t *box,
char_t *text,
const uint32_t maxLength,
uitextboxline_t *lines,
const uint32_t linesMax
);
/**
* Copies text into the textbox and marks layout as dirty.
* Resets currentPage and scroll to 0.
*
* @param box The textbox to update.
* @param text Null-terminated source string.
*/
void uiTextboxSetText(uitextbox_t *box, const char_t *text);
/**
* Rebuilds word-wrap and page layout for the given draw dimensions.
* Called automatically by uiTextboxDraw when width or height changes.
*
* @param box The textbox to rebuild.
* @param width Available content width in pixels.
* @param height Available content height in pixels.
*/
void uiTextboxBuildLayout(
uitextbox_t *box,
const float_t width,
const float_t height
);
/**
* Advances the typewriter scroll by UI_TEXTBOX_SCROLL_CHARS_PER_TICK.
* Skipped on dynamic ticks.
*
* @param box The textbox to update.
* @returns Any error that occurs.
*/
errorret_t uiTextboxUpdate(uitextbox_t *box);
/**
* Draws the textbox frame and visible text. Rebuilds layout automatically
* if width or height differs from the last draw call.
*
* @param box The textbox to draw.
* @param x Screen x position.
* @param y Screen y position.
* @param width Draw width in pixels.
* @param height Draw height in pixels.
* @returns Any error that occurs.
*/
errorret_t uiTextboxDraw(
uitextbox_t *box,
const float_t x,
const float_t y,
const float_t width,
const float_t height
);
/**
* Returns the total visible char count for the current page.
*
* @param box The textbox to query.
* @returns Total chars on the current page.
*/
int32_t uiTextboxGetPageCharCount(const uitextbox_t *box);
/**
* Returns true when scroll has fully revealed the current page.
*
* @param box The textbox to query.
* @returns True if the current page is fully visible.
*/
bool_t uiTextboxPageIsComplete(const uitextbox_t *box);
/**
* Returns true when there is at least one more page after the current one.
*
* @param box The textbox to query.
* @returns True if a next page exists.
*/
bool_t uiTextboxHasNextPage(const uitextbox_t *box);
/**
* Advances to the next page and resets scroll to 0.
* Has no effect if already on the last page.
*
* @param box The textbox to advance.
*/
void uiTextboxNextPage(uitextbox_t *box);
/**
* Rebuilds the cached glyph sprites (see uitextboxglyph_t) for the
* current page from its line layout. Called automatically by
* uiTextboxDraw whenever currentPage no longer matches the page the
* cache was last built for.
*
* @param box The textbox to rebuild.
*/
void uiTextboxBuildPageGlyphs(uitextbox_t *box);
+121
View File
@@ -0,0 +1,121 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uitextboxmain.h"
#include "ui/focus/uifocus.h"
#include "display/screen/screen.h"
#include "display/text/text.h"
#include "display/color.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
#include "ui/frame/uiframe.h"
uitextboxmain_t UI_TEXTBOX_MAIN;
static uifocusitem_t *focusItem = NULL;
errorret_t uiTextboxMainInit(void) {
uiTextboxInit(
&UI_TEXTBOX_MAIN.box,
UI_TEXTBOX_MAIN.text, UI_TEXTBOX_MAIN_TEXT_MAX,
UI_TEXTBOX_MAIN.lines, UI_TEXTBOX_MAIN_LINES_MAX
);
errorOk();
}
void uiTextboxMainSetText(const char_t *text) {
uiTextboxSetText(&UI_TEXTBOX_MAIN.box, text);
if(focusItem != NULL) return;
focusItem = uiFocusPush(
1, 1,
uiTextboxMainFocusSelected,
NULL,
uiTextboxMainFocusClosed,
NULL,
NULL
);
}
errorret_t uiTextboxMainUpdate(void) {
if(focusItem == NULL) errorOk();
return uiTextboxUpdate(&UI_TEXTBOX_MAIN.box);
}
errorret_t uiTextboxMainDraw(void) {
if(focusItem == NULL) errorOk();
float_t fontH = (float_t)FONT_DEFAULT.tileset->tileHeight;
float_t h = (float_t)UI_TEXTBOX_MAIN_LINES * fontH +
(float_t)(UI_TEXTBOX_MAIN_LINES - 1) * UI_TEXTBOX_LINE_SPACING +
2.0f * (float_t)UI_FRAME_START_Y;
float_t w = (float_t)SCREEN.scanWidth;
float_t x = (float_t)SCREEN.scanX;
float_t y = (float_t)(SCREEN.scanY + SCREEN.scanHeight) - h;
errorChain(uiTextboxDraw(&UI_TEXTBOX_MAIN.box, x, y, w, h));
if(!uiTextboxPageIsComplete(&UI_TEXTBOX_MAIN.box)) errorOk();
float_t fontW = (float_t)FONT_DEFAULT.tileset->tileWidth;
float_t contentX = x + (float_t)UI_FRAME_START_X;
float_t contentY = y + (float_t)UI_FRAME_START_Y;
float_t contentW = w - 2.0f * (float_t)UI_FRAME_START_X;
float_t contentH = h - 2.0f * (float_t)UI_FRAME_START_Y;
shadermaterial_t material = {
.unlit = {
.color = COLOR_WHITE,
.texture = FONT_DEFAULT.texture
}
};
spritebatchsprite_t caret = textGetSprite(
(vec2){
contentX + contentW - fontW,
contentY + contentH - fontH
},
'v',
&FONT_DEFAULT
);
errorChain(spriteBatchBuffer(&caret, 1, &SHADER_UNLIT, material));
errorOk();
}
bool_t uiTextboxMainPageIsComplete(void) {
return uiTextboxPageIsComplete(&UI_TEXTBOX_MAIN.box);
}
bool_t uiTextboxMainHasNextPage(void) {
return uiTextboxHasNextPage(&UI_TEXTBOX_MAIN.box);
}
void uiTextboxMainNextPage(void) {
uiTextboxNextPage(&UI_TEXTBOX_MAIN.box);
}
bool_t uiTextboxMainIsActive(void) {
return focusItem != NULL;
}
bool_t uiTextboxMainFocusSelected(const uifocusitem_t *item) {
if(!uiTextboxPageIsComplete(&UI_TEXTBOX_MAIN.box)) {
UI_TEXTBOX_MAIN.box.scroll =
uiTextboxGetPageCharCount(&UI_TEXTBOX_MAIN.box);
return true;
}
if(uiTextboxHasNextPage(&UI_TEXTBOX_MAIN.box)) {
uiTextboxNextPage(&UI_TEXTBOX_MAIN.box);
return true;
}
uiFocusPopItem(focusItem);
return true;
}
bool_t uiTextboxMainFocusClosed(const uifocusitem_t *item) {
focusItem = NULL;
return true;
}
@@ -0,0 +1,94 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "uitextbox.h"
#include "ui/focus/uifocusitem.h"
#define UI_TEXTBOX_MAIN_LINES 4
#define UI_TEXTBOX_MAIN_TEXT_MAX 1024
#define UI_TEXTBOX_MAIN_LINES_MAX 64
typedef struct {
uitextbox_t box;
char_t text[UI_TEXTBOX_MAIN_TEXT_MAX];
uitextboxline_t lines[UI_TEXTBOX_MAIN_LINES_MAX];
} uitextboxmain_t;
extern uitextboxmain_t UI_TEXTBOX_MAIN;
/**
* Initializes UI_TEXTBOX_MAIN.
*
* @returns Any error that occurs.
*/
errorret_t uiTextboxMainInit(void);
/**
* Copies text into UI_TEXTBOX_MAIN and resets page and scroll.
*
* @param text Null-terminated source string.
*/
void uiTextboxMainSetText(const char_t *text);
/**
* Advances the typewriter scroll for UI_TEXTBOX_MAIN.
*
* @returns Any error that occurs.
*/
errorret_t uiTextboxMainUpdate(void);
/**
* Draws UI_TEXTBOX_MAIN full-width at the bottom of the screen.
* Position and size are derived from SCREEN each call.
*
* @returns Any error that occurs.
*/
errorret_t uiTextboxMainDraw(void);
/**
* Returns true when the current page is fully scrolled in.
*
* @returns True if the current page is complete.
*/
bool_t uiTextboxMainPageIsComplete(void);
/**
* Returns true when at least one more page follows the current one.
*
* @returns True if a next page exists.
*/
bool_t uiTextboxMainHasNextPage(void);
/**
* Advances UI_TEXTBOX_MAIN to the next page and resets scroll.
* Has no effect if already on the last page.
*/
void uiTextboxMainNextPage(void);
/**
* Returns true when UI_TEXTBOX_MAIN has focus (is visible and active).
*
* @returns True if the textbox is currently active.
*/
bool_t uiTextboxMainIsActive(void);
/**
* Internal focus callback - skip scroll or advance page or dismiss.
*
* @param item The active focus item.
* @returns True.
*/
bool_t uiTextboxMainFocusSelected(const uifocusitem_t *item);
/**
* Internal focus callback - clears the focus item pointer on dismiss.
*
* @param item The focus item being closed.
* @returns True.
*/
bool_t uiTextboxMainFocusClosed(const uifocusitem_t *item);
+35
View File
@@ -0,0 +1,35 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uitestlabel.h"
#include "ui/widget/uilabel.h"
#include "display/text/text.h"
#include "display/screen/screen.h"
#include "engine/engine.h"
uilabel_t UI_TEST_LABEL;
errorret_t uiTestLabelInit() {
uiLabelInit(&UI_TEST_LABEL, &FONT_DEFAULT);
uiLabelSetText(&UI_TEST_LABEL, "duskrpg");
errorOk();
}
errorret_t uiTestLabelDraw() {
int32_t versionWidth, versionHeight;
textMeasure(ENGINE.version, &FONT_DEFAULT, &versionWidth, &versionHeight);
errorChain(uiLabelDraw(
&UI_TEST_LABEL,
(float_t)(SCREEN.scanX + SCREEN.scanWidth - UI_TEST_LABEL.width),
(float_t)(
SCREEN.scanY + SCREEN.scanHeight - versionHeight -
UI_TEST_LABEL.height
)
));
errorOk();
}
+24
View File
@@ -0,0 +1,24 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
/**
* Initializes the test label, a smoke test for the duskrpg-side UI
* element extension point (uielementgame.h).
*
* @return Any error that occurs.
*/
errorret_t uiTestLabelInit();
/**
* Draws the test label above the engine's debug version number.
*
* @return Any error that occurs.
*/
errorret_t uiTestLabelDraw();
+11
View File
@@ -0,0 +1,11 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
include(dusktest)
# Tests
dusktest(test_uiframe.c)
dusktest(test_uislider.c)
dusktest(test_uitab.c)
+68
View File
@@ -0,0 +1,68 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "dusktest.h"
#include "ui/frame/uiframe.h"
static void test_uiFrameBuildSprites_layout(void **state) {
UI_FRAME.tileset = (tileset_t){
.tileWidth = 1,
.tileHeight = 1,
.tileCount = 9,
.columns = 3,
.rows = 3,
.uv = { 0.25f, 0.25f }
};
const float_t x = 100.0f;
const float_t y = 50.0f;
const float_t width = 40.0f;
const float_t height = 30.0f;
const float_t tileW = (float_t)UI_FRAME_BORDER_WIDTH;
const float_t tileH = (float_t)UI_FRAME_BORDER_HEIGHT;
spritebatchsprite_t sprites[9];
uiFrameBuildSprites(sprites, x, y, width, height);
// Top-left corner sits exactly at the rect's origin.
assert_float_equal(sprites[0].min[0], x, 0.0001f);
assert_float_equal(sprites[0].min[1], y, 0.0001f);
assert_float_equal(sprites[0].max[0], x + tileW, 0.0001f);
assert_float_equal(sprites[0].max[1], y + tileH, 0.0001f);
assert_float_equal(sprites[0].uvMin[0], 0.0f, 0.0001f);
assert_float_equal(sprites[0].uvMin[1], 0.0f, 0.0001f);
assert_float_equal(sprites[0].uvMax[0], 0.25f, 0.0001f);
assert_float_equal(sprites[0].uvMax[1], 0.25f, 0.0001f);
// Top-middle edge stretches to fill the width minus both corners.
assert_float_equal(sprites[1].min[0], x + tileW, 0.0001f);
assert_float_equal(sprites[1].max[0], x + width - tileW, 0.0001f);
assert_float_equal(sprites[1].max[1], y + tileH, 0.0001f);
// Center tile fills the remaining interior on both axes.
assert_float_equal(sprites[4].min[0], x + tileW, 0.0001f);
assert_float_equal(sprites[4].min[1], y + tileH, 0.0001f);
assert_float_equal(sprites[4].max[0], x + width - tileW, 0.0001f);
assert_float_equal(sprites[4].max[1], y + height - tileH, 0.0001f);
// Bottom-right corner sits exactly at the rect's far corner, sampling
// tileset column 2, row 2.
assert_float_equal(sprites[8].min[0], x + width - tileW, 0.0001f);
assert_float_equal(sprites[8].min[1], y + height - tileH, 0.0001f);
assert_float_equal(sprites[8].max[0], x + width, 0.0001f);
assert_float_equal(sprites[8].max[1], y + height, 0.0001f);
assert_float_equal(sprites[8].uvMin[0], 0.5f, 0.0001f);
assert_float_equal(sprites[8].uvMin[1], 0.5f, 0.0001f);
}
int main(int argc, char **argv) {
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_uiFrameBuildSprites_layout),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
+114
View File
@@ -0,0 +1,114 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "dusktest.h"
#include "ui/widget/uislider.h"
#include "util/memory.h"
// uiSliderInitFloat/InitInt require a real font (FONT_DEFAULT) to build
// the label's glyph cache, which needs a live GL context this test binary
// doesn't have -- see the label size caching contract for why this is
// safe to bypass here (uiSliderRebuildGeometry only reads slider->label's
// already-measured width/height, it never touches the font itself).
static void sliderSetupFloat(
uislider_t *slider,
const float_t value,
const float_t min,
const float_t max,
const float_t step
) {
memoryZero(slider, sizeof(uislider_t));
slider->label.width = 20;
slider->label.height = 10;
slider->type = UI_SLIDER_TYPE_FLOAT;
slider->min.f = min;
slider->max.f = max;
slider->step.f = step;
slider->value.f = value;
}
static void sliderSetupInt(
uislider_t *slider,
const int32_t value,
const int32_t min,
const int32_t max,
const int32_t step
) {
memoryZero(slider, sizeof(uislider_t));
slider->label.width = 20;
slider->label.height = 10;
slider->type = UI_SLIDER_TYPE_INT;
slider->min.i = min;
slider->max.i = max;
slider->step.i = step;
slider->value.i = value;
}
static void test_uiSliderRebuildGeometry_trackPosition(void **state) {
uislider_t slider;
sliderSetupFloat(&slider, 0.0f, 0.0f, 1.0f, 0.1f);
uiSliderRebuildGeometry(&slider);
const float_t expectedX = (float_t)slider.label.width + UI_SLIDER_GAP;
const float_t expectedY =
((float_t)slider.label.height - UI_SLIDER_TRACK_HEIGHT) * 0.5f;
assert_float_equal(slider.cachedTrack.min[0], expectedX, 0.0001f);
assert_float_equal(slider.cachedTrack.min[1], expectedY, 0.0001f);
assert_float_equal(
slider.cachedTrack.max[0], expectedX + UI_SLIDER_TRACK_WIDTH, 0.0001f
);
}
static void test_uiSliderRebuildGeometry_fillVisibility(void **state) {
uislider_t slider;
// At the minimum value, the ratio is 0 -- no fill should be visible.
sliderSetupFloat(&slider, 0.0f, 0.0f, 10.0f, 1.0f);
uiSliderRebuildGeometry(&slider);
assert_false(slider.cachedFillVisible);
// Halfway to max -- fill should cover half the track.
sliderSetupFloat(&slider, 5.0f, 0.0f, 10.0f, 1.0f);
uiSliderRebuildGeometry(&slider);
assert_true(slider.cachedFillVisible);
assert_float_equal(
slider.cachedFill.max[0] - slider.cachedFill.min[0],
UI_SLIDER_TRACK_WIDTH * 0.5f,
0.0001f
);
}
static void test_uiSliderRebuildGeometry_stepMarkers(void **state) {
uislider_t slider;
// 5 steps between 0 and 10 -- under the marker cap, so markers render.
sliderSetupInt(&slider, 0, 0, 10, 2);
uiSliderRebuildGeometry(&slider);
assert_int_equal(slider.cachedMarkerCount, 6);
assert_float_equal(
slider.cachedMarkers[0].min[0], slider.cachedTrack.min[0] -
UI_SLIDER_STEP_MARKER_WIDTH * 0.5f,
0.0001f
);
// 100 steps -- over the marker cap, so it falls back to a smooth fill
// with no markers.
sliderSetupInt(&slider, 0, 0, 100, 1);
uiSliderRebuildGeometry(&slider);
assert_int_equal(slider.cachedMarkerCount, 0);
}
int main(int argc, char **argv) {
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_uiSliderRebuildGeometry_trackPosition),
cmocka_unit_test(test_uiSliderRebuildGeometry_fillVisibility),
cmocka_unit_test(test_uiSliderRebuildGeometry_stepMarkers),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
+36
View File
@@ -0,0 +1,36 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "dusktest.h"
#include "ui/widget/uitab.h"
#include "util/memory.h"
// uiTabInit requires a real font (FONT_DEFAULT) to build the label's
// glyph cache, which needs a live GL context this test binary doesn't
// have. uiTabRebuildBackground only reads the label's already-measured
// width/height, so it's safe to set those directly and exercise it here.
static void test_uiTabRebuildBackground_matchesLabelSize(void **state) {
uitab_t tab;
memoryZero(&tab, sizeof(uitab_t));
tab.label.width = 42;
tab.label.height = 12;
uiTabRebuildBackground(&tab);
assert_float_equal(tab.cachedBackground.min[0], 0.0f, 0.0001f);
assert_float_equal(tab.cachedBackground.min[1], 0.0f, 0.0001f);
assert_float_equal(tab.cachedBackground.max[0], 42.0f, 0.0001f);
assert_float_equal(tab.cachedBackground.max[1], 12.0f, 0.0001f);
}
int main(int argc, char **argv) {
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_uiTabRebuildBackground_matchesLabelSize),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
-47
View File
@@ -1,47 +0,0 @@
var Actions;
var camera, cameraPosition;
var cube, cubePosition, cubeRenderable, cubeMesh;
var ground, groundPosition, groundRenderable;
// init() is called via scriptManagerCallGlobal(), which pumps the asset
// system + job queue until any promise it returns settles - so it's safe
// to await include() here even though this runs before the main loop.
async function init() {
Actions = await include("input.js");
camera = new Entity();
cameraPosition = camera.add(POSITION);
camera.add(CAMERA);
cameraPosition.position = new Vec3(3, 3, -6);
cameraPosition.lookAt(new Vec3(0, 0, 0));
cube = new Entity();
cubePosition = cube.add(POSITION);
cubeRenderable = cube.add(RENDERABLE);
cubeMesh = Mesh.createCube();
cubeRenderable.mesh = cubeMesh;
cubeRenderable.color = Color.red();
ground = new Entity();
groundPosition = ground.add(POSITION);
groundRenderable = ground.add(RENDERABLE);
groundRenderable.mesh = Mesh.createCube();
groundRenderable.color = Color.dark_gray();
}
// Runs every frame (including dynamic/interpolation frames) - use for
// smooth, purely presentational animation.
function update() {
cubePosition.rotation.y += TIME.delta * 1.5;
cubePosition.rotation.x += TIME.delta * 0.7;
}
// Runs once per fixed timestep only - use for gameplay logic that should
// be deterministic and independent of display refresh rate.
function fixedUpdate() {
}
function deinit() {
cube.dispose();
camera.dispose();
}
-27
View File
@@ -1,27 +0,0 @@
// Binds physical buttons to abstract actions, then exports the action
// constants so other scripts don't need to know raw INPUT_ACTION_* names.
Input.bind("w", INPUT_ACTION_UP);
Input.bind("s", INPUT_ACTION_DOWN);
Input.bind("a", INPUT_ACTION_LEFT);
Input.bind("d", INPUT_ACTION_RIGHT);
Input.bind("space", INPUT_ACTION_ACCEPT);
Input.bind("escape", INPUT_ACTION_RAGEQUIT);
if(typeof INPUT_GAMEPAD !== "undefined") {
Input.bind("gamepad_up", INPUT_ACTION_UP);
Input.bind("gamepad_down", INPUT_ACTION_DOWN);
Input.bind("gamepad_left", INPUT_ACTION_LEFT);
Input.bind("gamepad_right", INPUT_ACTION_RIGHT);
Input.bind("gamepad_a", INPUT_ACTION_ACCEPT);
Input.bind("gamepad_start", INPUT_ACTION_RAGEQUIT);
}
module = {
UP: INPUT_ACTION_UP,
DOWN: INPUT_ACTION_DOWN,
LEFT: INPUT_ACTION_LEFT,
RIGHT: INPUT_ACTION_RIGHT,
ACCEPT: INPUT_ACTION_ACCEPT,
CANCEL: INPUT_ACTION_CANCEL,
RAGEQUIT: INPUT_ACTION_RAGEQUIT
};
+66 -2
View File
@@ -1,2 +1,66 @@
msgid "test.string"
msgstr "This is a test string"
msgid ""
msgstr ""
"Project-Id-Version: ExampleApp 1.0\n"
"Language: en\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=4; plural=(n==1 ? 0 : n==2 ? 1 : (n<7 ? 2 : 3));\n"
#: ui/menu.c:10
msgid "ui.title"
msgstr ""
"Welcome"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.general"
msgstr "General"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.input"
msgstr "Input"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.display"
msgstr "Display"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.audio"
msgstr "Audio"
msgid "ui.settings.input.deadzone"
msgstr "Deadzone"
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
msgid "ui.settings.general.language"
msgstr "Language"
msgid "ui.settings.general.language_detail"
msgstr "Takes effect after restarting the application."
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.apply"
msgstr "Apply"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.discard_changes"
msgstr "Discard unsaved changes?"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.characters"
msgstr "Characters"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.items"
msgstr "Items"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.settings"
msgstr "Settings"
msgid "item.potion.name"
msgstr "Potion"
msgid "item.potato.name"
msgstr "Potato"
msgid "item.apple.name"
msgstr "Apple"
+70
View File
@@ -0,0 +1,70 @@
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
@@ -0,0 +1,70 @@
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 "リンゴ"
+49
View File
@@ -0,0 +1,49 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Gamepad/keyboard-only for now -- no mouse support exists in the input
// system yet. Something else (e.g. a future Menu widget) is responsible
// for moving `highlighted` between multiple buttons; a Button only knows
// how to fire onSelect() when ACCEPT is pressed while it's the highlighted
// one.
class Button extends UIElement {
init() {
this.background = new Rectangle();
this.background.width = 120;
this.background.height = 32;
this.background.color = Button.COLOR_NORMAL;
this.add(this.background);
this.label = new Label();
this.label.x = 8;
this.label.y = 8;
this.add(this.label);
this.highlighted = false;
this.onSelect = null;
}
get text() { return this.label.text; }
set text(value) { this.label.text = value; }
setHighlighted(highlighted) {
this.highlighted = highlighted;
this.background.color = highlighted
? Button.COLOR_HIGHLIGHTED
: Button.COLOR_NORMAL;
}
update() {
this.updateChildren();
if(this.highlighted && Input.pressed(InputBind.ACCEPT) && this.onSelect) {
this.onSelect();
}
}
}
Button.COLOR_NORMAL = { r: 255, g: 255, b: 255, a: 255 };
Button.COLOR_HIGHLIGHTED = { r: 255, g: 0, b: 0, a: 255 };
module.exports = Button;
+61
View File
@@ -0,0 +1,61 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// A single label showing "Y "/"N " + the caller's text -- no background,
// matching the old widget exactly. Toggling itself (checked) is driven
// externally, typically by a Menu handing it LEFT/RIGHT via
// directionInput() while this checkbox is the highlighted item.
class Checkbox extends UIElement {
init() {
this.label = new Label();
this.add(this.label);
this._text = '';
this._checked = false;
this.highlighted = false;
this._refresh();
}
get text() { return this._text; }
set text(value) {
this._text = value;
this._refresh();
}
get checked() { return this._checked; }
set checked(value) {
this._checked = value;
this._refresh();
}
toggle() {
this.checked = !this.checked;
}
setHighlighted(highlighted) {
this.highlighted = highlighted;
this.label.color = highlighted
? Checkbox.COLOR_HIGHLIGHTED
: Checkbox.COLOR_NORMAL;
}
// Menu direction-input opt-out hook: LEFT/RIGHT toggles and consumes
// the input; UP/DOWN falls through to default cursor movement.
directionInput(dx, dy) {
if(dx === 0) return false;
this.toggle();
return true;
}
_refresh() {
this.label.text = (this._checked ? 'Y ' : 'N ') + this._text;
}
}
Checkbox.COLOR_NORMAL = { r: 255, g: 255, b: 255, a: 255 };
Checkbox.COLOR_HIGHLIGHTED = { r: 255, g: 0, b: 0, a: 255 };
module.exports = Checkbox;
+110
View File
@@ -0,0 +1,110 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var Menu = require('./Menu.js');
var Button = require('./Button.js');
// A Yes/No dialog: dim full-screen backdrop + a flat-color panel (see
// Fullbox.js/plan notes on why there's no real 9-slice Frame yet) +
// text + a 2-item Menu. Confirm.open(text, callback) lazily creates and
// reuses ONE shared instance rather than allocating fresh every time --
// the Menu stack already guarantees at most one confirm is ever
// meaningfully active, so there's nothing to gain from a fresh instance
// per call, and it sidesteps ever needing to dispose one (see Fullbox.js
// for why disposing from inside your own callback chain is risky).
class Confirm extends UIElement {
init() {
this.backdrop = new Rectangle();
this.backdrop.color = Confirm.COLOR_BACKDROP;
this.add(this.backdrop);
this.panel = new Rectangle();
this.panel.width = Confirm.PANEL_WIDTH;
this.panel.height = Confirm.PANEL_HEIGHT;
this.panel.color = Confirm.COLOR_PANEL;
this.add(this.panel);
this.label = new Label();
this.add(this.label);
this.menu = new Menu();
this.menu.cols = 2;
this.add(this.menu);
this.confirmButton = new Button();
this.confirmButton.text = 'Confirm';
this.menu.addItem(this.confirmButton);
this.cancelButton = new Button();
this.cancelButton.text = 'Cancel';
this.menu.addItem(this.cancelButton);
this.menu.onSelected = (index) => this._finish(index === 0);
// CANCEL (the bind, not the button) also closes the menu without
// firing onSelected -- treat that the same as picking Cancel.
this.menu.onClosed = () => this._finish(false);
this._callback = null;
this._finishing = false;
}
open(text, callback) {
this.label.text = text;
this._callback = callback;
this._finishing = false;
this._layout();
UI.add(this);
this.menu.open();
}
_finish(result) {
// menu.onClosed calling back into _finish (via close() below) would
// otherwise recurse into itself.
if(this._finishing) return;
this._finishing = true;
this.menu.close();
UI.remove(this);
const callback = this._callback;
this._callback = null;
if(callback) callback(result);
}
_layout() {
this.backdrop.width = Screen.width;
this.backdrop.height = Screen.height;
const panelX = (Screen.width - Confirm.PANEL_WIDTH) / 2;
const panelY = (Screen.height - Confirm.PANEL_HEIGHT) / 2;
this.panel.x = panelX;
this.panel.y = panelY;
this.label.x = panelX + Confirm.PADDING;
this.label.y = panelY + Confirm.PADDING;
this.confirmButton.x = panelX + Confirm.PADDING;
this.confirmButton.y = panelY + Confirm.PANEL_HEIGHT - Confirm.PADDING - 32;
this.cancelButton.x = this.confirmButton.x + 130;
this.cancelButton.y = this.confirmButton.y;
}
}
Confirm.PANEL_WIDTH = 300;
Confirm.PANEL_HEIGHT = 120;
Confirm.PADDING = 16;
Confirm.COLOR_BACKDROP = { r: 0, g: 0, b: 0, a: 160 };
Confirm.COLOR_PANEL = { r: 40, g: 40, b: 40, a: 255 };
Confirm.open = function(text, callback) {
if(!Confirm._shared) Confirm._shared = new Confirm();
Confirm._shared.open(text, callback);
return Confirm._shared;
};
module.exports = Confirm;
+60
View File
@@ -0,0 +1,60 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// One Label per console history slot, refreshed only when
// Console.consumeDirty() says the history actually changed -- reuses
// the normal Label/spritebatch render path instead of the old
// hand-rolled mesh-cache renderer.
//
// These Labels are NOT add()ed as children -- UIElement.add() caps at 8
// children per element, and CONSOLE_HISTORY_MAX (Console.lineCount) is
// 16, over that cap. Instead they're driven directly: render()/update()
// called explicitly below, and their world position is just their own
// x/y (never having a parent means nothing offsets it).
class ConsoleOverlay extends UIElement {
init() {
this.lines = [];
for(let i = 0; i < Console.lineCount; i++) {
const label = new Label();
label.x = 4;
label.y = 4 + i * ConsoleOverlay.LINE_HEIGHT;
this.lines.push(label);
}
this._refresh();
}
update() {
this.updateChildren();
if(Console.consumeDirty()) this._refresh();
for(let i = 0; i < this.lines.length; i++) this.lines[i].update();
}
// Overridden (rather than left to auto-render) so the console can be
// hidden entirely without disposing/rebuilding its Labels.
render() {
this.renderChildren();
if(!Console.visible) return;
for(let i = 0; i < this.lines.length; i++) this.lines[i].render();
}
// this.lines was never add()ed, so the normal dispose() cascade can't
// reach them -- release them explicitly first, or they'd leak their
// pool slots.
dispose() {
for(let i = 0; i < this.lines.length; i++) this.lines[i].dispose();
super.dispose();
}
_refresh() {
for(let i = 0; i < this.lines.length; i++) {
this.lines[i].text = Console.getLine(i);
}
}
}
ConsoleOverlay.LINE_HEIGHT = 12;
module.exports = ConsoleOverlay;
+64
View File
@@ -0,0 +1,64 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Up to 4 black letterbox/pillarbox bars sized from Screen.scanX/Y/
// scanWidth/scanHeight vs Screen.width/height. Recomputed every tick,
// unconditionally -- cheap (four rectangle field writes), and a no-op
// when the scan area already covers the full viewport (Rectangle
// already skips rendering at width/height <= 0).
class Crop extends UIElement {
init() {
this.top = new Rectangle();
this.bottom = new Rectangle();
this.left = new Rectangle();
this.right = new Rectangle();
this.top.color = Crop.COLOR_BARS;
this.bottom.color = Crop.COLOR_BARS;
this.left.color = Crop.COLOR_BARS;
this.right.color = Crop.COLOR_BARS;
this.add(this.top);
this.add(this.bottom);
this.add(this.left);
this.add(this.right);
}
update() {
this.updateChildren();
this._refresh();
}
_refresh() {
const scanX = Screen.scanX;
const scanY = Screen.scanY;
const scanRight = scanX + Screen.scanWidth;
const scanBottom = scanY + Screen.scanHeight;
this.top.x = 0;
this.top.y = 0;
this.top.width = Screen.width;
this.top.height = scanY;
this.bottom.x = 0;
this.bottom.y = scanBottom;
this.bottom.width = Screen.width;
this.bottom.height = Screen.height - scanBottom;
this.left.x = 0;
this.left.y = scanY;
this.left.width = scanX;
this.left.height = Screen.scanHeight;
this.right.x = scanRight;
this.right.y = scanY;
this.right.width = Screen.width - scanRight;
this.right.height = Screen.scanHeight;
}
}
Crop.COLOR_BARS = { r: 0, g: 0, b: 0, a: 255 };
module.exports = Crop;
+68
View File
@@ -0,0 +1,68 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Label + a "< option >"-style value label, cycling a caller-provided
// options array. Same directionInput()-consumes-LEFT/RIGHT shape as
// Slider, stepping the selected index (with wraparound) instead of a
// numeric value.
class Dropdown extends UIElement {
init() {
this.label = new Label();
this.add(this.label);
this.valueLabel = new Label();
this.valueLabel.x = 100;
this.add(this.valueLabel);
this.options = [];
this._index = 0;
this.highlighted = false;
this.onChange = null;
this._refresh();
}
get text() { return this.label.text; }
set text(value) { this.label.text = value; }
get selectedIndex() { return this._index; }
set selectedIndex(index) {
if(this.options.length === 0) {
this._index = 0;
this._refresh();
return;
}
const count = this.options.length;
this._index = ((index % count) + count) % count;
this._refresh();
if(this.onChange) this.onChange(this._index, this.options[this._index]);
}
get selected() { return this.options[this._index]; }
setHighlighted(highlighted) {
this.highlighted = highlighted;
this.label.color = highlighted
? Dropdown.COLOR_HIGHLIGHTED
: Dropdown.COLOR_NORMAL;
}
directionInput(dx, dy) {
if(dx === 0) return false;
this.selectedIndex = this._index + dx;
return true;
}
_refresh() {
const value = this.options[this._index];
this.valueLabel.text = value !== undefined ? ('< ' + value + ' >') : '< >';
}
}
Dropdown.COLOR_NORMAL = { r: 255, g: 255, b: 255, a: 255 };
Dropdown.COLOR_HIGHLIGHTED = { r: 255, g: 0, b: 0, a: 255 };
module.exports = Dropdown;
+43
View File
@@ -0,0 +1,43 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// extends UIElement (not Label) deliberately: only a UIElement/SCRIPTED
// instance's render()/update() override actually gets dispatched by the
// engine (the native Label/Rectangle callback tables never consult a
// subclass's override -- they're not scripted types themselves). So this
// composes a child Label instead of subclassing one, same as Button.
//
// Overrides render() rather than update(): update()/uiUpdate() only run
// on the one fixed-timestep tick per real frame that actually crosses a
// DUSK_TIME_STEP boundary (see Time.renderDelta's doc), but an FPS
// counter needs to sample every real frame -- which is exactly what
// render() does.
class FpsCounter extends UIElement {
init() {
this.label = new Label();
this.add(this.label);
this._average = 0;
}
render() {
const delta = Time.renderDelta;
if(delta > 0) {
const fps = 1 / delta;
this._average = this._average === 0
? fps
: this._average + (fps - this._average) * FpsCounter.SMOOTHING;
}
this.label.text = 'FPS: ' + Math.round(this._average);
this.renderChildren();
}
}
// Exponential-moving-average weight per sample -- lower is smoother/
// slower to react, higher tracks instantaneous frame time more closely.
FpsCounter.SMOOTHING = 0.1;
module.exports = FpsCounter;
+98
View File
@@ -0,0 +1,98 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// A tweened full-screen color quad -- covers both the old uifullbox
// (full-screen fade) and uitransition (fade transition with a
// completion callback): same shape, just parameterized, so there's no
// separate transition class/global.
//
// extends UIElement composing a child Rectangle (not extends Rectangle)
// for the same reason as FpsCounter: only a UIElement/SCRIPTED
// instance's render() override is actually dispatched by the engine.
// Overrides render() (not update()) so the tween advances every real
// frame, not just on fixed-timestep ticks.
//
// A finished Fullbox is only removed from the overlay roots, never
// disposed -- disposing an element from inside its own render()
// callback would free its JS instance registration while a native C
// caller further up the same call stack still holds it, risking the
// exact kind of delayed JerryScript refcount corruption this project
// has already hit once. Fullbox.under()/over() lazily create and cache
// one shared, reusable instance each (mirroring the old UNDER/OVER
// singletons), so repeated fades cost zero additional pool slots.
class Fullbox extends UIElement {
init() {
this.rect = new Rectangle();
this.add(this.rect);
this._from = Fullbox.COLOR_TRANSPARENT;
this._to = Fullbox.COLOR_TRANSPARENT;
this._duration = 0;
this._t = 0;
this._onComplete = null;
this._active = false;
}
// Starts (or restarts) this Fullbox tweening rect.color from
// options.fromColor to options.toColor over options.duration seconds,
// calling options.onComplete() once when done. Adds itself to the
// overlay roots if it isn't already there.
play(options) {
this._from = options.fromColor || Fullbox.COLOR_TRANSPARENT;
this._to = options.toColor || Fullbox.COLOR_TRANSPARENT;
this._duration = options.duration || 0;
this._t = 0;
this._onComplete = options.onComplete || null;
this._active = true;
this.rect.width = Screen.width;
this.rect.height = Screen.height;
this.rect.color = this._from;
UI.addOverlay(this);
}
render() {
if(this._active) {
this._t += Time.renderDelta;
const ratio = this._duration > 0
? Math.min(1, this._t / this._duration)
: 1;
this.rect.color = Fullbox._lerpColor(this._from, this._to, ratio);
if(ratio >= 1) {
this._active = false;
UI.removeOverlay(this);
if(this._onComplete) this._onComplete();
}
}
this.renderChildren();
}
}
Fullbox.COLOR_TRANSPARENT = { r: 0, g: 0, b: 0, a: 0 };
Fullbox._lerpColor = function(from, to, t) {
return {
r: from.r + (to.r - from.r) * t,
g: from.g + (to.g - from.g) * t,
b: from.b + (to.b - from.b) * t,
a: from.a + (to.a - from.a) * t
};
};
Fullbox.under = function() {
if(!Fullbox._under) Fullbox._under = new Fullbox();
return Fullbox._under;
};
Fullbox.over = function() {
if(!Fullbox._over) Fullbox._over = new Fullbox();
return Fullbox._over;
};
module.exports = Fullbox;
+187
View File
@@ -0,0 +1,187 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Gamepad/keyboard focus-navigation, replacing the old global uifocus_t
// stack. A Menu's children still render/update through the normal tree
// (add()), but navigation uses its own `items` list -- addItem() calls
// add() and also tracks the widget as focusable, so decorative elements
// (a title Label, a Rectangle background) just use add() directly and
// never enter navigation.
//
// open()/close() push/pop this Menu on a small global stack -- only the
// topmost entry consumes CANCEL/ACCEPT/direction input each tick, so a
// Menu opened on top of another (e.g. a Settings sub-page menu, or a
// Confirm dialog) doesn't fight it for input; everything underneath
// keeps rendering/updating, just doesn't react to input until it's
// topmost again.
class Menu extends UIElement {
init() {
this.items = [];
this.cols = 1;
this.index = 0;
this.onSelected = null;
this.onChanged = null;
this.onClosed = null;
this._heldDir = null;
this._heldTime = 0;
}
addItem(widget) {
this.add(widget);
this.items.push(widget);
return widget;
}
open() {
if(Menu._stack.indexOf(this) !== -1) return;
Menu._stack.push(this);
const item = this.items[this.index];
if(item && item.setHighlighted) item.setHighlighted(true);
}
// Closes this Menu and anything opened on top of it, matching the old
// uifocus_t's uiFocusPopItem (popping a mid-stack item also pops
// everything above it).
close() {
const idx = Menu._stack.indexOf(this);
if(idx === -1) return;
while(Menu._stack.length > idx) {
Menu._stack.pop()._onClosed();
}
}
// Safety net: dispose() has no override-preserving trampoline the way
// render()/update() do (see UIElement's dispose() docs), so a bare
// this.menu.dispose() would leave a disposed instance stuck at the top
// of Menu._stack forever if the caller forgot to close() first --
// always close() (a no-op if never opened) before the native cascade.
dispose() {
this.close();
super.dispose();
}
_onClosed() {
for(let i = 0; i < this.items.length; i++) {
const item = this.items[i];
if(item.setHighlighted) item.setHighlighted(false);
}
if(this.onClosed) this.onClosed();
}
update() {
this.updateChildren();
if(Menu.top() !== this) return;
if(Input.pressed(InputBind.CANCEL)) {
this.close();
return;
}
if(Input.pressed(InputBind.ACCEPT) && this.onSelected) {
this.onSelected(this.index, this.items[this.index]);
}
this._handleDirection();
}
_handleDirection() {
const dir = this._currentDirection();
if(!dir) {
this._heldDir = null;
this._heldTime = 0;
return;
}
if(dir !== this._heldDir) {
this._heldDir = dir;
this._heldTime = 0;
this._moveDirection(dir.dx, dir.dy);
return;
}
this._heldTime += Time.delta;
if(this._heldTime >= Menu.HOLD_DELAY) {
this._heldTime -= Menu.HOLD_REPEAT;
this._moveDirection(dir.dx, dir.dy);
}
}
// Identity-stable direction markers so _handleDirection's `dir !==
// this._heldDir` check works without allocating a fresh object (and
// therefore never matching) every tick.
_currentDirection() {
if(Input.isDown(InputBind.LEFT)) return Menu.DIR_LEFT;
if(Input.isDown(InputBind.RIGHT)) return Menu.DIR_RIGHT;
if(Input.isDown(InputBind.UP)) return Menu.DIR_UP;
if(Input.isDown(InputBind.DOWN)) return Menu.DIR_DOWN;
return null;
}
// Gives the currently-highlighted item first refusal (a Slider/
// Dropdown/Checkbox consuming LEFT/RIGHT itself), falling back to
// moving the cursor -- mirrors uifocus_t's per-item `direction`
// callback.
_moveDirection(dx, dy) {
if(this.items.length === 0) return;
const item = this.items[this.index];
if(item && typeof item.directionInput === 'function') {
if(item.directionInput(dx, dy)) return;
}
this._moveIndex(dx, dy);
}
_moveIndex(dx, dy) {
const count = this.items.length;
if(count === 0) return;
const cols = Math.max(1, this.cols);
const rows = Math.ceil(count / cols);
const col = ((this.index % cols) + dx + cols) % cols;
const row = ((Math.floor(this.index / cols)) + dy + rows) % rows;
let next = row * cols + col;
if(next >= count) next = count - 1;
this._setIndex(next);
}
_setIndex(next) {
if(next === this.index) return;
const oldItem = this.items[this.index];
if(oldItem && oldItem.setHighlighted) oldItem.setHighlighted(false);
this.index = next;
const newItem = this.items[this.index];
if(newItem && newItem.setHighlighted) newItem.setHighlighted(true);
if(this.onChanged) this.onChanged(this.index, newItem);
}
}
Menu._stack = [];
Menu.top = function() {
return Menu._stack.length > 0 ? Menu._stack[Menu._stack.length - 1] : null;
};
Menu.HOLD_DELAY = 0.5;
Menu.HOLD_REPEAT = 0.1;
Menu.DIR_LEFT = { dx: -1, dy: 0 };
Menu.DIR_RIGHT = { dx: 1, dy: 0 };
Menu.DIR_UP = { dx: 0, dy: -1 };
Menu.DIR_DOWN = { dx: 0, dy: 1 };
module.exports = Menu;
+52
View File
@@ -0,0 +1,52 @@
var Player = require('./Player.js');
var PlayerCamera = require('./PlayerCamera.js');
var TestPlane = require('./TestPlane.js');
var TestUIElement = require('./TestUIElement.js');
var FpsCounter = require('./FpsCounter.js');
var ConsoleOverlay = require('./ConsoleOverlay.js');
class OverworldScene {
constructor() {
}
init() {
this.player = new Player();
this.plane = new TestPlane();
this.camera = new PlayerCamera(this.player);
this.testUi = new TestUIElement();
UI.add(this.testUi);
this.fpsCounter = new FpsCounter();
UI.addOverlay(this.fpsCounter);
this.consoleOverlay = new ConsoleOverlay();
UI.addOverlay(this.consoleOverlay);
}
lateUpdate() {
this.camera.update();
}
dispose() {
this.camera.dispose();
this.player.dispose();
this.plane.dispose();
// testUi.dispose() cascades to its background/label children and
// removes itself from UI's render roots -- no separate UI.remove()
// needed.
this.testUi.dispose();
this.fpsCounter.dispose();
this.consoleOverlay.dispose();
this.camera = null;
this.player = null;
this.plane = null;
this.testUi = null;
this.fpsCounter = null;
this.consoleOverlay = null;
}
}
module.exports = OverworldScene;
+28
View File
@@ -0,0 +1,28 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
class Player extends Entity {
constructor() {
super();
this.position = this.add(POSITION);
this.position.setLocalPosition(0.0, 2.0, 0.0);
this.physics = this.add(PHYSICS);
this.physics.setShape(PHYSICS_SHAPE_CAPSULE, 0.5, 0.5);
this.renderable = this.add(RENDERABLE);
this.renderable.setMesh(0, MESH_CAPSULE);
this.renderable.setColor(0, 0, 255, 255);
this.add(PLAYER);
}
dispose() {
}
}
module.exports = Player;
+41
View File
@@ -0,0 +1,41 @@
var CAMERA_OFFSET_ANGLE = 0.0;
var CAMERA_OFFSET_RADIUS = 18.0;
var CAMERA_OFFSET_HEIGHT = 10.0;
class PlayerCamera extends Entity {
constructor(target) {
super();
this.target = target;
this.position = this.add(POSITION);
this.add(CAMERA);
this.update();
}
update() {
var targetPosition = this.target.position.getLocalPosition();
var eyeX = (
targetPosition.x + Math.cos(CAMERA_OFFSET_ANGLE) * CAMERA_OFFSET_RADIUS
);
var eyeY = (
targetPosition.y + CAMERA_OFFSET_HEIGHT
);
var eyeZ = (
targetPosition.z + Math.sin(CAMERA_OFFSET_ANGLE) * CAMERA_OFFSET_RADIUS
);
this.position.lookAt(
eyeX, eyeY, eyeZ,
targetPosition.x, targetPosition.y, targetPosition.z,
0.0, 1.0, 0.0
);
}
dispose() {
this.target = null;
}
}
module.exports = PlayerCamera;
+96
View File
@@ -0,0 +1,96 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var Menu = require('./Menu.js');
var Tab = require('./Tab.js');
var Confirm = require('./Confirm.js');
var SettingsGeneral = require('./SettingsGeneral.js');
var SettingsInput = require('./SettingsInput.js');
// Display/Audio pages are deliberately not here -- neither has any real
// engine system behind it, even in the old code (no resolution/
// fullscreen system, no audio subsystem at all).
var TABS = [
{ name: 'General', ctor: SettingsGeneral },
{ name: 'Input', ctor: SettingsInput }
];
// Owns a tabs Menu (General/Input) and swaps in the active tab's page
// widgets into a second, page-scoped Menu -- both Menus are open on the
// navigation stack simultaneously (tabsMenu below, pageMenu on top),
// matching the old settings screen's nested-menu behavior. Switching
// away from a dirty page opens a Confirm first.
class Settings extends UIElement {
init() {
this.tabsMenu = new Menu();
this.tabsMenu.cols = TABS.length;
this.add(this.tabsMenu);
this.tabs = TABS.map((def, index) => {
const tab = new Tab();
tab.text = def.name;
tab.x = index * 90;
this.tabsMenu.addItem(tab);
return tab;
});
this.tabsMenu.onSelected = (index) => this._activateTab(index);
this.page = null;
this.pageMenu = null;
this._activeTabIndex = -1;
}
open() {
UI.add(this);
this.tabsMenu.open();
this._activateTab(0);
}
close() {
this.tabsMenu.close();
if(this.pageMenu) this.pageMenu.close();
UI.remove(this);
}
_activateTab(index) {
if(index === this._activeTabIndex) return;
if(this.page && this.page.hasChanges && this.page.hasChanges()) {
Confirm.open('Discard changes?', (confirmed) => {
if(confirmed) this._swapTab(index);
});
return;
}
this._swapTab(index);
}
_swapTab(index) {
// pageMenu.dispose() cascades to every widget the outgoing page
// handed it via menuItems -- the page itself is a plain object (see
// SettingsGeneral.js), nothing else to release.
if(this.pageMenu) this.pageMenu.dispose();
for(let i = 0; i < this.tabs.length; i++) {
this.tabs[i].setHighlighted(i === index);
}
const def = TABS[index];
this.page = new def.ctor();
if(this.page.load) this.page.load();
this.pageMenu = new Menu();
this.pageMenu.y = 40;
const items = this.page.menuItems || [];
for(let i = 0; i < items.length; i++) this.pageMenu.addItem(items[i]);
this.add(this.pageMenu);
this.pageMenu.open();
this._activeTabIndex = index;
}
}
module.exports = Settings;
+48
View File
@@ -0,0 +1,48 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var Dropdown = require('./Dropdown.js');
var Button = require('./Button.js');
// A plain class, not a UIElement -- it owns no visual tree of its own.
// Its widgets are handed to Settings.js's pageMenu (via menuItems),
// which owns their parenting/rendering/disposal; this only holds
// load()/apply()/hasChanges() logic, mirroring the old settings system's
// per-tab def struct.
class SettingsGeneral {
constructor() {
this.dropdown = new Dropdown();
this.dropdown.text = 'Language';
this.dropdown.options = ['en-US', 'ja-JP', 'es-MX'];
this.applyButton = new Button();
this.applyButton.text = 'Apply';
this.applyButton.y = 40;
this.applyButton.onSelect = () => this.apply();
this._loadedIndex = 0;
}
get menuItems() {
return [this.dropdown, this.applyButton];
}
load() {
const index = this.dropdown.options.indexOf(Locale.current);
this.dropdown.selectedIndex = index >= 0 ? index : 0;
this._loadedIndex = this.dropdown.selectedIndex;
}
apply() {
Locale.set(this.dropdown.options[this.dropdown.selectedIndex]);
this._loadedIndex = this.dropdown.selectedIndex;
}
hasChanges() {
return this.dropdown.selectedIndex !== this._loadedIndex;
}
}
module.exports = SettingsGeneral;
+46
View File
@@ -0,0 +1,46 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var Slider = require('./Slider.js');
var Button = require('./Button.js');
// A plain class, not a UIElement -- see SettingsGeneral.js for why.
class SettingsInput {
constructor() {
this.deadzoneSlider = new Slider();
this.deadzoneSlider.text = 'Deadzone';
this.deadzoneSlider.min = 0;
this.deadzoneSlider.max = 1;
this.deadzoneSlider.step = 0.05;
this.applyButton = new Button();
this.applyButton.text = 'Apply';
this.applyButton.y = 40;
this.applyButton.onSelect = () => this.apply();
this._loadedValue = 0;
}
get menuItems() {
return [this.deadzoneSlider, this.applyButton];
}
load() {
this.deadzoneSlider.value = Input.deadzone;
this._loadedValue = this.deadzoneSlider.value;
}
apply() {
Input.deadzone = this.deadzoneSlider.value;
Save.write();
this._loadedValue = this.deadzoneSlider.value;
}
hasChanges() {
return this.deadzoneSlider.value !== this._loadedValue;
}
}
module.exports = SettingsInput;
+94
View File
@@ -0,0 +1,94 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Name label + value label + a track/fill Rectangle pair. Unlike Button,
// a Slider doesn't fire on ACCEPT -- it consumes LEFT/RIGHT itself via
// directionInput(), stepping value with wraparound at min/max, which is
// how a Menu gives the currently-highlighted item first refusal on
// direction input before falling back to moving the cursor.
class Slider extends UIElement {
init() {
this.nameLabel = new Label();
this.add(this.nameLabel);
this.valueLabel = new Label();
this.valueLabel.x = 100;
this.add(this.valueLabel);
this.track = new Rectangle();
this.track.y = 16;
this.track.width = 100;
this.track.height = 4;
this.track.color = Slider.COLOR_TRACK;
this.add(this.track);
this.fill = new Rectangle();
this.fill.y = 16;
this.fill.height = 4;
this.fill.color = Slider.COLOR_FILL;
this.add(this.fill);
this._min = 0;
this._max = 1;
this.step = 0.1;
this._value = 0;
this.highlighted = false;
this.onChange = null;
this._refresh();
}
get text() { return this.nameLabel.text; }
set text(value) { this.nameLabel.text = value; }
get min() { return this._min; }
set min(value) { this._min = value; this._refresh(); }
get max() { return this._max; }
set max(value) { this._max = value; this._refresh(); }
get value() { return this._value; }
set value(v) {
this._value = Math.min(this._max, Math.max(this._min, v));
this._refresh();
if(this.onChange) this.onChange(this._value);
}
setHighlighted(highlighted) {
this.highlighted = highlighted;
this.nameLabel.color = highlighted
? Slider.COLOR_HIGHLIGHTED
: Slider.COLOR_NORMAL;
}
directionInput(dx, dy) {
if(dx === 0) return false;
let next = this._value + dx * this.step;
const range = this._max - this._min;
if(range > 0) {
// Wrap within [min, max) rather than clamp, matching the old
// slider's step-with-wraparound behavior.
next = this._min + (((next - this._min) % range) + range) % range;
}
this.value = next;
return true;
}
_refresh() {
this.valueLabel.text = String(Math.round(this._value * 100) / 100);
const ratio = this._max > this._min
? (this._value - this._min) / (this._max - this._min)
: 0;
this.fill.width = this.track.width * ratio;
}
}
Slider.COLOR_NORMAL = { r: 255, g: 255, b: 255, a: 255 };
Slider.COLOR_HIGHLIGHTED = { r: 255, g: 0, b: 0, a: 255 };
Slider.COLOR_TRACK = { r: 80, g: 80, b: 80, a: 255 };
Slider.COLOR_FILL = { r: 0, g: 160, b: 220, a: 255 };
module.exports = Slider;
+45
View File
@@ -0,0 +1,45 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// A background Rectangle + Label, structurally a re-skinned Button --
// "active" (which content tab is currently shown) plays the same role
// Button's "highlighted" plays, so setHighlighted() is how a Menu drives
// it: a tab strip's Menu treats "cursor is here" and "this tab's content
// is showing" as the same thing, matching the old widget's behavior.
class Tab extends UIElement {
init() {
this.background = new Rectangle();
this.background.width = 80;
this.background.height = 24;
this.add(this.background);
this.label = new Label();
this.label.x = 4;
this.label.y = 4;
this.add(this.label);
this.active = false;
this._refresh();
}
get text() { return this.label.text; }
set text(value) { this.label.text = value; }
setHighlighted(active) {
this.active = active;
this._refresh();
}
_refresh() {
this.background.color = this.active
? Tab.COLOR_ACTIVE
: Tab.COLOR_INACTIVE;
}
}
Tab.COLOR_ACTIVE = { r: 0, g: 160, b: 0, a: 255 };
Tab.COLOR_INACTIVE = { r: 160, g: 0, b: 0, a: 255 };
module.exports = Tab;

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