-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
705 lines (636 loc) · 26.6 KB
/
Copy pathapp.js
File metadata and controls
705 lines (636 loc) · 26.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
// © 2026 Epic Games, Inc. RealityScan® is a trademark of Epic Games, Inc.
// This tool is provided under the RealityScan End User License Agreement:
// https://www.realityscan.com/eula
// UI orchestration: drag-drop (files + folders + videos), FOV control,
// video frame extraction, render loop, auto-batched ZIP packaging.
const els = {
dropZone: document.getElementById("dropZone"),
fileInput: document.getElementById("fileInput"),
folderInput: document.getElementById("folderInput"),
pickFilesBtn: document.getElementById("pickFilesBtn"),
pickFolderBtn: document.getElementById("pickFolderBtn"),
fileList: document.getElementById("fileList"),
fileSummary: document.getElementById("fileSummary"),
multiNotice: document.getElementById("multiPartNotice"),
progressLabel: document.getElementById("progressLabel"),
fovSlider: document.getElementById("fovSlider"),
fovValue: document.getElementById("fovValue"),
sizeSelect: document.getElementById("sizeSelect"),
intervalField: document.getElementById("intervalField"),
intervalInput: document.getElementById("intervalInput"),
writeXmp: document.getElementById("writeXmp"),
outputName: document.getElementById("outputNameInput"),
convertBtn: document.getElementById("convertBtn"),
clearBtn: document.getElementById("clearBtn"),
progress: document.getElementById("progress"),
progressBar: document.getElementById("progressBar"),
progressText:document.getElementById("progressText"),
downloadBox: document.getElementById("downloadBox"),
downloadLink:document.getElementById("downloadLink"),
errorBox: document.getElementById("errorBox"),
};
const ACTIVE_LAYOUT = LAYOUTS.cubemap;
let queuedFiles = []; // each File: .relPath, .kind ('image'|'video'), .videoMeta?, ._videoElement?
let renderer = null;
// ---------- File / folder collection ----------
function tagRelPath(file, relPath) {
try { file.relPath = relPath; } catch (e) { /* ignore */ }
return file;
}
async function walkEntry(entry, parentPath = "") {
const out = [];
if (entry.isFile) {
const file = await new Promise((resolve, reject) =>
entry.file(resolve, reject)
);
out.push(tagRelPath(file, parentPath + entry.name));
} else if (entry.isDirectory) {
const reader = entry.createReader();
const here = parentPath + entry.name + "/";
while (true) {
const batch = await new Promise((resolve, reject) =>
reader.readEntries(resolve, reject)
);
if (batch.length === 0) break;
for (const child of batch) {
const grandkids = await walkEntry(child, here);
out.push(...grandkids);
}
}
}
return out;
}
function isImage(file) {
if (file.type && file.type.startsWith("image/")) return true;
return /\.(jpe?g|png|webp)$/i.test(file.name);
}
function isVideo(file) {
if (file.type && file.type.startsWith("video/")) return true;
return /\.(mp4|mov|m4v|webm)$/i.test(file.name);
}
// Probe a video file for duration + resolution. ~100-300 ms typically.
function probeVideo(file) {
return new Promise((resolve, reject) => {
const v = document.createElement("video");
v.preload = "metadata";
v.muted = true;
const url = URL.createObjectURL(file);
v.src = url;
v.onloadedmetadata = () => {
const meta = {
duration: v.duration,
width: v.videoWidth,
height: v.videoHeight,
};
URL.revokeObjectURL(url);
resolve(meta);
};
v.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error(`Couldn't read video: ${file.name}. Format may not be supported in this browser.`));
};
});
}
// Probe an image for its pixel dimensions so the ZIP estimate reflects the real
// input size (a small, low-byte JPEG can still be very high resolution).
// Cheap: just reads natural dimensions, doesn't keep a decoded bitmap.
function probeImage(file) {
return new Promise(resolve => {
const img = new Image();
const url = URL.createObjectURL(file);
img.onload = () => {
const meta = { width: img.naturalWidth, height: img.naturalHeight };
URL.revokeObjectURL(url);
resolve(meta);
};
img.onerror = () => { URL.revokeObjectURL(url); resolve(null); };
img.src = url;
});
}
// Run an async fn over items with a bounded number of concurrent workers.
async function forEachLimited(items, limit, fn) {
let i = 0;
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
while (i < items.length) {
const idx = i++;
await fn(items[idx], idx);
}
});
await Promise.all(workers);
}
async function addFiles(files) {
const newVideos = [];
const newImages = [];
for (const f of files) {
if (isImage(f)) {
if (!f.relPath) tagRelPath(f, f.webkitRelativePath || f.name);
f.kind = "image";
f.imageMeta = null;
queuedFiles.push(f);
newImages.push(f);
} else if (isVideo(f)) {
if (!f.relPath) tagRelPath(f, f.webkitRelativePath || f.name);
f.kind = "video";
f.videoMeta = null;
queuedFiles.push(f);
newVideos.push(f);
}
// silently skip non-media files
}
updateFileList();
// Probe videos (for duration + dimensions) and image dimensions concurrently;
// refresh the estimate as results land. Image probing is bounded + non-blocking
// — Convert isn't gated on it; the ZIP estimate just refines as dims arrive.
let imgProbed = 0;
await Promise.all([
Promise.all(newVideos.map(async v => {
try { v.videoMeta = await probeVideo(v); }
catch (e) { v.videoError = e.message; }
updateFileList();
})),
forEachLimited(newImages, 16, async img => {
img.imageMeta = await probeImage(img);
if (++imgProbed % 16 === 0) updateFileList();
}).then(updateFileList),
]);
}
async function handleDrop(e) {
e.preventDefault();
els.dropZone.classList.remove("dragging");
const items = e.dataTransfer.items;
if (items && items.length && items[0].webkitGetAsEntry) {
const collected = [];
for (const item of items) {
const entry = item.webkitGetAsEntry && item.webkitGetAsEntry();
if (!entry) continue;
const files = await walkEntry(entry);
collected.push(...files);
}
await addFiles(collected);
} else {
await addFiles(e.dataTransfer.files);
}
}
function setupDropZone() {
["dragenter", "dragover"].forEach(evt =>
els.dropZone.addEventListener(evt, e => {
e.preventDefault();
els.dropZone.classList.add("dragging");
})
);
els.dropZone.addEventListener("dragleave", e => {
e.preventDefault();
els.dropZone.classList.remove("dragging");
});
els.dropZone.addEventListener("drop", handleDrop);
els.pickFilesBtn.addEventListener("click", () => els.fileInput.click());
els.fileInput.addEventListener("change", async e => {
await addFiles(e.target.files);
e.target.value = "";
});
els.pickFolderBtn.addEventListener("click", () => els.folderInput.click());
els.folderInput.addEventListener("change", async e => {
await addFiles(e.target.files);
e.target.value = "";
});
els.clearBtn.addEventListener("click", () => {
cleanupVideoElements();
queuedFiles = [];
updateFileList();
});
}
// ---------- Render unit expansion (images + video frames) ----------
// Expand the queue into individual render units: one per image, N per video
// (where N = ceil(duration / interval) frames, including t=0 and the last clean step).
function expandToUnits(files, frameInterval) {
const units = [];
for (const f of files) {
if (f.kind === "video") {
if (!f.videoMeta) continue;
const dur = f.videoMeta.duration;
const step = Math.max(0.05, frameInterval); // floor at 50ms
const n = Math.max(1, Math.floor(dur / step) + 1);
for (let i = 0; i < n; i++) {
const t = Math.min(i * step, Math.max(0, dur - 0.001));
units.push({ kind: "frame", file: f, frameIndex: i, time: t });
}
} else {
units.push({ kind: "image", file: f });
}
}
return units;
}
function formatSecondsForFilename(t) {
// Zero-padded for lexicographic sort: "00000.00" .. "99999.99"
return t.toFixed(2).padStart(8, "0");
}
// ---------- Output name derivation ----------
// Strip filesystem-unsafe characters. Allow letters, digits, dash, underscore, dot.
function sanitizeName(s) {
return s.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
}
// Pick a base name from the queued files:
// - If all files share a common top-level folder, use that folder's name
// - Else if exactly one file, use its filename stem
// - Else fall back to "pano2views"
function deriveBaseName(files) {
if (files.length === 0) return "pano2views";
const topFolders = new Set();
for (const f of files) {
const path = f.relPath || f.name;
const i = path.indexOf("/");
topFolders.add(i >= 0 ? path.slice(0, i) : null);
}
if (topFolders.size === 1) {
const only = [...topFolders][0];
if (only) return sanitizeName(only);
// Single loose file with no folder
if (files.length === 1) {
return sanitizeName(stemPath(files[0].name));
}
}
return "pano2views";
}
function currentBaseName() {
const userVal = (els.outputName.value || "").trim();
if (userVal) return sanitizeName(userVal) || "pano2views";
return deriveBaseName(queuedFiles);
}
// ---------- Auto-batching ----------
const ZIP_BUDGET_BYTES = 800 * 1024 * 1024; // ~800 MB per ZIP part
// Estimate output ZIP bytes for one source.
// match mode: 6 faces of (srcWidth/4 · fov/90) px, JPEG q=0.92 ≈ 0.5 byte/px
// → ~6·(W/4·fov/90)²·0.5 = 3/16·W²·(fov/90)². Conservatively padded to 0.3.
// Output area scales with the square of the per-face size, so it grows with
// both the input width AND the FOV (wider FOV = larger faces in match mode).
// fixed mode: 6·px²·0.5 — independent of input width and FOV.
function estimateOutputBytes(srcWidth, sizeSetting, fovDeg) {
if (sizeSetting !== "match") {
const px = parseInt(sizeSetting, 10);
return Math.ceil(6 * px * px * 0.5);
}
const f = (fovDeg || 90) / 90;
return Math.ceil(srcWidth * srcWidth * 0.3 * f * f);
}
function estimateUnitBytes(unit, sizeSetting, fovDeg) {
// Image in match mode whose dimensions haven't been probed yet: fall back to
// the source-bytes heuristic (FOV-scaled) until the probe lands.
if (sizeSetting === "match" && unit.kind === "image"
&& !(unit.file.imageMeta && unit.file.imageMeta.width)) {
const f = (fovDeg || 90) / 90;
return Math.ceil(unit.file.size * 1.5 * f * f);
}
const srcWidth = unit.kind === "frame"
? unit.file.videoMeta.width
: (unit.file.imageMeta ? unit.file.imageMeta.width : 0);
return estimateOutputBytes(srcWidth, sizeSetting, fovDeg);
}
function planChunks(units, sizeSetting, fovDeg) {
if (units.length === 0) return [];
const chunks = [[]];
let running = 0;
for (const u of units) {
const est = estimateUnitBytes(u, sizeSetting, fovDeg);
const cur = chunks[chunks.length - 1];
if (cur.length > 0 && running + est > ZIP_BUDGET_BYTES) {
chunks.push([u]);
running = est;
} else {
cur.push(u);
running += est;
}
}
return chunks;
}
function formatBytes(b) {
if (b < 1024 * 1024) return (b / 1024).toFixed(0) + " KB";
if (b < 1024 * 1024 * 1024) return (b / (1024 * 1024)).toFixed(0) + " MB";
return (b / (1024 * 1024 * 1024)).toFixed(1) + " GB";
}
// ---------- File list / summary display ----------
function updateFileList() {
const n = queuedFiles.length;
const nImg = queuedFiles.filter(f => f.kind === "image").length;
const nVid = queuedFiles.filter(f => f.kind === "video").length;
const probingVideos = queuedFiles.filter(f => f.kind === "video" && !f.videoMeta && !f.videoError).length;
// Show/hide the frame-interval field based on whether any videos are queued.
els.intervalField.style.display = nVid > 0 ? "block" : "none";
if (n === 0) {
els.fileSummary.textContent = "";
els.fileList.innerHTML = "";
els.clearBtn.style.display = "none";
els.multiNotice.style.display = "none";
els.convertBtn.disabled = true;
els.outputName.placeholder = "auto (from folder/file name)";
return;
}
els.outputName.placeholder = deriveBaseName(queuedFiles);
const folders = new Set();
for (const f of queuedFiles) {
const path = f.relPath || f.name;
const idx = path.lastIndexOf("/");
folders.add(idx >= 0 ? path.slice(0, idx) : "(loose files)");
}
const folderCount = folders.size;
const sizeSetting = els.sizeSelect.value;
const fov = parseFloat(els.fovSlider.value) || ACTIVE_LAYOUT.defaultFov;
const interval = parseFloat(els.intervalInput.value) || 1;
const units = expandToUnits(queuedFiles, interval);
const nFrames = units.filter(u => u.kind === "frame").length;
const totalEst = units.reduce((s, u) => s + estimateUnitBytes(u, sizeSetting, fov), 0);
const chunks = planChunks(units, sizeSetting, fov);
// Compose summary line.
const parts = [];
if (nImg > 0) parts.push(`${nImg} image${nImg === 1 ? "" : "s"}`);
if (nVid > 0) {
let v = `${nVid} video${nVid === 1 ? "" : "s"}`;
if (probingVideos > 0) v += ` (${probingVideos} probing…)`;
else v += ` → ${nFrames} frame${nFrames === 1 ? "" : "s"} @ ${interval}s`;
parts.push(v);
}
parts.push(`from ${folderCount} folder${folderCount === 1 ? "" : "s"}`);
if (probingVideos === 0) {
parts.push(`~${formatBytes(totalEst)} output, ${chunks.length} ZIP${chunks.length === 1 ? "" : "s"}`);
}
els.fileSummary.textContent = parts.join(" · ");
if (chunks.length > 1 && probingVideos === 0) {
els.multiNotice.innerHTML =
`<strong>This job will be split into ${chunks.length} ZIP files</strong> ` +
`(~${formatBytes(totalEst)} total) so the browser doesn't run out of memory. ` +
`Each ZIP downloads automatically when its part is ready. ` +
`Your browser will ask once whether to allow multiple downloads — ` +
`<strong>please click Allow</strong> so you receive every part. ` +
`When you extract them all to the same folder, they merge cleanly.`;
els.multiNotice.style.display = "block";
} else {
els.multiNotice.style.display = "none";
}
// First 8 file paths.
els.fileList.innerHTML = "";
const SHOW = 8;
queuedFiles.slice(0, SHOW).forEach(f => {
const li = document.createElement("li");
let label = f.relPath || f.name;
if (f.kind === "video") {
if (f.videoMeta) {
const fr = Math.floor(f.videoMeta.duration / (parseFloat(els.intervalInput.value) || 1)) + 1;
label += ` [video, ${f.videoMeta.duration.toFixed(1)}s → ${fr} frames]`;
} else if (f.videoError) {
label += ` [video, error: ${f.videoError}]`;
} else {
label += ` [video, probing…]`;
}
}
li.textContent = label;
els.fileList.appendChild(li);
});
if (n > SHOW) {
const li = document.createElement("li");
li.style.fontStyle = "italic";
li.style.color = "var(--muted)";
li.textContent = `…and ${n - SHOW} more`;
els.fileList.appendChild(li);
}
els.clearBtn.style.display = "inline-block";
// Disable convert while any probe is in flight.
els.convertBtn.disabled = probingVideos > 0;
}
// ---------- Field setup ----------
function setupFovSlider() {
const sync = () => {
els.fovValue.textContent = els.fovSlider.value + "°";
// FOV changes the match-mode face size, hence the output/ZIP estimate.
updateFileList();
};
els.fovSlider.addEventListener("input", sync);
els.fovSlider.value = ACTIVE_LAYOUT.defaultFov;
sync();
}
function setupSizeSelect() {
els.sizeSelect.addEventListener("change", updateFileList);
}
function setupIntervalInput() {
// Clamp + refresh on every change.
els.intervalInput.addEventListener("input", () => {
let v = parseFloat(els.intervalInput.value);
if (isNaN(v) || v < 0.1) v = 0.1;
if (v > 60) v = 60;
// Avoid clobbering the input while user is typing; only update if invalid.
updateFileList();
});
}
// ---------- Auto-download helper ----------
async function downloadBlob(blob, filename) {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
await new Promise(r => setTimeout(r, 800));
URL.revokeObjectURL(url);
}
// ---------- Video element lifecycle ----------
// Lazy-open a video element for a file. Reused across frames of the same file
// (and across chunks if the video spans multiple ZIP parts).
async function getVideoElement(file) {
if (file._videoElement) return file._videoElement;
const v = document.createElement("video");
v.muted = true;
v.preload = "auto";
v.playsInline = true;
v.src = URL.createObjectURL(file);
await new Promise((res, rej) => {
v.addEventListener("loadeddata", res, { once: true });
v.addEventListener("error", () =>
rej(new Error(`Couldn't load video: ${file.name}`)), { once: true });
});
file._videoElement = v;
return v;
}
function cleanupVideoElements() {
for (const f of queuedFiles) {
if (f._videoElement) {
URL.revokeObjectURL(f._videoElement.src);
f._videoElement = null;
}
}
}
async function seekVideo(videoEl, t) {
return new Promise((resolve, reject) => {
const onSeeked = () => { cleanup(); resolve(); };
const onErr = () => { cleanup(); reject(new Error("Video seek failed")); };
const cleanup = () => {
videoEl.removeEventListener("seeked", onSeeked);
videoEl.removeEventListener("error", onErr);
};
videoEl.addEventListener("seeked", onSeeked, { once: true });
videoEl.addEventListener("error", onErr, { once: true });
videoEl.currentTime = t;
});
}
// ---------- Conversion ----------
function showError(msg) {
els.errorBox.textContent = msg;
els.errorBox.style.display = "block";
}
function clearError() {
els.errorBox.textContent = "";
els.errorBox.style.display = "none";
}
function computeOutSize(equirectWidth, fovDeg, sizeSetting, maxTextureSize) {
if (sizeSetting === "match") {
return Math.min(maxTextureSize, Math.floor(equirectWidth / 4 * (fovDeg / 90)));
}
return parseInt(sizeSetting, 10);
}
function stemPath(relPath) {
return relPath.replace(/\.[^./]+$/, "");
}
// 35mm-equivalent focal from a horizontal FOV on a square sensor (36 mm wide).
// f = (36/2) / tan(fov/2). 90° -> 18 mm; 60° -> 31.18 mm; 120° -> 10.39 mm.
function focal35mmFromFov(fovDeg) {
const half = (fovDeg / 2) * Math.PI / 180;
return 18 / Math.tan(half);
}
// Minimal RealityScan XMP sidecar: fixed calibration only, no pose.
// CalibrationPrior="exact" tells RS not to refine the intrinsics.
// No xcr:Rotation / xcr:Position / xcr:PosePrior — alignment solves pose freely.
function buildXmp(fovDeg) {
const f = focal35mmFromFov(fovDeg).toFixed(6);
return `<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description xcr:Version="3"
xcr:DistortionModel="perspective" xcr:DistortionCoeficients="0 0 0 0 0 0"
xcr:FocalLength35mm="${f}" xcr:Skew="0" xcr:AspectRatio="1"
xcr:PrincipalPointU="0" xcr:PrincipalPointV="0"
xcr:CalibrationPrior="exact" xcr:CalibrationGroup="-1" xcr:DistortionGroup="-1"
xcr:InTexturing="1" xcr:InMeshing="1"
xmlns:xcr="http://www.capturingreality.com/ns/xcr/1.1#"/>
</rdf:RDF>
</x:xmpmeta>
`;
}
async function convertAll() {
clearError();
els.convertBtn.disabled = true;
els.downloadBox.style.display = "none";
try {
if (!renderer) renderer = new FaceRenderer();
const fov = parseFloat(els.fovSlider.value);
const sizeSetting = els.sizeSelect.value;
const interval = Math.max(0.1, parseFloat(els.intervalInput.value) || 1);
const xmpText = els.writeXmp && els.writeXmp.checked ? buildXmp(fov) : null;
const baseName = currentBaseName();
const units = expandToUnits(queuedFiles, interval);
const chunks = planChunks(units, sizeSetting, fov);
const totalSteps = units.length * ACTIVE_LAYOUT.faces.length;
let stepsDone = 0;
if (totalSteps === 0) {
throw new Error("Nothing to render. Add at least one image or video.");
}
els.progress.style.display = "block";
els.progressBar.style.width = "0%";
for (let ci = 0; ci < chunks.length; ci++) {
const chunk = chunks[ci];
const zip = new JSZip();
if (chunks.length > 1) {
els.progressLabel.textContent = `Part ${ci + 1} of ${chunks.length}`;
els.progressLabel.style.display = "block";
} else {
els.progressLabel.style.display = "none";
}
for (const u of chunk) {
if (u.kind === "image") {
await renderImageUnit(u, zip, fov, sizeSetting, xmpText);
} else {
await renderFrameUnit(u, zip, fov, sizeSetting, xmpText);
}
stepsDone += ACTIVE_LAYOUT.faces.length;
const pct = Math.floor((stepsDone / totalSteps) * 100);
els.progressBar.style.width = pct + "%";
}
els.progressText.textContent = `Packaging part ${ci + 1}/${chunks.length}…`;
const zipBlob = await zip.generateAsync({ type: "blob" });
const partLabel = chunks.length > 1
? `_part${String(ci + 1).padStart(2, "0")}_of_${String(chunks.length).padStart(2, "0")}`
: "";
const zipName = `${baseName}_cubemap_fov${Math.round(fov)}${partLabel}.zip`;
await downloadBlob(zipBlob, zipName);
}
els.downloadLink.style.display = "none";
const summary = chunks.length === 1
? "Your faces are ready — check your downloads folder."
: `${chunks.length} ZIPs downloaded — check your downloads folder. ` +
`(Your browser may have asked permission for multiple downloads; allow it to receive every part.)`;
els.downloadBox.querySelector("p").textContent = summary;
els.downloadBox.style.display = "block";
els.progressText.textContent =
`Done — ${units.length} render unit${units.length === 1 ? "" : "s"}, ${stepsDone} faces, ${chunks.length} ZIP${chunks.length === 1 ? "" : "s"}.`;
} catch (err) {
console.error(err);
showError(err.message || String(err));
} finally {
cleanupVideoElements();
els.convertBtn.disabled = queuedFiles.length === 0;
}
}
// "shoot/foo/bar" -> "shoot/foo/"; "bar" -> "" (loose-file case, root of ZIP)
function parentDir(relStem) {
const i = relStem.lastIndexOf("/");
return i >= 0 ? relStem.slice(0, i + 1) : "";
}
// Render one image -> 6 face JPEGs alongside the source's parent folder.
// shoot/IMG_0001.jpg -> shoot/IMG_0001_{face}.jpg
async function renderImageUnit(unit, zip, fov, sizeSetting, xmpText) {
const file = unit.file;
const relStem = stemPath(file.relPath || file.name); // "shoot/IMG_0001"
const fileStem = relStem.split("/").pop(); // "IMG_0001"
const parent = parentDir(relStem); // "shoot/"
const bitmap = await createImageBitmap(file);
renderer.setEquirect(bitmap);
const outSize = computeOutSize(bitmap.width, fov, sizeSetting, renderer.maxTextureSize);
for (const face of ACTIVE_LAYOUT.faces) {
const blob = await renderer.renderFace(face, fov, outSize);
const base = `${parent}${fileStem}_${face.name}`;
zip.file(`${base}.jpg`, blob);
if (xmpText) zip.file(`${base}.xmp`, xmpText);
els.progressText.textContent = `${file.relPath || file.name} — ${face.name}`;
await new Promise(r => setTimeout(r, 0));
}
bitmap.close && bitmap.close();
}
// Render one video frame -> 6 face JPEGs inside a single per-video folder.
// shoot/clip.mp4 @ t=2s -> shoot/clip/clip_t00002.00s_{face}.jpg
// Videos keep a folder of their own so many frames don't crowd sibling images.
async function renderFrameUnit(unit, zip, fov, sizeSetting, xmpText) {
const file = unit.file;
const relStem = stemPath(file.relPath || file.name); // "shoot/clip"
const videoStem = relStem.split("/").pop(); // "clip"
const parent = parentDir(relStem); // "shoot/"
const tLabel = formatSecondsForFilename(unit.time);
const frameName = `${videoStem}_t${tLabel}s`;
const folderPath = `${parent}${videoStem}/`; // "shoot/clip/"
const videoEl = await getVideoElement(file);
await seekVideo(videoEl, unit.time);
renderer.setEquirect(videoEl);
const outSize = computeOutSize(videoEl.videoWidth, fov, sizeSetting, renderer.maxTextureSize);
for (const face of ACTIVE_LAYOUT.faces) {
const blob = await renderer.renderFace(face, fov, outSize);
const base = `${folderPath}${frameName}_${face.name}`;
zip.file(`${base}.jpg`, blob);
if (xmpText) zip.file(`${base}.xmp`, xmpText);
els.progressText.textContent =
`${file.relPath || file.name} t=${unit.time.toFixed(2)}s — ${face.name}`;
await new Promise(r => setTimeout(r, 0));
}
}
// ---------- Init ----------
document.addEventListener("DOMContentLoaded", () => {
setupDropZone();
setupFovSlider();
setupSizeSelect();
setupIntervalInput();
els.convertBtn.addEventListener("click", convertAll);
});