-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimecube_slicer.js
1495 lines (1289 loc) · 60.1 KB
/
timecube_slicer.js
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
//to run in local server: go to Command Prompt,
//navigate to folder with this script, and type: `npx parcel index.html --public-url ./`
//Then, you can go to http://localhost:1234/ in your web browser to see it.
//You can also use `npm start` for an Electron app
import * as THREE from 'three';
import { PLYLoader } from 'three/examples/jsm/loaders/PLYLoader.js';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
//import { TransformControls } from 'three/examples/jsm/controls/TransformControls.js';
//import { MeshWboitMaterial, WboitPass } from 'three-wboit';
import * as dat from 'dat.gui';
import Stats from 'stats.js'; //check framerate
import Swal from 'sweetalert2';
//import custom code
import { createGrid, findNearestNeighbor } from './smaller_scripts/nearestNeighbor.js';
import * as tControls from './smaller_scripts/transformControls.js';
import { shuffleGeometry } from './smaller_scripts/geometryShuffler.js';
import * as depthSorter from './smaller_scripts/depthSorterSlow.js';
import * as planeDataExporter from './smaller_scripts/getPixelPointsFromPlane.js';
import { Renderer } from 'marked';
// import { listPlyFiles, createPlyFileDropdown } from './smaller_scripts/dropdownFromFolderItems.js';
//Declaring (most) global variables here
let defaultPlyFile = 'timecube_models/TINY man walking to bench.mp4.ply'; //replace with name of default .ply file to load
let url;
let file = defaultPlyFile;
let nameOfFile = file.replace('timecube_models/TINY ', '').replace('.mp4.ply', '');;
// List of predefined .ply files
var predefinedFiles = {
'Walking To Bench': 'timecube_models/TINY man walking to bench.mp4.ply', //doesn't yet have video
'Dancer At Night': 'timecube_models/Day-of-The-Dead Dance.mp4.ply', //has video
'Blinking Clown': 'timecube_models/TINY Clown blinking.mp4.ply', //has video
'Twirling Women': 'timecube_models/dancing_girls.mp4.ply', //has video
'Ring Around The Rosie': 'timecube_models/TINY INPUT ring around the rosie.mp4.ply', // has video
// ...add more here
};
// More variable declarations
let plane;
let planeIsMoving = true; //flag to indicate whether the plane has moved, begins as on
let isDragging = false; //Is anything currently being dragged?
let globalPlaneVisualizer;
let points;
let bbox;
let displayWidth = 100;
let displayWidthOriginal = displayWidth; //in order to reset display to original once we change it
let displayHeight = 100;
let displayHeightOriginal = displayHeight; //in order to reset display to original once we change it
let lowResWidth = displayWidth / 2;
let lowResHeight = displayHeight / 2;
let planeWidth = displayWidth;
let planeHeight = displayHeight;
let grid = {}; // Declare the grid variable outside the loader function
const cellSize = 2; // Set cellSize as a global variable
let bThreshold = { value: 0.5 }; // The brightness value should be between 0 (black) and 1 (white).
let cutoffController = null; // To enable or disable shader GUI options
let invertController = null;
let opacityController = null;
let RandomDepthSortController = null;
let canvas;
let ctx;
let material;
let basicMaterial; // different material types
let thresholdMaterial;
let translucentMaterial;
let randomSortMaterial;
let planeTexture;
let planeMaterial;
let animationPlaneStart;
let animationPlaneEnd;
let gammaPowerAmount;
let updateAfterMoving = false; //new flag
let forceRefreshDisplay = true;
let areArraysReady = false;
let debug = false; //set to true if you want to see fps counter, other dev help stuff.
let HideAllGUIs = false;
let dontShowLoading = false;
// Set up material variables here, so we can have fun messing with 'em :)
let uniforms = { // These are defaults for brightness threshold options
color: { value: new THREE.Color(0xffffff) }, // threshold color to check against
backColor: {value: new THREE.Color(0xffffff) }, // background color of scene
brightnessThreshold: { value: 0.5 }, // set `value: 0.5` for 50% threshhold
size: { value: 0.2 }, // this defines the size of the points in the point cloud
invertAlpha: { value: false }, // defines if translucency alpha channel is inverted or not
gammaCorrection: {value: 2.2 }, // defines gamma correction amount. Set to 1.0 to turn off
transparencyIntensity: { value: 1.0 } // 0 would make the object completely opaque; 1 (or greater) would make the object completely transparent
};
let optionOptions = {
openDialog: function() {
showDialog();
},
resetPlane: function() {
resetPlaneLocation();
},
}
// Event listener for key presses
document.addEventListener('keydown', function(event) {
// Cheat sheet for key presses:<br />"H" hide GUI
// "W" translate | "E" rotate | "R" scale | "+/-" adjust size<br />
// "Q" toggle world/local space | "Shift" snap to grid<br />
// "X" toggle X | "Y" toggle Y | "Z" toggle Z | "Spacebar" toggle enabled<br />
// "Esc" reset current transform<br />
// "C" toggle camera | "V" random zoom
// Check if the pressed key is 'h'
if (event.key === 'h') {
// Toggle the value of `HideAllGUIs`
HideAllGUIs = !HideAllGUIs;
toggleCanvasVisibility(!HideAllGUIs);
testCube.layers.toggle( 0 ); // hide/show red cube at center
planeWireframe.layers.toggle( 0 ); //hide/show plane wireframe
// Log the current state
console.log('GUIs hidden: ', HideAllGUIs);
}
//toggle debug mode if 'd' is pressed
if (event.key === 'd') {
debug = !debug;
onDebugToggle(debug);
console.log('Debug mode: ', debug);
}
// Update point sorting to face camera if 'u' is pressed
if (event.key === 'u') {
console.time('depthSortGeometry');
sortDistanceFromCamera();
console.timeEnd('depthSortGeometry');
console.log('transparency rendering order sorted from camera');
}
if (event.key === 'i') {
if (points) { //(points && camera.position.z < 0)
// Sort the geometry based on depth
console.time('2ndDepthSortGeometry');
const sortedGeometry = depthSorter.lossyDepthSortGeometry(points.geometry, camera);
console.timeEnd('2ndDepthSortGeometry');
// Update the points object with the sorted geometry
points.geometry = sortedGeometry;
grid = createGrid(points, cellSize);
}
console.log('(second version) transparency rendering order sorted from camera');
}
if (event.key === 'c') {
if (points) {
// Color the geometry based on depth
console.time('colorGeometry');
const coloredGeometry = depthSorter.colorByOrder(points.geometry, camera);
console.timeEnd('colorGeometry');
// Update the points object with the sorted geometry
points.geometry = coloredGeometry;
grid = createGrid(points, cellSize);
}
console.log('(second version) transparency rendering order sorted from camera');
}
//if 'j' is pressed, copy coordinates of plane edges to clipboard
if (event.key === 'j') {
// // Add visualizer for bounding box of TIMECUBE
// const boundingBoxVisualizer = new THREE.BoxHelper( points, 0xffff00 );
// scene.add( boundingBoxVisualizer );
// Get cooordinates of plane corners, and save past time this was called to memory
let corners = planeDataExporter.getPlaneCorners(plane, bbox);
if (animationPlaneEnd) {
animationPlaneStart = animationPlaneEnd;
}
animationPlaneEnd = corners;
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'Plane position saved as keyframe!',
showConfirmButton: false,
timer: 1500
})
// // Copy the text inside the text field
// navigator.clipboard.writeText(JSON.stringify(corners)).then(function(x) {
// alert("Coordinates of plane edges copied to clipboard");
// });
// Alert the info was copied
console.log('Plane corners location data: ' + JSON.stringify(corners));
}
});
// Function to let user download a file under a given name
function makeDownloadableFile(pathToFile, nameToCallFile) {
fetch(pathToFile)
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = nameToCallFile; // provide the file name you want
a.click(); // this will trigger the dialog window to save the file.
});
}
//function to allow for a more intuitive setTimeout
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// // Example usage:
// console.log("Hello");
// sleep(2000).then(() => { console.log("World!"); });
// Scene, Camera, Renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
console.log(renderer.capabilities.precision); // Get how high precision the scene is
//const renderer = new THREE.WebGLRenderer( { antialias : false } ); // For fps improvements if required
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Set camera position
camera.position.z = 5;
// Make window resizable!
window.addEventListener( 'resize', onWindowResize );
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
//transparency settings
renderer.setTransparentSort
// Orbit Controls for the scene as a whole
const orbitControls = new OrbitControls(camera, renderer.domElement);
function sortDistanceFromCamera(cameraObject) {
if (points) { //(points && camera.position.z < 0)
// Sort the geometry based on depth
const sortedGeometry = depthSorter.depthSortGeometry(points.geometry, camera);
// Update the points object with the sorted geometry
points.geometry = sortedGeometry;
grid = createGrid(points, cellSize);
}
}
// orbitControls.addEventListener('change', onCameraChange);
//create GUI
const gui = new dat.GUI();
// Create a style link element for GUI
const style = document.createElement('link');
// Set the link attributes
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = 'css/timecube_slicer.css'; // path to CSS stylesheet
// Append the stylesheet to the head of the document
document.head.appendChild(style);
//add GUI folders
const timecubeFolder = gui.addFolder('General Settings');
const planeFolder = gui.addFolder('Plane Controls');
const shaderFolder = gui.addFolder('Shader Controls');
// Make sure all main folders are open, subfolders closed
timecubeFolder.open();
planeFolder.open();
shaderFolder.open();
//instantiating fps counter if debugging mode is on
const fpsCounter = new Stats()
function onDebugToggle(debug) {
if (debug) {
fpsCounter.showPanel(0) // 0: fps, 1: ms, 2: mb, 3+: custom
document.body.appendChild(fpsCounter.dom);
//show clipping plane visualizer
globalPlaneVisualizer = new THREE.PlaneHelper(globalPlane, 100, 0xffff00);
scene.add(globalPlaneVisualizer);
} else {
// remove fps counter if it exists
if (document.body.contains(fpsCounter.dom)) {
document.body.removeChild(fpsCounter.dom);
}
//hide clipping plane visualizer
if (globalPlaneVisualizer) {
scene.remove(globalPlaneVisualizer);
globalPlaneVisualizer = false;
}
}
}
onDebugToggle(debug);
// Check if app is running in electron or not
let isElectron = false;
function electronChecker() {
try {
isElectron = !!window.navigator.userAgent.toLowerCase().includes('electron');
} catch(e) {
console.log('`isElectron` checker failed; error: ', e);
}
// Output result to console
if (isElectron) {
console.log("Running inside Electron!");
} else {
console.log("Not running inside Electron!");
}
}
electronChecker();
//function for lowering resolution while plane is being moved
function doWhileMoving() {
planeIsMoving = true;
displayWidth = lowResWidth;
displayHeight = lowResHeight;
updateAfterMoving = true;
displayColors = new Array(lowResHeight).fill(0).map(() => new Array(lowResWidth).fill([0, 0, 0, 0]));
updatePlane();
//makeNewOutline(planeGeometry);
}
// Add option to return to homepage
function showDialog() {
Swal.fire({
title: 'Return to homepage?',
showDenyButton: true,
confirmButtonText: 'Yes',
denyButtonText: `No`,
color: '#716add',
// background: '#fff url(images/treealgorithmic.png)',
}).then((result) => {
if (result.isConfirmed) {
window.location.href = 'index.html';
}
})
}
timecubeFolder.add(optionOptions, 'openDialog').name('Go Back');
// Add dropdown menu for pre-made timecube files
// Object with a property for the current selection
var selectedFile = {
file: 'Walking To Bench' // Default value
};
// Function to load a .ply file based on the current selection
function loadPredefinedFile() {
defaultPlyFile = predefinedFiles[selectedFile.file];
file = defaultPlyFile;
nameOfFile = file.replace('timecube_models/TINY ', '').replace('.mp4.ply', '');
selectedFile.file = Object.keys(predefinedFiles).find(key => predefinedFiles[key] === defaultPlyFile);
resetUserOptions(); //reset all user-defined settings
loadPly(defaultPlyFile);
}
// Add menu of loadable files to the GUI
timecubeFolder.add(selectedFile, 'file', Object.keys(predefinedFiles)).name('Load TIMECUBE').onChange(loadPredefinedFile);
// // Let user upload their own .ply timecube files
// function userPlyUploadOption() {
// // Set up file input event listener
// document.getElementById('plyFile').addEventListener('change', function(event) {
// const uploadedFile = event.target.files[0];
// file = uploadedFile;
// if (!uploadedFile) {
// console.log('No file selected!');
// return;
// }
// // This line creates a URL representing the File object
// url = URL.createObjectURL(file);
// defaultPlyFile = url;
// resetUserOptions(); //reset all user-defined settings
// // Ask the user for a name for the uploaded file
// Swal.fire({
// title: 'Enter a name for the uploaded file:',
// input: 'text',
// inputAttributes: {
// autocapitalize: 'off'
// },
// showCancelButton: true,
// confirmButtonText: 'Save',
// showLoaderOnConfirm: true,
// }).then((result) => {
// if (result.isConfirmed) {
// // Add the file to the predefinedFiles object
// predefinedFiles[result.value] = url;
// selectedFile.file = result.value;
// // Update the GUI
// timecubeFolder.__controllers.forEach(function(controller) {
// if (controller.property === 'file') {
// controller.remove();
// }
// });
// timecubeFolder.add(selectedFile, 'file', Object.keys(predefinedFiles)).name('Load TIMECUBE').onChange(loadPredefinedFile);
// // timecubeFolder.add(predefinedFiles[result.value], 'file', Object.keys(predefinedFiles)).name('Load TIMECUBE').onChange(loadPredefinedFile);
// }
// })
// // Now load the PLY from the generated URL
// loadPly(defaultPlyFile);
// });
// // Let user upload .ply file of their choice
// var params = {
// loadFile : function() {
// document.getElementById('plyFile').click();
// }
// };
// // Add .ply loader to GUI
// timecubeFolder.add(params, 'loadFile').name('Import TIMECUBE file');
// }
// // Call the function
// userPlyUploadOption();
// Let user upload video files, if environment is able to support it
function userVideoUploadOption() {
var videoUploadParams = {
loadFile : function() {
document.getElementById('vidFile').click();
// Start the Swal loading popup
setTimeout(function() {
Swal.fire({
title: 'Loading...\n(This may take a minute)',
allowEscapeKey: false,
allowOutsideClick: false,
didOpen: () => {
Swal.showLoading();
}
});
}, 500); // delay in milliseconds
return;
},
notAvailableAlert : function() {
Swal.fire({
title: 'Sorry, importing videos is not yet available on your computer.\nStay tuned for future compatibility updates!',
showDenyButton: false,
confirmButtonText: 'Okay',
color: '#716add',
// background: '#fff url(images/treealgorithmic.png)',
})
}
};
if (isElectron) { // If app is running in electron, let user upload video files
document.getElementById('vidFile').disabled = false;
// Run function which gets user's file, and load it in our scene
window.uploadNewVideoFile('vidFile', output_filename => {
if (output_filename.length > 0) {
console.log('output_filename: ' + output_filename);
// load PLY file created by our function, then close "loading" popup
dontShowLoading = true; // So we don't get two loading screens
file = output_filename.replace('./dist/', ''); // This is the path of the PLY file
nameOfFile = file.replace('timecube_models/TINY ', '').replace('.mp4.ply', '');
console.log('nameOfFile is: ' + nameOfFile + ', and file is: ' + file);
// This line creates a URL representing the File object
url = file; //URL.createObjectURL(file);
defaultPlyFile = url;
resetUserOptions(); //reset all user-defined settings
// Add the file to the predefinedFiles object
predefinedFiles[nameOfFile] = url;
selectedFile.file = nameOfFile;
// Update the GUI
timecubeFolder.__controllers.forEach(function(controller) {
if (controller.property === 'file') {
controller.remove();
}
});
timecubeFolder.add(selectedFile, 'file', Object.keys(predefinedFiles)).name('Load TIMECUBE').onChange(loadPredefinedFile);
loadPly(file).then((message) => {
console.log(message); // logs 'PLY file loaded' when the promise is resolved
Swal.close(); // Close the Swal loading popup
Swal.fire('Completed!', 'Your video file has been converted to TIMECUBE format', 'success');
dontShowLoading = false;
}).catch((error) => {
console.error('Failed to load PLY file', error);
Swal.close(); // Close the Swal loading popup
Swal.fire('Error', `An error occurred: ${error}`, 'error');
});
} else { // if output filepath string is blank, then we cancel, as some error happened
Swal.close(); // Close the Swal loading popup
Swal.fire('', `No valid filepath provided`);
}
});
// Add GUI button to run function
timecubeFolder.add(videoUploadParams, 'loadFile').name('Import Video');
} else { // If not running in electron, let user know option is disabled
timecubeFolder.add(videoUploadParams, 'notAvailableAlert').name('Import Video [Not Available]');
}
}
// Call the function
userVideoUploadOption();
// Let user export image of cross-section, if environment is able to support it
function userExportImage() {
var exportImageParams = {
startExport : function() {
document.getElementById('imgExport').click();
return;
},
notAvailableAlert : function() {
Swal.fire({
title: 'Sorry, exporting high-resolution images is not yet available on your computer.\nStay tuned for future compatibility updates!',
showDenyButton: false,
confirmButtonText: 'Okay',
color: '#716add',
// background: '#fff url(images/treealgorithmic.png)',
})
}
};
if (isElectron) { // If app is running in electron, let user upload video files
document.getElementById('imgExport').addEventListener('click', async () => {
// Start the Swal loading popup
Swal.fire({
title: 'Loading...\n(This may take a few seconds)',
allowEscapeKey: false,
allowOutsideClick: false,
didOpen: () => {
Swal.showLoading();
}
});
try {
// Get cooordinates of plane corners
let corners = planeDataExporter.getPlaneCorners(plane, bbox);
let pathOfOutputFile = '../' + 'cross_section_of_TIMECUBE.png';
let nameOfImageForUsers = 'TIMESLICED ' + nameOfFile + '.png';
// // Copy the text inside the text field
// navigator.clipboard.writeText(JSON.stringify(corners))
// let pointsArray = [[51.787123933939604, -1.2069462425104982, -7.17036082012239],[104.91694554306812, 21.7691466321827, 74.38618749385326],[54.622052382430184, 67.39184842565481, 9.830320134079496]];
let resolutionPercentage = [100, 100]; // percent (out of 100) resolution of image
// let video = './' + file.replace('.ply', '');
// let video = '../dist/timecube_models/' + nameOfFile + '.mp4';
let video = '../dist/' + file.replace('TINY ', '').replace('.ply', '');
console.log('video: ' + video + ' resolutionPercentage: ' + JSON.stringify(resolutionPercentage));
console.log('corner coordinates: ' + JSON.stringify(corners));
const scriptName = 'takeVideoCrossSection.py';
const args = ['ImageExport', video, JSON.stringify(corners), JSON.stringify(resolutionPercentage)];
window.runPythonScript(scriptName, args)
.then(result => {
console.log(result);
sleep(500) // wait so image can update
.then(() => Swal.close()) // Close the Swal loading popupSwal.close(); // Close the Swal loading popup
.then(() => Swal.fire({
// icon: 'success',
// title: 'TIMECUBE sliced!',
imageUrl: `${pathOfOutputFile}?${new Date().getTime()}`, //adds timestamp to avoid the image getting cached
imageAlt: 'cross section of TIMECUBE',
text: 'Save image?',
showCancelButton: true,
confirmButtonText: 'Save',
color: '#716add',
// background: '#fff url(images/treealgorithmic.png)',
}).then((result) => {
if (result.isConfirmed) {
makeDownloadableFile(pathOfOutputFile, nameOfImageForUsers);
}
}))
})
.catch(error => {
Swal.close(); // Close the Swal loading popup
Swal.fire('Error', `An error occurred: ${error}`, 'error');
});
} catch (error) {
console.error(`An error occurred: ${error}`);
Swal.close(); // Close the Swal loading popup
Swal.fire('Error', `An error occurred: ${error}`, 'error');
}
});
// Add GUI button to run function
timecubeFolder.add(exportImageParams, 'startExport').name('Export Image');
} else { // If not running in electron, let user know option is disabled
timecubeFolder.add(exportImageParams, 'notAvailableAlert').name('Export Image [Not Available]');
}
}
// Call the function
userExportImage();
// Let user export video of cross-section, if environment is able to support it
function userExportVideo() {
var exportVideoParams = {
startExport : function() {
document.getElementById('vidExport').click();
return;
},
notAvailableAlert : function() {
Swal.fire({
title: 'Sorry, exporting high-resolution video is not yet available on your computer.\nStay tuned for future compatibility updates!',
showDenyButton: false,
confirmButtonText: 'Okay',
color: '#716add',
// background: '#fff url(images/treealgorithmic.png)',
})
}
};
if (isElectron) { // If app is running in electron, let user upload video files
document.getElementById('vidExport').addEventListener('click', async () => {
// Start the Swal loading popup
Swal.fire({
title: 'Loading...\n(This may take a few minutes if your video resolution is high)',
allowEscapeKey: false,
allowOutsideClick: false,
didOpen: () => {
Swal.showLoading();
}
});
try {
// Get cooordinates of plane corners
let corners = planeDataExporter.getPlaneCorners(plane, bbox);
let pathOfOutputFile = '../' + 'cross_section_of_TIMECUBE.png';
let nameOfImageForUsers = 'TIMESLICED ' + nameOfFile + '.png';
// // Copy the text inside the text field
// navigator.clipboard.writeText(JSON.stringify(corners))
// let pointsArray = [[51.787123933939604, -1.2069462425104982, -7.17036082012239],[104.91694554306812, 21.7691466321827, 74.38618749385326],[54.622052382430184, 67.39184842565481, 9.830320134079496]];
let resolutionPercentage = [100, 100]; // percent (out of 100) resolution of image
// let video = './' + file.replace('.ply', '');
// let video = '../dist/timecube_models/' + nameOfFile + '.mp4';
let video = '../dist/' + file.replace('TINY ', '').replace('.ply', '');
console.log('video: ' + video + ' resolutionPercentage: ' + JSON.stringify(resolutionPercentage));
// console.log('corner coordinates: ' + JSON.stringify(corners));
const scriptName = 'takeVideoCrossSection.py';
const args = ['VideoExport', video, JSON.stringify(animationPlaneStart), JSON.stringify(resolutionPercentage), JSON.stringify(animationPlaneEnd)];
window.runPythonScript(scriptName, args)
.then(result => {
console.log(result);
sleep(500) // wait so image can update
.then(() => Swal.close()) // Close the Swal loading popupSwal.close(); // Close the Swal loading popup
.then(() => Swal.fire({
// icon: 'success',
// title: 'TIMECUBE sliced!',
imageUrl: `${pathOfOutputFile}?${new Date().getTime()}`, //adds timestamp to avoid the image getting cached
imageAlt: 'cross section of TIMECUBE',
text: 'Save image?',
showCancelButton: true,
confirmButtonText: 'Save',
color: '#716add',
// background: '#fff url(images/treealgorithmic.png)',
}).then((result) => {
if (result.isConfirmed) {
makeDownloadableFile(pathOfOutputFile, nameOfImageForUsers);
}
}))
})
.catch(error => {
Swal.close(); // Close the Swal loading popup
Swal.fire('Error', `An error occurred: ${error}`, 'error');
});
} catch (error) {
console.error(`An error occurred: ${error}`);
Swal.close(); // Close the Swal loading popup
Swal.fire('Error', `An error occurred: ${error}`, 'error');
}
});
// Add GUI button to run function
timecubeFolder.add(exportVideoParams, 'startExport').name('Export Video');
} else { // If not running in electron, let user know option is disabled
timecubeFolder.add(exportVideoParams, 'notAvailableAlert').name('Export Video [Not Available]');
}
}
// Call the function
userExportVideo();
// // Let user upload their own video files to be converted to timecube
// function userVidUploadOption() {
// // Set up file input event listener
// document.getElementById('vidFile').addEventListener('change', function(event) {
// const file = event.target.files[0];
// if (!file) {
// console.log('No file selected!');
// return;
// }
// // This line creates a URL representing the File object
// const url = URL.createObjectURL(file);
// // Now turn the video into a .ply file, and load it
// // Send the video to the serverless function
// sendFile(file);
// //loadPly(url);
// });
// // Let user upload .mp4 file of their choice
// var params = {
// loadFile : function() {
// document.getElementById('vidFile').click();
// }
// };
// // Add .ply loader to GUI
// timecubeFolder.add(params, 'loadFile').name('Upload Video');
// }
// // Call the function
// userVidUploadOption();
// //function for sending the file over to our Python script in Vercel
// function sendFile(file) {
// fetch('/api/convert', {
// method: 'POST',
// body: file
// })
// .then(response => response.blob())
// .then(blob => {
// // Create a URL for the blob
// const url = window.URL.createObjectURL(blob);
// // Call the loadPly function with the URL
// loadPly(url);
// if (points) {
// window.URL.revokeObjectURL(url);
// }
// });
// }
// Set background color
let backColor = {
backgroundColor: 'rgb(40, 40, 40)', //dark grey
planeBackgroundColor: 'rgba(0, 0, 0, 0)',
}
timecubeFolder.addColor( backColor, 'backgroundColor' ).name('Background').onChange(function(value) {
scene.background = new THREE.Color( backColor.backgroundColor )});;
scene.background = new THREE.Color( backColor.backgroundColor );
// Set plane background color if moved outside TIMECUBE
planeFolder.addColor(backColor, 'planeBackgroundColor').name('Plane Background');
// Log camera position and sort points by distance from camera (if required)
var lastMove = 0;
orbitControls.addEventListener( "change", event => {
// do nothing if last move was less than 1 second ago
if(Date.now() - lastMove > 1000) {
if (debug) {
console.log('camera position: ', orbitControls.object.position );
}
//onCameraChange();
lastMove = Date.now();
}
} )
//add red cube in center for debugging + troubleshooting
var testCubeGeometry = new THREE.BoxGeometry(1, 1, 1);
var testCubeMaterial = new THREE.MeshBasicMaterial({color: 0xff0000});
var testCube = new THREE.Mesh(testCubeGeometry, testCubeMaterial);
testCube.position.set(0, 0, 0);
scene.add(testCube);
// create a 2D array to store the color values for each pixel in the GUI display:
let displayColors = new Array(displayHeight).fill(0).map(() => new Array(displayWidth).fill([0, 0, 0, 0])); // Initialize to black
// Create a 2D canvas for the GUI
canvas = document.createElement('canvas');
canvas.width = displayWidth;
canvas.height = displayHeight;
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
//append the canvas to a <div> in the html instead of to the body
const canvasContainer = document.getElementById('canvasContainer');
canvasContainer.appendChild(canvas);
// Create a second canvas for buffering
let bufferCanvas = document.createElement('canvas');
bufferCanvas.width = displayWidth;
bufferCanvas.height = displayHeight;
let bufferCtx = bufferCanvas.getContext('2d');
// Function to toggle canvas and transform helper visibility
function toggleCanvasVisibility(isVisible) {
if (isVisible) {
canvas.style.display = 'block'; // Show the canvas
planeTransformControls.visible = true; //show transform helper for plane
} else {
canvas.style.display = 'none'; // Hide the canvas
planeTransformControls.visible = false; //hide transform helper for plane
}
}
// Create the texture here, after the canvas is created
planeTexture = new THREE.Texture(canvas);
planeTexture.format = THREE.RGBAFormat; //make sure alpha channel is being read correctly
planeTexture.type = THREE.UnsignedByteType;
planeTexture.minFilter = THREE.NearestFilter; // Disable minification filtering with THREE.NearestFilter
planeTexture.magFilter = THREE.NearestFilter; // Disable magnification filtering with THREE.NearestFilter
// Set up material setting for plane so it shows projection of the canvas
// (thereby showing the nearest neighbor pixels of point cloud).
//let planeMaterial = new THREE.MeshBasicMaterial({color: 'white', side: THREE.DoubleSide});
//const planeMaterial = new THREE.MeshBasicMaterial({ map: planeTexture, side: THREE.DoubleSide });
function definePlaneMaterial(planeTexture) {
//Modify plane material to correct gamma miscalibration problem and display the same thing canvas does
planeMaterial = new THREE.ShaderMaterial({
uniforms: {
map: { value: planeTexture },
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
precision mediump float; // Make floating point medium resolution
uniform sampler2D map;
varying vec2 vUv;
void main() {
vec4 texColor = texture2D(map, vUv);
vec3 color = texColor.rgb;
float alpha = texColor.a;
vec3 gamma = vec3(1.0 / 1.0);
vec3 correctedColor = pow(color, gamma);
gl_FragColor = vec4(correctedColor, alpha);
}
`,
depthTest: true,
side: THREE.DoubleSide,
transparent: true,
});
}
definePlaneMaterial(planeTexture);
//add intersecting plane to the scene
let planeGeometry = new THREE.PlaneGeometry(planeWidth, planeHeight); //width and height of plane
plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.name = 'plane';
// create infinite plane to use for clipping parallel to visible plane
let globalPlane = new THREE.Plane();
globalPlane.name = 'globalPlane';
//have plane be child of planeContainer (an invisible point in the center of world)
const planeContainer = new THREE.Object3D(); //this is what we are rotating around
planeContainer.name = 'planeContainer'
planeContainer.add(plane);
scene.add(planeContainer);
// Create wireframe outline of plane so it can be seen even if transparent
var lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 2 } );
var outlineGeometry = new THREE.EdgesGeometry( planeGeometry );
var planeWireframe = new THREE.LineSegments( outlineGeometry, lineMaterial );
planeWireframe.name = 'planeWireframe';
plane.add(planeWireframe);
// In-scene controller GUI for plane
let planeTransformControls = new tControls.TransformControls(camera, renderer.domElement);
planeTransformControls.name = 'plane transform controls';
// console.log(planeTransformControls);
planeTransformControls.attach(planeContainer);
planeTransformControls.setMode('combined');
planeTransformControls.setSpace('local');
//localtransformControls.worldPosition = new THREE.Vector3(3, 3, 3);; //localtransformControls.position
scene.add(planeTransformControls);
// Make sure the scene controls aren't activated when we change the local controls
planeTransformControls.addEventListener('dragging-changed', function (event) {
orbitControls.enabled = !event.value;
isDragging = event.value;
});
planeTransformControls.addEventListener('change', function() {
if (isDragging) {
doWhileMoving();
}
});
// Allow switching of transformation modes
window.addEventListener('keydown', function (event) {
switch (event.key) {
case 't':
planeTransformControls.setMode('translate');
break
case 'r':
planeTransformControls.setMode('rotate');
break
case 's':
planeTransformControls.setMode('scale');
break
case 'e':
planeTransformControls.setMode('combined');
break
}
})
// Call updatePlane() whenever you move or rotate the planeContainer
function updatePlane() {
// Obtain the world position of the plane
let worldPosition = new THREE.Vector3();
plane.getWorldPosition(worldPosition);
// Obtain the world "up" direction of the plane
let worldUp = new THREE.Vector3();
plane.getWorldDirection(worldUp);
// Update the globalPlane to match the position and orientation of the plane
globalPlane.setFromNormalAndCoplanarPoint(worldUp, worldPosition);
// // Update the position and quaternion of the Plane visualizer
if (debug) {
globalPlaneVisualizer.position.copy(worldPosition);
globalPlaneVisualizer.lookAt(worldPosition.clone().add(worldUp));
globalPlaneVisualizer.updateMatrixWorld(true); // force the update of world matrix
}
}
// Allow user to manipulate the location and visibility of the plane
function planeManipulation(){
const planeMoveFolder = planeFolder.addFolder('Location & Rotation');
//directions to manipulate plane in, and setting vars to check if user is moving the plane
planeMoveFolder.add(planeContainer.position, 'z', -100, 100).name('Plane Position').onChange(function() {doWhileMoving()}); //coordinates are how far to go in either direction
// Create objects to hold the user-friendly rotation values
let planeRotationHolder = {
rotationX: 0,
rotationY: 0,
rotationZ: 0,
};
function mapValue(value, start1, stop1, start2, stop2) {
return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
}
planeMoveFolder.add(planeRotationHolder, 'rotationX', -180, 180).name('Plane Rotation X').onChange(function(value) {
planeContainer.rotation.x = mapValue(value, -180, 180, -Math.PI, Math.PI);
doWhileMoving();
});
planeMoveFolder.add(planeRotationHolder, 'rotationY', -180, 180).name('Plane Rotation Y').onChange(function(value) {
planeContainer.rotation.y = mapValue(value, -180, 180, -Math.PI, Math.PI);
doWhileMoving();
});
planeMoveFolder.add(planeRotationHolder, 'rotationZ', -180, 180).name('Plane Rotation Z').onChange(function(value) {
planeContainer.rotation.z = mapValue(value, -180, 180, -Math.PI, Math.PI);
doWhileMoving();
});
//let player turn plane invisible (by default shown) by toggling which layer its on
let showPlane = { value: false };
planeFolder.add(showPlane, 'value').name('Hide Plane').onChange(function() {
plane.layers.toggle( 0 );
});
// planeFolder.open(); //have the folder start off with all options showing
}
planeManipulation();
// Add option to reset plane location/rotation
function resetPlaneLocation() {
let worldPosition = new THREE.Vector3();
let worldQuaternion = new THREE.Quaternion();