Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
AssetsFile.cs
1using ICSharpCode.SharpZipLib.Zip;
2using Microsoft.Extensions.Logging;
3using Newtonsoft.Json;
4
5namespace Gondwana.Assets;
6
16[JsonObject(IsReference = true)]
17public sealed class AssetsFile : IDisposable
18{
19 private static readonly List<AssetsFile> _allAssetsFiles = new();
20
24 public static IReadOnlyList<AssetsFile> AllAssetsFiles => _allAssetsFiles.AsReadOnly();
25
29 public static void ClearAll()
30 {
31 foreach (var assetFile in _allAssetsFiles.ToList())
32 assetFile.Dispose();
33 }
34
35 private ZipFile? _zipFile;
36
37 // In-memory source of truth.
38 // Each entry stores its complete bytes independently of any live ZipFile handle.
39 private readonly Dictionary<AssetsFileEntry, byte[]> _zipEntries = new();
40
41 private bool _isLoaded;
42
50 public static void Validate(string path, string? password = null, bool testData = true)
51 {
52 using var archive = new ZipFile(File.OpenRead(path));
53 archive.Password = password;
54 var keys = new HashSet<AssetsFileEntry>();
55
56 foreach (ZipEntry entry in archive)
57 {
58 if (!entry.IsFile)
59 continue;
60
61 var key = AssetsFileEntry.FromString(entry.Name);
62
63 if (key is null || !Enum.IsDefined(key.AssetType) || string.IsNullOrWhiteSpace(key.AssetName))
64 throw new InvalidDataException($"Invalid bundle entry key: {entry.Name}");
65
66 if (!keys.Add(key))
67 throw new InvalidDataException($"Duplicate bundle entry key: {entry.Name}");
68 }
69
70 if (!archive.TestArchive(testData))
71 throw new InvalidDataException("Bundle integrity check failed. Check the password and archive contents.");
72 }
73
74 [JsonConstructor]
75 private AssetsFile() : this(register: true)
76 {
77 }
78
79 private AssetsFile(bool register)
80 {
81 if (register)
82 _allAssetsFiles.Add(this);
83 }
84
93 public static AssetsFile LoadOrCreate(string path, string? password = null, bool encrypt = false)
94 => LoadOrCreate(
95 path,
96 password,
97 encrypt,
98 register: true);
99
109 public static AssetsFile LoadOrCreate(
110 string path,
111 string? password,
112 bool encrypt,
113 bool register)
114 {
115 if (string.IsNullOrWhiteSpace(path))
116 throw new ArgumentException("path cannot be null or empty.", nameof(path));
117
118 var assetFile = new AssetsFile(register)
119 {
120 FilePath = path,
121 Password = password,
122 UseEncryption = encrypt
123 };
124
125 try
126 {
127 if (File.Exists(path))
128 assetFile.LoadZip();
129 else
130 assetFile._isLoaded = true;
131
132 return assetFile;
133 }
134 catch
135 {
136 assetFile.Dispose();
137 throw;
138 }
139 }
140
153 public static AssetsFile Load(Stream stream, string? password = null, bool register = true)
154 => Load(
155 stream,
156 password,
157 register,
158 sourcePath: null);
159
166 public static AssetsFile Load(
167 Stream stream,
168 string? password,
169 bool register,
170 string? sourcePath)
171 => Load(
172 stream,
173 password,
174 register,
175 sourcePath,
176 limits: null);
177
185 public static AssetsFile Load(
186 Stream stream,
187 string? password,
188 bool register,
189 string? sourcePath,
190 AssetsFileReadLimits? limits)
191 {
192 ArgumentNullException.ThrowIfNull(stream);
193
194 if (!stream.CanRead)
195 throw new ArgumentException("Stream must be readable.", nameof(stream));
196
197 var assetFile = new AssetsFile(register)
198 {
199 Password = password,
200 SourcePath = string.IsNullOrWhiteSpace(sourcePath) ? null : sourcePath
201 };
202
203 try
204 {
205 assetFile.LoadZip(stream, limits);
206 return assetFile;
207 }
208 catch
209 {
210 assetFile.Dispose();
211 throw;
212 }
213 }
214
218 [JsonProperty]
219 public string FilePath { get; private set; } = string.Empty;
220
224 [JsonProperty]
225 public string? Password { get; private set; }
226
230 [JsonProperty]
231 public bool UseEncryption { get; private set; }
232
235 [JsonIgnore]
236 public string? SourcePath
237 {
238 get => string.IsNullOrWhiteSpace(FilePath) ? _sourcePath : FilePath;
239 private set => _sourcePath = value;
240 }
241
242 private string? _sourcePath;
243
244 private void EnsureLoaded()
245 {
246 if (!_isLoaded)
247 LoadZip();
248 }
249
250 private void LoadZip()
251 {
252 if (_isLoaded)
253 return;
254
255 if (!File.Exists(FilePath))
256 {
257 _isLoaded = true;
258 return;
259 }
260
261 using var stream = File.OpenRead(FilePath);
262 LoadZip(stream);
263 }
264
265 private void LoadZip(Stream stream, AssetsFileReadLimits? limits = null)
266 {
267 if (_isLoaded)
268 return;
269
270 if (limits is not null && !stream.CanSeek)
271 throw new ArgumentException("Bounded archive reads require a seekable stream.", nameof(stream));
272
273 try
274 {
275 Engine.Logger.LogInformation("Loading assets file.");
276
277 _zipFile?.Close();
278 _zipFile = null;
279 _zipEntries.Clear();
280
281 // SharpZipLib's ZipFile expects seekable input. Buffering here also gives
282 // stream-loaded GAFs the same lifetime semantics as path-loaded GAFs:
283 // the source stream is needed only for the duration of this call.
284 MemoryStream? bufferedStream = stream.CanSeek ? null : new MemoryStream();
285 Stream archiveStream = stream;
286
287 if (bufferedStream is not null)
288 {
289 stream.CopyTo(bufferedStream);
290 bufferedStream.Position = 0;
291 archiveStream = bufferedStream;
292 }
293
294 _zipFile = new ZipFile(archiveStream) { IsStreamOwner = false };
295 limits?.Validate(_zipFile);
296 long totalBytes = 0;
297 byte[]? copyBuffer = limits is null ? null : new byte[81920];
298
299 if (!string.IsNullOrEmpty(Password))
300 _zipFile.Password = Password;
301
302 // Force decryption on the first entry so a bad password fails early.
303 var testEntry = _zipFile.Cast<ZipEntry>().FirstOrDefault(e => e.IsFile);
304
305 if (testEntry != null)
306 {
307 using var testStream = _zipFile.GetInputStream(testEntry);
308 testStream.ReadByte();
309 }
310
311 foreach (ZipEntry entry in _zipFile)
312 {
313 if (!entry.IsFile)
314 continue;
315
316 // Preserve the loaded archive's encryption policy when tooling stages a replacement.
317 if (string.IsNullOrEmpty(FilePath))
318 UseEncryption |= entry.IsCrypted;
319
320 var key = AssetsFileEntry.FromString(entry.Name);
321
322 if (key == null)
323 {
324 Engine.Logger.LogWarning("Invalid entry in assets file: {EntryName}", entry.Name);
325 continue;
326 }
327
328 using var entryStream = _zipFile.GetInputStream(entry);
329 using var ms = new MemoryStream();
330
331 if (limits is null)
332 entryStream.CopyTo(ms);
333 else
334 {
335 int count;
336
337 while ((count = entryStream.Read(copyBuffer!, 0, copyBuffer!.Length)) > 0)
338 {
339 if (count > limits.MaximumEntryBytes - ms.Length ||
340 count > limits.MaximumTotalBytes - totalBytes || count > entry.Size - ms.Length)
341 throw new InvalidDataException($"Archive entry '{entry.Name}' exceeds the uncompressed read limits.");
342
343 ms.Write(copyBuffer!, 0, count);
344 totalBytes += count;
345 }
346 }
347
348 _zipEntries[key] = ms.ToArray();
349 }
350
351 _isLoaded = true;
352 }
353 catch (ZipException zex)
354 {
355 Engine.Logger.LogError(zex, "Decryption failed — check password or file integrity.");
356 throw;
357 }
358 catch (Exception ex)
359 {
360 Engine.Logger.LogError(ex, "Failed to load asset file.");
361 throw;
362 }
363 finally
364 {
365 // Once contents are buffered, no need to keep the archive or source stream open.
366 _zipFile?.Close();
367 _zipFile = null;
368 }
369 }
370
381 public void Add(AssetTypes type, string name, Func<Stream> streamFactory)
382 {
383 if (streamFactory == null)
384 throw new ArgumentNullException(nameof(streamFactory));
385
386 EnsureLoaded();
387
388 using var stream = streamFactory();
389 Add(type, name, stream);
390 }
391
401 public void Add(AssetTypes type, string filePath, string? name = null)
402 {
403 if (string.IsNullOrWhiteSpace(filePath))
404 throw new ArgumentException("File path cannot be null or empty.", nameof(filePath));
405
406 var nameToUse = name ?? Path.GetFileName(filePath);
407 using var stream = File.OpenRead(filePath);
408 Add(type, nameToUse, stream);
409 }
410
423 public void Add(AssetTypes type, string name, Stream stream)
424 {
425 if (stream == null)
426 throw new ArgumentNullException(nameof(stream));
427
428 if (string.IsNullOrWhiteSpace(name))
429 throw new ArgumentException("Asset name cannot be null or empty.", nameof(name));
430
431 if (!stream.CanRead)
432 throw new ArgumentException("Stream must be readable.", nameof(stream));
433
434 EnsureLoaded();
435
436 var key = new AssetsFileEntry
437 {
438 AssetType = type,
439 AssetName = name
440 };
441
442 using var ms = new MemoryStream();
443 stream.CopyTo(ms);
444 _zipEntries[key] = ms.ToArray();
445 }
446
452 public void Remove(AssetTypes type, string name)
453 {
454 if (string.IsNullOrWhiteSpace(name))
455 throw new ArgumentException("Asset name cannot be null or empty.", nameof(name));
456
457 EnsureLoaded();
458
459 var key = new AssetsFileEntry
460 {
461 AssetType = type,
462 AssetName = name
463 };
464
465 _zipEntries.Remove(key);
466 }
467
474 public Stream? this[AssetTypes type, string name] => Get(type, name);
475
487 public Stream? Get(AssetTypes type, string name)
488 {
489 if (string.IsNullOrWhiteSpace(name))
490 return null;
491
492 EnsureLoaded();
493
494 var exactKey = new AssetsFileEntry
495 {
496 AssetType = type,
497 AssetName = name
498 };
499
500 if (_zipEntries.TryGetValue(exactKey, out var exactData))
501 return new MemoryStream(exactData, writable: false);
502
503 var requestedBaseName = Path.GetFileNameWithoutExtension(name);
504
505 var match = _zipEntries.Keys.FirstOrDefault(k =>
506 k.AssetType == type &&
507 string.Equals(
508 Path.GetFileNameWithoutExtension(k.AssetName),
509 requestedBaseName,
510 StringComparison.OrdinalIgnoreCase));
511
512 return match != null && _zipEntries.TryGetValue(match, out var fallbackData)
513 ? new MemoryStream(fallbackData, writable: false)
514 : null;
515 }
516
521 public IEnumerable<AssetsFileEntry> GetAllEntries()
522 {
523 EnsureLoaded();
524 return _zipEntries.Keys.ToList();
525 }
526
530 public void Save()
531 {
532 EnsureLoaded();
533
534 _zipFile?.Close();
535 _zipFile = null;
536 _isLoaded = false;
537
538 using (var fs = File.Create(FilePath))
539 using (var zipStream = new ZipOutputStream(fs) { IsStreamOwner = true })
540 {
541 if (!string.IsNullOrEmpty(Password))
542 zipStream.Password = Password;
543
544 foreach (var (key, data) in _zipEntries)
545 {
546 var entry = new ZipEntry(key.ToString())
547 {
548 DateTime = DateTime.Now
549 };
550
551 if (UseEncryption && !string.IsNullOrEmpty(Password))
552 entry.AESKeySize = 256;
553
554 zipStream.PutNextEntry(entry);
555
556 using var inputStream = new MemoryStream(data, writable: false);
557 inputStream.CopyTo(zipStream);
558 zipStream.CloseEntry();
559 }
560
561 zipStream.Finish();
562 }
563
564 Engine.Logger.LogInformation(
565 "Assets file saved (Encrypted: {Encrypted}).",
567
568 // Keep the in-memory copy as the source of truth.
569 _isLoaded = true;
570 }
571
575 public void Dispose()
576 {
577 _zipFile?.Close();
578 _zipFile = null;
579 _isLoaded = false;
580 _zipEntries.Clear();
581 _allAssetsFiles.Remove(this);
582 }
583}
Represents an entry for an engine asset file, including its type and name.
Represents an asset file used by the engine, providing functionality to load, manage,...
Definition AssetsFile.cs:18
static void ClearAll()
Releases all assets held by the application and clears the internal collection of asset files.
Definition AssetsFile.cs:29
void Save()
Saves the current set of entries to a zip file at the specified file path.
string FilePath
Gets the file path associated with the current instance.
static void Validate(string path, string? password=null, bool testData=true)
Strictly validates an existing bundle's entry keys and archive integrity. Unlike runtime loading,...
Definition AssetsFile.cs:50
static AssetsFile Load(Stream stream, string? password, bool register, string? sourcePath)
Loads a buffered archive with an optional reconstructible source path.
string? SourcePath
Gets the archive's reconstructible origin, including an optional stream origin.
void Add(AssetTypes type, string name, Stream stream)
Adds an asset file entry to the collection with the specified type, name, and source stream.
string? Password
Gets the password associated with the current instance.
static AssetsFile Load(Stream stream, string? password, bool register, string? sourcePath, AssetsFileReadLimits? limits)
Loads an archive with optional bounds checked before and during decompression.
void Dispose()
Releases all resources used by the AssetsFile instance.
static IReadOnlyList< AssetsFile > AllAssetsFiles
Gets a read-only list of registered AssetsFile instances.
Definition AssetsFile.cs:24
static AssetsFile LoadOrCreate(string path, string? password=null, bool encrypt=false)
Loads an existing asset file from the specified path or creates a new one if the file does not exist.
void Add(AssetTypes type, string filePath, string? name=null)
Adds an asset file to the engine with the specified type and file path.
bool UseEncryption
Gets a value indicating whether encryption is enabled for the current operation.
static AssetsFile Load(Stream stream, string? password=null, bool register=true)
Loads an existing asset file from a readable stream.
static AssetsFile LoadOrCreate(string path, string? password, bool encrypt, bool register)
Loads or creates an asset file, optionally without adding it to the runtime collection....
void Remove(AssetTypes type, string name)
Removes the specified asset file entry from the collection.
Stream? Get(AssetTypes type, string name)
Retrieves a stream for the specified asset type and name.
IEnumerable< AssetsFileEntry > GetAllEntries()
Retrieves all entries from the asset file.
void Add(AssetTypes type, string name, Func< Stream > streamFactory)
Adds an asset file entry to the collection with the specified type, name, and stream factory.
Represents the core game engine singleton responsible for managing the main update loop,...
Definition Engine.cs:36
static ILogger< Engine > Logger
Gets the logger instance used by the engine for diagnostic and informational messages.
Definition Engine.cs:59
record AssetsFileReadLimits(long MaximumEntryBytes, long MaximumTotalBytes, int MaximumEntries=10_000)
Optional bounds for buffering untrusted archives. Normal runtime loads remain unrestricted.
AssetTypes
Defines the types of assets that can be stored and managed by the engine.
Definition AssetTypes.cs:8