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
Tile.cs
1using System.Drawing;
2using System.Runtime.Serialization;
9using Newtonsoft.Json;
10
11namespace Gondwana.Drawing;
12
17[JsonObject(IsReference = true)]
18public abstract class Tile : IDrawable, ICollisionEntity, IComparable<Tile>, IDisposable
19{
20 #region static members
21
25 public static List<Tile> TilesAnimating { get; } = new();
26
27 #endregion static members
28
29 #region fields
30
34 protected internal int zOrder = 0;
35
39 protected internal bool visible;
40
44 protected internal Frame frame;
45
49 protected internal bool enableFog = false;
50
54 protected internal Animator? animator;
55
59 protected bool pauseAnimation;
60
64 protected ICollider? _collider;
65
66 private CollisionAdjust _adjustCollisionArea = CollisionAdjust.None;
67 private bool _adjustCollisionAreaByFrame;
68 private bool _hasAssignedFrame;
69 private bool _collisionAdjustExplicitlySet;
70 private TileCollisionType _collisionType = TileCollisionType.None;
71 private bool _collisionTypeByFrame;
72 private bool _collisionTypeExplicitlySet;
73 private bool _collisionsEnabled;
74 private string? _collisionProfileName;
75 private long _sortKeyRenderPassId;
76 private TileSortKey _sortKey;
77
78 #endregion fields
79
80 #region abstract properties
81
85 public abstract bool IsPositionFixed { get; }
86
90 public abstract Rectangle DrawLocationWorld { get; }
91
95 public abstract PointF SceneLayerCoordinates { get; }
96
100 public abstract SceneLayer SceneLayer { get; }
101
102 #endregion abstract properties
103
104 #region IDrawable members
105
109 [JsonProperty]
110 public Guid Id { get; internal set; } = Guid.NewGuid();
111
115 [JsonProperty]
116 public string? Nickname { get; set; }
117
121 [JsonProperty]
122 public virtual bool Visible
123 {
124 get => visible;
125 set
126 {
127 visible = value;
128 SceneLayer.RefreshQueue.AddWorldRect(DrawLocationWorld);
129 }
130 }
131
135 [JsonProperty]
136 public virtual int ZOrder
137 {
138 get => zOrder;
139 set
140 {
141 zOrder = value;
142 SceneLayer.RefreshQueue.AddWorldRect(DrawLocationWorld);
143 }
144 }
145
151 public virtual RectangleF GetDrawLocationScreen(View view) =>
152 view.WorldRectToScreenRect(SceneLayer, DrawLocationWorld);
153
159 public virtual RectangleF GetCollisionAreaScreen(View view) =>
160 view.WorldRectToScreenRect(SceneLayer, CollisionArea);
161
167 public virtual void Draw(BackbufferBase backbuffer, RectangleF destRectScreen) =>
168 backbuffer.DrawTileFrame(this, destRectScreen);
169
170 #endregion IDrawable members
171
175 [JsonIgnore]
176 public virtual Spacing Overhang => frame.Overhang;
177
183 [JsonProperty]
184 public virtual Frame CurrentFrame
185 {
186 get => frame;
187 set
188 {
189 // Animation may change tile size, so bitmap rendering must invalidate
190 // the old and new bounds. GPU rendering redraws the full frame and does
191 // not consume RefreshQueue, so avoid calculating those bounds entirely.
192 bool usesDirtyRegionRendering =
193 SceneLayer.Scene?.UsesDirtyRegionRendering ?? true;
194
195 if (usesDirtyRegionRendering)
196 SceneLayer.RefreshQueue.AddWorldRect(DrawLocationWorld);
197
198 frame = value;
199
200 bool hasFrame = value.Tilesheet is not null;
201
202 if (hasFrame &&
203 (_adjustCollisionAreaByFrame ||
204 (!_hasAssignedFrame && !_collisionAdjustExplicitlySet)))
205 {
206 SetCollisionAdjustFromFrame(value);
207 }
208
209 if (hasFrame &&
210 (_collisionTypeByFrame ||
211 (!_hasAssignedFrame && !_collisionTypeExplicitlySet)))
212 {
213 SetCollisionTypeFromFrame(value);
214 }
215
216 _hasAssignedFrame = hasFrame;
217
218 if (usesDirtyRegionRendering)
219 SceneLayer.RefreshQueue.AddWorldRect(DrawLocationWorld);
220 }
221 }
222
226 [JsonIgnore]
227 public virtual Animator TileAnimator => animator!;
228
232 [JsonIgnore]
233 public virtual bool PauseAnimation { get; set; }
234
238 [JsonIgnore]
239 public virtual ICollider? Collider => _collider;
240
244 [JsonIgnore]
245 public virtual Rectangle CollisionArea =>
247
251 [JsonProperty]
252 public virtual bool EnableFog
253 {
254 get => enableFog;
255 set
256 {
257 enableFog = value;
258 SceneLayer.RefreshQueue.AddWorldRect(DrawLocationWorld);
259 }
260 }
261
265 [JsonIgnore]
266 public virtual Point[] OutlinePointsWorld =>
267 SceneLayer.CoordinateSystem.GetPolygonPts(this, false);
268
277 [JsonProperty]
278 public virtual bool AdjustCollisionAreaByFrame
279 {
280 get => _adjustCollisionAreaByFrame;
281 set
282 {
283 _adjustCollisionAreaByFrame = value;
284
285 if (value && frame.Tilesheet is not null)
286 SetCollisionAdjustFromFrame(frame);
287 }
288 }
289
293 [JsonProperty]
295 {
296 get => _adjustCollisionArea;
297 set
298 {
299 _adjustCollisionArea = value;
300 _collisionAdjustExplicitlySet = true;
301 }
302 }
303
308 [JsonProperty]
310 {
311 get => _collisionType;
312 set
313 {
314 _collisionTypeExplicitlySet = true;
315 SetCollisionTypeCore(value);
316 }
317 }
318
323 [JsonProperty]
324 public virtual bool CollisionTypeByFrame
325 {
326 get => _collisionTypeByFrame;
327 set
328 {
329 _collisionTypeByFrame = value;
330
331 if (value && frame.Tilesheet is not null)
332 SetCollisionTypeFromFrame(frame);
333 }
334 }
335
339 [JsonProperty]
340 public string? CollisionProfileName
341 {
342 get => _collisionProfileName;
343 private set => _collisionProfileName = value;
344 }
345
349 [JsonProperty]
351 {
352 get => _collisionsEnabled;
353 set
354 {
355 _collisionTypeExplicitlySet = true;
356
357 if (value)
358 {
359 var enabledType = _collisionType == TileCollisionType.None
363 : _collisionType;
364
365 SetCollisionTypeCore(enabledType);
366 }
367 else
368 {
369 SetCollisionTypeCore(TileCollisionType.None);
370 }
371 }
372 }
373
377 [JsonIgnore]
378 public TypedValueBag ValueBag { get; } = new();
379
386 public void SetCollisionProfile(string profileName)
387 {
388 if (string.IsNullOrWhiteSpace(profileName))
389 throw new ArgumentException("Collision profile name cannot be empty.", nameof(profileName));
390
391 var scene = SceneLayer.Scene;
392
393 if (scene is not null)
394 {
395 var profile = scene.CollisionProfiles.Get(profileName);
396 _ = profile.ResolveCollisionGroup(scene.CollisionGroups);
397 _ = profile.ResolveCollidesWith(scene.CollisionGroups);
398 }
399
400 CollisionProfileName = profileName;
401 ApplyCollisionProfileToCollider();
402 }
403
408 internal void RefreshCollisionProfile() => ApplyCollisionProfileToCollider();
409
414 protected void CopyCollisionSettingsFrom(Tile source)
415 {
416 ArgumentNullException.ThrowIfNull(source);
417
418 _adjustCollisionArea = source._adjustCollisionArea;
419 _adjustCollisionAreaByFrame = source._adjustCollisionAreaByFrame;
420 _hasAssignedFrame = frame.Tilesheet is not null;
421 _collisionAdjustExplicitlySet = source._collisionAdjustExplicitlySet;
422 _collisionType = source._collisionType;
423 _collisionTypeByFrame = source._collisionTypeByFrame;
424 _collisionTypeExplicitlySet = source._collisionTypeExplicitlySet;
425 _collisionsEnabled = source._collisionsEnabled;
426 _collisionProfileName = source._collisionProfileName;
427 }
428
429 private void SetCollisionAdjustFromFrame(Frame value)
430 {
431 // Deliberately bypass the public setter: following a frame should not mark
432 // the adjustment as an explicit tile-level override.
433 _adjustCollisionArea = value.CollisionAdjust;
434 }
435
436 private void SetCollisionTypeFromFrame(Frame value)
437 {
438 // Deliberately bypass the public setter: following a frame should not mark
439 // the collision type as an explicit tile-level override.
440 SetCollisionTypeCore(value.CollisionType);
441 }
442
443 private void SetCollisionTypeCore(TileCollisionType collisionType)
444 {
445 _collisionType = collisionType;
446 ApplyCollisionTypeToCollider();
447 SetCollisionsEnabledCore(collisionType != TileCollisionType.None);
448 }
449
450 private void ApplyCollisionTypeToCollider()
451 {
452 if (_collider is null)
453 return;
454
455 switch (_collisionType)
456 {
457 case TileCollisionType.Blocking:
458 _collider.ResponseType = CollisionResponseType.Solid;
459 break;
460 case TileCollisionType.Trigger:
461 _collider.ResponseType = CollisionResponseType.Trigger;
462 break;
463 }
464 }
465
466 private void SetCollisionsEnabledCore(bool enabled)
467 {
468 _collisionsEnabled = enabled;
469 SynchronizeColliderRegistration();
470 }
471
472 private void SynchronizeColliderRegistration()
473 {
474 if (_collider is null)
475 return;
476
477 if (_collisionsEnabled)
478 SceneLayer.ColliderRegistry.Register(_collider);
479 else
480 SceneLayer.ColliderRegistry.Unregister(_collider);
481 }
482
483 private void ApplyCollisionProfileToCollider()
484 {
485 if (_collider is null || string.IsNullOrWhiteSpace(_collisionProfileName))
486 return;
487
488 var scene = SceneLayer.Scene;
489
490 if (scene is null)
491 return;
492
493 var profile = scene.CollisionProfiles.Get(_collisionProfileName);
494 _collider.CollisionGroup = profile.ResolveCollisionGroup(scene.CollisionGroups);
495 _collider.CollidesWith = profile.ResolveCollidesWith(scene.CollisionGroups);
496 }
497
502 protected void DetachCollider()
503 {
504 if (_collider is null)
505 return;
506
507 SceneLayer.ColliderRegistry.Unregister(_collider);
508 _collider = null;
509 }
510
516 protected void AttachCollider(ICollider collider)
517 {
518 ArgumentNullException.ThrowIfNull(collider);
519
520 if (_collider is not null)
521 SceneLayer.ColliderRegistry.Unregister(_collider);
522
523 _collider = collider;
524 ApplyCollisionProfileToCollider();
525 ApplyCollisionTypeToCollider();
526 SynchronizeColliderRegistration();
527 }
528
529 [OnDeserialized]
530 private void OnTileDeserialized(StreamingContext context)
531 {
532 _hasAssignedFrame = frame.Tilesheet is not null;
533
534 if (_adjustCollisionAreaByFrame && _hasAssignedFrame)
535 SetCollisionAdjustFromFrame(frame);
536
537 if (_collisionTypeByFrame && _hasAssignedFrame)
538 SetCollisionTypeFromFrame(frame);
539 }
540
541 #region IComparable<Tile> Members
542
548 public int CompareTo(Tile? tile)
549 {
550 if (tile is null)
551 return -1;
552
553 var thisKey = GetSortKeyForCompare();
554 var tileKey = tile.GetSortKeyForCompare();
555
556 if (thisKey.IsPositionFixed && !tileKey.IsPositionFixed)
557 return -1;
558
559 if (!thisKey.IsPositionFixed && tileKey.IsPositionFixed)
560 return 1;
561
562 return (thisKey.Location, thisKey.ZOrder, thisKey.SceneLayerX)
563 .CompareTo((tileKey.Location, tileKey.ZOrder, tileKey.SceneLayerX));
564 }
565
566 private TileSortKey GetSortKeyForCompare()
567 {
568 var renderContext = RenderContext.Current;
569
570 // Outside an active render pass preserve the historical live comparison
571 // semantics. During rendering, capture the expensive virtual/property values
572 // once per tile and reuse them for every comparison in this sort pass.
573 if (renderContext is null)
574 return CaptureSortKey();
575
576 long renderPassId = renderContext.PassId;
577
578 if (_sortKeyRenderPassId != renderPassId)
579 {
580 _sortKey = CaptureSortKey();
581 _sortKeyRenderPassId = renderPassId;
582 }
583
584 return _sortKey;
585 }
586
587 private TileSortKey CaptureSortKey()
588 {
589 bool isPositionFixed = IsPositionFixed;
590 Rectangle drawLocationWorld = DrawLocationWorld;
591 Spacing overhang = Overhang;
592
593 float location = isPositionFixed
594 ? drawLocationWorld.Top + overhang.Top
595 : drawLocationWorld.Bottom - overhang.Bottom - 1;
596
597 return new TileSortKey(
598 isPositionFixed,
599 location,
600 zOrder,
602 }
603
604 private readonly record struct TileSortKey(
605 bool IsPositionFixed,
606 float Location,
607 int ZOrder,
608 float SceneLayerX);
609
610 #endregion IComparable<Tile> Members
611
612 #region IDisposable Members
613
617 public virtual void Dispose()
618 {
619 if (TilesAnimating.IndexOf(this) != -1)
620 TilesAnimating.Remove(this);
621
622 animator?.Dispose();
623
624 if (_collider is not null)
625 SceneLayer.ColliderRegistry.Unregister(_collider);
626
627 _collider = null;
628 GC.SuppressFinalize(this);
629 }
630
631 #endregion IDisposable Members
632}
Manages animation playback for a Tile, controlling animation cycles, frame timing,...
Definition Animator.cs:9
Represents an abstract base class for drawable tiles in the Gondwana engine. Provides core functional...
Definition Tile.cs:19
bool CollisionsEnabled
Gets or sets whether this tile participates in collision detection.
Definition Tile.cs:351
virtual bool EnableFog
Gets or sets whether scene-layer fog applies to this tile.
Definition Tile.cs:253
virtual bool Visible
Gets or sets whether this drawable is visible.
Definition Tile.cs:123
virtual RectangleF GetCollisionAreaScreen(View view)
Transforms the collision bounds into screen pixels for the specified view.
virtual Frame CurrentFrame
Gets or sets the current frame. The initial frame supplies the tile's default collision adjustment an...
Definition Tile.cs:185
virtual RectangleF GetDrawLocationScreen(View view)
Transforms the drawable bounds into screen pixels for the specified view.
void AttachCollider(ICollider collider)
Attaches this tile's collider and applies any collision state that was set before the collider became...
Definition Tile.cs:516
virtual Rectangle CollisionArea
Gets the effective collision area in world coordinates.
Definition Tile.cs:245
SceneLayer SceneLayer
Gets the scene layer that owns this tile.
Definition Tile.cs:100
virtual void Draw(BackbufferBase backbuffer, RectangleF destRectScreen)
Draws the current content into the backbuffer at the supplied screen-pixel bounds.
virtual ? ICollider Collider
Gets the collision shape associated with this tile.
Definition Tile.cs:239
bool pauseAnimation
The pause animation.
Definition Tile.cs:59
void CopyCollisionSettingsFrom(Tile source)
Copies collision behavior, profile, and effective frame metadata from another tile.
Definition Tile.cs:414
string? Nickname
Gets or sets the optional lookup name.
Definition Tile.cs:116
virtual Point[] OutlinePointsWorld
Gets the tile outline vertices in world pixels.
Definition Tile.cs:266
virtual TileCollisionType CollisionType
Gets or sets the tile's collision behavior. This is initialized from the first assigned frame and may...
Definition Tile.cs:310
virtual void Dispose()
Releases the resources owned by this instance.
Definition Tile.cs:617
virtual bool AdjustCollisionAreaByFrame
Gets or sets whether frame changes replace the tile's collision adjustment with the newly selected fr...
Definition Tile.cs:279
virtual bool PauseAnimation
Gets or sets whether animation is paused.
Definition Tile.cs:233
virtual int ZOrder
Gets or sets the drawing order within the layer.
Definition Tile.cs:137
void SetCollisionProfile(string profileName)
Applies a named profile from this tile's parent scene. If the layer has not yet been attached to a sc...
Definition Tile.cs:386
TypedValueBag ValueBag
Gets the custom typed values associated with this object.
Definition Tile.cs:378
int CompareTo(Tile? tile)
Compares this tile with another tile using their render ordering.
Definition Tile.cs:548
Rectangle DrawLocationWorld
Gets the tile drawing bounds in world pixels.
Definition Tile.cs:90
virtual Spacing Overhang
Gets the current frame's visual overhang beyond its tile bounds.
Definition Tile.cs:176
void DetachCollider()
Detaches the current collider from its scene-layer registry without otherwise changing this tile's se...
Definition Tile.cs:502
string? CollisionProfileName
Gets the scene-level collision profile currently associated with this tile.
Definition Tile.cs:341
ICollider? _collider
The collider.
Definition Tile.cs:64
virtual Animator TileAnimator
Gets the animator associated with this tile.
Definition Tile.cs:227
static List< Tile > TilesAnimating
Gets the collection of all tiles that are currently animating in the scene.
Definition Tile.cs:25
virtual CollisionAdjust AdjustCollisionArea
Gets or sets the collision adjustment used to derive CollisionArea.
Definition Tile.cs:295
Guid Id
Gets the unique identifier.
Definition Tile.cs:110
virtual bool CollisionTypeByFrame
Gets or sets whether frame changes replace this tile's collision type with the newly selected frame's...
Definition Tile.cs:325
bool IsPositionFixed
Gets whether the tile occupies a fixed position in its layer.
Definition Tile.cs:85
PointF SceneLayerCoordinates
Gets the position in scene-layer grid coordinates.
Definition Tile.cs:95
Represents a base class for managing a graphical backbuffer, and is the in-memory surface where rende...
Represents a rendered view of a scene, combining a camera position with a viewport configuration to c...
Definition View.cs:14
A flexible, strongly-typed value container intended for runtime-attached metadata and ephemeral engin...
Represents an object that can be drawn on a visual surface, with properties for visibility and stacki...
Definition IDrawable.cs:14
World-space axis-aligned collider used by the collision system.
Definition ICollider.cs:7
Represents an entity that participates in the collision system and has a defined collision area.
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.
Definition Spacing.cs:12
CollisionResponseType
Defines how a collider responds to collisions with other colliders.
@ Trigger
Trigger collision response that reports overlaps without applying push-out or blocking movement.
TileCollisionType
Defines the default collision behavior associated with a tilesheet region, frame, or runtime tile.
@ Blocking
Collision is enabled and overlapping solid colliders block movement.
@ Trigger
Collision is enabled and overlaps are reported without blocking movement.
Represents the source Tilesheet and its coordinates to render on a destination.
Definition Frame.cs:12
CollisionAdjust CollisionAdjust
Gets or sets the collision adjustment associated with this frame's region coordinates.
Definition Frame.cs:103
TileCollisionType CollisionType
Gets or sets the effective collision type associated with this frame's region coordinates.
Definition Frame.cs:151
Per-edge inset amounts applied to visual bounds to produce a collision rectangle.
static readonly CollisionAdjust None
Represents an adjustment with no pixel offsets.