import './style.css';
import { MODEL, LIMITS, EXAMPLES, RUNTIME } from './config.js';
import { workSize, rgbaToNCHW, depthStats, depthToRGBA, normalsToRGBA, measure, calibrationFactor, toPLY, validateFile, validateDims } from './geometry.js';
import { PointViewer } from './viewer.js';
const $ = (s) => document.querySelector(s);
const fmtM = (m) => (m < 1 ? `${(m * 100).toFixed(1).replace('.', ',')} cm` : `${m.toFixed(2).replace('.', ',')} m`);
const fmtN = (x, d = 2) => x.toFixed(d).replace('.', ',');
const DISPLAY_MAX = 1600;
const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
const state = { loaded: false, busy: false, base: null, baseRGBA: null, workRGBA: null, geo: null, normal: null, stats: null,
factor: 1, measurements: [], pending: null, view: 'original', example: null, jobId: 0, device: null };
const viewer = new PointViewer($('#viewer3d'));
const results = $('#results');
$('#hdr-weights').textContent = `${(MODEL.bytes / 1e6).toFixed(1).replace('.', ',')} MB`;
$('#pin-model').textContent = `${MODEL.repo}@${MODEL.revision.slice(0, 7)}`;
$('#pin-ort').textContent = RUNTIME.ort;
$('#chk-webgpu').checked = 'gpu' in navigator;
$('#iso').textContent = self.crossOriginIsolated ? 'sí (WASM multihilo)' : 'no (WASM 1 hilo: abre la URL directa *.static.hf.space)';
for (const s of LIMITS.workSides) $('#sel-side').add(new Option(`${s} px`, s, s === LIMITS.defaultWorkSide, s === LIMITS.defaultWorkSide));
for (const t of LIMITS.tokens) $('#sel-tokens').add(new Option(`${t} tokens`, t, t === LIMITS.defaultTokens, t === LIMITS.defaultTokens));
// ---------- ejemplos ----------
const exBox = $('#examples');
for (const ex of EXAMPLES) {
const b = document.createElement('button');
b.className = 'example'; b.dataset.id = ex.id; b.disabled = true;
b.innerHTML = `${ex.title}`;
b.onclick = () => runExample(ex);
exBox.appendChild(b);
}
const setEnabled = () => {
const on = state.loaded && !state.busy;
document.querySelectorAll('.example').forEach((b) => (b.disabled = !on));
$('#file').disabled = !on; $('#btn-rerun').disabled = !on || !state.base;
$('#btn-load').disabled = state.loaded || state.busy;
};
// ---------- modelo ----------
$('#btn-load').onclick = () => {
state.busy = true; setEnabled();
setStatus('Descargando modelo…');
worker.postMessage({ type: 'load', webgpu: $('#chk-webgpu').checked, threads: Math.min(4, navigator.hardwareConcurrency || 4) });
};
function setStatus(t, cls = '') { const e = $('#model-status'); e.textContent = t; e.className = cls; }
const pending = new Map();
worker.onmessage = ({ data }) => {
if (data.type === 'progress') {
$('#progress').value = data.loaded / data.total;
setStatus(data.verifying ? 'Verificando SHA-256 y creando la sesión…' : `Descargando modelo… ${(data.loaded / 1e6).toFixed(0)} / ${(data.total / 1e6).toFixed(0)} MB`);
} else if (data.type === 'loaded') {
state.loaded = true; state.busy = false; state.device = data.device;
const dev = data.device === 'webgpu' ? 'WebGPU' : `WASM/CPU (${data.threads} hilo${data.threads > 1 ? 's' : ''})`;
setStatus(`Modelo listo · ${dev} · ${data.fromCache ? 'desde caché' : `descarga ${(data.downloadMs / 1000).toFixed(1)} s`} · sesión ${(data.initMs / 1000).toFixed(1)} s`, 'ok');
if (data.warn) $('#warn').textContent = data.warn;
$('#progress').value = 1; setEnabled();
} else if (data.type === 'result' || data.type === 'error') {
const p = pending.get(data.id); pending.delete(data.id);
if (data.type === 'error' && data.stage === 'load') { state.busy = false; setStatus(`No se pudo cargar el modelo: ${data.message}`, 'err'); setEnabled(); return; }
p?.(data);
}
};
const callInfer = (msg, transfer) => new Promise((res) => { const id = ++state.jobId; pending.set(id, res); worker.postMessage({ ...msg, id, type: 'infer' }, transfer); });
// ---------- imágenes ----------
async function bitmapFrom(src) {
const blob = src instanceof Blob ? src : await (await fetch(src)).blob();
return createImageBitmap(blob);
}
function drawTo(bmp, W, H) {
const c = new OffscreenCanvas(W, H), x = c.getContext('2d');
x.imageSmoothingQuality = 'high'; x.drawImage(bmp, 0, 0, W, H);
return x.getImageData(0, 0, W, H).data;
}
async function setBase(bmp) {
const [W, H] = workSize(bmp.width, bmp.height, DISPLAY_MAX);
state.base = { bmp, W, H };
state.baseRGBA = drawTo(bmp, W, H);
}
async function runExample(ex) {
results.dataset.status = 'running';
state.example = ex;
results.dataset.exampleId = ex.id;
$('#example-hint').textContent = ex.hint;
await setBase(await bitmapFrom(ex.file));
await analyze(ex.measurements);
$('#calib-hint').textContent = ex.calibrate ? ex.calibrate.note : 'Si conoces la longitud real de algún segmento medido, escríbela y pulsa «Calibrar» (se usa la última medida).';
$('#calib-known').value = ex.calibrate ? String(ex.calibrate.known).replace('.', ',') : '';
}
$('#file').onchange = async (e) => {
const f = e.target.files?.[0]; if (!f) return;
const err = validateFile(f, LIMITS);
if (err) return showError(err);
let bmp;
try { bmp = await createImageBitmap(f); } catch { return showError('No se pudo decodificar la imagen.'); }
const e2 = validateDims(bmp.width, bmp.height, LIMITS.maxPixels);
if (e2) return showError(e2);
results.dataset.status = 'running';
state.example = null; results.dataset.exampleId = 'upload';
$('#example-hint').textContent = `Imagen propia (${bmp.width}×${bmp.height}). Haz clic en dos puntos para medir.`;
$('#calib-hint').textContent = '';
await setBase(bmp);
await analyze([]);
};
$('#btn-rerun').onclick = () => analyze(state.measurements.map(({ label, a, b, expected, expectedNote }) => ({ label, a, b, expected, expectedNote })));
function showError(msg) { results.dataset.status = 'error'; $('#stats').innerHTML = `
${msg}
`; } async function analyze(presetMeasurements) { state.busy = true; setEnabled(); results.dataset.status = 'running'; $('#stats').innerHTML = 'Calculando geometría 3D… (en CPU puede tardar decenas de segundos)
'; const side = +$('#sel-side').value, tokens = +$('#sel-tokens').value; const [W, H] = workSize(state.base.W, state.base.H, side); const t0 = performance.now(); state.workRGBA = drawTo(state.base.bmp, W, H); const pixels = rgbaToNCHW(state.workRGBA, W, H); const tPre = performance.now() - t0; const r = await callInfer({ pixels: pixels.buffer, W, H, numTokens: tokens }, [pixels.buffer]); state.busy = false; setEnabled(); if (r.type === 'error') return showError(`Error en la inferencia: ${r.message}`); state.geo = r.geo; state.normal = r.normal; state.factor = 1; state.pending = null; $('#calib-status').textContent = 'Sin calibrar (escala métrica del modelo).'; state.stats = depthStats(r.geo.depth); state.measurements = presetMeasurements.map((m) => ({ ...m })); state.timing = { preMs: tPre, inferMs: r.inferMs, postMs: r.postMs, device: r.device, tokens, side: `${W}×${H}` }; recompute(); renderStats(); draw(); viewer.setCloud(state.geo, state.workRGBA, state.factor, state.geo.fovY, state.stats.median); viewer.setMeasurements(state.measurements, state.factor); Object.assign(results.dataset, { status: 'ok', inferMs: Math.round(r.inferMs), postMs: Math.round(r.postMs), device: r.device, fovX: state.geo.fovX.toFixed(2), scale: state.geo.scale.toFixed(4), work: `${W}x${H}` }); } function recompute() { for (const m of state.measurements) m.result = measure(state.geo, m.a, m.b, state.base.W, state.base.H, state.factor); results.dataset.measurements = JSON.stringify(state.measurements.map((m) => ({ label: m.label, a: m.a, b: m.b, length: m.result?.length ?? null, depthA: m.result?.depthA, depthB: m.result?.depthB, expected: m.expected ?? null }))); results.dataset.factor = String(state.factor); renderMeasurements(); } function renderStats() { const g = state.geo, s = state.stats, t = state.timing; const gt = state.example?.gtFovX ? ` (verdad: ${state.example.gtFovX}°)` : ''; $('#stats').innerHTML = `Inferencia real en tu navegador · ${t.device === 'webgpu' ? 'WebGPU' : 'WASM/CPU'} · imagen de trabajo ${t.side} · ${t.tokens} tokens