-
Notifications
You must be signed in to change notification settings - Fork 49
/
index.js
1096 lines (985 loc) · 38.2 KB
/
index.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
var THREE = require('three');
var msgpack = require('msgpack-lite');
var dat = require('dat.gui').default; // TODO: why is .default needed?
import {BufferGeometryUtils} from 'three/examples/jsm/utils/BufferGeometryUtils.js';
import {OBJLoader2} from 'three/examples/jsm/loaders/OBJLoader2.js';
import {ColladaLoader} from 'three/examples/jsm/loaders/ColladaLoader.js';
import {MTLLoader} from 'three/examples/jsm/loaders/MTLLoader.js';
import {MtlObjBridge} from 'three/examples/jsm/loaders/obj2/bridge/MtlObjBridge.js';
import {STLLoader} from 'three/examples/jsm/loaders/STLLoader.js';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js';
require('ccapture.js');
// Merges a hierarchy of collada mesh geometries into a single
// `BufferGeometry` object:
// * A new merged `BufferGeometry` if the input contains meshes
// * empty `BufferGeometry` otherwise
function merge_geometries(object, preserve_materials = false) {
let materials = [];
let geometries = [];
let root_transform = object.matrix.clone();
function collectGeometries(node, parent_transform) {
let transform = parent_transform.clone().multiply(node.matrix);
if (node.type==='Mesh') {
node.geometry.applyMatrix(transform);
geometries.push(node.geometry);
materials.push(node.material);
}
for (let child of node.children) {
collectGeometries(child, transform);
}
}
collectGeometries(object, root_transform);
let result = null;
if (geometries.length == 1) {
result = geometries[0];
if (preserve_materials) {
result.material = materials[0];
}
} else if (geometries.length > 1) {
result = BufferGeometryUtils.mergeBufferGeometries(geometries, true);
if (preserve_materials) {
result.material = materials;
}
} else {
result = new THREE.BufferGeometry();
}
return result;
}
// Handler for special texture types that we want to support
// in addition to whatever three.js supports. This function
// takes a json object representing a single texture, and should
// return either:
// * A new `THREE.Texture` if that json represents a special texture
// * `null` otherwise
function handle_special_texture(json) {
if (json.type == "_text") {
let canvas = document.createElement('canvas');
// canvas width and height should be in the power of 2; otherwise although
// the page usually loads successfully, WebGL does complain/warn
canvas.width = 256;
canvas.height = 256;
let ctx = canvas.getContext('2d');
ctx.textAlign = "center";
let font_size = json.font_size;
// auto-resing the font_size to fit in the canvas
ctx.font = font_size + "px " + json.font_face;
while (ctx.measureText(json.text).width > canvas.width) {
font_size--;
ctx.font = font_size + "px " + json.font_face;
}
ctx.fillText(json.text, canvas.width / 2, canvas.height / 2);
let canvas_texture = new THREE.CanvasTexture(canvas);
canvas_texture.uuid = json.uuid;
return canvas_texture;
} else {
return null;
}
}
// Handler for special geometry types that we want to support
// in addition to whatever three.js supports. This function
// takes a json object representing a single geometry, and should
// return either:
// * A new `THREE.Mesh` if that json represents a special geometry
// * `null` otherwise
function handle_special_geometry(geom) {
if (geom.type == "_meshfile") {
console.warn("_meshfile is deprecated. Please use _meshfile_geometry for geometries and _meshfile_object for objects with geometry and material");
geom.type = "_meshfile_geometry";
}
if (geom.type == "_meshfile_geometry") {
if (geom.format == "obj") {
let loader = new OBJLoader2();
let obj = loader.parse(geom.data + "\n");
let loaded_geom = merge_geometries(obj);
loaded_geom.uuid = geom.uuid;
return loaded_geom;
} else if (geom.format == "dae") {
let loader = new ColladaLoader();
let obj = loader.parse(geom.data);
let result = merge_geometries(obj.scene);
result.uuid = geom.uuid;
return result;
} else if (geom.format == "stl") {
let loader = new STLLoader();
let loaded_geom = loader.parse(geom.data.buffer);
loaded_geom.uuid = geom.uuid;
return loaded_geom;
} else {
console.error("Unsupported mesh type:", geom);
return null;
}
}
return null;
}
// The ExtensibleObjectLoader extends the THREE.ObjectLoader
// interface, while providing some hooks for us to perform some
// custom loading for things other than three.js native JSON.
//
// We currently use this class to support some extensions to
// three.js JSON for objects which are easy to construct in
// javascript but hard to construct in Python and/or Julia.
// For example, we perform the following transformations:
//
// * Converting "_meshfile" geometries into actual meshes
// using the THREE.js native mesh loaders
// * Converting "_text" textures into text by drawing the
// requested text onto a canvas.
class ExtensibleObjectLoader extends THREE.ObjectLoader {
delegate(special_handler, base_handler, json, additional_objects) {
let result = {};
if (json === undefined) {
return result;
}
let remaining_json = [];
for (let data of json) {
let x = special_handler(data);
if (x !== null) {
result[x.uuid] = x;
} else {
remaining_json.push(data);
}
}
return Object.assign(result, base_handler(remaining_json, additional_objects));
}
parseTextures(json, images) {
return this.delegate(handle_special_texture,
super.parseTextures,
json, images);
}
parseGeometries(json, shapes) {
return this.delegate(handle_special_geometry,
super.parseGeometries,
json, shapes);
}
parseObject(json, geometries, materials) {
if (json.type == "_meshfile_object") {
let geometry;
let material;
let manager = new THREE.LoadingManager();
let path = ( json.url === undefined ) ? undefined : THREE.LoaderUtils.extractUrlBase( json.url );
manager.setURLModifier(url => {
if (json.resources[url] !== undefined) {
return json.resources[url];
}
return url;
});
if (json.format == "obj") {
let loader = new OBJLoader2(manager);
if (json.mtl_library) {
let mtl_loader = new MTLLoader(manager);
let mtl_parse_result = mtl_loader.parse(json.mtl_library + "\n", "");
console.log(mtl_parse_result);
let materials = MtlObjBridge.addMaterialsFromMtlLoader(mtl_parse_result);
console.log(materials);
loader.addMaterials(materials);
this.onTextureLoad();
}
let obj = loader.parse(json.data + "\n", path);
geometry = merge_geometries(obj, true);
geometry.uuid = json.uuid;
material = geometry.material;
} else if (json.format == "dae") {
let loader = new ColladaLoader(manager);
loader.onTextureLoad = this.onTextureLoad;
let obj = loader.parse(json.data, path);
geometry = merge_geometries(obj.scene, true);
geometry.uuid = json.uuid;
material = geometry.material;
} else if (json.format == "stl") {
let loader = new STLLoader();
geometry = loader.parse(json.data.buffer, path);
geometry.uuid = json.uuid;
material = geometry.material;
} else {
console.error("Unsupported mesh type:", json);
return null;
}
let object = new THREE.Mesh( geometry, material );
// Copied from ObjectLoader
object.uuid = json.uuid;
if ( json.name !== undefined ) object.name = json.name;
if ( json.matrix !== undefined ) {
object.matrix.fromArray( json.matrix );
if ( json.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = json.matrixAutoUpdate;
if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
} else {
if ( json.position !== undefined ) object.position.fromArray( json.position );
if ( json.rotation !== undefined ) object.rotation.fromArray( json.rotation );
if ( json.quaternion !== undefined ) object.quaternion.fromArray( json.quaternion );
if ( json.scale !== undefined ) object.scale.fromArray( json.scale );
}
if ( json.castShadow !== undefined ) object.castShadow = json.castShadow;
if ( json.receiveShadow !== undefined ) object.receiveShadow = json.receiveShadow;
if ( json.shadow ) {
if ( json.shadow.bias !== undefined ) object.shadow.bias = json.shadow.bias;
if ( json.shadow.radius !== undefined ) object.shadow.radius = json.shadow.radius;
if ( json.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( json.shadow.mapSize );
if ( json.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( json.shadow.camera );
}
if ( json.visible !== undefined ) object.visible = json.visible;
if ( json.frustumCulled !== undefined ) object.frustumCulled = json.frustumCulled;
if ( json.renderOrder !== undefined ) object.renderOrder = json.renderOrder;
if ( json.userjson !== undefined ) object.userjson = json.userData;
if ( json.layers !== undefined ) object.layers.mask = json.layers;
return object;
} else {
return super.parseObject(json, geometries, materials);
}
}
}
class SceneNode {
constructor(object, folder, on_update) {
this.object = object;
this.folder = folder;
this.children = {};
this.controllers = [];
this.on_update = on_update;
this.create_controls();
for (let c of this.object.children) {
this.add_child(c);
}
}
add_child(object) {
let f = this.folder.addFolder(object.name);
let node = new SceneNode(object, f, this.on_update);
this.children[object.name] = node;
return node;
}
create_child(name) {
let obj = new THREE.Group();
obj.name = name;
this.object.add(obj);
return this.add_child(obj);
}
find(path) {
if (path.length == 0) {
return this;
} else {
let name = path[0];
let child = this.children[name];
if (child === undefined) {
child = this.create_child(name);
}
return child.find(path.slice(1));
}
}
create_controls() {
for (let c of this.controllers) {
this.folder.remove(c);
}
if (this.vis_controller !== undefined) {
this.folder.domElement.removeChild(this.vis_controller.domElement);
}
this.vis_controller = new dat.controllers.BooleanController(this.object, "visible");
this.vis_controller.onChange(() => this.on_update());
this.folder.domElement.prepend(this.vis_controller.domElement);
this.vis_controller.domElement.style.height = "0";
this.vis_controller.domElement.style.float = "right";
this.vis_controller.domElement.classList.add("meshcat-visibility-checkbox");
this.vis_controller.domElement.children[0].addEventListener("change", (evt) => {
if (evt.target.checked) {
this.folder.domElement.classList.remove("meshcat-hidden-scene-element");
} else {
this.folder.domElement.classList.add("meshcat-hidden-scene-element");
}
});
if (this.object.isLight) {
let intensity_controller = this.folder.add(this.object, "intensity").min(0).step(0.01);
intensity_controller.onChange(() => this.on_update());
this.controllers.push(intensity_controller);
if (this.object.castShadow !== undefined){
let cast_shadow_controller = this.folder.add(this.object, "castShadow");
cast_shadow_controller.onChange(() => this.on_update());
this.controllers.push(cast_shadow_controller);
// Light source radius
let radius_controller = this.folder.add(this.object.shadow, "radius").min(0).step(0.05).max(3.0);
radius_controller.onChange(() => this.on_update());
this.controllers.push(radius_controller);
}
// Point light falloff distance
if (this.object.distance !== undefined){
let distance_controller = this.folder.add(this.object, "distance").min(0).step(0.1).max(100.0);
distance_controller.onChange(() => this.on_update());
this.controllers.push(distance_controller);
}
}
if (this.object.isCamera) {
let controller = this.folder.add(this.object, "zoom").min(0).step(0.1);
controller.onChange(() => {
// this.object.updateProjectionMatrix();
this.on_update()
});
this.controllers.push(controller);
}
}
set_property(property, value) {
if (property === "position") {
this.object.position.set(value[0], value[1], value[2]);
} else if (property === "quaternion") {
this.object.quaternion.set(value[0], value[1], value[2], value[3]);
} else if (property === "scale") {
this.object.scale.set(value[0], value[1], value[2]);
} else {
this.object[property] = value;
}
this.vis_controller.updateDisplay();
this.controllers.forEach(c => c.updateDisplay());
}
set_transform(matrix) {
let mat = new THREE.Matrix4();
mat.fromArray(matrix);
mat.decompose(this.object.position, this.object.quaternion, this.object.scale);
}
set_object(object) {
let parent = this.object.parent;
this.dispose_recursive();
this.object.parent.remove(this.object);
this.object = object;
parent.add(object);
this.create_controls();
}
dispose_recursive() {
for (let name of Object.keys(this.children)) {
this.children[name].dispose_recursive();
}
dispose(this.object);
}
delete(path) {
if (path.length == 0) {
console.error("Can't delete an empty path");
} else {
let parent = this.find(path.slice(0, path.length - 1));
let name = path[path.length - 1];
let child = parent.children[name];
if (child !== undefined) {
child.dispose_recursive();
parent.object.remove(child.object);
remove_folders(child.folder);
parent.folder.removeFolder(child.folder);
delete parent.children[name];
}
}
}
}
function remove_folders(gui) {
for (let name of Object.keys(gui.__folders)) {
let folder = gui.__folders[name];
remove_folders(folder);
dat.dom.dom.unbind(window, 'resize', folder.__resizeHandler);
gui.removeFolder(folder);
}
}
function dispose(object) {
if (!object) {
return;
}
if (object.geometry) {
object.geometry.dispose();
}
if (object.material) {
if (Array.isArray(object.material)) {
for (let material of object.material) {
if (material.map) {
material.map.dispose();
}
material.dispose();
}
} else {
if (object.material.map) {
object.material.map.dispose();
}
object.material.dispose();
}
}
}
function create_default_scene() {
var scene = new THREE.Scene();
scene.name = "Scene";
scene.rotateX(-Math.PI / 2);
return scene;
}
// https://stackoverflow.com/a/15832662
function download_data_uri(name, uri) {
let link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// https://stackoverflow.com/a/35251739
function download_file(name, contents, mime) {
mime = mime || "text/plain";
let blob = new Blob([contents], {
type: mime
});
let link = document.createElement("a");
document.body.appendChild(link);
link.download = name;
link.href = window.URL.createObjectURL(blob);
link.onclick = function(e) {
let scope = this;
setTimeout(function() {
window.URL.revokeObjectURL(scope.href);
}, 1500);
};
link.click();
link.remove();
}
class Animator {
constructor(viewer) {
this.viewer = viewer;
this.folder = this.viewer.gui.addFolder("Animations");
this.mixer = new THREE.AnimationMixer();
this.loader = new THREE.ObjectLoader();
this.clock = new THREE.Clock();
this.actions = [];
this.playing = false;
this.time = 0;
this.time_scrubber = null;
this.setup_capturer("png");
this.duration = 0;
}
setup_capturer(format) {
this.capturer = new CCapture({
format: format,
name: "meshcat_" + String(Date.now())
});
this.capturer.format = format;
}
play() {
this.clock.start();
// this.mixer.timeScale = 1;
for (let action of this.actions) {
action.play();
}
this.playing = true;
}
record() {
this.reset();
this.play();
this.recording = true;
this.capturer.start();
}
pause() {
// this.mixer.timeScale = 0;
this.clock.stop();
this.playing = false;
if (this.recording) {
this.stop_capture();
this.save_capture();
}
}
stop_capture() {
this.recording = false;
this.capturer.stop();
this.viewer.animate(); // restore the animation loop which gets disabled by capturer.stop()
}
save_capture() {
this.capturer.save();
if (this.capturer.format === "png") {
alert("To convert the still frames into a video, extract the `.tar` file and run: \nffmpeg -r 60 -i %07d.png \\\n\t -vcodec libx264 \\\n\t -preset slow \\\n\t -crf 18 \\\n\t output.mp4");
} else if (this.capturer.format === "jpg") {
alert("To convert the still frames into a video, extract the `.tar` file and run: \nffmpeg -r 60 -i %07d.jpg \\\n\t -vcodec libx264 \\\n\t -preset slow \\\n\t -crf 18 \\\n\t output.mp4");
}
}
display_progress(time) {
this.time = time;
if (this.time_scrubber !== null) {
this.time_scrubber.updateDisplay();
}
}
seek(time) {
this.actions.forEach((action) => {
action.time = Math.max(0, Math.min(action._clip.duration, time));
});
this.mixer.update(0);
this.viewer.set_dirty();
}
reset() {
for (let action of this.actions) {
action.reset();
}
this.display_progress(0);
this.mixer.update(0);
this.setup_capturer(this.capturer.format);
this.viewer.set_dirty();
}
clear() {
remove_folders(this.folder);
this.mixer.stopAllAction();
this.actions = [];
this.duration = 0;
this.display_progress(0);
this.mixer = new THREE.AnimationMixer();
}
load(animations, options) {
this.clear();
this.folder.open();
let folder = this.folder.addFolder("default");
folder.open();
folder.add(this, "play");
folder.add(this, "pause");
folder.add(this, "reset");
// Note, for some reason when you call `.max()` on a slider controller it does
// correctly change how the slider behaves but does not change the range of values
// that can be entered into the text box attached to the slider. Oh well. We work
// around this by creating the slider with an unreasonably huge range and then calling
// `.min()` and `.max()` on it later.
this.time_scrubber = folder.add(this, "time", 0, 1e9, 0.001);
this.time_scrubber.onChange((value) => this.seek(value));
folder.add(this.mixer, "timeScale").step(0.01).min(0);
let recording_folder = folder.addFolder("Recording");
recording_folder.add(this, "record");
recording_folder.add({format: "png"}, "format", ["png", "jpg"]).onChange(value => {
this.setup_capturer(value);
});
if (options.play === undefined) {
options.play = true
}
if (options.loopMode === undefined) {
options.loopMode = THREE.LoopRepeat
}
if (options.repetitions === undefined) {
options.repetitions = 1
}
if (options.clampWhenFinished === undefined) {
options.clampWhenFinished = true
}
this.duration = 0;
this.progress = 0;
for (let animation of animations) {
let target = this.viewer.scene_tree.find(animation.path).object;
let clip = this.loader.parseAnimations([animation.clip])[0];
let action = this.mixer.clipAction(clip, target);
action.clampWhenFinished = options.clampWhenFinished;
action.setLoop(options.loopMode, options.repetitions);
this.actions.push(action);
this.duration = Math.max(this.duration, clip.duration);
}
this.time_scrubber.min(0);
this.time_scrubber.max(this.duration);
this.reset();
if (options.play) {
this.play();
}
}
update() {
if (this.playing) {
this.mixer.update(this.clock.getDelta());
this.viewer.set_dirty();
if (this.duration != 0) {
let current_time = this.actions.reduce((acc, action) => {
return Math.max(acc, action.time);
}, 0);
this.display_progress(current_time);
} else {
this.display_progress(0);
}
if (this.actions.every((action) => action.paused)) {
this.pause();
for (let action of this.actions) {
action.reset();
}
}
}
}
after_render() {
if (this.recording) {
this.capturer.capture(this.viewer.renderer.domElement);
}
}
}
// Generates a gradient texture without filling up
// an entire canvas. We simply create a 2x1 image
// containing only the two colored pixels and then
// set up the appropriate magnification and wrapping
// modes to generate the gradient automatically
function gradient_texture(top_color, bottom_color) {
let colors = [bottom_color, top_color];
let width = 1;
let height = 2;
let size = width * height;
var data = new Uint8Array(3 * size);
for (let row = 0; row < height; row++) {
let color = colors[row];
for (let col = 0; col < width; col++) {
let i = 3 * (row * width + col);
for (let j = 0; j < 3; j++) {
data[i + j] = color[j];
}
}
}
var texture = new THREE.DataTexture(data, width, height, THREE.RGBFormat);
texture.magFilter = THREE.LinearFilter;
texture.encoding = THREE.LinearEncoding;
// By default, the points in our texture map to the center of
// the pixels, which means that the gradient only occupies
// the middle half of the screen. To get around that, we just have
// to tweak the UV transform matrix
texture.matrixAutoUpdate = false;
texture.matrix.set(0.5, 0, 0.25,
0, 0.5, 0.25,
0, 0, 1);
texture.needsUpdate = true
return texture;
}
class Viewer {
constructor(dom_element, animate) {
this.dom_element = dom_element;
this.renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
this.dom_element.appendChild(this.renderer.domElement);
this.scene = create_default_scene();
this.create_scene_tree();
this.add_default_scene_elements();
this.set_dirty();
this.create_camera();
// TODO: probably shouldn't be directly accessing window?
window.onload = (evt) => this.set_3d_pane_size();
window.addEventListener('resize', (evt) => this.set_3d_pane_size(), false);
requestAnimationFrame(() => this.set_3d_pane_size());
if (animate || animate === undefined) {
this.animate();
}
}
hide_background() {
this.scene.background = null;
this.set_dirty();
}
show_background() {
var top_color = this.scene_tree.find(["Background"]).object.top_color;
var bottom_color =
this.scene_tree.find(["Background"]).object.bottom_color;
this.scene.background = gradient_texture(top_color, bottom_color);
this.set_dirty();
}
set_dirty() {
this.needs_render = true;
}
create_camera() {
let mat = new THREE.Matrix4();
mat.makeRotationX(Math.PI / 2);
this.set_transform(["Cameras", "default", "rotated"], mat.toArray());
let camera = new THREE.PerspectiveCamera(75, 1, 0.01, 100)
this.set_camera(camera);
this.set_object(["Cameras", "default", "rotated"], camera)
camera.position.set(3, 1, 0);
}
create_default_spot_light() {
var spot_light = new THREE.SpotLight(0xffffff, 0.8);
spot_light.position.set(1.5, 1.5, 2);
// Make light not cast shadows by default (effectively
// disabling them, as there are no shadow-casting light
// sources in the default configuration). This is toggleable
// in the light options menu.
spot_light.castShadow = false;
spot_light.shadow.mapSize.width = 1024; // default 512
spot_light.shadow.mapSize.height = 1024; // default 512
spot_light.shadow.camera.near = 0.5; // default 0.5
spot_light.shadow.camera.far = 50.; // default 500
spot_light.shadow.bias = -0.001;
return spot_light;
}
add_default_scene_elements() {
var spot_light = this.create_default_spot_light();
this.set_object(["Lights", "SpotLight"], spot_light);
// By default, the spot light is turned off, since
// it's primarily used for casting detailed shadows
this.set_property(["Lights", "SpotLight"], "visible", false);
var point_light_px = new THREE.PointLight(0xffffff, 0.4);
point_light_px.position.set(1.5, 1.5, 2);
point_light_px.castShadow = false;
point_light_px.distance = 10.0;
point_light_px.shadow.mapSize.width = 1024; // default 512
point_light_px.shadow.mapSize.height = 1024; // default 512
point_light_px.shadow.camera.near = 0.5; // default 0.5
point_light_px.shadow.camera.far = 10.; // default 500
point_light_px.shadow.bias = -0.001; // Default 0
this.set_object(["Lights", "PointLightNegativeX"], point_light_px);
var point_light_nx = new THREE.PointLight(0xffffff, 0.4);
point_light_nx.position.set(-1.5, -1.5, 2);
point_light_nx.castShadow = false;
point_light_nx.distance = 10.0;
point_light_nx.shadow.mapSize.width = 1024; // default 512
point_light_nx.shadow.mapSize.height = 1024; // default 512
point_light_nx.shadow.camera.near = 0.5; // default 0.5
point_light_nx.shadow.camera.far = 10.; // default 500
point_light_nx.shadow.bias = -0.001; // Default 0
this.set_object(["Lights", "PointLightPositiveX"], point_light_nx);
var ambient_light = new THREE.AmbientLight(0xffffff, 0.3);
ambient_light.intensity = 0.6;
this.set_object(["Lights", "AmbientLight"], ambient_light);
var fill_light = new THREE.DirectionalLight(0xffffff, 0.4);
fill_light.position.set(-10, -10, 0);
this.set_object(["Lights", "FillLight"], fill_light);
var grid = new THREE.GridHelper(20, 40);
grid.rotateX(Math.PI / 2);
this.set_object(["Grid"], grid);
var axes = new THREE.AxesHelper(0.5);
// axes.visible = false;
this.set_object(["Axes"], axes);
}
create_scene_tree() {
if (this.gui) {
this.gui.destroy();
}
this.gui = new dat.GUI({
autoPlace: false
});
this.dom_element.parentElement.appendChild(this.gui.domElement);
this.gui.domElement.style.position = "absolute";
this.gui.domElement.style.right = 0;
this.gui.domElement.style.top = 0;
let scene_folder = this.gui.addFolder("Scene");
scene_folder.open();
this.scene_tree = new SceneNode(this.scene, scene_folder, () => this.set_dirty());
let save_folder = this.gui.addFolder("Save / Load / Capture");
save_folder.add(this, 'save_scene');
save_folder.add(this, 'load_scene');
save_folder.add(this, 'save_image');
this.animator = new Animator(this);
this.gui.close();
this.set_property(["Background"],
"top_color", [135, 206, 250]); // lightskyblue
this.set_property(["Background"],
"bottom_color", [25, 25, 112]); // midnightblue
this.scene_tree.find(["Background"]).on_update = () => {
if (this.scene_tree.find(["Background"]).object.visible)
this.show_background();
else
this.hide_background();
};
this.show_background();
}
set_3d_pane_size(w, h) {
if (w === undefined) {
w = this.dom_element.offsetWidth;
}
if (h === undefined) {
h = window.innerHeight;
}
if (this.camera.type == "OrthographicCamera") {
this.camera.right = this.camera.left + w*(this.camera.top - this.camera.bottom)/h;
} else {
this.camera.aspect = w / h;
}
this.camera.updateProjectionMatrix();
this.renderer.setSize(w, h);
this.set_dirty();
}
render() {
this.controls.update();
this.camera.updateProjectionMatrix();
this.renderer.render(this.scene, this.camera);
this.animator.after_render();
this.needs_render = false;
}
animate() {
requestAnimationFrame(() => this.animate());
this.animator.update();
if (this.needs_render) {
this.render();
}
}
capture_image() {
this.render();
return this.renderer.domElement.toDataURL();
}
save_image() {
download_data_uri("meshcat.png", this.capture_image());
}
set_camera(obj) {
this.camera = obj;
this.controls = new OrbitControls(obj, this.dom_element);
this.controls.enableKeys = false;
this.controls.screenSpacePanning = true; // see https://github.com/rdeits/MeshCat.jl/issues/132
this.controls.addEventListener('start', () => {
this.set_dirty()
});
this.controls.addEventListener('change', () => {
this.set_dirty()
});
}
set_camera_from_json(data) {
let loader = new ExtensibleObjectLoader();
loader.parse(data, (obj) => {
this.set_camera(obj);
});
}
set_transform(path, matrix) {
this.scene_tree.find(path).set_transform(matrix);
}
set_object(path, object) {
this.scene_tree.find(path.concat(["<object>"])).set_object(object);
}
set_object_from_json(path, object_json) {
let loader = new ExtensibleObjectLoader();
loader.onTextureLoad = () => {this.set_dirty();}
loader.parse(object_json, (obj) => {
if (obj.geometry !== undefined && obj.geometry.type == "BufferGeometry") {
if ((obj.geometry.attributes.normal === undefined) || obj.geometry.attributes.normal.count === 0) {
obj.geometry.computeVertexNormals();
}
} else if (obj.type.includes("Camera")) {
this.set_camera(obj);
this.set_3d_pane_size();
}
obj.castShadow = true;
obj.receiveShadow = true;
this.set_object(path, obj);
this.set_dirty();
});
}
delete_path(path) {
if (path.length == 0) {
console.error("Deleting the entire scene is not implemented")
} else {
this.scene_tree.delete(path);
}
}
set_property(path, property, value) {
this.scene_tree.find(path).set_property(property, value);
if (path[0] === "Background") {
// The background is not an Object3d, so needs a little help.
this.scene_tree.find(path).on_update();
}
// if (path[0] === "Cameras") {
// this.camera.updateProjectionMatrix();
// }
}
set_animation(animations, options) {
options = options || {};
this.animator.load(animations, options);
}
set_control(name, callback, value, min, max, step) {
let handler = {};
if (value !== undefined) {
handler[name] = value;
let controller = this.gui.add(handler, name, min, max, step);
controller.onChange(eval(callback));
} else {
handler[name] = eval(callback);
this.gui.add(handler, name);
}
}
handle_command(cmd) {
if (cmd.type == "set_transform") {
let path = split_path(cmd.path);
this.set_transform(path, cmd.matrix);
} else if (cmd.type == "delete") {
let path = split_path(cmd.path);
this.delete_path(path);
} else if (cmd.type == "set_object") {
let path = split_path(cmd.path);
this.set_object_from_json(path, cmd.object);
} else if (cmd.type == "set_property") {
let path = split_path(cmd.path);
this.set_property(path, cmd.property, cmd.value);
} else if (cmd.type == "set_animation") {
cmd.animations.forEach(animation => {
animation.path = split_path(animation.path);
});
this.set_animation(cmd.animations, cmd.options);
} else if (cmd.type == "set_control") {
this.set_control(cmd.name, cmd.callback, cmd.value, cmd.min, cmd.max, cmd.step);
} else if (cmd.type == "save_image") {
this.save_image()
}
this.set_dirty();
}
handle_command_bytearray(bytearray) {
let decoded = msgpack.decode(bytearray);
this.handle_command(decoded);
}
handle_command_message(message) {
this.handle_command_bytearray(new Uint8Array(message.data));