forked from tparisi/Unity-glTF-Exporter
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathTextureUnpacker.cs
427 lines (358 loc) · 10.6 KB
/
TextureUnpacker.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
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
// NOTES:
// - only checks first texture and first uv
public class TextureUnpacker {
class Entry {
public int left;
public int right;
public int top;
public int bottom;
public int texWidth;
public int texHeight;
public Dictionary<string, List<int>> subMeshMap = new Dictionary<string, List<int>>();
}
class UVTransform {
public Vector2 offset;
public Vector2 scale;
}
static Dictionary<string, Entry> entries = new Dictionary<string, Entry>(); // texture id->entry
static Dictionary<string, Dictionary<int, UVTransform>> meshMap = new Dictionary<string, Dictionary<int, UVTransform>>();
static Renderer GetRenderer(Transform tr) {
Renderer mr = tr.GetComponent<MeshRenderer>();
if (mr == null) {
mr = tr.GetComponent<SkinnedMeshRenderer>();
}
return mr;
}
static Mesh GetMesh(Transform tr) {
var mr = GetRenderer(tr);
Mesh m = null;
if (mr != null) {
var t = mr.GetType();
if (t == typeof(MeshRenderer)) {
MeshFilter mf = tr.GetComponent<MeshFilter>();
m = mf.sharedMesh;
} else if (t == typeof(SkinnedMeshRenderer)) {
SkinnedMeshRenderer smr = mr as SkinnedMeshRenderer;
m = smr.sharedMesh;
}
}
return m;
}
static List<Texture> GetTexturesFromRenderer(Renderer r) {
var ret = new List<Texture>();
var mats = r.sharedMaterials;
foreach (var mat in mats) {
if (mat == null) {
continue;
}
var s = mat.shader;
int spCount = ShaderUtil.GetPropertyCount(s);
for (var i = 0; i < spCount; ++i) {
var pName = ShaderUtil.GetPropertyName(s, i);
var pType = ShaderUtil.GetPropertyType(s, i);
if (pType == ShaderUtil.ShaderPropertyType.TexEnv) {
var td = ShaderUtil.GetTexDim(s, i);
if (td == UnityEngine.Rendering.TextureDimension.Tex2D) {
var t = mat.GetTexture(pName);
if (t != null) {
ret.Add(t);
}
}
}
}
}
return ret;
}
static List<Texture> GetTexturesFromMaterial(Material mat) {
var ret = new List<Texture>();
if (mat == null) {
return ret;
}
var s = mat.shader;
int spCount = ShaderUtil.GetPropertyCount(s);
for (var i = 0; i < spCount; ++i) {
var pName = ShaderUtil.GetPropertyName(s, i);
var pType = ShaderUtil.GetPropertyType(s, i);
if (pType == ShaderUtil.ShaderPropertyType.TexEnv) {
var td = ShaderUtil.GetTexDim(s, i);
if (td == UnityEngine.Rendering.TextureDimension.Tex2D) {
var t = mat.GetTexture(pName);
if (t != null) {
ret.Add(t);
}
}
}
}
return ret;
}
public static void CheckPackedTexture(Transform t, Preset preset) {
var m = GetMesh(t);
var r = GetRenderer(t);
if (m != null && r != null) {
for (int i = 0; i < m.subMeshCount; ++i) {
if (m.GetTopology(i) != MeshTopology.Triangles ||
i >= r.sharedMaterials.Length) {
continue;
}
var mat = r.sharedMaterials[i];
if (mat == null) {
Debug.LogWarning("Failed getting shader name from material on mesh " + m.name);
continue;
}
List<Preset.UnpackUV> unpackUVList = null;
preset.unpackUV.TryGetValue(mat.shader.name, out unpackUVList);
if (unpackUVList == null) {
unpackUVList = preset.GetDefaultUnpackUVList();
}
var tris = m.GetTriangles(i);
var uvsArr = new Vector2[][]{m.uv, m.uv2, m.uv3, m.uv4};
var mins = new Vector2[4];
var maxs = new Vector2[4];
var dxs = new float[4];
var dys = new float[4];
for (int k = 0; k < 4; ++k) {
Vector2 min = new Vector2(float.MaxValue, float.MaxValue);
Vector2 max = new Vector2(float.MinValue, float.MinValue);
var uvs = uvsArr[k];
if (uvs != null && uvs.Length > 0) {
for (int j = 0; j < tris.Length; ++j) {
Vector2 uv = uvs[tris[j]];
float y = 1.0f - uv.y; // flipped y
min.x = Mathf.Min(min.x, uv.x);
min.y = Mathf.Min(min.y, y);
max.x = Mathf.Max(max.x, uv.x);
max.y = Mathf.Max(max.y, y);
}
var dx = max.x - min.x;
var dy = max.y - min.y;
dxs[k] = dx;
dys[k] = dy;
}
mins[k] = min;
maxs[k] = max;
}
var texs = GetTexturesFromMaterial(mat);
foreach (var unpackUV in unpackUVList) {
foreach (var texIdx in unpackUV.textureIndex) {
if (texIdx < texs.Count) {
var tex = texs[texIdx];
var name = GlTF_Texture.GetNameFromObject(tex);
var dx = dxs[unpackUV.index];
var dy = dys[unpackUV.index];
var max = maxs[unpackUV.index];
var min = mins[unpackUV.index];
max.x = Mathf.Clamp01(max.x);
max.y = Mathf.Clamp01(max.y);
min.x = Mathf.Clamp01(min.x);
min.y = Mathf.Clamp01(min.y);
var tw = tex.width;
var th = tex.height;
var sx = Mathf.FloorToInt(min.x * tw);
var fx = Mathf.CeilToInt(max.x * tw);
var sy = Mathf.FloorToInt(min.y * th);
var fy = Mathf.CeilToInt(max.y * th);
int wx = fx - sx;
int wy = fy - sy;
wx = Mathf.NextPowerOfTwo(wx);
wy = Mathf.NextPowerOfTwo(wy);
var meshName = GlTF_Mesh.GetNameFromObject(m);
Entry e;
if (entries.ContainsKey(name)) {
e = entries[name];
//merge
var minX = Mathf.Min(e.left, sx);
var maxX = Mathf.Max(e.right, fx);
var minY = Mathf.Min(e.top, sy);
var maxY = Mathf.Max(e.bottom, fy);
var mw = maxX - minX;
var mh = maxY - minY;
mw = Mathf.NextPowerOfTwo(mw);
mh = Mathf.NextPowerOfTwo(mh);
e.left = minX;
e.right = maxX;
e.top = minY;
e.bottom = maxY;
} else {
e = new Entry();
e.left = sx;
e.right = fx;
e.top = sy;
e.bottom = fy;
e.texWidth = tex.width;
e.texHeight = tex.height;
entries[name] = e;
}
List<int> subMeshId = null;
if (e.subMeshMap.ContainsKey(meshName)) {
subMeshId = e.subMeshMap[meshName];
} else {
subMeshId = new List<int>();
e.subMeshMap[meshName] = subMeshId;
}
if (!subMeshId.Contains(i)) {
subMeshId.Add(i);
}
}
}
}
}
}
}
public static void Reset() {
entries.Clear();
meshMap.Clear();
}
public static void Build() {
var skipList = new List<string>();
foreach (var i in entries) {
var e = i.Value;
var mw = e.right - e.left;
var mh = e.bottom - e.top;
var dx = (float)mw / (float)e.texWidth;
var dy = (float)mh / (float)e.texHeight;
if (dx >= 0.9 || dy >= 0.9) {
skipList.Add(i.Key);
}
}
foreach (var sl in skipList) {
entries.Remove(sl);
}
foreach (var i in entries) {
var e = i.Value;
var mw = e.right - e.left;
var mh = e.bottom - e.top;
mw = Mathf.NextPowerOfTwo(mw);
mh = Mathf.NextPowerOfTwo(mh);
int left = e.left;
int right = left + (mw - 1);
if (right > e.texWidth - 1) {
// shift left
right = e.texWidth - 1;
left = right - (mw - 1);
}
int top = e.top;
int bottom = top + (mh - 1);
if (bottom > e.texHeight - 1) {
// shift up
bottom = e.texHeight - 1;
top = bottom - (mh - 1);
}
UVTransform uvt = new UVTransform();
uvt.offset = new Vector2(-(float)left / (float)e.texWidth, -(float)top / (float)e.texHeight);
uvt.scale = new Vector2((float)e.texWidth / (float)mw, (float)e.texHeight / (float)mh);
foreach (var j in e.subMeshMap) {
var list = j.Value;
Dictionary<int, UVTransform> uvtMap = null;
if (meshMap.ContainsKey(j.Key)) {
uvtMap = meshMap[j.Key];
} else {
uvtMap = new Dictionary<int, UVTransform>();
meshMap[j.Key] = uvtMap;
}
foreach (var subMeshIdx in list) {
uvtMap[subMeshIdx] = uvt;
}
}
}
}
public static void ProcessMesh(GlTF_Mesh mesh) {
if (meshMap.ContainsKey(mesh.name)) {
var uvtMap = meshMap[mesh.name];
HashSet<int> moddedIndex = new HashSet<int>(); // keep track modified uv
foreach (var i in uvtMap) {
var idx = i.Key;
var uvt = i.Value;
if (idx < mesh.primitives.Count) {
var prim = mesh.primitives[idx];
var ms = prim.indices.bufferView.memoryStream;
int offset = (int)prim.indices.byteOffset;
var len = prim.indices.count;
var buffer = new byte[len * 2];
// read indices
var pos = ms.Position;
ms.Position = offset;
ms.Read(buffer, 0, buffer.Length);
ushort[] indices = new ushort[len];
for (int j = 0; j < len; ++j) {
indices[j] = System.BitConverter.ToUInt16(buffer, j * 2);
}
ms.Position = pos;
//read uvs
ms = prim.attributes.texCoord0Accessor.bufferView.memoryStream;
offset = (int)prim.attributes.texCoord0Accessor.byteOffset;
len = prim.attributes.texCoord0Accessor.count;
buffer = new byte[len * 8];
pos = ms.Position;
ms.Position = offset;
ms.Read(buffer, 0, buffer.Length);
Vector2[] uvs = new Vector2[len];
for (int j = 0; j < len; ++j) {
var u = System.BitConverter.ToSingle(buffer, j * 8);
var v = System.BitConverter.ToSingle(buffer, j * 8 + 4);
uvs[j] = new Vector2(u, v);
}
ms.Position = pos;
// manipulate uvs
for (int j = 0; j < indices.Length; ++j) {
var ind = indices[j];
if (!moddedIndex.Contains(ind)) {
var uv = uvs[ind];
uv += uvt.offset;
uv.Scale(uvt.scale);
uvs[indices[j]] = uv;
moddedIndex.Add(ind);
}
}
// write back
prim.attributes.texCoord0Accessor.Populate(uvs);
}
}
}
}
public static Texture2D ProcessTexture(string name, Texture2D tex) {
if (entries.ContainsKey(name)) {
Entry e = entries[name];
var mw = e.right - e.left;
var mh = e.bottom - e.top;
mw = Mathf.NextPowerOfTwo(mw);
mh = Mathf.NextPowerOfTwo(mh);
int left = e.left;
int right = left + (mw - 1);
if (right > e.texWidth - 1) {
// shift left
right = e.texWidth - 1;
left = right - (mw - 1);
}
int top = e.top;
int bottom = top + (mh - 1);
if (bottom > e.texHeight - 1) {
// shift up
bottom = e.texHeight - 1;
top = bottom - (mh - 1);
}
// flip top & bottom
var ftop = e.texHeight - 1 - top;
var fbottom = e.texHeight - 1 - bottom;
top = fbottom;
bottom = ftop;
var src = tex.GetPixels32();
var dst = new Color32[mw * mh];
for (int i = 0; i < mh; ++i) {
for (int j = 0; j < mw; ++j) {
var dstIdx = i * mw + j;
var srcIdx = (top + i) * tex.width + (left + j);
dst[dstIdx] = src[srcIdx];
}
}
Texture2D t = new Texture2D(mw, mh, TextureFormat.RGBA32, false);
t.SetPixels32(dst);
t.Apply();
return t;
}
return tex;
}
}