-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLoader.cpp
More file actions
1807 lines (1645 loc) · 72.8 KB
/
Copy pathLoader.cpp
File metadata and controls
1807 lines (1645 loc) · 72.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "ClimaxEngine/Loader/ResourceLoader.h"
#include "ClimaxEngine/Core/RWS/RwStream.h"
#include "ClimaxEngine/SG/SceneObject.h"
#include "ClimaxEngine/Loader/Loader.h"
#include "ClimaxEngine/Render/GPUMesh.h"
#include "ClimaxEngine/Game/CameraLinks.h"
#include "ClimaxEngine/Core/RWS/FileSystem/CArchiveManager.h"
#include "ClimaxEngine/Core/Common.h"
static std::vector<MeshChunk> g_Chunks;
#include "ClimaxEngine/Platform/PS2/PS2Texture.h"
#include "ClimaxEngine/Platform/Wii/WiiTexture.h"
#include "ClimaxEngine/Platform/Wii/WiiGeometry.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <fstream>
#include <functional>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <iostream>
#include <map>
#include <set>
#include <vector>
// --- Utilits ---
std::vector<uint8_t> ReadWholeFile(const std::string &path) {
std::ifstream f(path, std::ios::binary | std::ios::ate);
if (!f)
return {};
const std::streamoff len = f.tellg();
if (len <= 0)
return {};
f.seekg(0);
std::vector<uint8_t> data((size_t)len);
if (!f.read((char *)data.data(), len))
return {};
return data;
}
// ------------------- LOADER LOGIC -------------------
// ---------------------------------------------------------------------------
// PS2 display-list geometry (see SH_FORMAT.md section 4)
//
// Geometry is a stream of VIF1 commands, not a vertex array. Each triangle strip
// is uploaded by one packet and then kicked with MSCAL:
//
// STCYCL 4,1 / UNPACK V3-32 or V4-32 imm 0x8000 positions
// STCYCL 4,1 / UNPACK V2-32 or V2-16 imm 0x8001 texture coords
// STCYCL 4,1 / UNPACK V4-8 imm 0xC002 vertex colours
// STCYCL 4,1 / UNPACK V3-8 imm 0x8003 normals
// ITOP / MSCAL
//
// Packets are located by anchoring on the position UNPACK. Two things about the
// search matter:
//
// * The scan must step one byte at a time. Packets are not aligned to any
// boundary: of the 887 packets in IntroRoad's first world section only 300
// begin at a 4-byte offset, the rest sit at offsets 1, 2 and 3.
// * The anchor must be the UNPACK, not STCYCL. The encoded STCYCL word occurs
// 3548 times inside vertex data in that same section.
// ---------------------------------------------------------------------------
static size_t g_DbgNoColor = 0;
namespace {
struct VifStream {
int vn = 0, vl = 0; // components - 1, element width selector
int num = 0; // vectors written
int addr = 0; // VU slot, 0..3
int bpv = 0; // bytes per vector
size_t dataOff = 0;
};
struct VifPacket {
size_t offset = 0;
std::vector<VifStream> streams;
int vertexCount = 0;
};
int BytesPerVector(int vn, int vl) {
if (vl == 3 && vn == 3)
return 2; // V4-5: four components packed into 16 bits
static const int BITS[4] = {32, 16, 8, 16};
return ((vn + 1) * BITS[vl] + 7) / 8;
}
bool IsPositionUnpack(uint32_t cmd) {
const uint32_t op = (cmd >> 24) & 0x7F;
if ((op & 0x60) != 0x60)
return false;
const int vn = (op >> 2) & 3, vl = op & 3;
return vl == 0 && (vn == 2 || vn == 3) && (cmd & 0xFFFF) == 0x8000;
}
// Reads one packet beginning at its position UNPACK. `after` receives the offset
// just past the MSCAL that ends it.
bool ReadPacket(const std::vector<uint8_t> &d, size_t p, size_t end,
VifPacket &out, size_t &after) {
auto word = [&](size_t o) {
uint32_t v;
memcpy(&v, &d[o], 4);
return v;
};
if (p + 4 > end || !IsPositionUnpack(word(p)))
return false;
out.offset = p;
out.streams.clear();
while (p + 4 <= end) {
const uint32_t cmd = word(p);
const uint32_t op = (cmd >> 24) & 0x7F;
const uint32_t num = (cmd >> 16) & 0xFF;
const uint32_t imm = cmd & 0xFFFF;
p += 4;
if (op == 0x14 || op == 0x15 || op == 0x17) { // MSCAL / MSCALF / MSCNT
after = p;
out.vertexCount = out.streams.empty() ? 0 : out.streams[0].num;
// A genuine packet uploads at least positions and one more stream.
return out.streams.size() >= 2;
}
if ((op & 0x60) == 0x60) {
VifStream s;
s.vn = (op >> 2) & 3;
s.vl = op & 3;
s.bpv = BytesPerVector(s.vn, s.vl);
s.num = num ? (int)num : 256;
s.addr = (int)(imm & 0x3FF);
s.dataOff = p;
// Streams within a packet all describe the same vertices.
if (!out.streams.empty() && s.num != out.streams[0].num)
return false;
if (s.addr > 3)
return false;
// CL=4 with WL=1 means CL >= WL, so every written vector has a source.
const size_t payload = ((size_t)s.num * s.bpv + 3) & ~size_t(3);
if (p + payload > end)
return false;
out.streams.push_back(s);
p += payload;
continue;
}
switch (op) {
case 0x00: case 0x01: case 0x02: case 0x03: // NOP STCYCL OFFSET BASE
case 0x04: case 0x05: case 0x06: case 0x07: // ITOP STMOD MSKPATH3 MARK
case 0x10: case 0x11: case 0x13: // FLUSHE FLUSH FLUSHA
continue;
case 0x20: p += 4; continue; // STMASK
case 0x30: case 0x31: p += 16; continue; // STROW STCOL
default:
return false; // not part of a vertex packet
}
}
return false;
}
} // namespace
// ---------------------------------------------------------------------------
// Two-pass transparency: "GreyAlpha_<base>" is a white-on-black mask that the
// game draws over the same geometry as <base>. Rather than replay the second
// pass, fold the mask's luminance into the base texture's alpha so the ordinary
// alpha test cuts the foliage out.
//
// NOTE: In release 0.1.1.5 this pass did not exist at all. Textures already
// carry the correct alpha in their CLUT (palette[transparent].alpha = 0).
// The merge loop was overwriting that correct alpha and making trees/wires
// appear as white squares. Removing the body restores 0.1.1.5 behaviour while
// keeping the Unswizzle4 fix that corrected the pine-tree texture decoding.
// ---------------------------------------------------------------------------
static void ApplyAlphaMasks() {
// Nothing to do — CLUT-decoded alpha is already correct for all textures.
(void)g_TexInfo;
}
// ---------------------------------------------------------------------------
// Shattered Memories containers
//
// Same chunk types as Origins, but with no 0x071C type directory and with the
// section header fields in big-endian. Geometry is GameCube native data and is
// not decoded yet; the texture dictionaries are, so a container loads as its
// full texture set plus a section listing.
//
// docs/SHSM_ARC_FORMAT.md section 4 has the layout and the figures behind it.
// ---------------------------------------------------------------------------
// Creates the GL objects for every chunk that does not have them yet. The
// Origins path builds its buffers as it goes; the Wii decoder produces plain
// vertex arrays and leaves the upload to here.
static void UploadChunks() {
for (auto &m : g_Chunks) {
if (GpuPeek(m) || m.vertices.empty()) continue;
GpuFor(m).Upload(m);
}
}
static bool IsShsmContainer(const std::vector<uint8_t> &d) {
if (d.size() < 64) return false;
auto le = [&](size_t o) {
return (uint32_t)d[o] | ((uint32_t)d[o + 1] << 8) |
((uint32_t)d[o + 2] << 16) | ((uint32_t)d[o + 3] << 24);
};
auto be = [&](size_t o) {
return ((uint32_t)d[o] << 24) | ((uint32_t)d[o + 1] << 16) |
((uint32_t)d[o + 2] << 8) | (uint32_t)d[o + 3];
};
// Origins opens with the 0x071C type directory; Shattered Memories opens
// straight with a section. The version word is not a discriminator -- 1698 of
// the 1857 containers in data.arc carry the same RW 3.7.0.2 build 0x0065 that
// Origins uses, and only 159 carry Climax's own 0x1802FFFF. What separates
// them is the byte order: reading the section header big-endian yields a
// plausible tag in all 1857, and nonsense lengths on an Origins container.
if (le(0) != 0x0716) return false;
const uint32_t tagLen = be(16);
if (tagLen > 1024 || 20 + tagLen + 20 >= d.size()) return false;
const uint32_t nameLen = be(20 + tagLen + 16);
if (nameLen >= 256 || 20 + tagLen + 20 + nameLen > d.size()) return false;
return d[20 + tagLen + 20] == 'r' && d[20 + tagLen + 21] == 'w';
}
static void ParseShsmContainer(const std::vector<uint8_t> &d) {
g_ContainerChunks.clear();
g_ShoTypes.clear();
g_ShoSections.clear();
g_Clumps.clear();
g_GameObjects.clear();
g_Sounds.clear();
ResetCollision(g_Collision);
auto le = [&](size_t o) -> uint32_t {
if (o + 4 > d.size()) return 0;
return (uint32_t)d[o] | ((uint32_t)d[o + 1] << 8) |
((uint32_t)d[o + 2] << 16) | ((uint32_t)d[o + 3] << 24);
};
auto be = [&](size_t o) -> uint32_t {
if (o + 4 > d.size()) return 0;
return ((uint32_t)d[o] << 24) | ((uint32_t)d[o + 1] << 16) |
((uint32_t)d[o + 2] << 8) | (uint32_t)d[o + 3];
};
size_t off = 0;
int objects = 0, textures = 0, meshes = 0;
size_t skipped = 0;
while (off + 12 <= d.size()) {
const uint32_t type = le(off);
const uint32_t size = le(off + 4);
if (size == 0 || off + 12 + size > d.size()) break;
if (type == 0x0704) {
objects++;
off += 12 + size;
continue;
}
if (type != 0x0716) {
off += 12 + size;
continue;
}
const size_t inner = off + 12;
const uint32_t headerSize = be(inner);
// Despite the name this length belongs to the asset's own name, the first
// of the header's two strings; the RenderWare type follows the GUID.
const uint32_t tagLen = be(inner + 4);
if (tagLen > 1024) { off += 12 + size; continue; }
const size_t guidOff = inner + 8 + tagLen;
const uint32_t nameLen = be(guidOff + 16);
ShoSection sec;
sec.offset = (uint32_t)off;
sec.size = size;
if (tagLen && inner + 8 + tagLen <= d.size()) {
const char *a = (const char *)&d[inner + 8];
sec.assetName.assign(a, strnlen(a, tagLen));
}
if (nameLen < 256 && guidOff + 20 + nameLen <= d.size()) {
const char *p = (const char *)&d[guidOff + 20];
sec.name.assign(p, strnlen(p, nameLen));
}
if (guidOff + 16 <= d.size())
sec.guid.assign((const char *)&d[guidOff], 16);
const size_t dataOff = inner + 4 + headerSize;
if (headerSize > 0 && dataOff + 8 <= d.size()) {
sec.dataStart = (uint32_t)dataOff;
sec.payloadSize = be(dataOff);
}
g_ShoSections.push_back(sec);
if (sec.name == "rwID_WORLD" && sec.dataStart + 4 + 12 <= d.size()) {
const size_t before = g_Chunks.size();
const size_t avail = d.size() - (sec.dataStart + 4);
const size_t len = sec.payloadSize && sec.payloadSize <= avail
? sec.payloadSize : avail;
// NOTE: the section is already in g_ShoSections, so the flag has to be
// set on the stored copy. Setting it on the local `sec` here left every
// stored section at isWorldSpace = false, and the renderer then hid all
// of them as unplaced models.
g_ShoSections.back().isWorldSpace = true;
WiiGeom::ReadWorld(d.data(), d.size(), sec.dataStart + 4, len,
(int)g_ShoSections.size() - 1, g_Chunks,
&g_MaterialNames);
meshes += (int)(g_Chunks.size() - before);
}
if ((sec.name == "rwID_CLUMP" || sec.name == "rwID_RWS") &&
sec.dataStart + 4 + 12 <= d.size()) {
// ReadClump bakes each atomic's composed frame matrix into its vertices,
// so the result is already in its final position and draws with identity.
// Marking it world-space is also what keeps it visible: the renderer
// hides a model section that no game object placed, and the Wii 0x0704
// records are not decoded yet.
g_ShoSections.back().isWorldSpace = true;
const size_t before = g_Chunks.size();
const size_t avail = d.size() - (sec.dataStart + 4);
const size_t len = sec.payloadSize && sec.payloadSize <= avail
? sec.payloadSize : avail;
WiiGeom::ReadClump(d.data(), d.size(), sec.dataStart + 4, len,
(int)g_ShoSections.size() - 1, g_Chunks,
&g_MaterialNames);
meshes += (int)(g_Chunks.size() - before);
}
if (sec.name == "rwID_TEXDICTIONARY" && sec.dataStart + 4 + 12 <= d.size()) {
const size_t avail = d.size() - (sec.dataStart + 4);
const size_t len = sec.payloadSize && sec.payloadSize <= avail
? sec.payloadSize : avail;
std::vector<uint8_t> wiiData(&d[sec.dataStart + 4], &d[sec.dataStart + 4 + len]);
Wii::WiiTextureDecoder().LoadDictionary(wiiData, {}, true);
textures++;
}
off += 12 + size;
}
// Ice and water are shaded by the GX TEV stages, which the container does
// not store -- the material only names a colour map and, sometimes, its
// frozen twin. The naming convention is the only marker in the data, so the
// surfaces are picked by name, the same hand-maintained approach the PS2
// effect sheets need.
static const char *kIceWords[] = {"ice", "frozen", "refract", "water"};
for (auto &c : g_Chunks) {
std::string low = c.texName;
for (auto &ch : low) ch = (char)tolower((unsigned char)ch);
for (const char *w : kIceWords)
if (low.find(w) != std::string::npos) { c.iceEffect = true; break; }
}
size_t tris = 0;
for (const auto &c : g_Chunks) tris += c.vertices.size() / 3;
std::cout << "[shsm] " << g_ShoSections.size() << " sections, " << objects
<< " game objects, " << textures << " textures, " << meshes
<< " meshes / " << tris << " triangles";
if (skipped)
std::cout << " (" << skipped << " paletted, not supported yet)";
std::cout << "\n";
}
void LoadLevelData(const std::string &displayName,
const std::vector<uint8_t> &container,
const std::vector<NamedBlob> &txds) {
std::vector<GLuint> uniqueIds;
for (auto &[name, id] : g_TextureMap)
if (std::find(uniqueIds.begin(), uniqueIds.end(), id) == uniqueIds.end())
uniqueIds.push_back(id);
if (!uniqueIds.empty())
glDeleteTextures((GLsizei)uniqueIds.size(), uniqueIds.data());
g_TextureMap.clear();
g_TexInfo.clear();
g_RawTextures.clear();
if (IsShsmContainer(container)) {
g_MaterialNames.clear();
g_MeshTexMap.clear();
g_Cameras.clear();
ParseShsmContainer(container);
return;
}
// Clear registrar for new level
ClimaxEngine::SG::CSceneObjectRegistrar::GetInstance().Clear();
// Parse sections (fills g_ShoSections)
ParseContainerStructureData(container);
// Use StreamLoader to process the entire container
ClimaxEngine::RWS::RwMemoryStream stream(container.data(), container.size());
ClimaxEngine::ResourceLoader::ResetWorldDedupe();
ClimaxEngine::ResourceLoader::CResourceHandler::GetInstance().ProcessStream(displayName.c_str(), &stream, container.size());
// Textures
for (const auto &[name, blob] : txds)
ClimaxEngine::Platform::PS2::PS2TextureDecoder().LoadDictionary(blob, g_MaterialNames, false);
std::vector<std::string> missing;
for (const auto &mat : g_MaterialNames)
if (g_TextureMap.find(mat) == g_TextureMap.end())
missing.push_back(mat);
if (!missing.empty())
for (const auto &[name, blob] : txds)
ClimaxEngine::Platform::PS2::PS2TextureDecoder().LoadDictionary(blob, missing, true);
if (g_TextureMap.empty())
ClimaxEngine::Platform::PS2::PS2TextureDecoder().LoadDictionary(container, g_MaterialNames, true);
ApplyAlphaMasks();
{
size_t m = 0;
for (auto &o : ClimaxEngine::SG::CSceneObjectRegistrar::GetInstance().GetObjects())
m += o->GetMeshes().size();
{
std::map<uint32_t, int> bm;
std::map<uint32_t, std::string> ex;
for (auto &o : ClimaxEngine::SG::CSceneObjectRegistrar::GetInstance().GetObjects())
for (auto *mc : o->GetMeshes()) {
bm[mc->blendMode]++;
if (mc->blendMode) ex[mc->blendMode] = mc->texName;
}
std::cout << "[scene] blend modes:";
for (auto &kv : bm)
std::cout << " " << kv.first << "=" << kv.second
<< (ex.count(kv.first) ? " (" + ex[kv.first] + ")" : "");
std::cout << "\n";
}
std::cout << "[scene] " << g_MaterialNames.size() << " material names, "
<< g_TextureMap.size() << " textures; registered "
<< ClimaxEngine::SG::CSceneObjectRegistrar::GetInstance().GetObjects().size()
<< " objects with " << m << " meshes in total\n";
}
g_CurrentMeshContainer = displayName;
g_CurrentTxdPaths.clear();
for (const auto &[name, blob] : txds)
g_CurrentTxdPaths.push_back(name);
// Re-instantiate Clumps based on g_ShoSections
auto& registrar = ClimaxEngine::SG::CSceneObjectRegistrar::GetInstance();
auto objects = registrar.GetObjects(); // Get a copy of the base objects
{
size_t withMeshes = 0, meshTotal = 0;
for (auto &o : objects) {
const size_t n = o->GetMeshes().size();
meshTotal += n;
if (n) withMeshes++;
}
std::cout << "[scene] loaders produced " << objects.size() << " objects, "
<< withMeshes << " of them carrying " << meshTotal << " meshes\n";
}
registrar.Clear(); // Clear so we can register the instanced versions
for (const auto& sec : g_ShoSections) {
// Find the base object parsed for this section
std::shared_ptr<ClimaxEngine::SG::CSceneObject> baseObj = nullptr;
std::string expectedName = std::to_string(sec.offset);
for (auto& obj : objects) {
if (obj->GetName() == expectedName || obj->GetName() == sec.name || obj->GetName() == (sec.name.empty() ? "WorldSpace" : sec.name)) {
baseObj = obj;
break;
}
}
if (!baseObj) {
std::cout << "[scene] section '" << sec.name << "' at " << sec.offset
<< " has no loaded object\n";
continue;
}
if (auto clump = std::dynamic_pointer_cast<ClimaxEngine::SG::CClumpObject>(baseObj)) {
if (clump->skeleton.bones.empty()) clump->skeleton = sec.skeleton;
if (clump->animClip.duration <= 0.0f) clump->animClip = sec.animClip;
}
if (sec.isWorldSpace || sec.instances.empty()) {
registrar.RegisterObject(baseObj);
}
if (!sec.isWorldSpace) {
for (size_t instIdx = 0; instIdx < sec.instances.size(); instIdx++) {
const auto& inst = sec.instances[instIdx];
std::string name = sec.name + "_Inst" + std::to_string(instIdx);
if (inst.gameObjectId >= 0 && inst.gameObjectId < (int)g_GameObjects.size()) {
name = g_GameObjects[inst.gameObjectId].instName;
}
if (auto clump = std::dynamic_pointer_cast<ClimaxEngine::SG::CClumpObject>(baseObj)) {
auto obj = std::make_shared<ClimaxEngine::SG::CClumpObject>(name);
obj->SetTransform(inst.transform);
obj->skeleton = clump->skeleton;
obj->animClip = clump->animClip;
if (inst.gameObjectId >= 0 && inst.gameObjectId < (int)g_GameObjects.size()) {
const auto& go = g_GameObjects[inst.gameObjectId];
if (!go.clipSectionIndices.empty()) {
int animIdx = go.clipSectionIndices[0];
if (animIdx >= 0 && animIdx < (int)g_ShoSections.size()) {
obj->animClip = g_ShoSections[animIdx].animClip;
}
}
}
for (auto* m : clump->GetMeshes()) {
MeshChunk copy = *m;
obj->AddMesh(std::move(copy));
}
registrar.RegisterObject(obj);
}
}
}
}
// Populate g_MeshTexMap
g_MeshTexMap.clear();
for (auto& obj : registrar.GetObjects()) {
for (auto* chunk : obj->GetMeshes()) {
const std::string &tName = chunk->texName;
g_MeshTexMap[tName.empty() ? "NULL" : tName].push_back(chunk);
}
}
}
// ── Path-based wrappers ─────────────────────────────────────────────────────
void LoadTexturesFromTxd(const std::string &txdPath,
const std::vector<std::string> &allowedNames,
bool fallback) {
ClimaxEngine::Platform::PS2::PS2TextureDecoder().LoadDictionary(ReadWholeFile(txdPath), allowedNames, fallback);
}
void LoadGeometry(const std::string &geomPath) {
std::vector<uint8_t> data = ReadWholeFile(geomPath);
ClimaxEngine::RWS::RwMemoryStream stream(data.data(), data.size());
ClimaxEngine::ResourceLoader::ResetWorldDedupe();
ClimaxEngine::ResourceLoader::CResourceHandler::GetInstance().ProcessStream(geomPath.c_str(), &stream, data.size());
}
void ParseContainerStructure(const std::string &path) {
ParseContainerStructureData(ReadWholeFile(path));
}
void LoadLevel(const std::string &meshContainerPath,
const std::vector<std::string> &txdPaths) {
std::vector<NamedBlob> txds;
txds.reserve(txdPaths.size());
for (const auto &p : txdPaths) {
auto blob = ReadWholeFile(p);
if (!blob.empty())
txds.emplace_back(p, std::move(blob));
}
LoadLevelData(meshContainerPath, ReadWholeFile(meshContainerPath), txds);
}
// ── Archive entry point ─────────────────────────────────────────────────────
bool LoadLevelFromArc(int entryIndex) {
if (!ClimaxEngine::RWS::FileSystem::CArchiveManager::GetInstance().GetFirstArchive() || entryIndex < 0 ||
entryIndex >= (int)ClimaxEngine::RWS::FileSystem::CArchiveManager::GetInstance().GetFirstArchive()->Entries().size())
return false;
const std::string &name = ClimaxEngine::RWS::FileSystem::CArchiveManager::GetInstance().GetFirstArchive()->Entries()[entryIndex].name;
std::vector<uint8_t> container;
if (!ClimaxEngine::RWS::FileSystem::CArchiveManager::GetInstance().GetFirstArchive()->Read((size_t)entryIndex, container) || container.empty()) {
std::cerr << "[arc] cannot inflate container '" << name << "'\n";
return false;
}
std::vector<NamedBlob> txds;
for (int ti : ClimaxEngine::RWS::FileSystem::CArchiveManager::GetInstance().GetFirstArchive()->TxdsFor(name)) {
std::vector<uint8_t> blob;
if (ClimaxEngine::RWS::FileSystem::CArchiveManager::GetInstance().GetFirstArchive()->Read((size_t)ti, blob) && !blob.empty())
txds.emplace_back(ClimaxEngine::RWS::FileSystem::CArchiveManager::GetInstance().GetFirstArchive()->Entries()[ti].name, std::move(blob));
}
std::cerr << "[arc] loading '" << name << "' (" << container.size()
<< " bytes) with " << txds.size() << " texture dictionaries\n";
LoadLevelData(name, container, txds);
return true;
}
// ============================================================
// SHO container structure parser — reads the REAL file header,
// enumerates all 0x716 sections, parses CBSP collision, clumps
// ============================================================
// ---------------------------------------------------------------------------
// 0x0704 — a placed game-object instance.
//
// The chunk body is a flat list of tagged records:
//
// [u32 recordSize][u32 recordId][payload (recordSize - 8 bytes)]
//
// The top byte of recordId selects the record kind, the low 24 bits are the
// property index within the current component:
//
// 0x20 component class name ("CPickupItem", "CStaticCamera", …)
// 0x40 16-byte GUID (usually a reference to a resource section)
// 0x80 instance / base-class name
// 0x00 indexed property
//
// Property 1 of the object's own component is a 64-byte, column-major 4x4 world
// matrix — this is the placement the viewer was missing, which is why every
// object used to sit at the origin. Names are padded with 0xBF filler bytes.
// ---------------------------------------------------------------------------
// True when a property payload holds designer text rather than binary.
//
// Names and GUIDs are both 16 bytes here, so length cannot separate them. A
// name is printable ASCII, at least three characters, followed by a terminator
// -- either NUL or the 0xBF padding this format uses. Requiring the terminator
// is what keeps four-byte floats out: a float whose bytes happen to be
// printable, like "333?", fills the payload with no room for one.
static bool IsNameProperty(const std::vector<uint8_t> &d, size_t off, size_t len) {
size_t k = 0;
while (k < len && d[off + k] >= 32 && d[off + k] < 127)
++k;
if (k < 3 || k >= len)
return false;
const uint8_t term = d[off + k];
return term == 0x00 || term == 0xBF;
}
static void ParseGameObject(const std::vector<uint8_t> &data, size_t off,
uint32_t size) {
const size_t sz = data.size();
const size_t body = off + 12;
const size_t bodyEnd = body + size;
if (bodyEnd > sz)
return;
auto ru32l = [&](size_t o) -> uint32_t {
uint32_t v;
memcpy(&v, &data[o], 4);
return v;
};
// Names are NUL-terminated and then padded with 0xBF up to the record size.
auto readName = [&](size_t o, size_t len) -> std::string {
size_t end = o;
while (end < o + len && data[end] != 0x00 && data[end] != 0xBF)
++end;
return std::string((const char *)&data[o], end - o);
};
GameObject go;
go.offset = (uint32_t)off;
bool haveClass = false;
bool haveXform = false;
// A 0x80 record is not the instance name -- it opens a new component and
// names its class. Property indices restart at 0 inside each one, because
// the engine's attribute iterator is filtered by class id, so an index means
// nothing without knowing which component it belongs to.
std::string component;
size_t p = body + 4; // the body opens with a 4-byte field we skip
while (p + 8 <= bodyEnd) {
const uint32_t rs = ru32l(p);
const uint32_t rid = ru32l(p + 4);
if (rs < 8 || p + rs > bodyEnd)
break;
const size_t payOff = p + 8;
const size_t payLen = rs - 8;
const uint32_t kind = rid >> 24;
const uint32_t idx = rid & 0x00FFFFFF;
if (kind == 0x20) {
if (!haveClass) {
go.className = readName(payOff, payLen);
haveClass = true;
}
} else if (kind == 0x80) {
component = readName(payOff, payLen);
if (go.instName.empty())
go.instName = component;
} else if (kind == 0x00 && payLen >= 4 && IsNameProperty(data, payOff, payLen)) {
// A designer-authored name. Checked before the GUID branch because both
// are 16 bytes wide -- a GUID is binary, a name is printable text with a
// terminator, so the content decides, not the length.
std::string nm = readName(payOff, payLen);
if (go.objName.empty())
go.objName = nm;
else
go.linkNames.push_back(nm);
} else if (kind == 0x00 && payLen == 16) {
go.guidRefs.emplace_back((const char *)&data[payOff], 16);
} else if (kind == 0x00 && payLen == 64 && component == "CZone" && idx == 3) {
// CZone carries its own 64-byte value as well. It is the zone's volume,
// not a placement -- measured on 120 containers: all 70 objects that hold
// two 64-byte properties are exactly (CSystemCommands, CZone) pairs.
memcpy(&go.volume[0][0], &data[payOff], 64);
go.haveVolume = true;
} else if (kind == 0x00 && idx == 2 && payLen == 4 &&
component == "CBaseCamera") {
// Field of view in degrees. Every camera class derives from
// Camera::CBaseCamera, and its HandleAttributes dispatches property 2
// straight into SetFOV__Q26Camera11CBaseCameraf -- the case is reached
// through a branch-likely (`beql $v0, $s2, ...` with $s2 = 2), which is
// why it stayed invisible until the disassembler learned that form.
//
// Reading it off the derived class instead was wrong: CStaticCamera's
// own property 4 is 90.0 on 420 of 473 objects, while CBaseCamera
// property 2 carries the values a level designer would actually pick --
// 46, 50, 52, 55, 60 and so on, 18 distinct across the archive.
memcpy(&go.fovDeg, &data[payOff], 4);
} else if (kind == 0x00 && idx == 1 && payLen == 64 &&
component == "CSystemCommands" && !haveXform) {
// The placement matrix always lives here: property 1 of the
// CSystemCommands component, in 3726 of 3726 placed objects across the
// sample. Keying on the index alone would let another component's
// 64-byte property win by arriving first.
glm::mat4 m;
memcpy(&m[0][0], &data[payOff], 64);
m[0][3] = 0.0f;
m[1][3] = 0.0f;
m[2][3] = 0.0f;
m[3][3] = 1.0f;
go.transform = m;
haveXform = true;
}
p += rs;
}
if (go.className.empty())
return;
if (haveXform) {
// Every class is placed the same way, so there is no list of "volume
// classes" to maintain. What made those classes look different is that
// they carry a *second* 64-byte property of their own; that one is now
// read separately as go.volume and never mistaken for a placement.
go.position = glm::vec3(go.transform[3]);
go.atOrigin = (glm::length(go.position) < 1e-4f);
}
// Second pass for CColorLight: the payload is spread over two components.
if (go.className == "CFogConfig") {
go.isFogConfig = true;
int group = 0;
long lastIdx = -1;
size_t q = body + 4;
while (q + 8 <= bodyEnd) {
const uint32_t rs = ru32l(q);
const uint32_t rid = ru32l(q + 4);
if (rid == 0x0711) {
size_t rq = q + 8;
const size_t rqEnd = rq + rs;
while (rq + 12 <= rqEnd) {
const uint32_t propType = ru32l(rq);
const uint32_t propSize = ru32l(rq + 4);
const uint32_t propId = ru32l(rq + 8);
if (propId <= lastIdx) group++;
lastIdx = propId;
const size_t payload = rq + 12;
if (propType == 2 && propSize == 4) { // Float
uint32_t bits = ru32l(payload);
float val;
std::memcpy(&val, &bits, 4);
if (propId == 2 && val >= 0.0f && val < 500.0f) go.fogStart = val;
if (propId == 3 && val > 0.0f && val < 500.0f) go.fogEnd = val;
if (propId == 5 && val >= 0.0f && val < 10.0f) go.fogDensity = val;
// These three are read as an RGB triple, and that reading is
// NOT established -- see the note below.
if (propId == 10 && val >= 0.0f && val <= 1.0f) go.fogColor.r = val;
if (propId == 11 && val >= 0.0f && val <= 1.0f) go.fogColor.g = val;
if (propId == 8 && val >= 0.0f && val <= 1.0f) go.fogColor.b = val;
}
rq += 12 + propSize;
}
}
q += 8 + rs;
}
// A stand-in, and it is worth being honest about what it stands in for.
//
// The game's fog is not this. CFogConfig property 0 is a *texture name* --
// `FX_fog_ALPHA` in IntroRoad and the Motel, `FX_fog2_ALPHA` in the Dahlia
// house -- so what the original draws is a configured sheet, not a depth
// fade tinted by an RGB triple. Nineteen properties describe it and this
// reads six of them.
//
// Treating 10/11/8 as r/g/b came from those three offsets (+0x9C, +0xA0,
// +0xA4) being adjacent floats with plausible defaults, not from reading
// the code that consumes them, and property 12 at +0x98 -- the float right
// before them -- is negative in IntroRoad (-0.2), so the four are not a
// colour block. Taken as a colour the values come out green in most levels,
// which does not match the game.
//
// So the clamp and this correction stay until the consumer is read. They
// are not a reading of the engine; they are what keeps the approximation
// looking like fog.
if (go.fogColor.g > go.fogColor.r * 1.5f || go.fogColor.g > go.fogColor.b * 1.5f ||
(go.fogColor.r <= 0.01f && go.fogColor.g <= 0.01f && go.fogColor.b <= 0.01f)) {
go.fogColor = glm::vec3(0.11f, 0.12f, 0.14f);
}
}
if (go.className == "CColorLight") {
go.isLight = true;
// Property indices restart at 0 for each component of the object, so a
// group boundary is simply "the index stopped increasing". That is more
// reliable than guessing which record type delimits a component.
int group = 0;
long lastIdx = -1;
size_t q = body + 4;
while (q + 8 <= bodyEnd) {
const uint32_t rs = ru32l(q);
const uint32_t rid = ru32l(q + 4);
if (rs < 8 || q + rs > bodyEnd)
break;
const size_t payOff = q + 8, payLen = rs - 8;
const uint32_t kind = rid >> 24, idx = rid & 0x00FFFFFF;
if (kind == 0x00) {
if ((long)idx <= lastIdx) {
++group;
}
lastIdx = (long)idx;
// The placement matrix, wherever its component sits.
if (payLen == 64) {
glm::mat4 mx;
memcpy(&mx, &data[payOff], 64);
go.lightPos = glm::vec3(mx[3]);
go.haveLightPos = true;
}
if (payLen == 4) {
float f;
memcpy(&f, &data[payOff], 4);
if (group == 0 && idx == 0) {
go.lightColor =
glm::vec3(data[payOff + 0] / 255.0f, data[payOff + 1] / 255.0f,
data[payOff + 2] / 255.0f);
} else if (group == 1) {
if (idx == 0)
memcpy(&go.lightType, &data[payOff], 4);
else if (idx == 1)
go.lightAngle = f;
else if (idx == 2)
go.lightRange = f;
}
}
}
q += rs;
}
}
go.label = go.className;
if (!go.instName.empty() && go.instName != go.className)
go.label += " (" + go.instName + ")";
g_GameObjects.push_back(std::move(go));
}
// Reads the container's UV animations out of its 0x2B sections.
//
// 0x2B is an RWS section type, not a RenderWare chunk id -- Ghost Rider names
// it outright, `CUVAnimationStreamLoader::GetTypeID` returns 0x2B. Inside sits
// a Struct holding the animation count, then one 0x1B chunk per animation whose
// payload is 88 bytes of header (the standard RtAnimAnimation fields, a 32-byte
// name, and a block of saved runtime pointers) followed by the keyframes.
//
// A keyframe is 32 bytes on disk; the 0x18 that `ClimaxT1KeyFrameStreamGetSizeCB`
// returns is the size it occupies in memory, which is smaller. The last word is
// the index of the previous keyframe, and following those links splits the
// frames into one chain per texture layer.
static void ParseUVAnimations(const std::vector<uint8_t> &data) {
const uint32_t RW_VER = 0x1c020065;
const size_t sz = data.size();
auto ru32 = [&](size_t o) -> uint32_t {
uint32_t v = 0;
if (o + 4 <= sz) memcpy(&v, &data[o], 4);
return v;
};
auto rf32 = [&](size_t o) -> float {
float v = 0.0f;
if (o + 4 <= sz) memcpy(&v, &data[o], 4);
return v;
};
// Scanned exhaustively rather than by walking chunk sizes: the 0x2B sections
// sit inside the container's shells, so a top-level walk steps straight over
// them. Byte-by-byte, not word-by-word — the sections are not word aligned
// (DH_1_Exterior has one at 1053589), so a stride of 4 misses them entirely.
for (size_t o = 0; o + 12 <= sz; o += 1) {
const uint32_t t = ru32(o), s = ru32(o + 4), v = ru32(o + 8);
if (t != 0x2B || v != RW_VER || s == 0 || o + 12 + s > sz) continue;
// Struct chunk carrying the animation count, then the animations.
size_t p = o + 12;
const uint32_t hdrSize = ru32(p + 4);
p += 12 + hdrSize;
while (p + 12 <= o + 12 + s) {
const uint32_t at = ru32(p), as = ru32(p + 4);
if (at != 0x1B || as == 0 || p + 12 + as > o + 12 + s) break;
const size_t h = p + 12;
const uint32_t numFrames = ru32(h + 8);
const float duration = rf32(h + 16);
std::string name;
for (size_t k = 0; k < 32 && data[h + 24 + k]; k++) name += (char)data[h + 24 + k];
// 20 bytes of RtAnimAnimation header + 68 of RpUVAnimCustomData, then
// the keyframes. RenderWare has two UV keyframe schemes and only the
// linear one is 32 bytes; the stride the data implies tells them apart.
const size_t keys = h + 88;
const uint32_t stride =
(numFrames && as > 88) ? (uint32_t)((as - 88) / numFrames) : 0;
if (numFrames && numFrames < 4096 && stride == 32 &&
keys + (size_t)numFrames * 32 <= h + as) {
UVAnimClip clip;
clip.duration = duration;
std::vector<UVAnimKey> flat(numFrames);
std::vector<uint32_t> prev(numFrames);
for (uint32_t k = 0; k < numFrames; k++) {
const size_t q = keys + k * 32;
flat[k].time = rf32(q);
flat[k].uScale = rf32(q + 8);
flat[k].vScale = rf32(q + 12);
flat[k].uOff = rf32(q + 20);
flat[k].vOff = rf32(q + 24);
prev[k] = ru32(q + 28);
}
// A frame whose previous index is not a real frame starts a new chain,
// and every other frame joins the chain its predecessor is in.
std::vector<int> layerOf(numFrames, -1);
for (uint32_t k = 0; k < numFrames; k++) {
if (prev[k] < numFrames && prev[k] != k && layerOf[prev[k]] >= 0)
layerOf[k] = layerOf[prev[k]];
else if (prev[k] >= numFrames) {
layerOf[k] = (int)clip.layers.size();
clip.layers.emplace_back();
}
}
for (uint32_t k = 0; k < numFrames; k++)
if (layerOf[k] >= 0) clip.layers[layerOf[k]].push_back(flat[k]);
if (!clip.layers.empty() && !name.empty()) {
for (auto &lay : clip.layers)
std::sort(lay.begin(), lay.end(),
[](const UVAnimKey &a, const UVAnimKey &b) { return a.time < b.time; });
g_UVAnims[name] = std::move(clip);
}
}
p += 12 + as;
}
}
if (!g_UVAnims.empty())
std::cout << "[uvanim] " << g_UVAnims.size() << " clips\n";
}
// Reads every skeletal animation clip in the container.
//
// Clips are 0x1B chunks sitting directly in the stream, not inside a 0x716
// shell, so the section walk never reaches them -- the same trap the UV
// animations sprang. Scanned byte-by-byte for the same reason: the chunks are
// not word aligned.
//
// Layout, confirmed by arithmetic over all 3029 clips in the archive: every one
// satisfies `chunkSize - records*20 - 20 == 24`, which is exactly the 20-byte
// RtAnimAnimation header, six floats of translation offset and scale, then one
// 20-byte record per keyframe.
// Byte offset each clip in g_AnimClips was scanned from, so a later pass can
// match it to the 0x0716 section that owns it and take its authored name.
static std::vector<size_t> g_AnimClipOffsets;
static void ParseSkeletalAnimations(const std::vector<uint8_t> &data) {
g_AnimClipOffsets.clear();
const uint32_t RW_VER = 0x1c020065;
const size_t sz = data.size();
auto ru32 = [&](size_t o) -> uint32_t {
uint32_t v = 0;
if (o + 4 <= sz) memcpy(&v, &data[o], 4);
return v;
};
auto rf32 = [&](size_t o) -> float {
float v = 0.0f;
if (o + 4 <= sz) memcpy(&v, &data[o], 4);
return v;
};
for (size_t o = 0; o + 32 <= sz; o += 1) {
if (ru32(o) != 0x1B || ru32(o + 8) != RW_VER) continue;
const uint32_t cs = ru32(o + 4);
if (cs < 44 || o + 12 + cs > sz) continue;
const size_t h = o + 12;
if (ru32(h) != 0x100) continue; // version
if (ru32(h + 4) != 0x1103) continue; // Climax keyframe scheme
const uint32_t records = ru32(h + 8);
const float duration = rf32(h + 16);
if (!records || records > 200000) continue;
if (!(duration > 0.0f && duration < 600.0f)) continue;
if (cs != 20 + 24 + records * 20) continue; // the layout must add up
float tOff[3], tScl[3];