Grids
A grid holds cells at positions: the pixels of a canvas, the sand of a falling-sand game, the blocks of a voxel world. Grid2<T> takes int2 positions and Grid3<T> takes int3 ones. Grids are fields of components, singletons and scenes, so a game can have as many as it needs: a canvas for each player, a grid for each ship, a dimension for each scene.
component Canvas
{
Grid2<Color> pixels = Grid2(1024, 1024);
}
singleton Terrain
{
Grid3<int> blocks; // No size: open every way
}Cells
cells[x, y] reads and writes a cell (cells[x, y, z] in 3D), and so does cells[p] for an int2 or int3 position p. A cell nobody set reads as zero.
system Paint(Brush brush, mut Canvas canvas)
{
canvas.pixels[brush.x, brush.y] = brush.color;
}Cells are plain values: numbers, bools, chars, enums, vectors, quaternions, matrices, colors, rects, entities, players and structs of those. Text, lists and grids can't be cells: keep them elsewhere, and a number for them in the cell. A cell is a copy, as a list's element is, so a struct cell is taken out, changed and put back:
mut var cell = field.cells[p];
cell.heat += 1;
field.cells[p] = cell;Size
A grid's size is given when it's made: Grid2(1024, 1024), or Grid3(16, 384, 16). An axis given 0, or left out, has no size: it takes any position, negative ones too. A grid with no size at all is open every way, like a voxel world that goes on forever.
Nothing about a grid fails: past its size, reads give zero and writes do nothing, so paint stays on its canvas without the game checking.
cells.sizeis its size, 0 on open axes.cells.Clear()sets every cell back to zero, and keeps the size.cells = Grid2(512, 512)gives the field a new, empty grid.cells.Copy()is a grid of its own, with the same size and cells.
Grids in code
Functions make grids, change them and return them, and a local can hold one. A grid is never copied without saying so: a field, a local or what a function returns has a grid of its own, never another's.
// Made from nothing, cells and all
Grid2<int> Ramp(int size)
{
mut Grid2<int> made = Grid2(size, size);
foreach (var at in made)
{
made[at] = at.x + at.y;
}
return made;
}
// Changes the caller's grid where it is: a field's, or a local's
void Border(mut Grid2<int> cells, int value)
{
for (int x = 0; x < cells.size.x; x++)
{
cells[x, 0] = value;
}
}
system Generate(mut Terrain terrain)
{
terrain.heights = Ramp(64); // The field gets the grid's size and cells
Border(terrain.heights, 9);
mut Grid2<int> copy = terrain.heights.Copy();
copy[0, 0] = 1; // The field's stays as it is
}- A local holds a new grid, a copy (
cells.Copy()) or what a function returns.var copy = terrain.heights;is an error that says to copy it: two names for one grid would change each other. - A function returns a new grid, a copy, or a local of its own. A field takes the same, and a field's grid is the world's: snapshotted, hashed and sent as any field is.
- A function takes a grid to read, or
mutto change it where it is. Its writes are the caller's, so a system that passesterrain.heightsasmutwritesTerrain. - A local's grid lasts until the system, view or handler that made it is done, and a lambda can't capture one. A task keeps one across its waits as it keeps its lists: a copy of its own, which it reads as it was and changes as its own after the wait, a read's grid and an asset's among them.
- An async function takes a grid as it takes a list: a copy of the task's own, made where it's called, so what the caller changes after the call isn't the task's, and kept in the task's frame across every wait. It can't be
mut: a task can't keep the caller's variable while it waits, so to change a field's grid it takes the component or singleton the field is in.
// A chunk's faces, made from its blocks and its neighbour's as they were when the view asked
async void Remesh(mut Chunk chunk, Grid3<Block> east)
{
var built = await Faces(chunk.blocks, east); // A local worker, which takes its own snapshots
chunk.mesh = Mesh(built.vertices, built.indices);
}Grids as bytes
cells.ToBytes() is the grid as a List<byte>, its size and its cells, and Grid3<Block>.FromBytes(bytes) (or Grid2<T>.FromBytes, named by the grid's type) the grid those bytes are, a grid of its own as Grid3(...) makes one. That's how a grid goes into the server's store (Saving the match), a command or a file.
// A chunk nobody is near is kept...
system Idle(Chunk chunk, Seen seen)
{
if (seen.audience == Audience.None && chunk.edits > 0) Storage.Save(chunk.key, chunk.blocks.ToBytes());
}
// ...and comes back as someone next comes near
event(Loaded loaded) Fill(mut Chunk chunk)
{
if (loaded.found) chunk.blocks = Grid3<Block>.FromBytes(loaded.bytes) ?? Grid3(16, 16, 16);
}- Small. Only the chunks with something in them are written, and runs of one cell as one: a 16-cube of air is 7 bytes, of stone 13, and a chunk of ground (layers of stone, dirt and grass, air above, a cave through it) about 400.
- The same everywhere. The same cells are the same bytes on every machine, however the grid came to have them, so match code can make and read them, as can views and local code.
- Safe on any bytes.
FromBytesfails withIOError.InvalidDatafor bytes that aren't a grid of those cells: cut short, spoiled, a size or a place past what a grid can be, chunks out of order, or cells of another size. A part of a cell that's no value of its type is read as its zero: a float that isn't finite, a bool that's neither false nor true, a char that's no character, an enum that's none of its members, aT?field that says it has nothing. Entities and players are what the bytes say: one that's gone, or no player's, is simply not found. A read makes 256 MB of cells at the most, refused before any is made (the log says so). The bytes say the grid's size, so check a grid from a player's bytes for the size your game expects (got.size) before keeping it. - Unwrap the result as any that can fail:
?? fallback,is Grid3<Block> got,!, ortryin a function that fails withIOError. - Read once, copied once. A component's or singleton's field given the grid takes its cells into the world once, written either of these ways:
chunk.blocks = Grid3<Block>.FromBytes(bytes) ?? Grid3(16, 16, 16);, orif (Grid3<Block>.FromBytes(bytes) is Grid3<Block> got) chunk.blocks = got.Copy();(theCopy()a field needs to take a local's grid makes no copy of its own there). About 2 µs for a 16-cube of blocks. A field inside a list's, a map's or an array's element givengot.Copy()still copies it twice.
The bytes say a cell's size, not its type: a grid's bytes read as another type with cells of the same size give that type's values of those bytes. Keep one type for one kind of key.
What a grid costs
A grid keeps its cells in chunks of 64 by 64 cells, or 16 by 16 by 16 in 3D: 16 KB for four-byte cells, 4 KB for a byte enum (enum Material : byte), which makes a big grid a quarter of the memory to keep, hash and send. Cells bigger than four bytes make chunks of fewer cells, 16 KB at most. A chunk only exists once a cell in it is set to something other than zero, so a blank canvas costs nothing, and an open grid costs what's in it rather than the space it spans.
A match is snapshotted every tick and rolled back when a guess about another player went wrong (see Networking). Snapshots share the chunks nothing changed, and hashes cover each chunk on its own, so changing a few cells copies and hashes a few chunks, never the whole grid. A player joining gets only the chunks that exist.
A grid on each of many entities (a chunk of a world, a ship's deck) is kept as well as one big grid is, and a system that runs for each entity and changes its own entity's grid goes across threads like any other (see Splitting across threads): every new chunk of a world made from its seed, or every loaded chunk stepped, on every core, with the same result as on one thread.
A local's grid isn't the world's, so nothing snapshots, hashes or sends it, and it costs what's in it. Assigning it to a field copies its cells into the world. A local worker can take a read-only snapshot of a grid as an input, and reads its grid parameters without keeping a grid in a local.
A Grid2<Color> or a Grid2<float> with a size is a Texture wherever one is wanted: a draw's texture, a frag's source, a Texture field or parameter (see Textures). The texture is the grid, not a copy of it. GPU sampling stays on the GPU; workers read their snapshot's cells by integer position.
Going through every cell
A grid's cells can all change every tick, like sand falling everywhere at once. A parallel loop goes through every cell at once, on threads:
singleton Heat
{
Grid2<int> cells = Grid2(1024, 1024);
}
// Each cell becomes the average of itself and the four beside it
system Spread(mut Heat heat)
{
parallel (var at in heat.cells)
{
var sum = heat.cells[at] * 4 + heat.cells[at + int2(1, 0)] + heat.cells[at + int2(-1, 0)]
+ heat.cells[at + int2(0, 1)] + heat.cells[at + int2(0, -1)];
heat.cells[at] = sum / 8;
}
}Each step reads the grid as the loop found it, and changes only its own cell, at. So it doesn't matter which steps run first, or on which thread: the result is exactly the same on one thread as on many, on every machine. Code after the loop runs once every step is done.
How many threads a loop gets never changes what it makes, only how soon. tidec reckons what a step costs, counting the functions it calls, and a loop whose steps come to little in all, under a millisecond or so, runs on one thread. More goes to threads, even a short list of costly steps, or a grid or list the system filled that same tick.
That loop runs below, 30 times a second, less a little heat each tick so it cools. Drag over the grid to heat its cells.
settings { title = "Grids"; tickRate = 30; maxPlayers = 1; }
const int SIZE = 40;
// A cell is an int here: how hot it is.
singleton Heat { Grid2<int> cells = Grid2(SIZE, SIZE); }
local singleton Brush
{
int2 cell;
bool down;
}
input Paint
{
// A cell, not something a player does: what another machine guesses of it stays
[Absolute, Clamp(0, 39)] int x;
[Absolute, Clamp(0, 39)] int y;
bool down;
Sample(Devices devices, Brush brush)
{
x = brush.cell.x;
y = brush.cell.y;
down = brush.down;
}
}
scene Main { }
system Warm(Paint paint, mut Heat heat, Time time)
{
// An ember that circles by itself, and the player's brush.
var ember = float2(Math.Cos(time.t), Math.Sin(time.t)) * 12 + SIZE * 0.5;
heat.cells[int2(ember)] = 4000;
if (!paint.down) return;
// Writes past the grid's size do nothing, so the edges need no checks.
for (var dx = -1; dx <= 1; dx++)
{
for (var dy = -1; dy <= 1; dy++) heat.cells[paint.x + dx, paint.y + dy] = 4000;
}
}
// Every cell at once, on threads: each becomes the average of itself and the
// four beside it, less a little. A step reads the grid as the loop found it,
// and changes only its own cell.
system Spread(mut Heat heat)
{
parallel (var at in heat.cells)
{
var sum = heat.cells[at] * 4 + heat.cells[at + int2(1, 0)] + heat.cells[at + int2(-1, 0)]
+ heat.cells[at + int2(0, 1)] + heat.cells[at + int2(0, -1)];
heat.cells[at] = Math.Max(sum / 8 - 3, 0);
}
}
view Show(Devices devices, Heat heat, mut Brush brush)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(SIZE * 0.5, SIZE * 0.5 + 2), SIZE * 0.58); // A cell is one unit
var pointer = Draw.ScreenToWorld(Screen.Flip(devices.pointer.position));
brush.cell = int2(Math.Floor(pointer));
brush.down = devices.pointer.press.pressed && pointer.x >= 0 && pointer.x < SIZE && pointer.y >= 0 && pointer.y < SIZE;
Draw.Rect(float2(SIZE * 0.5), float2(SIZE), Color(0.11, 0.11, 0.13));
foreach (var at in heat.cells)
{
float hot = heat.cells[at] / 4000.0;
if (hot > 0.004) Draw.Rect(float2(at) + 0.5, float2(1), Color(Math.Sqrt(hot), hot * hot * 0.75, 0.14 - hot * 0.1));
}
Draw.SetScreen();
Draw.Text("Drag to heat the cells", float2(16, 14), 16, Color.white);
}A step can declare variables, call functions (and C) and read any cell. What it can't do is change anything else: another cell, a variable from outside the loop, the whole grid (Clear), or anything whose order would count. tidec says so, and what to write instead. So a step can't:
breakout of the loop:continueends the step.return, wait, or start tasks.- Spawn, send events, add, remove or destroy, or load scenes.
- Draw or use the GUI.
- Hold another parallel loop.
To add things up, use a for loop, or a foreach that goes in order (see below).
A list's elements go through a parallel loop the same way, by index (see Lists), and so do a query's rows, whose steps can also send events (see Systems).
A parallel loop goes in a system, a view, an event handler that isn't async, or a local worker: not in ordinary functions, methods, async code or an input's Sample. It goes through a component's or a singleton's grid: a local's lives on the thread that made it, so a foreach goes through it in order. Workers can run parallel loops over their own lists, reading captured grids from each step. Their read-only grid inputs cannot be the writable output of an explicit parallel loop.
A view's parallel loops take the threads as a system's do. A step that reads a variable declared outside the loop holding text, a list, a map or a set keeps the whole loop on one thread, as those live on the thread that made them: read a component's or a singleton's instead, or plain values.
Moving things: blocks
Sand moves: a grain leaves its cell and lands in another. A step that only changes its own cell can't do that, so by gives each step a block of cells instead. Each step owns its block, reads any cell, and changes only the cells in its block, so things can move within it:
// 2 by 2 blocks: their corners are on even cells one tick, and odd ones the next
system Fall(Time time, mut Field field)
{
parallel (var at in field.cells by 2 offset time.tick % 2)
{
mut var top = field.cells[at + int2(0, 1)];
mut var bottom = field.cells[at];
if (top == Material.Sand && bottom == Material.Empty)
{
top = Material.Empty;
bottom = Material.Sand;
}
field.cells[at + int2(0, 1)] = top;
field.cells[at] = bottom;
}
}Blocks never overlap, so steps never fight over a cell. offset says where the blocks start, and changing it each tick moves where their edges are: a grain at the bottom of a block one tick is at the top of another the next, so it keeps falling. by int2(1, 2) gives blocks of 1 by 2, and offset int2(0, 1) moves them along one axis only. A block is 1 to 64 cells along each axis, a size known while compiling: numbers, or constants. The offset can be any int, or int2 or int3, and can change every time. A block that would go past the grid's size is left out (on an open axis, past the last number an int holds), so along a sized edge some cells are only in every other tick's blocks: walls around the field keep sand off it, as in the sand simulation.
In order: foreach
foreach (var at in cells) goes through the cells in order, rows from the first, each from its lowest x. Each step sees what the ones before it changed, which is what adding up a row needs, or anything that runs along the grid.
system Count(Field field, mut Stats stats)
{
mut var sand = 0;
foreach (var at in field.cells)
{
if (field.cells[at] == Material.Sand) sand += 1;
}
stats.sand = sand;
}When a foreach's steps only touch their own cell, and nothing outside the loop, the order can't show, so tidec runs them at once, like a parallel loop.
A grid with no size goes on forever, so a loop over it goes through the cells around what's been set: the chunks the grid has.
tide schedule shows which systems have parallel loops: Fall (once, 1 parallel loop).