Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-canvas

Source of release 0.5.1

0.5.1 / src / tiles / module.lucb

## Layer pixels, cut into 256 by 256 tiles that are immutable and structurally
## shared: cloning a Tiles is O(tiles) pointer copies, replacing one tile leaves
## every other one shared with the clone, and a tile's storage goes when its
## last holder does. That sharing is what makes destructive editing cheap: a
## stroke replaces only the tiles it touched, and history keeps the old ones.
## Texels are straight-alpha rgba16_float in the document's working space
## (linear light). A tile lives on the GPU, in RAM, or both (tiles/residency):
## `texture` brings it to the GPU when it is wanted there.
import c
import interop
from luce_std import files
from luce_gpu import gpu
import memory
import os
from luce_std import paths
import platform
import strings
import pool
from half import to_half, from_half
from wake import wake_frames
from luce_raster.errors import invalid, limit

pub let tile_size: u32 = 256

## One shared tile. Its texture is never written once shared; a stroke may
## draw again into a tile only it holds (`redrawn`), which gives it a new stamp.
## Its content has a copy on the GPU (`on_gpu`, `texture`), in RAM (`ram`, the
## texture's 256 rows of half floats), or both; see tiles/residency.
pub struct Tile:
    var texture: gpu.Texture
    var on_gpu: bool
    var ram: u8[]
    var references: usize
    ## Unique among every tile's content so far: what the compositor's cache
    ## keys on, so only the cells that changed are flattened again.
    var stamp: u64
    ## The residency epoch it was last handed out in: pinned on the GPU while
    ## that epoch lasts.
    var used: u64
    ## The marking generation that last found it in a document (not only in
    ## history or a job's copy).
    var live: u64
    ## Its slot in the scratch file (tiles/scratch), or -1 when it has none.
    var disk: i64
    ## How many bytes of the slot hold it compressed; 0 when the slot holds it whole.
    var disk_length: u32
    ## Its content compressed in RAM by the application's tile codec
    ## (tiles/compressed), or empty.
    var packed: u8[]
    ## The codec found it did not pay to compress: it goes to disk whole.
    var raw_only: bool
    ## A background batch is decoding it (tiles/prefetch).
    var loading: bool
    ## The document file record that also holds it (tiles/backing), if any:
    ## such a tile leaves the GPU and RAM without being written anywhere.
    var source: TileSource*?
    var source_offset: u64
    var source_length: u32
    var source_rows: u32
    ## Every tile, in the order made: what the governor walks.
    var previous: Tile*?
    var next: Tile*?

## The last stamp handed out; tiles live on the main thread.
var last_stamp: u64 = 0

## How many tiles exist, shared ones once: a diagnostic of GPU memory held by
## layers, masks, history and selections (caches count their own bytes).
var live_tiles: usize = 0

## How many tiles exist, each 512 KiB of GPU memory.
pub func tiles_alive() -> usize:
    return live_tiles

func next_stamp() -> u64:
    last_stamp += 1
    return last_stamp

func retain(tile: Tile*) -> Tile*:
    tile.references += 1
    return tile

func release(tile: Tile*):
    tile.references -= 1
    if tile.references == 0:
        forget_tile(tile)
        free(tile) in memory.heap
        live_tiles -= 1

## A box of whole pixels: `left` and `top` inside, `right` and `bottom` just past.
pub struct Bounds:
    pub var left: i64
    pub var top: i64
    pub var right: i64
    pub var bottom: i64

pub func tile_columns(width: u32) -> u32:
    return (width + tile_size - 1) // tile_size

## Cells by whole-cell position, signed: column 0 is the canvas's first;
## `right` and `bottom` are just past.
pub struct CellRange:
    pub var left: i64
    pub var top: i64
    pub var right: i64
    pub var bottom: i64

## A layer's pixels: `columns` by `rows` cells over the canvas, each a shared
## tile or `none` for a fully transparent one. Copies do not alias; clone what
## you keep.
##
## Pixels moved past the canvas are kept, as Compositor keeps them, in the
## `outside` grid: whole cells aligned with the canvas's, its first at cell
## (`outside_column`, `outside_row`) (negative to the left and above). Only
## what lies past the canvas counts there — a cell on the canvas's right or
## bottom edge holds the canvas part in the canvas grid (its `region`) and the
## rest in the outside grid, often as one shared tile. Everything that works
## on the canvas grid alone (painting, filters, compositing) leaves the
## outside grid be; clone, destroy and history carry it along.
pub struct Tiles:
    var owner: gpu.Device
    var extent_x: u32
    var extent_y: u32
    var cell_columns: u32
    var cell_rows: u32
    var cells: Tile*?[]
    var outside: Tiles*?
    var outside_column: i64
    var outside_row: i64

    ## Fully transparent pixels for a `width` by `height` layer.
    pub static func create(device: gpu.Device, width: u32, height: u32) -> Tiles!:
        if width == 0 or height == 0 or width > 65536 or height > 65536:
            error(invalid, "layer dimensions must be in 1..65536")
        let columns = tile_columns(width)
        let rows = tile_columns(height)
        let cells = try new Tile*?[(usize)columns * (usize)rows] --- in memory.heap
        for index in 0..<cells.length:
            cells[index] = none
        var owned = device
        _ = try owned.backend()
        return Tiles(owner = device, extent_x = width, extent_y = height, cell_columns = columns, cell_rows = rows, cells = cells, outside = none, outside_column = 0, outside_row = 0)

    pub func width() -> u32:
        return self.extent_x

    pub func height() -> u32:
        return self.extent_y

    pub func columns() -> u32:
        return self.cell_columns

    pub func rows() -> u32:
        return self.cell_rows

    ## The device the tiles live on.
    pub func device() -> gpu.Device:
        return self.owner

    ## The texels a cell covers, in layer pixels.
    pub func region(column: u32, row: u32) -> gpu.Region:
        let x = column * tile_size
        let y = row * tile_size
        return gpu.Region(0, 0, min_u32(tile_size, self.extent_x - x), min_u32(tile_size, self.extent_y - y))

    ## The tile at a cell, borrowed, or `none` when transparent.
    pub func tile(column: u32, row: u32) -> Tile*?:
        return self.cells[try_index(&self, column, row) else return none]

    ## The tile texture at a cell, borrowed for the current residency epoch
    ## (it stays on the GPU until the next frame's `advance`), or `none` when
    ## transparent. A tile kept only in RAM goes back to the GPU first.
    pub func texture(column: u32, row: u32) -> gpu.Texture?!:
        let tile = self.tile(column, row) else return none
        return try resident(tile, self.owner)

    ## The tile texture at a cell for one pass recorded now, or `none` when
    ## transparent: a tile kept only in RAM gets a transient upload that stays
    ## until `release_transients` back to a mark taken before, and the tile
    ## stays in RAM. What derived tiles (levels, composites) are made from.
    pub func pass_texture(column: u32, row: u32) -> gpu.Texture?!:
        let tile = self.tile(column, row) else return none
        return try pass_texture(tile, self.owner)

    ## Bring the tiles at `cells` that are only somewhere slower (compressed,
    ## in the scratch file, in the document file) into RAM together, decoded
    ## across the processors: what a draw is about to ask for, one at a time.
    pub func gather(cells: const Cell[]) -> !:
        try gather_cells(&self, cells)

    ## Whether a cell holds a tile (is not transparent), without bringing it
    ## to the GPU.
    pub func painted(column: u32, row: u32) -> bool:
        return self.tile(column, row) != none

    ## A second holder of the same tiles.
    pub func clone() -> Tiles!:
        let cells = try new Tile*?[self.cells.length] --- in memory.heap
        for index in 0..<cells.length:
            cells[index] = none
            if let tile = self.cells[index]:
                cells[index] = retain(tile)
        var copy = Tiles(owner = self.owner, extent_x = self.extent_x, extent_y = self.extent_y, cell_columns = self.cell_columns, cell_rows = self.cell_rows, cells = cells,
                         outside = none, outside_column = 0, outside_row = 0)
        if let outside = self.outside:
            errdefer copy.destroy()
            copy.outside = try box(try outside.clone())
            copy.outside_column = self.outside_column
            copy.outside_row = self.outside_row
        return copy

    ## Put `texture` (a full 256 by 256 rgba16_float texture this takes over) at a
    ## cell, replacing what was there. Other holders keep the old tile.
    pub func set(column: u32, row: u32, texture: gpu.Texture) -> !:
        let index = try self.index(column, row)
        if (try texture.width()) != tile_size or (try texture.height()) != tile_size or (try texture.pixel_format()) != gpu.Format.rgba16_float:
            error(invalid, "a tile is a 256 by 256 rgba16_float texture")
        let tile = try make_tile(texture)
        if let previous = self.cells[index]:
            release(previous)
        self.cells[index] = tile

    ## Put the tile of cell (`from_column`, `from_row`) at (`column`, `row`) too,
    ## shared: a store of many equal cells (a selection's fully selected ones)
    ## keeps one tile for them all. An empty source empties the cell.
    pub func share(column: u32, row: u32, from_column: u32, from_row: u32) -> !:
        let index = try self.index(column, row)
        let source = self.cells[try self.index(from_column, from_row)]
        if let previous = self.cells[index]:
            release(previous)
        self.cells[index] = none
        if let tile = source:
            self.cells[index] = retain(tile)

    ## The cell's content stamp, 0 when transparent: it changes whenever the
    ## cell's pixels do.
    pub func stamp(column: u32, row: u32) -> u64:
        let tile = self.tile(column, row) else return 0
        return tile.stamp

    ## Every cell's stamp folded into `seed`: it changes when any pixel does.
    pub func stamps(seed: u64) -> u64:
        var digest = seed
        for cell in self.cells:
            var stamp: u64 = 0
            if let tile = cell:
                stamp = tile.stamp
            digest = (digest ^ stamp) *% 1099511628211
        return digest

    ## Whether this is the only holder of the cell's tile, so it may be drawn
    ## into again in place (`redrawn`).
    pub func owns(column: u32, row: u32) -> bool:
        let tile = self.tile(column, row) else return false
        return tile.references == 1

    ## The cell's tile, held here alone, was drawn into again on the GPU: a new
    ## stamp, and the RAM copy and scratch slot of what it held before are let
    ## go, so a read or a reload never serves the old pixels.
    pub func redrawn(column: u32, row: u32) -> !:
        let tile = self.tile(column, row) else error(invalid, "no tile to redraw")
        if tile.references != 1:
            error(invalid, "a shared tile cannot be redrawn")
        tile.stamp = next_stamp()
        # The file no longer holds what it shows, nor do a compressed copy or a slot.
        release_backing(tile)
        tile.raw_only = false
        if tile.on_gpu:
            drop_ram_copy(tile)
            drop_packed(tile)
            release_disk(tile)

    ## Make a cell transparent again.
    pub func clear(column: u32, row: u32) -> !:
        let index = try self.index(column, row)
        if let previous = self.cells[index]:
            release(previous)
        self.cells[index] = none

    ## A fresh tile texture on the device, cleared to transparent, ready to be
    ## drawn into with a frame and then `set`.
    pub func blank() -> gpu.Texture!:
        var texture = try tile_texture(self.owner)
        errdefer texture.destroy()
        # Cleared on the device: no zeros filled and copied up from memory.
        let frame = try texture.frame()
        defer frame.release()
        _ = try frame.value().present(gpu.Color(0.0, 0.0, 0.0, 0.0))
        return texture

    ## Replace every pixel from straight-alpha RGBA f32 samples, top-down, four
    ## per pixel. Transparent tiles stay `none`. A row of cells at a time is
    ## converted to half floats on every processor, then uploaded whole (the
    ## padding past the extent zeroed), so no tile needs clearing first.
    pub func write(pixels: const f32[]) -> !:
        if pixels.length != (usize)self.extent_x * (usize)self.extent_y * 4:
            error(invalid, "pixel data must hold width * height RGBA samples")
        let columns = (usize)self.cell_columns
        let per_tile = (usize)tile_size * (usize)tile_size * 8
        let band = try new u8[columns * per_tile] --- in memory.heap
        defer free(band) in memory.heap
        let painted = try new bool[columns] --- in memory.heap
        defer free(painted) in memory.heap
        for row in 0..<self.cell_rows:
            try self.write_cells_of(row, pixels, 0, band, painted)

    ## Replace row `row` of cells from `pixels`: straight-alpha linear RGBA f32
    ## samples of the rows that row of cells covers only (256 of them, fewer in
    ## the last), the document's width. What a picture loads through a band at a
    ## time, never whole.
    pub func write_band(row: u32, pixels: const f32[]) -> !:
        let band = try new u8[packed_band_bytes(self.extent_x)] --- in memory.heap
        defer free(band) in memory.heap
        let painted = try new bool[(usize)self.cell_columns] --- in memory.heap
        defer free(painted) in memory.heap
        try pack_band(self.extent_x, self.extent_y, row, pixels, band, painted)
        try self.write_packed(row, band, painted)

    ## Replace row `row` of cells with the tiles `pack_band` made: each painted
    ## one uploaded, the others cleared. The GPU half of `write_band`.
    pub func write_packed(row: u32, band: const u8[], painted: const bool[]) -> !:
        let per_tile = (usize)tile_size * (usize)tile_size * 8
        if row >= self.cell_rows or band.length < (usize)self.cell_columns * per_tile or painted.length < (usize)self.cell_columns:
            error(invalid, "a packed band holds a tile for each of its row's cells")
        for column in 0..<self.cell_columns:
            if not painted[(usize)column]:
                try self.clear(column, row)
                continue
            var texture = try tile_texture(self.owner)
            errdefer texture.destroy()
            let at = (usize)column * per_tile
            try texture.upload(band[at..<at + per_tile])
            try self.set(column, row, texture)

    ## Row `row` of cells from `pixels`, whose first row is document row `origin`.
    func write_cells_of(row: u32, pixels: const f32[], origin: usize, band: u8[], painted: bool[]) -> !:
        let columns = (usize)self.cell_columns
        var job = WriteJob(pixels = pixels, band = band, painted = painted, extent_x = self.extent_x, extent_y = self.extent_y, row = row, origin = origin, first = 0, last = columns)
        try run_bands(&job, columns)
        try self.write_packed(row, band, painted)

    ## Replace cell (`column`, `row`) with `pixels`, one cell's premultiplied
    ## RGBA f32 samples, 256 rows of 256 whatever the cell's size (past the
    ## document's edge they are ignored); a cell left wholly clear is dropped.
    pub func write_cell_premultiplied(column: u32, row: u32, pixels: const f32[]) -> !:
        if pixels.length != (usize)tile_size * (usize)tile_size * 4:
            error(invalid, "a cell's pixels are 256 by 256 RGBA samples")
        let area = self.region(column, row)
        let bytes = try new u8[(usize)tile_size * (usize)tile_size * 8] --- in memory.heap
        defer free(bytes) in memory.heap
        for index in 0..<bytes.length:
            bytes[index] = 0
        var painted = false
        for y in 0..<(usize)area.height:
            for x in 0..<(usize)area.width:
                let source = (y * (usize)tile_size + x) * 4
                let destination = (y * (usize)tile_size + x) * 8
                let alpha = pixels[source + 3]
                if alpha > 0.0:
                    painted = true
                for channel in 0..<(usize)4:
                    var value = pixels[source + channel]
                    if channel < 3:
                        value = value / alpha if alpha > 0.0 else 0.0
                    let half = to_half(value)
                    bytes[destination + channel * 2] = (u8)(half & 0xff)
                    bytes[destination + channel * 2 + 1] = (u8)(half >> 8)
        if not painted:
            try self.clear(column, row)
            return
        var texture = try self.blank()
        errdefer texture.destroy()
        try texture.upload(bytes[..<((usize)area.height * (usize)tile_size * 8)], gpu.Region(0, 0, tile_size, area.height))
        try self.set(column, row, texture)

    ## Cell (`column`, `row`) read back into `pixels` as straight-alpha RGBA f32
    ## samples, 256 rows of 256; clear where the cell is empty or past the edge.
    pub func read_cell(column: u32, row: u32, pixels: f32[]) -> !:
        if pixels.length != (usize)tile_size * (usize)tile_size * 4:
            error(invalid, "a cell's pixels are 256 by 256 RGBA samples")
        for index in 0..<pixels.length:
            pixels[index] = 0.0
        var target = pixels
        let one: Cell[1] = [Cell(column = column, row = row)]
        try read_cells(&self, one, (void*)&target, cell_to_floats)

    ## Read `cells` back, calling `visit(context, cell, bytes)` for each in order
    ## (see `read_cells`): many cells per submission, the next batch on the GPU
    ## while the caller works through one.
    pub func read_many(cells: const Cell[], context: void*?, visit: func(void*?, Cell, const u8[]) -> unit!, warm: bool = true) -> !:
        try read_cells(&self, cells, context, visit, warm)

    ## Read every pixel back as straight-alpha RGBA f32 samples, top-down.
    pub func read(pixels: f32[]) -> !:
        if pixels.length != (usize)self.extent_x * (usize)self.extent_y * 4:
            error(invalid, "pixel buffer must hold width * height RGBA samples")
        for index in 0..<pixels.length:
            pixels[index] = 0.0
        let cells = try new Cell[(usize)self.cell_columns * (usize)self.cell_rows] --- in memory.heap
        defer free(cells) in memory.heap
        var count: usize = 0
        for row in 0..<self.cell_rows:
            for column in 0..<self.cell_columns:
                if self.painted(column, row):
                    cells[count] = Cell(column = column, row = row)
                    count += 1
        var whole = WholeRead(pixels = pixels, width = (usize)self.extent_x, height = (usize)self.extent_y)
        try read_cells(&self, cells[..<count], (void*)&whole, cell_into_whole)

    ## The smallest box of whole pixels holding every pixel with any alpha; none
    ## when there is none. It reads painted tiles back from the GPU, from the
    ## outside of the painted cells inwards, skipping any cell already inside
    ## the box found so far: a full layer reads only its outer ring of tiles.
    pub func content_bounds() -> Bounds?!:
        let cells = self.occupied_on_canvas() else return none
        var read = BoundsRead(bounds = Bounds(left = (i64)self.extent_x, top = (i64)self.extent_y, right = 0, bottom = 0), found = false, width = self.extent_x, height = self.extent_y)
        var list = CellList()
        defer list.release()
        let rings = (min_i64(cells.right - cells.left, cells.bottom - cells.top) + 1) // 2
        for ring in 0..<rings:
            # A ring's cells go in batches; inner rings skip what the outer ones already cover.
            let count = try ring_cells(&self, cells, ring, &read, &list)
            try read_cells(&self, list.cells[..<count], (void*)&read, cell_into_bounds)
        return read.bounds if read.found else none

    ## The cells of the canvas grid holding any tile; none when none do.
    func occupied_on_canvas() -> CellRange?:
        var found = false
        var range = CellRange(left = 0, top = 0, right = 0, bottom = 0)
        for row in 0..<self.cell_rows:
            for column in 0..<self.cell_columns:
                if self.cells[(usize)row * (usize)self.cell_columns + (usize)column] != none:
                    grow(&range, &found, (i64)column, (i64)row)
        return range if found else none

    # -- Past the canvas.

    ## Whether any pixels lie past the canvas.
    pub func has_outside() -> bool:
        return self.outside != none

    ## The cells holding any tile, on the canvas or past it; none when the
    ## layer is empty.
    pub func occupied() -> CellRange?:
        var found = false
        var range = CellRange(left = 0, top = 0, right = 0, bottom = 0)
        for row in 0..<self.cell_rows:
            for column in 0..<self.cell_columns:
                if self.cells[(usize)row * (usize)self.cell_columns + (usize)column] != none:
                    grow(&range, &found, (i64)column, (i64)row)
        if let outside = self.outside:
            for row in 0..<outside.cell_rows:
                for column in 0..<outside.cell_columns:
                    if outside.cells[(usize)row * (usize)outside.cell_columns + (usize)column] != none:
                        grow(&range, &found, self.outside_column + (i64)column, self.outside_row + (i64)row)
        return range if found else none

    ## Whether signed cell (`column`, `row`) is one of the canvas grid's.
    pub func on_canvas(column: i64, row: i64) -> bool:
        return column >= 0 and row >= 0 and column < (i64)self.cell_columns and row < (i64)self.cell_rows

    ## Whether cell (`column`, `row`) has pixels past the canvas: it is off
    ## the canvas grid, or on its right or bottom edge where the canvas ends
    ## inside the cell.
    pub func reaches_past(column: i64, row: i64) -> bool:
        if not self.on_canvas(column, row):
            return true
        let area = self.region((u32)column, (u32)row)
        return area.width < tile_size or area.height < tile_size

    ## The outside grid's cells, as signed cells on the canvas's grid.
    pub func outside_range() -> CellRange?:
        let outside = self.outside else return none
        return CellRange(left = self.outside_column, top = self.outside_row, right = self.outside_column + (i64)outside.cell_columns,
                         bottom = self.outside_row + (i64)outside.cell_rows)

    ## The outside grid's texture at signed cell (`column`, `row`), borrowed:
    ## only its part past the canvas counts.
    pub func outside_texture(column: i64, row: i64) -> gpu.Texture?!:
        let outside = self.outside else return none
        let x = column - self.outside_column
        let y = row - self.outside_row
        if x < 0 or y < 0:
            return none
        return try outside.texture((u32)x, (u32)y)

    ## Make the outside grid cover `range` as well as what it covers already,
    ## its tiles kept.
    pub func cover(range: CellRange) -> !:
        var wanted = range
        if let outside = self.outside:
            let right = self.outside_column + (i64)outside.cell_columns
            let bottom = self.outside_row + (i64)outside.cell_rows
            if range.left >= self.outside_column and range.top >= self.outside_row and range.right <= right and range.bottom <= bottom:
                return
            wanted.left = min_i64(wanted.left, self.outside_column)
            wanted.top = min_i64(wanted.top, self.outside_row)
            wanted.right = max_i64(wanted.right, right)
            wanted.bottom = max_i64(wanted.bottom, bottom)
        let columns = wanted.right - wanted.left
        let rows = wanted.bottom - wanted.top
        if columns * (i64)tile_size > 65536 or rows * (i64)tile_size > 65536:
            error(limit, "a layer reaches at most 65536 pixels, on the canvas and past it")
        var grown = try Tiles.create(self.owner, (u32)columns * tile_size, (u32)rows * tile_size)
        errdefer grown.destroy()
        if let outside = self.outside:
            for row in 0..<outside.cell_rows:
                for column in 0..<outside.cell_columns:
                    let tile = outside.cells[(usize)row * (usize)outside.cell_columns + (usize)column] else continue
                    let at = (usize)(self.outside_row + (i64)row - wanted.top) * (usize)columns + (usize)(self.outside_column + (i64)column - wanted.left)
                    grown.cells[at] = retain(tile)
            self.outside = none
            unbox(outside)
        self.outside = try box(grown)
        self.outside_column = wanted.left
        self.outside_row = wanted.top

    ## Put `texture` (a fresh tile this takes over) at signed cell (`column`,
    ## `row`): into the canvas grid when its canvas part holds anything
    ## (`inside`), into the outside grid when its part past the canvas does
    ## (`beyond`; `cover` it first) — one shared tile for both — and nowhere
    ## when neither.
    pub func place(column: i64, row: i64, texture: gpu.Texture, inside: bool, beyond: bool) -> !:
        let keep_inside = inside and self.on_canvas(column, row)
        let keep_beyond = beyond and self.reaches_past(column, row)
        if not keep_inside and not keep_beyond:
            var dropped = texture
            dropped.destroy()
            return
        let tile = try make_tile(texture)
        defer release(tile)
        if keep_inside:
            let index = try self.index((u32)column, (u32)row)
            if let previous = self.cells[index]:
                release(previous)
            self.cells[index] = retain(tile)
        if keep_beyond:
            let outside = self.outside else error(invalid, "cover the cell past the canvas before placing it")
            let x = column - self.outside_column
            let y = row - self.outside_row
            if x < 0 or y < 0 or x >= (i64)outside.cell_columns or y >= (i64)outside.cell_rows:
                error(invalid, "cover the cell past the canvas before placing it")
            let index = (usize)y * (usize)outside.cell_columns + (usize)x
            if let previous = outside.cells[index]:
                release(previous)
            outside.cells[index] = retain(tile)

    ## Clear the outside cells with nothing past the canvas — nothing with
    ## any alpha, or for a `mask` nothing but white — and drop the outside
    ## grid if nothing is left. Rebuilding places whole pieces, so a cell can
    ## hold only the transparent margin of one; this reads them back to know.
    pub func settle(mask: bool = false) -> !:
        let outside = self.outside else return
        let bytes = try new u8[(usize)tile_size * (usize)tile_size * 8] --- in memory.heap
        defer free(bytes) in memory.heap
        var kept = false
        for row in 0..<outside.cell_rows:
            for column in 0..<outside.cell_columns:
                let index = (usize)row * (usize)outside.cell_columns + (usize)column
                let tile = outside.cells[index] else continue
                let x = self.outside_column + (i64)column
                let y = self.outside_row + (i64)row
                # The canvas part, which does not count here.
                var inside_width: usize = 0
                var inside_height: usize = 0
                if self.on_canvas(x, y):
                    let area = self.region((u32)x, (u32)y)
                    inside_width = (usize)area.width
                    inside_height = (usize)area.height
                try (try resident(tile, self.owner)).read(bytes)
                var found = false
                for texel_y in 0..<(usize)tile_size:
                    for texel_x in 0..<(usize)tile_size:
                        if texel_x < inside_width and texel_y < inside_height:
                            continue
                        let at = (texel_y * (usize)tile_size + texel_x) * 8
                        if mask:
                            # Anything but white (half 1.0 is 0x3c00) hides something.
                            for channel in 0..<(usize)4:
                                if ((u16)bytes[at + channel * 2] | ((u16)bytes[at + channel * 2 + 1] << 8)) != 0x3c00:
                                    found = true
                        elif ((u16)bytes[at + 6] | ((u16)bytes[at + 7] << 8)) & 0x7fff != 0:
                            found = true
                        if found:
                            break
                    if found:
                        break
                if found:
                    kept = true
                else:
                    release(tile)
                    outside.cells[index] = none
        if not kept:
            self.outside = none
            unbox(outside)

    func index(column: u32, row: u32) -> usize!:
        if column >= self.cell_columns or row >= self.cell_rows:
            error(invalid, "tile cell out of range")
        return (usize)row * (usize)self.cell_columns + (usize)column

    pub func destroy():
        if let outside = self.outside:
            self.outside = none
            unbox(outside)
        for index in 0..<self.cells.length:
            if let tile = self.cells[index]:
                release(tile)
        if self.cells.length > 0:
            free(self.cells) in memory.heap
        var empty: Tile*?[]
        self.cells = empty
        self.cell_columns = 0
        self.cell_rows = 0

## Move `tiles` onto the heap, for holders that keep a pointer.
pub func box(tiles: Tiles) -> Tiles*!:
    # The whole value at once, so no field is forgotten.
    let boxed = try new Tiles in memory.heap
    *boxed = tiles
    return boxed

## Destroy boxed tiles and free the box.
pub func unbox(tiles: Tiles*):
    tiles.destroy()
    free(tiles) in memory.heap

func try_index(tiles: const Tiles*, column: u32, row: u32) -> usize?:
    if column >= tiles.cell_columns or row >= tiles.cell_rows:
        return none
    return (usize)row * (usize)tiles.cell_columns + (usize)column

func grow(range: CellRange*, found: bool*, column: i64, row: i64):
    if not *found:
        *range = CellRange(left = column, top = row, right = column + 1, bottom = row + 1)
        *found = true
        return
    range.left = min_i64(range.left, column)
    range.top = min_i64(range.top, row)
    range.right = max_i64(range.right, column + 1)
    range.bottom = max_i64(range.bottom, row + 1)

pub func min_i64(a: i64, b: i64) -> i64:
    return a if a < b else b

pub func max_i64(a: i64, b: i64) -> i64:
    return a if a > b else b

## The smaller of two unsigned sizes.
pub func min_u32(a: u32, b: u32) -> u32:
    return a if a < b else b

## The larger of two unsigned sizes.
pub func max_u32(a: u32, b: u32) -> u32:
    return a if a > b else b

## One row of cells for `Tiles.write`: cells `first..<last` of `row`, each
## converted into its place in `band`, `painted` saying whether it holds anything.
struct WriteJob:
    var pixels: const f32[]
    var band: u8[]
    var painted: bool[]
    var extent_x: u32
    var extent_y: u32
    var row: u32
    ## The document row `pixels` begins at: 0 for the whole picture, the band's top for a band.
    var origin: usize
    var first: usize
    var last: usize

func write_cells(job: WriteJob*):
    let per_tile = (usize)tile_size * (usize)tile_size * 8
    let top = (usize)job.row * (usize)tile_size
    let height = min_usize((usize)tile_size, (usize)job.extent_y - top)
    for column in job.first..<job.last:
        let left = column * (usize)tile_size
        let width = min_usize((usize)tile_size, (usize)job.extent_x - left)
        let bytes = job.band[column * per_tile..<(column + 1) * per_tile]
        var opaque = false
        for y in 0..<(usize)tile_size:
            for x in 0..<(usize)tile_size:
                let destination = (y * (usize)tile_size + x) * 8
                if y >= height or x >= width:
                    for index in 0..<(usize)8:
                        bytes[destination + index] = 0
                    continue
                let source = ((top + y - job.origin) * (usize)job.extent_x + left + x) * 4
                for channel in 0..<(usize)4:
                    let half = to_half(job.pixels[source + channel])
                    bytes[destination + channel * 2] = (u8)(half & 0xff)
                    bytes[destination + channel * 2 + 1] = (u8)(half >> 8)
                if job.pixels[source + 3] != 0.0:
                    opaque = true
        job.painted[column] = opaque

## `job`'s cells split over the processors, this thread taking the first share.
func run_bands(job: WriteJob*, count: usize) -> !:
    try run_shares(count, write_share, (void*)job)

## `write_cells` over cells `first..<last` of the job.
func write_share(context: void*?, first: usize, last: usize):
    var share = *(WriteJob*)(context else return)
    share.first = first
    share.last = last
    write_cells(&share)

func min_usize(a: usize, b: usize) -> usize:
    return a if a < b else b

func max_usize(a: usize, b: usize) -> usize:
    return a if a > b else b

## Every tile of `tiles` drawn into one texture of the whole extent, as stored;
## empty cells come out as `empty` (a mask's are white: they reveal).
pub func flatten(device: gpu.Device, tiles: const Tiles*, empty: gpu.Color = gpu.Color(0.0, 0.0, 0.0, 0.0)) -> gpu.Texture!:
    var flat = try gpu.Texture.create(device, tiles.width(), tiles.height(), gpu.Format.rgba16_float)
    errdefer flat.destroy()
    let frame = try flat.frame()
    defer frame.release()
    let whole = try frame.value().target()
    defer whole.release()
    for row in 0..<tiles.rows():
        for column in 0..<tiles.columns():
            let texture = (try tiles.texture(column, row)) else continue
            let area = tiles.region(column, row)
            try gpu.copy_image(whole.value(), texture, gpu.Rect((f64)(column * tile_size), (f64)(row * tile_size), (f64)area.width, (f64)area.height), area)
    _ = try frame.value().present(empty)
    return flat