gpu_metal source

← gpu_metal · API reference · version 0.2.3

6 file(s), 1949 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
table fn27—15 93 100 114 120 13 … (91 total)
checked fn49—25 29 36 45 60 62 … (11 total)
check fn55—84 91
faults fn60—37 39 64 69 77 87 … (7 total)
check_catches fn67—39 48 88

src/gpu_metal.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// The Metal backend of `gpu`.
//
//   dev = gpu::open(gpu_metal::table(), 960, 720, "view") ?? return;
//
// A game does not name this library: its host package asks each backend in turn.  A program's
// source for it carries the tag "msl" and is the Metal Shading Language:
//   - the vertex function is `vertex_main` and the fragment function `fragment_main`; the two
//     sources are compiled apart, so each declares what both use;
//   - the inputs read per vertex are `[[attribute(0)]]` onwards of the `[[stage_in]]` struct, in
//     the program's order, and the inputs read per copy follow them;
//   - the uniform block is a struct at `[[buffer(0)]]`; a block laid out otherwise than the
//     program declares builds no pipeline, and stderr shows both layouts;
//   - texture slot n is `[[texture(n)]]` and its sampler `[[sampler(n)]]`; a depth texture is a
//     `depth2d<float>`;
//   - the vertex function hands its position to `gpu_position(...)`, which this backend defines
//     ahead of the source: a position is written in `gpu`'s clip space (depth from -1 to 1), as
//     for every backend, and that call turns it into Metal's.

fn gm_table() -> integer;
#c "gm_table" "int64_t()"

// This backend's table, for `gpu::open`; 0 on a machine that is not a Mac.  `open` answers null
// on a Mac with no Metal.
pub fn table() -> i64 {
  gm_table()
}

fn gm_check(on: integer);
#c "gm_check" "void(int64_t)"
fn gm_faults() -> integer;
#c "gm_faults" "int64_t()"
fn gm_checked() -> integer;
#c "gm_checked" "int64_t()"
fn gm_check_self() -> integer;
#c "gm_check_self" "int64_t()"

// Whether this library was built checked (`c/checked.sh`) and its checks are on.  The library
// as it is published is not, and pays nothing for the checks: `faults` is then always 0.
//
// Metal's own validation (`MTL_DEBUG_LAYER=1`) sees a wrong call of Metal.  A checked build
// sees what it cannot: a buffer, texture, target or
// pipeline of this backend used after its release, released twice, or used after its device
// closed.  The call is refused, counted, and written to stderr with the call it came from.
// `GPU_METAL_DEBUG=abort` stops the program at the first fault, `GPU_METAL_DEBUG=0` turns
// the checks off.
pub fn checked() -> boolean {
  gm_checked() != 0
}

// Turn a checked build's checks off, or on again.  Ask before `table()`: a device opened
// through a table taken earlier keeps what that table did.
pub fn check(on: boolean) {
  gm_check(if on { 1 } else { 0 });
}

// How many faults a checked build has seen in this program.
pub fn faults() -> integer {
  gm_faults()
}

// For this library's own tests: release one buffer of the window opened last twice, then give
// it to a draw, as no program can through `gpu`, and answer how many faults that added — 2 in a
// checked build with its checks on (and not set to abort), 0 otherwise.
pub fn check_catches() -> integer {
  gm_check_self()
}

tests/after_close.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// What a program may do with the objects of a window it closed: let them go late.  A buffer, a
// texture, a target or a pipeline outlives its device whenever a program closes its window
// before the values that hold them die, and each is released then, into a backend whose
// device is gone, and perhaps beside a second device opened since.  That release frees
// nothing twice and touches nothing of the second device.
// Without a display every test returns at once (`DISPLAY`, or `GRAPHICS_TEST_WINDOW=1` on a
// Mac).
use gpu;
use gpu_metal;

fn display() -> boolean {
  gpu_metal::table() != 0 && must_draw((env_variable("GRAPHICS_TEST_WINDOW") ?? "") == "1")
}

// A run that says its tests must draw (`GRAPHICS_TEST_MUST_DRAW=1`: the library CI, on a runner
// it gave a display) fails here, where a test would otherwise return having drawn nothing.
fn must_draw(can: boolean) -> boolean {
  assert(can || (env_variable("GRAPHICS_TEST_MUST_DRAW") ?? "") != "1", "this run's tests must draw (GRAPHICS_TEST_MUST_DRAW=1) and found no display to draw on");
  can
}

const FLAT_V: text = `
struct Block {{ float4 color; float4 at; }};
struct In {{ float3 pos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; }};
vertex Out vertex_main(In in [[stage_in]], constant Block &u [[buffer(0)]]) {{
  Out o;
  o.position = gpu_position(float4(in.pos.xy * u.at.zw + u.at.xy, 0.0, 1.0));
  return o;
}}
`;

const FLAT_F: text = `
struct Block {{ float4 color; float4 at; }};
fragment float4 fragment_main(constant Block &u [[buffer(0)]]) {{ return u.color; }}
`;

fn flat() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::F4, gpu::F4],
    textures: 0,
    sources: [gpu::source("msl", FLAT_V, FLAT_F)],
  }
}

fn whole() -> vector<single> {
  [-1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f]
}

// One of everything a device makes.
struct Kit {
  mesh: gpu::Buffer,
  order: gpu::IndexBuffer,
  colour: gpu::Texture,
  depth: gpu::Texture,
  into: gpu::Target,
  pipe: gpu::Pipeline,
}

struct Held { kit: Kit? }

fn kit_of(dev: const gpu::Device) -> Kit? {
  colour = dev.texture(16, 16);
  depth = dev.depth_texture(16, 16);
  Kit {
    mesh: dev.buffer(whole()),
    order: dev.index_buffer([0, 1, 2, 3, 4, 5]),
    into: dev.target(colour, depth),
    colour: colour,
    depth: depth,
    pipe: dev.pipeline(flat(), gpu::State { depth: gpu::DEPTH_OFF }) ?? return null,
  }
}

// The rectangle scaled by (sx, sy) about (cx, cy), in one colour.
fn fill(dev: gpu::Device, pipe: const gpu::Pipeline, mesh: const gpu::Buffer, r: float, g: float, b: float, cx: float, sx: float) {
  u = pipe.block();
  u.f4(0, r, g, b, 1.0);
  u.f4(1, cx, 0.0, sx, 1.0);
  dev.bind(pipe);
  dev.uniforms(u);
  dev.vertices(mesh);
  dev.draw(0, 6);
}

// A device's objects are let go after it closed, with nothing else open.
fn test_objects_let_go_after_their_device_closed() {
  devo = gpu::open(gpu_metal::table(), 64, 48, "closed-first");
  if !display() { return; }
  dev = devo ?? return assert(false, "no device");
  held = Held { kit: kit_of(dev) };
  assert(held.kit != null, "the kit was made");
  dev.close();
  held.kit = null;
  again = gpu::open(gpu_metal::table(), 64, 48, "after") ?? return assert(false, "no second device");
  mine = kit_of(again) ?? return assert(false, "no second kit");
  again.begin_window(gpu::CLEAR, 0xFF0000FF);
  fill(again, mine.pipe, mine.mesh, 0.0, 1.0, 0.0, 0.0, 1.0);
  again.end();
  shot = again.capture();
  assert(len(again.refusals()) == 0, "nothing refused: {again.refusals()}");
  assert(shot[24 * 64 + 32] == 0xFF00FF00, "a device opened after draws: {shot[24 * 64 + 32]:x}");
}

// A closed device's objects are let go while a SECOND device is open and holds objects of its
// own, made after the close: the late release frees none of them.  The second device draws a
// frame before and a frame after, and the second frame reads as drawn.
fn test_objects_of_a_closed_device_let_go_beside_a_second_device() {
  firsto = gpu::open(gpu_metal::table(), 64, 48, "first");
  if !display() { return; }
  first = firsto ?? return assert(false, "no device");
  held = Held { kit: kit_of(first) };
  assert(held.kit != null, "the first kit was made");
  first.close();
  second = gpu::open(gpu_metal::table(), 64, 48, "second") ?? return assert(false, "no second device");
  mine = kit_of(second) ?? return assert(false, "no second kit");
  second.begin_window(gpu::CLEAR, 0xFF0000FF);
  fill(second, mine.pipe, mine.mesh, 0.0, 1.0, 0.0, 0.0, 1.0);
  second.end();
  before = second.capture();
  held.kit = null;
  // the left half red over the green frame, through the second device's own objects
  second.begin_window(gpu::KEEP, 0);
  fill(second, mine.pipe, mine.mesh, 1.0, 0.0, 0.0, -0.5, 0.5);
  second.end();
  // and into its own target, which the late release must not have taken either
  second.begin(mine.into, gpu::CLEAR, 0xFF000000);
  second.end();
  after = second.capture();
  assert(len(second.refusals()) == 0, "nothing refused: {second.refusals()}");
  assert(before[24 * 64 + 16] == 0xFF00FF00, "before the release the frame is green: {before[24 * 64 + 16]:x}");
  assert(after[24 * 64 + 16] == 0xFFFF0000, "after it the second device still draws, left: {after[24 * 64 + 16]:x}");
  assert(after[24 * 64 + 48] == 0xFF00FF00, "and kept what it had drawn, right: {after[24 * 64 + 48]:x}");
}

tests/checked.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// The checked build (`c/checked.sh`): that it is off in the library as committed, and that a
// checked build sees what it is for — a handle of this backend used after its release, released
// twice, or used after its device closed, none of which Metal's own validation can see.  A
// check that never fired would read the same as a library without a fault.
// Off a Mac, and without `GRAPHICS_TEST_WINDOW=1` on one, every test returns at once.
use gpu;
use gpu_metal;

fn display() -> boolean {
  gpu_metal::table() != 0 && must_draw((env_variable("GRAPHICS_TEST_WINDOW") ?? "") == "1")
}

// A run that says its tests must draw (`GRAPHICS_TEST_MUST_DRAW=1`: the library CI, on a runner
// it gave a display) fails here, where a test would otherwise return having drawn nothing.
fn must_draw(can: boolean) -> boolean {
  assert(can || (env_variable("GRAPHICS_TEST_MUST_DRAW") ?? "") != "1", "this run's tests must draw (GRAPHICS_TEST_MUST_DRAW=1) and found no display to draw on");
  can
}

// A build that stops at the first fault cannot count two of them.
fn counting() -> boolean {
  gpu_metal::checked() && (env_variable("GPU_METAL_DEBUG") ?? "") != "abort"
}

fn test_an_unchecked_build_counts_nothing_and_a_checked_one_starts_at_none() {
  devo = gpu::open(gpu_metal::table(), 64, 48, "checked-none");
  if !display() { return; }
  dev = devo ?? return assert(false, "no device");
  mesh = dev.buffer([0.0f, 0.0f, 0.0f]);
  assert(mesh.floats() == 3, "a buffer was made");
  dev.begin_window(gpu::CLEAR, 0xFF00FF00);
  dev.end();
  if gpu_metal::checked() {
    assert(gpu_metal::faults() == 0, "a program that keeps the rules has no fault: {gpu_metal::faults()}");
  } else {
    assert(gpu_metal::faults() == 0 && gpu_metal::check_catches() == 0, "an unchecked build counts no fault: {gpu_metal::faults()}");
  }
}

// A buffer released twice and used after: two faults, and the program goes on.
fn test_a_checked_build_refuses_a_handle_used_after_its_release() {
  devo = gpu::open(gpu_metal::table(), 64, 48, "checked-handle");
  if !display() || !counting() { return; }
  dev = devo ?? return assert(false, "no device");
  caught = gpu_metal::check_catches();
  assert(caught == 2, "a second release and a use after it are each a fault: {caught}");
  dev.begin_window(gpu::CLEAR, 0xFF00FF00);
  dev.end();
  shot = dev.capture();
  assert(shot[0] == 0xFF00FF00, "the device draws on after the refused calls: {shot[0]:x}");
}

// What a program CAN do through `gpu`: write a buffer after it closed the buffer's window.
// The library as it ships takes the call and does nothing; a checked build names it.  Letting
// the buffer go after the close stays in order, and is no fault.
fn test_a_checked_build_names_a_buffer_written_after_its_device_closed() {
  devo = gpu::open(gpu_metal::table(), 64, 48, "checked-closed");
  // a build set to stop at the first fault is not handed one
  if !display() || (gpu_metal::checked() && !counting()) { return; }
  dev = devo ?? return assert(false, "no device");
  before = gpu_metal::faults();
  {
    mesh = dev.buffer([0.0f, 0.0f, 0.0f]);
    dev.close();
    mesh.update([1.0f, 2.0f, 3.0f]);
    after = gpu_metal::faults();
    if counting() {
      assert(after == before + 1, "the write after the close is one fault: {after} after {before}");
    } else if !gpu_metal::checked() {
      assert(after == 0, "an unchecked build takes the call in silence: {after}");
    }
  }
  if counting() {
    assert(gpu_metal::faults() == before + 1, "letting the buffer go after the close is no fault: {gpu_metal::faults()}");
  }
}

// A checked build with its checks turned off from the program counts nothing more.
fn test_checks_turned_off_count_nothing() {
  if !display() || !counting() { return; }
  gpu_metal::check(false);
  devo = gpu::open(gpu_metal::table(), 64, 48, "checked-off");
  dev = devo ?? return assert(false, "no device");
  before = gpu_metal::faults();
  assert(!gpu_metal::checked() && gpu_metal::check_catches() == 0, "off: nothing is caught");
  assert(gpu_metal::faults() == before, "and nothing is counted: {gpu_metal::faults()} after {before}");
  dev.close();
  gpu_metal::check(true);
  assert(gpu_metal::checked(), "on again");
}

tests/host.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// What this backend answers on its own, against values worked out by hand: a small machine's
// RGB565 frame as a texture, a target's pixels read back, a block of any size, the window's
// keys and pointer, and the sources it refuses.  Without a Mac's display every test returns at
// once (`GRAPHICS_TEST_WINDOW=1`).
use gpu;
use gpu_metal;

fn display() -> boolean {
  gpu_metal::table() != 0 && must_draw((env_variable("GRAPHICS_TEST_WINDOW") ?? "") == "1")
}

// A run that says its tests must draw (`GRAPHICS_TEST_MUST_DRAW=1`: the library CI, on a runner
// it gave a display) fails here, where a test would otherwise return having drawn nothing.
fn must_draw(can: boolean) -> boolean {
  assert(can || (env_variable("GRAPHICS_TEST_MUST_DRAW") ?? "") != "1", "this run's tests must draw (GRAPHICS_TEST_MUST_DRAW=1) and found no display to draw on");
  can
}

const SHOW_V: text = `
struct In {{ float2 pos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; float2 uv; }};
vertex Out vertex_main(In in [[stage_in]]) {{
  Out o;
  o.uv = (in.pos + 1.0) / 2.0;
  o.position = gpu_position(float4(in.pos, 0.0, 1.0));
  return o;
}}
`;

const SHOW_F: text = `
struct Out {{ float4 position [[position]]; float2 uv; }};
fragment float4 fragment_main(Out in [[stage_in]], texture2d<float> tex0 [[texture(0)]], sampler s0 [[sampler(0)]]) {{
  return tex0.sample(s0, in.uv);
}}
`;

// A texture over the whole target: texture coordinate (0, 0) at clip (-1, -1).
fn show() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F2],
    instance: [],
    block: [],
    textures: 1,
    sources: [gpu::source("msl", SHOW_V, SHOW_F)],
  }
}

fn frame() -> vector<single> {
  [-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f]
}

fn test_this_is_the_metal_backend() {
  if !display() { return; }
  dev = gpu::open(gpu_metal::table(), 64, 48, "host-name") ?? return assert(false, "no device");
  assert(gpu::backend_name() == "gpu_metal", "the backend that serves the program: {gpu::backend_name()}");
  assert(dev.width() == 64 && dev.height() == 48, "the window's size in pixels: {dev.width()} x {dev.height()}");
}

fn test_a_small_machines_frame_is_shown_in_its_colours() {
  if !display() { return; }
  dev = gpu::open(gpu_metal::table(), 64, 48, "host-565") ?? return assert(false, "no device");
  pipe = dev.pipeline(show(), gpu::State {}) ?? return assert(false, "pipeline");
  quad = dev.buffer(frame());
  // Two by two.  Red, green and blue at their brightest, and a mixed one: red 16 of 31,
  // green 32 of 63, blue 8 of 31 is 16 * 2048 + 32 * 32 + 8 = 33800, which widens to
  // (16 << 3 | 16 >> 2, 32 << 2 | 32 >> 4, 8 << 3 | 8 >> 2) = (132, 130, 66).
  t = dev.texture(2, 2);
  t.nearest(true);
  t.put_rgb565(0, 0, [63488 as i32, 2016 as i32, 31 as i32, 33800 as i32], 2, 2);
  dev.begin_window(gpu::CLEAR, 0xFF000000);
  dev.bind(pipe);
  dev.sample(0, t);
  dev.vertices(quad);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  // The texture's first row is at the bottom of the frame (clip y = -1), and a capture's first
  // row is the top: the first two values are in the lower half, the last two in the upper.
  low_left = c[40 * 64 + 8] ?? 0;
  low_right = c[40 * 64 + 56] ?? 0;
  up_left = c[8 * 64 + 8] ?? 0;
  up_right = c[8 * 64 + 56] ?? 0;
  assert(low_left == 0xFFFF0000, "five bits of red are full red: {low_left:x}");
  assert(low_right == 0xFF00FF00, "six of green full green: {low_right:x}");
  assert(up_left == 0xFF0000FF, "five of blue full blue: {up_left:x}");
  assert(up_right == 0xFF848242, "a mixed one widens by repeating its high bits: {up_right:x}");
}

fn test_a_targets_pixels_are_what_the_window_shows_of_it() {
  if !display() { return; }
  dev = gpu::open(gpu_metal::table(), 64, 48, "host-target") ?? return assert(false, "no device");
  into_colour = dev.pipeline(show(), gpu::State { into: gpu::INTO_COLOUR }) ?? return assert(false, "pipeline");
  into_window = dev.pipeline(show(), gpu::State {}) ?? return assert(false, "pipeline");
  quad = dev.buffer(frame());
  picture = dev.texture_from([0xFF102030 as u32, 0xFF405060 as u32, 0xFF708090 as u32, 0xFFA0B0C0 as u32], 2, 2);
  picture.nearest(true);
  // The picture drawn into a 64 x 48 target, then that target drawn over the window.
  held = dev.texture(64, 48);
  held.nearest(true);
  target = dev.colour_target(held);
  dev.begin(target, gpu::CLEAR, 0xFF000000);
  dev.bind(into_colour);
  dev.sample(0, picture);
  dev.vertices(quad);
  dev.draw(0, 6);
  dev.end();
  // A pass into the window in between: the target is read, not whatever was drawn into last.
  dev.begin_window(gpu::CLEAR, 0xFF00FF00);
  dev.end();
  read = dev.capture_of(target);
  dev.begin_window(gpu::CLEAR, 0xFFFFFFFF);
  dev.bind(into_window);
  dev.sample(0, held);
  dev.vertices(quad);
  dev.draw(0, 6);
  dev.end();
  seen = dev.capture();
  assert(len(read) == 64 * 48 && len(seen) == len(read), "both are 64 x 48: {len(read)} and {len(seen)}");
  differ = 0;
  for p in read { if p != (seen[p#index] ?? 0) { differ += 1; } }
  assert(differ == 0, "{differ} pixels of the target read back differ from the window showing it");
  // by hand: the picture's first pixel is at the bottom left, so the capture's last row starts with it
  assert((read[47 * 64] ?? 0) == 0xFF102030 && (read[63] ?? 0) == 0xFFA0B0C0, "the corners: {read[47 * 64] ?? 0:x} {read[63] ?? 0:x}");
  // and the target's own first pixel is its bottom left: a put there lands where clip (-1, -1) draws
  held.put(0, 0, [0xFF112233 as u32], 1, 1);
  again = dev.capture_of(target);
  assert((again[47 * 64] ?? 0) == 0xFF112233 && (again[0] ?? 0) == 0xFF708090, "a put at the first pixel: {again[47 * 64] ?? 0:x} {again[0] ?? 0:x}");
}

// A block of 300 vectors is 4800 bytes: more than Metal copies into a frame.  The fragment
// stage reads the last one.
const BIG_V: text = `
struct In {{ float2 pos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; }};
vertex Out vertex_main(In in [[stage_in]]) {{
  Out o;
  o.position = gpu_position(float4(in.pos, 0.0, 1.0));
  return o;
}}
`;

const BIG_F: text = `
struct Block {{ float4 first; float4 many[300]; }};
fragment float4 fragment_main(constant Block &u [[buffer(0)]]) {{ return u.first + u.many[299]; }}
`;

fn test_a_block_larger_than_a_frame_copies_reaches_the_shader() {
  if !display() { return; }
  dev = gpu::open(gpu_metal::table(), 64, 48, "host-block") ?? return assert(false, "no device");
  big = gpu::Program {
    vertex: [gpu::F2],
    instance: [],
    block: [gpu::F4, gpu::f4s(300)],
    textures: 0,
    sources: [gpu::source("msl", BIG_V, BIG_F)],
  };
  pipe = dev.pipeline(big, gpu::State {}) ?? return assert(false, "pipeline");
  quad = dev.buffer(frame());
  u = pipe.block();
  u.f4(0, 0.2, 0.0, 0.0, 1.0);
  u.f4_at(1, 299, 0.0, 0.4, 0.6, 0.0);
  dev.begin_window(gpu::CLEAR, 0xFF000000);
  dev.bind(pipe);
  dev.uniforms(u);
  dev.vertices(quad);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  // 0.2, 0.4 and 0.6 of 255 are 51, 102 and 153
  assert((c[20 * 64 + 30] ?? 0) == 0xFF336699, "the first field plus the last vector: {c[20 * 64 + 30] ?? 0:x}");
}

// A block the shader lays out otherwise than the program declares builds no pipeline.
const WRONG_V: text = `
struct Block {{ packed_float3 tint; float z; }};
struct In {{ float3 pos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; }};
vertex Out vertex_main(In in [[stage_in]], constant Block &u [[buffer(0)]]) {{
  Out o;
  o.position = gpu_position(float4(in.pos.xy + float3(u.tint).xy, u.z, 1.0));
  return o;
}}
`;

const SHORT_V: text = `
struct Block {{ float4 color; }};
struct In {{ float3 pos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; }};
vertex Out vertex_main(In in [[stage_in]], constant Block &u [[buffer(0)]]) {{
  Out o;
  o.position = gpu_position(float4(in.pos.xy + u.color.xy, 0.0, 1.0));
  return o;
}}
`;

// The right size, and a float in between that moves the one the program declares.
const MOVED_V: text = `
struct Block {{ float4 color; float pad; float z; }};
struct In {{ float3 pos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; }};
vertex Out vertex_main(In in [[stage_in]], constant Block &u [[buffer(0)]]) {{
  Out o;
  o.position = gpu_position(float4(in.pos.xy + u.color.xy, u.z + u.pad, 1.0));
  return o;
}}
`;

const RIGHT_V: text = `
struct Block {{ float4 color; float z; }};
struct In {{ float3 pos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; }};
vertex Out vertex_main(In in [[stage_in]], constant Block &u [[buffer(0)]]) {{
  Out o;
  o.position = gpu_position(float4(in.pos.xy + u.color.xy, u.z, 1.0));
  return o;
}}
`;

// The same with its position left in the layer's clip space.
const UNTURNED_V: text = `
struct Block {{ float4 color; float z; }};
struct In {{ float3 pos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; }};
vertex Out vertex_main(In in [[stage_in]], constant Block &u [[buffer(0)]]) {{
  Out o;
  o.position = float4(in.pos.xy + u.color.xy, u.z, 1.0);
  return o;
}}
`;

const WHITE_F: text = `
fragment float4 fragment_main() {{ return float4(1.0); }}
`;

fn blocked(vertex: text) -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::F4, gpu::F1],
    textures: 0,
    sources: [gpu::source("msl", vertex, WHITE_F)],
  }
}

fn test_a_source_that_breaks_a_rule_builds_no_pipeline() {
  if !display() { return; }
  dev = gpu::open(gpu_metal::table(), 64, 48, "host-wrong") ?? return assert(false, "no device");
  // declared as a vector and a float (the float at byte 16); three packed floats put it at byte 12
  assert(dev.pipeline(blocked(WRONG_V), gpu::State {}) == null, "the float sits at byte 12 in the shader and 16 in the program");
  // every field of the shader's block is where the program has one: only the size differs
  assert(dev.pipeline(blocked(SHORT_V), gpu::State {}) == null, "the shader's block is 16 bytes and the program's 32");
  assert(dev.pipeline(blocked(MOVED_V), gpu::State {}) == null, "both blocks are 32 bytes, and the shader has a field at byte 20 where the program has none");
  assert(dev.pipeline(blocked(UNTURNED_V), gpu::State {}) == null, "a position not handed to gpu_position is in another clip space");
  assert(dev.pipeline(blocked("gpu_position( is not a shader"), gpu::State {}) == null, "a source that does not compile");
  none = gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [],
    textures: 0,
    sources: [gpu::source("msl", RIGHT_V, WHITE_F)],
  };
  assert(dev.pipeline(none, gpu::State {}) == null, "a shader that reads a block the program does not declare");
  assert(dev.pipeline(blocked(RIGHT_V), gpu::State {}) != null, "and the same program with a matching shader builds");
}

// Begin a pass into a target of `colour` that is gone as this returns.
fn begin_into(dev: gpu::Device, colour: const gpu::Texture) {
  gone = dev.colour_target(colour);
  dev.begin(gone, gpu::CLEAR, 0xFF000000);
}

// A target that is dropped inside the pass drawing into it (one that leaves its scope before
// `end`) is drawn into until that pass ends.  A second target made right after it takes the
// room the first one's record had, were that freed: the draws must not land in `other`.
fn test_a_target_dropped_inside_its_pass_is_drawn_into_until_the_pass_ends() {
  if !display() { return; }
  dev = gpu::open(gpu_metal::table(), 64, 48, "host-dropped") ?? return assert(false, "no device");
  into_colour = dev.pipeline(show(), gpu::State { into: gpu::INTO_COLOUR }) ?? return assert(false, "pipeline");
  quad = dev.buffer(frame());
  picture = dev.texture_from([0xFF102030 as u32, 0xFF405060 as u32, 0xFF708090 as u32, 0xFFA0B0C0 as u32], 2, 2);
  picture.nearest(true);
  held = dev.texture(64, 48);
  aside = dev.texture(64, 48);
  wipe = dev.colour_target(aside);
  dev.begin(wipe, gpu::CLEAR, 0xFF000000);
  dev.end();
  begin_into(dev, held);
  other = dev.colour_target(aside);
  // a texture written inside the pass: a backend that stops drawing for the copy takes the
  // pass up again from what it holds of the target
  picture.put(0, 0, [0xFF102030 as u32, 0xFF405060 as u32, 0xFF708090 as u32, 0xFFA0B0C0 as u32], 2, 2);
  dev.bind(into_colour);
  dev.sample(0, picture);
  dev.vertices(quad);
  dev.draw(0, 6);
  dev.end();
  // the device draws on after it: a pass into the window, and the two textures read back
  dev.begin_window(gpu::CLEAR, 0xFF00FF00);
  dev.end();
  read = dev.capture_of(dev.colour_target(held));
  beside = dev.capture_of(other);
  assert(len(read) == 64 * 48, "64 x 48: {len(read)}");
  // by hand: the picture's first pixel is at the bottom left, so the capture's last row starts with it
  assert((read[47 * 64] ?? 0) == 0xFF102030 && (read[63] ?? 0) == 0xFFA0B0C0, "the corners of the dropped target's texture: {read[47 * 64] ?? 0:x} {read[63] ?? 0:x}");
  assert((beside[47 * 64] ?? 0) == 0xFF000000 && (beside[63] ?? 0) == 0xFF000000, "the other target's texture stays as it was cleared: {beside[47 * 64] ?? 0:x} {beside[63] ?? 0:x}");
}

fn test_a_window_nobody_touches_holds_no_key_and_no_text() {
  if !display() { return; }
  dev = gpu::open(gpu_metal::table(), 64, 48, "host-input") ?? return assert(false, "no device");
  _ = dev.poll();
  assert(!dev.key_down(65), "no key is down");
  assert(dev.buttons() == 0, "no button is held");
  assert(len(dev.typed()) == 0, "nothing was typed");
  assert(len(dev.events()) % gpu::EVENT_WORDS == 0, "events come whole");
}

// What a device made outlives it: dropped after the window closed, nothing is touched twice.
fn test_what_a_device_made_may_outlive_it() {
  if !display() { return; }
  dev = gpu::open(gpu_metal::table(), 64, 48, "host-outlive") ?? return assert(false, "no device");
  pipe = dev.pipeline(show(), gpu::State {}) ?? return assert(false, "pipeline");
  quad = dev.buffer(frame());
  t = dev.texture(4, 4);
  z = dev.depth_texture(4, 4);
  target = dev.target(t, z);
  dev.begin(target, gpu::CLEAR, 0xFF000000);
  dev.end();
  dev.close();
  assert(dev.width() == 0 && !dev.poll(), "a closed device has no window");
  // Using what a closed device made does nothing in the library as it ships.  A checked
  // build reports it as a fault (tests/checked.loft holds that), so it is not done there.
  if !gpu_metal::checked() {
    quad.update(frame());
    t.put(0, 0, [0xFF010203 as u32], 1, 1);
  }
  assert(len(pipe.block().floats()) == 0, "the pipeline's block is still its own");
  assert(len(dev.capture_of(target)) == 16, "and a closed device reads nothing into a target's size");
}

// Frames shown one after another: each is drawn, captured as drawn and handed over.
fn test_frames_are_presented_one_after_another() {
  if !display() { return; }
  dev = gpu::open(gpu_metal::table(), 64, 48, "host-present") ?? return assert(false, "no device");
  for i in 0..5 {
    assert(dev.poll(), "the window stays open");
    dev.begin_window(gpu::CLEAR, 0xFF000000 + 40 * i);
    dev.end();
    c = dev.capture();
    assert((c[0] ?? 0) == ((0xFF000000 + 40 * i) & 4294967295) as u32, "frame {i} holds its own colour: {c[0] ?? 0:x}");
    dev.present();
  }
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
}

// ── a viewport that reaches outside what the pass draws into ──

const PLAIN_V: text = `
struct In {{ float2 pos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; }};
vertex Out vertex_main(In in [[stage_in]]) {{
  Out o;
  o.position = gpu_position(float4(in.pos, 0.0, 1.0));
  return o;
}}
`;

fn plain() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F2],
    instance: [],
    block: [],
    textures: 0,
    sources: [gpu::source("msl", PLAIN_V, WHITE_F)],
  }
}

// The white pixels of one triangle, corners (-1, -1), (1, -0.6) and (-0.2, 1), drawn through the
// viewport (x, y, width, height) into the window or a 64 x 48 target.
fn covered(into_target: boolean, x: integer, y: integer, width: integer, height: integer) -> integer {
  dev = gpu::open(gpu_metal::table(), 64, 48, "host-viewport") ?? return -1;
  pipe = dev.pipeline(plain(), gpu::State { into: if into_target { gpu::INTO_COLOUR } else { gpu::INTO_WINDOW } }) ?? return -2;
  corners = dev.buffer([-1.0f, -1.0f, 1.0f, -0.6f, -0.2f, 1.0f]);
  colour = dev.texture(64, 48);
  target = dev.colour_target(colour);
  if into_target { dev.begin(target, gpu::CLEAR, 0xFF000000); } else { dev.begin_window(gpu::CLEAR, 0xFF000000); }
  dev.bind(pipe);
  dev.vertices(corners);
  dev.viewport(x, y, width, height);
  dev.draw(0, 3);
  dev.end();
  c = if into_target { dev.capture_of(target) } else { dev.capture() };
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  white = 0;
  for p in c {
    if p == 0xFFFFFFFF { white += 1; }
  }
  white
}

// The part inside is drawn, and it is the part the whole viewport puts there.  Counted by hand,
// a pixel drawn when its middle lies inside the triangle: the viewport (-100, 20, 300, 20) maps
// the 64 columns onto clip x from -1/3 to 7/75, and covers 1045 middles, one more lying on an
// edge, which the rasteriser's tie rule decides; the viewport (10, -4000, 20, 8000) maps the 48
// rows onto clip y from 0 to 0.012, where the triangle spans 11 columns: 11 x 48 = 528.
fn test_a_viewport_that_reaches_outside_draws_the_part_inside() {
  if !display() { return; }
  for into_target in [false, true] {
    wide = covered(into_target, -100, 20, 300, 20);
    assert(wide == 1045 || wide == 1046, "the viewport 300 pixels wide: {wide} pixels drawn (1045, or 1046 with the edge one)");
    tall = covered(into_target, 10, -4000, 20, 8000);
    assert(tall == 528, "the viewport 8000 pixels tall: {tall} pixels drawn");
  }
}

tests/same_as_gl.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// One scene drawn through `gpu` on this backend and on `gpu_gl` gives the same picture.  Each
// scene is one function that opens a device of the backend it is given, draws and captures: the
// drawing is the same loft for both, only the shader source differs.  `gpu_gl` is not a
// dependency of this package: it is the picture this backend is measured against.  One backend
// serves a program at a time, so a scene's device is closed before the next one opens.
// Without a Mac's display every test returns at once (`GRAPHICS_TEST_WINDOW=1`).
use gpu;
use gpu_gl;
use gpu_metal;

fn display() -> boolean {
  gpu_metal::table() != 0 && must_draw((env_variable("GRAPHICS_TEST_WINDOW") ?? "") == "1")
}

// A run that says its tests must draw (`GRAPHICS_TEST_MUST_DRAW=1`: the library CI, on a runner
// it gave a display) fails here, where a test would otherwise return having drawn nothing.
fn must_draw(can: boolean) -> boolean {
  assert(can || (env_variable("GRAPHICS_TEST_MUST_DRAW") ?? "") != "1", "this run's tests must draw (GRAPHICS_TEST_MUST_DRAW=1) and found no display to draw on");
  can
}

// ── the comparison ──

// How far two channels of a pixel lie apart at most.
fn apart(a: integer, b: integer) -> integer {
  most = 0;
  for shift in [0, 8, 16, 24] {
    d = ((a >> shift) & 255) - ((b >> shift) & 255);
    if d < 0 { d = -d; }
    if d > most { most = d; }
  }
  most
}

// Whether the OpenGL measured against is Apple's software renderer: the OpenGL of a Mac with no
// GPU of its own to give it, as a virtual machine's (a CI runner's).  It rounds a colour its own
// way, by 1 or 2 of 255 where a Mac's GPU and Metal agree to the bit.  Known once a scene was
// drawn through `gpu_gl`.
fn software_reference() -> boolean {
  gpu_gl::renderer() == "Apple Software Renderer"
}

// The two pictures agree: at most `pixels` of them differ, none by more than `step` of 255 in
// a channel; against the software renderer any pixel may differ by 2 at most.  A scene of one
// colour proves nothing and fails.
fn agree(gl: const vector<u32>, metal: const vector<u32>, what: text, pixels: integer, step: integer) {
  assert(len(gl) == len(metal) && len(gl) > 0, "{what}: {len(gl)} pixels through OpenGL, {len(metal)} through Metal");
  if software_reference() {
    if pixels < len(gl) { pixels = len(gl); }
    if step < 2 { step = 2; }
  }
  differ = 0;
  worst = 0;
  first = -1;
  colours = 0;
  for p in gl {
    q = metal[p#index] ?? 0;
    if p != q {
      differ += 1;
      if first < 0 { first = p#index; }
      d = apart(p as integer, q as integer);
      if d > worst { worst = d; }
    }
    if p != gl[0] { colours += 1; }
  }
  assert(colours > 0, "{what}: the scene shows one colour only");
  assert(differ <= pixels && worst <= step, "{what}: {differ} pixels differ (at most {pixels} may), the worst by {worst} of 255 (at most {step}), the first at {first}: {gl[first] ?? 0:x} through OpenGL, {metal[first] ?? 0:x} through Metal");
}

// ── M1: one triangle ──
//
// A triangle with no edge along a pixel row or column, its corners red, green and blue: which
// pixels an edge covers and how a colour is carried between the corners are the two things a
// rasteriser decides on its own.

const TRI_V_GL: text = `
#version 330 core
layout(location = 0) in vec3 pos;
layout(location = 1) in vec4 tint;
out vec4 v_tint;
void main() {{ v_tint = tint; gl_Position = vec4(pos, 1.0); }}
`;

const TRI_F_GL: text = `
#version 330 core
in vec4 v_tint;
out vec4 frag;
void main() {{ frag = v_tint; }}
`;

const TRI_V_MSL: text = `
struct In {{ float3 pos [[attribute(0)]]; float4 tint [[attribute(1)]]; }};
struct Out {{ float4 position [[position]]; float4 tint; }};
vertex Out vertex_main(In in [[stage_in]]) {{
  Out o;
  o.tint = in.tint;
  o.position = gpu_position(float4(in.pos, 1.0));
  return o;
}}
`;

const TRI_F_MSL: text = `
struct Out {{ float4 position [[position]]; float4 tint; }};
fragment float4 fragment_main(Out in [[stage_in]]) {{ return in.tint; }}
`;

fn tinted() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3, gpu::F4],
    instance: [],
    block: [],
    textures: 0,
    sources: [gpu::source("glsl-330", TRI_V_GL, TRI_F_GL), gpu::source("msl", TRI_V_MSL, TRI_F_MSL)],
  }
}

fn triangle(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "triangle") ?? return [];
  pipe = dev.pipeline(tinted(), gpu::State {}) ?? return [];
  corners = dev.buffer([
    -0.8f, -0.7f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
    0.9f, -0.3f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
    -0.1f, 0.8f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f
  ]);
  dev.begin_window(gpu::CLEAR, 0xFF202020);
  dev.bind(pipe);
  dev.vertices(corners);
  dev.draw(0, 3);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_one_triangle() {
  if !display() { return; }
  gl = triangle(gpu_gl::table());
  metal = triangle(gpu_metal::table());
  agree(gl, metal, "one triangle", 0, 0);
}

// ── M2: one capability a scene ──

const BLUE = 0xFF0000FF;

// One colour, placed by a depth: the block is a vector and a float.
const FLAT_V_GL: text = `
#version 330 core
layout(location = 0) in vec3 pos;
layout(std140) uniform Block {{ vec4 color; float z; }};
void main() {{ gl_Position = vec4(pos.xy, z, 1.0); gl_PointSize = 1.0; }}
`;

const FLAT_F_GL: text = `
#version 330 core
layout(std140) uniform Block {{ vec4 color; float z; }};
out vec4 frag;
void main() {{ frag = color; }}
`;

const FLAT_V_MSL: text = `
struct Block {{ float4 color; float z; }};
struct In {{ float3 pos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; float size [[point_size]]; }};
vertex Out vertex_main(In in [[stage_in]], constant Block &u [[buffer(0)]]) {{
  Out o;
  o.position = gpu_position(float4(in.pos.xy, u.z, 1.0));
  o.size = 1.0;
  return o;
}}
`;

const FLAT_F_MSL: text = `
struct Block {{ float4 color; float z; }};
fragment float4 fragment_main(constant Block &u [[buffer(0)]]) {{ return u.color; }}
`;

fn flat() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::F4, gpu::F1],
    textures: 0,
    sources: [gpu::source("glsl-330", FLAT_V_GL, FLAT_F_GL), gpu::source("msl", FLAT_V_MSL, FLAT_F_MSL)],
  }
}

// A texture over the vertices: position, a normal nobody reads, a texture coordinate.
const TEX_V_GL: text = `
#version 330 core
layout(location = 0) in vec3 pos;
layout(location = 2) in vec2 uv;
out vec2 v_uv;
void main() {{ v_uv = uv; gl_Position = vec4(pos, 1.0); }}
`;

const TEX_F_GL: text = `
#version 330 core
uniform sampler2D tex0;
in vec2 v_uv;
out vec4 frag;
void main() {{ frag = texture(tex0, v_uv); }}
`;

const TEX_V_MSL: text = `
struct In {{ float3 pos [[attribute(0)]]; float2 uv [[attribute(2)]]; }};
struct Out {{ float4 position [[position]]; float2 uv; }};
vertex Out vertex_main(In in [[stage_in]]) {{
  Out o;
  o.uv = in.uv;
  o.position = gpu_position(float4(in.pos, 1.0));
  return o;
}}
`;

const TEX_F_MSL: text = `
struct Out {{ float4 position [[position]]; float2 uv; }};
fragment float4 fragment_main(Out in [[stage_in]], texture2d<float> tex0 [[texture(0)]], sampler s0 [[sampler(0)]]) {{
  return tex0.sample(s0, in.uv);
}}
`;

fn textured() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3, gpu::F3, gpu::F2],
    instance: [],
    block: [],
    textures: 1,
    sources: [gpu::source("glsl-330", TEX_V_GL, TEX_F_GL), gpu::source("msl", TEX_V_MSL, TEX_F_MSL)],
  }
}

// The same vertices showing a depth texture: its depth as a grey.
const DEPTH_F_GL: text = `
#version 330 core
uniform sampler2D tex0;
in vec2 v_uv;
out vec4 frag;
void main() {{ float d = texture(tex0, v_uv).r; frag = vec4(d, d, d, 1.0); }}
`;

const DEPTH_F_MSL: text = `
struct Out {{ float4 position [[position]]; float2 uv; }};
fragment float4 fragment_main(Out in [[stage_in]], depth2d<float> tex0 [[texture(0)]], sampler s0 [[sampler(0)]]) {{
  float d = tex0.sample(s0, in.uv);
  return float4(d, d, d, 1.0);
}}
`;

fn depth_shown() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3, gpu::F3, gpu::F2],
    instance: [],
    block: [],
    textures: 1,
    sources: [gpu::source("glsl-330", TEX_V_GL, DEPTH_F_GL), gpu::source("msl", TEX_V_MSL, DEPTH_F_MSL)],
  }
}

// Copies: a strip moved by a float read once per copy.
const COPY_V_GL: text = `
#version 330 core
layout(location = 0) in vec3 pos;
layout(location = 1) in float dx;
layout(std140) uniform Block {{ vec4 color; float z; }};
void main() {{ gl_Position = vec4(pos.x + dx, pos.y, 0.0, 1.0); }}
`;

const COPY_V_MSL: text = `
struct In {{ float3 pos [[attribute(0)]]; float dx [[attribute(1)]]; }};
struct Out {{ float4 position [[position]]; }};
vertex Out vertex_main(In in [[stage_in]]) {{
  Out o;
  o.position = gpu_position(float4(in.pos.x + in.dx, in.pos.y, 0.0, 1.0));
  return o;
}}
`;

fn copied() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3],
    instance: [gpu::F1],
    block: [gpu::F4, gpu::F1],
    textures: 0,
    sources: [gpu::source("glsl-330", COPY_V_GL, FLAT_F_GL), gpu::source("msl", COPY_V_MSL, FLAT_F_MSL)],
  }
}

// ── geometry ──

// Two triangles over (x0, y0)-(x1, y1), counter-clockwise, or clockwise.
fn rect(x0: float, y0: float, x1: float, y1: float, clockwise: boolean) -> vector<single> {
  ccw = [x0, y0, x1, y0, x1, y1, x0, y0, x1, y1, x0, y1];
  cw = [x0, y0, x1, y1, x1, y0, x0, y0, x0, y1, x1, y1];
  out: vector<single> = [];
  for i in 0..6 {
    x = if clockwise { cw[2 * i] } else { ccw[2 * i] };
    y = if clockwise { cw[2 * i + 1] } else { ccw[2 * i + 1] };
    out += [x as single, y as single, 0.0 as single];
  }
  out
}

// The rectangle (x0, y0)-(x1, y1) with a normal nobody reads and the whole texture over it.
fn frame8(x0: float, y0: float, x1: float, y1: float) -> vector<single> {
  xy = [x0, y0, x1, y0, x1, y1, x0, y0, x1, y1, x0, y1];
  uv = [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0];
  out: vector<single> = [];
  for i in 0..6 {
    out += [xy[2 * i] as single, xy[2 * i + 1] as single, 0.0f, 0.0f, 0.0f, 1.0f, uv[2 * i] as single, uv[2 * i + 1] as single];
  }
  out
}

// A `side` x `side` picture, every pixel its own opaque colour.
fn picture(side: integer) -> vector<u32> {
  out: vector<u32> = [];
  for i in 0..side * side {
    r = (40 + 12 * i) % 256;
    g = (250 - 13 * i) & 255;
    b = 17 * (i % 5) + 30;
    out += [((0xFF000000 | (r << 16) | (g << 8) | b) & 4294967295) as u32];
  }
  out
}

// ── depth and blending ──

// Red behind, green in front on the left, blue further back hidden, then a half-transparent
// white strip blended over the lower half; a second pass keeps the frame and adds a strip.
fn depth_and_blend(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "depth") ?? return [];
  solid = dev.pipeline(flat(), gpu::State { depth: gpu::DEPTH_TEST_WRITE }) ?? return [];
  tested = dev.pipeline(flat(), gpu::State { depth: gpu::DEPTH_TEST }) ?? return [];
  over = dev.pipeline(flat(), gpu::State { blend: gpu::blend(gpu::SRC_ALPHA, gpu::ONE_MINUS_SRC_ALPHA) }) ?? return [];
  added = dev.pipeline(flat(), gpu::State { blend: gpu::blend(gpu::ONE, gpu::ONE) }) ?? return [];
  b_left = dev.buffer(rect(-1.0, -1.0, 0.0, 1.0, false));
  b_whole = dev.buffer(rect(-1.0, -1.0, 1.0, 1.0, false));
  b_low = dev.buffer(rect(-1.0, -1.0, 1.0, 0.0, false));
  b_mid = dev.buffer(rect(-0.5, -0.5, 0.5, 0.5, false));
  u = solid.block();
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(solid);
  u.f4(0, 1.0, 0.0, 0.0, 1.0);
  u.f1(1, 0.5);
  dev.uniforms(u);
  dev.vertices(b_whole);
  dev.draw(0, 6);
  u.f4(0, 0.0, 1.0, 0.0, 1.0);
  u.f1(1, -0.5);
  dev.uniforms(u);
  dev.vertices(b_left);
  dev.draw(0, 6);
  u.f4(0, 0.0, 0.0, 1.0, 1.0);
  u.f1(1, 0.9);
  dev.uniforms(u);
  dev.vertices(b_whole);
  dev.draw(0, 6);
  // tested and not written: a grey square between the two depths shows on the right only, and
  // a second one behind it is still drawn over it, as nothing was written
  dev.bind(tested);
  u.f4(0, 0.5, 0.5, 0.5, 1.0);
  u.f1(1, 0.0);
  dev.uniforms(u);
  dev.vertices(b_mid);
  dev.draw(0, 6);
  u.f4(0, 0.2, 0.6, 0.8, 1.0);
  u.f1(1, 0.25);
  dev.uniforms(u);
  dev.vertices(b_low);
  dev.draw(0, 6);
  dev.bind(over);
  u.f4(0, 1.0, 1.0, 1.0, 0.4);
  u.f1(1, 0.0);
  dev.uniforms(u);
  dev.vertices(b_low);
  dev.draw(0, 6);
  dev.end();
  dev.begin_window(gpu::KEEP, 0);
  dev.bind(added);
  u.f4(0, 0.25, 0.125, 0.0, 1.0);
  dev.uniforms(u);
  dev.vertices(b_mid);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_depth_and_blending() {
  if !display() { return; }
  agree(depth_and_blend(gpu_gl::table()), depth_and_blend(gpu_metal::table()), "depth and blending", 0, 0);
}

// ── a depth written without a test ──

// A near red frame everywhere; then, inside a scissor over the left half, a green frame at the
// far end that writes its depth untested, which is what a clear of part of a target does; then
// a yellow frame further than the red one, tested.  It shows on the left only, where the depth
// was written over.
fn depth_written_untested(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "depth-write") ?? return [];
  solid = dev.pipeline(flat(), gpu::State { depth: gpu::DEPTH_TEST_WRITE }) ?? return [];
  wipe = dev.pipeline(flat(), gpu::State { depth: gpu::DEPTH_WRITE }) ?? return [];
  b_whole = dev.buffer(rect(-1.0, -1.0, 1.0, 1.0, false));
  u = solid.block();
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(solid);
  u.f4(0, 1.0, 0.0, 0.0, 1.0);
  u.f1(1, -0.5);
  dev.uniforms(u);
  dev.vertices(b_whole);
  dev.draw(0, 6);
  dev.bind(wipe);
  dev.scissor(0, 0, 32, 48);
  u.f4(0, 0.0, 1.0, 0.0, 1.0);
  u.f1(1, 1.0);
  dev.uniforms(u);
  dev.vertices(b_whole);
  dev.draw(0, 6);
  dev.no_scissor();
  dev.bind(solid);
  u.f4(0, 1.0, 1.0, 0.0, 1.0);
  u.f1(1, 0.5);
  dev.uniforms(u);
  dev.vertices(b_whole);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  assert(c[24 * 64 + 16] == 0xFFFFFF00, "left: the far frame shows where the depth was written over: {c[24 * 64 + 16]:x}");
  assert(c[24 * 64 + 48] == 0xFFFF0000, "right: the near frame kept its depth: {c[24 * 64 + 48]:x}");
  c
}

fn test_a_depth_written_without_a_test() {
  if !display() { return; }
  agree(depth_written_untested(gpu_gl::table()), depth_written_untested(gpu_metal::table()), "a depth written untested", 0, 0);
}

// ── culling, a scissor and a viewport ──

fn cull_scissor_viewport(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "rects") ?? return [];
  back = dev.pipeline(flat(), gpu::State { cull: gpu::CULL_BACK }) ?? return [];
  front = dev.pipeline(flat(), gpu::State { cull: gpu::CULL_FRONT }) ?? return [];
  plain = dev.pipeline(flat(), gpu::State {}) ?? return [];
  b_whole = dev.buffer(rect(-1.0, -1.0, 1.0, 1.0, false));
  b_turned = dev.buffer(rect(-1.0, -1.0, 1.0, 1.0, true));
  b_corner = dev.buffer(rect(0.5, 0.5, 1.0, 1.0, false));
  u = plain.block();
  dev.begin_window(gpu::CLEAR, BLUE);
  // a clockwise square is the back: not drawn where the back is dropped
  dev.bind(back);
  u.f4(0, 1.0, 1.0, 0.0, 1.0);
  dev.uniforms(u);
  dev.vertices(b_turned);
  dev.draw(0, 6);
  // and drawn where the front is; a counter-clockwise corner is not
  dev.bind(front);
  dev.viewport(0, 0, 20, 10);
  u.f4(0, 1.0, 0.0, 1.0, 1.0);
  dev.uniforms(u);
  dev.vertices(b_turned);
  dev.draw(0, 6);
  dev.viewport(0, 0, 64, 48);
  u.f4(0, 0.0, 0.0, 0.0, 1.0);
  dev.uniforms(u);
  dev.vertices(b_corner);
  dev.draw(0, 6);
  dev.bind(plain);
  dev.scissor(5, 7, 30, 20);
  u.f4(0, 0.0, 1.0, 0.0, 1.0);
  dev.uniforms(u);
  dev.vertices(b_whole);
  dev.draw(0, 6);
  // a scissor that leaves the window is cut to it, and one wholly outside draws nothing
  dev.scissor(50, 40, 30, 20);
  u.f4(0, 0.0, 1.0, 1.0, 1.0);
  dev.uniforms(u);
  dev.draw(0, 6);
  dev.scissor(70, 10, 5, 5);
  u.f4(0, 1.0, 1.0, 1.0, 1.0);
  dev.uniforms(u);
  dev.draw(0, 6);
  dev.no_scissor();
  dev.viewport(40, 30, 16, 12);
  u.f4(0, 1.0, 0.0, 0.0, 1.0);
  dev.uniforms(u);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_culling_a_scissor_and_a_viewport() {
  if !display() { return; }
  agree(cull_scissor_viewport(gpu_gl::table()), cull_scissor_viewport(gpu_metal::table()), "cull, scissor and viewport", 0, 0);
}

// ── textures ──

// A picture sampled nearest, a patch put into it between two passes of one frame, and an
// RGB565 strip put into another.
fn textures_put(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "texture") ?? return [];
  pipe = dev.pipeline(textured(), gpu::State {}) ?? return [];
  left = dev.buffer(frame8(-1.0, -1.0, 0.0, 1.0));
  right = dev.buffer(frame8(0.0, -1.0, 1.0, 1.0));
  low = dev.buffer(frame8(-0.5, -1.0, 0.5, -0.5));
  t = dev.texture_from(picture(4), 4, 4);
  t.nearest(true);
  small = dev.texture(2, 2);
  small.nearest(true);
  small.put_rgb565(0, 0, [63488 as i32, 2016 as i32, 31 as i32, 33800 as i32], 2, 2);
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(pipe);
  dev.sample(0, t);
  dev.vertices(left);
  dev.draw(0, 6);
  dev.end();
  // the left half was drawn with the picture as it was: the patch shows on the right only
  t.put(1, 2, [0xFF00FF00 as u32, 0xFFFF00FF as u32], 2, 1);
  // a put that leaves the texture changes nothing
  t.put(3, 3, [0xFFFFFFFF as u32, 0xFFFFFFFF as u32], 2, 1);
  dev.begin_window(gpu::KEEP, 0);
  dev.bind(pipe);
  dev.sample(0, t);
  dev.vertices(right);
  dev.draw(0, 6);
  dev.sample(0, small);
  dev.vertices(low);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_texture_put_and_sampled_nearest() {
  if !display() { return; }
  agree(textures_put(gpu_gl::table()), textures_put(gpu_metal::table()), "a texture put", 0, 0);
}

// Between its pixels a texture is sampled from both neighbours, and at its edge from the edge
// pixel alone: the frame reaches past the texture's edges.
fn texture_between(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "linear") ?? return [];
  pipe = dev.pipeline(textured(), gpu::State {}) ?? return [];
  xy = [-1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0];
  wide: vector<single> = [];
  for i in 0..6 {
    wide += [xy[2 * i] as single, xy[2 * i + 1] as single, 0.0f, 0.0f, 0.0f, 1.0f, (xy[2 * i] * 0.75 + 0.5) as single, (xy[2 * i + 1] * 0.75 + 0.5) as single];
  }
  b = dev.buffer(wide);
  t = dev.texture_from(picture(4), 4, 4);
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(pipe);
  dev.sample(0, t);
  dev.vertices(b);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_texture_sampled_between_its_pixels_is_clamped_at_its_edges() {
  if !display() { return; }
  agree(texture_between(gpu_gl::table()), texture_between(gpu_metal::table()), "a texture between its pixels", 0, 0);
}

// A 32 x 32 picture of four-pixel squares drawn a quarter and a tenth of its size: with its
// smaller copies built, each pixel is an average of the squares it covers.
fn texture_small(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "mipmaps") ?? return [];
  pipe = dev.pipeline(textured(), gpu::State {}) ?? return [];
  b = dev.buffer(frame8(-1.0, -1.0, 1.0, 1.0));
  px: vector<u32> = [];
  for i in 0..32 * 32 {
    on = (((i % 32) / 4) + ((i / 32) / 4)) % 2 == 0;
    px += [if on { 0xFFFFE010 as u32 } else { 0xFF2040C0 as u32 }];
  }
  t = dev.texture_from(px, 32, 32);
  t.mipmaps();
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(pipe);
  dev.sample(0, t);
  dev.vertices(b);
  dev.viewport(2, 2, 8, 8);
  dev.draw(0, 6);
  dev.viewport(20, 4, 3, 3);
  dev.draw(0, 6);
  dev.viewport(30, 10, 32, 32);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_texture_drawn_small_through_its_smaller_copies() {
  if !display() { return; }
  agree(texture_small(gpu_gl::table()), texture_small(gpu_metal::table()), "a texture drawn small", 0, 0);
}

// ── buffers: copies read from an offset, an index list, floats replaced ──

fn copies_and_indices(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "copies") ?? return [];
  many = dev.pipeline(copied(), gpu::State {}) ?? return [];
  one = dev.pipeline(flat(), gpu::State {}) ?? return [];
  strip = dev.buffer(rect(-0.9, -0.8, -0.7, 0.8, false));
  // two floats nobody reads, then a step for each of three copies
  per_copy = dev.buffer([9.0f, 9.0f, 0.0f, 0.5f, 1.25f]);
  corners = dev.buffer([-0.25f, -0.25f, 0.0f, 0.25f, -0.25f, 0.0f, 0.25f, 0.25f, 0.0f, -0.25f, 0.25f, 0.0f]);
  list = dev.index_buffer([0, 1, 2, 0, 2, 3]);
  moving = dev.buffer(rect(-1.0, -1.0, -0.5, -0.5, false));
  late = dev.buffer([0.0f, 0.0f, 0.0f]);
  u = many.block();
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(many);
  u.f4(0, 0.0, 1.0, 0.0, 1.0);
  dev.uniforms(u);
  dev.vertices(strip);
  dev.instances(per_copy, 2);
  dev.draw_copies(6, 3);
  dev.bind(one);
  u.f4(0, 1.0, 0.0, 0.0, 1.0);
  dev.uniforms(u);
  dev.vertices(corners);
  dev.indices(list);
  dev.draw_indexed(6);
  u.f4(0, 1.0, 1.0, 0.0, 1.0);
  dev.uniforms(u);
  dev.vertices(moving);
  dev.draw(0, 6);
  // new floats inside the pass: what was drawn stays, and the next draw reads the new ones
  moving.update(rect(-1.0, 0.5, -0.5, 1.0, false));
  dev.draw(0, 6);
  // a buffer nothing has read yet, given more floats than it was made with
  late.update(rect(-0.25, -1.0, 0.25, -0.75, false));
  dev.vertices(late);
  dev.draw(0, 6);
  dev.end();
  // new floats, of another length: the pass before keeps what it drew
  moving.update(rect(0.5, 0.5, 1.0, 1.0, false) + rect(0.5, -1.0, 1.0, -0.5, false));
  dev.begin_window(gpu::KEEP, 0);
  dev.bind(one);
  dev.uniforms(u);
  dev.vertices(moving);
  dev.draw(3, 9);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_copies_an_index_list_and_floats_replaced() {
  if !display() { return; }
  agree(copies_and_indices(gpu_gl::table()), copies_and_indices(gpu_metal::table()), "copies and an index list", 0, 0);
}

// ── lines and points ──

fn lines_and_points(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "lines") ?? return [];
  lines = dev.pipeline(flat(), gpu::State { shape: gpu::LINES }) ?? return [];
  points = dev.pipeline(flat(), gpu::State { shape: gpu::POINTS }) ?? return [];
  ends = dev.buffer([-0.9f, -0.9f, 0.0f, 0.9f, 0.7f, 0.0f, -0.9f, 0.5f, 0.0f, 0.4f, 0.5f, 0.0f, -0.6f, 0.9f, 0.0f, -0.6f, -0.9f, 0.0f]);
  // pixel middles: a point covers the pixel its middle lies in
  dots = dev.buffer([0.015625f, 0.0208333f, 0.0f, 0.515625f, -0.479167f, 0.0f, -0.484375f, 0.6875f, 0.0f]);
  u = lines.block();
  u.f4(0, 1.0, 1.0, 0.0, 1.0);
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(lines);
  dev.uniforms(u);
  dev.vertices(ends);
  dev.draw(0, 6);
  dev.bind(points);
  u.f4(0, 1.0, 1.0, 1.0, 1.0);
  dev.uniforms(u);
  dev.vertices(dots);
  dev.draw(0, 3);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_lines_and_points() {
  if !display() { return; }
  agree(lines_and_points(gpu_gl::table()), lines_and_points(gpu_metal::table()), "lines and points", 0, 0);
}

// ── targets ──

// Into a 32 x 24 colour and depth target — green on the left in front of red below, a
// clockwise square dropped, a scissor in its lower left — then the target shown over the
// window, with its upper right corner again in a smaller rectangle; then the target itself.
fn into_a_target(table: i64, read_target: boolean) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "target") ?? return [];
  inner = dev.pipeline(flat(), gpu::State { depth: gpu::DEPTH_TEST_WRITE, cull: gpu::CULL_BACK, into: gpu::INTO_COLOUR_DEPTH }) ?? return [];
  outer = dev.pipeline(textured(), gpu::State {}) ?? return [];
  b_left = dev.buffer(rect(-1.0, -1.0, 0.0, 1.0, false));
  b_low = dev.buffer(rect(-1.0, -1.0, 1.0, -0.25, false));
  b_turned = dev.buffer(rect(-1.0, -1.0, 1.0, 1.0, true));
  b_whole = dev.buffer(rect(-1.0, -1.0, 1.0, 1.0, false));
  b_frame = dev.buffer(frame8(-1.0, -1.0, 1.0, 1.0));
  colour = dev.texture(32, 24);
  colour.nearest(true);
  depth = dev.depth_texture(32, 24);
  target = dev.target(colour, depth);
  u = inner.block();
  dev.begin(target, gpu::CLEAR, 0xFF202020);
  dev.bind(inner);
  u.f4(0, 0.0, 1.0, 0.0, 1.0);
  u.f1(1, -0.5);
  dev.uniforms(u);
  dev.vertices(b_left);
  dev.draw(0, 6);
  u.f4(0, 1.0, 0.0, 0.0, 1.0);
  u.f1(1, 0.5);
  dev.uniforms(u);
  dev.vertices(b_low);
  dev.draw(0, 6);
  u.f4(0, 1.0, 1.0, 1.0, 1.0);
  u.f1(1, -0.9);
  dev.uniforms(u);
  dev.vertices(b_turned);
  dev.draw(0, 6);
  dev.scissor(2, 3, 6, 4);
  u.f4(0, 1.0, 1.0, 0.0, 1.0);
  dev.uniforms(u);
  dev.vertices(b_whole);
  dev.draw(0, 6);
  dev.no_scissor();
  dev.viewport(20, 16, 8, 6);
  u.f4(0, 0.0, 1.0, 1.0, 1.0);
  dev.uniforms(u);
  dev.draw(0, 6);
  dev.end();
  if read_target {
    c = dev.capture_of(target);
    assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
    return c;
  }
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(outer);
  dev.sample(0, colour);
  dev.vertices(b_frame);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_scene_drawn_into_a_texture_first() {
  if !display() { return; }
  agree(into_a_target(gpu_gl::table(), false), into_a_target(gpu_metal::table(), false), "a target shown over the window", 0, 0);
  agree(into_a_target(gpu_gl::table(), true), into_a_target(gpu_metal::table(), true), "a target read back", 0, 0);
}

// A depth alone: two squares at two depths drawn into a depth texture, which the window then
// shows as greys; and a colour alone, where a depth test passes whatever was drawn before.
fn depth_alone(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "depth-target") ?? return [];
  shadow = dev.pipeline(flat(), gpu::State { depth: gpu::DEPTH_TEST_WRITE, into: gpu::INTO_DEPTH }) ?? return [];
  only = dev.pipeline(flat(), gpu::State { depth: gpu::DEPTH_TEST_WRITE, into: gpu::INTO_COLOUR }) ?? return [];
  show_depth = dev.pipeline(depth_shown(), gpu::State {}) ?? return [];
  show = dev.pipeline(textured(), gpu::State {}) ?? return [];
  b_left = dev.buffer(rect(-1.0, -1.0, 0.0, 0.5, false));
  b_low = dev.buffer(rect(-0.5, -1.0, 1.0, 0.0, false));
  upper = dev.buffer(frame8(-1.0, 0.0, 1.0, 1.0));
  lower = dev.buffer(frame8(-1.0, -1.0, 1.0, 0.0));
  depth = dev.depth_texture(16, 12);
  d_target = dev.depth_target(depth);
  colour = dev.texture(16, 12);
  colour.nearest(true);
  c_target = dev.colour_target(colour);
  u = shadow.block();
  dev.begin(d_target, gpu::CLEAR, 0);
  dev.bind(shadow);
  u.f1(1, 0.2);
  dev.uniforms(u);
  dev.vertices(b_left);
  dev.draw(0, 6);
  // behind the first where they overlap, in front of the far end elsewhere
  u.f1(1, 0.6);
  dev.uniforms(u);
  dev.vertices(b_low);
  dev.draw(0, 6);
  dev.end();
  dev.begin(c_target, gpu::CLEAR, 0xFF404040);
  dev.bind(only);
  u.f4(0, 1.0, 0.0, 0.0, 1.0);
  u.f1(1, -0.5);
  dev.uniforms(u);
  dev.vertices(b_left);
  dev.draw(0, 6);
  u.f4(0, 0.0, 1.0, 0.0, 1.0);
  u.f1(1, 0.5);
  dev.uniforms(u);
  dev.vertices(b_low);
  dev.draw(0, 6);
  dev.end();
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(show_depth);
  dev.sample(0, depth);
  dev.vertices(upper);
  dev.draw(0, 6);
  dev.bind(show);
  dev.sample(0, colour);
  dev.vertices(lower);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_depth_alone_and_a_colour_alone() {
  if !display() { return; }
  agree(depth_alone(gpu_gl::table()), depth_alone(gpu_metal::table()), "a depth target and a colour target", 0, 0);
}

// ── calls in the order they are made ──
//
// A texture written, re-filtered or given its smaller copies between two draws of one pass: the
// first draw shows it as it was, the second as it is.

fn checker() -> vector<u32> {
  px: vector<u32> = [];
  for i in 0..32 * 32 {
    on = (((i % 32) / 4) + ((i / 32) / 4)) % 2 == 0;
    px += [if on { 0xFFFFE010 as u32 } else { 0xFF2040C0 as u32 }];
  }
  px
}

fn put_in_a_pass(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "put in a pass") ?? return [];
  pipe = dev.pipeline(textured(), gpu::State {}) ?? return [];
  left = dev.buffer(frame8(-1.0, -1.0, 0.0, 1.0));
  right = dev.buffer(frame8(0.0, -1.0, 1.0, 1.0));
  low = dev.buffer(frame8(-0.5, -1.0, 0.5, -0.5));
  t = dev.texture_from(picture(4), 4, 4);
  t.nearest(true);
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(pipe);
  dev.sample(0, t);
  dev.vertices(left);
  dev.draw(0, 6);
  t.put(1, 2, [0xFF00FF00 as u32, 0xFFFF00FF as u32], 2, 1);
  dev.vertices(right);
  dev.draw(0, 6);
  t.put_rgb565(0, 0, [63488 as i32, 2016 as i32, 31 as i32, 33800 as i32], 2, 2);
  dev.vertices(low);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_texture_put_between_two_draws_of_a_pass() {
  if !display() { return; }
  gl = put_in_a_pass(gpu_gl::table());
  // the left half holds the picture as it was, the right half the patch
  assert(gl[20 * 64 + 12] != gl[20 * 64 + 44], "the patch shows on the right only");
  agree(gl, put_in_a_pass(gpu_metal::table()), "a texture put inside a pass", 0, 0);
}

// The pass's own colour written between two of its draws: over the first, under the second.
fn put_on_the_target(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "put on the target") ?? return [];
  only = dev.pipeline(flat(), gpu::State { into: gpu::INTO_COLOUR }) ?? return [];
  b_left = dev.buffer(rect(-1.0, -1.0, 0.0, 1.0, false));
  b_low = dev.buffer(rect(-1.0, -1.0, 1.0, -0.5, false));
  colour = dev.texture(16, 12);
  target = dev.colour_target(colour);
  u = only.block();
  dev.begin(target, gpu::CLEAR, 0xFF404040);
  dev.bind(only);
  u.f4(0, 1.0, 0.0, 0.0, 1.0);
  u.f1(1, 0.0);
  dev.uniforms(u);
  dev.vertices(b_left);
  dev.draw(0, 6);
  patch: vector<u32> = [for i in 0..6 * 12 { ((0xFF00FF00 + 3 * i) & 4294967295) as u32 }];
  colour.put(5, 0, patch, 6, 12);
  u.f4(0, 0.0, 0.0, 1.0, 1.0);
  dev.uniforms(u);
  dev.vertices(b_low);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture_of(target);
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_pass_whose_own_colour_is_put_between_two_draws() {
  if !display() { return; }
  agree(put_on_the_target(gpu_gl::table()), put_on_the_target(gpu_metal::table()), "the target put inside its pass", 0, 0);
}

// Nearest and between, changed after the texture was named for the pass: each draw is sampled
// the way that was asked last before it.
fn filter_in_a_pass(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "filter in a pass") ?? return [];
  pipe = dev.pipeline(textured(), gpu::State {}) ?? return [];
  left = dev.buffer(frame8(-1.0, -1.0, 0.0, 1.0));
  right = dev.buffer(frame8(0.0, -1.0, 1.0, 1.0));
  t = dev.texture_from(picture(4), 4, 4);
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(pipe);
  dev.sample(0, t);
  t.nearest(true);
  dev.vertices(left);
  dev.draw(0, 6);
  t.nearest(false);
  dev.vertices(right);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_texture_filter_changed_between_two_draws_of_a_pass() {
  if !display() { return; }
  agree(filter_in_a_pass(gpu_gl::table()), filter_in_a_pass(gpu_metal::table()), "a filter changed inside a pass", 0, 0);
}

// Smaller copies asked for between two draws: the first small draw reads the picture itself,
// the second its averages.
fn mipmaps_in_a_pass(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "mipmaps in a pass") ?? return [];
  pipe = dev.pipeline(textured(), gpu::State {}) ?? return [];
  b = dev.buffer(frame8(-1.0, -1.0, 1.0, 1.0));
  t = dev.texture_from(checker(), 32, 32);
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(pipe);
  dev.sample(0, t);
  dev.vertices(b);
  dev.viewport(2, 2, 6, 6);
  dev.draw(0, 6);
  t.mipmaps();
  dev.viewport(20, 4, 6, 6);
  dev.draw(0, 6);
  dev.viewport(30, 10, 32, 32);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_smaller_copies_asked_for_between_two_draws_of_a_pass() {
  if !display() { return; }
  agree(mipmaps_in_a_pass(gpu_gl::table()), mipmaps_in_a_pass(gpu_metal::table()), "mipmaps inside a pass", 0, 0);
}

// The pass's own colour given its smaller copies half way: they hold what was drawn before the
// call, the texture itself also what was drawn after it.
fn mipmaps_on_the_target(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "mipmaps on the target") ?? return [];
  only = dev.pipeline(flat(), gpu::State { into: gpu::INTO_COLOUR }) ?? return [];
  show = dev.pipeline(textured(), gpu::State {}) ?? return [];
  b_left = dev.buffer(rect(-1.0, -1.0, 0.0, 1.0, false));
  b_low = dev.buffer(rect(-1.0, -1.0, 1.0, 0.0, false));
  b_frame = dev.buffer(frame8(-1.0, -1.0, 1.0, 1.0));
  colour = dev.texture(32, 32);
  target = dev.colour_target(colour);
  u = only.block();
  dev.begin(target, gpu::CLEAR, 0xFF404040);
  dev.bind(only);
  u.f4(0, 1.0, 0.0, 0.0, 1.0);
  u.f1(1, 0.0);
  dev.uniforms(u);
  dev.vertices(b_left);
  dev.draw(0, 6);
  colour.mipmaps();
  u.f4(0, 0.0, 1.0, 0.0, 1.0);
  dev.uniforms(u);
  dev.vertices(b_low);
  dev.draw(0, 6);
  dev.end();
  dev.begin_window(gpu::CLEAR, BLUE);
  dev.bind(show);
  dev.sample(0, colour);
  dev.vertices(b_frame);
  dev.viewport(2, 2, 8, 8);
  dev.draw(0, 6);
  dev.viewport(30, 10, 32, 32);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_pass_whose_own_colour_is_given_smaller_copies() {
  if !display() { return; }
  agree(mipmaps_on_the_target(gpu_gl::table()), mipmaps_on_the_target(gpu_metal::table()), "mipmaps of the target inside its pass", 0, 0);
}

// ── the window ──

// A window has no alpha: whatever a draw writes there, it reads back opaque and a blend by
// what the window holds finds 1.
fn window_alpha(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "alpha") ?? return [];
  plain = dev.pipeline(tinted(), gpu::State {}) ?? return [];
  by_held = dev.pipeline(tinted(), gpu::State { blend: gpu::blend(gpu::DST_ALPHA, gpu::ONE_MINUS_DST_ALPHA) }) ?? return [];
  faint = dev.buffer([
    -0.8f, -0.7f, 0.0f, 1.0f, 0.0f, 0.0f, 0.25f,
    0.9f, -0.3f, 0.0f, 0.0f, 1.0f, 0.0f, 0.25f,
    -0.1f, 0.8f, 0.0f, 0.0f, 0.0f, 1.0f, 0.25f
  ]);
  over = dev.buffer([
    -0.9f, 0.9f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f,
    0.2f, -0.9f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f,
    0.9f, 0.6f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f
  ]);
  dev.begin_window(gpu::CLEAR, 0x40202020);
  dev.bind(plain);
  dev.vertices(faint);
  dev.draw(0, 3);
  dev.bind(by_held);
  dev.vertices(over);
  dev.draw(0, 3);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn opaque(c: const vector<u32>, what: text) {
  for p in c {
    assert((p as integer >> 24) & 255 == 255, "{what}: pixel {p#index} reads back {p:x}");
  }
}

fn test_the_window_reads_back_opaque() {
  if !display() { return; }
  gl = window_alpha(gpu_gl::table());
  metal = window_alpha(gpu_metal::table());
  agree(gl, metal, "a window drawn with alpha", 0, 0);
  opaque(metal, "through Metal");
  opaque(gl, "through OpenGL");
}

// What the window shows is what a capture reads, before and after the frame was presented.
fn shown(table: i64, present: boolean) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "shown") ?? return [];
  pipe = dev.pipeline(tinted(), gpu::State {}) ?? return [];
  corners = dev.buffer([
    -0.8f, -0.7f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
    0.9f, -0.3f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
    -0.1f, 0.8f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f
  ]);
  for frame in 0..3 {
    dev.begin_window(gpu::CLEAR, 0xFF202020l + 0x300000l * (frame as i64));
    dev.bind(pipe);
    dev.vertices(corners);
    dev.draw(0, 3);
    dev.end();
    if present || frame < 2 { dev.present(); }
  }
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_capture_after_the_frame_was_presented() {
  if !display() { return; }
  before = shown(gpu_metal::table(), false);
  after = shown(gpu_metal::table(), true);
  agree(before, after, "the third frame before and after it was presented", 0, 0);
  agree(shown(gpu_gl::table(), false), after, "the third frame presented", 0, 0);
  agree(shown(gpu_gl::table(), true), after, "the third frame presented through OpenGL", 0, 0);
}

// A viewport that reaches outside what the pass draws into: the part inside is drawn, in the
// window and in a target.
fn viewport_outside(table: i64, into_target: boolean) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "viewport") ?? return [];
  pipe = dev.pipeline(tinted(), gpu::State { into: if into_target { gpu::INTO_COLOUR } else { gpu::INTO_WINDOW } }) ?? return [];
  corners = dev.buffer([
    -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
    1.0f, -0.6f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
    -0.2f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f
  ]);
  colour = dev.texture(64, 48);
  target = dev.colour_target(colour);
  if into_target { dev.begin(target, gpu::CLEAR, 0xFF202020); } else { dev.begin_window(gpu::CLEAR, 0xFF202020); }
  dev.bind(pipe);
  dev.vertices(corners);
  dev.viewport(-20, -10, 50, 40);
  dev.draw(0, 3);
  dev.viewport(40, 30, 64, 48);
  dev.draw(0, 3);
  dev.viewport(-100, 20, 300, 20);
  dev.draw(0, 3);
  dev.viewport(10, -4000, 20, 8000);
  dev.draw(0, 3);
  dev.scissor(30, 2, 30, 12);
  dev.viewport(-30000, -30000, 60064, 60048);
  dev.draw(0, 3);
  dev.end();
  c = if into_target { dev.capture_of(target) } else { dev.capture() };
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_viewport_that_reaches_outside_what_it_draws_into() {
  if !display() { return; }
  gl = viewport_outside(gpu_gl::table(), false);
  // Apple's software renderer draws a viewport that reaches far outside wrongly: against counts
  // made by hand it covers 893 of 1045 pixels for (-100, 20, 300, 20) and none of 528 for
  // (10, -4000, 20, 8000), where Metal covers them.  Against it, those two are counted by hand
  // in `host.loft` instead.
  if software_reference() { return; }
  agree(gl, viewport_outside(gpu_metal::table(), false), "a viewport outside the window", 0, 0);
  agree(viewport_outside(gpu_gl::table(), true), viewport_outside(gpu_metal::table(), true), "a viewport outside a target", 0, 0);
}

tests/two_devices.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// Two windows open at once.  Each device draws into its own window and reads its own frame
// back, also when the draws of the two are interleaved and when one is closed while the other
// goes on: nothing a draw depends on is shared between two devices.
// Without a display every test returns at once (`DISPLAY`, or `GRAPHICS_TEST_WINDOW=1` on a
// Mac).
use gpu;
use gpu_metal;

fn display() -> boolean {
  gpu_metal::table() != 0 && must_draw((env_variable("GRAPHICS_TEST_WINDOW") ?? "") == "1")
}

// A run that says its tests must draw (`GRAPHICS_TEST_MUST_DRAW=1`: the library CI, on a runner
// it gave a display) fails here, where a test would otherwise return having drawn nothing.
fn must_draw(can: boolean) -> boolean {
  assert(can || (env_variable("GRAPHICS_TEST_MUST_DRAW") ?? "") != "1", "this run's tests must draw (GRAPHICS_TEST_MUST_DRAW=1) and found no display to draw on");
  can
}

const FLAT_V: text = `
struct Block {{ float4 color; float4 at; }};
struct In {{ float3 pos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; }};
vertex Out vertex_main(In in [[stage_in]], constant Block &u [[buffer(0)]]) {{
  Out o;
  o.position = gpu_position(float4(in.pos.xy * u.at.zw + u.at.xy, 0.0, 1.0));
  return o;
}}
`;

const FLAT_F: text = `
struct Block {{ float4 color; float4 at; }};
fragment float4 fragment_main(constant Block &u [[buffer(0)]]) {{ return u.color; }}
`;

fn flat() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::F4, gpu::F4],
    textures: 0,
    sources: [gpu::source("msl", FLAT_V, FLAT_F)],
  }
}

fn whole() -> vector<single> {
  [-1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f]
}

// The rectangle scaled by (sx, sy) about (cx, cy), in one colour.
fn fill(dev: gpu::Device, pipe: const gpu::Pipeline, mesh: const gpu::Buffer, r: float, g: float, b: float, cx: float, sx: float) {
  u = pipe.block();
  u.f4(0, r, g, b, 1.0);
  u.f4(1, cx, 0.0, sx, 1.0);
  dev.bind(pipe);
  dev.uniforms(u);
  dev.vertices(mesh);
  dev.draw(0, 6);
}

// Two devices, their passes interleaved call for call: one green on blue with a red left half,
// the other yellow on black with a white right half, and of another size.
fn test_two_devices_draw_and_read_back_their_own_frames() {
  ao = gpu::open(gpu_metal::table(), 64, 48, "one");
  if !display() { return; }
  a = ao ?? return assert(false, "no device");
  b = gpu::open(gpu_metal::table(), 32, 24, "two") ?? return assert(false, "no second device beside the first");
  pa = a.pipeline(flat(), gpu::State { depth: gpu::DEPTH_OFF }) ?? return assert(false, "no pipeline on the first");
  pb = b.pipeline(flat(), gpu::State { depth: gpu::DEPTH_OFF }) ?? return assert(false, "no pipeline on the second");
  ma = a.buffer(whole());
  mb = b.buffer(whole());
  a.begin_window(gpu::CLEAR, 0xFF0000FF);
  b.begin_window(gpu::CLEAR, 0xFF000000);
  fill(a, pa, ma, 0.0, 1.0, 0.0, 0.0, 1.0);
  fill(b, pb, mb, 1.0, 1.0, 0.0, 0.0, 1.0);
  fill(a, pa, ma, 1.0, 0.0, 0.0, -0.5, 0.5);
  fill(b, pb, mb, 1.0, 1.0, 1.0, 0.5, 0.5);
  a.end();
  b.end();
  sa = a.capture();
  sb = b.capture();
  assert(len(a.refusals()) == 0 && len(b.refusals()) == 0, "nothing refused: {a.refusals()} {b.refusals()}");
  assert(a.width() == 64 && a.height() == 48 && b.width() == 32 && b.height() == 24, "each keeps its size: {a.width()}x{a.height()} and {b.width()}x{b.height()}");
  assert(len(sa) == 64 * 48 && len(sb) == 32 * 24, "each frame has its own size: {len(sa)} and {len(sb)}");
  assert(sa[24 * 64 + 16] == 0xFFFF0000 && sa[24 * 64 + 48] == 0xFF00FF00, "the first shows red and green: {sa[24 * 64 + 16]:x} {sa[24 * 64 + 48]:x}");
  assert(sb[12 * 32 + 8] == 0xFFFFFF00 && sb[12 * 32 + 24] == 0xFFFFFFFF, "the second shows yellow and white: {sb[12 * 32 + 8]:x} {sb[12 * 32 + 24]:x}");
  // the second is closed; the first draws on and still reads its own
  b.close();
  a.begin_window(gpu::KEEP, 0);
  fill(a, pa, ma, 0.0, 0.0, 1.0, 0.5, 0.5);
  a.end();
  sa = a.capture();
  assert(len(a.refusals()) == 0, "nothing refused after the other closed: {a.refusals()}");
  assert(sa[24 * 64 + 16] == 0xFFFF0000 && sa[24 * 64 + 48] == 0xFF0000FF, "the first drew on after the second closed: {sa[24 * 64 + 16]:x} {sa[24 * 64 + 48]:x}");
}