Spaces:
Running on Zero

gpwm-simulation / web /viewer.js
robertren1's picture
Drop anything: the Gradio app
c4ac8d1 verified
Raw History Blame Contribute Delete
33.6 kB
// Drop anything: the page side of the Space (run by Gradio's gr.HTML as js_on_load, with `element`, `trigger`, `server`).
// The renderer is the live demo's (pwm-live-drop web/index.html): lit point sprites, a soft contact shadow, each object's
// coloured points following its 4 nearest particles. Actions wait ("pending") until Run; Run sends them with
// trigger('click', {op, actions, req}); the reply comes back through window.dropAnything.receive(text).
(async () => {
if (element.__dropAnything) return;
element.__dropAnything = true;
const root = element.querySelector('.da');
const q = (s) => root.querySelector(s);
// a direct visit (not inside huggingface.co's frame): leave room for Hugging Face's badge at the top right
try { if (window.self === window.top) root.classList.add('da-badge'); } catch (e) { /* inside a frame */ }
const hintEl = q('.da-hint'), statusEl = q('.da-status'), busyEl = q('.da-busy');
let hintTimer = null;
const setHint = (t) => { hintEl.textContent = t; };
const flash = (t) => { setHint(t); clearTimeout(hintTimer); hintTimer = setTimeout(updateHint, 4000); };
let THREE, OrbitControls;
try {
THREE = await import('https://cdn.jsdelivr.net/npm/three@0.160.0/+esm');
({ OrbitControls } = await import('https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/controls/OrbitControls.js/+esm'));
} catch (e) {
setHint('The 3D view could not load (three.js from cdn.jsdelivr.net): ' + e);
return;
}
const LEVELS = 65535, BOX_LO = [-0.85, -0.85, -0.05], BOX_HI = [0.85, 0.85, 1.0];
const BOX = 0.42, MAX_OBJECTS = 20, FPS = 24;
const MATERIAL_NAMES = { 0: 'Elastic', 1: 'Clay', 2: 'Sand' };
const STIFF = [[1e4, 'Soft'], [1e5, 'Medium'], [1e6, 'Stiff']];
// ------------------------------------------------------------------------------------------------------- decoding
async function inflate(b64) {
const bin = atob(b64), bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate'));
return await new Response(stream).arrayBuffer();
}
function readWindow(buf) {
// header: magic, version, flags, frame count, first frame, point count; first frame uint16, then int16 changes
const dv = new DataView(buf);
const flags = dv.getUint8(5), L = dv.getUint16(6, true), first = dv.getUint32(8, true), N = dv.getUint32(12, true);
const n3 = N * 3, raw = new Uint16Array(buf, 16, L * n3), d = new Int16Array(buf, 16, L * n3);
const shift = (flags >> 4) & 15, half = (1 << shift) >> 1, coarse = new Int32Array(n3);
const span = [BOX_HI[0] - BOX_LO[0], BOX_HI[1] - BOX_LO[1], BOX_HI[2] - BOX_LO[2]];
const frames = [];
for (let k = 0; k < L; k++) {
const pos = new Float32Array(n3), off = k * n3;
for (let i = 0; i < n3; i++) {
coarse[i] = k === 0 ? raw[i] : coarse[i] + d[off + i];
const c = i % 3;
pos[i] = BOX_LO[c] + Math.min(LEVELS, (coarse[i] << shift) + half) / LEVELS * span[c];
}
frames.push(pos);
}
return { first, L, N, frames };
}
// ------------------------------------------------------------------------------------------------------- renderer
const canvas = q('.da-canvas'), stage = q('.da-stage');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeef0ec);
const camera = new THREE.PerspectiveCamera(32, 1, 0.05, 30);
camera.up.set(0, 0, 1);
camera.position.set(1.16, -0.94, 0.86);
const controls = new OrbitControls(camera, canvas);
controls.target.set(0, 0, 0.1);
controls.enableDamping = true; controls.dampingFactor = 0.08; controls.maxPolarAngle = Math.PI * 0.48;
controls.minDistance = 0.5; controls.maxDistance = 5; controls.enablePan = false;
const SHADOW_RES = 512, SHADOW_EXT = 2.0;
const shadowTarget = new THREE.WebGLRenderTarget(SHADOW_RES, SHADOW_RES, { type: THREE.HalfFloatType });
const shadowCam = new THREE.OrthographicCamera(-SHADOW_EXT / 2, SHADOW_EXT / 2, SHADOW_EXT / 2, -SHADOW_EXT / 2, 0.01, 10);
shadowCam.up.set(0, 1, 0); shadowCam.position.set(0, 0, 3); shadowCam.lookAt(0, 0, 0);
const shadowScene = new THREE.Scene();
const table = new THREE.Mesh(new THREE.PlaneGeometry(2.4, 2.0), new THREE.ShaderMaterial({
uniforms: { uShadow: { value: shadowTarget.texture }, uExt: { value: SHADOW_EXT }, uTable: { value: new THREE.Color(0xfbfbf8) },
uZone: { value: BOX } },
vertexShader: `varying vec3 vW; void main(){ vec4 w = modelMatrix*vec4(position,1.); vW = w.xyz; gl_Position = projectionMatrix*viewMatrix*w; }`,
fragmentShader: `uniform sampler2D uShadow; uniform float uExt, uZone; uniform vec3 uTable; varying vec3 vW;
void main(){
vec2 uv = vW.xy / uExt + 0.5; float occ = 0.;
if (all(greaterThan(uv, vec2(0.))) && all(lessThan(uv, vec2(1.)))) occ = texture2D(uShadow, uv).r;
float shade = 1. - 0.6 * (1. - exp(-1.5 * occ));
vec2 a = abs(vW.xy); float edge = max(a.x, a.y);
float line = smoothstep(0.0025, 0., abs(edge - uZone)) * step(0.5, fract((vW.x + vW.y) * 18.));
gl_FragColor = vec4(uTable * shade * (1. - 0.12 * line), 1.);
#include <colorspace_fragment>
}` }));
const slab = new THREE.Mesh(new THREE.BoxGeometry(2.4, 2.0, 0.04), new THREE.MeshStandardMaterial({ color: 0xe4e2db, roughness: 0.9 }));
slab.position.z = -0.0201;
scene.add(table, slab, new THREE.HemisphereLight(0xffffff, 0xd8d2c8, 1.2));
const ballVertex = `attribute vec3 color; attribute float alive; uniform float uRadius, uFocal; varying vec3 vColor; varying vec3 vCentre;
void main(){ vec4 mv = modelViewMatrix * vec4(position, 1.); vColor = color; vCentre = mv.xyz;
gl_Position = projectionMatrix * mv; gl_PointSize = alive < 0.5 ? 0. : 2. * uRadius * uFocal / max(-mv.z, 1e-3); }`;
const ballFragment = `uniform mat4 uProj; uniform float uRadius, uOpacity; uniform vec3 uKey; varying vec3 vColor; varying vec3 vCentre;
void main(){ vec2 p = gl_PointCoord * 2. - 1.; p.y = -p.y; float r2 = dot(p, p);
float edge = clamp((1. - r2) / max(fwidth(r2), 1e-4), 0., 1.); if (edge <= 0.) discard;
vec3 n = vec3(p, sqrt(max(1. - r2, 0.))); vec4 clip = uProj * vec4(vCentre + n * uRadius, 1.);
gl_FragDepth = clip.z / clip.w * 0.5 + 0.5;
vec3 albedo = pow(vColor, vec3(2.2)); float wrap = max((dot(n, uKey) + 0.35) / 1.35, 0.);
vec3 h = normalize(uKey + vec3(0., 0., 1.)); float spec = pow(max(dot(n, h), 0.), 24.) * 0.08;
vec3 lit = albedo * (0.45 + 0.55 * wrap) * mix(0.85, 1., n.z) + spec;
gl_FragColor = vec4(lit, edge * uOpacity);
#include <colorspace_fragment>
}`;
function ballMaterial(radius, opacity = 1) {
return new THREE.ShaderMaterial({ alphaToCoverage: opacity >= 1, transparent: opacity < 1, depthWrite: opacity >= 1,
uniforms: { uRadius: { value: radius }, uFocal: { value: 800 }, uProj: { value: camera.projectionMatrix },
uOpacity: { value: opacity }, uKey: { value: new THREE.Vector3(-0.35, -0.5, 0.8).normalize() } },
vertexShader: ballVertex, fragmentShader: ballFragment });
}
const shadowMaterial = new THREE.ShaderMaterial({
uniforms: { uPx: { value: SHADOW_RES / SHADOW_EXT } },
vertexShader: `attribute float alive; uniform float uPx; varying float vA;
void main(){ float h = max(position.z, 0.); vA = alive < 0.5 ? 0. : 0.16 * exp(-h / 0.08);
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.); gl_PointSize = alive < 0.5 ? 0. : (0.012 + 0.3 * h) * uPx; }`,
fragmentShader: `varying float vA; void main(){ vec2 p = gl_PointCoord*2.-1.; float r2 = dot(p,p); if (r2>1.) discard;
gl_FragColor = vec4(vA * exp(-3.*r2), 0., 0., 1.); }`,
transparent: true, blending: THREE.AdditiveBlending, depthTest: false, depthWrite: false });
const material = ballMaterial(0.0024), ghostMaterial = ballMaterial(0.0024, 0.45);
// ------------------------------------------------------------------------------------------------------- the shelf
let menu = [], shelf = new Map();
async function drawingOf(id) {
const s = shelf.get(id);
if (!s) throw new Error('unknown object ' + id);
if (s.data) return s.data;
if (s.loading) return s.loading;
s.loading = (async () => {
const buf = await inflate(await server.object_drawing(id));
const dv = new DataView(buf), P = dv.getUint32(0, true), M = dv.getUint32(4, true);
let o = 8;
const take = (Type, n, bytes) => { const a = new Type(buf.slice(o, o + n * bytes)); o += n * bytes; return a; };
const particles = take(Float32Array, P * 3, 4), near = take(Uint16Array, M * 4, 2), weight = take(Float32Array, M * 4, 4);
const offset = take(Float32Array, M * 3, 4), rgb = take(Uint8Array, M * 3, 1);
s.data = { P, M, particles, near, weight, offset, rgb };
return s.data;
})();
return s.loading;
}
function skin(data, particles, out, at, base = null) {
// each coloured point: the weighted position of its 4 particles plus its rest offset (base: an added translation)
const { M, near, weight, offset } = data;
for (let i = 0; i < M; i++) {
let x = offset[3 * i], y = offset[3 * i + 1], z = offset[3 * i + 2];
for (let k = 0; k < 4; k++) {
const j = near[4 * i + k] * 3, w = weight[4 * i + k];
x += w * particles[j]; y += w * particles[j + 1]; z += w * particles[j + 2];
}
if (base) { x += base[0]; y += base[1]; z += base[2]; }
out[at + 3 * i] = x; out[at + 3 * i + 1] = y; out[at + 3 * i + 2] = Math.max(z, 0.0005);
}
}
function cloud(data, base, mat) {
const g = new THREE.BufferGeometry();
const pos = new Float32Array(data.M * 3); skin(data, data.particles, pos, 0, base);
const col = new Float32Array(data.M * 3); for (let i = 0; i < data.M * 3; i++) col[i] = data.rgb[i] / 255;
g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('color', new THREE.BufferAttribute(col, 3));
g.setAttribute('alive', new THREE.BufferAttribute(new Float32Array(data.M).fill(1), 1));
const p = new THREE.Points(g, mat); p.frustumCulled = false; return p;
}
// ------------------------------------------------------------------------------------------------- the table state
let objects = [], version = -1, layoutKey = '';
const drawn = { geometry: null, points: null, shadow: null, layout: [] };
let run = null; // the last run: {first, L, N, frames}
let current = null; // the frame shown when nothing plays: Float32Array
let playStart = null;
function rebuild() {
if (drawn.points) { scene.remove(drawn.points); shadowScene.remove(drawn.shadow); drawn.geometry.dispose(); }
const layout = []; let total = 0;
for (const o of objects) { const s = shelf.get(o.shelf_id); if (!s || !s.data) continue; layout.push({ obj: o, data: s.data, offset: total }); total += s.data.M; }
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(Math.max(1, total) * 3), 3).setUsage(THREE.DynamicDrawUsage));
const colours = new Float32Array(Math.max(1, total) * 3), alive = new Float32Array(Math.max(1, total));
for (const l of layout) for (let i = 0; i < l.data.M * 3; i++) colours[l.offset * 3 + i] = l.data.rgb[i] / 255;
g.setAttribute('color', new THREE.BufferAttribute(colours, 3));
g.setAttribute('alive', new THREE.BufferAttribute(alive, 1).setUsage(THREE.DynamicDrawUsage));
drawn.geometry = g; drawn.layout = layout;
drawn.points = new THREE.Points(g, material); drawn.points.frustumCulled = false;
drawn.shadow = new THREE.Points(g, shadowMaterial); drawn.shadow.frustumCulled = false;
scene.add(drawn.points); shadowScene.add(drawn.shadow);
}
function pose(P, N) {
if (!drawn.geometry) return;
const pos = drawn.geometry.attributes.position.array, alive = drawn.geometry.attributes.alive.array;
for (const l of drawn.layout) {
const on = l.obj.start + l.obj.n <= N;
alive.fill(on ? 1 : 0, l.offset, l.offset + l.data.M);
if (on) skin(l.data, P.subarray(l.obj.start * 3, (l.obj.start + l.obj.n) * 3), pos, l.offset * 3);
}
drawn.geometry.attributes.position.needsUpdate = true; drawn.geometry.attributes.alive.needsUpdate = true;
}
// ------------------------------------------------------------------------------------------------ pending actions
let pending = []; // {type:'drop', id, x, y, height, material, E, ghost} | {type:'rain', count} | {type:'pull'|'lift', uid, ...}
let placing = null, selected = null, pulling = null, busy = false, req = 0, lastHover = 0;
const placeGhost = new THREE.Points(new THREE.BufferGeometry(), ghostMaterial); placeGhost.visible = false; placeGhost.frustumCulled = false;
const marker = new THREE.Mesh(new THREE.RingGeometry(0.03, 0.036, 48), new THREE.MeshBasicMaterial({ color: 0xd9662f, transparent: true, opacity: 0.85, depthTest: false }));
marker.renderOrder = 5; marker.visible = false;
const dropLine = new THREE.Line(new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(), new THREE.Vector3()]),
new THREE.LineDashedMaterial({ color: 0xd9662f, dashSize: 0.012, gapSize: 0.01, transparent: true, depthTest: false }));
dropLine.renderOrder = 5; dropLine.visible = false;
const arrow = new THREE.ArrowHelper(new THREE.Vector3(1, 0, 0), new THREE.Vector3(), 0.1, 0xd9662f, 0.03, 0.02); arrow.visible = false;
const pendingGroup = new THREE.Group();
scene.add(placeGhost, marker, dropLine, arrow, pendingGroup);
function drops() { return pending.filter((a) => a.type === 'drop'); }
function drags() { return pending.filter((a) => a.type === 'pull' || a.type === 'lift'); }
function rainCount() { return pending.filter((a) => a.type === 'rain').reduce((n, a) => n + a.count, 0); }
function waitingCount() { return drops().length + rainCount(); }
function renderPending() {
pendingGroup.clear();
for (const a of pending) {
if (a.type === 'drop' && a.ghost) {
pendingGroup.add(a.ghost);
const ring = marker.clone(); ring.visible = true; ring.position.set(a.x, a.y, 0.003); pendingGroup.add(ring);
} else if ((a.type === 'pull' || a.type === 'lift') && a.from) {
const dir = a.type === 'lift' ? new THREE.Vector3(0, 0, 1) : new THREE.Vector3(a.dx, a.dy, 0).normalize();
const len = a.type === 'lift' ? 0.12 : Math.max(0.02, Math.hypot(a.dx, a.dy));
pendingGroup.add(new THREE.ArrowHelper(dir, new THREE.Vector3(...a.from), len, 0xd9662f, 0.03, 0.02));
}
}
const parts = [];
if (drops().length) parts.push(`${drops().length} drop${drops().length > 1 ? 's' : ''}`);
if (rainCount()) parts.push(`${rainCount()} random`);
for (const a of drags()) parts.push(a.type === 'lift' ? 'a lift' : 'a pull');
for (const a of pending.filter((x) => x.type === 'material')) parts.push(`${MATERIAL_NAMES[a.material].toLowerCase()} for one object`);
q('.da-pending').textContent = parts.length ? `Waiting for Run: ${parts.join(', ')}.` : 'Nothing waiting.';
q('.da-clearp').hidden = !pending.length;
q('.da-run').disabled = busy || (!pending.length && !(run && !stillAfter));
updateHint();
}
function addPending(a) {
const isDrag = a.type === 'pull' || a.type === 'lift', isDrop = a.type === 'drop' || a.type === 'rain';
if (isDrag && (waitingCount() || drags().length)) { flash(drags().length ? 'One pull at a time: Run it first.' : 'Run the waiting drops first, then pull.'); return false; }
if (isDrop && drags().length) { flash('Run the waiting pull first, then drop.'); return false; }
if (isDrop && objects.length + waitingCount() + (a.type === 'rain' ? a.count : 1) > MAX_OBJECTS) { flash(`The table holds at most ${MAX_OBJECTS} objects.`); return false; }
pending.push(a); renderPending(); return true;
}
// -------------------------------------------------------------------------------------------------------- picking
const raycaster = new THREE.Raycaster(), ndc = new THREE.Vector2(), _v = new THREE.Vector3();
function tablePoint(ev, z = 0.002) {
const r = canvas.getBoundingClientRect();
ndc.set(((ev.clientX - r.left) / r.width) * 2 - 1, -((ev.clientY - r.top) / r.height) * 2 + 1);
raycaster.setFromCamera(ndc, camera);
const hit = new THREE.Vector3();
return raycaster.ray.intersectPlane(new THREE.Plane(new THREE.Vector3(0, 0, 1), -z), hit) ? [hit.x, hit.y] : null;
}
function pickObject(ev) {
if (!drawn.geometry) return null;
const r = canvas.getBoundingClientRect(), px = ev.clientX - r.left, py = ev.clientY - r.top;
const pos = drawn.geometry.attributes.position.array, alive = drawn.geometry.attributes.alive.array;
let best = null, bd = 14 * 14;
for (const l of drawn.layout) for (let i = 0; i < l.data.M; i += 3) {
const k = l.offset + i; if (alive[k] < 0.5) continue;
_v.set(pos[3 * k], pos[3 * k + 1], pos[3 * k + 2]).project(camera);
const d = ((_v.x + 1) / 2 * r.width - px) ** 2 + ((1 - _v.y) / 2 * r.height - py) ** 2;
if (d < bd) { bd = d; best = l.obj; }
}
return best;
}
function objectTop(uid) {
const l = drawn.layout.find((x) => x.obj.uid === uid); if (!l) return null;
const pos = drawn.geometry.attributes.position.array; let top = null;
for (let i = 0; i < l.data.M; i++) { const k = l.offset + i; if (!top || pos[3 * k + 2] > top[2]) top = [pos[3 * k], pos[3 * k + 1], pos[3 * k + 2]]; }
return top;
}
// -------------------------------------------------------------------------------------------------------- placing
async function startPlacing(entry) {
selected = null;
placing = { id: entry.id, entry, material: entry.material, E: entry.E, height: Number(q('.da-h').value) / 100, x: 0, y: 0, data: null };
canvas.style.cursor = 'crosshair';
renderPanel(); showShelf();
const data = await drawingOf(entry.id);
if (!placing || placing.id !== entry.id) return;
placing.data = data;
const p = cloud(data, null, ghostMaterial);
placeGhost.geometry.dispose(); placeGhost.geometry = p.geometry; placeGhost.visible = true;
}
function stopPlacing() { placing = null; placeGhost.visible = marker.visible = dropLine.visible = false; canvas.style.cursor = ''; renderPanel(); showShelf(); }
function setHeight(h) {
q('.da-htext').textContent = `${h} cm`;
if (placing) { placing.height = h / 100; placeGhost.position.z = 0.002 + placing.height; }
}
canvas.addEventListener('pointermove', (ev) => {
if (placing) {
const p = tablePoint(ev); if (!p) return;
placing.x = Math.max(-BOX, Math.min(BOX, p[0])); placing.y = Math.max(-BOX, Math.min(BOX, p[1]));
placeGhost.position.set(placing.x, placing.y, 0.002 + placing.height);
marker.position.set(placing.x, placing.y, 0.003); marker.visible = true;
dropLine.geometry.attributes.position.array.set([placing.x, placing.y, 0.003, placing.x, placing.y, 0.002 + placing.height]);
dropLine.geometry.attributes.position.needsUpdate = true; dropLine.computeLineDistances(); dropLine.visible = true;
} else if (!pulling && !busy && ev.buttons === 0) {
// a hand over objects that can be pulled (checked at most every 60 ms: it projects the object points)
const t = performance.now();
if (t - lastHover > 60) { lastHover = t; const hit = pickObject(ev); canvas.style.cursor = hit && hit.material !== 2 ? 'grab' : ''; }
} else if (pulling) {
const p = tablePoint(ev, pulling.from[2]); if (!p) return;
let dx = p[0] - pulling.from[0], dy = p[1] - pulling.from[1]; const len = Math.hypot(dx, dy), max = 0.19;
if (len > max) { dx *= max / len; dy *= max / len; }
pulling.to = [dx, dy];
arrow.position.set(...pulling.from); arrow.setDirection(_v.set(dx, dy, 0).normalize());
arrow.setLength(Math.max(0.02, Math.hypot(dx, dy)), 0.03, 0.02); arrow.visible = Math.hypot(dx, dy) > 0.01;
}
});
canvas.addEventListener('pointerdown', (ev) => {
if (ev.button !== 0 || busy) return;
if (placing) {
if (!placing.data) return;
const g = cloud(placing.data, [placing.x, placing.y, 0.002 + placing.height], ghostMaterial);
addPending({ type: 'drop', id: placing.id, x: placing.x, y: placing.y, height: placing.height, material: placing.material,
E: placing.E, ghost: g });
ev.stopImmediatePropagation(); return;
}
const hit = pickObject(ev);
if (hit && hit.material !== 2) {
selected = hit.uid; const top = objectTop(hit.uid);
if (top) { pulling = { uid: hit.uid, from: top, to: [0, 0] }; controls.enabled = false; canvas.setPointerCapture(ev.pointerId); canvas.style.cursor = 'grabbing'; }
renderPanel(); ev.stopImmediatePropagation();
} else if (hit) { selected = hit.uid; renderPanel(); }
}, true);
canvas.addEventListener('pointerup', () => {
if (pulling) {
const [dx, dy] = pulling.to;
if (Math.hypot(dx, dy) > 0.015) addPending({ type: 'pull', uid: pulling.uid, dx, dy, from: pulling.from });
pulling = null; arrow.visible = false; controls.enabled = true; canvas.style.cursor = 'grab';
updateHint();
}
});
canvas.addEventListener('wheel', (ev) => {
if (!placing) return;
ev.preventDefault();
const h = Math.max(8, Math.min(60, Math.round(placing.height * 100 - Math.sign(ev.deltaY) * 2)));
q('.da-h').value = h; setHeight(h);
}, { passive: false });
window.addEventListener('keydown', (ev) => { if (ev.key === 'Escape' && placing) stopPlacing(); });
q('.da-h').addEventListener('input', (ev) => setHeight(Number(ev.target.value)));
// ---------------------------------------------------------------------------------------------------------- panel
function chip(label, on, onClick) {
const b = document.createElement('button'); b.type = 'button'; b.className = 'da-btn'; b.textContent = label;
b.setAttribute('aria-pressed', String(on)); b.addEventListener('click', onClick); return b;
}
function renderPanel() {
const card = q('.da-sel'), obj = objects.find((o) => o.uid === selected), target = placing || obj;
card.hidden = !target;
if (target) {
const waitingMat = obj ? pending.find((a) => a.type === 'material' && a.uid === obj.uid) : null;
const mat = placing ? placing.material : (waitingMat ? waitingMat.material : obj.material);
const E = placing ? placing.E : (waitingMat ? waitingMat.E : obj.E);
q('.da-sel-title').textContent = placing ? `Dropping: ${placing.entry.label}` : `On the table: ${obj.label}`;
const setMat = (m, e) => {
if (placing) { placing.material = m; placing.E = e; }
else { pending = pending.filter((a) => !(a.type === 'material' && a.uid === obj.uid)); pending.push({ type: 'material', uid: obj.uid, material: m, E: e }); renderPending(); }
renderPanel();
};
q('.da-mats').replaceChildren(...[0, 1, 2].map((m) => chip(MATERIAL_NAMES[m], m === mat, () => setMat(m, E))));
q('.da-stiff').replaceChildren(...STIFF.map(([e, n]) => chip(n, Math.abs(Math.log10(e) - Math.log10(E)) < 0.01, () => setMat(mat, e))));
q('.da-height').hidden = !placing;
const acts = [];
if (placing) acts.push(Object.assign(document.createElement('button'), { className: 'da-btn', type: 'button', textContent: 'Done', onclick: stopPlacing }));
else if (obj.material !== 2) acts.push(Object.assign(document.createElement('button'), { className: 'da-btn', type: 'button',
textContent: 'Lift and drop', onclick: () => { const top = objectTop(obj.uid); addPending({ type: 'lift', uid: obj.uid, from: top }); } }));
q('.da-sel-actions').replaceChildren(...acts);
q('.da-sel-note').textContent = placing ? 'Each click on the table drops one more. Scroll over the table to change the height.'
: obj.material === 2 ? 'Sand can be dropped onto, not pulled: the pulling model never saw sand.'
: 'Drag it across the table to pull it by its top, or lift it and let go.';
}
updateHint();
}
let matFilter = null; // show one material only (null: all)
function renderFilters() {
const make = (label, n, value) => {
const b = chip(label, matFilter === value, () => { matFilter = value; renderFilters(); showShelf(); });
b.append(Object.assign(document.createElement('span'), { className: 'da-n', textContent: String(n) }));
return b;
};
const counts = [0, 1, 2].map((m) => menu.filter((e) => e.material === m).length);
q('.da-filters').replaceChildren(make('All', menu.length, null),
...[0, 1, 2].filter((m) => counts[m]).map((m) => make(MATERIAL_NAMES[m], counts[m], m)));
}
function showShelf() {
const grid = q('.da-grid'), f = q('.da-search').value.trim().toLowerCase();
grid.replaceChildren();
let shown = 0;
for (const e of menu) {
if (matFilter !== null && e.material !== matFilter) continue;
if (f && !(`${e.label} ${MATERIAL_NAMES[e.material]}`.toLowerCase().includes(f))) continue;
shown += 1;
const b = document.createElement('button');
b.className = 'da-item'; b.type = 'button'; b.dataset.id = e.id; b.setAttribute('aria-pressed', String(!!placing && placing.id === e.id));
b.title = `${e.label}: ${MATERIAL_NAMES[e.material]}, ${e.size_cm} cm`;
const img = document.createElement('img'); img.loading = 'lazy'; img.alt = ''; img.src = e.thumb;
const t = document.createElement('span'); t.textContent = e.label;
b.append(img, t); b.addEventListener('click', () => startPlacing(e)); grid.append(b);
}
if (!shown && menu.length) grid.append(Object.assign(document.createElement('div'), { className: 'da-empty', textContent: 'No object matches.' }));
q('.da-count').textContent = shown === menu.length ? `${menu.length}` : `${shown} of ${menu.length}`;
}
q('.da-search').addEventListener('input', showShelf);
let stillAfter = true;
function updateHint() {
if (busy) { setHint('Predicting the next 2 seconds…'); return; }
if (placing) { setHint('Click the table to drop it there. Scroll to change the height.'); return; }
if (pulling) { setHint('Let go to pull it that way.'); return; }
if (pending.length) { setHint('Press Run to see the next 2 seconds.'); return; }
if (run && !stillAfter) { setHint('Still moving: press Run for 2 more seconds.'); return; }
setHint(objects.length ? 'Drop more from the shelf, or drag an object to pull it.'
: 'Pick an object on the right, then click the table to drop it.');
}
// ------------------------------------------------------------------------------------------------- talking to Python
function payload(a) { const { ghost, from, ...rest } = a; return rest; }
let lastOp = null;
function send(op) {
busy = true; busyEl.hidden = false; q('.da-run').disabled = true; renderPending();
req += 1; lastOp = op;
trigger('click', { op, req, actions: op === 'run' ? pending.map(payload) : [] });
}
q('.da-run').addEventListener('click', () => { if (!busy) { stopPlacing(); send('run'); } });
q('.da-replay').addEventListener('click', () => { if (run) playStart = performance.now(); });
q('.da-rain').addEventListener('click', () => addPending({ type: 'rain', count: 5 }));
q('.da-clearp').addEventListener('click', () => { pending = []; renderPending(); renderPanel(); });
q('.da-reset').addEventListener('click', () => { if (!busy) { pending = []; stopPlacing(); selected = null; send('reset'); } });
// the maintainer's self-check: the golden scenes on this GPU against the training cluster's frames (?check=1)
try { q('.da-check').hidden = new URLSearchParams(window.location.search).get('check') !== '1'; } catch (e) { /* keep hidden */ }
q('.da-check').addEventListener('click', () => { if (!busy) send('check'); });
async function receive(text) {
let r;
try { r = JSON.parse(text); } catch (e) { return; }
if (r.req !== req) return; // an answer to an older request
busy = false; busyEl.hidden = true;
const ids = [...new Set((r.objects || []).map((o) => o.shelf_id))];
await Promise.all(ids.map((id) => drawingOf(id).catch(() => null)));
const key = JSON.stringify([r.version, (r.objects || []).map((o) => [o.uid, o.start, o.n])]);
objects = r.objects || [];
if (key !== layoutKey) { layoutKey = key; rebuild(); }
if (r.version !== version) { version = r.version; run = null; current = null; }
if (r.frames) {
run = readWindow(await inflate(r.frames));
playStart = performance.now();
current = run.frames[run.L - 1];
} else if (r.last) {
const w = readWindow(await inflate(r.last)); current = w.frames[0];
if (!objects.length) run = null;
} else { current = null; }
if (lastOp !== 'check') pending = []; // the waiting actions went with this Run
stillAfter = !!r.still; // before renderPending: Run stays on while things move
renderPending();
q('.da-replay').disabled = !run;
if (r.ms && r.ms.length) {
const total = r.ms.reduce((a, b) => a + b, 0) / 1000, motion = (r.count || 0) / FPS;
const models = [...new Set(r.models)].map((m) => m === 'dragging' ? 'Dragging model' : 'Free Fall model').join(' + ');
const gpu = String(r.gpu || 'the GPU').replace('NVIDIA ', '').replace(' Server Edition', '').replace(/\s+MIG\s.*$/, '');
statusEl.replaceChildren(Object.assign(document.createElement('b'), { textContent: models }),
document.createTextNode(` · ${motion.toFixed(1)} s of motion predicted in ${total.toFixed(1)} s · ${gpu}`));
statusEl.hidden = false;
}
if (selected !== null && !objects.some((o) => o.uid === selected)) selected = null;
renderPanel();
if (r.notes && r.notes.length) flash(r.notes.join(' ')); else updateHint();
}
window.dropAnything = { receive, get pending() { return pending; }, get objects() { return objects; }, get run() { return run; },
get busy() { return busy; }, get menu() { return menu; }, camera,
screenOf(x, y, z) { _v.set(x, y, z).project(camera); const r = canvas.getBoundingClientRect();
return { sx: r.left + (_v.x + 1) / 2 * r.width, sy: r.top + (1 - _v.y) / 2 * r.height }; } };
// ----------------------------------------------------------------------------------------------------- the loop
function resize() {
const w = Math.max(1, stage.clientWidth), h = Math.max(1, stage.clientHeight);
renderer.setSize(w, h, false); camera.aspect = w / h; camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(stage); resize();
const interp = { buf: new Float32Array(0) };
function draw(now) {
requestAnimationFrame(draw);
controls.update();
if (run && playStart !== null) {
// the animation frame's time can precede playStart (set later in the same frame): clamp at 0
const f = Math.max(0, Math.min((now - playStart) / 1000 * FPS, run.L - 1)), f0 = Math.floor(f), a = f - f0;
const A = run.frames[f0], B = run.frames[Math.min(f0 + 1, run.L - 1)], n3 = run.N * 3;
if (interp.buf.length < n3) interp.buf = new Float32Array(n3);
for (let i = 0; i < n3; i++) interp.buf[i] = A[i] + (B[i] - A[i]) * a;
pose(interp.buf, run.N);
if (f >= run.L - 1) playStart = null;
} else if (current) {
pose(current, current.length / 3);
}
renderer.autoClear = false;
renderer.setRenderTarget(shadowTarget); renderer.setClearColor(0x000000, 0); renderer.clear();
if (drawn.shadow) renderer.render(shadowScene, shadowCam);
renderer.setRenderTarget(null); renderer.autoClear = true;
const focal = renderer.domElement.height / (2 * Math.tan(THREE.MathUtils.degToRad(camera.fov) / 2));
material.uniforms.uFocal.value = ghostMaterial.uniforms.uFocal.value = focal;
renderer.render(scene, camera);
}
requestAnimationFrame(draw);
// ------------------------------------------------------------------------------------------------- the first look
try {
menu = (await server.shelf_menu()).sort((a, b) => a.label.localeCompare(b.label));
} catch (e) { setHint('The shelf could not load: ' + e); return; }
shelf = new Map(menu.map((e) => [e.id, { entry: e, data: null }]));
renderFilters();
showShelf();
// three sturdy objects wait above the table, so the first Run shows the model at once
const sturdy = menu.filter((e) => e.material === 0 && e.E >= 1e5);
const liked = sturdy.filter((e) => /ball|car|duck|apple|orange|toy|block|cube|mallet|lemon/i.test(e.label));
const picks = [...liked, ...sturdy].filter((e, i, all) => all.findIndex((x) => x.label === e.label) === i).slice(0, 3);
const spots = [[-0.16, -0.02, 0.26], [0.06, 0.14, 0.32], [0.13, -0.12, 0.2]];
for (let i = 0; i < picks.length; i++) {
const e = picks[i], data = await drawingOf(e.id).catch(() => null);
if (!data) continue;
const [x, y, h] = spots[i];
pending.push({ type: 'drop', id: e.id, x, y, height: h, material: e.material, E: e.E, ghost: cloud(data, [x, y, 0.002 + h], ghostMaterial) });
}
renderPending();
renderPanel();
})();