-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathScnFileIO.cs
1837 lines (1568 loc) · 52.6 KB
/
ScnFileIO.cs
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
using NetsphereScnTool.Scene;
using NetsphereScnTool.Scene.Chunks;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Unity.Collections;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
#if PROBUILDER
using UnityEngine.ProBuilder;
#endif
using System.Linq;
namespace AevenScnTool.IO
{
public static class ScnFileImporter
{
public static Dictionary<SceneChunk, GameObject> createdObjects = new Dictionary<SceneChunk, GameObject>();
public static void BuildFromContainer(SceneContainer container, GameObject sceneObj, bool identityMatrix = false)
{
List < TreeItem < SceneChunk >> rootItems = GetRootItems(container);
createdObjects.Clear();
foreach (var item in rootItems)
{
BuildTreeItem(item, container, sceneObj, identityMatrix);
}
}
public static List<TreeItem<SceneChunk>> GetRootItems(SceneContainer container)
{
List<SceneChunk> chunks = new();
foreach (var item in container)
{
chunks.Add(item);
}
List<TreeItem<SceneChunk>> items = GetChildItems(chunks, null, container.Header.Name);
return items;
}
static List<TreeItem<SceneChunk>> GetChildItems(List<SceneChunk> chunks, TreeItem<SceneChunk> parentItem, string parentName)
{
var items = new List<TreeItem<SceneChunk>>();
for (int i = 0; i < chunks.Count; i++)
{
SceneChunk chunk = chunks[i];
if (parentItem == null)
{
if (chunk.SubName != parentName && chunk.SubName != string.Empty)
continue;
}
else
{
if (chunk.SubName != parentName)
continue;
}
var treeItem = new TreeItem<SceneChunk>
{
item = chunk,
parent = parentItem
};
items.Add(treeItem);
}
foreach (var item in items)
{
chunks.Remove(item.item);
}
foreach (var item in items)
{
var children = GetChildItems(chunks, item, item.item.Name);
item.childs = children;
}
return items;
}
static void BuildTreeItem(TreeItem<SceneChunk> treeItem, SceneContainer container, GameObject parent, bool identityMatrix)
{
GameObject go = BuildFromChunk(treeItem, container.fileInfo.Directory, parent, identityMatrix);
createdObjects.Add(treeItem.item, go);
foreach (var child in treeItem.childs)
{
BuildTreeItem(child, container, go, identityMatrix);
}
}
static GameObject BuildFromChunk(TreeItem<SceneChunk> treeItem, DirectoryInfo di, GameObject parent, bool identityMatrix)
{
return treeItem.item.ChunkType switch
{
ChunkType.Box => CreateBox(treeItem.item as BoxChunk, parent),
ChunkType.ModelData => CreateModel(treeItem.item as ModelChunk, di, parent, identityMatrix),
ChunkType.Bone => CreateBone(treeItem.item as BoneChunk, parent),
ChunkType.SkyDirect1 => CreateSkyDirect1(treeItem.item as SkyDirect1Chunk, parent),
ChunkType.BoneSystem => CreateBoneSystem(treeItem.item as BoneSystemChunk, parent),
ChunkType.Shape => CreateShape(treeItem.item as ShapeChunk, parent),
_ => null,
};
}
static GameObject CreateModel(ModelChunk model, DirectoryInfo di, GameObject parent, bool identityMatrix)
{
GameObject go = CreateGameObject(model);
go.transform.SetParent(parent.transform);
go.transform.localPosition = model.Matrix.GetPosition() / ScnToolData.Instance.scale;
go.transform.localRotation = model.Matrix.rotation;
go.transform.localScale = model.Matrix.lossyScale;
if (identityMatrix)
{
go.transform.position = Vector3.zero;
go.transform.rotation = Quaternion.identity;
go.transform.localScale = Vector3.one;
}
Mesh mesh = ModelChunkImporter.CreateMesh(model);
Material mat = ScnToolData.GetMatFromShader(model.Shader);
TextureReference tr = go.AddComponent<TextureReference>();
tr.renderFlags = model.Shader;
Material[] mats = ModelChunkImporter.SetFaceData(mesh, model, di, tr);
if (mats.Length == 0)
{
mats = new Material[1];
}
if (model.WeightBone.Count > 0)
{
ModelChunkImporter.SetSkinnedMesh(go, model, mesh, mats);
}
else if (model.Name.StartsWith("oct_") && ScnToolData.Instance.importCollisionAsVisual == false)
{
ModelChunkImporter.SetOctMesh(go, model, mesh);
}
else
{
MeshFilter mf = go.AddComponent<MeshFilter>();
MeshRenderer mr = go.AddComponent<MeshRenderer>();
mr.materials = mats;
mf.mesh = mesh;
}
int isAnim = ModelChunkImporter.ModelAnimationIsTransform(model.Animation);
if (isAnim == 1)
{
go.transform.localPosition = model.Animation[0].transformKeyData2.TransformKey.Translation / ScnToolData.Instance.scale;
go.transform.localRotation = model.Animation[0].transformKeyData2.TransformKey.Rotation;
go.transform.localScale = model.Animation[0].transformKeyData2.TransformKey.Scale;
}
else if (isAnim == 2)
{
go.transform.localPosition = model.Animation[0].transformKeyData2.TransformKey.Translation / ScnToolData.Instance.scale;
go.transform.localRotation = model.Animation[0].transformKeyData2.TransformKey.Rotation;
go.transform.localScale = model.Animation[0].transformKeyData2.TransformKey.Scale;
tr.transparency = model.Animation[0].transformKeyData2.AlphaKeys[0].Alpha;
}
else if(isAnim == 3){
go.transform.localPosition = model.Animation[0].transformKeyData2.TransformKey.Translation / ScnToolData.Instance.scale;
go.transform.localRotation = model.Animation[0].transformKeyData2.TransformKey.Rotation;
go.transform.localScale = model.Animation[0].transformKeyData2.TransformKey.Scale;
go.AddComponent<S4Animations>().FromModelAnimation(model.Animation);
}
else if (isAnim == -1)
{
//We do Nothing!!
}
else
{
go.AddComponent<S4Animations>().FromModelAnimation(model.Animation);
}
return go;
}
static GameObject CreateBox(BoxChunk box, GameObject parent)
{
GameObject go = CreateGameObject(box);
go.transform.SetParent(parent.transform);
go.transform.localPosition = box.Matrix.GetPosition() / ScnToolData.Instance.scale;
go.transform.localRotation = box.Matrix.rotation;
go.transform.localScale = box.Matrix.lossyScale;
go.AddComponent<BoxCollider>().size = box.Size / ScnToolData.Instance.scale * 2;
if (go.name.Contains("jump_dir") || go.name.Contains("jump_char"))
{
go.AddComponent<Jumppad>();
}
if (go.name.Contains("alpha_spawn_pos"))
{
go.AddComponent<PointDrawer>().type = PointDrawer.PointType.alpha_spawn_pos;
}
if (go.name.Contains("beta_spawn_pos"))
{
go.AddComponent<PointDrawer>().type = PointDrawer.PointType.beta_spawn_pos;
}
if (go.name.Contains("ball_spawn_pos"))
{
go.AddComponent<PointDrawer>().type = PointDrawer.PointType.ball_spawn_pos;
}
if (go.name.Contains("alpha_net"))
{
go.AddComponent<PointDrawer>().type = PointDrawer.PointType.alpha_net;
}
if (go.name.Contains("beta_net"))
{
go.AddComponent<PointDrawer>().type = PointDrawer.PointType.beta_net;
}
return go;
}
static GameObject CreateBone(BoneChunk bone, GameObject parent)
{
GameObject go = CreateGameObject(bone);
go.transform.SetParent(parent.transform);
var b = go.AddComponent<Bone>();
int isAnim = BoneAnimationIsTransform(bone.Animation);
if (isAnim == 1)
{
go.transform.localPosition = bone.Animation[0].TransformKeyData.TransformKey.Translation / ScnToolData.Instance.scale;
go.transform.localRotation = bone.Animation[0].TransformKeyData.TransformKey.Rotation;
go.transform.localScale = bone.Animation[0].TransformKeyData.TransformKey.Scale;
}
else if (isAnim == 2)
{
go.transform.localPosition = bone.Animation[0].TransformKeyData.TransformKey.Translation / ScnToolData.Instance.scale;
go.transform.localRotation = bone.Animation[0].TransformKeyData.TransformKey.Rotation;
go.transform.localScale = bone.Animation[0].TransformKeyData.TransformKey.Scale;
var s4a = go.AddComponent<S4Animations>();
s4a.FromBoneAnimation(bone.Animation);
b.s4Animations = s4a;
}
else if (isAnim == -1)
{
//We do Nothing!!
}
else
{
var s4a = go.AddComponent<S4Animations>();
s4a.FromBoneAnimation(bone.Animation);
b.s4Animations = s4a;
}
return go;
}
static GameObject CreateBoneSystem(BoneSystemChunk boneSys, GameObject parent)
{
GameObject go = CreateGameObject(boneSys);
go.transform.SetParent(parent.transform);
go.AddComponent<Bonesystem>();
return go;
}
static GameObject CreateShape(ShapeChunk shape, GameObject parent)
{
GameObject go = CreateGameObject(shape);
go.transform.SetParent(parent.transform);
go.transform.localPosition = shape.Matrix.GetPosition() / ScnToolData.Instance.scale;
go.transform.localRotation = shape.Matrix.rotation;
LineRenderer lr = go.AddComponent<LineRenderer>();
lr.widthMultiplier = 0.01f;
Vector3[] points = new Vector3[shape.Unk.Count * 2];
for (int i = 0; i < shape.Unk.Count; i++)
{
points[i * 2] = shape.Unk[i].Item1 / ScnToolData.Instance.scale;
points[i * 2 + 1] = shape.Unk[i].Item2 / ScnToolData.Instance.scale;
}
lr.useWorldSpace = false;
lr.SetPositions(points);
return go;
}
static GameObject CreateSkyDirect1(SkyDirect1Chunk chunk, GameObject parent)
{
GameObject go = CreateGameObject(chunk);
go.transform.SetParent(parent.transform);
TextMesh light = go.AddComponent<TextMesh>();
light.text = $"Color 1: {chunk.color1}\nColor 2: {chunk.color2}\nColor 3: {chunk.color3}\nColor 4: {chunk.color4}\nColor 5: {chunk.color5}\nColor 6: {chunk.color6}\n";
return go;
}
static GameObject CreateGameObject(SceneChunk chunk)
{
GameObject go = new GameObject(chunk.Name);
go.transform.position = chunk.Matrix.GetPosition() / ScnToolData.Instance.scale;
go.transform.rotation = chunk.Matrix.rotation;
go.transform.localScale = chunk.Matrix.lossyScale;
return go;
}
static int BoneAnimationIsTransform(List<BoneAnimation> anims)
{
if (anims.Count == 0)
{
return -1;
}
else if (anims.Count > 1)
{
return 0;
}
else if (anims.Count == 1)
{
var anim = anims[0];
if (anim.TransformKeyData.TransformKey.TKey.Count != 0)
{
return 0;
}
if (anim.TransformKeyData.TransformKey.RKey.Count != 0)
{
return 0;
}
if (anim.TransformKeyData.TransformKey.SKey.Count != 0)
{
return 0;
}
if (anim.TransformKeyData.AlphaKeys.Count != 0)
{
return 2;
}
return 1;
}
return 0;
}
public static Texture2D ParseTextureDXT(byte[] ddsBytes)
{
try
{
byte a = ddsBytes[84];
byte b = ddsBytes[85];
byte c = ddsBytes[86];
byte d = ddsBytes[87];
string format = System.Text.Encoding.ASCII.GetString(new byte[] { a, b, c, d });
//Debug.Log(format);
TextureFormat textureFormat = TextureFormat.DXT1;
if (format == "DXT3" || format == "DXT5")
{
textureFormat = TextureFormat.DXT5;
}
byte ddsSizeCheck = ddsBytes[4];
if (ddsSizeCheck != 124)
{
Debug.Log("Invalid DDS DXTn texture. Unable to read. Oh no, looks like the file wasnt a dds, or maybe it's corrupted, check it out!"); //this header byte should be 124 for DDS image files
return Texture2D.whiteTexture;
}
int height = ddsBytes[13] * 256 + ddsBytes[12];
int width = ddsBytes[17] * 256 + ddsBytes[16];
int DDS_HEADER_SIZE = 128;
byte[] dxtBytes = new byte[ddsBytes.Length - DDS_HEADER_SIZE];
Buffer.BlockCopy(ddsBytes, DDS_HEADER_SIZE, dxtBytes, 0, ddsBytes.Length - DDS_HEADER_SIZE);
Texture2D texture = new Texture2D(width, height, textureFormat, false);
texture.LoadRawTextureData(dxtBytes);
texture.Apply();
Color[] pixels = texture.GetPixels(0);
for (int i = 0; i < height / 2; i++)
{
for (int j = 0; j < width; j++)
{
int alpha = i * width + j;
int beta = (height - 1 - i) * width + j;
if(beta >= pixels.Length || beta < 0){
Debug.Log("Beta was " + beta + " from heigh: " + height + " minus 1 minus: " + i + " times: " + width + " plus: " + j + " and length is " + dxtBytes.Length);
}
Color buffer = pixels[alpha];
pixels[alpha] = pixels[beta];
pixels[beta] = buffer;
}
}
Texture2D finalTexture = new Texture2D(width, height);
finalTexture.SetPixels(pixels);
finalTexture.Apply();
return finalTexture;
}
catch (Exception e)
{
Debug.LogError("Oopsie daisy! Something went wrong!\n\n" + e.Message);
Debug.LogError(e.StackTrace);
return Texture2D.whiteTexture;
}
}
public static Texture2D LoadTGA(string fileName)
{
using (var imageFile = File.OpenRead(fileName))
{
return LoadTGA(imageFile);
}
}
public static Texture2D LoadTGA(Stream TGAStream)
{
try
{
using (BinaryReader r = new BinaryReader(TGAStream))
{
// Skip some header info we don't care about.
// Even if we did care, we have to move the stream seek point to the beginning,
// as the previous method in the workflow left it at the end.
r.BaseStream.Seek(12, SeekOrigin.Begin);
short width = r.ReadInt16();
short height = r.ReadInt16();
int bitDepth = r.ReadByte();
// Skip a byte of header information we don't care about.
r.BaseStream.Seek(1, SeekOrigin.Current);
Texture2D tex = new Texture2D(width, height);
Color32[] pulledColors = new Color32[width * height];
if (bitDepth == 32)
{
for (int i = 0; i < width * height; i++)
{
byte red = r.ReadByte();
byte green = r.ReadByte();
byte blue = r.ReadByte();
byte alpha = r.ReadByte();
pulledColors[i] = new Color32(blue, green, red, alpha);
}
}
else if (bitDepth == 24)
{
for (int i = 0; i < width * height; i++)
{
byte red = r.ReadByte();
byte green = r.ReadByte();
byte blue = r.ReadByte();
pulledColors[i] = new Color32(blue, green, red, 1);
}
}
else
{
Debug.Log("TGA texture had non 32/24 bit depth.");
return Texture2D.whiteTexture;
}
tex.SetPixels32(pulledColors);
tex.Apply();
return tex;
}
}
catch (Exception e)
{
Debug.LogError("Oopsie daisy! Something went wrong!\n\n" + e.Message);
return Texture2D.whiteTexture;
}
}
public static ScnData LoadModel(string path, bool identityMatrix = false)
{
SceneContainer container = SceneContainer.ReadFrom(path);
var go = new GameObject(container.Header.Name);
container.fileInfo = new FileInfo(path);
ScnData sd = go.AddComponent<ScnData>();
sd.filePath = path;
BuildFromContainer(container, go, identityMatrix);
return sd;
}
}
public class TreeItem<T>
{
public T item;
public List<TreeItem<T>> childs;
public TreeItem<T> parent;
}
public static class ModelChunkImporter
{
public static Dictionary<string, Material> MainMaterials = new Dictionary<string, Material>();
public static Dictionary<string, Material> SideMaterials = new Dictionary<string, Material>();
public static Mesh CreateMesh(ModelChunk model)
{
Mesh mesh = new Mesh();
var verts = model.Mesh.Vertices.ToArray().Clone() as Vector3[];
for (int i = 0; i < verts.Length; i++)
{
verts[i] = verts[i] / ScnToolData.Instance.scale;
}
mesh.vertices = verts;
mesh.normals = model.Mesh.Normals.ToArray().Clone() as Vector3[];
mesh.tangents = model.Mesh.TangentsArray().Clone() as Vector4[];
mesh.uv = model.Mesh.UV.ToArray().Clone() as Vector2[];
mesh.uv2 = model.Mesh.UV2.ToArray().Clone() as Vector2[];
return mesh;
}
public static void SetSkinnedMesh(GameObject go, ModelChunk model, Mesh mesh, Material[] mats)
{
SkinnedMeshRenderer smr = go.AddComponent<SkinnedMeshRenderer>();
smr.sharedMesh = mesh;
smr.materials = mats;
//WeightBone
byte[] bonesPerVertex = new byte[mesh.vertexCount];
List<BoneWeight1>[] weights = new List<BoneWeight1>[mesh.vertexCount];
List<Transform> bones = new List<Transform>();
List<Matrix4x4> bindPoses = new List<Matrix4x4>();
ExtractBoneWeightData(model, bones, bindPoses, bonesPerVertex, weights);
for (int i = 0; i < bindPoses.Count; i++)
{
var pose = bindPoses[i];
bindPoses[i] = Matrix4x4.TRS(pose.GetPosition() / ScnToolData.Instance.scale, pose.rotation, pose.lossyScale);
}
List<BoneWeight1> w = new List<BoneWeight1>();
for (int i = 0; i < weights.Length; i++)
{
w.AddRange(weights[i]);
}
NativeArray<BoneWeight1> w_na = new NativeArray<BoneWeight1>(w.ToArray(), Allocator.Temp);
NativeArray<byte> bpv = new NativeArray<byte>(bonesPerVertex, Allocator.Temp);
smr.sharedMesh.SetBoneWeights(bpv, w_na);
smr.sharedMesh.bindposes = bindPoses.ToArray();
smr.bones = bones.ToArray();
GameObject rootBone = null;
foreach (SceneChunk chunk in ScnFileImporter.createdObjects.Keys)
{
if (ScnFileImporter.createdObjects[chunk].name == model.SubName)
{
rootBone = ScnFileImporter.createdObjects[chunk];
break;
}
}
if (rootBone != null)
{
smr.rootBone = rootBone.transform;
}
smr.ResetBounds();
}
public static void ExtractBoneWeightData(ModelChunk model, List<Transform> bones, List<Matrix4x4> bindPoses, byte[] bonesPerVertex, List<BoneWeight1>[] weights)
{
for (int i = 0; i < model.WeightBone.Count; i++)
{
int boneIndex = GetBoneIndexFromBoneName(model.WeightBone[i].Name, bones);
bindPoses.Add(model.WeightBone[i].Matrix);
if (boneIndex == -1)
{
Debug.LogWarning($"Bone '{model.WeightBone[i].Name}' couldnt be found. Did you made an oppsie? :P");
continue;
}
for (int j = 0; j < model.WeightBone[i].Weight.Count; j++)
{
int index = (int)(model.WeightBone[i].Weight[j].Vertex);
bonesPerVertex[index]++;
if (weights[index] == null)
{
weights[index] = new List<BoneWeight1>();
}
BoneWeight1 bw = new BoneWeight1();
bw.boneIndex = boneIndex;
bw.weight = model.WeightBone[i].Weight[j].Weight;
weights[index].Add(bw);
}
}
}
public static Material[] SetFaceData(Mesh mesh, ModelChunk model, DirectoryInfo di, TextureReference tr)
{
Material mat = ScnToolData.GetMatFromShader(model.Shader);
Material[] mats = new Material[model.TextureData.Textures.Count];
if (model.TextureData.Textures.Count > 0)
{
mesh.subMeshCount = model.TextureData.Textures.Count;
int[] tris = model.Mesh.Triangles();
for (int i = 0; i < tris.Length; i++)
{
if (tris[i] >= mesh.vertexCount)
{
Debug.Log("Goodness me, some face index are above the vert count X:");
}
if (tris[i] < 0)
{
Debug.Log("Goodness me, face index are negative D:");
}
}
if (model.TextureData.ExtraUV == 2)
{
tr.isNormal = true;
}
for (int i = 0; i < model.TextureData.Textures.Count; i++)
{
TextureEntry texEntry = model.TextureData.Textures[i];
mesh.SetTriangles(tris, texEntry.face_offset * 3, texEntry.face_count * 3, i);
Material mat_x = new Material(mat);
string mainTex = string.Empty;
if (texEntry.main_texture != string.Empty)
{
mainTex = di.FullName + Path.DirectorySeparatorChar + texEntry.main_texture.Replace(".tga", ".dds");
if (File.Exists(mainTex))
{
mat_x.mainTexture = LoadTexture(mainTex);
}
else{
string localMainTex = Application.dataPath + Path.DirectorySeparatorChar + "S4 Map Textures" + Path.DirectorySeparatorChar + texEntry.main_texture.Replace(".tga", ".dds");
mainTex = "Assets" + Path.DirectorySeparatorChar + "S4 Map Textures" + Path.DirectorySeparatorChar + texEntry.main_texture.Replace(".tga", ".dds");
if(File.Exists(localMainTex)){
mat_x.mainTexture = LoadTexture(localMainTex);
}
}
}
string sideTex = string.Empty;
if (texEntry.side_texture != string.Empty)
{
sideTex = di.FullName + Path.DirectorySeparatorChar + texEntry.side_texture.Replace(".tga", ".dds");
Debug.Log("sideTex: " + sideTex);
Texture2D st = null;
if (File.Exists(sideTex))
{
st = LoadTexture(sideTex);
}
else{
string localSideTex = Application.dataPath + Path.DirectorySeparatorChar + "S4 Map Textures" + Path.DirectorySeparatorChar + texEntry.side_texture.Replace(".tga", ".dds");
sideTex = "Assets" + Path.DirectorySeparatorChar + "S4 Map Textures" + Path.DirectorySeparatorChar + texEntry.side_texture.Replace(".tga", ".dds");
Debug.Log("localSideTex: " + localSideTex);
if(File.Exists(localSideTex)){
st = LoadTexture(localSideTex);
sideTex = localSideTex;
}
}
if (model.TextureData.ExtraUV == 1)
{
mat_x.SetTexture("_DetailAlbedoMap", st);
mat_x.EnableKeyword("_DETAIL_MULX2");
}
else
{
mat_x.SetTexture("_BumpMap", st);
mat_x.EnableKeyword("_NORMALMAP");
}
}
tr.textures.Add(new TextureItem(texEntry.main_texture, mainTex, sideTex));
mats[i] = mat_x;
}
}
else
{
mesh.triangles = model.Mesh.Triangles();
}
return mats;
}
static Texture2D LoadTexture(string path )
{
if (path.EndsWith(".tga"))
{
if (File.Exists(path))
{
return ScnFileImporter.LoadTGA(path);
}
else
{
path = path.Replace(".tga", ".dds");
if (File.Exists(path))
{
return ScnFileImporter.ParseTextureDXT(File.ReadAllBytes(path));
}
}
}
else if (path.EndsWith(".dds"))
{
if (File.Exists(path))
{
return ScnFileImporter.ParseTextureDXT(File.ReadAllBytes(path));
}
else
{
path = path.Replace(".dds", ".tga");
if (File.Exists(path))
{
return ScnFileImporter.LoadTGA(path);
}
}
}
return Texture2D.whiteTexture;
}
public static int GetBoneIndexFromBoneName(string name, List<Transform> bones)
{
GameObject go = null;
foreach (SceneChunk chunk in ScnFileImporter.createdObjects.Keys)
{
if (ScnFileImporter.createdObjects[chunk].name == name)
{
go = ScnFileImporter.createdObjects[chunk];
break;
}
}
if (go == null) return -1;
bones.Add(go.transform);
return bones.Count - 1;
}
public static void SetOctMesh(GameObject go, ModelChunk model, Mesh mesh)
{
MeshCollider mc = go.AddComponent<MeshCollider>();
CollisionData cd = go.AddComponent<CollisionData>();
string oct_name = model.Name[4..];
if (oct_name == "NONE")
{
cd.ground = GroundFlag.blast;
}
else if (Double.TryParse(oct_name, out _))
{
cd.ground = GroundFlag.blast;
}
else if (Enum.TryParse(oct_name, out GroundFlag result1))
{
cd.ground = result1;
}
else if (Enum.TryParse(oct_name, out WeaponFlag result2))
{
cd.weapon = result2;
}
else
{
cd.ground = GroundFlag.blast;
}
mc.cookingOptions = MeshColliderCookingOptions.EnableMeshCleaning;
if (mesh.vertices.Length > 0)
{
mc.sharedMesh = mesh;
}
}
public static int ModelAnimationIsTransform(List<ModelAnimation> anims)
{
if (anims.Count == 0)
{
return -1;
}
else if (anims.Count > 1)
{
return 0;
}
else if (anims.Count == 1)
{
var anim = anims[0];
if (anim.transformKeyData2.TransformKey.TKey.Count != 0)
{
return 0;
}
if (anim.transformKeyData2.TransformKey.RKey.Count != 0)
{
return 0;
}
if (anim.transformKeyData2.TransformKey.SKey.Count != 0)
{
return 0;
}
if (anim.transformKeyData2.MorphKeys.Count != 0)
{
return 0;
}
if (anim.transformKeyData2.AlphaKeys.Count == 1)
{
if (anim.transformKeyData2.AlphaKeys[0].Alpha != 1f)
{
return 2;
}
}
if (anim.transformKeyData2.AlphaKeys.Count != 0)
{
return 3;
}
return 1;
}
return 0;
}
}
public static class AnimationImporter
{
public static List<TreeItem<(string Object_Name, List<S4Animation> anims)>> LoadAnimations(string path)
{
SceneContainer sc = SceneContainer.ReadFrom(path);
if (sc != null)
{
return LoadAnimations(sc);
}
return null;
}
public static List<TreeItem<(string Object_Name, List<S4Animation> anims)>> LoadAnimations(SceneContainer container)
{
List<TreeItem<SceneChunk>> root = ScnFileImporter.GetRootItems(container);
List<TreeItem<(string Object_Name, List<S4Animation>)>> anims = new();
for (int i = 0; i < root.Count; i++)
{
anims.Add(Transcript(root[i]));
}
return anims;
}
static TreeItem<(string Object_Name, List<S4Animation> anims)> Transcript(TreeItem<SceneChunk> node)
{
TreeItem<(string Object_Name, List<S4Animation> anims)> anim_node = new();
anim_node.item.Object_Name = node.item.Name;
anim_node.item.anims = new();
if (node.item is ModelChunk mc)
{
for (int i = 0; i < mc.Animation.Count; i++)
{
anim_node.item.anims.Add(new S4Animation(mc.Animation[i]));
}
}
else if (node.item is BoneChunk bc)
{
for (int i = 0; i < bc.Animation.Count; i++)
{
anim_node.item.anims.Add(new S4Animation(bc.Animation[i]));
}
}
for (int i = 0; i < node.childs.Count; i++)
{
var child = Transcript(node.childs[i]);
anim_node.childs.Add(child);
child.parent = anim_node;
}
return anim_node;
}
}
public static class ScnFileExporter
{
static List<string> usedNames = new List<string>();
public static Dictionary<int,(string name,Texture2D tex)> lightmaps = new Dictionary<int,(string name, Texture2D tex)>();
public static string lightmapName = "";
public static SceneContainer CreateContainerFromScenes(string name, ScnData[] scenes)
{
usedNames.Clear();
lightmaps.Clear();
SceneContainer container = new SceneContainer();
container.Header.Name = name;
foreach (var scene in scenes)
{
lightmapName = scene.lightmapName;
CreateChunksFromChildren(scene.transform,scene.transform, container, null);
S4Armature armature = scene.GetComponent<S4Armature>();
if(armature != null){
armature.WriteAnimationsToSceneContainer(container);
}
}
lightmapName = "";
return container;
}
public static void CreateChunksFromChildren(Transform parent, Transform relativeParent, SceneContainer container, SceneChunk parentChunk)
{
try{
for (int i = 0; i < parent.childCount; i++)
{
Transform child = parent.GetChild(i);
if (!child.gameObject.activeInHierarchy)
{
continue;
}
SceneChunk childChunk = CreateChunk(child, container, parentChunk, relativeParent);
Transform relative;
if (childChunk != null)
{
relative = child;
}
else
{
relative = relativeParent;
childChunk = parentChunk;
}
CreateChunksFromChildren(child, relative, container, childChunk);
EditorUtility.DisplayProgressBar($"Parsing unity scene! OwO", $"{child.name}", (float)i/(float)parent.childCount);
}
EditorUtility.ClearProgressBar();
}
catch(Exception e){
EditorUtility.ClearProgressBar();
Debug.LogError(e.StackTrace);
throw e;
}
}
static SceneChunk CreateChunk(Transform child, SceneContainer container, SceneChunk parentChunk, Transform relativeParent)
{
Bone bone = child.GetComponent<Bone>();
if (bone) return CreateBoneChunk(bone, container, parentChunk);
Bonesystem bonesystem = child.GetComponent<Bonesystem>();
if (bonesystem) return CreateBoneSystemChunk(bonesystem, container, parentChunk);
SkinnedMeshRenderer smr = child.GetComponent<SkinnedMeshRenderer>();
if (smr) return ModelChunkExporter.CreateModelChunkSkinned(smr, container, parentChunk, relativeParent);
MeshRenderer mr = child.GetComponent<MeshRenderer>();
if (mr)
{
var mesh = ModelChunkExporter.CreateModelChunk(mr, container, parentChunk, relativeParent);
CollisionData cd_mr = child.GetComponent<CollisionData>();
if (cd_mr)
{
ModelChunkExporter.CreateCollisionChunk(cd_mr, container, mesh);
}
return mesh;
}