-
Notifications
You must be signed in to change notification settings - Fork 333
/
MaterialReader.cs
1071 lines (948 loc) · 44.6 KB
/
MaterialReader.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
// Project: Daggerfall Unity
// Copyright: Copyright (C) 2009-2023 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors:
//
// Notes:
//
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DaggerfallConnect;
using DaggerfallConnect.Utility;
using DaggerfallConnect.Arena2;
using DaggerfallWorkshop.Utility;
using DaggerfallWorkshop.Utility.AssetInjection;
namespace DaggerfallWorkshop
{
#region Uniforms
public static class KeyWords
{
public const string CutOut = "_ALPHATEST_ON";
public const string Fade = "_ALPHABLEND_ON";
public const string Transparent = "_ALPHAPREMULTIPLY_ON";
public const string NormalMap = "_NORMALMAP";
public const string HeightMap = "_PARALLAXMAP";
public const string Emission = "_EMISSION";
public const string MetallicGlossMap = "_METALLICGLOSSMAP";
public const string MacOSX = "_MacOSX";
}
public static class Uniforms
{
public static readonly int MainTex = Shader.PropertyToID("_MainTex");
public static readonly int Glossiness = Shader.PropertyToID("_Glossiness");
public static readonly int SmoothnessTextureChannel = Shader.PropertyToID("_SmoothnessTextureChannel");
public static readonly int Metallic = Shader.PropertyToID("_Metallic");
public static readonly int MetallicGlossMap = Shader.PropertyToID("_MetallicGlossMap");
public static readonly int Smoothness = Shader.PropertyToID("_Smoothness");
public static readonly int BumpMap = Shader.PropertyToID("_BumpMap");
public static readonly int HeightMap = Shader.PropertyToID("_ParallaxMap");
public static readonly int EmissionColor = Shader.PropertyToID("_EmissionColor");
public static readonly int EmissionMap = Shader.PropertyToID("_EmissionMap");
public static readonly int Mode = Shader.PropertyToID("_Mode");
public static readonly int SrcBlend = Shader.PropertyToID("_SrcBlend");
public static readonly int DstBlend = Shader.PropertyToID("_DstBlend");
public static readonly int ZWrite = Shader.PropertyToID("_ZWrite");
public static readonly int[] Textures = new int[]
{
MainTex, EmissionMap, BumpMap, HeightMap, MetallicGlossMap
};
}
public static class TileUniforms
{
public static readonly int TileAtlasTex = Shader.PropertyToID("_TileAtlasTex");
public static readonly int TilemapTex = Shader.PropertyToID("_TilemapTex");
public static readonly int TilemapDim = Shader.PropertyToID("_TilemapDim");
}
public static class TileTexArrUniforms
{
public static readonly int TileTexArr = Shader.PropertyToID("_TileTexArr");
public static readonly int TileNormalMapTexArr = Shader.PropertyToID("_TileNormalMapTexArr");
public static readonly int TileParallaxMapTexArr = Shader.PropertyToID("_TileParallaxMapTexArr");
public static readonly int TileMetallicGlossMapTexArr = Shader.PropertyToID("_TileMetallicGlossMapTexArr");
public static readonly int TilemapTex = Shader.PropertyToID("_TilemapTex");
}
#endregion
/// <summary>
/// Imports Daggerfall images into Unity.
/// Should only be attached to DaggerfallUnity singleton (for which it is a required component).
/// Note: Texture loading methods have been moved to TextureReader class.
/// </summary>
[RequireComponent(typeof(DaggerfallUnity))]
public class MaterialReader : MonoBehaviour
{
#region Fields
// Constants
public const int FireWallsArchive = 356;
// General settings
public bool AtlasTextures = true;
public bool CompressSkyTextures = false;
public bool CompressModdedTextures = true;
public bool Sharpen = false;
public bool GenerateNormals = false;
public float NormalTextureStrength = 0.2f;
public FilterMode MainFilterMode = FilterMode.Point;
public FilterMode SkyFilterMode = FilterMode.Point;
public bool MipMaps = true;
public bool ReadableTextures = false;
public SupportedAlphaTextureFormats AlphaTextureFormat = SupportedAlphaTextureFormats.ARGB32;
// Window settings
public Color DayWindowColor = new Color32(89, 154, 178, 0xff);
public Color NightWindowColor = new Color32(255, 182, 56, 0xff);
public Color FogWindowColor = new Color32(117, 117, 117, 0xff);
public Color CustomWindowColor = new Color32(200, 0, 200, 0xff);
public float DayWindowIntensity = 0.5f;
public float NightWindowIntensity = 0.8f;
public float FogWindowIntensity = 0.5f;
public float CustomWindowIntensity = 1.0f;
// Keys groups use increments of 512 as this the total number of texture file indices.
// Groups allow the same material to be uniquely cached based on usage.
// There can be a maximum of 128 unique groups of materials in cache.
public const int MainKeyGroup = 0;
public const int AtlasKeyGroup = 512;
public const int TileMapKeyGroup = 1024;
public const int CustomBillboardKeyGroup = 1536;
//public const int UnusedKeyGroup2 = 2048;
//public const int UnusedKeyGroup3 = 2560;
//public const int UnusedKeyGroup4 = 3584;
//public const int UnusedKeyGroup5 = 4096;
// Shader names
public const string _StandardShaderName = "Standard";
public const string _DaggerfallDefaultShaderName = "Daggerfall/Default";
public const string _DaggerfallTilemapShaderName = "Daggerfall/Tilemap";
public const string _DaggerfallTilemapTextureArrayShaderName = "Daggerfall/TilemapTextureArray";
public const string _DaggerfallBillboardShaderName = "Daggerfall/Billboard";
public const string _DaggerfallBillboardBatchShaderName = "Daggerfall/BillboardBatch";
public const string _DaggerfallBillboardBatchNoShadowsShaderName = "Daggerfall/BillboardBatchNoShadows";
public const string _DaggerfallGhostShaderName = "Daggerfall/GhostShader";
public const string _DaggerfallPixelFontShaderName = "Daggerfall/PixelFont";
public const string _DaggerfallSDFFontShaderName = "Daggerfall/SDFFont";
public const string _DaggerfallRetroDepthShaderName = "Daggerfall/DepthProcessShader";
public const string _DaggerfallRetroPosterizationShaderName = "Daggerfall/RetroPosterization";
public const string _DaggerfallRetroPalettizationShaderName = "Daggerfall/RetroPalettization";
public const string _DaggerfallUIBlendShaderName = "Daggerfall/UIBlend";
public const string _DaggerfallUIBlitShaderName = "Daggerfall/UIBlit";
DaggerfallUnity dfUnity;
TextureReader textureReader;
Dictionary<int, CachedMaterial> materialDict = new Dictionary<int, CachedMaterial>();
//TextureAtlasBuilder miscBillboardsAtlas = null;
#endregion
#region Enums & Structs
/// <summary>
/// Standard shader blend modes.
/// Using a custom enum as Unity does not expose outside of editor GUI.
/// </summary>
public enum CustomBlendMode
{
Opaque = 0,
Cutout = 1,
Fade = 2,
Transparent = 3,
}
/// <summary>
/// Standard shader smoothness map channel setting.
/// Using a custom enum as Unity does not expose outside of editor GUI.
/// </summary>
public enum CustomSmoothnessMapChannel
{
SpecularMetallicAlpha = 0,
AlbedoAlpha = 1,
}
#endregion
#region Properties
/// <summary>
/// Gets true if file reading is ready.
/// </summary>
public bool IsReady
{
get { return ReadyCheck(); }
}
/// <summary>
/// Gets managed texture reader.
/// </summary>
public TextureReader TextureReader
{
get { return (IsReady) ? textureReader : null; }
}
///// <summary>
///// TEMP: Gets a special misc billboards super-atlas for scene builders.
///// </summary>
//public TextureAtlasBuilder MiscBillboardAtlas
//{
// get
// {
// // Create new atlas or return existing
// if (miscBillboardsAtlas == null)
// {
// if (!IsReady)
// return null;
// miscBillboardsAtlas = textureReader.CreateTextureAtlasBuilder(
// textureReader.MiscFlatsTextureArchives,
// 2,
// true,
// DaggerfallUnity.Settings.MeshAndTextureReplacement ? 4096 : 2048,
// AlphaTextureFormat,
// NonAlphaTextureFormat);
// return miscBillboardsAtlas;
// }
// else
// {
// return miscBillboardsAtlas;
// }
// }
//}
#endregion
#region Material Creation
/// <summary>
/// Creates a new default material for world geometry.
/// </summary>
/// <returns>Material using Daggerfall/Default shader.</returns>
public static Material CreateDefaultMaterial()
{
Shader shader = Shader.Find(_DaggerfallDefaultShaderName);
Material material = new Material(shader);
//material.EnableKeyword("_COLORBOOST");
return material;
}
/// <summary>
/// Creates a new transparent cutout billboard material for mobiles, misc. objects, etc.
/// </summary>
/// <returns>Material using Daggerfall/Billboard shader.</returns>
public static Material CreateBillboardMaterial()
{
Shader shader = Shader.Find(_DaggerfallBillboardShaderName);
Material material = new Material(shader);
return material;
}
/// <summary>
/// Creates new Standard material with default properties suitable for most Daggerfall textures.
/// </summary>
/// <returns>Material using Standard shader.</returns>
public static Material CreateStandardMaterial(
CustomBlendMode blendMode = CustomBlendMode.Opaque,
CustomSmoothnessMapChannel smoothnessChannel = CustomSmoothnessMapChannel.AlbedoAlpha,
float metallic = 0,
float glossiness = 0)
{
// Create material
Shader shader = Shader.Find(_StandardShaderName);
Material material = new Material(shader);
// Set blend mode
SetBlendMode(material, blendMode, smoothnessChannel, metallic, glossiness);
return material;
}
/// <summary>
/// Change the blend mode of a Standard material at runtime.
/// </summary>
public static void SetBlendMode(
Material material,
CustomBlendMode blendMode,
CustomSmoothnessMapChannel smoothnessChannel,
float metallic,
float glossiness)
{
// Set properties
material.SetFloat(Uniforms.Mode, (int)blendMode);
material.SetFloat(Uniforms.SmoothnessTextureChannel, (int)smoothnessChannel);
material.SetFloat(Uniforms.Metallic, metallic);
material.SetFloat(Uniforms.Glossiness, glossiness);
switch (blendMode)
{
case CustomBlendMode.Opaque:
material.SetOverrideTag("RenderType", "");
material.SetInt(Uniforms.SrcBlend, (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt(Uniforms.DstBlend, (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt(Uniforms.ZWrite, 1);
material.DisableKeyword(KeyWords.CutOut);
material.DisableKeyword(KeyWords.Fade);
material.DisableKeyword(KeyWords.Transparent);
material.renderQueue = -1;
break;
case CustomBlendMode.Cutout:
material.SetOverrideTag("RenderType", "TransparentCutout");
material.SetInt(Uniforms.SrcBlend, (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt(Uniforms.DstBlend, (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt(Uniforms.ZWrite, 1);
material.EnableKeyword(KeyWords.CutOut);
material.DisableKeyword(KeyWords.Fade);
material.DisableKeyword(KeyWords.Transparent);
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
break;
case CustomBlendMode.Fade:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt(Uniforms.SrcBlend, (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt(Uniforms.DstBlend, (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt(Uniforms.ZWrite, 0);
material.DisableKeyword(KeyWords.CutOut);
material.EnableKeyword(KeyWords.Fade);
material.DisableKeyword(KeyWords.Transparent);
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
break;
case CustomBlendMode.Transparent:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt(Uniforms.SrcBlend, (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt(Uniforms.DstBlend, (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt(Uniforms.ZWrite, 0);
material.DisableKeyword(KeyWords.CutOut);
material.DisableKeyword(KeyWords.Fade);
material.EnableKeyword(KeyWords.Transparent);
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
break;
}
}
#endregion
#region Material Loading
/// <summary>
/// Gets Unity Material from Daggerfall texture.
/// </summary>
/// <param name="archive">Archive index.</param>
/// <param name="record">Record index.</param>
/// <param name="frame">Frame index.</param>
/// <param name="alphaIndex">Index to receive transparent alpha.</param>
/// <returns>Material or null.</returns>
public Material GetMaterial(int archive, int record, int frame = 0, int alphaIndex = -1)
{
Rect rect;
return GetMaterial(archive, record, frame, alphaIndex, out rect, 0, false);
}
/// <summary>
/// Gets Unity Material from Daggerfall texture with more options.
/// </summary>
/// <param name="archive">Archive index.</param>
/// <param name="record">Record index.</param>
/// <param name="frame">Frame index.</param>
/// <param name="rectOut">Receives UV rect for texture inside border.</param>
/// <param name="borderSize">Number of pixels internal border around each texture.</param>
/// <param name="dilate">Blend texture into surrounding empty pixels.</param>
/// <param name="isBillboard">Set true when creating atlas material for simple billboards.</param>
/// <returns>Material or null.</returns>
public Material GetMaterial(
int archive,
int record,
int frame,
int alphaIndex,
out Rect rectOut,
int borderSize = 0,
bool dilate = false,
bool isBillboard = false)
{
// Ready check
if (!IsReady)
{
rectOut = new Rect();
return null;
}
// Try to retrieve from cache
int key = MakeTextureKey((short)archive, (byte)record, (byte)frame);
if (materialDict.ContainsKey(key))
{
CachedMaterial cm = GetMaterialFromCache(key);
rectOut = cm.singleRect;
return cm.material;
}
Material material;
GetTextureResults results;
// Try to import a material from mods, otherwise create a standard material
// and import textures from Daggerfall files and loose files.
if (!TextureReplacement.TextureExistsAmongLooseFiles(archive, record, frame) &&
TextureReplacement.TryImportMaterial(archive, record, frame, out material))
{
results = TextureReplacement.MakeResults(material, archive, record);
TextureReplacement.AssignFiltermode(material);
}
else
{
// Create new texture settings
GetTextureSettings settings = TextureReader.CreateTextureSettings(archive, record, frame, alphaIndex, borderSize, dilate);
settings.autoEmissionForWindows = true;
settings.sharpen = Sharpen;
if (GenerateNormals)
{
settings.createNormalMap = true;
settings.normalStrength = NormalTextureStrength;
}
// Set emissive for self-illuminated textures
if (textureReader.IsEmissive(archive, record))
{
settings.createEmissionMap = true;
settings.emissionIndex = -1;
}
// Get texture
results = textureReader.GetTexture2D(settings, AlphaTextureFormat, TextureImport.AllLocations);
// Create material
if (isBillboard)
material = CreateBillboardMaterial();
else
material = CreateDefaultMaterial();
// Setup material
material.name = FormatName(archive, record);
material.mainTexture = results.albedoMap;
material.mainTexture.filterMode = MainFilterMode;
// Setup normal map
bool importedNormals = TextureReplacement.TextureExistsAmongLooseFiles(settings.archive, settings.record, settings.frame, TextureMap.Normal);
if ((GenerateNormals || importedNormals) && results.normalMap != null)
{
results.normalMap.filterMode = MainFilterMode;
material.SetTexture(Uniforms.BumpMap, results.normalMap);
material.EnableKeyword(KeyWords.NormalMap);
}
// Setup emission map
if (results.isEmissive && !results.isWindow && results.emissionMap != null)
{
results.emissionMap.filterMode = MainFilterMode;
material.SetTexture(Uniforms.EmissionMap, results.emissionMap);
material.SetColor(Uniforms.EmissionColor, Color.white);
material.EnableKeyword(KeyWords.Emission);
}
else if (results.isEmissive && results.isWindow && results.emissionMap != null)
{
results.emissionMap.filterMode = MainFilterMode;
material.SetTexture(Uniforms.EmissionMap, results.emissionMap);
material.SetColor(Uniforms.EmissionColor, DayWindowColor * DayWindowIntensity);
material.EnableKeyword(KeyWords.Emission);
}
// Import additional custom components of material
TextureReplacement.CustomizeMaterial(archive, record, frame, material);
}
Vector2[] recordSizes;
Vector2[] recordScales;
Vector2[] recordOffsets;
int singleFrameCount;
// Setup cached material
if (results.textureFile != null)
{
DFSize size = results.textureFile.GetSize(record);
DFSize scale = results.textureFile.GetScale(record);
DFPosition offset = results.textureFile.GetOffset(record);
recordSizes = new Vector2[1] { new Vector2(size.Width, size.Height) };
recordScales = new Vector2[1] { new Vector2(scale.Width, scale.Height) };
recordOffsets = new Vector2[1] { new Vector2(offset.X, offset.Y) };
singleFrameCount = results.textureFile.GetFrameCount(record);
}
else
{
// If we have no texture file, this means this is a non-classic texture
// Just use the albedo texture directly
recordSizes = new Vector2[1] { new Vector2(results.albedoMap.width, results.albedoMap.height) };
recordScales = new Vector2[1] { new Vector2(1.0f, 1.0f) };
recordOffsets = new Vector2[1] { new Vector2(0.0f, 0.0f) };
singleFrameCount = 1;
}
CachedMaterial newcm = new CachedMaterial()
{
key = key,
keyGroup = 0,
albedoMap = results.albedoMap,
normalMap = results.normalMap,
emissionMap = results.emissionMap,
singleRect = rectOut = results.singleRect,
material = material,
filterMode = MainFilterMode,
isWindow = results.isWindow,
recordSizes = recordSizes,
recordScales = recordScales,
recordOffsets = recordOffsets,
singleFrameCount = singleFrameCount,
framesPerSecond = archive == FireWallsArchive ? 5 : 0, // Slow down fire walls
};
materialDict.Add(key, newcm);
return material;
}
/// <summary>
/// Gets Unity Material atlas from Daggerfall texture archive.
/// </summary>
/// <param name="archive">Archive index to create atlas from.</param>
/// <param name="alphaIndex">Index to receive transparent alpha.</param>
/// <param name="padding">Number of pixels each sub-texture.</param>
/// <param name="maxAtlasSize">Max size of atlas.</param>
/// <param name="rectsOut">Array of rects, one for each record sub-texture and frame.</param>
/// <param name="indicesOut">Array of record indices into rect array, accounting for animation frames.</param>
/// <param name="border">Number of pixels internal border around each texture.</param>
/// <param name="dilate">Blend texture into surrounding empty pixels.</param>
/// <param name="shrinkUVs">Number of pixels to shrink UV rect.</param>
/// <param name="copyToOppositeBorder">Copy texture edges to opposite border. Requires border, will overwrite dilate.</param>
/// <param name="isBillboard">Set true when creating atlas material for simple billboards.</param>
/// <returns>Material or null.</returns>
public Material GetMaterialAtlas(
int archive,
int alphaIndex,
int padding,
int maxAtlasSize,
out Rect[] rectsOut,
out RecordIndex[] indicesOut,
int border = 0,
bool dilate = false,
int shrinkUVs = 0,
bool copyToOppositeBorder = false,
bool isBillboard = false)
{
// Ready check
if (!IsReady)
{
rectsOut = null;
indicesOut = null;
return null;
}
int key = MakeTextureKey((short)archive, (byte)0, (byte)0, AtlasKeyGroup);
if (materialDict.ContainsKey(key))
{
CachedMaterial cm = GetMaterialFromCache(key);
if (cm.filterMode == MainFilterMode)
{
// Properties are the same
rectsOut = cm.atlasRects;
indicesOut = cm.atlasIndices;
return cm.material;
}
else
{
// Properties don't match, remove material and reload
materialDict.Remove(key);
}
}
// Create material
Material material;
if (isBillboard)
material = CreateBillboardMaterial();
else
material = CreateDefaultMaterial();
// Create settings
GetTextureSettings settings = TextureReader.CreateTextureSettings(archive, 0, 0, alphaIndex, border, dilate);
settings.createNormalMap = GenerateNormals;
settings.autoEmission = true;
settings.atlasShrinkUVs = shrinkUVs;
settings.atlasPadding = padding;
settings.atlasMaxSize = maxAtlasSize;
settings.copyToOppositeBorder = copyToOppositeBorder;
// Setup material
material.name = string.Format("TEXTURE.{0:000} [Atlas]", archive);
GetTextureResults results = textureReader.GetTexture2DAtlas(settings, AlphaTextureFormat);
material.mainTexture = results.albedoMap;
material.mainTexture.filterMode = MainFilterMode;
// Setup normal map
if (GenerateNormals && results.normalMap != null)
{
results.normalMap.filterMode = MainFilterMode;
material.SetTexture(Uniforms.BumpMap, results.normalMap);
material.EnableKeyword(KeyWords.NormalMap);
}
// Setup emission map
if (results.isEmissive && results.emissionMap != null)
{
results.emissionMap.filterMode = MainFilterMode;
material.SetTexture(Uniforms.EmissionMap, results.emissionMap);
material.SetColor(Uniforms.EmissionColor, Color.white);
material.EnableKeyword(KeyWords.Emission);
}
// TEMP: Bridging between legacy material out params and GetTextureResults for now
Vector2[] sizesOut, scalesOut, offsetsOut;
sizesOut = results.atlasSizes.ToArray();
scalesOut = results.atlasScales.ToArray();
offsetsOut = results.atlasOffsets.ToArray();
rectsOut = results.atlasRects.ToArray();
indicesOut = results.atlasIndices.ToArray();
// Setup cached material
CachedMaterial newcm = new CachedMaterial();
newcm.key = key;
newcm.keyGroup = AtlasKeyGroup;
newcm.atlasRects = rectsOut;
newcm.atlasIndices = indicesOut;
newcm.material = material;
newcm.filterMode = MainFilterMode;
newcm.recordSizes = sizesOut;
newcm.recordScales = scalesOut;
newcm.recordOffsets = offsetsOut;
newcm.atlasFrameCounts = results.atlasFrameCounts.ToArray();
materialDict.Add(key, newcm);
return material;
}
/// <summary>
/// Gets Unity Material from Daggerfall terrain tilemap texture.
/// </summary>
/// <param name="archive">Archive index.</param>
/// <returns>Material or null.</returns>
public Material GetTerrainTilesetMaterial(int archive)
{
// Ready check
if (!IsReady)
return null;
// Return from cache if present
int key = MakeTextureKey((short)archive, (byte)0, (byte)0, TileMapKeyGroup);
if (materialDict.ContainsKey(key))
{
CachedMaterial cm = GetMaterialFromCache(key);
if (cm.filterMode == MainFilterMode)
{
// Properties are the same
return cm.material;
}
else
{
// Properties don't match, remove material and reload
materialDict.Remove(key);
}
}
//// TODO: Attempt to load prebuilt atlas asset, otherwise create one in memory
//Texture2D texture = TerrainAtlasBuilder.LoadTerrainAtlasTextureResource(archive, CreateTextureAssetResourcesPath);
//if (texture == null)
// Generate atlas
// Not currently generating normals as very slow on such a large texture
// and results are not very noticeable
GetTextureResults results = textureReader.GetTerrainTilesetTexture(archive);
results.albedoMap.filterMode = MainFilterMode;
Shader shader = Shader.Find(_DaggerfallTilemapShaderName);
Material material = new Material(shader);
material.name = string.Format("TEXTURE.{0:000} [Tilemap]", archive);
material.SetTexture("_TileAtlasTex", results.albedoMap);
CachedMaterial newcm = new CachedMaterial()
{
key = key,
keyGroup = TileMapKeyGroup,
material = material,
filterMode = MainFilterMode,
};
materialDict.Add(key, newcm);
return material;
}
/// <summary>
/// Gets Unity Material from Daggerfall terrain using texture arrays.
/// </summary>
/// <param name="archive">Archive index.</param>
/// <returns>Material or null.</returns>
public Material GetTerrainTextureArrayMaterial(int archive)
{
// Ready check
if (!IsReady)
return null;
// Return from cache if present
int key = MakeTextureKey((short)archive, (byte)0, (byte)0, TileMapKeyGroup);
if (materialDict.ContainsKey(key))
{
CachedMaterial cm = GetMaterialFromCache(key);
if (cm.filterMode == MainFilterMode)
{
// Properties are the same
return cm.material;
}
else
{
// Properties don't match, remove material and reload
materialDict.Remove(key);
}
}
// Generate texture array
Texture2DArray textureArrayTerrainTiles = textureReader.GetTerrainTextureArray(archive, TextureMap.Albedo);
Texture2DArray textureArrayTerrainTilesNormalMap = textureReader.GetTerrainTextureArray(archive, TextureMap.Normal);
Texture2DArray textureArrayTerrainTilesParallaxMap = textureReader.GetTerrainTextureArray(archive, TextureMap.Height);
Texture2DArray textureArrayTerrainTilesMetallicGloss = textureReader.GetTerrainTextureArray(archive, TextureMap.MetallicGloss);
textureArrayTerrainTiles.filterMode = MainFilterMode;
Shader shader = Shader.Find(_DaggerfallTilemapTextureArrayShaderName);
Material material = new Material(shader);
material.name = string.Format("TEXTURE.{0:000} [TilemapTextureArray]", archive);
material.SetTexture(TileTexArrUniforms.TileTexArr, textureArrayTerrainTiles);
if (textureArrayTerrainTilesNormalMap != null)
{
// If normal map texture array was loaded successfully enable _NORMALMAP in shader and set texture
material.SetTexture(TileTexArrUniforms.TileNormalMapTexArr, textureArrayTerrainTilesNormalMap);
material.EnableKeyword(KeyWords.NormalMap);
//textureArrayTerrainTilesNormalMap.filterMode = MainFilterMode;
}
if (textureArrayTerrainTilesParallaxMap != null)
{
// If parallax map texture array was loaded successfully enable _PARALLAXMAP in shader and set texture
material.SetTexture(TileTexArrUniforms.TileParallaxMapTexArr, textureArrayTerrainTilesParallaxMap);
material.EnableKeyword(KeyWords.HeightMap);
//textureArrayTerrainTilesParallaxMap.filterMode = MainFilterMode;
}
if (textureArrayTerrainTilesMetallicGloss != null)
{
// If metallic gloss map texture array was loaded successfully enable _METALLICGLOSSMAP in shader and set texture
material.SetTexture(TileTexArrUniforms.TileMetallicGlossMapTexArr, textureArrayTerrainTilesMetallicGloss);
material.EnableKeyword(KeyWords.MetallicGlossMap);
material.SetFloat(Uniforms.Smoothness, 0.35f);
//textureArrayTerrainTilesMetallicGloss.filterMode = MainFilterMode;
}
CachedMaterial newcm = new CachedMaterial()
{
key = key,
keyGroup = TileMapKeyGroup,
material = material,
filterMode = MainFilterMode,
};
materialDict.Add(key, newcm);
return material;
}
#endregion
#region Support
/// <summary>
/// Gets CachedMaterial properties.
/// Material will be loaded into cache if not present already.
/// </summary>
/// <param name="archive">Archive index.</param>
/// <param name="record">Record index.</param>
/// <param name="frame">Frame index.</param>
/// <param name="cachedMaterialOut">CachedMaterial out.</param>
/// <param name="alphaIndex">Alpha index used if material needs to be loaded.</param>
/// <returns>True if CachedMaterial found or loaded successfully.</returns>
public bool GetCachedMaterial(int archive, int record, int frame, out CachedMaterial cachedMaterialOut, int alphaIndex = -1)
{
int key = MakeTextureKey((short)archive, (byte)record, (byte)frame);
if (materialDict.ContainsKey(key))
{
cachedMaterialOut = GetMaterialFromCache(key);
return true;
}
else
{
// Not in cache - try to load material
if (GetMaterial(archive, record, frame, alphaIndex) == null)
{
cachedMaterialOut = new CachedMaterial();
return false;
}
}
cachedMaterialOut = materialDict[key];
return true;
}
/// <summary>
/// Sets CachedMaterial properties.
/// existing Material will be updated in cache with cachedMaterialIn.
/// </summary>
/// <param name="archive">Archive index.</param>
/// <param name="record">Record index.</param>
/// <param name="frame">Frame index.</param>
/// <param name="cachedMaterialIn">the CachedMaterial used to update the cache.</param>
/// <returns>True if CachedMaterial was found and updated successfully.</returns>
public bool SetCachedMaterial(int archive, int record, int frame, CachedMaterial cachedMaterialIn)
{
int key = MakeTextureKey((short)archive, (byte)record, (byte)frame);
if (materialDict.ContainsKey(key))
{
materialDict[key] = cachedMaterialIn;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Gets CachedMaterial properties for an atlased material.
/// Atlas material will not be loaded automatically if not found in cache.
/// </summary>
/// <param name="archive">Atlas archive index.</param>
/// <param name="cachedMaterialOut">CachedMaterial out</param>
/// <returns>True if CachedMaterial found.</returns>
public bool GetCachedMaterialAtlas(int archive, out CachedMaterial cachedMaterialOut)
{
int key = MakeTextureKey((short)archive, (byte)0, (byte)0, AtlasKeyGroup);
if (materialDict.ContainsKey(key))
{
cachedMaterialOut = GetMaterialFromCache(key);
return true;
}
cachedMaterialOut = new CachedMaterial();
return false;
}
/// <summary>
/// Gets CachedMaterial properties for a billboard with custom material.
/// </summary>
/// <param name="archive">Archive index.</param>
/// <param name="record">Record index.</param>
/// <param name="cachedMaterialOut">CachedMaterial out</param>
/// <returns>True if CachedMaterial found.</returns>
public bool GetCachedMaterialCustomBillboard(int archive, int record, int frame, out CachedMaterial cachedMaterialOut)
{
int key = MakeTextureKey((short)archive, (byte)record, (byte)frame, CustomBillboardKeyGroup);
if (materialDict.ContainsKey(key))
{
cachedMaterialOut = GetMaterialFromCache(key);
return true;
}
cachedMaterialOut = new CachedMaterial();
return false;
}
/// <summary>
/// Sets CachedMaterial properties for a billboard with custom material.
/// </summary>
/// <param name="archive">Archive index.</param>
/// <param name="record">Record index.</param>
public void SetCachedMaterialCustomBillboard(int archive, int record, int frame, CachedMaterial cachedMaterialIn)
{
int key = MakeTextureKey((short)archive, (byte)record, (byte)frame, CustomBillboardKeyGroup);
cachedMaterialIn.key = key;
cachedMaterialIn.keyGroup = CustomBillboardKeyGroup;
materialDict.Add(key, cachedMaterialIn);
}
/// <summary>
/// Get a new Material based on climate.
/// </summary>
/// <param name="key">Material key.</param>
/// <param name="climate">New climate base.</param>
/// <param name="season">New season.</param>
/// <param name="windowStyle">New window style.</param>
/// <returns>New material.</returns>
public Material ChangeClimate(int key, ClimateBases climate, ClimateSeason season, WindowStyle windowStyle)
{
// Ready check
if (!IsReady)
return null;
// Reverse key and apply climate
int archive, record, frame;
ReverseTextureKey(key, out archive, out record, out frame);
archive = ClimateSwaps.ApplyClimate(archive, record, climate, season);
// Get new material
Material material;
CachedMaterial cm = GetMaterialFromCache(archive, record, out material);
// Handle windows
if (cm.isWindow)
{
ChangeWindowEmissionColor(material, windowStyle);
}
return material;
}
/// <summary>
/// Change emission colour of window materials.
/// </summary>
/// <param name="material">Source material to change.</param>
/// <param name="windowStyle">New window style.</param>
public void ChangeWindowEmissionColor(Material material, WindowStyle windowStyle)
{
switch (windowStyle)
{
case WindowStyle.Day:
material.SetColor(Uniforms.EmissionColor, DayWindowColor * DayWindowIntensity);
break;
case WindowStyle.Night:
material.SetColor(Uniforms.EmissionColor, NightWindowColor * NightWindowIntensity);
break;
case WindowStyle.Fog:
material.SetColor(Uniforms.EmissionColor, FogWindowColor * FogWindowIntensity);
break;
case WindowStyle.Custom:
material.SetColor(Uniforms.EmissionColor, CustomWindowColor * CustomWindowIntensity);
break;
case WindowStyle.Disabled:
material.SetColor(Uniforms.EmissionColor, Color.black);
break;
}
}
/// <summary>
/// Removes from cache all materials that have not been accessed from the time in minutes defined
/// by <paramref name="threshold"/>.
/// </summary>
internal void PruneCache(float time, float threshold)
{
foreach (var item in materialDict.Where(x => time - x.Value.timeStamp > threshold).ToList())
materialDict.Remove(item.Key);
}
/// <summary>
/// Clears material cache dictionary, forcing material to reload.
/// </summary>
public void ClearCache()
{
materialDict.Clear();
}
#endregion
#region Static Methods
public static int MakeTextureKey(short archive, byte record, byte frame = 0, int group = 0)
{
return ((archive + group) << 16) + (record << 8) + frame;
}
public static void ReverseTextureKey(int key, out int archiveOut, out int recordOut, out int frameOut, int group = 0)
{
archiveOut = (key >> 16) - group;
recordOut = (key >> 8) & 0xff;
frameOut = key & 0xff;
}
public static FlatTypes GetFlatType(int archive)
{
// Single-archive types
switch (archive)
{
case 210:
return FlatTypes.Light;
case 199:
return FlatTypes.Editor;
case 201:
return FlatTypes.Animal;
}
// Nature set type
if (archive >= 500 && archive <= 511)
return FlatTypes.Nature;
// Everything else is just decoration for now
return FlatTypes.Decoration;
}
public static EditorFlatTypes GetEditorFlatType(int record)
{
switch (record)
{
case 8:
return EditorFlatTypes.Enter;
case 10: