gizlang/draw
Instanced 2D drawing for any application surface, independent from a game's world or simulation.
import * as Draw from "gizlang/draw";Types
Quad
type Quad = { x: f64; y: f64; width: f64; height: f64; u: f64; v: f64; du: f64; dv: f64; red: f64; green: f64; blue: f64; alpha: f64; rotation: f64; depth: f64; additive?: f64; }A pixel-space quad, its normalized atlas rectangle, straight RGBA tint, rotation and normalized depth. ADDITIVE in [0, 1] blends its light into what is below without covering it: 1 for glows and sparks, 0 for opaque art.
x:f64y:f64width:f64height:f64u:f64v:f64du:f64dv:f64red:f64green:f64blue:f64alpha:f64rotation:f64depth:f64additive:_gizlang_sdk_core.Option<f64>
TileChunk
type TileChunk = { x: f64; y: f64; columns: i64; rows: i64; tileWidth: f64; tileHeight: f64; cells: Vec<i64>; }An immutable tile-data projection. Cells index caller-owned atlas quads; -1 is empty. No gameplay state is retained.
x:f64y:f64columns:i64rows:i64tileWidth:f64tileHeight:f64cells:Vec<i64>
Batch2D
class Batch2D { private resources: Resources; private pipeline: Handle; private group: Handle; private instances: Handle; private view: Handle; private texture: Handle; private sampler: Handle; private shader: Handle; private maximum: i64; private width: i64; private height: i64; private pixels: bytes; constructor(resources: Resources, pixels: bytes, width: i64, height: i64, maximum: i64 = 16384, nearest: bool = true) throws string { if (width <1 || height <1 || width> 16384 || height> 16384 || pixels.length !== width * height * 4 || pixels[0] !== 255u || pixels[1] !== 255u || pixels[2] !== 255u || pixels[3] !== 255u || maximum <1 || maximum> 1048576) { throw "Invalid quad atlas or capacity"; } this.resources = resources; this.maximum = maximum; this.width = width; this.height = height; this.pixels = pixels; const made = resources.transaction((): Handles throws string => { const shader = resources.create("shader", parse(`{"code":${encode(SHADER) } }`)!); const view = resources.buffer(16, BUFFER_UNIFORM | BUFFER_COPY_DST); const instances = resources.buffer(maximum * 64, BUFFER_VERTEX | BUFFER_COPY_DST); const texture = resources.create("texture", parse(`{"size":[${width }, ${ height }, 1], "format": "rgba8unorm", "usage": ${ TEXTURE_COPY_DST | TEXTURE_BINDING } }`)!, width * height * 4); const filter = nearest ? "nearest": "linear"; const sampler = resources.create("sampler", parse(`{"minFilter":"${filter }", "magFilter": "${ filter }" }`)!); const module = encode(reference(shader)); const pipeline = resources.create("renderPipeline", parse(`{
"layout":"auto","vertex":{"module":${module }, "entryPoint": "vertex", "buffers": [{
"arrayStride": 64, "stepMode": "instance", "attributes": [
{ "shaderLocation": 0, "offset": 0, "format": "float32x4" },
{ "shaderLocation": 1, "offset": 16, "format": "float32x4" },
{ "shaderLocation": 2, "offset": 32, "format": "float32x4" },
{ "shaderLocation": 3, "offset": 48, "format": "float32x4" }] }] },
"fragment": { "module": ${ module }, "entryPoint": "fragment", "targets": [{ "format": "$surface-format",
"blend": { "color": { "srcFactor": "one", "dstFactor": "one-minus-src-alpha" },
"alpha": { "srcFactor": "one", "dstFactor": "one-minus-src-alpha" } } }] },
"primitive": { "topology": "triangle-list" } }`)!); const layout = `{"$layout":{"pipeline":${encode(pipeline) }, "index": 0 } }`; const group = resources.create("bindGroup", parse(`{"layout":${layout }, "entries": [
{ "binding": 0, "resource": { "buffer": ${ encode(reference(view)) } } },
{ "binding": 1, "resource": ${ encode(textureView(texture)) } },
{ "binding": 2, "resource": ${ encode(reference(sampler)) } }] }`)!); return { pipeline, group, instances, view, texture, sampler, shader }; }); this.pipeline = made.pipeline; this.group = made.group; this.instances = made.instances; this.view = made.view; this.texture = made.texture; this.sampler = made.sampler; this.shader = made.shader; } update(pixels: bytes): void throws string { if (pixels.length !== this.width*this.height*4 || pixels[0] !== 255u || pixels[1] !== 255u || pixels[2] !== 255u || pixels[3] !== 255u) { throw "Invalid replacement atlas"; } this.pixels = pixels; this.resources.invalidate(this.texture); } draw(graph: Graph, quads: Vec<Quad>, width: i64, height: i64, clear: Vec<f64> = [0.0, 0.0, 0.0, 1.0], name: string = "quads", load: bool = false, after: Vec<string> = []): void throws string { if (quads.length> this.maximum || width <1 || height <1 || clear.length !== 4) { throw "Invalid quad batch"; } let view = b""; for (const value of [f64(width), f64(height), 0.0, 0.0]) { writeF32LE(view, value); } graph.upload(this.view, view); let instances = b""; for (const quad of quads) { const values = [quad.x, quad.y, quad.width, quad.height, quad.u, quad.v, quad.du, quad.dv, quad.red, quad.green, quad.blue, quad.alpha, quad.depth, quad.rotation, quad.additive ?? 0.0, 0.0]; if (!values.every(value => Math.isFinite(value)) || quad.depth <0.0 || quad.depth> 1.0 || values[14] <0.0 || values[14]> 1.0) { throw "Invalid quad value"; } for (const value of values) { writeF32LE(instances, value); } } if (!this.resources.initialized(this.instances)) { while (instances.length <this.maximum * 64) { instances.push(0u); } } if (instances.length> 0) { graph.upload(this.instances, instances); } if (!this.resources.initialized(this.texture)) { graph.image(this.texture, this.pixels, this.width, this.height); } let commands: Vec<Command> = [{ method: "setPipeline", args: [reference(this.pipeline)] }, { method: "setBindGroup", args: [{ kind: "number", value: 0.0 }, reference(this.group)] }, { method: "setVertexBuffer", args: [{ kind: "number", value: 0.0 }, reference(this.instances)] }, { method: "draw", args: [{ kind: "number", value: 6.0 }, { kind: "number", value: f64(quads.length) }] }]; const loadOp = load ? "load": "clear"; graph.add({ name, kind: "render", descriptor: parse(`{"colorAttachments":[{"view":${encode(reference(surface())) },
"loadOp": "${ loadOp }", "storeOp": "store", "clearValue": ${ encode(clear) } }] }`)!, reads: [this.view, this.texture, this.instances], writes: [surface()], after, commands, loads: load ? [surface()]: [] }); } close(): void throws string { const resources = this.resources; resources.release(this.group); resources.release(this.pipeline); resources.release(this.shader); resources.release(this.sampler); resources.release(this.texture); resources.release(this.instances); resources.release(this.view); } }A reusable instancing pipeline with one atlas. Multiple batches may share the same Resources owner and Graph.
resources:Ref<gizlang_render.Resources>pipeline:gizlang_render.Handlegroup:gizlang_render.Handleinstances:gizlang_render.Handleview:gizlang_render.Handletexture:gizlang_render.Handlesampler:gizlang_render.Handleshader:gizlang_render.Handlemaximum:i64width:i64height:i64pixels:bytes
Atlas
class Atlas { width: i64; height: i64; pixels: bytes; private x: i64 = 2; private y: i64 = 0; private row: i64 = 2; private glyphs = new Map<string, Vec<f64>>(); constructor(width: i64, height: i64) { assert(width> = 4 && height> = 4 && width <= 8192 && height <= 8192); this.width = width; this.height = height; this.pixels = b""; for (const at of range(0, width * height * 4)) { this.pixels.push(0u); } for (const at of range(0, 8)) { this.pixels[at] = 255u; } } add(pixels: bytes, width: i64, height: i64): Vec<f64> throws string { if (width <1 || height <1 || width + 2> this.width || pixels.length !== width * height * 4) { throw "Invalid atlas image"; } let x = this.x; let y = this.y; let row = this.row; if (x + width + 2> this.width) { x = 0; y + = row; row = 0; } if (y + height + 2> this.height) { throw "Texture atlas is full"; } let atlas = this.pixels; for (const dy of range(-1, height + 1)) { const sy = Math.maxI64(0, Math.minI64(height - 1, dy)); for (const dx of range(-1, width + 1)) { const sx = Math.maxI64(0, Math.minI64(width - 1, dx)); atlas.copyFrom(((y + dy + 1) * this.width + x + dx + 1) * 4, pixels, (sy * width + sx) * 4, 4); } } this.pixels = atlas; this.x = x + width + 2; this.y = y; this.row = Math.maxI64(row, height + 2); return [f64(x + 1) / f64(this.width), f64(y + 1) / f64(this.height), f64(width) / f64(this.width), f64(height) / f64(this.height)]; } text(font: Font, text: string, size: f64, x: f64, baseline: f64, color: Vec<f64> = [1.0, 1.0, 1.0, 1.0], rtl: bool = false): Vec<Quad> throws string { if (color.length !== 4 || !color.every(value => Math.isFinite(value))) { throw "Invalid text color"; } const run = font.layout(text, size, x, baseline, 0.0, rtl); let out: Vec<Quad> = []; for (const glyph of run.glyphs) { const place = glyphPlace(glyph.x); const phase = place.phase; const key = `${font.at }/${ glyph.id }/${ glyph.size }/${ phase }`; let cached = this.glyphs.get(key); if (cached === undefined) { const coverage = font.bitmap({ ...glyph, x: i64(phase)*16, baseline: 0 }); const bitmap = coverage.bitmap; let values: Vec<f64> = [f64(coverage.x), f64(coverage.y), f64(bitmap.width), f64(bitmap.height), 0.0, 0.0, 0.0, 0.0]; if (bitmap.width> 0 && bitmap.height> 0) { const uv = this.add(bitmap.pixels, bitmap.width, bitmap.height); for (const lane of range(0, 4)) { values[4+lane] = uv[lane]; } } this.glyphs.set(key, values); cached = values; } const data = cached!; if (data[2] === 0.0 || data[3] === 0.0) { continue; } out.push({ x: f64(place.whole)+data[0], y: f64(glyph.baseline)+data[1], width: data[2], height: data[3], u: data[4], v: data[5], du: data[6], dv: data[7], red: color[0], green: color[1], blue: color[2], alpha: color[3], rotation: 0.0, depth: 0.0 }); } return out; } }A padded RGBA8 atlas. This owner packs images; image/font decoding stays in the existing SDK modules.
width:i64height:i64pixels:bytesx:i64y:i64row:i64glyphs:_gizlang_sdk_collections.Map<string, Vec<f64>>
Brush
type Brush = { glow: Vec<f64>; disc: Vec<f64>; }The atlas images Canvas2D draws text and its own light with: a soft glow and a hard disc.
glow:Vec<f64>disc:Vec<f64>
Canvas2D
class Canvas2D { quads: Vec<Quad> = []; viewport: Viewport2D; brush: Brush; shake: Point2 = { x: 0.0, y: 0.0 }; constructor(width: i64, height: i64, logicalWidth: f64, logicalHeight: f64, brush: Brush) throws string { const viewport = fitted2D(f64(width), f64(height), logicalWidth, logicalHeight); this.viewport = viewport; this.brush = brush; } sprite(uv: Vec<f64>, x: f64, y: f64, width: f64, height: f64, angle: f64 = 0.0, color: Vec<f64> = [1.0, 1.0, 1.0, 1.0], additive: f64 = 0.0): void { const scale = this.viewport.scale; const center = pixel2D(this.viewport, { x: x+this.shake.x, y: y+this.shake.y }); this.quads.push({ x: center.x-width*scale*0.5, y: center.y-height*scale*0.5, width: width*scale, height: height*scale, u: uv[0], v: uv[1], du: uv[2], dv: uv[3], red: color[0], green: color[1], blue: color[2], alpha: color[3], rotation: angle, depth: 0.0, additive }); } light(x: f64, y: f64, size: f64, color: Vec<f64>): void { this.sprite(this.brush.glow, x, y, size, size, 0.0, color, 1.0); } dot(x: f64, y: f64, diameter: f64, color: Vec<f64>, additive: f64 = 0.0): void { this.sprite(this.brush.disc, x, y, diameter, diameter, 0.0, color, additive); } text(text: string, x: f64, y: f64, dot: f64, color: Vec<f64>, align: f64 = 0.0): void { const advance = dot*6.0; const upper = text.toUpperCase(); let left = x-(f64(upper.length)*advance-dot)*align; for (const at of range(0, upper.length)) { const glyph = GLYPHS.indexOf(upper.slice(at, at+1)); if (glyph> = 0) { const rows = FONT[glyph]; for (const cell of range(0, 35)) { if (rows.slice(cell, cell+1) !== "1") { continue; } const cx = left+f64(cell%5)*dot; const cy = y+f64(cell/5)*dot; this.light(cx, cy, dot*3.4, [color[0], color[1], color[2], color[3]*0.22]); this.dot(cx, cy, dot*0.92, color); } } left+ = advance; } } logical(x: f64, y: f64): Point2 { return logical2D(this.viewport, { x, y }); } }One frame's 2D drawing in logical units, letterboxed into the surface: sprites and glowing dot-matrix text, in painter's order. SHAKE moves what is drawn while it is set, for a camera shake under a still heads-up display.
quads:Vec<gizlang_draw.Quad>viewport:gizlang_geometry.Viewport2Dbrush:gizlang_draw.Brushshake:gizlang_geometry.Point2
Functions
rectangle
function rectangle(x: f64, y: f64, width: f64, height: f64, red: f64, green: f64, blue: f64, alpha: f64 = 1.0): QuadA solid quad sampling the atlas's white texel.
tiles
function tiles(chunks: Vec<TileChunk>, atlas: Vec<Quad>, viewport: Viewport2D, width: i64, height: i64, pixelPerfect: bool = false, maximum: i64 = 65536): Vec<Quad> throws stringExtracts only visible cells. Camera/parallax offsets and pixel-perfect scale use the existing 2D viewport contract.
Effects: fail, alloc.
constructor
constructor(resources: Resources, pixels: bytes, width: i64, height: i64, maximum: i64 = 16384, nearest: bool = true) throws stringCreates the pipeline and atlas declarations. PIXELS is tightly packed RGBA8; texel (0,0) must be opaque white.
Effects: fail, read, write, console, io, alloc.
constructor
constructor(width: i64, height: i64)Reserves the first two pixels for solid primitives.
Effects: fail, read, write, alloc.
picture
function picture(size: i64, cover: (x: f64, y: f64) => Vec<f64>): bytesAn image of SIZE x SIZE pixels from COVER(x, y) = [brightness, alpha], sampled 4x4 a pixel for smooth edges.
Effects: fail, read, write, console, io, alloc.
inside
function inside(points: Vec<Point2>, x: f64, y: f64): boolWhether X, Y is inside the polygon POINTS (even-odd rule).
Effects: fail.
glow
function glow(size: i64): bytesA soft round glow of SIZE pixels, bright in the middle: the light of sparks, engines and clouds.
Effects: fail, read, write, console, io, alloc.
disc
function disc(size: i64): bytesA hard disc of SIZE pixels.
Effects: fail, read, write, console, io, alloc.
ring
function ring(size: i64, width: f64 = 3.2): bytesA ring of SIZE pixels and WIDTH pixels of line.
Effects: fail, read, write, console, io, alloc.
brush
function brush(atlas: mut Atlas): Brush throws stringPacks the images of a Brush into ATLAS.
Effects: fail, read, write, console, io, alloc.
constructor
constructor(width: i64, height: i64, logicalWidth: f64, logicalHeight: f64, brush: Brush) throws stringA canvas of LOGICAL width and height fitted into a WIDTH x HEIGHT pixel surface.
Effects: fail, read, write, alloc.
Methods
Batch2D.update
update(pixels: bytes): void throws stringReplaces CPU atlas content and invalidates its GPU content through the shared resource owner.
Effects: fail, read, write, alloc.
Batch2D.draw
draw(graph: Graph, quads: Vec<Quad>, width: i64, height: i64, clear: Vec<f64> = [0.0, 0.0, 0.0, 1.0], name: string = "quads", load: bool = false, after: Vec<string> = []): void throws stringAppends one instanced pass. Quad order is painter's order; no hidden sorting changes transparent composition.
Effects: fail, read, write, alloc.
Batch2D.close
close(): void throws stringReleases declarations in reverse dependency order through the one Resources owner.
Effects: fail, read, write, alloc.
Atlas.add
add(pixels: bytes, width: i64, height: i64): Vec<f64> throws stringPacks RGBA8 pixels with a one-pixel gutter duplicated at every edge. Returns normalized u,v,width,height.
Effects: fail, read, write, alloc.
Atlas.text
text(font: Font, text: string, size: f64, x: f64, baseline: f64, color: Vec<f64> = [1.0, 1.0, 1.0, 1.0], rtl: bool = false): Vec<Quad> throws stringPacks the existing OpenType masks and returns tinted quads. Synchronize changed pixels with Batch2D.update before drawing.
Effects: fail, read, write, alloc.
Canvas2D.sprite
sprite(uv: Vec<f64>, x: f64, y: f64, width: f64, height: f64, angle: f64 = 0.0, color: Vec<f64> = [1.0, 1.0, 1.0, 1.0], additive: f64 = 0.0): voidThe atlas image UV centered at X, Y, WIDTH x HEIGHT logical units, turned by ANGLE and tinted by straight RGBA COLOR.
Effects: fail, read, write, alloc.
Canvas2D.light
light(x: f64, y: f64, size: f64, color: Vec<f64>): voidA light: the brush's glow, added to what is below.
Effects: fail, read, write, alloc.
Canvas2D.dot
dot(x: f64, y: f64, diameter: f64, color: Vec<f64>, additive: f64 = 0.0): voidA solid disc of DIAMETER.
Effects: fail, read, write, alloc.
Canvas2D.text
text(text: string, x: f64, y: f64, dot: f64, color: Vec<f64>, align: f64 = 0.0): voidTEXT in the dot-matrix font: uppercase letters, digits and - . : ! /, dots DOT units apart, each a glowing disc. ALIGN 0 starts it at X, 0.5 centers it on X and 1 ends it at X.
Effects: fail, read, write, alloc.
Canvas2D.logical
logical(x: f64, y: f64): Point2A pointer position in surface pixels as logical units.
Effects: fail, read.