-
Notifications
You must be signed in to change notification settings - Fork 0
/
GLTFSceneExporter.cs
1406 lines (1195 loc) · 50.1 KB
/
GLTFSceneExporter.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 UnityGLTF.Plugins;
using UnityGLTF.Extensions;
using GLTF.Schema;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System;
#if UNITY_EDITOR
#define ANIMATION_EXPORT_SUPPORTED
#endif
#if ANIMATION_EXPORT_SUPPORTED && (UNITY_ANIMATION || !UNITY_2019_1_OR_NEWER)
#define ANIMATION_SUPPORTED
#endif
using System.Text;
using System.Text.RegularExpressions;
using Barbershop.gltf;
using Il2CppInterop.Runtime;
using Unity.Profiling;
using UnityEngine;
using Color = System.Drawing.Color;
namespace UnityGLTF
{
public class ExportContext
{
public bool TreatEmptyRootAsScene = false;
public bool MergeClipsWithMatchingNames = false;
public LayerMask ExportLayers = -1;
public INetLogger logger;
internal readonly GLTFSettings settings;
public ExportContext() : this(GLTFSettings.GetOrCreateSettings()) { }
public ExportContext(GLTFSettings settings)
{
if (settings == null) settings = GLTFSettings.GetOrCreateSettings();
if (settings.UseMainCameraVisibility)
ExportLayers = Camera.main ? Camera.main.cullingMask : -1;
this.settings = settings;
}
public GLTFSceneExporter.RetrieveTexturePathDelegate TexturePathRetriever = (texture) => texture.name;
// TODO Should we make all the callbacks on ExportContext obsolete?
// Pro: We can remove them from the API
// Con: No direct way to "just add callbacks" right now, always needs a plugin.
// See GLTFSceneExporter for a case here we "just want callbacks" instead of a new class/context
public GLTFSceneExporter.AfterSceneExportDelegate AfterSceneExport;
public GLTFSceneExporter.BeforeSceneExportDelegate BeforeSceneExport;
public GLTFSceneExporter.AfterNodeExportDelegate AfterNodeExport;
public GLTFSceneExporter.BeforeMaterialExportDelegate BeforeMaterialExport;
public GLTFSceneExporter.AfterMaterialExportDelegate AfterMaterialExport;
public GLTFSceneExporter.BeforeTextureExportDelegate BeforeTextureExport;
public GLTFSceneExporter.AfterTextureExportDelegate AfterTextureExport;
public GLTFSceneExporter.AfterPrimitiveExportDelegate AfterPrimitiveExport;
public GLTFSceneExporter.AfterMeshExportDelegate AfterMeshExport;
internal GLTFExportPluginContext GetExportContextCallbacks() => new ExportContextCallbacks(this);
#pragma warning disable CS0618 // Type or member is obsolete
internal class ExportContextCallbacks : GLTFExportPluginContext
{
private readonly ExportContext _exportContext;
internal ExportContextCallbacks(ExportContext context)
{
_exportContext = context;
}
public override void BeforeSceneExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot) => _exportContext.BeforeSceneExport?.Invoke(exporter, gltfRoot);
public override void AfterSceneExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot) => _exportContext.AfterSceneExport?.Invoke(exporter, gltfRoot);
public override void AfterNodeExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Transform transform, Node node) => _exportContext.AfterNodeExport?.Invoke(exporter, gltfRoot, transform, node);
public override bool BeforeMaterialExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Material material, GLTFMaterial materialNode)
{
// static callback, run after options callback
// we're iterating here because we want to stop calling any once we hit one that can export this material.
if (_exportContext.BeforeMaterialExport != null)
{
var list = _exportContext.BeforeMaterialExport.GetInvocationList();
foreach (var entry in list)
{
var cb = (GLTFSceneExporter.BeforeMaterialExportDelegate) entry;
if (cb != null && cb.Invoke(exporter, gltfRoot, material, materialNode))
{
return true;
}
}
}
return false;
}
public override void AfterMaterialExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Material material, GLTFMaterial materialNode) => _exportContext.AfterMaterialExport?.Invoke(exporter, gltfRoot, material, materialNode);
public override void BeforeTextureExport(GLTFSceneExporter exporter, ref GLTFSceneExporter.UniqueTexture texture, string textureSlot) => _exportContext.BeforeTextureExport?.Invoke(exporter, ref texture, textureSlot);
public override void AfterTextureExport(GLTFSceneExporter exporter, GLTFSceneExporter.UniqueTexture texture, int index, GLTFTexture tex) => _exportContext.AfterTextureExport?.Invoke(exporter, texture, index, tex);
public override void AfterPrimitiveExport(GLTFSceneExporter exporter, Mesh mesh, MeshPrimitive primitive, int index) => _exportContext.AfterPrimitiveExport?.Invoke(exporter, mesh, primitive, index);
public override void AfterMeshExport(GLTFSceneExporter exporter, Mesh mesh, GLTFMesh gltfMesh, int index) => _exportContext.AfterMeshExport?.Invoke(exporter, mesh, gltfMesh, index);
}
#pragma warning restore CS0618 // Type or member is obsolete
}
[Obsolete("Use UnityGLTF.ExportContext instead. (UnityUpgradable) -> UnityGLTF.ExportContext")]
public class ExportOptions: ExportContext
{
public ExportOptions(): base() { }
public ExportOptions(GLTFSettings settings): base(settings) { }
}
public partial class GLTFSceneExporter
{
// Available export callbacks.
// Callbacks can be either set statically (for exporters that register themselves)
// or added in the ExportOptions.
public delegate string RetrieveTexturePathDelegate(Texture texture);
public delegate void BeforeSceneExportDelegate(GLTFSceneExporter exporter, GLTFRoot gltfRoot);
public delegate void AfterSceneExportDelegate(GLTFSceneExporter exporter, GLTFRoot gltfRoot);
public delegate void AfterNodeExportDelegate(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Transform transform, Node node);
/// <returns>True: material export is complete. False: continue regular export.</returns>
public delegate bool BeforeMaterialExportDelegate(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Material material, GLTFMaterial materialNode);
public delegate void AfterMaterialExportDelegate(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Material material, GLTFMaterial materialNode);
public delegate void BeforeTextureExportDelegate(GLTFSceneExporter exporter, ref UniqueTexture texture, string textureSlot);
public delegate void AfterTextureExportDelegate(GLTFSceneExporter exporter, UniqueTexture texture, int index, GLTFTexture tex);
public delegate void AfterPrimitiveExportDelegate(GLTFSceneExporter exporter, Mesh mesh, MeshPrimitive primitive, int index);
public delegate void AfterMeshExportDelegate(GLTFSceneExporter exporter, Mesh mesh, GLTFMesh gltfMesh, int index);
private class LegacyCallbacksPlugin : GLTFExportPluginContext
{
public override void AfterSceneExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot) => GLTFSceneExporter.AfterSceneExport?.Invoke(exporter, gltfRoot);
public override void BeforeSceneExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot) => GLTFSceneExporter.BeforeSceneExport?.Invoke(exporter, gltfRoot);
public override void AfterNodeExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Transform transform, Node node) => GLTFSceneExporter.AfterNodeExport?.Invoke(exporter, gltfRoot, transform, node);
public override bool BeforeMaterialExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Material material, GLTFMaterial materialNode)
{
// static callback, run after options callback
// we're iterating here because we want to stop calling any once we hit one that can export this material.
if (GLTFSceneExporter.BeforeMaterialExport != null)
{
var list = GLTFSceneExporter.BeforeMaterialExport.GetInvocationList();
foreach (var entry in list)
{
var cb = (BeforeMaterialExportDelegate) entry;
if (cb != null && cb.Invoke(exporter, gltfRoot, material, materialNode))
{
return true;
}
}
}
return false;
}
public override void AfterMaterialExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Material material, GLTFMaterial materialNode) => GLTFSceneExporter.AfterMaterialExport?.Invoke(exporter, gltfRoot, material, materialNode);
}
private static INetLogger Debug = RelayedLogger.Instance;
private List<GLTFExportPluginContext> _plugins = new List<GLTFExportPluginContext>();
public struct TextureMapType
{
public const string BaseColor = "baseColorTexture";
[Obsolete("Use BaseColor instead")] public const string Main = BaseColor;
public const string Emissive = "emissiveTexture";
[Obsolete("Use Emissive instead")] public const string Emission = Emissive;
public const string Normal = "normalTexture";
[Obsolete("Use Normal instead")] public const string Bump = Normal;
public const string MetallicGloss = "metallicGloss";
public const string MetallicRoughness = "metallicRoughnessTexture";
public const string SpecGloss = "specularGlossinessTexture"; // not really supported anymore
public const string Light = Linear;
public const string Occlusion = "occlusionTexture";
public const string Linear = "linear";
public const string sRGB = "sRGB";
public const string Custom_Unknown = "linearWithAlpha";
public const string Custom_HDR = "hdr";
[Obsolete("Use Linear or the right texture slot instead")] public const string MetallicGloss_DontConvert = Linear;
}
public struct TextureExportSettings
{
public bool isValid;
// does the texture need a channel conversion when exporting
public Conversion conversion;
// do we know something about the alpha channel of this texture
public AlphaMode alphaMode;
// is the texture linear or sRGB
public bool linear;
// required for metallic-smoothness conversion
public float smoothnessMultiplier;
public TextureExportSettings(TextureExportSettings source)
{
conversion = source.conversion;
alphaMode = source.alphaMode;
linear = source.linear;
smoothnessMultiplier = source.smoothnessMultiplier;
isValid = true;
}
public enum Conversion
{
None,
MetalGlossChannelSwap,
MetalGlossOcclusionChannelSwap,
NormalChannel,
}
public enum AlphaMode
{
Never = 0,
Always = 1,
Heuristic = 2,
}
public static bool operator ==(TextureExportSettings lhs, TextureExportSettings rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(TextureExportSettings lhs, TextureExportSettings rhs)
{
return !(lhs == rhs);
}
public bool Equals(TextureExportSettings other)
{
return
conversion == other.conversion &&
alphaMode == other.alphaMode &&
linear == other.linear &&
Mathf.Approximately(smoothnessMultiplier, other.smoothnessMultiplier);
}
public override bool Equals(object obj)
{
return obj is TextureExportSettings other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (int)conversion;
hashCode = (hashCode * 397) ^ (int)alphaMode;
hashCode = (hashCode * 397) ^ linear.GetHashCode();
hashCode = (hashCode * 397) ^ smoothnessMultiplier.GetHashCode();
return hashCode;
}
}
}
public TextureExportSettings GetExportSettingsForSlot(string textureSlot)
{
var exportSettings = new TextureExportSettings();
exportSettings.isValid = true;
switch (textureSlot)
{
case TextureMapType.BaseColor: // Main = new TextureExportSettings() { alphaMode = AlphaMode.Heuristic };
exportSettings.linear = false;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Heuristic;
return exportSettings;
case TextureMapType.Emissive: // Emission = new TextureExportSettings() { alphaMode = AlphaMode.Heuristic };
exportSettings.linear = false;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Never;
return exportSettings;
case TextureMapType.Normal: // Bump = new TextureExportSettings() { alphaMode = AlphaMode.Never, conversion = Conversion.NormalChannel };
exportSettings.linear = true;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Never;
exportSettings.conversion = TextureExportSettings.Conversion.NormalChannel;
return exportSettings;
case TextureMapType.MetallicGloss: // MetallicGloss = new TextureExportSettings() { alphaMode = AlphaMode.Never, conversion = Conversion.MetalGlossChannelSwap, smoothnessMultiplier = 1f};
exportSettings.linear = true;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Never;
exportSettings.conversion = TextureExportSettings.Conversion.MetalGlossChannelSwap;
return exportSettings;
case TextureMapType.MetallicRoughness:
exportSettings.linear = true;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Never;
return exportSettings;
case TextureMapType.SpecGloss: // SpecGloss = MetallicGloss; // not really supported anymore
exportSettings.linear = true;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Never;
exportSettings.conversion = TextureExportSettings.Conversion.MetalGlossChannelSwap;
return exportSettings;
case TextureMapType.Occlusion: // Occlusion = Linear;
exportSettings.linear = true;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Never;
return exportSettings;
// custom slot types that allow us to export more arbitrary textures
case TextureMapType.Linear: // MetallicGloss_DontConvert = Linear;
exportSettings.linear = true;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Heuristic;
return exportSettings;
case TextureMapType.sRGB: // MetallicGloss_DontConvert = Linear;
exportSettings.linear = false;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Heuristic;
return exportSettings;
case TextureMapType.Custom_Unknown:
case "rgbm": // Custom_Unknown = new TextureExportSettings() { linear = true, alphaMode = AlphaMode.Always };
exportSettings.linear = true;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Always;
return exportSettings;
case TextureMapType.Custom_HDR: // Custom_HDR = new TextureExportSettings() { alphaMode = AlphaMode.Always };
exportSettings.linear = true;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Always;
return exportSettings;
}
// assume unknown linear
exportSettings.linear = true;
exportSettings.alphaMode = TextureExportSettings.AlphaMode.Heuristic;
return exportSettings;
}
private Material GetConversionMaterial(TextureExportSettings textureMapType)
{
switch (textureMapType.conversion)
{
case TextureExportSettings.Conversion.NormalChannel:
return _normalChannelMaterial;
case TextureExportSettings.Conversion.MetalGlossChannelSwap:
if (_metalGlossChannelSwapMaterial && _metalGlossChannelSwapMaterial.HasProperty("_SmoothnessMultiplier"))
_metalGlossChannelSwapMaterial.SetFloat("_SmoothnessMultiplier", textureMapType.smoothnessMultiplier);
return _metalGlossChannelSwapMaterial;
case TextureExportSettings.Conversion.MetalGlossOcclusionChannelSwap:
if (_metalGlossOcclusionChannelSwapMaterial && _metalGlossOcclusionChannelSwapMaterial.HasProperty("_SmoothnessMultiplier"))
_metalGlossOcclusionChannelSwapMaterial.SetFloat("_SmoothnessMultiplier", textureMapType.smoothnessMultiplier);
return _metalGlossOcclusionChannelSwapMaterial;
default:
return null;
}
}
private struct ImageInfo
{
public Texture2D texture;
public TextureExportSettings textureMapType;
public string outputPath;
public bool canBeExportedFromDisk;
}
private struct FileInfo
{
public Stream stream;
public string uniqueFileName;
}
public struct ExportFileResult
{
public string uri;
public string mimeType;
public BufferViewId bufferView;
}
public IReadOnlyList<Transform> RootTransforms => _rootTransforms;
private Transform[] _rootTransforms;
private GLTFRoot _root;
private BufferId _bufferId;
private GLTFBuffer _buffer;
private List<ImageInfo> _imageInfos;
private List<FileInfo> _fileInfos;
private HashSet<string> _fileNames;
private List<UniqueTexture> _textures;
private Dictionary<int, int> _exportedMaterials;
private bool _shouldUseInternalBufferForImages;
private Dictionary<int, int> _exportedTransforms;
private List<Transform> _animatedNodes;
private int _exportLayerMask;
private ExportContext _exportContext;
private Material _metalGlossChannelSwapMaterial;
private Material _metalGlossOcclusionChannelSwapMaterial;
private Material _normalChannelMaterial;
private const uint MagicGLTF = 0x46546C67;
private const uint Version = 2;
private const uint MagicJson = 0x4E4F534A;
private const uint MagicBin = 0x004E4942;
private const int GLTFHeaderSize = 12;
private const int SectionHeaderSize = 8;
public struct UniqueTexture : IEquatable<UniqueTexture>
{
public Texture Texture;
public int MaxSize;
// additional settings that make exporting a texture unique
public TextureExportSettings ExportSettings;
public int GetWidth() => Mathf.Min(MaxSize, Texture.width);
public int GetHeight() => Mathf.Min(MaxSize, Texture.height);
public UniqueTexture(Texture tex, string textureSlot, GLTFSceneExporter exporter)
{
Texture = tex;
ExportSettings = exporter.GetExportSettingsForSlot(textureSlot);
MaxSize = Mathf.Max(tex.width, tex.height);
}
public UniqueTexture(Texture tex, TextureExportSettings exportSettings)
{
Texture = tex;
ExportSettings = exportSettings;
MaxSize = Mathf.Max(tex.width, tex.height);
}
public bool Equals(UniqueTexture other)
{
return Equals(Texture, other.Texture) && MaxSize == other.MaxSize && ExportSettings == other.ExportSettings;
}
public override bool Equals(object obj)
{
return obj is UniqueTexture other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
// We dont want to use GetHashCode() for the texture here since it will change the hash after restarting the editor
#if UNITY_EDITOR
var hashCode = Texture ? Texture.imageContentsHash.GetHashCode() : 0;
#else
var hashCode = Texture ? Texture.GetHashCode() : 0;
#endif
hashCode = (hashCode * 397) ^ ExportSettings.GetHashCode();
hashCode = (hashCode * 397) ^ MaxSize;
return hashCode;
}
}
}
/// <summary>
/// A Primitive is a combination of Mesh + Material(s). It also contains a reference to the original SkinnedMeshRenderer,
/// if any, since that's the only way to get the actual current weights to export a blend shape primitive.
/// </summary>
public struct UniquePrimitive
{
public bool Equals(UniquePrimitive other)
{
if (!Equals(Mesh, other.Mesh)) return false;
if (Materials == null && other.Materials == null) return true;
if (!(Materials != null && other.Materials != null)) return false;
if (!Equals(Materials.Length, other.Materials.Length)) return false;
for (var i = 0; i < Materials.Length; i++)
{
if (!Equals(Materials[i], other.Materials[i])) return false;
}
return true;
}
public override bool Equals(object obj)
{
return obj is UniquePrimitive other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
var code = (Mesh != null ? Mesh.GetHashCode() : 0) * 397;
if (Materials != null)
{
code = code ^ Materials.Length.GetHashCode() * 397;
foreach (var mat in Materials)
code = (code ^ (mat != null ? mat.GetHashCode() : 0)) * 397;
}
return code;
}
}
public Mesh Mesh;
public Material[] Materials;
public SkinnedMeshRenderer SkinnedMeshRenderer; // needed for BlendShape export, since Unity stores the actually used blend shape weights on the renderer. see ExporterMeshes.ExportBlendShapes
}
private readonly Dictionary<UniquePrimitive, MeshId> _primOwner = new Dictionary<UniquePrimitive, MeshId>();
#region Settings
private GLTFSettings settings => _exportContext.settings;
private bool ExportNames => settings.ExportNames;
private bool RequireExtensions => settings.RequireExtensions;
private bool ExportAnimations => settings.ExportAnimations;
#endregion
#region Profiler Markers
// ReSharper disable InconsistentNaming
private static ProfilerMarker exportGltfMarker = new ProfilerMarker("Export glTF");
private static ProfilerMarker gltfSerializationMarker = new ProfilerMarker("Serialize exported data");
private static ProfilerMarker exportMeshMarker = new ProfilerMarker("Export Mesh");
private static ProfilerMarker exportPrimitiveMarker = new ProfilerMarker("Export Primitive");
private static ProfilerMarker exportBlendShapeMarker = new ProfilerMarker("Export BlendShape");
private static ProfilerMarker exportSkinFromNodeMarker = new ProfilerMarker("Export Skin");
private static ProfilerMarker exportSparseAccessorMarker = new ProfilerMarker("Export Sparse Accessor");
private static ProfilerMarker beforeNodeExportMarker = new ProfilerMarker("Before Node Export (Callback)");
private static ProfilerMarker exportNodeMarker = new ProfilerMarker("Export Node");
private static ProfilerMarker afterNodeExportMarker = new ProfilerMarker("After Node Export (Callback)");
private static ProfilerMarker exportAnimationFromNodeMarker = new ProfilerMarker("Export Animation from Node");
private static ProfilerMarker convertClipToGLTFAnimationMarker = new ProfilerMarker("Convert Clip to GLTF Animation");
private static ProfilerMarker beforeSceneExportMarker = new ProfilerMarker("Before Scene Export (Callback)");
private static ProfilerMarker exportSceneMarker = new ProfilerMarker("Export Scene");
private static ProfilerMarker beforeMaterialExportMarker = new ProfilerMarker("Before Material Export (Callback)");
private static ProfilerMarker exportMaterialMarker = new ProfilerMarker("Export Material");
private static ProfilerMarker afterMaterialExportMarker = new ProfilerMarker("After Material Export (Callback)");
private static ProfilerMarker writeImageToDiskMarker = new ProfilerMarker("Export Image - Write to Disk");
private static ProfilerMarker afterSceneExportMarker = new ProfilerMarker("After Scene Export (Callback)");
private static ProfilerMarker exportAccessorMarker = new ProfilerMarker("Export Accessor");
private static ProfilerMarker exportAccessorMatrix4x4ArrayMarker = new ProfilerMarker("Matrix4x4[]");
private static ProfilerMarker exportAccessorVector4ArrayMarker = new ProfilerMarker("Vector4[]");
private static ProfilerMarker exportAccessorUintArrayMarker = new ProfilerMarker("Uint[]");
private static ProfilerMarker exportAccessorColorArrayMarker = new ProfilerMarker("Color[]");
private static ProfilerMarker exportAccessorVector3ArrayMarker = new ProfilerMarker("Vector3[]");
private static ProfilerMarker exportAccessorVector2ArrayMarker = new ProfilerMarker("Vector2[]");
private static ProfilerMarker exportAccessorIntArrayIndicesMarker = new ProfilerMarker("int[] (Indices)");
private static ProfilerMarker exportAccessorIntArrayMarker = new ProfilerMarker("int[]");
private static ProfilerMarker exportAccessorFloatArrayMarker = new ProfilerMarker("float[]");
private static ProfilerMarker exportAccessorByteArrayMarker = new ProfilerMarker("byte[]");
private static ProfilerMarker exportAccessorMinMaxMarker = new ProfilerMarker("Calculate min/max");
private static ProfilerMarker exportAccessorBufferWriteMarker = new ProfilerMarker("Buffer.Write");
private static ProfilerMarker exportGltfInitMarker = new ProfilerMarker("Init glTF Export");
private static ProfilerMarker gltfWriteOutMarker = new ProfilerMarker("Write glTF");
private static ProfilerMarker gltfWriteJsonStreamMarker = new ProfilerMarker("Write JSON stream");
private static ProfilerMarker gltfWriteBinaryStreamMarker = new ProfilerMarker("Write binary stream");
private static ProfilerMarker addAnimationDataMarker = new ProfilerMarker("Add animation data to glTF");
private static ProfilerMarker exportRotationAnimationDataMarker = new ProfilerMarker("Rotation Keyframes");
private static ProfilerMarker exportPositionAnimationDataMarker = new ProfilerMarker("Position Keyframes");
private static ProfilerMarker exportScaleAnimationDataMarker = new ProfilerMarker("Scale Keyframes");
private static ProfilerMarker exportWeightsAnimationDataMarker = new ProfilerMarker("Weights Keyframes");
private static ProfilerMarker removeAnimationUnneededKeyframesMarker = new ProfilerMarker("Simplify Keyframes");
private static ProfilerMarker removeAnimationUnneededKeyframesInitMarker = new ProfilerMarker("Init");
private static ProfilerMarker removeAnimationUnneededKeyframesCheckIdenticalMarker = new ProfilerMarker("Check Identical");
private static ProfilerMarker removeAnimationUnneededKeyframesCheckIdenticalKeepMarker = new ProfilerMarker("Keep Keyframe");
private static ProfilerMarker removeAnimationUnneededKeyframesFinalizeMarker = new ProfilerMarker("Finalize");
// ReSharper restore InconsistentNaming
#endregion
/// <summary>
/// Create a GLTFExporter that exports out a transform
/// </summary>
/// <param name="rootTransforms">Root transform of object to export</param>
[Obsolete("Please switch to GLTFSceneExporter(Transform[] rootTransforms, ExportOptions options). This constructor is deprecated and will be removed in a future release.")]
public GLTFSceneExporter(Transform[] rootTransforms, RetrieveTexturePathDelegate texturePathRetriever)
: this(rootTransforms, new ExportContext { TexturePathRetriever = texturePathRetriever })
{
}
public GLTFSceneExporter(Transform rootTransform, ExportContext context) : this(new [] { rootTransform }, context)
{
}
/// <summary>
/// Create a GLTFExporter that exports out a transform
/// </summary>
/// <param name="rootTransforms">Root transform of object to export</param>
/// <param name="context">Export Settings</param>
public GLTFSceneExporter(Transform[] rootTransforms, ExportContext context)
{
_exportContext = context;
if (context.logger != null)
Debug = context.logger;
else
Debug = RelayedLogger.Instance;
// legacy: implicit plugin for all the static methods on GLTFSceneExporter
_plugins.Add(new LegacyCallbacksPlugin());
// legacy: implicit plugin for all the methods on ExportContext
_plugins.Add(context.GetExportContextCallbacks());
// create export plugin instances
foreach (var plugin in settings.ExportPlugins)
{
if (plugin != null && plugin.Enabled)
{
var instance = plugin.CreateInstance(context);
if (instance != null) _plugins.Add(instance);
}
}
_exportLayerMask = _exportContext.ExportLayers;
// TODO: Add shaders
//var metalGlossChannelSwapShader = Resources.Load("MetalGlossChannelSwap", Il2CppType.Of<Shader>()).TryCast<Shader>();
//_metalGlossChannelSwapMaterial = new Material(metalGlossChannelSwapShader);
//var metalGlossOcclusionChannelSwapShader = Resources.Load("MetalGlossOcclusionChannelSwap", Il2CppType.Of<Shader>()).TryCast<Shader>();
//_metalGlossOcclusionChannelSwapMaterial = new Material(metalGlossOcclusionChannelSwapShader);
//var normalChannelShader = Resources.Load("NormalChannel", Il2CppType.Of<Shader>()) as Shader;
//_normalChannelMaterial = new Material(normalChannelShader);
_rootTransforms = rootTransforms;
_exportedTransforms = new Dictionary<int, int>();
_exportedCameras = new Dictionary<int, int>();
_exportedLights = new Dictionary<int, int>();
_animatedNodes = new List<Transform>();
_skinnedNodes = new List<Transform>();
_bakedMeshes = new Dictionary<SkinnedMeshRenderer, UnityEngine.Mesh>();
_root = new GLTFRoot
{
Accessors = new List<Accessor>(),
Animations = new List<GLTFAnimation>(),
Asset = new Asset
{
Version = "2.0",
Generator = "UnityGLTF"
},
Buffers = new List<GLTFBuffer>(),
BufferViews = new List<BufferView>(),
Cameras = new List<GLTFCamera>(),
Images = new List<GLTFImage>(),
Materials = new List<GLTFMaterial>(),
Meshes = new List<GLTFMesh>(),
Nodes = new List<Node>(),
Samplers = new List<Sampler>(),
Scenes = new List<GLTFScene>(),
Skins = new List<Skin>(),
Textures = new List<GLTFTexture>()
};
_imageInfos = new List<ImageInfo>();
_fileInfos = new List<FileInfo>();
_fileNames = new HashSet<string>();
_exportedMaterials = new Dictionary<int, int>();
_textures = new List<UniqueTexture>();
_buffer = new GLTFBuffer();
_bufferId = new BufferId
{
Id = _root.Buffers.Count,
Root = _root
};
_root.Buffers.Add(_buffer);
}
/// <summary>
/// Gets the root object of the exported GLTF
/// </summary>
/// <returns>Root parsed GLTF Json</returns>
public GLTFRoot GetRoot()
{
return _root;
}
/// <summary>
/// Writes a binary GLB file with filename at path.
/// </summary>
/// <param name="path">File path for saving the binary file</param>
/// <param name="fileName">The name of the GLTF file</param>
public void SaveGLB(string path, string fileName)
{
var fullPath = GetFileName(path, fileName, ".glb");
var dirName = Path.GetDirectoryName(fullPath);
if (dirName != null && !Directory.Exists(dirName))
Directory.CreateDirectory(dirName);
_shouldUseInternalBufferForImages = true;
using (FileStream glbFile = new FileStream(fullPath, FileMode.Create))
{
SaveGLBToStream(glbFile, fileName);
}
if (!_shouldUseInternalBufferForImages)
{
ExportImages(path);
ExportFiles(path);
}
}
/// <summary>
/// In-memory GLB creation helper. Useful for platforms where no filesystem is available (e.g. WebGL).
/// </summary>
/// <param name="sceneName"></param>
/// <returns></returns>
public byte[] SaveGLBToByteArray(string sceneName)
{
_shouldUseInternalBufferForImages = true;
using (var stream = new MemoryStream())
{
SaveGLBToStream(stream, sceneName);
return stream.ToArray();
}
}
/// <summary>
/// Writes a binary GLB file into a stream (memory stream, filestream, ...)
/// </summary>
/// <param name="path">File path for saving the binary file</param>
/// <param name="fileName">The name of the GLTF file</param>
public void SaveGLBToStream(Stream stream, string sceneName)
{
exportGltfMarker.Begin();
exportGltfInitMarker.Begin();
Stream binStream = new MemoryStream();
Stream jsonStream = new MemoryStream();
_shouldUseInternalBufferForImages = true;
_bufferWriter = new BinaryWriterWithLessAllocations(binStream);
TextWriter jsonWriter = new StreamWriter(jsonStream, new UTF8Encoding(false));
exportGltfInitMarker.End();
beforeSceneExportMarker.Begin();
foreach (var plugin in _plugins)
plugin?.BeforeSceneExport(this, _root);
beforeSceneExportMarker.End();
_root.Scene = ExportScene(sceneName, _rootTransforms);
if (ExportAnimations)
{
ExportAnimation();
}
// Export skins
for (int i = 0; i < _skinnedNodes.Count; ++i)
{
Transform t = _skinnedNodes[i];
ExportSkinFromNode(t);
}
afterSceneExportMarker.Begin();
foreach (var plugin in _plugins)
plugin?.AfterSceneExport(this, _root);
afterSceneExportMarker.End();
animationPointerResolver?.Resolve(this);
_buffer.ByteLength = GLTFSceneExporter.CalculateAlignment((uint)_bufferWriter.BaseStream.Length, 4);
gltfSerializationMarker.Begin();
_root.Serialize(jsonWriter, true);
gltfSerializationMarker.End();
gltfWriteOutMarker.Begin();
_bufferWriter.Flush();
jsonWriter.Flush();
// align to 4-byte boundary to comply with spec.
GLTFSceneExporter.AlignToBoundary(jsonStream);
GLTFSceneExporter.AlignToBoundary(binStream, 0x00);
int glbLength = (int)(GLTFHeaderSize + SectionHeaderSize +
jsonStream.Length + SectionHeaderSize + binStream.Length);
BinaryWriter writer = new BinaryWriter(stream);
// write header
writer.Write(MagicGLTF);
writer.Write(Version);
writer.Write(glbLength);
gltfWriteJsonStreamMarker.Begin();
// write JSON chunk header.
writer.Write((int)jsonStream.Length);
writer.Write(MagicJson);
jsonStream.Position = 0;
GLTFSceneExporter.CopyStream(jsonStream, writer);
gltfWriteJsonStreamMarker.End();
gltfWriteBinaryStreamMarker.Begin();
writer.Write((int)binStream.Length);
writer.Write(MagicBin);
binStream.Position = 0;
GLTFSceneExporter.CopyStream(binStream, writer);
gltfWriteBinaryStreamMarker.End();
writer.Flush();
gltfWriteOutMarker.End();
exportGltfMarker.End();
}
/// <summary>
/// Specifies the path and filename for the GLTF Json and binary
/// </summary>
/// <param name="path">File path for saving the GLTF and binary files</param>
/// <param name="fileName">The name of the GLTF file</param>
public void SaveGLTFandBin(string path, string fileName, bool exportTextures = true)
{
exportGltfMarker.Begin();
exportGltfInitMarker.Begin();
_shouldUseInternalBufferForImages = false;
var toLower = fileName.ToLowerInvariant();
if (toLower.EndsWith(".gltf"))
fileName = fileName.Substring(0, fileName.Length - 5);
if (toLower.EndsWith(".bin"))
fileName = fileName.Substring(0, fileName.Length - 4);
var fullPath = GetFileName(path, fileName, ".bin");
var dirName = Path.GetDirectoryName(fullPath);
if (dirName != null && !Directory.Exists(dirName))
Directory.CreateDirectory(dirName);
// sanitized file path can differ
fileName = Path.GetFileNameWithoutExtension(fullPath);
var binFile = File.Create(fullPath);
_bufferWriter = new BinaryWriterWithLessAllocations(binFile);
exportGltfInitMarker.End();
beforeSceneExportMarker.Begin();
foreach (var plugin in _plugins)
plugin?.BeforeSceneExport(this, _root);
beforeSceneExportMarker.End();
if (_rootTransforms != null)
_root.Scene = ExportScene(fileName, _rootTransforms);
if (ExportAnimations)
ExportAnimation();
// Export skins
for (int i = 0; i < _skinnedNodes.Count; ++i)
{
Transform t = _skinnedNodes[i];
ExportSkinFromNode(t);
}
afterSceneExportMarker.Begin();
foreach (var plugin in _plugins)
plugin?.AfterSceneExport(this, _root);
afterSceneExportMarker.End();
animationPointerResolver?.Resolve(this);
// we don't need to create a .bin file if there's no buffer at all
var anyDataInBinFile = _bufferWriter.BaseStream.Length > 0;
if (anyDataInBinFile)
{
GLTFSceneExporter.AlignToBoundary(_bufferWriter.BaseStream, 0x00);
_buffer.Uri = fileName + ".bin";
_buffer.ByteLength = GLTFSceneExporter.CalculateAlignment((uint)_bufferWriter.BaseStream.Length, 4);
}
else
{
_buffer = null;
_root.Buffers.Clear();
}
var gltfFile = File.CreateText(Path.ChangeExtension(fullPath, ".gltf"));
gltfSerializationMarker.Begin();
_root.Serialize(gltfFile);
gltfSerializationMarker.End();
gltfWriteOutMarker.Begin();
_bufferWriter.Close();
#if WINDOWS_UWP
gltfFile.Dispose();
binFile.Dispose();
#else
gltfFile.Close();
binFile.Close();
#endif
if (!anyDataInBinFile)
File.Delete(fullPath);
if (exportTextures)
ExportImages(path);
ExportFiles(path);
gltfWriteOutMarker.End();
exportGltfMarker.End();
}
/// <summary>
/// Ensures a specific file extension from an absolute path that may or may not already have that extension.
/// </summary>
/// <param name="absolutePathThatMayHaveExtension">Absolute path that may or may not already have the required extension</param>
/// <param name="requiredExtension">The extension to ensure, with leading dot</param>
/// <returns>An absolute path that has the required extension</returns>
public static string GetFileName(string directory, string fileNameThatMayHaveExtension, string requiredExtension)
{
var absolutePathThatMayHaveExtension = Path.Combine(directory, EnsureValidFileName(fileNameThatMayHaveExtension));
if (!requiredExtension.StartsWith(".", StringComparison.Ordinal))
requiredExtension = "." + requiredExtension;
if (!Path.GetExtension(absolutePathThatMayHaveExtension).Equals(requiredExtension, StringComparison.OrdinalIgnoreCase))
return absolutePathThatMayHaveExtension + requiredExtension;
return absolutePathThatMayHaveExtension;
}
/// <summary>
/// Strip illegal chars and reserved words from a candidate filename (should not include the directory path)
/// </summary>
/// <remarks>
/// http://stackoverflow.com/questions/309485/c-sharp-sanitize-file-name
/// </remarks>
private static string EnsureValidFileName(string filename)
{
var invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
var invalidReStr = string.Format(@"[{0}]+", invalidChars);
var reservedWords = new []
{
"CON", "PRN", "AUX", "CLOCK$", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4",
"COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4",
"LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
};
var sanitisedNamePart = Regex.Replace(filename, invalidReStr, "_");
foreach (var reservedWord in reservedWords)
{
var reservedWordPattern = string.Format("^{0}\\.", reservedWord);
sanitisedNamePart = Regex.Replace(sanitisedNamePart, reservedWordPattern, "_reservedWord_.", RegexOptions.IgnoreCase);
}
return sanitisedNamePart;
}
public void DeclareExtensionUsage(string extension, bool isRequired=false)
{
if( _root.ExtensionsUsed == null ){
_root.ExtensionsUsed = new List<string>();
}
if(!_root.ExtensionsUsed.Contains(extension))
{
_root.ExtensionsUsed.Add(extension);
}
if(isRequired){
if( _root.ExtensionsRequired == null ){
_root.ExtensionsRequired = new List<string>();
}
if( !_root.ExtensionsRequired.Contains(extension))
{
_root.ExtensionsRequired.Add(extension);
}
}
}
private bool ShouldExportTransform(Transform transform)
{
// Root transforms should *always* be exported since this is a deliberate decision by the user calling - it should override any other setting that would prevent the export (e.g. if a user calls Export with disabled or hidden objects the exporter should never prevent this)
var isRoot = _rootTransforms.Contains(transform);
if (isRoot) return true;
if (!settings.ExportDisabledGameObjects && !transform.gameObject.activeSelf)
{
return false;
}
if (settings.UseMainCameraVisibility && (_exportLayerMask >= 0 && _exportLayerMask != (_exportLayerMask | 1 << transform.gameObject.layer))) return false;
if (transform.CompareTag("EditorOnly")) return false;
return true;
}
private SceneId ExportScene(string name, Transform[] rootObjTransforms)
{
exportSceneMarker.Begin();
var scene = new GLTFScene();
if (ExportNames)
{
scene.Name = name;
}
if(_exportContext.TreatEmptyRootAsScene)
{
// if we're exporting with a single object selected, that object can be the scene root, no need for an extra root node.
if (rootObjTransforms.Length == 1 && rootObjTransforms[0].GetComponents<Component>().Length == 1) // single root with a single transform
{
var firstRoot = rootObjTransforms[0];
var newRoots = new Transform[firstRoot.childCount];
for (int i = 0; i < firstRoot.childCount; i++)
newRoots[i] = firstRoot.GetChild(i);
rootObjTransforms = newRoots;
}
}