-
-
Notifications
You must be signed in to change notification settings - Fork 276
/
ContentManager.cs
711 lines (642 loc) · 17.9 KB
/
ContentManager.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
#region License
/* FNA - XNA4 Reimplementation for Desktop Platforms
* Copyright 2009-2024 Ethan Lee and the MonoGame Team
*
* Released under the Microsoft Public License.
* See LICENSE for details.
*/
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Media;
#endregion
namespace Microsoft.Xna.Framework.Content
{
public partial class ContentManager : IDisposable
{
#region Public ServiceProvider Property
public IServiceProvider ServiceProvider
{
get;
private set;
}
#endregion
#region Public RootDirectory Property
public string RootDirectory
{
get;
set;
}
#endregion
#region Internal Root Directory Path Property
internal string RootDirectoryFullPath
{
get
{
if (Path.IsPathRooted(RootDirectory))
{
return RootDirectory;
}
return Path.Combine(TitleLocation.Path, RootDirectory);
}
}
#endregion
#region Private Variables
private GraphicsDevice graphicsDevice;
private Dictionary<string, object> loadedAssets = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
private List<IDisposable> disposableAssets = new List<IDisposable>();
private bool disposed;
#endregion
#region Private Static Variables
private static object ContentManagerLock = new object();
private static List<WeakReference> ContentManagers = new List<WeakReference>();
private static readonly byte[] xnbHeader = new byte[4];
private static List<char> targetPlatformIdentifiers = new List<char>()
{
'w', // Windows (DirectX)
'x', // Xbox360
'm', // WindowsPhone
'i', // iOS
'a', // Android
'd', // DesktopGL
'X', // MacOSX
'W', // WindowsStoreApp
'n', // NativeClient
'u', // Ouya
'p', // PlayStationMobile
'M', // WindowsPhone8
'r', // RaspberryPi
'P', // Playstation 4
'g', // WindowsGL (deprecated for DesktopGL)
'l', // Linux (deprecated for DesktopGL)
};
// Note: These may not be in alphabetical order, for performance reasons
private static readonly string[] effectExtensions = new string[] { ".fxb" };
private static readonly string[] texture2DExtensions = new string[]
{
".png", ".jpg", ".jpeg", ".dds", ".qoi", ".bmp", ".gif", ".tga", ".tif", ".tiff"
};
private static readonly string[] textureCubeExtensions = new string[] { ".dds" };
private static readonly string[] soundEffectExtensions = new string[] { ".wav" };
#endregion
#region Public Constructors
public ContentManager(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
ServiceProvider = serviceProvider;
RootDirectory = string.Empty;
AddContentManager(this);
}
public ContentManager(IServiceProvider serviceProvider, string rootDirectory)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
if (rootDirectory == null)
{
throw new ArgumentNullException("rootDirectory");
}
ServiceProvider = serviceProvider;
RootDirectory = rootDirectory;
AddContentManager(this);
}
#endregion
#region Destructor
/* Use C# destructor syntax for finalization code.
* This destructor will run only if the Dispose method
* does not get called.
* It gives your base class the opportunity to finalize.
* Do not provide destructors in types derived from this class.
*/
~ContentManager()
{
/* Do not re-create Dispose clean-up code here.
* Calling Dispose(false) is optimal in terms of
* readability and maintainability.
*/
Dispose(false);
}
#endregion
#region Dispose Methods
public void Dispose()
{
Dispose(true);
/* Tell the garbage collector not to call the finalizer
* since all the cleanup will already be done.
*/
GC.SuppressFinalize(this);
// Once disposed, content manager wont be used again
RemoveContentManager(this);
}
/* If disposing is true, it was called explicitly and we should dispose managed
* objects. If disposing is false, it was called by the finalizer and managed
* objects should not be disposed.
*/
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
Unload();
}
disposed = true;
}
}
#endregion
#region Public Methods
public virtual T Load<T>(string assetName)
{
if (string.IsNullOrEmpty(assetName))
{
throw new ArgumentNullException("assetName");
}
if (disposed)
{
throw new ObjectDisposedException("ContentManager");
}
T result = default(T);
/* On some platforms, name and slash direction matter.
* We store the asset by a /-separating key rather than
* how the path to the file was passed to us to avoid
* loading "content/asset1.xnb" and "content\\ASSET1.xnb"
* as if they were two different files. this matches
* stock XNA behavior. The Dictionary will ignore case
* differences.
*/
string key = assetName.Replace('\\', '/');
// Check for a previously loaded asset first
object asset = null;
if (loadedAssets.TryGetValue(key, out asset))
{
if (asset is T)
{
return (T) asset;
}
}
// Load the asset.
result = ReadAsset<T>(assetName, null);
loadedAssets[key] = result;
return result;
}
public virtual void Unload()
{
// Look for disposable assets.
foreach (IDisposable disposable in disposableAssets)
{
if (disposable != null)
{
disposable.Dispose();
}
}
disposableAssets.Clear();
loadedAssets.Clear();
}
#endregion
#region Protected Methods
protected virtual Stream OpenStream(string assetName)
{
Stream stream;
try
{
stream = TitleContainer.OpenStream(
Path.Combine(RootDirectory, assetName) + ".xnb"
);
}
catch (FileNotFoundException fileNotFound)
{
throw new ContentLoadException("The content file was not found.", fileNotFound);
}
catch (DirectoryNotFoundException directoryNotFound)
{
throw new ContentLoadException("The directory was not found.", directoryNotFound);
}
catch (Exception exception)
{
throw new ContentLoadException("Opening stream error.", exception);
}
return stream;
}
protected T ReadAsset<T>(string assetName, Action<IDisposable> recordDisposableObject)
{
if (string.IsNullOrEmpty(assetName))
{
throw new ArgumentNullException("assetName");
}
if (disposed)
{
throw new ObjectDisposedException("ContentManager");
}
object result = null;
Stream stream = null;
try
{
stream = OpenStream(assetName);
}
catch (Exception e)
{
// Okay, so we couldn't open it. Maybe it needs a different extension?
stream = OpenStreamRaw<T>(assetName);
if (stream == null)
{
throw new ContentLoadException(
"Could not load asset " + assetName + "! Error: " + e.Message,
e
);
}
}
// Check for XNB header
stream.Read(xnbHeader, 0, xnbHeader.Length);
if ( xnbHeader[0] == 'X' &&
xnbHeader[1] == 'N' &&
xnbHeader[2] == 'B' &&
targetPlatformIdentifiers.Contains((char) xnbHeader[3]) )
{
using (BinaryReader xnbReader = new BinaryReader(stream))
using (ContentReader reader = GetContentReaderFromXnb(assetName, ref stream, xnbReader, (char) xnbHeader[3], recordDisposableObject))
{
result = reader.ReadAsset<T>();
GraphicsResource resource = result as GraphicsResource;
if (resource != null)
{
resource.Name = assetName;
}
}
}
else
{
// It's not an XNB file. Try to load as a raw asset instead.
// FIXME: Assuming seekable streams! -flibit
stream.Seek(0, SeekOrigin.Begin);
if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Texture))
{
Texture2D texture;
if ( xnbHeader[0] == 'D' &&
xnbHeader[1] == 'D' &&
xnbHeader[2] == 'S' &&
xnbHeader[3] == ' ' )
{
texture = Texture2D.DDSFromStreamEXT(
GetGraphicsDevice(),
stream
);
}
else
{
texture = Texture2D.FromStream(
GetGraphicsDevice(),
stream
);
}
texture.Name = assetName;
result = texture;
}
else if (typeof(T) == typeof(TextureCube))
{
TextureCube texture = TextureCube.DDSFromStreamEXT(
GetGraphicsDevice(),
stream
);
texture.Name = assetName;
result = texture;
}
else if (typeof(T) == typeof(SoundEffect))
{
SoundEffect effect = SoundEffect.FromStream(stream);
effect.Name = assetName;
result = effect;
}
else if (typeof(T) == typeof(Effect))
{
byte[] data = new byte[stream.Length];
stream.Read(data, 0, (int) stream.Length);
Effect effect = new Effect(GetGraphicsDevice(), data);
effect.Name = assetName;
result = effect;
}
else if (typeof(T) == typeof(Song))
{
// Song can't use the stream, get the file name and free the handle
string fileName = (stream as FileStream).Name;
stream.Close();
result = new Song(fileName);
}
else if (typeof(T) == typeof(Video))
{
// Video can't use the stream, get the file name and free the handle
string fileName = (stream as FileStream).Name;
stream.Close();
result = new Video(fileName, GetGraphicsDevice());
FNALoggerEXT.LogWarn(
"Video " +
fileName +
" does not have an XNB file! Hacking Duration property!"
);
}
else
{
stream.Close();
throw new ContentLoadException("Could not load " + assetName + " asset!");
}
/* Because Raw Assets skip the ContentReader step, they need to have their
* disposables recorded here. Doing it outside of this catch will
* result in disposables being logged twice.
*/
IDisposable disposableResult = result as IDisposable;
if (disposableResult != null)
{
if (recordDisposableObject != null)
{
recordDisposableObject(disposableResult);
}
else
{
disposableAssets.Add(disposableResult);
}
}
/* Because we're not using a BinaryReader for raw assets, we
* need to close the stream ourselves.
* -flibit
*/
stream.Close();
}
return (T) result;
}
#endregion
#region Internal Methods
internal void RecordDisposable(IDisposable disposable)
{
Debug.Assert(disposable != null, "The disposable is null!");
/* Avoid recording disposable objects twice. ReloadAsset will try to record
* the disposables again. We don't know which asset recorded which
* disposable so just guard against storing multiple of the same instance.
*/
if (!disposableAssets.Contains(disposable))
{
disposableAssets.Add(disposable);
}
}
internal GraphicsDevice GetGraphicsDevice()
{
if (graphicsDevice == null)
{
IGraphicsDeviceService result = ServiceProvider.GetService(
typeof(IGraphicsDeviceService)
) as IGraphicsDeviceService;
if (result == null)
{
throw new ContentLoadException("No Graphics Device Service");
}
graphicsDevice = result.GraphicsDevice;
}
return graphicsDevice;
}
#endregion
#region Private Methods
private ContentReader GetContentReaderFromXnb(string originalAssetName, ref Stream stream, BinaryReader xnbReader, char platform, Action<IDisposable> recordDisposableObject)
{
byte version = xnbReader.ReadByte();
byte flags = xnbReader.ReadByte();
bool compressed = (flags & 0x80) != 0;
if (version != 5 && version != 4)
{
throw new ContentLoadException("Invalid XNB version");
}
// The next int32 is the length of the XNB file
int xnbLength = xnbReader.ReadInt32();
ContentReader reader;
if (compressed)
{
/* Decompress the XNB
* Thanks to ShinAli (https://bitbucket.org/alisci01/xnbdecompressor)
*/
int compressedSize = xnbLength - 14;
int decompressedSize = xnbReader.ReadInt32();
// This will replace the XNB stream at the end
MemoryStream decompressedStream = new MemoryStream(
new byte[decompressedSize],
0,
decompressedSize,
true,
true // This MUST be true! Readers may need GetBuffer()!
);
/* Read in the whole XNB file at once, into a temp buffer.
* For slow disks, the extra malloc is more than worth the
* performance improvement from not constantly fread()ing!
*/
MemoryStream compressedStream = new MemoryStream(
new byte[compressedSize],
0,
compressedSize,
true,
true
);
stream.Read(compressedStream.GetBuffer(), 0, compressedSize);
// Default window size for XNB encoded files is 64Kb (need 16 bits to represent it)
LzxDecoder dec = new LzxDecoder(16);
int decodedBytes = 0;
long pos = 0;
while (pos < compressedSize)
{
/* The compressed stream is separated into blocks that will
* decompress into 32kB or some other size if specified.
* Normal, 32kB output blocks will have a short indicating
* the size of the block before the block starts. Blocks
* that have a defined output will be preceded by a byte of
* value 0xFF (255), then a short indicating the output size
* and another for the block size. All shorts for these
* cases are encoded in big endian order.
*/
int hi = compressedStream.ReadByte();
int lo = compressedStream.ReadByte();
int block_size = (hi << 8) | lo;
int frame_size = 0x8000; // Frame size is 32kB by default
// Does this block define a frame size?
if (hi == 0xFF)
{
hi = lo;
lo = (byte) compressedStream.ReadByte();
frame_size = (hi << 8) | lo;
hi = (byte) compressedStream.ReadByte();
lo = (byte) compressedStream.ReadByte();
block_size = (hi << 8) | lo;
pos += 5;
}
else
{
pos += 2;
}
// Either says there is nothing to decode
if (block_size == 0 || frame_size == 0)
{
break;
}
dec.Decompress(compressedStream, block_size, decompressedStream, frame_size);
pos += block_size;
decodedBytes += frame_size;
/* Reset the position of the input just in case the bit
* buffer read in some unused bytes.
*/
compressedStream.Seek(pos, SeekOrigin.Begin);
}
if (decompressedStream.Position != decompressedSize)
{
throw new ContentLoadException(
"Decompression of " + originalAssetName + " failed. "
);
}
decompressedStream.Seek(0, SeekOrigin.Begin);
reader = new ContentReader(
this,
decompressedStream,
originalAssetName,
version,
platform,
recordDisposableObject
);
}
else
{
reader = new ContentReader(
this,
stream,
originalAssetName,
version,
platform,
recordDisposableObject
);
}
return reader;
}
private Stream CheckRawExtensions(string assetName, string[] extensions)
{
// Start with the fastest path...
string fileName = MonoGame.Utilities.FileHelpers.NormalizeFilePathSeparators(
Path.Combine(RootDirectoryFullPath, assetName)
);
if (File.Exists(fileName))
{
return TitleContainer.OpenStream(fileName);
}
foreach (string ext in extensions)
{
// Concatenate the file name with valid extensions.
string fileNamePlusExt = fileName + ext;
if (File.Exists(fileNamePlusExt))
{
return TitleContainer.OpenStream(fileNamePlusExt);
}
}
// If we got here, we need to try the slower path :(
fileName = MonoGame.Utilities.FileHelpers.NormalizeFilePathSeparators(
assetName
);
try
{
return OpenStream(fileName);
}
catch
{
foreach (string ext in extensions)
{
// Concatenate the file name with valid extensions.
string fileNamePlusExt = fileName + ext;
try
{
return OpenStream(fileNamePlusExt);
}
catch
{
continue;
}
}
}
// No idea what we're looking at here!
return null;
}
private Stream OpenStreamRaw<T>(string assetName)
{
if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Texture))
{
return CheckRawExtensions(assetName, texture2DExtensions);
}
else if (typeof(T) == typeof(TextureCube))
{
return CheckRawExtensions(assetName, textureCubeExtensions);
}
else if (typeof(T) == typeof(SoundEffect))
{
return CheckRawExtensions(assetName, soundEffectExtensions);
}
else if (typeof(T) == typeof(Effect))
{
return CheckRawExtensions(assetName, effectExtensions);
}
else if (typeof(T) == typeof(Song))
{
return CheckRawExtensions(assetName, SongReader.supportedExtensions);
}
else if (typeof(T) == typeof(Video))
{
return CheckRawExtensions(assetName, VideoReader.supportedExtensions);
}
return null;
}
#endregion
#region Private Static Methods
private static void AddContentManager(ContentManager contentManager)
{
lock (ContentManagerLock)
{
/* Check if the list contains this content manager already. Also take
* the opportunity to prune the list of any finalized content managers.
*/
bool contains = false;
for (int i = ContentManagers.Count - 1; i >= 0; i -= 1)
{
WeakReference contentRef = ContentManagers[i];
if (ReferenceEquals(contentRef.Target, contentManager))
{
contains = true;
}
if (!contentRef.IsAlive)
{
ContentManagers.RemoveAt(i);
}
}
if (!contains)
{
ContentManagers.Add(new WeakReference(contentManager));
}
}
}
private static void RemoveContentManager(ContentManager contentManager)
{
lock (ContentManagerLock)
{
/* Check if the list contains this content manager and remove it. Also
* take the opportunity to prune the list of any finalized content managers.
*/
for (int i = ContentManagers.Count - 1; i >= 0; i -= 1)
{
WeakReference contentRef = ContentManagers[i];
if (!contentRef.IsAlive || ReferenceEquals(contentRef.Target, contentManager))
{
ContentManagers.RemoveAt(i);
}
}
}
}
#endregion
}
}