forked from AdrienTD/c47edit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gameobj.cpp
1235 lines (1124 loc) · 36.7 KB
/
gameobj.cpp
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
// c47edit - Scene editor for HM C47
// Copyright (C) 2018 AdrienTD
// Licensed under the GPL3+.
// See LICENSE file for more details.
#include <functional>
#include <array>
#include <map>
#include <unordered_map>
#include "global.h"
#include "gameobj.h"
#include "chunk.h"
#include "vecmat.h"
#include "ByteWriter.h"
#include "classInfo.h"
#include <miniz/miniz.h>
std::unordered_map<GameObject*, size_t> g_objRefCounts;
Scene g_scene;
const char *objtypenames[] = {
// 0x00
"Z0", "ZGROUP", "ZSTDOBJ", "ZCAMERA",
"?", "?", "?", "?",
"?", "?", "?", "Z2DOBJ",
"?", "ZENVIRONMENT", "?", "?",
// 0x10
"?", "?", "ZSNDOBJ", "?",
"?", "?", "?", "?",
"?", "?", "ZLIST", "? ",
"?", "?", "?", "?",
// 0x20
"?", "ZROOM", "?", "ZSPOTLIGHT",
"?", "?", "?", "ZIKLNKOBJ",
"?", "?", "?", "ZEDITORGROUP",
"ZWINOBJ", "ZCHAROBJ", "ZWINGROUP", "ZFONT",
// 0x30
"ZWINDOWS", "ZWINDOW", "?", "ZBUTTON",
"?", "?", "?", "?",
"ZLINEOBJ", "?", "ZTTFONT", "ZSCROLLAREA",
"?", "?", "?", "?",
// 0x40
"ZSCROLLBAR", "ZSCALESTDOBJ", "?", "?",
"?", "?", "?", "?",
"?", "?", "?", "?",
"?", "?", "?", "?",
// 0x50
"?", "?", "?", "?",
"?", "?", "?", "?",
"?", "?", "?", "?",
"?", "?", "?", "?",
// 0x60
"?", "?", "?", "?",
"?", "?", "ZITEMGROUP", "?",
"?", "ZITEMGROUPWEAPON", "ZITEMGROUPAMMO", "?",
"?", "?", "?", "?",
};
const char *GetObjTypeString(uint32_t ot)
{
const char *otname = "?";
if (ot < std::size(objtypenames)) otname = objtypenames[ot];
return otname;
}
uint32_t ComputeBytesum(void* data, size_t length) {
uint32_t sum = 0;
uint8_t* bytes = (uint8_t*)data;
for (size_t i = 0; i < length; ++i)
sum += bytes[i];
return sum;
}
static void ReadAssetPacks(Scene* scene, mz_zip_archive* zip)
{
static const auto readFile = [](const char* filename) {
void* repmem; size_t repsize;
FILE* repfile = fopen(filename, "rb");
if (!repfile) ferr("Could not open Repeat.* file.\nBe sure you copied all the 4 files named \"Repeat\" (with .ANM, .DXT, .PAL, .WAV extensions) from the Hitman C47 game's folder into the editor's folder (where c47edit.exe is).");
fseek(repfile, 0, SEEK_END);
repsize = ftell(repfile);
fseek(repfile, 0, SEEK_SET);
repmem = malloc(repsize);
fread(repmem, repsize, 1, repfile);
fclose(repfile);
return std::make_pair(repmem, repsize);
};
const auto readPack = [&zip](const char* ext, Chunk& pack, bool* outFound = nullptr) {
std::string fnPackRepeat = std::string("PackRepeat.") + ext;
std::string fnRepeat = std::string("Repeat.") + ext;
std::string fnPack = std::string("Pack.") + ext;
void* packmem; size_t packsize;
packmem = mz_zip_reader_extract_file_to_heap(zip, fnPackRepeat.c_str(), &packsize, 0);
if (packmem)
{
auto [repmem, repsize] = readFile(fnRepeat.c_str());
pack = Chunk::reconstructPackFromRepeat(packmem, packsize, repmem);
free(repmem);
}
else
{
packmem = mz_zip_reader_extract_file_to_heap(zip, fnPack.c_str(), &packsize, 0);
if (!packmem && !outFound) ferr("Failed to find Pack.* or PackRepeat.* in ZIP archive.");
if (packmem)
pack.load(packmem);
}
if (outFound)
*outFound = packmem;
if (packmem)
free(packmem);
};
readPack("PAL", scene->palPack);
readPack("DXT", scene->dxtPack);
readPack("LGT", scene->lgtPack);
readPack("WAV", scene->wavPack);
readPack("ANM", scene->anmPack, &scene->hasAnmPack);
if (scene->palPack.tag != 'PAL') ferr("Not a PAL chunk in Repeat.PAL");
if (scene->dxtPack.tag != 'DXT') ferr("Not a DXT chunk in Repeat.DXT");
if (scene->lgtPack.tag != 'LGT') ferr("Not a LGT chunk in Repeat.LGT");
assert(scene->palPack.subchunks.size() == scene->dxtPack.subchunks.size());
}
void Scene::LoadEmpty()
{
Close();
// Duplicated :(
rootobj = new GameObject("Root", 0x21 /*ZROOM*/);
cliprootobj = new GameObject("ClipRoot", 0x21 /*ZROOM*/);
superroot = new GameObject("SuperRoot", 0x21);
superroot->subobj.push_back(rootobj);
superroot->subobj.push_back(cliprootobj);
rootobj->parent = cliprootobj->parent = superroot;
rootobj->root = rootobj;
cliprootobj->root = cliprootobj;
palPack.tag = 'PAL';
dxtPack.tag = 'DXT';
lgtPack.tag = 'LGT';
anmPack.tag = 'ANM';
wavPack.tag = 'WAV';
dlcFiles = { "GeomsBase.dlc", "EventsBase.dlc" };
scenePaths = { "Worlds", "Masters", "Z:\\c47edit", "Sounds", "" };
zdefValues.entries.emplace_back().type = DBLEntry::EType::TERMINATOR;
audioMgr.audioNames.resize(1);
audioMgr.audioObjects.resize(1);
ready = true;
}
void Scene::LoadSceneSPK(const char *fn)
{
Close();
FILE *zipfile = fopen(fn, "rb");
if (!zipfile) ferr("Could not open the ZIP file.");
fseek(zipfile, 0, SEEK_END);
size_t zipsize = ftell(zipfile);
fseek(zipfile, 0, SEEK_SET);
zipmem.resize(zipsize);
fread(zipmem.data(), zipsize, 1, zipfile);
fclose(zipfile);
mz_zip_archive zip; void *spkmem; size_t spksize;
mz_zip_zero_struct(&zip);
mz_bool mzreadok = mz_zip_reader_init_mem(&zip, zipmem.data(), zipsize, 0);
if (!mzreadok) ferr("Failed to initialize ZIP reading.");
spkmem = mz_zip_reader_extract_file_to_heap(&zip, "Pack.SPK", &spksize, 0);
if (!spkmem) ferr("Failed to extract Pack.SPK from ZIP archive.");
ReadAssetPacks(this, &zip);
mz_zip_reader_end(&zip);
Chunk spkchk;
spkchk.load(spkmem);
free(spkmem);
lastspkfn = fn;
Chunk* prot = spkchk.findSubchunk('TORP');
Chunk* pclp = spkchk.findSubchunk('PLCP');
Chunk* phea = spkchk.findSubchunk('AEHP');
Chunk* pnam = spkchk.findSubchunk('MANP');
Chunk* ppos = spkchk.findSubchunk('SOPP');
Chunk* pmtx = spkchk.findSubchunk('XTMP');
Chunk* pver = spkchk.findSubchunk('REVP');
Chunk* pfac = spkchk.findSubchunk('CAFP');
Chunk* pftx = spkchk.findSubchunk('XTFP');
Chunk* puvc = spkchk.findSubchunk('CVUP');
Chunk* pdbl = spkchk.findSubchunk('LBDP');
Chunk* pdat = spkchk.findSubchunk('TADP');
Chunk* pexc = spkchk.findSubchunk('CXEP');
if (!(prot && pclp && phea && pnam && ppos && pmtx && pver && pfac && pftx && puvc && pdbl && pdat && pexc))
ferr("One or more important chunks were not found in Pack.SPK .");
rootobj = new GameObject("Root", 0x21 /*ZROOM*/);
cliprootobj = new GameObject("ClipRoot", 0x21 /*ZROOM*/);
superroot = new GameObject("SuperRoot", 0x21);
superroot->subobj.push_back(rootobj);
superroot->subobj.push_back(cliprootobj);
rootobj->parent = cliprootobj->parent = superroot;
rootobj->root = rootobj;
cliprootobj->root = cliprootobj;
// First, create the objects and an ID<->GameObject* map.
std::map<uint32_t, GameObject*> idobjmap;
std::map<Chunk*, GameObject*> chkobjmap;
std::function<void(Chunk*,GameObject*)> z;
uint32_t objid = 1;
z = [this, &z, &objid, &chkobjmap, &idobjmap, &phea, &pnam](Chunk *c, GameObject *parentobj) {
uint32_t pheaoff = c->tag & 0xFFFFFF;
uint32_t *p = (uint32_t*)((char*)phea->maindata.data() + pheaoff);
uint32_t ot = *(unsigned short*)(&p[5]);
char *objname = (char*)pnam->maindata.data() + p[2];
GameObject *o = new GameObject(objname, ot);
chkobjmap[c] = o;
parentobj->subobj.push_back(o);
o->parent = parentobj;
idobjmap[objid++] = o;
if (c->subchunks.size() > 0)
for (uint32_t i = 0; i < (uint32_t)c->subchunks.size(); i++)
z(&c->subchunks[i], o);
};
auto y = [z](Chunk *c, GameObject *o) {
for (uint32_t i = 0; i < (uint32_t)c->subchunks.size(); i++)
z(&c->subchunks[i], o);
};
y(pclp, cliprootobj);
y(prot, rootobj);
using MeshKey = std::array<uint32_t, 8>;
auto toMeshKey = [](uint32_t* p) {
return MeshKey{ p[6], p[7], p[8], p[9], p[10], p[11], p[12], p[14] };
};
struct MeshKeyHash {
size_t operator()(const MeshKey& mi) const noexcept {
return mi[6];
}
};
std::unordered_map<MeshKey, std::shared_ptr<Mesh>, MeshKeyHash> meshMap;
std::unordered_map<MeshKey, std::shared_ptr<ObjLine>, MeshKeyHash> lineMap;
// Then read/load the object properties.
std::function<void(Chunk*, GameObject*)> g;
g = [&](Chunk *c, GameObject *parentobj) {
uint32_t pheaoff = c->tag & 0xFFFFFF;
uint32_t *p = (uint32_t*)((char*)phea->maindata.data() + pheaoff);
uint32_t ot = *(unsigned short*)(&p[5]);
const char *otname = GetObjTypeString(ot);
char *objname = (char*)pnam->maindata.data() + p[2];
GameObject *o = chkobjmap[c];
uint8_t state = (c->tag >> 24) & 255;
assert(state >= 0 && state < 4);
o->isIncludedScene = state & 2;
o->flags = *((unsigned short*)(&p[5]) + 1);
o->root = o->parent->root;
Vector3 position = *(Vector3*)((char*)ppos->maindata.data() + p[4]);
o->matrix = Matrix::getTranslationMatrix(position);
float mc[4];
int32_t *mtxoff = (int32_t*)pmtx->maindata.data() + p[3] * 4;
for (int i = 0; i < 4; i++)
mc[i] = (float)((double)mtxoff[i] / 1073741824.0); // divide by 2^30
Vector3 rv[3];
rv[2] = Vector3(mc[0], mc[1], std::sqrt(std::max(0.0f, 1.0f - mc[0]*mc[0] - mc[1]*mc[1])));
rv[1] = Vector3(mc[2], mc[3], std::sqrt(std::max(0.0f, 1.0f - mc[2]*mc[2] - mc[3]*mc[3])));
if (mtxoff[0] & 1) rv[2].z = -rv[2].z;
if (mtxoff[2] & 1) rv[1].z = -rv[1].z;
rv[0] = rv[1].cross(rv[2]);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
o->matrix.m[i][j] = rv[i].coord[j];
if (o->flags & 0x0020)
{
o->color = p[13];
auto mi = toMeshKey(p);
auto [meshIt, isFirstTime] = meshMap.try_emplace(mi);
if (isFirstTime) {
meshIt->second = std::make_shared<Mesh>();
Mesh* m = meshIt->second.get();
m->weird = p[14];
float* verts = (float*)pver->maindata.data() + p[6];
uint16_t* quadInds = (uint16_t*)pfac->maindata.data() + p[7];
uint16_t* triInds = (uint16_t*)pfac->maindata.data() + p[8];
m->vertices.resize(3 * p[10]);
m->quadindices.resize(4 * p[11]);
m->triindices.resize(3 * p[12]);
memcpy(m->vertices.data(), verts, 4 * m->vertices.size());
memcpy(m->quadindices.data(), quadInds, 2 * m->quadindices.size());
memcpy(m->triindices.data(), triInds, 2 * m->triindices.size());
uint32_t ftxo = 0;
if (p[9] & 0x80000000) {
uint32_t* dat1 = (uint32_t*)(pdat->maindata.data() + (p[9] & 0x7FFFFFFF));
ftxo = dat1[0];
m->extension = std::make_unique<Mesh::Extension>();
m->extension->extUnk2 = dat1[1];
uint8_t* dat2 = pdat->maindata.data() + dat1[2];
uint8_t* ptr2 = dat2;
uint32_t numDings = *(uint32_t*)ptr2; ptr2 += 4;
m->extension->frames.resize(numDings);
memcpy(m->extension->frames.data(), ptr2, 8 * numDings);
ptr2 += numDings * 8;
m->extension->name = (const char*)ptr2;
}
else {
ftxo = p[9];
}
if (ftxo != 0) {
uint8_t* ftx = pftx->maindata.data() + ftxo - 1;
uint32_t uv1off = *(uint32_t*)ftx;
uint32_t uv2off = *(uint32_t*)(ftx + 4);
uint32_t numFaces = *(uint32_t*)(ftx + 8);
assert(numFaces == m->getNumTris() + m->getNumQuads());
float* uv1 = (float*)puvc->maindata.data() + uv1off;
float* uv2 = (float*)puvc->maindata.data() + uv2off;
m->ftxFaces.resize(numFaces);
memcpy(m->ftxFaces.data(), ftx + 12, numFaces * 12);
uint32_t numTexturedFaces = 0, numLitFaces = 0;
for (auto& face : m->ftxFaces) {
if (face[0] & 0x20)
numTexturedFaces += 1;
if (face[0] & 0x80)
numLitFaces += 1;
}
m->textureCoords.resize(numTexturedFaces * 8);
m->lightCoords.resize(numLitFaces * 8);
memcpy(m->textureCoords.data(), uv1, numTexturedFaces * 8 * 4);
memcpy(m->lightCoords.data(), uv2, numLitFaces * 8 * 4);
}
}
o->mesh = meshIt->second;
}
if (o->flags & 0x0400)
{
o->color = p[13];
auto mi = toMeshKey(p);
auto [lineIt, isFirstTime] = lineMap.try_emplace(mi);
if (isFirstTime) {
lineIt->second = std::make_shared<ObjLine>();
ObjLine* m = lineIt->second.get();
assert(p[7] == 0 && p[11] == 0);
m->vertices.resize(3 * p[10]);
m->terms.resize(p[12]);
float* verts = (float*)pver->maindata.data() + p[6];
memcpy(m->vertices.data(), verts, 4 * m->vertices.size());
memcpy(m->terms.data(), pdat->maindata.data() + p[8], 4 * m->terms.size());
m->ftxo = p[9];
m->weird = p[14];
}
o->line = lineIt->second;
}
if (o->flags & 0x0080)
{
o->light = std::make_shared<Light>();
for (int i = 0; i < 7; i++)
o->light->param[i] = p[6 + i];
}
uint8_t* dpbeg = pdbl->maindata.data() + p[0];
o->dbl.load(dpbeg, idobjmap);
uint32_t pexcoff = p[1];
if (pexcoff != 0) {
o->excChunk = std::make_shared<Chunk>();
o->excChunk->load(pexc->maindata.data() + pexcoff - 1);
}
if (c->subchunks.size() > 0)
{
for (uint32_t i = 0; i < (uint32_t)c->subchunks.size(); i++)
g(&c->subchunks[i], o);
}
};
auto f = [g](Chunk *c, GameObject *o) {
for (uint32_t i = 0; i < (uint32_t)c->subchunks.size(); i++)
g(&c->subchunks[i], o);
};
f(pclp, cliprootobj);
f(prot, rootobj);
// Audio objects
Chunk* ands = spkchk.findSubchunk('SDNA');
Chunk* sndr = spkchk.findSubchunk('RDNS');
assert(ands && sndr);
audioMgr.load(*ands, *sndr);
// ZDefines
Chunk* zdef = spkchk.findSubchunk('FEDZ');
assert(zdef);
zdefNames = (const char*)zdef->multidata[0].data();
zdefValues.load(zdef->multidata[1].data(), idobjmap);
zdefTypes = (const char*)zdef->multidata[2].data();
// Messages
Chunk* msgv = spkchk.findSubchunk('VGSM');
for (Chunk& msg : msgv->subchunks) {
uint32_t id = msg.tag;
msgDefinitions[id] = std::make_pair((char*)msg.multidata[0].data(), (char*)msg.multidata[1].data());
}
// Texture to material assignment map
Chunk* matl = spkchk.findSubchunk('LTAM');
assert(matl);
Chunk* mtlv = matl->findSubchunk('VLTM');
assert(mtlv && mtlv->maindata.size() == 4 && *(uint32_t*)mtlv->maindata.data() == 1);
for (size_t i = 0; i < matl->multidata.size(); i += 3) {
textureMaterialMap.emplace_back((char*)matl->multidata[i].data(), (char*)matl->multidata[i + 1].data(), *(uint32_t*)matl->multidata[i + 2].data());
}
// Texture info (last ID)
Chunk* ptxi = spkchk.findSubchunk('IXTP');
numTextures = *(uint32_t*)ptxi->maindata.data();
// Info string lists
Chunk* pzfi = spkchk.findSubchunk('IFZP');
Chunk* dlcf = spkchk.findSubchunk('FCLD');
Chunk* spat = spkchk.findSubchunk('TAPS');
assert(pzfi && dlcf && spat);
auto loadStrList = [](std::vector<std::string>& vec, Chunk* chk) {
if (chk->maindata.size())
vec.emplace_back((const char*)chk->maindata.data());
for (auto& dat : chk->multidata)
vec.emplace_back((const char*)dat.data());
};
loadStrList(zipFilesIncluded, pzfi);
loadStrList(dlcFiles, dlcf);
loadStrList(scenePaths, spat);
// Remaining chunks
static constexpr uint32_t knownChunks[] = {
'TORP', 'PLCP', 'AEHP', 'MANP', 'SOPP',
'XTMP', 'REVP', 'CAFP', 'XTFP', 'CVUP',
'LBDP', 'TADP', 'CXEP', 'SDNA', 'RDNS',
'FEDZ', 'VGSM', 'LTAM', 'IXTP',
'IFZP', 'FCLD', 'TAPS'
};
for (auto& chk : spkchk.subchunks) {
if (std::find(std::begin(knownChunks), std::end(knownChunks), chk.tag) == std::end(knownChunks)) {
remainingChunks.push_back(std::move(chk)); // move since spkchk is going to be destroyed anyway
}
}
oldSpkChunk = std::move(spkchk);
ready = true;
}
struct DBLHash
{
size_t operator() (const std::pair<uint32_t, std::string>& e) const
{
const std::hash<std::string> h;
return e.first + h(e.second);
}
};
template<typename Unit, uint32_t OffsetUnit, bool IncludeStringNullTerminator = false>
struct PackBuffer {
using Elem = typename Unit::value_type;
std::vector<uint8_t> buffer;
std::map<Unit, uint32_t> offmap;
[[nodiscard]] uint32_t addByteOffset(const Unit& elem) {
auto [it, inserted] = offmap.try_emplace(elem, (uint32_t)buffer.size());
if (inserted) {
uint8_t* ptr = (uint8_t*)std::data(elem);
size_t len = sizeof(Elem) * (std::size(elem) + (IncludeStringNullTerminator ? 1 : 0));
buffer.insert(buffer.end(), ptr, ptr + len);
}
return it->second;
}
[[nodiscard]] uint32_t add(const Unit& elem) {
return addByteOffset(elem) / OffsetUnit;
}
};
// Struct with all variables used when saving a Scene.
struct SceneSaver {
uint32_t moc_objcount;
std::map<GameObject*, uint32_t> objidmap;
ByteWriter<std::vector<uint8_t>> heabuf;
PackBuffer<std::array<float, 3>, 1> posPackBuf;
PackBuffer<std::array<uint32_t, 4>, 16> mtxPackBuf;
PackBuffer<std::string, 1, true> namPackBuf;
PackBuffer<std::string, 1> dblPackBuf;
PackBuffer<std::vector<float>, 4> verPackBuf;
PackBuffer<std::vector<uint16_t>, 2> facPackBuf;
PackBuffer<std::string, 1> datPackBuf;
PackBuffer<std::string, 1> ftxPackBuf;
PackBuffer<std::vector<float>, 4> uvcPackBuf;
PackBuffer<std::string, 1> excPackBuf;
void MakeObjChunk(Chunk* c, GameObject* o, bool isclp)
{
moc_objcount++;
*c = {};
// Position
Vector3 position = o->matrix.getTranslationVector();
std::array<float, 3> cpos = { position.x, position.y, position.z };
uint32_t posoff = posPackBuf.add(cpos);
// Matrix
std::array<uint32_t, 4> cmtx;
cmtx[0] = (uint32_t)(o->matrix._31 * 1073741824.0f) & ~1u; // multiply by 2^30
cmtx[1] = (uint32_t)(o->matrix._32 * 1073741824.0f);
if (o->matrix._33 < 0) cmtx[0] |= 1;
cmtx[2] = (uint32_t)(o->matrix._21 * 1073741824.0f) & ~1u;
cmtx[3] = (uint32_t)(o->matrix._22 * 1073741824.0f);
if (o->matrix._23 < 0) cmtx[2] |= 1;
uint32_t mtxoff = mtxPackBuf.add(cmtx);
// DBL
std::string dblsav = o->dbl.save(*this);
uint32_t dbloff = dblPackBuf.add(dblsav);
// Name
uint32_t namoff = namPackBuf.add(o->name);
// Vertices (Mesh+Line)
uint32_t veroff = 0, trifacoff = 0, quadfacoff = 0, linetermoff = 0, ftxoff = 0;
assert(!(o->mesh && o->line));
if (o->mesh || o->line) {
const auto& vertices = o->mesh ? o->mesh->vertices : o->line->vertices;
if (!vertices.empty()) {
veroff = verPackBuf.add(vertices);
}
}
// Mesh
if (o->mesh) {
if (!o->mesh->triindices.empty()) {
trifacoff = facPackBuf.add(o->mesh->triindices);
}
if (!o->mesh->quadindices.empty()) {
quadfacoff = facPackBuf.add(o->mesh->quadindices);
}
uint32_t realftxoff = 0;
if (!o->mesh->ftxFaces.empty()) {
uint32_t tcOff = 0, lcOff = 0;
if (!o->mesh->textureCoords.empty()) {
tcOff = uvcPackBuf.add(o->mesh->textureCoords);
}
if (!o->mesh->lightCoords.empty()) {
lcOff = uvcPackBuf.add(o->mesh->lightCoords);
}
ByteWriter<std::string> sb;
uint32_t numFaces = (uint32_t)o->mesh->ftxFaces.size();
std::array<uint32_t, 3> header = { tcOff, lcOff, numFaces };
sb.addData(header.data(), 12);
sb.addData(o->mesh->ftxFaces.data(), numFaces * 12);
realftxoff = ftxPackBuf.add(sb.take()) + 1;
}
if (o->mesh->extension) {
ByteWriter<std::string> sb;
uint32_t numFrames = o->mesh->extension->frames.size();
sb.addU32(numFrames);
for (auto& [p1, p2] : o->mesh->extension->frames) {
sb.addU32(p1);
sb.addU32(p2);
}
sb.addStringNT(o->mesh->extension->name);
uint32_t ext2off = datPackBuf.add(sb.take());
std::array<uint32_t, 3> ext1 = { realftxoff, o->mesh->extension->extUnk2, ext2off };
uint32_t ext1off = datPackBuf.add(std::string{ (char*)ext1.data(), 12 });
ftxoff = ext1off | 0x80000000;
}
else {
ftxoff = realftxoff;
}
}
// Line
if (o->line) {
if (!o->line->terms.empty()) {
const char* ptr = (const char*)o->line->terms.data();
linetermoff = datPackBuf.add(std::string{ ptr, 4 * o->line->terms.size() });
}
}
// EXC
uint32_t pexcoff = 0;
if (o->excChunk) {
pexcoff = excPackBuf.add(o->excChunk->saveToString()) + 1;
}
// Object Header
uint32_t heaoff = (uint32_t)heabuf.size();
heabuf.addU32(dbloff);
heabuf.addU32(pexcoff);
heabuf.addU32(namoff);
heabuf.addU32(mtxoff);
heabuf.addU32(posoff);
heabuf.addU16(o->type);
heabuf.addU16(o->flags);
if (o->flags & 0x0020)
{
assert(o->mesh);
heabuf.addU32(veroff);
heabuf.addU32(quadfacoff);
heabuf.addU32(trifacoff);
heabuf.addU32(ftxoff);
uint32_t versize = o->mesh->getNumVertices();
uint32_t quadsize = o->mesh->getNumQuads();
uint32_t trisize = o->mesh->getNumTris();
heabuf.addU32(versize);
heabuf.addU32(quadsize);
heabuf.addU32(trisize);
heabuf.addU32(o->color);
heabuf.addU32(o->mesh->weird);
}
if (o->flags & 0x0400)
{
assert(o->line);
uint32_t zero = 0;
heabuf.addU32(veroff);
heabuf.addU32(zero);
heabuf.addU32(linetermoff);
heabuf.addU32(o->line->ftxo);
uint32_t versize = o->line->getNumVertices();
uint32_t termsize = o->line->terms.size();
heabuf.addU32(versize);
heabuf.addU32(zero);
heabuf.addU32(termsize);
heabuf.addU32(o->color);
heabuf.addU32(o->line->weird);
}
if (o->flags & 0x0080)
{
assert(o->light);
for (int i = 0; i < 7; i++)
heabuf.addU32(o->light->param[i]);
}
// Object Chunk
uint32_t tagstate = (o->isIncludedScene ? 2 : 0) | (isclp ? 1 : 0);
c->tag = heaoff | (tagstate << 24);
c->subchunks.resize(o->subobj.size());
int i = 0;
for (auto e = o->subobj.begin(); e != o->subobj.end(); e++)
{
Chunk* s = &c->subchunks[i];
s->tag = 0;
MakeObjChunk(s, *e, isclp);
i++;
}
}
};
Chunk Scene::ConstructSPK()
{
SceneSaver saver;
Chunk newSpkChunk('SPK');
newSpkChunk.subchunks.reserve(30);
Chunk& nrot = newSpkChunk.subchunks.emplace_back('TORP');
Chunk& nclp = newSpkChunk.subchunks.emplace_back('PLCP');
uint32_t objid = 1;
auto z = [&objid,&saver](GameObject *o, auto& rec) -> void {
for (auto e = o->subobj.begin(); e != o->subobj.end(); e++)
{
saver.objidmap[*e] = objid++;
rec(*e, rec);
}
};
z(cliprootobj, z);
z(rootobj, z);
auto f = [this,&saver](Chunk *c, GameObject *o) {
c->subchunks.resize(o->subobj.size());
saver.moc_objcount = 0;
int i = 0;
for (auto e = o->subobj.begin(); e != o->subobj.end(); e++)
{
Chunk *s = &c->subchunks[i++];
saver.MakeObjChunk(s, *e, o==cliprootobj);
}
c->maindata.resize(4);
*(uint32_t*)c->maindata.data() = saver.moc_objcount;
};
f(&nrot, rootobj);
f(&nclp, cliprootobj);
// Fills a chunk
auto fillMaindata = [](uint32_t tag, Chunk *nthg, const auto& buf) {
using T = std::remove_reference_t<decltype(buf)>;
nthg->tag = tag;
nthg->maindata.resize(buf.size() * sizeof(T::value_type));
memcpy(nthg->maindata.data(), buf.data(), nthg->maindata.size());
};
// Chunk comparison
auto chkcmp = [](Chunk* chka, Chunk* chkb, const char* name) {
printf("----- Comparison of old and new %s -----\n", name);
if (chka->tag != chkb->tag)
printf("Different tag\n");
if (chka->multidata.size() != chkb->multidata.size())
printf("Different num_datas: %zu -> %zu\n", chka->multidata.size(), chkb->multidata.size());
if (chka->maindata.size() != chkb->maindata.size())
printf("Different maindata_size: %zu -> %zu\n", chka->maindata.size(), chkb->maindata.size());
else if(chka->maindata.size()) {
uint32_t mdcmp = 0;
for (size_t i = 0; i < (size_t)chka->maindata.size(); i++)
if (((char*)chka->maindata.data())[i] != ((char*)chkb->maindata.data())[i])
mdcmp += 1;
if (mdcmp != 0)
printf("Different maindata content: %u bytes are different\n", mdcmp);
auto sum_a = ComputeBytesum(chka->maindata.data(), chka->maindata.size());
auto sum_b = ComputeBytesum(chkb->maindata.data(), chkb->maindata.size());
if (sum_a != sum_b)
printf("Different bytesum\n");
else
printf("Same bytesum\n");
}
else if (chka->multidata.size()) {
int numSizeDiff = 0, numContentDiff = 0, numSame = 0, numTotal = (int)chka->multidata.size();
for (size_t i = 0; i < chka->multidata.size(); ++i) {
if (chka->multidata[i].size() != chkb->multidata[i].size())
numSizeDiff += 1;
else if (memcmp(chka->multidata[i].data(), chkb->multidata[i].data(), chka->multidata[i].size()))
numContentDiff += 1;
else
numSame += 1;
}
printf("%i/%i parts have different sizes\n", numSizeDiff, numTotal);
printf("%i/%i parts have same size but content is different\n", numContentDiff, numTotal);
printf("%i/%i parts have same size and content\n", numSame, numTotal);
}
};
// Final move
auto serveChunk = [&](const char* name, const auto& buffer) {
Chunk& newChunk = newSpkChunk.subchunks.emplace_back();
fillMaindata(*(uint32_t*)name, &newChunk, buffer);
};
serveChunk("PHEA", saver.heabuf.take());
serveChunk("PNAM", saver.namPackBuf.buffer);
serveChunk("PPOS", saver.posPackBuf.buffer);
serveChunk("PMTX", saver.mtxPackBuf.buffer);
serveChunk("PDBL", saver.dblPackBuf.buffer);
serveChunk("PVER", saver.verPackBuf.buffer);
serveChunk("PFAC", saver.facPackBuf.buffer);
serveChunk("PDAT", saver.datPackBuf.buffer);
serveChunk("PFTX", saver.ftxPackBuf.buffer);
serveChunk("PUVC", saver.uvcPackBuf.buffer);
serveChunk("PEXC", saver.excPackBuf.buffer);
newSpkChunk.maindata.resize(8);
((uint32_t*)newSpkChunk.maindata.data())[0] = 10;
((uint32_t*)newSpkChunk.maindata.data())[1] = 0x40000;
// Audio stuff
auto [andsNew, sndrNew] = audioMgr.save();
newSpkChunk.subchunks.emplace_back(std::move(andsNew));
newSpkChunk.subchunks.emplace_back(std::move(sndrNew));
// ZDefines
Chunk& zdefNew = newSpkChunk.subchunks.emplace_back('FEDZ');
zdefNew.multidata.resize(3);
auto strValues = zdefValues.save(saver);
zdefNew.multidata[0].resize(zdefNames.size() + 1);
zdefNew.multidata[1].resize(strValues.size());
zdefNew.multidata[2].resize(zdefTypes.size() + 1);
memcpy(zdefNew.multidata[0].data(), zdefNames.data(), zdefNew.multidata[0].size());
memcpy(zdefNew.multidata[1].data(), strValues.data(), zdefNew.multidata[1].size());
memcpy(zdefNew.multidata[2].data(), zdefTypes.data(), zdefNew.multidata[2].size());
// Messages
Chunk& msgvNew = newSpkChunk.subchunks.emplace_back('VGSM');
msgvNew.subchunks.reserve(msgDefinitions.size());
for (auto& [id, msg] : msgDefinitions) {
Chunk& chk = msgvNew.subchunks.emplace_back(id);
chk.multidata.resize(2);
chk.multidata[0].resize(msg.first.size() + 1);
chk.multidata[1].resize(msg.second.size() + 1);
memcpy(chk.multidata[0].data(), msg.first.data(), chk.multidata[0].size());
memcpy(chk.multidata[1].data(), msg.second.data(), chk.multidata[1].size());
}
// Texture to material assignment map
Chunk& matlNew = newSpkChunk.subchunks.emplace_back('LTAM');
Chunk& mtlvNew = matlNew.subchunks.emplace_back('VLTM');
mtlvNew.maindata.resize(4);
*(uint32_t*)mtlvNew.maindata.data() = 1;
matlNew.multidata.resize(3 * textureMaterialMap.size());
for (size_t i = 0; i < textureMaterialMap.size(); ++i) {
auto& [texName, matName, num] = textureMaterialMap[i];
matlNew.multidata[3 * i].resize(texName.size() + 1);
matlNew.multidata[3 * i + 1].resize(matName.size() + 1);
matlNew.multidata[3 * i + 2].resize(4);
memcpy(matlNew.multidata[3 * i].data(), texName.data(), matlNew.multidata[3 * i].size());
memcpy(matlNew.multidata[3 * i + 1].data(), matName.data(), matlNew.multidata[3 * i + 1].size());
*(uint32_t*)matlNew.multidata[3 * i + 2].data() = num;
}
// Texture info (last ID)
Chunk& ptxiNew = newSpkChunk.subchunks.emplace_back('IXTP');
ptxiNew.maindata.resize(4);
*(uint32_t*)ptxiNew.maindata.data() = numTextures;
// Scene info String lists
auto saveStrList = [&newSpkChunk](const std::vector<std::string>& vec, uint32_t tag) {
Chunk& chk = newSpkChunk.subchunks.emplace_back(tag);
chk.multidata.resize(vec.size());
for (size_t i = 0; i < vec.size(); ++i) {
auto& str = vec[i];
auto& dat = chk.multidata[i];
dat.resize(str.size() + 1);
memcpy(dat.data(), str.data(), str.size() + 1);
}
};
saveStrList(zipFilesIncluded, 'IFZP');
saveStrList(dlcFiles, 'FCLD');
saveStrList(scenePaths, 'TAPS');
// Remaining chunks
for (auto& rem : remainingChunks)
newSpkChunk.subchunks.push_back(rem);
// Chunk Comparisons
for (Chunk& nchunk : newSpkChunk.subchunks) {
Chunk* ochunk = oldSpkChunk.findSubchunk(nchunk.tag);
char name[5];
*(uint32_t*)name = nchunk.tag;
name[4] = 0;
if (ochunk) {
chkcmp(ochunk, &nchunk, name);
}
else {
printf("!! New chunk %s !!\n", name);
}
}
return newSpkChunk;
}
void Scene::SaveSceneSPK(const char *fn)
{
mz_zip_archive outzip;
mz_zip_zero_struct(&outzip);
mz_bool mzr;
mzr = mz_zip_writer_init_file(&outzip, fn, 0);
if (!mzr) { warn("Couldn't create the new scene ZIP file for saving."); return; }
if (!zipmem.empty()) {
mz_zip_archive inzip;
mz_zip_zero_struct(&inzip);
mzr = mz_zip_reader_init_mem(&inzip, zipmem.data(), zipmem.size(), 0);
if (!mzr) { warn("Couldn't reopen the original scene ZIP file."); return; }
int nfiles = mz_zip_reader_get_num_files(&inzip);
// Determine files to copy from original ZIP
static constexpr const char* nocopyFiles[] = { "Pack.SPK", "Pack.PAL", "Pack.DXT", "Pack.ANM", "Pack.WAV", "Pack.LGT",
"PackRepeat.PAL", "PackRepeat.DXT", "PackRepeat.ANM", "PackRepeat.WAV" };
std::vector<bool> allowCopy = std::vector<bool>(nfiles, true);
for (size_t i = 0; i < std::size(nocopyFiles); ++i) {
int x = mz_zip_reader_locate_file(&inzip, nocopyFiles[i], nullptr, 0);
if (x != -1)
allowCopy[x] = false;
}
// Copy the files
for (int i = 0; i < nfiles; i++)
if (allowCopy[i])
mz_zip_writer_add_from_zip_reader(&outzip, &inzip, i);
mz_zip_reader_end(&inzip);
}
auto saveChunk = [&outzip](Chunk* chk, const char* filename) {
auto str = chk->saveToString();
mz_zip_writer_add_mem(&outzip, filename, str.data(), str.size(), MZ_DEFAULT_COMPRESSION);
};
Chunk spkchk = ConstructSPK();
saveChunk(&spkchk, "Pack.SPK");
oldSpkChunk = std::move(spkchk);
saveChunk(&palPack, "Pack.PAL");
saveChunk(&dxtPack, "Pack.DXT");
saveChunk(&lgtPack, "Pack.LGT");
saveChunk(&wavPack, "Pack.WAV");
if (hasAnmPack)
saveChunk(&anmPack, "Pack.ANM");
mz_zip_writer_finalize_archive(&outzip);
mz_zip_writer_end(&outzip);
}
void Scene::Close()
{
if (!ready)
return;
auto destroyObj = [](GameObject* obj, const auto& rec) -> void {
for (GameObject* sub : obj->subobj)
rec(sub, rec);
delete obj;
};
if (superroot)
destroyObj(superroot, destroyObj);
ready = false;
*this = {}; // move a default-constructed scene
// clean ref counts
for (auto it = g_objRefCounts.begin(); it != g_objRefCounts.end();) {
if (it->second == 0u)
it = g_objRefCounts.erase(it);
else
++it;
}
}
void Scene::RemoveObject(GameObject *o)
{
if (o->parent)
{
auto &st = o->parent->subobj;
auto it = std::find(o->parent->subobj.begin(), o->parent->subobj.end(), o);
assert(it != o->parent->subobj.end());
o->parent->subobj.erase(it);
}
delete o;
}
GameObject* Scene::DuplicateObject(GameObject *o, GameObject *parent)
{
if (!parent) parent = rootobj;
if (!o->parent) return 0;
GameObject *d = new GameObject(*o);
//d->refcount = 0;
d->subobj.clear();
d->parent = parent;
parent->subobj.push_back(d);
for (int i = 0; i < o->subobj.size(); i++)
DuplicateObject(o->subobj[i], d);
return d;
}
void Scene::GiveObject(GameObject *o, GameObject *t)
{
if (o->parent)
{
auto &st = o->parent->subobj;
auto it = std::find(st.begin(), st.end(), o);
if (it != st.end())
st.erase(it);
}
t->subobj.push_back(o);
o->parent = t;
}
void DBLList::addMembers(const std::vector<ClassInfo::ObjectMember>& members)
{
using ET = DBLEntry::EType;
for (auto& mem : members) {
auto& cm = mem.info;
auto& defValue = cm->defaultValue;
DBLEntry& de = entries.emplace_back();
if (cm->type == "DOUBLE") {
de.type = ET::DOUBLE;
de.value.emplace<double>(defValue.empty() ? 0.0f : std::stod(defValue));
}
else if (cm->type == "FLOAT") {
de.type = ET::FLOAT;
de.value.emplace<float>(defValue.empty() ? 0.0f : std::stof(defValue));
}
else if (cm->type == "INT" || cm->type == "LONG" || cm->type == "BOOL" || cm->type == "COLOR") {
uint32_t value;
if (defValue.empty() || defValue == "false" || defValue == "FALSE")
value = 0;
else if (defValue == "true" || defValue == "TRUE")
value = 1;
else
value = std::stoi(defValue);
de.type = ET::INT;
de.value.emplace<uint32_t>(value);
}
else if (cm->type == "ENUM") {