-
Notifications
You must be signed in to change notification settings - Fork 308
/
BabylonExporter.Texture.cs
1566 lines (1338 loc) · 65.1 KB
/
BabylonExporter.Texture.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 System;
using System.Collections.Generic;
using System.IO;
using Autodesk.Max;
using BabylonExport.Entities;
using Utilities;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Linq;
using System.Text;
namespace Max2Babylon
{
static partial class MaxConstants
{
public const int IMAGE_ALPHA_FILE = 0;
public const int IMAGE_ALPHA_RGB = 2;
public const int IMAGE_ALPHA_NONE = 3;
}
partial class BabylonExporter
{
private static List<string> validFormats = new List<string>(new string[] { "png", "jpg", "jpeg", "tga", "bmp", "gif" });
private static List<string> invalidFormats = new List<string>(new string[] { "dds", "tif", "tiff" });
private Dictionary<string, BabylonTexture> textureMap = new Dictionary<string, BabylonTexture>();
public ITexmap GetSubTexmap(IStdMat2 stdMat, int index)
{
if (!stdMat.MapEnabled(index))
{
return null;
}
return stdMat.GetSubTexmap(index);
}
// -------------------------------
// --- "public" export methods ---
// -------------------------------
private ITexmap GetTexmap(IStdMat2 stdMat, int index, out BabylonFresnelParameters fresnelParameters, out float amount)
{
fresnelParameters = null;
amount = 0;
if (!stdMat.MapEnabled(index))
{
return null;
}
var texMap = stdMat.GetSubTexmap(index);
if (texMap == null)
{
RaiseWarning("Texture channel " + index + " activated but no texture found.", 2);
return null;
}
texMap = _exportFresnelParameters(texMap, out fresnelParameters);
amount = stdMat.GetTexmapAmt(index, 0);
return texMap;
}
private BabylonTexture ExportTexture(IStdMat2 stdMat, int index, out BabylonFresnelParameters fresnelParameters, BabylonScene babylonScene, bool allowCube = false, bool forceAlpha = false)
{
float amount = 1.0f;
ITexmap texMap = GetTexmap(stdMat, index, out fresnelParameters, out amount);
if (texMap == null)
{
return null;
}
return ExportTexture(texMap, babylonScene, amount, allowCube, forceAlpha);
}
private BabylonTexture ExportDiffuseTexture(IStdMat2 stdMat, int index, out BabylonFresnelParameters fresnelParameters, BabylonScene babylonScene, out float[] multiplyColor, bool allowCube = false, bool forceAlpha = false)
{
multiplyColor = null;
float amount = 1.0f;
ITexmap texMap = GetTexmap(stdMat, index, out fresnelParameters, out amount);
if (texMap == null)
{
return null;
}
return ExportDiffuseTexture(texMap, babylonScene, out multiplyColor, amount, allowCube, forceAlpha);
}
private BabylonTexture ExportSpecularTexture(IIGameMaterial materialNode, float[] specularColor, BabylonScene babylonScene)
{
ITexmap specularColorTexMap = _getTexMap(materialNode, 2);
ITexmap specularLevelTexMap = _getTexMap(materialNode, 3);
// --- Babylon texture ---
var specularColorTexture = _getBitmapTex(specularColorTexMap);
var specularLevelTexture = _getBitmapTex(specularLevelTexMap);
if (specularLevelTexture == null)
{
// Copy specular color image
// Assume specular color texture is already pre-multiplied by a global specular level value
// So do not use global specular level
return ExportTexture(specularColorTexture, babylonScene);
}
// Use one as a reference for UVs parameters
var texture = specularColorTexture != null ? specularColorTexture : specularLevelTexture;
if (texture == null)
{
return null;
}
RaiseMessage("Multiply specular color and level textures", 2);
string nameText = (specularColorTexture != null ? Path.GetFileNameWithoutExtension(specularColorTexture.Map.FullFilePath) : TextureUtilities.ColorToStringName(specularColor)) +
Path.GetFileNameWithoutExtension(specularLevelTexture.Map.FullFilePath) + "_specularColor";
var textureID = texture.GetGuid().ToString();
if (textureMap.ContainsKey(textureID))
{
return textureMap[textureID];
}
else
{
var babylonTexture = new BabylonTexture(textureID)
{
name = nameText + ".jpg" // TODO - unsafe name, may conflict with another texture name
};
// Level
babylonTexture.level = 1.0f;
// UVs
var uvGen = _exportUV(texture.UVGen, babylonTexture);
// Is cube
_exportIsCube(texture.Map.FullFilePath, babylonTexture, false);
// --- Multiply specular color and level maps ---
// Alpha
babylonTexture.hasAlpha = false;
babylonTexture.getAlphaFromRGB = false;
if (exportParameters.writeTextures)
{
// Load bitmaps
var specularColorBitmap = _loadTexture(specularColorTexMap);
var specularLevelBitmap = _loadTexture(specularLevelTexMap);
if (specularLevelBitmap == null)
{
// Copy specular color image
RaiseError("Failed to load specular level texture. Specular color is exported alone.", 3);
return ExportTexture(specularColorTexture, babylonScene);
}
// Retreive dimensions
int width = 0;
int height = 0;
var haveSameDimensions = TextureUtilities.GetMinimalBitmapDimensions(out width, out height, specularColorBitmap, specularLevelBitmap);
if (!haveSameDimensions)
{
RaiseError("Specular color and specular level maps should have same dimensions", 3);
}
// Create pre-multiplied specular color map
var _specularColor = Color.FromArgb(
(int)(specularColor[0] * 255),
(int)(specularColor[1] * 255),
(int)(specularColor[2] * 255));
Bitmap specularColorPreMultipliedBitmap = new Bitmap(width, height);
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
var specularColorAtPixel = specularColorBitmap != null ? specularColorBitmap.GetPixel(x, y) : _specularColor;
var specularLevelAtPixel = specularLevelBitmap.GetPixel(x, y);
var specularColorPreMultipliedAtPixel = specularColorAtPixel.multiply(specularLevelAtPixel);
specularColorPreMultipliedBitmap.SetPixel(x, y, specularColorPreMultipliedAtPixel);
}
}
// Write bitmap
if (isBabylonExported)
{
RaiseMessage($"Texture | write image '{babylonTexture.name}'", 3);
TextureUtilities.SaveBitmap(specularColorPreMultipliedBitmap, babylonScene.OutputPath, babylonTexture.name, ImageFormat.Jpeg, exportParameters.txtQuality, this);
}
else
{
// Store created bitmap for further use in gltf export
babylonTexture.bitmap = specularColorPreMultipliedBitmap;
}
}
textureMap.Add(babylonTexture.Id, babylonTexture);
return babylonTexture;
}
}
private BabylonTexture ExportPBRTexture(IIGameMaterial materialNode, int index, BabylonScene babylonScene, float amount = 1.0f, bool allowCube = false)
{
var texMap = _getTexMap(materialNode, index);
return texMap != null ? ExportTexture(texMap, babylonScene, amount, allowCube) : null;
}
private BabylonTexture ExportPBRTexture(IIGameMaterial materialNode, string name, BabylonScene babylonScene, float amount = 1.0f, bool allowCube = false)
{
var texMap = _getTexMap(materialNode, name);
return texMap != null?ExportTexture(texMap, babylonScene, amount, allowCube):null;
}
private BabylonTexture ExportClearCoatTexture(ITexmap intensityTexMap, ITexmap roughnessTexMap, float coatWeight, float coatRoughness, BabylonScene babylonScene, string materialName, bool invertRoughness)
{
// --- Babylon texture ---
var intensityTexture = _getBitmapTex(intensityTexMap);
var roughnessTexture = _getBitmapTex(roughnessTexMap);
var texture = intensityTexture != null ? intensityTexture : roughnessTexture;
if (texture == null)
{
return null;
}
// Use one as a reference for UVs parameters
RaiseMessage("Export Clear Coat weight+roughness texture", 2);
string nameText = Path.GetFileNameWithoutExtension(texture.Map.FullFilePath);
var textureID = texture.GetGuid().ToString();
if (textureMap.ContainsKey(textureID))
{
return textureMap[textureID];
}
else
{
var babylonTexture = new BabylonTexture(textureID)
{
name = nameText // TODO - unsafe name, may conflict with another texture name
};
// Level
babylonTexture.level = 1.0f;
// UVs
var uvGen = _exportUV(texture.UVGen, babylonTexture);
// Is cube
_exportIsCube(texture.Map.FullFilePath, babylonTexture, false);
// --- Merge maps ---
var hasIntensity = isTextureOk(intensityTexture);
var hasRoughness = isTextureOk(roughnessTexture);
if (!hasIntensity && !hasRoughness)
{
return null;
}
// Set image format
ImageFormat imageFormat = ImageFormat.Jpeg;
babylonTexture.name += ".jpg";
if (exportParameters.writeTextures)
{
// Load bitmaps
var intensityBitmap = _loadTexture(intensityTexture);
var roughnessBitmap = _loadTexture(roughnessTexture);
// Retreive dimensions
int width = 0;
int height = 0;
var haveSameDimensions = TextureUtilities.GetMinimalBitmapDimensions(out width, out height, intensityBitmap, roughnessBitmap);
if (!haveSameDimensions)
{
RaiseError("Base color and transparency color maps should have same dimensions", 3);
}
// Create map
var _intensity = (int)(coatWeight * 255);
var _roughness = (int)(coatRoughness * 255);
Bitmap intensityRoughnessBitmap = new Bitmap(width, height);
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
var intensityAtPixel = (intensityBitmap == null) ? _intensity : intensityBitmap.GetPixel(x, y).R;
Color intensityRoughness;
if (roughnessBitmap == null)
{
intensityRoughness = Color.FromArgb(intensityAtPixel, _roughness, 0);
}
else
{
var roughnessAtPixel = (roughnessBitmap == null) ?
_roughness :
invertRoughness ? 255 - roughnessBitmap.GetPixel(x, y).G : roughnessBitmap.GetPixel(x, y).G;
intensityRoughness = Color.FromArgb(intensityAtPixel, roughnessAtPixel, 0);
}
intensityRoughnessBitmap.SetPixel(x, y, intensityRoughness);
}
}
// Write bitmap
if (isBabylonExported)
{
RaiseMessage($"Texture | write image '{babylonTexture.name}'", 3);
TextureUtilities.SaveBitmap(intensityRoughnessBitmap, babylonScene.OutputPath, babylonTexture.name, imageFormat, exportParameters.txtQuality, this);
}
else
{
// Store created bitmap for further use in gltf export
babylonTexture.bitmap = intensityRoughnessBitmap;
}
}
return babylonTexture;
}
}
/// <returns></returns>
private BabylonTexture ExportBaseColorAlphaTexture(ITexmap baseColorTexMap, ITexmap alphaTexMap, float[] baseColor, float alpha, BabylonScene babylonScene, out float[] multiplyColor, bool isOpacity = false)
{
// --- Babylon texture ---
var baseColorTexture = _getBitmapTex(baseColorTexMap, out multiplyColor);
var alphaTexture = _getBitmapTex(alphaTexMap);
// If we don't retrieve any textures from Max, return null.
if (baseColorTexture == null && alphaTexture == null)
{
return null;
}
string baseColorTextureMapExtension = null;
var baseColorSourcePath = baseColorTexture?.Map.FullFilePath;
var alphaSourcePath = alphaTexture?.Map.FullFilePath;
// If we only have a base color texture, and we are using an opaque texture, export the base color image only.
if (baseColorTexture != null && alphaTexture == null)
{
baseColorTextureMapExtension = Path.GetExtension(baseColorTexture.Map.FullFilePath).ToLower();
if (alpha == 1)
{
if (baseColorTexture.AlphaSource == MaxConstants.IMAGE_ALPHA_FILE &&
(baseColorTextureMapExtension == ".tif" || baseColorTextureMapExtension == ".tiff"))
{
RaiseWarning($"Diffuse texture named {baseColorTexture.Map.FullFilePath} is a .tif file and its Alpha Source is 'Image Alpha' by default.", 3);
RaiseWarning($"If you don't want material to be in BLEND mode, set diffuse texture Alpha Source to 'None (Opaque)'", 3);
}
// Copy base color image
var outTexture = ExportTexture(baseColorTexture, babylonScene);
if (outTexture != null)
{
// used to keep trace of the base + apha merge sources
outTexture.baseColorPath = baseColorSourcePath;
outTexture.alphaPath = null;
textureMap[outTexture.Id] = outTexture;
}
return outTexture;
}
}
// Otherwise combine base color and alpha textures to a single output texture
RaiseMessage("Export baseColor+Alpha texture", 2);
var hasBaseColor = baseColorTexture != null && File.Exists(baseColorTexture.Map.FullFilePath);
var hasAlpha = isTextureOk(alphaTexMap);
var texture = hasBaseColor ? baseColorTexture : alphaTexture;
ImageFormat imageFormat = null;
if (hasBaseColor)
{
imageFormat = TextureUtilities.GetImageFormat(Path.GetExtension(baseColorTexture.Map.FullFilePath));
}
if (hasAlpha || imageFormat == null)
{
baseColorTextureMapExtension = ".png"; // since we are adding an alpha channel, export as png. This will convert any other input base texture format to PNG.
imageFormat = ImageFormat.Png;
}
// since we are creating a new texture, give it a unique ID based on the base color and alpha maps.
var nameText = (hasBaseColor ? Path.GetFileNameWithoutExtension(baseColorTexture.Map.FullFilePath) + (hasAlpha ? "_" + Path.GetFileNameWithoutExtension(alphaTexture.Map.FullFilePath) : "") : TextureUtilities.ColorToStringName(baseColor));
var textureID = hasBaseColor ? texture.GetGuid().ToString() + (hasAlpha ? "_" + alphaTexture.GetGuid().ToString() : "") : string.Format("{0}_{1}", texture.GetGuid().ToString(), nameText);
if (textureMap.ContainsKey(textureID))
{
return textureMap[textureID];
}
BabylonTexture babylonTexture = null;
babylonTexture = new BabylonTexture(textureID)
{
name = nameText,
// used to keep trace of the base + apha merge sources
baseColorPath = baseColorSourcePath,
alphaPath = alphaSourcePath
};
// Alpha
babylonTexture.hasAlpha = hasAlpha || (hasBaseColor && (baseColorTexture.AlphaSource == MaxConstants.IMAGE_ALPHA_FILE || baseColorTexture.AlphaSource == MaxConstants.IMAGE_ALPHA_RGB)) || alpha < 1.0f;
babylonTexture.getAlphaFromRGB = false;
if (!hasBaseColor && !hasAlpha)
{
return null;
}
if ((!isTextureOk(alphaTexMap) && alpha == 1.0f && (hasBaseColor && baseColorTexture.AlphaSource == MaxConstants.IMAGE_ALPHA_FILE)) &&
(baseColorTextureMapExtension == ".tif" || baseColorTextureMapExtension == ".tiff"))
{
RaiseWarning($"Diffuse texture named {baseColorTexture.Map.FullFilePath} is a .tif file and its Alpha Source is 'Image Alpha' by default.", 3);
RaiseWarning($"If you don't want material to be in BLEND mode, set diffuse texture Alpha Source to 'None (Opaque)'", 3);
}
// Set image format
if (hasAlpha)
{
babylonTexture.name += "_alpha_" + alphaTexture.Name;
}
if (imageFormat == ImageFormat.Jpeg)
{
babylonTexture.name += ".jpg";
}
else
{
babylonTexture.name += "." + imageFormat.ToString();
}
// Level
babylonTexture.level = 1.0f;
// UVs
var uvGen = _exportUV(texture.UVGen, babylonTexture);
// Is cube
_exportIsCube(texture.Map.FullFilePath, babylonTexture, false);
// --- Merge baseColor and alpha maps ---
if (exportParameters.writeTextures && baseColorTexture != alphaTexture && alphaTexture != null)
{
// Load bitmaps
var baseColorBitmap = baseColorTexture != null ? TextureUtilities.LoadTexture(baseColorTexture.Map.FullFilePath, this) : null;
var alphaBitmap = _loadTexture(alphaTexMap);
// Retreive dimensions
int width = 0;
int height = 0;
var haveSameDimensions = TextureUtilities.GetMinimalBitmapDimensions(out width, out height, baseColorBitmap, alphaBitmap);
if (!haveSameDimensions)
{
RaiseError("Base color and transparency color maps should have same dimensions", 3);
}
var getAlphaFromRGB = alphaTexture != null && ((alphaTexture.AlphaSource == MaxConstants.IMAGE_ALPHA_RGB) || (alphaTexture.AlphaSource == MaxConstants.IMAGE_ALPHA_NONE)); // 'RGB intensity' or 'None (Opaque)'
// Create baseColor+alpha map
var _baseColor = Color.FromArgb(
(int)(baseColor[0] * 255),
(int)(baseColor[1] * 255),
(int)(baseColor[2] * 255));
var _alpha = (int)(alpha * 255);
Bitmap baseColorAlphaBitmap = new Bitmap(width, height);
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
var baseColorAtPixel = baseColorBitmap != null ? baseColorBitmap.GetPixel(x, y) : _baseColor;
Color baseColorAlpha;
if (alphaBitmap != null)
{
// Retreive alpha from alpha texture
Color alphaColor = alphaBitmap.GetPixel(x, y);
int alphaAtPixel = getAlphaFromRGB ? alphaColor.R : alphaColor.A;
if (isOpacity == false)
{
// Convert transparency to opacity
alphaAtPixel = 255 - alphaAtPixel;
}
baseColorAlpha = Color.FromArgb(alphaAtPixel, baseColorAtPixel);
}
else if (baseColorTexture != null && baseColorTexture.AlphaSource == MaxConstants.IMAGE_ALPHA_FILE) // Alpha source is 'Image Alpha'
{
// Use all channels from base color
baseColorAlpha = baseColorAtPixel;
}
else
{
// Use RGB channels from base color and default alpha
baseColorAlpha = Color.FromArgb(_alpha, baseColorAtPixel.R, baseColorAtPixel.G, baseColorAtPixel.B);
}
baseColorAlphaBitmap.SetPixel(x, y, baseColorAlpha);
}
}
// If there is a "#" in the generated texture filename it causes problems with Exporter webserver
// when viewing the final exported project. This converts any troublesome characters to underscores
babylonTexture.name = PathUtilities.VerifyLegalFileName(babylonTexture.name);
// Write bitmap
if (isBabylonExported)
{
RaiseMessage($"Texture | write image '{babylonTexture.name}'", 3);
TextureUtilities.SaveBitmap(baseColorAlphaBitmap, babylonScene.OutputPath, babylonTexture.name, imageFormat, exportParameters.txtQuality, this);
}
else
{
// Store created bitmap for further use in gltf export
babylonTexture.bitmap = baseColorAlphaBitmap;
}
}
return babylonTexture;
}
/// <summary>
/// This texture Specifies both the specular color RGB and the glossiness A of the material per pixels.
/// </summary>
/// <param name="ambientOcclusionTexMap"></param>
/// <param name="glossinessTexMap"></param>
/// <param name="specularTexMap"></param>
/// <param name="glossiness"></param>
/// <param name="specularColor"></param>
/// <param name="babylonScene"></param>
/// <returns></returns>
private BabylonTexture ExportSpecularGlossinessTexture(float[] specularColor, ITexmap specularTexMap, float glossiness, ITexmap glossinessTexMap, BabylonScene babylonScene)
{
var specularTexture = _getBitmapTex(specularTexMap);
var glossinessTexture = _getBitmapTex(glossinessTexMap);
// we are trying to get the best output format, function of source and policy.
var paths = new IBitmapTex[] { specularTexture, glossinessTexture}.Where(t => t != null).Select(t => t.Map.FileName);
var policy = exportParameters.textureFormatExportPolicy;
var preferredExtension = TextureUtilities.GetPreferredFormat(paths, false, policy);
// Use metallic or roughness texture as a reference for UVs parameters
var refTexture = specularTexture?? glossinessTexture;
if (refTexture == null)
{
return null;
}
RaiseMessage("Export Specular Glossiness texture", 2);
var textureID = refTexture.GetGuid().ToString();
if (textureMap.ContainsKey(textureID))
{
return textureMap[textureID];
}
var babylonTexture = new BabylonTexture(textureID)
{
name = BuildSpecularGlossinessTextureName(specularColor, specularTexture, glossiness, glossinessTexture) + "." + preferredExtension // TODO - unsafe name, may conflict with another texture name
};
// UVs
var uvGen = _exportUV(refTexture.UVGen, babylonTexture);
// Is cube
_exportIsCube(refTexture.Map.FullFilePath, babylonTexture, false);
// --- Merge specular and gloossiness maps ---
if (!isTextureOk(specularTexMap) && !isTextureOk(glossinessTexMap))
{
return null;
}
if (exportParameters.writeTextures)
{
// Load bitmaps
var specularBitmap = _loadTexture(specularTexMap);
var glossinessBitmap = _loadTexture(glossinessTexMap);
// Retreive dimensions
int width = 0;
int height = 0;
var haveSameDimensions = TextureUtilities.GetMinimalBitmapDimensions(out width, out height, specularBitmap, glossinessBitmap);
if (!haveSameDimensions)
{
RaiseError("Specular and glossiness maps should have same dimensions", 3);
}
// Create specular glossiness map
Bitmap newBitmap = new Bitmap(width, height);
int[] rgbColor = specularColor.Select(v => (int)(v * 255)).ToArray();
int glossinessFactor = (int)(glossiness * 255);
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int alpha = glossinessBitmap?.GetPixel(x, y).R ?? glossinessFactor;
float [] rgb = specularBitmap?.GetPixel(x, y).toArrayRGB()??specularColor;
Color color = Color.FromArgb(alpha, (int)rgb[0], (int)rgb[1], (int)rgb[2]);
newBitmap.SetPixel(x, y, color);
}
}
// Write bitmap
if (isBabylonExported)
{
RaiseMessage($"Texture | write image '{babylonTexture.name}'", 3);
var imageFormat = TextureUtilities.GetImageFormat(Path.GetExtension(babylonTexture.name));
TextureUtilities.SaveBitmap(newBitmap, babylonScene.OutputPath, babylonTexture.name, imageFormat, exportParameters.txtQuality, this);
}
else
{
// Store created bitmap for further use in gltf export
babylonTexture.bitmap = newBitmap;
}
}
textureMap[babylonTexture.Id] = babylonTexture;
return babylonTexture;
}
private static string BuildSpecularGlossinessTextureName(float[] specularColor, IBitmapTex specularMap, float glossiness, IBitmapTex glossinessMap)
{
var specPart = $"{GetFileNameWithoutExtension(specularMap)}_{GetColorCode(specularColor)}";
var glossPart = $"{GetFileNameWithoutExtension(glossinessMap)}_{glossiness*255}";
return $"{specPart}_{glossPart}";
}
private static string GetFileNameWithoutExtension(IBitmapTex text)
{
var str = text.Map?.FileName;
return str != null ? Path.GetFileNameWithoutExtension(str) : string.Empty;
}
private static string GetColorCode(float[] c)
{
if( c == null)
{
return string.Empty;
}
StringBuilder sb = new StringBuilder();
for(int i=0; i < c.Length && i < 3; i++)
{
sb.Append(((int)(c[i]*255)).ToString("X2"));
}
return sb.ToString();
}
private BabylonTexture ExportORMTexture(ITexmap ambientOcclusionTexMap, ITexmap roughnessTexMap, ITexmap metallicTexMap, float metallic, float roughness, BabylonScene babylonScene, bool invertRoughness)
{
// --- Babylon texture ---
var metallicTexture = _getBitmapTex(metallicTexMap);
var roughnessTexture = _getBitmapTex(roughnessTexMap);
var ambientOcclusionTexture = _getBitmapTex(ambientOcclusionTexMap);
// we are trying to get the best output format, function of source and policy.
var paths = new IBitmapTex[] { metallicTexture, roughnessTexture, ambientOcclusionTexture }.Where(t => t != null).Select(t => t.Map.FileName);
var policy = exportParameters.textureFormatExportPolicy;
var preferredExtension = TextureUtilities.GetPreferredFormat(paths, false, policy);
// Use metallic or roughness texture as a reference for UVs parameters
var refTexture = metallicTexture != null ? metallicTexture : roughnessTexture;
if (refTexture == null)
{
return null;
}
RaiseMessage("Export ORM texture", 2);
var textureID = refTexture.GetGuid().ToString();
if (textureMap.ContainsKey(textureID))
{
return textureMap[textureID];
}
else {
var babylonTexture = new BabylonTexture(textureID)
{
name = (ambientOcclusionTexMap != null ? Path.GetFileNameWithoutExtension(ambientOcclusionTexture.Map.FileName) : "") +
(roughnessTexMap != null ? Path.GetFileNameWithoutExtension(roughnessTexture.Map.FileName) : ("" + (int)(roughness * 255))) +
(metallicTexMap != null ? Path.GetFileNameWithoutExtension(metallicTexture.Map.FileName) : ("" + (int)(metallic * 255))) + "." + preferredExtension // TODO - unsafe name, may conflict with another texture name
};
// UVs
var uvGen = _exportUV(refTexture.UVGen, babylonTexture);
// Is cube
_exportIsCube(refTexture.Map.FullFilePath, babylonTexture, false);
// --- Merge metallic and roughness maps ---
if (!isTextureOk(metallicTexMap) && !isTextureOk(roughnessTexMap))
{
return null;
}
if (exportParameters.writeTextures)
{
// Load bitmaps
var metallicBitmap = _loadTexture(metallicTexMap);
var roughnessBitmap = _loadTexture(roughnessTexMap);
var ambientOcclusionBitmap = _loadTexture(ambientOcclusionTexMap);
// Retreive dimensions
int width = 0;
int height = 0;
var haveSameDimensions = TextureUtilities.GetMinimalBitmapDimensions(out width, out height, metallicBitmap, roughnessBitmap, ambientOcclusionBitmap);
if (!haveSameDimensions)
{
RaiseError((ambientOcclusionBitmap != null ? "Occlusion, roughness and metallic " : "Metallic and roughness") + " maps should have same dimensions", 3);
}
// Create ORM map
Bitmap ormBitmap = new Bitmap(width, height);
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int _occlusion = ambientOcclusionBitmap != null ? ambientOcclusionBitmap.GetPixel(x, y).R : 0;
int _roughness = roughnessBitmap != null ? (invertRoughness ? 255 - roughnessBitmap.GetPixel(x, y).G : roughnessBitmap.GetPixel(x, y).G) : (int)(roughness * 255.0f);
int _metallic = metallicBitmap != null ? metallicBitmap.GetPixel(x, y).B : (int)(metallic * 255.0f);
// The occlusion values are sampled from the R channel.
// The roughness values are sampled from the G channel.
// The metalness values are sampled from the B channel.
Color colorMetallicRoughness = Color.FromArgb(_occlusion, _roughness, _metallic);
ormBitmap.SetPixel(x, y, colorMetallicRoughness);
}
}
// Write bitmap
if (isBabylonExported)
{
RaiseMessage($"Texture | write image '{babylonTexture.name}'", 3);
var imageFormat = TextureUtilities.GetImageFormat(Path.GetExtension(babylonTexture.name));
TextureUtilities.SaveBitmap(ormBitmap, babylonScene.OutputPath, babylonTexture.name, imageFormat, exportParameters.txtQuality, this);
}
else
{
// Store created bitmap for further use in gltf export
babylonTexture.bitmap = ormBitmap;
}
}
textureMap[babylonTexture.Id] = babylonTexture;
return babylonTexture;
}
}
private BabylonTexture ExportEnvironmnentTexture(ITexmap texMap, BabylonScene babylonScene)
{
if (texMap.GetParamBlock(0) == null || texMap.GetParamBlock(0).Owner == null)
{
RaiseWarning("Failed to export environment texture. Uncheck \"Use Map\" option to fix this warning.");
return null;
}
var texture = texMap.GetParamBlock(0).Owner as IBitmapTex;
if (texture == null)
{
RaiseWarning("Failed to export environment texture. Uncheck \"Use Map\" option to fix this warning.");
return null;
}
var sourcePath = texture.Map.FullFilePath;
var fileName = Path.GetFileName(sourcePath);
// Allow only dds file format
if (!fileName.EndsWith(".dds"))
{
RaiseWarning("Failed to export environment texture: only .dds format is supported. Uncheck \"Use map\" to fix this warning.");
return null;
}
var textureID = texture.GetGuid().ToString();
if (textureMap.ContainsKey(textureID))
{
return textureMap[textureID];
}
else
{
var babylonTexture = new BabylonTexture(textureID)
{
name = fileName
};
// Copy texture to output
if (isBabylonExported)
{
var destPath = Path.Combine(babylonScene.OutputPath, babylonTexture.name);
if (exportParameters.writeTextures)
{
try
{
if (File.Exists(sourcePath) && sourcePath != destPath)
{
File.Copy(sourcePath, destPath, true);
}
}
catch
{
// silently fails
}
}
}
return babylonTexture;
}
}
// -------------------------
// -- Export sub methods ---
// -------------------------
private ITexmap _getSpecialTexmap(ITexmap texMap, out float amount, out IEnumerable<TextureOperation> operations)
{
operations = null;
amount = 0.0f;
if (texMap == null)
{
return null;
}
#if MAX2022 || MAX2023
if (texMap.ClassName(false) == "Normal Bump")
#else
if (texMap.ClassName == "Normal Bump")
#endif
{
var block = texMap.GetParamBlockByID(0); // General Block
if (block != null)
{
amount = block.GetFloat(0, 0, 0); // Normal texture Mult Spin
var map = block.GetTexmap(2, 0, 0); // Normal texture
var mapEnabled = block.GetInt(4, 0, 0); // Normal texture Enable
if (map == null || mapEnabled == 0)
{
RaiseError($"Only Normal Bump Texture with Normal enabled are supported.", 2);
return null;
}
var method = block.GetInt(6, 0, 0); // Normal texture mode (Tangent, screen...)
if (method != 0)
{
RaiseError($"Only Normal Bump Texture in tangent space are supported.", 2);
return null;
}
operations = GetNormalBump3DSMaxOperations(texMap, block);
var bumpAmount = block.GetFloat(1, 0, 0); // Bump texture Mult Spin
var bumpMap = block.GetTexmap(3, 0, 0); // Bump texture
var bumpMapEnable = block.GetInt(5, 0, 0); // Bump texture Enable
if (bumpMap != null && bumpMapEnable == 1)
{
RaiseError($"Only Normal Bump Texture without Bump are supported.", 2);
return null;
}
return map;
}
}
RaiseError($"Texture type is not supported. Use a Bitmap or Normal Bump map instead.", 2);
return null;
}
/// <summary>
/// Create the list of operation to transform the NormalMap, according Max and Babylon attributes
/// </summary>
/// <param name="texMap"></param>
/// <param name="block"></param>
/// <returns></returns>
private IEnumerable<TextureOperation> GetNormalBump3DSMaxOperations(ITexmap texMap, IIParamBlock2 block)
{
var flipR = block.GetInt(7, 0, 0); // Normal texture Red chanel Flip
var flipG = block.GetInt(8, 0, 0); // Normal texture Green chanel Flip
var swapRG = block.GetInt(9, 0, 0); // Normal texture swap R and G channels
// try to retreive the custom Babylon Attributes
IICustAttribContainer custAtt = texMap.CustAttribContainer;
if( custAtt == null)
{
yield break;
}
var n = custAtt.NumCustAttribs;
ICustAttrib att = null;
for (int i = 0; i != n; i++)
{
var tmp = custAtt.GetCustAttrib(i);
#if MAX2022 || MAX2023
if (tmp.ClassName(false) == MaterialCustomBabylonAttributeName)
#else
if (tmp.ClassName == MaterialCustomBabylonAttributeName)
#endif
{
att = tmp;
break;
}
}
MaxNormalMapParameters parameters = new MaxNormalMapParameters();
IIParamBlock2 customBlock = att?.GetParamBlockByID(0);
if (customBlock != null)
{
parameters.useMaxTransforms = customBlock.GetInt(0, 0, 0) != 0;
parameters.Y = (NormalMapY)customBlock.GetInt(1, 0, 0);
parameters.Coordinate = (MapCoordinate)customBlock.GetInt(2, 0, 0);
}
bool mustFlipR = parameters.useMaxTransforms && flipR != 0;
bool mustSwapRG = parameters.useMaxTransforms && swapRG != 0;
// flip green G = 255-G (individual pixel values into the texture)
bool mustFlipG = parameters.useMaxTransforms && flipG != 0;
switch (parameters.Y)
{
case NormalMapY.positiv:
{
// opengl norm
if (isBabylonExported)
{
// texture source is OpenGL and babylon is DirectX, so we may flip G.
// May void the Max operation if selected.
mustFlipG = !mustFlipG;
}
break;
}
case NormalMapY.negativ:
{
// directx norm
if (isGltfExported)
{
// texture source is DirectX and Gltf is OpenGL, so we may flip G.
// May void the Max operation if selected.
mustFlipG = !mustFlipG;
}
break;
}
}
if (mustFlipR)
{
yield return new FlipChannel(FlipChannel.ChannelRed);
}
if (mustFlipG)
{
yield return new FlipChannel(FlipChannel.ChannelGreen);
}
if (mustSwapRG)
{
yield return new SwapChannel(FlipChannel.ChannelRed, FlipChannel.ChannelGreen);
}
// Invert Y coordinate Y = 1-Y (physical row layout into the texture)
bool mustInvertY = false;
switch (parameters.Coordinate)
{
case MapCoordinate.right:
{
// opengl norm
if (isBabylonExported)
{
// texture source is OpenGL and babylon is DirectX, so we may invert Y coordinate.
mustInvertY = true;
}
break;
}
case MapCoordinate.left:
{
// directx norm
if (isGltfExported)
{
// texture source is DirectX and Gltf is OpenGL, so we may invert Y coordinate.
mustInvertY = true;
}
break;
}
}
if (mustInvertY)
{
yield return new InvertY();
}
}
private BabylonTexture ExportTexture(ITexmap texMap, BabylonScene babylonScene, float amount = 1.0f, bool allowCube = false, bool forceAlpha = false)
{