summaryrefslogtreecommitdiff
path: root/web
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-30 21:34:41 -0300
committerGabriel Schneider <[email protected]>2026-11-12 13:22:02 -0300
commit2348776791e9dd17afeb12a06ba42a4a71917bcf (patch)
tree780c4b12b76c8b97a28408dd40944d65f159fdc7 /web
parent590ba7b9b579b97e34b51ab7e3460ebc85713343 (diff)
downloadsketchbook-2348776791e9dd17afeb12a06ba42a4a71917bcf.tar.gz
sketchbook-2348776791e9dd17afeb12a06ba42a4a71917bcf.zip
sketchbook: a drawing layer on top, host fixes for replay and migration
Diffstat (limited to 'web')
-rw-r--r--web/host.js152
1 files changed, 132 insertions, 20 deletions
diff --git a/web/host.js b/web/host.js
index aa45840..2c410f7 100644
--- a/web/host.js
+++ b/web/host.js
@@ -4,7 +4,9 @@
// about any particular sketch.
const canvas = document.querySelector('canvas');
const status = document.querySelector('#status');
-const ctx = canvas.getContext('2d', {alpha: false});
+const screen = canvas.getContext('2d', {alpha: false});
+// Where 2D commands draw: the canvas, or an image's (`Command.target`).
+let ctx = screen, drawing = null, composite = 'source-over';
const decoder = new TextDecoder();
const encoder = new TextEncoder();
const images = [null];
@@ -26,9 +28,9 @@ function fit() {
const box = canvas.getBoundingClientRect();
const pw = Math.round(box.width * ratio), ph = Math.round(box.height * ratio);
if (canvas.width !== pw || canvas.height !== ph) { canvas.width = pw; canvas.height = ph; clipped = false; }
- if (clipped) { ctx.restore(); clipped = false; }
- ctx.setTransform(canvas.width / w, 0, 0, canvas.height / h, 0, 0);
- ctx.imageSmoothingEnabled = false;
+ if (clipped && ctx === screen) { ctx.restore(); clipped = false; }
+ screen.setTransform(canvas.width / w, 0, 0, canvas.height / h, 0, 0);
+ screen.imageSmoothingEnabled = false;
}
// Hands bytes to the sketch: into memory it allocates, which the export
@@ -405,6 +407,66 @@ function deliver() {
gpu.arrived = [];
}
+// Draws `source` (or its `sw` x `sh` region at `sx`, `sy`) into `x, y, w,
+// h`, its colour multiplied by `r, g, b` as SDL's colour mod does, which
+// canvas compositing cannot do exactly where the image is translucent. So
+// the pixels are multiplied one by one into a scratch canvas kept per
+// image, and kept while the tint, region and image stay the same (an
+// animated alpha costs nothing: that is `globalAlpha`). A GPU pass's output
+// changes every frame and cannot be read cheaply: it goes through the
+// compositing approximation, exact where it is opaque.
+function drawTinted(entry, source, x, y, w, h, sx, sy, sw, sh, r, g, b) {
+ if (r === 255 && g === 255 && b === 255) {
+ if (sw > 0) ctx.drawImage(source, sx, sy, sw, sh, x, y, w, h); else ctx.drawImage(source, x, y, w, h);
+ return;
+ }
+ const iw = sw > 0 ? Math.ceil(sw) : source.width, ih = sh > 0 ? Math.ceil(sh) : source.height;
+ if (!iw || !ih) return;
+ const region = sw > 0 ? [sx, sy, sw, sh] : [0, 0, source.width, source.height];
+ const key = `${r},${g},${b},${region},${entry.version ?? 0}`;
+ const scratch = entry.tinted ??= document.createElement('canvas');
+ if (entry.texture || entry.tintKey !== key) {
+ if (scratch.width !== iw || scratch.height !== ih) { scratch.width = iw; scratch.height = ih; }
+ const t = scratch.getContext('2d', {willReadFrequently: !entry.texture});
+ t.globalCompositeOperation = 'copy';
+ t.drawImage(source, ...region, 0, 0, iw, ih);
+ if (entry.texture) {
+ t.globalCompositeOperation = 'multiply';
+ t.fillStyle = `rgb(${r},${g},${b})`;
+ t.fillRect(0, 0, iw, ih);
+ t.globalCompositeOperation = 'destination-in';
+ t.drawImage(source, ...region, 0, 0, iw, ih);
+ } else {
+ const pixels = t.getImageData(0, 0, iw, ih), d = pixels.data;
+ for (let i = 0; i < d.length; i += 4) { d[i] = d[i] * r / 255; d[i + 1] = d[i + 1] * g / 255; d[i + 2] = d[i + 2] * b / 255; }
+ t.putImageData(pixels, 0, 0);
+ }
+ entry.tintKey = entry.texture ? null : key;
+ }
+ ctx.drawImage(scratch, 0, 0, iw, ih, x, y, w, h);
+}
+
+// Command.image: as on native, a GPU pass's output scales smoothly, an
+// image nearest; `tint` multiplies, its alpha as `globalAlpha`. `place`
+// sets the transform `x, y, w, h` are drawn under.
+function drawImage(id, x, y, w, h, sx, sy, sw, sh, r, g, b, a, place) {
+ const entry = images[id];
+ if (id && entry === drawing) return; // Drawing into itself: nothing.
+ const ready = entry?.texture || (entry?.source && !(entry.source instanceof Image && !entry.w));
+ ctx.save();
+ if (place) ctx.transform(...place);
+ if (!ready) {
+ ctx.fillStyle = '#6e1e46';
+ ctx.fillRect(x, y, w, h);
+ } else {
+ if (entry.texture) gpu.present(entry);
+ ctx.globalAlpha = a / 255;
+ ctx.imageSmoothingEnabled = !!entry.texture;
+ drawTinted(entry, entry.texture ? entry.shown : entry.source, x, y, w, h, sx, sy, sw, sh, r, g, b);
+ }
+ ctx.restore();
+}
+
const imports = {
host: {
log(ptr, len) { console.log(string(ptr, len)); },
@@ -439,32 +501,78 @@ const imports = {
openFile(command, commandLen, pattern, patternLen) { openFile(string(command, commandLen), string(pattern, patternLen)); },
},
canvas: {
- clear(r, g, b, a) { ctx.fillStyle = rgba(r, g, b, a); ctx.fillRect(0, 0, size[0], size[1]); },
+ // Replaces, ignoring the blend, as SDL's clear does; into an image with
+ // its alpha too.
+ clear(r, g, b, a) {
+ ctx.save();
+ ctx.globalCompositeOperation = drawing ? 'copy' : 'source-over';
+ ctx.fillStyle = rgba(r, g, b, a);
+ ctx.fillRect(0, 0, drawing ? drawing.w : size[0], drawing ? drawing.h : size[1]);
+ ctx.restore();
+ },
fill(x, y, w, h, r, g, b, a) { ctx.fillStyle = rgba(r, g, b, a); ctx.fillRect(x, y, w, h); },
- image(id, x, y, w, h, sx, sy, sw, sh, alpha) {
- const entry = images[id];
- if (entry?.texture) {
- // GPU renders scale smoothly, as on native.
- gpu.present(entry);
- ctx.globalAlpha = alpha / 255;
- ctx.imageSmoothingEnabled = true;
- if (sw > 0) ctx.drawImage(entry.shown, sx, sy, sw, sh, x, y, w, h); else ctx.drawImage(entry.shown, x, y, w, h);
- ctx.imageSmoothingEnabled = false;
- ctx.globalAlpha = 1;
- return;
+ image(id, x, y, w, h, sx, sy, sw, sh, r, g, b, a) { drawImage(id, x, y, w, h, sx, sy, sw, sh, r, g, b, a, null); },
+ // The unit square onto the three corners, and the image into it.
+ imageCorners(id, x0, y0, x1, y1, x2, y2, sx, sy, sw, sh, r, g, b, a) {
+ drawImage(id, 0, 0, 1, 1, sx, sy, sw, sh, r, g, b, a, [x1 - x0, y1 - y0, x2 - x0, y2 - y0, x0, y0]);
+ },
+ // Command.target: later 2D commands draw into the image's canvas (at
+ // its pixels, 1:1), or the screen for 0. Unclips, as native does.
+ target(id) {
+ if (clipped) { ctx.restore(); clipped = false; }
+ const entry = id ? images[id] : null;
+ if (id && !entry?.ctx) return;
+ ctx = entry ? entry.ctx : screen;
+ drawing = entry;
+ if (entry) { entry.version = (entry.version ?? 0) + 1; ctx.imageSmoothingEnabled = false; }
+ ctx.globalCompositeOperation = composite;
+ },
+ // Command.blend, by abi.BlendMode value.
+ blend(mode) { composite = ['source-over', 'lighter'][mode] ?? 'source-over'; ctx.globalCompositeOperation = composite; },
+ // Command.shape: its subpaths filled nonzero (the triangles are for
+ // native), one path per positively wound subpath together with the
+ // negatively wound ones after it (its holes). One fill per shape, as
+ // native blends once per triangle: shapes batched into one command
+ // that overlap blend twice on both hosts. Canvas2D also slows down
+ // badly on one path of thousands of subpaths (5000 circles: 200 ms
+ // as one path, 9 ms as 5000).
+ // With `colors`, each group fills in its first subpath's colour.
+ shape(ptr, len, endsPtr, endsLen, colorsPtr, colorsLen, r, g, b, a) {
+ if (!len || !endsLen) return;
+ const p = new Float32Array(wasm.memory.buffer, ptr, len * 2);
+ const ends = new Uint32Array(wasm.memory.buffer, endsPtr, endsLen);
+ const colors = colorsLen ? new Uint8Array(wasm.memory.buffer, colorsPtr, colorsLen * 4) : null;
+ const style = k => k < colorsLen ? rgba(colors[4 * k], colors[4 * k + 1], colors[4 * k + 2], colors[4 * k + 3]) : rgba(r, g, b, a);
+ ctx.fillStyle = style(0);
+ ctx.beginPath();
+ let start = 0, open = false;
+ for (let k = 0; k < endsLen; k++) {
+ const end = Math.min(ends[k], len);
+ if (end - start >= 3) {
+ let area = 0;
+ for (let i = start, j = end - 1; i < end; j = i++) area += p[2 * j] * p[2 * i + 1] - p[2 * i] * p[2 * j + 1];
+ if (area > 0 && open) { ctx.fill('nonzero'); ctx.beginPath(); }
+ if (area > 0 && colors) ctx.fillStyle = style(k);
+ ctx.moveTo(p[2 * start], p[2 * start + 1]);
+ for (let i = start + 1; i < end; i++) ctx.lineTo(p[2 * i], p[2 * i + 1]);
+ ctx.closePath();
+ open = true;
+ }
+ start = Math.max(start, end);
}
- if (!entry?.source || (entry.source instanceof Image && !entry.w)) { ctx.fillStyle = '#6e1e46'; ctx.fillRect(x, y, w, h); return; }
- ctx.globalAlpha = alpha / 255;
- if (sw > 0) ctx.drawImage(entry.source, sx, sy, sw, sh, x, y, w, h); else ctx.drawImage(entry.source, x, y, w, h);
- ctx.globalAlpha = 1;
+ if (open) ctx.fill('nonzero');
},
+ // Always blended alpha, as native text is.
text(x, y, scale, ptr, len, r, g, b, a) {
+ ctx.save();
+ ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = rgba(r, g, b, a);
// The native font is a fixed 8px cell: the same advance, and a size
// whose capitals fill the cell as native ones do.
ctx.font = `${10 * scale}px monospace`;
ctx.textBaseline = 'top';
for (const [i, ch] of Array.from(string(ptr, len)).entries()) ctx.fillText(ch, x + i * 8 * scale, y);
+ ctx.restore();
},
clip(enabled, x, y, w, h) {
if (clipped) { ctx.restore(); clipped = false; }
@@ -481,6 +589,7 @@ const imports = {
if (a && a < 255) { data[i] = data[i] * 255 / a; data[i + 1] = data[i + 1] * 255 / a; data[i + 2] = data[i + 2] * 255 / a; }
}
entry.ctx.putImageData(new ImageData(data, w, h), 0, 0);
+ entry.version = (entry.version ?? 0) + 1;
},
},
gpu: {
@@ -629,6 +738,9 @@ try {
command(line) { const encoded = encoder.encode(line); wasm.sk_command(give(encoded), encoded.length); },
sound(name, samples) { const encoded = encoder.encode(name); wasm.sk_sound(give(encoded), encoded.length, give(samples), samples.length); },
size: () => size,
+ // Runs one frame now, at `ms` on the page's clock, for tests that time
+ // or compare frames without waiting for the display.
+ frame(ms) { frameNumber++; deliver(); wasm.sk_frame(ms); },
// 'running', or 'suspended' until a tap or key starts sound.
audio: () => sound.context.state,
};