Author SHA1 Message Date
YourWishes 798db14bb5 Recover from a corrupt or version-mismatched save file instead of crashing
saveLoadSettings()/saveLoadSlot() previously let a read failure (e.g. a
version mismatch from the new schema check) propagate all the way up
through saveUpdate()/engineUpdate() to main(), which just prints the
error and exits - taking down the whole game over one bad file. Both
now catch the failure, log it, and fall back to init defaults instead,
matching the existing "no file yet" convention.
2026-09-08 12:49:20 -05:00
YourWishes 178d78ef72 Persist the current map name in the save slot
mapSetMap() now keeps SAVE.slot.cachedData.mapName in sync with the
active map, so whichever map is loaded gets written out next time the
slot is actually saved.
2026-09-08 12:49:13 -05:00
YourWishes 8139a0ea54 Add versioned save slot/settings schemas with strict version checks
Splits saveslot_t/savesettings_t into a stable, version-independent
in-memory struct (save/slot/, save/settings/) and a separate frozen
per-schema-version struct (saveslotver1_t/savesettingsver1_t) used only
for JSON serialization, converted between manually. Every write now
stamps a "version" field (SAVE_SLOT_CURRENT/SAVE_SETTINGS_CURRENT), and
every read requires it to match exactly, rejecting anything else -
laying the groundwork for a real migration path instead of silently
misreading old/incompatible save data.
2026-09-08 12:49:06 -05:00
YourWishes 327c2bec70 Show map name in the debug player position overlay
Useful now that multiple maps can be loaded, to tell which map the
printed coordinates belong to.
2026-09-07 22:34:02 -05:00
YourWishes fc0195d9f7 Bump ASSET_FILE_NAME_MAX to 128
Per-map chunk model paths (maps/<map>/models/chunks/chunk_X_Y_Z_0.json)
were hitting the old 48-char limit, crashing assetEntryInit's length
assert during initial chunk/cutscene loading.
2026-09-07 22:33:57 -05:00
YourWishes db42bca44b Reintroduce multiple maps: per-map chunk directories + map_t name/mapSetMap
Move chunk assets from a single flat assetsraw/chunks (and assets/chunks)
into per-map assetsraw/maps/<map>/chunks (assets/maps/<map>/chunks), so
terrain mesh/model output no longer collides across maps sharing chunk
coordinates. map_t gains a name[MAP_NAME_MAX] field plus mapSetMap()/
mapIsLoaded() (checks name[0] == '\0') in place of the old bool loaded
flag; mapInit() now just resets state and mapSetMap() does the chunk
grid load. Updated the chunk asset tool and the map editor's dev
server/client to match.
2026-09-07 21:28:07 -05:00
64 changed files with 782 additions and 157 deletions

No files matched your search

@@ -1,5 +1,5 @@
{ {
"mesh": "meshes/chunks/chunk_-1_0_0_0.dmf", "mesh": "maps/overworld/meshes/chunks/chunk_-1_0_0_0.dmf",
"color": [ "color": [
255, 255,
255, 255,
@@ -1,5 +1,5 @@
{ {
"mesh": "meshes/chunks/chunk_0_0_0_0.dmf", "mesh": "maps/overworld/meshes/chunks/chunk_0_0_0_0.dmf",
"color": [ "color": [
255, 255,
255, 255,
@@ -1,5 +1,5 @@
{ {
"mesh": "meshes/chunks/chunk_0_1_0_0.dmf", "mesh": "maps/overworld/meshes/chunks/chunk_0_1_0_0.dmf",
"color": [ "color": [
255, 255,
255, 255,
@@ -1,5 +1,5 @@
{ {
"mesh": "meshes/chunks/chunk_1_0_0_0.dmf", "mesh": "maps/overworld/meshes/chunks/chunk_1_0_0_0.dmf",
"color": [ "color": [
255, 255,
255, 255,
@@ -1,5 +1,5 @@
{ {
"mesh": "meshes/chunks/chunk_1_1_0_0.dmf", "mesh": "maps/overworld/meshes/chunks/chunk_1_1_0_0.dmf",
"color": [ "color": [
255, 255,
255, 255,
@@ -1,5 +1,5 @@
{ {
"mesh": "meshes/chunks/chunk_2_0_0_0.dmf", "mesh": "maps/overworld/meshes/chunks/chunk_2_0_0_0.dmf",
"color": [ "color": [
255, 255,
255, 255,
+1
View File
@@ -0,0 +1 @@
{}
+7 -5
View File
@@ -345,12 +345,14 @@
return promise; return promise;
} }
const MAP_NAME = "overworld";
function chunkPaths(x, y, z) { function chunkPaths(x, y, z) {
return { return {
raw: `assetsraw/chunks/chunk_${x}_${y}_${z}.json`, raw: `assetsraw/maps/${MAP_NAME}/chunks/chunk_${x}_${y}_${z}.json`,
dcf: `assets/chunks/${x}_${y}_${z}.dcf`, dcf: `assets/maps/${MAP_NAME}/chunks/${x}_${y}_${z}.dcf`,
terrainDmf: `assets/meshes/chunks/chunk_${x}_${y}_${z}_0.dmf`, terrainDmf: `assets/maps/${MAP_NAME}/meshes/chunks/chunk_${x}_${y}_${z}_0.dmf`,
terrainModel: `assets/models/chunks/chunk_${x}_${y}_${z}_0.json`, terrainModel: `assets/maps/${MAP_NAME}/models/chunks/chunk_${x}_${y}_${z}_0.json`,
}; };
} }
@@ -767,7 +769,7 @@
async function buildChunkBrowseList() { async function buildChunkBrowseList() {
const list = document.getElementById("chunkBrowseList"); const list = document.getElementById("chunkBrowseList");
list.innerHTML = ""; list.innerHTML = "";
const res = await apiLs("assetsraw/chunks"); const res = await apiLs(`assetsraw/maps/${MAP_NAME}/chunks`);
for(const entry of res.entries || []) { for(const entry of res.entries || []) {
const m = entry.name.match(/^chunk_(-?\d+)_(-?\d+)_(-?\d+)\.json$/); const m = entry.name.match(/^chunk_(-?\d+)_(-?\d+)_(-?\d+)\.json$/);
if(!m) continue; if(!m) continue;
+4 -1
View File
@@ -209,7 +209,10 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({"error": "invalid chunk coordinates"}, 400) self.send_json({"error": "invalid chunk coordinates"}, 400)
return return
json_path = PROJECT_ROOT / "assetsraw" / "chunks" / f"chunk_{x}_{y}_{z}.json" json_path = (
PROJECT_ROOT / "assetsraw" / "maps" / "overworld" / "chunks"
/ f"chunk_{x}_{y}_{z}.json"
)
if not json_path.is_file(): if not json_path.is_file():
self.send_json({"error": "chunk json not found"}, 404) self.send_json({"error": "chunk json not found"}, 404)
return return
+1 -1
View File
@@ -9,7 +9,7 @@
#include "error/error.h" #include "error/error.h"
#include <zip.h> #include <zip.h>
#define ASSET_FILE_NAME_MAX 48 #define ASSET_FILE_NAME_MAX 128
// Max bytes requested per zip_fread() call in assetFileRead(). Some // Max bytes requested per zip_fread() call in assetFileRead(). Some
// zip_fread() implementations (seen on PSP) reject a single call asking // zip_fread() implementations (seen on PSP) reject a single call asking
+31 -9
View File
@@ -15,6 +15,7 @@
#include "rpg/entity/global/entityglobal.h" #include "rpg/entity/global/entityglobal.h"
#include "rpg/entity/item/entityitem.h" #include "rpg/entity/item/entityitem.h"
#include "rpg/overworld/maparea.h" #include "rpg/overworld/maparea.h"
#include "save/save.h"
map_t MAP; map_t MAP;
@@ -28,7 +29,29 @@ void mapChunkLoadingSlotClear(chunk_t *chunk) {
errorret_t mapInit() { errorret_t mapInit() {
memoryZero(&MAP, sizeof(map_t)); memoryZero(&MAP, sizeof(map_t));
MAP.loaded = true; errorOk();
}
bool_t mapIsLoaded() {
return MAP.name[0] != '\0';
}
errorret_t mapSetMap(const char_t *map) {
assertNotNull(map, "mapSetMap: map name cannot be NULL");
assertStrLenMax(map, MAP_NAME_MAX, "Map name too long");
if(mapIsLoaded()) {
for(chunkindex_t i = 0; i < MAP_CHUNK_COUNT; i++) {
mapChunkUnload(&MAP.chunks[i]);
}
}
memoryZero(&MAP, sizeof(map_t));
stringCopy(MAP.name, map, MAP_NAME_MAX);
// Keep the current save slot's cached map name in sync so whichever map
// is active gets persisted next time the slot is actually saved.
stringCopy(SAVE.slot.cachedData.mapName, MAP.name, MAP_NAME_MAX);
chunkindex_t i = 0; chunkindex_t i = 0;
for(chunkunit_t z = 0; z < MAP_CHUNK_DEPTH; z++) { for(chunkunit_t z = 0; z < MAP_CHUNK_DEPTH; z++) {
@@ -47,10 +70,6 @@ errorret_t mapInit() {
errorOk(); errorOk();
} }
bool_t mapIsLoaded() {
return MAP.loaded;
}
errorret_t mapPositionSet(const chunkpos_t newPos) { errorret_t mapPositionSet(const chunkpos_t newPos) {
if(!mapIsLoaded()) errorThrow("No map loaded"); if(!mapIsLoaded()) errorThrow("No map loaded");
if(chunkPositionIsEqual(newPos, MAP.chunkPosition)) errorOk(); if(chunkPositionIsEqual(newPos, MAP.chunkPosition)) errorOk();
@@ -132,6 +151,7 @@ errorret_t mapDispose() {
for(chunkindex_t i = 0; i < MAP_CHUNK_COUNT; i++) { for(chunkindex_t i = 0; i < MAP_CHUNK_COUNT; i++) {
mapChunkUnload(&MAP.chunks[i]); mapChunkUnload(&MAP.chunks[i]);
} }
MAP.name[0] = '\0';
errorOk(); errorOk();
} }
@@ -203,10 +223,11 @@ errorret_t mapChunkLoad(chunk_t *chunk) {
chunk->meshCount = 0; chunk->meshCount = 0;
char_t name[64]; char_t name[MAP_FILE_PATH_MAX];
stringFormat( stringFormat(
name, sizeof(name), name, sizeof(name),
"chunks/%d_%d_%d.dcf", "maps/%s/chunks/%d_%d_%d.dcf",
MAP.name,
(int32_t)chunk->position.x, (int32_t)chunk->position.x,
(int32_t)chunk->position.y, (int32_t)chunk->position.y,
(int32_t)chunk->position.z (int32_t)chunk->position.z
@@ -241,10 +262,11 @@ void mapChunkLoadNext() {
MAP.loadQueueCount--; MAP.loadQueueCount--;
MAP.loadingChunks[slot] = chunk; MAP.loadingChunks[slot] = chunk;
char_t name[64]; char_t name[MAP_FILE_PATH_MAX];
stringFormat( stringFormat(
name, sizeof(name), name, sizeof(name),
"chunks/%d_%d_%d.dcf", "maps/%s/chunks/%d_%d_%d.dcf",
MAP.name,
(int32_t)chunk->position.x, (int32_t)chunk->position.x,
(int32_t)chunk->position.y, (int32_t)chunk->position.y,
(int32_t)chunk->position.z (int32_t)chunk->position.z
+19 -2
View File
@@ -12,12 +12,18 @@
#define MAP_FILE_PATH_MAX 128 #define MAP_FILE_PATH_MAX 128
// Buffer size for a map's name, including the null terminator - so map
// names are at most 9 characters.
#define MAP_NAME_MAX 10
// Number of chunks that may be mid-load (asset locked & awaiting onLoaded/ // Number of chunks that may be mid-load (asset locked & awaiting onLoaded/
// onError) at the same time - everything past this waits in loadQueue. // onError) at the same time - everything past this waits in loadQueue.
#define MAP_CHUNK_LOAD_CONCURRENCY 2 #define MAP_CHUNK_LOAD_CONCURRENCY 2
typedef struct map_s { typedef struct map_s {
bool_t loaded; // Name of the currently loaded map, or an empty string if none is
// loaded (see mapIsLoaded).
char_t name[MAP_NAME_MAX];
chunk_t chunks[MAP_CHUNK_COUNT]; chunk_t chunks[MAP_CHUNK_COUNT];
chunk_t *chunkOrder[MAP_CHUNK_COUNT]; chunk_t *chunkOrder[MAP_CHUNK_COUNT];
@@ -31,7 +37,8 @@ typedef struct map_s {
extern map_t MAP; extern map_t MAP;
/** /**
* Initializes the map. * Initializes the map subsystem. No map is loaded until mapSetMap is
* called.
* *
* @return An error code. * @return An error code.
*/ */
@@ -44,6 +51,16 @@ errorret_t mapInit();
*/ */
bool_t mapIsLoaded(); bool_t mapIsLoaded();
/**
* Sets the active map by name, unloading the previously loaded map (if
* any) first, then starts loading the new map's chunks around chunk
* position (0, 0, 0).
*
* @param map The map's name, at most MAP_NAME_MAX - 1 characters.
* @return An error code.
*/
errorret_t mapSetMap(const char_t *map);
/** /**
* Updates the map. * Updates the map.
* *
+1 -2
View File
@@ -32,9 +32,8 @@ errorret_t rpgInit(void) {
errorChain(mapInit()); errorChain(mapInit());
rpgCameraInit(); rpgCameraInit();
// Init test world // Init test world
errorChain(mapPositionSet((chunkpos_t){ 0, 0, 0 })); errorChain(mapSetMap("overworld"));
// The player is the one entity that isn't sourced from map/chunk data - // 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 // every other entity (NPCs, items) and map area comes from the loaded
+4 -2
View File
@@ -8,6 +8,8 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
save.c save.c
savedevice.c savedevice.c
saveslot.c
savesettings.c
) )
# Subdirs
add_subdirectory(slot)
add_subdirectory(settings)
+25 -4
View File
@@ -9,6 +9,7 @@
#include "util/memory.h" #include "util/memory.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "rpg/cutscene/cutscenesystem.h" #include "rpg/cutscene/cutscenesystem.h"
#include "console/console.h"
save_t SAVE; save_t SAVE;
@@ -186,10 +187,18 @@ errorret_t saveSaveSettings() {
errorret_t saveLoadSettings() { errorret_t saveLoadSettings() {
assertTrue(SAVE.deviceCurrent != 0xFF, "No current device"); assertTrue(SAVE.deviceCurrent != 0xFF, "No current device");
errorChain(saveDeviceSettingsRead( errorret_t ret = saveDeviceSettingsRead(
&SAVE.devices[SAVE.deviceCurrent], &SAVE.devices[SAVE.deviceCurrent],
&SAVE.settings &SAVE.settings
)); );
if(errorIsNotOk(ret)) {
// Corrupt or incompatible (e.g. wrong/missing schema version) settings
// file - don't take the whole game down over it, just reset to
// defaults and carry on.
errorCatch(errorPrint(ret));
consolePrint("Settings file could not be loaded, resetting to defaults.\n");
saveSettingsInit(&SAVE.settings);
}
SAVE.settingsDirty = false; SAVE.settingsDirty = false;
errorOk(); errorOk();
@@ -222,11 +231,23 @@ errorret_t saveLoadSlot() {
errorOk(); errorOk();
} }
errorChain(saveDeviceSlotRead( errorret_t ret = saveDeviceSlotRead(
&SAVE.devices[SAVE.deviceCurrent], &SAVE.devices[SAVE.deviceCurrent],
&SAVE.slot, &SAVE.slot,
SAVE.slotCurrent SAVE.slotCurrent
)); );
if(errorIsNotOk(ret)) {
// Corrupt or incompatible (e.g. wrong/missing schema version) slot
// file - don't take the whole game down over it, treat it the same as
// an empty/unused slot.
errorCatch(errorPrint(ret));
consolePrint(
"Save slot %u could not be loaded, treating as empty.\n",
(uint32_t)SAVE.slotCurrent
);
saveSlotInit(&SAVE.slot);
}
// Update cache // Update cache
SAVE.caches[SAVE.slotCurrent] = SAVE.slot.cachedData; SAVE.caches[SAVE.slotCurrent] = SAVE.slot.cachedData;
+2 -2
View File
@@ -7,8 +7,8 @@
#pragma once #pragma once
#include "savedevice.h" #include "savedevice.h"
#include "saveslot.h" #include "save/slot/saveslot.h"
#include "savesettings.h" #include "save/settings/savesettings.h"
typedef struct { typedef struct {
// File state // File state
+2 -2
View File
@@ -12,8 +12,8 @@
#if defined(SAVE_DEVICE_DATA_RAW) #if defined(SAVE_DEVICE_DATA_RAW)
#include "yyjson.h" #include "yyjson.h"
#include "save/savejson.h" #include "save/savejson.h"
#include "save/saveslot.h" #include "save/slot/saveslot.h"
#include "save/savesettings.h" #include "save/settings/savesettings.h"
#include "util/crypt.h" #include "util/crypt.h"
#include "util/endian.h" #include "util/endian.h"
#include <zlib.h> #include <zlib.h>
+4 -4
View File
@@ -164,10 +164,10 @@ errorret_t saveDeviceDispose(savedevice_t *device);
#if defined(SAVE_DEVICE_DATA_RAW) #if defined(SAVE_DEVICE_DATA_RAW)
// Mirrors the same guarded default in saveslot.h - can't #include that // Mirrors the same guarded default in save/slot/saveslot.h - can't
// header here to get it directly, since saveslot.h itself includes this // #include that header here to get it directly, since it itself includes
// header (savedevice.h), and relying on include order to resolve the cycle // this header (savedevice.h), and relying on include order to resolve the
// correctly would be fragile. // cycle correctly would be fragile.
#ifndef SAVE_SLOT_COUNT #ifndef SAVE_SLOT_COUNT
#define SAVE_SLOT_COUNT 3 #define SAVE_SLOT_COUNT 3
#endif #endif
+27
View File
@@ -76,6 +76,33 @@
(dest) = hasInt32(key) ? \ (dest) = hasInt32(key) ? \
(int32_t)yyjson_get_int(yyjson_obj_get(object, key)) : (int32_t)(def) (int32_t)yyjson_get_int(yyjson_obj_get(object, key)) : (int32_t)(def)
/**
* Writes a schema version into the current JSON object's "version" key.
* Pair with requireVersion() on the read side.
*
* @param version The version constant to write (e.g. SAVE_SLOT_CURRENT).
*/
#define writeVersion(version) writeInt32("version", (version))
/**
* Requires the current JSON object's "version" key to exist and exactly
* match the given version constant, throwing otherwise. Used to reject a
* save file outright rather than trying to migrate an old schema.
*
* @param version The expected version constant (e.g. SAVE_SLOT_CURRENT).
*/
#define requireVersion(version) { \
requireInt32("version"); \
int32_t saveJsonVersion; \
readInt32("version", saveJsonVersion, 0); \
if(saveJsonVersion != (version)) { \
errorThrow( \
"Save JSON version mismatch (expected %d, got %d)", \
(int)(version), (int)saveJsonVersion \
); \
} \
}
/** /**
* Checks if the given key exists on the current JSON object. * Checks if the given key exists on the current JSON object.
* *
+12
View File
@@ -0,0 +1,12 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
savesettings.c
savesettingscurrent.c
savesettingsver1.c
)
+38
View File
@@ -0,0 +1,38 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "savesettings.h"
#include "save/settings/savesettingscurrent.h"
#include "assert/assert.h"
#include "util/memory.h"
void saveSettingsInit(savesettings_t *settings) {
assertNotNull(settings, "Settings cannot be null");
memorySet(settings, 0, sizeof(savesettings_t));
settings->audioMasterVolume = 1.0f;
audiomixerchannel_t channel = 0;
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
settings->audioChannelVolume[channel] = 1.0f;
channel++;
}
}
errorret_t saveSettingsWriteJSON(
savesettings_t *settings,
yyjson_mut_doc *doc,
yyjson_mut_val *object
) {
errorChain(saveSettingsCurrentWriteJSON(settings, doc, object));
errorOk();
}
errorret_t saveSettingsReadJSON(savesettings_t *settings, yyjson_val *object) {
errorChain(saveSettingsCurrentReadJSON(settings, object));
errorOk();
}
@@ -6,14 +6,19 @@
*/ */
#pragma once #pragma once
#include "time/timeepoch.h" #include "save/savedevice.h"
#include "savedevice.h"
#include "yyjson.h"
#include "audio/mixer/audiomixerchannel.h" #include "audio/mixer/audiomixerchannel.h"
#include "yyjson.h"
// The stable, version-independent in-memory shape of save settings - what
// the rest of the engine actually reads/writes, using live engine constants
// (AUDIO_MIXER_CHANNEL_COUNT) freely. Every save schema version
// (savesettingsver1_t, ...) redefines its own frozen copy of these fields
// for its JSON wire format; saveSettingsCurrentWriteJSON()/ReadJSON()
// (savesettingscurrent.c) manually copy field-by-field between this and
// whichever version is current, so a version's on-disk shape can never
// drift just because a live engine constant changes.
typedef struct savesettings_s { typedef struct savesettings_s {
int32_t someSetting;
// Persisted mixer volume preferences - see audiomixerchannelstate_t's own // Persisted mixer volume preferences - see audiomixerchannelstate_t's own
// comment on why these live here rather than on the mixer itself. // comment on why these live here rather than on the mixer itself.
float_t audioMasterVolume; float_t audioMasterVolume;
@@ -0,0 +1,66 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "savesettingscurrent.h"
#include "assert/assert.h"
errorret_t saveSettingsCurrentWriteJSON(
savesettings_t *settings,
yyjson_mut_doc *doc,
yyjson_mut_val *object
) {
assertNotNull(settings, "Settings cannot be null");
assertNotNull(doc, "Doc cannot be null");
assertNotNull(object, "Object cannot be null");
savesettingsver1_t ver1;
ver1.audioMasterVolume = settings->audioMasterVolume;
// Bounded by the smaller of the two counts, in case a future live channel
// count ever diverges from this frozen v1 schema's count.
uint8_t channelCount = AUDIO_MIXER_CHANNEL_COUNT;
if(SAVE_SETTINGS_VER1_AUDIO_CHANNEL_COUNT < channelCount) {
channelCount = SAVE_SETTINGS_VER1_AUDIO_CHANNEL_COUNT;
}
for(uint8_t i = 0; i < channelCount; i++) {
ver1.audioChannelVolume[i] = settings->audioChannelVolume[i];
}
for(
uint8_t i = channelCount; i < SAVE_SETTINGS_VER1_AUDIO_CHANNEL_COUNT; i++
) {
ver1.audioChannelVolume[i] = 1.0f;
}
errorChain(saveSettingsVer1WriteJSON(&ver1, doc, object));
errorOk();
}
errorret_t saveSettingsCurrentReadJSON(
savesettings_t *settings,
yyjson_val *object
) {
assertNotNull(settings, "Settings cannot be null");
assertNotNull(object, "Object cannot be null");
savesettingsver1_t ver1;
errorChain(saveSettingsVer1ReadJSON(&ver1, object));
settings->audioMasterVolume = ver1.audioMasterVolume;
uint8_t channelCount = AUDIO_MIXER_CHANNEL_COUNT;
if(SAVE_SETTINGS_VER1_AUDIO_CHANNEL_COUNT < channelCount) {
channelCount = SAVE_SETTINGS_VER1_AUDIO_CHANNEL_COUNT;
}
for(uint8_t i = 0; i < channelCount; i++) {
settings->audioChannelVolume[i] = ver1.audioChannelVolume[i];
}
for(uint8_t i = channelCount; i < AUDIO_MIXER_CHANNEL_COUNT; i++) {
settings->audioChannelVolume[i] = 1.0f;
}
errorOk();
}
@@ -0,0 +1,40 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "save/settings/savesettings.h"
#include "save/settings/savesettingsver1.h"
/**
* Converts the given save settings to whichever schema SAVE_SETTINGS_CURRENT
* (savesettingsver.h) selects and writes it out to the given JSON object.
* Update this (only) when bumping to a new SAVE_SETTINGS_VER_N.
*
* @param settings The save settings to write.
* @param doc The mutable JSON document that owns the object.
* @param object The mutable JSON object to write into.
* @return Error state if any.
*/
errorret_t saveSettingsCurrentWriteJSON(
savesettings_t *settings,
yyjson_mut_doc *doc,
yyjson_mut_val *object
);
/**
* Reads whichever schema SAVE_SETTINGS_CURRENT (savesettingsver.h) selects
* from the given JSON object and converts it into the given save settings.
* Update this (only) when bumping to a new SAVE_SETTINGS_VER_N.
*
* @param settings The save settings to read into.
* @param object The JSON object to read from.
* @return Error state if any.
*/
errorret_t saveSettingsCurrentReadJSON(
savesettings_t *settings,
yyjson_val *object
);
+15
View File
@@ -0,0 +1,15 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "time/timeepoch.h"
#include "save/savedevice.h"
#include "yyjson.h"
#define SAVE_SETTINGS_VER_1 1
#define SAVE_SETTINGS_CURRENT SAVE_SETTINGS_VER_1
@@ -5,26 +5,12 @@
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
*/ */
#include "savesettings.h" #include "savesettingsver1.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "save/savejson.h"
#include "savejson.h"
void saveSettingsInit(savesettings_t *settings) { errorret_t saveSettingsVer1WriteJSON(
assertNotNull(settings, "Settings cannot be null"); savesettingsver1_t *settings,
memorySet(settings, 0, sizeof(savesettings_t));
settings->audioMasterVolume = 1.0f;
audiomixerchannel_t channel = 0;
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
settings->audioChannelVolume[channel] = 1.0f;
channel++;
}
}
errorret_t saveSettingsWriteJSON(
savesettings_t *settings,
yyjson_mut_doc *doc, yyjson_mut_doc *doc,
yyjson_mut_val *object yyjson_mut_val *object
) { ) {
@@ -32,25 +18,29 @@ errorret_t saveSettingsWriteJSON(
assertNotNull(doc, "Doc cannot be null"); assertNotNull(doc, "Doc cannot be null");
assertNotNull(object, "Object cannot be null"); assertNotNull(object, "Object cannot be null");
writeInt32("someSetting", settings->someSetting); writeVersion(SAVE_SETTINGS_CURRENT);
writeFloat("audioMasterVolume", settings->audioMasterVolume); writeFloat("audioMasterVolume", settings->audioMasterVolume);
writeFloatArray( writeFloatArray(
"audioChannelVolume", settings->audioChannelVolume, "audioChannelVolume", settings->audioChannelVolume,
AUDIO_MIXER_CHANNEL_COUNT SAVE_SETTINGS_VER1_AUDIO_CHANNEL_COUNT
); );
errorOk(); errorOk();
} }
errorret_t saveSettingsReadJSON(savesettings_t *settings, yyjson_val *object) { errorret_t saveSettingsVer1ReadJSON(
savesettingsver1_t *settings,
yyjson_val *object
) {
assertNotNull(settings, "Settings cannot be null"); assertNotNull(settings, "Settings cannot be null");
assertNotNull(object, "Object cannot be null"); assertNotNull(object, "Object cannot be null");
readInt32("someSetting", settings->someSetting, 0); requireVersion(SAVE_SETTINGS_CURRENT);
readFloat("audioMasterVolume", settings->audioMasterVolume, 1.0f); readFloat("audioMasterVolume", settings->audioMasterVolume, 1.0f);
readFloatArray( readFloatArray(
"audioChannelVolume", settings->audioChannelVolume, "audioChannelVolume", settings->audioChannelVolume,
AUDIO_MIXER_CHANNEL_COUNT, 1.0f SAVE_SETTINGS_VER1_AUDIO_CHANNEL_COUNT, 1.0f
); );
errorOk(); errorOk();
+55
View File
@@ -0,0 +1,55 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "save/settings/savesettingsver.h"
#include "yyjson.h"
// This schema's own frozen channel count - never reference
// AUDIO_MIXER_CHANNEL_COUNT (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 constant does.
#define SAVE_SETTINGS_VER1_AUDIO_CHANNEL_COUNT 7
// Independent from savesettings_t (save/settings/savesettings.h) by design
// - this is what version 1 actually put on disk, frozen forever.
// saveSettingsCurrentWriteJSON()/ReadJSON() (savesettingscurrent.c) manually
// copy field-by-field between the two, since they're separate types that
// merely happen to currently look alike.
typedef struct savesettingsver1_s {
float_t audioMasterVolume;
float_t audioChannelVolume[SAVE_SETTINGS_VER1_AUDIO_CHANNEL_COUNT];
} savesettingsver1_t;
/**
* Writes the given v1 save settings data out to the given JSON object,
* stamping SAVE_SETTINGS_CURRENT as the "version" field.
*
* @param settings The v1 save settings data to write.
* @param doc The mutable JSON document that owns the object.
* @param object The mutable JSON object to write into.
* @return Error state if any.
*/
errorret_t saveSettingsVer1WriteJSON(
savesettingsver1_t *settings,
yyjson_mut_doc *doc,
yyjson_mut_val *object
);
/**
* Reads v1 save settings data in from the given JSON object. Throws if the
* JSON's "version" is missing or doesn't match SAVE_SETTINGS_CURRENT.
*
* @param settings The v1 save settings data to read into.
* @param object The JSON object to read from.
* @return Error state if any.
*/
errorret_t saveSettingsVer1ReadJSON(
savesettingsver1_t *settings,
yyjson_val *object
);
+12
View File
@@ -0,0 +1,12 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
saveslot.c
saveslotcurrent.c
saveslotver1.c
)
@@ -6,10 +6,9 @@
*/ */
#include "saveslot.h" #include "saveslot.h"
#include "save/slot/saveslotcurrent.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
#include "savejson.h"
#include "time/time.h"
void saveSlotInit(saveslot_t *slot) { void saveSlotInit(saveslot_t *slot) {
assertNotNull(slot, "Slot cannot be null"); assertNotNull(slot, "Slot cannot be null");
@@ -33,29 +32,11 @@ errorret_t saveSlotWriteJSON(
yyjson_mut_doc *doc, yyjson_mut_doc *doc,
yyjson_mut_val *object yyjson_mut_val *object
) { ) {
assertNotNull(slot, "Slot cannot be null"); errorChain(saveSlotCurrentWriteJSON(slot, doc, object));
assertNotNull(doc, "Doc cannot be null");
assertNotNull(object, "Object cannot be null");
// Update time
slot->cachedData.time = timeGetEpoch();
writeString("name", slot->cachedData.name);
writeTime("time", slot->cachedData.time);
writeInt32("playerLevel", slot->cachedData.playerLevel);
errorOk(); errorOk();
} }
errorret_t saveSlotReadJSON(saveslot_t *slot, yyjson_val *object) { errorret_t saveSlotReadJSON(saveslot_t *slot, yyjson_val *object) {
assertNotNull(slot, "Slot cannot be null"); errorChain(saveSlotCurrentReadJSON(slot, object));
assertNotNull(object, "Object cannot be null");
char_t saveJsonStringBuffer[SAVE_JSON_STRING_BUFFER_SIZE];
readString("name", slot->cachedData.name, "", SAVE_SLOT_NAME_LENGTH);
readTime("time", slot->cachedData.time);
readInt32("playerLevel", slot->cachedData.playerLevel, 1);
errorOk(); errorOk();
} }
@@ -6,8 +6,9 @@
*/ */
#pragma once #pragma once
#include "save/savedevice.h"
#include "rpg/overworld/map.h"
#include "time/timeepoch.h" #include "time/timeepoch.h"
#include "savedevice.h"
#include "yyjson.h" #include "yyjson.h"
#define SAVE_SLOT_NAME_LENGTH 8 #define SAVE_SLOT_NAME_LENGTH 8
@@ -15,10 +16,18 @@
#define SAVE_SLOT_COUNT 3 #define SAVE_SLOT_COUNT 3
#endif #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.
typedef struct { typedef struct {
char_t name[SAVE_SLOT_NAME_LENGTH + 1];// 8 characters + null terminator char_t name[SAVE_SLOT_NAME_LENGTH + 1];// 8 characters + null terminator
dusktimeepoch_t time; dusktimeepoch_t time;
int32_t playerLevel; int32_t playerLevel;
char_t mapName[MAP_NAME_MAX];
} saveslotcache_t; } saveslotcache_t;
typedef struct saveslot_s { typedef struct saveslot_s {
+51
View File
@@ -0,0 +1,51 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "saveslotcurrent.h"
#include "assert/assert.h"
#include "util/string.h"
#include "time/time.h"
errorret_t saveSlotCurrentWriteJSON(
saveslot_t *slot,
yyjson_mut_doc *doc,
yyjson_mut_val *object
) {
assertNotNull(slot, "Slot cannot be null");
assertNotNull(doc, "Doc cannot be null");
assertNotNull(object, "Object cannot be null");
// Stamped on the stable struct (not the throwaway ver1 copy below) so the
// fresh timestamp survives the write - saveSlotHasSaved() depends on it.
slot->cachedData.time = timeGetEpoch();
saveslotver1_t ver1;
stringCopy(ver1.name, slot->cachedData.name, sizeof(ver1.name));
ver1.time = slot->cachedData.time;
ver1.playerLevel = slot->cachedData.playerLevel;
stringCopy(ver1.mapName, slot->cachedData.mapName, sizeof(ver1.mapName));
errorChain(saveSlotVer1WriteJSON(&ver1, doc, object));
errorOk();
}
errorret_t saveSlotCurrentReadJSON(saveslot_t *slot, yyjson_val *object) {
assertNotNull(slot, "Slot cannot be null");
assertNotNull(object, "Object cannot be null");
saveslotver1_t ver1;
errorChain(saveSlotVer1ReadJSON(&ver1, object));
stringCopy(slot->cachedData.name, ver1.name, sizeof(slot->cachedData.name));
slot->cachedData.time = ver1.time;
slot->cachedData.playerLevel = ver1.playerLevel;
stringCopy(
slot->cachedData.mapName, ver1.mapName, sizeof(slot->cachedData.mapName)
);
errorOk();
}
+37
View File
@@ -0,0 +1,37 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "save/slot/saveslot.h"
#include "save/slot/saveslotver1.h"
/**
* Converts the given save slot to whichever schema SAVE_SLOT_CURRENT
* (saveslotver.h) selects and writes it out to the given JSON object.
* Update this (only) when bumping to a new SAVE_SLOT_VER_N.
*
* @param slot The save slot to write.
* @param doc The mutable JSON document that owns the object.
* @param object The mutable JSON object to write into.
* @return Error state if any.
*/
errorret_t saveSlotCurrentWriteJSON(
saveslot_t *slot,
yyjson_mut_doc *doc,
yyjson_mut_val *object
);
/**
* Reads whichever schema SAVE_SLOT_CURRENT (saveslotver.h) selects from the
* given JSON object and converts it into the given save slot. Update this
* (only) when bumping to a new SAVE_SLOT_VER_N.
*
* @param slot The save slot to read into.
* @param object The JSON object to read from.
* @return Error state if any.
*/
errorret_t saveSlotCurrentReadJSON(saveslot_t *slot, yyjson_val *object);
+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
// One constant per save slot JSON schema this codebase has ever shipped.
// Never remove or renumber an existing entry - old save files on disk may
// still declare it.
#define SAVE_SLOT_VER_1 1
// The schema saveSlotCurrentWriteJSON()/saveSlotCurrentReadJSON() use today.
// Bump this to a new SAVE_SLOT_VER_N when the slot JSON shape changes.
#define SAVE_SLOT_CURRENT SAVE_SLOT_VER_1
+46
View File
@@ -0,0 +1,46 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "saveslotver1.h"
#include "assert/assert.h"
#include "save/savejson.h"
errorret_t saveSlotVer1WriteJSON(
saveslotver1_t *slot,
yyjson_mut_doc *doc,
yyjson_mut_val *object
) {
assertNotNull(slot, "Slot cannot be null");
assertNotNull(doc, "Doc cannot be null");
assertNotNull(object, "Object cannot be null");
writeVersion(SAVE_SLOT_CURRENT);
writeString("name", slot->name);
writeTime("time", slot->time);
writeInt32("playerLevel", slot->playerLevel);
writeString("mapName", slot->mapName);
errorOk();
}
errorret_t saveSlotVer1ReadJSON(saveslotver1_t *slot, yyjson_val *object) {
assertNotNull(slot, "Slot cannot be null");
assertNotNull(object, "Object cannot be null");
char_t saveJsonStringBuffer[SAVE_JSON_STRING_BUFFER_SIZE];
requireVersion(SAVE_SLOT_CURRENT);
readString("name", slot->name, "", SAVE_SLOT_VER1_NAME_LENGTH);
readTime("time", slot->time);
readInt32("playerLevel", slot->playerLevel, 1);
readString(
"mapName", slot->mapName, "", SAVE_SLOT_VER1_MAP_NAME_MAX - 1
);
errorOk();
}
+56
View File
@@ -0,0 +1,56 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "time/timeepoch.h"
#include "save/slot/saveslotver.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.
#define SAVE_SLOT_VER1_NAME_LENGTH 8
#define SAVE_SLOT_VER1_MAP_NAME_MAX 10
// Independent from saveslotcache_t (save/slot/saveslot.h) by design - this
// is what version 1 actually put on disk, frozen forever. saveSlotCurrent
// WriteJSON()/ReadJSON() (saveslotcurrent.c) manually copy field-by-field
// between the two, since they're separate types that merely happen to
// currently look alike.
typedef struct saveslotver1_s {
char_t name[SAVE_SLOT_VER1_NAME_LENGTH + 1];
dusktimeepoch_t time;
int32_t playerLevel;
char_t mapName[SAVE_SLOT_VER1_MAP_NAME_MAX];
} saveslotver1_t;
/**
* Writes the given v1 save slot data out to the given JSON object, stamping
* SAVE_SLOT_CURRENT as the "version" field.
*
* @param slot The v1 save slot data to write.
* @param doc The mutable JSON document that owns the object.
* @param object The mutable JSON object to write into.
* @return Error state if any.
*/
errorret_t saveSlotVer1WriteJSON(
saveslotver1_t *slot,
yyjson_mut_doc *doc,
yyjson_mut_val *object
);
/**
* Reads v1 save slot data in from the given JSON object. Throws if the
* JSON's "version" is missing or doesn't match SAVE_SLOT_CURRENT.
*
* @param slot The v1 save slot data to read into.
* @param object The JSON object to read from.
* @return Error state if any.
*/
errorret_t saveSlotVer1ReadJSON(saveslotver1_t *slot, yyjson_val *object);
+3 -1
View File
@@ -13,6 +13,7 @@
#include "rpg/entity/entity.h" #include "rpg/entity/entity.h"
#include "rpg/entity/entitytype.h" #include "rpg/entity/entitytype.h"
#include "rpg/overworld/worldpos.h" #include "rpg/overworld/worldpos.h"
#include "rpg/overworld/map.h"
uiplayerpos_t UIPLAYERPOS; uiplayerpos_t UIPLAYERPOS;
@@ -46,7 +47,8 @@ errorret_t uiPlayerPosDraw() {
stringFormat( stringFormat(
UIPLAYERPOS.text, UIPLAYERPOS.text,
UI_PLAYERPOS_TEXT_MAX - 1, UI_PLAYERPOS_TEXT_MAX - 1,
"%d,%d,%d[%d,%d,%d]#%d", "%s %d,%d,%d[%d,%d,%d]#%d",
MAP.name,
(int_t)player->position.x, (int_t)player->position.x,
(int_t)player->position.y, (int_t)player->position.y,
(int_t)player->position.z, (int_t)player->position.z,
+3 -3
View File
@@ -28,9 +28,9 @@ extern uiplayerpos_t UIPLAYERPOS;
errorret_t uiPlayerPosInit(); errorret_t uiPlayerPosInit();
/** /**
* Draws the player world position, chunk position, and chunk index on * Draws the current map name, player world position, chunk position, and
* screen. Searches for the first ENTITY_TYPE_PLAYER and renders: * chunk index on screen. Searches for the first ENTITY_TYPE_PLAYER and
* WORLDX,WORLDY,WORLDZ[chunkx,chunky,chunkz]#chunkIndex * renders: MAPNAME WORLDX,WORLDY,WORLDZ[chunkx,chunky,chunkz]#chunkIndex
* *
* @return Any error that occurs. * @return Any error that occurs.
*/ */
+1 -1
View File
@@ -11,7 +11,7 @@
#include "ui/widget/uimenu.h" #include "ui/widget/uimenu.h"
#include "ui/widget/uiscrolling.h" #include "ui/widget/uiscrolling.h"
#include "ui/dialog/save/uisaveslot.h" #include "ui/dialog/save/uisaveslot.h"
#include "save/saveslot.h" #include "save/slot/saveslot.h"
#define UI_SELECT_SAVE_TITLE_TEXT_MAX 64 #define UI_SELECT_SAVE_TITLE_TEXT_MAX 64
#define UI_SELECT_SAVE_TITLE_SPRITES_MAX UI_SELECT_SAVE_TITLE_TEXT_MAX #define UI_SELECT_SAVE_TITLE_SPRITES_MAX UI_SELECT_SAVE_TITLE_TEXT_MAX
+2 -2
View File
@@ -7,8 +7,8 @@
#include "save/savedevice.h" #include "save/savedevice.h"
#include "save/savedevicelinux.h" #include "save/savedevicelinux.h"
#include "save/saveslot.h" #include "save/slot/saveslot.h"
#include "save/savesettings.h" #include "save/settings/savesettings.h"
#include "save/savejson.h" #include "save/savejson.h"
#include "asset/asset.h" #include "asset/asset.h"
#include "assert/assert.h" #include "assert/assert.h"
+2 -1
View File
@@ -9,12 +9,13 @@
#include "rpg/overworld/map.h" #include "rpg/overworld/map.h"
#include "rpg/overworld/tile.h" #include "rpg/overworld/tile.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h"
void entityTestFixtureReset(void) { void entityTestFixtureReset(void) {
memoryZero(ENTITIES, sizeof(ENTITIES)); memoryZero(ENTITIES, sizeof(ENTITIES));
memoryZero(&MAP, sizeof(map_t)); memoryZero(&MAP, sizeof(map_t));
MAP.loaded = true; stringCopy(MAP.name, "test", MAP_NAME_MAX);
MAP.chunkPosition = (chunkpos_t){ 0, 0, 0 }; MAP.chunkPosition = (chunkpos_t){ 0, 0, 0 };
chunk_t *chunk = &MAP.chunks[0]; chunk_t *chunk = &MAP.chunks[0];
+10 -10
View File
@@ -57,7 +57,7 @@ static void test_saveInit_setsDefaults(void **state) {
assert_int_equal(SAVE.slotCurrent, 0xFF); assert_int_equal(SAVE.slotCurrent, 0xFF);
assert_false(SAVE.findingAvailableDevice); assert_false(SAVE.findingAvailableDevice);
assert_false(SAVE.noAvailableDeviceFound); assert_false(SAVE.noAvailableDeviceFound);
assert_int_equal(SAVE.settings.someSetting, 0); assert_true(SAVE.settings.audioMasterVolume == 1.0f);
assert_int_equal(SAVE.devices[0].state, SAVE_DEVICE_STATE_UNKNOWN); assert_int_equal(SAVE.devices[0].state, SAVE_DEVICE_STATE_UNKNOWN);
for(uint8_t i = 0; i < SAVE_SLOT_COUNT; i++) { for(uint8_t i = 0; i < SAVE_SLOT_COUNT; i++) {
@@ -229,7 +229,7 @@ static void test_saveSaveSettings_notDirty_isNoop(void **state) {
// if someone changes the no-op condition without meaning to. // if someone changes the no-op condition without meaning to.
makeDeviceAvailable(); makeDeviceAvailable();
assert_false(SAVE.settingsDirty); assert_false(SAVE.settingsDirty);
SAVE.settings.someSetting = 123; SAVE.settings.audioMasterVolume = 12.0f;
errorret_t ret = saveSaveSettings(); errorret_t ret = saveSaveSettings();
assert_true(errorIsOk(ret)); assert_true(errorIsOk(ret));
@@ -238,7 +238,7 @@ static void test_saveSaveSettings_notDirty_isNoop(void **state) {
saveSettingsInit(&onDisk); saveSettingsInit(&onDisk);
errorret_t readRet = saveDeviceSettingsRead(&SAVE.devices[0], &onDisk); errorret_t readRet = saveDeviceSettingsRead(&SAVE.devices[0], &onDisk);
assert_true(errorIsOk(readRet)); assert_true(errorIsOk(readRet));
assert_int_equal(onDisk.someSetting, 0);// never actually written assert_true(onDisk.audioMasterVolume == 1.0f);// never actually written
} }
static void test_saveSaveSettings_dirtyForced_writesAndClearsFlag( static void test_saveSaveSettings_dirtyForced_writesAndClearsFlag(
@@ -246,7 +246,7 @@ static void test_saveSaveSettings_dirtyForced_writesAndClearsFlag(
) { ) {
makeDeviceAvailable(); makeDeviceAvailable();
SAVE.settingsDirty = true;// nothing in real code sets this - forced here SAVE.settingsDirty = true;// nothing in real code sets this - forced here
SAVE.settings.someSetting = 55; SAVE.settings.audioMasterVolume = 5.5f;
errorret_t ret = saveSaveSettings(); errorret_t ret = saveSaveSettings();
assert_true(errorIsOk(ret)); assert_true(errorIsOk(ret));
@@ -256,7 +256,7 @@ static void test_saveSaveSettings_dirtyForced_writesAndClearsFlag(
saveSettingsInit(&onDisk); saveSettingsInit(&onDisk);
errorret_t readRet = saveDeviceSettingsRead(&SAVE.devices[0], &onDisk); errorret_t readRet = saveDeviceSettingsRead(&SAVE.devices[0], &onDisk);
assert_true(errorIsOk(readRet)); assert_true(errorIsOk(readRet));
assert_int_equal(onDisk.someSetting, 55); assert_true(onDisk.audioMasterVolume == 5.5f);
} }
static void test_saveLoadSettings_noCurrentDeviceAsserts(void **state) { static void test_saveLoadSettings_noCurrentDeviceAsserts(void **state) {
@@ -268,16 +268,16 @@ static void test_saveLoadSettings_readsAndClearsDirtyFlag(void **state) {
savesettings_t onDisk; savesettings_t onDisk;
saveSettingsInit(&onDisk); saveSettingsInit(&onDisk);
onDisk.someSetting = 99; onDisk.audioMasterVolume = 9.25f;
errorret_t writeRet = saveDeviceSettingsWrite(&SAVE.devices[0], &onDisk); errorret_t writeRet = saveDeviceSettingsWrite(&SAVE.devices[0], &onDisk);
assert_true(errorIsOk(writeRet)); assert_true(errorIsOk(writeRet));
SAVE.settingsDirty = true; SAVE.settingsDirty = true;
SAVE.settings.someSetting = 0; SAVE.settings.audioMasterVolume = 0.0f;
errorret_t ret = saveLoadSettings(); errorret_t ret = saveLoadSettings();
assert_true(errorIsOk(ret)); assert_true(errorIsOk(ret));
assert_int_equal(SAVE.settings.someSetting, 99); assert_true(SAVE.settings.audioMasterVolume == 9.25f);
assert_false(SAVE.settingsDirty); assert_false(SAVE.settingsDirty);
} }
@@ -470,7 +470,7 @@ static void test_saveUpdate_foundDevice_rewritesSettingsUnconditionally(
// it, regardless of settingsDirty - independent of (and unguarded by) the // it, regardless of settingsDirty - independent of (and unguarded by) the
// same dirty-flag check saveSaveSettings() itself honors. // same dirty-flag check saveSaveSettings() itself honors.
resetFindCallbackState(); resetFindCallbackState();
SAVE.settings.someSetting = 321; SAVE.settings.audioMasterVolume = 3.25f;
assert_false(SAVE.settingsDirty); assert_false(SAVE.settingsDirty);
saveFindAvailableDevice(findAvailableCallback, NULL); saveFindAvailableDevice(findAvailableCallback, NULL);
@@ -482,7 +482,7 @@ static void test_saveUpdate_foundDevice_rewritesSettingsUnconditionally(
saveSettingsInit(&onDisk); saveSettingsInit(&onDisk);
errorret_t readRet = saveDeviceSettingsRead(&SAVE.devices[0], &onDisk); errorret_t readRet = saveDeviceSettingsRead(&SAVE.devices[0], &onDisk);
assert_true(errorIsOk(readRet)); assert_true(errorIsOk(readRet));
assert_int_equal(onDisk.someSetting, 321); assert_true(onDisk.audioMasterVolume == 3.25f);
} }
int main(void) { int main(void) {
+4 -4
View File
@@ -8,8 +8,8 @@
#include "dusktest.h" #include "dusktest.h"
#include "savetestfixture.h" #include "savetestfixture.h"
#include "save/savedevice.h" #include "save/savedevice.h"
#include "save/saveslot.h" #include "save/slot/saveslot.h"
#include "save/savesettings.h" #include "save/settings/savesettings.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h" #include "util/string.h"
@@ -224,7 +224,7 @@ static void test_saveDeviceSettings_dispatchesToPlatform(void **state) {
savesettings_t written; savesettings_t written;
saveSettingsInit(&written); saveSettingsInit(&written);
written.someSetting = 88; written.audioMasterVolume = 0.25f;// exactly representable, safe to compare
errorret_t writeRet = saveDeviceSettingsWrite(&device, &written); errorret_t writeRet = saveDeviceSettingsWrite(&device, &written);
assert_true(errorIsOk(writeRet)); assert_true(errorIsOk(writeRet));
@@ -234,7 +234,7 @@ static void test_saveDeviceSettings_dispatchesToPlatform(void **state) {
errorret_t readRet = saveDeviceSettingsRead(&device, &read); errorret_t readRet = saveDeviceSettingsRead(&device, &read);
assert_true(errorIsOk(readRet)); assert_true(errorIsOk(readRet));
assert_int_equal(read.someSetting, 88); assert_true(read.audioMasterVolume == 0.25f);
} }
// ============================================================ // ============================================================
+6 -6
View File
@@ -9,8 +9,8 @@
#include "savetestfixture.h" #include "savetestfixture.h"
#include "save/savedevice.h" #include "save/savedevice.h"
#include "save/savedevicelinux.h" #include "save/savedevicelinux.h"
#include "save/saveslot.h" #include "save/slot/saveslot.h"
#include "save/savesettings.h" #include "save/settings/savesettings.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h" #include "util/string.h"
#include <stdio.h> #include <stdio.h>
@@ -298,7 +298,7 @@ static void test_settingsWriteRead_roundTrip(void **state) {
savesettings_t written; savesettings_t written;
saveSettingsInit(&written); saveSettingsInit(&written);
written.someSetting = 314; written.audioMasterVolume = 3.25f;// exactly representable, safe to compare
errorret_t writeRet = saveDeviceLinuxSettingsWrite(&device, &written); errorret_t writeRet = saveDeviceLinuxSettingsWrite(&device, &written);
assert_true(errorIsOk(writeRet)); assert_true(errorIsOk(writeRet));
@@ -308,7 +308,7 @@ static void test_settingsWriteRead_roundTrip(void **state) {
errorret_t readRet = saveDeviceLinuxSettingsRead(&device, &read); errorret_t readRet = saveDeviceLinuxSettingsRead(&device, &read);
assert_true(errorIsOk(readRet)); assert_true(errorIsOk(readRet));
assert_int_equal(read.someSetting, 314); assert_true(read.audioMasterVolume == 3.25f);
} }
static void test_settingsRead_noFileYet_leavesUntouched(void **state) { static void test_settingsRead_noFileYet_leavesUntouched(void **state) {
@@ -317,11 +317,11 @@ static void test_settingsRead_noFileYet_leavesUntouched(void **state) {
savesettings_t settings; savesettings_t settings;
saveSettingsInit(&settings); saveSettingsInit(&settings);
settings.someSetting = 777; settings.audioMasterVolume = 7.75f;
errorret_t ret = saveDeviceLinuxSettingsRead(&device, &settings); errorret_t ret = saveDeviceLinuxSettingsRead(&device, &settings);
assert_true(errorIsOk(ret)); assert_true(errorIsOk(ret));
assert_int_equal(settings.someSetting, 777); assert_true(settings.audioMasterVolume == 7.75f);
} }
static void test_settingsRead_corruptFile_errors(void **state) { static void test_settingsRead_corruptFile_errors(void **state) {
+37 -14
View File
@@ -6,7 +6,7 @@
*/ */
#include "dusktest.h" #include "dusktest.h"
#include "save/savesettings.h" #include "save/settings/savesettings.h"
#include "save/savejson.h" #include "save/savejson.h"
#include "util/memory.h" #include "util/memory.h"
#include <stdlib.h> #include <stdlib.h>
@@ -51,14 +51,14 @@ static errorret_t settingsFromJSON(
// saveSettingsInit // saveSettingsInit
// ============================================================ // ============================================================
static void test_saveSettingsInit_zeroesSomeSetting(void **state) { static void test_saveSettingsInit_resetsAudioMasterVolume(void **state) {
savesettings_t settings; savesettings_t settings;
memoryZero(&settings, sizeof(settings)); memoryZero(&settings, sizeof(settings));
settings.someSetting = 42; settings.audioMasterVolume = 42.0f;
saveSettingsInit(&settings); saveSettingsInit(&settings);
assert_int_equal(settings.someSetting, 0); assert_true(settings.audioMasterVolume == 1.0f);
} }
static void test_saveSettingsInit_nullAsserts(void **state) { static void test_saveSettingsInit_nullAsserts(void **state) {
@@ -85,7 +85,6 @@ static void test_saveSettingsReadJSON_nullAsserts(void **state) {
savesettings_t settings; savesettings_t settings;
saveSettingsInit(&settings); saveSettingsInit(&settings);
writeInit(); writeInit();
yyjson_mut_obj_add_int(doc, object, "someSetting", 1);
size_t len; size_t len;
char_t *json = yyjson_mut_write(doc, 0, &len); char_t *json = yyjson_mut_write(doc, 0, &len);
@@ -105,7 +104,7 @@ static void test_saveSettingsReadJSON_nullAsserts(void **state) {
static void test_saveSettingsWriteReadJSON_roundTrip(void **state) { static void test_saveSettingsWriteReadJSON_roundTrip(void **state) {
savesettings_t written; savesettings_t written;
saveSettingsInit(&written); saveSettingsInit(&written);
written.someSetting = 12345; written.audioMasterVolume = 2.5f;
char_t *json; char_t *json;
size_t len; size_t len;
@@ -114,35 +113,59 @@ static void test_saveSettingsWriteReadJSON_roundTrip(void **state) {
savesettings_t read; savesettings_t read;
saveSettingsInit(&read); saveSettingsInit(&read);
read.someSetting = -1;// sentinel, should be overwritten read.audioMasterVolume = -1.0f;// sentinel, should be overwritten
errorret_t readRet = settingsFromJSON(&read, json); errorret_t readRet = settingsFromJSON(&read, json);
assert_true(errorIsOk(readRet)); assert_true(errorIsOk(readRet));
assert_int_equal(read.someSetting, 12345); assert_true(read.audioMasterVolume == 2.5f);
free(json); free(json);
} }
static void test_saveSettingsReadJSON_missingKeyDefaultsToZero(void **state) { static void test_saveSettingsReadJSON_missingKeyUsesDefault(void **state) {
savesettings_t settings;
saveSettingsInit(&settings);
settings.audioMasterVolume = 999.0f;// sentinel
errorret_t ret = settingsFromJSON(&settings, "{\"version\":1}");
assert_true(errorIsOk(ret));
assert_true(settings.audioMasterVolume == 1.0f);
}
// ============================================================
// saveSettingsReadJSON - version enforcement
// ============================================================
static void test_saveSettingsReadJSON_versionMissing_errors(void **state) {
savesettings_t settings; savesettings_t settings;
saveSettingsInit(&settings); saveSettingsInit(&settings);
settings.someSetting = 999;// sentinel
errorret_t ret = settingsFromJSON(&settings, "{}"); errorret_t ret = settingsFromJSON(&settings, "{}");
assert_true(errorIsOk(ret)); assert_true(errorIsNotOk(ret));
assert_int_equal(settings.someSetting, 0); errorCatch(ret);
}
static void test_saveSettingsReadJSON_versionMismatch_errors(void **state) {
savesettings_t settings;
saveSettingsInit(&settings);
errorret_t ret = settingsFromJSON(&settings, "{\"version\":999}");
assert_true(errorIsNotOk(ret));
errorCatch(ret);
} }
int main(void) { int main(void) {
assertInit(); assertInit();
const struct CMUnitTest tests[] = { const struct CMUnitTest tests[] = {
cmocka_unit_test(test_saveSettingsInit_zeroesSomeSetting), cmocka_unit_test(test_saveSettingsInit_resetsAudioMasterVolume),
cmocka_unit_test(test_saveSettingsInit_nullAsserts), cmocka_unit_test(test_saveSettingsInit_nullAsserts),
cmocka_unit_test(test_saveSettingsWriteJSON_nullAsserts), cmocka_unit_test(test_saveSettingsWriteJSON_nullAsserts),
cmocka_unit_test(test_saveSettingsReadJSON_nullAsserts), cmocka_unit_test(test_saveSettingsReadJSON_nullAsserts),
cmocka_unit_test(test_saveSettingsWriteReadJSON_roundTrip), cmocka_unit_test(test_saveSettingsWriteReadJSON_roundTrip),
cmocka_unit_test(test_saveSettingsReadJSON_missingKeyDefaultsToZero), cmocka_unit_test(test_saveSettingsReadJSON_missingKeyUsesDefault),
cmocka_unit_test(test_saveSettingsReadJSON_versionMissing_errors),
cmocka_unit_test(test_saveSettingsReadJSON_versionMismatch_errors),
}; };
return cmocka_run_group_tests(tests, NULL, NULL); return cmocka_run_group_tests(tests, NULL, NULL);
+42 -5
View File
@@ -6,7 +6,7 @@
*/ */
#include "dusktest.h" #include "dusktest.h"
#include "save/saveslot.h" #include "save/slot/saveslot.h"
#include "save/savejson.h" #include "save/savejson.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h" #include "util/string.h"
@@ -174,7 +174,9 @@ static void test_saveSlotReadJSON_missingFieldsUseDefaults(void **state) {
slot.cachedData.playerLevel = 999; slot.cachedData.playerLevel = 999;
errorret_t ret = slotFromJSON( errorret_t ret = slotFromJSON(
&slot, "{\"time\":{\"time\":1.0,\"timeZone\":0.0,\"offsetTime\":0.0}}" &slot,
"{\"version\":1,"
"\"time\":{\"time\":1.0,\"timeZone\":0.0,\"offsetTime\":0.0}}"
); );
assert_true(errorIsOk(ret)); assert_true(errorIsOk(ret));
@@ -186,7 +188,9 @@ static void test_saveSlotReadJSON_missingTimeKey_errors(void **state) {
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot); saveSlotInit(&slot);
errorret_t ret = slotFromJSON(&slot, "{\"name\":\"Hero\",\"playerLevel\":5}"); errorret_t ret = slotFromJSON(
&slot, "{\"version\":1,\"name\":\"Hero\",\"playerLevel\":5}"
);
assert_true(errorIsNotOk(ret)); assert_true(errorIsNotOk(ret));
errorCatch(ret); errorCatch(ret);
} }
@@ -197,7 +201,7 @@ static void test_saveSlotReadJSON_nameTooLong_errors(void **state) {
errorret_t ret = slotFromJSON( errorret_t ret = slotFromJSON(
&slot, &slot,
"{\"name\":\"WayTooLongAName\"," "{\"version\":1,\"name\":\"WayTooLongAName\","
"\"time\":{\"time\":1.0,\"timeZone\":0.0,\"offsetTime\":0.0}}" "\"time\":{\"time\":1.0,\"timeZone\":0.0,\"offsetTime\":0.0}}"
); );
assert_true(errorIsNotOk(ret)); assert_true(errorIsNotOk(ret));
@@ -209,12 +213,43 @@ static void test_saveSlotReadJSON_nonObjectRoot_errors(void **state) {
saveSlotInit(&slot); saveSlotInit(&slot);
// A non-object root has no keys, so every field falls back to its // A non-object root has no keys, so every field falls back to its
// default - except "time", which is not optional and errors instead. // default - except "version" and "time", which are required and error
// instead.
errorret_t ret = slotFromJSON(&slot, "[]"); errorret_t ret = slotFromJSON(&slot, "[]");
assert_true(errorIsNotOk(ret)); assert_true(errorIsNotOk(ret));
errorCatch(ret); errorCatch(ret);
} }
// ============================================================
// saveSlotReadJSON - version enforcement
// ============================================================
static void test_saveSlotReadJSON_versionMissing_errors(void **state) {
saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = slotFromJSON(
&slot,
"{\"name\":\"Hero\","
"\"time\":{\"time\":1.0,\"timeZone\":0.0,\"offsetTime\":0.0}}"
);
assert_true(errorIsNotOk(ret));
errorCatch(ret);
}
static void test_saveSlotReadJSON_versionMismatch_errors(void **state) {
saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = slotFromJSON(
&slot,
"{\"version\":999,\"name\":\"Hero\","
"\"time\":{\"time\":1.0,\"timeZone\":0.0,\"offsetTime\":0.0}}"
);
assert_true(errorIsNotOk(ret));
errorCatch(ret);
}
int main(void) { int main(void) {
assertInit(); assertInit();
const struct CMUnitTest tests[] = { const struct CMUnitTest tests[] = {
@@ -234,6 +269,8 @@ int main(void) {
cmocka_unit_test(test_saveSlotReadJSON_missingTimeKey_errors), cmocka_unit_test(test_saveSlotReadJSON_missingTimeKey_errors),
cmocka_unit_test(test_saveSlotReadJSON_nameTooLong_errors), cmocka_unit_test(test_saveSlotReadJSON_nameTooLong_errors),
cmocka_unit_test(test_saveSlotReadJSON_nonObjectRoot_errors), cmocka_unit_test(test_saveSlotReadJSON_nonObjectRoot_errors),
cmocka_unit_test(test_saveSlotReadJSON_versionMissing_errors),
cmocka_unit_test(test_saveSlotReadJSON_versionMismatch_errors),
}; };
return cmocka_run_group_tests(tests, NULL, NULL); return cmocka_run_group_tests(tests, NULL, NULL);
+57 -19
View File
@@ -7,7 +7,7 @@
Generates DCF + companion DMF files from raw chunk JSON files, or upgrades Generates DCF + companion DMF files from raw chunk JSON files, or upgrades
legacy DCF files (version 1 or 2) to the current version. legacy DCF files (version 1 or 2) to the current version.
JSON input (assetsraw/chunks/chunk_X_Y_Z.json): JSON input (assetsraw/maps/<map>/chunks/chunk_X_Y_Z.json):
{ {
"tiles": [ "tiles": [
{ "pos": [x, y, z], "type": <tile_shape_int>, "tile": <uv_tile_int> } { "pos": [x, y, z], "type": <tile_shape_int>, "tile": <uv_tile_int> }
@@ -35,6 +35,9 @@ JSON input (assetsraw/chunks/chunk_X_Y_Z.json):
Mesh files are located by searching under assets/meshes/ and referenced by Mesh files are located by searching under assets/meshes/ and referenced by
path from the assets root in the DCF. path from the assets root in the DCF.
<map> is the map's name, up to 9 characters (MAP_NAME_MAX in
src/dusk/rpg/overworld/map.h reserves 1 byte for the null terminator).
"entities" spawns things into the world when this chunk loads. A "global" "entities" spawns things into the world when this chunk loads. A "global"
entity is spawned via mapSpawnEntity() - globalId indexes entity is spawned via mapSpawnEntity() - globalId indexes
ENTITY_GLOBAL_LIST (src/dusk/rpg/entity/global/entitygloballist.h) and is ENTITY_GLOBAL_LIST (src/dusk/rpg/entity/global/entitygloballist.h) and is
@@ -53,7 +56,8 @@ JSON input (assetsraw/chunks/chunk_X_Y_Z.json):
trigger is bitwise MAP_TRIGGER_STEP(1)|ENTER(2)|EXIT(4). trigger is bitwise MAP_TRIGGER_STEP(1)|ENTER(2)|EXIT(4).
Output DCF is derived automatically: Output DCF is derived automatically:
assetsraw/chunks/chunk_X_Y_Z.json -> assets/chunks/X_Y_Z.dcf assetsraw/maps/<map>/chunks/chunk_X_Y_Z.json
-> assets/maps/<map>/chunks/X_Y_Z.dcf
Version 5 DCF format (after 8-byte header): Version 5 DCF format (after 8-byte header):
tile_t tiles[CHUNK_WIDTH * CHUNK_HEIGHT] (one per x/y column) tile_t tiles[CHUNK_WIDTH * CHUNK_HEIGHT] (one per x/y column)
@@ -85,7 +89,7 @@ DMF format:
Each vertex: uv[2] + pos[3] = 5 x float32 LE = 20 bytes Each vertex: uv[2] + pos[3] = 5 x float32 LE = 20 bytes
Usage: Usage:
python3 -m tools.asset.chunk # process all assetsraw/chunks/*.json python3 -m tools.asset.chunk # process all assetsraw/maps/*/chunks/*.json
python3 -m tools.asset.chunk <file.json> # process one JSON file python3 -m tools.asset.chunk <file.json> # process one JSON file
python3 -m tools.asset.chunk <file.dcf> # upgrade legacy (v1/v2) DCF in-place python3 -m tools.asset.chunk <file.dcf> # upgrade legacy (v1/v2) DCF in-place
""" """
@@ -118,6 +122,10 @@ CHUNK_MESH_NAME_MAX = 64
CHUNK_ENTITY_SPAWN_COUNT_MAX = 8 CHUNK_ENTITY_SPAWN_COUNT_MAX = 8
CHUNK_AREA_COUNT_MAX = 4 CHUNK_AREA_COUNT_MAX = 4
# Matches MAP_NAME_MAX in src/dusk/rpg/overworld/map.h (buffer size,
# including the null terminator - so map names are at most 9 characters).
MAP_NAME_MAX = 10
ENTITY_SPAWN_KIND_GLOBAL = 0 ENTITY_SPAWN_KIND_GLOBAL = 0
ENTITY_SPAWN_KIND_ITEM = 1 ENTITY_SPAWN_KIND_ITEM = 1
@@ -188,8 +196,29 @@ def write_model_json(path, mesh_rel, texture_rel, color):
print(f' Wrote model JSON {path}') print(f' Wrote model JSON {path}')
def chunk_map_name(json_path):
"""assetsraw/maps/<map>/chunks/chunk_X_Y_Z.json -> <map>
Raises ValueError if json_path isn't under that structure, or if <map>
is longer than MAP_NAME_MAX - 1 characters."""
rel = os.path.relpath(os.path.abspath(json_path), ASSETSRAW_DIR)
parts = rel.split(os.sep)
if len(parts) != 4 or parts[0] != 'maps' or parts[2] != 'chunks':
raise ValueError(
f"Chunk JSON must live at assetsraw/maps/<map>/chunks/*.json, got: "
f"{json_path}"
)
map_name = parts[1]
if len(map_name) > MAP_NAME_MAX - 1:
raise ValueError(
f"Map name too long (> {MAP_NAME_MAX - 1} characters): {map_name}"
)
return map_name
def derive_dcf_path(json_path): def derive_dcf_path(json_path):
"""assetsraw/chunks/chunk_X_Y_Z.json -> assets/chunks/X_Y_Z.dcf""" """assetsraw/maps/<map>/chunks/chunk_X_Y_Z.json
-> assets/maps/<map>/chunks/X_Y_Z.dcf"""
base = os.path.splitext(os.path.basename(json_path))[0] base = os.path.splitext(os.path.basename(json_path))[0]
if base.startswith('chunk_'): if base.startswith('chunk_'):
base = base[len('chunk_'):] base = base[len('chunk_'):]
@@ -351,6 +380,8 @@ def build_terrain_verts(tiles_bytes):
def from_json(json_path, dcf_path): def from_json(json_path, dcf_path):
map_name = chunk_map_name(json_path)
with open(json_path) as f: with open(json_path) as f:
data = json.load(f) data = json.load(f)
@@ -377,15 +408,17 @@ def from_json(json_path, dcf_path):
dcf_base = os.path.splitext(os.path.basename(dcf_path))[0] dcf_base = os.path.splitext(os.path.basename(dcf_path))[0]
# Terrain mesh + model (only written if non-empty) # Terrain mesh + model (only written if non-empty). Namespaced under the
terrain_dir = os.path.join(ASSETS_DIR, 'meshes', 'chunks') # owning map so two maps can each have a chunk at the same (x, y, z)
models_dir = os.path.join(ASSETS_DIR, 'models', 'chunks') # without their generated terrain assets colliding.
terrain_dir = os.path.join(ASSETS_DIR, 'maps', map_name, 'meshes', 'chunks')
models_dir = os.path.join(ASSETS_DIR, 'maps', map_name, 'models', 'chunks')
os.makedirs(terrain_dir, exist_ok=True) os.makedirs(terrain_dir, exist_ok=True)
os.makedirs(models_dir, exist_ok=True) os.makedirs(models_dir, exist_ok=True)
if terrain_verts: if terrain_verts:
dmf_name = f'chunk_{dcf_base}_0.dmf' dmf_name = f'chunk_{dcf_base}_0.dmf'
write_dmf(os.path.join(terrain_dir, dmf_name), terrain_verts) write_dmf(os.path.join(terrain_dir, dmf_name), terrain_verts)
mesh_rel = f'meshes/chunks/{dmf_name}' mesh_rel = f'maps/{map_name}/meshes/chunks/{dmf_name}'
json_name = f'chunk_{dcf_base}_0.json' json_name = f'chunk_{dcf_base}_0.json'
write_model_json( write_model_json(
os.path.join(models_dir, json_name), os.path.join(models_dir, json_name),
@@ -393,7 +426,7 @@ def from_json(json_path, dcf_path):
'tiles.png', 'tiles.png',
[255, 255, 255, 255] [255, 255, 255, 255]
) )
model_names.append(f'models/chunks/{json_name}') model_names.append(f'maps/{map_name}/models/chunks/{json_name}')
mesh_offsets.append((0.0, 0.0, 0.0)) mesh_offsets.append((0.0, 0.0, 0.0))
# External mesh references -> look up matching model JSON # External mesh references -> look up matching model JSON
@@ -555,22 +588,27 @@ def main():
parser.add_argument( parser.add_argument(
'path', nargs='?', 'path', nargs='?',
help='Chunk JSON file to process, or legacy DCF file to upgrade. ' help='Chunk JSON file to process, or legacy DCF file to upgrade. '
'If omitted, processes all assetsraw/chunks/*.json' 'If omitted, processes all assetsraw/maps/*/chunks/*.json'
) )
args = parser.parse_args() args = parser.parse_args()
if args.path is None: if args.path is None:
chunks_dir = os.path.join(ASSETSRAW_DIR, 'chunks') maps_dir = os.path.join(ASSETSRAW_DIR, 'maps')
if not os.path.isdir(chunks_dir): if not os.path.isdir(maps_dir):
print(f"No directory found: {chunks_dir}") print(f"No directory found: {maps_dir}")
sys.exit(1) sys.exit(1)
json_files = sorted( json_files = []
os.path.join(chunks_dir, f) for map_name in sorted(os.listdir(maps_dir)):
for f in os.listdir(chunks_dir) chunks_dir = os.path.join(maps_dir, map_name, 'chunks')
if f.endswith('.json') if not os.path.isdir(chunks_dir):
) continue
json_files.extend(sorted(
os.path.join(chunks_dir, f)
for f in os.listdir(chunks_dir)
if f.endswith('.json')
))
if not json_files: if not json_files:
print(f"No JSON files found in {chunks_dir}") print(f"No JSON files found under {maps_dir}")
sys.exit(0) sys.exit(0)
for p in json_files: for p in json_files:
process_json(p) process_json(p)