XML data layer: pugixml (external/pugixml, v1.15), a format-neutral DataNode API for every loader, DataFormat=auto|json|xml (default xml), KAGE's archive file system ported (index once, four unpackers, the original's mount order) so --resources can point at an install's resources/ with no import step, the original XML .anm2 loader beside Anm2Ed JSON, mods' own XML; 72 goldens identical from converted resources and from the install
This commit is contained in:
1 parent
74322af121
commit
6d8a43775d
52 files changed
+1503
-899
No files matched your search
@@ -30,3 +30,7 @@
|
||||
path = external/imgui
|
||||
url = https://github.com/ocornut/imgui.git
|
||||
shallow = true
|
||||
[submodule "external/pugixml"]
|
||||
path = external/pugixml
|
||||
url = https://github.com/zeux/pugixml.git
|
||||
shallow = true
|
||||
+8
-2
@@ -30,11 +30,17 @@ add_library(lua STATIC ${LUA_SOURCES})
|
||||
target_include_directories(lua SYSTEM PUBLIC external/lua)
|
||||
target_compile_definitions(lua PRIVATE LUA_USE_POSIX)
|
||||
|
||||
# simdjson: its single-file build, static, without exceptions, for the JSON the import tool writes into resources/.
|
||||
# simdjson: its single-file build, static, without exceptions, for the JSON the import tool writes into resources/
|
||||
# and Anm2Ed's .anm2 documents.
|
||||
add_library(simdjson STATIC external/simdjson/singleheader/simdjson.cpp)
|
||||
target_include_directories(simdjson SYSTEM PUBLIC external/simdjson/singleheader)
|
||||
target_compile_definitions(simdjson PUBLIC SIMDJSON_EXCEPTIONS=0)
|
||||
|
||||
# pugixml for the game's own XML (the install's data and anm2 files, mods' XML): static, without XPath or exceptions.
|
||||
add_library(pugixml STATIC external/pugixml/src/pugixml.cpp)
|
||||
target_include_directories(pugixml SYSTEM PUBLIC external/pugixml/src)
|
||||
target_compile_definitions(pugixml PUBLIC PUGIXML_NO_XPATH PUGIXML_NO_EXCEPTIONS)
|
||||
|
||||
# Xiph's Ogg, Vorbis and Theora for the cutscene videos (.ogv): static, decoders only.
|
||||
set(INCLUDE_INTTYPES_H 1)
|
||||
set(INCLUDE_STDINT_H 1)
|
||||
@@ -98,7 +104,7 @@ endif()
|
||||
add_executable(isaac ${SOURCES} generated-src/stubs.cpp)
|
||||
target_include_directories(isaac PRIVATE src)
|
||||
target_include_directories(isaac SYSTEM PRIVATE generated-src external/stb)
|
||||
target_link_libraries(isaac PRIVATE SDL3::SDL3-static lua simdjson theora vorbis ogg)
|
||||
target_link_libraries(isaac PRIVATE SDL3::SDL3-static lua simdjson pugixml theora vorbis ogg)
|
||||
if(ISAAC_OVERLAY)
|
||||
target_compile_definitions(isaac PRIVATE ISAAC_OVERLAY)
|
||||
target_link_libraries(isaac PRIVATE imgui)
|
||||
|
||||
@@ -30,7 +30,7 @@ scripts/ decompile.sh (print decompiled C for a function, by name regex or
|
||||
fields), build.sh (rebuild everything from the exe after a game update), and the Ghidra Java scripts
|
||||
and Python helpers they use
|
||||
tools/ gitignored local tools: the resource importer and the test harness (tools/harness/)
|
||||
external/ static submodules: SDL3, Lua 5.3, simdjson, Ogg, Vorbis, Theora, stb, Dear ImGui (docking)
|
||||
external/ static submodules: SDL3, Lua 5.3, pugixml, simdjson, Ogg, Vorbis, Theora, stb, Dear ImGui (docking)
|
||||
assets/ files the repository ships itself: the overlay's fonts (git-lfs), with their licences, and REPENTOGON's Lua
|
||||
scripts (assets/repentogon/, GPL-2), adapted where they reach API not ported yet
|
||||
repentogon/ shallow clone of TeamREPENTOGON/REPENTOGON (libzhl/functions/*.zhl = sigs, structs, enums)
|
||||
@@ -42,9 +42,25 @@ jdk/ ghidra_12.2_PUBLIC/ Temurin 21 (system java is 8, too old) and Ghidra
|
||||
|
||||
The goal is a C++ source tree that builds a native 64-bit Linux game: `git submodule update --init --recursive`, then
|
||||
`cmake -B build && cmake --build build`. SDL3 (window, OpenGL context, input, audio) and Lua 5.3 (mods) are submodules
|
||||
in `external/`, built statically, with simdjson for data and Xiph's Ogg, Vorbis and Theora (decoders only) for the cutscene videos. Online features (Steam, EOS, curl) are offline stubs. The game
|
||||
reads JSON, not XML: an import tool in `tools/` converts the player's own install (XML, packed archives) and mods into
|
||||
`resources/` (both gitignored). Nothing from the game ships here.
|
||||
in `external/`, built statically, with pugixml and simdjson for data and Xiph's Ogg, Vorbis and Theora (decoders only)
|
||||
for the cutscene videos. Online features (Steam, EOS, curl) are offline stubs. Nothing from the game ships here.
|
||||
|
||||
The game reads the player's own install as it is: `--resources <install>/resources` mounts its packed archives
|
||||
(`src/engine/filesys.cpp`, a port of KAGE's file system: each archive indexed once at start-up, its files unpacked on
|
||||
demand) in the original's order (loose files, then animations, config, fonts, graphics, music, rooms, sfx, videos,
|
||||
afterbirth, afterbirthp, the repentance_<language> archives and secret.a, a later archive overriding an earlier one),
|
||||
with the language's mount (`resources.<code>`) searched first and mods in the install's `mods/`. Every resource
|
||||
(documents, anm2, images, sounds, music, videos, shaders, fonts, rooms, string tables, the game's Lua scripts) is read
|
||||
through that one file system, and nothing is ever written into the install. XML documents and `.anm2` files are read
|
||||
as the original's XML, and mods' own XML loads as it ships. The import tool in `tools/` (gitignored) still converts an
|
||||
install into `resources/` (XML to JSON, anm2 to Anm2Ed's JSON), which the game reads just the same: loaders see one
|
||||
node API (`src/engine/data.h`) over pugixml's tree or simdjson's, with identical elements, attribute strings and text.
|
||||
An `.anm2` is told apart by its first character.
|
||||
|
||||
When both a document's XML (`items.xml`) and its JSON (`items.xml.json`) are mounted, options.ini's `DataFormat`
|
||||
(the overlay's Game Options, System tab) picks one: `xml` (the default) reads the XML wherever it is mounted, `json`
|
||||
the JSON, and `auto` whichever the first mount holding either has, XML first there. A missing one falls back to the
|
||||
other. The string tables load before options.ini, so they always prefer the XML.
|
||||
`generated-src/` is the whole decompiled game as C++, regenerated every build and never edited. `src/` is the readable
|
||||
game, written by hand on top of it one function at a time:
|
||||
|
||||
@@ -67,7 +83,8 @@ Regenerate `generated-src/` after adding or moving a function in `src/`:
|
||||
|
||||
```
|
||||
engine/ platform (SDL3 window, frame pacing, clock), gl, kage_* (graphics, input, sound), anm2, textures,
|
||||
fonts, video, renderers, data loading, log, seeds and RNG, the test harness
|
||||
fonts, video, renderers, the file system (packed archives) and data loading, log, seeds and RNG, the
|
||||
test harness
|
||||
game/ main, Manager, game_* (game/state, game/save, game/update ...), options, strings, save data, mods,
|
||||
sound and music managers, dailies, local versus
|
||||
level/ level_* (level/generator, level/stage ...), room*, backdrop, minimap, path finder, rails,
|
||||
@@ -111,6 +128,7 @@ and field where two traces differ; `tools/harness/bot/` is a Lua mod that plays
|
||||
`tools/harness/goldens/check.sh` replays about 70 recorded runs (every character, the main and alternate floors,
|
||||
every final boss, Greed and Greedier, challenges, typed seeds, saving and continuing) on three saves (nothing unlocked
|
||||
in Hard, everything unlocked in Normal and in Hard) and names each trace that changed; `--record` re-records them.
|
||||
`RESOURCES=<install>/resources` replays them on the install itself instead of `resources/`.
|
||||
Traces follow the compiler's float code, so check with a clang build, as the goldens were recorded.
|
||||
|
||||
## Quick use
|
||||
|
||||
+1
Submodule external/pugixml added at ee86beb30e.
@@ -211,6 +211,10 @@ struct DamageEvent;
|
||||
struct DamageHit;
|
||||
struct DamageInfo;
|
||||
struct Data;
|
||||
struct DataAttr;
|
||||
struct DataAttrs;
|
||||
struct DataChildren;
|
||||
struct DataNode;
|
||||
struct DateTime;
|
||||
struct DeathmatchManager;
|
||||
struct DeathmatchTypeBase;
|
||||
@@ -8447,7 +8451,6 @@ void FUN_009a8a40(); // 009a8a40
|
||||
void _player_hud_set_heart_anim_state(int param_1); // 009a90b0
|
||||
void move_directory_files(); // 009a90e0
|
||||
uint8_t delete_directory_recursive(uint8_t *path); // 009a9250
|
||||
void resources_mount_language(); // 009ab970
|
||||
void FUN_009abd50(); // 009abd50
|
||||
void FUN_009ad470(); // 009ad470
|
||||
void FUN_009ad500(char *param_1, char *param_2); // 009ad500
|
||||
@@ -12312,7 +12315,6 @@ bool FUN_00a68630(); // 00a68630
|
||||
void FUN_00a68640(); // 00a68640
|
||||
uint32_t FUN_00a68730(uint8_t *param_1); // 00a68730
|
||||
uint32_t FUN_00a68790(uint8_t *param_1); // 00a68790
|
||||
void FUN_00a68a50(int *param_1); // 00a68a50
|
||||
void FUN_00a68b50(uint8_t param_1); // 00a68b50
|
||||
uint32_t FUN_00a68c40(); // 00a68c40
|
||||
void FUN_00a68c50(); // 00a68c50
|
||||
|
||||
@@ -312,92 +312,6 @@ LAB_00a16b36:
|
||||
} while( true );
|
||||
}
|
||||
|
||||
// 00a16c60
|
||||
uint32_t FileSystem::find_mount(uint8_t *param_1, uint8_t *param_2)
|
||||
{
|
||||
int iVar1;
|
||||
uint64_t qVar2;
|
||||
uint8_t bVar3;
|
||||
uint8_t *normalizedPath;
|
||||
uint8_t *archivePath;
|
||||
int *entry;
|
||||
int in_ECX;
|
||||
uint64_t *allocatedBytes;
|
||||
int mountIndex;
|
||||
uint8_t hashIter [8];
|
||||
int hashNode;
|
||||
int fileSystem;
|
||||
void *local_10;
|
||||
uint8_t *puStack_c;
|
||||
uint32_t local_8;
|
||||
uint32_t blockSize;
|
||||
|
||||
local_8 = 0xffffffff;
|
||||
puStack_c = &LAB_00b10fa0;
|
||||
local_10 = ExceptionList;
|
||||
ExceptionList = &local_10;
|
||||
fileSystem = in_ECX;
|
||||
normalizedPath = path_join(param_1,GHIDRA_CAST<uint8_t *>(0x0),0,0);
|
||||
mountIndex = (*GHIDRA_CAST<int *>((in_ECX + 0xc)) - *GHIDRA_CAST<int *>((in_ECX + 8)) >> 2) + -1;
|
||||
if (-1 < mountIndex) {
|
||||
while( true ) {
|
||||
if (DAT_00c37b14 != 0) {
|
||||
archivePath = path_join(normalizedPath,
|
||||
*GHIDRA_CAST<uint8_t **>((*GHIDRA_CAST<int *>((*GHIDRA_CAST<int *>((in_ECX + 8)) + mountIndex * 4)) + 0xc)),0,
|
||||
0);
|
||||
bVar3 = open_archive_file(&PTR_vftable_00c37a10,archivePath,(void **)0x0);
|
||||
param_1 = GHIDRA_CAST<uint8_t *>(CONCAT13(bVar3,(*GHIDRA_CAST<uint8_t *>((GHIDRA_CAST<char *>(&(param_1)) + 0x0)))));
|
||||
if (archivePath != GHIDRA_CAST<uint8_t *>(0x0)) {
|
||||
operator_delete(archivePath,1);
|
||||
bVar3 = (*GHIDRA_CAST<uint8_t *>((GHIDRA_CAST<char *>(&(param_1)) + 0x3)));
|
||||
}
|
||||
if (bVar3 != 0) {
|
||||
iVar1 = *GHIDRA_CAST<int *>((fileSystem + 8));
|
||||
*param_2 = 1;
|
||||
ExceptionList = local_10;
|
||||
return *GHIDRA_CAST<uint32_t *>((iVar1 + mountIndex * 4));
|
||||
}
|
||||
in_ECX = fileSystem;
|
||||
}
|
||||
iVar1 = *GHIDRA_CAST<int *>((*GHIDRA_CAST<int *>((in_ECX + 8)) + mountIndex * 4));
|
||||
param_1 = GHIDRA_CAST<uint8_t *>(KAGE_Filesys_FileManager)::GetPrimaryFilePathHash(normalizedPath);
|
||||
_Find_lower_bound<>(hashIter,¶m_1);
|
||||
if (((*GHIDRA_CAST<char *>((hashNode + 0xd)) == '\0') && (*GHIDRA_CAST<uint8_t **>((hashNode + 0x10)) <= param_1)) &&
|
||||
(hashNode != *GHIDRA_CAST<int *>((iVar1 + 4)))) {
|
||||
entry = map_find_value((void *)(iVar1 + 4),GHIDRA_UINT(¶m_1));
|
||||
if (*entry != 0) {
|
||||
if (normalizedPath != GHIDRA_CAST<uint8_t *>(0x0)) {
|
||||
local_8 = 0;
|
||||
tracked_alloc(1,normalizedPath,0);
|
||||
}
|
||||
*param_2 = 0;
|
||||
ExceptionList = local_10;
|
||||
return *GHIDRA_CAST<uint32_t *>((*GHIDRA_CAST<int *>((fileSystem + 8)) + mountIndex * 4));
|
||||
}
|
||||
}
|
||||
mountIndex = mountIndex + -1;
|
||||
if (mountIndex < 0) break;
|
||||
in_ECX = fileSystem;
|
||||
}
|
||||
}
|
||||
if (normalizedPath != GHIDRA_CAST<uint8_t *>(0x0)) {
|
||||
if (g_mainHeap == (void *)0x0) {
|
||||
allocatedBytes = &g_allocatedBytesNoHeap;
|
||||
}
|
||||
else {
|
||||
allocatedBytes = GHIDRA_CAST<uint64_t *>((GHIDRA_INT(g_mainHeap) + 0x30));
|
||||
}
|
||||
blockSize = *GHIDRA_CAST<uint32_t *>((normalizedPath + -4));
|
||||
qVar2 = *allocatedBytes;
|
||||
*GHIDRA_CAST<uint32_t *>(allocatedBytes) = GHIDRA_UINT(*allocatedBytes) - blockSize;
|
||||
*GHIDRA_CAST<uint32_t *>((GHIDRA_CAST<char *>(allocatedBytes) + 4)) =
|
||||
*GHIDRA_CAST<uint32_t *>((GHIDRA_CAST<char *>(allocatedBytes) + 4)) - GHIDRA_UINT((GHIDRA_UINT(qVar2) < blockSize));
|
||||
free(normalizedPath + -4);
|
||||
}
|
||||
ExceptionList = local_10;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 00a17180
|
||||
uint8_t * FileSystem::ResolvePath(uint8_t *path)
|
||||
{
|
||||
@@ -456,53 +370,6 @@ uint8_t * FileSystem::ResolvePath(uint8_t *path)
|
||||
return pbVar1;
|
||||
}
|
||||
|
||||
// 00a178d0
|
||||
void * FileSystem::Open(uint8_t *path, int *outResolvedPath)
|
||||
{
|
||||
uint8_t *resolvedPath;
|
||||
void *this_00;
|
||||
void *local_10;
|
||||
uint8_t *puStack_c;
|
||||
int *local_8;
|
||||
|
||||
resolvedPath = path;
|
||||
local_8 = GHIDRA_CAST<int *>(0xffffffff);
|
||||
puStack_c = &LAB_00af0b60;
|
||||
local_10 = ExceptionList;
|
||||
if ((path == GHIDRA_CAST<uint8_t *>(0x0)) || (*path == 0)) {
|
||||
return (void *)0x0;
|
||||
}
|
||||
path = GHIDRA_CAST<uint8_t *>(0x0);
|
||||
ExceptionList = &local_10;
|
||||
resolvedPath = ResolvePath(resolvedPath);
|
||||
open_archive_file(this,resolvedPath,&path);
|
||||
if (path == GHIDRA_CAST<uint8_t *>(0x0)) {
|
||||
open_disk_file(this_00,resolvedPath,&path);
|
||||
if (outResolvedPath == GHIDRA_CAST<int *>(0x0)) {
|
||||
if (resolvedPath == GHIDRA_CAST<uint8_t *>(0x0)) {
|
||||
ExceptionList = local_10;
|
||||
return path;
|
||||
}
|
||||
local_8 = GHIDRA_CAST<int *>(0x1);
|
||||
LAB_00a1795c:
|
||||
tracked_alloc(1,resolvedPath,0);
|
||||
ExceptionList = local_10;
|
||||
return path;
|
||||
}
|
||||
}
|
||||
else if (outResolvedPath == GHIDRA_CAST<int *>(0x0)) {
|
||||
if (resolvedPath == GHIDRA_CAST<uint8_t *>(0x0)) {
|
||||
ExceptionList = local_10;
|
||||
return path;
|
||||
}
|
||||
local_8 = outResolvedPath;
|
||||
goto LAB_00a1795c;
|
||||
}
|
||||
*outResolvedPath = GHIDRA_INT(resolvedPath);
|
||||
ExceptionList = local_10;
|
||||
return path;
|
||||
}
|
||||
|
||||
// 00a17ea0
|
||||
uint8_t FileSystem::open_disk_file(uint8_t *path, void **outFile)
|
||||
{
|
||||
|
||||
@@ -58,207 +58,3 @@ uint32_t KAGE_Filesys_FileManager::GetSecondaryFilePathHash()
|
||||
}
|
||||
return uVar4;
|
||||
}
|
||||
|
||||
// 00a179c0
|
||||
void KAGE_Filesys_FileManager::LoadArchiveFile(uint8_t *param_1, uint32_t *param_2, uint16_t param_3)
|
||||
{
|
||||
uint8_t isExpectedChecksum;
|
||||
uint32_t uVar1;
|
||||
uint8_t *resolvedPath;
|
||||
uint8_t *loadedPathChar;
|
||||
uint32_t isExpectedChecksum;
|
||||
uint32_t *fileEntry;
|
||||
uint8_t *extraout_ECX;
|
||||
uint8_t *resolvedPathChar;
|
||||
int iVar3;
|
||||
int *piVar4;
|
||||
uint32_t uVar5;
|
||||
int dwordCount;
|
||||
bool isLess;
|
||||
char *format;
|
||||
uint32_t archiveIndex;
|
||||
uint32_t fileCount;
|
||||
uint8_t *archivePath;
|
||||
int local_e58;
|
||||
int *stream;
|
||||
uint8_t archiveType;
|
||||
uint32_t local_e4c;
|
||||
int archivedFile [3];
|
||||
int archivedFileRecord;
|
||||
int chunkBuffer [128];
|
||||
uint8_t headerMagic [7];
|
||||
uint8_t local_15;
|
||||
uint32_t local_14;
|
||||
void *local_10;
|
||||
uint8_t *puStack_c;
|
||||
uint32_t local_8;
|
||||
uint8_t ch;
|
||||
|
||||
local_8 = 0xffffffff;
|
||||
puStack_c = &LAB_00b11020;
|
||||
local_10 = ExceptionList;
|
||||
uVar1 = __security_cookie ^ GHIDRA_UINT((headerMagic + 0x18));
|
||||
ExceptionList = &local_10;
|
||||
archivePath = param_1;
|
||||
local_14 = uVar1;
|
||||
resolvedPath = FileSystem::ResolvePath(param_1);
|
||||
if (resolvedPath == GHIDRA_CAST<uint8_t *>(0x0)) {
|
||||
KAGE_LogMessage(8,GHIDRA_CAST<uint8_t *>("Failed to open archive file \'%s\'\n"));
|
||||
}
|
||||
else {
|
||||
uVar5 = 0;
|
||||
archiveIndex = 0;
|
||||
resolvedPathChar = extraout_ECX;
|
||||
if (DAT_00c37b14 != 0) {
|
||||
do {
|
||||
loadedPathChar = GHIDRA_CAST<uint8_t *>((&DAT_00c37a14)[uVar5 * 2]);
|
||||
resolvedPathChar = resolvedPath;
|
||||
do {
|
||||
ch = *loadedPathChar;
|
||||
isLess = ch < *resolvedPathChar;
|
||||
if (ch != *resolvedPathChar) {
|
||||
LAB_00a17a60:
|
||||
isExpectedChecksum = -GHIDRA_UINT(isLess) | 1;
|
||||
goto LAB_00a17a65;
|
||||
}
|
||||
if (ch == 0) break;
|
||||
ch = loadedPathChar[1];
|
||||
isLess = ch < resolvedPathChar[1];
|
||||
if (ch != resolvedPathChar[1]) goto LAB_00a17a60;
|
||||
loadedPathChar = loadedPathChar + 2;
|
||||
resolvedPathChar = resolvedPathChar + 2;
|
||||
} while (ch != 0);
|
||||
isExpectedChecksum = 0;
|
||||
LAB_00a17a65:
|
||||
} while ((isExpectedChecksum != 0) && (uVar5 = uVar5 + 1, uVar5 < DAT_00c37b14));
|
||||
archiveIndex = uVar5;
|
||||
if (0x1f < uVar5) {
|
||||
KAGE_LogMessage(8,(uint8_t *)
|
||||
"Cannot load archive file \'%s\', maximum number of archive files exceeded\n"
|
||||
);
|
||||
local_8 = 0;
|
||||
tracked_alloc(1,resolvedPath,0);
|
||||
ExceptionList = local_10;
|
||||
return;
|
||||
}
|
||||
}
|
||||
(&DAT_00c37a14)[archiveIndex * 2] = resolvedPath;
|
||||
stream = GHIDRA_CAST<int *>(0x0);
|
||||
(GHIDRA_CAST<FileSystem *>((resolvedPathChar)))->FileSystem::open_disk_file(resolvedPath,&stream);
|
||||
if ((stream == GHIDRA_CAST<int *>(0x0)) &&
|
||||
(FileSystem::open_archive_file
|
||||
(&PTR_vftable_00c37a10,GHIDRA_CAST<uint8_t *>((&DAT_00c37a14)[archiveIndex * 2]),&stream),
|
||||
stream == GHIDRA_CAST<int *>(0x0))) {
|
||||
KAGE_LogMessage(8,GHIDRA_CAST<uint8_t *>("Failed to open archive file \'%s\'\n"));
|
||||
if ((void *)(&DAT_00c37a14)[archiveIndex * 2] == (void *)0x0) {
|
||||
ExceptionList = local_10;
|
||||
return;
|
||||
}
|
||||
local_8 = 1;
|
||||
tracked_alloc(1,(void *)(&DAT_00c37a14)[archiveIndex * 2],0);
|
||||
(&DAT_00c37a14)[archiveIndex * 2] = 0;
|
||||
ExceptionList = local_10;
|
||||
return;
|
||||
}
|
||||
piVar4 = stream;
|
||||
(**(code **)(*stream + 0x14))(headerMagic,1,7,uVar1);
|
||||
local_15 = 0;
|
||||
archiveType = 0;
|
||||
(**(code **)(*piVar4 + 0x14))(&archiveType,1,1);
|
||||
(&DAT_00c37a18)[archiveIndex * 8] = archiveType;
|
||||
local_e58 = 0;
|
||||
(**(code **)(*piVar4 + 0x14))(&local_e58,4,1);
|
||||
fileCount = 0;
|
||||
(**(code **)(*piVar4 + 0x14))(&fileCount,2,1);
|
||||
(**(code **)(*piVar4 + 0xc))(local_e58,0);
|
||||
local_e58 = 0;
|
||||
if ((uint16_t)fileCount != 0) {
|
||||
do {
|
||||
fileEntry = operator_new(0x1c);
|
||||
piVar4 = stream;
|
||||
local_e4c = 0;
|
||||
*fileEntry = archiveIndex;
|
||||
(**(code **)(*stream + 0x14))(&local_e4c,4,1);
|
||||
fileEntry[1] = local_e4c;
|
||||
local_e4c = 0;
|
||||
(**(code **)(*piVar4 + 0x14))(&local_e4c,4,1);
|
||||
fileEntry[2] = local_e4c;
|
||||
local_e4c = 0;
|
||||
(**(code **)(*piVar4 + 0x14))(&local_e4c,4,1);
|
||||
fileEntry[3] = local_e4c;
|
||||
local_e4c = 0;
|
||||
(**(code **)(*piVar4 + 0x14))(&local_e4c,4,1);
|
||||
fileEntry[4] = local_e4c;
|
||||
local_e4c = 0;
|
||||
(**(code **)(*piVar4 + 0x14))(&local_e4c,4,1);
|
||||
fileEntry[5] = local_e4c;
|
||||
if (((uint16_t)local_e58 < param_3) && (*param_2 == local_e4c)) {
|
||||
isExpectedChecksum = 1;
|
||||
}
|
||||
else {
|
||||
isExpectedChecksum = 0;
|
||||
}
|
||||
*GHIDRA_CAST<uint8_t *>((fileEntry + 6)) = isExpectedChecksum;
|
||||
FUN_00a68a50(fileEntry);
|
||||
local_8 = 2;
|
||||
uVar1 = 0xababeb98;
|
||||
memset(chunkBuffer,0,0x200);
|
||||
local_e4c = *GHIDRA_CAST<uint32_t *>((archivedFileRecord + 0x10));
|
||||
do {
|
||||
uVar5 = local_e4c;
|
||||
if (0x200 < GHIDRA_INT(local_e4c)) {
|
||||
uVar5 = 0x200;
|
||||
}
|
||||
isExpectedChecksum = (**(code **)(archivedFile[0] + 0x14))(chunkBuffer,1,uVar5);
|
||||
iVar3 = 0;
|
||||
dwordCount = GHIDRA_INT(((GHIDRA_INT((isExpectedChecksum + 3)) >> 0x1f & 3U) + isExpectedChecksum + 3)) >> 2;
|
||||
if (0 < dwordCount) {
|
||||
do {
|
||||
piVar4 = chunkBuffer + iVar3;
|
||||
iVar3 = iVar3 + 1;
|
||||
uVar1 = uVar1 * -0x80000000 + *piVar4 + (uVar1 >> 1);
|
||||
} while (iVar3 < dwordCount);
|
||||
}
|
||||
local_e4c = local_e4c - uVar5;
|
||||
} while ((0 < GHIDRA_INT(local_e4c)) && (isExpectedChecksum == uVar5));
|
||||
if (uVar1 == *GHIDRA_CAST<uint32_t *>((archivedFileRecord + 0x14))) {
|
||||
uVar5 = fileEntry[1] & 0x7fff;
|
||||
iVar3 = *GHIDRA_CAST<int *>((&DAT_00c37b18 + uVar5 * 4));
|
||||
uVar1 = 0;
|
||||
if (iVar3 != 0) {
|
||||
do {
|
||||
if (((*GHIDRA_CAST<uint32_t *>((iVar3 + 4)) == fileEntry[1]) &&
|
||||
(isExpectedChecksum = uVar1, *GHIDRA_CAST<uint32_t *>((iVar3 + 8)) == fileEntry[2])) ||
|
||||
(isExpectedChecksum = uVar1 + 1, 0x7fff < uVar1)) break;
|
||||
uVar5 = uVar5 + 1 & 0x7fff;
|
||||
iVar3 = *GHIDRA_CAST<int *>((&DAT_00c37b18 + uVar5 * 4));
|
||||
uVar1 = isExpectedChecksum;
|
||||
} while (iVar3 != 0);
|
||||
if (0x7fff < isExpectedChecksum) {
|
||||
format = "Failed to load file %x%x from \'%s\', hash table is full\n";
|
||||
goto LAB_00a17dad;
|
||||
}
|
||||
}
|
||||
*GHIDRA_CAST<uint32_t **>((&DAT_00c37b18 + uVar5 * 4)) = fileEntry;
|
||||
}
|
||||
else {
|
||||
format = "Failed to load file %x%x from \'%s\', checksum is invalid\n";
|
||||
LAB_00a17dad:
|
||||
KAGE_LogMessage(8,GHIDRA_CAST<uint8_t *>(format));
|
||||
operator_delete(fileEntry,0x1c);
|
||||
}
|
||||
local_8 = 0xffffffff;
|
||||
(GHIDRA_CAST<KAGE::Filesys::ArchivedFile *>((archivedFile)))->KAGE::Filesys::ArchivedFile::~ArchivedFile();
|
||||
param_2 = param_2 + 1;
|
||||
local_e58 = local_e58 + 1;
|
||||
} while ((uint16_t)local_e58 < (uint16_t)fileCount);
|
||||
piVar4 = stream;
|
||||
}
|
||||
(**(code **)*piVar4)(1);
|
||||
if (DAT_00c37b14 < archiveIndex + 1) {
|
||||
DAT_00c37b14 = archiveIndex + 1;
|
||||
}
|
||||
}
|
||||
ExceptionList = local_10;
|
||||
return;
|
||||
}
|
||||
@@ -8284,9 +8284,7 @@ EntityList_Query::~EntityList_Query() { generated_stub("EntityList_Query::~Entit
|
||||
void EntitySaveStateRef::Set(void *state) { generated_stub("EntitySaveStateRef::Set 006eee10"); }
|
||||
void * FileSystem::GetMountPrefixes(void *outPrefixes) { generated_stub("FileSystem::GetMountPrefixes 00a16060"); }
|
||||
void FileSystem::load_mount_points() { generated_stub("FileSystem::load_mount_points 00a167d0"); }
|
||||
uint32_t FileSystem::find_mount(uint8_t *param_1, uint8_t *param_2) { generated_stub("FileSystem::find_mount 00a16c60"); }
|
||||
uint8_t * FileSystem::ResolvePath(uint8_t *path) { generated_stub("FileSystem::ResolvePath 00a17180"); }
|
||||
void * FileSystem::Open(uint8_t *path, int *outResolvedPath) { generated_stub("FileSystem::Open 00a178d0"); }
|
||||
uint8_t FileSystem::open_disk_file(uint8_t *path, void **outFile) { generated_stub("FileSystem::open_disk_file 00a17ea0"); }
|
||||
uint8_t FileSystem::open_archive_file(uint8_t *path, void **outFile) { generated_stub("FileSystem::open_archive_file 00a17f40"); }
|
||||
void FrameQueue::setSize(int count) { generated_stub("FrameQueue::setSize 00aaa500"); }
|
||||
@@ -9024,7 +9022,6 @@ void KAGE::Thread::vfunc_3() { generated_stub("KAGE::Thread::vfunc_3 00a5a700");
|
||||
uint32_t KAGE::Util::String::CharacterIteratorUTF8::FUN_00a55aa0() { generated_stub("KAGE::Util::String::CharacterIteratorUTF8::FUN_00a55aa0 00a55aa0"); }
|
||||
uint32_t KAGE_Filesys_FileManager::GetPrimaryFilePathHash(uint8_t *filePath) { generated_stub("KAGE_Filesys_FileManager::GetPrimaryFilePathHash 00a159d0"); }
|
||||
uint32_t KAGE_Filesys_FileManager::GetSecondaryFilePathHash() { generated_stub("KAGE_Filesys_FileManager::GetSecondaryFilePathHash 00a15ab0"); }
|
||||
void KAGE_Filesys_FileManager::LoadArchiveFile(uint8_t *param_1, uint32_t *param_2, uint16_t param_3) { generated_stub("KAGE_Filesys_FileManager::LoadArchiveFile 00a179c0"); }
|
||||
void KColor::FromRGBA255(int red, int green, int blue, int alpha) { generated_stub("KColor::FromRGBA255 00682f50"); }
|
||||
void KColor::SetFromARGB(uint32_t argb) { generated_stub("KColor::SetFromARGB 00a0f550"); }
|
||||
KColor * KColor::set_from_argb_signed(uint32_t argb) { generated_stub("KColor::set_from_argb_signed 00a0f610"); }
|
||||
@@ -12523,7 +12520,6 @@ void FUN_009a8a40() { generated_stub("FUN_009a8a40 009a8a40"); }
|
||||
void _player_hud_set_heart_anim_state(int param_1) { generated_stub("_player_hud_set_heart_anim_state 009a90b0"); }
|
||||
void move_directory_files() { generated_stub("move_directory_files 009a90e0"); }
|
||||
uint8_t delete_directory_recursive(uint8_t *path) { generated_stub("delete_directory_recursive 009a9250"); }
|
||||
void resources_mount_language() { generated_stub("resources_mount_language 009ab970"); }
|
||||
void FUN_009abd50() { generated_stub("FUN_009abd50 009abd50"); }
|
||||
void FUN_009ad470() { generated_stub("FUN_009ad470 009ad470"); }
|
||||
void FUN_009ad500(char *param_1, char *param_2) { generated_stub("FUN_009ad500 009ad500"); }
|
||||
@@ -16393,7 +16389,6 @@ bool FUN_00a68630() { generated_stub("FUN_00a68630 00a68630"); }
|
||||
void FUN_00a68640() { generated_stub("FUN_00a68640 00a68640"); }
|
||||
uint32_t FUN_00a68730(uint8_t *param_1) { generated_stub("FUN_00a68730 00a68730"); }
|
||||
uint32_t FUN_00a68790(uint8_t *param_1) { generated_stub("FUN_00a68790 00a68790"); }
|
||||
void FUN_00a68a50(int *param_1) { generated_stub("FUN_00a68a50 00a68a50"); }
|
||||
void FUN_00a68b50(uint8_t param_1) { generated_stub("FUN_00a68b50 00a68b50"); }
|
||||
uint32_t FUN_00a68c40() { generated_stub("FUN_00a68c40 00a68c40"); }
|
||||
void FUN_00a68c50() { generated_stub("FUN_00a68c50 00a68c50"); }
|
||||
|
||||
+236
-31
@@ -8,6 +8,7 @@
|
||||
#include "engine/render_passes.h"
|
||||
#include "level/room.h"
|
||||
#include "engine/texture_cache.h"
|
||||
#include "simdjson.h"
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
@@ -45,6 +46,8 @@ constexpr std::string_view IDLE_ANIMATION = "Idle";
|
||||
constexpr std::string_view CHAMPION_COLOR_UNIFORM = "ChampionColor";
|
||||
constexpr std::string_view COLOR_OFFSET_SHADER = "ColorOffset";
|
||||
constexpr std::string_view COLOR_OFFSET_CHAMPION_SHADER = "ColorOffsetChampion";
|
||||
// What may come before an .anm2's first character: whitespace and a UTF-8 byte order mark.
|
||||
constexpr std::string_view LEADING_SPACE = " \t\r\n\xef\xbb\xbf";
|
||||
|
||||
// Delirium's forms swap a boss's or monster's spritesheets for the ones under DELIRIUM_FORMS_FOLDER.
|
||||
constexpr int DELIRIUM_TYPE = 412;
|
||||
@@ -426,6 +429,16 @@ static void triggers_read(object source, const Anm2Parse& parse, AnimationData&
|
||||
}
|
||||
}
|
||||
|
||||
// Fills an animation's layerMap from its layer tracks.
|
||||
static void layer_map_build(AnimationData& animation)
|
||||
{
|
||||
for (size_t i = 0; i < animation.animLayers.size(); i++)
|
||||
{
|
||||
int layerId = animation.animLayers[i].layerId;
|
||||
if (layerId >= 0 && layerId < ANM2_LAYER_LIMIT) animation.layerMap[layerId] = (int)i;
|
||||
}
|
||||
}
|
||||
|
||||
// Every animation of a list in file order, a group's among them in its place.
|
||||
static void animations_read(object list, const Anm2Parse& parse, AnmFileData& file)
|
||||
{
|
||||
@@ -450,11 +463,7 @@ static void animations_read(object list, const Anm2Parse& parse, AnmFileData& fi
|
||||
layer_tracks_read(fields, parse, animation, root);
|
||||
null_tracks_read(fields, parse, animation, root);
|
||||
triggers_read(fields, parse, animation);
|
||||
for (size_t i = 0; i < animation.animLayers.size(); i++)
|
||||
{
|
||||
int layerId = animation.animLayers[i].layerId;
|
||||
if (layerId >= 0 && layerId < ANM2_LAYER_LIMIT) animation.layerMap[layerId] = (int)i;
|
||||
}
|
||||
layer_map_build(animation);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,33 +485,30 @@ static std::vector<std::string> names_read(object document, std::string_view key
|
||||
return names;
|
||||
}
|
||||
|
||||
// 0040ed50 Parses an .anm2, Anm2Ed's JSON document (its docs/json_format.md), into what the game plays.
|
||||
// Ids are indices into their lists. Spritesheet paths become relative to resources/, from the .anm2's folder.
|
||||
static std::shared_ptr<const AnmFileData> file_parse(const std::string& path)
|
||||
// A spritesheet's path from the .anm2's folder, relative to resources/.
|
||||
static std::string sheet_path_resolve(const std::string& path, std::string_view sheet)
|
||||
{
|
||||
std::string relative(sheet);
|
||||
std::replace(relative.begin(), relative.end(), '\\', '/');
|
||||
return (std::filesystem::path(path).parent_path() / relative).lexically_normal().generic_string();
|
||||
}
|
||||
|
||||
// Anm2Ed's JSON document (its docs/json_format.md). Ids are indices into their lists.
|
||||
static bool json_file_read(Anm2Parse& parse, std::string& bytes, AnmFileData& file)
|
||||
{
|
||||
static simdjson::dom::parser parser;
|
||||
auto file = std::make_shared<AnmFileData>();
|
||||
Anm2Parse parse = {path, {}, {}};
|
||||
std::vector<std::string> sheetPaths;
|
||||
const std::string& path = parse.path;
|
||||
object document;
|
||||
array list;
|
||||
|
||||
std::string redirected = g_manager ? g_manager->modManager.TryRedirectPath(path) : path;
|
||||
if (parser.load(resource_path(redirected)).get(document))
|
||||
{
|
||||
log_print(LOG_INFO, "ERROR Could not open %s\n", path.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (parser.parse(bytes).get(document)) return false;
|
||||
if (!document["sheets"].get(list))
|
||||
for (element entry : list)
|
||||
{
|
||||
object fields;
|
||||
if (entry.get(fields)) continue;
|
||||
std::string relative(text_get(fields, "path"));
|
||||
std::replace(relative.begin(), relative.end(), '\\', '/');
|
||||
auto resolved = std::filesystem::path(path).parent_path() / relative;
|
||||
sheetPaths.push_back(resolved.lexically_normal().generic_string());
|
||||
sheetPaths.push_back(sheet_path_resolve(path, text_get(fields, "path")));
|
||||
parse.regions.push_back(frames_read<AnimationFrame>(fields, "regions", nullptr));
|
||||
}
|
||||
|
||||
@@ -510,9 +516,9 @@ static std::shared_ptr<const AnmFileData> file_parse(const std::string& path)
|
||||
for (element entry : list)
|
||||
{
|
||||
object fields;
|
||||
LayerData& layer = file->layers.emplace_back();
|
||||
LayerData& layer = file.layers.emplace_back();
|
||||
bool isRead = !entry.get(fields);
|
||||
layer.id = (int)file->layers.size() - 1;
|
||||
layer.id = (int)file.layers.size() - 1;
|
||||
layer.name = isRead ? text_get(fields, "name") : "";
|
||||
layer.spriteSheetId = isRead ? (int)number_get(fields, "sheet", 0) : 0;
|
||||
if (layer.id >= ANM2_LAYER_LIMIT)
|
||||
@@ -522,18 +528,217 @@ static std::shared_ptr<const AnmFileData> file_parse(const std::string& path)
|
||||
else log_print(LOG_ASSERT, "%s: invalid spritesheet id %d\n", path.c_str(), layer.spriteSheetId);
|
||||
parse.layerSheets.push_back(layer.spriteSheetId);
|
||||
}
|
||||
if (file->layers.empty()) log_print(LOG_ASSERT, "%s: no layers\n", path.c_str());
|
||||
if (file.layers.empty()) log_print(LOG_ASSERT, "%s: no layers\n", path.c_str());
|
||||
|
||||
file->nullLayerNames = names_read(document, "nulls");
|
||||
if (file->nullLayerNames.size() > ANM2_LAYER_LIMIT)
|
||||
file.nullLayerNames = names_read(document, "nulls");
|
||||
if (file.nullLayerNames.size() > ANM2_LAYER_LIMIT)
|
||||
log_print(LOG_ASSERT, "%s: invalid Null ID %d\n", path.c_str(), ANM2_LAYER_LIMIT);
|
||||
file->eventNames = names_read(document, "events");
|
||||
if (file->eventNames.size() > ANM2_EVENT_LIMIT)
|
||||
file.eventNames = names_read(document, "events");
|
||||
if (file.eventNames.size() > ANM2_EVENT_LIMIT)
|
||||
log_print(LOG_ASSERT, "%s: invalid Event ID %d\n", path.c_str(), ANM2_EVENT_LIMIT);
|
||||
|
||||
file->defaultAnimation = text_get(document, "default");
|
||||
file.defaultAnimation = text_get(document, "default");
|
||||
object animations;
|
||||
if (!document["animations"].get(animations)) animations_read(animations, parse, *file);
|
||||
if (!document["animations"].get(animations)) animations_read(animations, parse, file);
|
||||
return true;
|
||||
}
|
||||
|
||||
// A number attribute as atoi reads it, or fallback when the element lacks it.
|
||||
static int xml_int(DataNode node, std::string_view name, int fallback)
|
||||
{
|
||||
std::optional<std::string_view> text = node_attr_find(node, name);
|
||||
return text ? std::atoi(text->data()) : fallback;
|
||||
}
|
||||
|
||||
static float xml_float(DataNode node, std::string_view name, float fallback)
|
||||
{
|
||||
std::optional<std::string_view> text = node_attr_find(node, name);
|
||||
return text ? (float)std::atof(text->data()) : fallback;
|
||||
}
|
||||
|
||||
// A bool attribute as the original reads it: "true", "True" or a nonzero number, false when empty.
|
||||
static bool is_xml_true(DataNode node, std::string_view name, bool fallback)
|
||||
{
|
||||
std::optional<std::string_view> text = node_attr_find(node, name);
|
||||
if (!text) return fallback;
|
||||
return *text == "true" || *text == "True" || std::atoi(text->data()) != 0;
|
||||
}
|
||||
|
||||
// The first child with a tag, as rapidxml's first_node finds it.
|
||||
static std::optional<DataNode> xml_child_find(DataNode node, std::string_view tag)
|
||||
{
|
||||
for (DataNode child : node_children(node))
|
||||
if (node_tag(child) == tag) return child;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// The keyframes of a track of the original's XML, each read as frame_read reads Anm2Ed's: tints and offsets out of
|
||||
// 255, scales out of 100. A missing attribute keeps Anm2Ed's default.
|
||||
template <class Frame> static std::vector<Frame> xml_frames_read(DataNode track)
|
||||
{
|
||||
constexpr std::string_view TINTS[] = {"RedTint", "GreenTint", "BlueTint", "AlphaTint"};
|
||||
constexpr std::string_view OFFSETS[] = {"RedOffset", "GreenOffset", "BlueOffset"};
|
||||
std::vector<Frame> frames;
|
||||
|
||||
for (DataNode node : node_children(track))
|
||||
{
|
||||
AnimationFrame frame;
|
||||
frame.crop = vector_make(xml_float(node, "XCrop", 0), xml_float(node, "YCrop", 0));
|
||||
frame.pivot = vector_make(xml_float(node, "XPivot", 0), xml_float(node, "YPivot", 0));
|
||||
frame.width = xml_float(node, "Width", 0);
|
||||
frame.height = xml_float(node, "Height", 0);
|
||||
for (int i = 0; i < 4; i++) frame.color._tint[i] = xml_float(node, TINTS[i], CHANNEL) / CHANNEL;
|
||||
for (int i = 0; i < 3; i++) frame.color._offset[i] = xml_float(node, OFFSETS[i], 0) / CHANNEL;
|
||||
frame.pos = vector_make(xml_float(node, "XPosition", 0), xml_float(node, "YPosition", 0));
|
||||
float scaleX = xml_float(node, "XScale", PERCENT);
|
||||
float scaleY = xml_float(node, "YScale", PERCENT);
|
||||
frame.scale = vector_make(scaleX / PERCENT, scaleY / PERCENT);
|
||||
frame.rotation = xml_float(node, "Rotation", 0);
|
||||
frame.duration = xml_int(node, "Delay", 1);
|
||||
frame.isVisible = is_xml_true(node, "Visible", true);
|
||||
frame.isInterpolated = is_xml_true(node, "Interpolated", false);
|
||||
frames.push_back(frame);
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
// The names a list gives by id, as many as it has children, each child's Name at its Id. An id outside the list's
|
||||
// limit logs error and names nothing.
|
||||
static std::vector<std::string> xml_names_read(std::optional<DataNode> list, size_t limit, const char* error,
|
||||
const std::string& path)
|
||||
{
|
||||
std::vector<std::string> names(limit);
|
||||
size_t count = 0;
|
||||
|
||||
for (DataNode node : list ? node_children(*list) : DataChildren())
|
||||
{
|
||||
int id = xml_int(node, "Id", (int)limit);
|
||||
count++;
|
||||
if (id >= 0 && id < (int)limit) names[id] = node_attr(node, "Name");
|
||||
else log_print(LOG_ASSERT, error, path.c_str(), id);
|
||||
}
|
||||
names.resize(count);
|
||||
return names;
|
||||
}
|
||||
|
||||
// The animations of the original's XML: every element from the first <Animation> on, its root track applied to its
|
||||
// layer and null tracks, and one trigger per event.
|
||||
static void xml_animations_read(DataNode list, const Anm2Parse& parse, AnmFileData& file)
|
||||
{
|
||||
bool isFound = false;
|
||||
|
||||
for (DataNode node : node_children(list))
|
||||
{
|
||||
isFound = isFound || node_tag(node) == "Animation";
|
||||
if (!isFound) continue;
|
||||
|
||||
AnimationData& animation = file.animations.emplace_back();
|
||||
std::optional<DataNode> rootTrack = xml_child_find(node, "RootAnimation");
|
||||
std::optional<DataNode> layers = xml_child_find(node, "LayerAnimations");
|
||||
std::optional<DataNode> nulls = xml_child_find(node, "NullAnimations");
|
||||
std::optional<DataNode> triggers = xml_child_find(node, "Triggers");
|
||||
animation.name = node_attr(node, "Name");
|
||||
animation.index = (int)file.animations.size() - 1;
|
||||
animation.length = xml_int(node, "FrameNum", 0);
|
||||
animation.isLooping = is_xml_true(node, "Loop", false);
|
||||
|
||||
std::vector<NullFrame> root;
|
||||
if (rootTrack) root = track_interpolate(xml_frames_read<NullFrame>(*rootTrack));
|
||||
for (DataNode track : layers ? node_children(*layers) : DataChildren())
|
||||
{
|
||||
if (animation.animLayers.size() >= ANM2_LAYER_LIMIT)
|
||||
log_print(LOG_ASSERT, "%s: too many animation layers\n", parse.path.c_str());
|
||||
auto frames = track_interpolate(xml_frames_read<AnimationFrame>(track));
|
||||
animation.animLayers.push_back({track_root_apply(frames, root, parse.path), xml_int(track, "LayerId", -1),
|
||||
is_xml_true(track, "Visible", true)});
|
||||
}
|
||||
for (DataNode track : nulls ? node_children(*nulls) : DataChildren())
|
||||
{
|
||||
if (animation.nullLayers.size() >= ANM2_LAYER_LIMIT)
|
||||
log_print(LOG_ASSERT, "%s: too many null layers\n", parse.path.c_str());
|
||||
auto frames = track_interpolate(xml_frames_read<NullFrame>(track));
|
||||
animation.nullLayers.push_back({track_root_apply(frames, root, parse.path), xml_int(track, "NullId", -1),
|
||||
is_xml_true(track, "Visible", true)});
|
||||
}
|
||||
for (DataNode trigger : triggers ? node_children(*triggers) : DataChildren())
|
||||
{
|
||||
if (animation.eventTriggers.size() >= ANM2_TRIGGER_LIMIT)
|
||||
log_print(LOG_ASSERT, "%s: too many triggers\n", parse.path.c_str());
|
||||
auto eventId = (uint32_t)xml_int(trigger, "EventId", 0);
|
||||
animation.eventTriggers.push_back({xml_int(trigger, "AtFrame", 0), eventId});
|
||||
}
|
||||
layer_map_build(animation);
|
||||
}
|
||||
}
|
||||
|
||||
// The original's XML (<AnimatedActor>, read through rapidxml): spritesheets, layers, nulls and events by their Id, the
|
||||
// layers in file order logging an Id out of place, then the animations.
|
||||
static bool xml_file_read(Anm2Parse& parse, std::string& bytes, AnmFileData& file)
|
||||
{
|
||||
Data data;
|
||||
data_parse(data, bytes);
|
||||
std::optional<DataNode> actor = xml_child_find(data.root, "AnimatedActor");
|
||||
if (data.isLoaded && node_tag(data.root) == "AnimatedActor") actor = data.root;
|
||||
if (!data.isLoaded || !actor) return false;
|
||||
|
||||
const std::string& path = parse.path;
|
||||
std::optional<DataNode> content = xml_child_find(*actor, "Content");
|
||||
std::optional<DataNode> sheets = content ? xml_child_find(*content, "Spritesheets") : std::nullopt;
|
||||
std::optional<DataNode> layers = content ? xml_child_find(*content, "Layers") : std::nullopt;
|
||||
std::vector<std::string> sheetPaths(ANM2_LAYER_LIMIT);
|
||||
int sheetCount = 0;
|
||||
|
||||
for (DataNode node : sheets ? node_children(*sheets) : DataChildren())
|
||||
{
|
||||
int id = xml_int(node, "Id", ANM2_LAYER_LIMIT);
|
||||
if (id != sheetCount++ || id >= ANM2_LAYER_LIMIT)
|
||||
log_print(LOG_ASSERT, "%s: invalid spritesheet id %d\n", path.c_str(), id);
|
||||
if (id >= 0 && id < ANM2_LAYER_LIMIT) sheetPaths[id] = sheet_path_resolve(path, node_attr(node, "Path"));
|
||||
}
|
||||
for (DataNode node : layers ? node_children(*layers) : DataChildren())
|
||||
{
|
||||
LayerData& layer = file.layers.emplace_back();
|
||||
int id = xml_int(node, "Id", ANM2_LAYER_LIMIT);
|
||||
layer.id = (int)file.layers.size() - 1;
|
||||
layer.name = node_attr(node, "Name");
|
||||
layer.spriteSheetId = xml_int(node, "SpritesheetId", -1);
|
||||
if (id != layer.id || id >= ANM2_LAYER_LIMIT)
|
||||
log_print(LOG_ASSERT, "%s: invalid layer id %d\n", path.c_str(), id);
|
||||
if (layer.spriteSheetId >= 0 && layer.spriteSheetId < sheetCount)
|
||||
layer.spriteSheetPath = sheetPaths[layer.spriteSheetId];
|
||||
else log_print(LOG_ASSERT, "%s: invalid spritesheet id %d\n", path.c_str(), layer.spriteSheetId);
|
||||
}
|
||||
if (file.layers.empty()) log_print(LOG_ASSERT, "%s: no layers\n", path.c_str());
|
||||
|
||||
std::optional<DataNode> nulls = content ? xml_child_find(*content, "Nulls") : std::nullopt;
|
||||
std::optional<DataNode> events = content ? xml_child_find(*content, "Events") : std::nullopt;
|
||||
file.nullLayerNames = xml_names_read(nulls, ANM2_LAYER_LIMIT, "%s: invalid Null ID %d\n", path);
|
||||
file.eventNames = xml_names_read(events, ANM2_EVENT_LIMIT, "%s: invalid Event ID %d\n", path);
|
||||
|
||||
std::optional<DataNode> animations = xml_child_find(*actor, "Animations");
|
||||
if (!animations) return true;
|
||||
file.defaultAnimation = node_attr(*animations, "DefaultAnimation");
|
||||
xml_animations_read(*animations, parse, file);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 0040ed50 Parses an .anm2 into what the game plays, by its first character: the original's XML ('<') or Anm2Ed's JSON
|
||||
// document. Spritesheet paths become relative to resources/, from the .anm2's folder.
|
||||
static std::shared_ptr<const AnmFileData> file_parse(const std::string& path)
|
||||
{
|
||||
auto file = std::make_shared<AnmFileData>();
|
||||
Anm2Parse parse = {path, {}, {}};
|
||||
std::string redirected = g_manager ? g_manager->modManager.TryRedirectPath(path) : path;
|
||||
std::string bytes;
|
||||
|
||||
bool isRead = resource_load(redirected, bytes);
|
||||
size_t first = bytes.find_first_not_of(LEADING_SPACE);
|
||||
bool isXml = first != std::string::npos && bytes[first] == '<';
|
||||
if (!isRead || !(isXml ? xml_file_read(parse, bytes, *file) : json_file_read(parse, bytes, *file)))
|
||||
{
|
||||
log_print(LOG_INFO, "ERROR Could not open %s\n", path.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
@@ -1386,7 +1591,7 @@ void ANM2::LoadDeliriumForm(ANM2& sprite, int type, int variant, bool isReloadAn
|
||||
if (!replaced) continue;
|
||||
|
||||
path.replace(GFX_FOLDER.size(), replaced, DELIRIUM_FORMS_FOLDER);
|
||||
if (std::filesystem::exists(resource_path(path))) sprite.ReplaceSpritesheet(i, path);
|
||||
if (resource_exists(path)) sprite.ReplaceSpritesheet(i, path);
|
||||
}
|
||||
|
||||
sprite.LoadGraphics();
|
||||
|
||||
+249
-79
@@ -1,122 +1,292 @@
|
||||
#include "engine/data.h"
|
||||
#include "game/manager.h"
|
||||
#include "engine/platform.h"
|
||||
#include <cctype>
|
||||
#include <filesystem>
|
||||
#include "pugixml.hpp"
|
||||
#include "simdjson.h"
|
||||
#include <bit>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
constexpr std::string_view EMPTY_ARRAY = "[]";
|
||||
// What a missing tag, attribute or text reads as: empty, but C text that atoi can take.
|
||||
// What a missing tag or attribute reads as: empty, but C text that atoi can take.
|
||||
constexpr std::string_view EMPTY_TEXT = "";
|
||||
constexpr std::string_view JSON_EXTENSION = ".json";
|
||||
// Where the import tool puts a language archive's files (the original's resources.<code> mount).
|
||||
constexpr std::string_view LANGUAGE_FOLDER = "lang/";
|
||||
// Mods reach their own files from resources/ through "../mods/", and here the mods live in resources/mods/.
|
||||
constexpr std::string_view MODS_FROM_RESOURCES = "../mods/";
|
||||
constexpr std::string_view PARENT_FOLDER = "../";
|
||||
constexpr std::string_view MODS_FOLDER = "mods/";
|
||||
// The game's own folder name, which the exe writes in front of some paths ("resources/gfx/1000.034_Fart.anm2").
|
||||
constexpr std::string_view GAME_RESOURCES_FOLDER = "resources/";
|
||||
constexpr std::string_view ASSETS_FOLDER = "assets";
|
||||
// The whitespace Python's strip takes off, which decides whether the import tool keeps an element's text.
|
||||
constexpr std::string_view TEXT_SPACE = " \t\n\r\v\f\x1c\x1d\x1e\x1f";
|
||||
// A run of text the import tool's fix-up leaves alone when it is only this whitespace, so expat turns its line ends
|
||||
// into '\n'. It keeps every other run's carriage returns, as rapidxml does.
|
||||
constexpr std::string_view PIECE_SPACE = " \t\n\r\v\f";
|
||||
constexpr std::string_view BYTE_ORDER_MARK = "\xef\xbb\xbf";
|
||||
constexpr std::string_view COMMENT_OPEN = "<!--";
|
||||
constexpr std::string_view COMMENT_CLOSE = "-->";
|
||||
// The parse keeps text as the XML holds it, whitespace and line ends included, as rapidxml and the import tool do.
|
||||
constexpr unsigned int XML_PARSE_FLAGS = pugi::parse_cdata | pugi::parse_escapes | pugi::parse_ws_pcdata;
|
||||
|
||||
std::string dataDirectory = "resources/";
|
||||
std::string languageDirectory;
|
||||
|
||||
// A game path lowercased with forward slashes, as the game normalizes every path before a lookup. A path already under
|
||||
// the resources or the mods folder, which mods build from their script's path as the original's absolute ones, stays
|
||||
// there.
|
||||
static std::string path_normalize(std::string_view path)
|
||||
// A simdjson element or iterator by its tape reference, which is all either holds.
|
||||
struct JsonRef
|
||||
{
|
||||
std::string_view mods = platform.modsDirectory;
|
||||
bool isModsPath = !mods.empty() && path.starts_with(mods);
|
||||
if (isModsPath) path.remove_prefix(mods.size());
|
||||
else if (path.starts_with(dataDirectory)) path.remove_prefix(dataDirectory.size());
|
||||
const void* document;
|
||||
size_t index;
|
||||
};
|
||||
|
||||
std::string normalized(path);
|
||||
for (char& letter : normalized) letter = letter == '\\' ? '/' : (char)std::tolower((unsigned char)letter);
|
||||
if (isModsPath) normalized.insert(0, MODS_FOLDER);
|
||||
else if (normalized.starts_with(MODS_FROM_RESOURCES)) normalized.erase(0, PARENT_FOLDER.size());
|
||||
else if (normalized.starts_with(GAME_RESOURCES_FOLDER)) normalized.erase(0, GAME_RESOURCES_FOLDER.size());
|
||||
return normalized;
|
||||
static_assert(sizeof(JsonRef) == sizeof(simdjson::dom::element));
|
||||
static_assert(std::is_trivially_copyable_v<simdjson::dom::element>);
|
||||
static_assert(sizeof(JsonRef) == sizeof(simdjson::dom::array::iterator));
|
||||
static_assert(sizeof(JsonRef) == sizeof(simdjson::dom::object::iterator));
|
||||
|
||||
// A document's parsed form: pugixml's tree of its XML, or simdjson's tape of its JSON.
|
||||
struct DataDocument
|
||||
{
|
||||
pugi::xml_document xml;
|
||||
simdjson::dom::parser parser;
|
||||
};
|
||||
|
||||
Data::Data() = default;
|
||||
Data::~Data() = default;
|
||||
|
||||
template <class Json> static Json json_get(DataNode node)
|
||||
{
|
||||
return std::bit_cast<Json>(JsonRef{node.json, node.jsonIndex});
|
||||
}
|
||||
|
||||
// A normalized path under the language's folder when that holds it, a mod's under the mods folder, under the data
|
||||
// directory otherwise.
|
||||
static std::string mount_resolve(const std::string& normalized)
|
||||
template <class Json> static DataNode json_node(Json json)
|
||||
{
|
||||
std::error_code error;
|
||||
std::string localized = languageDirectory + normalized;
|
||||
|
||||
if (!languageDirectory.empty() && std::filesystem::exists(localized, error)) return localized;
|
||||
if (normalized.starts_with(MODS_FOLDER) && !platform.modsDirectory.empty())
|
||||
return platform.modsDirectory + normalized.substr(MODS_FOLDER.size());
|
||||
return dataDirectory + normalized;
|
||||
JsonRef ref = std::bit_cast<JsonRef>(json);
|
||||
return {ref.document, ref.index, nullptr};
|
||||
}
|
||||
|
||||
// Where a game path lives once imported.
|
||||
std::string resource_path(std::string_view path)
|
||||
static pugi::xml_node xml_get(DataNode node)
|
||||
{
|
||||
return mount_resolve(path_normalize(path));
|
||||
return pugi::xml_node((pugi::xml_node_struct*)node.xml);
|
||||
}
|
||||
|
||||
// Where a file the repository ships itself lives: in assets/, beside the resources folder.
|
||||
std::string asset_path(std::string_view path)
|
||||
static DataNode xml_node(pugi::xml_node node)
|
||||
{
|
||||
return (std::filesystem::path(dataDirectory).parent_path().parent_path() / ASSETS_FOLDER / path).string();
|
||||
return {nullptr, 0, node.internal_object()};
|
||||
}
|
||||
|
||||
// Where a converted XML document lives: its game path with ".json" appended.
|
||||
std::string data_path(std::string_view path)
|
||||
static DataNode xml_attr_node(pugi::xml_attribute attr)
|
||||
{
|
||||
return mount_resolve(path_normalize(path) + std::string(JSON_EXTENSION));
|
||||
return {nullptr, 0, attr.internal_object()};
|
||||
}
|
||||
|
||||
// 009abbd0 Remounts the resources, with the folder of the string table's language in front once there is a manager.
|
||||
// The language folder is only mounted when the import tool wrote one, which finds the same files.
|
||||
// The original also mounts the game folder behind the resources when its file system already knows it. Nothing on
|
||||
// Linux reads from there.
|
||||
void reload_resource_paths()
|
||||
// The element itself, or the next element after it among its siblings.
|
||||
static pugi::xml_node element_from(pugi::xml_node node)
|
||||
{
|
||||
languageDirectory.clear();
|
||||
if (!g_manager) return;
|
||||
|
||||
std::string localized = dataDirectory + std::string(LANGUAGE_FOLDER) + std::string(Manager::GetLanguage()) + '/';
|
||||
std::error_code error;
|
||||
if (std::filesystem::is_directory(localized, error)) languageDirectory = localized;
|
||||
while (node && node.type() != pugi::node_element) node = node.next_sibling();
|
||||
return node;
|
||||
}
|
||||
|
||||
// Loads a converted document, leaving isLoaded false when it is missing or unreadable.
|
||||
// The attribute itself, or the next after it, that no later attribute of the same name repeats.
|
||||
static pugi::xml_attribute attr_from(pugi::xml_attribute attr)
|
||||
{
|
||||
for (; attr; attr = attr.next_attribute())
|
||||
{
|
||||
pugi::xml_attribute later = attr.next_attribute();
|
||||
while (later && std::strcmp(later.name(), attr.name()) != 0) later = later.next_attribute();
|
||||
if (!later) break;
|
||||
}
|
||||
return attr;
|
||||
}
|
||||
|
||||
// What rapidxml does with closing tags the import tool's fix-up redoes for expat: each closes the element open
|
||||
// there whatever its name, one with none open is dropped, and the end of the text closes the rest.
|
||||
static std::string tags_balance(std::string_view text)
|
||||
{
|
||||
std::vector<std::string_view> open;
|
||||
std::string balanced;
|
||||
size_t last = 0;
|
||||
|
||||
for (size_t start = text.find('<'); start != std::string_view::npos; start = text.find('<', start + 1))
|
||||
{
|
||||
if (text.substr(start).starts_with(COMMENT_OPEN))
|
||||
{
|
||||
start = text.find(COMMENT_CLOSE, start);
|
||||
if (start == std::string_view::npos) break;
|
||||
continue;
|
||||
}
|
||||
size_t end = start + 1;
|
||||
for (char quote = 0; end < text.size() && (quote || text[end] != '>'); end++)
|
||||
if (text[end] == '"' || text[end] == '\'') quote = quote == text[end] ? 0 : quote ? quote : text[end];
|
||||
if (end >= text.size()) break;
|
||||
|
||||
std::string_view tag = text.substr(start, end + 1 - start);
|
||||
if (tag[1] == '?' || tag[1] == '!' || tag.ends_with("/>"))
|
||||
{
|
||||
start = end;
|
||||
continue;
|
||||
}
|
||||
if (tag[1] != '/') open.push_back(tag.substr(1, tag.find_first_of(" \t\r\n/>") - 1));
|
||||
else
|
||||
{
|
||||
balanced.append(text.substr(last, start - last));
|
||||
if (!open.empty()) balanced.append("</").append(open.back()).append(">");
|
||||
if (!open.empty()) open.pop_back();
|
||||
last = end + 1;
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
balanced.append(text.substr(last));
|
||||
for (auto name = open.rbegin(); name != open.rend(); name++) balanced.append("</").append(*name).append(">");
|
||||
return balanced;
|
||||
}
|
||||
|
||||
// Parses an XML document as the game's rapidxml reads it, closing tags matched to the elements they close. Its root
|
||||
// is its one top-level element, or the document over several.
|
||||
static bool xml_parse(Data& data, std::string_view bytes)
|
||||
{
|
||||
pugi::xml_document& xml = data.document->xml;
|
||||
pugi::xml_parse_result result = xml.load_buffer(bytes.data(), bytes.size(), XML_PARSE_FLAGS);
|
||||
if (result.status == pugi::status_end_element_mismatch)
|
||||
{
|
||||
std::string balanced = tags_balance(bytes);
|
||||
result = xml.load_buffer(balanced.data(), balanced.size(), XML_PARSE_FLAGS);
|
||||
}
|
||||
if (!result) return false;
|
||||
|
||||
pugi::xml_node root = element_from(xml.first_child());
|
||||
if (!root) return false;
|
||||
data.root = xml_node(element_from(root.next_sibling()) ? xml : root);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Parses a document's bytes by their first character: '<' XML, '{' the import tool's JSON. isLoaded tells whether it
|
||||
// parsed. A JSON document parses in place, so bytes may gain room for simdjson's padding.
|
||||
void data_parse(Data& data, std::string& bytes)
|
||||
{
|
||||
std::string_view text = bytes;
|
||||
if (text.starts_with(BYTE_ORDER_MARK)) text.remove_prefix(BYTE_ORDER_MARK.size());
|
||||
size_t first = text.find_first_not_of(TEXT_SPACE);
|
||||
|
||||
data.document = std::make_unique<DataDocument>();
|
||||
data.isLoaded = false;
|
||||
if (first != std::string_view::npos && text[first] == '<') data.isLoaded = xml_parse(data, bytes);
|
||||
if (first == std::string_view::npos || text[first] != '{') return;
|
||||
|
||||
simdjson::dom::element root;
|
||||
bytes.reserve(bytes.size() + simdjson::SIMDJSON_PADDING);
|
||||
data.isLoaded = data.document->parser.parse(bytes.data(), bytes.size(), false).get(root) == simdjson::SUCCESS;
|
||||
data.root = json_node(root);
|
||||
}
|
||||
|
||||
// Loads a game document in the form the DataFormat option prefers, leaving isLoaded false when neither form is
|
||||
// mounted or the one read does not parse.
|
||||
void data_load(Data& data, std::string_view path)
|
||||
{
|
||||
data.isLoaded = data.parser.load(data_path(path)).get(data.root) == simdjson::SUCCESS;
|
||||
DataFormat format = g_manager ? g_manager->optionsConfig.dataFormat : DATA_FORMAT_XML;
|
||||
std::string json = std::string(path) + std::string(JSON_EXTENSION);
|
||||
std::string bytes;
|
||||
bool isRead = format == DATA_FORMAT_AUTO ? resource_load_first({path, json}, bytes)
|
||||
: format == DATA_FORMAT_JSON ? resource_load(json, bytes) || resource_load(path, bytes)
|
||||
: resource_load(path, bytes) || resource_load(json, bytes);
|
||||
|
||||
data.isLoaded = false;
|
||||
if (isRead) data_parse(data, bytes);
|
||||
}
|
||||
|
||||
std::string_view node_tag(DataNode node)
|
||||
{
|
||||
std::string_view tag;
|
||||
return node["tag"].get(tag) == simdjson::SUCCESS ? tag : EMPTY_TEXT;
|
||||
if (node.xml) return xml_get(node).type() == pugi::node_document ? DOCUMENT_TAG : xml_get(node).name();
|
||||
return json_get<simdjson::dom::element>(node)["tag"].get(tag) == simdjson::SUCCESS ? tag : EMPTY_TEXT;
|
||||
}
|
||||
|
||||
// An attribute's raw string, the last of a repeated one, or nothing when the element lacks it.
|
||||
std::optional<std::string_view> node_attr_find(DataNode node, std::string_view name)
|
||||
{
|
||||
std::optional<std::string_view> found;
|
||||
std::string_view value;
|
||||
|
||||
if (!node.xml)
|
||||
{
|
||||
if (json_get<simdjson::dom::element>(node)["attrs"][name].get(value) == simdjson::SUCCESS) found = value;
|
||||
return found;
|
||||
}
|
||||
for (pugi::xml_attribute attr = xml_get(node).last_attribute(); attr; attr = attr.previous_attribute())
|
||||
if (attr.name() == name) return attr.value();
|
||||
return found;
|
||||
}
|
||||
|
||||
// An attribute's raw string, or an empty one when the element lacks it.
|
||||
std::string_view node_attr(DataNode node, std::string_view name)
|
||||
{
|
||||
return node_attr_find(node, name).value_or(EMPTY_TEXT);
|
||||
}
|
||||
|
||||
// The element's text, all of it between its children joined, or empty when that is only whitespace. Line ends read as
|
||||
// in the import tool's JSON.
|
||||
std::string node_text(DataNode node)
|
||||
{
|
||||
std::string_view value;
|
||||
return node["attrs"][name].get(value) == simdjson::SUCCESS ? value : EMPTY_TEXT;
|
||||
}
|
||||
std::string text;
|
||||
|
||||
std::string_view node_text(DataNode node)
|
||||
if (!node.xml)
|
||||
{
|
||||
std::string_view text;
|
||||
return node["text"].get(text) == simdjson::SUCCESS ? text : EMPTY_TEXT;
|
||||
if (json_get<simdjson::dom::element>(node)["text"].get(value) == simdjson::SUCCESS) text = value;
|
||||
return text;
|
||||
}
|
||||
|
||||
// The element's children in document order, empty when it has none.
|
||||
// A default-constructed array points at no document, so a parsed empty one stands in.
|
||||
simdjson::dom::array node_children(DataNode node)
|
||||
for (pugi::xml_node child : xml_get(node).children())
|
||||
{
|
||||
static simdjson::dom::parser emptyParser;
|
||||
static simdjson::dom::array empty =
|
||||
emptyParser.parse(EMPTY_ARRAY.data(), EMPTY_ARRAY.size()).get_array().value_unsafe();
|
||||
simdjson::dom::array children;
|
||||
std::string_view piece = child.value();
|
||||
bool isKept = child.type() == pugi::node_pcdata && piece.find_first_not_of(PIECE_SPACE) != std::string::npos;
|
||||
if (child.type() != pugi::node_pcdata && child.type() != pugi::node_cdata) continue;
|
||||
|
||||
return node["children"].get(children) == simdjson::SUCCESS ? children : empty;
|
||||
for (size_t i = 0; i < piece.size(); i++)
|
||||
if (isKept || piece[i] != '\r') text += piece[i];
|
||||
else if (i + 1 == piece.size() || piece[i + 1] != '\n') text += '\n';
|
||||
}
|
||||
if (text.find_first_not_of(TEXT_SPACE) == std::string::npos) text.clear();
|
||||
return text;
|
||||
}
|
||||
|
||||
DataChildren node_children(DataNode node)
|
||||
{
|
||||
DataChildren children;
|
||||
simdjson::dom::array list;
|
||||
|
||||
if (node.xml) children.first.cursor = xml_node(element_from(xml_get(node).first_child()));
|
||||
if (node.xml) children.last.cursor = xml_node(pugi::xml_node());
|
||||
if (node.xml || json_get<simdjson::dom::element>(node)["children"].get(list) != simdjson::SUCCESS) return children;
|
||||
children.first.cursor = json_node(list.begin());
|
||||
children.last.cursor = json_node(list.end());
|
||||
return children;
|
||||
}
|
||||
|
||||
DataChildren::iterator& DataChildren::iterator::operator++()
|
||||
{
|
||||
if (cursor.xml) cursor = xml_node(element_from(xml_get(cursor).next_sibling()));
|
||||
else cursor = json_node(++json_get<simdjson::dom::array::iterator>(cursor));
|
||||
return *this;
|
||||
}
|
||||
|
||||
DataAttrs node_attrs(DataNode node)
|
||||
{
|
||||
DataAttrs attrs;
|
||||
simdjson::dom::object fields;
|
||||
|
||||
if (node.xml) attrs.first.cursor = xml_attr_node(attr_from(xml_get(node).first_attribute()));
|
||||
if (node.xml) attrs.last.cursor = xml_attr_node(pugi::xml_attribute());
|
||||
if (node.xml || json_get<simdjson::dom::element>(node)["attrs"].get(fields) != simdjson::SUCCESS) return attrs;
|
||||
attrs.first.cursor = json_node(fields.begin());
|
||||
attrs.last.cursor = json_node(fields.end());
|
||||
return attrs;
|
||||
}
|
||||
|
||||
DataAttr DataAttrs::iterator::operator*() const
|
||||
{
|
||||
std::string_view value;
|
||||
if (cursor.xml)
|
||||
{
|
||||
pugi::xml_attribute attr((pugi::xml_attribute_struct*)cursor.xml);
|
||||
return {attr.name(), attr.value()};
|
||||
}
|
||||
|
||||
auto field = json_get<simdjson::dom::object::iterator>(cursor);
|
||||
if (field.value().get(value) != simdjson::SUCCESS) value = EMPTY_TEXT;
|
||||
return {field.key(), value};
|
||||
}
|
||||
|
||||
DataAttrs::iterator& DataAttrs::iterator::operator++()
|
||||
{
|
||||
pugi::xml_attribute attr((pugi::xml_attribute_struct*)cursor.xml);
|
||||
if (cursor.xml) cursor = xml_attr_node(attr_from(attr.next_attribute()));
|
||||
else cursor = json_node(++json_get<simdjson::dom::object::iterator>(cursor));
|
||||
return *this;
|
||||
}
|
||||
+87
-21
@@ -1,36 +1,102 @@
|
||||
#pragma once
|
||||
|
||||
#include "simdjson.h"
|
||||
#include "engine/filesys.h"
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
// The root node a converted XML file opens with.
|
||||
// The root a document with several top-level elements opens with, as the import tool names it.
|
||||
constexpr std::string_view DOCUMENT_TAG = "#document";
|
||||
// What the import tool appends to a document's path for its JSON.
|
||||
constexpr std::string_view JSON_EXTENSION = ".json";
|
||||
|
||||
// A game document the import tool converted from XML (items.xml, entities2.xml ...) into resources/<path>.json.
|
||||
// (.anm2 files are Anm2Ed's own JSON documents under their own names instead.)
|
||||
// Each element is {"tag", "attrs", "children", "text"}, with every attribute value kept as the string the XML held,
|
||||
// so loaders read it the way the game read its rapidxml nodes.
|
||||
struct Data
|
||||
// Which form of a game document data_load reads when there are both: the XML file, or the import tool's JSON beside
|
||||
// it (<path>.json). auto takes the first mount that holds either, XML first there. A missing one falls back to the
|
||||
// other.
|
||||
enum DataFormat : int
|
||||
{
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element root;
|
||||
bool isLoaded = false;
|
||||
DATA_FORMAT_AUTO,
|
||||
DATA_FORMAT_JSON,
|
||||
DATA_FORMAT_XML
|
||||
};
|
||||
|
||||
using DataNode = simdjson::dom::element;
|
||||
constexpr std::string_view DATA_FORMAT_NAMES[] = {"auto", "json", "xml"};
|
||||
|
||||
// An element of a loaded document, the same to loaders in either form: a pugixml node of the XML, or a simdjson
|
||||
// element of the JSON the import tool converts it to ({"tag", "attrs", "children", "text"}). Attribute values are the
|
||||
// strings the XML held, NUL-terminated as atoi reads them.
|
||||
struct DataNode
|
||||
{
|
||||
const void* json = nullptr;
|
||||
size_t jsonIndex = 0;
|
||||
void* xml = nullptr;
|
||||
|
||||
bool operator==(const DataNode& other) const = default;
|
||||
};
|
||||
|
||||
struct DataAttr
|
||||
{
|
||||
std::string_view name;
|
||||
std::string_view value;
|
||||
};
|
||||
|
||||
// A node's child elements in document order.
|
||||
struct DataChildren
|
||||
{
|
||||
struct iterator
|
||||
{
|
||||
DataNode cursor;
|
||||
|
||||
DataNode operator*() const { return cursor; }
|
||||
iterator& operator++();
|
||||
bool operator==(const iterator& other) const = default;
|
||||
};
|
||||
iterator first;
|
||||
iterator last;
|
||||
|
||||
iterator begin() const { return first; }
|
||||
iterator end() const { return last; }
|
||||
};
|
||||
|
||||
// A node's attributes in document order. A repeated one counts once, with its last value where it last stands.
|
||||
struct DataAttrs
|
||||
{
|
||||
struct iterator
|
||||
{
|
||||
DataNode cursor;
|
||||
|
||||
DataAttr operator*() const;
|
||||
iterator& operator++();
|
||||
bool operator==(const iterator& other) const = default;
|
||||
};
|
||||
iterator first;
|
||||
iterator last;
|
||||
|
||||
iterator begin() const { return first; }
|
||||
iterator end() const { return last; }
|
||||
};
|
||||
|
||||
struct DataDocument;
|
||||
|
||||
// A loaded document: its parsed tree and its root, the one top-level element or DOCUMENT_TAG over several. isLoaded is
|
||||
// false when the file is missing or does not parse.
|
||||
struct Data
|
||||
{
|
||||
std::unique_ptr<DataDocument> document;
|
||||
DataNode root;
|
||||
bool isLoaded = false;
|
||||
|
||||
Data();
|
||||
~Data();
|
||||
};
|
||||
|
||||
void data_load(Data& data, std::string_view path);
|
||||
std::string data_path(std::string_view path);
|
||||
std::string resource_path(std::string_view path);
|
||||
std::string asset_path(std::string_view path);
|
||||
void reload_resource_paths();
|
||||
void data_parse(Data& data, std::string& bytes);
|
||||
|
||||
std::string_view node_tag(DataNode node);
|
||||
std::string_view node_attr(DataNode node, std::string_view name);
|
||||
std::string_view node_text(DataNode node);
|
||||
simdjson::dom::array node_children(DataNode node);
|
||||
|
||||
// The resources, and the language's own folder looked in first (empty while it has none).
|
||||
extern std::string dataDirectory;
|
||||
extern std::string languageDirectory;
|
||||
std::optional<std::string_view> node_attr_find(DataNode node, std::string_view name);
|
||||
std::string node_text(DataNode node);
|
||||
DataChildren node_children(DataNode node);
|
||||
DataAttrs node_attrs(DataNode node);
|
||||
@@ -0,0 +1,658 @@
|
||||
#include "engine/filesys.h"
|
||||
#include "engine/platform.h"
|
||||
#include "game/manager.h"
|
||||
#include "stb_image.h"
|
||||
#include <SDL3/SDL_filesystem.h>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
// The archives IsaacStartup (009aa040) mounts, in its order, later ones overriding earlier ones. secret.a is a file of
|
||||
// afterbirthp.a. A language archive holds its files under resources.<code>/.
|
||||
constexpr std::array<std::string_view, 18> ARCHIVE_NAMES = {
|
||||
"packed/animations.a", "packed/config.a", "packed/fonts.a", "packed/graphics.a",
|
||||
"packed/music.a", "packed/rooms.a", "packed/sfx.a", "packed/videos.a",
|
||||
"packed/afterbirth.a", "packed/afterbirthp.a", "packed/repentance_de.a", "packed/repentance_es.a",
|
||||
"packed/repentance_jp.a", "packed/repentance_kr.a", "packed/repentance_ru.a", "packed/repentance_zh.a",
|
||||
"packed/repentance_fr.a", "secret.a"};
|
||||
constexpr std::string_view ARCHIVE_MAGIC = "ARCH000";
|
||||
constexpr char LANGUAGE_SEPARATOR = '_';
|
||||
constexpr size_t ARCHIVE_HEADER_SIZE = 14;
|
||||
constexpr size_t ARCHIVE_TYPE_OFFSET = 7;
|
||||
constexpr size_t ARCHIVE_INDEX_OFFSET = 8;
|
||||
constexpr size_t ARCHIVE_COUNT_OFFSET = 12;
|
||||
// An index row: primary hash, secondary hash, data offset, unpacked size, checksum.
|
||||
constexpr size_t ARCHIVE_ROW_SIZE = 20;
|
||||
constexpr size_t ROW_SECONDARY = 4;
|
||||
constexpr size_t ROW_START = 8;
|
||||
constexpr size_t ROW_SIZE = 12;
|
||||
|
||||
constexpr std::string_view BASE_MOUNT = "resources/";
|
||||
constexpr std::string_view LANGUAGE_MOUNT = "resources.";
|
||||
// Where the import tool puts a language archive's files.
|
||||
constexpr std::string_view LANGUAGE_FOLDER = "lang/";
|
||||
// Mods reach their own files from resources/ through "../mods/".
|
||||
constexpr std::string_view MODS_FROM_RESOURCES = "../mods/";
|
||||
constexpr std::string_view PARENT_FOLDER = "../";
|
||||
constexpr std::string_view MODS_FOLDER = "mods/";
|
||||
// The game's own folder name, which the exe writes in front of some paths ("resources/gfx/1000.034_Fart.anm2").
|
||||
constexpr std::string_view GAME_RESOURCES_FOLDER = "resources/";
|
||||
constexpr std::string_view ASSETS_FOLDER = "assets";
|
||||
// Room for simdjson's padding after a file's bytes, so a JSON document parses where it was read.
|
||||
constexpr size_t READ_PADDING = 64;
|
||||
|
||||
// The path hashes (GetPrimaryFilePathHash 00a159d0, FUN_00a15ab0): djb2, and FNV-1a from another seed.
|
||||
constexpr uint32_t DJB_SEED = 5381;
|
||||
constexpr uint32_t DJB_FACTOR = 33;
|
||||
constexpr uint32_t FNV_SEED = 0x5bb2220e;
|
||||
constexpr uint32_t FNV_PRIME = 0x1000193;
|
||||
|
||||
// Type 0: dwords XORed with a xorshift32 key, then shuffled by the key's low nibble.
|
||||
constexpr uint32_t XORSHIFT_KEY = 0xf9524287;
|
||||
constexpr uint32_t NIBBLE_MASK = 15;
|
||||
constexpr uint32_t NIBBLE_REVERSE = 2;
|
||||
constexpr uint32_t NIBBLE_SWAP_BYTES = 9;
|
||||
constexpr uint32_t NIBBLE_SWAP_HALVES = 13;
|
||||
constexpr uint32_t LOW_BYTES_MASK = 0x00ff00ff;
|
||||
constexpr int BYTE_BITS = 8;
|
||||
constexpr int HALF_BITS = 16;
|
||||
constexpr int XORSHIFT_FIRST = 8;
|
||||
constexpr int XORSHIFT_SECOND = 9;
|
||||
constexpr int XORSHIFT_THIRD = 23;
|
||||
|
||||
// Type 1: LZW codes from 8 to 12 bits wide, the dictionary starting over at 0xfff entries.
|
||||
constexpr int LZW_LITERALS = 256;
|
||||
constexpr int LZW_RESET = 0xfff;
|
||||
constexpr int LZW_TABLE_SIZE = 0x1000;
|
||||
constexpr int LZW_NO_PREFIX = -1;
|
||||
// The bytes a code can straddle: up to 12 bits from any bit of the first.
|
||||
constexpr size_t LZW_WINDOW_BYTES = 3;
|
||||
|
||||
// Type 2: raw deflate chunks until a full 1 KiB one that is not the last, stored and keyed by ISAAC from there on.
|
||||
constexpr uint32_t LAST_CHUNK = 0x80000000;
|
||||
constexpr uint32_t STORED_CHUNK_SIZE = 0x400;
|
||||
// A last, empty stored block, which ends a stream the chunks leave open at a flush.
|
||||
constexpr std::string_view DEFLATE_END = {"\x01\x00\x00\xff\xff", 5};
|
||||
constexpr int ISAAC_SIZE = 256;
|
||||
constexpr int ISAAC_MIX_SIZE = 8;
|
||||
constexpr int ISAAC_WARMUP_ROUNDS = 4;
|
||||
constexpr uint32_t GOLDEN_RATIO = 0x9e3779b9;
|
||||
constexpr uint64_t PCG_FACTOR = 0x5851f42d4c957f2d;
|
||||
constexpr uint64_t PCG_INCREMENT = 0x7f;
|
||||
|
||||
// Type 5 (secret.a only): bytes XORed with a fixed key.
|
||||
constexpr std::array<uint8_t, 128> SECRET_KEY = {
|
||||
0xb0, 0x22, 0x5d, 0x47, 0xd3, 0x1b, 0x59, 0xd1, 0x97, 0x37, 0xfb, 0xd2, 0xc0, 0x31, 0x86, 0xfd, 0xb5, 0xdd, 0xac,
|
||||
0x4b, 0xb4, 0x01, 0x15, 0x52, 0x01, 0x0a, 0x75, 0x08, 0x5d, 0x50, 0xfe, 0x8c, 0xa8, 0xaf, 0xd5, 0xcb, 0x09, 0xee,
|
||||
0xdc, 0xca, 0x76, 0xc4, 0x3f, 0x67, 0xed, 0x09, 0x8f, 0x64, 0x43, 0x56, 0x30, 0x1a, 0x89, 0x2e, 0xdf, 0xf9, 0xe4,
|
||||
0xb8, 0x13, 0x1a, 0xbe, 0xaf, 0xa4, 0x02, 0xff, 0x60, 0x22, 0xe0, 0x0b, 0xff, 0xae, 0xc9, 0x7d, 0xa0, 0x27, 0xf9,
|
||||
0x11, 0x63, 0x2f, 0xe1, 0x20, 0x7e, 0x51, 0xd7, 0x0e, 0xcd, 0xc4, 0xd4, 0xcf, 0xcf, 0xa1, 0x88, 0x99, 0x42, 0x96,
|
||||
0xcf, 0xf0, 0xc1, 0x54, 0xc3, 0x36, 0x94, 0xc2, 0x92, 0xdc, 0xb8, 0x63, 0xca, 0xca, 0x32, 0x12, 0x7a, 0x3c, 0x88,
|
||||
0x5f, 0xd2, 0x4b, 0xc3, 0xe4, 0x69, 0x74, 0x32, 0xbd, 0x2c, 0x42, 0x28, 0xb2, 0x34};
|
||||
|
||||
// How an archive packs its files, from its header's type byte.
|
||||
enum ArchiveType : uint8_t
|
||||
{
|
||||
ARCHIVE_XORSHIFT = 0,
|
||||
ARCHIVE_LZW = 1,
|
||||
ARCHIVE_MINIZ = 2,
|
||||
ARCHIVE_SECRET = 5
|
||||
};
|
||||
|
||||
// A mounted archive: its file on disk, or its bytes when it is itself a file of an earlier archive.
|
||||
struct Archive
|
||||
{
|
||||
std::string bytes;
|
||||
std::FILE* file = nullptr;
|
||||
ArchiveType type = ARCHIVE_XORSHIFT;
|
||||
};
|
||||
|
||||
// A file of an archive by its index row: where its packed bytes start and how far they can run (to the next file's
|
||||
// start), its unpacked size and the secondary hash its key derives from.
|
||||
struct ArchiveEntry
|
||||
{
|
||||
uint32_t length = 0;
|
||||
uint32_t secondary = 0;
|
||||
uint32_t size = 0;
|
||||
uint32_t start = 0;
|
||||
uint16_t archive = 0;
|
||||
};
|
||||
|
||||
// Where a game path is: in an archive or on disk.
|
||||
struct ResourceFile
|
||||
{
|
||||
std::string path;
|
||||
const ArchiveEntry* entry = nullptr;
|
||||
};
|
||||
|
||||
// The keystream's words are used as their little-endian bytes.
|
||||
static_assert(std::endian::native == std::endian::little);
|
||||
|
||||
// Bob Jenkins' ISAAC seeded from 256 PCG32 outputs (FUN_00aa93e0, isaac_randinit 00aa9580, isaac FUN_00aa94a0), whose
|
||||
// rounds key a miniz archive's stored chunks.
|
||||
class IsaacStream
|
||||
{
|
||||
public:
|
||||
std::array<uint32_t, ISAAC_SIZE> memory = {};
|
||||
std::array<uint32_t, ISAAC_SIZE> results = {};
|
||||
uint32_t a = 0;
|
||||
uint32_t b = 0;
|
||||
uint32_t c = 0;
|
||||
|
||||
explicit IsaacStream(uint32_t seed);
|
||||
void round_run();
|
||||
};
|
||||
|
||||
std::string dataDirectory = "resources/";
|
||||
std::string languageDirectory;
|
||||
|
||||
static std::vector<Archive> archives;
|
||||
static std::unordered_map<uint64_t, ArchiveEntry> archiveEntries;
|
||||
static std::vector<std::string> archiveLanguages;
|
||||
// The language's mount prefix ("resources.de/") while languageDirectory is set.
|
||||
static std::string languageMount;
|
||||
// Each folder's entries by lowercased name, read once a lookup there misses with its exact case.
|
||||
static std::unordered_map<std::string, std::unordered_map<std::string, std::string>> folderListings;
|
||||
|
||||
static void isaac_mix(std::array<uint32_t, ISAAC_MIX_SIZE>& v)
|
||||
{
|
||||
v[0] ^= v[1] << 11;
|
||||
v[3] += v[0];
|
||||
v[1] += v[2];
|
||||
v[1] ^= v[2] >> 2;
|
||||
v[4] += v[1];
|
||||
v[2] += v[3];
|
||||
v[2] ^= v[3] << 8;
|
||||
v[5] += v[2];
|
||||
v[3] += v[4];
|
||||
v[3] ^= v[4] >> 16;
|
||||
v[6] += v[3];
|
||||
v[4] += v[5];
|
||||
v[4] ^= v[5] << 10;
|
||||
v[7] += v[4];
|
||||
v[5] += v[6];
|
||||
v[5] ^= v[6] >> 4;
|
||||
v[0] += v[5];
|
||||
v[6] += v[7];
|
||||
v[6] ^= v[7] << 8;
|
||||
v[1] += v[6];
|
||||
v[7] += v[0];
|
||||
v[7] ^= v[0] >> 9;
|
||||
v[2] += v[7];
|
||||
v[0] += v[1];
|
||||
}
|
||||
|
||||
IsaacStream::IsaacStream(uint32_t seed)
|
||||
{
|
||||
uint64_t state = (uint64_t)seed << 32 | (((seed << 15 ^ seed) << 8) ^ (seed >> 9) ^ seed);
|
||||
for (uint32_t& result : results)
|
||||
{
|
||||
result = std::rotr((uint32_t)((state >> 18 ^ state) >> 27), (int)(state >> 59));
|
||||
state = state * PCG_FACTOR + PCG_INCREMENT;
|
||||
}
|
||||
|
||||
std::array<uint32_t, ISAAC_MIX_SIZE> v;
|
||||
v.fill(GOLDEN_RATIO);
|
||||
for (int i = 0; i < ISAAC_WARMUP_ROUNDS; i++) isaac_mix(v);
|
||||
for (std::array<uint32_t, ISAAC_SIZE>* source : {&results, &memory})
|
||||
for (int i = 0; i < ISAAC_SIZE; i += ISAAC_MIX_SIZE)
|
||||
{
|
||||
for (int j = 0; j < ISAAC_MIX_SIZE; j++) v[j] += (*source)[i + j];
|
||||
isaac_mix(v);
|
||||
std::copy(v.begin(), v.end(), memory.begin() + i);
|
||||
}
|
||||
}
|
||||
|
||||
// Fills results with the next 256 words.
|
||||
void IsaacStream::round_run()
|
||||
{
|
||||
auto step = [&](int i, uint32_t mixed)
|
||||
{
|
||||
uint32_t x = memory[i];
|
||||
a = (a ^ mixed) + memory[(i + ISAAC_SIZE / 2) & (ISAAC_SIZE - 1)];
|
||||
uint32_t y = memory[i] = memory[(x >> 2) & (ISAAC_SIZE - 1)] + a + b;
|
||||
b = results[i] = memory[(y >> 10) & (ISAAC_SIZE - 1)] + x;
|
||||
};
|
||||
|
||||
b += ++c;
|
||||
for (int i = 0; i < ISAAC_SIZE; i += 4)
|
||||
{
|
||||
step(i, a << 13);
|
||||
step(i + 1, a >> 6);
|
||||
step(i + 2, a << 2);
|
||||
step(i + 3, a >> 16);
|
||||
}
|
||||
}
|
||||
|
||||
// A path's primary and secondary hash under a mount, ASCII-lowercased with '\' as '/', as one key.
|
||||
static uint64_t path_hash(std::string_view mount, std::string_view path)
|
||||
{
|
||||
uint32_t primary = DJB_SEED;
|
||||
uint32_t secondary = FNV_SEED;
|
||||
|
||||
for (std::string_view text : {mount, path})
|
||||
for (unsigned char letter : text)
|
||||
{
|
||||
letter = letter == '\\' ? '/' : letter >= 'A' && letter <= 'Z' ? letter + ('a' - 'A') : letter;
|
||||
primary = primary * DJB_FACTOR + letter;
|
||||
secondary = (secondary ^ letter) * FNV_PRIME;
|
||||
}
|
||||
return (uint64_t)primary << 32 | secondary;
|
||||
}
|
||||
|
||||
// A little-endian dword, zero past the end.
|
||||
static uint32_t word_get(std::string_view bytes, size_t offset)
|
||||
{
|
||||
uint32_t word = 0;
|
||||
std::memcpy(&word, bytes.data() + std::min(offset, bytes.size()),
|
||||
std::min(sizeof(word), bytes.size() - std::min(offset, bytes.size())));
|
||||
return word;
|
||||
}
|
||||
|
||||
// Type 0 (ArchivedFile refill_buffer 00a68cf0).
|
||||
static void xorshift_unpack(std::string_view packed, const ArchiveEntry& entry, std::string& bytes)
|
||||
{
|
||||
uint32_t key = (entry.secondary ^ XORSHIFT_KEY) | 1;
|
||||
|
||||
bytes.resize((entry.size + 3) & ~3u);
|
||||
for (size_t offset = 0; offset < bytes.size(); offset += sizeof(key))
|
||||
{
|
||||
uint32_t word = word_get(packed, offset) ^ key;
|
||||
uint32_t swapped = (word & LOW_BYTES_MASK) << BYTE_BITS | (word >> BYTE_BITS & LOW_BYTES_MASK);
|
||||
switch (key & NIBBLE_MASK)
|
||||
{
|
||||
case NIBBLE_REVERSE: word = std::rotl(swapped, HALF_BITS); break;
|
||||
case NIBBLE_SWAP_BYTES: word = swapped; break;
|
||||
case NIBBLE_SWAP_HALVES: word = std::rotl(word, HALF_BITS); break;
|
||||
}
|
||||
std::memcpy(bytes.data() + offset, &word, sizeof(word));
|
||||
key ^= key << XORSHIFT_FIRST;
|
||||
key ^= key >> XORSHIFT_SECOND;
|
||||
key ^= key << XORSHIFT_THIRD;
|
||||
}
|
||||
}
|
||||
|
||||
// Type 1 (lzw_decompress 00a85320): chunks of [u32 length][MSB-first codes], the dictionary kept across chunks. The
|
||||
// first code of a chunk adds no entry.
|
||||
static void lzw_unpack(std::string_view packed, const ArchiveEntry& entry, std::string& bytes)
|
||||
{
|
||||
struct Code
|
||||
{
|
||||
int length;
|
||||
int prefix;
|
||||
char first;
|
||||
char last;
|
||||
};
|
||||
std::vector<Code> table(LZW_TABLE_SIZE);
|
||||
int count = LZW_LITERALS;
|
||||
int width = BYTE_BITS;
|
||||
size_t offset = 0;
|
||||
|
||||
for (int i = 0; i < LZW_LITERALS; i++) table[i] = {1, LZW_NO_PREFIX, (char)i, (char)i};
|
||||
auto emit = [&](int code)
|
||||
{
|
||||
size_t end = bytes.size() + table[code].length;
|
||||
bytes.resize(end);
|
||||
for (int link = code; link != LZW_NO_PREFIX; link = table[link].prefix) bytes[--end] = table[link].last;
|
||||
};
|
||||
|
||||
while (bytes.size() < entry.size && offset + sizeof(uint32_t) <= packed.size())
|
||||
{
|
||||
size_t bitCount = word_get(packed, offset) * (size_t)BYTE_BITS;
|
||||
const uint8_t* bits = (const uint8_t*)packed.data() + offset + sizeof(uint32_t);
|
||||
size_t position = 0;
|
||||
offset += sizeof(uint32_t) + bitCount / BYTE_BITS;
|
||||
if (offset > packed.size()) return;
|
||||
auto code_read = [&](int codeWidth)
|
||||
{
|
||||
size_t first = position / BYTE_BITS;
|
||||
uint32_t window = 0;
|
||||
for (size_t i = first; i < first + LZW_WINDOW_BYTES; i++)
|
||||
window = window << BYTE_BITS | (i < bitCount / BYTE_BITS ? bits[i] : 0);
|
||||
int shift = LZW_WINDOW_BYTES * BYTE_BITS - (int)(position % BYTE_BITS) - codeWidth;
|
||||
position += codeWidth;
|
||||
return (int)(window >> shift & ((1u << codeWidth) - 1));
|
||||
};
|
||||
|
||||
int previous = code_read(width);
|
||||
emit(previous);
|
||||
while (true)
|
||||
{
|
||||
if (count >= LZW_RESET)
|
||||
{
|
||||
count = LZW_LITERALS;
|
||||
width = BYTE_BITS;
|
||||
previous = code_read(width);
|
||||
emit(previous);
|
||||
}
|
||||
if (bitCount - position < BYTE_BITS) break;
|
||||
while (1 << width <= count) width++;
|
||||
|
||||
int code = code_read(width);
|
||||
if (code > count) return;
|
||||
if (code == count || count < LZW_TABLE_SIZE)
|
||||
{
|
||||
char last = code == count ? table[previous].first : table[code].first;
|
||||
table[count++] = {table[previous].length + 1, previous, table[previous].first, last};
|
||||
}
|
||||
emit(code);
|
||||
previous = code;
|
||||
if (bitCount - position < BYTE_BITS) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Type 2 (FUN_00a89f80): one raw deflate stream over its chunks, then from the first full 1 KiB chunk that is not
|
||||
// the last, stored chunks XORed with the ISAAC stream the secondary hash seeds, a round per chunk.
|
||||
static void miniz_unpack(std::string_view packed, const ArchiveEntry& entry, std::string& bytes)
|
||||
{
|
||||
std::string deflated;
|
||||
std::unique_ptr<IsaacStream> keys;
|
||||
size_t offset = 0;
|
||||
auto inflate = [&]
|
||||
{
|
||||
deflated += DEFLATE_END;
|
||||
bytes.resize(entry.size);
|
||||
int size = deflated.empty() ? 0
|
||||
: stbi_zlib_decode_noheader_buffer(bytes.data(), (int)bytes.size(),
|
||||
deflated.data(), (int)deflated.size());
|
||||
bytes.resize(std::max(size, 0));
|
||||
};
|
||||
|
||||
while (offset + sizeof(uint32_t) <= packed.size() && bytes.size() < entry.size)
|
||||
{
|
||||
uint32_t header = word_get(packed, offset);
|
||||
uint32_t length = header & ~LAST_CHUNK;
|
||||
std::string_view chunk = packed.substr(std::min(offset + sizeof(uint32_t), packed.size()), length);
|
||||
offset += sizeof(uint32_t) + length;
|
||||
|
||||
if (!keys && length == STORED_CHUNK_SIZE && !(header & LAST_CHUNK))
|
||||
{
|
||||
keys = std::make_unique<IsaacStream>(entry.secondary);
|
||||
inflate();
|
||||
if (bytes.size() >= entry.size) break;
|
||||
}
|
||||
if (!keys)
|
||||
{
|
||||
deflated += chunk;
|
||||
if (header & LAST_CHUNK) break;
|
||||
continue;
|
||||
}
|
||||
|
||||
size_t at = bytes.size();
|
||||
auto key = (const char*)keys->results.data();
|
||||
keys->round_run();
|
||||
bytes.append(chunk);
|
||||
for (size_t i = 0; i < chunk.size(); i++) bytes[at + i] ^= key[i];
|
||||
}
|
||||
if (!keys) inflate();
|
||||
}
|
||||
|
||||
// Type 5: bytes XORed with the fixed key.
|
||||
static void secret_unpack(std::string_view packed, const ArchiveEntry& entry, std::string& bytes)
|
||||
{
|
||||
bytes.assign(packed.substr(0, entry.size));
|
||||
for (size_t i = 0; i < bytes.size(); i++) bytes[i] ^= (char)SECRET_KEY[i % SECRET_KEY.size()];
|
||||
}
|
||||
|
||||
// Up to length of an archive's raw bytes from start on.
|
||||
static bool archive_read(const Archive& archive, uint32_t start, uint32_t length, std::string& packed)
|
||||
{
|
||||
if (!archive.file)
|
||||
{
|
||||
packed = std::string_view(archive.bytes).substr(std::min<size_t>(start, archive.bytes.size()), length);
|
||||
return true;
|
||||
}
|
||||
if (std::fseek(archive.file, start, SEEK_SET) != 0) return false;
|
||||
packed.resize(length);
|
||||
packed.resize(std::fread(packed.data(), 1, length, archive.file));
|
||||
return true;
|
||||
}
|
||||
|
||||
// 00a68a50 An archived file's bytes, unpacked by its archive's type, with room after them for a parser's padding.
|
||||
static bool entry_read(const ArchiveEntry& entry, std::string& bytes)
|
||||
{
|
||||
const Archive& archive = archives[entry.archive];
|
||||
std::string packed;
|
||||
|
||||
bytes.clear();
|
||||
bytes.reserve(entry.size + READ_PADDING);
|
||||
if (!archive_read(archive, entry.start, entry.length, packed)) return false;
|
||||
switch (archive.type)
|
||||
{
|
||||
case ARCHIVE_XORSHIFT: xorshift_unpack(packed, entry, bytes); break;
|
||||
case ARCHIVE_LZW: lzw_unpack(packed, entry, bytes); break;
|
||||
case ARCHIVE_MINIZ: miniz_unpack(packed, entry, bytes); break;
|
||||
case ARCHIVE_SECRET: secret_unpack(packed, entry, bytes); break;
|
||||
default: return false;
|
||||
}
|
||||
bytes.resize(entry.size);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 00a179c0 (LoadArchiveFile) Indexes one archive, a file of an earlier one or on disk: its header, then a row per
|
||||
// file. A file's packed bytes run to the next file's start, the index or the end. False when it is missing or not an
|
||||
// archive.
|
||||
static bool archive_index(std::string_view name)
|
||||
{
|
||||
Archive& archive = archives.emplace_back();
|
||||
auto nested = archiveEntries.find(path_hash(BASE_MOUNT, name));
|
||||
std::string header;
|
||||
std::string rows;
|
||||
uint32_t end = 0;
|
||||
|
||||
if (nested != archiveEntries.end()) entry_read(nested->second, archive.bytes);
|
||||
else archive.file = std::fopen((dataDirectory + std::string(name)).c_str(), "rb");
|
||||
if (archive.file && std::fseek(archive.file, 0, SEEK_END) == 0) end = (uint32_t)std::ftell(archive.file);
|
||||
if (!archive.file) end = (uint32_t)archive.bytes.size();
|
||||
if (end < ARCHIVE_HEADER_SIZE || !archive_read(archive, 0, ARCHIVE_HEADER_SIZE, header) ||
|
||||
!header.starts_with(ARCHIVE_MAGIC))
|
||||
{
|
||||
if (archive.file) std::fclose(archive.file);
|
||||
archives.pop_back();
|
||||
return false;
|
||||
}
|
||||
|
||||
archive.type = (ArchiveType)header[ARCHIVE_TYPE_OFFSET];
|
||||
uint32_t indexOffset = word_get(header, ARCHIVE_INDEX_OFFSET);
|
||||
uint32_t count = word_get(header, ARCHIVE_COUNT_OFFSET) & UINT16_MAX;
|
||||
archive_read(archive, indexOffset, count * ARCHIVE_ROW_SIZE, rows);
|
||||
|
||||
std::vector<uint32_t> bounds = {indexOffset, end};
|
||||
for (size_t row = 0; row + ARCHIVE_ROW_SIZE <= rows.size(); row += ARCHIVE_ROW_SIZE)
|
||||
bounds.push_back(word_get(rows, row + ROW_START));
|
||||
std::ranges::sort(bounds);
|
||||
|
||||
for (size_t row = 0; row + ARCHIVE_ROW_SIZE <= rows.size(); row += ARCHIVE_ROW_SIZE)
|
||||
{
|
||||
ArchiveEntry entry;
|
||||
entry.secondary = word_get(rows, row + ROW_SECONDARY);
|
||||
entry.start = word_get(rows, row + ROW_START);
|
||||
entry.size = word_get(rows, row + ROW_SIZE);
|
||||
entry.archive = (uint16_t)(archives.size() - 1);
|
||||
auto next = std::ranges::upper_bound(bounds, entry.start);
|
||||
entry.length = next == bounds.end() ? 0 : *next - entry.start;
|
||||
archiveEntries[(uint64_t)word_get(rows, row) << 32 | entry.secondary] = entry;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// 009aa040 (IsaacStartup) Mounts the archives of an install's resources folder, indexing every file once. A language
|
||||
// archive (repentance_de.a) makes its language's mount.
|
||||
void archives_load()
|
||||
{
|
||||
for (std::string_view name : ARCHIVE_NAMES)
|
||||
{
|
||||
if (!archive_index(name)) continue;
|
||||
size_t separator = name.rfind(LANGUAGE_SEPARATOR);
|
||||
if (separator != std::string_view::npos)
|
||||
archiveLanguages.emplace_back(name.substr(separator + 1, name.find('.', separator) - separator - 1));
|
||||
}
|
||||
}
|
||||
|
||||
// Whether the resources are an install's, read from its packed archives. Its folders are only read.
|
||||
bool is_archive_mounted()
|
||||
{
|
||||
return !archives.empty();
|
||||
}
|
||||
|
||||
// A game path lowercased with forward slashes, as the game normalizes every path before a lookup. A path already under
|
||||
// the language's folder, the resources or the mods folder, which mods build from their script's path as the original's
|
||||
// absolute ones, stays there.
|
||||
static std::string path_normalize(std::string_view path)
|
||||
{
|
||||
std::string_view mods = platform.modsDirectory;
|
||||
bool isModsPath = !mods.empty() && path.starts_with(mods);
|
||||
if (isModsPath) path.remove_prefix(mods.size());
|
||||
else if (!languageDirectory.empty() && path.starts_with(languageDirectory))
|
||||
path.remove_prefix(languageDirectory.size());
|
||||
else if (path.starts_with(dataDirectory)) path.remove_prefix(dataDirectory.size());
|
||||
|
||||
std::string normalized(path);
|
||||
for (char& letter : normalized) letter = letter == '\\' ? '/' : (char)std::tolower((unsigned char)letter);
|
||||
if (isModsPath) normalized.insert(0, MODS_FOLDER);
|
||||
else if (normalized.starts_with(MODS_FROM_RESOURCES)) normalized.erase(0, PARENT_FOLDER.size());
|
||||
else if (normalized.starts_with(GAME_RESOURCES_FOLDER)) normalized.erase(0, GAME_RESOURCES_FOLDER.size());
|
||||
return normalized;
|
||||
}
|
||||
|
||||
// A file or folder under a directory by its lowercased path, each name matched without case, as the original's
|
||||
// FileMap (FileMap::scan_directory 00a687f0) matches them, when the exact one is missing. Empty when there is none.
|
||||
static std::string disk_find(std::string directory, std::string_view normalized)
|
||||
{
|
||||
std::error_code error;
|
||||
std::string exact = directory + std::string(normalized);
|
||||
|
||||
if (std::filesystem::exists(exact, error)) return exact;
|
||||
for (size_t start = 0; start < normalized.size();)
|
||||
{
|
||||
size_t end = std::min(normalized.find('/', start), normalized.size());
|
||||
auto [listing, isNew] = folderListings.try_emplace(directory);
|
||||
for (auto& entry : std::filesystem::directory_iterator(isNew ? directory : std::string(), error))
|
||||
{
|
||||
std::string name = entry.path().filename().string();
|
||||
std::string lowered = name;
|
||||
for (char& letter : lowered) letter = (char)std::tolower((unsigned char)letter);
|
||||
listing->second.emplace(lowered, name);
|
||||
}
|
||||
|
||||
auto found = listing->second.find(std::string(normalized.substr(start, end - start)));
|
||||
if (found == listing->second.end()) return "";
|
||||
directory += found->second + (end < normalized.size() ? "/" : "");
|
||||
start = end + 1;
|
||||
}
|
||||
return directory;
|
||||
}
|
||||
|
||||
// 00a16c60 (find_mount) The first of some game paths in the language's mount, then in the resources, each mount's
|
||||
// archives before its folder. A mod's files are only in its folder.
|
||||
static ResourceFile resource_find(std::initializer_list<std::string_view> paths)
|
||||
{
|
||||
ResourceFile file;
|
||||
std::pair<std::string_view, std::string_view> mounts[] = {{languageMount, languageDirectory},
|
||||
{BASE_MOUNT, dataDirectory}};
|
||||
std::vector<std::string> normalized;
|
||||
|
||||
for (std::string_view path : paths) normalized.push_back(path_normalize(path));
|
||||
for (auto [mount, directory] : mounts)
|
||||
for (std::string_view path : normalized)
|
||||
{
|
||||
bool isModsPath = path.starts_with(MODS_FOLDER) && !platform.modsDirectory.empty();
|
||||
if (isModsPath && mount == BASE_MOUNT)
|
||||
file.path = disk_find(platform.modsDirectory, path.substr(MODS_FOLDER.size()));
|
||||
if (!file.path.empty()) return file;
|
||||
if (isModsPath || directory.empty()) continue;
|
||||
|
||||
auto found = archiveEntries.empty() ? archiveEntries.end() : archiveEntries.find(path_hash(mount, path));
|
||||
if (found != archiveEntries.end()) file.entry = &found->second;
|
||||
else file.path = disk_find(std::string(directory), path);
|
||||
if (file.entry || !file.path.empty()) return file;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
// Where a game path is mounted, the key the caches keep it under: under the language's folder when that mount has
|
||||
// it, a mod's under the mods folder, under the resources otherwise.
|
||||
std::string resource_path(std::string_view path)
|
||||
{
|
||||
std::string normalized = path_normalize(path);
|
||||
std::error_code error;
|
||||
|
||||
if (normalized.starts_with(MODS_FOLDER) && !platform.modsDirectory.empty())
|
||||
return platform.modsDirectory + normalized.substr(MODS_FOLDER.size());
|
||||
if (!languageDirectory.empty() && (archiveEntries.contains(path_hash(languageMount, normalized)) ||
|
||||
std::filesystem::exists(languageDirectory + normalized, error)))
|
||||
return languageDirectory + normalized;
|
||||
return dataDirectory + normalized;
|
||||
}
|
||||
|
||||
// Whether a game path is mounted anywhere.
|
||||
bool resource_exists(std::string_view path)
|
||||
{
|
||||
ResourceFile file = resource_find({path});
|
||||
return file.entry || !file.path.empty();
|
||||
}
|
||||
|
||||
// 00a178d0 (FileSystem::Open) The bytes of the first of some game paths that the first mount holding any has, from
|
||||
// its archive or its file, with room after them for a parser's padding. False when none is mounted or it cannot be
|
||||
// read.
|
||||
bool resource_load_first(std::initializer_list<std::string_view> paths, std::string& bytes)
|
||||
{
|
||||
ResourceFile file = resource_find(paths);
|
||||
if (file.entry) return entry_read(*file.entry, bytes);
|
||||
|
||||
std::error_code error;
|
||||
bool isFile = !file.path.empty() && std::filesystem::is_regular_file(file.path, error);
|
||||
std::FILE* stream = isFile ? std::fopen(file.path.c_str(), "rb") : nullptr;
|
||||
if (!stream) return false;
|
||||
|
||||
std::fseek(stream, 0, SEEK_END);
|
||||
long size = std::max(std::ftell(stream), 0L);
|
||||
std::fseek(stream, 0, SEEK_SET);
|
||||
bytes.clear();
|
||||
bytes.reserve(size + READ_PADDING);
|
||||
bytes.resize(size);
|
||||
bytes.resize(std::fread(bytes.data(), 1, bytes.size(), stream));
|
||||
std::fclose(stream);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool resource_load(std::string_view path, std::string& bytes)
|
||||
{
|
||||
return resource_load_first({path}, bytes);
|
||||
}
|
||||
|
||||
// Where a file the repository ships itself lives: in assets/, beside the resources folder, or beside the folder the
|
||||
// executable is built into when the resources are an install's.
|
||||
std::string asset_path(std::string_view path)
|
||||
{
|
||||
std::filesystem::path folder = is_archive_mounted() ? SDL_GetBasePath() : dataDirectory.c_str();
|
||||
return (folder.parent_path().parent_path() / ASSETS_FOLDER / path).string();
|
||||
}
|
||||
|
||||
// 009abbd0 Remounts the resources, with the mount of the string table's language (009ab970) in front once there is a
|
||||
// manager. That mount is only made when the language has an archive or the import tool wrote its folder.
|
||||
// The original also mounts the game folder behind the resources when its file system already knows it. Nothing on
|
||||
// Linux reads from there.
|
||||
void reload_resource_paths()
|
||||
{
|
||||
languageDirectory.clear();
|
||||
languageMount.clear();
|
||||
if (!g_manager) return;
|
||||
|
||||
std::string code(Manager::GetLanguage());
|
||||
std::string localized = dataDirectory + std::string(LANGUAGE_FOLDER) + code + '/';
|
||||
std::error_code error;
|
||||
if (std::ranges::find(archiveLanguages, code) == archiveLanguages.end() &&
|
||||
!std::filesystem::is_directory(localized, error))
|
||||
return;
|
||||
|
||||
languageDirectory = localized;
|
||||
languageMount = std::string(LANGUAGE_MOUNT) + code + '/';
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <initializer_list>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
// The resources, and the language's own folder looked in first (empty while it has none).
|
||||
extern std::string dataDirectory;
|
||||
extern std::string languageDirectory;
|
||||
|
||||
void archives_load();
|
||||
bool is_archive_mounted();
|
||||
void reload_resource_paths();
|
||||
std::string resource_path(std::string_view path);
|
||||
std::string asset_path(std::string_view path);
|
||||
bool resource_exists(std::string_view path);
|
||||
bool resource_load(std::string_view path, std::string& bytes);
|
||||
bool resource_load_first(std::initializer_list<std::string_view> paths, std::string& bytes);
|
||||
+3
-5
@@ -3,8 +3,6 @@
|
||||
#include "engine/log.h"
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <tuple>
|
||||
|
||||
constexpr char FONT_MAGIC[] = "BMF";
|
||||
@@ -193,10 +191,10 @@ bool Font::Load(std::string_view path)
|
||||
{
|
||||
Unload();
|
||||
|
||||
std::ifstream stream(resource_path(path), std::ios::binary);
|
||||
std::string file((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
|
||||
std::string file;
|
||||
if (!resource_load(path, file)) return false;
|
||||
FontReader reader = {file, std::size(FONT_MAGIC) - 1};
|
||||
if (!stream || file.compare(0, reader.offset, FONT_MAGIC) != 0) return false;
|
||||
if (file.compare(0, reader.offset, FONT_MAGIC) != 0) return false;
|
||||
if (reader.read<uint8_t>() != FONT_VERSION) return false;
|
||||
|
||||
size_t slash = path.find_last_of(PATH_SEPARATORS);
|
||||
|
||||
@@ -122,14 +122,7 @@ static bool is_text_true(std::string_view text)
|
||||
// Calls visit with each attribute's name and text, in document order.
|
||||
template <typename Visit> static void attrs_visit(DataNode node, Visit visit)
|
||||
{
|
||||
simdjson::dom::object attrs;
|
||||
if (node["attrs"].get(attrs) != simdjson::SUCCESS) return;
|
||||
|
||||
for (simdjson::dom::key_value_pair attr : attrs)
|
||||
{
|
||||
std::string_view text;
|
||||
if (attr.value.get(text) == simdjson::SUCCESS) visit(attr.key, text);
|
||||
}
|
||||
for (auto [name, text] : node_attrs(node)) visit(name, text);
|
||||
}
|
||||
|
||||
// Calls visit with the children from the first one tagged tag on, as the game walks them: rapidxml's first_node(tag),
|
||||
|
||||
@@ -5,8 +5,6 @@
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
@@ -147,6 +145,16 @@ std::string path_key(std::string_view path)
|
||||
return key;
|
||||
}
|
||||
|
||||
// A file's image as RGBA texels, which stbi_image_free frees, or null when it is missing or does not decode.
|
||||
uint8_t* texels_load(std::string_view path, int& width, int& height)
|
||||
{
|
||||
std::string file;
|
||||
int channels = 0;
|
||||
|
||||
if (!resource_load(path, file)) return nullptr;
|
||||
return stbi_load_from_memory((stbi_uc*)file.data(), (int)file.size(), &width, &height, &channels, STBI_rgb_alpha);
|
||||
}
|
||||
|
||||
// 00a114d0 Sets one of the three blend modes, the source color factor depending on premultiplied alpha. Another type
|
||||
// leaves the mode as it was.
|
||||
void BlendMode::SetMode(BlendType type)
|
||||
@@ -977,28 +985,18 @@ bool Manager::shader_create(std::string_view shaderName, std::span<const VertexA
|
||||
return true;
|
||||
}
|
||||
|
||||
// Reads a whole file, false when it cannot be opened.
|
||||
static bool file_read(const std::string& path, std::string& text)
|
||||
{
|
||||
std::ifstream file(path, std::ios::binary | std::ios::ate);
|
||||
if (!file) return false;
|
||||
text.resize((size_t)file.tellg());
|
||||
file.seekg(0);
|
||||
return (bool)file.read(text.data(), (std::streamsize)text.size());
|
||||
}
|
||||
|
||||
// 00a147e0 Builds a shader from its two GLSL files, given as the paths in files, and caches it.
|
||||
bool Manager::shader_load(std::string_view shaderName, std::span<const VertexAttribute> attributes, ShaderSource files)
|
||||
{
|
||||
std::string vertex;
|
||||
std::string fragment;
|
||||
|
||||
if (!file_read(resource_path(files.vertex), vertex))
|
||||
if (!resource_load(files.vertex, vertex))
|
||||
{
|
||||
log_printf(LOG_ERROR, "Failed to load vertex shader '%s'\n", std::string(files.vertex).c_str());
|
||||
return false;
|
||||
}
|
||||
if (!file_read(resource_path(files.fragment), fragment))
|
||||
if (!resource_load(files.fragment, fragment))
|
||||
{
|
||||
log_printf(LOG_ERROR, "Failed to load pixel shader '%s'\n", std::string(files.fragment).c_str());
|
||||
return false;
|
||||
@@ -1200,14 +1198,12 @@ static bool extension_type_get(std::string_view path, ImageFileType& type)
|
||||
// file is missing or does not decode.
|
||||
ImagePtr Manager::image_load(std::string_view imagePath)
|
||||
{
|
||||
std::string resolved = resource_path(imagePath);
|
||||
std::error_code error;
|
||||
if (!std::filesystem::is_regular_file(resolved, error)) return nullptr;
|
||||
if (!resource_exists(imagePath)) return nullptr;
|
||||
if (ImagePtr cached = image_find(imagePath)) return cached;
|
||||
|
||||
ImageFileType type = FILE_PLATFORM;
|
||||
std::string file;
|
||||
if (!extension_type_get(imagePath, type) || !file_read(resolved, file)) return nullptr;
|
||||
if (!extension_type_get(imagePath, type) || !resource_load(imagePath, file)) return nullptr;
|
||||
|
||||
ImagePtr image = image_open({(const uint8_t*)file.data(), file.size()}, type, imagePath);
|
||||
if (!image) return nullptr;
|
||||
|
||||
@@ -388,6 +388,7 @@ public:
|
||||
extern Manager manager;
|
||||
|
||||
std::string path_key(std::string_view path);
|
||||
uint8_t* texels_load(std::string_view path, int& width, int& height);
|
||||
ColorQuad color_quad_rect(const Vector& position, const Vector& size, const KColor& color);
|
||||
SourceQuad source_quad_rect(const Vector& position, const Vector& size);
|
||||
bool is_quad_on_screen(const DestinationQuad& quad);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "engine/harness.h"
|
||||
#include "engine/platform.h"
|
||||
#include <SDL3/SDL_init.h>
|
||||
#include <SDL3/SDL_iostream.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
@@ -159,21 +160,26 @@ void Manager::Resume()
|
||||
if (output) SDL_ResumeAudioStreamDevice(output);
|
||||
}
|
||||
|
||||
// Opens a sound file into a source: a wav whole, an ogg whole or as a stream.
|
||||
static bool source_open(SoundSource& source, const std::string& file, bool isOgg)
|
||||
// Opens a sound file into a source: a wav whole, an ogg whole or as a stream over the file's bytes it keeps.
|
||||
static bool source_open(SoundSource& source, std::string_view path, bool isOgg)
|
||||
{
|
||||
if (!resource_load(path, source.file)) return false;
|
||||
if (!isOgg)
|
||||
{
|
||||
uint8_t* buffer = nullptr;
|
||||
uint32_t length = 0;
|
||||
if (!SDL_LoadWAV(file.c_str(), &source.spec, &buffer, &length)) return false;
|
||||
SDL_IOStream* stream = SDL_IOFromConstMem(source.file.data(), source.file.size());
|
||||
bool isLoaded = SDL_LoadWAV_IO(stream, true, &source.spec, &buffer, &length);
|
||||
source.file = {};
|
||||
if (!isLoaded) return false;
|
||||
source.samples.assign(buffer, buffer + length);
|
||||
SDL_free(buffer);
|
||||
return true;
|
||||
}
|
||||
|
||||
int error = 0;
|
||||
source.stream = stb_vorbis_open_filename(file.c_str(), &error, nullptr);
|
||||
auto bytes = (const unsigned char*)source.file.data();
|
||||
source.stream = stb_vorbis_open_memory(bytes, (int)source.file.size(), &error, nullptr);
|
||||
if (!source.stream) return false;
|
||||
stb_vorbis_info info = stb_vorbis_get_info(source.stream);
|
||||
source.spec = {SDL_AUDIO_S16, info.channels, (int)info.sample_rate};
|
||||
@@ -185,6 +191,7 @@ static bool source_open(SoundSource& source, const std::string& file, bool isOgg
|
||||
source.samples.assign((uint8_t*)decoded.data(), (uint8_t*)(decoded.data() + (size_t)frames * info.channels));
|
||||
stb_vorbis_close(source.stream);
|
||||
source.stream = nullptr;
|
||||
source.file = {};
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -214,7 +221,7 @@ std::shared_ptr<SoundSource> Manager::load_sound(std::string_view soundPath, Sou
|
||||
auto source = std::make_shared<SoundSource>();
|
||||
source->path = pathText;
|
||||
source->type = type;
|
||||
if (!source_open(*source, resource_path(soundPath), isOgg))
|
||||
if (!source_open(*source, soundPath, isOgg))
|
||||
{
|
||||
const char* kind = type == SOURCE_STREAM ? "stream" : "sample";
|
||||
log_printf(LOG_ERROR, "Failed to open %s \"%s\"\n", kind, pathText.c_str());
|
||||
|
||||
@@ -29,6 +29,7 @@ class SoundSource
|
||||
{
|
||||
public:
|
||||
std::vector<uint8_t> samples;
|
||||
std::string file;
|
||||
std::string path;
|
||||
SDL_AudioSpec spec = {};
|
||||
stb_vorbis* stream = nullptr;
|
||||
|
||||
@@ -178,8 +178,9 @@ static void folder_create(const std::string& path, const char* error)
|
||||
// 009a9510 Finds the save folder (SDL's per-user folder for the game) and the mods and mod data folders, removes the
|
||||
// mods folder older versions kept with the saves, moves loose online logs into online_logs/desyncs/ and notes the
|
||||
// folders in savedatapath.txt.
|
||||
// The game's own folder, where it kept mods/, data/ and savedatapath.txt, is resources/ here. Mod data goes with saves.
|
||||
// The harness's --mods replaces the mods folder.
|
||||
// The game's own folder, where it kept mods/, data/ and savedatapath.txt, is resources/ here, or the install's own
|
||||
// folder when the resources are an install's, which is only read: savedatapath.txt is left out there. Mod data goes
|
||||
// with saves. The harness's --mods replaces the mods folder.
|
||||
void Platform::directories_load()
|
||||
{
|
||||
char* prefPath = SDL_GetPrefPath("", SAVE_FOLDER.data());
|
||||
@@ -187,7 +188,8 @@ void Platform::directories_load()
|
||||
SDL_free(prefPath);
|
||||
if (userDataDirectory.empty()) SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", SAVE_FOLDER_ERROR, nullptr);
|
||||
|
||||
modsDirectory = harness.modsDirectory.empty() ? dataDirectory + "mods/" : harness.modsDirectory;
|
||||
std::string gameDirectory = is_archive_mounted() ? dataDirectory + "../" : dataDirectory;
|
||||
modsDirectory = harness.modsDirectory.empty() ? gameDirectory + "mods/" : harness.modsDirectory;
|
||||
modsSaveDirectory = userDataDirectory + "data/";
|
||||
folder_create(modsDirectory, "Modding data path %s is not a writable directory!");
|
||||
folder_create(modsSaveDirectory, "Modding save data path %s is not a writable directory!");
|
||||
@@ -204,7 +206,7 @@ void Platform::directories_load()
|
||||
std::filesystem::rename(entry.path(), std::filesystem::path(desyncs) / entry.path().filename(), result);
|
||||
}
|
||||
|
||||
FILE* info = std::fopen((dataDirectory + "savedatapath.txt").c_str(), "w");
|
||||
FILE* info = is_archive_mounted() ? nullptr : std::fopen((dataDirectory + "savedatapath.txt").c_str(), "w");
|
||||
if (!info) return;
|
||||
std::fputs(SAVE_PATHS_NOTICE, info);
|
||||
std::fprintf(info, "Save Data Path: %s\n", userDataDirectory.c_str());
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
#include "engine/platform.h"
|
||||
#include <SDL3/SDL_audio.h>
|
||||
#include <algorithm>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <ogg/ogg.h>
|
||||
#include <theora/theoradec.h>
|
||||
#include <vector>
|
||||
@@ -43,7 +43,7 @@ constexpr int CB_TO_BLUE = 132201;
|
||||
// Its time is the sound the device took, run on by the clock between the device's reads, or the clock alone.
|
||||
struct VideoClip
|
||||
{
|
||||
std::ifstream file;
|
||||
std::istringstream file;
|
||||
std::vector<float> samples;
|
||||
std::vector<uint8_t> texels;
|
||||
ogg_sync_state sync = {};
|
||||
@@ -340,8 +340,10 @@ bool VideoPlayer::load(const std::string& path)
|
||||
unload();
|
||||
|
||||
auto video = std::make_unique<VideoClip>();
|
||||
video->file.open(resource_path(path), std::ios::binary);
|
||||
if (!video->file || !video->headers_load())
|
||||
std::string bytes;
|
||||
bool isRead = resource_load(path, bytes);
|
||||
video->file.str(std::move(bytes));
|
||||
if (!isRead || !video->headers_load())
|
||||
{
|
||||
log_printf(LOG_INFO, "ERROR: Failed creating video clip: %s\n", path.c_str());
|
||||
return false;
|
||||
|
||||
@@ -189,11 +189,8 @@ static void backdrop_tint(ANM2& versus, uint32_t bossId1)
|
||||
const KAGE::Graphics::ImagePtr& sheet = versus.GetLayer(LAYER_BOSS_SPOT)->spriteSheet;
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
int channels = 0;
|
||||
stbi_uc* texels = nullptr;
|
||||
uint8_t* texels = sheet && sheet->isLoaded ? KAGE::Graphics::texels_load(sheet->path, width, height) : nullptr;
|
||||
|
||||
if (sheet && sheet->isLoaded)
|
||||
texels = stbi_load(resource_path(sheet->path).c_str(), &width, &height, &channels, STBI_rgb_alpha);
|
||||
if (!texels || width < 2)
|
||||
{
|
||||
layer_tint(versus, LAYER_BACKGROUND, 0, 0, 0);
|
||||
|
||||
@@ -86,10 +86,7 @@ constexpr std::array<BossPoolStage, 26> BOSS_POOL_STAGES = {{{"basement", 1},
|
||||
// Calls visit with each attribute of an element, in document order.
|
||||
template <class Visit> static void attrs_walk(DataNode node, Visit visit)
|
||||
{
|
||||
simdjson::dom::object attrs;
|
||||
if (node["attrs"].get(attrs) != simdjson::SUCCESS) return;
|
||||
|
||||
for (auto [name, value] : attrs) visit(name, value.get_string().value_unsafe());
|
||||
for (auto [name, value] : node_attrs(node)) visit(name, value);
|
||||
}
|
||||
|
||||
// Whether a boss id is one the pools track, as only those have a bit in the removed and blacklisted sets.
|
||||
|
||||
+5
-17
@@ -72,7 +72,7 @@ struct PlayerLoad
|
||||
std::string skinRoot;
|
||||
};
|
||||
|
||||
// Attribute text as atoi and atof read it. Every attribute is NUL-terminated where simdjson keeps it.
|
||||
// Attribute text as atoi and atof read it. Every attribute is NUL-terminated where the document keeps it.
|
||||
static int text_int(std::string_view text)
|
||||
{
|
||||
return text.empty() ? 0 : atoi(text.data());
|
||||
@@ -124,20 +124,15 @@ template <size_t N> static uint32_t flags_parse(std::string_view text, const std
|
||||
// Calls visit with each attribute's name and text.
|
||||
template <class Visit> static void attrs_walk(DataNode node, Visit visit)
|
||||
{
|
||||
simdjson::dom::object attrs;
|
||||
if (node["attrs"].get(attrs) != simdjson::SUCCESS) return;
|
||||
|
||||
for (auto [name, value] : attrs) visit(name, value.get_string().value_unsafe());
|
||||
for (auto [name, value] : node_attrs(node)) visit(name, value);
|
||||
}
|
||||
|
||||
// Calls visit with the children walk picks, in document order. A leaf has no children array to walk at all.
|
||||
// Calls visit with the children walk picks, in document order.
|
||||
template <class Visit> static void children_walk(DataNode node, std::string_view tag, ChildWalk walk, Visit visit)
|
||||
{
|
||||
simdjson::dom::array children;
|
||||
bool isFound = walk == CHILDREN_ALL;
|
||||
if (node["children"].get(children) != simdjson::SUCCESS) return;
|
||||
|
||||
for (DataNode child : children)
|
||||
for (DataNode child : node_children(node))
|
||||
{
|
||||
bool isTagged = node_tag(child) == tag;
|
||||
isFound = isFound || isTagged;
|
||||
@@ -154,13 +149,6 @@ static std::optional<DataNode> child_find(DataNode node, std::string_view tag)
|
||||
return found;
|
||||
}
|
||||
|
||||
static std::optional<std::string_view> attr_find(DataNode node, std::string_view name)
|
||||
{
|
||||
std::string_view value;
|
||||
if (node["attrs"][name].get(value) != simdjson::SUCCESS) return std::nullopt;
|
||||
return value;
|
||||
}
|
||||
|
||||
// The document's root element of a tag, logging its absence. The original goes on to read the missing root and crashes.
|
||||
static std::optional<DataNode> root_find(Data& data, std::string_view tag, std::string_view path)
|
||||
{
|
||||
@@ -441,7 +429,7 @@ bool EntityConfig::LoadEntities(std::string_view path, ModEntry* mod)
|
||||
path.data());
|
||||
|
||||
load.anm2Root = node_attr(*root, "anm2root");
|
||||
std::optional<std::string_view> deathAnm2 = attr_find(*root, "deathanm2");
|
||||
std::optional<std::string_view> deathAnm2 = node_attr_find(*root, "deathanm2");
|
||||
if (mod && deathAnm2)
|
||||
{
|
||||
mod->load_content_anm2(MOD_SPRITE_DEATH_ENEMIES, *deathAnm2);
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
#include "level/room_descriptor.h"
|
||||
#include "level/room_grid.h"
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
|
||||
// Lil Spewer's five kinds (its state): normal, white, red, black and yellow, each with its sheet, creep, charge tint and
|
||||
@@ -765,8 +764,7 @@ void minisaac_init(Entity_Familiar& minisaac)
|
||||
size_t dot = sheet.find_last_of('.');
|
||||
if (dot == std::string::npos) continue;
|
||||
std::string path = g_manager->modManager.TryRedirectPath(sheet.substr(0, dot) + std::string(suffix) + sheet.substr(dot));
|
||||
std::error_code error;
|
||||
if (std::filesystem::exists(resource_path(path), error)) minisaac.sprite.ReplaceSpritesheet(layer, path);
|
||||
if (resource_exists(path)) minisaac.sprite.ReplaceSpritesheet(layer, path);
|
||||
}
|
||||
minisaac.sprite.LoadGraphics();
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
#include "entity/weapon/weapon.h"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -448,8 +447,7 @@ void Entity_Familiar::delirium_morph()
|
||||
continue;
|
||||
std::string sheet = g_manager->modManager.TryRedirectPath(
|
||||
std::string(data->spriteSheetPath).insert(DELIRIUM_SHEET_PREFIX, DELIRIUM_SHEET_FOLDER));
|
||||
std::error_code error;
|
||||
if (!std::filesystem::exists(resource_path(sheet), error)) continue;
|
||||
if (!resource_exists(sheet)) continue;
|
||||
sprite.ReplaceSpritesheet(layer, sheet);
|
||||
isRecolored = true;
|
||||
}
|
||||
|
||||
@@ -35,7 +35,6 @@
|
||||
#include "entity/npc/alt.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#ifdef ISAAC_REPENTOGON
|
||||
#include "repentogon/callbacks.h"
|
||||
#include "repentogon/npc.h"
|
||||
@@ -868,7 +867,7 @@ std::string sheet_path_resolve(const std::string& path, std::string_view floorSu
|
||||
std::string stem = path.substr(0, path.size() - SHEET_EXTENSION_SIZE);
|
||||
std::string extension = path.substr(path.size() - SHEET_EXTENSION_SIZE);
|
||||
auto isFound = [&](const std::string& candidate) {
|
||||
return std::filesystem::exists(resource_path(g_manager->modManager.TryRedirectPath(candidate)));
|
||||
return resource_exists(g_manager->modManager.TryRedirectPath(candidate));
|
||||
};
|
||||
|
||||
std::string both = stem + std::string(championSuffix) + std::string(floorSuffix) + extension;
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
#include "entity/config.h"
|
||||
#include "game/manager.h"
|
||||
#include "ui/menu/manager.h"
|
||||
#include <filesystem>
|
||||
|
||||
// A spider rests 14 frames, then runs at its target (leading it) when near and in sight, else somewhere at random
|
||||
// within 70 to 110, keeping out of the walls. The jumping kinds leap there one time in three.
|
||||
@@ -282,7 +281,7 @@ bool spider_load_graphics(Entity_NPC& npc, std::string_view suffix)
|
||||
if (path.empty() || dot == std::string::npos) return false;
|
||||
|
||||
std::string redirected = g_manager->modManager.TryRedirectPath(path.substr(0, dot) + std::string(suffix) + path.substr(dot));
|
||||
if (!std::filesystem::exists(resource_path(redirected))) return false;
|
||||
if (!resource_exists(redirected)) return false;
|
||||
|
||||
std::string animation = npc.sprite.GetAnimation();
|
||||
npc.sprite.Load(redirected, GRAPHICS_LOAD);
|
||||
|
||||
@@ -151,30 +151,15 @@ static std::optional<DataNode> document_open_warned(Data& data, std::string_view
|
||||
return root;
|
||||
}
|
||||
|
||||
// An attribute's text, null-terminated, or nothing when the element lacks it.
|
||||
static std::optional<std::string_view> attr_find(DataNode node, std::string_view name)
|
||||
{
|
||||
std::string_view text;
|
||||
if (node["attrs"][name].get(text) != simdjson::SUCCESS) return std::nullopt;
|
||||
return text;
|
||||
}
|
||||
|
||||
static std::string_view attr_get(DataNode node, std::string_view name)
|
||||
{
|
||||
return attr_find(node, name).value_or("");
|
||||
return node_attr_find(node, name).value_or("");
|
||||
}
|
||||
|
||||
// Calls function with each attribute's name and text, in document order, as rapidxml's attribute walk visits them.
|
||||
template <class Function> static void attrs_each(DataNode node, Function function)
|
||||
{
|
||||
simdjson::dom::object attrs;
|
||||
if (node["attrs"].get(attrs) != simdjson::SUCCESS) return;
|
||||
|
||||
for (auto [name, value] : attrs)
|
||||
{
|
||||
std::string_view text;
|
||||
if (value.get(text) == simdjson::SUCCESS) function(name, text);
|
||||
}
|
||||
for (auto [name, text] : node_attrs(node)) function(name, text);
|
||||
}
|
||||
|
||||
// The game's bool attribute: "true", "True" or a nonzero number, so empty is false.
|
||||
@@ -211,7 +196,7 @@ static void value_parse(std::string_view text, std::string& value)
|
||||
// Reads an attribute into value, leaving value as it is when the element lacks it.
|
||||
template <class T> static void attr_read(DataNode node, std::string_view name, T& value)
|
||||
{
|
||||
if (auto text = attr_find(node, name)) value_parse(*text, value);
|
||||
if (auto text = node_attr_find(node, name)) value_parse(*text, value);
|
||||
}
|
||||
|
||||
// Calls function on each word between single spaces, as getline splits: doubled spaces give an empty word, a trailing
|
||||
@@ -648,11 +633,11 @@ static std::unique_ptr<ItemConfig_Item> item_parse(DataNode node, std::string_vi
|
||||
attr_read(node, "id", item->id);
|
||||
attr_read(node, "name", item->name);
|
||||
attr_read(node, "description", item->desc);
|
||||
if (auto gfx = attr_find(node, "gfx"))
|
||||
if (auto gfx = node_attr_find(node, "gfx"))
|
||||
item->gfxFilename = std::string(gfxRoot) + (item->IsTrinket() ? "trinkets/" : "collectibles/") += *gfx;
|
||||
attr_read(node, "achievement", item->achievementId);
|
||||
if (auto cache = attr_find(node, "cache")) item->cacheFlags |= cache_flags_parse(*cache);
|
||||
if (auto tags = attr_find(node, "tags")) item->tags = tags_parse(*tags);
|
||||
if (auto cache = node_attr_find(node, "cache")) item->cacheFlags |= cache_flags_parse(*cache);
|
||||
if (auto tags = node_attr_find(node, "tags")) item->tags = tags_parse(*tags);
|
||||
|
||||
attr_read(node, "maxhearts", item->addMaxHearts);
|
||||
attr_read(node, "hearts", item->addHearts);
|
||||
@@ -676,7 +661,7 @@ static std::unique_ptr<ItemConfig_Item> item_parse(DataNode node, std::string_vi
|
||||
attr_read(node, "hidden", item->isHidden);
|
||||
attr_read(node, "persistent", item->isPersistentEffect);
|
||||
|
||||
if (auto chargeType = attr_find(node, "chargetype"))
|
||||
if (auto chargeType = node_attr_find(node, "chargetype"))
|
||||
{
|
||||
if (*chargeType == "normal")
|
||||
item->chargeType = CHARGE_NORMAL;
|
||||
@@ -715,7 +700,7 @@ bool ItemConfig::Load(std::string_view path, ModEntry* mod)
|
||||
|
||||
std::string_view version = attr_get(*root, "version");
|
||||
std::string_view gfxRoot = attr_get(*root, "gfxroot");
|
||||
std::optional<std::string_view> deathAnm2 = attr_find(*root, "deathanm2");
|
||||
std::optional<std::string_view> deathAnm2 = node_attr_find(*root, "deathanm2");
|
||||
if (version != ITEMS_VERSION)
|
||||
log_print(LOG_ASSERT, "Invalid version %s for %s\n", version.data(), std::string(path).c_str());
|
||||
if (mod && deathAnm2) mod->load_content_anm2(MOD_SPRITE_DEATH_ITEMS, *deathAnm2);
|
||||
@@ -750,7 +735,8 @@ static ItemConfig_Costume costume_parse(DataNode node, std::string_view anm2Root
|
||||
|
||||
costume.id = 0;
|
||||
attr_read(node, "id", costume.id);
|
||||
if (auto anm2Path = attr_find(node, "anm2path")) costume.anm2Path = std::string(anm2Root) + std::string(*anm2Path);
|
||||
if (auto anm2Path = node_attr_find(node, "anm2path"))
|
||||
costume.anm2Path = std::string(anm2Root) + std::string(*anm2Path);
|
||||
attr_read(node, "priority", costume.priority);
|
||||
attr_read(node, "skinColor", costume.skinColor);
|
||||
attr_read(node, "hasOverlay", costume.isHasOverlay);
|
||||
@@ -862,9 +848,9 @@ bool ItemConfig::LoadCraftingRecipes(std::string_view path, ModEntry* mod)
|
||||
if (!root) return data.isLoaded;
|
||||
for (DataNode node : node_children(*root))
|
||||
{
|
||||
std::optional<std::string_view> input = attr_find(node, "input");
|
||||
std::optional<std::string_view> output = attr_find(node, "output");
|
||||
std::optional<std::string_view> outputName = attr_find(node, "outputName");
|
||||
std::optional<std::string_view> input = node_attr_find(node, "input");
|
||||
std::optional<std::string_view> output = node_attr_find(node, "output");
|
||||
std::optional<std::string_view> outputName = node_attr_find(node, "outputName");
|
||||
int outputId = 0;
|
||||
int pool = std::atoi(attr_get(node, "pool").data());
|
||||
|
||||
@@ -939,7 +925,7 @@ bool ItemConfig::LoadPocketItems(std::string_view path, ModEntry* mod)
|
||||
std::string_view tag = node_tag(node);
|
||||
CardType cardType = CARD_SPECIAL;
|
||||
|
||||
if (auto type = attr_find(node, "type")) cardType = card_type_parse(*type);
|
||||
if (auto type = node_attr_find(node, "type")) cardType = card_type_parse(*type);
|
||||
if (tag == "card" || tag == "rune")
|
||||
{
|
||||
auto card = std::make_unique<ItemConfig_Card>();
|
||||
@@ -968,7 +954,7 @@ bool ItemConfig::LoadPocketItems(std::string_view path, ModEntry* mod)
|
||||
auto pill = std::make_unique<ItemConfig_Pill>();
|
||||
pocket_item_parse(*pill, node, mod);
|
||||
attr_read(node, "announcer2", pill->announcerVoiceSuper);
|
||||
if (auto effectClass = attr_find(node, "class")) pill_class_parse(*pill, *effectClass);
|
||||
if (auto effectClass = node_attr_find(node, "class")) pill_class_parse(*pill, *effectClass);
|
||||
if (pill->id < 0)
|
||||
{
|
||||
log_print(LOG_INFO, "[warn] %s: Pill Effect ID %d out of range!\n", pathText.c_str(), pill->id);
|
||||
@@ -1003,8 +989,8 @@ bool ItemConfig::player_forms_load(std::string_view path)
|
||||
attr_read(node, "id", form->id);
|
||||
attr_read(node, "name", form->name);
|
||||
attr_read(node, "costume", form->costume);
|
||||
if (auto tags = attr_find(node, "tags")) form->tags = tags_parse(*tags);
|
||||
if (auto cache = attr_find(node, "cache")) form->cacheFlags = cache_flags_parse(*cache);
|
||||
if (auto tags = node_attr_find(node, "tags")) form->tags = tags_parse(*tags);
|
||||
if (auto cache = node_attr_find(node, "cache")) form->cacheFlags = cache_flags_parse(*cache);
|
||||
if (form->id >= 0 && form->id < (int)playerForms.size())
|
||||
playerForms[form->id] = std::move(form);
|
||||
else
|
||||
@@ -1113,7 +1099,7 @@ bool ItemConfig::LoadWispConfig(std::string_view path, ModEntry* mod)
|
||||
for (DataNode node : node_children(*root))
|
||||
{
|
||||
std::string_view tag = node_tag(node);
|
||||
std::optional<std::string_view> id = attr_find(node, "id");
|
||||
std::optional<std::string_view> id = node_attr_find(node, "id");
|
||||
std::unique_ptr<WispEntry>* slot = nullptr;
|
||||
|
||||
if (tag == "color") color_preset_load(presets, node);
|
||||
@@ -1239,7 +1225,7 @@ void ItemConfig::LoadLocustConfig(std::string_view path, ModEntry* mod)
|
||||
}
|
||||
if (tag != "locust") continue;
|
||||
|
||||
std::optional<std::string_view> id = attr_find(node, "id");
|
||||
std::optional<std::string_view> id = node_attr_find(node, "id");
|
||||
if (!id) continue;
|
||||
int collectibleId = mod_id_get(mod ? &mod->collectibleIdMap : nullptr, std::atoi(id->data()));
|
||||
if (ItemConfig_Item* item = item_find(collectibles, collectibleId, COLLECTIBLE_OUT_OF_BOUNDS))
|
||||
|
||||
@@ -152,14 +152,6 @@ static bool is_kind_allowed(ItemConfig_Item* item, uint32_t flags)
|
||||
return !((flags & POOL_FLAG_BAN_ACTIVES) && isActive) && !((flags & POOL_FLAG_BAN_PASSIVES) && !isActive);
|
||||
}
|
||||
|
||||
// An attribute's text, or nothing when the element lacks it.
|
||||
static std::optional<std::string_view> attr_find(DataNode node, std::string_view name)
|
||||
{
|
||||
std::string_view text;
|
||||
if (node["attrs"][name].get(text) != simdjson::SUCCESS) return std::nullopt;
|
||||
return text;
|
||||
}
|
||||
|
||||
// The children of node from the first with a tag on, as rapidxml's first_node(tag) then next_sibling() walks them.
|
||||
static std::vector<DataNode> elements_from(DataNode node, std::string_view tag)
|
||||
{
|
||||
@@ -174,15 +166,10 @@ static std::vector<DataNode> elements_from(DataNode node, std::string_view tag)
|
||||
static PoolItem pool_item_parse(DataNode node)
|
||||
{
|
||||
PoolItem item;
|
||||
simdjson::dom::object attrs;
|
||||
|
||||
if (node["attrs"].get(attrs) == simdjson::SUCCESS)
|
||||
for (auto [name, value] : attrs)
|
||||
{
|
||||
std::string_view text;
|
||||
if (value.get(text) != simdjson::SUCCESS) continue;
|
||||
|
||||
auto& names = g_manager->itemConfig.collectibleNameMap;
|
||||
|
||||
for (auto [name, text] : node_attrs(node))
|
||||
{
|
||||
if (name == "Id") item.itemId = std::atoi(text.data());
|
||||
if (name == "Weight") item.initialWeight = item.weight = (float)std::atof(text.data());
|
||||
if (name == "DecreaseBy") item.decreaseBy = (float)std::atof(text.data());
|
||||
@@ -305,7 +292,7 @@ void ItemPool::load_pools(std::string_view path, PoolsLoad load)
|
||||
|
||||
for (DataNode node : elements_from(*root, "Pool"))
|
||||
{
|
||||
std::optional<std::string_view> name = attr_find(node, "Name");
|
||||
std::optional<std::string_view> name = node_attr_find(node, "Name");
|
||||
if (!name) continue;
|
||||
|
||||
auto found = std::ranges::find(POOL_NAMES, *name);
|
||||
|
||||
@@ -472,8 +472,7 @@ static void trinket_icon_load(PlayerHUDTrinket& trinket)
|
||||
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
int channels = 0;
|
||||
stbi_uc* pixels = stbi_load(resource_path(trinket.image->path).c_str(), &width, &height, &channels, STBI_rgb_alpha);
|
||||
uint8_t* pixels = KAGE::Graphics::texels_load(trinket.image->path, width, height);
|
||||
std::array<uint8_t, TRINKET_ICON_PIXELS * TRINKET_ICON_PIXELS * RGBA> square{};
|
||||
for (int row = 0; pixels && row < std::min(height, TRINKET_ICON_PIXELS); row++)
|
||||
std::copy_n(pixels + (size_t)row * width * RGBA, std::min(width, TRINKET_ICON_PIXELS) * RGBA, square.begin() + row * TRINKET_ICON_PIXELS * RGBA);
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
#include "level/room_grid.h"
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <filesystem>
|
||||
#ifdef ISAAC_REPENTOGON
|
||||
#include "repentogon/player.h"
|
||||
#endif
|
||||
@@ -86,13 +85,6 @@ constexpr const char* CHARGE_BAR_PATHS[CHARGE_BAR_COUNT] = {
|
||||
"gfx/chargebar_poop.anm2", "gfx/chargebar_berserk.anm2",
|
||||
"gfx/chargebar_sumptorium.anm2"};
|
||||
|
||||
// Whether a resource file exists, after the mods redirected it.
|
||||
static bool is_file_found(const std::string& path)
|
||||
{
|
||||
std::error_code error;
|
||||
return std::filesystem::exists(resource_path(path), error);
|
||||
}
|
||||
|
||||
// A color from bytes as ColorParams::set_from_bytes builds it: a tint and an offset over 255, no colorize.
|
||||
static ColorMod color_from_bytes(int tintRed, int tintGreen, int tintBlue, int tintAlpha, int offsetRed,
|
||||
int offsetGreen, int offsetBlue)
|
||||
@@ -1555,7 +1547,7 @@ std::string costume_path_apply_skin_color(const std::string& path, int skinColor
|
||||
{
|
||||
std::string candidate = path.substr(0, slash) + "_" + playerConfig->costumeSuffixName + path.substr(slash);
|
||||
std::string redirected = g_manager->modManager.TryRedirectPath(candidate);
|
||||
if (is_file_found(redirected))
|
||||
if (resource_exists(redirected))
|
||||
{
|
||||
result = redirected;
|
||||
isPlayerFound = true;
|
||||
@@ -1571,7 +1563,7 @@ std::string costume_path_apply_skin_color(const std::string& path, int skinColor
|
||||
std::string_view suffix = SKIN_COLOR_SUFFIXES[skinColor < (int)SKIN_COLOR_SUFFIXES.size() ? skinColor : 0];
|
||||
std::string candidate = result.substr(0, dot) + std::string(suffix) + result.substr(dot);
|
||||
std::string redirected = g_manager->modManager.TryRedirectPath(candidate);
|
||||
if (is_file_found(redirected))
|
||||
if (resource_exists(redirected))
|
||||
{
|
||||
result = redirected;
|
||||
isSkinFound = true;
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
#include "game/sfx_manager.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#ifdef ISAAC_REPENTOGON
|
||||
#include "repentogon/callbacks.h"
|
||||
#endif
|
||||
@@ -1124,8 +1123,7 @@ static std::string suffixed_sheet_get(const std::string& path, const std::vector
|
||||
for (const std::string& suffix : suffixes)
|
||||
{
|
||||
std::string candidate = g_manager->modManager.TryRedirectPath(path.substr(0, stem) + suffix + path.substr(stem));
|
||||
std::error_code error;
|
||||
if (std::filesystem::exists(resource_path(candidate), error)) return candidate;
|
||||
if (resource_exists(candidate)) return candidate;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
+11
-19
@@ -211,14 +211,6 @@ void Game::LoadConfigXmls()
|
||||
game.console.reset();
|
||||
}
|
||||
|
||||
// An attribute when the element has it, empty or not.
|
||||
static std::optional<std::string_view> attr_find(DataNode node, std::string_view name)
|
||||
{
|
||||
std::string_view value;
|
||||
if (node["attrs"][name].get(value) != simdjson::SUCCESS) return std::nullopt;
|
||||
return value;
|
||||
}
|
||||
|
||||
// An attribute as the game reads booleans: "true", "True" or a nonzero number.
|
||||
static bool attr_bool(std::string_view value)
|
||||
{
|
||||
@@ -257,10 +249,10 @@ bool Game::load_giantbook_xml(std::string_view path)
|
||||
if (node_tag(node) != "entry") continue;
|
||||
GiantbookEntry entry;
|
||||
|
||||
if (auto text = attr_find(node, "id")) id = std::atoi(text->data());
|
||||
if (auto text = attr_find(node, "anm2")) entry.anm2Path = anm2Root + std::string(*text);
|
||||
if (auto text = attr_find(node, "anim")) entry.animation = *text;
|
||||
if (auto text = attr_find(node, "gfx")) entry.gfxPath = anm2Root + std::string(*text);
|
||||
if (auto text = node_attr_find(node, "id")) id = std::atoi(text->data());
|
||||
if (auto text = node_attr_find(node, "anm2")) entry.anm2Path = anm2Root + std::string(*text);
|
||||
if (auto text = node_attr_find(node, "anim")) entry.animation = *text;
|
||||
if (auto text = node_attr_find(node, "gfx")) entry.gfxPath = anm2Root + std::string(*text);
|
||||
|
||||
for (DataNode layerNode : node_children(node))
|
||||
{
|
||||
@@ -271,7 +263,7 @@ bool Game::load_giantbook_xml(std::string_view path)
|
||||
|
||||
layer.name = node_attr(layerNode, "name");
|
||||
for (size_t channel = 0; channel < TINT_ATTRIBUTES.size(); channel++)
|
||||
if (auto text = attr_find(layerNode, TINT_ATTRIBUTES[channel]))
|
||||
if (auto text = node_attr_find(layerNode, TINT_ATTRIBUTES[channel]))
|
||||
tint[channel] = (float)std::atoi(text->data()) / COLOR_CHANNEL_MAX;
|
||||
if (!layer.name.empty()) entry.layers.push_back(layer);
|
||||
}
|
||||
@@ -302,10 +294,10 @@ bool Game::load_bossoverlays_xml(std::string_view path)
|
||||
if (node_tag(node) != "entry") continue;
|
||||
BossOverlayEntry entry;
|
||||
|
||||
if (auto text = attr_find(node, "id")) entry.id = std::atoi(text->data());
|
||||
if (auto text = attr_find(node, "anm2")) entry.anm2Path = anm2Root + std::string(*text);
|
||||
if (auto text = attr_find(node, "anim")) entry.animation = *text;
|
||||
if (auto text = attr_find(node, "persist")) entry.isPersistent = attr_bool(*text);
|
||||
if (auto text = node_attr_find(node, "id")) entry.id = std::atoi(text->data());
|
||||
if (auto text = node_attr_find(node, "anm2")) entry.anm2Path = anm2Root + std::string(*text);
|
||||
if (auto text = node_attr_find(node, "anim")) entry.animation = *text;
|
||||
if (auto text = node_attr_find(node, "persist")) entry.isPersistent = attr_bool(*text);
|
||||
if ((unsigned)entry.id < BOSS_OVERLAY_COUNT) bossOverlay.entries[entry.id] = std::move(entry);
|
||||
}
|
||||
return true;
|
||||
@@ -345,8 +337,8 @@ void Game::LoadBossRushXml(std::string_view path)
|
||||
int count = 1;
|
||||
spawn.type = std::atoi(node_attr(enemyNode, "type").data());
|
||||
spawn.variant = std::atoi(node_attr(enemyNode, "variant").data());
|
||||
if (auto text = attr_find(enemyNode, "chunks")) spawn.chunks = std::atoi(text->data());
|
||||
if (auto text = attr_find(enemyNode, "count")) count = std::atoi(text->data());
|
||||
if (auto text = node_attr_find(enemyNode, "chunks")) spawn.chunks = std::atoi(text->data());
|
||||
if (auto text = node_attr_find(enemyNode, "count")) count = std::atoi(text->data());
|
||||
slot.insert(slot.end(), std::max(count, 0), spawn);
|
||||
}
|
||||
}
|
||||
|
||||
+4
-2
@@ -78,8 +78,9 @@ int IsaacMain(int argc, uint8_t** argv)
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The Linux entry point: "--resources <dir>" says where the imported game files are, "--mute" plays nothing, the
|
||||
// harness takes its flags, then the game's own main runs.
|
||||
// The Linux entry point: "--resources <dir>" says where the game files are (the import tool's folder, or an install's
|
||||
// resources folder with its packed archives, mounted here), "--mute" plays nothing, the harness takes its flags, then
|
||||
// the game's own main runs.
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
harness.arguments_load(argc, argv);
|
||||
@@ -89,5 +90,6 @@ int main(int argc, char** argv)
|
||||
else if (std::strcmp(argv[i], RESOURCES_FLAG) == 0 && i + 1 < argc)
|
||||
dataDirectory = std::string(argv[i + 1]) + "/";
|
||||
}
|
||||
archives_load();
|
||||
return IsaacMain(argc, (uint8_t**)argv);
|
||||
}
|
||||
@@ -758,13 +758,9 @@ bool Manager::LoadChallenges(std::string_view path, ChallengeSource source)
|
||||
if (!isFirstFound) continue;
|
||||
|
||||
ChallengeParam param;
|
||||
simdjson::dom::object attributes;
|
||||
param.isPathTypeSet = true;
|
||||
if (node["attrs"].get(attributes) == simdjson::SUCCESS)
|
||||
for (auto [name, text] : node_attrs(node))
|
||||
{
|
||||
for (auto [name, value] : attributes)
|
||||
{
|
||||
std::string_view text = value.get_string().value_unsafe();
|
||||
std::string nameText(name);
|
||||
auto found = CHALLENGE_ATTRIBUTES.find(name);
|
||||
|
||||
@@ -772,7 +768,6 @@ bool Manager::LoadChallenges(std::string_view path, ChallengeSource source)
|
||||
else if (found != CHALLENGE_ATTRIBUTES.end()) found->second(param, text);
|
||||
else log_printf(LOG_ASSERT, "Got invald parameter %s when reading challenges!\n", nameText.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
if (source == CHALLENGES_MOD) challengeParams.push_back(std::move(param));
|
||||
else if (challengeId >= 0 && challengeId < (int)challengeParams.size())
|
||||
|
||||
+13
-44
@@ -8,6 +8,7 @@
|
||||
#include "ui/menu/manager.h"
|
||||
#include "ui/pause_screen.h"
|
||||
#include "engine/platform.h"
|
||||
#include "pugixml.hpp"
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
@@ -135,30 +136,10 @@ static std::string text_lower(std::string text)
|
||||
return text;
|
||||
}
|
||||
|
||||
// Text as a JSON string.
|
||||
static std::string text_quote(std::string_view text)
|
||||
{
|
||||
std::string quoted = "\"";
|
||||
for (char letter : text)
|
||||
{
|
||||
char escaped[8];
|
||||
|
||||
if (letter == '"' || letter == '\\') quoted += '\\';
|
||||
if ((unsigned char)letter >= ' ') quoted += letter;
|
||||
else
|
||||
{
|
||||
std::snprintf(escaped, sizeof(escaped), "\\u%04x", letter);
|
||||
quoted += escaped;
|
||||
}
|
||||
}
|
||||
return quoted + '"';
|
||||
}
|
||||
|
||||
// Whether a game path exists under resources/, as itself or as a converted XML document.
|
||||
// Whether a game path is mounted, as itself or as a converted XML document.
|
||||
static bool is_resource_found(std::string_view path)
|
||||
{
|
||||
std::error_code error;
|
||||
return std::filesystem::exists(resource_path(path), error) || std::filesystem::exists(data_path(path), error);
|
||||
return resource_exists(path) || resource_exists(std::string(path) + std::string(JSON_EXTENSION));
|
||||
}
|
||||
|
||||
// A mod folder's twin, whose files win over the folder's own.
|
||||
@@ -168,14 +149,11 @@ static std::string dlc_folder_get(std::string_view folder)
|
||||
}
|
||||
|
||||
// The child elements with this tag, in document order.
|
||||
// The children are read here, since iterating node_children's empty array crashes on a leaf.
|
||||
static std::vector<DataNode> node_children_find(DataNode node, std::string_view tag)
|
||||
{
|
||||
std::vector<DataNode> found;
|
||||
simdjson::dom::array children;
|
||||
|
||||
if (node["children"].get(children) != simdjson::SUCCESS) return found;
|
||||
for (DataNode child : children)
|
||||
for (DataNode child : node_children(node))
|
||||
if (node_tag(child) == tag) found.push_back(child);
|
||||
return found;
|
||||
}
|
||||
@@ -229,10 +207,7 @@ static void metadata_load(ModEntry& mod, std::string& modPath)
|
||||
for (MetadataField field : METADATA_FIELDS)
|
||||
if (std::optional<DataNode> child = node_child_find(*metadata, field.tag)) mod.*field.field = node_text(*child);
|
||||
for (DataNode tag : node_children_find(*metadata, TAG_TAG))
|
||||
{
|
||||
std::string_view id;
|
||||
if (tag["attrs"][ID_ATTRIBUTE].get(id) == simdjson::SUCCESS) mod.tags.emplace_back(id);
|
||||
}
|
||||
if (std::optional<std::string_view> id = node_attr_find(tag, ID_ATTRIBUTE)) mod.tags.emplace_back(*id);
|
||||
}
|
||||
|
||||
// A mod read from its folder: its metadata (missing fields defaulted and written back), its folders, and whether it
|
||||
@@ -499,26 +474,20 @@ std::string ModEntry::GetContentPath(std::string_view fileName)
|
||||
return is_resource_found(dlcPath) ? dlcPath : contentDirectory + std::string(fileName);
|
||||
}
|
||||
|
||||
// 008f92b0 Writes the mod's metadata back as its converted metadata.xml, where the game reads it.
|
||||
// The original writes XML with rapidxml. This writes the JSON the import tool makes of it, blank text left out.
|
||||
// 008f92b0 Writes the mod's metadata back as its metadata.xml, tab-indented as rapidxml prints it.
|
||||
// The workshop id stays out of the file, as in the original.
|
||||
void ModEntry::WriteMetadata()
|
||||
{
|
||||
std::string children;
|
||||
pugi::xml_document document;
|
||||
pugi::xml_node metadata = document.append_child(METADATA_TAG);
|
||||
|
||||
for (MetadataField field : METADATA_FIELDS)
|
||||
{
|
||||
if (field.field == &ModEntry::metadataWorkshopID) continue;
|
||||
std::string& text = this->*field.field;
|
||||
bool isBlank = text.find_first_not_of(" \t\r\n") == std::string::npos;
|
||||
std::string textField = isBlank ? "" : ",\"text\":" + text_quote(text);
|
||||
children += "{\"tag\":\"" + std::string(field.tag) + '"' + textField + "},";
|
||||
}
|
||||
for (std::string& tag : tags) children += "{\"tag\":\"tag\",\"attrs\":{\"id\":" + text_quote(tag) + "}},";
|
||||
children.pop_back();
|
||||
if (field.field != &ModEntry::metadataWorkshopID)
|
||||
metadata.append_child(field.tag).text() = (this->*field.field).c_str();
|
||||
for (std::string& tag : tags) metadata.append_child(TAG_TAG).append_attribute(ID_ATTRIBUTE) = tag.c_str();
|
||||
|
||||
std::ofstream file(data_path(MODS_FOLDER + directory + METADATA_FILE));
|
||||
file << "{\"tag\":\"metadata\",\"children\":[" << children << "]}";
|
||||
std::string path = resource_path(MODS_FOLDER + directory + METADATA_FILE);
|
||||
document.save_file(path.c_str(), "\t", pugi::format_indent | pugi::format_no_declaration);
|
||||
}
|
||||
|
||||
// Writes disable.it into the mod's folder while the mod is off, and removes it once it is on (inlined in
|
||||
|
||||
@@ -221,20 +221,6 @@ static std::optional<DataNode> root_find(Data& data, std::string_view tag)
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// An element's attributes in document order, none when it has none.
|
||||
static simdjson::dom::object attrs_get(DataNode node)
|
||||
{
|
||||
simdjson::dom::object attrs;
|
||||
return node["attrs"].get(attrs) == simdjson::SUCCESS ? attrs : simdjson::dom::object();
|
||||
}
|
||||
|
||||
// An attribute's text, NUL-terminated as atoi needs.
|
||||
static std::string_view text_get(simdjson::dom::element value)
|
||||
{
|
||||
std::string_view text;
|
||||
return value.get(text) == simdjson::SUCCESS ? text : std::string_view("");
|
||||
}
|
||||
|
||||
// A file music.xml names, under its root, where the mods redirect it.
|
||||
static std::string path_redirect(std::string_view root, std::string_view path)
|
||||
{
|
||||
@@ -252,9 +238,8 @@ static MusicLayer layer_parse(DataNode node, std::string_view root)
|
||||
{
|
||||
MusicLayer layer;
|
||||
|
||||
for (auto [key, value] : attrs_get(node))
|
||||
for (auto [key, text] : node_attrs(node))
|
||||
{
|
||||
std::string_view text = text_get(value);
|
||||
if (key == "intro") layer.introPath = path_redirect(root, text);
|
||||
else if (key == "path") layer.path = path_redirect(root, text);
|
||||
else if (key == "mul") layer.volume = (float)std::atof(text.data());
|
||||
@@ -269,9 +254,8 @@ static MusicTrack track_parse(DataNode node, std::string_view root)
|
||||
MusicTrack track;
|
||||
MusicLayer attrLayer;
|
||||
|
||||
for (auto [key, value] : attrs_get(node))
|
||||
for (auto [key, text] : node_attrs(node))
|
||||
{
|
||||
std::string_view text = text_get(value);
|
||||
if (key == "id") track.id = std::atoi(text.data());
|
||||
else if (key == "name") track.name = text;
|
||||
else if (key == "intro") track.introPath = path_redirect(root, text);
|
||||
|
||||
+27
-12
@@ -112,6 +112,14 @@ static void option_read(KeyValueMap& map, const char* key, float& value)
|
||||
value = keyvalue_map_read_float(map, key, value);
|
||||
}
|
||||
|
||||
// The data format, by its name.
|
||||
static void option_read(KeyValueMap& map, const char* key, DataFormat& value)
|
||||
{
|
||||
std::string text = keyvalue_map_get(map, key);
|
||||
auto found = std::ranges::find(DATA_FORMAT_NAMES, text);
|
||||
if (found != std::end(DATA_FORMAT_NAMES)) value = (DataFormat)(found - std::begin(DATA_FORMAT_NAMES));
|
||||
}
|
||||
|
||||
// Ints and the enums options.ini stores as ints.
|
||||
template <typename T> static void option_read(KeyValueMap& map, const char* key, T& value)
|
||||
{
|
||||
@@ -125,6 +133,11 @@ static void line_write(std::string& text, const char* key, float value)
|
||||
text.append(line, std::snprintf(line, sizeof(line), "%s=%.4f\r\n", key, value));
|
||||
}
|
||||
|
||||
static void line_write(std::string& text, const char* key, DataFormat value)
|
||||
{
|
||||
text.append(key).append("=").append(DATA_FORMAT_NAMES[value]).append("\r\n");
|
||||
}
|
||||
|
||||
// Ints, bools and enums, all written as numbers.
|
||||
static void line_write(std::string& text, const char* key, int value)
|
||||
{
|
||||
@@ -157,20 +170,22 @@ void OptionsConfig::defaults_reset()
|
||||
// 00924180 Reads config.ini's effect switches, each on unless the file turns it off.
|
||||
void OptionsConfig::config_ini_load()
|
||||
{
|
||||
std::string text;
|
||||
render = {};
|
||||
std::optional<KeyValueMap> map = ini_load(resource_path(CONFIG_INI).c_str());
|
||||
if (!map) return;
|
||||
if (!resource_load(CONFIG_INI, text)) return;
|
||||
|
||||
option_read(*map, "EnableColorCorrection", render.isColorCorrectionEnabled);
|
||||
option_read(*map, "EnableCaustics", render.isCausticsEnabled);
|
||||
option_read(*map, "EnableShockwave", render.isShockwaveEnabled);
|
||||
option_read(*map, "EnableLighting", render.isLightingEnabled);
|
||||
option_read(*map, "EnableFilter", render.isFilterEnabled);
|
||||
option_read(*map, "EnablePixelation", render.isPixelationEnabled);
|
||||
option_read(*map, "EnableBloom", render.isBloomEnabled);
|
||||
option_read(*map, "EnableWaterSurface", render.isWaterSurfaceEnabled);
|
||||
option_read(*map, "EnableInterpolation", render.isInterpolationEnabled);
|
||||
option_read(*map, "EnableColorModifier", render.isColorModifierEnabled);
|
||||
KeyValueMap map = keyvalue_map_parse(text);
|
||||
|
||||
option_read(map, "EnableColorCorrection", render.isColorCorrectionEnabled);
|
||||
option_read(map, "EnableCaustics", render.isCausticsEnabled);
|
||||
option_read(map, "EnableShockwave", render.isShockwaveEnabled);
|
||||
option_read(map, "EnableLighting", render.isLightingEnabled);
|
||||
option_read(map, "EnableFilter", render.isFilterEnabled);
|
||||
option_read(map, "EnablePixelation", render.isPixelationEnabled);
|
||||
option_read(map, "EnableBloom", render.isBloomEnabled);
|
||||
option_read(map, "EnableWaterSurface", render.isWaterSurfaceEnabled);
|
||||
option_read(map, "EnableInterpolation", render.isInterpolationEnabled);
|
||||
option_read(map, "EnableColorModifier", render.isColorModifierEnabled);
|
||||
render.isWaterOverlayEnabled = render.isWaterSurfaceEnabled;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "engine/data.h"
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
@@ -94,6 +95,7 @@ struct OptionsConfig
|
||||
AnnouncerVoiceMode announcerVoiceMode = ANNOUNCER_VOICE_MODE_RANDOM;
|
||||
CameraStyle cameraStyle = CAMERA_STYLE_ACTIVE_CAM_ON;
|
||||
ConsoleFont consoleFont = CONSOLE_FONT_DEFAULT;
|
||||
DataFormat dataFormat = DATA_FORMAT_XML;
|
||||
ExtraHudStyle historyHudMode = EXTRA_HUD_STYLE_OFF;
|
||||
int eosCrossplay = 0;
|
||||
int jacobEsauControls = 1;
|
||||
@@ -202,6 +204,7 @@ template <typename Visit> void options_visit(OptionsConfig& options, Visit visit
|
||||
visit("UseExclusiveFullscreen", options.isExclusiveFullscreen);
|
||||
visit("EnableEpicOverlay", options.isEpicOverlayEnabled);
|
||||
visit("EosCrossplay", options.eosCrossplay);
|
||||
visit("DataFormat", options.dataFormat);
|
||||
}
|
||||
|
||||
std::string options_path();
|
||||
|
||||
@@ -8,14 +8,6 @@
|
||||
constexpr std::string_view ROOT_TAG = "preloads";
|
||||
constexpr std::string_view GROUP_TAG = "preload";
|
||||
|
||||
// An attribute when the element has it, empty or not.
|
||||
static std::optional<std::string_view> attr_find(DataNode node, std::string_view name)
|
||||
{
|
||||
std::string_view value;
|
||||
if (node["attrs"][name].get(value) != simdjson::SUCCESS) return std::nullopt;
|
||||
return value;
|
||||
}
|
||||
|
||||
// The first element of a document with a tag, as rapidxml's first_node finds it.
|
||||
static std::optional<DataNode> root_find(const Data& data, std::string_view tag)
|
||||
{
|
||||
@@ -46,12 +38,13 @@ bool PreloadManager::xml_load(std::string_view path)
|
||||
for (DataNode node : node_children(*root))
|
||||
{
|
||||
isStarted = isStarted || node_tag(node) == GROUP_TAG;
|
||||
std::optional<std::string_view> id = attr_find(node, "id");
|
||||
std::optional<std::string_view> id = node_attr_find(node, "id");
|
||||
if (!isStarted || !id) continue;
|
||||
|
||||
PreloadGroup& group = groups[std::string(*id)];
|
||||
for (DataNode child : node_children(node))
|
||||
if (auto imagePath = attr_find(child, "path")) group.entries.push_back({std::string(*imagePath), nullptr});
|
||||
if (auto imagePath = node_attr_find(child, "path"))
|
||||
group.entries.push_back({std::string(*imagePath), nullptr});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -24,7 +24,9 @@ static std::string text_lower(std::string_view text)
|
||||
// An attribute's text, or false when the element lacks it.
|
||||
static bool attr_find(DataNode node, std::string_view name, std::string_view& value)
|
||||
{
|
||||
return node["attrs"][name].get(value) == simdjson::SUCCESS;
|
||||
std::optional<std::string_view> found = node_attr_find(node, name);
|
||||
value = found.value_or(value);
|
||||
return found.has_value();
|
||||
}
|
||||
|
||||
// The first child named tag, as rapidxml's first_node finds it, or false.
|
||||
|
||||
@@ -289,13 +289,9 @@ static BackdropConfig config_load(DataNode node, const BackdropConfig& base, std
|
||||
std::string_view gridRoot)
|
||||
{
|
||||
BackdropConfig config = base;
|
||||
simdjson::dom::object attrs;
|
||||
|
||||
if (node["attrs"].get(attrs) != simdjson::SUCCESS) return config;
|
||||
for (auto field : attrs)
|
||||
for (auto [name, value] : node_attrs(node))
|
||||
{
|
||||
std::string_view name = field.key;
|
||||
std::string_view value = node_attr(node, name);
|
||||
std::string sheet = std::string(gfxRoot) + std::string(value);
|
||||
|
||||
if (name == "id") config.backdropId = attr_int(node, name);
|
||||
|
||||
+39
-126
@@ -7,7 +7,6 @@
|
||||
#include <algorithm>
|
||||
#include <bitset>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <optional>
|
||||
@@ -109,7 +108,7 @@ constexpr SplitRule SPLIT_RULES[] = {
|
||||
// the game never checks.
|
||||
struct StbReader
|
||||
{
|
||||
std::vector<char> bytes;
|
||||
std::string bytes;
|
||||
size_t position = 0;
|
||||
|
||||
void read(void* destination, size_t size)
|
||||
@@ -152,14 +151,6 @@ static std::string localized_get(std::string_view category, std::string_view tex
|
||||
return std::string(isMissing ? text : localized);
|
||||
}
|
||||
|
||||
// An attribute's text, or nothing when the element lacks it.
|
||||
static std::optional<std::string_view> attr_find(DataNode node, std::string_view name)
|
||||
{
|
||||
std::string_view text;
|
||||
if (node["attrs"][name].get(text) != simdjson::SUCCESS) return std::nullopt;
|
||||
return text;
|
||||
}
|
||||
|
||||
// A loaded document's root element, as rapidxml's first_node(tag) finds it, or nothing.
|
||||
static std::optional<DataNode> root_find(Data& data, std::string_view tag)
|
||||
{
|
||||
@@ -192,9 +183,9 @@ static std::string doors_text(uint32_t doors)
|
||||
// Reads a whole file of the game's resources, or nothing when it is missing.
|
||||
static std::optional<StbReader> file_read(std::string_view path)
|
||||
{
|
||||
std::ifstream stream(resource_path(path), std::ios::binary);
|
||||
if (!stream) return std::nullopt;
|
||||
return StbReader{std::vector<char>(std::istreambuf_iterator<char>(stream), {})};
|
||||
StbReader reader;
|
||||
if (!resource_load(path, reader.bytes)) return std::nullopt;
|
||||
return reader;
|
||||
}
|
||||
|
||||
static bool is_stb_header_read(StbReader& reader)
|
||||
@@ -384,27 +375,27 @@ bool RoomConfig::LoadStages(std::string_view path)
|
||||
std::optional<DataNode> root = root_find(data, "stages");
|
||||
if (!root) return false;
|
||||
|
||||
std::string roomsRoot(attr_find(*root, "root").value_or("rooms/"));
|
||||
std::string greedRoot(attr_find(*root, "greedroot").value_or("rooms/greed/"));
|
||||
std::string bossRoot(attr_find(*root, "bossgfxroot").value_or(""));
|
||||
std::string roomsRoot(node_attr_find(*root, "root").value_or("rooms/"));
|
||||
std::string greedRoot(node_attr_find(*root, "greedroot").value_or("rooms/greed/"));
|
||||
std::string bossRoot(node_attr_find(*root, "bossgfxroot").value_or(""));
|
||||
int id = 0;
|
||||
|
||||
for (DataNode node : elements_from(data, "stages", "stage"))
|
||||
{
|
||||
RoomConfig_Stage stage;
|
||||
|
||||
if (auto text = attr_find(node, "id")) id = std::atoi(text->data());
|
||||
if (auto text = attr_find(node, "name")) stage.displayName = *text;
|
||||
if (auto text = attr_find(node, "path"))
|
||||
if (auto text = node_attr_find(node, "id")) id = std::atoi(text->data());
|
||||
if (auto text = node_attr_find(node, "name")) stage.displayName = *text;
|
||||
if (auto text = node_attr_find(node, "path"))
|
||||
{
|
||||
stage.rooms[ROOM_MODE_NORMAL].filePath = roomsRoot + std::string(*text);
|
||||
stage.rooms[ROOM_MODE_GREED].filePath = greedRoot + std::string(*text);
|
||||
}
|
||||
if (auto text = attr_find(node, "playerspot")) stage.playerSpot = bossRoot + std::string(*text);
|
||||
if (auto text = attr_find(node, "bossspot")) stage.bossSpot = bossRoot + std::string(*text);
|
||||
if (auto text = attr_find(node, "music")) stage.musicId = std::atoi(text->data());
|
||||
if (auto text = attr_find(node, "backdrop")) stage.backdrop = std::atoi(text->data());
|
||||
if (auto text = attr_find(node, "suffix")) stage.suffix = *text;
|
||||
if (auto text = node_attr_find(node, "playerspot")) stage.playerSpot = bossRoot + std::string(*text);
|
||||
if (auto text = node_attr_find(node, "bossspot")) stage.bossSpot = bossRoot + std::string(*text);
|
||||
if (auto text = node_attr_find(node, "music")) stage.musicId = std::atoi(text->data());
|
||||
if (auto text = node_attr_find(node, "backdrop")) stage.backdrop = std::atoi(text->data());
|
||||
if (auto text = node_attr_find(node, "suffix")) stage.suffix = *text;
|
||||
|
||||
stage.id = id;
|
||||
if (id >= 0 && id < STAGE_SLOTS) stages[id] = std::move(stage);
|
||||
@@ -426,9 +417,9 @@ bool RoomConfig::LoadCurses(std::string_view path, CursesLoad load)
|
||||
|
||||
for (DataNode node : elements_from(data, "curses", "curse"))
|
||||
{
|
||||
std::string name(attr_find(node, "name").value_or(""));
|
||||
std::string name(node_attr_find(node, "name").value_or(""));
|
||||
|
||||
if (auto text = attr_find(node, "id")) id = std::atoi(text->data());
|
||||
if (auto text = node_attr_find(node, "id")) id = std::atoi(text->data());
|
||||
if (load == CURSES_APPEND) id = (int)curses.size();
|
||||
if (load == CURSES_APPEND) curses.push_back({name, id});
|
||||
else if (id >= 0 && id < (int)curses.size()) curses[id] = {name, id};
|
||||
@@ -447,9 +438,9 @@ bool RoomConfig::LoadMinibosses(std::string_view path)
|
||||
|
||||
for (DataNode node : elements_from(data, "minibosses", "miniboss"))
|
||||
{
|
||||
std::string name(attr_find(node, "name").value_or(""));
|
||||
std::string name(node_attr_find(node, "name").value_or(""));
|
||||
|
||||
if (auto text = attr_find(node, "id")) id = (uint32_t)std::atoi(text->data());
|
||||
if (auto text = node_attr_find(node, "id")) id = (uint32_t)std::atoi(text->data());
|
||||
if (id < MINIBOSS_SLOTS) minibosses[id] = {name, (int)id};
|
||||
}
|
||||
return true;
|
||||
@@ -503,94 +494,16 @@ void RoomConfig::ResetRoomWeights(int stageId, RoomMode mode)
|
||||
for (RoomConfig_Room& room : set.configs) room.weight = room.initialWeight;
|
||||
}
|
||||
|
||||
// An XML attribute value or name as JSON string text: its entities decoded, quotes, backslashes and controls escaped.
|
||||
static std::string xml_value_json(std::string_view text)
|
||||
{
|
||||
constexpr std::array<std::pair<std::string_view, char>, 5> ENTITIES = {
|
||||
{{"<", '<'}, {">", '>'}, {"&", '&'}, {""", '"'}, {"'", '\''}}};
|
||||
std::string json = "\"";
|
||||
|
||||
for (size_t i = 0; i < text.size(); i++)
|
||||
{
|
||||
char letter = text[i];
|
||||
for (auto [entity, decoded] : ENTITIES)
|
||||
{
|
||||
if (!text.substr(i).starts_with(entity)) continue;
|
||||
letter = decoded;
|
||||
i += entity.size() - 1;
|
||||
break;
|
||||
}
|
||||
if (letter == '"' || letter == '\\') json += '\\';
|
||||
if ((unsigned char)letter < ' ') json += std::format("\\u{:04x}", (int)letter);
|
||||
else json += letter;
|
||||
}
|
||||
return json + '"';
|
||||
}
|
||||
|
||||
// An XML document as the import tool's JSON (tag, attrs and children, under #document), for a file nothing converted.
|
||||
// Text, comments and declarations are left out, as no room file holds text.
|
||||
static std::string xml_json_get(std::string_view text)
|
||||
{
|
||||
constexpr std::string_view NAME_END = " \t\r\n/>";
|
||||
std::string json = "{\"tag\":\"#document\",\"attrs\":{},\"children\":[";
|
||||
std::vector<int> childCounts = {0};
|
||||
size_t pos = 0;
|
||||
|
||||
while ((pos = text.find('<', pos)) != std::string_view::npos && pos + 1 < text.size())
|
||||
{
|
||||
std::string_view rest = text.substr(pos);
|
||||
size_t end = rest.starts_with("<!--") ? text.find("-->", pos) : text.find('>', pos);
|
||||
if (rest[1] == '?' || rest[1] == '!' || end == std::string_view::npos)
|
||||
{
|
||||
pos = end;
|
||||
continue;
|
||||
}
|
||||
if (rest[1] == '/')
|
||||
{
|
||||
if (childCounts.size() > 1) json += "]}";
|
||||
if (childCounts.size() > 1) childCounts.pop_back();
|
||||
pos = end;
|
||||
continue;
|
||||
}
|
||||
|
||||
size_t nameEnd = text.find_first_of(NAME_END, pos + 1);
|
||||
json += childCounts.back()++ ? "," : "";
|
||||
json += "{\"tag\":" + xml_value_json(text.substr(pos + 1, nameEnd - pos - 1)) + ",\"attrs\":{";
|
||||
pos = nameEnd;
|
||||
for (bool isFirst = true;; isFirst = false)
|
||||
{
|
||||
pos = text.find_first_not_of(" \t\r\n", pos);
|
||||
if (pos == std::string_view::npos || text[pos] == '/' || text[pos] == '>') break;
|
||||
size_t equals = text.find('=', pos);
|
||||
size_t open = text.find_first_of("\"'", equals);
|
||||
size_t close = open == std::string_view::npos ? open : text.find(text[open], open + 1);
|
||||
if (close == std::string_view::npos) break;
|
||||
|
||||
std::string_view name = text.substr(pos, text.find_last_not_of(" \t\r\n=", equals) + 1 - pos);
|
||||
json += (isFirst ? "" : ",") + xml_value_json(name) + ":" +
|
||||
xml_value_json(text.substr(open + 1, close - open - 1));
|
||||
pos = close + 1;
|
||||
}
|
||||
json += "},\"children\":[";
|
||||
pos = text.find('>', pos);
|
||||
if (pos == std::string_view::npos) break;
|
||||
if (text[pos - 1] == '/') json += "]}";
|
||||
else childCounts.push_back(0);
|
||||
}
|
||||
for (size_t open = childCounts.size(); open > 1; open--) json += "]}";
|
||||
return json + "]}";
|
||||
}
|
||||
|
||||
// An attribute as rapidxml handed it to atoi: its text, or empty when the element lacks it.
|
||||
static int attr_int(DataNode node, std::string_view name)
|
||||
{
|
||||
return std::atoi(std::string(attr_find(node, name).value_or("")).c_str());
|
||||
return std::atoi(std::string(node_attr_find(node, name).value_or("")).c_str());
|
||||
}
|
||||
|
||||
// An attribute as atof read it, 0 when the element lacks it.
|
||||
static float attr_float(DataNode node, std::string_view name)
|
||||
{
|
||||
return (float)std::atof(std::string(attr_find(node, name).value_or("")).c_str());
|
||||
return (float)std::atof(std::string(node_attr_find(node, name).value_or("")).c_str());
|
||||
}
|
||||
|
||||
// 00829af0 (RoomConfigRoom::ParseXml) Reads a room element: its attributes, then for a typed room the doors that
|
||||
@@ -603,13 +516,13 @@ static void room_parse(DataNode node, RoomConfig_Room& room)
|
||||
room.type = attr_int(node, "type");
|
||||
room.variant = room.originalVariant = attr_int(node, "variant");
|
||||
room.subtype = attr_int(node, "subtype");
|
||||
room.name = attr_find(node, "name").value_or("");
|
||||
room.name = node_attr_find(node, "name").value_or("");
|
||||
room.difficulty = attr_int(node, "difficulty");
|
||||
room.weight = room.initialWeight = attr_float(node, "weight");
|
||||
room.flags = (uint32_t)attr_int(node, "flags");
|
||||
if (attr_find(node, "width")) room.width = (uint8_t)attr_int(node, "width");
|
||||
if (attr_find(node, "height")) room.height = (uint8_t)attr_int(node, "height");
|
||||
if (attr_find(node, "shape")) room.shape = (RoomShape)attr_int(node, "shape");
|
||||
if (node_attr_find(node, "width")) room.width = (uint8_t)attr_int(node, "width");
|
||||
if (node_attr_find(node, "height")) room.height = (uint8_t)attr_int(node, "height");
|
||||
if (node_attr_find(node, "shape")) room.shape = (RoomShape)attr_int(node, "shape");
|
||||
if (room.type == 0) return;
|
||||
|
||||
short doorX = 0;
|
||||
@@ -622,9 +535,9 @@ static void room_parse(DataNode node, RoomConfig_Room& room)
|
||||
std::string_view tag = node_tag(child);
|
||||
if (tag == "door")
|
||||
{
|
||||
if (attr_find(child, "x")) doorX = (short)attr_int(child, "x");
|
||||
if (attr_find(child, "y")) doorY = (short)attr_int(child, "y");
|
||||
if (auto text = attr_find(child, "exists"))
|
||||
if (node_attr_find(child, "x")) doorX = (short)attr_int(child, "x");
|
||||
if (node_attr_find(child, "y")) doorY = (short)attr_int(child, "y");
|
||||
if (auto text = node_attr_find(child, "exists"))
|
||||
isDoorExisting = *text == "true" || *text == "True" || attr_int(child, "exists") != 0;
|
||||
|
||||
int slot = isDoorExisting ? RoomConfig::get_door_from_position(doorX, doorY, room.shape) : DOOR_NONE;
|
||||
@@ -638,11 +551,11 @@ static void room_parse(DataNode node, RoomConfig_Room& room)
|
||||
for (DataNode entity : node_children(child))
|
||||
{
|
||||
if (node_tag(entity) != "entity") continue;
|
||||
if (attr_find(entity, "type")) entry.type = (uint32_t)attr_int(entity, "type");
|
||||
if (attr_find(entity, "variant")) entry.variant = (uint16_t)attr_int(entity, "variant");
|
||||
if (attr_find(entity, "subtype")) entry.subtype = (uint16_t)attr_int(entity, "subtype");
|
||||
if (attr_find(entity, "weight")) entry.weight = attr_float(entity, "weight");
|
||||
if (attr_find(entity, "weight")) spawn.sumWeights += entry.weight;
|
||||
if (node_attr_find(entity, "type")) entry.type = (uint32_t)attr_int(entity, "type");
|
||||
if (node_attr_find(entity, "variant")) entry.variant = (uint16_t)attr_int(entity, "variant");
|
||||
if (node_attr_find(entity, "subtype")) entry.subtype = (uint16_t)attr_int(entity, "subtype");
|
||||
if (node_attr_find(entity, "weight")) entry.weight = attr_float(entity, "weight");
|
||||
if (node_attr_find(entity, "weight")) spawn.sumWeights += entry.weight;
|
||||
|
||||
int slot = RoomConfig::get_door_from_position(spawn.x, spawn.y, room.shape);
|
||||
bool isQuestDoor = entry.type == ENTITY_ENVIRONMENT && entry.variant == QUEST_DOOR_VARIANT;
|
||||
@@ -656,9 +569,9 @@ static void room_parse(DataNode node, RoomConfig_Room& room)
|
||||
{ return a.y < b.y || (a.y == b.y && a.x < b.x); });
|
||||
}
|
||||
|
||||
// 00829710 Reads the room element of a room file, for the --load-room start option: its converted JSON through the
|
||||
// resources when the import tool converted it, else the XML file itself. An unreadable file gives an empty room, as
|
||||
// does a file without a room element, where the original crashes.
|
||||
// 00829710 Reads the room element of a room file, for the --load-room start option: a game path through the resources,
|
||||
// else the file itself. An unreadable file gives an empty room, as does a file without a room element, where the
|
||||
// original crashes.
|
||||
RoomConfig_Room RoomConfig::LoadRoomFromXmlFile(std::string_view path)
|
||||
{
|
||||
RoomConfig_Room room;
|
||||
@@ -668,13 +581,13 @@ RoomConfig_Room RoomConfig::LoadRoomFromXmlFile(std::string_view path)
|
||||
if (!data.isLoaded)
|
||||
{
|
||||
std::ifstream file{std::string(path), std::ios::binary};
|
||||
if (!file)
|
||||
std::string text{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
|
||||
if (!file.is_open())
|
||||
{
|
||||
log_printf(LOG_INFO, "[error] Could not open %s\n", std::string(path).c_str());
|
||||
return room;
|
||||
}
|
||||
std::string text{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
|
||||
data.isLoaded = data.parser.parse(xml_json_get(text)).get(data.root) == simdjson::SUCCESS;
|
||||
data_parse(data, text);
|
||||
}
|
||||
|
||||
std::optional<DataNode> root = root_find(data, "room");
|
||||
|
||||
@@ -302,14 +302,15 @@ static std::string module_path_find(std::string_view name, std::string& tried)
|
||||
|
||||
std::string scriptPath = lua_engine_get().scriptPath;
|
||||
std::string local = scriptPath.substr(0, scriptPath.find_last_of(PATH_SEPARATORS)) + "/" + module;
|
||||
std::string resource = resource_path(SCRIPTS_FOLDER + module);
|
||||
for (const std::string& path : {
|
||||
#ifdef ISAAC_REPENTOGON
|
||||
repentogon_script_path(module),
|
||||
#endif
|
||||
resource_path(SCRIPTS_FOLDER + module), local, platform.modsDirectory + local})
|
||||
resource, local, platform.modsDirectory + local})
|
||||
{
|
||||
std::error_code error;
|
||||
if (std::filesystem::exists(path, error)) return path;
|
||||
if (path == resource ? resource_exists(path) : std::filesystem::exists(path, error)) return path;
|
||||
tried += "\n\tno file '" + path + "'";
|
||||
}
|
||||
return "";
|
||||
@@ -329,7 +330,7 @@ static int module_require(lua_State* state)
|
||||
std::string tried;
|
||||
std::string path = module_path_find(name, tried);
|
||||
if (path.empty()) return luaL_error(state, "module '%s' not found:%s", name, tried.c_str());
|
||||
if (luaL_loadfile(state, path.c_str()) != LUA_OK)
|
||||
if (lua_script_load(state, path) != LUA_OK)
|
||||
return luaL_error(state, "error loading module '%s' from file '%s':\n\t%s", name, path.c_str(),
|
||||
lua_tostring(state, -1));
|
||||
|
||||
@@ -355,7 +356,7 @@ static int module_include(lua_State* state)
|
||||
if (path.empty()) return 1;
|
||||
|
||||
int top = lua_gettop(state);
|
||||
if (luaL_loadfile(state, path.c_str()) != LUA_OK) return luaL_error(state, "%s", lua_tostring(state, -1));
|
||||
if (lua_script_load(state, path) != LUA_OK) return luaL_error(state, "%s", lua_tostring(state, -1));
|
||||
lua_call(state, 0, LUA_MULTRET);
|
||||
return lua_gettop(state) - top;
|
||||
}
|
||||
|
||||
+13
-1
@@ -24,6 +24,7 @@ constexpr const char* SCRIPT_MODULES = "scripts/?.lua";
|
||||
constexpr const char* SCRIPT_FOLDER_MODULES = "/?.lua;";
|
||||
constexpr const char* UPDATE_MARKER = "/update.it";
|
||||
constexpr const char* PATH_SEPARATORS = "/\\";
|
||||
constexpr std::string_view BYTE_ORDER_MARK = "\xef\xbb\xbf";
|
||||
constexpr const char* RUN_CALLBACK = "_RunCallback";
|
||||
constexpr const char* UNLOAD_MOD = "_UnloadMod";
|
||||
|
||||
@@ -208,6 +209,17 @@ void LuaEngine::destroy()
|
||||
state = nullptr;
|
||||
}
|
||||
|
||||
// Loads a script as luaL_loadfile does: a file of the resources through them, archived or not, any other from disk.
|
||||
int lua_script_load(lua_State* state, const std::string& path)
|
||||
{
|
||||
std::string bytes;
|
||||
if (!path.starts_with(dataDirectory) || !resource_load(path, bytes)) return luaL_loadfile(state, path.c_str());
|
||||
|
||||
std::string_view chunk = bytes;
|
||||
if (chunk.starts_with(BYTE_ORDER_MARK)) chunk.remove_prefix(BYTE_ORDER_MARK.size());
|
||||
return luaL_loadbuffer(state, chunk.data(), chunk.size(), ("@" + path).c_str());
|
||||
}
|
||||
|
||||
// 0086e6c0 Runs a script file, after unloading the mods it registered when it last ran. In debug mode require searches
|
||||
// the script's folder first. An error is logged, and a mod registered with an API version other than 1 gets an
|
||||
// update.it in its folder. After a run Lua collects its garbage and logs its memory. Whether the script ran.
|
||||
@@ -233,7 +245,7 @@ bool LuaEngine::RunScript(std::string_view path)
|
||||
}
|
||||
scriptPath = file;
|
||||
scriptApiVersion = API_VERSION_NONE;
|
||||
bool isFailed = luaL_loadfile(state, file.c_str()) != LUA_OK || lua_pcall(state, 0, LUA_MULTRET, 0) != LUA_OK;
|
||||
bool isFailed = lua_script_load(state, file) != LUA_OK || lua_pcall(state, 0, LUA_MULTRET, 0) != LUA_OK;
|
||||
if (mode == LUA_MODE_DEBUG) package_field_set(state, "path", modulesPath);
|
||||
|
||||
if (!isFailed)
|
||||
|
||||
@@ -251,6 +251,7 @@ extern void* g_luaEngine;
|
||||
|
||||
const void* lua_class_key(LuaClass luaClass);
|
||||
void lua_error_log(lua_State* state, const char* name);
|
||||
int lua_script_load(lua_State* state, const std::string& path);
|
||||
bool is_input_hook_asked();
|
||||
|
||||
// The game's Lua engine, which Manager creates at startup.
|
||||
|
||||
+1
-6
@@ -12,7 +12,6 @@
|
||||
#include "engine/texture_cache.h"
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
constexpr std::string_view ANM2_PART_TAG = "anm2part";
|
||||
@@ -152,16 +151,12 @@ static uint32_t subtitle_time_get(std::string_view stamp)
|
||||
// four lines of text. A line ending the file is left out, as the game's reader reports the end before it.
|
||||
void CutscenePart::load_subtitles()
|
||||
{
|
||||
std::ifstream file(resource_path(subtitlesPath), std::ios::binary);
|
||||
std::stringstream contents;
|
||||
LineReader reader;
|
||||
|
||||
subtitles.clear();
|
||||
subtitleFrame = 0;
|
||||
subtitleIndex = 0;
|
||||
if (!file) return;
|
||||
contents << file.rdbuf();
|
||||
reader.text = contents.str();
|
||||
if (!resource_load(subtitlesPath, reader.text)) return;
|
||||
|
||||
while (!reader.is_end())
|
||||
{
|
||||
|
||||
@@ -123,13 +123,6 @@ void Menu_SpecialSeeds::LoadGraphics()
|
||||
specialSeedsSprite.Load(SEEDS_MENU_ANM2, GRAPHICS_LOAD);
|
||||
}
|
||||
|
||||
// Whether a node has an attribute at all, even an empty one.
|
||||
static bool node_has_attr(DataNode node, std::string_view name)
|
||||
{
|
||||
std::string_view value;
|
||||
return node["attrs"][name].get(value) == simdjson::SUCCESS;
|
||||
}
|
||||
|
||||
// The first child of a node with a tag, or the node itself when there is none.
|
||||
static DataNode node_child_find(DataNode node, std::string_view tag)
|
||||
{
|
||||
@@ -170,7 +163,7 @@ void Menu_SpecialSeeds::entries_load()
|
||||
std::string implemented(node_attr(node, IMPLEMENTED_ATTR));
|
||||
int id = std::atoi(std::string(node_attr(node, "id")).c_str());
|
||||
bool isKnown = id >= 0 && id < SPECIAL_SEED_COUNT;
|
||||
bool isImplemented = !node_has_attr(node, IMPLEMENTED_ATTR) ||
|
||||
bool isImplemented = !node_attr_find(node, IMPLEMENTED_ATTR) ||
|
||||
std::ranges::count(IMPLEMENTED_TRUE, implemented) || std::atoi(implemented.c_str());
|
||||
|
||||
if (isImplemented && isKnown && data.specialSeeds[id])
|
||||
|
||||
@@ -51,11 +51,6 @@ constexpr int STAGE_ICONS_PER_ALT_CHAPTER = 2;
|
||||
// The stage whose icon the void's slot shows again.
|
||||
constexpr int STAGE_VOID_SLOT = 10;
|
||||
|
||||
static bool is_attr_present(DataNode node, std::string_view name)
|
||||
{
|
||||
return node["attrs"][name].error() == simdjson::SUCCESS;
|
||||
}
|
||||
|
||||
// 0091fe80 Reads nightmares.xml, adding its nightmares to those known and shuffling their order, and loads the
|
||||
// progress bar and background unless loaded. Paths are under the root. False when the file is missing.
|
||||
bool NightmareScene::load_nightmares_xml(std::string_view path)
|
||||
@@ -67,11 +62,10 @@ bool NightmareScene::load_nightmares_xml(std::string_view path)
|
||||
|
||||
std::string root(node_attr(data.root, "root"));
|
||||
std::string progressPath = root + std::string(node_attr(data.root, "progressAnm2"));
|
||||
std::string backgroundPath =
|
||||
root + std::string(is_attr_present(data.root, "backgroundAnm2") ? node_attr(data.root, "backgroundAnm2")
|
||||
: BACKGROUND_DEFAULT);
|
||||
std::string background(node_attr_find(data.root, "backgroundAnm2").value_or(BACKGROUND_DEFAULT));
|
||||
std::string backgroundPath = root + background;
|
||||
for (DataNode node : node_children(data.root))
|
||||
if (node_tag(node) == "nightmare" && is_attr_present(node, "anm2"))
|
||||
if (node_tag(node) == "nightmare" && node_attr_find(node, "anm2"))
|
||||
nightmarePaths.push_back(root + std::string(node_attr(node, "anm2")));
|
||||
|
||||
if (!progressBarSprite.isLoaded) progressBarSprite.Load(progressPath, GRAPHICS_LOAD);
|
||||
|
||||
@@ -104,6 +104,7 @@ constexpr OptionSpec OPTION_SPECS[] = {
|
||||
{"TryImportSave", "Import save", OPTIONS_TAB_SYSTEM},
|
||||
{"AcceptedPublicBeta_v1.9.7.17", "Public beta accepted", OPTIONS_TAB_SYSTEM},
|
||||
{"AcceptedDataCollectionDisclaimer", "Data collection accepted", OPTIONS_TAB_SYSTEM},
|
||||
{"DataFormat", "Data format", OPTIONS_TAB_SYSTEM, 0, 2, "Auto\0JSON\0XML\0"},
|
||||
#ifdef ISAAC_REPENTOGON
|
||||
{"VanillaParity", "Vanilla parity", OPTIONS_TAB_REPENTOGON},
|
||||
{"SyncVanillaOptions", "Sync vanilla options", OPTIONS_TAB_REPENTOGON},
|
||||
|
||||
@@ -27,10 +27,9 @@ unsigned int Overlay::thumbnail_get(ModEntry& mod)
|
||||
|
||||
unsigned int texture = 0;
|
||||
int bound = 0;
|
||||
int channels = 0;
|
||||
int height = 0;
|
||||
int width = 0;
|
||||
if (stbi_uc* pixels = stbi_load(path.c_str(), &width, &height, &channels, STBI_rgb_alpha))
|
||||
if (uint8_t* pixels = KAGE::Graphics::texels_load(path, width, height))
|
||||
{
|
||||
gl.GetIntegerv(GL_TEXTURE_BINDING_2D, &bound);
|
||||
gl.GenTextures(1, &texture);
|
||||
|
||||
Reference in new issue
Block a user