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OrbitControls } from 'three/addons/controls/OrbitControls.js';
|
| 3 |
+
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
|
| 4 |
+
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1/+esm';
|
| 5 |
+
import * as ort from 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/webgpu/+esm';
|
| 6 |
+
|
| 7 |
+
const MODEL_ROOT = 'https://huggingface.co/needle-tools/SF3D-webgpu/resolve/main/';
|
| 8 |
+
const SAMPLE_URL = 'https://huggingface.co/spaces/stabilityai/stable-fast-3d/resolve/main/demo_files/examples/axe.png';
|
| 9 |
+
const INPUT_SIZE = 512;
|
| 10 |
+
const GRID_RESOLUTION = 160;
|
| 11 |
+
const ISO_THRESHOLD = 10;
|
| 12 |
+
const TRIPLANE_CHANNELS = 40;
|
| 13 |
+
const TRIPLANE_SIZE = 384;
|
| 14 |
+
const DECODE_BATCH = 16384;
|
| 15 |
+
const BACKGROUND_COLOR = 0.5;
|
| 16 |
+
|
| 17 |
+
const el = (id) => document.getElementById(id);
|
| 18 |
+
const ui = {
|
| 19 |
+
file: el('image-file'),
|
| 20 |
+
dropzone: el('dropzone'),
|
| 21 |
+
previewWrap: el('preview-wrap'),
|
| 22 |
+
preview: el('input-preview'),
|
| 23 |
+
previewName: el('preview-name'),
|
| 24 |
+
previewSize: el('preview-size'),
|
| 25 |
+
sample: el('sample-button'),
|
| 26 |
+
removeBackground: el('remove-background'),
|
| 27 |
+
generate: el('generate-button'),
|
| 28 |
+
generateLabel: el('generate-label'),
|
| 29 |
+
webgpuDot: el('webgpu-dot'),
|
| 30 |
+
webgpuLabel: el('webgpu-label'),
|
| 31 |
+
stage: el('viewer-stage'),
|
| 32 |
+
canvas: el('viewer-canvas'),
|
| 33 |
+
empty: el('viewer-empty'),
|
| 34 |
+
progress: el('viewer-progress'),
|
| 35 |
+
progressPercent: el('progress-percent'),
|
| 36 |
+
progressTitle: el('progress-title'),
|
| 37 |
+
progressDetail: el('progress-detail'),
|
| 38 |
+
error: el('viewer-error'),
|
| 39 |
+
errorTitle: el('error-title'),
|
| 40 |
+
errorDetail: el('error-detail'),
|
| 41 |
+
errorDismiss: el('error-dismiss'),
|
| 42 |
+
reset: el('reset-view'),
|
| 43 |
+
stats: el('mesh-stats'),
|
| 44 |
+
runtime: el('runtime-metric'),
|
| 45 |
+
vertices: el('vertices-metric'),
|
| 46 |
+
faces: el('faces-metric'),
|
| 47 |
+
download: el('download-button'),
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
let selectedFile = null;
|
| 51 |
+
let selectedObjectUrl = null;
|
| 52 |
+
let preparedCanvas = null;
|
| 53 |
+
let backgroundPipeline = null;
|
| 54 |
+
let sessions = null;
|
| 55 |
+
let currentMeshObject = null;
|
| 56 |
+
let currentMeshData = null;
|
| 57 |
+
let webgpuReady = false;
|
| 58 |
+
|
| 59 |
+
function setWebGPUStatus(kind, label) {
|
| 60 |
+
ui.webgpuDot.className = `status-dot ${kind}`;
|
| 61 |
+
ui.webgpuLabel.textContent = label;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
function setProgress(title, detail, percent = null) {
|
| 65 |
+
ui.progressTitle.textContent = title;
|
| 66 |
+
ui.progressDetail.textContent = detail;
|
| 67 |
+
if (percent === null) {
|
| 68 |
+
ui.progressPercent.textContent = '…';
|
| 69 |
+
} else {
|
| 70 |
+
ui.progressPercent.textContent = `${Math.round(percent)}%`;
|
| 71 |
+
}
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
function showProgress(visible) {
|
| 75 |
+
ui.progress.classList.toggle('is-hidden', !visible);
|
| 76 |
+
ui.empty.classList.toggle('is-hidden', visible || Boolean(currentMeshObject));
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
function showError(title, detail) {
|
| 80 |
+
ui.errorTitle.textContent = title;
|
| 81 |
+
ui.errorDetail.textContent = detail;
|
| 82 |
+
ui.error.classList.remove('is-hidden');
|
| 83 |
+
showProgress(false);
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
function clearError() {
|
| 87 |
+
ui.error.classList.add('is-hidden');
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
function formatBytes(bytes) {
|
| 91 |
+
if (!Number.isFinite(bytes) || bytes <= 0) return '—';
|
| 92 |
+
const units = ['B', 'KB', 'MB', 'GB'];
|
| 93 |
+
const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
|
| 94 |
+
return `${(bytes / 1024 ** index).toFixed(index ? 1 : 0)} ${units[index]}`;
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
function formatDuration(ms) {
|
| 98 |
+
return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
function isTransparentCanvas(canvas) {
|
| 102 |
+
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
| 103 |
+
const { data } = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
| 104 |
+
for (let i = 3; i < data.length; i += 4) {
|
| 105 |
+
if (data[i] < 250) return true;
|
| 106 |
+
}
|
| 107 |
+
return false;
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
function loadImageFromBlob(blob) {
|
| 111 |
+
return new Promise((resolve, reject) => {
|
| 112 |
+
const url = URL.createObjectURL(blob);
|
| 113 |
+
const image = new Image();
|
| 114 |
+
image.onload = () => {
|
| 115 |
+
URL.revokeObjectURL(url);
|
| 116 |
+
resolve(image);
|
| 117 |
+
};
|
| 118 |
+
image.onerror = () => {
|
| 119 |
+
URL.revokeObjectURL(url);
|
| 120 |
+
reject(new Error('The selected file could not be decoded as an image.'));
|
| 121 |
+
};
|
| 122 |
+
image.src = url;
|
| 123 |
+
});
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
function imageToCanvas(image, maxSize = 1200) {
|
| 127 |
+
const scale = Math.min(1, maxSize / Math.max(image.naturalWidth || image.width, image.naturalHeight || image.height));
|
| 128 |
+
const canvas = document.createElement('canvas');
|
| 129 |
+
canvas.width = Math.max(1, Math.round((image.naturalWidth || image.width) * scale));
|
| 130 |
+
canvas.height = Math.max(1, Math.round((image.naturalHeight || image.height) * scale));
|
| 131 |
+
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
| 132 |
+
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
| 133 |
+
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
|
| 134 |
+
return canvas;
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
function rawImageToCanvas(rawImage) {
|
| 138 |
+
const canvas = document.createElement('canvas');
|
| 139 |
+
canvas.width = rawImage.width;
|
| 140 |
+
canvas.height = rawImage.height;
|
| 141 |
+
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
| 142 |
+
const rgba = new Uint8ClampedArray(canvas.width * canvas.height * 4);
|
| 143 |
+
const source = rawImage.data;
|
| 144 |
+
const channels = rawImage.channels || 4;
|
| 145 |
+
for (let i = 0, j = 0; i < source.length; i += channels, j += 4) {
|
| 146 |
+
rgba[j] = source[i];
|
| 147 |
+
rgba[j + 1] = source[i + 1] ?? source[i];
|
| 148 |
+
rgba[j + 2] = source[i + 2] ?? source[i];
|
| 149 |
+
rgba[j + 3] = channels >= 4 ? source[i + 3] : 255;
|
| 150 |
+
}
|
| 151 |
+
ctx.putImageData(new ImageData(rgba, canvas.width, canvas.height), 0, 0);
|
| 152 |
+
return canvas;
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
async function getBackgroundPipeline() {
|
| 156 |
+
if (!backgroundPipeline) {
|
| 157 |
+
setProgress('Loading cleanup model', 'Transformers.js is downloading MODNet for this browser.', null);
|
| 158 |
+
backgroundPipeline = await pipeline('background-removal', 'Xenova/modnet', {
|
| 159 |
+
device: 'webgpu',
|
| 160 |
+
dtype: 'fp16',
|
| 161 |
+
});
|
| 162 |
+
}
|
| 163 |
+
return backgroundPipeline;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
async function prepareSourceCanvas(file) {
|
| 167 |
+
const image = await loadImageFromBlob(file);
|
| 168 |
+
const original = imageToCanvas(image);
|
| 169 |
+
if (!ui.removeBackground.checked || isTransparentCanvas(original)) {
|
| 170 |
+
return original;
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
let blobUrl = null;
|
| 174 |
+
try {
|
| 175 |
+
const remover = await getBackgroundPipeline();
|
| 176 |
+
blobUrl = URL.createObjectURL(file);
|
| 177 |
+
const output = await remover(blobUrl);
|
| 178 |
+
const first = Array.isArray(output) ? output[0] : output;
|
| 179 |
+
if (!first?.data || !first.width || !first.height) {
|
| 180 |
+
throw new Error('The cleanup model returned an empty image.');
|
| 181 |
+
}
|
| 182 |
+
return rawImageToCanvas(first);
|
| 183 |
+
} catch (error) {
|
| 184 |
+
console.warn('Background cleanup skipped:', error);
|
| 185 |
+
setProgress('Using original image', 'Background cleanup was skipped; continuing with the uploaded pixels.', 5);
|
| 186 |
+
return original;
|
| 187 |
+
} finally {
|
| 188 |
+
if (blobUrl) URL.revokeObjectURL(blobUrl);
|
| 189 |
+
}
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
function alphaBounds(canvas) {
|
| 193 |
+
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
| 194 |
+
const { data, width, height } = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
| 195 |
+
let minX = width;
|
| 196 |
+
let minY = height;
|
| 197 |
+
let maxX = -1;
|
| 198 |
+
let maxY = -1;
|
| 199 |
+
for (let y = 0; y < height; y += 1) {
|
| 200 |
+
for (let x = 0; x < width; x += 1) {
|
| 201 |
+
if (data[(y * width + x) * 4 + 3] > 8) {
|
| 202 |
+
minX = Math.min(minX, x);
|
| 203 |
+
minY = Math.min(minY, y);
|
| 204 |
+
maxX = Math.max(maxX, x);
|
| 205 |
+
maxY = Math.max(maxY, y);
|
| 206 |
+
}
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
if (maxX < 0) return { x: 0, y: 0, width, height };
|
| 210 |
+
return { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 };
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
function prepareModelCanvas(source, ratio = 0.85) {
|
| 214 |
+
const bounds = alphaBounds(source);
|
| 215 |
+
const side = Math.max(bounds.width, bounds.height) / ratio;
|
| 216 |
+
const centerX = bounds.x + bounds.width / 2;
|
| 217 |
+
const centerY = bounds.y + bounds.height / 2;
|
| 218 |
+
const cropX = centerX - side / 2;
|
| 219 |
+
const cropY = centerY - side / 2;
|
| 220 |
+
const canvas = document.createElement('canvas');
|
| 221 |
+
canvas.width = INPUT_SIZE;
|
| 222 |
+
canvas.height = INPUT_SIZE;
|
| 223 |
+
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
| 224 |
+
ctx.clearRect(0, 0, INPUT_SIZE, INPUT_SIZE);
|
| 225 |
+
ctx.imageSmoothingEnabled = true;
|
| 226 |
+
ctx.imageSmoothingQuality = 'high';
|
| 227 |
+
ctx.drawImage(source, cropX, cropY, side, side, 0, 0, INPUT_SIZE, INPUT_SIZE);
|
| 228 |
+
return canvas;
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
function renderInputPreview(canvas, name, bytes) {
|
| 232 |
+
if (selectedObjectUrl) URL.revokeObjectURL(selectedObjectUrl);
|
| 233 |
+
canvas.toBlob((blob) => {
|
| 234 |
+
if (!blob) return;
|
| 235 |
+
selectedObjectUrl = URL.createObjectURL(blob);
|
| 236 |
+
ui.preview.src = selectedObjectUrl;
|
| 237 |
+
}, 'image/png');
|
| 238 |
+
ui.previewName.textContent = name;
|
| 239 |
+
ui.previewSize.textContent = formatBytes(bytes);
|
| 240 |
+
ui.previewWrap.classList.remove('is-hidden');
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
function selectFile(file) {
|
| 244 |
+
if (!file || !file.type.startsWith('image/')) {
|
| 245 |
+
showError('Unsupported file', 'Choose a PNG, JPEG, or WebP image.');
|
| 246 |
+
return;
|
| 247 |
+
}
|
| 248 |
+
selectedFile = file;
|
| 249 |
+
clearError();
|
| 250 |
+
preparedCanvas = null;
|
| 251 |
+
ui.generate.disabled = !webgpuReady;
|
| 252 |
+
ui.generateLabel.textContent = webgpuReady ? 'Generate 3D mesh' : 'WebGPU required';
|
| 253 |
+
ui.previewWrap.classList.add('is-hidden');
|
| 254 |
+
const reader = new FileReader();
|
| 255 |
+
reader.onload = () => {
|
| 256 |
+
ui.preview.src = reader.result;
|
| 257 |
+
ui.previewName.textContent = file.name;
|
| 258 |
+
ui.previewSize.textContent = formatBytes(file.size);
|
| 259 |
+
ui.previewWrap.classList.remove('is-hidden');
|
| 260 |
+
};
|
| 261 |
+
reader.readAsDataURL(file);
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
async function loadSample() {
|
| 265 |
+
ui.sample.disabled = true;
|
| 266 |
+
ui.sample.querySelector('span').textContent = 'Loading sample…';
|
| 267 |
+
try {
|
| 268 |
+
const response = await fetch(SAMPLE_URL);
|
| 269 |
+
if (!response.ok) throw new Error(`Sample request failed (${response.status}).`);
|
| 270 |
+
const blob = await response.blob();
|
| 271 |
+
selectFile(new File([blob], 'axe.png', { type: blob.type || 'image/png' }));
|
| 272 |
+
} catch (error) {
|
| 273 |
+
showError('Sample unavailable', error.message);
|
| 274 |
+
} finally {
|
| 275 |
+
ui.sample.disabled = false;
|
| 276 |
+
ui.sample.querySelector('span').textContent = 'Try a sample';
|
| 277 |
+
}
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
function urlFor(path) {
|
| 281 |
+
return `${MODEL_ROOT}${path}?download=true`;
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
function resolveName(names, preferred, index = 0) {
|
| 285 |
+
return preferred.find((candidate) => names.includes(candidate)) || names[index];
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
function resolveOutput(outputs, preferred, index = 0) {
|
| 289 |
+
for (const name of preferred) {
|
| 290 |
+
if (outputs[name]) return outputs[name];
|
| 291 |
+
}
|
| 292 |
+
const first = Object.keys(outputs)[index];
|
| 293 |
+
if (!first) throw new Error('The ONNX graph returned no output tensor.');
|
| 294 |
+
return outputs[first];
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
async function createSessions() {
|
| 298 |
+
if (sessions) return sessions;
|
| 299 |
+
if (!webgpuReady) throw new Error('WebGPU is not available in this browser.');
|
| 300 |
+
if (ort.env?.wasm) {
|
| 301 |
+
ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/';
|
| 302 |
+
ort.env.wasm.numThreads = 1;
|
| 303 |
+
}
|
| 304 |
+
const options = {
|
| 305 |
+
executionProviders: ['webgpu'],
|
| 306 |
+
graphOptimizationLevel: 'all',
|
| 307 |
+
enableMemPattern: true,
|
| 308 |
+
};
|
| 309 |
+
setProgress('Loading SF3D graphs', 'Downloading the tokenizer, backbone, and decoder. They will be cached after this run.', null);
|
| 310 |
+
const [imageTokenizer, backbone, decoder] = await Promise.all([
|
| 311 |
+
ort.InferenceSession.create(urlFor('onnx/image_tokenizer_single.onnx'), options),
|
| 312 |
+
ort.InferenceSession.create(urlFor('onnx/backbone_fp16.onnx'), options),
|
| 313 |
+
ort.InferenceSession.create(urlFor('onnx/decoder_single.onnx'), options),
|
| 314 |
+
]);
|
| 315 |
+
sessions = { imageTokenizer, backbone, decoder };
|
| 316 |
+
return sessions;
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
async function fetchBinary(path, label, progressOffset, progressScale) {
|
| 320 |
+
const response = await fetch(urlFor(path));
|
| 321 |
+
if (!response.ok) throw new Error(`Could not load ${label} (${response.status}).`);
|
| 322 |
+
const total = Number(response.headers.get('content-length')) || 0;
|
| 323 |
+
const reader = response.body?.getReader();
|
| 324 |
+
if (!reader) return response.arrayBuffer();
|
| 325 |
+
const chunks = [];
|
| 326 |
+
let loaded = 0;
|
| 327 |
+
while (true) {
|
| 328 |
+
const { done, value } = await reader.read();
|
| 329 |
+
if (done) break;
|
| 330 |
+
chunks.push(value);
|
| 331 |
+
loaded += value.byteLength;
|
| 332 |
+
if (total) setProgress('Loading mesh grid', `${label} · ${formatBytes(loaded)} / ${formatBytes(total)}`, progressOffset + (loaded / total) * progressScale);
|
| 333 |
+
}
|
| 334 |
+
const buffer = new ArrayBuffer(loaded);
|
| 335 |
+
const output = new Uint8Array(buffer);
|
| 336 |
+
let offset = 0;
|
| 337 |
+
for (const chunk of chunks) {
|
| 338 |
+
output.set(chunk, offset);
|
| 339 |
+
offset += chunk.byteLength;
|
| 340 |
+
}
|
| 341 |
+
return buffer;
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
async function loadGrid() {
|
| 345 |
+
setProgress('Loading mesh grid', 'Fetching the tetrahedral surface grid.', 68);
|
| 346 |
+
const [verticesBuffer, indicesBuffer] = await Promise.all([
|
| 347 |
+
fetchBinary('tets_vertices.bin', 'vertices', 68, 7),
|
| 348 |
+
fetchBinary('tets_indices.bin', 'tetrahedra', 75, 7),
|
| 349 |
+
]);
|
| 350 |
+
return {
|
| 351 |
+
vertices: new Float32Array(verticesBuffer),
|
| 352 |
+
indices: new Uint32Array(indicesBuffer),
|
| 353 |
+
};
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
function createInputTensors(canvas, imageTokenizer) {
|
| 357 |
+
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
| 358 |
+
const { data } = ctx.getImageData(0, 0, INPUT_SIZE, INPUT_SIZE);
|
| 359 |
+
const rgb = new Float32Array(INPUT_SIZE * INPUT_SIZE * 3);
|
| 360 |
+
for (let i = 0, j = 0; i < data.length; i += 4, j += 3) {
|
| 361 |
+
const alpha = data[i + 3] / 255;
|
| 362 |
+
rgb[j] = BACKGROUND_COLOR * (1 - alpha) + (data[i] / 255) * alpha;
|
| 363 |
+
rgb[j + 1] = BACKGROUND_COLOR * (1 - alpha) + (data[i + 1] / 255) * alpha;
|
| 364 |
+
rgb[j + 2] = BACKGROUND_COLOR * (1 - alpha) + (data[i + 2] / 255) * alpha;
|
| 365 |
+
}
|
| 366 |
+
const inputNames = imageTokenizer.inputNames;
|
| 367 |
+
const rgbName = resolveName(inputNames, ['rgb'], 0);
|
| 368 |
+
const c2wName = resolveName(inputNames, ['c2w'], 1);
|
| 369 |
+
const intrinsicName = resolveName(inputNames, ['intrinsic_normed'], 2);
|
| 370 |
+
const focal = 1 / (2 * Math.tan((40 * Math.PI) / 360));
|
| 371 |
+
return {
|
| 372 |
+
[rgbName]: new ort.Tensor('float32', rgb, [1, INPUT_SIZE, INPUT_SIZE, 3]),
|
| 373 |
+
[c2wName]: new ort.Tensor('float32', new Float32Array([
|
| 374 |
+
0, 0, 1, 1.6,
|
| 375 |
+
1, 0, 0, 0,
|
| 376 |
+
0, 1, 0, 0,
|
| 377 |
+
0, 0, 0, 1,
|
| 378 |
+
]), [1, 4, 4]),
|
| 379 |
+
[intrinsicName]: new ort.Tensor('float32', new Float32Array([
|
| 380 |
+
focal, 0, 0.5,
|
| 381 |
+
0, focal, 0.5,
|
| 382 |
+
0, 0, 1,
|
| 383 |
+
]), [1, 3, 3]),
|
| 384 |
+
};
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
async function decodeGrid(grid, triplane, decoder) {
|
| 388 |
+
const vertexCount = grid.vertices.length / 3;
|
| 389 |
+
const density = new Float32Array(vertexCount);
|
| 390 |
+
const deformation = new Float32Array(vertexCount * 3);
|
| 391 |
+
const triplaneTensor = new ort.Tensor('float32', triplane, [1, 3, TRIPLANE_CHANNELS, TRIPLANE_SIZE, TRIPLANE_SIZE]);
|
| 392 |
+
const positions = new Float32Array(DECODE_BATCH * 3);
|
| 393 |
+
const inputNames = decoder.inputNames;
|
| 394 |
+
const triplaneName = resolveName(inputNames, ['triplane'], 0);
|
| 395 |
+
const positionsName = resolveName(inputNames, ['positions'], 1);
|
| 396 |
+
const densityName = 'density';
|
| 397 |
+
const offsetName = 'vertex_offset';
|
| 398 |
+
for (let start = 0; start < vertexCount; start += DECODE_BATCH) {
|
| 399 |
+
const count = Math.min(DECODE_BATCH, vertexCount - start);
|
| 400 |
+
const currentPositions = positions.subarray(0, count * 3);
|
| 401 |
+
for (let i = 0; i < count; i += 1) {
|
| 402 |
+
const base = (start + i) * 3;
|
| 403 |
+
currentPositions[i * 3] = grid.vertices[base] * 2 - 1;
|
| 404 |
+
currentPositions[i * 3 + 1] = grid.vertices[base + 1] * 2 - 1;
|
| 405 |
+
currentPositions[i * 3 + 2] = grid.vertices[base + 2] * 2 - 1;
|
| 406 |
+
}
|
| 407 |
+
const outputs = await decoder.run({
|
| 408 |
+
[triplaneName]: triplaneTensor,
|
| 409 |
+
[positionsName]: new ort.Tensor('float32', currentPositions, [1, count, 3]),
|
| 410 |
+
});
|
| 411 |
+
const densityTensor = resolveOutput(outputs, [densityName]);
|
| 412 |
+
const offsetTensor = resolveOutput(outputs, [offsetName]);
|
| 413 |
+
for (let i = 0; i < count; i += 1) {
|
| 414 |
+
density[start + i] = densityTensor.data[i];
|
| 415 |
+
deformation[(start + i) * 3] = offsetTensor.data[i * 3];
|
| 416 |
+
deformation[(start + i) * 3 + 1] = offsetTensor.data[i * 3 + 1];
|
| 417 |
+
deformation[(start + i) * 3 + 2] = offsetTensor.data[i * 3 + 2];
|
| 418 |
+
}
|
| 419 |
+
const percent = 82 + ((start + count) / vertexCount) * 15;
|
| 420 |
+
setProgress('Decoding surface', `${(start + count).toLocaleString()} / ${vertexCount.toLocaleString()} grid points`, percent);
|
| 421 |
+
}
|
| 422 |
+
return { density, deformation };
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
const TRIANGLE_TABLE = [
|
| 426 |
+
[-1, -1, -1, -1, -1, -1], [1, 0, 2, -1, -1, -1], [4, 0, 3, -1, -1, -1], [1, 4, 2, 1, 3, 4],
|
| 427 |
+
[3, 1, 5, -1, -1, -1], [2, 3, 0, 2, 5, 3], [1, 4, 0, 1, 5, 4], [4, 2, 5, -1, -1, -1],
|
| 428 |
+
[4, 5, 2, -1, -1, -1], [4, 1, 0, 4, 5, 1], [3, 2, 0, 3, 5, 2], [1, 3, 5, -1, -1, -1],
|
| 429 |
+
[4, 1, 2, 4, 3, 1], [3, 0, 4, -1, -1, -1], [2, 0, 1, -1, -1, -1], [-1, -1, -1, -1, -1, -1],
|
| 430 |
+
];
|
| 431 |
+
function buildMesh(grid, decoded) {
|
| 432 |
+
const vertexCount = grid.vertices.length / 3;
|
| 433 |
+
const tetCount = grid.indices.length / 4;
|
| 434 |
+
const occupied = new Uint8Array(vertexCount);
|
| 435 |
+
for (let i = 0; i < vertexCount; i += 1) occupied[i] = decoded.density[i] > ISO_THRESHOLD ? 1 : 0;
|
| 436 |
+
|
| 437 |
+
const positions = [];
|
| 438 |
+
const faces = [];
|
| 439 |
+
const edgeMap = new Map();
|
| 440 |
+
const deformed = (index, axis) => {
|
| 441 |
+
const value = grid.vertices[index * 3 + axis] + (2 / GRID_RESOLUTION) * Math.tanh(decoded.deformation[index * 3 + axis]);
|
| 442 |
+
return value * 2 - 1;
|
| 443 |
+
};
|
| 444 |
+
const edgeVertex = (a, b) => {
|
| 445 |
+
if (occupied[a] === occupied[b]) return -1;
|
| 446 |
+
const low = Math.min(a, b);
|
| 447 |
+
const high = Math.max(a, b);
|
| 448 |
+
const key = low * vertexCount + high;
|
| 449 |
+
const existing = edgeMap.get(key);
|
| 450 |
+
if (existing !== undefined) return existing;
|
| 451 |
+
const s0 = decoded.density[a] - ISO_THRESHOLD;
|
| 452 |
+
const s1 = decoded.density[b] - ISO_THRESHOLD;
|
| 453 |
+
const denominator = s0 - s1 || 1e-6;
|
| 454 |
+
const t = Math.max(0, Math.min(1, s0 / denominator));
|
| 455 |
+
const x = deformed(a, 0) * (1 - t) + deformed(b, 0) * t;
|
| 456 |
+
const y = deformed(a, 1) * (1 - t) + deformed(b, 1) * t;
|
| 457 |
+
const z = deformed(a, 2) * (1 - t) + deformed(b, 2) * t;
|
| 458 |
+
const index = positions.length / 3;
|
| 459 |
+
positions.push(x, y, z);
|
| 460 |
+
edgeMap.set(key, index);
|
| 461 |
+
return index;
|
| 462 |
+
};
|
| 463 |
+
|
| 464 |
+
for (let tet = 0; tet < tetCount; tet += 1) {
|
| 465 |
+
const offset = tet * 4;
|
| 466 |
+
const c0 = grid.indices[offset];
|
| 467 |
+
const c1 = grid.indices[offset + 1];
|
| 468 |
+
const c2 = grid.indices[offset + 2];
|
| 469 |
+
const c3 = grid.indices[offset + 3];
|
| 470 |
+
const mask = occupied[c0] | (occupied[c1] << 1) | (occupied[c2] << 2) | (occupied[c3] << 3);
|
| 471 |
+
if (mask === 0 || mask === 15) continue;
|
| 472 |
+
const edgeIndices = new Int32Array(6);
|
| 473 |
+
edgeIndices[0] = edgeVertex(c0, c1);
|
| 474 |
+
edgeIndices[1] = edgeVertex(c0, c2);
|
| 475 |
+
edgeIndices[2] = edgeVertex(c0, c3);
|
| 476 |
+
edgeIndices[3] = edgeVertex(c1, c2);
|
| 477 |
+
edgeIndices[4] = edgeVertex(c1, c3);
|
| 478 |
+
edgeIndices[5] = edgeVertex(c2, c3);
|
| 479 |
+
const table = TRIANGLE_TABLE[mask];
|
| 480 |
+
for (let i = 0; i < 6 && table[i] !== -1; i += 3) {
|
| 481 |
+
faces.push(edgeIndices[table[i]], edgeIndices[table[i + 1]], edgeIndices[table[i + 2]]);
|
| 482 |
+
}
|
| 483 |
+
}
|
| 484 |
+
if (!faces.length) throw new Error('No surface was found. Try a clearer image with one centered object.');
|
| 485 |
+
return { positions: new Float32Array(positions), faces: new Uint32Array(faces) };
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
function initViewer() {
|
| 489 |
+
const scene = new THREE.Scene();
|
| 490 |
+
const camera = new THREE.PerspectiveCamera(35, 1, 0.01, 100);
|
| 491 |
+
camera.position.set(0, 0.15, 3.4);
|
| 492 |
+
const renderer = new THREE.WebGLRenderer({ canvas: ui.canvas, antialias: true, alpha: true });
|
| 493 |
+
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
| 494 |
+
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
| 495 |
+
renderer.toneMapping = THREE.ACESFilmicToneMapping;
|
| 496 |
+
renderer.toneMappingExposure = 1.15;
|
| 497 |
+
const controls = new OrbitControls(camera, renderer.domElement);
|
| 498 |
+
controls.enableDamping = true;
|
| 499 |
+
controls.dampingFactor = 0.07;
|
| 500 |
+
controls.minDistance = 1.2;
|
| 501 |
+
controls.maxDistance = 7;
|
| 502 |
+
controls.target.set(0, 0, 0);
|
| 503 |
+
scene.add(new THREE.HemisphereLight(0xdcd7ff, 0x1f2330, 2.1));
|
| 504 |
+
const keyLight = new THREE.DirectionalLight(0xffffff, 3.5);
|
| 505 |
+
keyLight.position.set(3, 4, 4);
|
| 506 |
+
scene.add(keyLight);
|
| 507 |
+
const rimLight = new THREE.DirectionalLight(0xc7baff, 2.2);
|
| 508 |
+
rimLight.position.set(-4, 2, -3);
|
| 509 |
+
scene.add(rimLight);
|
| 510 |
+
|
| 511 |
+
const resize = () => {
|
| 512 |
+
const width = ui.stage.clientWidth;
|
| 513 |
+
const height = ui.stage.clientHeight;
|
| 514 |
+
renderer.setSize(width, height, false);
|
| 515 |
+
camera.aspect = width / Math.max(height, 1);
|
| 516 |
+
camera.updateProjectionMatrix();
|
| 517 |
+
};
|
| 518 |
+
const reset = () => {
|
| 519 |
+
camera.position.set(0, 0.15, 3.4);
|
| 520 |
+
controls.target.set(0, 0, 0);
|
| 521 |
+
controls.update();
|
| 522 |
+
};
|
| 523 |
+
window.addEventListener('resize', resize);
|
| 524 |
+
ui.reset.addEventListener('click', reset);
|
| 525 |
+
resize();
|
| 526 |
+
const animate = () => {
|
| 527 |
+
requestAnimationFrame(animate);
|
| 528 |
+
controls.update();
|
| 529 |
+
renderer.render(scene, camera);
|
| 530 |
+
};
|
| 531 |
+
animate();
|
| 532 |
+
|
| 533 |
+
return {
|
| 534 |
+
scene,
|
| 535 |
+
camera,
|
| 536 |
+
reset,
|
| 537 |
+
setMesh(meshData) {
|
| 538 |
+
if (currentMeshObject) {
|
| 539 |
+
scene.remove(currentMeshObject);
|
| 540 |
+
currentMeshObject.geometry.dispose();
|
| 541 |
+
currentMeshObject.material.dispose();
|
| 542 |
+
}
|
| 543 |
+
const geometry = new THREE.BufferGeometry();
|
| 544 |
+
geometry.setAttribute('position', new THREE.BufferAttribute(meshData.positions, 3));
|
| 545 |
+
geometry.setIndex(new THREE.BufferAttribute(meshData.faces, 1));
|
| 546 |
+
geometry.computeVertexNormals();
|
| 547 |
+
geometry.computeBoundingBox();
|
| 548 |
+
const center = geometry.boundingBox.getCenter(new THREE.Vector3());
|
| 549 |
+
const size = geometry.boundingBox.getSize(new THREE.Vector3());
|
| 550 |
+
const maxDimension = Math.max(size.x, size.y, size.z) || 1;
|
| 551 |
+
geometry.translate(-center.x, -center.y, -center.z);
|
| 552 |
+
geometry.scale(2.15 / maxDimension, 2.15 / maxDimension, 2.15 / maxDimension);
|
| 553 |
+
const material = new THREE.MeshStandardMaterial({ color: 0xc9b9ff, roughness: 0.44, metalness: 0.14, side: THREE.DoubleSide });
|
| 554 |
+
currentMeshObject = new THREE.Mesh(geometry, material);
|
| 555 |
+
scene.add(currentMeshObject);
|
| 556 |
+
reset();
|
| 557 |
+
ui.empty.classList.add('is-hidden');
|
| 558 |
+
ui.stats.textContent = `${meshData.faces.length / 3} triangles · drag to orbit`;
|
| 559 |
+
ui.download.disabled = false;
|
| 560 |
+
},
|
| 561 |
+
};
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
const viewer = initViewer();
|
| 565 |
+
|
| 566 |
+
async function runGeneration() {
|
| 567 |
+
if (!selectedFile || !webgpuReady) return;
|
| 568 |
+
const started = performance.now();
|
| 569 |
+
ui.generate.disabled = true;
|
| 570 |
+
ui.download.disabled = true;
|
| 571 |
+
clearError();
|
| 572 |
+
showProgress(true);
|
| 573 |
+
try {
|
| 574 |
+
setProgress('Preparing image', 'Composing the subject over SF3D’s neutral background.', 5);
|
| 575 |
+
const sourceCanvas = await prepareSourceCanvas(selectedFile);
|
| 576 |
+
preparedCanvas = prepareModelCanvas(sourceCanvas);
|
| 577 |
+
renderInputPreview(preparedCanvas, `${selectedFile.name} · prepared`, selectedFile.size);
|
| 578 |
+
setProgress('Loading models', 'Connecting to the browser-compatible SF3D export.', 15);
|
| 579 |
+
const [modelSessions, grid] = await Promise.all([createSessions(), loadGrid()]);
|
| 580 |
+
setProgress('Encoding image', 'The image tokenizer is running on WebGPU.', 78);
|
| 581 |
+
const tokenizerInputs = createInputTensors(preparedCanvas, modelSessions.imageTokenizer);
|
| 582 |
+
const tokenizerOutputs = await modelSessions.imageTokenizer.run(tokenizerInputs);
|
| 583 |
+
const imageTokens = resolveOutput(tokenizerOutputs, ['image_tokens']);
|
| 584 |
+
setProgress('Reconstructing shape', 'The SF3D backbone is predicting a 3D triplane.', 80);
|
| 585 |
+
const backboneInputName = resolveName(modelSessions.backbone.inputNames, ['image_tokens'], 0);
|
| 586 |
+
const backboneOutputs = await modelSessions.backbone.run({ [backboneInputName]: imageTokens });
|
| 587 |
+
const triplane = resolveOutput(backboneOutputs, ['triplane']).data;
|
| 588 |
+
setProgress('Decoding surface', 'Sampling the triplane and extracting the tetrahedral surface.', 82);
|
| 589 |
+
const decoded = await decodeGrid(grid, triplane, modelSessions.decoder);
|
| 590 |
+
const meshData = buildMesh(grid, decoded);
|
| 591 |
+
currentMeshData = meshData;
|
| 592 |
+
viewer.setMesh(meshData);
|
| 593 |
+
const elapsed = performance.now() - started;
|
| 594 |
+
ui.runtime.textContent = formatDuration(elapsed);
|
| 595 |
+
ui.vertices.textContent = (meshData.positions.length / 3).toLocaleString();
|
| 596 |
+
ui.faces.textContent = (meshData.faces.length / 3).toLocaleString();
|
| 597 |
+
setProgress('Done', 'Your mesh is ready.', 100);
|
| 598 |
+
showProgress(false);
|
| 599 |
+
} catch (error) {
|
| 600 |
+
console.error(error);
|
| 601 |
+
showError('Generation failed', error?.message || 'The browser could not complete WebGPU inference.');
|
| 602 |
+
ui.stats.textContent = 'No mesh loaded';
|
| 603 |
+
} finally {
|
| 604 |
+
ui.generate.disabled = false;
|
| 605 |
+
ui.generateLabel.textContent = 'Generate 3D mesh';
|
| 606 |
+
}
|
| 607 |
+
}
|
| 608 |
+
|
| 609 |
+
async function downloadGLB() {
|
| 610 |
+
if (!currentMeshObject) return;
|
| 611 |
+
ui.download.disabled = true;
|
| 612 |
+
try {
|
| 613 |
+
const exporter = new GLTFExporter();
|
| 614 |
+
const result = await new Promise((resolve, reject) => exporter.parse(currentMeshObject, resolve, reject, { binary: true }));
|
| 615 |
+
const blob = new Blob([result], { type: 'model/gltf-binary' });
|
| 616 |
+
const url = URL.createObjectURL(blob);
|
| 617 |
+
const anchor = document.createElement('a');
|
| 618 |
+
anchor.href = url;
|
| 619 |
+
anchor.download = 'stable-fast-3d-mesh.glb';
|
| 620 |
+
anchor.click();
|
| 621 |
+
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
| 622 |
+
} catch (error) {
|
| 623 |
+
showError('Download failed', error.message || 'The GLB exporter could not finish.');
|
| 624 |
+
} finally {
|
| 625 |
+
ui.download.disabled = false;
|
| 626 |
+
}
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
async function checkWebGPU() {
|
| 630 |
+
if (!navigator.gpu) {
|
| 631 |
+
setWebGPUStatus('error', 'WebGPU unavailable');
|
| 632 |
+
ui.generateLabel.textContent = 'WebGPU required';
|
| 633 |
+
return;
|
| 634 |
+
}
|
| 635 |
+
try {
|
| 636 |
+
const adapter = await navigator.gpu.requestAdapter();
|
| 637 |
+
if (!adapter) throw new Error('No compatible GPU adapter found.');
|
| 638 |
+
webgpuReady = true;
|
| 639 |
+
setWebGPUStatus('ready', 'WebGPU ready');
|
| 640 |
+
ui.generate.disabled = !selectedFile;
|
| 641 |
+
ui.generateLabel.textContent = selectedFile ? 'Generate 3D mesh' : 'Select an image';
|
| 642 |
+
} catch (error) {
|
| 643 |
+
setWebGPUStatus('error', 'WebGPU unavailable');
|
| 644 |
+
showError('WebGPU is required', error.message || 'Use a recent Chrome or Edge browser with WebGPU enabled.');
|
| 645 |
+
}
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
ui.file.addEventListener('change', (event) => selectFile(event.target.files?.[0]));
|
| 649 |
+
ui.sample.addEventListener('click', loadSample);
|
| 650 |
+
ui.generate.addEventListener('click', runGeneration);
|
| 651 |
+
ui.download.addEventListener('click', downloadGLB);
|
| 652 |
+
ui.errorDismiss.addEventListener('click', clearError);
|
| 653 |
+
ui.dropzone.addEventListener('dragover', (event) => { event.preventDefault(); ui.dropzone.classList.add('dragging'); });
|
| 654 |
+
ui.dropzone.addEventListener('dragleave', () => ui.dropzone.classList.remove('dragging'));
|
| 655 |
+
ui.dropzone.addEventListener('drop', (event) => {
|
| 656 |
+
event.preventDefault();
|
| 657 |
+
ui.dropzone.classList.remove('dragging');
|
| 658 |
+
selectFile(event.dataTransfer.files?.[0]);
|
| 659 |
+
});
|
| 660 |
+
window.addEventListener('pagehide', () => {
|
| 661 |
+
if (backgroundPipeline?.dispose) backgroundPipeline.dispose();
|
| 662 |
+
if (sessions) Object.values(sessions).forEach((session) => session.release?.());
|
| 663 |
+
});
|
| 664 |
+
|
| 665 |
+
checkWebGPU();
|