forked from Rampastring/Rampastring.XNAUI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AssetLoader.cs
339 lines (295 loc) · 10.9 KB
/
AssetLoader.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
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Rampastring.Tools;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Media;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Png;
using Color = Microsoft.Xna.Framework.Color;
using System.Globalization;
namespace Rampastring.XNAUI;
/// <summary>
/// A static class that provides easy-to-use methods
/// for loading and generating assets such as textures and sounds.
/// </summary>
public static class AssetLoader
{
/// <summary>
/// A list of filesystem paths that assets are attempted to load from.
/// </summary>
public static List<string> AssetSearchPaths;
private static GraphicsDevice graphicsDevice;
private static ContentManager contentManager;
private static List<Texture2D> textureCache;
private static List<SoundEffect> soundCache;
public static bool IsInitialized { get; private set; } = false;
/// <summary>
/// Initializes the AssetLoader.
/// </summary>
/// <param name="gd">The graphics device.</param>
/// <param name="content">The game content manager.</param>
public static void Initialize(GraphicsDevice gd, ContentManager content)
{
if (IsInitialized)
throw new InvalidOperationException("AssetLoader is already initialized.");
IsInitialized = true;
graphicsDevice = gd;
AssetSearchPaths = new List<string>();
textureCache = new List<Texture2D>();
soundCache = new List<SoundEffect>();
contentManager = content;
}
/// <summary>
/// Loads a texture with the specific name. If the texture isn't found from any
/// asset search path, returns a dummy texture.
/// </summary>
/// <param name="name">The name of the texture.</param>
/// <returns>The texture if it was found and could be loaded, otherwise a dummy texture.</returns>
public static Texture2D LoadTexture(string name)
{
var cachedTexture = textureCache.Find(t => t.Name == name);
if (cachedTexture != null)
return cachedTexture;
var texture = LoadTextureInternal(name);
if (texture != null)
{
textureCache.Add(texture);
return texture;
}
return CreateDummyTexture();
}
/// <summary>
/// Loads a texture with the specific name. Does not look at textures in
/// the texture cache, and doesn't add loaded textures to the texture cache.
/// </summary>
/// <param name="name">The name of the texture.</param>
/// <returns>The texture if it was found and could be loaded, otherwise a dummy texture.</returns>
public static Texture2D LoadTextureUncached(string name)
{
var texture = LoadTextureInternal(name);
if (texture != null)
return texture;
return CreateDummyTexture();
}
private static Texture2D LoadTextureInternal(string name)
{
try
{
foreach (string searchPath in AssetSearchPaths)
{
FileInfo fileInfo = SafePath.GetFile(searchPath, name);
if (fileInfo.Exists)
{
using FileStream fs = fileInfo.OpenRead();
var texture = Texture2D.FromStream(graphicsDevice, fs);
texture.Name = name;
PremultiplyAlpha(texture);
return texture;
}
}
}
catch (Exception ex)
{
Logger.Log("AssetLoader.LoadTextureInternal: loading texture " + name + " failed! Message: " + ex.Message);
}
return null;
}
private static void PremultiplyAlpha(Texture2D texture)
{
var data = new Color[texture.Width * texture.Height];
texture.GetData(data);
for (int i = 0; i < data.Length; i++)
{
data[i].R = (byte)(data[i].R * data[i].A / 255);
data[i].G = (byte)(data[i].G * data[i].A / 255);
data[i].B = (byte)(data[i].B * data[i].A / 255);
}
texture.SetData(data);
}
/// <summary>
/// Creates and returns a 100x100 pink square.
/// </summary>
private static Texture2D CreateDummyTexture()
{
return CreateTexture(new Color(255, 54, 244), 100, 100);
}
/// <summary>
/// Checks if a specified asset file exists.
/// </summary>
/// <param name="name">The name of the asset file.</param>
/// <returns></returns>
public static bool AssetExists(string name)
{
foreach (string searchPath in AssetSearchPaths)
{
if (SafePath.GetFile(searchPath, name).Exists)
return true;
}
return false;
}
/// <summary>
/// Creates a one-colored texture.
/// </summary>
/// <param name="color">The color of the texture.</param>
/// <param name="width">The width of the texture in pixels.</param>
/// <param name="height">The height of the texture in pixels.</param>
/// <returns>A texture.</returns>
public static Texture2D CreateTexture(Color color, int width, int height)
{
var texture = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color);
var colorArray = new Color[width * height];
for (int i = 0; i < colorArray.Length; i++)
colorArray[i] = color;
texture.SetData(colorArray);
return texture;
}
/// <summary>
/// Creates a texture from a <see cref="Image"/>.
/// Returns null if creating the texture fails.
/// </summary>
/// <param name="image">The image.</param>
/// <returns>The created texture, or null if creating the texture fails.</returns>
public static Texture2D TextureFromImage(Image image)
{
try
{
using var stream = new MemoryStream();
image.Save(stream, new PngEncoder());
var texture = Texture2D.FromStream(graphicsDevice, stream);
PremultiplyAlpha(texture);
return texture;
}
catch (Exception ex)
{
Logger.Log("AssetLoader.TextureFromImage: failed to create texture! Message: " + ex.Message);
return null;
}
}
/// <summary>
/// Loads a sound effect with the given name.
/// </summary>
/// <param name="name">The name of the sound effect.</param>
/// <returns>The loaded sound effect, or null if the sound effect isn't found.</returns>
public static SoundEffect LoadSound(string name)
{
SoundEffect cachedSound = soundCache.Find(se => se.Name == name);
if (cachedSound != null)
return cachedSound;
foreach (string searchPath in AssetSearchPaths)
{
FileInfo fileInfo = SafePath.GetFile(searchPath, name);
if (fileInfo.Exists)
{
using FileStream fs = fileInfo.OpenRead();
var se = SoundEffect.FromStream(fs);
se.Name = name;
soundCache.Add(se);
return se;
}
}
Logger.Log("AssetLoader.LoadSound: Sound not found! " + name);
return null;
}
/// <summary>
/// Loads a <see cref="Song"/> with the specified name.
/// </summary>
/// <param name="name">The name of the song.</param>
/// <returns>The loaded song, or null if loading the song fails.</returns>
public static Song LoadSong(string name)
{
try
{
return contentManager.Load<Song>(name);
}
catch (Exception ex)
{
Logger.Log("Loading song " + name + " failed! Message: " + ex.Message);
return null;
}
}
/// <summary>
/// Loads an <see cref="Effect"/> with the specified name.
/// </summary>
/// <param name="name">The name of the effect.</param>
/// <returns>The loaded effect, or null if loading the effect fails.</returns>
public static Effect LoadEffect(string name)
{
try
{
return contentManager.Load<Effect>(name);
}
catch (Exception ex)
{
Logger.Log("Loading shader effect " + name + " failed! Message: " + ex.Message);
return null;
}
}
/// <summary>
/// Creates a color based on a color string in the form "R,G,B" or "R,G,B,A". All values must be between 0 and 255.
/// </summary>
/// <param name="colorString">The color string in the form "R,G,B,A". All values must be between 0 and 255.</param>
/// <returns>A XNA Color struct based on the given string.</returns>
public static Color GetColorFromString(string colorString)
{
try
{
string[] colorArray = colorString.Split(',');
int alpha = 255;
if (colorArray.Length == 4)
{
alpha = Convert.ToByte(colorArray[3], CultureInfo.InvariantCulture);
}
var color = new Color(
Convert.ToByte(colorArray[0], CultureInfo.InvariantCulture),
Convert.ToByte(colorArray[1], CultureInfo.InvariantCulture),
Convert.ToByte(colorArray[2], CultureInfo.InvariantCulture),
alpha);
return color;
}
catch
{
throw new FormatException("AssetLoader.GetColorFromString: Failed to convert " + colorString + " to a valid color!");
}
}
/// <summary>
/// Creates a color based on a color string in the form "R,G,B". All values must be between 0 and 255.
/// Returns a given default color if parsing the given string fails.
/// </summary>
/// <param name="colorString">The color string.</param>
/// <param name="defaultColor">The default color to return if parsing the string fails.</param>
/// <returns>A XNA Color struct.</returns>
public static Color GetColorFromString(string colorString, Color defaultColor)
{
try
{
return GetColorFromString(colorString);
}
catch
{
return defaultColor;
}
}
/// <summary>
/// Creates a color based on a color string in the form "R,G,B,A". All values must be between 0 and 255.
/// </summary>
public static Color GetRGBAColorFromString(string colorString)
{
try
{
string[] colorArray = colorString.Split(',');
var color = new Color(
Convert.ToByte(colorArray[0], CultureInfo.InvariantCulture),
Convert.ToByte(colorArray[1], CultureInfo.InvariantCulture),
Convert.ToByte(colorArray[2], CultureInfo.InvariantCulture),
Convert.ToByte(colorArray[3], CultureInfo.InvariantCulture));
return color;
}
catch
{
throw new FormatException("AssetLoader.GetRGBAColorFromString: Failed to convert " + colorString + " to a valid color!");
}
}
}