gpu_gl source

← gpu_gl · API reference · version 0.3.6

7 file(s), 879 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 fn22—91 98 112 118 29 41 … (19 total)
renderer fn33—none in this package
checked fn55—25 29 34 41 52
check fn61—none in this package
faults fn66—35 44 47
check_catches fn73—35 55

src/gpu_gl.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// The OpenGL backend of `gpu`.
//
//   dev = gpu::open(gpu_gl::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 "glsl-330" and is GLSL 3.30 (`#version 330 core`), which this
// backend also gives to OpenGL ES 3 and WebGL2:
//   - the inputs read per vertex are `layout(location = 0)` onwards, in the program's order,
//     and the inputs read per copy follow them;
//   - the uniform block is the source's one `layout(std140) uniform` block; a block laid out
//     otherwise than the program declares builds no pipeline, and stderr shows both layouts;
//   - the sampler of texture slot n is named `tex<n>`.

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

// This backend's table, for `gpu::open`; 0 on a machine it has no window host for.  `open`
// answers null where the machine has no OpenGL.
pub fn table() -> i64 {
  gq_table()
}

fn gq_renderer() -> text;
#c "gq_renderer" "const char*()"

// The OpenGL renderer of the window opened last through this backend, as its driver names it:
// "Apple M3 Max", "llvmpipe (LLVM 19.1.7, 256 bits)", "Apple Software Renderer".  Empty before
// a window opened, and in a browser page.  A test that measures another backend against this
// one reads it to know what it measures against.
pub fn renderer() -> text {
  gq_renderer()
}

fn gq_check(on: integer);
#c "gq_check" "void(int64_t)"
fn gq_faults() -> integer;
#c "gq_faults" "int64_t()"
fn gq_checked() -> integer;
#c "gq_checked" "int64_t()"
fn gq_check_self() -> integer;
#c "gq_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.
//
// A checked build looks at the error OpenGL kept after every call this backend makes of it,
// turns the driver's own messages on where it has them, and refuses the use of a handle that
// was released or whose device closed.  Each fault is counted and written to stderr with the
// call it came from.  OpenGL takes a wrong call in silence, so this is how a mistake in this
// backend, or in a shader, is seen.  `GPU_GL_DEBUG=abort` stops the program at the first fault,
// `GPU_GL_DEBUG=0` turns the checks off.
pub fn checked() -> boolean {
  gq_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) {
  gq_check(if on { 1 } else { 0 });
}

// How many faults a checked build has seen in this program.
pub fn faults() -> integer {
  gq_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 {
  gq_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_gl;

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 FLAT_V: text = `
#version 330 core
layout(location = 0) in vec3 pos;
layout(std140) uniform Block {{ vec4 color; vec4 at; }};
void main() {{ gl_Position = vec4(pos.xy * at.zw + at.xy, 0.0, 1.0); }}
`;

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

fn flat() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::F4, gpu::F4],
    textures: 0,
    sources: [gpu::source("glsl-330", 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_gl::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_gl::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_gl::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_gl::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 — an error OpenGL kept, and a handle used after its
// release.  A check that never fired would read the same as a library without a fault.
// Without a display every test returns at once (`DISPLAY`, or `GRAPHICS_TEST_WINDOW=1` on a
// Mac).
use gpu;
use gpu_gl;

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
}

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

fn test_an_unchecked_build_counts_nothing_and_a_checked_one_starts_at_none() {
  devo = gpu::open(gpu_gl::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");
  if !gpu_gl::checked() {
    assert(gpu_gl::faults() == 0 && gpu_gl::check_catches() == 0, "an unchecked build counts no fault: {gpu_gl::faults()}");
  }
}

// A texture wider than any OpenGL takes: the call is an error OpenGL keeps to itself.
fn test_a_checked_build_counts_an_error_opengl_kept() {
  devo = gpu::open(gpu_gl::table(), 64, 48, "checked-error");
  if !display() || !counting() { return; }
  dev = devo ?? return assert(false, "no device");
  before = gpu_gl::faults();
  wide = dev.texture(4000000, 4);
  assert(wide.width() == 4000000, "the texture's own record says what was asked");
  assert(gpu_gl::faults() > before, "the error of a texture no OpenGL can hold was counted: {gpu_gl::faults()} after {before}");
}

// 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_gl::table(), 64, 48, "checked-handle");
  if !display() || !counting() { return; }
  dev = devo ?? return assert(false, "no device");
  caught = gpu_gl::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}");
}

tests/host.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// What a host needs of a device beyond drawing: a target's pixels read back, a small machine's
// RGB565 frame taken as a texture, and the window's keys and pointer.  The colours are computed
// by hand.  Without a display every test returns at once (`DISPLAY`, or
// `GRAPHICS_TEST_WINDOW=1` on a Mac).
use gpu;
use gpu_gl;

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 SHOW_V: text = `
#version 330 core
layout(location = 0) in vec2 pos;
out vec2 v_uv;
void main() {{ v_uv = (pos + 1.0) / 2.0; gl_Position = vec4(pos, 0.0, 1.0); }}
`;

const SHOW_F: text = `
#version 330 core
uniform sampler2D tex0;
in vec2 v_uv;
out vec4 frag;
void main() {{ frag = texture(tex0, v_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("glsl-330", 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_a_small_machines_frame_is_shown_in_its_colours() {
  if !display() { return; }
  dev = gpu::open(gpu_gl::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_gl::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}");
}

// 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_gl::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_gl::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");
}

tests/in_order.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// What `gpu` promises of every backend and OpenGL does not give by itself, against values
// worked out by hand: a texture changed between two draws of a pass, a uniform block given again
// between draws, a depth written without a test, a point of the size its shader writes, and a window that has no alpha and reads back the frame it shows.
// Without a display every test returns at once (`DISPLAY`, or `GRAPHICS_TEST_WINDOW=1` on a
// Mac).
use gpu;
use gpu_gl;

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 TEX_V: text = `
#version 330 core
layout(location = 0) in vec3 pos;
layout(location = 1) in vec2 uv;
out vec2 v_uv;
void main() {{ v_uv = uv; gl_Position = vec4(pos, 1.0); }}
`;

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

fn textured() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3, gpu::F2],
    instance: [],
    block: [],
    textures: 1,
    sources: [gpu::source("glsl-330", TEX_V, TEX_F)],
  }
}

// The rectangle (x0, y0)-(x1, y1) with the whole texture over it.
fn frame(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, uv[2 * i] as single, uv[2 * i + 1] as single];
  }
  out
}

// A 4 x 4 picture, every pixel its own colour, half transparent: pixel i is red 40 + 12 i,
// green 250 - 13 i, blue 30 + 17 (i % 5).
fn picture() -> vector<u32> {
  out: vector<u32> = [];
  for i in 0..16 {
    r = 40 + 12 * i;
    g = 250 - 13 * i;
    b = 17 * (i % 5) + 30;
    out += [((0x80000000 | (r << 16) | (g << 8) | b) & 4294967295) as u32];
  }
  out
}

// Pixel 9 of the picture (column 1, row 2) covers x 8..15 and the rows 12..23 from the top of
// a 32 x 48 rectangle; opaque, as a window shows it.
const NINTH = 0xFF948562;
const PATCH = 0xFF00FF00;

fn test_a_texture_put_and_refiltered_between_two_draws_of_a_pass() {
  if !display() { return; }
  dev = gpu::open(gpu_gl::table(), 64, 48, "in order") ?? return assert(false, "no device");
  pipe = dev.pipeline(textured(), gpu::State {}) ?? return assert(false, "no pipeline");
  left = dev.buffer(frame(-1.0, -1.0, 0.0, 1.0));
  right = dev.buffer(frame(0.0, -1.0, 1.0, 1.0));
  t = dev.texture_from(picture(), 4, 4);
  t.nearest(true);
  dev.begin_window(gpu::CLEAR, 0x40203040);
  dev.bind(pipe);
  dev.sample(0, t);
  dev.vertices(left);
  dev.draw(0, 6);
  t.put(1, 2, [PATCH as u32, PATCH as u32], 2, 1);
  dev.vertices(right);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(c[18 * 64 + 12] as integer == NINTH, "drawn before the put: {c[18 * 64 + 12]:x}");
  assert(c[18 * 64 + 44] as integer == PATCH, "drawn after the put: {c[18 * 64 + 44]:x}");
  // sampled between its pixels from here on: a pixel off a texel's middle is a mix
  dev.begin_window(gpu::CLEAR, 0x40203040);
  dev.bind(pipe);
  dev.sample(0, t);
  dev.vertices(left);
  dev.draw(0, 6);
  t.nearest(false);
  dev.vertices(right);
  dev.draw(0, 6);
  dev.end();
  c = dev.capture();
  assert(c[18 * 64 + 9] as integer == PATCH, "drawn nearest: {c[18 * 64 + 9]:x}");
  assert(c[18 * 64 + 41] as integer != PATCH, "drawn between its pixels: {c[18 * 64 + 41]:x}");
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
}

fn test_a_window_has_no_alpha_and_reads_back_the_frame_it_shows() {
  if !display() { return; }
  dev = gpu::open(gpu_gl::table(), 64, 48, "window") ?? return assert(false, "no device");
  pipe = dev.pipeline(textured(), gpu::State {}) ?? return assert(false, "no pipeline");
  left = dev.buffer(frame(-1.0, -1.0, 0.0, 1.0));
  t = dev.texture_from(picture(), 4, 4);
  t.nearest(true);
  for round in 0..3 {
    dev.begin_window(gpu::CLEAR, 0x40203040l + 0x200000l * (round as i64));
    dev.bind(pipe);
    dev.sample(0, t);
    dev.vertices(left);
    dev.draw(0, 6);
    dev.end();
    before = dev.capture();
    for p in before {
      assert((p as integer >> 24) & 255 == 255, "round {round}: pixel {p#index} reads back {p:x}");
    }
    assert(before[18 * 64 + 12] as integer == NINTH, "round {round}: the picture, {before[18 * 64 + 12]:x}");
    assert(before[18 * 64 + 44] as integer == 0xFF203040 + 0x200000 * round, "round {round}: the cleared part, {before[18 * 64 + 44]:x}");
    dev.present();
    after = dev.capture();
    differ = 0;
    for p in before {
      if p != (after[p#index] ?? 0) { differ += 1; }
    }
    assert(differ == 0, "round {round}: {differ} pixels differ once the frame was presented");
  }
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
}

const FLAT_V: text = `
#version 330 core
layout(location = 0) in vec3 pos;
layout(std140) uniform Block {{ vec4 color; vec4 at; }};
void main() {{ gl_Position = vec4(pos.xy * at.zw + at.xy, 0.0, 1.0); }}
`;

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

// Each draw of a pass shows the block it was given, also when the block is given again after
// it: three draws of one rectangle, a quarter of the window each, each its own colour.  The
// same pipeline's one uniform buffer carries all three.
fn test_a_block_given_again_between_draws_leaves_the_earlier_draws_as_drawn() {
  devo = gpu::open(gpu_gl::table(), 64, 48, "blocks-in-order");
  if !display() { return; }
  dev = devo ?? return assert(false, "no device");
  prog = gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::F4, gpu::F4],
    textures: 0,
    sources: [gpu::source("glsl-330", FLAT_V, FLAT_F)],
  };
  pipe = dev.pipeline(prog, gpu::State { depth: gpu::DEPTH_OFF }) ?? return assert(false, "no pipeline");
  unit: 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];
  q = dev.buffer(unit);
  u = pipe.block();
  dev.begin_window(gpu::CLEAR, 0xFF000000);
  dev.bind(pipe);
  dev.vertices(q);
  // left-bottom quarter red, right-bottom green, right-top blue; the left-top stays cleared
  u.f4(0, 1.0, 0.0, 0.0, 1.0); u.f4(1, -0.5, -0.5, 0.5, 0.5);
  dev.uniforms(u); dev.draw(0, 6);
  u.f4(0, 0.0, 1.0, 0.0, 1.0); u.f4(1, 0.5, -0.5, 0.5, 0.5);
  dev.uniforms(u); dev.draw(0, 6);
  u.f4(0, 0.0, 0.0, 1.0, 1.0); u.f4(1, 0.5, 0.5, 0.5, 0.5);
  dev.uniforms(u); dev.draw(0, 6);
  dev.end();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  shot = dev.capture();
  // the top row first: (16, 36) is left-bottom, (48, 36) right-bottom, (48, 12) right-top
  assert(shot[36 * 64 + 16] == 0xFFFF0000, "the first draw kept its red: {shot[36 * 64 + 16]:x}");
  assert(shot[36 * 64 + 48] == 0xFF00FF00, "the second draw kept its green: {shot[36 * 64 + 48]:x}");
  assert(shot[12 * 64 + 48] == 0xFF0000FF, "the third draw is blue: {shot[12 * 64 + 48]:x}");
  assert(shot[12 * 64 + 16] == 0xFF000000, "the quarter nothing drew is the clear colour: {shot[12 * 64 + 16]:x}");
}

const DEEP_V: 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); }}
`;

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

// `DEPTH_WRITE` covers what is there and leaves its own depth behind, tested by nothing: a near
// red frame everywhere, then a green one at the far end inside a scissor over the left half,
// then a yellow one further than the red, tested.  The yellow shows on the left only.
fn test_a_depth_written_without_a_test_lets_a_further_draw_through() {
  devo = gpu::open(gpu_gl::table(), 64, 48, "depth-write");
  if !display() { return; }
  dev = devo ?? return assert(false, "no device");
  prog = gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::F4, gpu::F1],
    textures: 0,
    sources: [gpu::source("glsl-330", DEEP_V, DEEP_F)],
  };
  solid = dev.pipeline(prog, gpu::State { depth: gpu::DEPTH_TEST_WRITE }) ?? return assert(false, "no pipeline");
  wipe = dev.pipeline(prog, gpu::State { depth: gpu::DEPTH_WRITE }) ?? return assert(false, "no pipeline that writes a depth untested");
  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];
  q = dev.buffer(whole);
  u = solid.block();
  dev.begin_window(gpu::CLEAR, 0xFF0000FF);
  dev.bind(solid);
  u.f4(0, 1.0, 0.0, 0.0, 1.0); u.f1(1, -0.5);
  dev.uniforms(u); dev.vertices(q); 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(q); dev.draw(0, 6);
  mid = dev.capture();
  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(q); dev.draw(0, 6);
  dev.end();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  shot = dev.capture();
  assert(mid[24 * 64 + 16] == 0xFF00FF00, "the untested frame covered the nearer one on the left: {mid[24 * 64 + 16]:x}");
  assert(mid[24 * 64 + 48] == 0xFFFF0000, "and was cut by the scissor on the right: {mid[24 * 64 + 48]:x}");
  assert(shot[24 * 64 + 16] == 0xFFFFFF00, "left: the further frame passed the depth it left: {shot[24 * 64 + 16]:x}");
  assert(shot[24 * 64 + 48] == 0xFFFF0000, "right: the near frame kept its depth: {shot[24 * 64 + 48]:x}");
}

const DOT_V: text = `
#version 330 core
layout(location = 0) in vec3 pos;
layout(std140) uniform Block {{ vec4 color; float size; }};
void main() {{ gl_Position = vec4(pos.xy, 0.0, 1.0); gl_PointSize = size; }}
`;

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

// A point is as large as its vertex stage says, here as on every other backend: one of 5
// pixels at the centre of pixel (40, 24) covers the 5 x 5 around it, one of 1 its own pixel.
fn test_a_point_has_the_size_its_shader_writes() {
  devo = gpu::open(gpu_gl::table(), 64, 48, "point-size");
  if !display() { return; }
  dev = devo ?? return assert(false, "no device");
  prog = gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::F4, gpu::F1],
    textures: 0,
    sources: [gpu::source("glsl-330", DOT_V, DOT_F)],
  };
  pipe = dev.pipeline(prog, gpu::State { shape: gpu::POINTS }) ?? return assert(false, "no pipeline");
  // x = (40.5 / 32) - 1, y = 1 - (24.5 / 24)
  dot = dev.buffer([0.265625f, -0.0208333333f, 0.0f]);
  u = pipe.block();
  u.f4(0, 0.0, 1.0, 0.0, 1.0);
  u.f1(1, 5.0);
  dev.begin_window(gpu::CLEAR, 0xFF000000);
  dev.bind(pipe);
  dev.uniforms(u); dev.vertices(dot); dev.draw(0, 1);
  dev.end();
  big = dev.capture();
  u.f1(1, 1.0);
  dev.begin_window(gpu::CLEAR, 0xFF000000);
  dev.bind(pipe);
  dev.uniforms(u); dev.vertices(dot); dev.draw(0, 1);
  dev.end();
  small = dev.capture();
  assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
  assert(big[24 * 64 + 40] == 0xFF00FF00 && big[26 * 64 + 42] == 0xFF00FF00 && big[22 * 64 + 38] == 0xFF00FF00, "5 pixels: the corners of the 5 x 5 are drawn: {big[26 * 64 + 42]:x} {big[22 * 64 + 38]:x}");
  assert(big[24 * 64 + 43] == 0xFF000000 && big[24 * 64 + 37] == 0xFF000000, "and it stops there: {big[24 * 64 + 43]:x} {big[24 * 64 + 37]:x}");
  assert(small[24 * 64 + 40] == 0xFF00FF00 && small[24 * 64 + 41] == 0xFF000000 && small[25 * 64 + 40] == 0xFF000000, "1 pixel: its own alone: {small[24 * 64 + 41]:x}");
}

tests/many_devices.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// Many windows, one after another, each the only one while it lives.  Each device holds a
// connection to the display, and an X server serves 256 clients by default: 300 devices that
// were not let go would be refused long before the last.  And an X server starts over when
// its last client leaves (unless it was started with `-noreset`, and a desktop always has
// other clients): a connection that arrives while it does is dropped, so a program that
// closes its only window and opens another meets a server that hangs up on it.  The backend
// asks again, and every open here answers a device.  On an idle machine a drop is rare (one
// open in a thousand under Xvfb); `gpu_host/parity/under_load.sh` runs this file with the
// machine loaded, where one open in three is dropped.
// Without a display the test returns at once.
use gpu;
use gpu_gl;

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
}

// Every one of 300 devices opens, is its own size, and shows the colour it was cleared to: the
// i-th is 8 + i % 5 pixels wide and red i % 256.
fn test_every_device_in_a_long_row_opens() {
  if !display() { return; }
  // no device is kept beside the one in the loop: the server is left with no client between two
  for i in 0..300 {
    dev = gpu::open(gpu_gl::table(), 8 + i % 5, 8, "one of many") ?? return assert(false, "device {i} of 300 did not open");
    dev.begin_window(gpu::CLEAR, 0xFF000000 + ((i % 256) << 16));
    dev.end();
    shot = dev.capture();
    assert(dev.width() == 8 + i % 5 && len(shot) == (8 + i % 5) * 8, "device {i} is {dev.width()} wide, {len(shot)} pixels");
    assert(shot[0] == 0xFF000000 + ((i % 256) << 16), "device {i} shows its own red: {shot[0]:x}");
  }
}

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_gl;

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 FLAT_V: text = `
#version 330 core
layout(location = 0) in vec3 pos;
layout(std140) uniform Block {{ vec4 color; vec4 at; }};
void main() {{ gl_Position = vec4(pos.xy * at.zw + at.xy, 0.0, 1.0); }}
`;

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

fn flat() -> gpu::Program {
  gpu::Program {
    vertex: [gpu::F3],
    instance: [],
    block: [gpu::F4, gpu::F4],
    textures: 0,
    sources: [gpu::source("glsl-330", 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_gl::table(), 64, 48, "one");
  if !display() { return; }
  a = ao ?? return assert(false, "no device");
  b = gpu::open(gpu_gl::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}");
}