12 Commits
Author SHA1 Message Date
YourWishesandClaude Sonnet 5 083deb8357 Move cutscene item type enum and authoring macros to their own headers
cutsceneitemtype_t moves from cutsceneitem.h into cutsceneitembase.h,
alongside a new CUTSCENE_ITEM(TYPE, UNION_NAME, ...) shorthand that
fills in a cutsceneitem_t literal's .type and union member together.

Every CUTSCENE_* authoring macro (CUTSCENE_WAIT, CUTSCENE_TEXT,
CUTSCENE_AUDIO_PLAY, etc.) moves out of the single, ever-growing
cutscene.h into the header of the item type it actually authors,
built on top of CUTSCENE_ITEM. cutscene.h now only holds cutscene_t
itself plus the CUTSCENE/CUTSCENE_REFERENCE/CUTSCENE_CUTSCENE macros,
which aren't tied to any one item type. Every relocated macro also
gained a proper JSDoc-style comment block with @param tags.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 22:30:23 -05:00
YourWishesandClaude Sonnet 5 ffb375faeb Add battle abilities and wire them into START_BATTLE cutscene parsing
Adds a battleability_t enum (starting with FIRE) and a fixed
abilities[8] array on battlefighter_t. Extends the START_BATTLE
cutscene item to parse an optional per-enemy "abilities" JSON array
(via a new cutsceneJsonLookupBattleAbility name lookup) and copies
abilities onto every spawned fighter, from the party roster for
allies and from the parsed config for enemies.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 22:30:12 -05:00
YourWishesandClaude Sonnet 5 b8cbd8ff6a Make party and save-slot init/new-game operate on SAVE.slot directly
party.c's functions no longer take a party_t* - they always operate on
SAVE.slot.party, since gameplay only ever has one active party. That
forced the same change on saveSlotInit/saveSlotNewGame (they called
partyInit/partyAddMember internally), so those are now parameterless
too, always resetting/seeding SAVE.slot. Callers building a save at a
specific index (new-game creation, slot deletion) now set
SAVE.slotCurrent first instead of building an independent local struct -
safe since the select-save screen is only ever reached before any
gameplay starts.

saveSlotWriteJSON/saveSlotReadJSON deliberately keep their explicit
saveslot_t* parameter - they're genuine serialization primitives used
by the save-device layer and tests against arbitrary structs, unrelated
to the single-current-party assumption. saveSlotReadJSON's internal
reset is now a plain memset instead of delegating to the now-global-only
saveSlotInit().

Updates test_save/test_savedevice/test_savedevicelinux/test_saveslot for
the new signatures. Note: test_savedevice/test_savedevicelinux/test_save
have pre-existing failures in this sandbox unrelated to this change -
savetestfixture.c swaps $HOME, but saveDeviceLinuxGetDirectory actually
derives the save path from ASSET.baseDirectory (the executable's own
location), so the fixture's sandboxing never actually applies. test_
saveslot.c (which doesn't depend on that fixture) passes 15/15.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 21:30:08 -05:00
YourWishesandClaude Sonnet 5 c2bd761383 Remove testbattle - superseded by the JSON-driven battle cutscene
testBattleStart() was never actually called anywhere (its only trace
was a stray unused include in uimainmenu.c) - battletest.jsonc's
START_BATTLE/REGULAR_BATTLE flow replaces it.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 21:14:50 -05:00
YourWishesandClaude Sonnet 5 878e3438c8 Complete REGULAR_BATTLE immediately, fix stale saveslot tests
REGULAR_BATTLE previously never completed on its own, hanging any
cutscene that reached it - START_BATTLE already waits out the whole
encounter and returns to the overworld before this item ever runs, so
it's now a completes-immediately hook point for future regular-battle-
specific follow-up.

Also updates test_saveslot.c for the mapName/partyMembers schema
additions: the round-trip test now writes a valid map name for its
in-use slot, "missingFieldsUseDefaults" is replaced with a test for the
blank-slot short-circuit it was actually hitting, and a new regression
test locks in that an in-use slot with no map name is treated as corrupt.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 19:59:16 -05:00
YourWishesandClaude Sonnet 5 3da65370e0 Add requireStrMin save-JSON shorthand
Replaces the hand-rolled mapName missing/null/empty check in
saveSlotVer1ReadJSON with a reusable macro.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 19:55:17 -05:00
YourWishesandClaude Sonnet 5 83e646cba9 Load the save's map on select, seed a real new-game slot, fix readString off-by-one
New games now go through saveSlotNewGame (starting party + default map
name) instead of the empty saveSlotInit, and selecting a save loads its
stored map instead of the hardcoded boot-time overworld. Save loading now
requires an in-use slot to have a non-empty map name, treating a blank one
as corruption instead of silently faking a default.

Also fixes a real off-by-one in the readString save-JSON macro: it passed
its maxLength (documented as excluding the null terminator) straight
through as stringCopy's destSize, which needs +1 for the terminator - so a
string exactly at the length limit (e.g. "overworld", 9 chars) always
asserted "src is too long".

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-10 23:14:44 -05:00
YourWishesandClaude Sonnet 5 0566166af4 Persist party across saves and flag/warn on corrupt save slots
Party moves off a global singleton onto each save slot, letting
START_BATTLE pick specific active-order members to bring into a fight,
and round-trips through save/load via saveslotver1. A corrupt slot load
now flags the cache and shows a red "Corrupted Save" warning in the
select-save UI instead of silently resetting.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-10 14:19:03 -05:00
YourWishesandClaude Sonnet 5 ed0b8c3911 Exit delete mode on save select after delete or back button
Previously deleting a save left the panel in delete mode, and pressing
back while in delete mode closed the whole save-select screen instead
of just returning to the normal load view.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-09 21:38:28 -05:00
YourWishesandClaude Sonnet 5 03d753a83f Move cutscene JSON parsing entirely into the async loader phase
File read, yyjson parse, and all item dispatch now happen in
assetCutsceneLoaderAsync - none of it touches the main thread now that
CUTSCENE items defer their nested asset resolution to start time. The
sync phase is now just a state flip, kept only so assetUpdate()'s
onLoaded dispatch (which only fires for entries finishing via the sync
path) still runs.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-09 21:34:47 -05:00
YourWishes cf51ed1988 Fixed cutscene item cutscene trying to recursively load 2026-09-09 21:21:50 -05:00
YourWishesandClaude Sonnet 5 70f46e89d3 Merge branch 'raw-json-maps' into main
Load map chunks from raw JSON at runtime instead of a baked DCF/DMF
step, add a reusable perf timing module, fix a real PSP logDebug/logError
Memory Stick I/O cost bug, and switch chunk tile storage to a dense
minified grid.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-09 15:34:08 -05:00
85 changed files with 1816 additions and 878 deletions

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
{
"items": [
{
"type": "START_BATTLE",
"encounterType": "REGULAR",
"fleeAvailable": true,
"enemies": [
{
"stats": { "attack": 8, "defense": 4, "magic": 0, "speed": 5, "luck": 2 },
"healthMax": 30,
"mpMax": 0
},
{
"stats": { "attack": 6, "defense": 3, "magic": 0, "speed": 7, "luck": 2 },
"healthMax": 20,
"mpMax": 0
}
]
},
{
"type": "REGULAR_BATTLE"
}
]
}
+6
View File
@@ -73,6 +73,12 @@ msgstr "Select Save"
msgid "ui.select_save.empty"
msgstr "Empty Slot"
msgid "ui.select_save.corrupt"
msgstr "Corrupted Save"
msgid "ui.select_save.corrupt_warning"
msgstr "This save file is corrupted and could not be loaded. Please contact support if this issue persists."
msgid "ui.select_save.slot_format"
msgstr "%s Lv.%d %s"
@@ -1 +1 @@
{"tiles":[[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[6,0],[2,0],[2,0],[2,0],[2,0],[2,0],[2,0],[7,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[8,0],[4,0],[4,0],[4,0],[12,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[8,0],[4,0],[4,0],[9,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0]],"meshes":[{"file":"house_5_3.dmf","pos":[1,1,0]}],"entities":[{"type":"global","globalId":3,"pos":[8,8,1]},{"type":"item","itemId":1,"quantity":1,"pos":[12,2,0]}],"areas":[{"min":[11,3,0],"max":[16,9,10],"callbackId":1,"notify":3,"trigger":6}]}
{"tiles":[[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[6,0],[2,0],[2,0],[2,0],[2,0],[2,0],[2,0],[7,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[8,0],[4,0],[4,0],[4,0],[12,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[8,0],[4,0],[4,0],[9,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0]],"meshes":[{"file":"house_5_3.dmf","pos":[1,1,0]}],"entities":[{"type":"global","globalId":3,"pos":[8,8,1]},{"type":"global","globalId":4,"pos":[12,2,0]}],"areas":[{"min":[11,3,0],"max":[16,9,10],"callbackId":1,"notify":3,"trigger":6}]}
@@ -101,8 +101,6 @@ errorret_t assetCutsceneLoaderAsync(assetloading_t *loading) {
errorOk();
}
assertNull(loading->loading.cutscene.buffer, "Buffer already defined?");
assetfile_t *file = &loading->loading.cutscene.file;
assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL)
@@ -125,35 +123,17 @@ errorret_t assetCutsceneLoaderAsync(assetloading_t *loading) {
assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file));
loading->loading.cutscene.buffer = buffer;
loading->loading.cutscene.size = fileSize;
loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_PARSE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetCutsceneLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_CUTSCENE, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
if(loading->loading.cutscene.state == ASSET_CUTSCENE_LOADING_STATE_INITIAL) {
loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_READ_FILE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
errorOk();
}
// Parsing is pure CPU work with no main-thread dependency (every item
// type's load callback just parses fields - see cutsceneCutsceneLoad's
// doc comment for how CUTSCENE items avoid needing one), so it happens
// right here instead of bouncing to the sync phase.
assetcutsceneoutput_t *out = &loading->entry->data.cutscene;
uint8_t *buffer = loading->loading.cutscene.buffer;
assertNotNull(buffer, "Cutscene data should have been loaded by now.");
size_t bufferSize = loading->loading.cutscene.size;
yyjson_doc *doc = yyjson_read(
(char *)buffer, bufferSize,
(char *)buffer, fileSize,
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
);
memoryFree(buffer);
loading->loading.cutscene.buffer = NULL;
if(doc == NULL) {
assetLoaderErrorThrow(loading, "Failed to parse cutscene JSON");
@@ -210,6 +190,31 @@ errorret_t assetCutsceneLoaderSync(assetloading_t *loading) {
out->cutscene.pause = pause;
out->cutscene.dataSize = 0;
loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_PARSE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetCutsceneLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_CUTSCENE, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
if(loading->loading.cutscene.state == ASSET_CUTSCENE_LOADING_STATE_INITIAL) {
loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_READ_FILE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
errorOk();
}
// Everything else already happened in the async phase - see
// assetCutsceneLoaderAsync. This flip still has to happen from here
// rather than the async phase setting LOADED directly, since
// assetUpdate() only fires an entry's onLoaded callback for entries
// that finish via this sync path.
assertTrue(
loading->loading.cutscene.state == ASSET_CUTSCENE_LOADING_STATE_PARSE,
"Unexpected cutscene loading state."
);
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
@@ -30,8 +30,6 @@ typedef enum {
typedef struct {
assetfile_t file;
assetcutsceneloadingstate_t state;
uint8_t *buffer;
size_t size;
} assetcutsceneloaderloading_t;
typedef struct {
@@ -80,8 +78,11 @@ void assetCutsceneFreeParsed(assetcutsceneoutput_t *out);
/**
* Asynchronous loader for cutscene assets. Reads the raw JSONC file bytes
* into the loading buffer so the sync phase can parse without blocking the
* main thread on I/O.
* and, in the same call, parses them into a heap-allocated cutsceneitem_t
* array + pool - none of that work touches the main thread (every item
* type's load callback is pure parsing now; CUTSCENE items defer their
* nested asset resolution to cutsceneCutsceneStart), so doing it all here
* keeps a large cutscene from ever blocking a frame.
*
* @param loading Loading information for the asset being loaded.
* @return Error code indicating success or failure of the load operation.
@@ -89,8 +90,11 @@ void assetCutsceneFreeParsed(assetcutsceneoutput_t *out);
errorret_t assetCutsceneLoaderAsync(assetloading_t *loading);
/**
* Synchronous loader for cutscene assets. Parses the JSONC previously read
* by the async phase into a heap-allocated cutsceneitem_t array + pool.
* Synchronous loader for cutscene assets. All actual work already
* happened in the async phase - this only flips the entry to LOADED,
* which must happen through this sync callback (rather than the async
* phase setting it directly) so assetUpdate()'s onLoaded dispatch, which
* only fires for entries finishing via the sync path, still runs.
*
* @param loading Loading information for the asset being loaded.
* @return Error code indicating success or failure of the load operation.
-3
View File
@@ -10,6 +10,3 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
battlefighter.c
party.c
)
# Subdirs
add_subdirectory(testbattle)
+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
*/
#pragma once
#include "error/error.h"
typedef enum {
BATTLE_ABILITY_NULL,
BATTLE_ABILITY_FIRE,
BATTLE_ABILITY_COUNT
} battleability_t;
+4
View File
@@ -7,6 +7,9 @@
#pragma once
#include "error/error.h"
#include "battleability.h"
#define BATTLE_FIGHTER_ABILITY_COUNT_MAX 8
// An empty status means the slot in BATTLE.fighters is unused.
typedef enum {
@@ -55,6 +58,7 @@ typedef struct {
uint16_t mpMax;
battlefighterstats_t stats;
battleability_t abilities[BATTLE_FIGHTER_ABILITY_COUNT_MAX];
} battlefighter_t;
/**
+18 -12
View File
@@ -8,22 +8,25 @@
#include "party.h"
#include "assert/assert.h"
#include "util/memory.h"
party_t PARTY;
#include "save/save.h"
void partyInit(void) {
memoryZero(&PARTY, sizeof(party_t));
party_t *party = &SAVE.slot.party;
memoryZero(party, sizeof(party_t));
for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; i++) {
PARTY.members[i].id = i;
party->members[i].id = i;
}
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
PARTY.order[i] = PARTY_ORDER_EMPTY;
party->order[i] = PARTY_ORDER_EMPTY;
}
}
uint8_t partyGetAvailableMember(void) {
const party_t *party = &SAVE.slot.party;
for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; i++) {
if(PARTY.members[i].status == BATTLE_FIGHTER_STATUS_NULL) return i;
if(party->members[i].status == BATTLE_FIGHTER_STATUS_NULL) return i;
}
return 0xFF;
@@ -34,18 +37,20 @@ battlefighter_t *partyAddMember(
const uint16_t healthMax,
const uint16_t mpMax
) {
party_t *party = &SAVE.slot.party;
const uint8_t index = partyGetAvailableMember();
if(index == 0xFF) return NULL;
battlefighter_t *member = &PARTY.members[index];
battlefighter_t *member = &party->members[index];
battleFighterInit(
member, BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER,
stats, healthMax, mpMax
);
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
if(PARTY.order[i] != PARTY_ORDER_EMPTY) continue;
PARTY.order[i] = index;
if(party->order[i] != PARTY_ORDER_EMPTY) continue;
party->order[i] = index;
break;
}
@@ -55,9 +60,10 @@ battlefighter_t *partyAddMember(
battlefighter_t *partyGetOrderMember(const uint8_t slot) {
assertTrue(slot < PARTY_ACTIVE_SIZE_MAX, "Invalid party order slot");
const uint8_t index = PARTY.order[slot];
party_t *party = &SAVE.slot.party;
const uint8_t index = party->order[slot];
if(index == PARTY_ORDER_EMPTY) return NULL;
return &PARTY.members[index];
return &party->members[index];
}
void partySetOrder(const uint8_t slot, const uint8_t memberIndex) {
@@ -67,5 +73,5 @@ void partySetOrder(const uint8_t slot, const uint8_t memberIndex) {
"Invalid party member index"
);
PARTY.order[slot] = memberIndex;
SAVE.slot.party.order[slot] = memberIndex;
}
+13 -10
View File
@@ -22,24 +22,25 @@ typedef struct {
uint8_t order[PARTY_ACTIVE_SIZE_MAX];
} party_t;
extern party_t PARTY;
/**
* Initializes the party system with an empty roster and order.
* Initializes the current save slot's party (SAVE.slot.party) with an
* empty roster and order.
*/
void partyInit(void);
/**
* Gets an available (unused) party member slot index.
* Gets an available (unused) member slot index in the current save slot's
* party.
*
* @return The index of an available slot, or 0xFF if the party is full.
*/
uint8_t partyGetAvailableMember(void);
/**
* Adds a member to the party roster in the next available slot. Party
* members are always allies controlled by the player. If there is a
* free active order slot, the new member is placed into it.
* Adds a member to the current save slot's party roster in the next
* available slot. Party members are always allies controlled by the
* player. If there is a free active order slot, the new member is placed
* into it.
*
* @param stats The member's base combat stats.
* @param healthMax The member's maximum health.
@@ -54,7 +55,8 @@ battlefighter_t *partyAddMember(
);
/**
* Gets the roster member currently occupying an active order slot.
* Gets the roster member currently occupying an active order slot in the
* current save slot's party.
*
* @param slot The active order slot to query.
* @return Pointer to the member in that slot, or NULL if the slot is
@@ -63,8 +65,9 @@ battlefighter_t *partyAddMember(
battlefighter_t *partyGetOrderMember(const uint8_t slot);
/**
* Assigns a roster member to an active order slot, replacing whatever
* was there. Use PARTY_ORDER_EMPTY to clear a slot.
* Assigns a roster member to an active order slot in the current save
* slot's party, replacing whatever was there. Use PARTY_ORDER_EMPTY to
* clear a slot.
*
* @param slot The active order slot to assign.
* @param memberIndex The roster member index to place there, or
@@ -1,10 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
testbattle.c
)
@@ -1,43 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "testbattle.h"
#include "rpg/battle/battle.h"
#include "scene/scene.h"
void testBattleStart(void) {
battleInit();
const battlefighterstats_t allyOneStats =
{ .attack = 10, .defense = 5, .magic = 0, .speed = 10, .luck = 0 };
const battlefighterstats_t allyTwoStats =
{ .attack = 8, .defense = 4, .magic = 0, .speed = 8, .luck = 0 };
const battlefighterstats_t enemyOneStats =
{ .attack = 6, .defense = 3, .magic = 0, .speed = 6, .luck = 0 };
const battlefighterstats_t enemyTwoStats =
{ .attack = 7, .defense = 3, .magic = 0, .speed = 5, .luck = 0 };
battleAddFighter(
BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER,
allyOneStats, 30, 10
);
battleAddFighter(
BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER,
allyTwoStats, 25, 10
);
battleAddFighter(
BATTLE_FIGHTER_TEAM_ENEMY, BATTLE_FIGHTER_CONTROLLER_AI,
enemyOneStats, 20, 5
);
battleAddFighter(
BATTLE_FIGHTER_TEAM_ENEMY, BATTLE_FIGHTER_CONTROLLER_AI,
enemyTwoStats, 20, 5
);
battleStart(BATTLE_ENCOUNTER_REGULAR, true);
sceneSet(SCENE_TYPE_BATTLE);
}
@@ -1,16 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
/**
* TEMPORARY test hook: sets up a hardcoded mock battle and switches to the
* battle scene, so the battle scene (camera/fighters/HUD) can be seen and
* played without a real encounter trigger yet.
*/
void testBattleStart(void);
+28 -477
View File
@@ -1,6 +1,6 @@
/**
* Copyright (c) 2025 Dominic Masters
*
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
@@ -19,6 +19,18 @@ typedef struct cutscene_s {
size_t dataSize;
} cutscene_t;
/**
* Declares a standalone, named cutscene_t (and its backing item array) -
* the entry point for a C-authored cutscene.
*
* @param NAME Suffix for the generated CUTSCENE_##NAME cutscene/items
* statics.
* @param SIZE Bytes of custom user data this cutscene needs, carved out
* of CUTSCENE_SYSTEM.data while it runs.
* @param PAUSE_TYPE Suffix of the CUTSCENE_PAUSE_* flag(s) to apply
* while this cutscene runs (e.g. NONE, ALL).
* @param ... The cutscene's cutsceneitem_t entries, in order.
*/
#define CUTSCENE(NAME, SIZE, PAUSE_TYPE, ...) \
static const cutsceneitem_t CUTSCENE_##NAME##_ITEMS[] = { __VA_ARGS__ }; \
static const cutscene_t CUTSCENE_##NAME = { \
@@ -28,486 +40,25 @@ typedef struct cutscene_s {
.dataSize = SIZE \
};
/**
* References a CUTSCENE(NAME, ...)-declared cutscene by name.
*
* @param CUTSCENE The cutscene's NAME, as passed to CUTSCENE(...).
*/
#define CUTSCENE_REFERENCE(CUTSCENE) \
&CUTSCENE_##CUTSCENE
#define CUTSCENE_TEXT(TEXT) \
{ .type = CUTSCENE_ITEM_TYPE_TEXT, .text = { .text = TEXT } }
#define CUTSCENE_TEXT_MINI(TEXT, X, Y, Z, DURATION) \
{ \
.type = CUTSCENE_ITEM_TYPE_TEXT_MINI, \
.textMini = { \
.text = TEXT, \
.position = { X, Y, Z }, \
.duration = DURATION \
} \
}
#define CUTSCENE_TEXT_MINI_HIDE(INDEX) \
{ \
.type = CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE, \
.textMiniHide = { .index = INDEX } \
}
#define CUTSCENE_WAIT(WAIT) \
{ .type = CUTSCENE_ITEM_TYPE_WAIT, .wait = WAIT }
// A named, otherwise no-op position in the item list that cutsceneGoTo
// can jump execution straight to. NAME is matched with stringEquals,
// not pointer identity, so it's safe to use separate string literals
// with the same contents at the marker and at each call site.
#define CUTSCENE_MARKER(NAME) \
{ .type = CUTSCENE_ITEM_TYPE_MARKER, .marker = { .name = NAME } }
// Restarts the currently running cutscene from its first item,
// preserving whatever interact/interacted entities triggered it.
#define CUTSCENE_RESTART() \
{ .type = CUTSCENE_ITEM_TYPE_RESTART }
// Blocks the cutscene here indefinitely - it never completes on its own,
// only cutsceneGoTo (called externally, e.g. from a UI callback) can move
// execution past it.
#define CUTSCENE_IDLE() \
{ .type = CUTSCENE_ITEM_TYPE_IDLE }
// Opens a full-screen UI panel (e.g. the main menu) declaratively, then
// immediately continues on to whatever follows this item.
#define CUTSCENE_UI_SHOW(SCREEN) \
{ .type = CUTSCENE_ITEM_TYPE_UI_SHOW, .uiShow = { .screen = SCREEN } }
// Requests a switch to a different SCENE_TYPE via sceneSet, then
// immediately continues on to whatever follows this item - the switch
// itself doesn't happen until the next sceneUpdate() tick, so it does
// not take effect this frame.
#define CUTSCENE_SCENE(TYPE) \
{ .type = CUTSCENE_ITEM_TYPE_SCENE, .sceneChange = { .type = TYPE } }
/**
* Hands control over to another CUTSCENE(NAME, ...)-declared cutscene.
* Has no dedicated item header of its own - cutscenecutsceneref_t is
* defined inline in cutsceneitem.h, tightly bound to the asset/loader
* system, so this shorthand stays here too.
*
* @param CUTSCENE The referenced cutscene's NAME, as passed to
* CUTSCENE(...).
*/
#define CUTSCENE_CUTSCENE(CUTSCENE) \
{ \
.type = CUTSCENE_ITEM_TYPE_CUTSCENE, \
.cutscene = CUTSCENE_REFERENCE(CUTSCENE) \
}
#define CUTSCENE_CALLBACK(CALLBACK) \
{ .type = CUTSCENE_ITEM_TYPE_CALLBACK, .callback = CALLBACK }
#define CUTSCENE_PRINT(TEXT) \
{ .type = CUTSCENE_ITEM_TYPE_PRINT, .print = { .text = TEXT } }
// Shows a message-only modal (no option buttons) and immediately
// continues on to whatever follows this item - it does not wait for
// the dialog to be dismissed. Script the rest of the interaction (e.g.
// CUTSCENE_CALLBACK to kick off work, CUTSCENE_WAIT, then
// CUTSCENE_MODAL_CLOSE) as later items in the same cutscene.
// TITLE and MESSAGE are each displayed as-is unless they match a
// locale message ID, in which case the translated string is shown
// instead - see uiModalLocalize.
#define CUTSCENE_MODAL(TITLE, MESSAGE) \
{ \
.type = CUTSCENE_ITEM_TYPE_MODAL, \
.modal = { .title = TITLE, .message = MESSAGE } \
}
// Shows a modal with option buttons and immediately continues on, same
// as CUTSCENE_MODAL - it does not block waiting for a selection.
// Back/cancel input is disabled while it's open (see
// uiMenuSetDisableBack), so it must be dismissed by picking one; CALLBACK
// then fires with the selected option index once the dialog closes.
// Option labels are passed as trailing arguments, e.g.
// CUTSCENE_MODAL_OPTIONS(title, message, callback, "Retry", "Cancel") -
// their strings are not copied by this item, so they must stay valid
// until the modal opens (string literals are fine). Like TITLE and
// MESSAGE, each option is translated if it matches a locale message ID.
#define CUTSCENE_MODAL_OPTIONS(TITLE, MESSAGE, CALLBACK, ...) \
{ \
.type = CUTSCENE_ITEM_TYPE_MODAL, \
.modal = { \
.title = TITLE, .message = MESSAGE, \
.options = (const char_t *[]){ __VA_ARGS__ }, \
.optionCount = (uint8_t)( \
sizeof((const char_t *[]){ __VA_ARGS__ }) / sizeof(const char_t *) \
), \
.callback = CALLBACK \
} \
}
// Same as CUTSCENE_MODAL_OPTIONS, but fixed to exactly one option and
// MARKER1 to jump straight to via cutsceneGoTo once it's selected - no
// callback function to write. Does not fall through to whatever follows
// this item, so MARKER1 must be scripted elsewhere in the same cutscene.
#define CUTSCENE_MODAL_OPTIONS_ONE(TITLE, MESSAGE, OPTION1, MARKER1) \
{ \
.type = CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS, \
.modalOptionsMarkers = { \
.title = TITLE, .message = MESSAGE, \
.options = { OPTION1 }, \
.markers = { MARKER1 }, \
.optionCount = 1 \
} \
}
// Same as CUTSCENE_MODAL_OPTIONS, but fixed to exactly two options,
// jumping straight to OPTION1_MARKER or OPTION2_MARKER via cutsceneGoTo
// once the corresponding option is selected - no callback function to
// write. Does not fall through to whatever follows this item, so both
// markers must be scripted elsewhere in the same cutscene.
#define CUTSCENE_MODAL_OPTIONS_TWO( \
TITLE, MESSAGE, OPTION1, OPTION1_MARKER, OPTION2, OPTION2_MARKER \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS, \
.modalOptionsMarkers = { \
.title = TITLE, .message = MESSAGE, \
.options = { OPTION1, OPTION2 }, \
.markers = { OPTION1_MARKER, OPTION2_MARKER }, \
.optionCount = 2 \
} \
}
// Closes the currently open modal (if any). Useful when a modal was
// opened outside of a blocking CUTSCENE_MODAL item (e.g. directly via
// uiModalOpen) and this cutscene just needs to dismiss it and continue
// on to whatever follows this item in the sequence.
#define CUTSCENE_MODAL_CLOSE() \
{ .type = CUTSCENE_ITEM_TYPE_MODAL_CLOSE }
// Opens the on-screen keyboard and blocks the cutscene until it closes,
// then caches whatever was typed - see cutsceneSystemGetTextCache to
// read it back afterwards. __VA_ARGS__ are uikeyboardopen_t designated
// initializers, e.g. CUTSCENE_KEYBOARD(.cancel = true, .maxLength = 8).
#define CUTSCENE_KEYBOARD(...) \
{ \
.type = CUTSCENE_ITEM_TYPE_KEYBOARD, \
.keyboard = { .open = { __VA_ARGS__ } } \
}
// (Re)requests an available save device and jumps straight to
// SUCCESS_MARKER or FAILURE_MARKER once it resolves, same as a
// CUTSCENE_MODAL_OPTIONS callback - it does not fall through to
// whatever follows this item, so both markers must be scripted
// elsewhere in the same cutscene.
#define CUTSCENE_SAVE_DEVICE_CHECK(SUCCESS_MARKER, FAILURE_MARKER) \
{ \
.type = CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK, \
.saveDeviceCheck = { \
.successMarker = SUCCESS_MARKER, \
.failureMarker = FAILURE_MARKER \
} \
}
// (Re)loads every save slot via saveLoadAllSlots() and jumps straight to
// SUCCESS_MARKER or FAILURE_MARKER once it resolves, same shape as
// CUTSCENE_SAVE_DEVICE_CHECK - it does not fall through to whatever
// follows this item, so both markers must be scripted elsewhere in the
// same cutscene.
#define CUTSCENE_SAVE_LOAD_ALL_SLOTS(SUCCESS_MARKER, FAILURE_MARKER) \
{ \
.type = CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS, \
.saveLoadAllSlots = { \
.successMarker = SUCCESS_MARKER, \
.failureMarker = FAILURE_MARKER \
} \
}
#define CUTSCENE_ENTITY_WALK_TO(ENTITY_INDEX, X, Y, Z) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO, \
.entityWalkTo = { \
.entityIndex = ENTITY_INDEX, \
.positions = (const worldpos_t[]){ { X, Y, Z } }, \
.count = 1, \
.walkAround = true \
} \
}
#define CUTSCENE_ENTITY_WALK_PATH(NAME, ENTITY_INDEX, ...) \
static const worldpos_t CUTSCENE_##NAME##_POSITIONS[] = { __VA_ARGS__ }; \
static const cutsceneitem_t CUTSCENE_##NAME = { \
.type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO, \
.entityWalkTo = { \
.entityIndex = ENTITY_INDEX, \
.positions = CUTSCENE_##NAME##_POSITIONS, \
.count = sizeof(CUTSCENE_##NAME##_POSITIONS) / sizeof(worldpos_t), \
.walkAround = true \
} \
}
#define CUTSCENE_ENTITY_REMOVE(ENTITY_INDEX) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_REMOVE, \
.entityRemove = { .entityIndex = ENTITY_INDEX } \
}
#define CUTSCENE_ENTITY_ADD(TYPE, X, Y, Z) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_ADD, \
.entityAdd = { .entityType = TYPE, .position = { X, Y, Z } } \
}
#define CUTSCENE_ENTITY_TURN(ENTITY_INDEX, DIRECTION) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_TURN, \
.entityTurn = { .entityIndex = ENTITY_INDEX, .direction = DIRECTION } \
}
// Walks ENTITY_INDEX to stand beside TARGET_ENTITY_INDEX, offset by
// (OFFSET_X, OFFSET_Y) on the 2D plane. The destination Z is resolved
// from nearby terrain each frame, so ramps between the two entities are
// accounted for automatically.
#define CUTSCENE_ENTITY_WALK_TO_ENTITY( \
ENTITY_INDEX, TARGET_ENTITY_INDEX, OFFSET_X, OFFSET_Y \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY, \
.entityWalkToEntity = { \
.entityIndex = ENTITY_INDEX, \
.targetEntityIndex = TARGET_ENTITY_INDEX, \
.offsetX = OFFSET_X, \
.offsetY = OFFSET_Y \
} \
}
#define CUTSCENE_ENTITY_TELEPORT(ENTITY_INDEX, X, Y, Z) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT, \
.entityTeleport = { .entityIndex = ENTITY_INDEX, .target = { X, Y, Z } } \
}
#define CUTSCENE_FADE(FROM, TO, DURATION, EASING) \
{ \
.type = CUTSCENE_ITEM_TYPE_FADE, \
.fade = { .from = FROM, .to = TO, .duration = DURATION, .easing = EASING } \
}
#define CUTSCENE_FADE_TO_BLACK(DURATION) \
CUTSCENE_FADE(COLOR_TRANSPARENT_BLACK, COLOR_BLACK, DURATION, EASING_LINEAR)
#define CUTSCENE_FADE_FROM_BLACK(DURATION) \
CUTSCENE_FADE(COLOR_BLACK, COLOR_TRANSPARENT_BLACK, DURATION, EASING_LINEAR)
#define CUTSCENE_FADE_TO_WHITE(DURATION) \
CUTSCENE_FADE(COLOR_TRANSPARENT_WHITE, COLOR_WHITE, DURATION, EASING_LINEAR)
#define CUTSCENE_FADE_FROM_WHITE(DURATION) \
CUTSCENE_FADE(COLOR_WHITE, COLOR_TRANSPARENT_WHITE, DURATION, EASING_LINEAR)
#define CUTSCENE_EMOJI(ENTITY_INDEX, EMOJI_TYPE, DURATION) \
{ \
.type = CUTSCENE_ITEM_TYPE_EMOJI, \
.emoji = { \
.entityIndex = ENTITY_INDEX, \
.emojiType = EMOJI_TYPE, \
.duration = DURATION \
} \
}
// AMOUNT ranges 0 (no shake) to 4 (three tiles): 1 is half a tile, 2 is
// a full tile, 3 is two tiles, and 4 is three tiles.
#define CUTSCENE_SHAKE(AMOUNT, DURATION) \
{ \
.type = CUTSCENE_ITEM_TYPE_SHAKE, \
.shake = { .amount = AMOUNT, .duration = DURATION } \
}
// Waits until BATTLE.state reaches STATE. Put this BEFORE
// CUTSCENE_SET_PAUSE(CUTSCENE_PAUSE_BATTLE), not after -- pausing first
// freezes BATTLE.state wherever it already is, so it would never reach
// STATE on its own to satisfy the wait. Waiting unpaused, then pausing the
// moment it's satisfied, catches the battle right at STATE before it can
// advance further.
#define CUTSCENE_BATTLE_WAIT_STATE(STATE) \
{ \
.type = CUTSCENE_ITEM_TYPE_BATTLE_WAIT_STATE, \
.battleWaitState = { .state = STATE } \
}
// Immediately queues an attack for FIGHTER_INDEX against TARGET_INDEX,
// bypassing normal player/AI selection for that fighter this round.
#define CUTSCENE_BATTLE_FORCE_ACTION(FIGHTER_INDEX, TARGET_INDEX) \
{ \
.type = CUTSCENE_ITEM_TYPE_BATTLE_FORCE_ACTION, \
.battleForceAction = { \
.fighterIndex = FIGHTER_INDEX, .targetIndex = TARGET_INDEX \
} \
}
#define CUTSCENE_SET_PAUSE(FLAGS) \
{ .type = CUTSCENE_ITEM_TYPE_SET_PAUSE, .setPause = (FLAGS) }
#define CUTSCENE_ITEM_GIVE(ITEM_ID, QUANTITY) \
{ \
.type = CUTSCENE_ITEM_TYPE_ITEM_GIVE, \
.itemGive = { .item = ITEM_ID, .quantity = QUANTITY } \
}
// Runs all listed items simultaneously and waits until all are done.
// Concurrent items cannot be nested inside another CUTSCENE_CONCURRENT.
#define CUTSCENE_CONCURRENT(...) \
{ \
.type = CUTSCENE_ITEM_TYPE_CONCURRENT, \
.concurrent = { \
.items = (const cutsceneitem_t[]){ __VA_ARGS__ }, \
.count = (uint8_t)( \
sizeof((cutsceneitem_t[]){ __VA_ARGS__ }) / \
sizeof(cutsceneitem_t) \
) \
} \
}
#define CUTSCENE_MAP_AREA_ADD( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, CALLBACK, NOTIFY, TRIGGER \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_MAP_AREA_ADD, \
.mapAreaAdd = { \
.min = { MIN_X, MIN_Y, MIN_Z }, \
.max = { MAX_X, MAX_Y, MAX_Z }, \
.callback = CALLBACK, \
.notify = NOTIFY, \
.trigger = TRIGGER \
} \
}
#define CUTSCENE_MAP_AREA_REMOVE(AREA_ID) \
{ \
.type = CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE, \
.mapAreaRemove = { .areaId = AREA_ID } \
}
// Waits until any one of the given map area IDs has its callback invoked.
// Accepts CUTSCENE_AREA_LAST_CREATED in place of a literal area ID.
#define CUTSCENE_MAP_AREA_WAIT(...) \
{ \
.type = CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT, \
.mapAreaWait = { \
.areaIds = (const uint8_t[]){ __VA_ARGS__ }, \
.count = (uint8_t)( \
sizeof((const uint8_t[]){ __VA_ARGS__ }) / sizeof(uint8_t) \
) \
} \
}
// Adds a map area, waits for it to be triggered once, then removes it
// before the cutscene continues. Uses a no-op callback since the wait is
// driven by the area's trigger count rather than callback logic.
#define CUTSCENE_MAP_AREA_TRIGGER_ONCE( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, NOTIFY, TRIGGER \
) \
CUTSCENE_MAP_AREA_ADD( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, \
mapAreaNoopCallback, NOTIFY, TRIGGER \
), \
CUTSCENE_MAP_AREA_WAIT(CUTSCENE_AREA_LAST_CREATED), \
CUTSCENE_MAP_AREA_REMOVE(CUTSCENE_AREA_LAST_CREATED)
// Longhand - every audioMixerQueuePlay() parameter. See
// CUTSCENE_AUDIO_PLAY_SIMPLE/CUTSCENE_AUDIO_PLAY_LOOPED below for the
// shorthands.
#define CUTSCENE_AUDIO_PLAY( \
FILE, CHANNEL, VOLUME, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_PLAY, \
.audioPlay = { \
.file = FILE, \
.channel = CHANNEL, \
.volume = VOLUME, \
.pan = PAN, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
} \
}
// Shorthand: play FILE on CHANNEL once, full volume, centered (0.0f, same
// as AUDIO_STREAM_CENTER), no loop.
#define CUTSCENE_AUDIO_PLAY_SIMPLE(FILE, CHANNEL) \
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, false, 0, -1.0f, 0.0f)
// Shorthand: play FILE on CHANNEL looping the whole clip forever, full
// volume, centered (0.0f, same as AUDIO_STREAM_CENTER).
#define CUTSCENE_AUDIO_PLAY_LOOPED(FILE, CHANNEL) \
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, true, 0, -1.0f, 0.0f)
#define CUTSCENE_AUDIO_STOP(CHANNEL) \
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_STOP, .audioStopChannel = CHANNEL }
#define CUTSCENE_AUDIO_PAUSE(CHANNEL) \
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_PAUSE, .audioPauseChannel = CHANNEL }
#define CUTSCENE_AUDIO_RESUME(CHANNEL) \
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_RESUME, .audioResumeChannel = CHANNEL }
// Longhand - starts CHANNEL fading from FROM to TO over DURATION seconds,
// eased by EASING. Doesn't wait for it - pair with
// CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) to block until it finishes. See
// CUTSCENE_AUDIO_FADE_OUT/CUTSCENE_AUDIO_FADE_IN below for the shorthands;
// use this directly for a custom range, e.g.
// CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.3f, 5.0f, EASING_LINEAR) to fade
// down to "playing quietly" rather than silent.
#define CUTSCENE_AUDIO_FADE(CHANNEL, FROM, TO, DURATION, EASING) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_FADE, \
.audioFade = { \
.channel = CHANNEL, \
.from = FROM, \
.to = TO, \
.duration = DURATION, \
.easing = EASING \
} \
}
// Shorthand: fade CHANNEL from full volume to silent over DURATION seconds.
#define CUTSCENE_AUDIO_FADE_OUT(CHANNEL, DURATION) \
CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.0f, DURATION, EASING_LINEAR)
// Shorthand: fade CHANNEL from silent to full volume over DURATION seconds.
#define CUTSCENE_AUDIO_FADE_IN(CHANNEL, DURATION) \
CUTSCENE_AUDIO_FADE(CHANNEL, 0.0f, 1.0f, DURATION, EASING_LINEAR)
// Waits until CHANNEL's fade (started elsewhere by CUTSCENE_AUDIO_FADE)
// has finished - a no-op wait if CHANNEL isn't fading.
#define CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_FADE_WAIT, \
.audioFadeWaitChannel = CHANNEL \
}
#define CUTSCENE_AUDIO_SET_PAN(CHANNEL, PAN) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN, \
.audioSetPan = { .channel = CHANNEL, .pan = PAN } \
}
#define CUTSCENE_AUDIO_SET_LOOP( \
CHANNEL, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP, \
.audioSetLoop = { \
.channel = CHANNEL, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
} \
}
// Combined form of CUTSCENE_AUDIO_SET_PAN + CUTSCENE_AUDIO_SET_LOOP, for
// setting both at once rather than as two separate items.
#define CUTSCENE_AUDIO_SET( \
CHANNEL, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET, \
.audioSet = { \
.channel = CHANNEL, \
.pan = PAN, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
} \
.cutsceneRef = { .cutscene = CUTSCENE_REFERENCE(CUTSCENE), .name = NULL } \
}
@@ -18,6 +18,50 @@ typedef struct {
easingtype_t easing;
} cutsceneaudiofade_t;
/**
* Longhand - starts CHANNEL fading from FROM to TO over DURATION seconds,
* eased by EASING. Doesn't wait for it - pair with
* CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) to block until it finishes. See
* CUTSCENE_AUDIO_FADE_OUT/CUTSCENE_AUDIO_FADE_IN below for the
* shorthands; use this directly for a custom range, e.g.
* CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.3f, 5.0f, EASING_LINEAR) to fade
* down to "playing quietly" rather than silent.
*
* @param CHANNEL audiomixerchannel_t to fade.
* @param FROM Starting volume (0.0-1.0).
* @param TO Ending volume (0.0-1.0).
* @param DURATION Duration in seconds.
* @param EASING easingtype_t to apply.
*/
#define CUTSCENE_AUDIO_FADE(CHANNEL, FROM, TO, DURATION, EASING) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_FADE, audioFade, { \
.channel = CHANNEL, \
.from = FROM, \
.to = TO, \
.duration = DURATION, \
.easing = EASING \
})
/**
* Shorthand: fade CHANNEL from full volume to silent over DURATION
* seconds.
*
* @param CHANNEL audiomixerchannel_t to fade.
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_AUDIO_FADE_OUT(CHANNEL, DURATION) \
CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.0f, DURATION, EASING_LINEAR)
/**
* Shorthand: fade CHANNEL from silent to full volume over DURATION
* seconds.
*
* @param CHANNEL audiomixerchannel_t to fade.
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_AUDIO_FADE_IN(CHANNEL, DURATION) \
CUTSCENE_AUDIO_FADE(CHANNEL, 0.0f, 1.0f, DURATION, EASING_LINEAR)
/**
* Starts an audio fade step (starts the fade via audioMixerFadeTo() -
* doesn't wait for it; pair with CUTSCENE_AUDIO_FADE_WAIT to block on it).
@@ -9,6 +9,15 @@
#include "audio/mixer/audiomixerchannel.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Waits until CHANNEL's fade (started elsewhere by CUTSCENE_AUDIO_FADE)
* has finished - a no-op wait if CHANNEL isn't fading.
*
* @param CHANNEL audiomixerchannel_t to wait on.
*/
#define CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_FADE_WAIT, audioFadeWaitChannel, CHANNEL)
/**
* Updates an audio fade-wait step, completing once the watched channel's
* fade (started by a CUTSCENE_AUDIO_FADE elsewhere) finishes. Has no Start
@@ -9,6 +9,14 @@
#include "audio/mixer/audiomixerchannel.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Pauses CHANNEL immediately.
*
* @param CHANNEL audiomixerchannel_t to pause.
*/
#define CUTSCENE_AUDIO_PAUSE(CHANNEL) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_PAUSE, audioPauseChannel, CHANNEL)
/**
* Starts an audio pause step (pauses the channel immediately).
*
@@ -20,6 +20,55 @@ typedef struct {
float_t loopTo;
} cutsceneaudioplay_t;
/**
* Longhand - queues a sound via audioMixerQueuePlay() (see its own
* comment on when it actually starts). See CUTSCENE_AUDIO_PLAY_SIMPLE/
* CUTSCENE_AUDIO_PLAY_LOOPED below for the shorthands.
*
* @param FILE Audio file path.
* @param CHANNEL audiomixerchannel_t to play on.
* @param VOLUME Playback volume (0.0-1.0).
* @param PAN Stereo pan (-1.0 left to 1.0 right, 0.0 centered).
* @param LOOPING Whether the clip loops.
* @param LOOP_COUNT Number of loop repeats (0 = infinite, if LOOPING).
* @param LOOP_START Loop region start in seconds, or -1.0f for the clip
* start.
* @param LOOP_TO Loop region end/return point in seconds.
*/
#define CUTSCENE_AUDIO_PLAY( \
FILE, CHANNEL, VOLUME, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_PLAY, audioPlay, { \
.file = FILE, \
.channel = CHANNEL, \
.volume = VOLUME, \
.pan = PAN, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
})
/**
* Shorthand: play FILE on CHANNEL once, full volume, centered (0.0f, same
* as AUDIO_STREAM_CENTER), no loop.
*
* @param FILE Audio file path.
* @param CHANNEL audiomixerchannel_t to play on.
*/
#define CUTSCENE_AUDIO_PLAY_SIMPLE(FILE, CHANNEL) \
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, false, 0, -1.0f, 0.0f)
/**
* Shorthand: play FILE on CHANNEL looping the whole clip forever, full
* volume, centered (0.0f, same as AUDIO_STREAM_CENTER).
*
* @param FILE Audio file path.
* @param CHANNEL audiomixerchannel_t to play on.
*/
#define CUTSCENE_AUDIO_PLAY_LOOPED(FILE, CHANNEL) \
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, true, 0, -1.0f, 0.0f)
/**
* Starts an audio play step (queues the sound via audioMixerQueuePlay() -
* see its own comment on when it actually starts).
@@ -9,6 +9,14 @@
#include "audio/mixer/audiomixerchannel.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Resumes CHANNEL immediately.
*
* @param CHANNEL audiomixerchannel_t to resume.
*/
#define CUTSCENE_AUDIO_RESUME(CHANNEL) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_RESUME, audioResumeChannel, CHANNEL)
/**
* Starts an audio resume step (resumes the channel immediately).
*
@@ -18,6 +18,30 @@ typedef struct {
float_t loopTo;
} cutsceneaudioset_t;
/**
* Combined form of CUTSCENE_AUDIO_SET_PAN + CUTSCENE_AUDIO_SET_LOOP, for
* setting both at once rather than as two separate items.
*
* @param CHANNEL audiomixerchannel_t to adjust.
* @param PAN Stereo pan (-1.0 left to 1.0 right, 0.0 centered).
* @param LOOPING Whether the clip loops.
* @param LOOP_COUNT Number of loop repeats (0 = infinite, if LOOPING).
* @param LOOP_START Loop region start in seconds, or -1.0f for the clip
* start.
* @param LOOP_TO Loop region end/return point in seconds.
*/
#define CUTSCENE_AUDIO_SET( \
CHANNEL, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_SET, audioSet, { \
.channel = CHANNEL, \
.pan = PAN, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
})
/**
* Starts an audio set step - applies pan and looping behaviour together in
* one item (via audioMixerSetPan()/audioMixerSetLoop()), for when you want
@@ -17,6 +17,27 @@ typedef struct {
float_t loopTo;
} cutsceneaudiosetloop_t;
/**
* Applies new looping behaviour immediately, via audioMixerSetLoop().
*
* @param CHANNEL audiomixerchannel_t to adjust.
* @param LOOPING Whether the clip loops.
* @param LOOP_COUNT Number of loop repeats (0 = infinite, if LOOPING).
* @param LOOP_START Loop region start in seconds, or -1.0f for the clip
* start.
* @param LOOP_TO Loop region end/return point in seconds.
*/
#define CUTSCENE_AUDIO_SET_LOOP( \
CHANNEL, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP, audioSetLoop, { \
.channel = CHANNEL, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
})
/**
* Starts an audio set-loop step (applies the new looping behaviour
* immediately, via audioMixerSetLoop()).
@@ -14,6 +14,17 @@ typedef struct {
float_t pan;
} cutsceneaudiosetpan_t;
/**
* Applies a new pan immediately, via audioMixerSetPan().
*
* @param CHANNEL audiomixerchannel_t to adjust.
* @param PAN Stereo pan (-1.0 left to 1.0 right, 0.0 centered).
*/
#define CUTSCENE_AUDIO_SET_PAN(CHANNEL, PAN) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN, audioSetPan, { \
.channel = CHANNEL, .pan = PAN \
})
/**
* Starts an audio set-pan step (applies the new pan immediately, via
* audioMixerSetPan()).
@@ -9,6 +9,14 @@
#include "audio/mixer/audiomixerchannel.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Stops CHANNEL immediately.
*
* @param CHANNEL audiomixerchannel_t to stop.
*/
#define CUTSCENE_AUDIO_STOP(CHANNEL) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_STOP, audioStopChannel, CHANNEL)
/**
* Starts an audio stop step (stops the channel immediately).
*
@@ -8,4 +8,5 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
cutscenestartbattle.c
cutscenebattlewaitstate.c
cutscenebattleforceaction.c
cutsceneregularbattle.c
)
@@ -14,6 +14,18 @@ typedef struct {
uint8_t targetIndex;
} cutscenebattleforceaction_t;
/**
* Immediately queues an attack for FIGHTER_INDEX against TARGET_INDEX,
* bypassing normal player/AI selection for that fighter this round.
*
* @param FIGHTER_INDEX Attacking fighter's battle index.
* @param TARGET_INDEX Target fighter's battle index.
*/
#define CUTSCENE_BATTLE_FORCE_ACTION(FIGHTER_INDEX, TARGET_INDEX) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_BATTLE_FORCE_ACTION, battleForceAction, { \
.fighterIndex = FIGHTER_INDEX, .targetIndex = TARGET_INDEX \
})
/**
* Starts a battle force-action step: immediately queues an attack for the
* given fighter against the given target, bypassing normal player/AI
@@ -13,6 +13,21 @@ typedef struct {
battlestate_t state;
} cutscenebattlewaitstate_t;
/**
* Waits until BATTLE.state reaches STATE. Put this BEFORE
* CUTSCENE_SET_PAUSE(CUTSCENE_PAUSE_BATTLE), not after -- pausing first
* freezes BATTLE.state wherever it already is, so it would never reach
* STATE on its own to satisfy the wait. Waiting unpaused, then pausing
* the moment it's satisfied, catches the battle right at STATE before it
* can advance further.
*
* @param STATE battlestate_t to wait for.
*/
#define CUTSCENE_BATTLE_WAIT_STATE(STATE) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_BATTLE_WAIT_STATE, battleWaitState, { \
.state = STATE \
})
/**
* Updates a battle wait-state step, completing once BATTLE.state reaches
* the watched state. Has no Start callback -- there's nothing to do until
@@ -0,0 +1,15 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
bool_t cutsceneRegularBattleUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
@@ -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 "rpg/cutscene/item/cutsceneitembase.h"
/**
* Updates a regular-battle step. By the time this item runs, the preceding
* START_BATTLE item has already waited out the whole encounter, synced
* party HP/MP, and returned to the overworld scene - so this is currently
* just a completes-immediately hook point for whatever regular-battle-
* specific follow-up (loot, post-battle dialogue, etc.) gets added later.
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true always.
*/
bool_t cutsceneRegularBattleUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
// REGULAR_BATTLE has no fields of its own to parse yet - see
// cutsceneItemLoadNoop (cutsceneitembase.h), used directly as its .load
// callback.
@@ -8,8 +8,11 @@
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/battle/party.h"
#include "scene/scene.h"
#include "save/save.h"
#include "rpg/cutscene/item/json/cutscenejsonbattleencounter.h"
#include "rpg/cutscene/item/json/cutscenejsonbattleability.h"
#include "rpg/cutscene/item/json/cutscenejsonfield.h"
#include "util/memory.h"
void cutsceneStartBattleStart(
const cutsceneitem_t *item,
@@ -19,8 +22,9 @@ void cutsceneStartBattleStart(
battleInit();
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
battlefighter_t *member = partyGetOrderMember(i);
for(uint8_t i = 0; i < config->playerCount; i++) {
battlefighter_t *member =
partyGetOrderMember(config->players[i]);
if(member == NULL) continue;
battlefighter_t *fighter = battleAddFighter(
@@ -32,14 +36,18 @@ void cutsceneStartBattleStart(
fighter->health = member->health;
fighter->mp = member->mp;
fighter->status = member->status;
memoryCopy(fighter->abilities, member->abilities, sizeof(fighter->abilities));
}
for(uint8_t i = 0; i < config->enemyCount; i++) {
const cutscenestartbattleenemy_t *enemy = &config->enemies[i];
battleAddFighter(
battlefighter_t *fighter = battleAddFighter(
BATTLE_FIGHTER_TEAM_ENEMY, BATTLE_FIGHTER_CONTROLLER_AI,
enemy->stats, enemy->healthMax, enemy->mpMax
);
if(fighter == NULL) continue;
memoryCopy(fighter->abilities, enemy->abilities, sizeof(fighter->abilities));
}
battleStart(config->encounterType, config->fleeAvailable);
@@ -52,13 +60,15 @@ bool_t cutsceneStartBattleUpdate(
) {
if(BATTLE.result == BATTLE_RESULT_NONE) return false;
const cutscenestartbattle_t *config = &item->startBattle;
// Sync ally HP/MP back to the persistent party roster. Relies on
// ally fighters having been added to BATTLE.fighters in the same
// order partyGetOrderMember() iterates, starting at index 0 (see
// cutsceneStartBattleStart).
// order config->players iterates (see cutsceneStartBattleStart).
uint8_t allySlot = 0;
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
battlefighter_t *member = partyGetOrderMember(i);
for(uint8_t i = 0; i < config->playerCount; i++) {
battlefighter_t *member =
partyGetOrderMember(config->players[i]);
if(member == NULL) continue;
battlefighter_t *fighter = &BATTLE.fighters[allySlot++];
@@ -89,6 +99,38 @@ errorret_t cutsceneStartBattleLoad(
item->startBattle.fleeAvailable =
cutsceneJsonGetBool(itemObj, "fleeAvailable", true);
yyjson_val *players = yyjson_obj_get(itemObj, "players");
if(players == NULL) {
item->startBattle.playerCount = PARTY_ACTIVE_SIZE_MAX;
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
item->startBattle.players[i] = i;
}
} else {
size_t playerCount = yyjson_arr_size(players);
if(!yyjson_is_arr(players) || playerCount > PARTY_ACTIVE_SIZE_MAX) {
errorThrow(
"Cutscene item (START_BATTLE): 'players' must have 0-%u entries",
(uint32_t)PARTY_ACTIVE_SIZE_MAX
);
}
item->startBattle.playerCount = (uint8_t)playerCount;
yyjson_arr_iter playerIter = yyjson_arr_iter_with(players);
yyjson_val *playerVal;
size_t p = 0;
while((playerVal = yyjson_arr_iter_next(&playerIter)) != NULL) {
int64_t index = yyjson_get_int(playerVal);
if(index < 0 || index >= PARTY_ACTIVE_SIZE_MAX) {
errorThrow(
"Cutscene item (START_BATTLE): players[%u] must be 0-%u",
(uint32_t)p, (uint32_t)(PARTY_ACTIVE_SIZE_MAX - 1)
);
}
item->startBattle.players[p] = (uint8_t)index;
p++;
}
}
yyjson_val *enemies = yyjson_obj_get(itemObj, "enemies");
size_t enemyCount = yyjson_arr_size(enemies);
if(!yyjson_is_arr(enemies) || enemyCount == 0 ||
@@ -126,6 +168,37 @@ errorret_t cutsceneStartBattleLoad(
(uint16_t)yyjson_get_int(yyjson_obj_get(enemyVal, "healthMax"));
enemy->mpMax =
(uint16_t)yyjson_get_int(yyjson_obj_get(enemyVal, "mpMax"));
yyjson_val *abilities = yyjson_obj_get(enemyVal, "abilities");
if(abilities != NULL) {
size_t abilityCount = yyjson_arr_size(abilities);
if(!yyjson_is_arr(abilities) ||
abilityCount > BATTLE_FIGHTER_ABILITY_COUNT_MAX) {
errorThrow(
"Cutscene item (START_BATTLE): enemies[%u].abilities must have "
"0-%u entries",
(uint32_t)e, (uint32_t)BATTLE_FIGHTER_ABILITY_COUNT_MAX
);
}
yyjson_arr_iter abilityIter = yyjson_arr_iter_with(abilities);
yyjson_val *abilityVal;
size_t a = 0;
while((abilityVal = yyjson_arr_iter_next(&abilityIter)) != NULL) {
battleability_t ability;
if(!cutsceneJsonLookupBattleAbility(
yyjson_get_str(abilityVal), &ability
)) {
errorThrow(
"Cutscene item (START_BATTLE): enemies[%u].abilities[%u] is "
"invalid",
(uint32_t)e, (uint32_t)a
);
}
enemy->abilities[a] = ability;
a++;
}
}
e++;
}
@@ -7,6 +7,7 @@
#pragma once
#include "rpg/battle/battle.h"
#include "rpg/battle/party.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
#define CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX 4
@@ -15,6 +16,7 @@ typedef struct {
battlefighterstats_t stats;
uint16_t healthMax;
uint16_t mpMax;
battleability_t abilities[BATTLE_FIGHTER_ABILITY_COUNT_MAX];
} cutscenestartbattleenemy_t;
typedef struct {
@@ -22,6 +24,13 @@ typedef struct {
bool_t fleeAvailable;
uint8_t enemyCount;
cutscenestartbattleenemy_t enemies[CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX];
// Active party order slots (see party.h) to bring into the battle, in
// the order they should be added. Defaults to every active slot, 0
// through PARTY_ACTIVE_SIZE_MAX - 1 in order, when the item's JSON
// omits "players" - see cutsceneStartBattleLoad.
uint8_t players[PARTY_ACTIVE_SIZE_MAX];
uint8_t playerCount;
} cutscenestartbattle_t;
/**
@@ -13,6 +13,22 @@
/** Maximum number of items that may run inside a CUTSCENE_CONCURRENT. */
#define CUTSCENE_CONCURRENT_MAX 8
/**
* Runs all listed items simultaneously and waits until all are done.
* Concurrent items cannot be nested inside another CUTSCENE_CONCURRENT.
*
* @param ... Child cutsceneitem_t entries (e.g. CUTSCENE_WAIT(...),
* CUTSCENE_ENTITY_WALK_TO(...)) to run at the same time.
*/
#define CUTSCENE_CONCURRENT(...) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_CONCURRENT, concurrent, { \
.items = (const cutsceneitem_t[]){ __VA_ARGS__ }, \
.count = (uint8_t)( \
sizeof((cutsceneitem_t[]){ __VA_ARGS__ }) / \
sizeof(cutsceneitem_t) \
) \
})
/**
* Static (const) data for a concurrent cutscene item.
*/
@@ -8,6 +8,14 @@
#pragma once
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Blocks the cutscene here indefinitely - it never completes on its own,
* only cutsceneGoTo (called externally, e.g. from a UI callback) can move
* execution past it.
*/
#define CUTSCENE_IDLE() \
{ .type = CUTSCENE_ITEM_TYPE_IDLE }
/**
* Updates an idle item. Never completes on its own - the cutscene blocks
* here indefinitely until something external (e.g. a UI callback) calls
@@ -12,6 +12,17 @@ typedef struct {
const char_t *name;
} cutscenemarker_t;
/**
* A named, otherwise no-op position in the item list that cutsceneGoTo
* can jump execution straight to.
*
* @param NAME Marker name, matched with stringEquals (not pointer
* identity) - safe to use separate string literals with the same
* contents at the marker and at each call site.
*/
#define CUTSCENE_MARKER(NAME) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MARKER, marker, { .name = NAME })
/**
* Starts a marker item. A marker does nothing on its own - it exists
* purely as a named position for cutsceneGoTo to jump to.
@@ -8,6 +8,13 @@
#pragma once
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Restarts the currently running cutscene from its first item,
* preserving whatever interact/interacted entities triggered it.
*/
#define CUTSCENE_RESTART() \
{ .type = CUTSCENE_ITEM_TYPE_RESTART }
/**
* Starts a restart item (restarts the currently running cutscene from
* its first item via cutsceneRestart).
@@ -13,6 +13,17 @@ typedef struct {
scenetype_t type;
} cutscenescene_t;
/**
* Requests a switch to a different SCENE_TYPE via sceneSet, then
* immediately continues on to whatever follows this item - the switch
* itself doesn't happen until the next sceneUpdate() tick, so it does
* not take effect this frame.
*
* @param TYPE Target scenetype_t to switch to.
*/
#define CUTSCENE_SCENE(TYPE) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_SCENE, sceneChange, { .type = TYPE })
/**
* Starts a scene item (requests a switch to the given scene via
* sceneSet). The switch itself doesn't happen until the next
@@ -9,6 +9,14 @@
#include "rpg/cutscene/cutscenepause.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Applies the given pause flags immediately.
*
* @param FLAGS CUTSCENE_PAUSE_* flags, OR'd together.
*/
#define CUTSCENE_SET_PAUSE(FLAGS) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_SET_PAUSE, setPause, (FLAGS))
/**
* Starts a set-pause item (applies the new pause flags immediately).
*
@@ -11,6 +11,14 @@
typedef float_t cutscenewait_t;
typedef float_t cutscenewaitdata_t;
/**
* Waits WAIT seconds before continuing.
*
* @param WAIT Duration in seconds.
*/
#define CUTSCENE_WAIT(WAIT) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_WAIT, wait, WAIT)
/**
* Starts a wait item (stores the duration in data).
*
@@ -10,6 +10,15 @@
typedef void (*cutscenecallback_t)(void *userData);
/**
* Invokes CALLBACK immediately, then continues on to whatever follows
* this item.
*
* @param CALLBACK A cutscenecallback_t function pointer.
*/
#define CUTSCENE_CALLBACK(CALLBACK) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_CALLBACK, callback, CALLBACK)
/**
* Starts a callback item (invokes the callback immediately).
*
+35 -13
View File
@@ -11,6 +11,7 @@
#include "asset/assetfile.h"
#include "asset/loader/assetloader.h"
#include "util/string.h"
#include "ui/overlay/uifatalerror.h"
cutsceneitemcallbacks_t CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT] = {
[CUTSCENE_ITEM_TYPE_NULL] = { 0 },
@@ -326,6 +327,12 @@ cutsceneitemcallbacks_t CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT] = {
.update = cutsceneUIShowUpdate,
.jsonName = "UI_SHOW",
.load = cutsceneUIShowLoad
},
[CUTSCENE_ITEM_TYPE_REGULAR_BATTLE] = {
.update = cutsceneRegularBattleUpdate,
.jsonName = "REGULAR_BATTLE",
.load = cutsceneItemLoadNoop
}
};
@@ -364,7 +371,14 @@ void cutsceneCutsceneStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
if(item->cutscene != NULL) cutsceneSystemStartCutscene(item->cutscene);
const cutscene_t *cutscene = item->cutsceneRef.cutscene;
if(cutscene == NULL && item->cutsceneRef.name != NULL) {
cutscene = cutsceneCutsceneResolve(item->cutsceneRef.name);
// Cache the resolved pointer back so replaying this same item (e.g.
// a looping intro) never re-resolves/re-locks the asset again.
((cutsceneitem_t *)item)->cutsceneRef.cutscene = cutscene;
}
if(cutscene != NULL) cutsceneSystemStartCutscene(cutscene);
}
bool_t cutsceneCutsceneUpdate(
@@ -374,6 +388,21 @@ bool_t cutsceneCutsceneUpdate(
return false;
}
const cutscene_t * cutsceneCutsceneResolve(const char_t *name) {
char_t path[ASSET_FILE_NAME_MAX];
stringFormat(path, sizeof(path), "cutscenes/%s.jsonc", name);
assetentry_t *entry = assetLock(path, ASSET_LOADER_TYPE_CUTSCENE, NULL);
errorret_t result = assetRequireLoaded(entry);
if(errorIsNotOk(result)) {
errorCatch(errorPrint(result));
uiFatalErrorOpen(NULL);
return NULL;
}
return &entry->data.cutscene.cutscene;
}
errorret_t cutsceneCutsceneLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
@@ -385,23 +414,16 @@ errorret_t cutsceneCutsceneLoad(
errorThrow("Cutscene item (CUTSCENE): missing 'name'");
}
// Referenced cutscene is a sibling asset (assets/cutscenes/<name>.jsonc),
// resolved to a stable pointer right now rather than deferred to
// runtime - assetRequireLoaded re-enters assetUpdate() safely from
// within this sync load (see its ASSET_ENTRY_STATE_LOADING_SYNC case),
// and the entry is locked forever (never unlocked) so the pointer
// stays valid for the process lifetime, same convention as
// ui/screen/mainmenu/uimainmenu.c's MAIN_MENU_CUTSCENE_ENTRY.
char_t path[ASSET_FILE_NAME_MAX];
// Only validate that the eventual "cutscenes/<name>.jsonc" path would
// fit - the reference itself is not resolved/locked until this item
// actually runs (see cutsceneCutsceneStart/cutsceneCutsceneResolve).
int32_t pathLen = stringFormat(NULL, 0, "cutscenes/%s.jsonc", name);
if(pathLen < 0 || (size_t)pathLen >= ASSET_FILE_NAME_MAX) {
errorThrow("Cutscene item (CUTSCENE): 'name' too long");
}
stringFormat(path, sizeof(path), "cutscenes/%s.jsonc", name);
assetentry_t *refEntry = assetLock(path, ASSET_LOADER_TYPE_CUTSCENE, NULL);
errorChain(assetRequireLoaded(refEntry));
item->cutscene = &refEntry->data.cutscene.cutscene;
item->cutsceneRef.cutscene = NULL;
item->cutsceneRef.name = name;
errorOk();
}
+41 -58
View File
@@ -8,6 +8,7 @@
#pragma once
#include "error/error.h"
#include "yyjson.h"
#include "cutsceneitembase.h"
#include "cutscenecallback.h"
#include "cutsceneprint.h"
#include "control/cutscenewait.h"
@@ -41,6 +42,7 @@
#include "battle/cutscenestartbattle.h"
#include "battle/cutscenebattlewaitstate.h"
#include "battle/cutscenebattleforceaction.h"
#include "battle/cutsceneregularbattle.h"
#include "save/cutscenesavedevicecheck.h"
#include "save/cutscenesaveloadallslots.h"
#include "audio/cutsceneaudioplay.h"
@@ -55,58 +57,19 @@
typedef struct cutscene_s cutscene_t;
typedef enum {
CUTSCENE_ITEM_TYPE_NULL,
CUTSCENE_ITEM_TYPE_TEXT,
CUTSCENE_ITEM_TYPE_TEXT_MINI,
CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE,
CUTSCENE_ITEM_TYPE_CALLBACK,
CUTSCENE_ITEM_TYPE_WAIT,
CUTSCENE_ITEM_TYPE_CUTSCENE,
CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT,
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO,
CUTSCENE_ITEM_TYPE_FADE,
CUTSCENE_ITEM_TYPE_SET_PAUSE,
CUTSCENE_ITEM_TYPE_CONCURRENT,
CUTSCENE_ITEM_TYPE_ITEM_GIVE,
CUTSCENE_ITEM_TYPE_ENTITY_REMOVE,
CUTSCENE_ITEM_TYPE_ENTITY_ADD,
CUTSCENE_ITEM_TYPE_ENTITY_TURN,
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY,
CUTSCENE_ITEM_TYPE_MAP_AREA_ADD,
CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE,
CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT,
CUTSCENE_ITEM_TYPE_START_BATTLE,
CUTSCENE_ITEM_TYPE_EMOJI,
CUTSCENE_ITEM_TYPE_SHAKE,
CUTSCENE_ITEM_TYPE_BATTLE_WAIT_STATE,
CUTSCENE_ITEM_TYPE_BATTLE_FORCE_ACTION,
CUTSCENE_ITEM_TYPE_MODAL,
CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS,
CUTSCENE_ITEM_TYPE_MODAL_CLOSE,
CUTSCENE_ITEM_TYPE_PRINT,
CUTSCENE_ITEM_TYPE_MARKER,
CUTSCENE_ITEM_TYPE_RESTART,
CUTSCENE_ITEM_TYPE_QUIT_GAME,
CUTSCENE_ITEM_TYPE_SCENE,
CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK,
CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS,
CUTSCENE_ITEM_TYPE_KEYBOARD,
CUTSCENE_ITEM_TYPE_AUDIO_PLAY,
CUTSCENE_ITEM_TYPE_AUDIO_STOP,
CUTSCENE_ITEM_TYPE_AUDIO_PAUSE,
CUTSCENE_ITEM_TYPE_AUDIO_RESUME,
CUTSCENE_ITEM_TYPE_AUDIO_FADE,
CUTSCENE_ITEM_TYPE_AUDIO_FADE_WAIT,
CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN,
CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP,
CUTSCENE_ITEM_TYPE_AUDIO_SET,
CUTSCENE_ITEM_TYPE_IDLE,
CUTSCENE_ITEM_TYPE_UI_SHOW,
CUTSCENE_ITEM_TYPE_COUNT
} cutsceneitemtype_t;
// A CUTSCENE item's target. C-authored cutscenes (the CUTSCENE_CUTSCENE
// macro in cutscene.h) resolve cutscene at compile time and leave name
// NULL. JSON-authored cutscenes (cutsceneCutsceneLoad) do the opposite -
// only name is set at parse time, since resolving/locking the referenced
// asset there would eagerly load every cutscene a cutscene merely
// references, even ones never played. cutsceneCutsceneStart resolves
// name to cutscene the first time this item actually runs (via
// cutsceneCutsceneResolve) and caches the result back into this field so
// replaying the same item never re-resolves it.
typedef struct {
const cutscene_t *cutscene;
const char_t *name;
} cutscenecutsceneref_t;
struct cutsceneitem_s {
cutsceneitemtype_t type;
@@ -117,7 +80,7 @@ struct cutsceneitem_s {
cutscenetextminihide_t textMiniHide;
cutscenecallback_t callback;
cutscenewait_t wait;
const cutscene_t *cutscene;
cutscenecutsceneref_t cutsceneRef;
cutsceneentityteleport_t entityTeleport;
cutsceneentitywalkto_t entityWalkTo;
cutscenefade_t fade;
@@ -235,7 +198,9 @@ bool_t cutsceneItemLookupType(
/**
* Starts a nested-cutscene item, handing control over to the
* referenced cutscene.
* referenced cutscene. If item->cutsceneRef.cutscene hasn't been
* resolved yet (a JSON-authored reference, only known by name so far),
* resolves and caches it first via cutsceneCutsceneResolve.
*
* @param item The cutscene item.
* @param data Runtime data storage.
@@ -245,6 +210,22 @@ void cutsceneCutsceneStart(
cutsceneitemdata_t *data
);
/**
* Resolves a JSON-authored CUTSCENE item's referenced cutscene by name,
* locking (forever - never unlocked, matching cutsceneCutsceneLoad's old
* convention) and blocking on assets/cutscenes/<name>.jsonc. Called
* lazily from cutsceneCutsceneStart the first time the item actually
* runs, not at parse time, so a cutscene referencing many others doesn't
* load every one of them up front. On failure, opens the fatal error
* overlay (matching cutsceneSystemLoad's runtime-failure handling) and
* returns NULL.
*
* @param name Bare cutscene name (without "cutscenes/" prefix or
* ".jsonc" suffix).
* @return The resolved cutscene, or NULL on failure.
*/
const cutscene_t * cutsceneCutsceneResolve(const char_t *name);
/**
* Updates a nested-cutscene item. By the time this would run, control
* has already moved on to the referenced cutscene, so this always
@@ -262,10 +243,12 @@ bool_t cutsceneCutsceneUpdate(
/**
* Parses a CUTSCENE cutscene item's JSON fields into item. Kept inline here
* (rather than its own file) since it's tightly bound to the asset/loader
* system itself - it resolves its 'name' to a sibling
* assets/cutscenes/<name>.jsonc asset at parse time, mirroring how
* cutsceneCutsceneStart/cutsceneCutsceneUpdate stay inline in
* cutsceneitem.c rather than getting their own file.
* system itself. Only stores the 'name' string (which points into the
* cutscene asset's still-alive yyjson doc, so no copy is needed) -
* resolving it to the referenced assets/cutscenes/<name>.jsonc asset is
* deferred to cutsceneCutsceneStart, the first time this item actually
* runs, so a cutscene referencing many others doesn't pay to load every
* one of them up front.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
@@ -13,6 +13,75 @@
typedef struct cutsceneitem_s cutsceneitem_t;
typedef union cutsceneitemdata_u cutsceneitemdata_t;
typedef enum {
CUTSCENE_ITEM_TYPE_NULL,
CUTSCENE_ITEM_TYPE_TEXT,
CUTSCENE_ITEM_TYPE_TEXT_MINI,
CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE,
CUTSCENE_ITEM_TYPE_CALLBACK,
CUTSCENE_ITEM_TYPE_WAIT,
CUTSCENE_ITEM_TYPE_CUTSCENE,
CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT,
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO,
CUTSCENE_ITEM_TYPE_FADE,
CUTSCENE_ITEM_TYPE_SET_PAUSE,
CUTSCENE_ITEM_TYPE_CONCURRENT,
CUTSCENE_ITEM_TYPE_ITEM_GIVE,
CUTSCENE_ITEM_TYPE_ENTITY_REMOVE,
CUTSCENE_ITEM_TYPE_ENTITY_ADD,
CUTSCENE_ITEM_TYPE_ENTITY_TURN,
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY,
CUTSCENE_ITEM_TYPE_MAP_AREA_ADD,
CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE,
CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT,
CUTSCENE_ITEM_TYPE_START_BATTLE,
CUTSCENE_ITEM_TYPE_EMOJI,
CUTSCENE_ITEM_TYPE_SHAKE,
CUTSCENE_ITEM_TYPE_BATTLE_WAIT_STATE,
CUTSCENE_ITEM_TYPE_BATTLE_FORCE_ACTION,
CUTSCENE_ITEM_TYPE_MODAL,
CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS,
CUTSCENE_ITEM_TYPE_MODAL_CLOSE,
CUTSCENE_ITEM_TYPE_PRINT,
CUTSCENE_ITEM_TYPE_MARKER,
CUTSCENE_ITEM_TYPE_RESTART,
CUTSCENE_ITEM_TYPE_QUIT_GAME,
CUTSCENE_ITEM_TYPE_SCENE,
CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK,
CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS,
CUTSCENE_ITEM_TYPE_KEYBOARD,
CUTSCENE_ITEM_TYPE_AUDIO_PLAY,
CUTSCENE_ITEM_TYPE_AUDIO_STOP,
CUTSCENE_ITEM_TYPE_AUDIO_PAUSE,
CUTSCENE_ITEM_TYPE_AUDIO_RESUME,
CUTSCENE_ITEM_TYPE_AUDIO_FADE,
CUTSCENE_ITEM_TYPE_AUDIO_FADE_WAIT,
CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN,
CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP,
CUTSCENE_ITEM_TYPE_AUDIO_SET,
CUTSCENE_ITEM_TYPE_IDLE,
CUTSCENE_ITEM_TYPE_UI_SHOW,
CUTSCENE_ITEM_TYPE_REGULAR_BATTLE,
CUTSCENE_ITEM_TYPE_COUNT
} cutsceneitemtype_t;
/**
* Shorthand for a cutsceneitem_t literal - used by each item type's own
* authoring macro (e.g. CUTSCENE_WAIT in cutscenewait.h) to fill in .type
* and its union member together.
*
* @param TYPE The item's CUTSCENE_ITEM_TYPE_* enum value.
* @param UNION_NAME Name of the cutsceneitem_t union member to fill.
* @param ... The union member's value. Passed through __VA_ARGS__ (rather
* than a single named parameter) so it may itself be a brace initializer
* with top-level commas, e.g.
* CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_FADE, fade, { .from = A, .to = B }).
*/
#define CUTSCENE_ITEM(TYPE, UNION_NAME, ...) \
{ .type = TYPE, .UNION_NAME = __VA_ARGS__ }
/**
* Shared no-op Load for item types with no JSON fields of their own to
* parse (IDLE, RESTART, MODAL_CLOSE) - always succeeds without touching
@@ -14,6 +14,14 @@ typedef struct {
char_t text[CUTSCENE_PRINT_MAX_CHARS];
} cutsceneprint_t;
/**
* Prints TEXT to the console.
*
* @param TEXT Text to print.
*/
#define CUTSCENE_PRINT(TEXT) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_PRINT, print, { .text = TEXT })
/**
* Starts a print item (prints the item's text to the console).
*
@@ -15,6 +15,19 @@ typedef struct {
worldpos_t position;
} cutsceneentityadd_t;
/**
* Spawns a new entity into the world immediately.
*
* @param TYPE Entity type to spawn.
* @param X Spawn world X.
* @param Y Spawn world Y.
* @param Z Spawn world Z.
*/
#define CUTSCENE_ENTITY_ADD(TYPE, X, Y, Z) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_ADD, entityAdd, { \
.entityType = TYPE, .position = { X, Y, Z } \
})
/**
* Starts an entity add step (spawns the entity into the world immediately).
*
@@ -12,6 +12,16 @@ typedef struct {
uint8_t entityIndex;
} cutsceneentityremove_t;
/**
* Removes an entity from the world immediately.
*
* @param ENTITY_INDEX Entity index to remove.
*/
#define CUTSCENE_ENTITY_REMOVE(ENTITY_INDEX) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_REMOVE, entityRemove, { \
.entityIndex = ENTITY_INDEX \
})
/**
* Starts an entity remove step (removes the entity from the world immediately).
*
@@ -14,6 +14,19 @@ typedef struct {
worldpos_t target;
} cutsceneentityteleport_t;
/**
* Teleports an entity to a world position immediately.
*
* @param ENTITY_INDEX Entity index to teleport.
* @param X Target world X.
* @param Y Target world Y.
* @param Z Target world Z.
*/
#define CUTSCENE_ENTITY_TELEPORT(ENTITY_INDEX, X, Y, Z) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT, entityTeleport, { \
.entityIndex = ENTITY_INDEX, .target = { X, Y, Z } \
})
/**
* Starts an entity teleport item (teleports the entity immediately).
*
@@ -14,6 +14,17 @@ typedef struct {
entitydir_t direction;
} cutsceneentityturn_t;
/**
* Turns an entity to face a direction.
*
* @param ENTITY_INDEX Entity index to turn.
* @param DIRECTION Target entitydir_t to face.
*/
#define CUTSCENE_ENTITY_TURN(ENTITY_INDEX, DIRECTION) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_TURN, entityTurn, { \
.entityIndex = ENTITY_INDEX, .direction = DIRECTION \
})
/**
* Starts an entity turn step. The turn itself is driven from Update, since
* the entity may still be finishing a previous action.
@@ -20,6 +20,45 @@ typedef struct {
uint8_t currentIndex;
} cutsceneentitywalktodata_t;
/**
* Walks an entity to a single world position, navigating around
* obstacles.
*
* @param ENTITY_INDEX Entity index to move.
* @param X Target world X.
* @param Y Target world Y.
* @param Z Target world Z.
*/
#define CUTSCENE_ENTITY_WALK_TO(ENTITY_INDEX, X, Y, Z) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO, entityWalkTo, { \
.entityIndex = ENTITY_INDEX, \
.positions = (const worldpos_t[]){ { X, Y, Z } }, \
.count = 1, \
.walkAround = true \
})
/**
* Declares a standalone, named cutsceneitem_t (not a list entry) that
* walks an entity through a fixed sequence of waypoints.
*
* @param NAME Suffix for the generated CUTSCENE_##NAME item/positions
* statics.
* @param ENTITY_INDEX Entity index to move.
* @param ... One or more worldpos_t-shaped waypoint initializers, e.g.
* { X, Y, Z }, { X2, Y2, Z2 }.
*/
#define CUTSCENE_ENTITY_WALK_PATH(NAME, ENTITY_INDEX, ...) \
static const worldpos_t CUTSCENE_##NAME##_POSITIONS[] = { __VA_ARGS__ }; \
static const cutsceneitem_t CUTSCENE_##NAME = { \
.type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO, \
.entityWalkTo = { \
.entityIndex = ENTITY_INDEX, \
.positions = CUTSCENE_##NAME##_POSITIONS, \
.count = sizeof(CUTSCENE_##NAME##_POSITIONS) / sizeof(worldpos_t), \
.walkAround = true \
} \
};
/**
* Starts an entity walk-to item (resets the waypoint index).
*
@@ -16,6 +16,27 @@ typedef struct {
worldunit_t offsetY;
} cutsceneentitywalktoentity_t;
/**
* Walks ENTITY_INDEX to stand beside TARGET_ENTITY_INDEX, offset by
* (OFFSET_X, OFFSET_Y) on the 2D plane. The destination Z is resolved
* from nearby terrain each frame, so ramps between the two entities are
* accounted for automatically.
*
* @param ENTITY_INDEX Entity index to move.
* @param TARGET_ENTITY_INDEX Entity index to walk toward.
* @param OFFSET_X X offset from the target entity's position.
* @param OFFSET_Y Y offset from the target entity's position.
*/
#define CUTSCENE_ENTITY_WALK_TO_ENTITY( \
ENTITY_INDEX, TARGET_ENTITY_INDEX, OFFSET_X, OFFSET_Y \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY, entityWalkToEntity, { \
.entityIndex = ENTITY_INDEX, \
.targetEntityIndex = TARGET_ENTITY_INDEX, \
.offsetX = OFFSET_X, \
.offsetY = OFFSET_Y \
})
/**
* Starts an entity walk-to-entity item. No setup is needed, the destination
* is recomputed from the target's live position every Update.
@@ -14,6 +14,17 @@ typedef struct {
uint8_t quantity;
} cutsceneitemgive_t;
/**
* Adds an item to the player's backpack immediately.
*
* @param ITEM_ID Item ID to give.
* @param QUANTITY Quantity to give.
*/
#define CUTSCENE_ITEM_GIVE(ITEM_ID, QUANTITY) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ITEM_GIVE, itemGive, { \
.item = ITEM_ID, .quantity = QUANTITY \
})
/**
* Starts a give-item step (adds the item to the player's backpack immediately).
*
@@ -16,6 +16,7 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
cutscenejsonentitytype.c
cutscenejsonentitydir.c
cutscenejsonbattleencounter.c
cutscenejsonbattleability.c
cutscenejsonbattlestate.c
cutscenejsonscenetype.c
cutscenejsonuiscreentype.c
@@ -0,0 +1,31 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "cutscenejsonbattleability.h"
#include "cutscenejsonenum.h"
static const cutscenejsonenumentry_t CUTSCENE_JSON_BATTLE_ABILITY_TABLE[] = {
{ "FIRE", BATTLE_ABILITY_FIRE },
};
#define CUTSCENE_JSON_BATTLE_ABILITY_TABLE_COUNT \
(sizeof(CUTSCENE_JSON_BATTLE_ABILITY_TABLE) / \
sizeof(cutscenejsonenumentry_t))
bool_t cutsceneJsonLookupBattleAbility(
const char_t *name,
battleability_t *out
) {
int32_t value;
if(!cutsceneJsonLookupEnumInsensitive(
CUTSCENE_JSON_BATTLE_ABILITY_TABLE,
CUTSCENE_JSON_BATTLE_ABILITY_TABLE_COUNT, name, &value
)) {
return false;
}
*out = (battleability_t)value;
return true;
}
@@ -0,0 +1,22 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#include "rpg/battle/battleability.h"
/**
* Looks up name (case-insensitively) against the battle ability table.
*
* @param name Name to search for.
* @param out Set to the matching ability on success.
* @return true if a matching entry was found, false otherwise.
*/
bool_t cutsceneJsonLookupBattleAbility(
const char_t *name,
battleability_t *out
);
@@ -8,6 +8,8 @@
#pragma once
#include "rpg/cutscene/item/cutsceneitembase.h"
#include "rpg/overworld/maparea.h"
#include "rpg/cutscene/item/maparea/cutscenemapareawait.h"
#include "rpg/cutscene/item/maparea/cutscenemaparearemove.h"
typedef struct {
worldpos_t min;
@@ -17,6 +19,55 @@ typedef struct {
uint8_t trigger;
} cutscenemapareaadd_t;
/**
* Adds a map area immediately, storing its ID in
* CUTSCENE_SYSTEM.areaLastCreated.
*
* @param MIN_X Area bounding box minimum world X.
* @param MIN_Y Area bounding box minimum world Y.
* @param MIN_Z Area bounding box minimum world Z.
* @param MAX_X Area bounding box maximum world X.
* @param MAX_Y Area bounding box maximum world Y.
* @param MAX_Z Area bounding box maximum world Z.
* @param CALLBACK mapareacallback_t to invoke when the area is triggered.
* @param NOTIFY Notify count/threshold passed to the area.
* @param TRIGGER Trigger count/threshold passed to the area.
*/
#define CUTSCENE_MAP_AREA_ADD( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, CALLBACK, NOTIFY, TRIGGER \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MAP_AREA_ADD, mapAreaAdd, { \
.min = { MIN_X, MIN_Y, MIN_Z }, \
.max = { MAX_X, MAX_Y, MAX_Z }, \
.callback = CALLBACK, \
.notify = NOTIFY, \
.trigger = TRIGGER \
})
/**
* Adds a map area, waits for it to be triggered once, then removes it
* before the cutscene continues. Uses a no-op callback since the wait is
* driven by the area's trigger count rather than callback logic.
*
* @param MIN_X Area bounding box minimum world X.
* @param MIN_Y Area bounding box minimum world Y.
* @param MIN_Z Area bounding box minimum world Z.
* @param MAX_X Area bounding box maximum world X.
* @param MAX_Y Area bounding box maximum world Y.
* @param MAX_Z Area bounding box maximum world Z.
* @param NOTIFY Notify count/threshold passed to the area.
* @param TRIGGER Trigger count/threshold passed to the area.
*/
#define CUTSCENE_MAP_AREA_TRIGGER_ONCE( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, NOTIFY, TRIGGER \
) \
CUTSCENE_MAP_AREA_ADD( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, \
mapAreaNoopCallback, NOTIFY, TRIGGER \
), \
CUTSCENE_MAP_AREA_WAIT(CUTSCENE_AREA_LAST_CREATED), \
CUTSCENE_MAP_AREA_REMOVE(CUTSCENE_AREA_LAST_CREATED)
/**
* Starts a map area add step (adds the area immediately, storing its ID
* in CUTSCENE_SYSTEM.areaLastCreated).
@@ -12,6 +12,17 @@ typedef struct {
uint8_t areaId;
} cutscenemaparearemove_t;
/**
* Removes a map area immediately.
*
* @param AREA_ID Area ID to remove, or CUTSCENE_AREA_LAST_CREATED in
* place of a literal area ID.
*/
#define CUTSCENE_MAP_AREA_REMOVE(AREA_ID) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE, mapAreaRemove, { \
.areaId = AREA_ID \
})
/**
* Starts a map area remove step (removes the area immediately). Accepts
* CUTSCENE_AREA_LAST_CREATED in place of a literal area ID.
@@ -20,6 +20,20 @@ typedef struct {
uint32_t baseline[CUTSCENE_MAP_AREA_WAIT_MAX];
} cutscenemapareawaitdata_t;
/**
* Waits until any one of the given map area IDs has its callback invoked.
*
* @param ... One or more area IDs to watch. Accepts
* CUTSCENE_AREA_LAST_CREATED in place of a literal area ID.
*/
#define CUTSCENE_MAP_AREA_WAIT(...) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT, mapAreaWait, { \
.areaIds = (const uint8_t[]){ __VA_ARGS__ }, \
.count = (uint8_t)( \
sizeof((const uint8_t[]){ __VA_ARGS__ }) / sizeof(uint8_t) \
) \
})
/**
* Starts a map area wait step, snapshotting each watched area's current
* trigger count.
@@ -13,6 +13,22 @@ typedef struct {
const char_t *failureMarker;
} cutscenesavedevicecheck_t;
/**
* (Re)requests an available save device and jumps straight to
* SUCCESS_MARKER or FAILURE_MARKER once it resolves, same as a
* CUTSCENE_MODAL_OPTIONS callback - it does not fall through to
* whatever follows this item, so both markers must be scripted
* elsewhere in the same cutscene.
*
* @param SUCCESS_MARKER Marker to jump to if a device is available.
* @param FAILURE_MARKER Marker to jump to if no device is available.
*/
#define CUTSCENE_SAVE_DEVICE_CHECK(SUCCESS_MARKER, FAILURE_MARKER) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK, saveDeviceCheck, { \
.successMarker = SUCCESS_MARKER, \
.failureMarker = FAILURE_MARKER \
})
/**
* Starts a save-device-check item: (re)requests an available save
* device via saveFindAvailableDevice. Never completes on its own - see
@@ -13,6 +13,22 @@ typedef struct {
const char_t *failureMarker;
} cutscenesaveloadallslots_t;
/**
* (Re)loads every save slot via saveLoadAllSlots() and jumps straight to
* SUCCESS_MARKER or FAILURE_MARKER once it resolves, same shape as
* CUTSCENE_SAVE_DEVICE_CHECK - it does not fall through to whatever
* follows this item, so both markers must be scripted elsewhere in the
* same cutscene.
*
* @param SUCCESS_MARKER Marker to jump to on success.
* @param FAILURE_MARKER Marker to jump to on failure.
*/
#define CUTSCENE_SAVE_LOAD_ALL_SLOTS(SUCCESS_MARKER, FAILURE_MARKER) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS, saveLoadAllSlots, { \
.successMarker = SUCCESS_MARKER, \
.failureMarker = FAILURE_MARKER \
})
/**
* Starts a save-load-all-slots item: calls saveLoadAllSlots() and jumps
* straight to the item's successMarker or failureMarker via
@@ -15,6 +15,21 @@ typedef struct {
uiemojitype_t emojiType;
} cutsceneemoji_t;
/**
* Shows an emoji above an entity for a duration, then completes
* immediately.
*
* @param ENTITY_INDEX Entity index to show the emoji above.
* @param EMOJI_TYPE uiemojitype_t to show.
* @param DURATION Duration in seconds to show it.
*/
#define CUTSCENE_EMOJI(ENTITY_INDEX, EMOJI_TYPE, DURATION) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_EMOJI, emoji, { \
.entityIndex = ENTITY_INDEX, \
.emojiType = EMOJI_TYPE, \
.duration = DURATION \
})
/**
* Starts an emoji step (shows an emoji above the entity for the given
* duration, then completes immediately).
@@ -17,6 +17,52 @@ typedef struct {
easingtype_t easing;
} cutscenefade_t;
/**
* Longhand - begins a full-screen overlay transition between two colors.
* See the CUTSCENE_FADE_(TO|FROM)_(BLACK|WHITE) shorthands below.
*
* @param FROM Starting color_t.
* @param TO Ending color_t.
* @param DURATION Duration in seconds.
* @param EASING easingtype_t to apply.
*/
#define CUTSCENE_FADE(FROM, TO, DURATION, EASING) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_FADE, fade, { \
.from = FROM, .to = TO, .duration = DURATION, .easing = EASING \
})
/**
* Shorthand: fades from transparent to black over DURATION seconds.
*
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_FADE_TO_BLACK(DURATION) \
CUTSCENE_FADE(COLOR_TRANSPARENT_BLACK, COLOR_BLACK, DURATION, EASING_LINEAR)
/**
* Shorthand: fades from black to transparent over DURATION seconds.
*
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_FADE_FROM_BLACK(DURATION) \
CUTSCENE_FADE(COLOR_BLACK, COLOR_TRANSPARENT_BLACK, DURATION, EASING_LINEAR)
/**
* Shorthand: fades from transparent to white over DURATION seconds.
*
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_FADE_TO_WHITE(DURATION) \
CUTSCENE_FADE(COLOR_TRANSPARENT_WHITE, COLOR_WHITE, DURATION, EASING_LINEAR)
/**
* Shorthand: fades from white to transparent over DURATION seconds.
*
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_FADE_FROM_WHITE(DURATION) \
CUTSCENE_FADE(COLOR_WHITE, COLOR_TRANSPARENT_WHITE, DURATION, EASING_LINEAR)
/**
* Starts a fade item (begins the overlay transition).
*
@@ -14,6 +14,19 @@ typedef struct {
uikeyboardopen_t open;
} cutscenekeyboard_t;
/**
* Opens the on-screen keyboard and blocks the cutscene until it closes,
* then caches whatever was typed - see cutsceneSystemGetTextCache to
* read it back afterwards.
*
* @param ... uikeyboardopen_t designated initializers, e.g.
* CUTSCENE_KEYBOARD(.cancel = true, .maxLength = 8).
*/
#define CUTSCENE_KEYBOARD(...) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_KEYBOARD, keyboard, { \
.open = { __VA_ARGS__ } \
})
/**
* Starts a keyboard item (opens the on-screen keyboard with the item's
* open parameters, unmodified - see uiKeyboardOpen).
@@ -41,6 +41,59 @@ typedef struct {
cutscenemodaloptioncallback_t callback;
} cutscenemodal_t;
/**
* Shows a message-only modal (no option buttons) and immediately
* continues on to whatever follows this item - it does not wait for
* the dialog to be dismissed. Script the rest of the interaction (e.g.
* CUTSCENE_CALLBACK to kick off work, CUTSCENE_WAIT, then
* CUTSCENE_MODAL_CLOSE) as later items in the same cutscene.
*
* @param TITLE Modal title - displayed as-is unless it matches a locale
* message ID, in which case the translated string is shown - see
* uiModalLocalize.
* @param MESSAGE Modal message, same locale-matching rule as TITLE.
*/
#define CUTSCENE_MODAL(TITLE, MESSAGE) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MODAL, modal, { \
.title = TITLE, .message = MESSAGE \
})
/**
* Shows a modal with option buttons and immediately continues on, same
* as CUTSCENE_MODAL - it does not block waiting for a selection.
* Back/cancel input is disabled while it's open (see
* uiMenuSetDisableBack), so it must be dismissed by picking one; CALLBACK
* then fires with the selected option index once the dialog closes.
*
* @param TITLE Modal title (locale-matched, see CUTSCENE_MODAL).
* @param MESSAGE Modal message (locale-matched, see CUTSCENE_MODAL).
* @param CALLBACK cutscenemodaloptioncallback_t fired with the selected
* option index once the dialog closes.
* @param ... Option label strings, e.g.
* CUTSCENE_MODAL_OPTIONS(title, message, callback, "Retry", "Cancel") -
* not copied by this item, so they must stay valid until the modal opens
* (string literals are fine). Each is translated if it matches a locale
* message ID, same as TITLE/MESSAGE.
*/
#define CUTSCENE_MODAL_OPTIONS(TITLE, MESSAGE, CALLBACK, ...) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MODAL, modal, { \
.title = TITLE, .message = MESSAGE, \
.options = (const char_t *[]){ __VA_ARGS__ }, \
.optionCount = (uint8_t)( \
sizeof((const char_t *[]){ __VA_ARGS__ }) / sizeof(const char_t *) \
), \
.callback = CALLBACK \
})
/**
* Closes the currently open modal (if any). Useful when a modal was
* opened outside of a blocking CUTSCENE_MODAL item (e.g. directly via
* uiModalOpen) and this cutscene just needs to dismiss it and continue
* on to whatever follows this item in the sequence.
*/
#define CUTSCENE_MODAL_CLOSE() \
{ .type = CUTSCENE_ITEM_TYPE_MODAL_CLOSE }
/**
* Starts a modal item (shows the modal dialog with the item's title,
* message, and options, wiring callback to fire with the selected
@@ -7,6 +7,7 @@
#pragma once
#include "rpg/cutscene/item/cutsceneitembase.h"
#include "rpg/cutscene/item/ui/cutscenemodal.h"
// Backs CUTSCENE_MODAL_OPTIONS_ONE and CUTSCENE_MODAL_OPTIONS_TWO, so two
// is the most either macro ever needs.
@@ -25,6 +26,49 @@ typedef struct {
uint8_t optionCount;
} cutscenemodaloptionsmarkers_t;
/**
* Same as CUTSCENE_MODAL_OPTIONS, but fixed to exactly one option and
* MARKER1 to jump straight to via cutsceneGoTo once it's selected - no
* callback function to write. Does not fall through to whatever follows
* this item, so MARKER1 must be scripted elsewhere in the same cutscene.
*
* @param TITLE Modal title (locale-matched, see CUTSCENE_MODAL).
* @param MESSAGE Modal message (locale-matched, see CUTSCENE_MODAL).
* @param OPTION1 The single option's label.
* @param MARKER1 Marker to jump to when OPTION1 is selected.
*/
#define CUTSCENE_MODAL_OPTIONS_ONE(TITLE, MESSAGE, OPTION1, MARKER1) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS, modalOptionsMarkers, { \
.title = TITLE, .message = MESSAGE, \
.options = { OPTION1 }, \
.markers = { MARKER1 }, \
.optionCount = 1 \
})
/**
* Same as CUTSCENE_MODAL_OPTIONS, but fixed to exactly two options,
* jumping straight to OPTION1_MARKER or OPTION2_MARKER via cutsceneGoTo
* once the corresponding option is selected - no callback function to
* write. Does not fall through to whatever follows this item, so both
* markers must be scripted elsewhere in the same cutscene.
*
* @param TITLE Modal title (locale-matched, see CUTSCENE_MODAL).
* @param MESSAGE Modal message (locale-matched, see CUTSCENE_MODAL).
* @param OPTION1 First option's label.
* @param OPTION1_MARKER Marker to jump to when OPTION1 is selected.
* @param OPTION2 Second option's label.
* @param OPTION2_MARKER Marker to jump to when OPTION2 is selected.
*/
#define CUTSCENE_MODAL_OPTIONS_TWO( \
TITLE, MESSAGE, OPTION1, OPTION1_MARKER, OPTION2, OPTION2_MARKER \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS, modalOptionsMarkers, { \
.title = TITLE, .message = MESSAGE, \
.options = { OPTION1, OPTION2 }, \
.markers = { OPTION1_MARKER, OPTION2_MARKER }, \
.optionCount = 2 \
})
/**
* Starts a modal-options-markers item (shows the modal dialog with the
* item's title, message, and options).
@@ -13,6 +13,18 @@ typedef struct {
float_t duration;
} cutsceneshake_t;
/**
* Kicks off a camera shake immediately.
*
* @param AMOUNT Shake amount, 0 (no shake) to 4 (three tiles): 1 is half
* a tile, 2 is a full tile, 3 is two tiles, and 4 is three tiles.
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_SHAKE(AMOUNT, DURATION) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_SHAKE, shake, { \
.amount = AMOUNT, .duration = DURATION \
})
/**
* Starts a camera shake item (kicks off the shake on the RPG camera).
*
@@ -14,6 +14,14 @@ typedef struct {
char_t text[CUTSCENE_TEXT_MAX_CHARS];
} cutscenetext_t;
/**
* Shows the textbox with TEXT, blocking until it's dismissed.
*
* @param TEXT Text to display.
*/
#define CUTSCENE_TEXT(TEXT) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_TEXT, text, { .text = TEXT })
/**
* Starts a text item (shows the textbox with the item's text).
*
@@ -16,6 +16,23 @@ typedef struct {
float_t duration;
} cutscenetextmini_t;
/**
* Shows a mini textbox at a world position for a duration, then
* completes immediately.
*
* @param TEXT Text to display.
* @param X World X of the mini textbox.
* @param Y World Y of the mini textbox.
* @param Z World Z of the mini textbox.
* @param DURATION Duration in seconds to show it.
*/
#define CUTSCENE_TEXT_MINI(TEXT, X, Y, Z, DURATION) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_TEXT_MINI, textMini, { \
.text = TEXT, \
.position = { X, Y, Z }, \
.duration = DURATION \
})
/**
* Starts a mini text item (shows a mini textbox at the given world
* position for the given duration, then completes immediately).
@@ -12,6 +12,16 @@ typedef struct {
uint8_t index;
} cutscenetextminihide_t;
/**
* Closes a mini textbox immediately.
*
* @param INDEX Mini textbox index to close.
*/
#define CUTSCENE_TEXT_MINI_HIDE(INDEX) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE, textMiniHide, { \
.index = INDEX \
})
/**
* Starts a mini text hide step (closes the mini textbox immediately).
*
@@ -21,6 +21,15 @@ typedef struct {
uiscreentype_t screen;
} cutsceneuishow_t;
/**
* Opens a full-screen UI panel (e.g. the main menu) declaratively, then
* immediately continues on to whatever follows this item.
*
* @param SCREEN uiscreentype_t to open.
*/
#define CUTSCENE_UI_SHOW(SCREEN) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_UI_SHOW, uiShow, { .screen = SCREEN })
/**
* Starts a UI_SHOW item, opening the requested full-screen UI panel.
*
@@ -8,6 +8,7 @@
#pragma once
#include "entityglobaldefs.h"
#include "rpg/cutscene/scene/testcutscene.h"
#include "rpg/cutscene/item/cutsceneitem.h"
ENTITY_GLOBAL_CALLBACK(3) {
create->entity->data.npc.moveType = NPC_MOVE_TYPE_PATH;
@@ -20,11 +21,17 @@ ENTITY_GLOBAL_CALLBACK(3) {
create->entity->interact.data.cutscene = CUTSCENE_REFERENCE(TEST_TWO);
}
ENTITY_GLOBAL_CALLBACK(4) {
create->entity->interact.type = ENTITY_INTERACT_CUTSCENE;
create->entity->interact.data.cutscene = cutsceneCutsceneResolve("battletest");
}
static const entityglobaldef_t ENTITY_GLOBAL_LIST[] = {
ENTITY_GLOBAL(ENTITY_GLOBAL_ID_NULL, ENTITY_TYPE_NULL, NULL),
ENTITY_GLOBAL(ENTITY_GLOBAL_ID_PLAYER, ENTITY_TYPE_PLAYER, NULL),
ENTITY_GLOBAL(3, ENTITY_TYPE_NPC, ENTITY_GLOBAL_REF(3)),
ENTITY_GLOBAL(4, ENTITY_TYPE_NPC, ENTITY_GLOBAL_REF(4)),
};
//EOF
+1 -3
View File
@@ -12,6 +12,7 @@
#include "rpg/cutscene/cutscenesystem.h"
#include "rpg/item/backpack.h"
#include "rpg/battle/party.h"
#include "save/save.h"
#include "ui/rpg/textbox/uitextboxminilist.h"
#include "time/time.h"
#include "rpgcamera.h"
@@ -32,9 +33,6 @@ errorret_t rpgInit(void) {
errorChain(mapInit());
rpgCameraInit();
// Init test world
errorChain(mapSetMap("overworld"));
// The player is the one entity that isn't sourced from map/chunk data -
// every other entity (NPCs, items) and map area comes from the loaded
// chunks' own spawn data (see rpg/overworld/map.c mapChunkLoaded).
+5 -4
View File
@@ -21,7 +21,7 @@ errorret_t saveInit() {
// Initialize the slots and settings
saveSettingsInit(&SAVE.settings);
saveSlotInit(&SAVE.slot);
saveSlotInit();
// Update caches to match default data.
for(uint8_t i = 0; i < SAVE_SLOT_COUNT; i++) {
@@ -226,7 +226,7 @@ errorret_t saveLoadSlot() {
if(SAVE.deviceCurrent == 0xFF) {
// No save device available, so we assume an empty slot.
saveSlotInit(&SAVE.slot);
saveSlotInit();
SAVE.caches[SAVE.slotCurrent] = SAVE.slot.cachedData;
errorOk();
}
@@ -245,7 +245,8 @@ errorret_t saveLoadSlot() {
"Save slot %u could not be loaded, treating as empty.\n",
(uint32_t)SAVE.slotCurrent
);
saveSlotInit(&SAVE.slot);
saveSlotInit();
SAVE.slot.cachedData.corrupt = true;
}
@@ -259,7 +260,7 @@ errorret_t saveLoadSlot() {
errorret_t saveLoadAllSlots() {
for(uint8_t i = 0; i < SAVE_SLOT_COUNT; i++) {
SAVE.slotCurrent = i;
saveSlotInit(&SAVE.slot);
saveSlotInit();
errorChain(saveLoadSlot());// Load slot updates the cache.
}
+8 -1
View File
@@ -340,8 +340,15 @@ errorret_t saveDeviceRawStoreItem(
slotItems[i].ptr = oldSpans.slots[i].ptr;
slotItems[i].len = oldSpans.slots[i].len;
} else {
// A raw reset, not saveSlotInit() - this fills in a slot index the
// current write isn't touching, and saveSlotInit() only ever
// operates on SAVE.slot now. A blank ("" name) slot never actually
// needs a properly-initialized party (see saveSlotReadJSON's early
// return for an unused slot), so this is equivalent for this
// filler-only purpose.
saveslot_t defaultSlot;
saveSlotInit(&defaultSlot);
memorySet(&defaultSlot, 0, sizeof(defaultSlot));
defaultSlot.version = 1;
char_t *json = NULL;
size_t len = 0;
errorret_t result = saveDeviceRawSerializeSlot(&defaultSlot, &json, &len);
+136 -3
View File
@@ -353,6 +353,119 @@
} \
}
/**
* Attaches an already-built mutable value (e.g. a yyjson_mut_arr() of
* per-element objects the caller populated by hand) to the current JSON
* object under the given key.
*
* @param key The key to write to.
* @param value The yyjson_mut_val* to attach.
*/
#define writeValue(key, value) yyjson_mut_obj_add_val(doc, object, key, value)
/**
* Appends a new JSON object to the given mutable array as one element and
* declares `object` in the calling scope pointing at it, shadowing any
* outer `object` - so the writeX macros above, once called inside the loop
* that builds `arr`, populate this element instead of the outer object.
*
* @param arr The yyjson_mut_val* array (from yyjson_mut_arr()) to append to.
*/
#define writeArrayObject(arr) \
yyjson_mut_val *object = yyjson_mut_arr_add_obj(doc, arr)
/**
* Requires a key on the current JSON object to be a JSON array of exactly
* the given size, throwing otherwise. Declares `dest` (a yyjson_val*) in
* the calling scope pointing at the array, ready for the caller to iterate
* (e.g. with yyjson_arr_foreach) - unlike the readXArray macros, this
* doesn't copy the elements out itself, since each element here is a
* nested object the caller parses by hand.
*
* @param key The key to read from.
* @param dest The yyjson_val* variable to declare, pointing at the array.
* @param count The exact number of elements the array must have.
*/
#define requireArrayOfSize(key, dest, count) \
yyjson_val *dest = yyjson_obj_get(object, key); \
if((dest) == NULL) errorThrow("Save JSON missing '%s' key", key); \
if(yyjson_arr_size(dest) != (size_t)(count)) { \
errorThrow( \
"Save JSON array '%s' has wrong length, expected %d", \
key, (int)(count) \
); \
}
/**
* Checks if the given key exists on the current JSON object.
*
* @param key The key to check for.
*/
#define hasUInt8Array(key) (yyjson_obj_get(object, key) != NULL)
/**
* Errors if the given key does not exist on the current JSON object.
*
* @param key The key that must exist.
*/
#define requireUInt8Array(key) \
if(!hasUInt8Array(key)) errorThrow("Save JSON missing '%s' key", key)
/**
* Writes a uint8_t array to the current JSON object.
*
* @param key The key to write to.
* @param value The array to write.
* @param count Number of elements in the array.
*/
#define writeUInt8Array(key, value, count) { \
yyjson_mut_val *saveJsonArr = yyjson_mut_arr(doc); \
size_t saveJsonArrIdx = 0; \
while(saveJsonArrIdx < (size_t)(count)) { \
yyjson_mut_arr_add_uint( \
doc, saveJsonArr, (uint64_t)(value)[saveJsonArrIdx] \
); \
saveJsonArrIdx++; \
} \
yyjson_mut_obj_add_val(doc, object, key, saveJsonArr); \
}
/**
* Reads a uint8_t array from the current JSON object into dest, falling
* back to filling every element with def if the key is missing. Errors if
* the JSON array's length doesn't exactly match count.
*
* @param key The key to read from.
* @param dest The destination array to assign to.
* @param count Number of elements dest holds.
* @param def The default value to fill every element with if the key is
* missing.
*/
#define readUInt8Array(key, dest, count, def) { \
yyjson_val *saveJsonArr = yyjson_obj_get(object, key); \
if(saveJsonArr != NULL) { \
if(yyjson_arr_size(saveJsonArr) != (size_t)(count)) { \
errorThrow( \
"Save JSON array '%s' has wrong length, expected %d", \
key, (int)(count) \
); \
} \
size_t saveJsonArrIdx, saveJsonArrLen; \
yyjson_val *saveJsonArrElem; \
yyjson_arr_foreach( \
saveJsonArr, saveJsonArrIdx, saveJsonArrLen, saveJsonArrElem \
) { \
(dest)[saveJsonArrIdx] = (uint8_t)yyjson_get_uint(saveJsonArrElem); \
} \
} else { \
size_t saveJsonArrIdx = 0; \
while(saveJsonArrIdx < (size_t)(count)) { \
(dest)[saveJsonArrIdx] = (uint8_t)(def); \
saveJsonArrIdx++; \
} \
} \
}
/**
* Checks if the given key exists on the current JSON object.
*
@@ -368,6 +481,26 @@
#define requireString(key) \
if(!hasString(key)) errorThrow("Save JSON missing '%s' key", key)
/**
* Errors if the given key is missing, not a string, or a string shorter
* than the given minimum length - e.g. requireStrMin(key, 1) to reject a
* missing/null/empty string outright.
*
* @param key The key to check.
* @param len The minimum string length required.
*/
#define requireStrMin(key, len) { \
yyjson_val *saveJsonStrMinVal = yyjson_obj_get(object, key); \
if( \
saveJsonStrMinVal == NULL || !yyjson_is_str(saveJsonStrMinVal) || \
yyjson_get_len(saveJsonStrMinVal) < (size_t)(len) \
) { \
errorThrow( \
"Save JSON '%s' must be a string of at least length %d", key, (int)(len) \
); \
} \
}
/**
* Writes a string to the current JSON object. The string is copied, so it
* does not need to outlive the JSON document.
@@ -399,12 +532,12 @@
); \
} \
stringCopy( \
saveJsonStringBuffer, yyjson_get_str(saveJsonStrVal), (maxLength) \
saveJsonStringBuffer, yyjson_get_str(saveJsonStrVal), (maxLength) + 1 \
); \
} else { \
stringCopy(saveJsonStringBuffer, (def), (maxLength)); \
stringCopy(saveJsonStringBuffer, (def), (maxLength) + 1); \
} \
stringCopy((dest), saveJsonStringBuffer, (maxLength)); \
stringCopy((dest), saveJsonStringBuffer, (maxLength) + 1); \
}
/**
+34 -4
View File
@@ -7,14 +7,32 @@
#include "saveslot.h"
#include "save/slot/saveslotcurrent.h"
#include "save/save.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
void saveSlotInit(saveslot_t *slot) {
assertNotNull(slot, "Slot cannot be null");
void saveSlotInit(void) {
memorySet(&SAVE.slot, 0, sizeof(saveslot_t));
memorySet(slot, 0, sizeof(saveslot_t));
slot->version = 1;
SAVE.slot.version = 1;
partyInit();
}
void saveSlotNewGame(void) {
saveSlotInit();
stringCopy(
SAVE.slot.cachedData.mapName, SAVE_SLOT_MAP_NAME_DEFAULT,
sizeof(SAVE.slot.cachedData.mapName)
);
// TEMPORARY: placeholder starting party stats - replace once there's a
// real starting-party/character-creation flow.
const battlefighterstats_t startingStats =
{ .attack = 10, .defense = 5, .magic = 0, .speed = 10, .luck = 0 };
partyAddMember(startingStats, 30, 10);
}
bool_t saveSlotInUse(saveslotcache_t *slot) {
@@ -37,6 +55,18 @@ errorret_t saveSlotWriteJSON(
}
errorret_t saveSlotReadJSON(saveslot_t *slot, yyjson_val *object) {
assertNotNull(slot, "Slot cannot be null");
assertNotNull(object, "Object cannot be null");
// A plain reset, not saveSlotInit() - this may be reading into a slot
// other than SAVE.slot (e.g. a save-device round trip in a test), and
// saveSlotInit() only ever operates on SAVE.slot now. saveSlotCurrent
// ReadJSON() fully overwrites every field below anyway (including
// party.members/order), so this only needs to reset the bookkeeping
// fields (version/dataType) that aren't part of the JSON wire format.
memorySet(slot, 0, sizeof(saveslot_t));
slot->version = 1;
errorChain(saveSlotCurrentReadJSON(slot, object));
errorOk();
}
+20 -14
View File
@@ -8,6 +8,7 @@
#pragma once
#include "save/savedevice.h"
#include "rpg/overworld/map.h"
#include "rpg/battle/party.h"
#include "time/timeepoch.h"
#include "yyjson.h"
@@ -16,35 +17,40 @@
#define SAVE_SLOT_COUNT 3
#endif
// The stable, version-independent in-memory shape of a save slot - what the
// rest of the engine actually reads/writes. Every save schema version
// (saveslotver1_t, ...) redefines its own copy of these same fields for its
// JSON wire format; saveSlotCurrentWriteJSON()/ReadJSON() (saveslotcurrent.c)
// manually copy field-by-field between this and whichever version is
// current, so a version's frozen on-disk shape can never drift just because
// this stable struct (or a live engine constant like MAP_NAME_MAX) changes.
#define SAVE_SLOT_MAP_NAME_DEFAULT "overworld"
typedef struct {
char_t name[SAVE_SLOT_NAME_LENGTH + 1];// 8 characters + null terminator
dusktimeepoch_t time;
int32_t playerLevel;
char_t mapName[MAP_NAME_MAX];
bool_t corrupt;
} saveslotcache_t;
typedef struct saveslot_s {
uint8_t version;
uint8_t dataType;
saveslotcache_t cachedData;
party_t party;
} saveslot_t;
/**
* Inits the save slot with the default state, this is functionally "new game"
* but will not set the player name, as that is what we use to determine if a
* save slot is "in use" or not.
*
* @param slot The save slot to init.
* Inits the current save slot (SAVE.slot) with the default state, this is
* functionally "new game" but will not set the player name, as that is
* what we use to determine if a save slot is "in use" or not.
*/
void saveSlotInit(saveslot_t *slot);
void saveSlotInit(void);
/**
* Sets up the current save slot (SAVE.slot) for a brand new game: calls
* saveSlotInit, then seeds it with a starting party. Use this (not
* saveSlotInit) whenever a new save is actually being created for a
* player - saveSlotInit alone leaves the party empty, which every other
* caller (resetting the slot before a load attempt, wiping a deleted
* slot) wants. Callers creating a new save at a specific index should set
* SAVE.slotCurrent first.
*/
void saveSlotNewGame(void);
/**
* Checks if the save slot is in use, this is determined by checking if the
+15
View File
@@ -8,6 +8,7 @@
#include "saveslotcurrent.h"
#include "assert/assert.h"
#include "util/string.h"
#include "util/memory.h"
#include "time/time.h"
errorret_t saveSlotCurrentWriteJSON(
@@ -29,6 +30,11 @@ errorret_t saveSlotCurrentWriteJSON(
ver1.playerLevel = slot->cachedData.playerLevel;
stringCopy(ver1.mapName, slot->cachedData.mapName, sizeof(ver1.mapName));
memoryCopy(
ver1.partyMembers, slot->party.members, sizeof(ver1.partyMembers)
);
memoryCopy(ver1.partyOrder, slot->party.order, sizeof(ver1.partyOrder));
errorChain(saveSlotVer1WriteJSON(&ver1, doc, object));
errorOk();
}
@@ -37,7 +43,11 @@ errorret_t saveSlotCurrentReadJSON(saveslot_t *slot, yyjson_val *object) {
assertNotNull(slot, "Slot cannot be null");
assertNotNull(object, "Object cannot be null");
// Zeroed up front: saveSlotVer1ReadJSON returns early (leaving everything
// past "name" untouched) for a blank/never-used slot, so this must not be
// left as uninitialized stack garbage.
saveslotver1_t ver1;
memoryZero(&ver1, sizeof(ver1));
errorChain(saveSlotVer1ReadJSON(&ver1, object));
stringCopy(slot->cachedData.name, ver1.name, sizeof(slot->cachedData.name));
@@ -47,5 +57,10 @@ errorret_t saveSlotCurrentReadJSON(saveslot_t *slot, yyjson_val *object) {
slot->cachedData.mapName, ver1.mapName, sizeof(slot->cachedData.mapName)
);
memoryCopy(
slot->party.members, ver1.partyMembers, sizeof(slot->party.members)
);
memoryCopy(slot->party.order, ver1.partyOrder, sizeof(slot->party.order));
errorOk();
}
+60
View File
@@ -24,6 +24,28 @@ errorret_t saveSlotVer1WriteJSON(
writeInt32("playerLevel", slot->playerLevel);
writeString("mapName", slot->mapName);
yyjson_mut_val *partyMembersArr = yyjson_mut_arr(doc);
for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; i++) {
battlefighter_t *member = &slot->partyMembers[i];
writeArrayObject(partyMembersArr);
writeUInt32("id", member->id);
writeUInt32("status", member->status);
writeUInt32("team", member->team);
writeUInt32("controller", member->controller);
writeUInt32("health", member->health);
writeUInt32("healthMax", member->healthMax);
writeUInt32("mp", member->mp);
writeUInt32("mpMax", member->mpMax);
writeUInt32("statAttack", member->stats.attack);
writeUInt32("statDefense", member->stats.defense);
writeUInt32("statMagic", member->stats.magic);
writeUInt32("statSpeed", member->stats.speed);
writeUInt32("statLuck", member->stats.luck);
}
writeValue("partyMembers", partyMembersArr);
writeUInt8Array("partyOrder", slot->partyOrder, PARTY_ACTIVE_SIZE_MAX);
errorOk();
}
@@ -36,11 +58,49 @@ errorret_t saveSlotVer1ReadJSON(saveslotver1_t *slot, yyjson_val *object) {
requireVersion(SAVE_SLOT_CURRENT);
readString("name", slot->name, "", SAVE_SLOT_VER1_NAME_LENGTH);
if(slot->name[0] == '\0') errorOk();
readTime("time", slot->time);
readInt32("playerLevel", slot->playerLevel, 1);
requireStrMin("mapName", 1);
readString(
"mapName", slot->mapName, "", SAVE_SLOT_VER1_MAP_NAME_MAX - 1
);
requireArrayOfSize(
"partyMembers", partyMembersArr, PARTY_MEMBER_COUNT_MAX
);
size_t memberIdx, memberLen;
yyjson_val *memberObj;
yyjson_arr_foreach(
partyMembersArr, memberIdx, memberLen, memberObj
) {
battlefighter_t *member = &slot->partyMembers[memberIdx];
// Shadows the outer `object` so readUInt32() below (which hardcodes
// that name) reads from this member's object instead.
yyjson_val *object = memberObj;
readUInt32("id", member->id, 0);
readUInt32("status", member->status, BATTLE_FIGHTER_STATUS_NULL);
readUInt32("team", member->team, BATTLE_FIGHTER_TEAM_ALLY);
readUInt32(
"controller", member->controller, BATTLE_FIGHTER_CONTROLLER_PLAYER
);
readUInt32("health", member->health, 0);
readUInt32("healthMax", member->healthMax, 0);
readUInt32("mp", member->mp, 0);
readUInt32("mpMax", member->mpMax, 0);
readUInt32("statAttack", member->stats.attack, 0);
readUInt32("statDefense", member->stats.defense, 0);
readUInt32("statMagic", member->stats.magic, 0);
readUInt32("statSpeed", member->stats.speed, 0);
readUInt32("statLuck", member->stats.luck, 0);
}
readUInt8Array(
"partyOrder", slot->partyOrder, PARTY_ACTIVE_SIZE_MAX,
PARTY_ORDER_EMPTY
);
errorOk();
}
+8 -1
View File
@@ -9,12 +9,16 @@
#include "error/error.h"
#include "time/timeepoch.h"
#include "save/slot/saveslotver.h"
#include "rpg/battle/party.h"
#include "yyjson.h"
// This schema's own frozen copies of save/slot/saveslot.h's field sizes -
// never reference SAVE_SLOT_NAME_LENGTH/MAP_NAME_MAX (or any other live
// constant) here. Once shipped, this file's on-disk shape must never change
// underneath old save files, even if the live engine constants do.
// underneath old save files, even if the live engine constants do. The
// party arrays below are the exception - saveSlotVer1ReadJSON() checks their
// JSON array lengths explicitly, so PARTY_MEMBER_COUNT_MAX/
// PARTY_ACTIVE_SIZE_MAX (rpg/battle/party.h) can be referenced directly.
#define SAVE_SLOT_VER1_NAME_LENGTH 8
#define SAVE_SLOT_VER1_MAP_NAME_MAX 10
@@ -28,6 +32,9 @@ typedef struct saveslotver1_s {
dusktimeepoch_t time;
int32_t playerLevel;
char_t mapName[SAVE_SLOT_VER1_MAP_NAME_MAX];
battlefighter_t partyMembers[PARTY_MEMBER_COUNT_MAX];
uint8_t partyOrder[PARTY_ACTIVE_SIZE_MAX];
} saveslotver1_t;
/**
+13 -1
View File
@@ -57,6 +57,16 @@ void uiSaveSlotSetHighlighted(
saveSlot->highlighted = highlighted;
}
bool_t uiSaveSlotIsCorrupt(const uisaveslot_t *saveSlot) {
assertNotNull(saveSlot, "Save slot cannot be NULL");
return saveSlot->corrupt;
}
void uiSaveSlotSetCorrupt(uisaveslot_t *saveSlot, const bool_t corrupt) {
assertNotNull(saveSlot, "Save slot cannot be NULL");
saveSlot->corrupt = corrupt;
}
uisaveslotdisplaytype_t uiSaveSlotGetDisplayType(const uisaveslot_t *saveSlot) {
assertNotNull(saveSlot, "Save slot cannot be NULL");
return saveSlot->displayType;
@@ -85,7 +95,9 @@ errorret_t uiSaveSlotDraw(
const float_t contentY = y + UI_FRAME_START_Y;
color_t color;
if(saveSlot->highlighted) {
if(saveSlot->corrupt) {
color = COLOR_RED;
} else if(saveSlot->highlighted) {
color = COLOR_RED;
} else if(saveSlot->displayType == UI_SAVE_SLOT_DISPLAY_TYPE_DELETE) {
color = COLOR_ORANGE;
+18
View File
@@ -42,6 +42,7 @@ typedef struct {
spritebatchsprite_t nameSprites[UI_SAVE_SLOT_NAME_SPRITES_MAX];
bool_t highlighted;
bool_t corrupt;
} uisaveslot_t;
/**
@@ -75,6 +76,23 @@ bool_t uiSaveSlotIsHighlighted(const uisaveslot_t *saveSlot);
*/
void uiSaveSlotSetHighlighted(uisaveslot_t *saveSlot, const bool_t highlighted);
/**
* Returns whether the save slot widget is flagged as corrupt.
*
* @param saveSlot The save slot widget to query.
* @returns True if flagged as corrupt.
*/
bool_t uiSaveSlotIsCorrupt(const uisaveslot_t *saveSlot);
/**
* Sets whether the save slot widget is flagged as corrupt - drawn in red
* regardless of highlighted/display-type state, taking priority over both.
*
* @param saveSlot The save slot widget to update.
* @param corrupt The new corrupt state.
*/
void uiSaveSlotSetCorrupt(uisaveslot_t *saveSlot, const bool_t corrupt);
/**
* Returns the save slot widget's display type.
*
+127 -83
View File
@@ -7,6 +7,7 @@
#include "uiselectsave.h"
#include "ui/widget/uiframe.h"
#include "ui/widget/uimodal.h"
#include "ui/dialog/uiconfirm.h"
#include "ui/dialog/keyboard/uikeyboard.h"
#include "ui/overlay/uifatalerror.h"
@@ -31,6 +32,14 @@ void uiSelectSaveFormatSlot(
) {
saveslotcache_t *cache = &SAVE.caches[index];
if(cache->corrupt) {
errorret_t result = localeManagerGetString(
"ui.select_save.corrupt", buffer, bufferSize, 0
);
if(errorIsNotOk(result)) errorCatch(result);
return;
}
if(!saveSlotInUse(cache)) {
errorret_t result = localeManagerGetString(
"ui.select_save.empty", buffer, bufferSize, 0
@@ -58,90 +67,9 @@ void uiSelectSaveRefreshSlot(const uint8_t index) {
UI_SELECT_SAVE.type == UI_SELECT_SAVE_TYPE_DELETE ?
UI_SAVE_SLOT_DISPLAY_TYPE_DELETE : UI_SAVE_SLOT_DISPLAY_TYPE_NORMAL;
uiSaveSlotSetDisplayType(&UI_SELECT_SAVE.slots[index], displayType);
}
void uiSelectSaveDeleteConfirmed(const bool_t result, void *user) {
if(!result) return;
assertTrue(SAVE.deviceCurrent != 0xFF, "No current device");
const uint8_t index = UI_SELECT_SAVE.pendingDeleteIndex;
saveslot_t slot;
saveSlotInit(&slot);
errorret_t writeResult = saveDeviceSlotWrite(
&SAVE.devices[SAVE.deviceCurrent], &slot, index
uiSaveSlotSetCorrupt(
&UI_SELECT_SAVE.slots[index], SAVE.caches[index].corrupt
);
if(errorIsNotOk(writeResult)) {
errorCatch(errorPrint(writeResult));
return;
}
SAVE.caches[index] = slot.cachedData;
uiSelectSaveRefreshSlot(index);
uiSaveSlotSetHighlighted(&UI_SELECT_SAVE.slots[index], true);
}
void uiSelectSaveConfirmDelete(const uint8_t index) {
UI_SELECT_SAVE.pendingDeleteIndex = index;
uiConfirmOpen(
"ui.select_save.delete_confirm", uiSelectSaveDeleteConfirmed, NULL
);
}
void uiSelectSaveNameEntered(
const char_t *text,
const bool_t confirmed,
void *user
) {
if(!confirmed) return;
const uint8_t index = UI_SELECT_SAVE.pendingNameIndex;
saveslot_t slot;
saveSlotInit(&slot);
stringCopy(slot.cachedData.name, text, SAVE_SLOT_NAME_LENGTH);
// No save device available - proceed with an in-memory-only slot rather
// than writing to a device that doesn't exist (see saveLoadSlot()'s own
// comment on the same "continue without a save device" flow).
if(SAVE.deviceCurrent != 0xFF) {
errorret_t writeResult = saveDeviceSlotWrite(
&SAVE.devices[SAVE.deviceCurrent], &slot, index
);
if(errorIsNotOk(writeResult)) {
errorCatch(errorPrint(writeResult));
uiFatalErrorOpen(writeResult.state->message);
return;
}
}
SAVE.caches[index] = slot.cachedData;
uiSelectSaveRefreshSlot(index);
UI_SELECT_SAVE.result = index;
uiSelectSaveClose();
}
void uiSelectSaveNameEmptySlot(const uint8_t index) {
UI_SELECT_SAVE.pendingNameIndex = index;
char_t title[UI_KEYBOARD_TITLE_TEXT_MAX];
errorret_t result = localeManagerGetString(
"ui.select_save.name_title", title, sizeof(title), 0
);
if(errorIsNotOk(result)) errorCatch(result);
uikeyboardopen_t open = {
.title = title,
.onInput = uiSelectSaveNameEntered,
.cancel = true,
.maxLength = SAVE_SLOT_NAME_LENGTH,
.trimmed = true,
.allowBlank = false
};
uiKeyboardOpen(&open);
}
void uiSelectSaveSetActionLabel(const uiselectsavetype_t type) {
@@ -169,6 +97,116 @@ void uiSelectSaveSwitchType(const uiselectsavetype_t type) {
uiSelectSaveSetActionLabel(type);
}
void uiSelectSaveDeleteConfirmed(const bool_t result, void *user) {
if(!result) return;
assertTrue(SAVE.deviceCurrent != 0xFF, "No current device");
const uint8_t index = UI_SELECT_SAVE.pendingDeleteIndex;
// uiSelectSaveOpen is only ever reached before any gameplay starts (see
// uimainmenu.c), so it's safe to reuse SAVE.slot as scratch for whichever
// index is being written here - nothing else is relying on it.
SAVE.slotCurrent = index;
saveSlotInit();
errorret_t writeResult = saveDeviceSlotWrite(
&SAVE.devices[SAVE.deviceCurrent], &SAVE.slot, index
);
if(errorIsNotOk(writeResult)) {
errorCatch(errorPrint(writeResult));
return;
}
SAVE.caches[index] = SAVE.slot.cachedData;
uiSelectSaveSwitchType(UI_SELECT_SAVE_TYPE_LOAD);
uiSelectSaveRefreshSlot(index);
uiSaveSlotSetHighlighted(&UI_SELECT_SAVE.slots[index], true);
}
void uiSelectSaveConfirmDelete(const uint8_t index) {
UI_SELECT_SAVE.pendingDeleteIndex = index;
uiConfirmOpen(
"ui.select_save.delete_confirm", uiSelectSaveDeleteConfirmed, NULL
);
}
void uiSelectSaveNameEntered(
const char_t *text,
const bool_t confirmed,
void *user
) {
if(!confirmed) return;
const uint8_t index = UI_SELECT_SAVE.pendingNameIndex;
// uiSelectSaveOpen is only ever reached before any gameplay starts (see
// uimainmenu.c), so it's safe to reuse SAVE.slot as scratch for whichever
// index is being written here - nothing else is relying on it.
SAVE.slotCurrent = index;
saveSlotNewGame();
stringCopy(SAVE.slot.cachedData.name, text, SAVE_SLOT_NAME_LENGTH);
// No save device available - proceed with an in-memory-only slot rather
// than writing to a device that doesn't exist (see saveLoadSlot()'s own
// comment on the same "continue without a save device" flow).
if(SAVE.deviceCurrent != 0xFF) {
errorret_t writeResult = saveDeviceSlotWrite(
&SAVE.devices[SAVE.deviceCurrent], &SAVE.slot, index
);
if(errorIsNotOk(writeResult)) {
errorCatch(errorPrint(writeResult));
uiFatalErrorOpen(writeResult.state->message);
return;
}
}
SAVE.caches[index] = SAVE.slot.cachedData;
uiSelectSaveRefreshSlot(index);
UI_SELECT_SAVE.result = index;
uiSelectSaveClose();
}
void uiSelectSaveNameEmptySlot(const uint8_t index) {
UI_SELECT_SAVE.pendingNameIndex = index;
char_t title[UI_KEYBOARD_TITLE_TEXT_MAX];
errorret_t result = localeManagerGetString(
"ui.select_save.name_title", title, sizeof(title), 0
);
if(errorIsNotOk(result)) errorCatch(result);
uikeyboardopen_t open = {
.title = title,
.onInput = uiSelectSaveNameEntered,
.cancel = true,
.maxLength = SAVE_SLOT_NAME_LENGTH,
.trimmed = true,
.allowBlank = false
};
uiKeyboardOpen(&open);
}
void uiSelectSaveWarnCorrupt(void) {
const char_t *options[] = { "ui.confirm.confirm" };
// Acknowledging just closes the warning - the player stays on the
// select-save list rather than being pushed into naming/overwriting
// the slot.
uiModalOpen(
"ui.select_save.corrupt", "ui.select_save.corrupt_warning",
options, 1,
NULL, NULL, NULL
);
}
bool_t uiSelectSaveMenuCancelled(const uimenu_t *menu) {
if(UI_SELECT_SAVE.type != UI_SELECT_SAVE_TYPE_DELETE) return false;
uiSelectSaveSwitchType(UI_SELECT_SAVE_TYPE_LOAD);
return true;
}
void uiSelectSaveSlotSelected(
const uimenu_t *menu,
const uint8_t index,
@@ -187,6 +225,11 @@ void uiSelectSaveSlotSelected(
return;
}
if(SAVE.caches[index].corrupt) {
uiSelectSaveWarnCorrupt();
return;
}
if(!saveSlotInUse(&SAVE.caches[index])) {
uiSelectSaveNameEmptySlot(index);
return;
@@ -244,6 +287,7 @@ errorret_t uiSelectSaveInit(void) {
&UI_SELECT_SAVE.slotMenu, uiSelectSaveSlotSelected, uiSelectSaveSlotClosed,
uiSelectSaveSlotChanged
);
uiMenuSetCancelCallback(&UI_SELECT_SAVE.slotMenu, uiSelectSaveMenuCancelled);
uiMenuSetItems(
&UI_SELECT_SAVE.slotMenu, UI_SELECT_SAVE.slotItems, SAVE_SLOT_COUNT, 1
);
+12 -2
View File
@@ -7,7 +7,6 @@
#include "uimainmenu.h"
#include "ui/widget/uiframe.h"
#include "rpg/battle/testbattle/testbattle.h"
#include "util/memory.h"
#include "display/spritebatch/spritebatch.h"
#include "display/screen/screen.h"
@@ -20,6 +19,7 @@
#include "scene/scene.h"
#include "asset/asset.h"
#include "save/save.h"
#include "rpg/overworld/map.h"
#define UI_MAIN_MENU_INDEX_START_GAME 0
#define UI_MAIN_MENU_INDEX_OPTIONS 1
@@ -50,7 +50,7 @@ void uiMainMenuSelectSaveResult(const uint8_t slotIndex, void *user) {
}
SAVE.slotCurrent = slotIndex;
saveSlotInit(&SAVE.slot);
saveSlotInit();
errorret_t result = saveLoadSlot();
if(errorIsNotOk(result)) {
errorCatch(errorPrint(result));
@@ -58,6 +58,16 @@ void uiMainMenuSelectSaveResult(const uint8_t slotIndex, void *user) {
return;
}
assertStrLenMin(
SAVE.slot.cachedData.mapName, 1, "Save slot has no map name"
);
errorret_t mapResult = mapSetMap(SAVE.slot.cachedData.mapName);
if(errorIsNotOk(mapResult)) {
errorCatch(errorPrint(mapResult));
uiFatalErrorOpen(mapResult.state->message);
return;
}
sceneSet(SCENE_TYPE_OVERWORLD);
}
+18 -12
View File
@@ -298,7 +298,7 @@ static void test_saveSaveSlot_invalidSlotIndexAsserts(void **state) {
static void test_saveSaveSlot_success(void **state) {
makeDeviceAvailable();
SAVE.slotCurrent = 1;
saveSlotInit(&SAVE.slot);
saveSlotInit();
stringCopy(
SAVE.slot.cachedData.name, "Hero", sizeof(SAVE.slot.cachedData.name)
);
@@ -311,8 +311,9 @@ static void test_saveSaveSlot_success(void **state) {
assert_true(stringEquals(SAVE.caches[1].name, "Hero"));
assert_int_equal(SAVE.caches[1].playerLevel, 12);
// No pre-init needed - saveSlotReadJSON() (via saveDeviceSlotRead) fully
// resets/overwrites its destination struct regardless of prior content.
saveslot_t onDisk;
saveSlotInit(&onDisk);
errorret_t readRet = saveDeviceSlotRead(&SAVE.devices[0], &onDisk, 1);
assert_true(errorIsOk(readRet));
assert_true(stringEquals(onDisk.cachedData.name, "Hero"));
@@ -331,15 +332,20 @@ static void test_saveLoadSlot_invalidSlotIndexAsserts(void **state) {
static void test_saveLoadSlot_success(void **state) {
makeDeviceAvailable();
saveslot_t onDisk;
saveSlotInit(&onDisk);
stringCopy(onDisk.cachedData.name, "Zelda", sizeof(onDisk.cachedData.name));
onDisk.cachedData.playerLevel = 30;
errorret_t writeRet = saveDeviceSlotWrite(&SAVE.devices[0], &onDisk, 2);
// Write slot 2's on-disk file via SAVE.slot itself (saveSlotInit() only
// ever operates on SAVE.slot now), then reset it again below - the
// write and the load-under-test don't overlap in time.
SAVE.slotCurrent = 2;
saveSlotInit();
stringCopy(
SAVE.slot.cachedData.name, "Zelda", sizeof(SAVE.slot.cachedData.name)
);
SAVE.slot.cachedData.playerLevel = 30;
errorret_t writeRet = saveDeviceSlotWrite(&SAVE.devices[0], &SAVE.slot, 2);
assert_true(errorIsOk(writeRet));
SAVE.slotCurrent = 2;
saveSlotInit(&SAVE.slot);
saveSlotInit();
SAVE.slotDirty = true;
errorret_t ret = saveLoadSlot();
@@ -365,7 +371,7 @@ static void test_saveLoadSlot_deviceReadFails_cacheStaysStale(void **state) {
fclose(file);
SAVE.slotCurrent = 0;
saveSlotInit(&SAVE.slot);
saveSlotInit();
SAVE.caches[0].playerLevel = 77;// sentinel
errorret_t ret = saveLoadSlot();
@@ -385,7 +391,7 @@ static void test_saveLoadAllSlots_loadsAllAndEndsAtLastIndex(void **state) {
for(uint8_t i = 0; i < SAVE_SLOT_COUNT; i++) {
SAVE.slotCurrent = i;
saveSlotInit(&SAVE.slot);
saveSlotInit();
SAVE.slot.cachedData.playerLevel = (int32_t)(i + 1);
errorret_t saveRet = saveSaveSlot();
assert_true(errorIsOk(saveRet));
@@ -404,7 +410,7 @@ static void test_saveLoadAllSlots_missingFileLeavesInitDefaults(void **state) {
makeDeviceAvailable();
SAVE.slotCurrent = 0;
saveSlotInit(&SAVE.slot);
saveSlotInit();
SAVE.slot.cachedData.playerLevel = 5;
errorret_t saveRet = saveSaveSlot();
assert_true(errorIsOk(saveRet));
@@ -427,7 +433,7 @@ static void test_saveLoadAllSlots_middleSlotCorrupt_stopsAtFailingIndex(
makeDeviceAvailable();
SAVE.slotCurrent = 0;
saveSlotInit(&SAVE.slot);
saveSlotInit();
errorret_t saveRet = saveSaveSlot();
assert_true(errorIsOk(saveRet));
+10 -7
View File
@@ -10,6 +10,7 @@
#include "save/savedevice.h"
#include "save/slot/saveslot.h"
#include "save/settings/savesettings.h"
#include "save/save.h"
#include "util/memory.h"
#include "util/string.h"
@@ -155,8 +156,9 @@ static void test_saveDeviceCheckAvailability_resolvesSynchronouslyOnLinux(
static void test_saveDeviceSlotWrite_nullAsserts(void **state) {
savedevice_t device;
// Content is never touched - both calls assert on a NULL argument
// before either device or slot would actually be read.
saveslot_t slot;
saveSlotInit(&slot);
expect_assert_failure(saveDeviceSlotWrite(NULL, &slot, 0));
expect_assert_failure(saveDeviceSlotWrite(&device, NULL, 0));
@@ -165,7 +167,6 @@ static void test_saveDeviceSlotWrite_nullAsserts(void **state) {
static void test_saveDeviceSlotRead_nullAsserts(void **state) {
savedevice_t device;
saveslot_t slot;
saveSlotInit(&slot);
expect_assert_failure(saveDeviceSlotRead(NULL, &slot, 0));
expect_assert_failure(saveDeviceSlotRead(&device, NULL, 0));
@@ -198,15 +199,17 @@ static void test_saveDeviceSlot_dispatchesToPlatform(void **state) {
saveDeviceCheckAvailability(&device, updateCallback, NULL);
saveDeviceUpdate(&device);
saveslot_t written;
saveSlotInit(&written);
written.cachedData.playerLevel = 21;
// saveSlotInit() only ever operates on SAVE.slot now, so that's the
// write source here.
saveSlotInit();
SAVE.slot.cachedData.playerLevel = 21;
errorret_t writeRet = saveDeviceSlotWrite(&device, &written, 0);
errorret_t writeRet = saveDeviceSlotWrite(&device, &SAVE.slot, 0);
assert_true(errorIsOk(writeRet));
// No pre-init needed - saveSlotReadJSON() (via saveDeviceSlotRead) fully
// resets/overwrites its destination struct regardless of prior content.
saveslot_t read;
saveSlotInit(&read);
errorret_t readRet = saveDeviceSlotRead(&device, &read, 0);
assert_true(errorIsOk(readRet));
+18 -11
View File
@@ -11,6 +11,7 @@
#include "save/savedevicelinux.h"
#include "save/slot/saveslot.h"
#include "save/settings/savesettings.h"
#include "save/save.h"
#include "util/memory.h"
#include "util/string.h"
#include <stdio.h>
@@ -180,8 +181,9 @@ static void test_checkAvailability_mkdirpFails(void **state) {
static void test_slotWrite_nullAsserts(void **state) {
savedevice_t device;
// Content is never touched - both calls assert on a NULL argument
// before either device or slot would actually be read.
saveslot_t slot;
saveSlotInit(&slot);
expect_assert_failure(saveDeviceLinuxSlotWrite(NULL, &slot, 0));
expect_assert_failure(saveDeviceLinuxSlotWrite(&device, NULL, 0));
@@ -190,7 +192,6 @@ static void test_slotWrite_nullAsserts(void **state) {
static void test_slotRead_nullAsserts(void **state) {
savedevice_t device;
saveslot_t slot;
saveSlotInit(&slot);
expect_assert_failure(saveDeviceLinuxSlotRead(NULL, &slot, 0));
expect_assert_failure(saveDeviceLinuxSlotRead(&device, NULL, 0));
@@ -203,17 +204,21 @@ static void test_slotWriteRead_roundTrip(void **state) {
// saveDeviceLinuxCheckAvailability does this via mkdirp.
checkAvailabilityAndDrain(&device);
saveslot_t written;
saveSlotInit(&written);
stringCopy(written.cachedData.name, "Hero", sizeof(written.cachedData.name));
written.cachedData.playerLevel = 9;
// saveSlotInit() only ever operates on SAVE.slot now, so that's the
// write source here.
saveSlotInit();
stringCopy(
SAVE.slot.cachedData.name, "Hero", sizeof(SAVE.slot.cachedData.name)
);
SAVE.slot.cachedData.playerLevel = 9;
errorret_t writeRet = saveDeviceLinuxSlotWrite(&device, &written, 1);
errorret_t writeRet = saveDeviceLinuxSlotWrite(&device, &SAVE.slot, 1);
assert_true(errorIsOk(writeRet));
// No pre-init needed - saveSlotReadJSON() (via saveDeviceLinuxSlotRead)
// fully resets/overwrites its destination struct regardless of prior
// content.
saveslot_t read;
saveSlotInit(&read);
errorret_t readRet = saveDeviceLinuxSlotRead(&device, &read, 1);
assert_true(errorIsOk(readRet));
@@ -225,8 +230,11 @@ static void test_slotRead_noFileYet_leavesSlotUntouched(void **state) {
savedevice_t device;
memoryZero(&device, sizeof(device));
// Deliberately not saveSlotInit()'d - a missing slot file means
// saveDeviceLinuxSlotRead never even calls saveSlotReadJSON, so slot
// must come in exactly as the caller left it and go out unchanged.
saveslot_t slot;
saveSlotInit(&slot);
memoryZero(&slot, sizeof(slot));
stringCopy(slot.cachedData.name, "sentinel", sizeof(slot.cachedData.name));
slot.cachedData.playerLevel = 555;
@@ -260,7 +268,6 @@ static void test_slotRead_corruptFile_errors(void **state) {
fclose(file);
saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = saveDeviceLinuxSlotRead(&device, &slot, 0);
assert_true(errorIsNotOk(ret));
+74 -51
View File
@@ -7,6 +7,7 @@
#include "dusktest.h"
#include "save/slot/saveslot.h"
#include "save/save.h"
#include "save/savejson.h"
#include "util/memory.h"
#include "util/string.h"
@@ -45,24 +46,19 @@ static errorret_t slotFromJSON(saveslot_t *slot, const char_t *json) {
}
// ============================================================
// saveSlotInit
// saveSlotInit - only ever operates on SAVE.slot now.
// ============================================================
static void test_saveSlotInit_defaults(void **state) {
saveslot_t slot;
memorySet(&slot, 0xFF, sizeof(slot));
memorySet(&SAVE.slot, 0xFF, sizeof(SAVE.slot));
saveSlotInit(&slot);
saveSlotInit();
assert_int_equal(slot.version, 1);
assert_int_equal(slot.dataType, 0);
assert_int_equal(slot.cachedData.name[0], '\0');
assert_true(slot.cachedData.time.time == 0.0);
assert_int_equal(slot.cachedData.playerLevel, 0);
}
static void test_saveSlotInit_nullAsserts(void **state) {
expect_assert_failure(saveSlotInit(NULL));
assert_int_equal(SAVE.slot.version, 1);
assert_int_equal(SAVE.slot.dataType, 0);
assert_int_equal(SAVE.slot.cachedData.name[0], '\0');
assert_true(SAVE.slot.cachedData.time.time == 0.0);
assert_int_equal(SAVE.slot.cachedData.playerLevel, 0);
}
// ============================================================
@@ -70,13 +66,14 @@ static void test_saveSlotInit_nullAsserts(void **state) {
// ============================================================
static void test_saveSlotInUse(void **state) {
saveslot_t slot;
saveSlotInit(&slot);
saveSlotInit();
assert_false(saveSlotInUse(&slot.cachedData));
assert_false(saveSlotInUse(&SAVE.slot.cachedData));
stringCopy(slot.cachedData.name, "Hero", sizeof(slot.cachedData.name));
assert_true(saveSlotInUse(&slot.cachedData));
stringCopy(
SAVE.slot.cachedData.name, "Hero", sizeof(SAVE.slot.cachedData.name)
);
assert_true(saveSlotInUse(&SAVE.slot.cachedData));
}
static void test_saveSlotInUse_nullAsserts(void **state) {
@@ -84,18 +81,17 @@ static void test_saveSlotInUse_nullAsserts(void **state) {
}
static void test_saveSlotHasSaved(void **state) {
saveslot_t slot;
saveSlotInit(&slot);
saveSlotInit();
assert_false(saveSlotHasSaved(&slot.cachedData));
assert_false(saveSlotHasSaved(&SAVE.slot.cachedData));
// Writing to JSON stamps the current time as a side effect, so even a
// pure serialize (no device write) flips "has ever saved" to true.
char_t *json;
size_t len;
errorret_t ret = slotToJSON(&slot, &json, &len);
errorret_t ret = slotToJSON(&SAVE.slot, &json, &len);
assert_true(errorIsOk(ret));
assert_true(saveSlotHasSaved(&slot.cachedData));
assert_true(saveSlotHasSaved(&SAVE.slot.cachedData));
free(json);
}
@@ -109,8 +105,9 @@ static void test_saveSlotHasSaved_nullAsserts(void **state) {
// ============================================================
static void test_saveSlotWriteJSON_nullAsserts(void **state) {
// Content is never touched - both calls assert on a NULL doc/object
// argument before slot itself would actually be read.
saveslot_t slot;
saveSlotInit(&slot);
writeInit();
expect_assert_failure(saveSlotWriteJSON(NULL, doc, object));
@@ -126,7 +123,6 @@ static void test_saveSlotWriteJSON_nullAsserts(void **state) {
static void test_saveSlotReadJSON_nullAsserts(void **state) {
saveslot_t slot;
saveSlotInit(&slot);
yyjson_doc *readDoc = yyjson_read("{}", 2, 0);
yyjson_val *readObject = yyjson_doc_get_root(readDoc);
@@ -138,55 +134,86 @@ static void test_saveSlotReadJSON_nullAsserts(void **state) {
}
static void test_saveSlotReadJSON_roundTrip(void **state) {
saveslot_t written;
saveSlotInit(&written);
written.version = 7;// deliberately non-default, not part of the JSON schema
stringCopy(written.cachedData.name, "Hero", sizeof(written.cachedData.name));
written.cachedData.playerLevel = 42;
// saveSlotInit() only ever operates on SAVE.slot now, so that's the
// write source here.
saveSlotInit();
SAVE.slot.version = 7;// deliberately non-default, not part of the JSON schema
stringCopy(
SAVE.slot.cachedData.name, "Hero", sizeof(SAVE.slot.cachedData.name)
);
SAVE.slot.cachedData.playerLevel = 42;
// An in-use slot (non-empty name) requires a non-empty map name too -
// see saveSlotNewGame/requireStrMin("mapName", 1) in saveSlotVer1ReadJSON.
stringCopy(
SAVE.slot.cachedData.mapName, "overworld",
sizeof(SAVE.slot.cachedData.mapName)
);
char_t *json;
size_t len;
errorret_t writeRet = slotToJSON(&written, &json, &len);
errorret_t writeRet = slotToJSON(&SAVE.slot, &json, &len);
assert_true(errorIsOk(writeRet));
saveslot_t read;
saveSlotInit(&read);
const dusktimeepoch_t writtenTime = SAVE.slot.cachedData.time;
// No pre-init needed - saveSlotReadJSON() fully resets/overwrites its
// destination struct regardless of prior content.
saveslot_t read;
errorret_t readRet = slotFromJSON(&read, json);
assert_true(errorIsOk(readRet));
assert_true(stringEquals(read.cachedData.name, "Hero"));
assert_int_equal(read.cachedData.playerLevel, 42);
assert_true(read.cachedData.time.time == written.cachedData.time.time);
assert_true(stringEquals(read.cachedData.mapName, "overworld"));
assert_true(read.cachedData.time.time == writtenTime.time);
// version/dataType are struct-only bookkeeping, never serialized - the
// reader keeps whatever saveSlotInit gave it regardless of the writer's
// version.
// reader resets them to the default regardless of the writer's version.
assert_int_equal(read.version, 1);
free(json);
}
static void test_saveSlotReadJSON_missingFieldsUseDefaults(void **state) {
static void test_saveSlotReadJSON_blankSlot_shortCircuits(void **state) {
// Deliberately not saveSlotInit()'d - saveSlotReadJSON() fully resets its
// destination struct itself before parsing, so these sentinel values are
// only here to prove they get overwritten, not preserved.
saveslot_t slot;
saveSlotInit(&slot);
memorySet(&slot, 0, sizeof(slot));
stringCopy(slot.cachedData.name, "sentinel", sizeof(slot.cachedData.name));
slot.cachedData.playerLevel = 999;
errorret_t ret = slotFromJSON(
&slot,
"{\"version\":1,"
"\"time\":{\"time\":1.0,\"timeZone\":0.0,\"offsetTime\":0.0}}"
);
// No "name" key (or an empty one) means a blank/never-used slot (see
// saveSlotInUse) - the reader returns right after reading that, without
// needing or validating time/mapName/partyMembers/partyOrder at all, so
// this succeeds despite omitting fields that would otherwise be required.
errorret_t ret = slotFromJSON(&slot, "{\"version\":1}");
assert_true(errorIsOk(ret));
assert_int_equal(slot.cachedData.name[0], '\0');
assert_int_equal(slot.cachedData.playerLevel, 1);
assert_int_equal(slot.cachedData.mapName[0], '\0');
// Not readInt32's own default of 1 - the early return happens before
// playerLevel is ever read, leaving the zero-init saveSlotCurrentReadJSON
// seeds ver1 with (see the memoryZero in saveSlotCurrentReadJSON).
assert_int_equal(slot.cachedData.playerLevel, 0);
}
static void test_saveSlotReadJSON_inUseMissingMapName_errors(void **state) {
saveslot_t slot;
// "name" is present (in use) but "mapName" is missing - a real save
// (via saveSlotNewGame) always has both, so this is corrupt.
errorret_t ret = slotFromJSON(
&slot,
"{\"version\":1,\"name\":\"Hero\","
"\"time\":{\"time\":1.0,\"timeZone\":0.0,\"offsetTime\":0.0}}"
);
assert_true(errorIsNotOk(ret));
errorCatch(ret);
}
static void test_saveSlotReadJSON_missingTimeKey_errors(void **state) {
saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = slotFromJSON(
&slot, "{\"version\":1,\"name\":\"Hero\",\"playerLevel\":5}"
@@ -197,7 +224,6 @@ static void test_saveSlotReadJSON_missingTimeKey_errors(void **state) {
static void test_saveSlotReadJSON_nameTooLong_errors(void **state) {
saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = slotFromJSON(
&slot,
@@ -210,7 +236,6 @@ static void test_saveSlotReadJSON_nameTooLong_errors(void **state) {
static void test_saveSlotReadJSON_nonObjectRoot_errors(void **state) {
saveslot_t slot;
saveSlotInit(&slot);
// A non-object root has no keys, so every field falls back to its
// default - except "version" and "time", which are required and error
@@ -226,7 +251,6 @@ static void test_saveSlotReadJSON_nonObjectRoot_errors(void **state) {
static void test_saveSlotReadJSON_versionMissing_errors(void **state) {
saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = slotFromJSON(
&slot,
@@ -239,7 +263,6 @@ static void test_saveSlotReadJSON_versionMissing_errors(void **state) {
static void test_saveSlotReadJSON_versionMismatch_errors(void **state) {
saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = slotFromJSON(
&slot,
@@ -254,7 +277,6 @@ int main(void) {
assertInit();
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_saveSlotInit_defaults),
cmocka_unit_test(test_saveSlotInit_nullAsserts),
cmocka_unit_test(test_saveSlotInUse),
cmocka_unit_test(test_saveSlotInUse_nullAsserts),
@@ -265,7 +287,8 @@ int main(void) {
cmocka_unit_test(test_saveSlotReadJSON_nullAsserts),
cmocka_unit_test(test_saveSlotReadJSON_roundTrip),
cmocka_unit_test(test_saveSlotReadJSON_missingFieldsUseDefaults),
cmocka_unit_test(test_saveSlotReadJSON_blankSlot_shortCircuits),
cmocka_unit_test(test_saveSlotReadJSON_inUseMissingMapName_errors),
cmocka_unit_test(test_saveSlotReadJSON_missingTimeKey_errors),
cmocka_unit_test(test_saveSlotReadJSON_nameTooLong_errors),
cmocka_unit_test(test_saveSlotReadJSON_nonObjectRoot_errors),