← scene3d · API reference · version 0.7.0
6 file(s), 2615 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.
| Item | Defined | Worked example | Call sites |
|---|---|---|---|
NONE const | 26 | — | 615 101 |
NO_LIGHT const | 28 | — | 243 35 40 135 |
WIDE const | 31 | — | 741 1410 |
DEEP const | 32 | — | 746 762 1411 1412 1416 |
TALL const | 33 | — | 746 762 1411 1412 1416 |
Scene struct | 444 | — | 517 532 584 591 605 625 … (38 total) |
new_scene fn | 517 | — | 82 55 92 142 176 203 … (19 total) |
resize fn | 584 | — | 376 384 280 313 319 |
placed fn | 591 | — | 606 1458 281 320 |
screen_point fn | 605 | — | 284 285 286 |
add_picture fn | 625 | — | 83 84 85 57 93 95 … (23 total) |
add_image fn | 634 | — | 627 328 332 337 |
set_tile fn | 714 | — | 86 61 96 144 182 245 … (18 total) |
drop_tile fn | 856 | — | 79 |
tiles fn | 866 | — | 80 |
set_light fn | 875 | — | 68 72 77 196 199 201 … (10 total) |
offers_torches fn | 926 | — | 217 |
set_torch_reach fn | 986 | — | 223 226 237 238 251 80 … (11 total) |
drop_torch fn | 1029 | — | 260 191 |
set_torches fn | 1045 | — | 241 82 107 129 134 150 … (11 total) |
torches fn | 1062 | — | 217 227 247 263 |
set_actors fn | 1076 | — | 99 114 118 124 209 249 … (20 total) |
hidden_groups fn | 1285 | — | 257 264 124 127 130 155 … (16 total) |
set_overlay fn | 1292 | — | 101 129 |
offers_free_camera fn | 1316 | — | 67 |
free_camera fn | 1323 | — | 89 147 158 210 218 247 … (14 total) |
fixed_camera fn | 1394 | — | 62 102 163 183 224 290 … (13 total) |
draw fn | 1455 | — | 1437 1442 1448 1480 35 90 … (54 total) |
draw_into fn | 1486 | — | none in this package |
src/scene3d.loft
// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// A 3D scene, drawn through `gpu`.
//
// scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, 0xFF94BFE6) ?? return;
// gable = scene.add_image(argb, width); // any size, 0xAARRGGBB (a PNG's)
// stone = scene.add_picture(texels); // 16 x 16 RGB565, NONE where clear
// scene.set_tile(key, faces); // a square of cells, whole
// scene.set_light([layer, x0, y0, w, h, …lights]); // the cells' light, as data
// …each frame…
// scene.set_actors(actors, hero);
// scene.fixed_camera(px, py);
// scene.draw(dev); // a pass into the window
//
// What a view gives is what tile-world-game's scene contract names, in the arrays its CPU
// implementation (`raster3d`) takes, so one view feeds either: pictures by number, tiles of
// faces under a key, the cells' light, the actors of a frame, the camera. Units: x east, y up
// in layers, z south; a cell is 1 across, a layer 1 high.
//
// Changes come by key: a tile given again or dropped, a box of light, the actors. A frame is
// the scene as it is, never what an earlier frame drew.
use gpu;
/// A texel that is not there (RGB565).
pub const NONE = 63519;
/// A face's light that comes from no cell (`set_tile`): its corners' own.
pub const NO_LIGHT = -1000000;
/// The fixed camera's scale: pixels a cell is across, a cell's ground is deep, a layer is tall.
pub const WIDE = 48;
pub const DEEP = 40;
pub const TALL = 48;
// A slot's texels each way, the atlas's slots each way, and its texels each way: a picture
// takes the slots it covers.
const TS = 16;
const SLOTS = 64;
const ATLAS = 1024;
// The light map: cells each way on a layer, and the layers it holds, one above the other.
const LIGHT_CELLS = 256;
const LIGHT_LAYERS = 8;
// How many torches a scene draws, the cells a torch's reach is across at most, and the reach
// atlas: a square of REACH + 1 texels a torch, ATLAS_ROW squares a row.
const TORCHES = 64;
const REACH = 15;
const ATLAS_ROW = 8;
// Floats a vertex: its place (3), where it lies on its picture (2), its picture's corner in the
// atlas and its size, in texels (4), the cell its light comes from and the factor (4), its own
// light (1).
const VERTEX = 14;
const LAND_VERTEX_GLSL: text = `
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aUV;
layout (location = 2) in vec4 aSlot;
layout (location = 3) in vec4 aLit;
layout (location = 4) in float aOwn;
layout (std140) uniform Block {{ mat4 uView; vec4 uPlace[64]; vec4 uColour[64]; }};
uniform sampler2D tex1;
uniform sampler2D tex2;
out vec2 vUV;
flat out vec4 vSlot;
out float vLight;
out vec2 vGrid;
flat out vec4 vTorch;
void main() {{
gl_Position = uView * vec4(aPos, 1.0);
vUV = aUV;
vSlot = aSlot;
vGrid = aPos.xz;
vTorch = vec4(0.0);
float l = aOwn;
if (aLit.z > -999999.0) {{
vec2 at = vec2(mod(aLit.x, 256.0) + 0.5, mod(aLit.y, 256.0) + 0.5 + 256.0 * mod(aLit.z, 8.0));
// a factor under 0 marks a card: its own light, and the torches of the cell it stands on
if (aLit.w >= 0.0) {{
vec4 c = textureLod(tex1, at / vec2(256.0, 2048.0), 0.0);
if (c.a > 0.5) l = (c.r * 255.0 * 256.0 + c.g * 255.0) / 65535.0 * aLit.w;
}}
vTorch = textureLod(tex2, at / vec2(256.0, 2048.0), 0.0) * 255.0;
}}
vLight = clamp(l, 0.0, 1.0);
}}
`;
// SPIR-V of LAND_VERTEX_GLSL (vertex), written by gpu_vulkan/spirv.py: do not edit.
const LAND_VERTEX_SPV: text = `AwIjBwADAQALAAgAhwAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAA
AAAAAQAAAA8AEAAAAAAABAAAAG1haW4AAAAADQAAABwAAAAoAAAAKgAAACwAAAAuAAAAMAAAADMA
AAA5AAAAOwAAAIQAAABHAAMACwAAAAIAAABIAAUACwAAAAAAAAALAAAAAAAAAEgABQALAAAAAQAA
AAsAAAABAAAASAAFAAsAAAACAAAACwAAAAMAAABIAAUACwAAAAMAAAALAAAABAAAAEcABAASAAAA
BgAAABAAAABHAAQAEwAAAAYAAAAQAAAARwADABQAAAACAAAASAAEABQAAAAAAAAABQAAAEgABQAU
AAAAAAAAAAcAAAAQAAAASAAFABQAAAAAAAAAIwAAAAAAAABIAAUAFAAAAAEAAAAjAAAAQAAAAEgA
BQAUAAAAAgAAACMAAABABAAAR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FADYAAAB0AAAAXwAAAAkAAAA9AAQABgAAAHUAAAB0AAAAhQAFAAYAAAB2AAAAdQAAAHEA
AACBAAUABgAAAHcAAABzAAAAdgAAAIgABQAGAAAAeQAAAHcAAAB4AAAAQQAFADgAAAB6AAAAOwAA
AFgAAAA9AAQABgAAAHsAAAB6AAAAhQAFAAYAAAB8AAAAeQAAAHsAAAA+AAMANwAAAHwAAAD5AAIA
bgAAAPgAAgBuAAAA+QACAF0AAAD4AAIAXQAAAD0ABABhAAAAfgAAAH0AAAA9AAQAJgAAAH8AAABF
AAAAiAAFACYAAACAAAAAfwAAAGcAAABYAAcABwAAAIEAAAB+AAAAgAAAAAIAAAA0AAAAjgAFAAcA
AACCAAAAgQAAAHEAAAA+AAMAMwAAAIIAAAD5AAIAQwAAAPgAAgBDAAAAPQAEAAYAAACFAAAANwAA
AAwACAAGAAAAhgAAAAEAAAArAAAAhQAAADQAAAAeAAAAPgADAIQAAACGAAAA/QABADgAAQA=`;
const LAND_FRAGMENT_GLSL: text = `
#version 330 core
layout (std140) uniform Block {{ mat4 uView; vec4 uPlace[64]; vec4 uColour[64]; }};
in vec2 vUV;
flat in vec4 vSlot;
in float vLight;
in vec2 vGrid;
flat in vec4 vTorch;
uniform sampler2D tex0;
uniform sampler2D tex3;
out vec4 FragColor;
// The light a torch (its square in the atlas plus one; 0: none) gives this point: its reach
// read between the cells' middles, times its glow and colour. The point is kept inside the
// torch's own square, whose last row and column are dark.
vec3 torch(float id) {{
if (id < 0.5) return vec3(0.0);
int s = int(id + 0.5) - 1;
vec4 p = uPlace[s];
vec2 t = clamp(vGrid - p.xy, 0.5, 15.5);
vec2 o = vec2(float(s - 8 * (s / 8)), float(s / 8)) * 16.0;
vec4 c = texture(tex3, (o + t) / 128.0);
return (c.r * 255.0 * 256.0 + c.g * 255.0) / 65535.0 * p.z * uColour[s].rgb;
}}
void main() {{
// a pixel whose middle lies on a texel's edge takes the texel before it, as the CPU does:
// left to the GPU it is the one after it on some (a Mac's), a pixel off every second row
vec2 t = clamp(floor(vUV * vSlot.zw - 0.002), vec2(0.0), vSlot.zw - 1.0);
vec4 c = texture(tex0, (vSlot.xy + t + 0.5) / 1024.0);
if (c.a < 0.5) discard;
vec3 light = max(max(vec3(vLight), max(torch(vTorch.x), torch(vTorch.y))), max(torch(vTorch.z), torch(vTorch.w)));
FragColor = vec4(c.rgb * min(light, vec3(1.0)), 1.0);
}}
`;
// SPIR-V of LAND_FRAGMENT_GLSL (fragment), written by gpu_vulkan/spirv.py: do not edit.
const LAND_FRAGMENT_SPV: text = `AwIjBwADAQALAAgAvQAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAA
AAAAAQAAAA8ACwAEAAAABAAAAG1haW4AAAAAMQAAAHAAAABzAAAAmQAAAJwAAACyAAAAEAADAAQA
AAAHAAAARwAEACQAAAAGAAAAEAAAAEcABAAlAAAABgAAABAAAABHAAMAJgAAAAIAAABIAAQAJgAA
AAAAAAAFAAAASAAFACYAAAAAAAAABwAAABAAAABIAAUAJgAAAAAAAAAjAAAAAAAAAEgABQAmAAAA
AQAAACMAAABAAAAASAAFACYAAAACAAAAIwAAAEAEAABHAAQAKAAAACEAAAAAAAAARwAEACgAAAAi
AAAAAAAAAEcABAAxAAAAHgAAAAMAAABHAAQATAAAACEAAAAEAAAARwAEAEwAAAAiAAAAAAAAAEcA
BABwAAAAHgAAAAAAAABHAAMAcwAAAA4AAABHAAQAcwAAAB4AAAABAAAARwAEAIMAAAAhAAAAAQAA
AEcABACDAAAAIgAAAAAAAABHAAQAmQAAAB4AAAACAAAARwADAJwAAAAOAAAARwAEAJwAAAAeAAAA
BAAAAEcABACyAAAAHgAAAAAAAAATAAIAAgAAACEAAwADAAAAAgAAABYAAwAGAAAAIAAAACAABAAH
AAAABwAAAAYAAAAXAAQACAAAAAYAAAADAAAAIQAEAAkAAAAIAAAABwAAACsABAAGAAAADgAAAAAA
AD8UAAIADwAAACsABAAGAAAAEwAAAAAAA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AAGAAAABhAAAAQQAFAAcAAABkAAAA
IAAAAGMAAAA9AAQABgAAAGUAAABkAAAAhQAFAAYAAABmAAAAYgAAAGUAAAA9AAQAFgAAAGgAAAAY
AAAAQQAGACoAAABpAAAAKAAAAGcAAABoAAAAPQAEAB4AAABqAAAAaQAAAE8ACAAIAAAAawAAAGoA
AABqAAAAAAAAAAEAAAACAAAAjgAFAAgAAABsAAAAawAAAGYAAAD+AAIAbAAAADgAAQA=`;
// The same program in the Metal Shading Language (`gpu_metal`). `wrap` is GLSL's `mod`, which
// answers a number from 0 up for a negative one too. A value marked `flat` is the same on a
// face's three corners, so it does not matter which corner a backend takes it from.
const LAND_VERTEX_MSL: text = `
struct Block {{ float4x4 uView; float4 uPlace[64]; float4 uColour[64]; }};
struct In {{
float3 aPos [[attribute(0)]];
float2 aUV [[attribute(1)]];
float4 aSlot [[attribute(2)]];
float4 aLit [[attribute(3)]];
float aOwn [[attribute(4)]];
}};
struct Out {{
float4 position [[position]];
float2 vUV;
float4 vSlot [[flat]];
float vLight;
float2 vGrid;
float4 vTorch [[flat]];
}};
static float wrap(float x, float y) {{ return x - y * floor(x / y); }}
vertex Out vertex_main(In in [[stage_in]], constant Block &u [[buffer(0)]],
texture2d<float> tex1 [[texture(1)]], sampler s1 [[sampler(1)]],
texture2d<float> tex2 [[texture(2)]], sampler s2 [[sampler(2)]]) {{
Out o;
o.position = gpu_position(u.uView * float4(in.aPos, 1.0));
o.vUV = in.aUV;
o.vSlot = in.aSlot;
o.vGrid = in.aPos.xz;
o.vTorch = float4(0.0);
float l = in.aOwn;
if (in.aLit.z > -999999.0) {{
float2 at = float2(wrap(in.aLit.x, 256.0) + 0.5, wrap(in.aLit.y, 256.0) + 0.5 + 256.0 * wrap(in.aLit.z, 8.0));
// a factor under 0 marks a card: its own light, and the torches of the cell it stands on
if (in.aLit.w >= 0.0) {{
float4 c = tex1.sample(s1, at / float2(256.0, 2048.0), level(0.0));
if (c.a > 0.5) l = (c.r * 255.0 * 256.0 + c.g * 255.0) / 65535.0 * in.aLit.w;
}}
o.vTorch = tex2.sample(s2, at / float2(256.0, 2048.0), level(0.0)) * 255.0;
}}
o.vLight = clamp(l, 0.0, 1.0);
return o;
}}
`;
const LAND_FRAGMENT_MSL: text = `
struct Block {{ float4x4 uView; float4 uPlace[64]; float4 uColour[64]; }};
struct Out {{
float4 position [[position]];
float2 vUV;
float4 vSlot [[flat]];
float vLight;
float2 vGrid;
float4 vTorch [[flat]];
}};
// The light a torch gives this point, as the GLSL source has it.
static float3 torch(float id, float2 grid, constant Block &u, texture2d<float> tex3, sampler s3) {{
if (id < 0.5) return float3(0.0);
int s = int(id + 0.5) - 1;
float4 p = u.uPlace[s];
float2 t = clamp(grid - p.xy, 0.5, 15.5);
float2 o = float2(float(s - 8 * (s / 8)), float(s / 8)) * 16.0;
float4 c = tex3.sample(s3, (o + t) / 128.0);
return (c.r * 255.0 * 256.0 + c.g * 255.0) / 65535.0 * p.z * u.uColour[s].rgb;
}}
fragment float4 fragment_main(Out in [[stage_in]], constant Block &u [[buffer(0)]],
texture2d<float> tex0 [[texture(0)]], sampler s0 [[sampler(0)]],
texture2d<float> tex3 [[texture(3)]], sampler s3 [[sampler(3)]]) {{
// a pixel whose middle lies on a texel's edge takes the texel before it, as the CPU does
float2 t = clamp(floor(in.vUV * in.vSlot.zw - 0.002), float2(0.0), in.vSlot.zw - 1.0);
float4 c = tex0.sample(s0, (in.vSlot.xy + t + 0.5) / 1024.0);
if (c.a < 0.5) discard_fragment();
float3 light = max(max(float3(in.vLight), max(torch(in.vTorch.x, in.vGrid, u, tex3, s3), torch(in.vTorch.y, in.vGrid, u, tex3, s3))),
max(torch(in.vTorch.z, in.vGrid, u, tex3, s3), torch(in.vTorch.w, in.vGrid, u, tex3, s3)));
return float4(c.rgb * min(light, float3(1.0)), 1.0);
}}
`;
fn land_program() -> gpu::Program {
gpu::Program {
vertex: [gpu::F3, gpu::F2, gpu::F4, gpu::F4, gpu::F1],
instance: [],
block: [gpu::MAT4, gpu::f4s(TORCHES), gpu::f4s(TORCHES)],
textures: 4,
sources: [
gpu::source("glsl-330", LAND_VERTEX_GLSL, LAND_FRAGMENT_GLSL),
gpu::source("msl", LAND_VERTEX_MSL, LAND_FRAGMENT_MSL),
gpu::source("spirv", LAND_VERTEX_SPV, LAND_FRAGMENT_SPV),
gpu::source("record", "", ""),
],
}
}
// The overlay: a picture over part of the target, its clear pixels not drawn.
const OVER_VERTEX_GLSL: text = `
#version 330 core
layout (location = 0) in vec2 aPos;
layout (location = 1) in vec2 aUV;
out vec2 vUV;
void main() {{ gl_Position = vec4(aPos, 0.0, 1.0); vUV = aUV; }}
`;
// SPIR-V of OVER_VERTEX_GLSL (vertex), written by gpu_vulkan/spirv.py: do not edit.
const OVER_VERTEX_SPV: text = `AwIjBwADAQALAAgAHwAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAA
AAAAAQAAAA8ACQAAAAAABAAAAG1haW4AAAAADQAAABIAAAAcAAAAHQAAAEcAAwALAAAAAgAAAEgA
BQALAAAAAAAAAAsAAAAAAAAASAAFAAsAAAABAAAACwAAAAEAAABIAAUACwAAAAIAAAALAAAAAwAA
AEgABQALAAAAAwAAAAsAAAAEAAAARwAEABIAAAAeAAAAAAAAAEcABAAcAAAAHgAAAAAAAABHAAQA
HQAAAB4AAAABAAAAEwACAAIAAAAhAAMAAwAAAAIAAAAWAAMABgAAACAAAAAXAAQABwAAAAYAAAAE
AAAAFQAEAAgAAAAgAAAAAAAAACsABAAIAAAACQAAAAEAAAAcAAQACgAAAAYAAAAJAAAAHgAGAAsA
AAAHAAAABgAAAAoAAAAKAAAAIAAEAAwAAAADAAAACwAAADsABAAMAAAADQAAAAMAAAAVAAQADgAA
ACAAAAABAAAAKwAEAA4AAAAPAAAAAAAAABcABAAQAAAABgAAAAIAAAAgAAQAEQAAAAEAAAAQAAAA
OwAEABEAAAASAAAAAQAAACsABAAGAAAAFAAAAAAAAAArAAQABgAAABUAAAAAAIA/IAAEABkAAAAD
AAAABwAAACAABAAbAAAAAwAAABAAAAA7AAQAGwAAABwAAAADAAAAOwAEABEAAAAdAAAAAQAAADYA
BQACAAAABAAAAAAAAAADAAAA+AACAAUAAAA9AAQAEAAAABMAAAASAAAAUQAFAAYAAAAWAAAAEwAA
AAAAAABRAAUABgAAABcAAAATAAAAAQAAAFAABwAHAAAAGAAAABYAAAAXAAAAFAAAABUAAABBAAUA
GQAAABoAAAANAAAADwAAAD4AAwAaAAAAGAAAAD0ABAAQAAAAHgAAAB0AAAA+AAMAHAAAAB4AAAD9
AAEAOAABAA==`;
const OVER_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.5) discard;
FragColor = vec4(c.rgb, 1.0);
}}
`;
// SPIR-V of OVER_FRAGMENT_GLSL (fragment), written by gpu_vulkan/spirv.py: do not edit.
const OVER_FRAGMENT_SPV: text = `AwIjBwADAQALAAgAKQAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAA
AAAAAQAAAA8ABwAEAAAABAAAAG1haW4AAAAAEQAAACAAAAAQAAMABAAAAAcAAABHAAQADQAAACEA
AAABAAAARwAEAA0AAAAiAAAAAAAAAEcABAARAAAAHgAAAAAAAABHAAQAIAAAAB4AAAAAAAAAEwAC
AAIAAAAhAAMAAwAAAAIAAAAWAAMABgAAACAAAAAXAAQABwAAAAYAAAAEAAAAIAAEAAgAAAAHAAAA
BwAAABkACQAKAAAABgAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAABsAAwALAAAACgAAACAABAAM
AAAAAAAAAAsAAAA7AAQADAAAAA0AAAAAAAAAFwAEAA8AAAAGAAAAAgAAACAABAAQAAAAAQAAAA8A
AAA7AAQAEAAAABEAAAABAAAAFQAEABQAAAAgAAAAAAAAACsABAAUAAAAFQAAAAMAAAAgAAQAFgAA
AAcAAAAGAAAAKwAEAAYAAAAZAAAAAAAAPxQAAgAaAAAAIAAEAB8AAAADAAAABwAAADsABAAfAAAA
IAAAAAMAAAAXAAQAIQAAAAYAAAADAAAAKwAEAAYAAAAkAAAAAACAPzYABQACAAAABAAAAAAAAAAD
AAAA+AACAAUAAAA7AAQACAAAAAkAAAAHAAAAPQAEAAsAAAAOAAAADQAAAD0ABAAPAAAAEgAAABEA
AABXAAUABwAAABMAAAAOAAAAEgAAAD4AAwAJAAAAEwAAAEEABQAWAAAAFwAAAAkAAAAVAAAAPQAE
AAYAAAAYAAAAFwAAALgABQAaAAAAGwAAABgAAAAZAAAA9wADAB0AAAAAAAAA+gAEABsAAAAcAAAA
HQAAAPgAAgAcAAAA/AABAPgAAgAdAAAAPQAEAAcAAAAiAAAACQAAAE8ACAAhAAAAIwAAACIAAAAi
AAAAAAAAAAEAAAACAAAAUQAFAAYAAAAlAAAAIwAAAAAAAABRAAUABgAAACYAAAAjAAAAAQAAAFEA
BQAGAAAAJwAAACMAAAACAAAAUAAHAAcAAAAoAAAAJQAAACYAAAAnAAAAJAAAAD4AAwAgAAAAKAAA
AP0AAQA4AAEA`;
const OVER_VERTEX_MSL: text = `
struct In {{ float2 aPos [[attribute(0)]]; float2 aUV [[attribute(1)]]; }};
struct Out {{ float4 position [[position]]; float2 vUV; }};
vertex Out vertex_main(In in [[stage_in]]) {{
Out o;
o.position = gpu_position(float4(in.aPos, 0.0, 1.0));
o.vUV = in.aUV;
return o;
}}
`;
const OVER_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.5) discard_fragment();
return float4(c.rgb, 1.0);
}}
`;
fn over_program() -> gpu::Program {
gpu::Program {
vertex: [gpu::F2, gpu::F2],
instance: [],
block: [],
textures: 1,
sources: [
gpu::source("glsl-330", OVER_VERTEX_GLSL, OVER_FRAGMENT_GLSL),
gpu::source("msl", OVER_VERTEX_MSL, OVER_FRAGMENT_MSL),
gpu::source("spirv", OVER_VERTEX_SPV, OVER_FRAGMENT_SPV),
gpu::source("record", "", ""),
],
}
}
// Where tile `key` is kept.
struct Slot {
const key: integer,
at: integer,
}
/// A scene on a device: its pictures, its tiles, the cells' light, this frame's actors and the
/// camera.
pub struct Scene {
into: integer,
sky: i64,
land: gpu::Pipeline,
values: gpu::Block,
atlas: gpu::Texture,
lights: gpu::Texture,
// The four torches strongest at each cell, laid out as `lights`: the torches' squares plus
// one in red, green, blue and alpha, 0 for none.
torch_map: gpu::Texture,
// The torches' reaches, a square each.
reach_atlas: gpu::Texture,
// For each square: the torch's id (-1: free), its reach as it was given (the layer, the
// box's corner, its width and height, then the reach of each cell), its glow and colour
// this frame.
torch_ids: vector<integer>,
reaches: vector<vector<single>>,
glows: vector<float>,
colours: vector<float>,
pictures: integer,
// Each picture's corner in the atlas and its size, in texels: four numbers a picture.
places: vector<integer>,
// The atlas's slots a picture covers, row by row, and the first that may be free.
taken: vector<boolean>,
first_free: integer,
slots: hash<Slot[key]>,
// A tile's faces as they were given, its vertices on the GPU and how many it has; a dropped
// tile keeps its place, empty.
faces: vector<vector<single>>,
buffers: vector<gpu::Buffer>,
counts: vector<integer>,
// A tile's triangles that belong to a group, six numbers each: the group, the triangle's
// rectangle in world pixels (x0, y0, x1, y1) and how near it reaches — what the cut-away asks.
walls: vector<vector<integer>>,
// The same triangles in the world, ten numbers each — the group, then three corners (x, y, z) —
// and the box round a tile's (x, y, z least, then most; none for a tile without): what the free
// camera's cut-away asks.
solids: vector<vector<float>>,
bounds: vector<vector<float>>,
// The groups hidden now (the walls cut away).
hidden: vector<integer>,
// This frame's actors as they were given, and the one never hidden: the cards are made from
// them for the camera there is.
actors: vector<single>,
keep: integer,
cards: gpu::Buffer,
card_count: integer,
over: gpu::Pipeline,
over_quad: gpu::Buffer,
over_picture: gpu::Texture,
over_on: boolean,
// What fills the screen's own rectangle with the sky where the window is another shape: made
// the first time it is needed.
backdrop: gpu::Texture?,
back_quad: gpu::Buffer?,
// The camera: free (a matrix the view gave), or fixed with the screen's top-left in world
// pixels; and the screen's size.
free: boolean,
view: vector<float>,
// The free camera's eye, and the level direction to its right (x, z): the way a card's width
// lies.
eye: vector<float>,
right_x: float,
right_z: float,
cam_x: integer,
cam_y: integer,
width: integer,
height: integer,
}
/// A scene for passes into `into` (`gpu::INTO_WINDOW`, `gpu::INTO_COLOUR_DEPTH` for a target
/// with depth), `sky` (0xAARRGGBB) where nothing is, on a screen the size of the device's
/// window. Null on a device whose backend this library has no shader source for.
pub fn new_scene(dev: const gpu::Device, into: integer, sky: i64) -> Scene? {
land = dev.pipeline(land_program(), gpu::State { depth: gpu::DEPTH_TEST_WRITE, into: into }) ?? return null;
over = dev.pipeline(over_program(), gpu::State { into: into }) ?? return null;
atlas = dev.texture(ATLAS, ATLAS);
atlas.nearest(true);
lights = dev.texture(LIGHT_CELLS, LIGHT_CELLS * LIGHT_LAYERS);
lights.nearest(true);
// nothing is lit from a cell until its light is given
lights.put(0, 0, [for _ in 0..LIGHT_CELLS * LIGHT_CELLS * LIGHT_LAYERS { 0 as u32 }], LIGHT_CELLS, LIGHT_CELLS * LIGHT_LAYERS);
torch_map = dev.texture(LIGHT_CELLS, LIGHT_CELLS * LIGHT_LAYERS);
torch_map.nearest(true);
torch_map.put(0, 0, [for _ in 0..LIGHT_CELLS * LIGHT_CELLS * LIGHT_LAYERS { 0 as u32 }], LIGHT_CELLS, LIGHT_CELLS * LIGHT_LAYERS);
side = ATLAS_ROW * (REACH + 1);
reach_atlas = dev.texture(side, side);
reach_atlas.put(0, 0, [for _ in 0..side * side { 0 as u32 }], side, side);
Scene {
into: into,
sky: sky,
values: land.block(),
land: land,
atlas: atlas,
lights: lights,
torch_map: torch_map,
reach_atlas: reach_atlas,
torch_ids: [for _ in 0..TORCHES { -1 }],
reaches: [for _ in 0..TORCHES { [] }],
glows: [for _ in 0..4 * TORCHES { 0.0 }],
colours: [for _ in 0..4 * TORCHES { 0.0 }],
pictures: 0,
places: [],
taken: [for _ in 0..SLOTS * SLOTS { false }],
first_free: 0,
slots: [],
faces: [],
buffers: [],
counts: [],
walls: [],
solids: [],
bounds: [],
hidden: [],
actors: [],
keep: -1,
cards: dev.buffer([0.0f]),
card_count: 0,
over: over,
over_quad: dev.buffer([0.0f]),
over_picture: dev.texture(1, 1),
over_on: false,
backdrop: null,
back_quad: null,
free: false,
view: [],
eye: [0.0, 0.0, 0.0],
right_x: 1.0,
right_z: 0.0,
cam_x: 0,
cam_y: 0,
width: dev.width(),
height: dev.height(),
}
}
/// The screen's size: what the fixed camera shows (a cell `WIDE` of these across) and the
/// overlay is laid out on. In a window of another size the screen is drawn as large as fits,
/// in its own shape, in the middle, with black beside it: a view made for 800 x 480 fills a
/// whole-screen window so, showing what it showed. A pass into a target (`draw_into`) covers
/// the whole target.
pub fn resize(self: Scene, width: integer, height: integer) {
self.width = width;
self.height = height;
}
/// Where the screen lies in a window `wide` x `high`: its left, its bottom, its width and its
/// height in the window's pixels.
pub fn placed(self: const Scene, wide: integer, high: integer) -> (integer, integer, integer, integer) {
if self.width <= 0 || self.height <= 0 || (self.width == wide && self.height == high) { return (0, 0, wide, high); }
scale = (wide as float / self.width as float) ?? 1.0;
other = (high as float / self.height as float) ?? 1.0;
if other < scale { scale = other; }
w = (self.width as float * scale + 0.5) as integer;
h = (self.height as float * scale + 0.5) as integer;
if w > wide { w = wide; }
if h > high { h = high; }
((wide - w) / 2, (high - h) / 2, w, h)
}
/// The screen's pixel under the window's pixel (x, y), both from the top-left: where a pointer
/// is on the screen. It lies outside 0 .. width, 0 .. height when the pointer is beside it.
pub fn screen_point(self: const Scene, wide: integer, high: integer, x: integer, y: integer) -> (integer, integer) {
at = self.placed(wide, high);
if at.2 <= 0 || at.3 <= 0 { return (x, y); }
top = high - at.1 - at.3;
(floor_of(((x - at.0) as float * self.width as float / at.2 as float) ?? 0.0),
floor_of(((y - top) as float * self.height as float / at.3 as float) ?? 0.0))
}
// An RGB565 value as 0xAARRGGBB: each channel's high bits repeated in its low ones; NONE clear.
fn wide(v: integer) -> i64 {
if v == NONE { return 0l; }
r = (v >> 11) & 31;
g = (v >> 5) & 63;
b = v & 31;
0xFF000000l | ((((r << 3) | (r >> 2)) << 16) as i64) | ((((g << 2) | (g >> 4)) << 8) as i64) | (((b << 3) | (b >> 2)) as i64)
}
/// A picture, 16 x 16 RGB565 texels row by row (NONE where it is clear): its number, for a
/// face or an actor; -1 when the texels are too few or the scene holds no more. The form a
/// small machine's pictures ship in; `add_image` takes the picture as it was drawn.
pub fn add_picture(self: Scene, texels: const vector<i32>) -> integer {
if len(texels) < TS * TS { return -1; }
self.add_image([for t in texels[0..TS * TS] { (wide(t) & 4294967295) as u32 }], TS)
}
/// A picture of any size up to the atlas's 1024 each way, `width` texels a row, row by row as
/// 0xAARRGGBB (imaging's `rgba()`): its number, for a face or an actor. A face's u and v run
/// 0 .. 1 over it whatever its size, and a texel under half opacity is clear. -1 when it has
/// no texels, is larger than the atlas, or the atlas has no room left for it.
pub fn add_image(self: Scene, texels: const vector<u32>, width: integer) -> integer {
if width < 1 || width > ATLAS { return -1; }
high = len(texels) / width ?? 0;
if high < 1 || high > ATLAS { return -1; }
at = self.room(width, high);
if at < 0 { return -1; }
sx = at % SLOTS;
sy = at / SLOTS;
for j in 0..(high + TS - 1) / TS {
for i in 0..(width + TS - 1) / TS { self.taken[(sy + j) * SLOTS + sx + i] = true; }
}
while self.first_free < SLOTS * SLOTS && (self.taken[self.first_free] ?? true) { self.first_free += 1; }
if len(texels) == width * high {
self.atlas.put(sx * TS, sy * TS, texels, width, high);
} else {
self.atlas.put(sx * TS, sy * TS, [for t in texels[0..width * high] { t }], width, high);
}
self.places += [sx * TS, sy * TS, width, high];
self.pictures += 1;
self.pictures - 1
}
// The first slot, row by row, from which a picture of `w` x `h` texels covers only free slots:
// pictures of one size fill the atlas in the order they come. -1 when there is none.
fn room(self: const Scene, w: integer, h: integer) -> integer {
sw = (w + TS - 1) / TS;
sh = (h + TS - 1) / TS;
for at in self.first_free..SLOTS * SLOTS {
x = at % SLOTS;
y = at / SLOTS;
if x + sw > SLOTS || y + sh > SLOTS { continue; }
free = true;
for j in 0..sh {
for i in 0..sw { if self.taken[(y + j) * SLOTS + x + i] ?? true { free = false; } }
}
if free { return at; }
}
-1
}
// Picture `pic`'s corner in the atlas and its size, in texels, as a vertex holds them.
fn place(self: const Scene, pic: integer) -> vector<single> {
[for k in 0..4 { (self.places[4 * pic + k] ?? 0) as single }]
}
// The vertices of the faces in `d` that are not hidden: a fan of triangles a face.
fn vertices(self: const Scene, d: const vector<single>) -> vector<single> {
out: vector<single> = [];
i = 0;
while i + 7 <= len(d) {
pic = ((d[i] ?? 0.0f) as float) as integer;
group = ((d[i + 1] ?? 0.0f) as float) as integer;
n = ((d[i + 2] ?? 0.0f) as float) as integer;
at = i + 7;
if n < 3 || at + 6 * n > len(d) { break; }
shown = pic >= 0 && pic < self.pictures;
if group >= 0 { for h in self.hidden { if h == group { shown = false; } } }
if shown {
pl = self.place(pic);
for t in 1..n - 1 {
for c in [0, t, t + 1] {
k = at + 6 * c;
out += [
d[k] ?? 0.0f, d[k + 1] ?? 0.0f, d[k + 2] ?? 0.0f,
d[k + 3] ?? 0.0f, d[k + 4] ?? 0.0f, pl[0] ?? 0.0f, pl[1] ?? 0.0f, pl[2] ?? 0.0f, pl[3] ?? 0.0f,
d[i + 3] ?? 0.0f, d[i + 4] ?? 0.0f, d[i + 5] ?? 0.0f,
d[i + 6] ?? 0.0f, d[k + 5] ?? 0.0f,
];
}
}
}
i = at + 6 * n;
}
out
}
/// Tile `key`'s faces, in place of the ones it had (none: it is empty). Faces follow one
/// another in `d`: the picture, the group it is hidden with (-1: none), its corners n, where
/// its light comes from (the cell x, y, its layer, and a factor; layer NO_LIGHT: its corners'
/// own), then n times x, y, z, u, v, light — u and v 0 .. 1 over the picture, light 0 .. 1.
pub fn set_tile(self: Scene, dev: const gpu::Device, key: integer, d: const vector<single>) {
verts = self.vertices(d);
old = self.slots[key];
if old != null {
self.faces[old.at] = d;
self.walls[old.at] = walls_of(d);
solid = solids_of(d);
self.bounds[old.at] = bounds_of(solid);
self.solids[old.at] = solid;
self.counts[old.at] = len(verts) / VERTEX;
b = &self.buffers[old.at]; // `at` names a buffer: slots and buffers grow together
if b == null { return; }
b.update(verts);
return;
}
self.slots += [Slot { key: key, at: len(self.buffers) }];
self.faces += [d];
self.walls += [walls_of(d)];
solid = solids_of(d);
self.bounds += [bounds_of(solid)];
self.solids += [solid];
self.counts += [len(verts) / VERTEX];
self.buffers += [dev.buffer(verts)];
}
// A world place in the fixed camera's subpixels (16 a pixel), rounded as the CPU rounds it.
fn sub_x(x: float) -> integer {
v = x * (WIDE as float) * 16.0;
if v < 0.0 { -((-v + 0.5) as integer) } else { (v + 0.5) as integer }
}
fn sub_y(y: float, z: float) -> integer {
v = (z * (DEEP as float) - y * (TALL as float)) * 16.0;
if v < 0.0 { -((-v + 0.5) as integer) } else { (v + 0.5) as integer }
}
// The pixel a subpixel lies in, and the first pixel past it.
fn pixel_of(sub: integer) -> integer {
if sub >= 0 { sub / 16 } else { -((-sub + 15) / 16) }
}
fn pixel_past(sub: integer) -> integer {
pixel_of(sub + 15)
}
// How near a place is: smaller is nearer, as the CPU's depth (a layer up and a cell south
// are nearer).
fn nearness(y: float, z: float) -> float {
32768.0 - 16.0 * (y * (DEEP as float) + z * (TALL as float))
}
fn floor_of(v: float) -> integer {
i = v as integer;
if (i as float) > v { i - 1 } else { i }
}
// The triangle of three corners (x, y, z each) as six numbers under `group`: its rectangle in
// world pixels and the nearest it reaches.
fn wall_of(group: integer, c: const vector<float>) -> vector<integer> {
x0 = sub_x(c[0]);
x1 = x0;
y0 = sub_y(c[1], c[2]);
y1 = y0;
near = nearness(c[1], c[2]);
for k in 1..3 {
x = sub_x(c[3 * k] ?? 0.0);
y = sub_y(c[3 * k + 1] ?? 0.0, c[3 * k + 2] ?? 0.0);
n = nearness(c[3 * k + 1] ?? 0.0, c[3 * k + 2] ?? 0.0);
if x < x0 { x0 = x; }
if x > x1 { x1 = x; }
if y < y0 { y0 = y; }
if y > y1 { y1 = y; }
if n < near { near = n; }
}
[group, pixel_of(x0), pixel_of(y0), pixel_past(x1), pixel_past(y1), floor_of(near)]
}
fn least(a: integer, b: integer) -> integer {
if a < b { a } else { b }
}
// Every triangle in `d` that belongs to a group.
fn walls_of(d: const vector<single>) -> vector<integer> {
out: vector<integer> = [];
i = 0;
while i + 7 <= len(d) {
group = ((d[i + 1] ?? 0.0f) as float) as integer;
n = ((d[i + 2] ?? 0.0f) as float) as integer;
at = i + 7;
if n < 3 || at + 6 * n > len(d) { break; }
if group >= 0 {
for t in 1..n - 1 {
c: vector<float> = [];
for k in [0, t, t + 1] { c += [(d[at + 6 * k] ?? 0.0f) as float, (d[at + 6 * k + 1] ?? 0.0f) as float, (d[at + 6 * k + 2] ?? 0.0f) as float]; }
out += wall_of(group, c);
}
}
i = at + 6 * n;
}
out
}
// Every triangle in `d` that belongs to a group, in the world: the group, then its three
// corners (x, y, z).
fn solids_of(d: const vector<single>) -> vector<float> {
out: vector<float> = [];
i = 0;
while i + 7 <= len(d) {
group = ((d[i + 1] ?? 0.0f) as float) as integer;
n = ((d[i + 2] ?? 0.0f) as float) as integer;
at = i + 7;
if n < 3 || at + 6 * n > len(d) { break; }
if group >= 0 {
for t in 1..n - 1 {
out += [group as float];
for k in [0, t, t + 1] { out += [(d[at + 6 * k] ?? 0.0f) as float, (d[at + 6 * k + 1] ?? 0.0f) as float, (d[at + 6 * k + 2] ?? 0.0f) as float]; }
}
}
i = at + 6 * n;
}
out
}
// The box round the triangles of `solid`: x, y, z least, then most; none when there are none.
fn bounds_of(solid: const vector<float>) -> vector<float> {
if len(solid) < 10 { return []; }
lo = [solid[1] ?? 0.0, solid[2] ?? 0.0, solid[3] ?? 0.0];
hi = [solid[1] ?? 0.0, solid[2] ?? 0.0, solid[3] ?? 0.0];
j = 0;
while j + 10 <= len(solid) {
for k in 0..9 {
v = solid[j + 1 + k] ?? 0.0;
if v < lo[k % 3] { lo[k % 3] = v; }
if v > hi[k % 3] { hi[k % 3] = v; }
}
j += 10;
}
both = lo + hi;
both
}
/// Tile `key` gone.
pub fn drop_tile(self: Scene, key: integer) {
old = self.slots[key] ?? return;
self.faces[old.at] = [];
self.walls[old.at] = [];
self.solids[old.at] = [];
self.bounds[old.at] = [];
self.counts[old.at] = 0;
}
/// How many tiles hold faces now.
pub fn tiles(self: const Scene) -> integer {
n = 0;
for c in self.counts { if c > 0 { n += 1; } }
n
}
/// The light of cells as data: `d` is the layer, the box's corner (x0, y0), its width and
/// height, then each cell's light (0 .. 1) row by row. The faces lit from those cells are lit
/// by it from the next frame; no face is given again.
pub fn set_light(self: Scene, d: const vector<single>) {
if len(d) < 5 { return; }
z = ((d[0] ?? 0.0f) as float) as integer;
x0 = ((d[1] ?? 0.0f) as float) as integer;
y0 = ((d[2] ?? 0.0f) as float) as integer;
w = ((d[3] ?? 0.0f) as float) as integer;
h = ((d[4] ?? 0.0f) as float) as integer;
if w <= 0 || h <= 0 || len(d) < 5 + w * h { return; }
write_cells(self.lights, z, x0, y0, w, h, light_texels(d, 5, w * h));
}
// Write the texels of the cells x0 .. x0 + w - 1, y0 .. y0 + h - 1 on layer z, row by row, into
// a map laid out as the light's: the whole box in one write where it lies inside the map;
// where it crosses the map's edge it goes on at the other side, so it is written a run of
// cells at a time.
fn write_cells(map: const gpu::Texture, z: integer, x0: integer, y0: integer, w: integer, h: integer, texels: const vector<u32>) {
layer = ((z % LIGHT_LAYERS) + LIGHT_LAYERS) % LIGHT_LAYERS;
cx0 = ((x0 % LIGHT_CELLS) + LIGHT_CELLS) % LIGHT_CELLS;
cy0 = ((y0 % LIGHT_CELLS) + LIGHT_CELLS) % LIGHT_CELLS;
if cx0 + w <= LIGHT_CELLS && cy0 + h <= LIGHT_CELLS {
map.put(cx0, cy0 + LIGHT_CELLS * layer, texels, w, h);
return;
}
for j in 0..h {
cy = (cy0 + j) % LIGHT_CELLS;
i = 0;
while i < w {
cx = (cx0 + i) % LIGHT_CELLS;
run = least(w - i, LIGHT_CELLS - cx);
map.put(cx, cy + LIGHT_CELLS * layer, texels[j * w + i..j * w + i + run], run, 1);
i += run;
}
}
}
// `count` lights of `d` from `first` as texels: the light's high byte in red, its low byte in
// green; alpha says a light was given.
fn light_texels(d: const vector<single>, first: integer, count: integer) -> vector<u32> {
out: vector<u32> = [];
for k in 0..count {
l = (d[first + k] ?? 0.0f) as float;
v = (if l < 0.0 { 0.0 } else if l > 1.0 { 1.0 } else { l } * 65535.0 + 0.5) as integer;
out += [((0xFF000000 | ((v >> 8) << 16) | ((v & 255) << 8)) & 4294967295) as u32];
}
out
}
// ── torches ──
/// Whether this implementation lights torches of their own: it does. One that does not is
/// given the cells' light with the torches in it.
pub fn offers_torches(self: const Scene) -> boolean {
self.into >= 0
}
// The square torch `id` has, or a free one for it; -1 when every square is taken.
fn square_of(self: const Scene, id: integer, take: boolean) -> integer {
free = -1;
for t in self.torch_ids {
if t == id { return t#index; }
if t < 0 && free < 0 { free = t#index; }
}
if take { free } else { -1 }
}
// The reach torch square `sq` gives cell (x, y) on `layer`: 0 where it does not reach.
fn reach_at(self: const Scene, sq: integer, layer: integer, x: integer, y: integer) -> float {
r = self.reaches[sq] ?? [];
if len(r) < 5 || ((r[0] ?? 0.0f) as float) as integer != layer { return 0.0; }
i = x - ((r[1] ?? 0.0f) as float) as integer;
j = y - ((r[2] ?? 0.0f) as float) as integer;
w = ((r[3] ?? 0.0f) as float) as integer;
h = ((r[4] ?? 0.0f) as float) as integer;
if i < 0 || j < 0 || i >= w || j >= h { return 0.0; }
(r[5 + j * w + i] ?? 0.0f) as float
}
// Work out again, for every cell of a box, which four torches reach it most, and write them:
// their squares plus one, the strongest in red, then green, blue and alpha; 0 for none.
fn rank_cells(self: Scene, layer: integer, x0: integer, y0: integer, w: integer, h: integer) {
texels: vector<u32> = [];
for j in 0..h {
for i in 0..w {
// the four strongest so far, strongest first, and their reaches
who = [0, 0, 0, 0];
how = [0.0, 0.0, 0.0, 0.0];
for t in self.torch_ids {
if t < 0 { continue; }
v = self.reach_at(t#index, layer, x0 + i, y0 + j);
at = 4;
for k in rev(0..4) { if v > how[k] { at = k; } }
if at < 4 {
for k in rev(at + 1..4) {
who[k] = who[k - 1];
how[k] = how[k - 1];
}
who[at] = t#index + 1;
how[at] = v;
}
}
texels += [(((who[3] << 24) | (who[0] << 16) | (who[1] << 8) | who[2]) & 4294967295) as u32];
}
}
write_cells(self.torch_map, layer, x0, y0, w, h, texels);
}
/// A torch's reach: `d` is its id, the layer, the box's corner (x0, y0), its width and height
/// (15 cells at most each way), then the light it gives each cell of the box (0 .. 1) row by
/// row, 0 where it does not reach. Given when the torch is new, has moved, or burns
/// otherwise; walls stop it where the reach says so. False, and nothing kept, when the box is
/// too large or the scene holds its 64 torches already.
pub fn set_torch_reach(self: Scene, d: const vector<single>) -> boolean {
if len(d) < 6 { return false; }
id = ((d[0] ?? 0.0f) as float) as integer;
layer = ((d[1] ?? 0.0f) as float) as integer;
x0 = ((d[2] ?? 0.0f) as float) as integer;
y0 = ((d[3] ?? 0.0f) as float) as integer;
w = ((d[4] ?? 0.0f) as float) as integer;
h = ((d[5] ?? 0.0f) as float) as integer;
if id < 0 || w <= 0 || h <= 0 || w > REACH || h > REACH || len(d) < 6 + w * h { return false; }
sq = self.square_of(id, true);
if sq < 0 { return false; }
// where it reached before is ranked again too, once it is replaced: read before it is
old = self.box_of(sq);
self.torch_ids[sq] = id;
self.reaches[sq] = d[1..6 + w * h];
// its square of the atlas: the reach, the rest dark
side = REACH + 1;
texels: vector<u32> = [];
for j in 0..side {
for i in 0..side {
l = if i < w && j < h { (d[6 + j * w + i] ?? 0.0f) as float } else { 0.0 };
v = (if l < 0.0 { 0.0 } else if l > 1.0 { 1.0 } else { l } * 65535.0 + 0.5) as integer;
texels += [((0xFF000000 | ((v >> 8) << 16) | ((v & 255) << 8)) & 4294967295) as u32];
}
}
self.reach_atlas.put((sq % ATLAS_ROW) * side, (sq / ATLAS_ROW) * side, texels, side, side);
self.glows[4 * sq] = x0 as float;
self.glows[4 * sq + 1] = y0 as float;
self.glows[4 * sq + 3] = layer as float;
if len(old) == 5 { self.rank_cells(old[0] ?? 0, old[1] ?? 0, old[2] ?? 0, old[3] ?? 0, old[4] ?? 0); }
self.rank_cells(layer, x0, y0, w, h);
true
}
// The box torch square `sq` reaches, as five whole numbers of its own — the layer, the corner
// (x0, y0), the width and height — or none when the square holds no reach.
fn box_of(self: const Scene, sq: integer) -> vector<integer> {
r = self.reaches[sq] ?? [];
if len(r) < 5 { return []; }
[for k in 0..5 { ((r[k] ?? 0.0f) as float) as integer }]
}
/// Torch `id` gone: its light with it.
pub fn drop_torch(self: Scene, id: integer) {
sq = self.square_of(id, false);
if sq < 0 { return; }
old = self.box_of(sq);
self.torch_ids[sq] = -1;
self.reaches[sq] = [];
self.glows[4 * sq + 2] = 0.0;
if len(old) == 5 { self.rank_cells(old[0] ?? 0, old[1] ?? 0, old[2] ?? 0, old[3] ?? 0, old[4] ?? 0); }
}
/// This frame's torches, nine numbers each in `d`: its id, its place (x, y, z as a face's
/// corners), the shade
/// it starts at, its glow (0 .. 1: how brightly it burns now, a flicker eased), and its colour
/// (red, green, blue, 0 .. 1). A torch whose reach was given and that is not named burns
/// dark this frame; one named with no reach given is not drawn. A flicker is these numbers
/// alone: nothing else is given again.
pub fn set_torches(self: Scene, d: const vector<single>) {
for sq in 0..TORCHES { self.glows[4 * sq + 2] = 0.0; }
self.colours = [for _ in 0..4 * TORCHES { 0.0 }];
i = 0;
while i + 9 <= len(d) {
sq = self.square_of(((d[i] ?? 0.0f) as float) as integer, false);
if sq >= 0 {
self.glows[4 * sq + 2] = (d[i + 5] ?? 0.0f) as float;
self.colours[4 * sq] = (d[i + 6] ?? 0.0f) as float;
self.colours[4 * sq + 1] = (d[i + 7] ?? 0.0f) as float;
self.colours[4 * sq + 2] = (d[i + 8] ?? 0.0f) as float;
}
i += 9;
}
}
/// How many torches' reaches the scene holds.
pub fn torches(self: const Scene) -> integer {
n = 0;
for t in self.torch_ids { if t >= 0 { n += 1; } }
n
}
/// This frame's actors, eleven numbers each in `d`: an id, the picture, the bottom middle
/// (x, y, z) of the picture as it stands unturned, its size in cells, its light, how far it is
/// turned (degrees clockwise as the camera sees it), the point of the picture it turns about
/// (u, v: 0 .. 1 across and down) and whether it is mirrored (1) or not (0). A card stands
/// upright and faces the camera: for the fixed camera in the plane it looks at, for the free
/// one turned about its foot so its width lies across the view. The actor `keep_seen` is never
/// hidden: the wall groups between the camera and its card are cut away, and shown again when
/// they no longer are (-1: none).
pub fn set_actors(self: Scene, d: const vector<single>, keep_seen: integer) {
self.actors = d;
self.keep = keep_seen;
self.place_actors();
}
// Make the cards of the actors as they were given, for the camera there is, and cut away the
// walls in front of the one never hidden.
fn place_actors(self: Scene) {
d = self.actors;
verts: vector<single> = [];
hero: vector<float> = [];
i = 0;
while i + 11 <= len(d) {
pic = ((d[i + 1] ?? 0.0f) as float) as integer;
x = (d[i + 2] ?? 0.0f) as float;
y = (d[i + 3] ?? 0.0f) as float;
z = (d[i + 4] ?? 0.0f) as float;
size = (d[i + 5] ?? 0.0f) as float;
light = (d[i + 6] ?? 0.0f) as float;
deg = (d[i + 7] ?? 0.0f) as float;
pu = (d[i + 8] ?? 0.0f) as float;
pv = (d[i + 9] ?? 0.0f) as float;
mirror = ((d[i + 10] ?? 0.0f) as float) != 0.0;
if pic >= 0 && pic < self.pictures {
sn = sin(deg * PI / 180.0);
cs = cos(deg * PI / 180.0);
bx = x - size / 2.0 + pu * size;
by = y + (1.0 - pv) * size;
// the picture's corners about its pivot, turned: top-left, top-right, bottom-right,
// bottom-left; each its place (x, y, z) and its point of the picture (u, v)
c: vector<float> = [];
for uv in [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] {
px = (uv.0 - pu) * size;
py = (pv - uv.1) * size;
across = px * cs + py * sn;
if self.free {
// its width lies along the camera's right, from the foot
along = (pu - 0.5) * size + across;
c += [x + along * self.right_x, by - px * sn + py * cs, z + along * self.right_z];
} else {
c += [bx + across, by - px * sn + py * cs, z];
}
c += [if mirror { 1.0 - uv.0 } else { uv.0 }, uv.1];
}
pl = self.place(pic);
for k in [0, 1, 2, 0, 2, 3] {
verts += [
(c[5 * k] ?? 0.0) as single, (c[5 * k + 1] ?? 0.0) as single, (c[5 * k + 2] ?? 0.0) as single, (c[5 * k + 3] ?? 0.0) as single,
(c[5 * k + 4] ?? 0.0) as single, pl[0] ?? 0.0f, pl[1] ?? 0.0f, pl[2] ?? 0.0f, pl[3] ?? 0.0f, floor_of(x) as single, floor_of(z) as single, floor_of(y) as single, -1.0f, light as single,
];
}
if ((d[i] ?? 0.0f) as float) as integer == self.keep {
for k in 0..4 { hero += [c[5 * k] ?? 0.0, c[5 * k + 1] ?? 0.0, c[5 * k + 2] ?? 0.0]; }
}
}
i += 11;
}
self.card_count = len(verts) / VERTEX;
if len(verts) > 0 { self.cards.update(verts); }
want: vector<integer> = [];
if self.keep >= 0 && len(hero) >= 12 { want = if self.free { self.crossed(hero) } else { self.covering(hero) }; }
self.hide(want);
}
// The wall groups that cover the card with corners `c` (four of x, y, z) on the fixed camera's
// screen and reach nearer than it.
fn covering(self: const Scene, c: const vector<float>) -> vector<integer> {
want: vector<integer> = [];
a = wall_of(0, c[0..9]);
b = wall_of(0, c[0..3] + c[6..12]);
x0 = least(a[1] ?? 0, b[1] ?? 0);
y0 = least(a[2] ?? 0, b[2] ?? 0);
x1 = -least(-(a[3] ?? 0), -(b[3] ?? 0));
y1 = -least(-(a[4] ?? 0), -(b[4] ?? 0));
near = least(a[5] ?? 0, b[5] ?? 0);
for ws in self.walls {
j = 0;
while j + 6 <= len(ws) {
g = ws[j] ?? 0;
covers = (ws[j + 1] ?? 0) < x1 && x0 < (ws[j + 3] ?? 0) && (ws[j + 2] ?? 0) < y1 && y0 < (ws[j + 4] ?? 0)
&& (ws[j + 1] ?? 0) < (ws[j + 3] ?? 0) && (ws[j + 2] ?? 0) < (ws[j + 4] ?? 0) && x0 < x1 && y0 < y1;
if covers && (ws[j + 5] ?? 0) < near {
known = false;
for w in want { if w == g { known = true; } }
if !known { want += [g]; }
}
j += 6;
}
}
want
}
// The wall groups a line from the free camera's eye to the card with corners `c` (four of
// x, y, z) crosses. Five lines: to the card's middle and to the point halfway from the middle
// to each corner, so a wall the card only touches at its edge is not one of them.
fn crossed(self: const Scene, c: const vector<float>) -> vector<integer> {
want: vector<integer> = [];
ex = self.eye[0] ?? 0.0;
ey = self.eye[1] ?? 0.0;
ez = self.eye[2] ?? 0.0;
mid = [0.0, 0.0, 0.0];
// the box round the eye and the card: a tile whose walls lie outside it is not looked at
lo = [ex, ey, ez];
hi = [ex, ey, ez];
for k in 0..12 {
v = c[k] ?? 0.0;
mid[k % 3] += v / 4.0;
if v < lo[k % 3] { lo[k % 3] = v; }
if v > hi[k % 3] { hi[k % 3] = v; }
}
ends: vector<float> = mid;
for k in 0..12 { ends += [((mid[k % 3] ?? 0.0) + (c[k] ?? 0.0)) / 2.0]; }
for solid in self.solids {
bd = self.bounds[solid#index] ?? [];
if len(bd) < 6 { continue; }
apart = false;
for k in 0..3 { if (bd[k] ?? 0.0) > (hi[k] ?? 0.0) || (bd[k + 3] ?? 0.0) < (lo[k] ?? 0.0) { apart = true; } }
if apart { continue; }
j = 0;
while j + 10 <= len(solid) {
g = (solid[j] ?? 0.0) as integer;
known = false;
for w in want { if w == g { known = true; } }
if !known {
hit = false;
for e in 0..5 {
if !hit && between(solid, j + 1, (ex, ey, ez), (ends[3 * e] ?? 0.0, ends[3 * e + 1] ?? 0.0, ends[3 * e + 2] ?? 0.0)) { hit = true; }
}
if hit { want += [g]; }
}
j += 10;
}
}
want
}
// Whether the triangle whose corners are the nine numbers of `t` from `at` lies between the
// points a and b: the line from a to b goes through it, past a and before b.
fn between(t: const vector<float>, at: integer, a: (float, float, float), b: (float, float, float)) -> boolean {
px = t[at] ?? 0.0;
py = t[at + 1] ?? 0.0;
pz = t[at + 2] ?? 0.0;
// the triangle's two edges from its first corner, and the line's way
ux = (t[at + 3] ?? 0.0) - px;
uy = (t[at + 4] ?? 0.0) - py;
uz = (t[at + 5] ?? 0.0) - pz;
vx = (t[at + 6] ?? 0.0) - px;
vy = (t[at + 7] ?? 0.0) - py;
vz = (t[at + 8] ?? 0.0) - pz;
dx = b.0 - a.0;
dy = b.1 - a.1;
dz = b.2 - a.2;
// h = d x v
hx = dy * vz - dz * vy;
hy = dz * vx - dx * vz;
hz = dx * vy - dy * vx;
det = ux * hx + uy * hy + uz * hz;
// the line runs along the triangle's plane: it does not go through it
if det > -0.000000001 && det < 0.000000001 { return false; }
sx = a.0 - px;
sy = a.1 - py;
sz = a.2 - pz;
u = ((sx * hx + sy * hy + sz * hz) / det) ?? -1.0;
if u < 0.0 || u > 1.0 { return false; }
// q = s x u
qx = sy * uz - sz * uy;
qy = sz * ux - sx * uz;
qz = sx * uy - sy * ux;
v = ((dx * qx + dy * qy + dz * qz) / det) ?? -1.0;
if v < 0.0 || u + v > 1.0 { return false; }
along = ((vx * qx + vy * qy + vz * qz) / det) ?? -1.0;
along > 0.000001 && along < 0.999999
}
// Hide the groups `want` and show those hidden before that are not among them. The tiles
// holding a group that changed are given to the GPU again.
fn hide(self: Scene, want: const vector<integer>) {
changed: vector<integer> = [];
for h in self.hidden {
still = false;
for w in want { if w == h { still = true; } }
if !still { changed += [h]; }
}
for w in want {
was = false;
for h in self.hidden { if h == w { was = true; } }
if !was { changed += [w]; }
}
if len(changed) == 0 { return; }
self.hidden = want;
for ws in self.walls {
touched = false;
j = 0;
while j + 6 <= len(ws) && !touched {
for g in changed { if g == (ws[j] ?? -1) { touched = true; } }
j += 6;
}
if touched {
verts = self.vertices(self.faces[ws#index] ?? []);
self.counts[ws#index] = len(verts) / VERTEX;
again = &self.buffers[ws#index]; // walls and buffers grow together
if again == null { continue; }
again.update(verts);
}
}
}
/// The groups hidden now: the walls cut away between the camera and the actor never hidden.
pub fn hidden_groups(self: const Scene) -> vector<integer> {
self.hidden
}
/// A picture over everything — the status line, talk bubbles — `w` x `h` RGB565 values row by
/// row, NONE where it is clear, each drawn `scale` x `scale` from the screen's top-left. One
/// with too few values takes it away.
pub fn set_overlay(self: Scene, dev: const gpu::Device, px: const vector<i32>, w: integer, h: integer, scale: integer) {
if w <= 0 || h <= 0 || scale <= 0 || len(px) < w * h {
self.over_on = false;
return;
}
if self.over_picture.width() != w || self.over_picture.height() != h {
self.over_picture = dev.texture(w, h);
self.over_picture.nearest(true);
}
wide_px: vector<u32> = [];
for v in px[0..w * h] { wide_px += [(wide(v) & 4294967295) as u32]; }
self.over_picture.put(0, 0, wide_px, w, h);
// the picture's rectangle from the screen's top-left, in clip space; its first row on top
right = ((2.0 * (w * scale) as float / self.width as float) ?? 0.0) - 1.0;
low = 1.0 - ((2.0 * (h * scale) as float / self.height as float) ?? 0.0);
self.over_quad.update([
-1.0f, 1.0f, 0.0f, 0.0f, right as single, 1.0f, 1.0f, 0.0f, right as single, low as single, 1.0f, 1.0f,
-1.0f, 1.0f, 0.0f, 0.0f, right as single, low as single, 1.0f, 1.0f, -1.0f, low as single, 0.0f, 1.0f,
]);
self.over_on = true;
}
/// Whether this implementation offers a free camera: it does. One on a CPU offers the fixed
/// camera only, so a view asks before it chooses.
pub fn offers_free_camera(self: const Scene) -> boolean {
self.into >= 0
}
/// The free camera: an eye, a point looked at, and a field of view in degrees, in perspective.
/// The cards turn to face it, and the walls between the eye and the actor never hidden are cut
/// away, whichever of the camera and the actors is given first.
pub fn free_camera(self: Scene, eye: (float, float, float), at: (float, float, float), field: float) {
aspect = (self.width as float / self.height as float) ?? 1.0;
self.view = times(perspective(field, aspect, 0.05, 200.0), look(eye, at));
// the level direction to the camera's right, as `look` takes it; east when it looks straight
// up or down
rx = eye.2 - at.2;
rz = at.0 - eye.0;
rl = sqrt(rx * rx + rz * rz);
if rl == 0.0 { rx = 1.0; rz = 0.0; rl = 1.0; }
rx = (rx / rl) ?? 1.0;
rz = (rz / rl) ?? 0.0;
same = self.free && rx == self.right_x && rz == self.right_z && eye.0 == (self.eye[0] ?? 0.0) && eye.1 == (self.eye[1] ?? 0.0)
&& eye.2 == (self.eye[2] ?? 0.0);
self.free = true;
self.eye = [eye.0, eye.1, eye.2];
self.right_x = rx;
self.right_z = rz;
if !same { self.place_actors(); }
}
// A perspective projection, column-major: `field` degrees high, depth -1 at `near` to 1 at `far`.
fn perspective(field: float, aspect: float, near: float, far: float) -> vector<float> {
f = (1.0 / tan(field * PI / 360.0)) ?? 1.0;
[
(f / aspect) ?? f, 0.0, 0.0, 0.0, 0.0, f, 0.0, 0.0, 0.0, 0.0, ((far + near) / (near - far)) ?? -1.0, -1.0,
0.0, 0.0, ((2.0 * far * near) / (near - far)) ?? 0.0, 0.0,
]
}
// The view from `eye` towards `at`, y up, column-major.
fn look(eye: (float, float, float), at: (float, float, float)) -> vector<float> {
fx = at.0 - eye.0;
fy = at.1 - eye.1;
fz = at.2 - eye.2;
fl = sqrt(fx * fx + fy * fy + fz * fz);
if fl == 0.0 { fl = 1.0; }
fx = (fx / fl) ?? 0.0;
fy = (fy / fl) ?? 0.0;
fz = (fz / fl) ?? 0.0;
// right = forward x up, with up (0, 1, 0)
rx = -fz;
rz = fx;
rl = sqrt(rx * rx + rz * rz);
if rl == 0.0 { rx = 1.0; rz = 0.0; rl = 1.0; }
rx = (rx / rl) ?? 1.0;
rz = (rz / rl) ?? 0.0;
// up = right x forward
ux = -rz * fy;
uy = rz * fx - rx * fz;
uz = rx * fy;
[
rx, ux, -fx, 0.0, 0.0, uy, -fy, 0.0, rz, uz, -fz, 0.0,
-(rx * eye.0 + rz * eye.2), -(ux * eye.0 + uy * eye.1 + uz * eye.2), fx * eye.0 + fy * eye.1 + fz * eye.2, 1.0,
]
}
// a times b, both column-major.
fn times(a: const vector<float>, b: const vector<float>) -> vector<float> {
out: vector<float> = [];
for c in 0..4 {
for r in 0..4 {
v = 0.0;
for k in 0..4 { v += (a[k * 4 + r] ?? 0.0) * (b[c * 4 + k] ?? 0.0); }
out += [v];
}
}
out
}
/// The fixed camera, from the south: the screen's top-left at world pixel (px, py), where cell
/// (x, z) on layer y lies at (x * WIDE, z * DEEP - y * TALL).
pub fn fixed_camera(self: Scene, px: integer, py: integer) {
was = self.free;
self.free = false;
self.cam_x = px;
self.cam_y = py;
// the cards and the cut-away were the free camera's
if was { self.place_actors(); }
}
// The fixed camera as a matrix, column-major: a parallel projection onto the screen's pixels,
// the depth growing away from the camera — nearer is higher and further south.
fn fixed_matrix(self: const Scene) -> vector<float> {
w = self.width as float;
h = self.height as float;
far = 2048.0;
[
(WIDE as float * 2.0 / w) ?? 0.0, 0.0, 0.0, 0.0,
0.0, (TALL as float * 2.0 / h) ?? 0.0, (-(DEEP as float) / far) ?? 0.0, 0.0,
0.0, (-(DEEP as float) * 2.0 / h) ?? 0.0, (-(TALL as float) / far) ?? 0.0, 0.0,
((-2.0 * self.cam_x as float / w) ?? 0.0) - 1.0, 1.0 + ((2.0 * self.cam_y as float / h) ?? 0.0),
// the depth measured from the ground of the row at the screen's middle: a scene far from the
// origin is inside the depth's range as one near it is
((TALL as float * (self.cam_y as float + h / 2.0) / DEEP as float) / far) ?? 0.0, 1.0,
]
}
// Draw the scene inside the pass in progress.
fn draw_in(self: Scene, dev: gpu::Device) {
self.values.mat4(0, if self.free { self.view } else { self.fixed_matrix() });
for sq in 0..TORCHES {
self.values.f4_at(1, sq, self.glows[4 * sq] ?? 0.0, self.glows[4 * sq + 1] ?? 0.0, self.glows[4 * sq + 2] ?? 0.0, self.glows[4 * sq + 3] ?? 0.0);
self.values.f4_at(2, sq, self.colours[4 * sq] ?? 0.0, self.colours[4 * sq + 1] ?? 0.0, self.colours[4 * sq + 2] ?? 0.0, 0.0);
}
dev.bind(self.land);
dev.uniforms(self.values);
dev.sample(0, self.atlas);
dev.sample(1, self.lights);
dev.sample(2, self.torch_map);
dev.sample(3, self.reach_atlas);
for b in self.buffers {
n = self.counts[b#index] ?? 0;
if n > 0 {
dev.vertices(b);
dev.draw(0, n);
}
}
if self.card_count > 0 {
dev.vertices(self.cards);
dev.draw(0, self.card_count);
}
if self.over_on {
dev.bind(self.over);
dev.sample(0, self.over_picture);
dev.vertices(self.over_quad);
dev.draw(0, 6);
}
}
/// Draw the scene into the window: a pass of its own, cleared to the sky. Where the window
/// is not the screen's size (`resize`), the screen is drawn as large as fits in the middle of
/// it and the rest is black.
pub fn draw(self: Scene, dev: gpu::Device) {
wide = dev.width();
high = dev.height();
at = self.placed(wide, high);
if at.0 == 0 && at.1 == 0 && at.2 == wide && at.3 == high {
dev.begin_window(gpu::CLEAR, self.sky);
self.draw_in(dev);
dev.end();
return;
}
if !self.backdrop {
one = dev.texture(1, 1);
one.put(0, 0, [(self.sky & 4294967295) as u32], 1, 1);
self.backdrop = one;
self.back_quad = dev.buffer([
-1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f,
]);
}
dev.begin_window(gpu::CLEAR, 0xFF000000);
dev.viewport(at.0, at.1, at.2, at.3);
// the sky, over the screen's own rectangle
dev.bind(self.over);
dev.sample(0, self.backdrop!);
dev.vertices(self.back_quad!);
dev.draw(0, 6);
self.draw_in(dev);
dev.end();
}
/// Draw the scene into `target` (made for the kind the scene was made for).
pub fn draw_into(self: Scene, dev: gpu::Device, target: const gpu::Target) {
dev.begin(target, gpu::CLEAR, self.sky);
self.draw_in(dev);
dev.end();
}
tests/backends.loft
// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// A town seen by the free camera is one picture on every backend this machine has, but for
// the pixels an edge runs through the middle of.
//
// THE TOLERANCE, measured on an Apple M3 Max, `gpu_metal` against `gpu_gl`:
// - a scene whose edges lie on pixel borders (tests/pixels.loft, tests/torches.loft, and the
// backends' own suites) is the same byte for byte;
// - a scene in perspective differs in single pixels where a face's edge, or the border of two
// texels, passes within rounding of a pixel's middle: the pixel then shows the face or the
// texel on the other side. At 960 x 720, 12 views of the town of gpu_host/bench: 336 of
// their 691,200 pixels each in all, at most 39 in one; its 600th frame: 80 (0.012 %);
// - that is as much as one backend differs from ITSELF when it draws the same view into a
// texture instead of the window (OpenGL 358, Metal 371 over the same 12 views), so it is the
// rasteriser's rounding at an edge, not a difference in what the two are asked to draw;
// - not the cause: Metal's fast-math compilation (the count is the same with it off).
// So the bound here is a count of pixels and no channel step — a pixel on the wrong side of an
// edge shows another face's colour whole: at most 1 pixel in 5,000. This test's four views at
// 320 x 240 differ in 0, 0, 2 and 0 pixels. On Linux, OpenGL against Vulkan: `edge_bound`.
// Without a display, or on a machine with one backend, the test returns at once.
use gpu;
use gpu_gl;
use gpu_metal;
use gpu_vulkan;
use scene3d;
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
}
fn backends() -> vector<i64> {
[for t in [gpu_gl::table(), gpu_metal::table(), gpu_vulkan::table()] if t != 0 { t }]
}
fn s(v: const vector<float>) -> vector<single> {
[for x in v { x as single }]
}
// A picture: a grid of two RGB565 colours.
fn picture(a: integer, b: integer) -> vector<i32> {
out: vector<i32> = [];
for y in 0..16 { for x in 0..16 { out += [((if (x / 4 + y / 4) % 2 == 0 { a } else { b }) & 65535) as i32]; } }
out
}
fn face(out: vector<float>, pic: integer, x: integer, z: integer, lk: float, corners: const vector<float>) {
out += [pic as float, -1.0, (len(corners) / 6) as float, x as float, z as float, 0.0, lk];
out += corners;
}
// A town of 16 x 12 cells: ground, and on every fifth cell a block with its top and two sides.
fn town() -> vector<float> {
out: vector<float> = [];
for z in 0..12 {
for x in 0..16 {
fx = x as float;
fz = z as float;
if (x + 2 * z) % 5 == 0 {
face(out, 1, x, z, 1.0, [fx, 1.0, fz, 0.0, 0.0, 1.0, fx + 1.0, 1.0, fz, 1.0, 0.0, 1.0, fx + 1.0, 1.0, fz + 1.0, 1.0, 1.0, 1.0, fx, 1.0, fz + 1.0, 0.0, 1.0, 1.0]);
face(out, 2, x, z, 0.8, [fx, 1.0, fz + 1.0, 0.0, 0.0, 1.0, fx + 1.0, 1.0, fz + 1.0, 1.0, 0.0, 1.0, fx + 1.0, 0.0, fz + 1.0, 1.0, 1.0, 1.0, fx, 0.0, fz + 1.0, 0.0, 1.0, 1.0]);
face(out, 2, x, z, 0.6, [fx + 1.0, 1.0, fz + 1.0, 0.0, 0.0, 1.0, fx + 1.0, 1.0, fz, 1.0, 0.0, 1.0, fx + 1.0, 0.0, fz, 1.0, 1.0, 1.0, fx + 1.0, 0.0, fz + 1.0, 0.0, 1.0, 1.0]);
} else {
face(out, 0, x, z, 1.0, [fx, 0.0, fz, 0.0, 0.0, 1.0, fx + 1.0, 0.0, fz, 1.0, 0.0, 1.0, fx + 1.0, 0.0, fz + 1.0, 1.0, 1.0, 1.0, fx, 0.0, fz + 1.0, 0.0, 1.0, 1.0]);
}
}
}
out
}
// Four views of the town from the south-east, each a step further round.
fn views(table: i64) -> vector<vector<u32>> {
out: vector<vector<u32>> = [];
dev = gpu::open(table, 320, 240, "town") ?? return out;
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, 0xFF94BFE6) ?? return out;
_ = scene.add_picture(picture(19270, 17226));
_ = scene.add_picture(picture(44374, 31696));
_ = scene.add_picture(picture(38603, 27397));
scene.set_tile(dev, 1, s(town()));
for i in 0..4 {
turn = (20 + 37 * i) as float * PI / 180.0;
scene.free_camera((8.0 + 9.0 * cos(turn), 5.0, 6.0 + 8.0 * sin(turn)), (8.0, 0.0, 6.0), 55.0);
scene.draw(dev);
out += [dev.capture()];
}
assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
out
}
// How many of a view's 76,800 pixels two backends may differ in: 1 in 5,000 (15), as Metal and
// OpenGL on a Mac, and as two Vulkan drivers (lavapipe and RADV: 5 to 10 a view). OpenGL against
// Vulkan on Linux is measured where the OpenGL is llvmpipe (under Xvfb, the only OpenGL there):
// llvmpipe draws every edge about 0.2 of a pixel lower and 0.07 to the left of where the spec's
// arithmetic puts it, where both Vulkan drivers put it within 1/32 of a pixel, so the pixels an
// edge passes near show the other side: 837 to 940 a view. Bounded at 1 in 70 (1,100).
fn edge_bound(a: text, b: text) -> integer {
if (a == "gpu_gl" && b == "gpu_vulkan") || (a == "gpu_vulkan" && b == "gpu_gl") { 1100 } else { 15 }
}
// 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 a pixel off an edge may lie apart in a channel: nothing between two GPUs. Apple's
// software renderer, the OpenGL of a Mac with no GPU to give it (a CI runner), rounds a lit
// colour its own way, by 1 or 2 of 255.
fn rounding(first: text) -> integer {
if first == "gpu_gl" && gpu_gl::renderer() == "Apple Software Renderer" { 2 } else { 0 }
}
fn test_a_town_in_perspective_is_one_picture_but_for_pixels_on_an_edge() {
if !display() { return; }
tables = backends();
if len(tables) < 2 { return; }
// the first backend against each other one
first = views(tables[0]);
first_name = gpu::backend_name();
for t in tables {
if t#index == 0 { continue; }
second = views(t);
bound = edge_bound(first_name, gpu::backend_name());
allowed = rounding(first_name);
// The software renderer also puts a face's edge elsewhere in a view from close by: 475 of
// the 76800 pixels in the fourth, measured on a CI runner. One pixel in a hundred still
// tells a town drawn from a town drawn wrongly.
if allowed > 0 { bound = 768; }
assert(len(first) == 4 && len(second) == 4, "both backends drew four views: {len(first)} and {len(second)}");
for i in 0..4 {
differ = 0;
colours = 0;
for p in first[i] {
if apart(p as integer, (second[i][p#index] ?? 0) as integer) > allowed { differ += 1; }
if p != first[i][0] { colours += 1; }
}
assert(colours > 10000, "view {i} shows the town: {colours} pixels are not the first one's colour");
assert(differ <= bound, "view {i}: {differ} of 76800 pixels differ between {first_name} and {gpu::backend_name()}, more than an edge's rounding gives ({bound})");
}
}
}
tests/pixels.loft
// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// A scene drawn by each backend this machine has, against pixels worked out by hand. The window is 64 x 48 and the
// fixed camera's top-left is the world's origin, so cell (0, 0) on layer 0 covers the pixels
// x 0 .. 47, y 0 .. 39 (a cell is 48 across and its ground 40 deep). Without a display every
// test returns at once (`DISPLAY`, or `GRAPHICS_TEST_WINDOW=1` on a Mac).
use gpu;
use gpu_gl;
use gpu_metal;
use gpu_vulkan;
use scene3d;
// The numbers of a face, a light box or an actor as the scene takes them: single precision.
fn s(v: const vector<float>) -> vector<single> {
[for x in v { x as single }]
}
// The backends this machine has: each test's scene is drawn by every one of them, against
// the same pixels. One backend serves a program at a time, so a scene's device is closed
// before the next one's opens.
fn backends() -> vector<i64> {
[for t in [gpu_gl::table(), gpu_metal::table(), gpu_vulkan::table()] if t != 0 { t }]
}
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 SKY = 0xFF94BFE6;
const GREEN = 0xFF00FF00;
const RED = 0xFFFF0000;
const BLUE = 0xFF0000FF;
const BLACK = 0xFF000000;
// The ground of cell (0, 0), lit from that cell; its corners' own light is full.
fn ground() -> vector<float> {
[0.0, -1.0, 4.0, 0.0, 0.0, 0.0, 1.0,
0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0]
}
fn at(c: const vector<u32>, x: integer, y: integer) -> integer {
c[y * 64 + x] ?? 0
}
fn a_face_takes_its_cells_light_once_it_is_given_on(table: i64) {
dev = gpu::open(table, 64, 48, "scene-light") ?? return assert(false, "no device");
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, SKY) ?? return assert(false, "no scene");
// 2016 is six bits of green: full green
_ = scene.add_picture([for _ in 0..256 { 2016 as i32 }]);
// and the ground of the cell east of it (x 48 .. 95 on the screen), lit from cell (0, 0) on layer 1
east = [0.0, -1.0, 4.0, 0.0, 0.0, 1.0, 1.0,
1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 0.0, 0.0, 1.0, 0.0, 1.0, 2.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0];
scene.set_tile(dev, 1, s(ground() + east));
scene.fixed_camera(0, 0);
scene.draw(dev);
c = dev.capture();
assert(at(c, 10, 10) == GREEN && at(c, 47, 39) == GREEN, "no light given yet: the corners' own, full: {at(c, 10, 10):x}");
assert(at(c, 48, 10) == GREEN && at(c, 10, 40) == SKY, "the cells end at y 40: {at(c, 48, 10):x} {at(c, 10, 40):x}");
// its cell dark, the cell east of it bright: only its own cell counts
scene.set_light(s([0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 1.0]));
scene.draw(dev);
c = dev.capture();
assert(at(c, 10, 10) == BLACK, "its cell's light is 0: {at(c, 10, 10):x}");
scene.set_light(s([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]));
scene.draw(dev);
c = dev.capture();
assert(at(c, 10, 10) == GREEN, "and full again, with no face given again: {at(c, 10, 10):x}");
// the same cell on another layer does not light it
scene.set_light(s([1.0, 0.0, 0.0, 1.0, 1.0, 0.0]));
scene.draw(dev);
c = dev.capture();
assert(at(c, 10, 10) == GREEN, "layer 1's light is not layer 0's: {at(c, 10, 10):x}");
assert(at(c, 56, 10) == BLACK, "and the face lit from layer 1 takes it: {at(c, 56, 10):x}");
assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
}
fn test_a_face_takes_its_cells_light_once_it_is_given() {
if !display() { return; }
for table in backends() { a_face_takes_its_cells_light_once_it_is_given_on(table); }
}
fn an_actor_stands_over_the_land_and_the_overlay_over_both_on(table: i64) {
dev = gpu::open(table, 64, 48, "scene-actor") ?? return assert(false, "no device");
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, SKY) ?? return assert(false, "no scene");
_ = scene.add_picture([for _ in 0..256 { 2016 as i32 }]);
// 63488 is five bits of red
_ = scene.add_picture([for _ in 0..256 { 63488 as i32 }]);
scene.set_tile(dev, 1, s(ground()));
// A red card half a cell wide and tall, its foot in the middle of the cell: x 12 .. 35, from
// y = 0.5 * 40 = 20 up to 20 - 24 = -4.
scene.set_actors(s([1.0, 1.0, 0.5, 0.0, 0.5, 0.5, 1.0, 0.0, 0.5, 1.0, 0.0]), -1);
// Two overlay pixels, each four screen pixels square: blue, then clear. 31 is five bits of blue.
scene.set_overlay(dev, [31 as i32, scene3d::NONE as i32], 2, 1, 4);
scene.fixed_camera(0, 0);
scene.draw(dev);
c = dev.capture();
assert(at(c, 24, 10) == RED && at(c, 13, 19) == RED, "the card, in front of the ground behind it: {at(c, 24, 10):x}");
assert(at(c, 11, 10) == GREEN && at(c, 36, 10) == GREEN && at(c, 24, 21) == GREEN, "and nothing past its edges: {at(c, 11, 10):x} {at(c, 36, 10):x} {at(c, 24, 21):x}");
assert(at(c, 0, 0) == BLUE && at(c, 3, 3) == BLUE, "the overlay's first pixel, four by four: {at(c, 0, 0):x}");
assert(at(c, 5, 2) == GREEN && at(c, 2, 4) == GREEN, "its clear pixel and what lies past it show the scene: {at(c, 5, 2):x} {at(c, 2, 4):x}");
// A picture red on its left half and blue on its right, on a card of the same place and
// size: as it is, red is on the left; mirrored, on the right.
halves: vector<i32> = [];
for _ in 0..16 { for x in 0..16 { halves += [(if x < 8 { 63488 } else { 31 }) as i32]; } }
both = scene.add_picture(halves);
scene.set_actors(s([1.0, both as float, 0.5, 0.0, 0.5, 0.5, 1.0, 0.0, 0.5, 1.0, 0.0]), -1);
scene.draw(dev);
c = dev.capture();
assert(at(c, 14, 10) == RED && at(c, 33, 10) == BLUE, "as it is: {at(c, 14, 10):x} {at(c, 33, 10):x}");
scene.set_actors(s([1.0, both as float, 0.5, 0.0, 0.5, 0.5, 1.0, 0.0, 0.5, 1.0, 1.0]), -1);
scene.draw(dev);
c = dev.capture();
assert(at(c, 14, 10) == BLUE && at(c, 33, 10) == RED, "mirrored: {at(c, 14, 10):x} {at(c, 33, 10):x}");
// Turned a quarter clockwise about its foot, the card lies to the right of the foot: its
// top (the picture's left half is still on the card's own left, now up the screen) at x 24 .. 47.
scene.set_actors(s([1.0, 1.0, 0.5, 0.0, 0.5, 0.5, 1.0, 90.0, 0.5, 1.0, 0.0]), -1);
scene.draw(dev);
c = dev.capture();
assert(at(c, 40, 14) == RED && at(c, 20, 14) == GREEN && at(c, 30, 2) == GREEN, "turned a quarter, it lies east of its foot: {at(c, 40, 14):x} {at(c, 20, 14):x} {at(c, 30, 2):x}");
// the overlay taken away
scene.set_overlay(dev, [], 0, 0, 0);
scene.draw(dev);
c = dev.capture();
assert(at(c, 0, 0) == GREEN, "no overlay: {at(c, 0, 0):x}");
}
fn test_an_actor_stands_over_the_land_and_the_overlay_over_both() {
if !display() { return; }
for table in backends() { an_actor_stands_over_the_land_and_the_overlay_over_both_on(table); }
}
fn the_free_camera_looks_where_it_is_pointed_on(table: i64) {
dev = gpu::open(table, 64, 48, "scene-free") ?? return assert(false, "no device");
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, SKY) ?? return assert(false, "no scene");
_ = scene.add_picture([for _ in 0..256 { 2016 as i32 }]);
scene.set_tile(dev, 1, s(ground()));
// From the south and above, looking at the middle of the cell: it is in the middle of the
// frame, and the sky is over it.
scene.free_camera((0.5, 1.5, 3.0), (0.5, 0.0, 0.5), 50.0);
scene.draw(dev);
c = dev.capture();
assert(at(c, 32, 24) == GREEN, "the point looked at is the frame's middle: {at(c, 32, 24):x}");
assert(at(c, 32, 2) == SKY && at(c, 2, 24) == SKY, "sky above and beside: {at(c, 32, 2):x} {at(c, 2, 24):x}");
// The cell's corners, projected by hand (50 degrees high, 64 x 48): the far edge at
// y 20.04 from x 24.30 to 39.70, the near edge at y 29.32 from x 21.65 to 42.35.
assert(at(c, 32, 19) == SKY && at(c, 32, 28) == GREEN && at(c, 32, 30) == SKY, "its far and near edges: {at(c, 32, 19):x} {at(c, 32, 28):x} {at(c, 32, 30):x}");
assert(at(c, 20, 28) == SKY && at(c, 22, 28) == GREEN && at(c, 41, 28) == GREEN && at(c, 43, 28) == SKY, "wide near the eye: {at(c, 20, 28):x} {at(c, 22, 28):x} {at(c, 41, 28):x} {at(c, 43, 28):x}");
assert(at(c, 25, 21) == GREEN && at(c, 39, 21) == GREEN && at(c, 40, 21) == SKY, "narrow far from it: {at(c, 25, 21):x} {at(c, 39, 21):x} {at(c, 40, 21):x}");
// Looking away from it: nothing but sky.
scene.free_camera((0.5, 1.5, 3.0), (0.5, 1.5, 9.0), 50.0);
scene.draw(dev);
c = dev.capture();
assert(at(c, 32, 24) == SKY && at(c, 32, 46) == SKY, "turned round, the cell is behind the eye: {at(c, 32, 24):x}");
// Back to the fixed camera: the cell at the top left again.
scene.fixed_camera(0, 0);
scene.draw(dev);
c = dev.capture();
assert(at(c, 10, 10) == GREEN && at(c, 60, 44) == SKY, "the fixed camera again: {at(c, 10, 10):x}");
}
fn test_the_free_camera_looks_where_it_is_pointed() {
if !display() { return; }
for table in backends() { the_free_camera_looks_where_it_is_pointed_on(table); }
}
fn a_scene_far_from_the_origin_is_drawn_as_one_near_it_on(table: i64) {
dev = gpu::open(table, 64, 48, "scene-far") ?? return assert(false, "no device");
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, SKY) ?? return assert(false, "no scene");
_ = scene.add_picture([for _ in 0..256 { 2016 as i32 }]);
// the ground of cell (0, 60), 60 rows south of the origin as a town's street is, and the camera
// over it: its depth is measured from the camera, not from the origin, so it is not cut off
far = [0.0, -1.0, 4.0, 0.0, 60.0, 0.0, 1.0,
0.0, 0.0, 60.0, 0.0, 0.0, 1.0, 1.0, 0.0, 60.0, 1.0, 0.0, 1.0, 1.0, 0.0, 61.0, 1.0, 1.0, 1.0, 0.0, 0.0, 61.0, 0.0, 1.0, 1.0];
scene.set_tile(dev, 1, s(far));
scene.fixed_camera(0, 60 * 40);
scene.draw(dev);
c = dev.capture();
assert(at(c, 10, 10) == GREEN && at(c, 10, 40) == SKY, "the cell 60 rows south: {at(c, 10, 10):x} {at(c, 10, 40):x}");
}
fn test_a_scene_far_from_the_origin_is_drawn_as_one_near_it() {
if !display() { return; }
for table in backends() { a_scene_far_from_the_origin_is_drawn_as_one_near_it_on(table); }
}
// A picture red on its left half and blue on its right.
fn halves() -> vector<i32> {
out: vector<i32> = [];
for _ in 0..16 { for x in 0..16 { out += [(if x < 8 { 63488 } else { 31 }) as i32]; } }
out
}
fn a_card_turns_to_face_the_free_camera_on(table: i64) {
dev = gpu::open(table, 64, 48, "scene-facing") ?? return assert(false, "no device");
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, SKY) ?? return assert(false, "no scene");
both = scene.add_picture(halves());
// A card a cell wide and tall, its foot at (0.5, 0, 0.5), seen level from three cells east.
// It stands across the view: 50 degrees high on 64 x 48, half a cell at three cells is
// 0.5 / 3 / tan 25 * 24 = 8.58 pixels each way from the middle, x 23.4 .. 40.6, y 15.4 .. 32.6.
// The picture's left is on the left. Unturned it would stand edge-on and show nothing.
scene.set_actors(s([1.0, both as float, 0.5, 0.0, 0.5, 1.0, 1.0, 0.0, 0.5, 1.0, 0.0]), -1);
scene.free_camera((3.5, 0.5, 0.5), (0.5, 0.5, 0.5), 50.0);
scene.draw(dev);
c = dev.capture();
assert(at(c, 26, 24) == RED && at(c, 38, 24) == BLUE, "facing east, its left on the left: {at(c, 26, 24):x} {at(c, 38, 24):x}");
assert(at(c, 30, 17) == RED && at(c, 30, 31) == RED, "a cell tall: {at(c, 30, 17):x} {at(c, 30, 31):x}");
assert(at(c, 22, 24) == SKY && at(c, 42, 24) == SKY && at(c, 32, 14) == SKY && at(c, 32, 34) == SKY,
"and no larger: {at(c, 22, 24):x} {at(c, 42, 24):x} {at(c, 32, 14):x} {at(c, 32, 34):x}");
// From three cells north it has turned round: the same picture, its left still on the left.
scene.free_camera((0.5, 0.5, -2.5), (0.5, 0.5, 0.5), 50.0);
scene.draw(dev);
c = dev.capture();
assert(at(c, 26, 24) == RED && at(c, 38, 24) == BLUE, "facing north: {at(c, 26, 24):x} {at(c, 38, 24):x}");
assert(at(c, 22, 24) == SKY && at(c, 42, 24) == SKY, "the same size: {at(c, 22, 24):x} {at(c, 42, 24):x}");
// The fixed camera again: it stands as it stood, x 0 .. 47, from y = 20 up.
scene.fixed_camera(0, 0);
scene.draw(dev);
c = dev.capture();
assert(at(c, 10, 10) == RED && at(c, 40, 10) == BLUE && at(c, 50, 10) == SKY, "for the fixed camera, in its plane: {at(c, 10, 10):x} {at(c, 40, 10):x} {at(c, 50, 10):x}");
}
fn test_a_card_turns_to_face_the_free_camera() {
if !display() { return; }
for table in backends() { a_card_turns_to_face_the_free_camera_on(table); }
}
fn the_hero_is_seen_through_a_wall_the_free_camera_looks_at_on(table: i64) {
dev = gpu::open(table, 64, 48, "scene-through") ?? return assert(false, "no device");
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, SKY) ?? return assert(false, "no scene");
_ = scene.add_picture([for _ in 0..256 { 2016 as i32 }]);
_ = scene.add_picture([for _ in 0..256 { 63488 as i32 }]);
// A green wall a cell wide and tall at z = 1.5, in group 5, and a red card behind it, its
// foot at (0.5, 0, 0.5); the eye level with both at z = 4.5. The wall is three cells off:
// 8.58 pixels each way from the middle (x 23.4 .. 40.6). The card is four: 6.43 (x 25.6 .. 38.4).
wall = [0.0, 5.0, 4.0, 0.0, 0.0, scene3d::NO_LIGHT as float, 1.0,
0.0, 1.0, 1.5, 0.0, 0.0, 1.0, 1.0, 1.0, 1.5, 1.0, 0.0, 1.0, 1.0, 0.0, 1.5, 1.0, 1.0, 1.0, 0.0, 0.0, 1.5, 0.0, 1.0, 1.0];
scene.set_tile(dev, 1, s(wall));
card = [7.0, 1.0, 0.5, 0.0, 0.5, 1.0, 1.0, 0.0, 0.5, 1.0, 0.0];
scene.free_camera((0.5, 0.5, 4.5), (0.5, 0.5, 0.5), 50.0);
// nobody is kept in view: the wall hides the card
scene.set_actors(s(card), -1);
scene.draw(dev);
c = dev.capture();
assert(at(c, 32, 24) == GREEN && at(c, 24, 24) == GREEN, "the wall in front: {at(c, 32, 24):x} {at(c, 24, 24):x}");
// the card is the hero's: the wall is gone, and where only the wall was is sky
scene.set_actors(s(card), 7);
scene.draw(dev);
c = dev.capture();
assert("{scene.hidden_groups()}" == "[5]", "the wall is cut away: {scene.hidden_groups()}");
assert(at(c, 32, 24) == RED && at(c, 27, 24) == RED && at(c, 37, 24) == RED, "the hero is seen: {at(c, 32, 24):x}");
assert(at(c, 24, 24) == SKY && at(c, 40, 24) == SKY, "and the wall is not: {at(c, 24, 24):x} {at(c, 40, 24):x}");
// from behind the hero the wall is no longer between them
scene.free_camera((0.5, 0.5, -3.5), (0.5, 0.5, 0.5), 50.0);
scene.draw(dev);
c = dev.capture();
assert("{scene.hidden_groups()}" == "[]", "shown again: {scene.hidden_groups()}");
// the wall is five cells off now, 5.15 pixels each way (x 26.9 .. 37.1): all of it behind the card
assert(at(c, 32, 24) == RED && at(c, 24, 24) == SKY, "the hero in front of the wall: {at(c, 32, 24):x} {at(c, 24, 24):x}");
// without the card the wall is there
scene.set_actors(s([]), -1);
scene.draw(dev);
c = dev.capture();
assert(at(c, 32, 24) == GREEN && at(c, 27, 24) == GREEN && at(c, 25, 24) == SKY, "the wall, shown: {at(c, 32, 24):x} {at(c, 27, 24):x} {at(c, 25, 24):x}");
}
fn test_the_hero_is_seen_through_a_wall_the_free_camera_looks_at() {
if !display() { return; }
for table in backends() { the_hero_is_seen_through_a_wall_the_free_camera_looks_at_on(table); }
}
fn a_pixel_on_a_texels_edge_takes_the_texel_before_it_on(table: i64) {
dev = gpu::open(table, 64, 48, "scene-ties") ?? return assert(false, "no device");
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, SKY) ?? return assert(false, "no scene");
// The picture's first row red, the rest green. On the ground of cell (0, 0) a texel is 40 / 16
// = 2.5 pixels deep, so the middle of pixel row 2 (y = 2.5) lies exactly on the edge between
// the first texel row and the second. The CPU implementation takes the texel before the edge;
// so must this one, or every second texel row is a pixel off against it.
rows: vector<i32> = [];
for y in 0..16 { for _ in 0..16 { rows += [(if y == 0 { 63488 } else { 2016 }) as i32]; } }
_ = scene.add_picture(rows);
scene.set_tile(dev, 1, s(ground()));
scene.fixed_camera(0, 0);
scene.draw(dev);
c = dev.capture();
assert(at(c, 10, 1) == RED && at(c, 10, 3) == GREEN, "the rows beside the edge: {at(c, 10, 1):x} {at(c, 10, 3):x}");
assert(at(c, 10, 2) == RED && at(c, 40, 2) == RED, "on the edge, the texel before it: {at(c, 10, 2):x} {at(c, 40, 2):x}");
// the same at the next edge that falls on a pixel's middle: y = 7.5, between texel rows 2 and 3;
// and across, where a texel is 3 pixels wide and no edge falls on a middle
assert(at(c, 10, 7) == GREEN && at(c, 2, 1) == RED && at(c, 3, 1) == RED, "elsewhere: {at(c, 10, 7):x} {at(c, 2, 1):x}");
}
fn test_a_pixel_on_a_texels_edge_takes_the_texel_before_it() {
if !display() { return; }
for table in backends() { a_pixel_on_a_texels_edge_takes_the_texel_before_it_on(table); }
}
// The ground of cell (cx, 0) under picture `pic`, lit from that cell: u runs east over the
// cell's 48 pixels, v south over its 40.
fn ground_of(pic: integer, cx: float) -> vector<float> {
[pic as float, -1.0, 4.0, cx, 0.0, 0.0, 1.0,
cx, 0.0, 0.0, 0.0, 0.0, 1.0, cx + 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, cx + 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, cx, 0.0, 1.0, 0.0, 1.0, 1.0]
}
// The 48 x 40 picture's texel (x, y): its red x times 5, its green y times 6, its blue 0x40 —
// no two alike.
fn texel_of(x: integer, y: integer) -> integer {
0xFF000000 + x * 5 * 0x10000 + y * 6 * 0x100 + 0x40
}
fn a_picture_of_any_size_shows_every_texel_on(table: i64) {
dev = gpu::open(table, 64, 48, "scene-image") ?? return assert(false, "no device");
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, SKY) ?? return assert(false, "no scene");
// a 16 x 16 picture first, all red: it takes the atlas's first slot
red = scene.add_picture([for _ in 0..256 { 63488 as i32 }]);
// 48 x 40 texels: 3 x 3 slots, its last row of slots partly used; texel (5, 5) clear
argb: vector<u32> = [];
for y in 0..40 {
for x in 0..48 { argb += [(if x == 5 && y == 5 { 0x7FFFFFFF } else { texel_of(x, y) }) as u32]; }
}
big = scene.add_image(argb, 48);
// and a 16 x 16 one after it, all blue: on the first slot the two before it left free
blue = scene.add_picture([for _ in 0..256 { 31 as i32 }]);
assert(red == 0 && big == 1 && blue == 2, "numbered as they came: {red} {big} {blue}");
assert(scene.add_image([], 4) == -1 && scene.add_image([0 as u32], 1025) == -1, "none, or wider than the atlas");
// fill the rest of the first row of slots (64 across: 1 + 3 + 1 taken, 59 more); the second
// row's first slot is free and its next is the big one's, so a 32 x 16 picture fits first at
// that row's fifth slot: laid over the big one's, it would show in the pixels below
for _ in 0..59 { _ = scene.add_picture([for _ in 0..256 { 0 as i32 }]); }
wide = scene.add_image([for _ in 0..512 { 0xFFFFFF00 as u32 }], 32);
assert(wide == 62, "after 62 others: {wide}");
// the big one over cell (0, 0): a texel a pixel, x 0 .. 47, y 0 .. 39; the blue one east of it
scene.set_tile(dev, 1, s(ground_of(big, 0.0) + ground_of(blue, 1.0)));
scene.fixed_camera(0, 0);
scene.draw(dev);
c = dev.capture();
wrong = 0;
first = "";
for y in 0..40 {
for x in 0..48 {
want = if x == 5 && y == 5 { SKY } else { texel_of(x, y) };
if at(c, x, y) != want {
if wrong == 0 { first = "({x}, {y}) {at(c, x, y):x} for {want:x}"; }
wrong += 1;
}
}
}
assert(wrong == 0, "every pixel its own texel, the clear one the sky: {wrong} wrong, first {first}");
assert(at(c, 48, 0) == BLUE && at(c, 63, 39) == BLUE && at(c, 10, 40) == SKY, "the blue one beside it: {at(c, 48, 0):x} {at(c, 63, 39):x}");
assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
}
fn test_a_picture_of_any_size_shows_every_texel() {
if !display() { return; }
for table in backends() { a_picture_of_any_size_shows_every_texel_on(table); }
}
fn a_screen_is_drawn_as_large_as_fits_in_the_window_on(table: i64) {
dev = gpu::open(table, 64, 48, "scene-fit") ?? return assert(false, "no device");
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, SKY) ?? return assert(false, "no scene");
// the picture's first row red, the rest green, on the ground of cell (0, 0)
rows: vector<i32> = [];
for y in 0..16 { for _ in 0..16 { rows += [(if y == 0 { 63488 } else { 2016 }) as i32]; } }
_ = scene.add_picture(rows);
scene.set_tile(dev, 1, s(ground()));
scene.fixed_camera(0, 0);
// A screen 32 x 48 in the 64 x 48 window: as it is, x 16 .. 47, black beside it. The cell is
// 48 across, so it fills the screen's width; its ground ends at y 40, the sky under it.
scene.resize(32, 48);
scene.draw(dev);
c = dev.capture();
assert(at(c, 15, 10) == BLACK && at(c, 48, 10) == BLACK && at(c, 2, 44) == BLACK, "black beside the screen: {at(c, 15, 10):x} {at(c, 48, 10):x}");
assert(at(c, 16, 10) == GREEN && at(c, 47, 10) == GREEN && at(c, 20, 1) == RED, "the cell across the screen: {at(c, 16, 10):x} {at(c, 47, 10):x} {at(c, 20, 1):x}");
assert(at(c, 20, 44) == SKY && at(c, 46, 41) == SKY, "the sky inside it: {at(c, 20, 44):x}");
// A screen 32 x 24: twice as large, the whole window. A texel row is 2.5 screen pixels
// deep, 5 of the window's: the red row is y 0 .. 4.
scene.resize(32, 24);
scene.draw(dev);
c = dev.capture();
assert(at(c, 0, 0) == RED && at(c, 63, 4) == RED && at(c, 10, 5) == GREEN, "twice as large: {at(c, 0, 0):x} {at(c, 63, 4):x} {at(c, 10, 5):x}");
assert(at(c, 0, 47) == GREEN && at(c, 63, 47) == GREEN, "no bars: {at(c, 0, 47):x}");
}
fn test_a_screen_is_drawn_as_large_as_fits_in_the_window() {
if !display() { return; }
for table in backends() { a_screen_is_drawn_as_large_as_fits_in_the_window_on(table); }
}
tests/record.loft
// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// What a scene asks of a backend, read from the recording one, and which walls it cuts away:
// no display is needed. The expected logs and groups are worked out by hand.
use gpu;
use gpu_record;
use scene3d;
// The numbers of a face, a light box or an actor as the scene takes them: single precision.
fn s(v: const vector<float>) -> vector<single> {
[for x in v { x as single }]
}
fn lines(of: const vector<text>) -> text {
out = "";
for l in of { out += "{l}\n"; }
out
}
// A face of four corners: the picture, its group, where its light comes from, the corners.
fn quad(pic: integer, group: integer, lit: (integer, integer, integer), corners: const vector<float>) -> vector<float> {
out = [pic as float, group as float, 4.0, lit.0 as float, lit.1 as float, lit.2 as float, 1.0];
out += corners;
out
}
// The ground of cell (x, z) on layer 0, lit from its own cell.
fn ground(x: float, z: float) -> vector<float> {
quad(0, -1, (x as integer, z as integer, 0), [x, 0.0, z, 0.0, 0.0, 1.0, x + 1.0, 0.0, z, 1.0, 0.0, 1.0, x + 1.0, 0.0, z + 1.0, 1.0, 1.0, 1.0, x, 0.0, z + 1.0, 0.0, 1.0, 1.0])
}
// The south side of a block a layer high on cell (x, z), in group `group`.
fn south(x: float, z: float, group: integer) -> vector<float> {
quad(0, group, (0, 0, scene3d::NO_LIGHT), [x, 1.0, z + 1.0, 0.0, 0.0, 1.0, x + 1.0, 1.0, z + 1.0, 1.0, 0.0, 1.0, x + 1.0, 0.0, z + 1.0, 1.0, 1.0, 1.0, x, 0.0, z + 1.0, 0.0, 1.0, 1.0])
}
// The top of that block.
fn top(x: float, z: float, group: integer) -> vector<float> {
quad(0, group, (0, 0, scene3d::NO_LIGHT), [x, 1.0, z, 0.0, 0.0, 1.0, x + 1.0, 1.0, z, 1.0, 0.0, 1.0, x + 1.0, 1.0, z + 1.0, 1.0, 1.0, 1.0, x, 1.0, z + 1.0, 0.0, 1.0, 1.0])
}
fn open() -> gpu::Device {
gpu_record::reset();
gpu::open(gpu_record::table(), 800, 480, "scene")!
}
fn test_a_scene_is_two_pipelines_an_atlas_and_a_light_map() {
dev = open();
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, 0xFF94BFE6)!;
// The land pipeline: a place, a point on the picture, the picture's corner in the atlas and
// its size, the light's cell and factor, an own light; one matrix and two arrays of 64 for the torches; the atlas, the
// light map, the torches' cells and their reaches. It tests and writes
// depth (2). The overlay's: a place and a point on the picture, one texture, no depth.
made = lines([
"open 1 800x480 \"scene\"",
"pipeline 2 vertex 3 2 4 4 1 instance block 16x1@0 4x64@16 4x64@272 size 528 textures 4",
" state shape 0 depth 2 blend 0 cull 0 into 0",
"pipeline 3 vertex 2 2 instance block size 0 textures 1",
" state shape 0 depth 0 blend 0 cull 0 into 0",
"texture 4 1024x1024 colour",
"texture_nearest 4 on",
"texture 5 256x2048 colour",
"texture_nearest 5 on",
]);
assert(gpu_record::log().starts_with(made), "what a scene is made of:\n{gpu_record::log()}");
assert(scene.offers_free_camera(), "an implementation on a GPU offers the free camera");
}
fn test_a_frame_draws_each_tile_that_holds_faces_then_the_actors() {
dev = open();
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, 0xFF94BFE6)!;
assert(scene.add_picture([for _ in 0..256 { 2016 as i32 }]) == 0, "the first picture is number 0");
assert(scene.add_picture([2016 as i32]) == -1, "too few texels are no picture");
// tile 7: two faces of four corners, six vertices each; tile 9: one; tile 8 given and dropped
scene.set_tile(dev, 7, s(ground(0.0, 0.0) + ground(1.0, 0.0)));
scene.set_tile(dev, 8, s(ground(5.0, 5.0)));
scene.set_tile(dev, 9, s(ground(2.0, 0.0)));
scene.drop_tile(8);
assert(scene.tiles() == 2, "two tiles hold faces, got {scene.tiles()}");
// one actor of picture 0: a card of two triangles
scene.set_actors(s([1.0, 0.0, 0.5, 0.0, 0.5, 1.0, 1.0, 0.0, 0.5, 1.0, 0.0]), -1);
scene.fixed_camera(0, 0);
before = gpu_record::log();
scene.draw(dev);
// The block is the matrix (its first float 2 * 48 / 800 = 0.12) and the torches' two arrays,
// dark: its last float is 0. Handles: the device, two pipelines, the atlas (4), the light
// map (5), the torches' cells (6) and reaches (7), the cards (8), the overlay's quad (9) and
// picture (10), then the tiles' buffers 11, 12 and 13.
drawn = lines([
"begin 0 clear ff94bfe6",
" bind 2",
" uniforms floats 528 first 0.120 last 0.000",
" sample 0 texture 4",
" sample 1 texture 5",
" sample 2 texture 6",
" sample 3 texture 7",
" vertices 11",
" draw from 0 count 12 copies 0",
" vertices 13",
" draw from 0 count 6 copies 0",
" vertices 8",
" draw from 0 count 6 copies 0",
"end",
]);
got = gpu_record::log()[len(before)..];
assert(got == drawn, "a frame:\n{got}");
assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
}
fn test_the_walls_in_front_of_the_hero_are_cut_away_and_shown_again() {
dev = open();
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, 0xFF94BFE6)!;
_ = scene.add_picture([for _ in 0..256 { 2016 as i32 }]);
// Two blocks: one on cell (4, 3), group 11, south of where the hero will stand; one on cell
// (8, 0), group 12, far to the east.
scene.set_tile(dev, 1, s(top(4.0, 3.0, 11) + south(4.0, 3.0, 11) + top(8.0, 0.0, 12) + south(8.0, 0.0, 12)));
// The hero's card: a cell wide and tall, its foot at (4.5, 0, 2.6). On the screen it lies
// from y = 2.6 * 40 - 48 = 56 to 104 and x = 192 to 240. Block 11's top lies from
// y = 3 * 40 - 48 = 72 to 112 over the same x, and is nearer (further south and higher): cut.
// Block 12 is at x = 384 to 432: not over the card.
hero = [1.0, 0.0, 4.5, 0.0, 2.6, 1.0, 1.0, 0.0, 0.5, 1.0, 0.0];
scene.set_actors(s(hero), 1);
assert("{scene.hidden_groups()}" == "[11]", "the block south of the hero is cut away: {scene.hidden_groups()}");
// The hero south of the block, at z = 4.5: the block is behind it, and is shown again.
scene.set_actors(s([1.0, 0.0, 4.5, 0.0, 4.5, 1.0, 1.0, 0.0, 0.5, 1.0, 0.0]), 1);
assert("{scene.hidden_groups()}" == "[]", "behind the hero it is shown again: {scene.hidden_groups()}");
// No actor is the one never hidden: nothing is cut for it.
scene.set_actors(s(hero), -1);
assert("{scene.hidden_groups()}" == "[]", "nobody to keep in view: {scene.hidden_groups()}");
}
// The west side of a block a layer high on cell (x, z), in group `group`.
fn west(x: float, z: float, group: integer) -> vector<float> {
quad(0, group, (0, 0, scene3d::NO_LIGHT), [x, 1.0, z, 0.0, 0.0, 1.0, x, 1.0, z + 1.0, 1.0, 0.0, 1.0, x, 0.0, z + 1.0, 1.0, 1.0, 1.0, x, 0.0, z, 0.0, 1.0, 1.0])
}
fn test_the_free_camera_cuts_away_the_walls_between_its_eye_and_the_hero() {
dev = open();
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, 0xFF94BFE6)!;
_ = scene.add_picture([for _ in 0..256 { 2016 as i32 }]);
// Three walls round a hero whose foot is at (4.5, 0, 2.5), its card a cell wide and tall:
// group 21, a block on cell (4, 3), south of it; group 22, the west side of cell (2, 2), at
// x = 2 from z 2 to 3; group 23, a side at x = 4.9 from z 2 to 4, which passes through the
// card's east edge when it faces south: the lines end a quarter of the card inside its edges,
// so a wall at its edge is not between. Each in a tile of its own.
scene.set_tile(dev, 1, s(top(4.0, 3.0, 21) + south(4.0, 3.0, 21)));
scene.set_tile(dev, 2, s(west(2.0, 2.0, 22)));
scene.set_tile(dev, 3, s(west(4.9, 2.0, 23) + west(4.9, 3.0, 23)));
hero = [1.0, 0.0, 4.5, 0.0, 2.5, 1.0, 1.0, 0.0, 0.5, 1.0, 0.0];
// From the south and above: the line to the card's middle (4.5, 0.5, 2.5) is at y = 1 after
// 0.8 of its way, where z = 9 - 0.8 * 6.5 = 3.8: through the block's top.
scene.free_camera((4.5, 3.0, 9.0), (4.5, 0.5, 2.5), 60.0);
scene.set_actors(s(hero), 1);
assert("{scene.hidden_groups()}" == "[21]", "the block between the eye and the hero: {scene.hidden_groups()}");
// Level with the hero: the line is at z = 4 at y = 0.5, through the block's south side.
scene.free_camera((4.5, 0.5, 9.0), (4.5, 0.5, 2.5), 60.0);
assert("{scene.hidden_groups()}" == "[21]", "through its side: {scene.hidden_groups()}");
// From the north the block is behind the hero. The camera alone is given: the actors stay.
scene.free_camera((4.5, 3.0, -4.0), (4.5, 0.5, 2.5), 60.0);
assert("{scene.hidden_groups()}" == "[]", "behind the hero it is shown again: {scene.hidden_groups()}");
// From high over the block: the line to the middle is at y = 1 where z = 4.5 - 2 * 8 / 8.5 =
// 2.62, north of the block's top.
scene.free_camera((4.5, 9.0, 4.5), (4.5, 0.5, 2.5), 60.0);
assert("{scene.hidden_groups()}" == "[]", "over the block, the hero is seen: {scene.hidden_groups()}");
// From the west, level: the line crosses x = 2 at z = 2.5, y = 0.5.
scene.free_camera((0.5, 0.5, 2.5), (4.5, 0.5, 2.5), 60.0);
assert("{scene.hidden_groups()}" == "[22]", "the side west of the hero: {scene.hidden_groups()}");
// The actors first, then the camera: the same walls.
scene.set_actors(s([1.0, 0.0, 4.5, 0.0, 6.5, 1.0, 1.0, 0.0, 0.5, 1.0, 0.0]), 1);
assert("{scene.hidden_groups()}" == "[]", "the hero south of every wall, seen from the west: {scene.hidden_groups()}");
scene.set_actors(s(hero), 1);
scene.free_camera((4.5, 3.0, 9.0), (4.5, 0.5, 2.5), 60.0);
assert("{scene.hidden_groups()}" == "[21]", "whichever is given last: {scene.hidden_groups()}");
// Nobody to keep in view: nothing is cut, whatever was.
scene.set_actors(s(hero), -1);
assert("{scene.hidden_groups()}" == "[]", "nobody to keep in view: {scene.hidden_groups()}");
// The fixed camera after the free one cuts as the fixed camera does: seen from the west only
// the side at x = 2 is between; on the fixed camera's screen the card lies from y = 2.5 * 40
// - 48 = 52 to 100 at x 192 to 240, the block's top over it from y = 72, and nearer.
scene.free_camera((0.5, 0.5, 2.5), (4.5, 0.5, 2.5), 60.0);
scene.set_actors(s(hero), 1);
assert("{scene.hidden_groups()}" == "[22]", "the free camera's: {scene.hidden_groups()}");
// The side at x = 4.9 is cut too: seen from the south it is a strip one pixel wide (x 235) from
// y = 32 to 160, over the card, and its south end (z = 4) is nearer than the card.
scene.fixed_camera(0, 0);
assert("{scene.hidden_groups()}" == "[21,23]", "the fixed camera's: {scene.hidden_groups()}");
}
fn test_a_box_of_light_is_one_write_and_a_few_where_it_crosses_the_maps_edge() {
dev = open();
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, 0xFF94BFE6)!;
before = gpu_record::log();
// Three cells by two on layer 1, from cell (10, 20): one write of 3 x 2 at (10, 20 + 256).
// Its first light is 1: 65535, red ff and green ff under a full alpha.
scene.set_light(s([1.0, 10.0, 20.0, 3.0, 2.0, 1.0, 0.5, 0.0, 0.25, 0.75, 1.0]));
// Four cells in a row from cell (254, 0) on layer 0: the map is 256 cells wide, so two go at
// x 254 and two at x 0. The first light is 0.5: 32768, red 80 and green 00.
scene.set_light(s([0.0, 254.0, 0.0, 4.0, 1.0, 0.5, 0.5, 1.0, 1.0]));
// A cell west of the origin is the map's last column.
scene.set_light(s([0.0, -1.0, 0.0, 1.0, 1.0, 0.0]));
// Too few lights for the box: nothing is written.
scene.set_light(s([0.0, 0.0, 0.0, 2.0, 2.0, 1.0]));
got = gpu_record::log()[len(before)..];
want = lines([
"texture_put 5 at 10,276 3x2 first ffffff00",
"texture_put 5 at 254,0 2x1 first ff800000",
"texture_put 5 at 0,0 2x1 first ffffff00",
"texture_put 5 at 255,0 1x1 first ff000000",
]);
assert(got == want, "the light's writes:\n{got}");
}
fn test_a_torch_is_its_reach_once_and_nine_numbers_a_frame() {
dev = open();
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, 0xFF94BFE6)!;
assert(scene.offers_torches(), "an implementation on a GPU lights torches of their own");
before = gpu_record::log();
// Torch 7 on layer 0: a reach of 3 x 2 cells from cell (4, 9), full at its first cell. It
// takes the first square of the reach atlas (16 x 16 texels at 0, 0; the reach is 65535:
// red ff, green ff), and the cells of its box name it: square 0 plus one, in red — the
// strongest there; green, blue and alpha hold the second to the fourth.
assert(scene.set_torch_reach(s([7.0, 0.0, 4.0, 9.0, 3.0, 2.0, 1.0, 0.5, 0.25, 0.5, 0.5, 0.25])), "the reach is kept");
// Torch 8 on the same cells, weaker at the first: it is the second there, in green (square 1
// plus one), and its square is the atlas's second, at x 16. 0.5 is 32768: red 80, green 00.
assert(scene.set_torch_reach(s([8.0, 0.0, 4.0, 9.0, 1.0, 1.0, 0.5])), "a second reach");
assert(scene.torches() == 2, "two torches, got {scene.torches()}");
got = gpu_record::log()[len(before)..];
want = lines([
"texture_put 7 at 0,0 16x16 first ffffff00",
"texture_put 6 at 4,9 3x2 first 00010000",
"texture_put 7 at 16,0 16x16 first ff800000",
"texture_put 6 at 4,9 1x1 first 00010200",
]);
assert(got == want, "two reaches given:\n{got}");
// A box too large, or with too few numbers, is refused and nothing is written.
assert(!scene.set_torch_reach(s([9.0, 0.0, 0.0, 0.0, 16.0, 1.0, 1.0])), "16 cells across is too many");
assert(!scene.set_torch_reach(s([9.0, 0.0, 0.0, 0.0, 2.0, 2.0, 1.0])), "four cells need four numbers");
// A frame: the torches' numbers go into the block and nothing is written to a texture. The
// block's last float is the last torch's colour's fourth, 0.
scene.set_torches(s([7.0, 4.0, 9.0, 0.0, 1.0, 0.9, 1.0, 0.8, 0.5]));
mid = gpu_record::log();
scene.fixed_camera(0, 0);
scene.draw(dev);
frame = gpu_record::log()[len(mid)..];
assert(!frame.contains("texture_put"), "a flicker writes no texture:\n{frame}");
assert(frame.contains(" uniforms floats 528 first 0.120 last 0.000\n"), "the torches ride in the block:\n{frame}");
// Moved a cell east, torch 7's old box is ranked again as well as its new one: at cell
// (4, 9) only torch 8 is left (square 1 plus one, first), and the new box starts at (5, 9).
mid = gpu_record::log();
assert(scene.set_torch_reach(s([7.0, 0.0, 5.0, 9.0, 3.0, 2.0, 1.0, 0.5, 0.25, 0.5, 0.5, 0.25])), "moved");
got = gpu_record::log()[len(mid)..];
assert(got == lines([
"texture_put 7 at 0,0 16x16 first ffffff00",
"texture_put 6 at 4,9 3x2 first 00020000",
"texture_put 6 at 5,9 3x2 first 00010000",
]), "torch 7 moved:\n{got}");
// Dropped, the cells it reached are ranked again: none is left at cell (5, 9).
mid = gpu_record::log();
scene.drop_torch(7);
got = gpu_record::log()[len(mid)..];
assert(got == lines(["texture_put 6 at 5,9 3x2 first 00000000"]), "torch 7 dropped:\n{got}");
assert(scene.torches() == 1, "one torch left");
}
// A tuple as text: a tuple is not formatted as it is.
fn four(t: (integer, integer, integer, integer)) -> text {
"({t.0},{t.1},{t.2},{t.3})"
}
fn two(t: (integer, integer)) -> text {
"({t.0},{t.1})"
}
fn test_a_screen_of_another_shape_than_the_window_is_fitted_in_its_middle() {
dev = open();
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, 0xFF94BFE6)!;
// The window is 800 x 480. A screen of 400 x 300 fits 1.6 times (480 / 300; across it would
// be 2): 640 x 480, 80 from the left.
scene.resize(400, 300);
assert("{four(scene.placed(800, 480))}" == "(80,0,640,480)", "where the screen lies: {four(scene.placed(800, 480))}");
// The window's pixel (80, 0) is the screen's first; (719, 479) its last, 399.4 and 299.4 in;
// 40 left of it is 25 screen pixels out.
assert("{two(scene.screen_point(800, 480, 80, 0))}" == "(0,0)", "its first pixel: {two(scene.screen_point(800, 480, 80, 0))}");
assert("{two(scene.screen_point(800, 480, 719, 479))}" == "(399,299)", "its last: {two(scene.screen_point(800, 480, 719, 479))}");
assert("{two(scene.screen_point(800, 480, 40, 10))}" == "(-25,6)", "beside it: {two(scene.screen_point(800, 480, 40, 10))}");
before = gpu_record::log();
scene.draw(dev);
// A texture of the sky and a quad for it (11, 12, after the overlay's picture), made once;
// the pass cleared black, drawn inside the screen's rectangle: the sky over it by the
// overlay's pipeline (3), then the land, its matrix for 400 across (2 * 48 / 400 = 0.24).
fitted = lines([
"texture 11 1x1 colour",
"texture_put 11 at 0,0 1x1 first ff94bfe6",
"buffer 12 floats 24",
"begin 0 clear ff000000",
" viewport 80,0 640x480",
" bind 3",
" sample 0 texture 11",
" vertices 12",
" draw from 0 count 6 copies 0",
" bind 2",
" uniforms floats 528 first 0.240 last 0.000",
" sample 0 texture 4",
" sample 1 texture 5",
" sample 2 texture 6",
" sample 3 texture 7",
"end",
]);
got = gpu_record::log()[len(before)..];
assert(got == fitted, "a fitted frame:\n{got}");
// The screen the window's size again: the whole window, cleared to the sky, nothing made.
scene.resize(800, 480);
before = gpu_record::log();
scene.draw(dev);
got = gpu_record::log()[len(before)..];
assert(got.starts_with("begin 0 clear ff94bfe6\n bind 2\n"), "the whole window:\n{got}");
// A screen of the window's shape at half its size fills it: no bars.
scene.resize(400, 240);
assert("{four(scene.placed(800, 480))}" == "(0,0,800,480)", "twice as large: {four(scene.placed(800, 480))}");
assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
}
tests/torches.loft
// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// Torchlight drawn by each backend this machine has, against values worked out by hand. The window is 64 x 48 and
// the fixed camera's top-left is the world's origin: a cell is 48 pixels across and 40 deep, so
// pixel (px, py) shows the ground at x = (px + 0.5) / 48, y = (py + 0.5) / 40. The picture is
// white, so a pixel shows the light itself. A reach is read between the cells' middles: at
// (x, y) it is the four nearest cells' reach, weighed by how near each middle is. A colour is
// compared within 3 of 255: the reach is kept in 16 bits and the frame in 8. Without a display
// every test returns at once (`DISPLAY`, or `GRAPHICS_TEST_WINDOW=1` on a Mac).
use gpu;
use gpu_gl;
use gpu_metal;
use gpu_vulkan;
use scene3d;
fn s(v: const vector<float>) -> vector<single> {
[for x in v { x as single }]
}
// The backends this machine has: each test's scene is drawn by every one of them, against
// the same pixels. One backend serves a program at a time, so a scene's device is closed
// before the next one's opens.
fn backends() -> vector<i64> {
[for t in [gpu_gl::table(), gpu_metal::table(), gpu_vulkan::table()] if t != 0 { t }]
}
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
}
// The ground of cell (x, 0) on layer 0, lit from its own cell.
fn ground(x: float) -> vector<float> {
[0.0, -1.0, 4.0, x, 0.0, 0.0, 1.0,
x, 0.0, 0.0, 0.0, 0.0, 1.0, x + 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, x + 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, x, 0.0, 1.0, 0.0, 1.0, 1.0]
}
// Whether pixel (x, y) of `c` is the colour (r, g, b), each within 3.
fn near(c: const vector<u32>, x: integer, y: integer, rgb: (integer, integer, integer)) -> boolean {
p = c[y * 64 + x] ?? 0;
dr = ((p >> 16) & 255) - rgb.0;
dg = ((p >> 8) & 255) - rgb.1;
db = (p & 255) - rgb.2;
dr >= -3 && dr <= 3 && dg >= -3 && dg <= 3 && db >= -3 && db <= 3
}
fn hex(c: const vector<u32>, x: integer, y: integer) -> text {
"{c[y * 64 + x] ?? 0:x}"
}
// A scene of two dark cells, (0, 0) and (1, 0), in a white picture.
fn dark(dev: const gpu::Device) -> scene3d::Scene {
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, 0xFF000040)!;
// 65535 is every bit of red, green and blue: white
_ = scene.add_picture([for _ in 0..256 { 65535 as i32 }]);
scene.set_tile(dev, 1, s(ground(0.0) + ground(1.0)));
scene.set_light(s([0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 0.0]));
scene.fixed_camera(0, 0);
scene
}
// A torch on cell (0, 0): full there, half on the eight cells round it.
fn ring() -> vector<float> {
[1.0, 0.0, -1.0, -1.0, 3.0, 3.0, 0.5, 0.5, 0.5, 0.5, 1.0, 0.5, 0.5, 0.5, 0.5]
}
fn a_torch_lights_smoothly_across_the_cells_it_reaches_on(table: i64) {
dev = gpu::open(table, 64, 48, "torch-smooth") ?? return assert(false, "no device");
scene = dark(dev);
scene.draw(dev);
c = dev.capture();
assert(near(c, 24, 20, (0, 0, 0)), "no torch yet: dark, {hex(c, 24, 20)}");
assert(scene.set_torch_reach(s(ring())), "the reach");
// its glow full, its colour yellow
scene.set_torches(s([1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0]));
scene.draw(dev);
c = dev.capture();
// Near the torch cell's middle (x 0.5104, y 0.5125): 1 - 0.0104 * 0.5 along the row, then
// 0.9948 * 0.9875 + 0.5 * 0.0125 = 0.9886 of 255 is 252.
assert(near(c, 24, 20, (252, 252, 0)), "by the torch: {hex(c, 24, 20)}");
// At the cell's east edge (x 0.9896): 1 - 0.4896 * 0.5 = 0.7552, then 0.7520: 192. Just
// past it, in the next cell (x 1.0104): 0.7448, then 0.7417: 189. No step at the edge.
assert(near(c, 47, 20, (192, 192, 0)), "at its cell's edge: {hex(c, 47, 20)}");
assert(near(c, 48, 20, (189, 189, 0)), "just past the edge: {hex(c, 48, 20)}");
// Further into the next cell (x 1.2604): 1 - 0.7604 * 0.5 = 0.6198, then 0.6183: 158.
assert(near(c, 60, 20, (158, 158, 0)), "into the next cell: {hex(c, 60, 20)}");
assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
}
fn test_a_torch_lights_smoothly_across_the_cells_it_reaches() {
if !display() { return; }
for table in backends() { a_torch_lights_smoothly_across_the_cells_it_reaches_on(table); }
}
fn a_cell_a_torch_does_not_reach_stays_dark_on(table: i64) {
dev = gpu::open(table, 64, 48, "torch-mask") ?? return assert(false, "no device");
scene = dark(dev);
// A reach of one cell: a wall stands east of it.
assert(scene.set_torch_reach(s([1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0])), "the reach");
scene.set_torches(s([1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0]));
scene.draw(dev);
c = dev.capture();
// (1 - 0.0104) * (1 - 0.0125) = 0.9772: 249. It fades towards its own edge
// ((1 - 0.4896) * 0.9875 = 0.5040: 129), and the cell beyond is not lit at all.
assert(near(c, 24, 20, (249, 249, 0)), "by the torch: {hex(c, 24, 20)}");
assert(near(c, 47, 20, (129, 129, 0)), "fading to its edge: {hex(c, 47, 20)}");
assert(near(c, 48, 20, (0, 0, 0)) && near(c, 60, 20, (0, 0, 0)), "past the wall: {hex(c, 48, 20)} {hex(c, 60, 20)}");
}
fn test_a_cell_a_torch_does_not_reach_stays_dark() {
if !display() { return; }
for table in backends() { a_cell_a_torch_does_not_reach_stays_dark_on(table); }
}
fn the_brightest_of_the_cells_light_and_the_torch_a_channel_at_a_time_on(table: i64) {
dev = gpu::open(table, 64, 48, "torch-channels") ?? return assert(false, "no device");
scene = dark(dev);
scene.set_light(s([0.0, 0.0, 0.0, 1.0, 1.0, 0.5]));
assert(scene.set_torch_reach(s(ring())), "the reach");
// A red torch over a cell half lit: red from the torch (0.9886: 252), green and blue from
// the cell (0.5: 128).
scene.set_torches(s([1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0]));
scene.draw(dev);
c = dev.capture();
assert(near(c, 24, 20, (252, 128, 128)), "a red torch in half light: {hex(c, 24, 20)}");
// Its glow a quarter: 0.247 is under the cell's 0.5, which wins every channel.
scene.set_torches(s([1.0, 0.0, 0.0, 0.0, 1.0, 0.25, 1.0, 0.0, 0.0]));
scene.draw(dev);
c = dev.capture();
assert(near(c, 24, 20, (128, 128, 128)), "a faint torch under the cell's light: {hex(c, 24, 20)}");
}
fn test_the_brightest_of_the_cells_light_and_the_torch_a_channel_at_a_time() {
if !display() { return; }
for table in backends() { the_brightest_of_the_cells_light_and_the_torch_a_channel_at_a_time_on(table); }
}
fn a_glow_dims_a_torch_and_one_not_named_is_dark_on(table: i64) {
dev = gpu::open(table, 64, 48, "torch-glow") ?? return assert(false, "no device");
scene = dark(dev);
assert(scene.set_torch_reach(s(ring())), "the reach");
// 0.9886 * 0.5 = 0.4943: 126
scene.set_torches(s([1.0, 0.0, 0.0, 0.0, 1.0, 0.5, 1.0, 1.0, 0.0]));
scene.draw(dev);
c = dev.capture();
assert(near(c, 24, 20, (126, 126, 0)), "at half its glow: {hex(c, 24, 20)}");
scene.set_torches(s([]));
scene.draw(dev);
c = dev.capture();
assert(near(c, 24, 20, (0, 0, 0)), "not named this frame: {hex(c, 24, 20)}");
// named again, it burns again: nothing but the nine numbers was given
scene.set_torches(s([1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0]));
scene.draw(dev);
c = dev.capture();
assert(near(c, 24, 20, (252, 252, 0)), "named again: {hex(c, 24, 20)}");
}
fn test_a_glow_dims_a_torch_and_one_not_named_is_dark() {
if !display() { return; }
for table in backends() { a_glow_dims_a_torch_and_one_not_named_is_dark_on(table); }
}
fn the_four_strongest_torches_light_a_cell_and_a_dropped_one_gives_way_on(table: i64) {
dev = gpu::open(table, 64, 48, "torch-four") ?? return assert(false, "no device");
scene = dark(dev);
// Five torches reach cell (0, 0) alone: red at 1, blue at 0.8, red at 0.5, blue at 0.4, and
// the weakest, green, at 0.3.
reaches = [1.0, 0.8, 0.5, 0.4, 0.3];
colours = [(1.0, 0.0, 0.0), (0.0, 0.0, 1.0), (1.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 1.0, 0.0)];
all: vector<float> = [];
for r in reaches {
id = (r#index + 1) as float;
assert(scene.set_torch_reach(s([id, 0.0, 0.0, 0.0, 1.0, 1.0, r])), "reach {r#index}");
tint = colours[r#index] ?? (0.0, 0.0, 0.0);
all += [id, 0.0, 0.0, 0.0, 1.0, 1.0, tint.0, tint.1, tint.2];
}
scene.set_torches(s(all));
scene.draw(dev);
c = dev.capture();
// red 0.9772 (249), blue 0.8 * 0.9772 = 0.7818 (199); the fifth torch, the green, is not drawn
assert(near(c, 24, 20, (249, 0, 199)), "the four strongest: {hex(c, 24, 20)}");
// The strongest dropped: the green one is among the four now. Red 0.5 * 0.9772 = 0.4886
// (125), green 0.3 * 0.9772 = 0.2932 (75).
scene.drop_torch(1);
scene.set_torches(s(all));
scene.draw(dev);
c = dev.capture();
assert(near(c, 24, 20, (125, 75, 199)), "the strongest dropped: {hex(c, 24, 20)}");
}
fn test_the_four_strongest_torches_light_a_cell_and_a_dropped_one_gives_way() {
if !display() { return; }
for table in backends() { the_four_strongest_torches_light_a_cell_and_a_dropped_one_gives_way_on(table); }
}
fn a_card_is_lit_by_the_torches_of_the_cell_it_stands_on_on(table: i64) {
dev = gpu::open(table, 64, 48, "torch-card") ?? return assert(false, "no device");
scene = dark(dev);
assert(scene.set_torch_reach(s(ring())), "the reach");
scene.set_torches(s([1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0]));
// A white card with no light of its own, half a cell wide and tall, its foot in the middle
// of the torch's cell (x 12 .. 35, y -4 .. 19 on the screen). Its plane is at y 0.5, the
// row's middle: at x 0.5104 the reach is 1 - 0.0104 * 0.5 = 0.9948: 254.
scene.set_actors(s([1.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.0, 0.0, 0.5, 1.0, 0.0]), -1);
scene.draw(dev);
c = dev.capture();
assert(near(c, 24, 10, (254, 254, 0)), "the card in the torch's light: {hex(c, 24, 10)}");
// With a light of its own it keeps the brighter, a channel at a time.
scene.set_actors(s([1.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.6, 0.0, 0.5, 1.0, 0.0]), -1);
scene.draw(dev);
c = dev.capture();
assert(near(c, 24, 10, (254, 254, 153)), "and its own light in blue: {hex(c, 24, 10)}");
}
fn test_a_card_is_lit_by_the_torches_of_the_cell_it_stands_on() {
if !display() { return; }
for table in backends() { a_card_is_lit_by_the_torches_of_the_cell_it_stands_on_on(table); }
}
tests/width32.loft
#width 32
// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// A 32-bit view (`#width 32`, as the scene contract's CPU side is written) gives its scene to
// this library: the arrays are the single-precision ones it builds, the sky a 64-bit literal.
// Read from the recording backend: no display is needed.
use gpu;
use gpu_record;
use scene3d;
fn test_a_32_bit_view_gives_its_arrays_as_they_are() {
gpu_record::reset();
dev = gpu::open(gpu_record::table(), 800, 480, "w32") ?? return assert(false, "no device");
scene = scene3d::new_scene(dev, gpu::INTO_WINDOW, 0xFF94BFE6l) ?? return assert(false, "no scene");
assert(scene.add_picture([for _ in 0..256 { 2016 }]) == 0, "a picture");
// a block's top on cell (4, 3), group 11, and the hero's card behind it: here a number
// written 4.0 is a single, and the vector is what `raster3d` takes too
top = [0.0, 11.0, 4.0, 0.0, 0.0, -1000000.0, 1.0,
4.0, 1.0, 3.0, 0.0, 0.0, 1.0, 5.0, 1.0, 3.0, 1.0, 0.0, 1.0, 5.0, 1.0, 4.0, 1.0, 1.0, 1.0, 4.0, 1.0, 4.0, 0.0, 1.0, 1.0];
scene.set_tile(dev, 1, top);
scene.set_light([0.0, 0.0, 0.0, 1.0, 1.0, 0.5]);
scene.set_actors([1.0, 0.0, 4.5, 0.0, 2.6, 1.0, 1.0, 0.0, 0.5, 1.0, 0.0], 1);
assert("{scene.hidden_groups()}" == "[11]", "the block in front of the hero is cut away: {scene.hidden_groups()}");
scene.fixed_camera(0, 0);
scene.draw(dev);
log = gpu_record::log();
// the tile's vertices are all hidden, so the frame draws the hero's card alone, over the sky
assert(log.ends_with("begin 0 clear ff94bfe6\n bind 2\n uniforms floats 528 first 0.120 last 0.000\n sample 0 texture 4\n sample 1 texture 5\n sample 2 texture 6\n sample 3 texture 7\n vertices 8\n draw from 0 count 6 copies 0\nend\n"), "the frame:\n{log}");
assert(len(dev.refusals()) == 0, "nothing refused: {dev.refusals()}");
}