summaryrefslogtreecommitdiff
path: root/VRCSDK3Worlds/Assets/MeshBaker/scripts/MB2_TextureBakeResults.cs
blob: 5a39562d06c0eaa033f0567d77e0735508286409 (plain)
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
using UnityEngine;
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using DigitalOpus.MB.Core;
using UnityEngine.Serialization;


/// <summary>
/// Used internally during the material baking process
/// </summary>
[Serializable]
public class MB_AtlasesAndRects{
    /// <summary>
    /// One atlas per texture property.
    /// </summary>
	public Texture2D[] atlases;
    [NonSerialized]
	public List<MB_MaterialAndUVRect> mat2rect_map;
	public string[] texPropertyNames;
}

public class MB_TextureArrayResultMaterial
{
    public MB_AtlasesAndRects[] slices;
}

[System.Serializable]
public class MB_MultiMaterial{
	public Material combinedMaterial;
    public bool considerMeshUVs;
	public List<Material> sourceMaterials = new List<Material>();
}

[System.Serializable]
public class MB_TexArraySliceRendererMatPair
{
    public Material sourceMaterial;
    public GameObject renderer;
}

[System.Serializable]
public class MB_TexArraySlice
{
    public bool considerMeshUVs;
    public List<MB_TexArraySliceRendererMatPair> sourceMaterials = new List<MB_TexArraySliceRendererMatPair>();
    public bool ContainsMaterial(Material mat)
    {
        for (int i = 0; i < sourceMaterials.Count; i++)
        {
            if (sourceMaterials[i].sourceMaterial == mat) return true;
        }

        return false;
    }

    public HashSet<Material> GetDistinctMaterials()
    {
        HashSet<Material> distinctMats = new HashSet<Material>();
        if (sourceMaterials == null) return distinctMats;
        for (int i = 0; i < sourceMaterials.Count; i++)
        {
            distinctMats.Add(sourceMaterials[i].sourceMaterial);
        }

        return distinctMats;
    }

    public bool ContainsMaterialAndMesh(Material mat, Mesh mesh)
    {
        for (int i = 0; i < sourceMaterials.Count; i++)
        {
            if (sourceMaterials[i].sourceMaterial == mat &&
                MB_Utility.GetMesh(sourceMaterials[i].renderer) == mesh) return true;
        }

        return false;
    }

    public List<Material> GetAllUsedMaterials(List<Material> usedMats)
    {
        usedMats.Clear();
        for (int i = 0; i < sourceMaterials.Count; i++)
        {
            usedMats.Add(sourceMaterials[i].sourceMaterial);
        }
        return usedMats;
    }

    public List<GameObject> GetAllUsedRenderers(List<GameObject> allObjsFromTextureBaker)
    {
        if (considerMeshUVs)
        {
            List<GameObject> usedRendererGOs = new List<GameObject>();
            for (int i = 0; i < sourceMaterials.Count; i++)
            {
                usedRendererGOs.Add(sourceMaterials[i].renderer);
            }

            return usedRendererGOs;
        }
        else
        {
            return allObjsFromTextureBaker;
        }
    }
}

[System.Serializable]
public class MB_TextureArrayReference
{
    public string texFromatSetName;
    public Texture2DArray texArray;

    public MB_TextureArrayReference(string formatSetName, Texture2DArray ta)
    {
        texFromatSetName = formatSetName;
        texArray = ta;
    }
}

[System.Serializable]
public class MB_TexArrayForProperty
{
    public string texPropertyName;
    public MB_TextureArrayReference[] formats = new MB_TextureArrayReference[0];

    public MB_TexArrayForProperty(string name, MB_TextureArrayReference[] texRefs)
    {
        texPropertyName = name;
        formats = texRefs;
    }
}

[System.Serializable]
public class MB_MultiMaterialTexArray
{
    public Material combinedMaterial;
    public List<MB_TexArraySlice> slices = new List<MB_TexArraySlice>();
    public List<MB_TexArrayForProperty> textureProperties = new List<MB_TexArrayForProperty>();
}

[System.Serializable]
public class MB_TextureArrayFormat
{
    public string propertyName;
    public TextureFormat format;
}

[System.Serializable]
public class MB_TextureArrayFormatSet
{
    public string name;
    public TextureFormat defaultFormat;
    public MB_TextureArrayFormat[] formatOverrides;

    public bool ValidateTextureImporterFormatsExistsForTextureFormats(MB2_EditorMethodsInterface editorMethods, int idx)
    {
        if (editorMethods == null) return true;
        if (!editorMethods.TextureImporterFormatExistsForTextureFormat(defaultFormat))
        {
            Debug.LogError("TextureImporter format does not exist for Texture Array Output Formats: " + idx + " Defaut Format " + defaultFormat);
            return false;
        }

        for (int i = 0; i < formatOverrides.Length; i++)
        {
            if (!editorMethods.TextureImporterFormatExistsForTextureFormat(formatOverrides[i].format))
            {
                Debug.LogError("TextureImporter format does not exist for Texture Array Output Formats: " + idx + " Format Overrides: " + i + " (" + formatOverrides[i].format + ")");
                return false;
            }
        }
        return true;
    }

    public TextureFormat GetFormatForProperty(string propName)
    {
        for (int i = 0; i < formatOverrides.Length; i++)
        {
            if (formatOverrides.Equals(formatOverrides[i].propertyName))
            {
                return formatOverrides[i].format;
            }
        }

        return defaultFormat;
    }
}

[System.Serializable]
public class MB_MaterialAndUVRect
{
    /// <summary>
    /// The source material that was baked into the atlas.
    /// </summary>
    public Material material;
    
    /// <summary>
    /// The rectangle in the atlas where the texture (including all tiling) was copied to.
    /// </summary>
    public Rect atlasRect;

    /// <summary>
    /// For debugging. The name of the first srcObj that uses this MaterialAndUVRect.
    /// </summary>
    public string srcObjName;

    public int textureArraySliceIdx = -1;

    public bool allPropsUseSameTiling = true;

    /// <summary>
    /// Only valid if allPropsUseSameTiling = true. Else should be 0,0,0,0
    /// The material tiling on the source material
    /// </summary>
    [FormerlySerializedAs("sourceMaterialTiling")]
    public Rect allPropsUseSameTiling_sourceMaterialTiling;

    /// <summary>
    /// Only valid if allPropsUseSameTiling = true. Else should be 0,0,0,0
    /// The encapsulating sampling rect that was used to sample for the atlas. Note that the case
    /// of dont-considerMeshUVs is the same as do-considerMeshUVs where the uv rect is 0,0,1,1 
    /// </summary>
    [FormerlySerializedAs("samplingEncapsulatinRect")]
    public Rect allPropsUseSameTiling_samplingEncapsulatinRect;

    /// <summary>
    /// Only valid if allPropsUseSameTiling = false.
    /// The UVrect of the source mesh that was baked. We are using a trick here.
    /// Instead of storing the material tiling for each
    /// texture property here, we instead bake all those tilings into the atlases and here we pretend
    /// that all those tilings were 0,0,1,1. Then all we need is to store is the 
    /// srcUVsamplingRect
    /// </summary>
    public Rect propsUseDifferntTiling_srcUVsamplingRect;

    [NonSerialized]
    public List<GameObject> objectsThatUse;

    /// <summary>
    /// The tilling type for this rectangle in the atlas.
    /// </summary>
    public MB_TextureTilingTreatment tilingTreatment = MB_TextureTilingTreatment.unknown;

    /// <param name="mat">The Material</param>
    /// <param name="destRect">The rect in the atlas this material maps to</param>
    /// <param name="allPropsUseSameTiling">If true then use sourceMaterialTiling and samplingEncapsulatingRect.
    /// if false then use srcUVsamplingRect. None used values should be 0,0,0,0.</param>
    /// <param name="sourceMaterialTiling">allPropsUseSameTiling_sourceMaterialTiling</param>
    /// <param name="samplingEncapsulatingRect">allPropsUseSameTiling_samplingEncapsulatinRect</param>
    /// <param name="srcUVsamplingRect">propsUseDifferntTiling_srcUVsamplingRect</param>
    public MB_MaterialAndUVRect(Material mat, 
        Rect destRect, 
        bool allPropsUseSameTiling,
        Rect sourceMaterialTiling, 
        Rect samplingEncapsulatingRect,
        Rect srcUVsamplingRect,
        MB_TextureTilingTreatment treatment, 
        string objName)
    {
        if (allPropsUseSameTiling)
        {
            Debug.Assert(srcUVsamplingRect == new Rect(0, 0, 0, 0));
        }

        if (!allPropsUseSameTiling) {
            Debug.Assert(samplingEncapsulatingRect == new Rect(0, 0, 0, 0));
            Debug.Assert(sourceMaterialTiling == new Rect(0, 0, 0, 0));
        }

        material = mat;
        atlasRect = destRect;
        tilingTreatment = treatment;
        this.allPropsUseSameTiling = allPropsUseSameTiling;
        allPropsUseSameTiling_sourceMaterialTiling = sourceMaterialTiling;
        allPropsUseSameTiling_samplingEncapsulatinRect = samplingEncapsulatingRect;
        propsUseDifferntTiling_srcUVsamplingRect = srcUVsamplingRect;
        srcObjName = objName;
    }

    public override int GetHashCode()
    {
        return material.GetInstanceID() ^ allPropsUseSameTiling_samplingEncapsulatinRect.GetHashCode() ^ propsUseDifferntTiling_srcUVsamplingRect.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        if (!(obj is MB_MaterialAndUVRect)) return false;
        MB_MaterialAndUVRect b = (MB_MaterialAndUVRect)obj;
        return material == b.material && 
            allPropsUseSameTiling_samplingEncapsulatinRect == b.allPropsUseSameTiling_samplingEncapsulatinRect &&
            allPropsUseSameTiling_sourceMaterialTiling == b.allPropsUseSameTiling_sourceMaterialTiling &&
            allPropsUseSameTiling == b.allPropsUseSameTiling &&
            propsUseDifferntTiling_srcUVsamplingRect == b.propsUseDifferntTiling_srcUVsamplingRect;
    }

    public Rect GetEncapsulatingRect()
    {
        if (allPropsUseSameTiling)
        {
            return allPropsUseSameTiling_samplingEncapsulatinRect;
        }
        else
        {
            return propsUseDifferntTiling_srcUVsamplingRect;
        }
    }

    public Rect GetMaterialTilingRect()
    {
        if (allPropsUseSameTiling)
        {
            return allPropsUseSameTiling_sourceMaterialTiling;
        }
        else
        {
            return new Rect(0, 0, 1, 1);
        }
    }
}

/// <summary>
/// This class stores the results from an MB2_TextureBaker when materials are combined into atlases. It stores
/// a list of materials and the corresponding UV rectangles in the atlases. It also stores the configuration
/// options that were used to generate the combined material.
/// 
/// It can be saved as an asset in the project so that textures can be baked in one scene and used in another.
/// </summary>
public class MB2_TextureBakeResults : ScriptableObject {

    public enum ResultType
    {
        atlas,
        textureArray,
    }

    public static int VERSION { get { return 3252; } }

    public int version;

    public ResultType resultType = ResultType.atlas;

    /// <summary>
    /// Information about the atlas UV rects.
    /// IMPORTANT a source material can appear more than once in this list. If we are using considerUVs,
    /// then different parts of a source texture could be extracted to different atlas rects.
    /// </summary>
    public MB_MaterialAndUVRect[] materialsAndUVRects;

    /// <summary>
    /// This is like the combinedMeshRenderer.sharedMaterials. Some materials may be omitted if they have zero submesh triangles.
    /// There is one of these per MultiMaterial mapping.
    /// Lists source materials that were combined into each result material, and whether considerUVs was used.
    /// This is the result materials if building for atlases.
    /// </summary>
    public MB_MultiMaterial[] resultMaterials;


    /// <summary>
    /// This is like combinedMeshRenderer.sharedMaterials. Each result mat likely uses a different shader.
    /// There is one of these per MultiMaterialTexArray mapping.
    /// Each of these lists the slices and each slice has list of source mats that are in that slice.
    /// This is the result materials if building for texArrays.
    /// </summary>
    public MB_MultiMaterialTexArray[] resultMaterialsTexArray;

    public bool doMultiMaterial;

    public MB2_TextureBakeResults()
    {
        version = VERSION;
    }

    private void OnEnable()
    {
        // backward compatibility copy depricated fixOutOfBounds values to resultMaterials
        if (version < 3251)
        {
            for (int i = 0; i < materialsAndUVRects.Length; i++)
            {
                materialsAndUVRects[i].allPropsUseSameTiling = true;
            }
        }

        version = VERSION;
    }

    public int NumResultMaterials()
    {
        if (resultType == ResultType.atlas) return resultMaterials.Length;
        else return resultMaterialsTexArray.Length;
    }

    public Material GetCombinedMaterialForSubmesh(int idx)
    {
        if (resultType == ResultType.atlas)
        {
            return resultMaterials[idx].combinedMaterial;
        } else
        {
            return resultMaterialsTexArray[idx].combinedMaterial;
        }
    }

    public bool GetConsiderMeshUVs(int idxInSrcMats, Material srcMaterial)
    {
        if (resultType == ResultType.atlas)
        {
            return resultMaterials[idxInSrcMats].considerMeshUVs;
        }
        else
        {
            // TODO do this once and cache.
            List<MB_TexArraySlice> slices = resultMaterialsTexArray[idxInSrcMats].slices;
            for (int i = 0; i < slices.Count; i++)
            {
                if (slices[i].ContainsMaterial(srcMaterial)) return slices[i].considerMeshUVs;
            }

            Debug.LogError("There were no source materials for any slice in this result material.");
            return false;
        }
    }

    public List<Material> GetSourceMaterialsUsedByResultMaterial(int resultMatIdx)
    {
        if (resultType == ResultType.atlas)
        {
            return resultMaterials[resultMatIdx].sourceMaterials;
        } else
        {
            // TODO do this once and cache.
            HashSet<Material> output = new HashSet<Material>();
            List<MB_TexArraySlice> slices = resultMaterialsTexArray[resultMatIdx].slices;
            for (int i = 0; i < slices.Count; i++)
            {
                List<Material> usedMaterials = new List<Material>();
                slices[i].GetAllUsedMaterials(usedMaterials);
                for (int j = 0; j < usedMaterials.Count; j++)
                {
                    output.Add(usedMaterials[j]);
                }
                
            }

            List<Material> outMats = new List<Material>(output);
            return outMats;
        }
    }

    /// <summary>
    /// Creates for materials on renderer.
    /// </summary>
    /// <returns>Generates an MB2_TextureBakeResult that can be used if all objects to be combined use the same material.
    /// Returns a MB2_TextureBakeResults that will map all materials used by renderer r to
    /// the rectangle 0,0..1,1 in the atlas.</returns>
    public static MB2_TextureBakeResults CreateForMaterialsOnRenderer(GameObject[] gos, List<Material> matsOnTargetRenderer)
    {
        HashSet<Material> fullMaterialList = new HashSet<Material>(matsOnTargetRenderer);
        for (int i = 0; i < gos.Length; i++)
        {
            if (gos[i] == null)
            {
                Debug.LogError(string.Format("Game object {0} in list of objects to add was null", i));
                return null;
            }
            Material[] oMats = MB_Utility.GetGOMaterials(gos[i]);
            if (oMats.Length == 0)
            {
                Debug.LogError(string.Format("Game object {0} in list of objects to add no renderer", i));
                return null;
            }
            for (int j = 0; j < oMats.Length; j++)
            {
                if (!fullMaterialList.Contains(oMats[j])) { fullMaterialList.Add(oMats[j]); }
            }
        }

        Material[] rms = new Material[fullMaterialList.Count];
        fullMaterialList.CopyTo(rms);
        MB2_TextureBakeResults tbr = (MB2_TextureBakeResults) ScriptableObject.CreateInstance( typeof(MB2_TextureBakeResults) );
        List<MB_MaterialAndUVRect> mss = new List<MB_MaterialAndUVRect>();
        for (int i = 0; i < rms.Length; i++)
        {
            if (rms[i] != null)
            {
                MB_MaterialAndUVRect matAndUVRect = new MB_MaterialAndUVRect(rms[i], new Rect(0f, 0f, 1f, 1f), true, new Rect(0f,0f,1f,1f), new Rect(0f,0f,1f,1f), new Rect(0,0,0,0), MB_TextureTilingTreatment.none, "");
                if (!mss.Contains(matAndUVRect))
                {
                    mss.Add(matAndUVRect);
                }
            }
        }

        tbr.resultMaterials = new MB_MultiMaterial[mss.Count];
        for (int i = 0; i < mss.Count; i++){
			tbr.resultMaterials[i] = new MB_MultiMaterial();
			List<Material> sourceMats = new List<Material>();
			sourceMats.Add (mss[i].material);
			tbr.resultMaterials[i].sourceMaterials = sourceMats;
			tbr.resultMaterials[i].combinedMaterial = mss[i].material;
            tbr.resultMaterials[i].considerMeshUVs = false;
		}
        if (rms.Length == 1)
        {
            tbr.doMultiMaterial = false;
        } else
        {
            tbr.doMultiMaterial = true;
        }

        tbr.materialsAndUVRects = mss.ToArray();
        return tbr;
	}
	
    public bool DoAnyResultMatsUseConsiderMeshUVs()
    {
        if (resultType == ResultType.atlas)
        {
            if (resultMaterials == null) return false;
            for (int i = 0; i < resultMaterials.Length; i++)
            {
                if (resultMaterials[i].considerMeshUVs) return true;
            }

            return false;
        }
        else
        {
            if (resultMaterialsTexArray == null) return false;
            for (int i = 0; i < resultMaterialsTexArray.Length; i++)
            {
                MB_MultiMaterialTexArray resMat = resultMaterialsTexArray[i];
                for (int j = 0; j < resMat.slices.Count; j++)
                {
                    if (resMat.slices[j].considerMeshUVs) return true;
                }
            }
            return false;
        }
    }

    public bool ContainsMaterial(Material m)
    {
        for (int i = 0; i < materialsAndUVRects.Length; i++)
        {
            if (materialsAndUVRects[i].material == m){
                return true;
            }
        }
        return false;
    }


	public string GetDescription(){
		StringBuilder sb = new StringBuilder();
		sb.Append("Shaders:\n");
		HashSet<Shader> shaders = new HashSet<Shader>();
		if (materialsAndUVRects != null){
			for (int i = 0; i < materialsAndUVRects.Length; i++){
                if (materialsAndUVRects[i].material != null)
                {
                    shaders.Add(materialsAndUVRects[i].material.shader);
                }	
			}
		}
		
		foreach(Shader m in shaders){
			sb.Append("  ").Append(m.name).AppendLine();
		}
		sb.Append("Materials:\n");
		if (materialsAndUVRects != null){
			for (int i = 0; i < materialsAndUVRects.Length; i++){
                if (materialsAndUVRects[i].material != null)
                {
                    sb.Append("  ").Append(materialsAndUVRects[i].material.name).AppendLine();
                }
			}
		}
		return sb.ToString();
	}

    public void UpgradeToCurrentVersion(MB2_TextureBakeResults tbr)
    {
        if (tbr.version < 3252)
        {
            for (int i = 0; i < tbr.materialsAndUVRects.Length; i++)
            {
                tbr.materialsAndUVRects[i].allPropsUseSameTiling = true;
            }
        }
    }

    public static bool IsMeshAndMaterialRectEnclosedByAtlasRect(MB_TextureTilingTreatment tilingTreatment, Rect uvR, Rect sourceMaterialTiling, Rect samplingEncapsulatinRect, MB2_LogLevel logLevel)
    {
        Rect potentialRect = new Rect();
        // test to see if this would fit in what was baked in the atlas

        potentialRect = MB3_UVTransformUtility.CombineTransforms(ref uvR, ref sourceMaterialTiling);
        if (logLevel >= MB2_LogLevel.trace)
        {
            if (logLevel >= MB2_LogLevel.trace) Debug.Log("IsMeshAndMaterialRectEnclosedByAtlasRect Rect in atlas uvR=" + uvR.ToString("f5") + " sourceMaterialTiling=" + sourceMaterialTiling.ToString("f5") + "Potential Rect (must fit in encapsulating) " + potentialRect.ToString("f5") + " encapsulating=" + samplingEncapsulatinRect.ToString("f5") + " tilingTreatment=" + tilingTreatment);
        }

        if (tilingTreatment == MB_TextureTilingTreatment.edgeToEdgeX)
        {
            if (MB3_UVTransformUtility.LineSegmentContainsShifted(samplingEncapsulatinRect.y, samplingEncapsulatinRect.height, potentialRect.y, potentialRect.height))
            {
                return true;
            }
        }
        else if (tilingTreatment == MB_TextureTilingTreatment.edgeToEdgeY)
        {
            if (MB3_UVTransformUtility.LineSegmentContainsShifted(samplingEncapsulatinRect.x, samplingEncapsulatinRect.width, potentialRect.x, potentialRect.width))
            {
                return true;
            }
        }
        else if (tilingTreatment == MB_TextureTilingTreatment.edgeToEdgeXY)
        {
            //only one rect in atlas and is edge to edge in both X and Y directions.
            return true;
        }
        else
        {
            if (MB3_UVTransformUtility.RectContainsShifted(ref samplingEncapsulatinRect, ref potentialRect))
            {
                return true;
            }
        }
        return false;
    }
}