Class ScyllaSparseSquareGrid<TCell>
Sparse, dictionary-backed square grid that stores per-cell data of type
TCell, addressed by SquareCoord.
Inherited Members
Namespace: Scylla.Core.Structures
Assembly: ScyllaCore.dll
Syntax
public sealed class ScyllaSparseSquareGrid<TCell> : IScyllaGrid<SquareCoord, TCell>, IScyllaCollection
Type Parameters
| Name | Description |
|---|---|
| TCell | The type of data stored in each populated cell. May be any managed type. |
Remarks
Unlike ScyllaSquareGrid<TCell>, a sparse grid only allocates memory for cells that have been explicitly written via TrySet(SquareCoord, TCell), the indexer setter, or TrySet(TCoord, TCell). This makes it well-suited for procedurally generated worlds, infinite maps, or grids where a small fraction of cells are ever active.
The grid is optionally bounded. When constructed without bounds (or via the unbounded constructor overload) the grid grows dynamically and any integer coordinate is valid. When constructed with explicit bounds, writes outside those bounds are rejected. Use HasBounds to check at runtime.
Lookup and insertion are O(1) average case (dictionary hashing). Neighbor queries consider a neighbor present only when it has been explicitly set in the dictionary; see GetNeighborsNonAlloc(SquareCoord, Span<SquareCoord>, SquareAdjacency).
This class is not thread-safe by default. Call AsSynchronized(object) to obtain a ScyllaSparseSquareGrid<TCell>.SynchronizedScyllaSparseSquareGrid wrapper that locks all operations with a shared monitor.
Use CreateBuilder() for a fluent construction API that supports optional bounds and synchronization.
Constructors
ScyllaSparseSquareGrid(SquareGridLayout)
Creates a new unbounded sparse square grid with the specified spatial layout. The grid can grow to accept any integer coordinate.
Declaration
public ScyllaSparseSquareGrid(SquareGridLayout layout)
Parameters
| Type | Name | Description |
|---|---|---|
| SquareGridLayout | layout | The spatial layout that defines cell size and world-space origin. |
ScyllaSparseSquareGrid(SquareGridLayout, int, int, int, int)
Creates a new bounded sparse square grid with the specified spatial layout and inclusive coordinate bounds.
Declaration
public ScyllaSparseSquareGrid(SquareGridLayout layout, int minCol, int minRow, int maxCol, int maxRow)
Parameters
| Type | Name | Description |
|---|---|---|
| SquareGridLayout | layout | The spatial layout that defines cell size and world-space origin. |
| int | minCol | The minimum column value (inclusive). Must be <= |
| int | minRow | The minimum row value (inclusive). Must be <= |
| int | maxCol | The maximum column value (inclusive). Must be >= |
| int | maxRow | The maximum row value (inclusive). Must be >= |
Remarks
Cells outside the defined bounds cannot be written; writes are silently rejected by TrySet(SquareCoord, TCell) or raise ArgumentOutOfRangeException via the indexer.
Exceptions
| Type | Condition |
|---|---|
| ArgumentOutOfRangeException | Thrown when |
Properties
Capabilities
Gets the feature and capability flags supported by this collection instance.
Declaration
public ScyllaCollectionCapabilities Capabilities { get; }
Property Value
| Type | Description |
|---|---|
| ScyllaCollectionCapabilities | A bitfield of ScyllaCollectionCapabilities flags describing which optional operations the concrete instance supports. The value None indicates that only the base contract (Count, IsEmpty, Clear()) is available. |
Remarks
Use Capabilities for feature detection in place of type-casting. For example:
if ((collection.Capabilities & ScyllaCollectionCapabilities.SupportsPeek) != 0)
{
// safe to call TryPeek through IScyllaCollection<T>
}
Synchronized wrappers cache the capability flags of their inner collection at construction time, so the value returned is stable and does not require synchronization.
See Also
CellCount
Gets the number of populated (logically active) cells in the grid.
Declaration
public int CellCount { get; }
Property Value
| Type | Description |
|---|---|
| int | For dense grids, this always equals Count - every cell slot is pre-allocated and considered populated regardless of its stored value. The value is fixed at construction and never changes. For sparse grids, this equals the number of cells that have been explicitly written via TrySet(TCoord, TCell) and not yet removed. The value may be zero on a freshly created or cleared sparse grid. |
See Also
Count
Gets the number of items currently contained in the collection.
Declaration
public int Count { get; }
Property Value
| Type | Description |
|---|---|
| int | A non-negative integer representing the current element count.
Returns |
Remarks
On unsynchronized collections, Count is not thread-safe and may return a stale
value when accessed concurrently. On synchronized wrappers, reading Count is
protected by the internal lock.
HasBounds
Gets whether this grid enforces coordinate bounds.
When false, any integer coordinate can be written.
When true, writes outside the bounds defined at construction time are rejected.
Declaration
public bool HasBounds { get; }
Property Value
| Type | Description |
|---|---|
| bool |
See Also
Height
Gets the number of rows in the bounded region, computed as
maxRow - minRow + 1.
Only valid when HasBounds is true.
Declaration
public int Height { get; }
Property Value
| Type | Description |
|---|---|
| int |
Exceptions
| Type | Condition |
|---|---|
| InvalidOperationException | Thrown when the grid is unbounded (HasBounds is |
IsEmpty
Gets a value indicating whether the collection contains no items.
Declaration
public bool IsEmpty { get; }
Property Value
| Type | Description |
|---|---|
| bool |
|
Remarks
This is a convenience property equivalent to Count == 0. Prefer it over comparing
Count directly when the actual count is not needed, as some implementations may
compute it more efficiently.
this[SquareCoord]
Gets or sets the cell value at the specified coordinate.
Declaration
public TCell this[SquareCoord coord] { get; set; }
Parameters
| Type | Name | Description |
|---|---|---|
| SquareCoord | coord | The grid coordinate to read from or write to. |
Property Value
| Type | Description |
|---|---|
| TCell |
Remarks
The getter throws KeyNotFoundException (from the underlying
dictionary) if no value has been set at coord.
For safe retrieval use TryGet(SquareCoord, out TCell) instead.
The setter throws ArgumentOutOfRangeException when the grid is
bounded and coord falls outside the defined bounds. For
non-throwing conditional writes use TrySet(SquareCoord, TCell) instead.
Exceptions
| Type | Condition |
|---|---|
| KeyNotFoundException | Thrown on get when no value has been set at |
| ArgumentOutOfRangeException | Thrown on set when the grid is bounded and |
Layout
Gets the spatial layout used for world-space coordinate conversion.
Declaration
public SquareGridLayout Layout { get; }
Property Value
| Type | Description |
|---|---|
| SquareGridLayout |
SyncRoot
Gets the synchronization root object used to externally coordinate multi-step operations with this collection.
Declaration
public object SyncRoot { get; }
Property Value
| Type | Description |
|---|---|
| object | A non-null object suitable for use with |
Remarks
When this collection is a synchronized wrapper, SyncRoot must be non-null and
stable for the entire lifetime of the wrapper. All internal operations on the wrapper
must lock on this same object. This allows callers to perform atomic multi-step
sequences:
lock (collection.SyncRoot)
{
if (!collection.IsEmpty)
typedCollection.TryRemove(out var item);
}
For unsynchronized collections (SyncRoot == null), callers are responsible for
supplying and consistently applying their own external synchronization mechanism.
A null SyncRoot does not mean the collection is thread-safe;
consult ThreadSafety for the authoritative guarantee.
See Also
ThreadSafety
Gets the thread-safety guarantees provided by this collection instance.
Declaration
public ScyllaCollectionThreadSafety ThreadSafety { get; }
Property Value
| Type | Description |
|---|---|
| ScyllaCollectionThreadSafety | A ScyllaCollectionThreadSafety value indicating whether the collection is unsynchronized, synchronized via a lock, or safe for lock-free concurrent access. Most core implementations return Unsynchronized. Synchronized wrappers return Synchronized. |
Remarks
Always check this property (or SyncRoot) before assuming a collection is
safe for concurrent use. Do not rely solely on the absence of a non-null SyncRoot
to infer thread safety; use this property as the authoritative source.
See Also
Width
Gets the number of columns in the bounded region, computed as
maxCol - minCol + 1.
Only valid when HasBounds is true.
Declaration
public int Width { get; }
Property Value
| Type | Description |
|---|---|
| int |
Exceptions
| Type | Condition |
|---|---|
| InvalidOperationException | Thrown when the grid is unbounded (HasBounds is |
Methods
AsSynchronized(object)
Creates and returns a thread-safe ScyllaSparseSquareGrid<TCell>.SynchronizedScyllaSparseSquareGrid wrapper around this grid instance.
Declaration
public ScyllaSparseSquareGrid<TCell>.SynchronizedScyllaSparseSquareGrid AsSynchronized(object syncRoot = null)
Parameters
| Type | Name | Description |
|---|---|---|
| object | syncRoot | An optional external lock object to share. When |
Returns
| Type | Description |
|---|---|
| ScyllaSparseSquareGrid<TCell>.SynchronizedScyllaSparseSquareGrid | A ScyllaSparseSquareGrid<TCell>.SynchronizedScyllaSparseSquareGrid that wraps this grid and synchronizes all reads and writes. |
Remarks
All operations on the returned wrapper are synchronized using a shared lock. Multiple
synchronized wrappers sharing the same syncRoot can be used to
implement compound atomic operations across two or more collections.
Clear()
Removes all items from the collection and resets it to an empty state.
Declaration
public void Clear()
Remarks
Implementations that store reference-type elements should null out internal slots after
clearing to avoid retaining object references and preventing garbage collection.
After Clear returns, Count must be 0 and
IsEmpty must be true.
On synchronized wrappers this operation is protected by the collection's internal lock. On unsynchronized collections, callers are responsible for external coordination.
Contains(SquareCoord)
Determines whether the specified coordinate is addressable and populated in this grid.
Declaration
public bool Contains(SquareCoord coord)
Parameters
| Type | Name | Description |
|---|---|---|
| SquareCoord | coord | The coordinate to test. |
Returns
| Type | Description |
|---|---|
| bool |
For dense grids, returns
For sparse grids, returns |
Remarks
This method is equivalent to checking whether TryGet(TCoord, out TCell) would return
true for the same coordinate. Use it when you only need the existence check
and do not need the value.
See Also
CreateBuilder()
Creates and returns a new fluent ScyllaSparseSquareGrid<TCell>.Builder for configuring and constructing a ScyllaSparseSquareGrid<TCell> instance.
Declaration
public static ScyllaSparseSquareGrid<TCell>.Builder CreateBuilder()
Returns
| Type | Description |
|---|---|
| ScyllaSparseSquareGrid<TCell>.Builder | A fresh ScyllaSparseSquareGrid<TCell>.Builder with default settings (no layout, no bounds). |
GetEnumerator()
Returns a value-type enumerator that iterates through all populated cells.
Declaration
public ScyllaSparseSquareGrid<TCell>.Enumerator GetEnumerator()
Returns
| Type | Description |
|---|---|
| ScyllaSparseSquareGrid<TCell>.Enumerator | An ScyllaSparseSquareGrid<TCell>.Enumerator positioned before the first populated cell. |
Remarks
Because the return type is the concrete value-type ScyllaSparseSquareGrid<TCell>.Enumerator, using
this method in a foreach loop on the concrete grid type avoids heap allocation.
Only cells that have been explicitly set are yielded; unpopulated coordinates are skipped.
Iteration order matches the internal dictionary's unspecified insertion-dependent order.
GetNeighborsNonAlloc(SquareCoord, Span<SquareCoord>, SquareAdjacency)
Writes the populated neighbors of coord into buffer.
Declaration
public int GetNeighborsNonAlloc(SquareCoord coord, Span<SquareCoord> buffer, SquareAdjacency adjacency = SquareAdjacency.VonNeumann)
Parameters
| Type | Name | Description |
|---|---|---|
| SquareCoord | coord | The cell whose populated neighbors are requested. |
| Span<SquareCoord> | buffer | A Span<T> to receive the neighbor coordinates. Writing stops when the buffer is full, so provide at least 4 elements for VonNeumann or 8 for Moore to guarantee all neighbors are returned. |
| SquareAdjacency | adjacency | The adjacency model to use. Defaults to VonNeumann. |
Returns
| Type | Description |
|---|---|
| int | The number of populated neighbor coordinates written into |
Remarks
Unlike the dense grid counterpart, this method considers a neighbor present only when a value has been explicitly set at that coordinate in the dictionary. In-bounds but unpopulated neighbors are not returned.
With VonNeumann the offsets are tested in the order N, E, S, W. With Moore the order is N, NE, E, SE, S, SW, W, NW.
GridToWorld(SquareCoord)
Converts a grid coordinate to the world-space center of the corresponding cell using this grid's Layout.
Declaration
public Vector2 GridToWorld(SquareCoord coord)
Parameters
| Type | Name | Description |
|---|---|---|
| SquareCoord | coord | The grid coordinate to convert. |
Returns
| Type | Description |
|---|---|
| Vector2 | The world-space UnityEngine.Vector2 at the center of the cell. |
See Also
IsInBounds(int, int)
Determines whether the specified column and row are within this grid's bounds.
Declaration
public bool IsInBounds(int col, int row)
Parameters
| Type | Name | Description |
|---|---|---|
| int | col | The column index to test. |
| int | row | The row index to test. |
Returns
| Type | Description |
|---|---|
| bool |
|
Remarks
For unbounded grids (HasBounds is false) this method always
returns true, regardless of the coordinate values.
TryGet(SquareCoord, out TCell)
Attempts to retrieve the value stored at the specified coordinate without throwing on failure.
Declaration
public bool TryGet(SquareCoord coord, out TCell value)
Parameters
| Type | Name | Description |
|---|---|---|
| SquareCoord | coord | The grid coordinate to look up. |
| TCell | value | When this method returns |
Returns
| Type | Description |
|---|---|
| bool |
|
Remarks
Prefer this method over direct indexer access when the coordinate's validity is not guaranteed, as it avoids the cost of exception handling on out-of-bounds access. For dense grids, "within bounds" means the coordinate maps to a valid flat-array index. For sparse grids, "within bounds" additionally requires that the cell has been set.
See Also
TryRemove(SquareCoord, out TCell)
Attempts to remove the cell at coord and retrieve its value.
Declaration
public bool TryRemove(SquareCoord coord, out TCell value)
Parameters
| Type | Name | Description |
|---|---|---|
| SquareCoord | coord | The coordinate of the cell to remove. |
| TCell | value | When this method returns |
Returns
| Type | Description |
|---|---|
| bool |
|
TrySet(SquareCoord, TCell)
Attempts to store a value at the specified coordinate without throwing on failure.
Declaration
public bool TrySet(SquareCoord coord, TCell value)
Parameters
| Type | Name | Description |
|---|---|---|
| SquareCoord | coord | The grid coordinate to write to. |
| TCell | value | The value to store at |
Returns
| Type | Description |
|---|---|
| bool |
|
Remarks
For dense grids, this writes to the pre-allocated cell at
coord and returns false if the coordinate falls outside
the grid's dimensions.
For sparse grids, this inserts or updates the entry at
coord and returns false only when the grid is bounded
and coord falls outside the defined bounds. On unbounded sparse
grids this method always returns true.
A successful call increments CellCount on sparse grids when
coord is newly written for the first time.
See Also
WorldToGrid(Vector2)
Converts a world-space position to the grid coordinate of the cell that contains it, using this grid's Layout.
Declaration
public SquareCoord WorldToGrid(Vector2 worldPos)
Parameters
| Type | Name | Description |
|---|---|---|
| Vector2 | worldPos | The world-space position to convert. |
Returns
| Type | Description |
|---|---|
| SquareCoord | The SquareCoord of the cell containing |