Repository navigation
Expand file tree
/
Copy pathtesseract.js
More file actions
4341 lines (3993 loc) · 194 KB
/
Copy pathtesseract.js
File metadata and controls
4341 lines (3993 loc) · 194 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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2026 Michael Pilosov. All rights reserved. */
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { installSkyboxLibrary } from './viewer-skyboxes.js';
import { installVisualMusic } from './visual-music.js';
// Main Three.js scene setup
let scene, camera, renderer, controls;
const physicalLights = [];
let shadowState = '';
let tesseract;
let visualMusic;
let restoredMusicSettings = null;
let currentShape = 'tesseract';
let rotationSpeed = 0.005;
let time = 0;
let animationPaused = true;
let timelineFrame = 0;
let exportFps = 60;
let videoExportWidth = 1920;
let videoExportHeight = 1080;
let videoExportQuality = 'standard';
let videoExportRunning = false;
let activeVideoExportJob = null;
let activeVideoExportPlan = null;
let cancelVideoExportRequested = false;
let videoExportAbort = null;
let videoExportStopAction = null;
let videoExportStopPromise = null;
let videoExportStopJobId = null;
let videoCaptureSurface = null;
let videoCaptureContext = null;
let videoCaptureFallback = false;
let loopTiming = { period: 0, frameCount: 1, timeStep: 0, exact: true };
let lastAnimationTimestamp = null;
let frameAccumulator = 0;
// Track object references
let vertices = [];
let edges = [];
let faces = [];
// Rotation coefficients
let rotationCoefficients = {
xw: 0.0,
yw: 0.0,
zw: 0.0
};
// Shader options
let currentShader = 'chrome';
// Lighting options
let currentLighting = 'diagonal';
let lightDistance = 0.1;
// UI elements
let controlPanel;
let showVertices = false;
// Chrome's per-pixel grain re-randomizes as the projection moves, so every
// frame carries fresh noise that dominates video bitrate.
let surfaceGrain = true;
// Aged edge grime and dust fixed to each face: texture that moves with the
// glass, so it compresses far better than per-frame grain.
let dirtyMirrors = false;
let mirrorReflections = false;
let mirrorTraceState = null;
let showOverlay = true;
let cameraInfoDisplay;
let motionStepSlider;
let motionStepLabel;
let loopInfoDisplay;
let timelineSlider;
let timelineFrameDisplay;
let timelineFrameInput;
let exportFpsSelect;
let videoExportButton;
let videoExportDialog;
let soundToggle;
let videoExportDialogRequest = 0;
let videoResumeJobsRequest = 0;
let panelExpanded = true;
let videoTimingExpanded = false;
let savedCameraPosition = { x: 3, y: 3, z: 3 };
let savedCameraTarget = { x: 0, y: 0, z: 0 };
const VIEWER_SETTINGS_KEY = 'tesseract.viewer-settings.v1';
const VIDEO_EXPORT_INTERRUPTED_KEY = 'tesseract.video-export-interrupted';
let videoExportWasInterrupted = false;
try {
videoExportWasInterrupted = sessionStorage.getItem(VIDEO_EXPORT_INTERRUPTED_KEY) === 'yes';
sessionStorage.removeItem(VIDEO_EXPORT_INTERRUPTED_KEY);
} catch {
// Session storage is optional; navigation protection still works without it.
}
let publication = null;
try {
const text = document.getElementById('piece-config')?.textContent.trim();
if (text) publication = JSON.parse(text);
} catch (error) {
console.error('Invalid published piece configuration', error);
}
if (publication?.schemaVersion === 1 && publication.title) document.title = publication.title;
function viewerSettings() {
return {
shape: currentShape,
rotationSpeed,
rotationCoefficients: { ...rotationCoefficients },
shader: currentShader,
lighting: currentLighting,
lightDistance,
showVertices,
surfaceGrain,
dirtyMirrors,
mirrorReflections,
animationPaused,
exportFps,
videoExportWidth,
videoExportHeight,
videoExportQuality,
timelineFrame,
panelExpanded,
videoTimingExpanded,
music: visualMusic?.settings ?? restoredMusicSettings,
camera: {
position: camera ? { x: camera.position.x, y: camera.position.y, z: camera.position.z } : { ...savedCameraPosition },
target: controls ? { x: controls.target.x, y: controls.target.y, z: controls.target.z } : { ...savedCameraTarget }
}
};
}
function defaultViewerSettings() {
return {
shape: 'tesseract',
rotationSpeed: 0.005,
rotationCoefficients: { xw: 0, yw: 0, zw: 0 },
shader: 'chrome',
lighting: 'diagonal',
lightDistance: 0.1,
showVertices: false,
surfaceGrain: true,
dirtyMirrors: false,
mirrorReflections: false,
animationPaused: true,
exportFps: 60,
videoExportWidth: 1920,
videoExportHeight: 1080,
videoExportQuality: 'standard',
timelineFrame: 0,
panelExpanded: true,
videoTimingExpanded: false,
music: visualMusic?.defaultSettings ?? { enabled: false },
camera: {
position: { x: 3, y: 3, z: 3 },
target: { x: 0, y: 0, z: 0 }
}
};
}
function applyViewerSettings(saved) {
if (!saved || typeof saved !== 'object') return;
const clamp = (value, min, max, fallback) => {
const number = Number(value);
return Number.isFinite(number) ? Math.min(max, Math.max(min, number)) : fallback;
};
setViewerShape(saved.shape || 'tesseract');
rotationSpeed = clamp(saved.rotationSpeed, 0, 0.01, rotationSpeed);
lightDistance = clamp(saved.lightDistance, 0.1, 20, lightDistance);
for (const axis of ['xw', 'yw', 'zw']) {
rotationCoefficients[axis] = clamp(saved.rotationCoefficients?.[axis], -1, 1, rotationCoefficients[axis]);
}
if (['rough', 'iridescent', 'chrome'].includes(saved.shader)) currentShader = saved.shader;
if (['diagonal', 'topdown', 'quad'].includes(saved.lighting)) currentLighting = saved.lighting;
if ([24, 25, 30, 50, 60].includes(Number(saved.exportFps))) exportFps = Number(saved.exportFps);
const videoWidth = Number(saved.videoExportWidth);
const videoHeight = Number(saved.videoExportHeight);
if ([[1280, 720], [1920, 1080], [2560, 1440], [3840, 2160], [1080, 1080]].some(([width, height]) => width === videoWidth && height === videoHeight)) {
videoExportWidth = videoWidth;
videoExportHeight = videoHeight;
}
if (['draft', 'standard', 'high', 'capped', 'master'].includes(saved.videoExportQuality)) videoExportQuality = saved.videoExportQuality;
if (typeof saved.showVertices === 'boolean') showVertices = saved.showVertices;
if (typeof saved.surfaceGrain === 'boolean') surfaceGrain = saved.surfaceGrain;
if (typeof saved.dirtyMirrors === 'boolean') dirtyMirrors = saved.dirtyMirrors;
if (typeof saved.mirrorReflections === 'boolean') mirrorReflections = saved.mirrorReflections;
if (typeof saved.animationPaused === 'boolean') animationPaused = saved.animationPaused;
if (typeof saved.panelExpanded === 'boolean') panelExpanded = saved.panelExpanded;
if (typeof saved.videoTimingExpanded === 'boolean') videoTimingExpanded = saved.videoTimingExpanded;
if (saved.music && typeof saved.music === 'object') {
restoredMusicSettings = saved.music;
visualMusic?.setSettings(saved.music);
}
const vector = (value, fallback) => {
if (!value || !['x', 'y', 'z'].every(axis => Number.isFinite(Number(value[axis])))) return fallback;
return { x: Number(value.x), y: Number(value.y), z: Number(value.z) };
};
savedCameraPosition = vector(saved.camera?.position, savedCameraPosition);
savedCameraTarget = vector(saved.camera?.target, savedCameraTarget);
timelineFrame = Math.max(0, Math.trunc(Number(saved.timelineFrame) || 0));
}
function loadViewerSettings() {
if (publication?.schemaVersion === 1) {
applyViewerSettings(publication.viewer);
// Published work opens as artwork first; controls remain available
// behind the small corner button.
panelExpanded = false;
return;
}
try {
applyViewerSettings(JSON.parse(localStorage.getItem(VIEWER_SETTINGS_KEY)));
} catch {
// Keep defaults when local storage is unavailable or contains invalid data.
}
}
function persistViewerSettings() {
if (publication?.schemaVersion === 1) return;
try {
localStorage.setItem(VIEWER_SETTINGS_KEY, JSON.stringify(viewerSettings()));
} catch {
// The viewer remains usable when local storage is blocked or full.
}
}
loadViewerSettings();
window.addEventListener('beforeunload', event => {
// Once cancel is requested, don't trap the tab. The in-flight upload is
// aborted and pagehide tells the server to drop the job.
if (!videoExportRunning || cancelVideoExportRequested) return;
event.preventDefault();
event.returnValue = '';
});
window.addEventListener('pagehide', () => {
if (activeVideoExportJob && videoExportStopAction !== 'discard') {
try { sessionStorage.setItem(VIDEO_EXPORT_INTERRUPTED_KEY, 'yes'); } catch { /* Optional. */ }
const body = new Blob([JSON.stringify({
id: activeVideoExportJob.id,
lease: activeVideoExportJob.lease
})], { type: 'text/plain' });
navigator.sendBeacon('/api/video/pause', body);
}
});
window.addEventListener('pageshow', event => {
// A back/forward-cache restore would otherwise revive a frozen progress UI.
if (event.persisted && videoExportRunning) location.reload();
});
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden' && !videoExportRunning) persistViewerSettings();
});
// File drop zone
let dropZone;
let dropZoneVisible = false;
// Environment map for reflections
let envMap;
let skyboxLibrary;
// Bound both ends of the view, including restored and programmatic camera changes.
function clampCameraCoordinates() {
camera.position.clampScalar(-3, 3);
controls.target.clampScalar(-3, 3);
camera.lookAt(controls.target);
}
function updatePhysicalLighting() {
const quad = currentLighting === 'quad';
const radius = lightDistance;
physicalLights.forEach((light, index) => {
light.intensity = quad ? Math.PI : index === 0 ? 4 * Math.PI : 0;
light.visible = light.castShadow = light.intensity > 0;
if (quad) {
light.position.set(index === 0 ? radius : index === 1 ? -radius : 0, 0,
index === 2 ? radius : index === 3 ? -radius : 0);
} else if (currentLighting === 'topdown') {
light.position.set(0, radius, 0);
} else {
light.position.setScalar(radius / Math.sqrt(3));
}
// scene.onBeforeRender runs after the renderer's matrix traversal.
light.updateMatrixWorld();
});
// Camera movement alone does not invalidate world-space shadow maps.
const state = `${time}/${currentShape}/${currentLighting}/${lightDistance}/${showVertices}`;
if (state !== shadowState) {
renderer.shadowMap.needsUpdate = true;
shadowState = state;
}
}
// Initialize the scene
function init() {
console.log("Initializing...");
// Create scene
scene = new THREE.Scene();
for (let i = 0; i < 4; i++) {
const light = new THREE.PointLight(0xffffff, 0, 0, 2);
light.shadow.mapSize.set(256, 256);
light.shadow.camera.near = 0.01;
light.shadow.camera.far = 40;
light.shadow.bias = -0.00005;
light.shadow.normalBias = 0; // Receiver-plane correction handles either side without a normal offset.
physicalLights.push(light);
scene.add(light);
}
// Runs for live view, screenshots, soundtrack sampling, and video alike.
scene.onBeforeRender = updatePhysicalLighting;
// Create camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 1000);
camera.position.set(savedCameraPosition.x, savedCameraPosition.y, savedCameraPosition.z);
// Create renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
// Compress HDR highlights before sRGB encoding instead of clipping them flat.
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFShadowMap;
renderer.shadowMap.autoUpdate = false;
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Add orbit controls
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.minDistance = 0.01; // Hard stop for scroll/pinch zoom toward the target.
controls.target.set(savedCameraTarget.x, savedCameraTarget.y, savedCameraTarget.z);
controls.addEventListener('change', clampCameraCoordinates);
clampCameraCoordinates();
controls.addEventListener('end', persistViewerSettings);
// Create the tesseract
createTesseract();
// Handle window resize
window.addEventListener('resize', onWindowResize, false);
// Add keyboard controls
window.addEventListener('keydown', onKeyDown, false);
// Add UI controls, then connect the soundtrack and export library to the scene.
createControls();
visualMusic = installVisualMusic({
mount: document.getElementById('controlPanelContent'),
canvas: renderer.domElement,
sampleFrame: sampleLiveSoundFrame,
initialSettings: restoredMusicSettings,
onStateChange: persistViewerSettings,
onPlaybackChange: updateSoundToggle
});
if (publication?.schemaVersion === 1 && publication.viewer?.musicAutoplay === true) {
visualMusic.requestAutoplay();
}
createEnvironmentMap();
// Initialize file upload for loading views
initFileUpload();
// Create drop zone for file dropping
createDropZone();
// Setup drag and drop handlers
setupDragAndDropHandlers();
// Start on a real frame timestamp. A direct call has none, and the first
// delta would otherwise become NaN and freeze playback until a manual seek.
requestAnimationFrame(animate);
console.log("Initialization complete");
}
const SOUND_ICONS = {
on: '<path d="M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13"/>',
off: '<path d="m16 9 6 6m0-6-6 6"/>'
};
function updateSoundToggle(playing) {
if (!soundToggle) return;
const label = playing ? 'Mute soundtrack' : 'Play soundtrack';
soundToggle.setAttribute('aria-label', label);
soundToggle.setAttribute('aria-pressed', String(playing));
soundToggle.title = label;
soundToggle.innerHTML = `<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="display:block;margin:auto"><path d="M11 5 6 9H3v6h3l5 4z" fill="currentColor"/>${SOUND_ICONS[playing ? 'on' : 'off']}</svg>`;
Object.assign(soundToggle.style, {
flex: 'none',
width: '30px',
height: '30px',
padding: '0',
background: 'rgba(0, 0, 0, 0.18)',
color: playing ? 'rgba(255, 255, 255, 0.86)' : 'rgba(255, 255, 255, 0.68)',
border: '1px solid rgba(255, 255, 255, 0.16)',
cursor: 'pointer'
});
}
// Create environment map for reflections
function createEnvironmentMap() {
skyboxLibrary = installSkyboxLibrary({
mount: document.getElementById('controlPanelContent'),
renderer,
publication,
getViewerState: viewerSettings,
getDefaultViewerState: defaultViewerSettings,
getShader: () => currentShader,
onTexture: texture => {
const previous = envMap;
envMap = texture;
updateMaterialsWithEnvMap();
previous?.dispose();
},
onStateChange: refreshVideoEnvironmentState,
confirmAction,
onSwitchChrome: () => {
const select = document.getElementById('viewer-shader');
select.value = 'chrome';
select.dispatchEvent(new Event('change', { bubbles: true }));
}
});
}
// Setup drag and drop handlers for loading views
function setupDragAndDropHandlers() {
const dropZone = document.getElementById('drop-zone');
if (!dropZone) return;
let dragDepth = 0;
let dragTimeout = null;
const hideDropZone = () => {
dragDepth = 0;
clearTimeout(dragTimeout);
dragTimeout = null;
dropZone.style.display = 'none';
};
const showDropZone = () => {
dropZone.style.display = 'block';
clearTimeout(dragTimeout);
// External drags cancelled by the OS may send no dragleave/dragend.
// Active drags keep sending dragover, including while stationary.
dragTimeout = setTimeout(hideDropZone, 1200);
};
window.addEventListener('dragenter', () => {
dragDepth += 1;
showDropZone();
});
window.addEventListener('dragover', function(e) {
e.preventDefault();
e.stopPropagation();
showDropZone();
});
window.addEventListener('dragleave', function(e) {
e.preventDefault();
e.stopPropagation();
dragDepth = Math.max(0, dragDepth - 1);
if (dragDepth === 0 || e.clientX <= 0 || e.clientX >= window.innerWidth ||
e.clientY <= 0 || e.clientY >= window.innerHeight) hideDropZone();
});
window.addEventListener('dragend', hideDropZone);
window.addEventListener('blur', hideDropZone);
window.addEventListener('keydown', e => {
if (e.key === 'Escape') hideDropZone();
}, true);
document.addEventListener('visibilitychange', () => {
if (document.hidden) hideDropZone();
});
// Handle drop
window.addEventListener('drop', function(e) {
e.preventDefault();
e.stopPropagation();
hideDropZone();
if (e.dataTransfer.files.length > 0) {
const file = e.dataTransfer.files[0];
if (file.type === 'image/png') {
readMetadataFromPNG(file);
} else {
alert('Please drop a PNG image file.');
}
}
});
}
// Create a visual drop zone for dragging and dropping files
function createDropZone() {
const dropZone = document.createElement('div');
dropZone.id = 'drop-zone';
dropZone.innerHTML = 'Drop PNG here to load view';
dropZone.style.display = 'none';
dropZone.style.position = 'absolute';
dropZone.style.top = '0';
dropZone.style.left = '0';
dropZone.style.width = '100%';
dropZone.style.height = '100%';
dropZone.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
dropZone.style.color = 'white';
dropZone.style.textAlign = 'center';
dropZone.style.paddingTop = '45vh';
dropZone.style.fontSize = '24px';
dropZone.style.zIndex = '1000';
dropZone.style.pointerEvents = 'none';
document.body.appendChild(dropZone);
}
// Read metadata from a PNG file
function readMetadataFromPNG(file) {
console.log("Reading metadata from PNG file:", file.name);
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
let metadataSource = "embedded";
let success = false;
try {
// Create a canvas to read the PNG data
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// Try to extract metadata - first from pixel data
let metadata = null;
try {
// Method 1: Try to read from pixel data
const metadataRows = Math.min(canvas.height, 16);
const imgData = ctx.getImageData(0, 0, canvas.width, metadataRows);
const pixelData = imgData.data;
// Check for our marker pixel
if (pixelData[0] === 254 && pixelData[1] === 0 && pixelData[2] === 254) {
console.log("Found marker pixel, trying to extract metadata from pixels");
// Reconstruct string from pixel data
let dataString = "";
for (let i = 1; i < pixelData.length / 4; i++) { // Read the bounded metadata area
const pixelIndex = i * 4;
if (pixelIndex >= pixelData.length) break;
const charCode = pixelData[pixelIndex];
if (charCode === 0) break; // End of data
dataString += String.fromCharCode(charCode);
}
console.log("Extracted data string:", dataString);
// Check if we found our metadata marker
const marker = "tESSdata=";
if (dataString.startsWith(marker)) {
const jsonStr = dataString.substring(marker.length);
try {
// Extract only the valid JSON part by finding the last closing brace
let jsonEnd = jsonStr.lastIndexOf('}');
if (jsonEnd > 0) {
const cleanJsonStr = jsonStr.substring(0, jsonEnd + 1);
metadata = JSON.parse(cleanJsonStr);
console.log("Successfully extracted metadata from pixels:", metadata);
} else {
console.error("Failed to find valid JSON end delimiter in pixel data");
}
} catch (e) {
console.error("Failed to parse pixel metadata JSON:", e);
}
}
}
} catch (pixelError) {
console.error("Error reading pixel data:", pixelError);
}
// If we have valid metadata, apply it
if (metadata) {
console.log("Applying extracted metadata from PNG");
success = applyViewSettings(metadata);
if (success) {
alert("Successfully loaded view settings from embedded metadata!");
return;
}
}
// Fallback to filename parsing if no metadata found
console.log("No embedded metadata found, falling back to filename parsing");
metadataSource = "filename";
success = parseMetadataFromFilename(file.name);
if (success) {
alert("Successfully loaded view settings from filename!");
} else {
alert("Could not load view settings from either embedded metadata or filename.");
}
} catch (error) {
console.error('Error reading PNG metadata:', error);
// Fallback to filename parsing
console.log("Error reading PNG, falling back to filename parsing");
metadataSource = "filename (after error)";
success = parseMetadataFromFilename(file.name);
if (success) {
alert("Successfully loaded view settings from filename (after error)!");
} else {
alert("Failed to load view settings from either method.\nError: " + error.message);
}
}
};
img.onerror = function() {
alert('Failed to load the image.');
};
img.src = event.target.result;
};
reader.onerror = function() {
alert('Failed to read the file.');
};
reader.readAsDataURL(file);
}
// Parse metadata from filename for backward compatibility
function parseMetadataFromFilename(filename) {
console.log("Parsing metadata from filename:", filename);
try {
// First, remove any file extension
const cleanName = filename.replace(/\.png$/i, '');
// Expected format: tesseract_TIMESTAMP_pos_X_Y_Z_rot_XW_YW_ZW_time_T_target_TX_TY_TZ
const parts = cleanName.split('_');
console.log("Filename parts:", parts);
// Extract data from filename parts
let metadata = {
camera: { position: {} },
rotation: {},
time: 0, // Default time value
target: { x: 0, y: 0, z: 0 } // Default target at origin
};
// Find position values
const posIndex = parts.indexOf('pos');
if (posIndex > 0 && posIndex + 3 < parts.length) {
metadata.camera.position.x = parseFloat(parts[posIndex + 1]);
metadata.camera.position.y = parseFloat(parts[posIndex + 2]);
metadata.camera.position.z = parseFloat(parts[posIndex + 3]);
console.log("Found position:", metadata.camera.position);
}
// Find rotation values
const rotIndex = parts.indexOf('rot');
if (rotIndex > 0 && rotIndex + 3 < parts.length) {
metadata.rotation.xw = parseFloat(parts[rotIndex + 1]);
metadata.rotation.yw = parseFloat(parts[rotIndex + 2]);
metadata.rotation.zw = parseFloat(parts[rotIndex + 3]);
console.log("Found rotation:", metadata.rotation);
}
// Find time value
const timeIndex = parts.indexOf('time');
if (timeIndex > 0 && timeIndex + 1 < parts.length) {
metadata.time = parseFloat(parts[timeIndex + 1]);
console.log("Found time:", metadata.time);
}
// Find target values
const targetIndex = parts.indexOf('target');
if (targetIndex > 0 && targetIndex + 3 < parts.length) {
metadata.target.x = parseFloat(parts[targetIndex + 1]);
metadata.target.y = parseFloat(parts[targetIndex + 2]);
metadata.target.z = parseFloat(parts[targetIndex + 3]);
console.log("Found target:", metadata.target);
}
console.log("Extracted metadata from filename:", metadata);
// Apply the extracted settings
return applyViewSettings(metadata);
} catch (error) {
console.error("Error parsing metadata from filename:", error);
return false;
}
}
// Apply view settings from extracted metadata
function applyViewSettings(metadata) {
console.log("Applying view settings from metadata:", metadata);
try {
setViewerShape(metadata.shape || metadata.render?.shape || 'tesseract');
if (metadata.music) {
restoredMusicSettings = metadata.music;
visualMusic?.setSettings(metadata.music);
}
if (metadata.render) {
const { camera: renderCamera, ...renderSettings } = metadata.render;
restoreVideoRenderSettings({
...renderSettings,
shape: metadata.shape || metadata.render.shape || 'tesseract',
exportFps: metadata.render.fps,
videoExportWidth: metadata.video?.width,
videoExportHeight: metadata.video?.height,
videoExportQuality: metadata.video?.quality
});
}
// Set camera position
if (metadata.camera && metadata.camera.position) {
camera.position.set(
parseFloat(metadata.camera.position.x),
parseFloat(metadata.camera.position.y),
parseFloat(metadata.camera.position.z)
);
console.log("Set camera position to:", camera.position);
}
// Set rotation coefficients
if (metadata.rotation) {
rotationCoefficients.xw = parseFloat(metadata.rotation.xw) || 0;
rotationCoefficients.yw = parseFloat(metadata.rotation.yw) || 0;
rotationCoefficients.zw = parseFloat(metadata.rotation.zw) || 0;
console.log("Set rotation coefficients to:", rotationCoefficients);
// Update UI sliders if they exist
updateRotationSliders();
}
// Restore video timing before mapping the saved time onto the deterministic timeline.
if (metadata.animation?.fps) {
exportFps = parseInt(metadata.animation.fps, 10) || exportFps;
if (exportFpsSelect) exportFpsSelect.value = String(exportFps);
}
if (metadata.animation?.motionStep !== undefined) {
rotationSpeed = Math.max(0, parseFloat(metadata.animation.motionStep) || 0);
if (motionStepSlider) motionStepSlider.value = String(rotationSpeed * 1000);
if (motionStepLabel) motionStepLabel.textContent = `Motion Step: ${rotationSpeed.toFixed(3)} / frame`;
}
refreshLoopTiming({ preserveTime: false });
if (metadata.animation?.frame !== undefined) {
setTimelineFrame(parseInt(metadata.animation.frame, 10) || 0);
} else if (metadata.time !== undefined) {
setTimelineTime(parseFloat(metadata.time) || 0);
}
console.log("Set animation time to:", time);
// Set camera target
if (metadata.target) {
controls.target.set(
parseFloat(metadata.target.x) || 0,
parseFloat(metadata.target.y) || 0,
parseFloat(metadata.target.z) || 0
);
console.log("Set camera target to:", controls.target);
}
// Update controls and camera
controls.update();
camera.updateProjectionMatrix();
// Ensure all material uniforms are updated correctly
// For backward compatibility - reapply current lighting parameters
const materials = [];
faces.forEach(face => {
if (face.material && !materials.includes(face.material)) {
materials.push(face.material);
}
});
vertices.forEach(vertex => {
if (vertex.material && !materials.includes(vertex.material)) {
materials.push(vertex.material);
}
});
// Convert lighting type to integer for shader
let lightingTypeInt;
switch(currentLighting) {
case 'topdown':
lightingTypeInt = 1;
break;
case 'quad':
lightingTypeInt = 2;
break;
case 'diagonal':
default:
lightingTypeInt = 0;
break;
}
// Update the uniform values in all materials
materials.forEach(material => {
if (material.uniforms) {
if (material.uniforms.lightDistance) {
material.uniforms.lightDistance.value = lightDistance;
}
if (material.uniforms.lightingType) {
material.uniforms.lightingType.value = lightingTypeInt;
}
// Without this, a restored "grain off" only unticks the checkbox while
// the existing faces keep rendering grain (and exports record it as off).
if (material.uniforms.surfaceGrain) {
material.uniforms.surfaceGrain.value = surfaceGrain ? 1 : 0;
}
if (material.uniforms.dirtyMirrors) {
material.uniforms.dirtyMirrors.value = dirtyMirrors ? 1 : 0;
}
if (material.uniforms.mirrorReflections) {
material.uniforms.mirrorReflections.value = mirrorReflections ? 1 : 0;
}
}
});
// If no materials were found, create new ones
if (materials.length === 0) {
updateMaterials();
}
// Pause animation when a view is restored
pauseAnimation();
persistViewerSettings();
console.log("Successfully applied view settings");
return true;
} catch (error) {
console.error("Error applying view settings:", error);
return false;
}
}
// Update rotation sliders in the UI
function updateRotationSliders() {
console.log("Updating rotation sliders to:", rotationCoefficients);
try {
// Look specifically for the rotation sliders in the rotationControls container
const rotationControls = document.getElementById('rotationControls');
if (!rotationControls) {
console.warn("Could not find rotation controls container - skipping slider update");
return;
}
const sliders = rotationControls.querySelectorAll('input[type="range"]');
if (sliders.length < 3) {
console.warn("Could not find enough rotation sliders, found:", sliders.length);
return;
}
// The sliders are now directly identified by their index in the rotation controls section
const xwSlider = sliders[0];
const ywSlider = sliders[1];
const zwSlider = sliders[2];
console.log("Found rotation sliders");
// Set slider values - using 20 as the multiplier for a step of 0.05 (1/20 = 0.05)
xwSlider.value = rotationCoefficients.xw * 20;
ywSlider.value = rotationCoefficients.yw * 20;
zwSlider.value = rotationCoefficients.zw * 20;
console.log("Set slider values to:", xwSlider.value, ywSlider.value, zwSlider.value);
// Update displayed values - with two decimal places
const valueDisplays = rotationControls.querySelectorAll('span');
if (valueDisplays.length >= 3) {
// Values are now directly targeted
valueDisplays[0].textContent = rotationCoefficients.xw.toFixed(2);
valueDisplays[1].textContent = rotationCoefficients.yw.toFixed(2);
valueDisplays[2].textContent = rotationCoefficients.zw.toFixed(2);
console.log("Updated value displays");
} else {
console.warn("Could not find enough value display elements, found:", valueDisplays.length);
}
// Force the slider input event to ensure any attached handlers run
try {
const event = new Event('input', { bubbles: true });
xwSlider.dispatchEvent(event);
ywSlider.dispatchEvent(event);
zwSlider.dispatchEvent(event);
} catch (e) {
console.warn("Could not dispatch events to sliders:", e);
}
} catch (error) {
console.warn("Error updating rotation sliders:", error);
// Continue execution, this is not a critical error
}
}
function syncRangeStepper(slider) {
const buttons = slider.closest('.range-stepper')?.querySelectorAll('button');
buttons?.forEach(button => { button.disabled = slider.disabled; });
}
function addRangeStepper(slider) {
if (slider.closest('.range-stepper')) return;
const wrapper = document.createElement('div');
wrapper.className = 'range-stepper';
const decrease = document.createElement('button');
const increase = document.createElement('button');
decrease.type = increase.type = 'button';
decrease.textContent = '−';
increase.textContent = '+';
decrease.title = 'Decrease by one step';
increase.title = 'Increase by one step';
decrease.setAttribute('aria-label', decrease.title);
increase.setAttribute('aria-label', increase.title);
slider.before(wrapper);
wrapper.append(decrease, slider, increase);
const step = direction => {
if (slider.disabled) return;
direction < 0 ? slider.stepDown() : slider.stepUp();
slider.dispatchEvent(new Event('input', { bubbles: true }));
slider.dispatchEvent(new Event('change', { bubbles: true }));
};
decrease.addEventListener('click', () => step(-1));
increase.addEventListener('click', () => step(1));
syncRangeStepper(slider);
}
// Create UI controls
function createControls() {
controlPanel = document.createElement('div');
controlPanel.id = 'controlPanel';
controlPanel.style.position = 'absolute';
controlPanel.style.top = '10px';
controlPanel.style.left = '10px';
controlPanel.style.width = 'min(290px, calc(100vw - 20px))';
controlPanel.style.boxSizing = 'border-box';
controlPanel.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
controlPanel.style.color = 'white';
controlPanel.style.padding = '10px';
controlPanel.style.borderRadius = '0';
controlPanel.style.fontFamily = 'Arial, sans-serif';
controlPanel.style.fontSize = '14px';
controlPanel.style.zIndex = '100';
controlPanel.style.maxHeight = 'calc(100vh - 20px)';
controlPanel.style.overflowY = 'auto';
// Create camera info display
cameraInfoDisplay = document.createElement('div');
cameraInfoDisplay.id = 'viewer-camera-info';
cameraInfoDisplay.style.marginBottom = '10px';
controlPanel.appendChild(cameraInfoDisplay);
// Create speed control
const speedContainer = document.createElement('div');
speedContainer.style.marginBottom = '10px';
motionStepLabel = document.createElement('label');
motionStepLabel.htmlFor = 'viewer-motion-step';
motionStepLabel.style.display = 'block';
motionStepLabel.textContent = `Motion Step: ${rotationSpeed.toFixed(3)} / frame`;
motionStepLabel.style.marginBottom = '5px';
speedContainer.appendChild(motionStepLabel);
motionStepSlider = document.createElement('input');
motionStepSlider.id = 'viewer-motion-step';
motionStepSlider.type = 'range';
motionStepSlider.min = '0';
motionStepSlider.max = '10';
motionStepSlider.step = '1';
motionStepSlider.value = rotationSpeed * 1000;
motionStepSlider.style.width = '100%';
motionStepSlider.addEventListener('input', function() {
rotationSpeed = this.value / 1000;
motionStepLabel.textContent = `Motion Step: ${rotationSpeed.toFixed(3)} / frame`;
refreshLoopTiming();
});
speedContainer.appendChild(motionStepSlider);
controlPanel.appendChild(speedContainer);
// Create vertex visibility toggle (moved above rotation controls)
const vertexToggle = document.createElement('div');
vertexToggle.style.marginBottom = '10px';
const vertexCheckbox = document.createElement('input');
vertexCheckbox.type = 'checkbox';
vertexCheckbox.id = 'vertexToggle';
vertexCheckbox.checked = showVertices;
vertexCheckbox.addEventListener('change', function() {
showVertices = this.checked;
vertices.forEach(vertex => {
vertex.visible = showVertices;
});
});
const vertexLabel = document.createElement('label');
vertexLabel.htmlFor = 'vertexToggle';
vertexLabel.textContent = 'Show Vertices';
vertexLabel.style.marginLeft = '5px';
vertexToggle.appendChild(vertexCheckbox);
vertexToggle.appendChild(vertexLabel);
controlPanel.appendChild(vertexToggle);
const grainToggle = document.createElement('div');
grainToggle.style.marginBottom = '10px';