gpu_paint source

← gpu_paint · API reference · version 0.2.1

4 file(s), 1032 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
Sprites struct306—328 330 341 352 450
cols const308—325 332 343 344 345 347 … (8 total)
rows const309—326 333 346 347 353 457
sprites fn320—71 191 204 221 224 233 … (10 total)
draw fn352—360 433 443 464 54 59 … (16 total)
Painter struct366—386 393 411 417 437 448
painter fn386—22 39 116 131 158 173 … (19 total)
resize fn411—124 139 259 264 278 88 … (7 total)
rect fn416—43 109 120 121 123 125 … (20 total)
image fn437—45 63 151 166 167 172 … (14 total)
sprite fn447—86 214 215 230 231 132 … (7 total)

src/gpu_paint.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// 2D drawing through `gpu`: rectangles, images and sprites at pixel positions.
//
//   p = gpu_paint::painter(dev, gpu::INTO_WINDOW) ?? return;   // origin top-left, y down
//   dev.begin_window(gpu::CLEAR, 0xFF202020);
//   p.rect(dev, 10.0, 10.0, 100.0, 20.0, 1.0, 0.5, 0.0, 1.0);
//   p.image(dev, icon, 120.0, 10.0, 32.0, 32.0);
//   p.sprite(dev, sheet, 160.0, 10.0, 32.0, 32.0, 3);
//   dev.end();
//
// A painter draws inside the pass the caller began, in call order, over whatever the pass
// holds: nothing it draws is tested against depth, so a later rectangle covers an earlier one
// and a HUD is never hidden behind a 3D scene.  It blends by a colour's alpha unless `blend`
// is switched off.  It names no backend: its shaders carry a source for each backend that
// exists, and a device of a backend it has no source for gives no painter.
use gpu;

// ── the shaders ──
//
// Each maps the unit quad (0, 0)-(1, 1) by the block's matrix onto pixel positions.

const FLAT_VERTEX_GLSL: text = `
#version 330 core
layout (location = 0) in vec3 aPos;
layout (std140) uniform Block {{ mat4 uMVP; vec4 uColor; }};
void main() {{ gl_Position = uMVP * vec4(aPos, 1.0); }}
`;

// SPIR-V of FLAT_VERTEX_GLSL (vertex), written by gpu_vulkan/spirv.py: do not edit.
const FLAT_VERTEX_SPV: text = `AwIjBwADAQALAAgAIwAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAA
AAAAAQAAAA8ABwAAAAAABAAAAG1haW4AAAAADQAAABkAAABHAAMACwAAAAIAAABIAAUACwAAAAAA
AAALAAAAAAAAAEgABQALAAAAAQAAAAsAAAABAAAASAAFAAsAAAACAAAACwAAAAMAAABIAAUACwAA
AAMAAAALAAAABAAAAEcAAwARAAAAAgAAAEgABAARAAAAAAAAAAUAAABIAAUAEQAAAAAAAAAHAAAA
EAAAAEgABQARAAAAAAAAACMAAAAAAAAASAAFABEAAAABAAAAIwAAAEAAAABHAAQAEwAAACEAAAAA
AAAARwAEABMAAAAiAAAAAAAAAEcABAAZAAAAHgAAAAAAAAATAAIAAgAAACEAAwADAAAAAgAAABYA
AwAGAAAAIAAAABcABAAHAAAABgAAAAQAAAAVAAQACAAAACAAAAAAAAAAKwAEAAgAAAAJAAAAAQAA
ABwABAAKAAAABgAAAAkAAAAeAAYACwAAAAcAAAAGAAAACgAAAAoAAAAgAAQADAAAAAMAAAALAAAA
OwAEAAwAAAANAAAAAwAAABUABAAOAAAAIAAAAAEAAAArAAQADgAAAA8AAAAAAAAAGAAEABAAAAAH
AAAABAAAAB4ABAARAAAAEAAAAAcAAAAgAAQAEgAAAAIAAAARAAAAOwAEABIAAAATAAAAAgAAACAA
BAAUAAAAAgAAABAAAAAXAAQAFwAAAAYAAAADAAAAIAAEABgAAAABAAAAFwAAADsABAAYAAAAGQAA
AAEAAAArAAQABgAAABsAAAAAAIA/IAAEACEAAAADAAAABwAAADYABQACAAAABAAAAAAAAAADAAAA
+AACAAUAAABBAAUAFAAAABUAAAATAAAADwAAAD0ABAAQAAAAFgAAABUAAAA9AAQAFwAAABoAAAAZ
AAAAUQAFAAYAAAAcAAAAGgAAAAAAAABRAAUABgAAAB0AAAAaAAAAAQAAAFEABQAGAAAAHgAAABoA
AAACAAAAUAAHAAcAAAAfAAAAHAAAAB0AAAAeAAAAGwAAAJEABQAHAAAAIAAAABYAAAAfAAAAQQAF
ACEAAAAiAAAADQAAAA8AAAA+AAMAIgAAACAAAAD9AAEAOAABAA==`;

const FLAT_FRAGMENT_GLSL: text = `
#version 330 core
layout (std140) uniform Block {{ mat4 uMVP; vec4 uColor; }};
out vec4 FragColor;
void main() {{ FragColor = uColor; }}
`;

// SPIR-V of FLAT_FRAGMENT_GLSL (fragment), written by gpu_vulkan/spirv.py: do not edit.
const FLAT_FRAGMENT_SPV: text = `AwIjBwADAQALAAgAEwAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAA
AAAAAQAAAA8ABgAEAAAABAAAAG1haW4AAAAACQAAABAAAwAEAAAABwAAAEcABAAJAAAAHgAAAAAA
AABHAAMACwAAAAIAAABIAAQACwAAAAAAAAAFAAAASAAFAAsAAAAAAAAABwAAABAAAABIAAUACwAA
AAAAAAAjAAAAAAAAAEgABQALAAAAAQAAACMAAABAAAAARwAEAA0AAAAhAAAAAAAAAEcABAANAAAA
IgAAAAAAAAATAAIAAgAAACEAAwADAAAAAgAAABYAAwAGAAAAIAAAABcABAAHAAAABgAAAAQAAAAg
AAQACAAAAAMAAAAHAAAAOwAEAAgAAAAJAAAAAwAAABgABAAKAAAABwAAAAQAAAAeAAQACwAAAAoA
AAAHAAAAIAAEAAwAAAACAAAACwAAADsABAAMAAAADQAAAAIAAAAVAAQADgAAACAAAAABAAAAKwAE
AA4AAAAPAAAAAQAAACAABAAQAAAAAgAAAAcAAAA2AAUAAgAAAAQAAAAAAAAAAwAAAPgAAgAFAAAA
QQAFABAAAAARAAAADQAAAA8AAAA9AAQABwAAABIAAAARAAAAPgADAAkAAAASAAAA/QABADgAAQA=`;

// The whole texture over the quad; a fully transparent texel is not drawn.
const IMAGE_VERTEX_GLSL: text = `
#version 330 core
layout (location = 0) in vec3 aPos;
layout (std140) uniform Block {{ mat4 uMVP; }};
out vec2 vUV;
void main() {{
    gl_Position = uMVP * vec4(aPos, 1.0);
    vUV = vec2(aPos.x, aPos.y);
}}
`;

// SPIR-V of IMAGE_VERTEX_GLSL (vertex), written by gpu_vulkan/spirv.py: do not edit.
const IMAGE_VERTEX_SPV: text = `AwIjBwADAQALAAgALQAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAA
AAAAAQAAAA8ACAAAAAAABAAAAG1haW4AAAAADQAAABkAAAAlAAAARwADAAsAAAACAAAASAAFAAsA
AAAAAAAACwAAAAAAAABIAAUACwAAAAEAAAALAAAAAQAAAEgABQALAAAAAgAAAAsAAAADAAAASAAF
AAsAAAADAAAACwAAAAQAAABHAAMAEQAAAAIAAABIAAQAEQAAAAAAAAAFAAAASAAFABEAAAAAAAAA
BwAAABAAAABIAAUAEQAAAAAAAAAjAAAAAAAAAEcABAATAAAAIQAAAAAAAABHAAQAEwAAACIAAAAA
AAAARwAEABkAAAAeAAAAAAAAAEcABAAlAAAAHgAAAAAAAAATAAIAAgAAACEAAwADAAAAAgAAABYA
AwAGAAAAIAAAABcABAAHAAAABgAAAAQAAAAVAAQACAAAACAAAAAAAAAAKwAEAAgAAAAJAAAAAQAA
ABwABAAKAAAABgAAAAkAAAAeAAYACwAAAAcAAAAGAAAACgAAAAoAAAAgAAQADAAAAAMAAAALAAAA
OwAEAAwAAAANAAAAAwAAABUABAAOAAAAIAAAAAEAAAArAAQADgAAAA8AAAAAAAAAGAAEABAAAAAH
AAAABAAAAB4AAwARAAAAEAAAACAABAASAAAAAgAAABEAAAA7AAQAEgAAABMAAAACAAAAIAAEABQA
AAACAAAAEAAAABcABAAXAAAABgAAAAMAAAAgAAQAGAAAAAEAAAAXAAAAOwAEABgAAAAZAAAAAQAA
ACsABAAGAAAAGwAAAAAAgD8gAAQAIQAAAAMAAAAHAAAAFwAEACMAAAAGAAAAAgAAACAABAAkAAAA
AwAAACMAAAA7AAQAJAAAACUAAAADAAAAKwAEAAgAAAAmAAAAAAAAACAABAAnAAAAAQAAAAYAAAA2
AAUAAgAAAAQAAAAAAAAAAwAAAPgAAgAFAAAAQQAFABQAAAAVAAAAEwAAAA8AAAA9AAQAEAAAABYA
AAAVAAAAPQAEABcAAAAaAAAAGQAAAFEABQAGAAAAHAAAABoAAAAAAAAAUQAFAAYAAAAdAAAAGgAA
AAEAAABRAAUABgAAAB4AAAAaAAAAAgAAAFAABwAHAAAAHwAAABwAAAAdAAAAHgAAABsAAACRAAUA
BwAAACAAAAAWAAAAHwAAAEEABQAhAAAAIgAAAA0AAAAPAAAAPgADACIAAAAgAAAAQQAFACcAAAAo
AAAAGQAAACYAAAA9AAQABgAAACkAAAAoAAAAQQAFACcAAAAqAAAAGQAAAAkAAAA9AAQABgAAACsA
AAAqAAAAUAAFACMAAAAsAAAAKQAAACsAAAA+AAMAJQAAACwAAAD9AAEAOAABAA==`;

const TEXTURE_FRAGMENT_GLSL: text = `
#version 330 core
in vec2 vUV;
uniform sampler2D tex0;
out vec4 FragColor;
void main() {{
    vec4 c = texture(tex0, vUV);
    if (c.a < 0.01) discard;
    FragColor = c;
}}
`;

// SPIR-V of TEXTURE_FRAGMENT_GLSL (fragment), written by gpu_vulkan/spirv.py: do not edit.
const TEXTURE_FRAGMENT_SPV: text = `AwIjBwADAQALAAgAIgAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAA
AAAAAQAAAA8ABwAEAAAABAAAAG1haW4AAAAAEQAAACAAAAAQAAMABAAAAAcAAABHAAQADQAAACEA
AAABAAAARwAEAA0AAAAiAAAAAAAAAEcABAARAAAAHgAAAAAAAABHAAQAIAAAAB4AAAAAAAAAEwAC
AAIAAAAhAAMAAwAAAAIAAAAWAAMABgAAACAAAAAXAAQABwAAAAYAAAAEAAAAIAAEAAgAAAAHAAAA
BwAAABkACQAKAAAABgAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAABsAAwALAAAACgAAACAABAAM
AAAAAAAAAAsAAAA7AAQADAAAAA0AAAAAAAAAFwAEAA8AAAAGAAAAAgAAACAABAAQAAAAAQAAAA8A
AAA7AAQAEAAAABEAAAABAAAAFQAEABQAAAAgAAAAAAAAACsABAAUAAAAFQAAAAMAAAAgAAQAFgAA
AAcAAAAGAAAAKwAEAAYAAAAZAAAACtcjPBQAAgAaAAAAIAAEAB8AAAADAAAABwAAADsABAAfAAAA
IAAAAAMAAAA2AAUAAgAAAAQAAAAAAAAAAwAAAPgAAgAFAAAAOwAEAAgAAAAJAAAABwAAAD0ABAAL
AAAADgAAAA0AAAA9AAQADwAAABIAAAARAAAAVwAFAAcAAAATAAAADgAAABIAAAA+AAMACQAAABMA
AABBAAUAFgAAABcAAAAJAAAAFQAAAD0ABAAGAAAAGAAAABcAAAC4AAUAGgAAABsAAAAYAAAAGQAA
APcAAwAdAAAAAAAAAPoABAAbAAAAHAAAAB0AAAD4AAIAHAAAAPwAAQD4AAIAHQAAAD0ABAAHAAAA
IQAAAAkAAAA+AAMAIAAAACEAAAD9AAEAOAABAA==`;

// One cell of a sheet over the quad: the block's second field holds the cell's corners
// (u0, v0, u1, v1).
const CELL_VERTEX_GLSL: text = `
#version 330 core
layout (location = 0) in vec3 aPos;
layout (std140) uniform Block {{ mat4 uMVP; vec4 uCell; }};
out vec2 vUV;
void main() {{
    gl_Position = uMVP * vec4(aPos, 1.0);
    vUV = vec2(mix(uCell.x, uCell.z, aPos.x), mix(uCell.y, uCell.w, aPos.y));
}}
`;

// SPIR-V of CELL_VERTEX_GLSL (vertex), written by gpu_vulkan/spirv.py: do not edit.
const CELL_VERTEX_SPV: text = `AwIjBwADAQALAAgAOwAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAA
AAAAAQAAAA8ACAAAAAAABAAAAG1haW4AAAAADQAAABkAAAAlAAAARwADAAsAAAACAAAASAAFAAsA
AAAAAAAACwAAAAAAAABIAAUACwAAAAEAAAALAAAAAQAAAEgABQALAAAAAgAAAAsAAAADAAAASAAF
AAsAAAADAAAACwAAAAQAAABHAAMAEQAAAAIAAABIAAQAEQAAAAAAAAAFAAAASAAFABEAAAAAAAAA
BwAAABAAAABIAAUAEQAAAAAAAAAjAAAAAAAAAEgABQARAAAAAQAAACMAAABAAAAARwAEABMAAAAh
AAAAAAAAAEcABAATAAAAIgAAAAAAAABHAAQAGQAAAB4AAAAAAAAARwAEACUAAAAeAAAAAAAAABMA
AgACAAAAIQADAAMAAAACAAAAFgADAAYAAAAgAAAAFwAEAAcAAAAGAAAABAAAABUABAAIAAAAIAAA
AAAAAAArAAQACAAAAAkAAAABAAAAHAAEAAoAAAAGAAAACQAAAB4ABgALAAAABwAAAAYAAAAKAAAA
CgAAACAABAAMAAAAAwAAAAsAAAA7AAQADAAAAA0AAAADAAAAFQAEAA4AAAAgAAAAAQAAACsABAAO
AAAADwAAAAAAAAAYAAQAEAAAAAcAAAAEAAAAHgAEABEAAAAQAAAABwAAACAABAASAAAAAgAAABEA
AAA7AAQAEgAAABMAAAACAAAAIAAEABQAAAACAAAAEAAAABcABAAXAAAABgAAAAMAAAAgAAQAGAAA
AAEAAAAXAAAAOwAEABgAAAAZAAAAAQAAACsABAAGAAAAGwAAAAAAgD8gAAQAIQAAAAMAAAAHAAAA
FwAEACMAAAAGAAAAAgAAACAABAAkAAAAAwAAACMAAAA7AAQAJAAAACUAAAADAAAAKwAEAA4AAAAm
AAAAAQAAACsABAAIAAAAJwAAAAAAAAAgAAQAKAAAAAIAAAAGAAAAKwAEAAgAAAArAAAAAgAAACAA
BAAuAAAAAQAAAAYAAAArAAQACAAAADQAAAADAAAANgAFAAIAAAAEAAAAAAAAAAMAAAD4AAIABQAA
AEEABQAUAAAAFQAAABMAAAAPAAAAPQAEABAAAAAWAAAAFQAAAD0ABAAXAAAAGgAAABkAAABRAAUA
BgAAABwAAAAaAAAAAAAAAFEABQAGAAAAHQAAABoAAAABAAAAUQAFAAYAAAAeAAAAGgAAAAIAAABQ
AAcABwAAAB8AAAAcAAAAHQAAAB4AAAAbAAAAkQAFAAcAAAAgAAAAFgAAAB8AAABBAAUAIQAAACIA
AAANAAAADwAAAD4AAwAiAAAAIAAAAEEABgAoAAAAKQAAABMAAAAmAAAAJwAAAD0ABAAGAAAAKgAA
ACkAAABBAAYAKAAAACwAAAATAAAAJgAAACsAAAA9AAQABgAAAC0AAAAsAAAAQQAFAC4AAAAvAAAA
GQAAACcAAAA9AAQABgAAADAAAAAvAAAADAAIAAYAAAAxAAAAAQAAAC4AAAAqAAAALQAAADAAAABB
AAYAKAAAADIAAAATAAAAJgAAAAkAAAA9AAQABgAAADMAAAAyAAAAQQAGACgAAAA1AAAAEwAAACYA
AAA0AAAAPQAEAAYAAAA2AAAANQAAAEEABQAuAAAANwAAABkAAAAJAAAAPQAEAAYAAAA4AAAANwAA
AAwACAAGAAAAOQAAAAEAAAAuAAAAMwAAADYAAAA4AAAAUAAFACMAAAA6AAAAMQAAADkAAAA+AAMA
JQAAADoAAAD9AAEAOAABAA==`;

// The same three in the Metal Shading Language (`gpu_metal`): the block at buffer 0, the
// position handed to `gpu_position`.

const FLAT_VERTEX_MSL: text = `
struct Block {{ float4x4 uMVP; float4 uColor; }};
struct In {{ float3 aPos [[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(u.uMVP * float4(in.aPos, 1.0));
    return o;
}}
`;

const FLAT_FRAGMENT_MSL: text = `
struct Block {{ float4x4 uMVP; float4 uColor; }};
fragment float4 fragment_main(constant Block &u [[buffer(0)]]) {{ return u.uColor; }}
`;

const IMAGE_VERTEX_MSL: text = `
struct Block {{ float4x4 uMVP; }};
struct In {{ float3 aPos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; float2 vUV; }};
vertex Out vertex_main(In in [[stage_in]], constant Block &u [[buffer(0)]]) {{
    Out o;
    o.position = gpu_position(u.uMVP * float4(in.aPos, 1.0));
    o.vUV = in.aPos.xy;
    return o;
}}
`;

const TEXTURE_FRAGMENT_MSL: text = `
struct Out {{ float4 position [[position]]; float2 vUV; }};
fragment float4 fragment_main(Out in [[stage_in]], texture2d<float> tex0 [[texture(0)]], sampler s0 [[sampler(0)]]) {{
    float4 c = tex0.sample(s0, in.vUV);
    if (c.a < 0.01) discard_fragment();
    return c;
}}
`;

const CELL_VERTEX_MSL: text = `
struct Block {{ float4x4 uMVP; float4 uCell; }};
struct In {{ float3 aPos [[attribute(0)]]; }};
struct Out {{ float4 position [[position]]; float2 vUV; }};
vertex Out vertex_main(In in [[stage_in]], constant Block &u [[buffer(0)]]) {{
    Out o;
    o.position = gpu_position(u.uMVP * float4(in.aPos, 1.0));
    o.vUV = float2(mix(u.uCell.x, u.uCell.z, in.aPos.x), mix(u.uCell.y, u.uCell.w, in.aPos.y));
    return o;
}}
`;

// The recording backend reads no shader: an empty source lets a program's drawing be tested
// with no display.
fn recorded() -> gpu::Source {
  gpu::source("record", "", "")
}

fn flat_program() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::MAT4, gpu::F4],
    textures: 0,
    sources: [
      gpu::source("glsl-330", FLAT_VERTEX_GLSL, FLAT_FRAGMENT_GLSL),
      gpu::source("msl", FLAT_VERTEX_MSL, FLAT_FRAGMENT_MSL),
      gpu::source("spirv", FLAT_VERTEX_SPV, FLAT_FRAGMENT_SPV),
      recorded(),
    ],
  }
}

fn image_program() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::MAT4],
    textures: 1,
    sources: [
      gpu::source("glsl-330", IMAGE_VERTEX_GLSL, TEXTURE_FRAGMENT_GLSL),
      gpu::source("msl", IMAGE_VERTEX_MSL, TEXTURE_FRAGMENT_MSL),
      gpu::source("spirv", IMAGE_VERTEX_SPV, TEXTURE_FRAGMENT_SPV),
      recorded(),
    ],
  }
}

fn cell_program() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::MAT4, gpu::F4],
    textures: 1,
    sources: [
      gpu::source("glsl-330", CELL_VERTEX_GLSL, TEXTURE_FRAGMENT_GLSL),
      gpu::source("msl", CELL_VERTEX_MSL, TEXTURE_FRAGMENT_MSL),
      gpu::source("spirv", CELL_VERTEX_SPV, TEXTURE_FRAGMENT_SPV),
      recorded(),
    ],
  }
}

// The orthographic projection of a `width` x `height` target, origin top-left.
fn pixel_projection(width: integer, height: integer) -> vector<float> {
  [
    2.0 / width as float ?? 0.0, 0.0, 0.0, 0.0, 0.0, -2.0 / height as float ?? 0.0, 0.0, 0.0, 0.0,
    0.0, -1.0, 0.0, -1.0, 1.0, 0.0, 1.0,
  ]
}

// The unit quad (0, 0)-(1, 1) as two triangles.
fn unit_quad() -> vector<single> {
  [
    0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f,
    1.0f, 0.0f,
  ]
}

// `proj` times a move to (x, y) and a stretch to `w` x `h`: the model is sparse, so it is four
// column updates of the projection.
fn placed(proj: const vector<float>, x: float, y: float, w: float, h: float) -> vector<float> {
  [
    proj[0] * w, proj[1] * w, proj[2] * w, proj[3] * w, proj[4] * h, proj[5] * h, proj[6] * h,
    proj[7] * h, proj[8], proj[9], proj[10], proj[11], proj[0] * x + proj[4] * y + proj[12],
    proj[1] * x + proj[5] * y + proj[13], proj[2] * x + proj[6] * y + proj[14],
    proj[3] * x + proj[7] * y + proj[15],
  ]
}

// How a painter's draws combine with what the pass holds when it blends: by the colour's alpha.
fn by_alpha() -> integer {
  gpu::blend(gpu::SRC_ALPHA, gpu::ONE_MINUS_SRC_ALPHA)
}

// ── sprite sheets ──

// A picture on the GPU cut into a grid of `cols` x `rows` sprites; sprite 0 is the top left,
// counting along the rows.
pub struct Sprites {
  pub texture: gpu::Texture,
  pub const cols: integer,
  pub const rows: integer,
  // For `draw`: a sprite placed in a 3D scene, tested against depth and written to it.
  scene: gpu::Pipeline,
  values: gpu::Block,
  quad: gpu::Buffer,
}

// Upload `pixels` (0xAARRGGBB, `width` to a row, the top row first) as a sheet of `cols` x
// `rows` cells, sampled between its pixels (`sheet.texture.nearest(true)` for pixel art).
// `into` is what `draw` will draw into (`gpu::INTO_WINDOW`, …).  Null on a device whose backend
// this library has no shader source for.
pub fn sprites(
  dev: const gpu::Device,
  pixels: const vector<u32>,
  width: integer,
  height: integer,
  cols: integer,
  rows: integer,
  into: integer
) -> Sprites? {
  scene = dev.pipeline(cell_program(), gpu::State { depth: gpu::DEPTH_TEST_WRITE, into: into }) ?? return null;
  Sprites {
    texture: dev.texture_from(pixels, width, height),
    cols: cols,
    rows: rows,
    values: scene.block(),
    scene: scene,
    quad: dev.buffer(unit_quad()),
  }
}

// The corners (u0, v0, u1, v1) of sprite `index` into `values`' second field.
fn cell_into(self: const Sprites, values: gpu::Block, index: integer) {
  // the divisors are positive (the callers check), so no default is ever taken
  col = (index % self.cols) ?? 0;
  row = (index / self.cols) ?? 0;
  cols = self.cols as float;
  rows = self.rows as float;
  values.f4(1, (col as float / cols) ?? 0.0, (row as float / rows) ?? 0.0, ((col + 1) as float / cols) ?? 0.0, ((row + 1) as float / rows) ?? 0.0);
}

// Draw sprite `index` through `mvp`, which maps the unit quad onto the target (16 floats,
// column-major), in the pass in progress: tested against the depth drawn so far.
pub fn draw(self: Sprites, dev: gpu::Device, mvp: const vector<float>, index: integer) {
  if self.cols <= 0 || self.rows <= 0 { return; }
  self.values.mat4(0, mvp);
  self.cell_into(self.values, index);
  dev.bind(self.scene);
  dev.uniforms(self.values);
  dev.sample(0, self.texture);
  dev.vertices(self.quad);
  dev.draw(0, 6);
}

// ── the painter ──

// Pipelines and a unit quad for drawing at pixel positions.
pub struct Painter {
  // Whether a draw is combined with what the pass holds by its alpha (how a painter starts),
  // or replaces it.
  pub blend: boolean,
  flat: gpu::Pipeline,
  flat_over: gpu::Pipeline,
  whole: gpu::Pipeline,
  whole_over: gpu::Pipeline,
  cell: gpu::Pipeline,
  cell_over: gpu::Pipeline,
  flat_values: gpu::Block,
  image_values: gpu::Block,
  cell_values: gpu::Block,
  quad: gpu::Buffer,
  proj: vector<float>,
}

// A painter for passes that draw into `into` (`gpu::INTO_WINDOW`, `gpu::INTO_COLOUR`, …),
// sized to the device's window.  Null on a device whose backend this library has no shader
// source for.
pub fn painter(dev: const gpu::Device, into: integer) -> Painter? {
  flat = dev.pipeline(flat_program(), gpu::State { into: into }) ?? return null;
  flat_over = dev.pipeline(flat_program(), gpu::State { blend: by_alpha(), into: into }) ?? return null;
  whole = dev.pipeline(image_program(), gpu::State { into: into }) ?? return null;
  whole_over = dev.pipeline(image_program(), gpu::State { blend: by_alpha(), into: into }) ?? return null;
  cell = dev.pipeline(cell_program(), gpu::State { into: into }) ?? return null;
  cell_over = dev.pipeline(cell_program(), gpu::State { blend: by_alpha(), into: into }) ?? return null;
  Painter {
    blend: true,
    flat_values: flat.block(),
    image_values: whole.block(),
    cell_values: cell.block(),
    flat: flat,
    flat_over: flat_over,
    whole: whole,
    whole_over: whole_over,
    cell: cell,
    cell_over: cell_over,
    quad: dev.buffer(unit_quad()),
    proj: pixel_projection(dev.width(), dev.height()),
  }
}

// Draw for a target of `width` x `height` pixels from now on: after the window was resized, or
// for a pass into a texture of another size.
pub fn resize(self: Painter, width: integer, height: integer) {
  self.proj = pixel_projection(width, height);
}

// A filled rectangle at (x, y) of `w` x `h` pixels, channels 0.0-1.0.
pub fn rect(
  self: Painter,
  dev: gpu::Device,
  x: float,
  y: float,
  w: float,
  h: float,
  r: float,
  g: float,
  b: float,
  a: float
) {
  self.flat_values.mat4(0, placed(self.proj, x, y, w, h));
  self.flat_values.f4(1, r, g, b, a);
  dev.bind(if self.blend { self.flat_over } else { self.flat });
  dev.uniforms(self.flat_values);
  dev.vertices(self.quad);
  dev.draw(0, 6);
}

// A texture stretched over (x, y) of `w` x `h` pixels; fully transparent pixels are not drawn.
pub fn image(self: Painter, dev: gpu::Device, t: const gpu::Texture, x: float, y: float, w: float, h: float) {
  self.image_values.mat4(0, placed(self.proj, x, y, w, h));
  dev.bind(if self.blend { self.whole_over } else { self.whole });
  dev.uniforms(self.image_values);
  dev.sample(0, t);
  dev.vertices(self.quad);
  dev.draw(0, 6);
}

// Sprite `index` of `sheet` over (x, y) of `w` x `h` pixels.
pub fn sprite(
  self: Painter,
  dev: gpu::Device,
  sheet: const Sprites,
  x: float,
  y: float,
  w: float,
  h: float,
  index: integer
) {
  if sheet.cols <= 0 || sheet.rows <= 0 { return; }
  self.cell_values.mat4(0, placed(self.proj, x, y, w, h));
  sheet.cell_into(self.cell_values, index);
  dev.bind(if self.blend { self.cell_over } else { self.cell });
  dev.uniforms(self.cell_values);
  dev.sample(0, sheet.texture);
  dev.vertices(self.quad);
  dev.draw(0, 6);
}

tests/record.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// What a painter asks of a backend, read from the recording one: no display is needed.  The
// expected log is written by hand.  Handles count from 1: the device, the painter's six
// pipelines (flat, image and cell, each replacing and blending), its quad.  Blending by alpha
// is state 1 + 8 * 2 + 3 = 20.  On a 64 x 48 window a rectangle 16 wide has 2 / 64 * 16 = 0.5
// as its matrix's first float; an image over the whole window has 2, and its last float is 1.
use gpu;
use gpu_paint;
use gpu_record;

fn lines(of: const vector<text>) -> text {
  out = "";
  for l in of { out += "{l}\n"; }
  out
}

fn test_a_painter_asks_for_six_pipelines_and_four_calls_a_draw() {
  gpu_record::reset();
  dev = gpu::open(gpu_record::table(), 64, 48, "paint")!;
  p = gpu_paint::painter(dev, gpu::INTO_WINDOW)!;
  made = lines([
    "open 1 64x48 \"paint\"",
    "pipeline 2 vertex 3 instance block 16x1@0 4x1@16 size 20 textures 0",
    "  state shape 0 depth 0 blend 0 cull 0 into 0",
    "pipeline 3 vertex 3 instance block 16x1@0 4x1@16 size 20 textures 0",
    "  state shape 0 depth 0 blend 20 cull 0 into 0",
    "pipeline 4 vertex 3 instance block 16x1@0 size 16 textures 1",
    "  state shape 0 depth 0 blend 0 cull 0 into 0",
    "pipeline 5 vertex 3 instance block 16x1@0 size 16 textures 1",
    "  state shape 0 depth 0 blend 20 cull 0 into 0",
    "pipeline 6 vertex 3 instance block 16x1@0 4x1@16 size 20 textures 1",
    "  state shape 0 depth 0 blend 0 cull 0 into 0",
    "pipeline 7 vertex 3 instance block 16x1@0 4x1@16 size 20 textures 1",
    "  state shape 0 depth 0 blend 20 cull 0 into 0",
    "buffer 8 floats 18",
  ]);
  assert(gpu_record::log() == made, "what a painter is made of:\n{gpu_record::log()}");

  picture = dev.texture_from([0xFF112233 as u32, 0 as u32], 2, 1);
  dev.begin_window(gpu::KEEP, 0);
  p.rect(dev, 8.0, 4.0, 16.0, 10.0, 1.0, 0.0, 0.0, 0.25);
  p.blend = false;
  p.image(dev, picture, 0.0, 0.0, 64.0, 48.0);
  dev.end();
  drawn = lines([
    "texture 9 2x1 colour",
    "texture_put 9 at 0,0 2x1 first ff112233",
    "begin 0 keep",
    "  bind 3",
    "  uniforms floats 20 first 0.500 last 0.250",
    "  vertices 8",
    "  draw from 0 count 6 copies 0",
    "  bind 4",
    "  uniforms floats 16 first 2.000 last 1.000",
    "  sample 0 texture 9",
    "  vertices 8",
    "  draw from 0 count 6 copies 0",
    "end",
  ]);
  got = gpu_record::log()[len(made)..];
  assert(got == drawn, "a rectangle and an image:\n{got}");
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
}

fn test_a_sheet_names_its_cell_in_the_block() {
  gpu_record::reset();
  dev = gpu::open(gpu_record::table(), 64, 48, "sheet")!;
  // four cells in a row: cell 2 spans u 0.5 to 0.75, so the block's last float (v1) is 1
  sheet = gpu_paint::sprites(dev, [for _ in 0..8 { 0xFFFFFFFF as u32 }], 8, 1, 4, 1, gpu::INTO_WINDOW)!;
  before = gpu_record::log();
  dev.begin_window(gpu::KEEP, 0);
  sheet.draw(dev, [for i in 0..16 { if i % 5 == 0 { 3.0 } else { 0.0 } }], 2);
  dev.end();
  drawn = lines([
    "begin 0 keep",
    "  bind 2",
    "  uniforms floats 20 first 3.000 last 1.000",
    "  sample 0 texture 3",
    "  vertices 4",
    "  draw from 0 count 6 copies 0",
    "end",
  ]);
  got = gpu_record::log()[len(before)..];
  assert(got == drawn, "a sprite in a scene:\n{got}");
  assert(gpu_record::log().starts_with(lines(["open 1 64x48 \"sheet\"", "pipeline 2 vertex 3 instance block 16x1@0 4x1@16 size 20 textures 1", "  state shape 0 depth 2 blend 0 cull 0 into 0"])), "its pipeline tests and writes depth:\n{before}");
}

tests/same_as_graphics.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// A painter and a sprite sheet through `gpu` draw the same pixels as the graphics library's
// own `Painter` and `Sprites`, byte for byte.  Each test opens a window of each, draws one
// scene both ways and compares the two captures whole; it also asks that the scene shows more
// than one colour.  Each test runs on every backend here: `gpu_gl`, and `gpu_vulkan` on Linux.
// graphics and the backends are not dependencies of this package: one is the path it is
// measured against, the others draw here.  Without a display every test returns at once
// (`DISPLAY`, or `GRAPHICS_TEST_WINDOW=1` on a Mac).
use gpu;
use gpu_gl;
use gpu_vulkan;
use gpu_paint;
use graphics;

// The backends each test draws through: OpenGL, and Vulkan on a machine it has a window host
// for (Linux), where a Vulkan driver is then expected (Mesa's lavapipe serves).
fn backends() -> vector<i64> {
  out: vector<i64> = [gpu_gl::table()];
  if gpu_vulkan::table() != 0 { out += [gpu_vulkan::table()]; }
  out
}

fn display() -> boolean {
  must_draw((env_variable("DISPLAY") ?? "") != "" || (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 BLACK = 0xFF000000;
const RED = 0xFFFF0000;
const GREEN = 0xFF00FF00;
const BLUE = 0xFF0000FF;

// The largest gap between two pixels in any one channel.
fn channel_gap(a: u32, b: u32) -> integer {
  worst = 0;
  for shift in [0, 8, 16, 24] {
    x = ((a as integer) >> shift) & 255;
    y = ((b as integer) >> shift) & 255;
    gap = if x > y { x - y } else { y - x };
    if gap > worst { worst = gap; }
  }
  worst
}

// The same pixels, byte for byte, through OpenGL: graphics draws on OpenGL too.  Through another
// stack two differences are measured and allowed, the rest held byte for byte:
//   - a channel off by 1, where a stack rounds a blend or a filter's weights its own way (RADV
//     against llvmpipe's OpenGL: 504 pixels of the rectangles, 223 of the images);
//   - `edges` pixels more, where an edge passes within a quarter of a pixel of pixels' middles
//     and llvmpipe's OpenGL places it a quarter of a pixel off where Vulkan places it by the
//     spec's arithmetic (the sprites: their one top row, 11 pixels, on lavapipe and RADV).
fn same(old: const vector<u32>, new: const vector<u32>, what: text, edges: integer) {
  assert(len(old) == len(new) && len(old) > 0, "{what}: {len(old)} pixels through graphics, {len(new)} through {gpu::backend_name()}");
  other = gpu::backend_name() != "gpu_gl";
  differ = 0;
  first = -1;
  colours = 0;
  for p in old {
    q = new[p#index] ?? 0;
    // a window of `gpu` reads back opaque; graphics' alpha, where its window has one, is not compared
    if (p as integer) | 0xFF000000 != (q as integer) {
      gap = channel_gap((((p as integer) | 0xFF000000) & 4294967295) as u32, q);
      if !other || gap > 1 {
        differ += 1;
        if first < 0 { first = p#index; }
      }
    }
    if p != old[0] { colours += 1; }
  }
  allowed = if other { edges } else { 0 };
  assert(colours > 0, "{what}: the scene shows one colour only");
  assert(differ <= allowed, "{what}: {differ} pixels differ ({allowed} allowed), the first at {first}: {old[first] ?? 0:x} through graphics, {new[first] ?? 0:x} through {gpu::backend_name()}");
}

// The old painter blends where its window does: plain transparency, as the new one blends.
fn blending(w: graphics::Window, on: boolean) {
  if on {
    w.enable(graphics::GL_BLEND);
    w.blend(graphics::BLEND_SRC_ALPHA, graphics::BLEND_ONE_MINUS_SRC_ALPHA);
  } else {
    w.disable(graphics::GL_BLEND);
  }
}

// A 4 x 2 picture: two cells of 2 x 2, each pixel its own colour, one of them see-through.
fn sheet_pixels() -> vector<u32> {
  out: vector<u32> = [];
  for i in 0..8 {
    alpha = if i == 5 { 0 } else { 255 };
    out += [(graphics::rgba(30 + 25 * i, 240 - 22 * i, 60 + 9 * (i % 3), alpha) & 4294967295) as u32];
  }
  out
}

// The unit quad stretched to `sx` x `sy` around the middle of the target, at depth `z`.
fn placed(sx: float, sy: float, z: float) -> vector<float> {
  [sx, 0.0, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -sx / 2.0, -sy / 2.0, z, 1.0]
}

fn rectangles_opaque_blended_and_after_a_resize_on(table: i64) {
  wo = graphics::open_window(64, 48, "old-rect");
  if !display() { return; }
  // Everything the window made is let go before the device opens: a program has one backend
  // at a time, and a release goes to the one that is there.
  old_px: vector<u32> = [];
  {
    w = wo ?? return assert(false, "a display is set and no window opened");
    op = w.painter() ?? return assert(false, "the old painter");

    w.clear(BLACK);
    blending(w, false);
    op.rect(w, 8.0, 4.0, 16.0, 10.0, 1.0, 0.0, 0.0, 0.3);
    op.rect(w, 20.5, 9.25, 30.0, 20.5, 0.0, 0.0, 1.0, 1.0);
    blending(w, true);
    op.rect(w, 4.0, 8.0, 40.0, 30.0, 0.2, 1.0, 0.4, 0.35);
    op.resize(32, 24);
    op.rect(w, 24.0, 18.0, 8.0, 6.0, 1.0, 1.0, 0.0, 0.5);
    old = w.capture();
    old_px += old.data;
    w.close();
  }
  dev = gpu::open(table, 64, 48, "new-rect") ?? return assert(false, "no device");
  np = gpu_paint::painter(dev, gpu::INTO_WINDOW) ?? return assert(false, "the new painter");

  dev.begin_window(gpu::CLEAR, BLACK);
  np.blend = false;
  np.rect(dev, 8.0, 4.0, 16.0, 10.0, 1.0, 0.0, 0.0, 0.3);
  np.rect(dev, 20.5, 9.25, 30.0, 20.5, 0.0, 0.0, 1.0, 1.0);
  np.blend = true;
  np.rect(dev, 4.0, 8.0, 40.0, 30.0, 0.2, 1.0, 0.4, 0.35);
  np.resize(32, 24);
  np.rect(dev, 24.0, 18.0, 8.0, 6.0, 1.0, 1.0, 0.0, 0.5);
  dev.end();
  same(old_px, dev.capture(), "rectangles", 0);
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()} [{gpu::backend_name()}]");
}

fn test_rectangles_opaque_blended_and_after_a_resize() {
  for t in backends() { rectangles_opaque_blended_and_after_a_resize_on(t); }
}

fn an_image_keeps_its_rows_and_skips_the_transparent_on(table: i64) {
  wo = graphics::open_window(64, 48, "old-image");
  if !display() { return; }
  // Everything the window made is let go before the device opens: a program has one backend
  // at a time, and a release goes to the one that is there.
  old_px: vector<u32> = [];
  {
    w = wo ?? return assert(false, "a display is set and no window opened");
    op = w.painter() ?? return assert(false, "the old painter");
    px = sheet_pixels();

    ot = w.texture_from(graphics::Canvas { width: 4, height: 2, data: px });
    ot.filter(true);
    ol = w.texture_from(graphics::Canvas { width: 4, height: 2, data: px });
    w.clear(BLUE);
    blending(w, true);
    op.image(w, ot, 30.0, 2.0, 32.0, 40.0);
    op.image(w, ol, 2.0, 20.0, 24.0, 24.0);
    old = w.capture();
    old_px += old.data;
    w.close();
  }
  dev = gpu::open(table, 64, 48, "new-image") ?? return assert(false, "no device");
  np = gpu_paint::painter(dev, gpu::INTO_WINDOW) ?? return assert(false, "the new painter");

  nt = dev.texture_from(sheet_pixels(), 4, 2);
  nt.nearest(true);
  nl = dev.texture_from(sheet_pixels(), 4, 2);
  dev.begin_window(gpu::CLEAR, BLUE);
  np.image(dev, nt, 30.0, 2.0, 32.0, 40.0);
  np.image(dev, nl, 2.0, 20.0, 24.0, 24.0);
  dev.end();
  same(old_px, dev.capture(), "images", 0);
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()} [{gpu::backend_name()}]");
}

fn test_an_image_keeps_its_rows_and_skips_the_transparent() {
  for t in backends() { an_image_keeps_its_rows_and_skips_the_transparent_on(t); }
}

fn sprites_at_pixel_positions_and_in_a_scene_with_depth_on(table: i64) {
  wo = graphics::open_window(64, 48, "old-sprites");
  if !display() { return; }
  // Everything the window made is let go before the device opens: a program has one backend
  // at a time, and a release goes to the one that is there.
  old_px: vector<u32> = [];
  {
    w = wo ?? return assert(false, "a display is set and no window opened");
    op = w.painter() ?? return assert(false, "the old painter");
    px = sheet_pixels();

    // Two sprites in a scene: the near one drawn first, so the far one is hidden where they
    // overlap only if depth is tested and written.  Then two by the painter, over them, in
    // call order whatever the depth.
    os = w.sprites(graphics::Canvas { width: 4, height: 2, data: px }, 2, 1) ?? return assert(false, "the old sheet");
    os.texture.filter(true);
    // In a page the two libraries draw in the page's one context, and graphics takes the state
    // it finds: say what this scene relies on, which a painter before it turned off.
    w.enable(graphics::GL_DEPTH_TEST);
    w.depth_write(true);
    w.clear(BLACK);
    blending(w, false);
    os.draw(w, placed(1.2, 1.4, -0.5), 1);
    os.draw(w, placed(1.9, 0.8, 0.5), 0);
    op.sprite(w, os, 2.0, 30.0, 20.0, 16.0, 0);
    op.sprite(w, os, 12.0, 34.0, 20.0, 12.0, 1);
    assert(w.enabled(graphics::GL_DEPTH_TEST), "the old painter handed depth testing back on [{gpu::backend_name()}]");
    old = w.capture();
    old_px += old.data;
    w.close();
  }
  dev = gpu::open(table, 64, 48, "new-sprites") ?? return assert(false, "no device");
  np = gpu_paint::painter(dev, gpu::INTO_WINDOW) ?? return assert(false, "the new painter");

  ns = gpu_paint::sprites(dev, sheet_pixels(), 4, 2, 2, 1, gpu::INTO_WINDOW) ?? return assert(false, "the new sheet");
  ns.texture.nearest(true);
  np.blend = false;
  dev.begin_window(gpu::CLEAR, BLACK);
  ns.draw(dev, placed(1.2, 1.4, -0.5), 1);
  ns.draw(dev, placed(1.9, 0.8, 0.5), 0);
  np.sprite(dev, ns, 2.0, 30.0, 20.0, 16.0, 0);
  np.sprite(dev, ns, 12.0, 34.0, 20.0, 12.0, 1);
  dev.end();
  same(old_px, dev.capture(), "sprites", 11);
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()} [{gpu::backend_name()}]");
}

fn test_sprites_at_pixel_positions_and_in_a_scene_with_depth() {
  for t in backends() { sprites_at_pixel_positions_and_in_a_scene_with_depth_on(t); }
}

fn a_painter_draws_into_a_texture_that_another_shows_on(table: i64) {
  wo = graphics::open_window(64, 48, "old-into");
  if !display() { return; }
  // Everything the window made is let go before the device opens: a program has one backend
  // at a time, and a release goes to the one that is there.
  old_px: vector<u32> = [];
  {
    w = wo ?? return assert(false, "a display is set and no window opened");
    op = w.painter() ?? return assert(false, "the old painter");

    // A 32 x 24 picture painted first, then shown over part of the window.
    oc = w.texture(32, 24);
    oc.filter(true);
    of = w.framebuffer(oc);
    w.render_to(of);
    w.viewport(0, 0, 32, 24);
    w.clear(RED);
    blending(w, false);
    op.resize(32, 24);
    op.rect(w, 4.0, 3.0, 12.0, 8.0, 0.0, 1.0, 0.0, 1.0);
    w.render_to_window();
    w.viewport(0, 0, 64, 48);
    w.clear(BLACK);
    op.resize(64, 48);
    op.image(w, oc, 8.0, 6.0, 48.0, 36.0);
    old = w.capture();
    old_px += old.data;
    w.close();
  }
  dev = gpu::open(table, 64, 48, "new-into") ?? return assert(false, "no device");
  inner = gpu_paint::painter(dev, gpu::INTO_COLOUR) ?? return assert(false, "a painter into a texture");
  outer = gpu_paint::painter(dev, gpu::INTO_WINDOW) ?? return assert(false, "a painter into the window");

  nc = dev.texture(32, 24);
  nc.nearest(true);
  nf = dev.colour_target(nc);
  inner.blend = false;
  inner.resize(32, 24);
  dev.begin(nf, gpu::CLEAR, RED);
  inner.rect(dev, 4.0, 3.0, 12.0, 8.0, 0.0, 1.0, 0.0, 1.0);
  dev.end();
  outer.blend = false;
  dev.begin_window(gpu::CLEAR, BLACK);
  outer.image(dev, nc, 8.0, 6.0, 48.0, 36.0);
  dev.end();
  same(old_px, dev.capture(), "a painted texture shown", 0);
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()} [{gpu::backend_name()}]");
}

fn test_a_painter_draws_into_a_texture_that_another_shows() {
  for t in backends() { a_painter_draws_into_a_texture_that_another_shows_on(t); }
}

fn a_painter_for_the_window_is_refused_in_a_pass_into_a_texture_on(table: i64) {
  if !display() { return; }
  dev = gpu::open(table, 64, 48, "new-kind") ?? return assert(false, "no device");
  np = gpu_paint::painter(dev, gpu::INTO_WINDOW) ?? return assert(false, "the new painter");
  t = dev.texture(16, 16);
  f = dev.colour_target(t);
  dev.begin(f, gpu::CLEAR, GREEN);
  np.rect(dev, 0.0, 0.0, 8.0, 8.0, 1.0, 0.0, 0.0, 1.0);
  dev.end();
  got = dev.refusals();
  assert((got[0] ?? "") == "bind: the pipeline was built for another kind of target than this pass draws into", "the painter's pipeline is the window's: {got} [{gpu::backend_name()}]");
}

fn test_a_painter_for_the_window_is_refused_in_a_pass_into_a_texture() {
  for t in backends() { a_painter_for_the_window_is_refused_in_a_pass_into_a_texture_on(t); }
}

tests/same_on_metal.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// A painter and a sprite sheet draw the same pixels on `gpu_metal` as on `gpu_gl`, byte for
// byte.  Each scene is one function that opens a device of the backend it is given, draws and
// captures; one backend serves a program at a time, so a scene's device is closed before the
// next opens.  Neither backend is a dependency of this package.  Without a Mac's display every
// test returns at once (`GRAPHICS_TEST_WINDOW=1`).
use gpu;
use gpu_gl;
use gpu_metal;
use gpu_paint;

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 BLACK = 0xFF000000;
const RED = 0xFFFF0000;
const BLUE = 0xFF0000FF;

// 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
}

// What two pictures may lie apart in a channel: nothing on a Mac's own GPU.  Apple's software
// renderer, the OpenGL of a Mac with no GPU to give it (a CI runner), rounds a colour its own
// way, by 1 or 2 of 255.
fn rounding() -> integer {
  if gpu_gl::renderer() == "Apple Software Renderer" { 2 } else { 0 }
}

fn same(gl: const vector<u32>, metal: const vector<u32>, what: text) {
  assert(len(gl) == len(metal) && len(gl) > 0, "{what}: {len(gl)} pixels through OpenGL, {len(metal)} through Metal");
  allowed = rounding();
  differ = 0;
  first = -1;
  colours = 0;
  for p in gl {
    if apart(p as integer, (metal[p#index] ?? 0) as integer) > allowed {
      differ += 1;
      if first < 0 { first = p#index; }
    }
    if p != gl[0] { colours += 1; }
  }
  assert(colours > 0, "{what}: the scene shows one colour only");
  assert(differ == 0, "{what}: {differ} pixels differ by more than {allowed}, the first at {first}: {gl[first] ?? 0:x} through OpenGL, {metal[first] ?? 0:x} through Metal");
}

// A 4 x 2 picture: two cells of 2 x 2, each pixel its own colour, one of them see-through.
fn sheet_pixels() -> vector<u32> {
  out: vector<u32> = [];
  for i in 0..8 {
    alpha = if i == 5 { 0 } else { 255 };
    out += [(((alpha << 24) | ((30 + 25 * i) << 16) | ((240 - 22 * i) << 8) | (60 + 9 * (i % 3))) & 4294967295) as u32];
  }
  out
}

// The unit quad stretched to `sx` x `sy` around the middle of the target, at depth `z`.
fn placed(sx: float, sy: float, z: float) -> vector<float> {
  [sx, 0.0, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -sx / 2.0, -sy / 2.0, z, 1.0]
}

fn rectangles(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "paint-rect") ?? return [];
  np = gpu_paint::painter(dev, gpu::INTO_WINDOW) ?? return [];
  dev.begin_window(gpu::CLEAR, BLACK);
  np.blend = false;
  np.rect(dev, 8.0, 4.0, 16.0, 10.0, 1.0, 0.0, 0.0, 0.3);
  np.rect(dev, 20.5, 9.25, 30.0, 20.5, 0.0, 0.0, 1.0, 1.0);
  np.blend = true;
  np.rect(dev, 4.0, 8.0, 40.0, 30.0, 0.2, 1.0, 0.4, 0.35);
  np.resize(32, 24);
  np.rect(dev, 24.0, 18.0, 8.0, 6.0, 1.0, 1.0, 0.0, 0.5);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_rectangles_opaque_blended_and_after_a_resize() {
  if !display() { return; }
  same(rectangles(gpu_gl::table()), rectangles(gpu_metal::table()), "rectangles");
}

fn images(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "paint-image") ?? return [];
  np = gpu_paint::painter(dev, gpu::INTO_WINDOW) ?? return [];
  px = sheet_pixels();
  nt = dev.texture_from(px, 4, 2);
  nt.nearest(true);
  nl = dev.texture_from(px, 4, 2);
  dev.begin_window(gpu::CLEAR, BLUE);
  np.image(dev, nt, 30.0, 2.0, 32.0, 40.0);
  np.image(dev, nl, 2.0, 20.0, 24.0, 24.0);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_an_image_keeps_its_rows_and_skips_the_transparent() {
  if !display() { return; }
  same(images(gpu_gl::table()), images(gpu_metal::table()), "images");
}

// Two sprites in a scene, the near one drawn first, then two by the painter over them.
fn sprites(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "paint-sprites") ?? return [];
  np = gpu_paint::painter(dev, gpu::INTO_WINDOW) ?? return [];
  ns = gpu_paint::sprites(dev, sheet_pixels(), 4, 2, 2, 1, gpu::INTO_WINDOW) ?? return [];
  ns.texture.nearest(true);
  np.blend = false;
  dev.begin_window(gpu::CLEAR, BLACK);
  ns.draw(dev, placed(1.2, 1.4, -0.5), 1);
  ns.draw(dev, placed(1.9, 0.8, 0.5), 0);
  np.sprite(dev, ns, 2.0, 30.0, 20.0, 16.0, 0);
  np.sprite(dev, ns, 12.0, 34.0, 20.0, 12.0, 1);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_sprites_at_pixel_positions_and_in_a_scene_with_depth() {
  if !display() { return; }
  same(sprites(gpu_gl::table()), sprites(gpu_metal::table()), "sprites");
}

// A 32 x 24 picture painted first, then shown over part of the window.
fn painted_texture(table: i64) -> vector<u32> {
  dev = gpu::open(table, 64, 48, "paint-into") ?? return [];
  inner = gpu_paint::painter(dev, gpu::INTO_COLOUR) ?? return [];
  outer = gpu_paint::painter(dev, gpu::INTO_WINDOW) ?? return [];
  nc = dev.texture(32, 24);
  nc.nearest(true);
  nf = dev.colour_target(nc);
  inner.blend = false;
  inner.resize(32, 24);
  dev.begin(nf, gpu::CLEAR, RED);
  inner.rect(dev, 4.0, 3.0, 12.0, 8.0, 0.0, 1.0, 0.0, 1.0);
  dev.end();
  outer.blend = false;
  dev.begin_window(gpu::CLEAR, BLACK);
  outer.image(dev, nc, 8.0, 6.0, 48.0, 36.0);
  dev.end();
  c = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  c
}

fn test_a_painter_draws_into_a_texture_that_another_shows() {
  if !display() { return; }
  same(painted_texture(gpu_gl::table()), painted_texture(gpu_metal::table()), "a painted texture shown");
}