forked from alvani/Unity-glTF-Exporter
-
Notifications
You must be signed in to change notification settings - Fork 14
/
GlTF_Writer.cs
657 lines (567 loc) · 18 KB
/
GlTF_Writer.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
#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class GlTF_Writer {
public static FileStream fs;
public static StreamWriter jsonWriter;
public static BinaryWriter binWriter;
public static Stream binFile;
public static int indent = 0;
public static string binFileName;
public static bool binary;
static bool[] firsts = new bool[100];
public static GlTF_BufferView ushortBufferView = new GlTF_BufferView("ushortBufferView", 0, 34963);
public static GlTF_BufferView floatBufferView = new GlTF_BufferView("floatBufferView", 0);
public static GlTF_BufferView vec2BufferView = new GlTF_BufferView("vec2BufferView", 8);
public static GlTF_BufferView vec3BufferView = new GlTF_BufferView("vec3BufferView", 12);
public static GlTF_BufferView vec4BufferView = new GlTF_BufferView("vec4BufferView", 16);
public static GlTF_BufferView vec4UshortBufferView = new GlTF_BufferView("vec4UshortBufferView", 8);
public static GlTF_BufferView mat4BufferView = new GlTF_BufferView("mat4BufferView", 64);
public static GlTF_BufferView vec3BufferViewAnim = new GlTF_BufferView("vec3BufferViewAnim", 12);
public static GlTF_BufferView vec4BufferViewAnim = new GlTF_BufferView("vec4BufferViewAnim", 16);
public static List<GlTF_BufferView> bufferViews = new List<GlTF_BufferView>();
public static List<GlTF_Camera> cameras = new List<GlTF_Camera>();
public static List<GlTF_Light> lights = new List<GlTF_Light>();
public static List<GlTF_Mesh> meshes = new List<GlTF_Mesh>();
public static List<GlTF_Accessor> accessors = new List<GlTF_Accessor>();
public static List<string> nodeNames = new List<string>();
public static List<GlTF_Node> nodes = new List<GlTF_Node>();
public static List<string> materialNames = new List<string>();
public static List<GlTF_Material> materials = new List<GlTF_Material>();
public static List<string> samplerNames = new List<string>();
public static List<GlTF_Sampler> samplers = new List<GlTF_Sampler>();
public static List<string> textureNames = new List<string>();
public static List<GlTF_Texture> textures = new List<GlTF_Texture>();
public static List<string> imageNames = new List<string>();
public static List<GlTF_Image> images = new List<GlTF_Image>();
public static List<GlTF_Animation> animations = new List<GlTF_Animation>();
public static List<string> techniqueNames = new List<string>();
public static List<GlTF_Technique> techniques = new List<GlTF_Technique>();
public static List<GlTF_Program> programs = new List<GlTF_Program>();
public static List<GlTF_Shader> shaders = new List<GlTF_Shader>();
public static List<GlTF_Skin> skins = new List<GlTF_Skin>();
public static List<GlTF_Node> rootNodes = new List<GlTF_Node>();
// Keys are original file path, values correspond to the directory in the output zip file
public static Dictionary<string, string> exportedFiles = new Dictionary<string, string>();
// Exporter specifics
public static bool bakeAnimation;
public static bool exportPBRMaterials;
public static bool hasSpecularMaterials = false;
public static bool convertRightHanded = true;
public static string exporterVersion = "2.2.1";
public static Regex rgx = new Regex("[^a-zA-Z0-9 -_.]");
static public string cleanNonAlphanumeric(string s)
{
return rgx.Replace(s, "");
}
static public string GetNameFromObject(Object o, bool useId = false)
{
var ret = cleanNonAlphanumeric(o.name);
if (useId)
{
ret += "_" + o.GetInstanceID();
}
return ret;
}
public void convertVector3LeftToRightHandedness(ref Vector3 vect)
{
vect.z = -vect.z;
}
public void convertVector4LeftToRightHandedness(ref Vector4 vect)
{
vect.z = -vect.z;
vect.w = -vect.w;
}
public void convertQuatLeftToRightHandedness(ref Quaternion quat)
{
quat.w = -quat.w;
quat.z = -quat.z;
}
// Decomposes a matrix, converts each component from left to right handed and
// rebuilds a matrix
// FIXME: there is probably a better way to do that. It doesn't work well with non uniform scales
public void convertMatrixLeftToRightHandedness(ref Matrix4x4 mat)
{
Vector3 position = mat.GetColumn(3);
convertVector3LeftToRightHandedness(ref position);
Quaternion rotation = Quaternion.LookRotation(mat.GetColumn(2), mat.GetColumn(1));
convertQuatLeftToRightHandedness(ref rotation);
Vector3 scale = new Vector3(mat.GetColumn(0).magnitude, mat.GetColumn(1).magnitude, mat.GetColumn(2).magnitude);
float epsilon = 0.00001f;
// Some issues can occurs with non uniform scales
if(Mathf.Abs(scale.x - scale.y) > epsilon || Mathf.Abs(scale.y - scale.z) > epsilon || Mathf.Abs(scale.x - scale.z) > epsilon)
{
Debug.LogWarning("A matrix with non uniform scale is being converted from left to right handed system. This code is not working correctly in this case");
}
// Handle negative scale component in matrix decomposition
if (Matrix4x4.Determinant(mat) < 0)
{
Quaternion rot = Quaternion.LookRotation(mat.GetColumn(2), mat.GetColumn(1));
Matrix4x4 corr = Matrix4x4.TRS(mat.GetColumn(3), rot, Vector3.one).inverse;
Matrix4x4 extractedScale = corr * mat;
scale = new Vector3(extractedScale.m00, extractedScale.m11, extractedScale.m22);
}
// convert transform values from left handed to right handed
mat.SetTRS(position, rotation, scale);
}
public void Init()
{
firsts = new bool[100];
ushortBufferView = new GlTF_BufferView("ushortBufferView", 0, 34963);
floatBufferView = new GlTF_BufferView("floatBufferView", 0);
vec2BufferView = new GlTF_BufferView("vec2BufferView", 8);
vec3BufferView = new GlTF_BufferView("vec3BufferView", 12);
vec4BufferView = new GlTF_BufferView("vec4BufferView", 16);
vec4UshortBufferView = new GlTF_BufferView("vec4iBufferView", 8);
mat4BufferView = new GlTF_BufferView("mat4BufferView", 64);
//Animation
vec3BufferViewAnim = new GlTF_BufferView("vec3BufferViewAnim", 12);
vec4BufferViewAnim = new GlTF_BufferView("vec4BufferViewAnim", 16);
vec2BufferView.target = (int)GlTF_BufferView.TARGET.ARRAY;
vec3BufferView.target = (int)GlTF_BufferView.TARGET.ARRAY;
vec4BufferView.target = (int)GlTF_BufferView.TARGET.ARRAY;
ushortBufferView.target = (int)GlTF_BufferView.TARGET.ELEMENT;
bufferViews = new List<GlTF_BufferView>();
cameras = new List<GlTF_Camera>();
lights = new List<GlTF_Light>();
meshes = new List<GlTF_Mesh>();
accessors = new List<GlTF_Accessor>();
nodes = new List<GlTF_Node>();
nodeNames = new List<string>();
materialNames = new List<string>();
materials = new List<GlTF_Material>();
samplerNames = new List<string>();
samplers = new List<GlTF_Sampler>();
textureNames = new List<string>();
textures = new List<GlTF_Texture>();
imageNames = new List<string>();
images = new List<GlTF_Image>();
animations = new List<GlTF_Animation>();
techniqueNames = new List<string>();
techniques = new List<GlTF_Technique>();
programs = new List<GlTF_Program>();
shaders = new List<GlTF_Shader>();
skins = new List<GlTF_Skin>();
rootNodes = new List<GlTF_Node>();
bakeAnimation = true;
hasSpecularMaterials = false;
}
public void Indent() {
for (int i = 0; i < indent; i++)
jsonWriter.Write ("\t");
}
public void IndentIn() {
indent++;
firsts[indent] = true;
}
public void IndentOut() {
indent--;
}
public void CommaStart() {
firsts[indent] = false;
}
public void CommaNL() {
if (!firsts[indent])
jsonWriter.Write (",\n");
firsts[indent] = false;
}
public string id;
public string name; // name of this object
// Extra data for objects
public Dictionary<string, string> extraString = new Dictionary<string, string>();
public Dictionary<string, float> extraFloat = new Dictionary<string, float>();
public Dictionary<string, bool> extraBool = new Dictionary<string, bool>();
public void OpenFiles (string filepath) {
fs = File.Open(filepath, FileMode.Create);
exportedFiles.Add(filepath, ""); // Value is an empty string since we want the file at the root of the .zip file
if (binary)
{
binWriter = new BinaryWriter(fs);
binFile = fs;
fs.Seek(20, SeekOrigin.Begin); // header skip
}
else
{
// separate bin file
binFileName = Path.GetFileNameWithoutExtension(filepath) + ".bin";
var binPath = Path.Combine(Path.GetDirectoryName(filepath), binFileName);
exportedFiles.Add(binPath, ""); // Value is an empty string since we want the file at the root of the .zip file
binFile = File.Open(binPath, FileMode.Create);
}
jsonWriter = new StreamWriter (fs);
}
public void CloseFiles() {
if (binary)
{
binWriter.Close();
}
else
{
binFile.Close();
}
jsonWriter.Close ();
fs.Close();
}
public void writeExtras()
{
if (extraFloat.Count > 0 || extraString.Count > 0 || extraBool.Count > 0)
{
Indent(); jsonWriter.Write("\"extras\": {\n");
IndentIn();
foreach (var s in extraString)
{
CommaNL();
Indent(); jsonWriter.Write("\"" + s.Key + "\" : \"" + s.Value + "\"");
}
foreach (var s in extraFloat)
{
CommaNL();
Indent(); jsonWriter.Write("\"" + s.Key + "\" : " + s.Value + "");
}
foreach (var s in extraBool)
{
CommaNL();
Indent(); jsonWriter.Write("\"" + s.Key + "\" : " + (s.Value ? "true" : "false") + "");
}
IndentOut();
jsonWriter.Write("\n");
Indent(); jsonWriter.Write("},");
jsonWriter.Write("\n");
}
}
public virtual void Write () {
if(ushortBufferView.byteLength > 0)
bufferViews.Add (ushortBufferView);
if (floatBufferView.byteLength > 0)
bufferViews.Add (floatBufferView);
if (vec2BufferView.byteLength > 0)
bufferViews.Add (vec2BufferView);
if (vec3BufferView.byteLength > 0)
bufferViews.Add (vec3BufferView);
if (vec4BufferView.byteLength > 0)
bufferViews.Add (vec4BufferView);
if (vec4UshortBufferView.byteLength > 0)
bufferViews.Add(vec4UshortBufferView);
if (mat4BufferView.byteLength > 0)
bufferViews.Add (mat4BufferView);
if (vec3BufferViewAnim.byteLength > 0)
bufferViews.Add(vec3BufferViewAnim);
if (vec4BufferViewAnim.byteLength > 0)
bufferViews.Add(vec4BufferViewAnim);
ushortBufferView.bin = binary;
floatBufferView.bin = binary;
vec2BufferView.bin = binary;
vec3BufferView.bin = binary;
vec4BufferView.bin = binary;
vec4UshortBufferView.bin = binary;
mat4BufferView.bin = binary;
vec3BufferViewAnim.bin = binary;
vec4BufferViewAnim.bin = binary;
// write memory streams to binary file
floatBufferView.byteOffset = 0;
vec2BufferView.byteOffset = floatBufferView.byteOffset + floatBufferView.byteLength;
vec3BufferView.byteOffset = vec2BufferView.byteOffset + vec2BufferView.byteLength;
vec4BufferView.byteOffset = vec3BufferView.byteOffset + vec3BufferView.byteLength;
vec4UshortBufferView.byteOffset = vec4BufferView.byteOffset + vec4BufferView.byteLength;
mat4BufferView.byteOffset = vec4UshortBufferView.byteOffset + vec4UshortBufferView.byteLength;
ushortBufferView.byteOffset = mat4BufferView.byteOffset + mat4BufferView.byteLength;
vec3BufferViewAnim.byteOffset = ushortBufferView.byteOffset + ushortBufferView.byteLength;
vec4BufferViewAnim.byteOffset = vec3BufferViewAnim.byteOffset + vec3BufferViewAnim.byteLength;
long bufferByteLength = vec4BufferViewAnim.byteOffset + vec4BufferViewAnim.byteLength;
jsonWriter.Write ("{\n");
IndentIn();
// asset
CommaNL();
Indent(); jsonWriter.Write ("\"asset\": {\n");
IndentIn();
Indent(); jsonWriter.Write ("\"generator\": \"Unity "+ Application.unityVersion + "\",\n");
writeExtras();
Indent(); jsonWriter.Write ("\"version\": \"2.0\"\n");
IndentOut();
Indent(); jsonWriter.Write ("}");
if (accessors != null && accessors.Count > 0)
{
CommaNL();
Indent(); jsonWriter.Write ("\"accessors\": [\n");
IndentIn();
foreach (GlTF_Accessor a in accessors)
{
CommaNL();
a.Write ();
}
jsonWriter.WriteLine();
IndentOut();
Indent(); jsonWriter.Write ("]");
}
if (animations.Count > 0)
{
CommaNL();
Indent(); jsonWriter.Write ("\"animations\": [\n");
IndentIn();
foreach (GlTF_Animation a in animations)
{
CommaNL();
a.Write ();
}
jsonWriter.WriteLine();
IndentOut();
Indent(); jsonWriter.Write ("]");
}
if (!binary)
{
// FIX: Should support multiple buffers
CommaNL();
Indent(); jsonWriter.Write ("\"buffers\": [\n");
IndentIn();
Indent(); jsonWriter.Write ("{\n");
IndentIn();
Indent(); jsonWriter.Write ("\"byteLength\": "+ (bufferByteLength) +",\n");
Indent(); jsonWriter.Write ("\"uri\": \"" + GlTF_Writer.binFileName + "\"\n");
IndentOut();
Indent(); jsonWriter.Write ("}\n");
IndentOut();
Indent(); jsonWriter.Write ("]");
}
else
{
CommaNL();
Indent(); jsonWriter.Write ("\"buffers\": {\n");
IndentIn();
Indent(); jsonWriter.Write ("\"binary_glTF\": {\n");
IndentIn();
Indent(); jsonWriter.Write ("\"byteLength\": "+ (vec4BufferViewAnim.byteOffset+ vec4BufferViewAnim.byteLength)+",\n");
Indent(); jsonWriter.Write ("\"type\": \"arraybuffer\"\n");
IndentOut();
Indent(); jsonWriter.Write ("}\n");
IndentOut();
Indent(); jsonWriter.Write ("}");
}
if (bufferViews != null && bufferViews.Count > 0)
{
CommaNL();
Indent(); jsonWriter.Write ("\"bufferViews\": [\n");
IndentIn();
foreach (GlTF_BufferView bv in bufferViews)
{
if (bv.byteLength > 0)
{
CommaNL();
bv.Write ();
}
}
jsonWriter.WriteLine();
IndentOut();
Indent(); jsonWriter.Write ("]");
}
if (cameras != null && cameras.Count > 0)
{
CommaNL();
Indent(); jsonWriter.Write ("\"cameras\": [\n");
IndentIn();
foreach (GlTF_Camera c in cameras)
{
CommaNL();
c.Write ();
}
jsonWriter.WriteLine();
IndentOut();
Indent(); jsonWriter.Write ("]");
}
if(hasSpecularMaterials)
{
CommaNL();
Indent(); jsonWriter.Write("\"extensionsRequired\": [\n");
IndentIn();
Indent(); jsonWriter.Write("\"KHR_materials_pbrSpecularGlossiness\"\n");
IndentOut();
Indent(); jsonWriter.Write("]");
}
if(hasSpecularMaterials || binary)
{
CommaNL();
Indent(); jsonWriter.Write("\"extensionsUsed\": [\n");
IndentIn();
if (hasSpecularMaterials)
{
Indent(); jsonWriter.Write("\"KHR_materials_pbrSpecularGlossiness\"\n");
}
if (binary)
{
Indent(); jsonWriter.Write("\"KHR_binary_glTF\"\n");
}
IndentOut();
Indent(); jsonWriter.Write("]");
}
if (images.Count > 0)
{
CommaNL();
Indent(); jsonWriter.Write ("\"images\": [\n");
IndentIn();
foreach (var i in images)
{
CommaNL();
i.Write ();
}
jsonWriter.WriteLine();
IndentOut();
Indent(); jsonWriter.Write ("]");
}
if (materials.Count > 0)
{
CommaNL();
Indent(); jsonWriter.Write ("\"materials\": [\n");
IndentIn();
foreach (GlTF_Material m in materials)
{
CommaNL();
m.Write ();
}
jsonWriter.WriteLine();
IndentOut();
Indent(); jsonWriter.Write ("]");
}
if (meshes != null && meshes.Count > 0)
{
CommaNL();
Indent();
jsonWriter.Write ("\"meshes\": [\n");
IndentIn();
foreach (GlTF_Mesh m in meshes)
{
CommaNL();
m.Write ();
}
jsonWriter.WriteLine();
IndentOut();
Indent();
jsonWriter.Write ("]");
}
if (nodes != null && nodes.Count > 0)
{
CommaNL();
Indent(); jsonWriter.Write ("\"nodes\": [\n");
IndentIn();
foreach (GlTF_Node n in nodes)
{
CommaNL();
n.Write();
}
jsonWriter.WriteLine();
IndentOut();
Indent(); jsonWriter.Write ("]");
}
if (samplers.Count > 0)
{
CommaNL();
Indent(); jsonWriter.Write ("\"samplers\": [\n");
IndentIn();
foreach (GlTF_Sampler s in samplers)
{
CommaNL();
s.Write ();
}
jsonWriter.WriteLine();
IndentOut();
Indent(); jsonWriter.Write ("]");
}
CommaNL();
Indent(); jsonWriter.Write ("\"scenes\": [\n");
IndentIn();
Indent(); jsonWriter.Write ("{\n");
IndentIn();
CommaNL();
Indent(); jsonWriter.Write("\"name\":\"defaultScene\",\n");
Indent(); jsonWriter.Write ("\"nodes\": [\n");
IndentIn();
foreach (GlTF_Node n in rootNodes)
{
CommaNL();
Indent(); jsonWriter.Write(nodes.IndexOf(n));
}
jsonWriter.WriteLine();
IndentOut();
Indent(); jsonWriter.Write ("]\n");
IndentOut();
Indent(); jsonWriter.Write ("}\n");
IndentOut();
Indent(); jsonWriter.Write ("],\n");
Indent(); jsonWriter.Write("\"scene\": 0");
if(skins.Count > 0)
{
CommaNL();
Indent(); jsonWriter.Write("\"skins\": [\n");
IndentIn();
foreach(GlTF_Skin skin in skins)
{
CommaNL();
skin.Write();
}
jsonWriter.WriteLine();
IndentOut();
Indent(); jsonWriter.Write("]");
}
if (textures.Count > 0)
{
CommaNL();
Indent(); jsonWriter.Write ("\"textures\": [\n");
IndentIn();
foreach (GlTF_Texture t in textures)
{
CommaNL();
t.Write ();
}
jsonWriter.WriteLine();
IndentOut();
Indent(); jsonWriter.Write ("]");
}
IndentOut();
jsonWriter.Write ("\n}");
jsonWriter.Flush();
uint contentLength = 0;
if (binary)
{
long curLen = fs.Position;
var rem = curLen % 4;
if (rem != 0)
{
// add padding if not aligned to 4 bytes
var next = (curLen / 4 + 1) * 4;
rem = next - curLen;
for (int i = 0; i < rem; ++i)
{
jsonWriter.Write(" ");
}
}
jsonWriter.Flush();
// current pos - header size
contentLength = (uint)(fs.Position - 20);
}
floatBufferView.memoryStream.WriteTo(binFile);
vec2BufferView.memoryStream.WriteTo (binFile);
vec3BufferView.memoryStream.WriteTo (binFile);
vec4BufferView.memoryStream.WriteTo (binFile);
vec4UshortBufferView.memoryStream.WriteTo(binFile);
mat4BufferView.memoryStream.WriteTo(binFile);
ushortBufferView.memoryStream.WriteTo(binFile);
vec3BufferViewAnim.memoryStream.WriteTo(binFile);
vec4BufferViewAnim.memoryStream.WriteTo(binFile);
binFile.Flush();
if (binary)
{
uint fileLength = (uint)fs.Length;
// write header
fs.Seek(0, SeekOrigin.Begin);
jsonWriter.Write("glTF"); // magic
jsonWriter.Flush();
binWriter.Write(1); // version
binWriter.Write(fileLength);
binWriter.Write(contentLength);
binWriter.Write(0); // format
binWriter.Flush();
}
}
}
#endif