forked from OpenKotOR/mdledit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasciipostprocess.cpp
More file actions
1841 lines (1651 loc) · 105 KB
/
Copy pathasciipostprocess.cpp
File metadata and controls
1841 lines (1651 loc) · 105 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 "MDL.h"
#include "embedded_supermodels.h"
#include <algorithm>
#include <cmath>
#include "shlwapi.h"
namespace {
bool BuildPreservedAabbRecursive(const std::vector<Aabb> & linear, unsigned int & cursor, Aabb & out){
if(cursor >= linear.size()) return false;
out = linear.at(cursor++);
const bool bHasChild1 = out.nChild1.Valid() && out.nChild1 > 0;
const bool bHasChild2 = out.nChild2.Valid() && out.nChild2 > 0;
// nChild1/nChild2 are temporary child-presence flags when read from ASCII.
// WriteAabb() regenerates real offsets from the Child vectors.
out.nChild1 = 0;
out.nChild2 = 0;
out.Child1.clear();
out.Child2.clear();
if(bHasChild1){
out.Child1.resize(1);
if(!BuildPreservedAabbRecursive(linear, cursor, out.Child1.front())) return false;
}
if(bHasChild2){
out.Child2.resize(1);
if(!BuildPreservedAabbRecursive(linear, cursor, out.Child2.front())) return false;
}
return true;
}
Node * FindAsciiRootNode(std::vector<Node> & nodes, const std::string & sContext){
Node * pRoot = nullptr;
for(Node & node : nodes){
if(node.Head.nType == 0 || !node.Head.nNameIndex.Valid()) continue;
if(!node.Head.nParentIndex.Valid()){
if(pRoot != nullptr){
throw mdlexception("ASCII post-processing found multiple root nodes in " + sContext + "; refusing to choose one and orphan the rest.");
}
pRoot = &node;
}
}
return pRoot;
}
bool ContainsNameIndex(const std::vector<unsigned short> & values, unsigned short value){
return std::find(values.begin(), values.end(), value) != values.end();
}
unsigned short CheckedAsciiVertexIndex(std::size_t index, const std::string & sContext){
const std::size_t nInvalid = static_cast<std::size_t>(std::numeric_limits<unsigned short>::max());
if(index >= nInvalid){
throw mdlexception(sContext + " would require a vertex index outside the 16-bit MDL range.");
}
return static_cast<unsigned short>(index);
}
int FindAsciiNodeIndexByNameIndex(ModelHeader & header, unsigned short nNameIndex){
for(std::size_t i = 0; i < header.ArrayOfNodes.size(); ++i){
Node & node = header.ArrayOfNodes.at(i);
if(node.Head.nNameIndex.Valid() && static_cast<unsigned short>(node.Head.nNameIndex) == nNameIndex){
return static_cast<int>(i);
}
}
return -1;
}
Node & GetAsciiNodeByNameIndex(ModelHeader & header, unsigned short nNameIndex, const std::string & sContext){
const int nIndex = FindAsciiNodeIndexByNameIndex(header, nNameIndex);
if(nIndex < 0){
throw mdlexception(sContext + " references node name index " + std::to_string(nNameIndex) + ", but no geometry node with that name index exists.");
}
return header.ArrayOfNodes.at(static_cast<unsigned int>(nIndex));
}
unsigned short CheckedAsciiNameIndex(ModelHeader & header, MdlInteger<unsigned short> nNameIndex, const std::string & sContext){
if(!nNameIndex.Valid()){
throw mdlexception(sContext + " has an invalid node name index.");
}
const unsigned short nIndex = static_cast<unsigned short>(nNameIndex);
if(nIndex >= header.Names.size()){
throw mdlexception(sContext + " references node name index " + std::to_string(nIndex) + ", which is outside the name table.");
}
return nIndex;
}
void GatherChildrenRecursive(Node & node,
std::vector<Node> & arrayOfNodes,
Vector vFromRoot,
std::vector<unsigned short> & active,
std::vector<unsigned short> & visited){
if(!node.Head.nNameIndex.Valid()){
throw mdlexception("GatherChildren() error: node has an invalid name index.");
}
const unsigned short nNameIndex = static_cast<unsigned short>(node.Head.nNameIndex);
if(ContainsNameIndex(active, nNameIndex)){
throw mdlexception("GatherChildren() error: cyclic node hierarchy detected while collecting children.");
}
if(ContainsNameIndex(visited, nNameIndex)){
throw mdlexception("GatherChildren() error: hierarchy reaches the same node more than once.");
}
active.push_back(nNameIndex);
/// Propagate only the Vector from the root through recursion. The node's
/// own static orientation rotates the incoming offset before the node
/// position is added.
if(node.Head.nType & NODE_MESH){
Location location = node.GetLocation();
Quaternion qNode = location.oOrientation.GetQuaternion();
vFromRoot.Rotate(qNode);
vFromRoot += location.vPosition;
node.Head.vFromRoot = vFromRoot;
}
std::vector<MdlInteger<unsigned short>> childIndices;
childIndices.reserve(arrayOfNodes.size());
for(Node & child : arrayOfNodes){
if(child.Head.nNameIndex.Valid() && child.Head.nParentIndex == node.Head.nNameIndex){
childIndices.push_back(child.Head.nNameIndex);
GatherChildrenRecursive(child, arrayOfNodes, vFromRoot, active, visited);
}
}
childIndices.shrink_to_fit();
node.Head.ChildIndices = std::move(childIndices);
active.pop_back();
visited.push_back(nNameIndex);
}
}
/*
Functions:
GetNormal()
FindThirdIndex()
MDL::GatherChildren()
MDL::GetSupernodes()
MDL::AsciiPostProcess()
*/
namespace {
inline void CalculateWorld(MDL& mdl, FileHeader& data, Patch& patch, bool bNormal, bool bTangent){
if(!bNormal && !bTangent) return;
Node& patch_node = data.MH.ArrayOfNodes.at(static_cast<unsigned int>(patch.nNodeArrayIndex));
for(unsigned int face_ind : patch.FaceIndices){
Face& face = patch_node.Mesh.Faces.at(face_ind);
Vertex& v1 = patch_node.Mesh.Vertices.at(face.nIndexVertex[0]);
Vertex& v2 = patch_node.Mesh.Vertices.at(face.nIndexVertex[1]);
Vertex& v3 = patch_node.Mesh.Vertices.at(face.nIndexVertex[2]);
Vector Edge1 = v2.vFromRoot - v1.vFromRoot;
Vector Edge2 = v3.vFromRoot - v1.vFromRoot;
Vector Edge3 = v3.vFromRoot - v2.vFromRoot;
if(face.fAreaUV == 0.0) patch.bBadUV = true;
if(face.fArea <= 0.0) patch.bBadGeo = true;
Vector vAdd = cross(Edge1, Edge2);
vAdd.Normalize();
if(mdl.bSmoothAreaWeighting) vAdd *= (face.fArea > 0.000001 ? face.fArea : 0.0);
if(mdl.bSmoothAngleWeighting){
if(patch.nVertex == face.nIndexVertex[0]) vAdd *= Angle(Edge1, Edge2);
else if(patch.nVertex == face.nIndexVertex[1]) vAdd *= Angle(Edge1, Edge3);
else if(patch.nVertex == face.nIndexVertex[2]) vAdd *= Angle(Edge2, Edge3);
}
if(mdl.bCreaseAngle && Angle(patch.vWorldNormal, vAdd) > static_cast<double>(mdl.nCreaseAngle)) continue;
if(bNormal) patch.vWorldNormal += vAdd;
vAdd.Normalize();
if(bTangent){
Vector& UVvert1 = v1.MDXData.vUV1;
Vector& UVvert2 = v2.MDXData.vUV1;
Vector& UVvert3 = v3.MDXData.vUV1;
Vector UVedge1 = UVvert2 - UVvert1;
Vector UVedge2 = UVvert3 - UVvert1;
double r = (UVedge1.fX * UVedge2.fY - UVedge1.fY * UVedge2.fX);
if(r != 0.0) r = 1.0 / r;
else r = 2406.6388;
Vector vAddT = r * (Edge1 * UVedge2.fY - Edge2 * UVedge1.fY);
Vector vAddB = r * (Edge2 * UVedge1.fX - Edge1 * UVedge2.fX);
vAddT.Normalize();
vAddB.Normalize();
if(vAddT.Null()) vAddT = Vector(1.0, 0.0, 0.0);
if(vAddB.Null()) vAddB = Vector(1.0, 0.0, 0.0);
Vector vCross = cross(vAdd, vAddT);
double fDot = dot(vCross, vAddB);
if(fDot > 0.0000000001) vAddT *= -1.0;
Vector vNormalUV = cross(UVedge1, UVedge2);
if(vNormalUV.fZ < 0.0){
vAddT *= -1.0;
vAddB *= -1.0;
}
patch.vWorldT += vAddT;
patch.vWorldB += vAddB;
patch.vWorldN += cross(vAddB, vAddT);
}
}
}
inline void CalculateVertex(MDL& mdl, FileHeader& data, Patch& patch, bool bNormal, bool bTangent, std::vector<MdlInteger<unsigned int>>* patches = nullptr){
(void)mdl;
if(!bNormal && !bTangent) return;
if(!patches) patches = &patch.SmoothedPatches;
std::vector<Patch>& patch_group = data.MH.PatchArrayPointers.at(static_cast<unsigned int>(patch.nPatchGroup));
std::vector<MdlInteger<unsigned int>>& smoothed_patches = *patches;
Vector vWorking, vWorkingTST, vWorkingTSB, vWorkingTSN;
patch.bGroupBadGeo = false;
patch.bGroupBadUV = false;
std::vector<int> CheckedPatches;
CheckedPatches.reserve(smoothed_patches.size());
for(int n = 0; n < static_cast<int>(smoothed_patches.size()); n++){
Patch& curpatch = patch_group.at(static_cast<unsigned int>(smoothed_patches.at(n)));
if(std::find(CheckedPatches.begin(), CheckedPatches.end(), curpatch.nNodeArrayIndex) != CheckedPatches.end()) continue;
CheckedPatches.push_back(curpatch.nNodeArrayIndex);
int nNormals = 0;
Vector vMeshNormal, vMeshTST, vMeshTSB, vMeshTSN;
for(int n2 = n; n2 < static_cast<int>(smoothed_patches.size()); n2++){
Patch& curpatch2 = patch_group.at(static_cast<unsigned int>(smoothed_patches.at(n2)));
if(curpatch.nNodeArrayIndex != curpatch2.nNodeArrayIndex) continue;
if(!patch.bGroupBadGeo && curpatch2.bBadGeo) patch.bGroupBadGeo = true;
if(!patch.bGroupBadUV && curpatch2.bBadUV) patch.bGroupBadUV = true;
nNormals++;
if(bNormal) vMeshNormal += curpatch2.vWorldNormal;
if(bTangent) vMeshTSB += curpatch2.vWorldB;
if(bTangent) vMeshTST += curpatch2.vWorldT;
if(bTangent) vMeshTSN += curpatch2.vWorldN;
}
double fMeshNormalLength = vMeshNormal.GetLength();
double fMeshTSBLength = vMeshTSB.GetLength();
double fMeshTSTLength = vMeshTST.GetLength();
double fMeshTSNLength = vMeshTSN.GetLength();
if(bNormal && fMeshNormalLength > 0.000000000001 && std::isfinite(fMeshNormalLength)) vWorking += (nNormals * vMeshNormal / fMeshNormalLength);
if(bTangent && fMeshTSBLength > 0.000000000001 && std::isfinite(fMeshTSBLength)) vWorkingTSB += (vMeshTSB / fMeshTSBLength);
if(bTangent && fMeshTSTLength > 0.000000000001 && std::isfinite(fMeshTSTLength)) vWorkingTST += (vMeshTST / fMeshTSTLength);
if(bTangent && fMeshTSNLength > 0.000000000001 && std::isfinite(fMeshTSNLength)) vWorkingTSN += (vMeshTSN / fMeshTSNLength);
}
if(bNormal) vWorking.Normalize();
if(bTangent) vWorkingTSB.Normalize();
if(bTangent) vWorkingTST.Normalize();
if(bTangent) vWorkingTSN.Normalize();
if(bNormal) patch.vVertexNormal = vWorking;
if(bTangent) patch.vVertexB = vWorkingTSB;
if(bTangent) patch.vVertexT = vWorkingTST;
if(bTangent) patch.vVertexN = vWorkingTSN;
}
}
/// Utility function, gets triangular face normalized normal from vert vectors
Vector GetNormal(Vector v1, Vector v2, Vector v3){
Vector vNormal = (v2 - v1) / (v3 - v1);
vNormal.Normalize();
return vNormal;
}
/// Utility function for mesh->saber conversion
/// Loops through the faces, until it finds one where both of the vert indices exits, then it returns the third index (unless it's being ignored), otherwise -1
int FindThirdIndex(const std::vector<Face> & faces, int ind1, int ind2, int ignore = -1){
for(int f = 0; f < static_cast<int>(faces.size()); f++){
const Face & face = faces.at(f);
int nFound = 0;
for(int i = 0; i < 3; i++){
if(face.nIndexVertex.at(i) == ind1 || face.nIndexVertex.at(i) == ind2) nFound++;
}
if(nFound == 2){
for(int i = 0; i < 3; i++){
if(face.nIndexVertex.at(i) != ind1 && face.nIndexVertex.at(i) != ind2 && face.nIndexVertex.at(i) != ignore) return face.nIndexVertex.at(i);
}
}
}
return -1;
}
void MDL::GatherChildren(Node & node, std::vector<Node> & ArrayOfNodes, Vector vFromRoot){
std::vector<unsigned short> active;
std::vector<unsigned short> visited;
active.reserve(ArrayOfNodes.size());
visited.reserve(ArrayOfNodes.size());
GatherChildrenRecursive(node, ArrayOfNodes, vFromRoot, active, visited);
}
void GetSupernodes(ModelHeader & MH, ModelHeader & superMH, int & nHighest, int & nTotalSupermodelNodes, int nNodeCurrentNameIndex, int nSupernodeCurrentNameIndex){
if(nNodeCurrentNameIndex < 0) return;
Node & node = GetAsciiNodeByNameIndex(MH,
static_cast<unsigned short>(nNodeCurrentNameIndex),
"GetSupernodes()");
if(nSupernodeCurrentNameIndex == -1){
if(nHighest < 0 || nHighest > std::numeric_limits<unsigned short>::max()){
throw mdlexception("GetSupernodes() generated a supernode number outside the 16-bit node field range.");
}
node.Head.nSupernodeNumber = static_cast<unsigned short>(nHighest);
nHighest++;
for(auto childNameIndex : node.Head.ChildIndices){
const unsigned short nChildNameIndex = CheckedAsciiNameIndex(MH, childNameIndex, "GetSupernodes() child");
GetSupernodes(MH, superMH, nHighest, nTotalSupermodelNodes, nChildNameIndex, -2);
}
}
else if(nSupernodeCurrentNameIndex == -2){
/// Question: I am adding this to an already existing value in this variable.
/// It is probably the name index, but is it possible that it actually has to be the node index?
const unsigned int nBaseSupernode = static_cast<unsigned short>(node.Head.nSupernodeNumber);
const unsigned int nAdjustedSupernode = nBaseSupernode + static_cast<unsigned int>(nTotalSupermodelNodes) + 1u;
if(nTotalSupermodelNodes < 0 || nAdjustedSupernode > std::numeric_limits<unsigned short>::max()){
throw mdlexception("GetSupernodes() adjusted a supernode number outside the 16-bit node field range.");
}
node.Head.nSupernodeNumber = static_cast<unsigned short>(nAdjustedSupernode);
for(auto childNameIndex : node.Head.ChildIndices){
const unsigned short nChildNameIndex = CheckedAsciiNameIndex(MH, childNameIndex, "GetSupernodes() child");
GetSupernodes(MH, superMH, nHighest, nTotalSupermodelNodes, nChildNameIndex, -2);
}
}
else{
Node & supernode = GetAsciiNodeByNameIndex(superMH,
static_cast<unsigned short>(nSupernodeCurrentNameIndex),
"GetSupernodes() supermodel");
node.Head.nSupernodeNumber = supernode.Head.nSupernodeNumber;
for(auto childNameIndex : node.Head.ChildIndices){
const unsigned short nChildNameIndex = CheckedAsciiNameIndex(MH, childNameIndex, "GetSupernodes() child");
bool bFound = false;
std::string sNodeName = MH.Names.at(nChildNameIndex).sName.c_str();
ToLowerInPlace(sNodeName);
for(auto superChildNameIndexValue : supernode.Head.ChildIndices){
if(bFound) break;
const unsigned short nSuperChildNameIndex = CheckedAsciiNameIndex(superMH, superChildNameIndexValue, "GetSupernodes() supermodel child");
std::string sSupernodeName = superMH.Names.at(nSuperChildNameIndex).sName.c_str();
ToLowerInPlace(sSupernodeName);
if(sNodeName == sSupernodeName){
bFound = true;
GetSupernodes(MH, superMH, nHighest, nTotalSupermodelNodes, nChildNameIndex, nSuperChildNameIndex);
}
}
if(!bFound) GetSupernodes(MH, superMH, nHighest, nTotalSupermodelNodes, nChildNameIndex, -1);
}
}
}
void MDL::AsciiPostProcess(std::vector<std::string> & sBumpmapped){
ReportObject ReportMdl(*this);
ReportMdl << "Ascii post-processing...\n";
Report("Post-processing imported ASCII...");
FileHeader & Data = *FH;
/// PART 0 ///
/// Get rid of the duplication marks
for(int n = 0; n < static_cast<int>(Data.MH.Names.size()); n++){
std::string & sNode = Data.MH.Names.at(n).sName;
if(sNode.find("__dpl") != std::string::npos){
sNode.resize(sNode.find("__dpl"));
}
}
/// Implementation of 'bumpmapped_texture': applies bumpmaps
for(int s = 0; s < static_cast<int>(sBumpmapped.size()); s++){
for(int n = 0; n < static_cast<int>(Data.MH.ArrayOfNodes.size()); n++){
//ReportMdl << "Checking node\n";
Node & node = Data.MH.ArrayOfNodes.at(n);
if(node.Head.nType & NODE_MESH && !(node.Head.nType & NODE_AABB) && !(node.Head.nType & NODE_SABER)){
if(std::string(node.Mesh.cTexture1.c_str()) != "" && std::string(node.Mesh.cTexture1.c_str()) != "NULL"){
if(StringEqual(sBumpmapped.at(s).c_str(), node.Mesh.cTexture1.c_str(), true)){
node.Mesh.nMdxDataBitmap = node.Mesh.nMdxDataBitmap | MDX_FLAG_TANGENT1;
}
}
if(node.Mesh.cTexture2.c_str() != std::string("") && node.Mesh.cTexture2.c_str() != std::string("NULL")){
if(StringEqual(sBumpmapped.at(s).c_str(), node.Mesh.cTexture2.c_str(), true)){
node.Mesh.nMdxDataBitmap = node.Mesh.nMdxDataBitmap | MDX_FLAG_TANGENT2;
}
}
if(node.Mesh.cTexture3.c_str() != std::string("") && node.Mesh.cTexture3.c_str() != std::string("NULL")){
if(StringEqual(sBumpmapped.at(s).c_str(), node.Mesh.cTexture3.c_str(), true)){
node.Mesh.nMdxDataBitmap = node.Mesh.nMdxDataBitmap | MDX_FLAG_TANGENT3;
}
}
if(node.Mesh.cTexture4.c_str() != std::string("") && node.Mesh.cTexture4.c_str() != std::string("NULL")){
if(StringEqual(sBumpmapped.at(s).c_str(), node.Mesh.cTexture4.c_str(), true)){
node.Mesh.nMdxDataBitmap = node.Mesh.nMdxDataBitmap | MDX_FLAG_TANGENT4;
}
}
}
}
}
/// PART 1 ///
/// Gather all the children (the indices!!!)
/// This part means going from every node only specifying its parent to every node also specifying its children
// 1. Gather children for animations
for(Animation & anim : Data.MH.Animations){
Node * pRoot = FindAsciiRootNode(anim.ArrayOfNodes, "animation '" + std::string(anim.sName.c_str()) + "'");
if(pRoot == nullptr){
if(!anim.ArrayOfNodes.empty()){
throw mdlexception("ASCII post-processing could not find a root node for animation '" + std::string(anim.sName.c_str()) + "'.");
}
}
else GatherChildren(*pRoot, anim.ArrayOfNodes, Vector());
}
// 2. Gather children for geometry
Node * pGeometryRoot = FindAsciiRootNode(Data.MH.ArrayOfNodes, "geometry");
if(pGeometryRoot == nullptr){
throw mdlexception("ASCII post-processing could not find a geometry root node.");
}
GatherChildren(*pGeometryRoot, Data.MH.ArrayOfNodes, Vector());
/// PART 2 ///
/// Do supernodes
/// This loads up all the supermodels and calculates the supernode numbers
if(!Data.MH.bPreserveTotalNumberOfNodes){
Data.MH.GH.nTotalNumberOfNodes = Data.MH.nNodeCount;
}
nSupermodel = 0; // As far as we're concerned, supermodel not loaded (yet).
if(Data.MH.cSupermodelName != "NULL" && Data.MH.cSupermodelName != ""){
std::unique_ptr<MDL> Supermodel;
ModelHeader embeddedSupermodelHeader;
ModelHeader * pSupermodelHeader = nullptr;
// A correct neighboring binary remains authoritative, which preserves
// support for custom or modified supermodels. For the stock K1/K2
// humanoid supermodels, suppress the missing-file dialog because a
// generated metadata-only fallback is available.
const bool bEmbeddedAvailable = HasEmbeddedSupermodel(bK2, Data.MH.cSupermodelName);
LoadSupermodel(*this, Supermodel, !bEmbeddedAvailable);
if(Supermodel){
pSupermodelHeader = &Supermodel->GetFileData()->MH;
ReportMdl << "Using neighboring binary supermodel metadata.\n";
}
else if(BuildEmbeddedSupermodel(bK2, Data.MH.cSupermodelName, embeddedSupermodelHeader)){
pSupermodelHeader = &embeddedSupermodelHeader;
ReportMdl << "Using embedded " << (bK2 ? "K2" : "K1")
<< " stock supermodel metadata for "
<< Data.MH.cSupermodelName << ".\n";
}
// First, update the TotalNodeCount.
if(pSupermodelHeader != nullptr){
/// Supernode metadata loaded, record its status.
nSupermodel = bK2 ? 2 : 1;
int nTotalSupermodelNodes = static_cast<int>(pSupermodelHeader->GH.nTotalNumberOfNodes);
ReportMdl << "Total Supermodel Nodes: " << nTotalSupermodelNodes << "\n";
if(nTotalSupermodelNodes > 0 && !Data.MH.bPreserveTotalNumberOfNodes)
Data.MH.GH.nTotalNumberOfNodes += 1 + nTotalSupermodelNodes;
// Next we need the largest supernode number.
int nMaxSupernode = 0;
for(const Node & supermodelNode : pSupermodelHeader->ArrayOfNodes){
nMaxSupernode = std::max(nMaxSupernode,
static_cast<int>(supermodelNode.Head.nSupernodeNumber));
}
int nCurrentSupernode = nMaxSupernode + 1;
Node * pSuperRoot = FindAsciiRootNode(
pSupermodelHeader->ArrayOfNodes,
"supermodel '" + pSupermodelHeader->GH.sName + "'");
if(pSuperRoot == nullptr){
throw mdlexception("ASCII post-processing could not find a root node in supermodel '" +
pSupermodelHeader->GH.sName + "'.");
}
const unsigned short nGeometryRootNameIndex =
CheckedAsciiNameIndex(Data.MH,
pGeometryRoot->Head.nNameIndex,
"GetSupernodes() geometry root");
const unsigned short nSuperRootNameIndex =
CheckedAsciiNameIndex(*pSupermodelHeader,
pSuperRoot->Head.nNameIndex,
"GetSupernodes() supermodel root");
GetSupernodes(Data.MH,
*pSupermodelHeader,
nCurrentSupernode,
nTotalSupermodelNodes,
nGeometryRootNameIndex,
nSuperRootNameIndex);
}
}
/// Apply supernode numbers to anim nodes
for(Animation & anim : Data.MH.Animations){
for(Node & anim_node : anim.ArrayOfNodes){
int nNodeIndex = GetNodeIndexByNameIndex(anim_node.Head.nNameIndex);
if(nNodeIndex != -1){
anim_node.Head.nSupernodeNumber = Data.MH.ArrayOfNodes.at(nNodeIndex).Head.nSupernodeNumber;
}
else{
/// I don't know what to do with the name indices that are present as animation nodes but are not found as geometry nodes.
}
}
}
/// Build Array of Indices By Tree Order
if(Data.MH.ArrayOfNodes.empty()){
throw mdlexception("ASCII post-processing produced no geometry nodes.");
}
Data.MH.NameIndicesInTreeOrder.reserve(Data.MH.ArrayOfNodes.size());
pGeometryRoot = FindAsciiRootNode(Data.MH.ArrayOfNodes, "geometry");
if(pGeometryRoot == nullptr){
throw mdlexception("ASCII post-processing could not find a geometry root node for tree-order construction.");
}
Data.MH.BuildTreeOrderArray(*pGeometryRoot);
/// PART 3 ///
/// Interpret ascii data
/// This constructs the Mesh.Vertices, Mesh.VertIndices, Dangly.Data2, Dangly.Constraints and Saber.SaberData structures.
/// And not to forget the weights. Also face normals, average, aabb tree .... everything.
Report("Interpreting ascii data...");
ProgressSize(0, Data.MH.ArrayOfNodes.size());
ProgressPos(0);
for(int n = 0; n < static_cast<int>(Data.MH.ArrayOfNodes.size()); n++){
//ReportMdl << "n = " << n << "\n";
Node & node = Data.MH.ArrayOfNodes.at(n);
//std::cout << "Processing: " << GetNodeName(node) << std::endl;
//ReportMdl << "Analyzing node " << Data.MH.Names.at(node.Head.nNameIndex).sName << " (" << n << "/" << Data.MH.ArrayOfNodes.size() << ")\n";
//ReportMdl << "PART 3 - stage 1" << "\n";
if(node.Head.nType & NODE_SABER){
/// Saber interpretation goes here.
const bool bHasPreservedSaberData = node.Saber.bPreserveSaberData;
if(bHasPreservedSaberData){
// Exact binary saber payload was supplied through ASCII. Do not regenerate it
// from the old 16-point blade recipe. Keep parsed faces as-is and rebuild
// only Mesh.Vertices for shared bookkeeping/bounding calculations.
node.Mesh.Vertices.clear();
node.Mesh.Vertices.reserve(node.Saber.SaberData.size());
for(VertexData & sd : node.Saber.SaberData) node.Mesh.Vertices.push_back(Vertex().assign(sd.vVertex));
}
else if((node.Mesh.TempVerts.size() == 16 && node.Mesh.TempTverts.size() == 16) ||
(node.Mesh.TempVerts.size() == 176 && node.Mesh.TempTverts.size() == 176)){
int nBase = 8;
if (node.Mesh.TempVerts.size() == 176) nBase = 88;
Vector v0 = node.Mesh.TempVerts.at(0);
Vector v1 = node.Mesh.TempVerts.at(1);
Vector v2 = node.Mesh.TempVerts.at(2);
Vector v3 = node.Mesh.TempVerts.at(3);
Vector v4 = node.Mesh.TempVerts.at(4);
Vector v5 = node.Mesh.TempVerts.at(5);
Vector v6 = node.Mesh.TempVerts.at(6);
Vector v7 = node.Mesh.TempVerts.at(7);
Vector v8 = node.Mesh.TempVerts.at(nBase+0);
Vector v9 = node.Mesh.TempVerts.at(nBase+1);
Vector v10 = node.Mesh.TempVerts.at(nBase+2);
Vector v11 = node.Mesh.TempVerts.at(nBase+3);
Vector v12 = node.Mesh.TempVerts.at(nBase+4);
Vector v13 = node.Mesh.TempVerts.at(nBase+5);
Vector v14 = node.Mesh.TempVerts.at(nBase+6);
Vector v15 = node.Mesh.TempVerts.at(nBase+7);
node.Saber.SaberData.clear();
node.Saber.SaberData.reserve(176);
node.Saber.SaberData.push_back(VertexData(v0, node.Mesh.TempTverts.at(0)));
node.Saber.SaberData.push_back(VertexData(v1, node.Mesh.TempTverts.at(1)));
node.Saber.SaberData.push_back(VertexData(v2, node.Mesh.TempTverts.at(2)));
node.Saber.SaberData.push_back(VertexData(v3, node.Mesh.TempTverts.at(3)));
node.Saber.SaberData.push_back(VertexData(v4, node.Mesh.TempTverts.at(4)));
node.Saber.SaberData.push_back(VertexData(v5, node.Mesh.TempTverts.at(5)));
node.Saber.SaberData.push_back(VertexData(v6, node.Mesh.TempTverts.at(6)));
node.Saber.SaberData.push_back(VertexData(v7, node.Mesh.TempTverts.at(7)));
for(int r = 0; r < 20; r++){
node.Saber.SaberData.push_back(VertexData(v0, node.Mesh.TempTverts.at(0)));
node.Saber.SaberData.push_back(VertexData(v1, node.Mesh.TempTverts.at(1)));
node.Saber.SaberData.push_back(VertexData(v2, node.Mesh.TempTverts.at(2)));
node.Saber.SaberData.push_back(VertexData(v3, node.Mesh.TempTverts.at(3)));
}
node.Saber.SaberData.push_back(VertexData(v8, node.Mesh.TempTverts.at(nBase+0)));
node.Saber.SaberData.push_back(VertexData(v9, node.Mesh.TempTverts.at(nBase+1)));
node.Saber.SaberData.push_back(VertexData(v10, node.Mesh.TempTverts.at(nBase+2)));
node.Saber.SaberData.push_back(VertexData(v11, node.Mesh.TempTverts.at(nBase+3)));
node.Saber.SaberData.push_back(VertexData(v12, node.Mesh.TempTverts.at(nBase+4)));
node.Saber.SaberData.push_back(VertexData(v13, node.Mesh.TempTverts.at(nBase+5)));
node.Saber.SaberData.push_back(VertexData(v14, node.Mesh.TempTverts.at(nBase+6)));
node.Saber.SaberData.push_back(VertexData(v15, node.Mesh.TempTverts.at(nBase+7)));
for(int r = 0; r < 20; r++){
node.Saber.SaberData.push_back(VertexData(v8, node.Mesh.TempTverts.at(nBase+0)));
node.Saber.SaberData.push_back(VertexData(v9, node.Mesh.TempTverts.at(nBase+1)));
node.Saber.SaberData.push_back(VertexData(v10, node.Mesh.TempTverts.at(nBase+2)));
node.Saber.SaberData.push_back(VertexData(v11, node.Mesh.TempTverts.at(nBase+3)));
}
node.Mesh.Faces.resize(0);
node.Mesh.Faces.shrink_to_fit();
}
else{
ReportMdl << "Warning! Requirements for saber mesh not met for '" << Data.MH.Names.at(node.Head.nNameIndex).sName << "'! Converting to trimesh...\n";
node.Head.nType = NODE_HEADER | NODE_MESH;
}
}
//ReportMdl << "PART 3 - stage 2" << "\n";
if(node.Head.nType & NODE_MESH && !(node.Head.nType & NODE_SABER)){
std::vector<Vector> vectorarray;
if(node.Mesh.Faces.size() > vectorarray.max_size() / 3u){
throw mdlexception("Node '" + Data.MH.Names.at(node.Head.nNameIndex).sName + "' has too many faces to allocate temporary vertex data safely.");
}
vectorarray.reserve(node.Mesh.Faces.size()*3u);
node.Mesh.fTotalArea = 0.0;
/// Build mdx bitmap
if(node.Mesh.TempVerts.size() > 0) node.Mesh.nMdxDataBitmap |= (MDX_FLAG_VERTEX | MDX_FLAG_NORMAL);
if(node.Mesh.TempNormals.size() > 0){
node.Mesh.nMdxDataBitmap |= MDX_FLAG_NORMAL;
node.Mesh.bPreserveMdxNormals = true;
}
if(node.Mesh.TempColors.size() > 0) node.Mesh.nMdxDataBitmap |= (MDX_FLAG_COLOR);
if(node.Mesh.TempTverts.size() > 0) node.Mesh.nMdxDataBitmap |= (MDX_FLAG_UV1);
if(node.Mesh.TempTverts1.size() > 0) node.Mesh.nMdxDataBitmap |= (MDX_FLAG_UV2);
if(node.Mesh.TempTverts2.size() > 0) node.Mesh.nMdxDataBitmap |= (MDX_FLAG_UV3);
if(node.Mesh.TempTverts3.size() > 0) node.Mesh.nMdxDataBitmap |= (MDX_FLAG_UV4);
if(node.Mesh.TempTangent1.size() > 0){
node.Mesh.TangentSpace.at(0) = true;
node.Mesh.bPreserveMdxTangent1 = true;
}
if(node.Mesh.TangentSpace.at(0)) node.Mesh.nMdxDataBitmap |= (MDX_FLAG_TANGENT1);
if(node.Mesh.TangentSpace.at(1)) node.Mesh.nMdxDataBitmap |= (MDX_FLAG_TANGENT2);
if(node.Mesh.TangentSpace.at(2)) node.Mesh.nMdxDataBitmap |= (MDX_FLAG_TANGENT3);
if(node.Mesh.TangentSpace.at(3)) node.Mesh.nMdxDataBitmap |= (MDX_FLAG_TANGENT4);
/// If this a skin, we need to build the bonemap, the bone indices and convert the name indices in the weights to bone indices
if(node.Head.nType & NODE_SKIN){
/// First, get the correct name index to all the bones
for(int nb = 0; nb < static_cast<int>(node.Skin.Bones.size()); nb++){
Bone & bone = node.Skin.Bones.at(nb);
bone.nNameIndex = Data.MH.NameIndicesInTreeOrder.at(nb);
}
/// Next, go through the weights and build the actual bones.
/// Keep the compact palette order from decompiled ASCII when present.
/// TSL/K2 has one more compact skin slot than K1; in the binary header
/// that 17th reverse-map slot lives in nPadding1. K1 uses nPadding1
/// as an actual padding short, and vanilla K1 models often contain
/// arbitrary non-zero values there, so do not treat it as slot 16.
const unsigned int nMaxCompactSlots = bK2 ? 17 : 16;
std::vector<int> nBoneIndices(nMaxCompactSlots, -1); // compact slot -> full/tree-order bone index
// Preserve raw compact reverse-map header values before applying
// semantic compactbonemap overrides or assigning slots for edited
// weights. The binary header stores 18 uint16 values: 16 compact
// slots, then nPadding1 and nPadding2. K2 treats nPadding1 as
// semantic slot 16; K1 treats both trailing shorts as raw padding.
const unsigned int nRawCompactHeaderShorts = 18;
for(unsigned int nSlot = 0; nSlot < node.Skin.TempCompactBoneRawIndices.size() && nSlot < nRawCompactHeaderShorts; nSlot++){
MdlInteger<unsigned short> nRawFullBone = node.Skin.TempCompactBoneRawIndices.at(nSlot);
if(!nRawFullBone.Valid()) continue;
if(nSlot < 16) node.Skin.nBoneIndices.at(nSlot) = static_cast<unsigned short>(nRawFullBone);
else if(nSlot == 16) node.Skin.nPadding1 = static_cast<unsigned short>(nRawFullBone);
else node.Skin.nPadding2 = static_cast<unsigned short>(nRawFullBone);
if(nSlot < nMaxCompactSlots &&
static_cast<unsigned short>(nRawFullBone) < node.Skin.Bones.size() &&
node.Skin.Bones.at(static_cast<unsigned short>(nRawFullBone)).nBonemap.Valid() &&
static_cast<unsigned short>(node.Skin.Bones.at(static_cast<unsigned short>(nRawFullBone)).nBonemap) == nSlot){
nBoneIndices.at(nSlot) = static_cast<unsigned short>(nRawFullBone);
}
}
for(unsigned int nSlot = nRawCompactHeaderShorts; nSlot < node.Skin.TempCompactBoneRawIndices.size(); nSlot++){
if(node.Skin.TempCompactBoneRawIndices.at(nSlot).Valid()){
throw mdlexception("compactbonemapraw on node '" + Data.MH.Names.at(node.Head.nNameIndex).sName +
"' contains more raw header values than the binary skin header can store.");
}
}
auto FindTreeOrderIndex = [&](MdlInteger<unsigned short> nNameIndex, unsigned short & nNodeIndex) -> bool {
if(!nNameIndex.Valid()) return false;
for(unsigned short ind2 = 0; ind2 < Data.MH.NameIndicesInTreeOrder.size(); ind2++){
if(nNameIndex == Data.MH.NameIndicesInTreeOrder.at(ind2)){
nNodeIndex = ind2;
return true;
}
}
return false;
};
auto SetCompactSlot = [&](unsigned short nSlot, unsigned short nNodeIndex, MdlInteger<unsigned short> nNameIndex){
if(nSlot >= nMaxCompactSlots) throw mdlexception("Skin compact slot is outside the active game range.");
if(nBoneIndices.at(nSlot) != -1 && nBoneIndices.at(nSlot) != nNodeIndex){
throw mdlexception("Conflicting compact skin palette data on node '" + Data.MH.Names.at(node.Head.nNameIndex).sName + "'.");
}
nBoneIndices.at(nSlot) = nNodeIndex;
if(node.Skin.BoneNameIndices.size() <= nSlot) node.Skin.BoneNameIndices.resize(nSlot + 1);
node.Skin.BoneNameIndices.at(nSlot) = nNameIndex;
node.Skin.Bones.at(nNodeIndex).nBonemap = nSlot;
if(nSlot < 16) node.Skin.nBoneIndices.at(nSlot) = nNodeIndex;
else node.Skin.nPadding1 = nNodeIndex;
};
for(unsigned int nSlot = 0; nSlot < node.Skin.TempCompactBoneNameIndices.size() && nSlot < nMaxCompactSlots; nSlot++){
MdlInteger<unsigned short> nNameIndex = node.Skin.TempCompactBoneNameIndices.at(nSlot);
if(!nNameIndex.Valid()) continue;
unsigned short nNodeIndex = 0;
if(!FindTreeOrderIndex(nNameIndex, nNodeIndex)){
throw mdlexception("compactbonemap on node '" + Data.MH.Names.at(node.Head.nNameIndex).sName +
"' references a bone that is not present in the geometry tree.");
}
SetCompactSlot(nSlot, nNodeIndex, nNameIndex);
}
for(unsigned int nSlot = nMaxCompactSlots; nSlot < node.Skin.TempCompactBoneNameIndices.size(); nSlot++){
if(node.Skin.TempCompactBoneNameIndices.at(nSlot).Valid()){
throw mdlexception("compactbonemap on node '" + Data.MH.Names.at(node.Head.nNameIndex).sName +
"' defines a compact slot that this game does not support.");
}
}
for(Weight & w : node.Skin.TempWeights){
for(int nWeightSlot = 0; nWeightSlot < 4; nWeightSlot++){
MdlInteger<unsigned short> & ind = w.nWeightIndex.at(nWeightSlot);
double fWeightValue = w.fWeightValue.at(nWeightSlot);
if(abs(fWeightValue) < 0.0000001){
ind = -1;
continue;
}
if(!std::isfinite(fWeightValue)){
throw mdlexception("Skin weight on node '" + Data.MH.Names.at(node.Head.nNameIndex).sName + "' is not finite.");
}
if(!ind.Valid()){
throw mdlexception("Active skin weight on node '" + Data.MH.Names.at(node.Head.nNameIndex).sName +
"' has no valid bone. 'root' is not a valid active skin influence in compiled MDX data.");
}
unsigned short nNodeIndex = 0;
if(!FindTreeOrderIndex(ind, nNodeIndex)){
throw mdlexception("Skin weight on node '" + Data.MH.Names.at(node.Head.nNameIndex).sName +
"' references a bone that is not present in the geometry tree.");
}
int nBoneIndex = -1;
for(int nSlot = 0; nSlot < static_cast<int>(nBoneIndices.size()); nSlot++){
if(nBoneIndices.at(nSlot) == nNodeIndex){
nBoneIndex = nSlot;
break;
}
}
if(nBoneIndex == -1){
for(int nSlot = 0; nSlot < static_cast<int>(nBoneIndices.size()); nSlot++){
if(nBoneIndices.at(nSlot) == -1){
nBoneIndex = nSlot;
break;
}
}
if(nBoneIndex == -1){
throw mdlexception("Skin node '" + Data.MH.Names.at(node.Head.nNameIndex).sName +
"' uses more active compact bones than this game supports.");
}
SetCompactSlot(static_cast<unsigned short>(nBoneIndex), nNodeIndex, ind);
}
/// Now that we have a compact bone index, update the one in the weights.
ind = static_cast<unsigned short>(nBoneIndex);
}
}
}
//std::cout << "Done with bones" << std::endl;
/// Go through all the faces
for(int f = 0; f < static_cast<int>(node.Mesh.Faces.size()); f++){
Face & face = node.Mesh.Faces.at(f);
face.nID = f; /// Why is this necessary?
/// MDLOps may leave out texindicesX arrays, I need to check for unset indices and make them use the diffuse ones instead.
for(int i = 0; i < 3; i++){
if(node.Mesh.TempTverts1.size() > 0 && !face.nIndexTvert1.at(i).Valid()){
for(int i2 = 0; i2 < 3; i2++) face.nIndexTvert1.at(i2) = face.nIndexTvert.at(i2);
}
if(node.Mesh.TempTverts2.size() > 0 && !face.nIndexTvert2.at(i).Valid()){
for(int i2 = 0; i2 < 3; i2++) face.nIndexTvert2.at(i2) = face.nIndexTvert.at(i2);
}
if(node.Mesh.TempTverts3.size() > 0 && !face.nIndexTvert3.at(i).Valid()){
for(int i2 = 0; i2 < 3; i2++) face.nIndexTvert3.at(i2) = face.nIndexTvert.at(i2);
}
}
/// Go through all the verts in the face
for(int i = 0; i < 3; i++){
if(!face.bProcessed[i]){
bool bIgnoreVert = true, bIgnoreTvert = true, bIgnoreTvert1 = true, bIgnoreTvert2 = true, bIgnoreTvert3 = true, bIgnoreColor = true, bIgnoreNormal = true, bIgnoreTangent1 = true;
Vertex vert;
vert.MDXData.nNameIndex = node.Head.nNameIndex;
if(node.Mesh.TempVerts.size() > 0){
bIgnoreVert = false;
vert.assign(node.Mesh.TempVerts.at(face.nIndexVertex[i]));
//Add to vectorarray if no identical
bool bAdd = true;
for(int v = 0; v < static_cast<int>(vectorarray.size()) && bAdd; v++){
if(vectorarray.at(v).Compare(node.Mesh.TempVerts.at((unsigned short) face.nIndexVertex[i]))) bAdd = false;
}
if(bAdd){
vectorarray.push_back(node.Mesh.TempVerts.at((unsigned short) face.nIndexVertex[i]));
}
vert.vFromRoot = node.Mesh.TempVerts.at((unsigned short) face.nIndexVertex[i]);
vert.vFromRoot.Rotate(node.GetLocation().oOrientation.GetQuaternion());
vert.vFromRoot += node.Head.vFromRoot;
vert.MDXData.vVertex = node.Mesh.TempVerts.at((unsigned short) face.nIndexVertex[i]);
if(node.Head.nType & NODE_DANGLY){
node.Dangly.Data2.push_back(node.Mesh.TempVerts.at((unsigned short) face.nIndexVertex[i]));
node.Dangly.Constraints.push_back(node.Dangly.TempConstraints.at((unsigned short) face.nIndexVertex[i]));
}
if(node.Head.nType & NODE_SKIN){
vert.MDXData.Weights = node.Skin.TempWeights.at((unsigned short) face.nIndexVertex[i]);
double fTotalWeight = 0.0;
fTotalWeight += vert.MDXData.Weights.fWeightValue.at(0);
fTotalWeight += vert.MDXData.Weights.fWeightValue.at(1);
fTotalWeight += vert.MDXData.Weights.fWeightValue.at(2);
fTotalWeight += vert.MDXData.Weights.fWeightValue.at(3);
if(abs(fTotalWeight - 1.0) >= 0.0001) ReportMdl << "Warning! Skin weights for ascii vertex " << (unsigned short) face.nIndexVertex[i] << " on '" << Data.MH.Names.at(node.Head.nNameIndex).sName << "' do not equal 1.0, instead they equal " << fTotalWeight << ". This may cause problems in the game.\n";
}
}
if(node.Mesh.TempTverts.size() > 0){
bIgnoreTvert = false;
vert.MDXData.vUV1 = node.Mesh.TempTverts.at((unsigned short) face.nIndexTvert[i]);
}
if(node.Mesh.TempTverts1.size() > 0){
bIgnoreTvert1 = false;
vert.MDXData.vUV2 = node.Mesh.TempTverts1.at((unsigned short) face.nIndexTvert1[i]);
}
if(node.Mesh.TempTverts2.size() > 0){
bIgnoreTvert2 = false;
vert.MDXData.vUV3 = node.Mesh.TempTverts2.at((unsigned short) face.nIndexTvert2[i]);
}
if(node.Mesh.TempTverts3.size() > 0){
bIgnoreTvert3 = false;
vert.MDXData.vUV4 = node.Mesh.TempTverts3.at((unsigned short) face.nIndexTvert3[i]);
}
if(node.Mesh.TempColors.size() > 0){
bIgnoreColor = false;
vert.MDXData.cColor = node.Mesh.TempColors.at((unsigned short) face.nIndexColor[i]);
}
if(node.Mesh.TempNormals.size() > 0){
bIgnoreNormal = false;
MdlInteger<unsigned short> nNormalIndex = face.nIndexNormal[i];
if(!nNormalIndex.Valid()) nNormalIndex = face.nIndexVertex[i];
vert.MDXData.vNormal = node.Mesh.TempNormals.at((unsigned short) nNormalIndex);
}
if(node.Mesh.TempTangent1.size() > 0){
bIgnoreTangent1 = false;
vert.MDXData.vTangent1 = node.Mesh.TempTangent1.at((unsigned short) face.nIndexVertex[i]);
}
//Find identical verts
for(int f2 = f; f2 < static_cast<int>(node.Mesh.Faces.size()); f2++){
Face & face2 = node.Mesh.Faces.at(f2);
for(int i2 = 0; i2 < 3; i2++){
//Make sure that we're only changing what's past our current position if we are in the same face.
if(f2 != f || i2 > i){
if(bMinimizeVerts){
try{
if( !face2.bProcessed[i2] &&
(bIgnoreVert || node.Mesh.TempVerts.at(face2.nIndexVertex[i2]).Compare(node.Mesh.TempVerts.at(face.nIndexVertex[i]), 0.00001) ) &&
(bIgnoreVert || !(node.Head.nType & NODE_DANGLY) || node.Dangly.TempConstraints.at(face2.nIndexVertex[i2]) == node.Dangly.TempConstraints.at(face.nIndexVertex[i]) ) &&
(bIgnoreVert || !(node.Head.nType & NODE_SKIN) || node.Skin.TempWeights.at(face2.nIndexVertex[i2]) == node.Skin.TempWeights.at(face.nIndexVertex[i]) ) &&
(bIgnoreTvert || node.Mesh.TempTverts.at(face2.nIndexTvert[i2]) == node.Mesh.TempTverts.at(face.nIndexTvert[i]) ) &&
(bIgnoreTvert1 || node.Mesh.TempTverts1.at(face2.nIndexTvert1[i2]) == node.Mesh.TempTverts1.at(face.nIndexTvert1[i]) ) &&
(bIgnoreTvert2 || node.Mesh.TempTverts2.at(face2.nIndexTvert2[i2]) == node.Mesh.TempTverts2.at(face.nIndexTvert2[i]) ) &&
(bIgnoreTvert3 || node.Mesh.TempTverts3.at(face2.nIndexTvert3[i2]) == node.Mesh.TempTverts3.at(face.nIndexTvert3[i]) ) &&
(bIgnoreColor || node.Mesh.TempColors.at(face2.nIndexColor[i2]) == node.Mesh.TempColors.at(face.nIndexColor[i]) ) &&
(bIgnoreNormal || node.Mesh.TempNormals.at(face2.nIndexNormal[i2].Valid() ? static_cast<unsigned short>(face2.nIndexNormal[i2]) : static_cast<unsigned short>(face2.nIndexVertex[i2])) == node.Mesh.TempNormals.at(face.nIndexNormal[i].Valid() ? static_cast<unsigned short>(face.nIndexNormal[i]) : static_cast<unsigned short>(face.nIndexVertex[i])) ) &&
(bIgnoreTangent1 ||
(node.Mesh.TempTangent1.at(face2.nIndexVertex[i2]).at(0) == node.Mesh.TempTangent1.at(face.nIndexVertex[i]).at(0) &&
node.Mesh.TempTangent1.at(face2.nIndexVertex[i2]).at(1) == node.Mesh.TempTangent1.at(face.nIndexVertex[i]).at(1) &&
node.Mesh.TempTangent1.at(face2.nIndexVertex[i2]).at(2) == node.Mesh.TempTangent1.at(face.nIndexVertex[i]).at(2))) &&
(!bIgnoreNormal || (face.nSmoothingGroup & face2.nSmoothingGroup)))
{
//If we find a reference to the exact same vert, we have to link to it
//Actually we only need to link vert indices, the correct UV are now already included in the Vertex struct
face2.nIndexVertex[i2] = CheckedAsciiVertexIndex(node.Mesh.Vertices.size(), "ASCII mesh post-processing");
face2.bProcessed[i2] = true;
}
}
catch(const std::exception & e){
throw mdlexception("Exception while handling temp arrays (face2=" + std::to_string(f2) + ", i2=" + std::to_string(i2) + ") node '" + Data.MH.Names.at(node.Head.nNameIndex).sName + "':\n" + e.what());
}
}
else{
if( (bIgnoreVert || face2.nIndexVertex[i2] == face.nIndexVertex[i] ) &&
(bIgnoreTvert || face2.nIndexTvert[i2] == face.nIndexTvert[i] ) &&
(bIgnoreTvert1 || face2.nIndexTvert1[i2] == face.nIndexTvert1[i] ) &&
(bIgnoreTvert2 || face2.nIndexTvert2[i2] == face.nIndexTvert2[i] ) &&
(bIgnoreTvert3 || face2.nIndexTvert3[i2] == face.nIndexTvert3[i] ) &&
(bIgnoreColor || face2.nIndexColor[i2] == face.nIndexColor[i] ) &&
(bIgnoreNormal || face2.nIndexNormal[i2] == face.nIndexNormal[i] ) &&
(bIgnoreTangent1 || face2.nIndexVertex[i2] == face.nIndexVertex[i] ) &&
!face2.bProcessed[i2] &&
(!bIgnoreNormal || (face.nSmoothingGroup & face2.nSmoothingGroup)))
{
//If we find a reference to the exact same vert, we have to link to it
//Actually we only need to link vert indices, the correct UV are now already included in the Vertex struct
face2.nIndexVertex[i2] = CheckedAsciiVertexIndex(node.Mesh.Vertices.size(), "ASCII mesh post-processing");
face2.bProcessed[i2] = true;
}
}
}
}
}
//Now we're allowed to link the original vert as well
face.nIndexVertex[i] = CheckedAsciiVertexIndex(node.Mesh.Vertices.size(), "ASCII mesh post-processing");
face.bProcessed[i] = true;
//Put the new vert into the array
node.Mesh.Vertices.push_back(std::move(vert));
}
}
std::array<unsigned short, 3> vertindicesarray = {face.nIndexVertex[0], face.nIndexVertex[1], face.nIndexVertex[2]};
node.Mesh.VertIndices.push_back(std::move(vertindicesarray));
/// Surprise! Face normal calculation! Moved here so it can be used by BuildAABB
Vertex & v1 = node.Mesh.Vertices.at(face.nIndexVertex[0]);
Vertex & v2 = node.Mesh.Vertices.at(face.nIndexVertex[1]);
Vertex & v3 = node.Mesh.Vertices.at(face.nIndexVertex[2]);
Vector & v1UV = v1.MDXData.vUV1;
Vector & v2UV = v2.MDXData.vUV1;
Vector & v3UV = v3.MDXData.vUV1;
Vector Edge1 = v2 - v1;
Vector Edge2 = v3 - v1;
Vector Edge3 = v3 - v2;
Vector EUV1 = v2UV - v1UV;
Vector EUV2 = v3UV - v1UV;
Vector EUV3 = v3UV - v2UV;
/// This is for the face normal
face.vNormal = cross(Edge1, Edge2); //Cross product, unnormalized
face.vNormal.Normalize();
/// This is for the distance.
face.fDistance = - (face.vNormal.fX * v1.fX +
face.vNormal.fY * v1.fY +
face.vNormal.fZ * v1.fZ);
// When the binary face runtime fields were
// supplied, keep them rather than mutating them during compile.
// Area/bounds/tangent calculations below still use the preserved
// face plane so user-visible edits can coexist with preservation.
if(face.bPreserveRuntimeFaceData){
face.vNormal = face.vPreservedNormal;
face.fDistance = face.fPreservedDistance;
face.nAdjacentFaces = face.nPreservedAdjacentFaces;
}
/// Area calculation
face.fArea = HeronFormulaEdge(Edge1, Edge2, Edge3);
face.fAreaUV = HeronFormulaEdge(EUV1, EUV2, EUV3);
/// TODO: report problematic cases
if(face.fArea != -1.0) node.Mesh.fTotalArea += face.fArea;
/// Tangent space vectors
//Now comes the calculation. Will be using edges 1 and 2
double r = (EUV1.fX * EUV2.fY - EUV1.fY * EUV2.fX);
//This is division, need to check for 0
if(r != 0){
r = 1.0 / r;
}
else{
/*
It can be 0 in several ways.
1. any of the two edges is zero (ie. we're dealing with a line, not a triangle) - this happens
2. both x's or both y's are zero, implying parallel edges, but we cannot have any in a triangle
3. both x's are the same and both y's are the same, therefore they have the same angle and are parallel
4. both edges have the same x and y, they both have a 45° angle and are therefore parallel
*/
//ndix UR's magic factor
r = 2406.6388;
}
face.vTangent = r * (Edge1 * EUV2.fY - Edge2 * EUV1.fY);
face.vBitangent = r * (Edge2 * EUV1.fX - Edge1 * EUV2.fX);
face.vTangent.Normalize();
face.vBitangent.Normalize();
if(face.vTangent.Null()) face.vTangent = Vector(1.0, 0.0, 0.0);
if(face.vBitangent.Null()) face.vBitangent = Vector(1.0, 0.0, 0.0);