6using Microsoft.Extensions.Logging;
14public sealed class Tilesheet : IDisposable
16 private SKImage? _atlasImage;
18 [Newtonsoft.Json.JsonIgnore]
internal DefinitionProvenance? DefinitionProvenance {
get;
set; }
24 internal SKImage? AtlasImage
31 return _atlasImage ??= SKImage.FromBitmap(
SkBitmap);
40 private Tilesheet() { }
42 internal Tilesheet(
string name, SKBitmap bitmap,
bool addDefaultRegion =
true)
45 SkBitmap = bitmap ??
throw new ArgumentNullException(nameof(bitmap));
51 internal Tilesheet(
string name, Stream stream,
bool addDefaultRegion =
true)
54 SKBitmap.Decode(stream) ?? throw new ArgumentException(
"Invalid image stream."),
59 internal Tilesheet(
string name,
string file,
bool addDefaultRegion =
true)
62 SKBitmap.Decode(file) ?? throw new ArgumentException($
"Invalid image file: {file}"),
68 internal Tilesheet(
AssetsFile resFile,
string entryName,
bool addDefaultRegion =
true)
70 ArgumentNullException.ThrowIfNull(resFile);
72 if (
string.IsNullOrWhiteSpace(entryName))
73 throw new ArgumentException(
"Asset entry name must be a non-empty string.", nameof(entryName));
77 using var assetStream = AssetIdentifier.Data
78 ??
throw new InvalidOperationException(
79 $
"Tilesheet asset '{entryName}' could not be loaded from AssetsFile '{resFile.FilePath}'. " +
80 "The asset entry does not exist or returned a null data stream.");
82 SkBitmap = SKBitmap.Decode(assetStream)
83 ??
throw new ArgumentException(
84 $
"Failed to decode tilesheet bitmap from asset '{entryName}' in AssetsFile '{resFile.FilePath}'. " +
85 "The asset data is corrupt or not a supported image format.");
100 internal Tilesheet(Tilesheet baseSheet,
string name,
string file)
102 ArgumentNullException.ThrowIfNull(baseSheet);
107 ??
throw new ArgumentException($
"Invalid image file: {file}");
112 foreach (var region
in baseSheet.Regions)
121 region.CollisionAdjust,
122 region.CollisionType);
124 for (
int y = 0; y < region.Rows; y++)
126 for (
int x = 0; x < region.Columns; x++)
128 if (region.TryGetFrameCollisionAdjustOverride(
131 out var frameCollisionAdjust))
133 copiedRegion.SetFrameCollisionAdjust(
136 frameCollisionAdjust);
139 if (region.TryGetFrameCollisionTypeOverride(
142 out var frameCollisionType))
144 copiedRegion.SetFrameCollisionType(
157 public SKBitmap
SkBitmap {
get;
private set; } =
null!;
167 public string Name {
get;
internal set; } =
string.Empty;
172 public List<TilesheetRegion>
Regions {
get;
private set; } =
new();
227 Spacing? overhangPixels =
null,
231 if (
string.IsNullOrWhiteSpace(name))
232 throw new ArgumentException(
"Region name must be a non-empty string.", nameof(name));
235 throw new ArgumentException($
"A tilesheet region named '{name}' already exists.", nameof(name));
244 overhangPixels ??
Spacing.None,
259 if (
string.IsNullOrWhiteSpace(name))
262 foreach (var region
in Regions)
264 if (
string.Equals(region.Name, name, StringComparison.OrdinalIgnoreCase))
324 public void ApplyMask(SKColor? maskColor =
null,
byte tolerance = 5)
327 throw new ArgumentException(
"Invalid bitmap.");
329 var targetColor = maskColor ?? SKColors.White;
335 InvalidateAtlasImage();
338 if (
SkBitmap.Info.AlphaType == SKAlphaType.Opaque)
340 var info =
new SKImageInfo(
346 var withAlpha =
new SKBitmap(info);
348 using (var canvas =
new SKCanvas(withAlpha))
358 SkBitmap.ApplyAlphaMask(targetColor, tolerance);
370 throw new ArgumentException(
"Invalid bitmap.");
373 InvalidateAtlasImage();
390 SKEncodedImageFormat format = SKEncodedImageFormat.Png,
394 throw new ArgumentException(
"Invalid bitmap.");
396 return SkBitmap.EncodeBitmapToBytes(format, quality);
412 string imageFilePath,
413 SKEncodedImageFormat format = SKEncodedImageFormat.Png,
417 throw new ObjectDisposedException(nameof(Tilesheet));
419 if (
string.IsNullOrWhiteSpace(imageFilePath))
421 throw new ArgumentException(
422 "Image file path must be a non-empty string.",
423 nameof(imageFilePath));
426 if (quality is < 0 or > 100)
428 throw new ArgumentOutOfRangeException(
431 "Image encoding quality must be between 0 and 100.");
436 throw new InvalidOperationException(
437 "Tilesheet does not contain a valid bitmap to persist.");
440 var fullPath = Path.GetFullPath(imageFilePath);
441 var directory = Path.GetDirectoryName(fullPath);
443 if (!
string.IsNullOrWhiteSpace(directory))
444 Directory.CreateDirectory(directory);
447 var imageBytes = sourceBitmap.EncodeBitmapToBytes(format, quality);
448 File.WriteAllBytes(fullPath, imageBytes);
461 public SKImage?
GetImage(
string regionName,
int x,
int y) =>
471 public SKBitmap?
GetBitmap(
string regionName,
int x,
int y) =>
478 public Dictionary<(
string regionName,
int x,
int y), SKBitmap>
GetAllBitmaps()
480 var tiles =
new Dictionary<(string regionName, int x, int y), SKBitmap>();
482 foreach (var region
in Regions)
484 foreach (var tile
in region.GetAllBitmaps())
485 tiles[(region.Name, tile.Key.x, tile.Key.y)] = tile.Value;
495 public Dictionary<(
string regionName,
int x,
int y), SKImage>
GetAllImages()
497 var tiles =
new Dictionary<(string regionName, int x, int y), SKImage>();
499 foreach (var region
in Regions)
501 foreach (var tile
in region.GetAllImages())
502 tiles[(region.Name, tile.Key.x, tile.Key.y)] = tile.Value;
514 ??
throw new ArgumentException(
515 $
"No tilesheet region named '{regionName}' exists.",
524 public Frame this[
string regionName,
int x,
int y] =>
534 private void BuildTileCache()
536 foreach (var region
in Regions)
537 region.BuildTileCache();
540 private void ClearTileCache()
542 foreach (var region
in Regions)
543 region.ClearTileCache();
546 private void InvalidateAtlasImage()
548 _atlasImage?.Dispose();
552 private void AddDefaultRegion(
553 Size? tileSize =
null,
556 Spacing? overhangPixels =
null,
561 TilesheetRegion.DefaultRegionName,
567 tileSize ?? Size.Empty,
570 overhangPixels ??
Spacing.None,
575 private bool _disposed;
583 GC.SuppressFinalize(
this);
586 private void Dispose(
bool disposing)
596 foreach (var region
in Regions)
601 InvalidateAtlasImage();
611 Engine.
Logger.LogError(ex,
"Error during Tilesheet Disposed event handling.");
Represents an identifier for a specific asset within a file, including its type and name.
Represents an asset file used by the engine, providing functionality to load, manage,...
Represents a rectangular region within a tilesheet that contains a grid of frames.
SKImage? GetImage(int x, int y)
Gets the cached image for the specified frame.
SKBitmap? GetBitmap(int x, int y)
Gets the cached bitmap for the specified frame.
static readonly string DefaultRegionName
The default name assigned to tilesheet regions when no name is specified.
Represents a tilesheet image and metadata for rendering tiles.
bool Premultiplied
Gets whether alpha premultiplication has been applied.
TilesheetRegion DefaultRegion
Gets the default tilesheet region.
TypedValueBag ValueBag
Gets or sets the custom typed values associated with this object.
void PersistImageToFile(string imageFilePath, SKEncodedImageFormat format=SKEncodedImageFormat.Png, int quality=100)
Persists this tilesheet's source image to a file and promotes the tilesheet from a runtime-only bitma...
AssetsFileIdentifier? AssetIdentifier
Gets the packed asset from which the image was loaded, if any.
Frame GetFrame(string regionName, int x, int y)
Creates a frame reference at the specified tile coordinates.
SKImage? GetImage(string regionName, int x, int y)
Gets the cached image for the specified frame.
Action< Tilesheet >? Disposed
Occurs after the object releases its resources.
void ApplyMask(SKColor? maskColor=null, byte tolerance=5)
Applies a color-key transparency mask and rebuilds the frame cache.
byte MaskTolerance
Gets the per-channel tolerance used for transparency masking.
void ApplyPremultiplyAlpha()
Premultiplies the bitmap alpha and rebuilds the frame cache.
Dictionary<(string regionName, int x, int y), SKImage > GetAllImages()
Collects the cached frame images indexed by their tile coordinates.
bool RemoveRegion(string name, bool dispose=true)
Removes the named tilesheet region and optionally disposes it.
SKBitmap? GetBitmap(string regionName, int x, int y)
Gets the cached bitmap for the specified frame.
void Dispose()
Releases the resources owned by this instance.
Dictionary<(string regionName, int x, int y), SKBitmap > GetAllBitmaps()
Collects the cached frame bitmaps indexed by their tile coordinates.
List< TilesheetRegion > Regions
Gets the named frame regions in the tilesheet.
SKColor? MaskColor
Gets the color used for transparency masking.
string Name
Gets the name.
byte[] ToByteArray(SKEncodedImageFormat format=SKEncodedImageFormat.Png, int quality=100)
Encodes the tilesheet bitmap using the requested image format and quality.
string ImageFilePath
Gets the loose source image path, when available.
SKBitmap? SkBitmapOriginal
Gets the source bitmap retained before masking or alpha conversion.
SKBitmap SkBitmap
Gets the current tilesheet bitmap used for rendering.
Frame GetFrame(int x, int y)
Creates a frame reference at the specified tile coordinates.
TilesheetRegion? GetRegion(string name)
Finds a tilesheet region by its case-insensitive name.
TilesheetRegion AddRegion(string name, Rectangle area, Size tileSize, Spacing? tilePadding=null, Spacing? regionMargin=null, Spacing? overhangPixels=null, CollisionAdjust? collisionAdjust=null, TileCollisionType collisionType=TileCollisionType.None)
Adds a region with the supplied default collision adjustment and collision type.
Represents the core game engine singleton responsible for managing the main update loop,...
static ILogger< Engine > Logger
Gets the logger instance used by the engine for diagnostic and informational messages.
A flexible, strongly-typed value container intended for runtime-attached metadata and ephemeral engin...
AssetTypes
Defines the types of assets that can be stored and managed by the engine.
record struct Spacing([property:JsonProperty("left")] int Left, [property:JsonProperty("top")] int Top, [property:JsonProperty("right")] int Right, [property:JsonProperty("bottom")] int Bottom)
Represents dimensions in pixels when spacing Tilesheets.
TileCollisionType
Defines the default collision behavior associated with a tilesheet region, frame, or runtime tile.
Represents the source Tilesheet and its coordinates to render on a destination.
Per-edge inset amounts applied to visual bounds to produce a collision rectangle.
static readonly CollisionAdjust None
Represents an adjustment with no pixel offsets.