39public class SceneLayer : IEnumerable<SceneLayerTile>, IDisposable
136 #region private fields
138 private int _tileWidth;
139 private int _tileHeight;
140 private bool _visible;
141 private string _defaultTileCollisionProfile = CollisionProfileNames.World;
142 private bool _fixedGridRenderEligibilityDirty;
143 private bool _fixedGridRenderEligible =
true;
144 private bool _sceneLayerTileArrayExternallyExposed;
146 [JsonIgnore]
internal float EffectOpacity {
get;
set; } = 1f;
148 [JsonIgnore]
internal float EffectReveal {
get;
set; } = 1f;
152 [JsonIgnore]
internal PointF EffectOffsetFactor {
get;
set; } = PointF.Empty;
154 [JsonIgnore]
internal PointF EffectOffsetPx {
get;
set; } = PointF.Empty;
156 #endregion private fields
158 #region constructors / finalizer
178 var tileArray =
new SceneLayerTile[columnCount, rowCount];
192 private void OnDeserialized(StreamingContext context)
196 bool fastPathEligible =
true;
197 int? fixedZOrder =
null;
202 var tile = _sceneLayerTileArray[x, y] ??=
new SceneLayerTile(
this);
203 tile.parentSceneLayer =
this;
206 TransformedTiles.Add(tile);
208 tile.sceneLayerCoordinates =
new Point(x, y);
210 if (tile.GetType() != typeof(SceneLayerTile) || tile.EnableFog)
211 fastPathEligible =
false;
213 if (fixedZOrder.HasValue && fixedZOrder.Value != tile.ZOrder)
214 fastPathEligible =
false;
216 fixedZOrder ??= tile.ZOrder;
219 _fixedGridRenderEligible = fastPathEligible;
220 _fixedGridRenderEligibilityDirty =
false;
221 _sceneLayerTileArrayExternallyExposed =
false;
222 BuildTileColliders();
239 #endregion constructors / finalizer
257 [JsonIgnore]
internal ISceneLayerCoordinates CoordinateSystem {
get;
private set; } =
new OrthogonalCoordinates();
288 return CoordinateSystem
switch
297 _ =>
throw new InvalidOperationException(
298 $
"Unknown coordinate system type: {CoordinateSystem.GetType().Name}")
303 CoordinateSystem = value
switch
312 _ =>
throw new ArgumentOutOfRangeException(nameof(value), $
"Unknown coordinate system type: {value}")
327 public string ID {
get;
protected internal set; } = Guid.NewGuid().ToString();
341 [JsonIgnore]
internal RefreshQueue RefreshQueue {
get;
set; }
343 private int _zOrder = 0;
370 private float _parallax = 1f;
395 get {
return _parallax; }
421 get {
return _tileHeight; }
447 get {
return _tileWidth; }
473 get {
return _visible; }
481 [JsonIgnore]
internal HashSet<SceneLayerTile> TransformedTiles {
get; } =
new();
483 [JsonProperty(
"SceneLayerTileArray")]
484 [JsonConverter(typeof(SceneLayerTileArrayConverter))]
485 private SceneLayerTile[,] _sceneLayerTileArray;
514 _sceneLayerTileArrayExternallyExposed =
true;
515 return _sceneLayerTileArray;
541 [JsonProperty(
"WrapHorizontally")]
private bool _wrapHoriz =
false;
560 get {
return _wrapHoriz; }
568 [JsonProperty(
"WrapVertically")]
private bool _wrapVerti =
false;
587 get {
return _wrapVerti; }
595 [JsonProperty(
"ShowGridLines")]
private bool showGridLines =
false;
613 get {
return showGridLines; }
616 showGridLines = value;
621 [JsonProperty(
"ShowCollisionBoxes")]
private bool showCollisionBoxes =
false;
640 get {
return showCollisionBoxes; }
643 showCollisionBoxes = value;
650 [JsonProperty(
"OriginPx")]
private Point _originPx = Point.Empty;
673 if (_originPx == value)
693 [JsonIgnore]
internal CollisionResolver CollisionResolver {
get;
private set; } =
null!;
712 get => _defaultTileCollisionProfile;
715 if (
string.IsNullOrWhiteSpace(value))
717 throw new ArgumentException(
718 "Default tile collision profile cannot be empty.",
722 if (
Scene is not
null)
724 var profile =
Scene.CollisionProfiles.Get(value);
725 _ = profile.ResolveCollisionGroup(
Scene.CollisionGroups);
726 _ = profile.ResolveCollidesWith(
Scene.CollisionGroups);
729 _defaultTileCollisionProfile = value;
731 if (
Scene is not
null && _sceneLayerTileArray is not
null)
732 ApplyDefaultTileCollisionProfile();
736 #endregion properties
738 #region public methods
758 _tileWidth = newWidth;
759 _tileHeight = newHeight;
767 internal void ApplyDefaultTileCollisionProfile()
769 if (
Scene is
null || _sceneLayerTileArray is
null)
776 foreach (var tile
in _sceneLayerTileArray)
777 tile?.SetCollisionProfile(_defaultTileCollisionProfile);
787 public PointF
GridToWorldPx(PointF grid) => CoordinateSystem.GetAnchorPixelAtSceneLayerCoordinates(
this, grid);
796 public PointF
WorldPxToGrid(PointF worldPx) => CoordinateSystem.GetSceneLayerCoordinatesAtPixel(
this, worldPx);
810 CoordinateSystem.GetAdjacentSceneLayerTile(tile, direction);
826 if (!
float.IsFinite(grid.X) || !
float.IsFinite(grid.Y))
827 throw new ArgumentOutOfRangeException(nameof(grid));
845 static int Mod(
int value,
int period)
847 int remainder = value % period;
848 return remainder < 0 ? remainder + period : remainder;
867 return GetPeriod().Offsets(contentBounds, queryBounds);
869 return contentBounds.IntersectsWith(queryBounds) ?
new[] { PointF.Empty } : Array.Empty<PointF>();
872 internal LayerPeriod GetPeriod() => CoordinateSystem.GetWrapPeriod(
this);
884 return RectangleF.Empty;
898 RectangleF result = RectangleF.Empty;
899 bool hasBounds =
false;
901 foreach (var tile
in corners)
903 var px = CoordinateSystem.GetPixelRangeForTile(tile, includeOverhang:
true);
905 var rf = RectangleF.FromLTRB(
918 result = RectangleF.Union(result, rf);
923 foreach (var tile
in TransformedTiles)
924 result = RectangleF.Union(result, tile.DrawLocationWorld);
929 #endregion public methods
931 #region private methods
933 private void InitValues(
940 _sceneLayerTileArray = tileArray;
941 _parallax = parallax;
943 _tileHeight = height;
946 _originPx = Point.Empty;
950 EffectOffsetFactor = PointF.Empty;
951 EffectOffsetPx = PointF.Empty;
959 SaveGridCoordinatesToSceneLayerTiles();
960 _fixedGridRenderEligible =
true;
961 _fixedGridRenderEligibilityDirty =
false;
962 _sceneLayerTileArrayExternallyExposed =
false;
963 BuildTileColliders();
966 RefreshQueue =
new RefreshQueue(() =>
Scene?.UsesDirtyRegionRendering ??
true);
969 private void SaveGridCoordinatesToSceneLayerTiles()
972 for (
int X = 0; X <= _sceneLayerTileArray.GetUpperBound(0); X++)
974 for (
int Y = 0; Y <= _sceneLayerTileArray.GetUpperBound(1); Y++)
976 _sceneLayerTileArray[X, Y] =
new SceneLayerTile(
this);
977 _sceneLayerTileArray[X, Y].sceneLayerCoordinates =
new Point(X, Y);
982 private void BuildTileColliders()
984 foreach (var tile
in _sceneLayerTileArray)
989 tile.EnsureCollider();
993 internal bool IsFixedGridSnapshotFastPathEligible
997 if (_sceneLayerTileArrayExternallyExposed)
1000 if (_fixedGridRenderEligibilityDirty)
1001 RecalculateFixedGridRenderEligibility();
1003 return _fixedGridRenderEligible;
1007 internal void InvalidateFixedGridRenderEligibility() =>
1008 _fixedGridRenderEligibilityDirty =
true;
1010 private void RecalculateFixedGridRenderEligibility()
1012 bool eligible =
true;
1013 int? fixedZOrder =
null;
1015 foreach (var tile
in _sceneLayerTileArray)
1018 tile.GetType() != typeof(SceneLayerTile) ||
1019 !ReferenceEquals(tile.SceneLayer,
this) ||
1026 if (fixedZOrder.HasValue && fixedZOrder.Value != tile.ZOrder)
1032 fixedZOrder ??= tile.ZOrder;
1035 _fixedGridRenderEligible = eligible;
1036 _fixedGridRenderEligibilityDirty =
false;
1039 internal virtual List<IDrawable> GetDrawablesInWorldRect(Rectangle worldRect,
bool includeOverhang =
true) =>
1040 GetDrawablesInWorldRectCore(
1043 collectSortDiagnostics:
false,
1046 internal virtual List<IDrawable> GetDrawablesInWorldRectWithDiagnostics(
1047 Rectangle worldRect,
1049 bool includeOverhang =
true) =>
1050 GetDrawablesInWorldRectCore(
1053 collectSortDiagnostics:
true,
1056 private List<IDrawable> GetDrawablesInWorldRectCore(
1057 Rectangle worldRect,
1058 bool includeOverhang,
1059 bool collectSortDiagnostics,
1063 return GetWrappedDrawables(worldRect, collectSortDiagnostics, out sortTicks);
1067 var queryRect = worldRect;
1069 queryRect.Inflate(1, 1);
1073 var renderTiles = CoordinateSystem.GetSceneLayerTilesForRendering(
1078 var sceneLayerTiles = renderTiles.Tiles;
1080 var list =
new List<IDrawable>(sceneLayerTiles.Count);
1081 bool uniformGridZOrder =
true;
1082 int? gridZOrder =
null;
1084 for (
int i = 0; i < sceneLayerTiles.Count; i++)
1086 var tile = sceneLayerTiles[i];
1088 if (!tile.Visible || !HasRenderableTileContent(tile))
1091 int tileZ = tile.ZOrder;
1093 if (gridZOrder.HasValue && gridZOrder.Value != tileZ)
1094 uniformGridZOrder =
false;
1096 gridZOrder ??= tileZ;
1101 bool hasNonGridDrawables =
false;
1104 var sprites = SpriteManager.Instance.GetSpritesInWorldRectRange(
1107 fullEnclosures:
false);
1109 for (
int i = 0; i < sprites.Count; i++)
1111 var sprite = sprites[i];
1116 if (!sprite.VisualBoundsWorld.IntersectsWith(queryRect))
1120 hasNonGridDrawables =
true;
1124 var drawings = DirectDrawingManager.Instance.GetDrawingsForLayer(
this);
1126 for (
int i = 0; i < drawings.Count; i++)
1128 var drawing = drawings[i];
1130 if (!drawing.Visible)
1136 if (!drawing.WorldBounds.IntersectsWith(worldRect))
1140 hasNonGridDrawables =
true;
1146 bool gridOrderGuaranteed =
1147 renderTiles.IsRenderOrdered &&
1150 long sortStartTick = collectSortDiagnostics ? HighResTimer.GetCurrentTick() : 0;
1152 if (hasNonGridDrawables)
1154 list.Sort(CompareDrawables);
1156 else if (!gridOrderGuaranteed && !IsSorted(list, CompareDrawables))
1158 list.Sort(CompareDrawables);
1161 sortTicks = collectSortDiagnostics
1162 ? Math.Max(0, HighResTimer.GetCurrentTick() - sortStartTick)
1168 private List<IDrawable> GetWrappedDrawables(
1169 Rectangle worldRect,
1170 bool collectSortDiagnostics,
1173 var period = GetPeriod();
1174 var instances =
new List<IDrawable>();
1176 void Add(IDrawable drawable, RectangleF bounds)
1181 foreach (var offset
in period.Offsets(bounds, worldRect))
1183 if (instances.Count >= 1_000_000)
1184 throw new InvalidOperationException(
"Too many visible wrapped instances.");
1186 instances.Add(
new WrappedDrawable(drawable,
this, offset));
1192 foreach (var tile
in _sceneLayerTileArray)
1193 if (tile is not
null)
1194 Add(tile, tile.DrawLocationWorld);
1196 foreach (var sprite
in SpriteManager.Instance.AllSprites)
1197 if (ReferenceEquals(sprite.SceneLayer,
this))
1198 Add(sprite, sprite.VisualBoundsWorld);
1200 foreach (var drawing
in DirectDrawingManager.Instance.GetDrawingsForLayer(
this))
1202 Add(drawing, drawing.WorldBounds);
1204 long sortStartTick = collectSortDiagnostics ? HighResTimer.GetCurrentTick() : 0;
1205 instances.Sort(CompareWrappedDrawables);
1207 sortTicks = collectSortDiagnostics
1208 ? Math.Max(0, HighResTimer.GetCurrentTick() - sortStartTick)
1214 private bool HasRenderableTileContent(SceneLayerTile tile)
1217 if (tile.GetType() != typeof(SceneLayerTile))
1220 if (tile.CurrentFrame.Tilesheet is not
null)
1225 return tile.EnableFog ||
1230 private static bool IsSorted(
1231 List<IDrawable> drawables,
1232 Comparison<IDrawable> comparison)
1234 for (
int i = 1; i < drawables.Count; i++)
1236 if (comparison(drawables[i - 1], drawables[i]) > 0)
1243 private static int CompareWrappedDrawables(IDrawable a, IDrawable b)
1245 var x = (WrappedDrawable)a;
1246 var y = (WrappedDrawable)b;
1252 if (x.Owner is Tile ta && y.Owner is Tile tb)
1254 if (ta.IsPositionFixed != tb.IsPositionFixed)
1255 return ta.IsPositionFixed ? -1 : 1;
1259 ? ta.DrawLocationWorld.Top + ta.Overhang.Top
1260 : ta.DrawLocationWorld.Bottom - ta.Overhang.Bottom - 1) +
1265 ? tb.DrawLocationWorld.Top + tb.Overhang.Top
1266 : tb.DrawLocationWorld.Bottom - tb.Overhang.Bottom - 1) +
1269 int depth = ay.CompareTo(by);
1275 (ta.DrawLocationWorld.Left + x.Offset.X)
1276 .CompareTo(tb.DrawLocationWorld.Left + y.Offset.X);
1278 if (horizontal != 0)
1282 int identity = a.
Id.CompareTo(b.
Id);
1284 return identity != 0
1286 : (x.Offset.Y, x.Offset.X).CompareTo((y.Offset.Y, y.Offset.X));
1289 private static int CompareDrawables(IDrawable a, IDrawable b)
1296 if (a is Tile ta && b is Tile tb)
1297 return ta.CompareTo(tb);
1299 return a.
Id.CompareTo(b.
Id);
1302 #endregion private methods
1356 if (x > _sceneLayerTileArray.GetUpperBound(0)
1357 || y > _sceneLayerTileArray.GetUpperBound(1)
1362 return _sceneLayerTileArray[x, y];
1367 #region IEnumerable Members
1390 IEnumerator<SceneLayerTile> IEnumerable<SceneLayerTile>.GetEnumerator()
1392 for (
int x = 0; x <= _sceneLayerTileArray.GetUpperBound(0); x++)
1394 for (
int y = 0; y <= _sceneLayerTileArray.GetUpperBound(1); y++)
1396 yield
return _sceneLayerTileArray[x, y];
1401 #endregion IEnumerable Members
1403 #region IDisposable Members
1429 GC.SuppressFinalize(
this);
1443 #endregion IDisposable Members
1445 #region empty SceneLayer
1470 public static SceneLayer
Empty {
get; } =
new EmptySceneLayer();
1472 private sealed class EmptySceneLayer :
SceneLayer
1474 internal EmptySceneLayer()
1487 #endregion empty SceneLayer