Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: agent-og, brain chat, x402-pay og, voxel build + coincommunities updates
nirholas963e43b9470d
diff --git a/api/agent-og.js b/api/agent-og.jsindex 8916f9a8f..507cc416d 100644--- a/api/agent-og.js+++ b/api/agent-og.js@@ -16,13 +16,20 @@ import { cors, wrap } from './_lib/http.js';const CACHE_CARD = 'public, max-age=3600, s-maxage=86400';const CACHE_REDIR = 'public, max-age=3600';+// agent_identities.id is a uuid column. Crawlers and broken share links hit this+// public route with a literal ":id" placeholder (when a page template forgets to+// interpolate the real id) or other junk; passing that straight to Postgres throws+// `invalid input syntax for type uuid` (22P02) and 500s. Validate the shape up+// front so any non-uuid degrades to a clean 404 instead of an unhandled error.+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('id');- if (!agentId) return sendNotFound(res);+ if (!agentId || !UUID_RE.test(agentId)) return sendNotFound(res);const [agent] = await sql`SELECT id, name, description, avatar_iddiff --git a/api/brain/chat.js b/api/brain/chat.jsindex e8288a7f6..50e312a17 100644--- a/api/brain/chat.js+++ b/api/brain/chat.js@@ -75,7 +75,7 @@ const PROVIDERS = {maxOutput: 16384,description: 'OpenAI flagship. Strong multimodal reasoning.',build: () => {- if (env.OPENAI_API_KEY) return createOpenAI({ apiKey: env.OPENAI_API_KEY })('gpt-4o');+ if (env.OPENAI_API_KEY) return createOpenAI({ apiKey: env.OPENAI_API_KEY }).chat('gpt-4o');if (env.OPENROUTER_API_KEY) return openrouter()('openai/gpt-4o');return null;},@@ -87,7 +87,7 @@ const PROVIDERS = {maxOutput: 16384,description: 'Fast, affordable GPT. Great for simple tasks.',build: () => {- if (env.OPENAI_API_KEY) return createOpenAI({ apiKey: env.OPENAI_API_KEY })('gpt-4o-mini');+ if (env.OPENAI_API_KEY) return createOpenAI({ apiKey: env.OPENAI_API_KEY }).chat('gpt-4o-mini');if (env.OPENROUTER_API_KEY) return openrouter()('openai/gpt-4o-mini');return null;},@@ -99,7 +99,7 @@ const PROVIDERS = {maxOutput: 16384,description: 'Reasoning-optimized. Fast chain-of-thought.',build: () => {- if (env.OPENAI_API_KEY) return createOpenAI({ apiKey: env.OPENAI_API_KEY })('o3-mini');+ if (env.OPENAI_API_KEY) return createOpenAI({ apiKey: env.OPENAI_API_KEY }).chat('o3-mini');if (env.OPENROUTER_API_KEY) return openrouter()('openai/o3-mini');return null;},@@ -115,7 +115,7 @@ const PROVIDERS = {return createOpenAI({apiKey: env.GROQ_API_KEY,baseURL: 'https://api.groq.com/openai/v1',- })('llama-3.3-70b-versatile');+ }).chat('llama-3.3-70b-versatile');}if (env.OPENROUTER_API_KEY) return openrouter()('meta-llama/llama-3.3-70b-instruct');return null;@@ -144,7 +144,7 @@ const PROVIDERS = {return createOpenAI({apiKey: env.MODELSCOPE_API_KEY,baseURL: 'https://api-inference.modelscope.cn/v1',- })('Qwen/Qwen3-Coder-480B-A35B-Instruct');+ }).chat('Qwen/Qwen3-Coder-480B-A35B-Instruct');}if (env.OPENROUTER_API_KEY) return openrouter()('qwen/qwen3-coder');return null;@@ -161,7 +161,7 @@ const PROVIDERS = {return createOpenAI({apiKey: env.DEEPSEEK_API_KEY,baseURL: 'https://api.deepseek.com/v1',- })('deepseek-reasoner');+ }).chat('deepseek-reasoner');}if (env.OPENROUTER_API_KEY) return openrouter()('deepseek/deepseek-r1');return null;@@ -359,19 +359,16 @@ export default wrap(async function handler(req, res) {let firstTokenMs = null;- try {- // watsonx.ai isn't an AI SDK model — stream it through the shared client,- // emitting the same first/chunk/done event protocol the page expects.- if (spec.watsonx) {- await streamWatsonx(res, { messages, system, maxTokens, t0 });- return;- }-+ // Drains one streamText attempt to the SSE response. Returns true on success.+ // firstTokenMs is set on the first delta; once tokens have been written we are+ // committed and can no longer transparently retry (the client already has+ // partial output).+ const streamOnce = async (budget) => {const result = streamText({model,system,messages,- maxOutputTokens: maxTokens,+ maxOutputTokens: budget,});for await (const delta of result.textStream) {@@ -395,6 +392,32 @@ export default wrap(async function handler(req, res) {})}\n\n`);res.write('data: [DONE]\n\n');res.end();+ };++ try {+ // watsonx.ai isn't an AI SDK model — stream it through the shared client,+ // emitting the same first/chunk/done event protocol the page expects.+ if (spec.watsonx) {+ await streamWatsonx(res, { messages, system, maxTokens, t0 });+ return;+ }++ try {+ await streamOnce(maxTokens);+ } catch (err) {+ // OpenRouter free tier: "requires more credits, or fewer max_tokens.+ // You requested up to 1024 tokens, but can only afford 788." The+ // upstream tells us the affordable ceiling — retry once at that budget+ // (with a small safety margin) instead of hard-failing. Only safe+ // before any token has been streamed.+ const m = /can only afford (\d+)/i.exec(err?.message || '');+ if (m && firstTokenMs === null && !res.writableEnded) {+ const affordable = Math.max(64, Math.floor(Number(m[1]) * 0.9));+ await streamOnce(affordable);+ } else {+ throw err;+ }+ }} catch (err) {const elapsedMs = Date.now() - t0;if (!res.writableEnded) {diff --git a/api/x402-pay/og.js b/api/x402-pay/og.jsindex ddf82e183..98ac316c9 100644--- a/api/x402-pay/og.js+++ b/api/x402-pay/og.js@@ -191,19 +191,17 @@ export default async function handler(req, res) {}const svg = record ? svgFor(record, tx) : fallbackSvg();- try {- const png = await sharp(Buffer.from(svg)).png({ compressionLevel: 6 }).toBuffer();- res.statusCode = 200;- res.setHeader('content-type', 'image/png');- res.setHeader('cache-control', 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400');- return res.end(png);- } catch (err) {- // Graceful fallback to SVG if sharp can't render (some envs — e.g.- // missing libvips). Surface why so we notice if sharp regresses.- log.warn('og_png_render_failed', { message: err?.message });- res.statusCode = 200;- res.setHeader('content-type', 'image/svg+xml');- res.setHeader('cache-control', 'public, max-age=300');- return res.end(svg);- }+ // Serve the card as SVG directly. The previous sharp→PNG raster relied on+ // libvips' text shaping, which needs a system fontconfig that doesn't exist+ // on the Vercel serverless runtime — so every render logged+ // "Fontconfig error: Cannot load default config file" and produced+ // glyph-less text before falling back to SVG anyway. SVG is the right output+ // here: it's resolution-independent, needs no native font stack, and every+ // major unfurler (X, Discord, Slack, Telegram) accepts image/svg+xml OG+ // images — the same approach api/agent-og.js already uses. The SVG specifies+ // system-font fallback stacks so the consumer renders it with its own fonts.+ res.statusCode = 200;+ res.setHeader('content-type', 'image/svg+xml; charset=utf-8');+ res.setHeader('cache-control', 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400');+ return res.end(svg);}diff --git a/src/game/build-voxels.js b/src/game/build-voxels.jsindex 1089b2d38..bf35e428f 100644--- a/src/game/build-voxels.js+++ b/src/game/build-voxels.js@@ -118,11 +118,13 @@ export function parseKey(key) { const p = key.split(','); return [+p[0], +p[1],// Rotate a horizontal footprint offset by a quarter-turn step (0–3 = 0/90/180/270°)// about the anchor. Integer-only so a rotated piece stays perfectly grid-aligned.export function rotateXZ(dx, dz, rot) {+ // `|| 0` folds negative zero (e.g. -dx when dx===0) back to +0 so rotated+ // offsets compare cleanly and never key a cell as "-0".switch (((rot % 4) + 4) % 4) {- case 1: return [dz, -dx];- case 2: return [-dx, -dz];- case 3: return [-dz, dx];- default: return [dx, dz];+ case 1: return [dz || 0, -dx || 0];+ case 2: return [-dx || 0, -dz || 0];+ case 3: return [-dz || 0, dx || 0];+ default: return [dx || 0, dz || 0];}}diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.jsindex 45532aba9..a8c3ab842 100644--- a/src/game/coincommunities-ui.js+++ b/src/game/coincommunities-ui.js@@ -14,6 +14,7 @@ import { resolveAvatarUrl } from './avatar-rig.js';import { validateGlb, uploadGlb } from './avatar-upload.js';import { GUEST_SENTINEL, playAs } from './play-handoff.js';import { COMPOSITE_PIECES } from './build-voxels.js';+import { PROP_CATALOG } from './world-objects.js';import { log } from '../shared/log.js';// Degrees shown on the rotate button for each quarter-turn step (0–3).@@ -78,6 +79,7 @@ export class CommunityUI {this._buildLobby();this._buildHud();this._buildStructures();+ this._buildPropPalette();}// ---------------------------------------------------------------- lobby@@ -1250,6 +1252,61 @@ export class CommunityUI {this.rotateBtn.querySelector('.cc-st-rotate-deg').textContent = ROT_DEG[((rot % 4) + 4) % 4];}+ // ---------------------------------------------------------------- build props (R18)+ // The props palette that rides beside the structures toolbar in build mode: a+ // scroll-row of placeable props (crates, lamps, arches, a stage…) plus a rotate+ // button for touch (desktop also has the R key). Selecting a prop arms the object+ // placement layer; selecting it again returns to voxel building. Deleting your own+ // props reuses the build HUD's place/break toggle (break + tap removes).+ _buildPropPalette() {+ this._activeProp = null;+ this._propBtns = new Map();++ const items = PROP_CATALOG.map((p) => {+ const btn = el('button', {+ class: 'cc-prop', type: 'button',+ role: 'radio', 'aria-checked': 'false',+ title: `${p.name} — place a prop (R rotates, break mode removes yours)`,+ 'aria-label': p.name,+ onclick: () => this.h.onPickProp?.(this._activeProp === p.id ? null : p.id),+ }, [+ el('span', { class: 'cc-prop-ico', 'aria-hidden': 'true', text: p.icon || '◆' }),+ el('span', { class: 'cc-prop-name', text: p.name }),+ ]);+ this._propBtns.set(p.id, btn);+ return btn;+ });+ const row = el('div', { class: 'cc-prop-row', role: 'radiogroup', 'aria-label': 'Place a prop' }, items);++ this.propRotateBtn = el('button', {+ class: 'cc-prop-rotate', type: 'button', disabled: true,+ title: 'Rotate the prop a quarter-turn (R)', 'aria-label': 'Rotate prop',+ onclick: () => this.h.onRotateProp?.(),+ }, [el('span', { 'aria-hidden': 'true', text: '⟳' })]);++ const head = el('div', { class: 'cc-prop-head' }, [+ el('span', { class: 'cc-prop-title', text: 'Props' }),+ this.propRotateBtn,+ ]);++ this.propPalette = el('div', { id: 'cc-props', hidden: true, 'aria-label': 'Build props' }, [head, row]);+ document.body.appendChild(this.propPalette);+ }++ /** Show/hide the props palette with build mode. */+ setPropPaletteVisible(on) { if (this.propPalette) this.propPalette.hidden = !on; }++ /** Reflect the armed prop (null = voxel layer); toggles the rotate button. */+ setPropSelected(id) {+ this._activeProp = id ?? null;+ for (const [pid, btn] of this._propBtns) {+ const on = pid === this._activeProp;+ btn.classList.toggle('cc-on', on);+ btn.setAttribute('aria-checked', on ? 'true' : 'false');+ }+ if (this.propRotateBtn) this.propRotateBtn.disabled = this._activeProp == null;+ }+// ---------------------------------------------------------------- share sheet (R20)// A modal that shows the captured screenshot and offers three ways to share the// build: copy a deep link back into this world, download the image, or publishdiff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssindex 6582031d1..e3da2aa69 100644--- a/src/game/coincommunities.css+++ b/src/game/coincommunities.css@@ -1549,6 +1549,68 @@ html, body {.cc-st-piece { min-width: 46px; }}+/* ---------------- build props palette (R18) ---------------- */+/* Rides just above the structures toolbar while build mode is on: a horizontal+ scroll-row of placeable props. Arming a prop switches build clicks to the R01+ object channel; break mode + a tap removes one you placed. */+#cc-props {+ position: fixed; left: 50%; bottom: 156px; transform: translateX(-50%);+ z-index: 22; display: flex; flex-direction: column; gap: 6px;+ width: min(560px, 94vw); pointer-events: none;+ font: 13px/1.3 system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;+ animation: cc-build-in 0.16s ease;+}+#cc-props[hidden] { display: none; }+#cc-props button { pointer-events: auto; }+.cc-prop-head {+ display: flex; align-items: center; justify-content: space-between; gap: 8px;+ padding: 0 2px;+}+.cc-prop-title {+ color: var(--cc-dim); font-size: 10.5px; font-weight: 700;+ letter-spacing: 0.18em; text-transform: uppercase;+}+.cc-prop-rotate {+ display: inline-flex; align-items: center; justify-content: center;+ width: 30px; height: 30px; border-radius: var(--cc-radius-sm);+ border: 1px solid var(--cc-edge); background: var(--cc-panel); color: var(--cc-text);+ font-size: 15px; cursor: pointer;+ -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);+ transition: background 0.12s, border-color 0.12s, opacity 0.12s, transform 0.08s;+}+.cc-prop-rotate:hover { background: rgba(255, 255, 255, 0.12); border-color: var(--cc-edge-hi); }+.cc-prop-rotate:active { transform: translateY(1px) rotate(90deg); }+.cc-prop-rotate:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }+.cc-prop-rotate:disabled { opacity: 0.4; cursor: not-allowed; }+.cc-prop-row {+ display: flex; align-items: stretch; gap: 6px; padding: 7px;+ background: var(--cc-panel); border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius); box-shadow: var(--cc-shadow);+ -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);+ overflow-x: auto; scrollbar-width: thin; scroll-snap-type: x proximity;+}+.cc-prop-row::-webkit-scrollbar { height: 6px; }+.cc-prop-row::-webkit-scrollbar-thumb { background: var(--cc-edge); border-radius: 3px; }+.cc-prop {+ flex: 0 0 auto; scroll-snap-align: start;+ display: inline-flex; flex-direction: column; align-items: center; gap: 3px;+ min-width: 54px; padding: 6px 8px; border-radius: var(--cc-radius-sm);+ border: 1px solid transparent; background: rgba(255, 255, 255, 0.04);+ color: var(--cc-dim); cursor: pointer; font-weight: 600;+ transition: background 0.12s, border-color 0.12s, color 0.12s, transform 0.08s;+}+.cc-prop:hover { background: rgba(255, 255, 255, 0.1); color: var(--cc-text); transform: translateY(-2px); }+.cc-prop:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }+.cc-prop.cc-on { background: #f4f5f7; color: var(--cc-ink); border-color: #f4f5f7; }+.cc-prop-ico { font-size: 19px; line-height: 1; }+.cc-prop-name { font-size: 10px; letter-spacing: 0.02em; white-space: nowrap; }++@media (pointer: coarse) { #cc-props { bottom: 150px; } }+@media (max-width: 560px) {+ #cc-props { bottom: 156px; width: 96vw; }+ .cc-prop { min-width: 48px; }+}+/* ---------------- share-a-build sheet (R20) ---------------- */#cc-share, #cc-featured {position: fixed; inset: 0; z-index: 120; display: grid; place-items: center;@@ -1650,7 +1712,7 @@ html, body {.cc-fb-retry:hover { background: rgba(255, 255, 255, 0.12); border-color: var(--cc-edge-hi); }.cc-fb-retry:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }@media (prefers-reduced-motion: reduce) {- #cc-structures, #cc-share, #cc-featured, .cc-share-card, .cc-fb-card, .cc-fb-skel::after { animation: none; transition: none; }+ #cc-structures, #cc-props, #cc-share, #cc-featured, .cc-share-card, .cc-fb-card, .cc-fb-skel::after { animation: none; transition: none; }}/* ---------------- play gate (wallet sign-in) ----------------diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 920b7cec1..49d4d447b 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -261,6 +261,9 @@ export class CoinCommunities {// screenshot of the build, or open this coin's featured builds.onPickPiece: (id) => this._pickPiece(id),onRotateBuild: () => this._rotateBuild(),+ // Build props (R18): arm/disarm a placeable prop and rotate the armed one.+ onPickProp: (id) => this._pickProp(id),+ onRotateProp: () => this._rotateProp(),onShareBuild: () => this._shareBuild(),onOpenFeatured: () => this._openFeatured(),onPublishBuild: (meta) => this._publishBuild(meta),@@ -1160,6 +1163,8 @@ export class CoinCommunities {this.ui.setBuildPiece(null);this.ui.setPropSelected(null);this.ui.setBuildToolsVisible(false);+ this.ui.setPropPaletteVisible(false);+ this.propGhost?.hide();this.ui.closeShareSheet();this.ui.closeFeatured();try { this.localCosmetics?.dispose(); } catch {}@@ -1597,6 +1602,9 @@ export class CoinCommunities {_pickPiece(id) {this.buildPiece = COMPOSITE_PIECES.some((p) => p.id === id) ? id : null;this.buildRot = 0;+ // Arming a voxel tool disarms the prop layer — the two placement modes are+ // mutually exclusive so a build click is never ambiguous.+ if (this.buildProp) { this.buildProp = null; this.ui.setPropSelected(null); this.propGhost?.hide(); }this.ui.setBuildPiece(this.buildPiece);this.ui.setBuildRotation(this.buildRot);this._refreshGhost();@@ -1610,6 +1618,118 @@ export class CoinCommunities {this._refreshGhost();}+ // ── Props build layer (R18) ───────────────────────────────────────────────+ // Arm a placeable prop (or null to return to the voxel layer). Disarms any voxel+ // composite so the two placement modes never both fire on a click. Resets the+ // prop's rotation so each newly-picked prop starts square-on, and primes the+ // ghost so the preview appears without waiting for pointer motion.+ _pickProp(id) {+ const def = id ? propDef(id) : null;+ this.buildProp = def ? def.id : null;+ this.buildPropRot = 0;+ if (this.buildProp) {+ // Leaving the voxel layer: clear any armed composite + hide the voxel ghost.+ this.buildPiece = null; this.buildRot = 0;+ this.ui.setBuildPiece(null);+ this.voxels?.hideGhost(); this.voxels?.hideFootprint();+ this.propGhost?.setType(this.buildProp);+ } else {+ this.propGhost?.hide();+ }+ this.ui.setPropSelected(this.buildProp);+ this._refreshGhost();+ }++ // Rotate the armed prop a quarter-turn and re-preview it in place.+ _rotateProp() {+ if (!this.buildProp) return;+ this.buildPropRot = (this.buildPropRot + 1) % 4;+ this._refreshGhost();+ }++ // Where, in world space, is the player aiming a prop? A prop drops onto the+ // ground plane (props stand on the floor, they don't stack on cells), snapped to+ // a half-block grid so neighbouring props line up. Returns the snapped point + a+ // validity flag (inside the build radius), or null when aiming at the sky.+ _propTarget(clientX, clientY) {+ const ray = this._pointerRay(clientX, clientY).ray;+ if (ray.direction.y >= -1e-4) return null; // looking up / parallel — no floor+ const t = -ray.origin.y / ray.direction.y;+ if (t <= 0) return null;+ const px = ray.origin.x + ray.direction.x * t;+ const pz = ray.origin.z + ray.direction.z * t;+ const snap = BLOCK / 2;+ const x = Math.round(px / snap) * snap;+ const z = Math.round(pz / snap) * snap;+ const valid = Math.hypot(x, z) <= WORLD_RADIUS;+ return { x, y: 0, z, valid };+ }++ // Place or delete a prop under the pointer. Placing sends obj:spawn kind:'block'+ // (durable, server-persisted via R17); the prop appears for everyone when the+ // server echoes its objects state back. Right-click / hold deletes a prop YOU own+ // (server enforces ownership; we only offer it on your own pieces — R19 hardens it).+ _buildPropAt(clientX, clientY, forceRemove) {+ const removing = forceRemove || this.buildHud.mode === 'remove';+ if (removing) { this._deleteOwnPropAt(clientX, clientY); return; }+ const target = this._propTarget(clientX, clientY);+ if (!target) return;+ if (!target.valid) { this._updatePropGhost(clientX, clientY); return; }+ const online = this.net?.status === 'online';+ if (!online) {+ // Solo: there's no shared object channel to place into, so be honest rather+ // than faking a local-only prop that no one else will ever see.+ this.ui.toast('Props need a live connection — reconnect to place them.', 'warn');+ return;+ }+ const yaw = this.buildPropRot * (Math.PI / 2);+ this.net.spawnObject('block', { type: this.buildProp, x: target.x, y: target.y, z: target.z, yaw, scale: this.buildPropScale });+ // A short haptic tick confirms the place on touch devices.+ if (typeof navigator !== 'undefined' && navigator.vibrate) navigator.vibrate(12);+ this._updatePropGhost(clientX, clientY);+ }++ // Delete the nearest prop under the pointer that this client owns. Raycasts only+ // owned object nodes, so a click never offers to delete someone else's build.+ _deleteOwnPropAt(clientX, clientY) {+ if (!this.worldObjects) return;+ const owned = this.worldObjects.ownedNodes(this._ownedScratch || (this._ownedScratch = []));+ if (!owned.length) { this.ui.toast('Nothing of yours to remove here.', 'info'); return; }+ const hits = this._pointerRay(clientX, clientY).intersectObjects(owned, true);+ const id = hits.length ? this.worldObjects.idForHit(hits[0].object) : null;+ if (!id) return;+ this.net?.removeObject(id);+ if (typeof navigator !== 'undefined' && navigator.vibrate) navigator.vibrate(20);+ }++ // Drive the prop ghost: in place mode show the translucent prop at the snapped+ // pose (green valid / red blocked); in remove mode highlight nothing (the delete+ // raycast is per-click) and hide the place ghost.+ _updatePropGhost(clientX, clientY) {+ if (!this.propGhost || !this.buildProp) return;+ if (this.buildHud.mode === 'remove') { this.propGhost.hide(); return; }+ const target = this._propTarget(clientX, clientY);+ if (!target) { this.propGhost.hide(); return; }+ this.propGhost.setType(this.buildProp);+ this.propGhost.setPose(target.x, target.y, target.z, this.buildPropRot * (Math.PI / 2), this.buildPropScale);+ this.propGhost.setValid(target.valid && this.net?.status === 'online');+ this.propGhost.show();+ }++ // Explain a server-refused spawn (room full, or this player's object cap hit) so a+ // prop that never appeared isn't a silent mystery. Throttled like edit rejects.+ _onObjectReject(reason) {+ const now = performance.now();+ this._objRejectAt ||= {};+ if (now - (this._objRejectAt[reason] || 0) < 4000) return;+ this._objRejectAt[reason] = now;+ const msg = {+ world_full: 'This world is full of props — remove some to place more.',+ player_full: 'You’ve hit your prop limit for this world — remove some to place more.',+ }[reason] || 'That prop couldn’t be placed.';+ this.ui.toast(msg, 'warn');+ }+// Arm a hold-to-break timer for the current press. If the player keeps the// pointer down and still (no drag) past LONG_PRESS_MS, break the targeted block// — the touch-native equivalent of a right-click. Cancelled by movement or release.diff --git a/tests/build-voxels.test.js b/tests/build-voxels.test.jsindex cb7b843b6..1e0cd6b93 100644--- a/tests/build-voxels.test.js+++ b/tests/build-voxels.test.js@@ -17,6 +17,7 @@ globalThis.self = globalThis;import {VoxelWorld, keyOf, parseKey, cellToWorld, cellInBounds,BLOCK, MAX_GRID_XZ, MAX_GRID_Y, MAX_BLOCKS, BLOCK_TYPE_COUNT, BLOCK_TYPES,+ COMPOSITE_PIECES, MAX_COMPOSITE_CELLS, rotateXZ, compositeCells,} from '../src/game/build-voxels.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -166,6 +167,61 @@ describe('VoxelWorld', () => {});});+describe('composite pieces (R20)', () => {+ it('rotateXZ is a pure quarter-turn that round-trips after 4 steps', () => {+ expect(rotateXZ(1, 0, 0)).toEqual([1, 0]);+ expect(rotateXZ(1, 0, 1)).toEqual([0, -1]);+ expect(rotateXZ(1, 0, 2)).toEqual([-1, 0]);+ expect(rotateXZ(1, 0, 3)).toEqual([0, 1]);+ // Negative + wrapping rotations normalise to the same four orientations.+ expect(rotateXZ(2, 3, -1)).toEqual(rotateXZ(2, 3, 3));+ expect(rotateXZ(2, 3, 4)).toEqual([2, 3]);+ });++ it('every piece resolves to in-pool, integer, type-bearing cells', () => {+ for (const piece of COMPOSITE_PIECES) {+ const cells = compositeCells(piece.id, [5, 0, 5], 0, 3);+ expect(cells.length).toBeGreaterThan(0);+ expect(cells.length).toBeLessThanOrEqual(MAX_COMPOSITE_CELLS);+ for (const c of cells) {+ expect(Number.isInteger(c.x) && Number.isInteger(c.y) && Number.isInteger(c.z)).toBe(true);+ expect(c.t).toBe(3); // inherits the selected block type+ }+ // No piece repeats a cell within itself.+ const keys = new Set(cells.map((c) => keyOf(c.x, c.y, c.z)));+ expect(keys.size).toBe(cells.length);+ }+ });++ it('rotation preserves a piece\'s cell count and keeps it on the grid', () => {+ for (const piece of COMPOSITE_PIECES) {+ const base = compositeCells(piece.id, [0, 0, 0], 0, 0).length;+ for (let rot = 1; rot < 4; rot++) {+ expect(compositeCells(piece.id, [0, 0, 0], rot, 0).length).toBe(base);+ }+ }+ });++ it('an unknown piece id yields no cells (safe no-op)', () => {+ expect(compositeCells('nope', [0, 0, 0], 0, 0)).toEqual([]);+ expect(compositeCells('wall', null, 0, 0)).toEqual([]);+ });++ it('VoxelWorld.canPlaceAll gates on bounds, occupancy, and budget', () => {+ const w = new VoxelWorld(fakeScene());+ const cells = compositeCells('wall', [4, 0, 4], 0, 0);+ expect(w.canPlaceAll(cells, MAX_BLOCKS)).toBe(true);+ // Out of bounds (beyond the circular plaza) → rejected wholesale.+ expect(w.canPlaceAll(compositeCells('wall', [MAX_GRID_XZ + 5, 0, 0], 0, 0), MAX_BLOCKS)).toBe(false);+ // Budget that can't fit the fresh cells → rejected.+ expect(w.canPlaceAll(cells, 3)).toBe(false);+ // Already-occupied cells don't count against a fresh budget.+ for (const c of cells) w.setBlock(c.x, c.y, c.z, c.t);+ expect(w.canPlaceAll(cells, w.count)).toBe(true); // repaint-in-place fits exactly+ w.dispose();+ });+});+describe('client ↔ server constant parity', () => {// The server validates every edit against its own copies of these caps. If the// client's diverge, players get a build experience that lies (placeable cells@@ -184,4 +240,11 @@ describe('client ↔ server constant parity', () => {expect(BLOCK_TYPE_COUNT).toBe(num('BLOCK_TYPE_COUNT'));expect(BLOCK_TYPES.length).toBe(BLOCK_TYPE_COUNT);});++ it('the largest composite piece fits the server\'s place-batch cap', () => {+ // The server rejects any batch larger than MAX_BATCH_CELLS, so the biggest+ // piece the client can stamp must never exceed it — else a legit piece would+ // be silently refused.+ expect(MAX_COMPOSITE_CELLS).toBeLessThanOrEqual(num('MAX_BATCH_CELLS'));+ });});