// sketchbook web host: forwards input to the sketch and draws what it asks. // It knows nothing about any particular sketch. const canvas = document.querySelector('canvas'); const status = document.querySelector('#status'); const ctx = canvas.getContext('2d', {alpha: false}); const decoder = new TextDecoder(); const images = [null]; const byPath = new Map(); const loads = []; let wasm, clipped = false, size = [960, 600]; const bytes = (ptr, len) => new Uint8Array(wasm.memory.buffer, ptr, len); const string = (ptr, len) => decoder.decode(bytes(ptr, len)); const rgba = (r, g, b, a) => `rgba(${r},${g},${b},${a / 255})`; const Kind = {move: 1, down: 2, up: 3, wheel: 4, keyDown: 5, keyUp: 6, text: 7, cancel: 8}; function fit() { const [w, h] = size; canvas.style.width = `min(100vw, ${w / h * 100}vh)`; canvas.style.height = `min(${h / w * 100}vw, 100vh)`; const ratio = Math.min(window.devicePixelRatio || 1, 2); 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; } const imports = { host: { log(ptr, len) { console.log(string(ptr, len)); }, loadImage(ptr, len) { const path = string(ptr, len); if (byPath.has(path)) return byPath.get(path); const entry = {source: new Image(), w: 0, h: 0}; loads.push(new Promise(resolve => { entry.source.onload = () => { entry.w = entry.source.naturalWidth; entry.h = entry.source.naturalHeight; resolve(); }; entry.source.onerror = () => { console.warn(`missing image ${path}`); entry.source = null; resolve(); }; })); entry.source.src = path; images.push(entry); byPath.set(path, images.length - 1); return images.length - 1; }, clock: () => performance.now(), imageWidth: id => images[id]?.w ?? 0, imageHeight: id => images[id]?.h ?? 0, newImage(w, h) { const source = document.createElement('canvas'); source.width = w; source.height = h; images.push({source, w, h, ctx: source.getContext('2d')}); return images.length - 1; }, }, canvas: { clear(r, g, b, a) { ctx.fillStyle = rgba(r, g, b, a); ctx.fillRect(0, 0, size[0], size[1]); }, 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?.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; }, text(x, y, scale, ptr, len, r, g, b, a) { ctx.fillStyle = rgba(r, g, b, a); ctx.font = `${12 * scale}px monospace`; ctx.textBaseline = 'top'; // The native font is a fixed 8px cell; keep the same geometry. for (const [i, ch] of Array.from(string(ptr, len)).entries()) ctx.fillText(ch, x + i * 8 * scale, y); }, clip(enabled, x, y, w, h) { if (clipped) { ctx.restore(); clipped = false; } if (enabled) { ctx.save(); ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip(); clipped = true; } }, canvas(w, h) { if (size[0] !== w || size[1] !== h) { size = [w, h]; } fit(); }, cursor(kind) { canvas.style.cursor = ['none', 'default', 'pointer'][kind] ?? 'default'; }, pixels(id, w, h, ptr, len, premultiplied) { const entry = images[id]; if (!entry?.ctx || len < w * h * 4) return; const data = new Uint8ClampedArray(wasm.memory.buffer.slice(ptr, ptr + w * h * 4)); if (premultiplied) for (let i = 0; i < data.length; i += 4) { const a = data[i + 3]; 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); }, }, }; // DOM `code` to USB HID usage, the numbering recordings and sketches use. const hid = code => { if (/^Key[A-Z]$/.test(code)) return code.charCodeAt(3) - 61; if (/^Digit[0-9]$/.test(code)) return code[5] === '0' ? 39 : code.charCodeAt(5) - 19; return {Enter: 40, Escape: 41, Backspace: 42, Tab: 43, Space: 44, Minus: 45, Equal: 46, BracketLeft: 47, BracketRight: 48, Backslash: 49, Semicolon: 51, Quote: 52, Backquote: 53, Comma: 54, Period: 55, Slash: 56, Home: 74, PageUp: 75, Delete: 76, End: 77, PageDown: 78, ArrowRight: 79, ArrowLeft: 80, ArrowDown: 81, ArrowUp: 82, NumpadEnter: 88, ControlLeft: 224, ShiftLeft: 225, AltLeft: 226, MetaLeft: 227, ControlRight: 228, ShiftRight: 229, AltRight: 230, MetaRight: 231}[code] ?? 0; }; const floatBits = f => new Uint32Array(new Float32Array([f]).buffer)[0]; try { const response = await fetch('sketch.wasm'); if (!response.ok) throw new Error('The sketch could not be loaded.'); wasm = (await WebAssembly.instantiate(await response.arrayBuffer(), imports)).instance.exports; wasm.sk_init(); wasm.sk_frame(0); await Promise.all(loads); status.hidden = true; const send = (kind, x = 0, y = 0, code = 0, value = 0) => wasm.sk_event(kind, code, x, y, value); const point = e => { const r = canvas.getBoundingClientRect(); return [(e.clientX - r.left) * size[0] / r.width, (e.clientY - r.top) * size[1] / r.height]; }; let pointer = null; canvas.addEventListener('pointerdown', e => { if (pointer !== null) return; e.preventDefault(); pointer = e.pointerId; canvas.setPointerCapture(pointer); send(Kind.down, ...point(e), e.button + 1); }); canvas.addEventListener('pointermove', e => send(Kind.move, ...point(e))); canvas.addEventListener('pointerup', e => { if (e.pointerId !== pointer) return; send(Kind.up, ...point(e), e.button + 1); const id = pointer; pointer = null; if (canvas.hasPointerCapture(id)) canvas.releasePointerCapture(id); }); const cancel = () => { pointer = null; send(Kind.cancel); }; canvas.addEventListener('pointercancel', cancel); canvas.addEventListener('lostpointercapture', () => { if (pointer !== null) cancel(); }); canvas.addEventListener('pointerleave', () => { if (pointer === null) send(Kind.move, -1, -1); }); canvas.addEventListener('wheel', e => { e.preventDefault(); send(Kind.wheel, ...point(e), 0, floatBits(-Math.sign(e.deltaY))); }, {passive: false}); window.addEventListener('keydown', e => { send(Kind.keyDown, 0, 0, hid(e.code), 0); if (e.key.length === 1 && !e.ctrlKey && !e.metaKey) send(Kind.text, 0, 0, 0, e.key.codePointAt(0)); }); window.addEventListener('keyup', e => send(Kind.keyUp, 0, 0, hid(e.code), 0)); window.addEventListener('blur', cancel); window.addEventListener('resize', fit); document.addEventListener('visibilitychange', () => { if (document.hidden) cancel(); }); // Tests read state by field path, like the native probe. window.sketch = { field(path) { const encoded = new TextEncoder().encode(path); new Uint8Array(wasm.memory.buffer, wasm.sk_buffer(), encoded.length).set(encoded); return wasm.sk_field(encoded.length); }, size: () => size, }; const frame = ms => { try { wasm.sk_frame(ms); requestAnimationFrame(frame); } catch (error) { status.textContent = 'The sketch stopped. Reload to start again.'; status.hidden = false; console.error(error); } }; requestAnimationFrame(frame); } catch (error) { status.textContent = 'The sketch could not start. Reload to try again.'; console.error(error); }