forked from ducakar/TextureReplacer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Loader.cs
339 lines (283 loc) · 12.6 KB
/
Loader.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
/*
* Copyright © 2013-2018 Davorin Učakar, RangeMachine
* Copyright © 2013 Ryan Bray
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
namespace TextureReplacer
{
internal class Loader
{
private static readonly string HUD_NAVBALL = Replacer.DIR_TEXTURES + Replacer.HUD_NAVBALL;
private static readonly string IVA_NAVBALL = Replacer.DIR_TEXTURES + Replacer.IVA_NAVBALL;
// Texture compression and mipmap generation parameters.
private int lastTextureCount = 0;
// List of substrings for paths where mipmap generating is enabled.
private readonly List<Regex> generateMipmaps = new List<Regex> {
new Regex("^" + Util.DIR + "(Default|Heads|Suits)/")
};
// List of substrings for paths where textures shouldn't be unloaded.
private readonly List<Regex> keepLoaded = new List<Regex> {
new Regex("^" + Reflections.DIR_ENVMAP)
};
// Features.
private bool? isCompressionEnabled = null;
private bool? isMipmapGenEnabled = null;
private bool? isUnloadingEnabled = null;
// Instance.
public static Loader instance = null;
/**
* Estimate texture size in system RAM.
*
* This is only a rough estimate. It doesn't bother with details like the padding bytes.
*/
private static int textureSize(Texture2D texture)
{
int nPixels = texture.width * texture.height;
return texture.format == TextureFormat.DXT1 || texture.format == TextureFormat.RGB24 ? nPixels * 3 : nPixels * 4;
}
/**
* Read configuration and perform pre-load initialisation.
*/
public void readConfig(ConfigNode rootNode)
{
string sIsCompressionEnabled = rootNode.GetValue("isCompressionEnabled");
if (sIsCompressionEnabled != null)
{
switch (sIsCompressionEnabled)
{
case "always":
isCompressionEnabled = true;
break;
case "never":
isCompressionEnabled = false;
break;
case "auto":
isCompressionEnabled = null;
break;
default:
Util.log("Invalid value for isCompressionEnabled: {0}", sIsCompressionEnabled);
break;
}
}
string sIsMipmapGenEnabled = rootNode.GetValue("isMipmapGenEnabled");
if (sIsMipmapGenEnabled != null)
{
switch (sIsMipmapGenEnabled)
{
case "always":
isMipmapGenEnabled = true;
break;
case "never":
isMipmapGenEnabled = false;
break;
case "auto":
isMipmapGenEnabled = null;
break;
default:
Util.log("Invalid value for isMipmapGenEnabled: {0}", sIsMipmapGenEnabled);
break;
}
}
Util.addRELists(rootNode.GetValues("generateMipmaps"), generateMipmaps);
string sIsUnloadingEnabled = rootNode.GetValue("isUnloadingEnabled");
if (sIsUnloadingEnabled != null)
{
switch (sIsUnloadingEnabled)
{
case "always":
isUnloadingEnabled = true;
break;
case "never":
isUnloadingEnabled = false;
break;
case "auto":
isUnloadingEnabled = null;
break;
default:
Util.log("Invalid value for isUnloadingEnabled: {0}", sIsUnloadingEnabled);
break;
}
}
Util.addRELists(rootNode.GetValues("keepLoaded"), keepLoaded);
}
/**
* This must be run only once after all configuration files are read.
*/
public void configure()
{
// Prevent conflicts with TextureCompressor. If it is found among loaded plugins, texture
// compression step will be skipped since TextureCompressor should handle it (better).
bool isATMDetected = AssemblyLoader.loadedAssemblies
.Any(a => a.name.StartsWith("ActiveTextureManagement", StringComparison.Ordinal));
if (isATMDetected)
{
if (isCompressionEnabled == null)
{
Util.log("Detected Active Texture Management, disabling texture compression.");
isCompressionEnabled = false;
}
if (isMipmapGenEnabled == null)
{
Util.log("Detected Active Texture Management, disabling mipmap generation.");
isMipmapGenEnabled = false;
}
if (isUnloadingEnabled == null)
{
Util.log("Detected Active Texture Management, disabling texture unloading.");
isUnloadingEnabled = false;
}
}
else
{
if (isCompressionEnabled == null)
isCompressionEnabled = true;
if (isMipmapGenEnabled == null)
isMipmapGenEnabled = true;
if (isUnloadingEnabled == null)
isUnloadingEnabled = true;
}
}
/**
* Texture compression & mipmap generation pass.
*
* This is run on each game update until game database is loaded.
*/
public void processTextures()
{
List<GameDatabase.TextureInfo> texInfos = GameDatabase.Instance.databaseTexture;
for (int i = lastTextureCount; i < texInfos.Count; ++i)
{
GameDatabase.TextureInfo texInfo = texInfos[i];
Texture2D texture = texInfo.texture;
if (texture == null)
continue;
// Apply trilinear filter.
if (texture.filterMode == FilterMode.Bilinear)
texture.filterMode = FilterMode.Trilinear;
if (!texInfo.isReadable)
continue;
// `texture.GetPixel() throws an exception if the texture is not readable and hence it
// cannot be compressed nor mipmaps generated.
try
{
texture.GetPixel(0, 0);
}
catch (UnityException)
{
continue;
}
TextureFormat format = texture.format;
bool hasGenMipmaps = false;
bool hasCompressed = false;
// Generate mipmaps if necessary. Images that may be UI icons should be excluded to prevent
// blurriness when using less-than-full texture quality.
if (isMipmapGenEnabled.Value && texture.mipmapCount == 1
&& (texture.width > 1 || texture.height > 1)
&& generateMipmaps.Any(r => r.IsMatch(texture.name))
&& texture.name != HUD_NAVBALL && texture.name != IVA_NAVBALL)
{
Color32[] pixels32 = texture.GetPixels32();
// PNGs are always loaded as transparent, so we check if they actually contain any
// transparent pixels. Convert non-transparent PNGs to RGB.
bool hasAlpha = format == TextureFormat.RGBA32 || format == TextureFormat.DXT5;
bool isTransparent = hasAlpha && pixels32.Any(p => p.a != 255);
// Workaround for a Unity + D3D bug.
int quality = QualitySettings.masterTextureLimit;
if (isCompressionEnabled.Value && quality > 0
&& (texture.width >> quality) % 4 != 0 && (texture.width >> quality) % 4 != 0)
{
QualitySettings.masterTextureLimit = 0;
}
// Rebuild texture. This time with mipmaps.
TextureFormat newFormat = isTransparent ? TextureFormat.RGBA32 : TextureFormat.RGB24;
texture.Resize(texture.width, texture.height, newFormat, true);
texture.SetPixels32(pixels32);
texture.Apply(true, false);
if (quality != QualitySettings.masterTextureLimit)
QualitySettings.masterTextureLimit = quality;
hasGenMipmaps = true;
}
// Compress if necessary.
if (isCompressionEnabled.Value && texture.format != TextureFormat.DXT1 && texture.format != TextureFormat.DXT5)
{
texture.Compress(true);
texInfos[i].isCompressed = true;
hasCompressed = true;
}
if (hasGenMipmaps || hasCompressed)
{
Util.log("{0} {1} [{2}x{3} {4} -> {5}]",
hasGenMipmaps && hasCompressed ? "Generated mipmaps & compressed" :
hasGenMipmaps ? "Generated mipmaps for" : "Compressed",
texture.name, texture.width, texture.height, format, texture.format);
}
}
lastTextureCount = texInfos.Count;
}
/**
* Unload textures.
*/
public void initialise()
{
List<GameDatabase.TextureInfo> texInfos = GameDatabase.Instance.databaseTexture;
int memorySpared = 0;
foreach (GameDatabase.TextureInfo texInfo in texInfos)
{
Texture2D texture = texInfo.texture;
if (texture == null || !texInfo.isReadable)
continue;
// Following line makes sure that buttons aren't unloaded from memory
// Needed to allow other mods to manipulate the toolbar buttons (ie: Janitor's Closet
if (texture.width <= 38 && texture.height <= 38)
continue;
// Unload texture from RAM (a.k.a. "make it unreadable") unless set otherwise.
if (isUnloadingEnabled.Value && !keepLoaded.Any(r => r.IsMatch(texture.name)))
{
try
{
texture.GetPixel(0, 0);
}
catch (UnityException)
{
continue;
}
memorySpared += textureSize(texture);
texture.Apply(false, true);
texInfo.isReadable = false;
Util.log("Unloaded {0}", texture.name);
}
}
generateMipmaps.Clear();
generateMipmaps.TrimExcess();
keepLoaded.Clear();
keepLoaded.TrimExcess();
if (memorySpared > 0)
{
Util.log("Texture unloading freed approximately {0:0.0} MiB = {1:0.0} MB of system RAM",
memorySpared / 1024.0 / 1024.0, memorySpared / 1000.0 / 1000.0);
}
}
}
}