10 Commits
Author SHA1 Message Date
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
37 changed files with 859 additions and 349 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)
+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);
+1 -1
View File
@@ -86,7 +86,7 @@ typedef struct cutscene_s {
#define CUTSCENE_CUTSCENE(CUTSCENE) \
{ \
.type = CUTSCENE_ITEM_TYPE_CUTSCENE, \
.cutscene = CUTSCENE_REFERENCE(CUTSCENE) \
.cutsceneRef = { .cutscene = CUTSCENE_REFERENCE(CUTSCENE), .name = NULL } \
}
#define CUTSCENE_CALLBACK(CALLBACK) \
@@ -8,4 +8,5 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
cutscenestartbattle.c
cutscenebattlewaitstate.c
cutscenebattleforceaction.c
cutsceneregularbattle.c
)
@@ -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,6 +8,7 @@
#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/cutscenejsonfield.h"
@@ -19,8 +20,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(
@@ -52,13 +54,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 +93,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 ||
@@ -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
@@ -22,6 +23,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;
/**
+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();
}
+42 -6
View File
@@ -41,6 +41,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,6 +56,20 @@
typedef struct cutscene_s cutscene_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;
typedef enum {
CUTSCENE_ITEM_TYPE_NULL,
@@ -104,6 +119,7 @@ typedef enum {
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;
@@ -117,7 +133,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 +251,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 +263,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 +296,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.
@@ -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),