-
Notifications
You must be signed in to change notification settings - Fork 475
/
ExporterMaterials.cs
982 lines (872 loc) · 35.6 KB
/
ExporterMaterials.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
using System;
using System.Collections.Generic;
using GLTF.Schema;
using UnityEngine;
using UnityEngine.Rendering;
using UnityGLTF.Extensions;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityGLTF
{
public partial class GLTFSceneExporter
{
/// <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);
// Static callbacks
public static event BeforeSceneExportDelegate BeforeSceneExport;
public static event AfterSceneExportDelegate AfterSceneExport;
public static event AfterNodeExportDelegate AfterNodeExport;
/// <returns>True: material export is complete. False: continue regular export.</returns>
public static event BeforeMaterialExportDelegate BeforeMaterialExport;
public static event AfterMaterialExportDelegate AfterMaterialExport;
// mock for Default material
private static Material _defaultMaterial = null;
public static Material DefaultMaterial
{
get
{
if (_defaultMaterial) return _defaultMaterial;
#if UNITY_2019_3_OR_NEWER
var pipelineAsset = GraphicsSettings.currentRenderPipeline;
if (pipelineAsset)
{
_defaultMaterial = pipelineAsset.defaultMaterial;
}
else
#endif
{
var shader = Shader.Find("Legacy Shaders/Diffuse"); // by default in the always included shaders list
if (shader)
_defaultMaterial = new Material(shader);
}
return _defaultMaterial;
}
}
public MaterialId ExportMaterial(Material materialObj)
{
MaterialId id = GetMaterialId(_root, materialObj);
if (id != null)
{
return id;
}
var material = new GLTFMaterial();
if (!materialObj)
{
if (ExportNames)
{
material.Name = "default";
}
// create default material
// TODO check why we need to do anything here
material.PbrMetallicRoughness = new PbrMetallicRoughness() { MetallicFactor = 0, RoughnessFactor = 1.0f };
return CreateAndAddMaterialId(materialObj, material);
}
if (ExportNames)
{
material.Name = materialObj.name;
}
// before material export: only continue with regular export if that didn't succeed.
if (_exportOptions.BeforeMaterialExport != null)
{
beforeMaterialExportMarker.Begin();
if (_exportOptions.BeforeMaterialExport.Invoke(this, _root, materialObj, material))
{
beforeMaterialExportMarker.End();
return CreateAndAddMaterialId(materialObj, material);
}
else
{
beforeMaterialExportMarker.End();
}
}
// 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 (BeforeMaterialExport != null)
{
var list = BeforeMaterialExport.GetInvocationList();
foreach (var entry in list)
{
beforeMaterialExportMarker.Begin();
var cb = (BeforeMaterialExportDelegate) entry;
if (cb != null && cb.Invoke(this, _root, materialObj, material))
{
beforeMaterialExportMarker.End();
return CreateAndAddMaterialId(materialObj, material);
}
else
{
beforeMaterialExportMarker.End();
}
}
}
exportMaterialMarker.Begin();
var isBirp =
#if UNITY_2019_3_OR_NEWER
!GraphicsSettings.currentRenderPipeline;
#else
true;
#endif
switch (materialObj.GetTag("RenderType", false, ""))
{
case "TransparentCutout":
if (materialObj.HasProperty("alphaCutoff"))
material.AlphaCutoff = materialObj.GetFloat("alphaCutoff");
else if (materialObj.HasProperty("_AlphaCutoff"))
material.AlphaCutoff = materialObj.GetFloat("_AlphaCutoff");
else if (materialObj.HasProperty("_Cutoff"))
material.AlphaCutoff = materialObj.GetFloat("_Cutoff");
material.AlphaMode = AlphaMode.MASK;
break;
case "Transparent":
case "Fade":
material.AlphaMode = AlphaMode.BLEND;
break;
default:
if ((!isBirp && materialObj.IsKeywordEnabled("_ALPHATEST_ON")) ||
(isBirp && materialObj.IsKeywordEnabled("_BUILTIN_ALPHATEST_ON")) ||
materialObj.renderQueue == 2450)
{
if (materialObj.HasProperty("alphaCutoff"))
material.AlphaCutoff = materialObj.GetFloat("alphaCutoff");
else if (materialObj.HasProperty("_AlphaCutoff"))
material.AlphaCutoff = materialObj.GetFloat("_AlphaCutoff");
else if (materialObj.HasProperty("_Cutoff"))
material.AlphaCutoff = materialObj.GetFloat("_Cutoff");
material.AlphaMode = AlphaMode.MASK;
}
else
{
material.AlphaMode = AlphaMode.OPAQUE;
}
break;
}
material.DoubleSided = (materialObj.HasProperty("_Cull") && materialObj.GetInt("_Cull") == (int)CullMode.Off) ||
(materialObj.HasProperty("_CullMode") && materialObj.GetInt("_CullMode") == (int)CullMode.Off) ||
(materialObj.shader.name.EndsWith("-Double")); // workaround for exporting shaders that are set to double-sided on 2020.3
if (materialObj.IsKeywordEnabled("_EMISSION") || materialObj.IsKeywordEnabled("EMISSION") || materialObj.HasProperty("emissiveTexture") || materialObj.HasProperty("_EmissiveTexture"))
{
// In Gamma space, some materials treat their emissive color inputs differently than in Linear space.
// This is super confusing when converting materials, but we also need to handle it correctly here.
var isUnityMaterialWithWeirdColorspaceHandling = QualitySettings.activeColorSpace == ColorSpace.Gamma &&
(materialObj.shader.name == "Standard" || materialObj.shader.name == "Standard (Specular setup)" ||
materialObj.shader.name == "Standard (Roughness setup)" ||
materialObj.shader.name == "Universal Render Pipeline/Lit" ||
materialObj.shader.name == "Universal Render Pipeline/Simple Lit" ||
materialObj.shader.name == "Universal Render Pipeline/Unlit");
if (materialObj.HasProperty("_EmissionColor") || materialObj.HasProperty("emissiveFactor") || materialObj.HasProperty("_EmissiveFactor"))
{
var c = materialObj.HasProperty("_EmissionColor") ? materialObj.GetColor("_EmissionColor") : materialObj.HasProperty("emissiveFactor") ? materialObj.GetColor("emissiveFactor") : materialObj.GetColor("_EmissiveFactor");
DecomposeEmissionColor(c, out var emissiveAmount, out var maxEmissiveAmount);
if (isUnityMaterialWithWeirdColorspaceHandling)
material.EmissiveFactor = emissiveAmount.ToNumericsColorRaw();
else
material.EmissiveFactor = emissiveAmount.ToNumericsColorGamma();
if(maxEmissiveAmount > 1)
{
material.AddExtension(KHR_materials_emissive_strength_Factory.EXTENSION_NAME, new KHR_materials_emissive_strength() { emissiveStrength = maxEmissiveAmount });
DeclareExtensionUsage(KHR_materials_emissive_strength_Factory.EXTENSION_NAME, false);
}
}
if (materialObj.HasProperty("_EmissionMap") || materialObj.HasProperty("_EmissiveMap") || materialObj.HasProperty("_EmissiveTexture") || materialObj.HasProperty("emissiveTexture"))
{
var propName = materialObj.HasProperty("emissiveTexture") ? "emissiveTexture" : materialObj.HasProperty("_EmissiveTexture") ? "_EmissiveTexture" : materialObj.HasProperty("_EmissionMap") ? "_EmissionMap" : "_EmissiveMap";
var emissionTex = materialObj.GetTexture(propName);
if (emissionTex)
{
if(emissionTex is Texture2D)
{
material.EmissiveTexture = ExportTextureInfo(emissionTex, TextureMapType.Emissive);
ExportTextureTransform(material.EmissiveTexture, materialObj, propName);
}
else
{
Debug.LogFormat(LogType.Error, "Can't export a {0} emissive texture in material {1}", emissionTex.GetType(), materialObj.name);
}
}
}
}
// workaround for glTFast roundtrip: has a _BumpMap but no _NORMALMAP or _BUMPMAP keyword.
var is_glTFastShader = materialObj.shader.name.IndexOf("glTF", StringComparison.Ordinal) > -1;
if (materialObj.HasProperty("_BumpMap") && (materialObj.IsKeywordEnabled("_NORMALMAP") || materialObj.IsKeywordEnabled("_BUMPMAP") || is_glTFastShader))
{
var normalTex = materialObj.GetTexture("_BumpMap");
if (normalTex)
{
if(normalTex is Texture2D)
{
material.NormalTexture = ExportNormalTextureInfo(normalTex, TextureMapType.Normal, materialObj);
ExportTextureTransform(material.NormalTexture, materialObj, "_BumpMap");
}
else
{
Debug.LogFormat(LogType.Error, "Can't export a {0} normal texture in material {1}", normalTex.GetType(), materialObj.name);
}
}
}
if (materialObj.HasProperty("normalTexture") || materialObj.HasProperty("_NormalTexture"))
{
var propName = materialObj.HasProperty("normalTexture") ? "normalTexture" : "_NormalTexture";
var normalTex = materialObj.GetTexture(propName);
if (normalTex)
{
if(normalTex is Texture2D)
{
material.NormalTexture = ExportNormalTextureInfo(normalTex, TextureMapType.Normal, materialObj);
ExportTextureTransform(material.NormalTexture, materialObj, propName);
}
else
{
Debug.LogFormat(LogType.Error, "Can't export a {0} normal texture in material {1}", normalTex.GetType(), materialObj.name);
}
}
}
if (materialObj.HasProperty("_OcclusionMap") || materialObj.HasProperty("occlusionTexture") || materialObj.HasProperty("_OcclusionTexture"))
{
var propName = materialObj.HasProperty("occlusionTexture") ? "occlusionTexture" : materialObj.HasProperty("_OcclusionTexture") ? "_OcclusionTexture" : "_OcclusionMap";
var occTex = materialObj.GetTexture(propName);
if (occTex)
{
if(occTex is Texture2D)
{
material.OcclusionTexture = ExportOcclusionTextureInfo(occTex, TextureMapType.Occlusion, materialObj);
ExportTextureTransform(material.OcclusionTexture, materialObj, propName);
material.OcclusionTexture.TexCoord = materialObj.HasProperty("occlusionTextureTexCoord") ?
Mathf.RoundToInt(materialObj.GetFloat("occlusionTextureTexCoord")) :
materialObj.HasProperty("_OcclusionTextureTexCoord") ?
Mathf.RoundToInt(materialObj.GetFloat("_OcclusionTextureTexCoord")) : 0;
}
else
{
Debug.LogFormat(LogType.Error, "Can't export a {0} occlusion texture in material {1}", occTex.GetType(), materialObj.name);
}
}
}
if (IsUnlit(materialObj))
{
ExportUnlit( material, materialObj );
}
else if (IsPBRMetallicRoughness(materialObj))
{
material.PbrMetallicRoughness = ExportPBRMetallicRoughness(materialObj);
}
else if (IsPBRSpecularGlossiness(materialObj))
{
ExportPBRSpecularGlossiness(material, materialObj);
}
else if (IsCommonConstant(materialObj))
{
material.CommonConstant = ExportCommonConstant(materialObj);
}
else if (materialObj.HasProperty("_BaseMap"))
{
var mainTex = materialObj.GetTexture("_BaseMap");
material.PbrMetallicRoughness = new PbrMetallicRoughness()
{
BaseColorFactor = (materialObj.HasProperty("_BaseColor")
? materialObj.GetColor("_BaseColor")
: Color.white).ToNumericsColorLinear(),
BaseColorTexture = mainTex ? ExportTextureInfo(mainTex, TextureMapType.BaseColor) : null
};
ExportTextureTransform(material.PbrMetallicRoughness.BaseColorTexture, materialObj, "_BaseMap");
}
else if (materialObj.HasProperty("_ColorTexture"))
{
var mainTex = materialObj.GetTexture("_ColorTexture");
material.PbrMetallicRoughness = new PbrMetallicRoughness()
{
BaseColorFactor = (materialObj.HasProperty("_BaseColor")
? materialObj.GetColor("_BaseColor")
: Color.white).ToNumericsColorLinear(),
BaseColorTexture = mainTex ? ExportTextureInfo(mainTex, TextureMapType.BaseColor) : null
};
ExportTextureTransform(material.PbrMetallicRoughness.BaseColorTexture, materialObj, "_ColorTexture");
}
else if (materialObj.HasProperty("_MainTex")) //else export main texture
{
var mainTex = materialObj.GetTexture("_MainTex");
if (mainTex != null)
{
material.PbrMetallicRoughness = new PbrMetallicRoughness() { MetallicFactor = 0, RoughnessFactor = 1.0f };
material.PbrMetallicRoughness.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
ExportTextureTransform(material.PbrMetallicRoughness.BaseColorTexture, materialObj, "_MainTex");
}
if (materialObj.HasProperty("_TintColor")) //particles use _TintColor instead of _Color
{
if (material.PbrMetallicRoughness == null)
material.PbrMetallicRoughness = new PbrMetallicRoughness() { MetallicFactor = 0, RoughnessFactor = 1.0f };
material.PbrMetallicRoughness.BaseColorFactor = materialObj.GetColor("_TintColor").ToNumericsColorLinear();
}
else if (materialObj.HasProperty("_Color"))
{
if (material.PbrMetallicRoughness == null)
material.PbrMetallicRoughness = new PbrMetallicRoughness() { MetallicFactor = 0, RoughnessFactor = 1.0f };
material.PbrMetallicRoughness.BaseColorFactor = materialObj.GetColor("_Color").ToNumericsColorLinear();
}
material.DoubleSided = true;
}
exportMaterialMarker.End();
return CreateAndAddMaterialId(materialObj, material);
}
private MaterialId CreateAndAddMaterialId(Material materialObj, GLTFMaterial material)
{
var key = materialObj ? materialObj.GetInstanceID() : 0;
if(!_exportedMaterials.ContainsKey(key))
_exportedMaterials.Add(key, _root.Materials.Count);
var id = new MaterialId
{
Id = _root.Materials.Count,
Root = _root
};
_root.Materials.Add(material);
// after material export
afterMaterialExportMarker.Begin();
if (materialObj)
{
_exportOptions.AfterMaterialExport?.Invoke(this, _root, materialObj, material);
AfterMaterialExport?.Invoke(this, _root, materialObj, material);
}
afterMaterialExportMarker.End();
return id;
}
private bool IsPBRMetallicRoughness(Material material)
{
return (material.HasProperty("_Metallic") || material.HasProperty("_MetallicFactor") || material.HasProperty("metallicFactor")) &&
(material.HasProperty("_MetallicGlossMap") || material.HasProperty("_Glossiness") ||
material.HasProperty("_Roughness") || material.HasProperty("_RoughnessFactor") || material.HasProperty("roughnessFactor") ||
material.HasProperty("_MetallicRoughnessTexture") || material.HasProperty("metallicRoughnessTexture"));
}
private bool IsUnlit(Material material)
{
return material.shader.name.ToLowerInvariant().Contains("unlit") || material.shader.name == "Sprites/Default";
}
private bool IsPBRSpecularGlossiness(Material material)
{
return material.HasProperty("_SpecColor") && material.HasProperty("_SpecGlossMap");
}
private bool IsCommonConstant(Material material)
{
return material.HasProperty("_AmbientFactor") &&
material.HasProperty("_LightMap") &&
material.HasProperty("_LightFactor");
}
#if UNITY_2019_1_OR_NEWER
private static bool CheckForPropertyInShader(Shader shader, string name, ShaderPropertyType type)
{
// TODO result can be cached, we might do many similar checks for one export
var c = shader.GetPropertyCount();
var foundProperty = false;
for (var i = 0; i < c; i++)
{
if (shader.GetPropertyName(i) == name && shader.GetPropertyType(i) == type)
{
foundProperty = true;
break;
}
}
return foundProperty;
}
#endif
private void ExportTextureTransform(TextureInfo def, Material mat, string texName)
{
if (def == null) return;
// early out if texture transform is explicitly disabled
if (mat.HasProperty("_TEXTURE_TRANSFORM") && !mat.IsKeywordEnabled("_TEXTURE_TRANSFORM_ON"))
return;
Vector2 offset = mat.GetTextureOffset(texName);
Vector2 scale = mat.GetTextureScale(texName);
//var rotationMatrix = mat.GetVector(texName + "Rotation");
//var rotation = -Mathf.Atan2(offset.y, rotationMatrix.x);
var rotProp = texName + "Rotation";
var uvProp = texName + "TexCoord";
var rotation = 0f;
var uvChannel = 0f;
#if UNITY_2021_1_OR_NEWER
if (mat.HasFloat(rotProp))
#else
if (mat.HasProperty(rotProp)
#if UNITY_2019_1_OR_NEWER
&& CheckForPropertyInShader(mat.shader, rotProp, ShaderPropertyType.Float)
#endif
)
#endif
rotation = mat.GetFloat(rotProp);
#if UNITY_2021_1_OR_NEWER
if (mat.HasFloat(uvProp))
#else
if (mat.HasProperty(uvProp)
#if UNITY_2019_1_OR_NEWER
&& CheckForPropertyInShader(mat.shader, uvProp, ShaderPropertyType.Float)
#endif
)
#endif
uvChannel = mat.GetFloat(uvProp);
if (offset == Vector2.zero && scale == Vector2.one && rotation == 0)
{
var checkForName = texName + "_ST";
// Debug.Log("Checking for property: " + checkForName + " : " + mat.HasProperty(checkForName) + " == " + (mat.HasProperty(checkForName) ? mat.GetVector(checkForName) : "null"));
var textureHasTilingOffset = mat.HasProperty(checkForName);
#if UNITY_2019_1_OR_NEWER
// turns out we have to check extra hard if that property actually exists
// the material ALWAYS says true for mat.HasProperty(someTex_ST) when someTex is defined and doesn't have [NoTextureScale] attribute
if (textureHasTilingOffset)
{
if (!CheckForPropertyInShader(mat.shader, checkForName, ShaderPropertyType.Vector))
textureHasTilingOffset = false;
}
#endif
if (textureHasTilingOffset)
{
// ignore, texture has explicit _ST property
}
else if(mat.HasProperty("_MainTex_ST") || mat.HasProperty("_BaseMap_ST") || mat.HasProperty("_BaseColorMap_ST") || mat.HasProperty("_BaseColorTexture_ST") || mat.HasProperty("baseColorTexture_ST"))
{
// difficult choice here: some shaders might support texture transform per-texture, others use the main transform.
if (mat.HasProperty("baseColorTexture"))
{
offset = mat.GetTextureOffset("baseColorTexture");
scale = mat.GetTextureScale("baseColorTexture");
rotation = mat.HasProperty("baseColorTextureRotation") ? mat.GetFloat("baseColorTextureRotation") : 0;
}
else if (mat.HasProperty("_BaseColorTexture"))
{
offset = mat.GetTextureOffset("_BaseColorTexture");
scale = mat.GetTextureScale("_BaseColorTexture");
rotation = mat.HasProperty("_BaseColorTextureRotation") ? mat.GetFloat("_BaseColorTextureRotation") : 0;
}
else if (mat.HasProperty("_BaseColorMap"))
{
offset = mat.GetTextureOffset("_BaseColorMap");
scale = mat.GetTextureScale("_BaseColorMap");
}
else if (mat.HasProperty("_BaseMap"))
{
offset = mat.GetTextureOffset("_BaseMap");
scale = mat.GetTextureScale("_BaseMap");
}
else if(mat.HasProperty("_MainTex"))
{
offset = mat.mainTextureOffset;
scale = mat.mainTextureScale;
rotation = 0;
#if UNITY_2021_1_OR_NEWER
if (mat.HasFloat("_MainTexRotation"))
#else
if (mat.HasProperty("_MainTexRotation"))
#endif
rotation = mat.GetFloat("_MainTexRotation");
}
}
else
{
offset = Vector2.zero;
scale = Vector2.one;
}
}
if (_root.ExtensionsUsed == null)
{
_root.ExtensionsUsed = new List<string>(
new[] { ExtTextureTransformExtensionFactory.EXTENSION_NAME }
);
}
else if (!_root.ExtensionsUsed.Contains(ExtTextureTransformExtensionFactory.EXTENSION_NAME))
{
_root.ExtensionsUsed.Add(ExtTextureTransformExtensionFactory.EXTENSION_NAME);
}
if (RequireExtensions)
{
if (_root.ExtensionsRequired == null)
{
_root.ExtensionsRequired = new List<string>(
new[] { ExtTextureTransformExtensionFactory.EXTENSION_NAME }
);
}
else if (!_root.ExtensionsRequired.Contains(ExtTextureTransformExtensionFactory.EXTENSION_NAME))
{
_root.ExtensionsRequired.Add(ExtTextureTransformExtensionFactory.EXTENSION_NAME);
}
}
if (def.Extensions == null)
def.Extensions = new Dictionary<string, IExtension>();
def.Extensions[ExtTextureTransformExtensionFactory.EXTENSION_NAME] = new ExtTextureTransformExtension(
new GLTF.Math.Vector2(offset.x, 1 - offset.y - scale.y),
rotation,
new GLTF.Math.Vector2(scale.x, scale.y),
(int)uvChannel
);
}
public NormalTextureInfo ExportNormalTextureInfo(
Texture texture,
string textureSlot,
Material material)
{
var info = new NormalTextureInfo();
info.Index = ExportTexture(texture, textureSlot);
if (material.HasProperty("normalScale"))
{
info.Scale = material.GetFloat("normalScale");
}
else if (material.HasProperty("_NormalScale"))
{
info.Scale = material.GetFloat("_NormalScale");
}
else if (material.HasProperty("_BumpScale"))
{
info.Scale = material.GetFloat("_BumpScale");
}
return info;
}
private OcclusionTextureInfo ExportOcclusionTextureInfo(
Texture texture,
string textureSlot,
Material material)
{
var info = new OcclusionTextureInfo();
info.Index = ExportTexture(texture, textureSlot);
if (material.HasProperty("occlusionStrength"))
{
info.Strength = material.GetFloat("occlusionStrength");
}
else if (material.HasProperty("_OcclusionStrength"))
{
info.Strength = material.GetFloat("_OcclusionStrength");
}
return info;
}
public PbrMetallicRoughness ExportPBRMetallicRoughness(Material material)
{
var pbr = new PbrMetallicRoughness() { MetallicFactor = 0, RoughnessFactor = 1.0f };
var isGltfPbrMetallicRoughnessShader = material.shader.name.Equals("GLTF/PbrMetallicRoughness", StringComparison.Ordinal);
var isGlTFastShader = material.shader.name.Equals("glTF/PbrMetallicRoughness", StringComparison.Ordinal);
if (material.HasProperty("baseColorFactor"))
{
pbr.BaseColorFactor = material.GetColor("baseColorFactor").ToNumericsColorLinear();
}
else if (material.HasProperty("_BaseColorFactor"))
{
pbr.BaseColorFactor = material.GetColor("_BaseColorFactor").ToNumericsColorLinear();
}
else if (material.HasProperty("_BaseColor"))
{
pbr.BaseColorFactor = material.GetColor("_BaseColor").ToNumericsColorLinear();
}
else if (material.HasProperty("_Color"))
{
pbr.BaseColorFactor = material.GetColor("_Color").ToNumericsColorLinear();
}
if (material.HasProperty("_TintColor")) //particles use _TintColor instead of _Color
{
float white = 1;
if (material.HasProperty("_Color"))
{
var c = material.GetColor("_Color");
white = (c.r + c.g + c.b) / 3.0f; //multiply alpha by overall whiteness of TintColor
}
pbr.BaseColorFactor = (material.GetColor("_TintColor") * white).ToNumericsColorLinear() ;
}
if (material.HasProperty("_MainTex") || material.HasProperty("_BaseMap") || material.HasProperty("_BaseColorTexture") || material.HasProperty("baseColorTexture")) //TODO if additive particle, render black into alpha
{
// TODO use private Material.GetFirstPropertyNameIdByAttribute here, supported from 2020.1+
var mainTexPropertyName = material.HasProperty("_BaseMap") ? "_BaseMap" : material.HasProperty("_MainTex") ? "_MainTex" : material.HasProperty("baseColorTexture") ? "baseColorTexture" : "_BaseColorTexture";
var mainTex = material.GetTexture(mainTexPropertyName);
if (mainTex)
{
pbr.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
ExportTextureTransform(pbr.BaseColorTexture, material, mainTexPropertyName);
pbr.BaseColorTexture.TexCoord = material.HasProperty("baseColorTextureTexCoord") ?
Mathf.RoundToInt(material.GetFloat("baseColorTextureTexCoord")) :
material.HasProperty("_BaseColorTextureTexCoord") ?
Mathf.RoundToInt(material.GetFloat("_BaseColorTextureTexCoord")) : 0;
}
}
var ignoreMetallicFactor = (material.IsKeywordEnabled("_METALLICGLOSSMAP") || material.IsKeywordEnabled("_METALLICSPECGLOSSMAP")) && !isGltfPbrMetallicRoughnessShader && !isGlTFastShader;
if (material.HasProperty("metallicFactor") && !ignoreMetallicFactor)
{
pbr.MetallicFactor = material.GetFloat("metallicFactor");
}
else if (material.HasProperty("_MetallicFactor") && !ignoreMetallicFactor)
{
pbr.MetallicFactor = material.GetFloat("_MetallicFactor");
}
else if (material.HasProperty("_Metallic") && !ignoreMetallicFactor)
{
pbr.MetallicFactor = material.GetFloat("_Metallic");
}
var needToBakeRoughnessIntoTexture = false;
float roughnessMultiplier = 1f;
if (material.HasProperty("roughnessFactor"))
{
float roughness = material.GetFloat("roughnessFactor");
pbr.RoughnessFactor = roughness;
}
else if (material.HasProperty("_RoughnessFactor"))
{
float roughness = material.GetFloat("_RoughnessFactor");
pbr.RoughnessFactor = roughness;
}
else if (material.HasProperty("_Roughness"))
{
float roughness = material.GetFloat("_Roughness");
pbr.RoughnessFactor = roughness;
}
else if (material.HasProperty("_Glossiness") || material.HasProperty("_Smoothness"))
{
var smoothnessPropertyName = material.HasProperty("_Smoothness") ? "_Smoothness" : "_Glossiness";
var metallicGlossMap = material.HasProperty("_MetallicGlossMap") ? material.GetTexture("_MetallicGlossMap") : null;
float smoothness = material.GetFloat(smoothnessPropertyName);
// legacy workaround: the UnityGLTF shaders misuse "_Glossiness" as roughness but don't have a keyword for it.
if (isGltfPbrMetallicRoughnessShader)
smoothness = 1 - smoothness;
if (metallicGlossMap && material.HasProperty("_GlossMapScale") && material.IsKeywordEnabled("_METALLICGLOSSMAP"))
smoothness = material.GetFloat("_GlossMapScale");
var hasMetallicRoughnessMap =
(material.HasProperty("metallicRoughnessTexture") && material.GetTexture("metallicRoughnessTexture")) ||
(material.HasProperty("_MetallicRoughnessTexture") && material.GetTexture("_MetallicRoughnessTexture")) ||
(material.HasProperty("_MetallicGlossMap") && material.GetTexture("_MetallicGlossMap"));
if (!hasMetallicRoughnessMap)
pbr.RoughnessFactor = 1 - smoothness;
else
{
needToBakeRoughnessIntoTexture = true;
roughnessMultiplier = 1 - smoothness;
pbr.RoughnessFactor = 1;
}
}
if (material.HasProperty("metallicRoughnessTexture"))
{
var mrTex = material.GetTexture("metallicRoughnessTexture");
if (mrTex)
{
pbr.MetallicRoughnessTexture = ExportTextureInfo(mrTex, TextureMapType.MetallicRoughness);
ExportTextureTransform(pbr.MetallicRoughnessTexture, material, "metallicRoughnessTexture");
}
}
else if (material.HasProperty("_MetallicRoughnessTexture"))
{
var mrTex = material.GetTexture("_MetallicRoughnessTexture");
if (mrTex)
{
pbr.MetallicRoughnessTexture = ExportTextureInfo(mrTex, TextureMapType.MetallicRoughness);
ExportTextureTransform(pbr.MetallicRoughnessTexture, material, "_MetallicRoughnessTexture");
}
}
else if (material.HasProperty("_MetallicGlossMap"))
{
var mrTex = material.GetTexture("_MetallicGlossMap");
if (mrTex)
{
var conversion = GetExportSettingsForSlot((isGltfPbrMetallicRoughnessShader || isGlTFastShader) ? TextureMapType.Linear : TextureMapType.MetallicGloss);
if (needToBakeRoughnessIntoTexture)
{
conversion = new TextureExportSettings(conversion);
conversion.smoothnessMultiplier = 1 - roughnessMultiplier;
}
pbr.MetallicRoughnessTexture = ExportTextureInfo(mrTex, TextureMapType.MetallicRoughness, conversion);
// in the Standard shader, _METALLICGLOSSMAP replaces _Metallic and so we need to set the multiplier to 1;
// that's not true for the gltf shaders though, so we keep the value there.
if (ignoreMetallicFactor)
pbr.MetallicFactor = 1.0f;
ExportTextureTransform(pbr.MetallicRoughnessTexture, material, "_MetallicGlossMap");
}
}
return pbr;
}
public void ExportUnlit(GLTFMaterial def, Material material){
const string extname = KHR_MaterialsUnlitExtensionFactory.EXTENSION_NAME;
DeclareExtensionUsage( extname, true );
def.AddExtension( extname, new KHR_MaterialsUnlitExtension());
var pbr = new PbrMetallicRoughness();
if (material.HasProperty("baseColorFactor"))
{
pbr.BaseColorFactor = material.GetColor("baseColorFactor").ToNumericsColorLinear();
}
else if (material.HasProperty("_BaseColorFactor"))
{
pbr.BaseColorFactor = material.GetColor("_BaseColorFactor").ToNumericsColorLinear();
}
else if (material.HasProperty("_BaseColor"))
{
pbr.BaseColorFactor = material.GetColor("_BaseColor").ToNumericsColorLinear();
}
else if (material.HasProperty("_Color"))
{
pbr.BaseColorFactor = material.GetColor("_Color").ToNumericsColorLinear();
}
if (material.HasProperty("baseColorTexture"))
{
var mainTex = material.GetTexture("baseColorTexture");
if (mainTex)
{
pbr.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
ExportTextureTransform(pbr.BaseColorTexture, material, "baseColorTexture");
}
}
else if (material.HasProperty("_BaseColorTexture"))
{
var mainTex = material.GetTexture("_BaseColorTexture");
if (mainTex)
{
pbr.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
ExportTextureTransform(pbr.BaseColorTexture, material, "_BaseColorTexture");
}
}
else if (material.HasProperty("_BaseMap"))
{
var mainTex = material.GetTexture("_BaseMap");
if (mainTex)
{
pbr.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
ExportTextureTransform(pbr.BaseColorTexture, material, "_BaseMap");
}
}
else if (material.HasProperty("_MainTex"))
{
var mainTex = material.GetTexture("_MainTex");
if (mainTex)
{
pbr.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
ExportTextureTransform(pbr.BaseColorTexture, material, "_MainTex");
}
}
def.PbrMetallicRoughness = pbr;
}
private void ExportPBRSpecularGlossiness(GLTFMaterial material, Material materialObj)
{
if (_root.ExtensionsUsed == null)
{
_root.ExtensionsUsed = new List<string>(new[] { "KHR_materials_pbrSpecularGlossiness" });
}
else if (!_root.ExtensionsUsed.Contains("KHR_materials_pbrSpecularGlossiness"))
{
_root.ExtensionsUsed.Add("KHR_materials_pbrSpecularGlossiness");
}
if (RequireExtensions)
{
if (_root.ExtensionsRequired == null)
{
_root.ExtensionsRequired = new List<string>(new[] { "KHR_materials_pbrSpecularGlossiness" });
}
else if (!_root.ExtensionsRequired.Contains("KHR_materials_pbrSpecularGlossiness"))
{
_root.ExtensionsRequired.Add("KHR_materials_pbrSpecularGlossiness");
}
}
if (material.Extensions == null)
{
material.Extensions = new Dictionary<string, IExtension>();
}
GLTF.Math.Color diffuseFactor = KHR_materials_pbrSpecularGlossinessExtension.DIFFUSE_FACTOR_DEFAULT;
TextureInfo diffuseTexture = KHR_materials_pbrSpecularGlossinessExtension.DIFFUSE_TEXTURE_DEFAULT;
GLTF.Math.Vector3 specularFactor = KHR_materials_pbrSpecularGlossinessExtension.SPEC_FACTOR_DEFAULT;
double glossinessFactor = KHR_materials_pbrSpecularGlossinessExtension.GLOSS_FACTOR_DEFAULT;
TextureInfo specularGlossinessTexture = KHR_materials_pbrSpecularGlossinessExtension.SPECULAR_GLOSSINESS_TEXTURE_DEFAULT;
if (materialObj.HasProperty("_BaseColor"))
{
diffuseFactor = materialObj.GetColor("_BaseColor").ToNumericsColorLinear();
}
else if (materialObj.HasProperty("_Color"))
{
diffuseFactor = materialObj.GetColor("_Color").ToNumericsColorLinear();
}
if (materialObj.HasProperty("_BaseMap"))
{
var mainTex = materialObj.GetTexture("_BaseMap");
if (mainTex != null)
{
diffuseTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
ExportTextureTransform(diffuseTexture, materialObj, "_BaseMap");
}
}
else if (materialObj.HasProperty("_MainTex"))
{
var mainTex = materialObj.GetTexture("_MainTex");
if (mainTex != null)
{
diffuseTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
ExportTextureTransform(diffuseTexture, materialObj, "_MainTex");
}
}
if (materialObj.HasProperty("_SpecColor"))
{
var specGlossMap = materialObj.GetTexture("_SpecGlossMap");
if (specGlossMap == null)
{
var specColor = materialObj.GetColor("_SpecColor").ToNumericsColorLinear();
specularFactor = new GLTF.Math.Vector3(specColor.R, specColor.G, specColor.B);
}
}
if (materialObj.HasProperty("_Glossiness"))
{
var specGlossMap = materialObj.GetTexture("_SpecGlossMap");
if (specGlossMap == null)
{
glossinessFactor = materialObj.GetFloat("_Glossiness");
}
}
if (materialObj.HasProperty("_SpecGlossMap"))
{
var mgTex = materialObj.GetTexture("_SpecGlossMap");
if (mgTex)
{
specularGlossinessTexture = ExportTextureInfo(mgTex, TextureMapType.SpecGloss);
ExportTextureTransform(specularGlossinessTexture, materialObj, "_SpecGlossMap");
}
}
material.Extensions[KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME] = new KHR_materials_pbrSpecularGlossinessExtension(
diffuseFactor,
diffuseTexture,
specularFactor,
glossinessFactor,
specularGlossinessTexture
);
}
private MaterialCommonConstant ExportCommonConstant(Material materialObj)
{
if (_root.ExtensionsUsed == null)
{
_root.ExtensionsUsed = new List<string>(new[] { "KHR_materials_common" });
}
else if (!_root.ExtensionsUsed.Contains("KHR_materials_common"))
{
_root.ExtensionsUsed.Add("KHR_materials_common");
}
if (RequireExtensions)
{
if (_root.ExtensionsRequired == null)
{
_root.ExtensionsRequired = new List<string>(new[] { "KHR_materials_common" });
}
else if (!_root.ExtensionsRequired.Contains("KHR_materials_common"))
{
_root.ExtensionsRequired.Add("KHR_materials_common");
}
}
var constant = new MaterialCommonConstant();
if (materialObj.HasProperty("_AmbientFactor"))
{
constant.AmbientFactor = materialObj.GetColor("_AmbientFactor").ToNumericsColorRaw();
}
if (materialObj.HasProperty("_LightMap"))
{
var lmTex = materialObj.GetTexture("_LightMap");
if (lmTex)
{
constant.LightmapTexture = ExportTextureInfo(lmTex, TextureMapType.Linear);
ExportTextureTransform(constant.LightmapTexture, materialObj, "_LightMap");
}
}
if (materialObj.HasProperty("_LightFactor"))
{
constant.LightmapFactor = materialObj.GetColor("_LightFactor").ToNumericsColorRaw();
}
return constant;
}
// TODO make internal
public Texture GetSourceTextureForExportedTexture(GLTFTexture exported)
{
var textureIndex = _root.Textures.FindIndex(x => x == exported);
return _textures[textureIndex].Texture;
}
}
}