-
Notifications
You must be signed in to change notification settings - Fork 0
/
timecube_slicer - VR.js
1392 lines (1174 loc) · 52.8 KB
/
timecube_slicer - VR.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 { VRButton } from 'three/examples/jsm/webxr/VRButton.js'; //VR
import { XRControllerModelFactory } from 'three/examples/jsm/webxr/XRControllerModelFactory.js';
import { XRHandModelFactory } from 'three/examples/jsm/webxr/XRHandModelFactory.js';
import { InteractiveGroup } from 'three/examples/jsm/interactive/InteractiveGroup.js';
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';
import { HTMLMesh } from 'three/examples/jsm/interactive/HTMLMesh.js';
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/Operation_Nutmeg.ply'; //replace with name of default .ply file to load
// List of predefined .ply files
var predefinedFiles = {
'Operation Nutmeg' : 'timecube_models/Operation_Nutmeg.ply',
'Walking To A Bench': 'timecube_models/man walking to bench.ply',
'Blinking Clown': 'timecube_models/Clown blinking.ply',
'Dancing Ladies': 'timecube_models/dancing_girls.ply',
'Yitz Test' : 'timecube_models/Clown blinking Copy.yitz'
// ...add more here
};
// VR variables
let hand1, hand2;
let controller1, controller2;
let controllerGrip1, controllerGrip2;
// 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 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;
// 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
timecubeScale: { value: 1.0 }
};
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') {
const box = new THREE.BoxHelper( points, 0xffff00 );
scene.add( box );
let corners = planeDataExporter.getPlaneCorners(plane, bbox);
// 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(JSON.stringify(corners));
}
});
// 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();
renderer.xr.enabled = true; // For VR
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);
//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 A Bench' // Default value
};
// Function to load a .ply file based on the current selection
function loadPredefinedFile() {
defaultPlyFile = predefinedFiles[selectedFile.file];
resetUserOptions(); //reset all user-defined settings
loadPly(defaultPlyFile);
}
// Add the dropdown 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 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);
defaultPlyFile = url;
resetUserOptions(); //reset all user-defined settings
// 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 Custom TIMECUBE');
}
// Call the function
userPlyUploadOption();
// // 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
localtransformControls.visible = true; //show transform helper for plane
} else {
canvas.style.display = 'none'; // Hide the canvas
localtransformControls.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);
// create infinite plane to use for clipping parallel to visible plane
let globalPlane = new THREE.Plane();
//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.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 );
plane.add(planeWireframe);
// In-scene controller GUI for plane
let localtransformControls = new tControls.TransformControls(camera, renderer.domElement);
localtransformControls.attach(planeContainer);
localtransformControls.setMode('combined');
localtransformControls.setSpace('local');
//localtransformControls.worldPosition = new THREE.Vector3(3, 3, 3);; //localtransformControls.position
scene.add(localtransformControls);
// Make sure the scene controls aren't activated when we change the local controls
localtransformControls.addEventListener('dragging-changed', function (event) {
orbitControls.enabled = !event.value;
isDragging = event.value;
});
localtransformControls.addEventListener('change', function() {
if (isDragging) {
doWhileMoving();
}
});
// Allow switching of transformation modes
window.addEventListener('keydown', function (event) {
switch (event.key) {
case 't':
localtransformControls.setMode('translate');
break
case 'r':
localtransformControls.setMode('rotate');
break
case 's':
localtransformControls.setMode('scale');
break
case 'e':
localtransformControls.setMode('combined');
break
}
})
// Visualizer for clipping plane
// if (debug) {
// globalPlaneVisualizer = new THREE.PlaneHelper(globalPlane, 100, 0xffff00);
// scene.add(globalPlaneVisualizer);
// }
// 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(){
//directions to manipulate plane in, and setting vars to check if user is moving the plane
planeFolder.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));
}
planeFolder.add(planeRotationHolder, 'rotationX', -180, 180).name('Plane Rotation X').onChange(function(value) {
planeContainer.rotation.x = mapValue(value, -180, 180, -Math.PI, Math.PI);
doWhileMoving();
});
planeFolder.add(planeRotationHolder, 'rotationY', -180, 180).name('Plane Rotation Y').onChange(function(value) {
planeContainer.rotation.y = mapValue(value, -180, 180, -Math.PI, Math.PI);
doWhileMoving();
});
planeFolder.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();
let worldScale = new THREE.Vector3();
// desired absolute transformation
worldPosition.set(0, 0, 0);
worldQuaternion.setFromEuler(new THREE.Euler(0, 0, 0, 'XYZ'));
worldScale.set(1, 1, 1);
// inverse of the parent's world transformation
let parentWorldMatrix = new THREE.Matrix4();
if (plane.parent) {
parentWorldMatrix.copy(plane.parent.matrixWorld);
}
let inverseParentWorldMatrix = new THREE.Matrix4();
inverseParentWorldMatrix.copy(parentWorldMatrix).invert();
// apply the inverse parent world matrix to the desired world matrix
let matrix = new THREE.Matrix4();
matrix.compose(worldPosition, worldQuaternion, worldScale);
matrix.premultiply(inverseParentWorldMatrix);
// Apply the resulting matrix to the plane
plane.matrix.copy(matrix);
plane.matrix.decompose(plane.position, plane.quaternion, plane.scale);
plane.updateMatrixWorld(true); // update the world matrix
doWhileMoving();
console.log('plane reset');
}
planeFolder.add(optionOptions, 'resetPlane').name('Reset Plane');
// Set up different material properties
basicMaterial = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: `
uniform float size;
varying vec3 vColor;
#include <clipping_planes_pars_vertex> //clipping plane
void main() {
#include <begin_vertex> //clipping plane
#include <project_vertex> //clipping plane
#include <clipping_planes_vertex> //clipping plane
vColor = color; // Original code
vec4 mvPositionNew = modelViewMatrix * vec4( position, 1.0 );
gl_PointSize = size * ( 300.0 / -mvPositionNew.z );
gl_Position = projectionMatrix * mvPositionNew;
}
`,
fragmentShader: `
precision mediump float; // Make floating point medium resolution
uniform vec3 color;
uniform float gammaCorrection;
varying vec3 vColor;
#include <clipping_planes_pars_fragment> //clipping plane
void main() {
#include <clipping_planes_fragment> //clipping plane
vec3 gamma = vec3(1.0 / gammaCorrection);
vec3 correctedColor = pow(vColor, gamma);
gl_FragColor = vec4( correctedColor, 1.0 );
}
`,
transparent: false, // Basic material is opaque
depthTest: true, //set to true, as false will make the object render on top of everything else
depthWrite: true, // set to false for translucent objects
vertexColors: true, // ensures that the colors from geometry.attributes.color are used
blending: THREE.NoBlending, // Was THREE.NormalBlending for normal scene shading
clipping: true,
//clippingPlanes : [globalPlanes]
});
thresholdMaterial = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: `
uniform float size;
varying vec3 vColor;
#include <clipping_planes_pars_vertex> //clipping plane
void main() {
#include <begin_vertex> //clipping plane
#include <project_vertex> //clipping plane
#include <clipping_planes_vertex> //clipping plane
vColor = color;
vec4 mvPositionNew = modelViewMatrix * vec4( position, 1.0 );
gl_PointSize = size * ( 300.0 / -mvPositionNew.z );
gl_Position = projectionMatrix * mvPositionNew;
}
`,
fragmentShader: `
precision mediump float; // Make floating point medium resolution
uniform vec3 color;
uniform float gammaCorrection;
uniform float brightnessThreshold;
uniform int invertAlpha;
varying vec3 vColor;
#include <clipping_planes_pars_fragment> //clipping plane
void main() {
#include <clipping_planes_fragment> //clipping plane
vec3 gamma = vec3(1.0 / gammaCorrection);
vec3 correctedColor = pow(vColor, gamma);
float brightness = dot(correctedColor, vec3(0.299, 0.587, 0.114)); // calculate brightness
if (invertAlpha == 0) {
brightness = 1.0 - brightness;
}
if (brightness < brightnessThreshold) {
discard;
} else {
gl_FragColor = vec4( correctedColor, 1.0 );
}
}
`,
transparent: true,
depthTest: true, //set to true, as false will make the object render on top of everything else
depthWrite: true, // set to false for translucent objects
vertexColors: true, // ensures that the colors from geometry.attributes.color are used
blending: THREE.NormalBlending
});
translucentMaterial = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: `
uniform float size;
varying vec3 vColor;
#include <clipping_planes_pars_vertex> //clipping plane
void main() {
#include <begin_vertex> //clipping plane
#include <project_vertex> //clipping plane
#include <clipping_planes_vertex> //clipping plane
vColor = color;
vec4 mvPositionNew = modelViewMatrix * vec4( position, 1.0 );
gl_PointSize = size * ( 300.0 / -mvPositionNew.z );
gl_Position = projectionMatrix * mvPositionNew;
}
`,
fragmentShader: `
precision mediump float; // Make floating point medium resolution
uniform vec3 color;
uniform float gammaCorrection;
uniform float brightnessThreshold;
uniform int invertAlpha;
uniform float transparencyIntensity;
varying vec3 vColor;
#include <clipping_planes_pars_fragment> //clipping plane
void main() {
#include <clipping_planes_fragment> //clipping plane
vec3 gamma = vec3(1.0 / gammaCorrection);
vec3 correctedColor = pow(vColor, gamma);
float brightness = dot(correctedColor, vec3(0.299, 0.587, 0.114));
float alpha = brightness * transparencyIntensity; // Modified alpha calculation
if (invertAlpha == 0) {
alpha = 1.0 - alpha;
}
gl_FragColor = vec4( correctedColor, alpha );
//// Reverse depth value
//gl_FragDepth = 1.0 - gl_FragCoord.z;
}
`,
transparent: true,
depthTest: true, // enable depth testing
depthWrite: false, // disable depth writing
vertexColors: true,
blending: THREE.NormalBlending,
// blending: THREE.CustomBlending,
// blendEquation: THREE.AddEquation,
// blendSrc: THREE.SrcAlphaFactor,
// blendDst: THREE.OneMinusSrcAlphaFactor,
});
// let VRBasicMaterial = new THREE.ShaderMaterial({
// uniforms: uniforms,
// vertexShader: `
// uniform float size;
// varying vec3 vColor;
// // #include <clipping_planes_pars_vertex> //clipping plane
// void main() {
// // #include <begin_vertex> //clipping plane
// // #include <project_vertex> //clipping plane
// // #include <clipping_planes_vertex> //clipping plane
// vColor = color; // Original code
// vec4 mvPositionNew = modelViewMatrix * vec4( position, 1.0 );
// gl_PointSize = size * ( 300.0 / -mvPositionNew.z );
// gl_Position = projectionMatrix * mvPositionNew;
// }
// `,
// fragmentShader: `
// precision mediump float; // Make floating point medium resolution
// uniform vec3 color;
// uniform float gammaCorrection;
// varying vec3 vColor;
// // #include <clipping_planes_pars_fragment> //clipping plane
// void main() {
// // #include <clipping_planes_fragment> //clipping plane
// vec3 gamma = vec3(1.0 / gammaCorrection);
// vec3 correctedColor = pow(vColor, gamma);
// gl_FragColor = vec4( correctedColor, 1.0 );
// }
// `,
// transparent: false, // Basic material is opaque
// depthTest: true, //set to true, as false will make the object render on top of everything else
// depthWrite: true, // set to false for translucent objects
// vertexColors: true, // ensures that the colors from geometry.attributes.color are used
// blending: THREE.NoBlending, // Was THREE.NormalBlending for normal scene shading
// clipping: true,
// //clippingPlanes : [globalPlanes]
// });
//to test the minimal requirements for problems to happen with oculus Browser rendering
let VRMinimalTestMaterial = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: `
uniform float size;
varying vec3 vColor;
// #include <clipping_planes_pars_vertex> //clipping plane
void main() {
// #include <begin_vertex> //clipping plane
// #include <project_vertex> //clipping plane
// #include <clipping_planes_vertex> //clipping plane
vColor = color; // Original code
vec4 mvPositionNew = modelViewMatrix * vec4( position, 1.0 );
gl_PointSize = size * ( 300.0 / -mvPositionNew.z );
gl_Position = projectionMatrix * mvPositionNew;
}
`,
fragmentShader: `
precision mediump float; // Make floating point medium resolution
uniform vec3 color;
uniform float gammaCorrection;
varying vec3 vColor;
// #include <clipping_planes_pars_fragment> //clipping plane
void main() {
// #include <clipping_planes_fragment> //clipping plane
vec3 gamma = vec3(1.0 / gammaCorrection);
vec3 correctedColor = pow(vColor, gamma);
gl_FragColor = vec4( correctedColor, 1.0 );
}
`,
transparent: false, // Basic material is opaque
depthTest: true, //set to true, as false will make the object render on top of everything else
depthWrite: true, // set to false for translucent objects
vertexColors: true, // ensures that the colors from geometry.attributes.color are used
blending: THREE.NoBlending, // Was THREE.NormalBlending for normal scene shading
// clipping: true,
//clippingPlanes : [globalPlanes]
});
//current VR-friendly material to use
let VRBasicMaterial = new THREE.PointsMaterial();
VRBasicMaterial.vertexColors = true;
VRBasicMaterial.size = uniforms.size.value;
// Initialize material, should be basicMaterial normally
material = VRBasicMaterial;
function VRStuff() {
// Scale scene down if in VR
if(renderer.xr.isPresenting){
scene.scale.set( 0.1, 0.1, 0.1 );
uniforms.size.value = 0.1;
console.log("in VR Mode!");
}
// scene.scale.set( uniforms.size.value, uniforms.size.value, uniforms.size.value );
// uniforms.size.value = 0.1;
// console.log("in VR Mode!");
// controllers
controller1 = renderer.xr.getController( 0 );
scene.add( controller1 );
controller2 = renderer.xr.getController( 1 );
scene.add( controller2 );
const controllerModelFactory = new XRControllerModelFactory();
const handModelFactory = new XRHandModelFactory();
// Hand 1
controllerGrip1 = renderer.xr.getControllerGrip( 0 );
controllerGrip1.add( controllerModelFactory.createControllerModel( controllerGrip1 ) );
scene.add( controllerGrip1 );
hand1 = renderer.xr.getHand( 0 );
hand1.add( handModelFactory.createHandModel( hand1 ) );
scene.add( hand1 );
// Hand 2
controllerGrip2 = renderer.xr.getControllerGrip( 1 );
controllerGrip2.add( controllerModelFactory.createControllerModel( controllerGrip2 ) );
scene.add( controllerGrip2 );
hand2 = renderer.xr.getHand( 1 );
hand2.add( handModelFactory.createHandModel( hand2 ) );
scene.add( hand2 );
// Show hands in 3D
const geometry = new THREE.BufferGeometry().setFromPoints( [ new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, - 1 ) ] );
const line = new THREE.Line( geometry, new THREE.MeshBasicMaterial({color: 0xff0000}) );
line.name = 'line';
line.scale.z = 5;
controller1.add( line.clone() );
controller2.add( line.clone() );
//
// GUI
function onChange() {
// Add code here to do on GUIVR change
}
function onThicknessChange() {
//add code here
}
// 3D embedded dat.gui object
const guiVR = new GUI( { width: 300 } );
// Shader GUIVR options
guiVR.add(uniforms.size, 'value', 0, 2).name('Voxel Size').onChange(function(value) {
VRBasicMaterial.size = uniforms.size.value;
}); // Add size option to GUI
guiVR.add(uniforms.timecubeScale, 'value', 0.01, 1).name('Scale TIMECUBE').onChange(function(value) {
points.scale.set(uniforms.timecubeScale.value, uniforms.timecubeScale.value, uniforms.timecubeScale.value);
}); // Add size option to GUI
// guiVR.add(uniforms.timecubeScale, 'value', 0.1, 10).name('TIMECUBE Scaling').onChange(function(value) {
// points.geometry.scale(uniforms.size.value, uniforms.size.value, uniforms.size.value);
// }); // change TIMECUBE object scaling amount
// guiVR.add( parameters, 'radius', 0.0, 1.0 ).onChange( onChange );
// guiVR.add( parameters, 'tube', 0.0, 1.0 ).onChange( onChange );
// guiVR.add( parameters, 'tubularSegments', 10, 150, 1 ).onChange( onChange );
// guiVR.add( parameters, 'radialSegments', 2, 20, 1 ).onChange( onChange );