tiles source

← tiles · API reference · version 0.7.2

2 file(s), 989 lines. This is the source the published version ships, and it is loft — the library is written in the same language you call it from.

Public items

A worked example is a call site the author chose as the thing to read first. Call sites are every line naming the item, found mechanically over the source with comments excluded — so an item with no worked example is not an item nobody uses.

ItemDefinedWorked exampleCall sites
rgb fn87—50 51 168
sheet fn97—108 120 121 124 125 128 … (25 total)
sheet_from_image fn104—116
sheet_from_png fn112—none in this package
tile_count fn120—60 119
colour_count fn124—61
free_sheet fn128—none in this package
surface fn136—140 141 145 146 151 152 … (94 total)
free_surface fn140—none in this package
clear fn145—168 493 517 522 527
rect fn151—159 160 161 162 203 204 … (12 total)
frame fn157—230 234 235 236
SHADES const166—178 228 252
draw fn175—45 67 86 89 91 96 … (24 total)
display_surface fn195—none in this package
on_display fn201—none in this package
camera fn212—536 545 554 564 569 574 … (11 total)
sprite fn223—546 565 597
fill fn235—179 590
draw_turned fn248—448 462 474 494 504 505 … (10 total)
SHADE_PARTS const258—none in this package
draw_ground fn275—282 292 299 307 315 323 … (23 total)
pixels fn284—46 68 87 90 92 97 … (47 total)
present fn294—157 158 159 162
cell fn304—68 317 343 344 130 142 … (8 total)
from_tiled fn312—333 139 140 141 142 143
layer fn321—335 338 339 343 344 347 … (11 total)
layer_from_tiled_csv fn329—144
free_layer fn338—none in this package
set_cell fn343—147
get_cell fn347—145 146 148 149
draw_layer fn354—132

src/tiles.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// tiles — tile sheets, map layers and sprites on a 16-bit surface, the same on every target.
//
// A surface is drawn at its own resolution.  Its camera (`camera`) says how many of its pixels
// one unit is and which point is at its top-left; every primitive — a sprite placed, turned and
// stretched by fractions of a unit, a filled rectangle, a piece of sloping ground, a map layer —
// is placed in units and rasterised at the surface's pixels, each pixel showing what lies under
// its centre.  So a surface the size of the display draws a game of 16 px tiles at the
// display's full resolution, and zooming is a change of camera.  Without a camera a surface is
// one pixel per unit: the small frame `present` scales up whole (200x120 at 4x for 800x480).
//
// A sheet is converted once, when it is made: one byte per pixel (index 0 transparent, 1..255
// RGB565 colours), tile after tile.  A Kenney 16 px pack of 132 tiles is 34 KB that way, where
// RGBA would be 135 KB.  Colours are RGB565 — `rgb(r, g, b)` makes one — and a sheet with more
// than 255 of them, once in RGB565, is refused.
//
// Orientation is Tiled's: a tile is transposed (the diagonal flip) first, then mirrored
// horizontally, then vertically, so the eight combinations are the eight ways a square can lie.
//
// Handles: a sheet, a surface or a layer is a positive integer, null when it could not be made.
use imaging;

fn tl_set_new(rgba: const vector<u8>, width: integer, height: integer, tile_w: integer,
              tile_h: integer, spacing: integer, margin: integer) -> integer;
#c "tl_set_new" "int64_t(const uint8_t*, int64_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t)"
fn tl_set_count(set: integer) -> integer;
#c "tl_set_count" "int64_t(int64_t)"
fn tl_set_colours(set: integer) -> integer;
#c "tl_set_colours" "int64_t(int64_t)"
fn tl_set_free(set: integer);
#c "tl_set_free" "void(int64_t)"
fn tl_surf_new(width: integer, height: integer) -> integer;
#c "tl_surf_new" "int64_t(int32_t, int32_t)"
fn tl_surf_free(surf: integer);
#c "tl_surf_free" "void(int64_t)"
fn tl_clear(surf: integer, colour: integer);
#c "tl_clear" "void(int64_t, int32_t)"
fn tl_rect(surf: integer, x: integer, y: integer, w: integer, h: integer, colour: integer);
#c "tl_rect" "void(int64_t, int64_t, int64_t, int64_t, int64_t, int32_t)"
fn tl_pixels(surf: integer, out: vector<i32>);
#c "tl_pixels" "void(int64_t, int32_t*)"
fn tl_draw(surf: integer, set: integer, tile: integer, x: integer, y: integer, flags: integer);
#c "tl_draw" "void(int64_t, int64_t, int32_t, int32_t, int32_t, int32_t)"
fn tl_draw_ground(surf: integer, set: integer, tile: integer, x: integer, y: integer,
                  lift_tl: integer, lift_tr: integer, lift_bl: integer, lift_br: integer,
                  dark_tl: integer, dark_tr: integer, dark_bl: integer, dark_br: integer, flags: integer);
#c "tl_draw_ground" "void(int64_t, int64_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t)"
fn tl_draw_turned(surf: integer, set: integer, tile: integer, x: integer, y: integer, degrees: integer,
                  pivot_x: integer, pivot_y: integer, flags: integer);
#c "tl_draw_turned" "void(int64_t, int64_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t)"
fn tl_display_new(width: integer, height: integer) -> integer;
#c "tl_display_new" "int64_t(int32_t, int32_t)"
fn tl_on_display(surf: integer) -> integer;
#c "tl_on_display" "int64_t(int64_t)"
fn tl_camera(surf: integer, zoom: integer, cam_x: integer, cam_y: integer);
#c "tl_camera" "void(int64_t, int64_t, int64_t, int64_t)"
fn tl_sprite(surf: integer, set: integer, tile: integer, x: integer, y: integer, turn: integer,
             pivot_x: integer, pivot_y: integer, scale_x: integer, scale_y: integer, flags: integer);
#c "tl_sprite" "void(int64_t, int64_t, int32_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int32_t)"
fn tl_fill(surf: integer, x: integer, y: integer, w: integer, h: integer, colour: integer);
#c "tl_fill" "void(int64_t, int64_t, int64_t, int64_t, int64_t, int32_t)"
fn tl_map_new(cells: const vector<i32>, cols: integer, rows: integer) -> integer;
#c "tl_map_new" "int64_t(const int32_t*, int64_t, int32_t, int32_t)"
fn tl_map_free(map: integer);
#c "tl_map_free" "void(int64_t)"
fn tl_map_set(map: integer, x: integer, y: integer, cell: integer);
#c "tl_map_set" "void(int64_t, int32_t, int32_t, int32_t)"
fn tl_map_get(map: integer, x: integer, y: integer) -> integer;
#c "tl_map_get" "int64_t(int64_t, int32_t, int32_t)"
fn tl_draw_map(surf: integer, map: integer, set: integer, cam_x: integer, cam_y: integer);
#c "tl_draw_map" "void(int64_t, int64_t, int64_t, int32_t, int32_t)"
fn tl_present(surf: integer, out: vector<i32>, scale: integer, rotate: integer);
#c "tl_present" "void(int64_t, int32_t*, int64_t, int32_t, int32_t)"

fn handle(h: integer) -> integer? {
  if h <= 0 { return null; }
  h
}

fn flags(flip_h: boolean, flip_v: boolean, flip_d: boolean) -> integer {
  (if flip_h { 1 } else { 0 }) + (if flip_v { 2 } else { 0 }) + (if flip_d { 4 } else { 0 })
}

/// An RGB565 colour from 8-bit channels: 5 bits of red, 6 of green, 5 of blue.
pub fn rgb(r: integer, g: integer, b: integer) -> integer {
  ((r & 255) / 8) * 2048 + ((g & 255) / 4) * 32 + (b & 255) / 8
}

// --- Sheets ---

/// A sheet from `width * height` RGBA bytes, cut into `tile_w * tile_h` tiles with `margin`
/// pixels round the sheet and `spacing` between tiles (Tiled's names).  A pixel with alpha
/// below 128 is transparent.  Tiles are numbered from 0, row by row.  Null when the sizes do not
/// fit or the sheet has more than 255 colours once in RGB565.
pub fn sheet(rgba: const vector<u8>, width: integer, height: integer, tile_w: integer,
             tile_h: integer, spacing: integer = 0, margin: integer = 0) -> integer? {
  if len(rgba) < width * height * 4 { return null; }
  handle(tl_set_new(rgba, width, height, tile_w, tile_h, spacing, margin))
}

/// A sheet from a decoded image (`imaging::png`).
pub fn sheet_from_image(img: const imaging::Image, tile_w: integer, tile_h: integer,
                        spacing: integer = 0, margin: integer = 0) -> integer? {
  bytes: vector<u8> = [];
  for p in img.data { bytes += [p.r as u8, p.g as u8, p.b as u8, p.a as u8]; }
  sheet(bytes, img.width, img.height, tile_w, tile_h, spacing, margin)
}

/// A sheet from a PNG file.
pub fn sheet_from_png(path: text, tile_w: integer, tile_h: integer, spacing: integer = 0,
                      margin: integer = 0) -> integer? {
  img = file(path).png();
  if img == null { return null; }
  sheet_from_image(img ?? imaging::Image { }, tile_w, tile_h, spacing, margin)
}

/// How many tiles a sheet holds, and how many colours (at most 255).
pub fn tile_count(sheet: integer) -> integer {
  tl_set_count(sheet)
}

pub fn colour_count(sheet: integer) -> integer {
  tl_set_colours(sheet)
}

pub fn free_sheet(sheet: integer) {
  tl_set_free(sheet);
}

// --- Surfaces ---

/// An RGB565 surface of `width` x `height` pixels, cleared to black, its camera at one pixel per
/// unit (`camera` changes it).
pub fn surface(width: integer, height: integer) -> integer? {
  handle(tl_surf_new(width, height))
}

pub fn free_surface(surface: integer) {
  tl_surf_free(surface);
}

/// Fill a surface with one RGB565 colour.
pub fn clear(surface: integer, colour: integer) {
  tl_clear(surface, colour);
}

/// Fill the `w * h` rectangle with its top-left at (x, y) with one RGB565 colour.  What falls
/// off the surface is skipped, and a rectangle with no width or height draws nothing.
pub fn rect(surface: integer, x: integer, y: integer, w: integer, h: integer, colour: integer) {
  tl_rect(surface, x, y, w, h, colour);
}

/// The one-pixel outline of that rectangle, inside it: a cursor, a selection, the frame round
/// a palette.  Clipped like `rect`.
pub fn frame(surface: integer, x: integer, y: integer, w: integer, h: integer, colour: integer) {
  if w <= 0 || h <= 0 { return; }
  rect(surface, x, y, w, 1, colour);
  rect(surface, x, y + h - 1, w, 1, colour);
  rect(surface, x, y + 1, 1, h - 2, colour);
  rect(surface, x + w - 1, y + 1, 1, h - 2, colour);
}

/// How many shades a tile can be drawn at: 0 is the tile as it is, `SHADES - 1` the darkest.
pub const SHADES = 8;

/// Draw tile `tile` of `sheet` with its top-left at (x, y), in any of the eight orientations.
/// A sprite is a tile drawn this way.  Transparent pixels and whatever falls off the surface
/// are skipped.  `shade` darkens it: 0 is the tile as it is, and each shade up to
/// `SHADES - 1` is darker, down to about a quarter of the light, so the darkest still shows
/// what is there.  A shade costs nothing: each sheet keeps its palette at every shade.  A
/// `ghost` draws every other pixel only, in a checkerboard fixed to the surface — what is behind
/// shows through: a figure seen through what stands in front of it.
pub fn draw(surface: integer, sheet: integer, tile: integer, x: integer, y: integer,
            flip_h: boolean = false, flip_v: boolean = false, flip_d: boolean = false,
            shade: integer = 0, ghost: boolean = false) {
  s = if shade < 0 { 0 } else if shade >= SHADES { SHADES - 1 } else { shade };
  tl_draw(surface, sheet, tile, x, y, flags(flip_h, flip_v, flip_d) + s * 256 + (if ghost { GHOST } else { 0 }));
}

// The flags bit of a ghost (c/tiles.c).
const GHOST = 4096;

// A value in 256ths, rounded to the nearest.
fn q8(v: float) -> integer {
  round(v * 256.0) as integer
}

/// A surface for the display, `width` x `height` pixels — the screen's own size.  It is always
/// drawn through its camera, and where the machine draws faster another way it is drawn that
/// way: in a page, by the GPU, straight onto the canvas (when the canvas is this size).  What it
/// draws is the same picture either way; `pixels` reads it back.  Ask `on_display` whether
/// there is anything left to show.
pub fn display_surface(width: integer, height: integer) -> integer? {
  handle(tl_display_new(width, height))
}

/// True when the surface is drawn straight onto the display, so the frame is on the screen as
/// soon as it is drawn and nothing needs showing.
pub fn on_display(surface: integer) -> boolean {
  tl_on_display(surface) != 0
}

/// Point the surface's camera: `zoom` surface pixels per unit, with the point (x, y), in units,
/// at the surface's top-left.  Everything drawn after it is placed in units and rasterised at
/// the surface's own pixels, so a surface the size of the display draws a game at the display's
/// resolution: a sprite placed between pixels, turned and stretched lands where it is put, and
/// zooming in on two figures or out over the land is a change of camera.  A new surface's
/// camera is 1 pixel per unit at (0, 0), where every call draws as it does without one.
/// A zoom outside 1/256 .. 4096 is ignored.
pub fn camera(surface: integer, zoom: float, x: float = 0.0, y: float = 0.0) {
  tl_camera(surface, round(zoom * 65536.0) as integer, q8(x), q8(y));
}

/// Draw tile `tile` of `sheet` as a sprite: its top-left at (x, y) units, stretched by
/// (`scale_x`, `scale_y`) and turned `turn` degrees clockwise, both about its point
/// (`pivot_x`, `pivot_y`) — in the tile's own pixels, so (8.0, 16.0) is the middle of a 16 px
/// tile's bottom edge.  Every value may be fractional: under a camera the sprite is drawn at
/// the surface's resolution, each pixel showing the tile's pixel under its centre, so pixel
/// art stays crisp at every zoom and angle.  Flips, shade and ghost are `draw`'s; a ghost leaves
/// out every other pixel of the tile, so it turns and stretches with it.
pub fn sprite(surface: integer, sheet: integer, tile: integer, x: float, y: float,
              turn: float = 0.0, pivot_x: float = 0.0, pivot_y: float = 0.0,
              scale_x: float = 1.0, scale_y: float = 1.0,
              flip_h: boolean = false, flip_v: boolean = false, flip_d: boolean = false,
              shade: integer = 0, ghost: boolean = false) {
  s = if shade < 0 { 0 } else if shade >= SHADES { SHADES - 1 } else { shade };
  tl_sprite(surface, sheet, tile, q8(x), q8(y), q8(turn), q8(pivot_x), q8(pivot_y), q8(scale_x),
            q8(scale_y), flags(flip_h, flip_v, flip_d) + s * 256 + (if ghost { GHOST } else { 0 }));
}

/// Fill the rectangle with its top-left at (x, y) and `w` x `h` units in one RGB565 colour, at
/// the surface's resolution: the pixels whose centres lie inside it.
pub fn fill(surface: integer, x: float, y: float, w: float, h: float, colour: integer) {
  tl_fill(surface, q8(x), q8(y), q8(w), q8(h), colour);
}

/// Draw tile `tile` of `sheet` turned `degrees` clockwise about its pixel `pivot` (x, y within
/// the tile): placed as `draw` places it at (x, y), oriented by the flips first, then turned —
/// a character's slight lean as it walks, a weapon held at an angle or swung.  Under a camera it
/// is `sprite` turned about the pivot pixel's centre: a true rotation at the surface's
/// resolution.  At one pixel per unit every pixel of the tile lands on exactly one pixel of the
/// surface instead (the turn is whole quarter turns and three shears of whole rows and
/// columns), so the pixel art keeps its pixels and colours where there are no finer pixels to
/// turn it with.  0 degrees is `draw`, and 90, 180 and 270 are its quarter turns.  The shade,
/// the ghost, transparency and clipping are `draw`'s.
pub fn draw_turned(surface: integer, sheet: integer, tile: integer, x: integer, y: integer,
                   degrees: integer, pivot: (integer, integer), flip_h: boolean = false,
                   flip_v: boolean = false, flip_d: boolean = false, shade: integer = 0,
                   ghost: boolean = false) {
  s = if shade < 0 { 0 } else if shade >= SHADES { SHADES - 1 } else { shade };
  tl_draw_turned(surface, sheet, tile, x, y, degrees, pivot.0, pivot.1,
                 flags(flip_h, flip_v, flip_d) + s * 256 + (if ghost { GHOST } else { 0 }));
}

/// How finely `draw_ground` shades: its darkness is counted in sixteenths of a shade.
pub const SHADE_PARTS = 16;

/// Draw tile `tile` of `sheet` as a piece of ground that slopes and is lit gradually: its place
/// is the plain `draw`'s at (x, y), with its corners — top-left, top-right, bottom-left,
/// bottom-right — lifted `lift` pixels (up is positive, so (4, 4, 0, 0) leans its far edge up
/// a step) and darkened `shade` sixteenths of a shade (`SHADE_PARTS` is one whole shade darker;
/// past `SHADES - 1` whole shades it stays the darkest).
///
/// Each column of the tile stays a column of pixels, stretched or squeezed between its top and
/// bottom edges, whose lifts are interpolated from the corners at the column's centre.  So two
/// tiles that give their shared corners the same lifts meet exactly, with no gap — a slope, a
/// mound, a ramp onto a higher floor; and a drop between them shows as the gap a wall tile (or a
/// darker one) fills, drawn the same way.  The darkness is interpolated across the tile and
/// shared between the two nearest shades by a fixed 4x4 dither, so light fades smoothly within
/// a tile and the pattern stays with the ground as the view moves.  Over a plain `draw` it costs
/// a little per column and a table lookup per pixel; a tile with every lift and shade 0 draws
/// exactly what `draw` draws.  Orientation, transparency and clipping are `draw`'s.
pub fn draw_ground(surface: integer, sheet: integer, tile: integer, x: integer, y: integer,
                   lift: (integer, integer, integer, integer),
                   shade: (integer, integer, integer, integer) = (0, 0, 0, 0),
                   flip_h: boolean = false, flip_v: boolean = false, flip_d: boolean = false) {
  tl_draw_ground(surface, sheet, tile, x, y, lift.0, lift.1, lift.2, lift.3,
                 shade.0, shade.1, shade.2, shade.3, flags(flip_h, flip_v, flip_d));
}

/// The surface's pixels, row by row, each an RGB565 value.
pub fn pixels(surface: integer, width: integer, height: integer) -> vector<i32> {
  out: vector<i32> = [0 as i32; width * height];
  tl_pixels(surface, out);
  out
}

/// The surface scaled by the integer `scale`, as `present` hands it to a display: row by row,
/// (width * scale) x (height * scale) RGB565 values — or, `rotate`d a quarter turn clockwise
/// for a portrait panel, (height * scale) x (width * scale), the surface's top-left at the
/// top-right.
pub fn present(surface: integer, width: integer, height: integer, scale: integer,
               rotate: boolean = false) -> vector<i32> {
  out: vector<i32> = [0 as i32; width * height * scale * scale];
  tl_present(surface, out, scale, if rotate { 1 } else { 0 });
  out
}

// --- Map layers ---

/// A layer cell: tile `tile` (from 0) in one of the eight orientations.  0 is an empty cell.
pub fn cell(tile: integer, flip_h: boolean = false, flip_v: boolean = false,
            flip_d: boolean = false) -> integer {
  (tile + 1) + flags(flip_h, flip_v, flip_d) * 16777216
}

/// A Tiled global tile id (with its flip bits: 31 horizontal, 30 vertical, 29 diagonal) as a
/// cell of a sheet whose first id is `firstgid`; 0 for an empty one or a tile of another sheet
/// (an id below `firstgid`).
pub fn from_tiled(gid: i64, firstgid: integer = 1) -> integer {
  // a Tiled id is 32 unsigned bits with its flips at the top: wider than a 32-bit integer
  id = (gid % 536870912) as integer ?? 0;
  if id < firstgid || id == 0 { return 0; }
  bits = (gid / 536870912) as integer ?? 0;
  cell(id - firstgid, bits / 4 % 2 == 1, bits / 2 % 2 == 1, bits % 2 == 1)
}

/// A map layer of `cols * rows` cells, row by row.  Null when the cell count does not match.
pub fn layer(cells: const vector<integer>, cols: integer, rows: integer) -> integer? {
  if len(cells) != cols * rows { return null; }
  packed: vector<i32> = [];
  for c in cells { packed += [c & 2147483647]; }
  handle(tl_map_new(packed, cols, rows))
}

/// A layer from a Tiled layer's CSV data (`<data encoding="csv">`), its gids read by `from_tiled`.
pub fn layer_from_tiled_csv(csv: text, cols: integer, rows: integer, firstgid: integer = 1) -> integer? {
  cells: vector<integer> = [];
  for part in csv.split(',') {
    t = part.trim();
    if len(t) > 0 { cells += [from_tiled(t as integer? ?? 0, firstgid)]; }
  }
  layer(cells, cols, rows)
}

pub fn free_layer(layer: integer) {
  tl_map_free(layer);
}

/// Set or read one cell; a position off the map is ignored, and reads 0.
pub fn set_cell(layer: integer, x: integer, y: integer, cell: integer) {
  tl_map_set(layer, x, y, cell & 2147483647);
}

pub fn get_cell(layer: integer, x: integer, y: integer) -> integer {
  tl_map_get(layer, x, y)
}

/// Draw every cell of `layer` that shows on `surface` when the layer's pixel (cam_x, cam_y) is
/// the surface's top-left — one call per layer, scrolling to the pixel.  Draw layers back to
/// front.
pub fn draw_layer(surface: integer, layer: integer, sheet: integer, cam_x: integer = 0,
                  cam_y: integer = 0) {
  tl_draw_map(surface, layer, sheet, cam_x, cam_y);
}

tests/tiles.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// The tile layer, read back pixel by pixel; every expected value is computed by hand in its
// cell.  The fixture sheet is 4x2 RGBA pixels, two 2x2 tiles side by side:
//   tile 0:  R G      tile 1:  W W
//            B .               W W      (. transparent)
// In RGB565, R = 63488 (31 << 11), G = 2016 (63 << 5), B = 31, W = 65535; a fresh or cleared
// surface is 0.  A tile drawn at (0, 0) on a 2x2 surface fills it, so a 2x2 cell reads as
// `[top-left, top-right, bottom-left, bottom-right]`.
use tiles;

const R = 63488;
const G = 2016;
const B = 31;
const W = 65535;

fn px(r: integer, g: integer, b: integer, a: integer) -> vector<u8> {
  [(r & 255) as u8, (g & 255) as u8, (b & 255) as u8, (a & 255) as u8]
}

// Row 0: R G W W; row 1: B . W W.
fn fixture() -> integer {
  bytes: vector<u8> = [];
  bytes += px(255, 0, 0, 255);
  bytes += px(0, 255, 0, 255);
  bytes += px(255, 255, 255, 255);
  bytes += px(255, 255, 255, 255);
  bytes += px(0, 0, 255, 255);
  bytes += px(0, 0, 0, 0);
  bytes += px(255, 255, 255, 255);
  bytes += px(255, 255, 255, 255);
  tiles::sheet(bytes, 4, 2, 2, 2) ?? 0
}

fn show(v: const vector<i32>) -> text {
  t = "";
  for p in v { t += "{p},"; }
  t
}

// Tile 0 drawn on a 2x2 surface with the given flips.
fn oriented(flip_h: boolean, flip_v: boolean, flip_d: boolean) -> text {
  s = tiles::surface(2, 2) ?? 0;
  tiles::draw(s, fixture(), 0, 0, 0, flip_h, flip_v, flip_d);
  show(tiles::pixels(s, 2, 2))
}

fn main() {
  assert(tiles::rgb(255, 0, 0) == R && tiles::rgb(0, 255, 0) == G, "RGB565 red and green");
  assert(tiles::rgb(0, 0, 255) == B && tiles::rgb(255, 255, 255) == W, "RGB565 blue and white");
}

// A size far past any surface, as wide as this build's integer holds.
fn huge(n: i64) -> integer { n as integer ?? 2147483647 }

fn test_sheet_counts() {
  s = fixture();
  assert(s > 0, "the sheet is made");
  assert(tiles::tile_count(s) == 2, "two tiles, got {tiles::tile_count(s)}");
  assert(tiles::colour_count(s) == 4, "R, G, B, W, got {tiles::colour_count(s)}");
}

// At (1, 1) on a 4x3 surface; the transparent pixel leaves the background.
fn test_draw_places_and_keeps_transparency() {
  s = tiles::surface(4, 3) ?? 0;
  tiles::draw(s, fixture(), 0, 1, 1);
  got = show(tiles::pixels(s, 4, 3));
  assert(got == "0,0,0,0,0,{R},{G},0,0,{B},0,0,", "got {got}");
}

fn test_the_eight_orientations() {
  assert(oriented(false, false, false) == "{R},{G},{B},0,", "as is: {oriented(false, false, false)}");
  assert(oriented(true, false, false) == "{G},{R},0,{B},", "mirrored: {oriented(true, false, false)}");
  assert(oriented(false, true, false) == "{B},0,{R},{G},", "flipped: {oriented(false, true, false)}");
  assert(oriented(false, false, true) == "{R},{B},{G},0,", "transposed: {oriented(false, false, true)}");
  assert(oriented(true, false, true) == "{B},{R},0,{G},", "a quarter turn clockwise: {oriented(true, false, true)}");
  assert(oriented(true, true, false) == "0,{B},{G},{R},", "a half turn: {oriented(true, true, false)}");
  assert(oriented(false, true, true) == "{G},0,{R},{B},", "a quarter turn back: {oriented(false, true, true)}");
  assert(oriented(true, true, true) == "0,{G},{B},{R},", "the anti-transpose: {oriented(true, true, true)}");
}

// Tile 1 (white) half off the surface at either corner: only the pixel inside is drawn.
fn test_clipping() {
  s = tiles::surface(2, 2) ?? 0;
  tiles::draw(s, fixture(), 1, -1, -1);
  assert(show(tiles::pixels(s, 2, 2)) == "{W},0,0,0,", "top-left: {show(tiles::pixels(s, 2, 2))}");
  t = tiles::surface(2, 2) ?? 0;
  tiles::draw(t, fixture(), 1, 1, 1);
  assert(show(tiles::pixels(t, 2, 2)) == "0,0,0,{W},", "bottom-right: {show(tiles::pixels(t, 2, 2))}");
  tiles::draw(t, fixture(), 7, 0, 0);
  assert(show(tiles::pixels(t, 2, 2)) == "0,0,0,{W},", "a tile the sheet has not draws nothing");
  // Over the left and the right edge, whole rows: a column that is not clipped would land in
  // the neighbouring row (x -1 of row 1 is x 1 of row 0, x 2 of row 0 is x 0 of row 1).
  l = tiles::surface(2, 2) ?? 0;
  tiles::draw(l, fixture(), 1, -1, 0);
  assert(show(tiles::pixels(l, 2, 2)) == "{W},0,{W},0,", "left edge: {show(tiles::pixels(l, 2, 2))}");
  r = tiles::surface(2, 2) ?? 0;
  tiles::draw(r, fixture(), 1, 1, 0);
  assert(show(tiles::pixels(r, 2, 2)) == "0,{W},0,{W},", "right edge: {show(tiles::pixels(r, 2, 2))}");
}

// A 7x4 sheet, margin 1, spacing 1: two 2x2 tiles at x 1..2 and 4..5, y 1..2, the rest magenta.
// Tile 0 is red, tile 1 blue; neither may show magenta.
fn test_margin_and_spacing() {
  bytes: vector<u8> = [];
  for y in 0..4 {
    for x in 0..7 {
      if y >= 1 && y <= 2 && x >= 1 && x <= 2 {
        bytes += px(255, 0, 0, 255);
      } else if y >= 1 && y <= 2 && x >= 4 && x <= 5 {
        bytes += px(0, 0, 255, 255);
      } else {
        bytes += px(255, 0, 255, 255);
      }
    }
  }
  sh = tiles::sheet(bytes, 7, 4, 2, 2, 1, 1) ?? 0;
  assert(tiles::tile_count(sh) == 2, "two tiles, got {tiles::tile_count(sh)}");
  s = tiles::surface(4, 2) ?? 0;
  tiles::draw(s, sh, 0, 0, 0);
  tiles::draw(s, sh, 1, 2, 0);
  got = show(tiles::pixels(s, 4, 2));
  assert(got == "{R},{R},{B},{B},{R},{R},{B},{B},", "got {got}");
}

// A 2x1 layer [tile 0, tile 1] on a 4x2 surface scrolled one pixel right: tile 0's right column
// at x 0 (G over transparent), tile 1 at x 1..2, and nothing past the map's end at x 3.
fn test_layer_scrolls_to_the_pixel() {
  m = tiles::layer([tiles::cell(0), tiles::cell(1)], 2, 1) ?? 0;
  s = tiles::surface(4, 2) ?? 0;
  tiles::draw_layer(s, m, fixture(), 1, 0);
  got = show(tiles::pixels(s, 4, 2));
  assert(got == "{G},{W},{W},0,0,{W},{W},0,", "got {got}");
}

// Tiled ids: bit 31 horizontal, 30 vertical, 29 diagonal; a cell is (tile + 1) | flags << 24.
fn test_tiled_ids() {
  assert(tiles::from_tiled(2) == 2, "gid 2 is tile 1");
  assert(tiles::from_tiled(2147483650l) == 16777218, "0x80000002: tile 1 mirrored");
  assert(tiles::from_tiled(2684354561l) == 83886081, "0xA0000001: tile 0 mirrored and transposed");
  assert(tiles::from_tiled(0) == 0, "an empty cell");
  assert(tiles::from_tiled(5, 10) == 0, "a tile of an earlier sheet");
  m = tiles::layer_from_tiled_csv("1,2,\n0,2147483650", 2, 2) ?? 0;
  assert(tiles::get_cell(m, 0, 0) == 1 && tiles::get_cell(m, 1, 0) == 2, "the first row");
  assert(tiles::get_cell(m, 0, 1) == 0 && tiles::get_cell(m, 1, 1) == 16777218, "the second row");
  tiles::set_cell(m, 0, 1, tiles::cell(1, true));
  assert(tiles::get_cell(m, 0, 1) == 16777218, "a cell set");
  assert(tiles::get_cell(m, 9, 9) == 0, "off the map reads 0");
}

// A 2x1 surface [R, G] scaled 2: two rows of R R G G.  Rotated a quarter turn clockwise it is
// 1x2 (R over G), and scaled 2 that is 2x4.
fn test_present_scales_and_rotates() {
  s = tiles::surface(2, 1) ?? 0;
  tiles::draw(s, fixture(), 0, 0, 0);
  assert(show(tiles::present(s, 2, 1, 2)) == "{R},{R},{G},{G},{R},{R},{G},{G},", "scaled");
  assert(show(tiles::present(s, 2, 1, 1, true)) == "{R},{G},", "rotated");
  assert(show(tiles::present(s, 2, 1, 2, true)) == "{R},{R},{R},{R},{G},{G},{G},{G},", "rotated, scaled");
  q = tiles::surface(2, 2) ?? 0;
  tiles::draw(q, fixture(), 0, 0, 0);
  got = show(tiles::present(q, 2, 2, 1, true));
  assert(got == "{B},{R},0,{G},", "R G over B . turns to B R over . G: {got}");
}

fn test_clear() {
  s = tiles::surface(2, 1) ?? 0;
  tiles::clear(s, tiles::rgb(0, 255, 0));
  assert(show(tiles::pixels(s, 2, 1)) == "{G},{G},", "cleared to green");
}

// 272 distinct RGB565 colours (red in 32 steps, green in 9) are more than a sheet's 255.
fn test_too_many_colours() {
  bytes: vector<u8> = [];
  for i in 0..272 { bytes += px(i % 32 * 8, i / 32 * 4, 0, 255); }
  assert(!tiles::sheet(bytes, 272, 1, 1, 1), "refused");
  assert(!tiles::sheet(bytes, 4, 1, 8, 8), "a tile larger than the sheet");
  assert(!tiles::surface(0, 5), "an empty surface");
  assert(!tiles::layer([1, 2, 3], 2, 2), "a layer whose cells do not fill it");
}

// A shade multiplies each RGB565 channel by a level's factor out of 256, rounded down:
// level 1 is 208 (red 31 -> 25: 51200; green 63 -> 51: 1632; blue 31 -> 25), level 7 is 58 (red 31 -> 7: 14336; white is red 7,
// green 63 -> 14, blue 7: 14336 + 448 + 7 = 14791).  A shade past the last is the last.
fn test_shades() {
  s = tiles::surface(2, 2) ?? 0;
  tiles::draw(s, fixture(), 0, 0, 0, false, false, false, 1);
  assert(show(tiles::pixels(s, 2, 2)) == "51200,1632,25,0,", "level 1: {show(tiles::pixels(s, 2, 2))}");
  t = tiles::surface(2, 2) ?? 0;
  tiles::draw(t, fixture(), 1, 0, 0, false, false, false, 7);
  assert(show(tiles::pixels(t, 2, 2)) == "14791,14791,14791,14791,", "level 7: {show(tiles::pixels(t, 2, 2))}");
  u = tiles::surface(2, 2) ?? 0;
  tiles::draw(u, fixture(), 1, 0, 0, false, false, false, 99);
  assert(show(tiles::pixels(u, 2, 2)) == "14791,14791,14791,14791,", "past the last: {show(tiles::pixels(u, 2, 2))}");
}


// A filled rectangle is clipped at every edge.  On a 4x3 surface, (-1, 1) 3x5 covers x 0..1 and
// y 1..2; (3, 2) 9x9 only the bottom-right pixel.  Off the surface, or with no width or height,
// it draws nothing.
fn test_rect_clips() {
  s = tiles::surface(4, 3) ?? 0;
  tiles::rect(s, -1, 1, 3, 5, G);
  tiles::rect(s, 3, 2, 9, 9, R);
  tiles::rect(s, 4, 0, 1, 1, B);
  tiles::rect(s, 0, -1, 4, 1, B);
  tiles::rect(s, 0, 0, 0, 3, B);
  tiles::rect(s, 0, 0, 2, -1, B);
  got = show(tiles::pixels(s, 4, 3));
  assert(got == "0,0,0,0,{G},{G},0,0,{G},{G},0,{R},", "got {got}");
}

// Sizes past 32 bits are clipped, not wrapped: 4294967297 is 2^32 + 1, which as a 32-bit
// width would be 1 and fill one pixel of the two.
fn test_rect_is_clipped_not_wrapped() {
  s = tiles::surface(2, 1) ?? 0;
  tiles::rect(s, 0, 0, huge(4294967297l), 1, W);
  assert(show(tiles::pixels(s, 2, 1)) == "{W},{W},", "got {show(tiles::pixels(s, 2, 1))}");
  t = tiles::surface(2, 1) ?? 0;
  // its left edge a thousand million to the left, its width past the right edge at either width
  tiles::rect(t, -1000000000, -5, huge(2000000000000l), 10, R);
  assert(show(tiles::pixels(t, 2, 1)) == "{R},{R},", "got {show(tiles::pixels(t, 2, 1))}");
}

// The outline of a 4x3 rectangle at (0, 0) leaves the two middle pixels; one 3x3 at (-1, -1)
// on a 3x3 surface keeps only its bottom row (x 0..1 at y 1) and its right column (x 1, y 0);
// a 1x1 frame is one pixel and a 0-wide one nothing.
fn test_frame() {
  s = tiles::surface(4, 3) ?? 0;
  tiles::frame(s, 0, 0, 4, 3, R);
  got = show(tiles::pixels(s, 4, 3));
  assert(got == "{R},{R},{R},{R},{R},0,0,{R},{R},{R},{R},{R},", "4x3: {got}");
  t = tiles::surface(3, 3) ?? 0;
  tiles::frame(t, -1, -1, 3, 3, B);
  tiles::frame(t, 2, 2, 1, 1, G);
  tiles::frame(t, 0, 2, 0, 1, W);
  got = show(tiles::pixels(t, 3, 3));
  assert(got == "0,{B},0,{B},{B},0,0,0,{G},", "clipped: {got}");
}

// --- Ground: draw_ground ---
//
// A second fixture: one 2x4 tile, a colour per row — R, G, B, W from the top — so a column read
// top to bottom shows which tile row each pixel took.  `column(s, x, h)` reads column x of a
// surface h high, one letter a pixel (. for nothing drawn).

fn rows_fixture() -> integer {
  bytes: vector<u8> = [];
  for c in [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)] {
    bytes += px(c.0, c.1, c.2, 255);
    bytes += px(c.0, c.1, c.2, 255);
  }
  tiles::sheet(bytes, 2, 4, 2, 4) ?? 0
}

// Shade 1 (x 208 / 256 per channel, rounded down) as lower case: r = 25 << 11, g = 51 << 5,
// b = 25, w = all three; shade 2 (x 168 / 256) as digits: 1 = 20 << 11, 2 = 41 << 5, 3 = 20,
// 4 = all three.
fn letter(p: integer) -> text {
  if p == R { "R" } else if p == G { "G" } else if p == B { "B" } else if p == W { "W" }
  else if p == 51200 { "r" } else if p == 1632 { "g" } else if p == 25 { "b" } else if p == 52857 { "w" }
  else if p == 40960 { "1" } else if p == 1312 { "2" } else if p == 20 { "3" } else if p == 42292 { "4" }
  else if p == 0 { "." } else { "?" }
}

fn column(s: integer, x: integer, w: integer, h: integer) -> text {
  v = tiles::pixels(s, w, h);
  t = "";
  for y in 0..h { t += letter(v[y * w + x] ?? -1); }
  t
}

// With every lift and shade 0 it is `draw`, in all eight orientations, transparency included.
fn test_flat_ground_is_draw() {
  for o in 0..8 {
    fh = (o & 1) != 0;
    fv = (o & 2) != 0;
    fd = (o & 4) != 0;
    a = tiles::surface(4, 3) ?? 0;
    tiles::draw(a, fixture(), 0, 1, 1, fh, fv, fd);
    b = tiles::surface(4, 3) ?? 0;
    tiles::draw_ground(b, fixture(), 0, 1, 1, (0, 0, 0, 0), (0, 0, 0, 0), fh, fv, fd);
    assert(show(tiles::pixels(a, 4, 3)) == show(tiles::pixels(b, 4, 3)),
           "orientation {o}: {show(tiles::pixels(a, 4, 3))} against {show(tiles::pixels(b, 4, 3))}");
  }
}

// The top edge lifted 2 at y 2: rows 0 .. 5 (6 pixels for 4 rows), each taking the row under its
// centre, floor((2k + 1) * 4 / 12): R G G B W W.
fn test_a_lifted_edge_stretches() {
  s = tiles::surface(2, 8) ?? 0;
  tiles::draw_ground(s, rows_fixture(), 0, 0, 2, (2, 2, 0, 0));
  assert(column(s, 0, 2, 8) == "RGGBWW.." && column(s, 1, 2, 8) == "RGGBWW..", "got {column(s, 0, 2, 8)}");
}

// The bottom edge lifted 2 at y 0: two pixels, rows floor(4 / 4) = 1 and floor(12 / 4) = 3.
fn test_a_lifted_bottom_squeezes() {
  s = tiles::surface(2, 4) ?? 0;
  tiles::draw_ground(s, rows_fixture(), 0, 0, 0, (0, 0, 2, 2));
  assert(column(s, 0, 2, 4) == "GW.." && column(s, 1, 2, 4) == "GW..", "got {column(s, 0, 2, 4)}");
}

// The right corners lifted 4 at y 4: column 0 (centre 1/4 across) lifts round(1) = 1, column 1
// (3/4) round(3) = 3 — a ramp, each column whole.
fn test_a_ramp_shears_by_column() {
  s = tiles::surface(2, 8) ?? 0;
  tiles::draw_ground(s, rows_fixture(), 0, 0, 4, (0, 4, 0, 4));
  assert(column(s, 0, 2, 8) == "...RGBW." && column(s, 1, 2, 8) == ".RGBW...",
         "got {column(s, 0, 2, 8)} {column(s, 1, 2, 8)}");
}

// Lowered 2 (negative lifts round down, floor(-1.5) = -2): rows 2 .. 5.
fn test_a_negative_lift_lowers() {
  s = tiles::surface(2, 8) ?? 0;
  tiles::draw_ground(s, rows_fixture(), 0, 0, 0, (-2, -2, -2, -2));
  assert(column(s, 0, 2, 8) == "..RGBW..", "got {column(s, 0, 2, 8)}");
}

// Two tiles sharing their corners' lifts meet exactly: the north one (y 4, lifts 4 and 2) spans
// rows 0 .. 5, the south one (y 8, lifts 2 and 0) rows 6 .. 11 — no gap, no overlap.
fn test_shared_corners_meet_without_a_seam() {
  s = tiles::surface(2, 16) ?? 0;
  tiles::draw_ground(s, rows_fixture(), 0, 0, 4, (4, 4, 2, 2));
  tiles::draw_ground(s, rows_fixture(), 0, 0, 8, (2, 2, 0, 0));
  assert(column(s, 0, 2, 16) == "RGGBWWRGGBWW....", "got {column(s, 0, 2, 16)}");
}

// Clipped like draw: lifted 4 at y 2 the tile spans rows -2 .. 1, and only rows 0, 1 (tile rows
// floor(20 / 8) = 2 and 3) are drawn.  A ramp (0, 4, 0, 4) at x -1 shows only its second
// column, at the surface's x 0: lifted 3, it spans rows -3 .. 0, so only its last row (W) shows.
fn test_ground_clips() {
  s = tiles::surface(2, 4) ?? 0;
  tiles::draw_ground(s, rows_fixture(), 0, 0, 2, (4, 4, 4, 4));
  assert(column(s, 0, 2, 4) == "BW.." && column(s, 1, 2, 4) == "BW..", "top: {column(s, 0, 2, 4)}");
  t = tiles::surface(2, 4) ?? 0;
  tiles::draw_ground(t, rows_fixture(), 0, -1, 0, (0, 4, 0, 4));
  assert(column(t, 0, 2, 4) == "W..." && column(t, 1, 2, 4) == "....", "left: {column(t, 0, 2, 4)} {column(t, 1, 2, 4)}");
}

// Shade 0 at the top corners, 16 (one shade) at the bottom: the white 2x2 tile's rows are
// 4 and 12 sixteenths darker (interpolated at the row centres, (16 * 1 + 2) / 4 and
// (16 * 3 + 2) / 4), so a pixel takes shade 1 where that exceeds its dither threshold — row 0
// (thresholds 0, 8): the first; row 1 (12, 4): the second.  Shade 1 of white is 52857.
fn test_shade_fades_with_a_dither() {
  s = tiles::surface(2, 2) ?? 0;
  tiles::draw_ground(s, fixture(), 1, 0, 0, (0, 0, 0, 0), (0, 0, 16, 16));
  got = show(tiles::pixels(s, 2, 2));
  assert(got == "52857,{W},{W},52857,", "got {got}");
}

// Whole shades need no dither: 32 sixteenths everywhere is shade 2 on every pixel; past the
// darkest it is the darkest (14791 for white), and below 0 it is the tile as it is.
fn test_shade_whole_and_clamped() {
  s = tiles::surface(2, 2) ?? 0;
  tiles::draw(s, fixture(), 1, 0, 0, false, false, false, 2);
  want = show(tiles::pixels(s, 2, 2));
  t = tiles::surface(2, 2) ?? 0;
  tiles::draw_ground(t, fixture(), 1, 0, 0, (0, 0, 0, 0), (32, 32, 32, 32));
  assert(show(tiles::pixels(t, 2, 2)) == want, "shade 2: {show(tiles::pixels(t, 2, 2))} against {want}");
  u = tiles::surface(2, 2) ?? 0;
  tiles::draw_ground(u, fixture(), 1, 0, 0, (0, 0, 0, 0), (999, 999, 999, 999));
  assert(show(tiles::pixels(u, 2, 2)) == "14791,14791,14791,14791,", "darkest: {show(tiles::pixels(u, 2, 2))}");
  v = tiles::surface(2, 2) ?? 0;
  tiles::draw_ground(v, fixture(), 1, 0, 0, (0, 0, 0, 0), (-50, -50, -50, -50));
  assert(show(tiles::pixels(v, 2, 2)) == "{W},{W},{W},{W},", "lightest: {show(tiles::pixels(v, 2, 2))}");
}

// Half pixels round up: a ramp (0, 2, 0, 2) lifts column 0 by round(0.5) = 1 and column 1 by
// round(1.5) = 2; lowered (0, -2, 0, -2), round(-0.5) = 0 and round(-1.5) = -1.
fn test_half_pixels_round_up() {
  s = tiles::surface(2, 8) ?? 0;
  tiles::draw_ground(s, rows_fixture(), 0, 0, 2, (0, 2, 0, 2));
  assert(column(s, 0, 2, 8) == ".RGBW..." && column(s, 1, 2, 8) == "RGBW....", "up: {column(s, 0, 2, 8)} {column(s, 1, 2, 8)}");
  t = tiles::surface(2, 8) ?? 0;
  tiles::draw_ground(t, rows_fixture(), 0, 0, 2, (0, -2, 0, -2));
  assert(column(t, 0, 2, 8) == "..RGBW.." && column(t, 1, 2, 8) == "...RGBW.", "down: {column(t, 0, 2, 8)} {column(t, 1, 2, 8)}");
}

// Uneven shared corners still meet: north at y 5 lifted (3, 5, 1, 2), south at y 9 (1, 2, 0, 0).
// Column 0: the north edge lifted round(14 / 4) = 4 and round(5 / 4) = 1 — rows 1 .. 7, seven
// pixels, tile rows floor((2k + 1) * 4 / 14) = R R G B B W W; the south one from row 8 to 12,
// rows floor((2k + 1) * 4 / 10) = R G B B W.  Column 1: lifts round(18 / 4) = 5 and
// round(7 / 4) = 2 — north rows 0 .. 6, south 7 .. 12 (floor((2k + 1) * 4 / 12) = R G G B W W).
fn test_uneven_corners_meet_without_a_seam() {
  s = tiles::surface(2, 16) ?? 0;
  tiles::draw_ground(s, rows_fixture(), 0, 0, 5, (3, 5, 1, 2));
  tiles::draw_ground(s, rows_fixture(), 0, 0, 9, (1, 2, 0, 0));
  assert(column(s, 0, 2, 16) == ".RRGBBWWRGBBW..." && column(s, 1, 2, 16) == "RRGBBWWRGGBWW...",
         "got {column(s, 0, 2, 16)} {column(s, 1, 2, 16)}");
}

// A ramp in one whole shade: the ramp of test_a_ramp_shears_by_column, every pixel shade 2.
fn test_a_ramp_in_one_shade() {
  s = tiles::surface(2, 8) ?? 0;
  tiles::draw_ground(s, rows_fixture(), 0, 0, 4, (0, 4, 0, 4), (32, 32, 32, 32));
  assert(column(s, 0, 2, 8) == "...1234." && column(s, 1, 2, 8) == ".1234...", "got {column(s, 0, 2, 8)} {column(s, 1, 2, 8)}");
}

// Stretched and fading: the tile of test_a_lifted_edge_stretches (rows R G G B W W) darkening
// from 0 at the top corners to 16 at the bottom ones.  Tile row q is 4q + 2 sixteenths dark
// (floor((16 * (2q + 1) + 4) / 8)), so 2, 6, 10, 14; a pixel takes shade 1 where that exceeds
// the dither threshold of its TILE row — column 0's thresholds 0, 12, 3, 15 darken rows 0 and 2,
// column 1's 8, 4, 11, 7 rows 1 and 3 — and a stretched row's two pixels choose alike.
fn test_a_stretched_tile_fades() {
  s = tiles::surface(2, 8) ?? 0;
  tiles::draw_ground(s, rows_fixture(), 0, 0, 2, (2, 2, 0, 0), (0, 0, 16, 16));
  assert(column(s, 0, 2, 8) == "rGGbWW.." && column(s, 1, 2, 8) == "RggBww..", "got {column(s, 0, 2, 8)} {column(s, 1, 2, 8)}");
}

// Half a shade (8 sixteenths) everywhere is no whole shade: it dithers, flat and on a ramp alike.
// A pixel takes shade 1 where 8 exceeds its threshold: flat, the white 2x2 tile's thresholds
// 0, 8 / 12, 4 darken its first and last pixel; on the ramp of test_a_ramp_shears_by_column,
// column 0 (0, 12, 3, 15) darkens tile rows 0 and 2, column 1 (8, 4, 11, 7) rows 1 and 3.
fn test_a_fraction_of_a_shade_dithers_evenly() {
  s = tiles::surface(2, 2) ?? 0;
  tiles::draw_ground(s, fixture(), 1, 0, 0, (0, 0, 0, 0), (8, 8, 8, 8));
  assert(show(tiles::pixels(s, 2, 2)) == "52857,{W},{W},52857,", "flat: {show(tiles::pixels(s, 2, 2))}");
  t = tiles::surface(2, 8) ?? 0;
  tiles::draw_ground(t, rows_fixture(), 0, 0, 4, (0, 4, 0, 4), (8, 8, 8, 8));
  assert(column(t, 0, 2, 8) == "...rGbW." && column(t, 1, 2, 8) == ".RgBw...", "ramp: {column(t, 0, 2, 8)} {column(t, 1, 2, 8)}");
}

// --- Turned: draw_turned ---

// Opaque pixels of a w x h surface, and how many of each fixture colour.
fn census(s: integer, w: integer, h: integer) -> text {
  n = 0;
  r = 0;
  g = 0;
  b = 0;
  wh = 0;
  for p in tiles::pixels(s, w, h) {
    if p != 0 { n += 1; }
    if p == R { r += 1; }
    if p == G { g += 1; }
    if p == B { b += 1; }
    if p == W { wh += 1; }
  }
  "{n}: {r} {g} {b} {wh}"
}

// No turn is draw, in every orientation and about any pivot.
fn test_no_turn_is_draw() {
  for o in 0..8 {
    a = tiles::surface(4, 3) ?? 0;
    tiles::draw(a, fixture(), 0, 1, 1, (o & 1) != 0, (o & 2) != 0, (o & 4) != 0);
    b = tiles::surface(4, 3) ?? 0;
    tiles::draw_turned(b, fixture(), 0, 1, 1, 0, (1, 0), (o & 1) != 0, (o & 2) != 0, (o & 4) != 0);
    assert(show(tiles::pixels(a, 4, 3)) == show(tiles::pixels(b, 4, 3)), "orientation {o}: {show(tiles::pixels(b, 4, 3))}");
  }
}

// Quarter turns about the top-left pixel are draw's quarter turns, moved so that pixel stays:
// 90 (a quarter turn clockwise) lands at x - 1, 180 (a half turn) at (x - 1, y - 1), 270 (a
// quarter turn back) at y - 1; and -90 is 270, 450 is 90.
fn test_quarter_turns_are_draw() {
  for c in [(90, -1, 0, true, false, true), (180, -1, -1, true, true, false), (270, 0, -1, false, true, true),
            (-90, 0, -1, false, true, true), (450, -1, 0, true, false, true)] {
    a = tiles::surface(4, 4) ?? 0;
    tiles::draw(a, fixture(), 0, 1 + c.1, 1 + c.2, c.3, c.4, c.5);
    b = tiles::surface(4, 4) ?? 0;
    tiles::draw_turned(b, fixture(), 0, 1, 1, c.0, (0, 0));
    assert(show(tiles::pixels(a, 4, 4)) == show(tiles::pixels(b, 4, 4)), "{c.0}: {show(tiles::pixels(b, 4, 4))} against {show(tiles::pixels(a, 4, 4))}");
  }
}

// 45 degrees about the bottom-left pixel of the R G B W column tile, drawn at (2, 1) so the
// pivot is (2, 4).  Each pixel (u, v) about the pivot goes u += round(-0.414 v),
// v += round(0.707 u), u += round(-0.414 v): R (0, -3) to (2, -2) and (1, -3) to (3, -2); G
// (0, -2) to (1, -1), (1, -2) to (2, -1); B (0, -1) stays, (1, -1) to (1, 0); W (0, 0) stays,
// (1, 0) to (1, 1).
fn test_forty_five_degrees() {
  s = tiles::surface(6, 6) ?? 0;
  tiles::draw_turned(s, rows_fixture(), 0, 2, 1, 45, (0, 3));
  t = "";
  for y in 2..6 { t += "{column_row(s, y, 6)}/"; }
  assert(t == "....RR/..BGG./..WB../...W../", "got {t}");
}

fn column_row(s: integer, y: integer, w: integer) -> text {
  v = tiles::pixels(s, w, 6);
  t = "";
  for x in 0..w { t += letter(v[y * w + x] ?? -1); }
  t
}

// Every turn keeps every pixel: at each whole degree of a full turn, the column tile turned about
// its middle on a surface it cannot leave shows its 8 pixels, two of each colour.
fn test_every_turn_keeps_every_pixel() {
  s = tiles::surface(12, 12) ?? 0;
  bad = "";
  for deg in -180..181 {
    tiles::clear(s, 0);
    tiles::draw_turned(s, rows_fixture(), 0, 5, 4, deg, (1, 2));
    c = census(s, 12, 12);
    if c != "8: 2 2 2 2" { bad += "{deg}={c} "; }
  }
  assert(bad == "", "lost or doubled pixels: {bad}");
}

// Turned off the surface's edge it is clipped, and shaded like draw.
fn test_turned_clips_and_shades() {
  s = tiles::surface(2, 2) ?? 0;
  tiles::draw_turned(s, fixture(), 1, -1, -1, 30, (1, 1));
  tiles::draw_turned(s, fixture(), 1, 50, 50, 30, (1, 1));
  assert(census(s, 2, 2) != "0: 0 0 0 0", "the corner inside is drawn: {census(s, 2, 2)}");
  t = tiles::surface(2, 2) ?? 0;
  tiles::draw_turned(t, fixture(), 1, 0, 0, 0, (0, 0), false, false, false, 7);
  assert(show(tiles::pixels(t, 2, 2)) == "14791,14791,14791,14791,", "shade 7: {show(tiles::pixels(t, 2, 2))}");
}

// A ghost draws every other pixel, a checkerboard fixed to the surface: the white tile at (1, 1)
// on a blue surface keeps (1, 1) and (2, 2) — x + y even — and leaves the blue at (2, 1) and
// (1, 2); at (2, 1) it keeps (3, 1) and (2, 2).  Turned 0 degrees, the same.
fn test_a_ghost_lets_what_is_behind_show() {
  s = tiles::surface(4, 3) ?? 0;
  tiles::clear(s, B);
  tiles::draw(s, fixture(), 1, 1, 1, false, false, false, 0, true);
  got = show(tiles::pixels(s, 4, 3));
  assert(got == "{B},{B},{B},{B},{B},{W},{B},{B},{B},{B},{W},{B},", "at (1, 1): {got}");
  t = tiles::surface(4, 3) ?? 0;
  tiles::clear(t, B);
  tiles::draw(t, fixture(), 1, 2, 1, false, false, false, 0, true);
  got2 = show(tiles::pixels(t, 4, 3));
  assert(got2 == "{B},{B},{B},{B},{B},{B},{B},{W},{B},{B},{W},{B},", "at (2, 1): {got2}");
  u = tiles::surface(4, 3) ?? 0;
  tiles::clear(u, B);
  tiles::draw_turned(u, fixture(), 1, 1, 1, 0, (0, 0), false, false, false, 0, true);
  assert(show(tiles::pixels(u, 4, 3)) == got, "turned 0: {show(tiles::pixels(u, 4, 3))}");
}

// ── A camera: drawing at the surface's own resolution ──

fn test_a_camera_zoom_draws_each_texel_as_a_block() {
  s = tiles::surface(4, 4) ?? 0;
  tiles::camera(s, 2.0);
  tiles::draw(s, fixture(), 0, 0, 0);
  got = show(tiles::pixels(s, 4, 4));
  assert(got == "{R},{R},{G},{G},{R},{R},{G},{G},{B},{B},0,0,{B},{B},0,0,", "R G over B . at zoom 2: {got}");
}

// At zoom 2 a pixel is half a unit: a sprite half a unit right moves one pixel.
fn test_half_a_unit_is_a_pixel_at_zoom_two() {
  s = tiles::surface(6, 2) ?? 0;
  tiles::camera(s, 2.0);
  tiles::sprite(s, fixture(), 0, 0.5, 0.0);
  got = show(tiles::pixels(s, 6, 2));
  assert(got == "0,{R},{R},{G},{G},0,0,{R},{R},{G},{G},0,", "shifted one pixel: {got}");
}

// Pixel centres at zoom 1.5 are 1/3, 1 and 5/3 units: texel 0, then texel 1 twice.
fn test_a_fractional_zoom_samples_pixel_centres() {
  s = tiles::surface(3, 1) ?? 0;
  tiles::camera(s, 1.5);
  tiles::draw(s, fixture(), 0, 0, 0);
  got = show(tiles::pixels(s, 3, 1));
  assert(got == "{R},{G},{G},", "zoom 1.5: {got}");
}

// Under a camera a turn is a true rotation: a quarter turn clockwise about the tile's centre
// takes R G over B . to B R over . G, here at zoom 2.
fn test_a_quarter_turn_under_a_camera() {
  s = tiles::surface(4, 4) ?? 0;
  tiles::camera(s, 2.0);
  tiles::sprite(s, fixture(), 0, 0.0, 0.0, 90.0, 1.0, 1.0);
  got = show(tiles::pixels(s, 4, 4));
  assert(got == "{B},{B},{R},{R},{B},{B},{R},{R},0,0,{G},{G},0,0,{G},{G},", "turned: {got}");
  t = tiles::surface(4, 4) ?? 0;
  tiles::camera(t, 2.0);
  tiles::draw_turned(t, fixture(), 0, 0, 0, 90, (0, 0));
  got = show(tiles::pixels(t, 4, 4));
  // About pixel (0, 0)'s centre, (0.5, 0.5): the tile turns onto x -1 .. 1, so its right
  // column (B R) is what lands on the surface, its left (. G) off it.
  assert(got == "{R},{R},0,0,{R},{R},0,0,{G},{G},0,0,{G},{G},0,0,", "draw_turned under a camera: {got}");
}

fn test_the_camera_moves_the_view() {
  s = tiles::surface(2, 2) ?? 0;
  tiles::camera(s, 1.0, 1.0, 0.0);
  tiles::draw(s, fixture(), 0, 0, 0);
  got = show(tiles::pixels(s, 2, 2));
  assert(got == "{G},0,0,0,", "the view starts a unit right: {got}");
}

// A fill covers the pixels whose centres lie inside it: at zoom 4 the centres are 1/8, 3/8, 5/8
// and 7/8, so 1/4 .. 3/4 covers the middle two.
fn test_a_fill_covers_pixel_centres() {
  s = tiles::surface(4, 1) ?? 0;
  tiles::camera(s, 4.0);
  tiles::fill(s, 0.25, 0.0, 0.5, 1.0, W);
  got = show(tiles::pixels(s, 4, 1));
  assert(got == "0,{W},{W},0,", "the middle two: {got}");
}

fn test_a_sprite_stretches() {
  s = tiles::surface(4, 2) ?? 0;
  tiles::sprite(s, fixture(), 0, 0.0, 0.0, scale_x: 2.0);
  got = show(tiles::pixels(s, 4, 2));
  assert(got == "{R},{R},{G},{G},{B},{B},0,0,", "twice as wide: {got}");
}

// A ghost leaves out every other texel, so at zoom 2 the checkerboard is of 2x2 blocks.
fn test_a_ghost_turns_with_the_tile() {
  s = tiles::surface(4, 4) ?? 0;
  tiles::camera(s, 2.0);
  tiles::draw(s, fixture(), 1, 0, 0, ghost: true);
  got = show(tiles::pixels(s, 4, 4));
  assert(got == "{W},{W},0,0,{W},{W},0,0,0,0,{W},{W},0,0,{W},{W},", "blocks: {got}");
}

// Ground under a camera: flat and in one shade it is `draw`'s blocks.  Lifted, its top edge is
// a straight line at the surface's resolution: tile 1 (all W) at (0, 3), its top-right corner
// lifted 4, at zoom 2.  Column i's centre is a = (2i + 1) / 4 units in, so its top is at
// 3 - 4a/2 = 3 - 2a: 2.5, 1.5, 0.5 and -0.5; row j's centre is (2j + 1) / 4, so the first
// row covered is 5, 3, 1 and 0, and every column ends above the bottom at 5 units (row 9).
fn test_ground_under_a_camera() {
  s = tiles::surface(4, 4) ?? 0;
  tiles::camera(s, 2.0);
  tiles::draw_ground(s, fixture(), 0, 0, 0, (0, 0, 0, 0));
  got = show(tiles::pixels(s, 4, 4));
  assert(got == "{R},{R},{G},{G},{R},{R},{G},{G},{B},{B},0,0,{B},{B},0,0,", "flat: {got}");
  t = tiles::surface(4, 11) ?? 0;
  tiles::camera(t, 2.0);
  tiles::draw_ground(t, fixture(), 1, 0, 3, (0, 4, 0, 0));
  first = [5, 3, 1, 0];
  want = "";
  for j in 0..11 {
    for i in 0..4 { want += if j >= first[i] && j <= 9 { "{W}," } else { "0," }; }
  }
  got = show(tiles::pixels(t, 4, 11));
  assert(got == want, "a lifted corner, row by row: {got}");
}