-
Notifications
You must be signed in to change notification settings - Fork 419
Expand file tree
/
Copy pathviewer.js
More file actions
1694 lines (1491 loc) · 60.7 KB
/
viewer.js
File metadata and controls
1694 lines (1491 loc) · 60.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright Contributors to the MaterialX Project
// SPDX-License-Identifier: Apache-2.0
//
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { HDRLoader } from 'three/examples/jsm/loaders/HDRLoader.js';
import { prepareEnvTexture, getLightRotation, findLights, registerLights, getUniformValues } from './helper.js'
import { Group } from 'three';
import GUI from 'lil-gui';
const ALL_GEOMETRY_SPECIFIER = "*";
const NO_GEOMETRY_SPECIFIER = "";
const DAG_PATH_SEPERATOR = "/";
// Logging toggle
var logDetailedTime = false;
/*
Scene management
*/
export class Scene
{
constructor()
{
this._geometryURL = new URLSearchParams(document.location.search).get("geom");
if (!this._geometryURL)
{
this._geometryURL = 'Geometry/shaderball.glb';
}
}
initialize()
{
this._scene = new THREE.Scene();
this._scene.background = new THREE.Color(this.#_backgroundColor);
const aspectRatio = window.innerWidth / window.innerHeight;
const cameraNearDist = 0.05;
const cameraFarDist = 100.0;
const cameraFOV = 60.0;
this._camera = new THREE.PerspectiveCamera(cameraFOV, aspectRatio, cameraNearDist, cameraFarDist);
this._frame = 0;
this.#_gltfLoader = new GLTFLoader();
this.#_normalMat = new THREE.Matrix3();
this.#_viewProjMat = new THREE.Matrix4();
this.#_worldViewPos = new THREE.Vector3();
}
// Set whether to flip UVs in V for loaded geometry
setFlipGeometryV(val)
{
this.#_flipV = val;
}
// Get whether to flip UVs in V for loaded geometry
getFlipGeometryV()
{
return this.#_flipV;
}
// Utility to perform geometry file load
loadGeometryFile(geometryFilename, loader)
{
return new Promise((resolve, reject) =>
{
loader.load(geometryFilename, data => resolve(data), null, reject);
});
}
//
// Load in geometry specified by a given file name,
// then update the scene geometry and camera.
//
async loadGeometry(viewer, orbitControls)
{
var startTime = performance.now();
var geomLoadTime = startTime;
const gltfData = await this.loadGeometryFile(this.getGeometryURL(), this.#_gltfLoader);
const scene = this.getScene();
while (scene.children.length > 0)
{
scene.remove(scene.children[0]);
}
this.#_rootNode = null;
let model = gltfData.scene;
if (!model)
{
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0xdddddd });
const cube = new THREE.Mesh(geometry, material);
model = new Group();
model.add(cube);
}
else
{
this.#_rootNode = model;
}
scene.add(model);
// Set up onBeforeRender callbacks so that we can update uniforms per object right before rendering.
model.traverse((child) =>
{
child.onBeforeRender = (_renderer, _scene, camera, _geometry, material, _group) =>
{
this.updateObjectUniforms(child, material, camera);
};
})
console.log("- Scene load time: ", performance.now() - geomLoadTime, "ms");
// Always reset controls based on camera for each load.
orbitControls.reset();
this.updateScene(viewer, orbitControls);
console.log("Total geometry load time: ", performance.now() - startTime, " ms.");
viewer.getMaterial().clearSoloMaterialUI();
viewer.getMaterial().updateMaterialAssignments(viewer, "");
}
//
// Update the geometry buffer, assigned materials, and camera controls.
//
updateScene(viewer, orbitControls)
{
var startUpdateSceneTime = performance.now();
var uvTime = 0;
var normalTime = 0;
var tangentTime = 0;
var streamTime = 0;
var bboxTime = 0;
var startBboxTime = performance.now();
const bbox = new THREE.Box3().setFromObject(this._scene);
const bsphere = new THREE.Sphere();
bbox.getBoundingSphere(bsphere);
bboxTime = performance.now() - startBboxTime;
let theScene = viewer.getScene();
let flipV = theScene.getFlipGeometryV();
this._scene.traverse((child) =>
{
if (child.isMesh)
{
var startUVTime = performance.now();
if (!child.geometry.attributes.uv)
{
const posCount = child.geometry.attributes.position.count;
const uvs = [];
const pos = child.geometry.attributes.position.array;
for (let i = 0; i < posCount; i++)
{
uvs.push((pos[i * 3] - bsphere.center.x) / bsphere.radius);
uvs.push((pos[i * 3 + 1] - bsphere.center.y) / bsphere.radius);
}
child.geometry.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(uvs), 2));
}
else if (flipV)
{
const uvCount = child.geometry.attributes.position.count;
const uvs = child.geometry.attributes.uv.array;
for (let i = 0; i < uvCount; i++)
{
let v = 1.0 - (uvs[i * 2 + 1]);
uvs[i * 2 + 1] = v;
}
}
uvTime += performance.now() - startUVTime;
if (!child.geometry.attributes.normal)
{
var startNormalTime = performance.now();
child.geometry.computeVertexNormals();
normalTime += performance.now() - startNormalTime;
}
if (child.geometry.getIndex())
{
if (!child.geometry.attributes.tangent)
{
var startTangentTime = performance.now();
child.geometry.computeTangents();
tangentTime += performance.now() - startTangentTime;
}
}
// Use default MaterialX naming convention.
var startStreamTime = performance.now();
child.geometry.attributes.i_position = child.geometry.attributes.position;
if (child.geometry.attributes.normal)
child.geometry.attributes.i_normal = child.geometry.attributes.normal;
if (child.geometry.attributes.tangent)
child.geometry.attributes.i_tangent = child.geometry.attributes.tangent;
if (child.geometry.attributes.color)
child.geometry.attributes.i_color_0 = child.geometry.attributes.color;
if (child.geometry.attributes.color_1)
child.geometry.attributes.i_color_1 = child.geometry.attributes.color_1;
if (child.geometry.attributes.uv)
child.geometry.attributes.i_texcoord_0 = child.geometry.attributes.uv;
if (child.geometry.attributes.uv1)
child.geometry.attributes.i_texcoord_1 = child.geometry.attributes.uv1;
if (child.geometry.attributes.uv2)
child.geometry.attributes.i_texcoord_2 = child.geometry.attributes.uv2;
streamTime += performance.now() - startStreamTime;
}
});
console.log("- Stream update time: ", performance.now() - startUpdateSceneTime, "ms");
if (logDetailedTime)
{
console.log(' - UV time: ', uvTime);
console.log(' - Normal time: ', normalTime);
console.log(' - Tangent time: ', tangentTime);
console.log(' - Stream Update time: ', streamTime);
console.log(' - Bounds compute time: ', bboxTime);
}
// Update the background
this._scene.background = this.getBackground();
// Fit camera to model
const camera = this.getCamera();
camera.position.y = bsphere.center.y;
camera.position.z = bsphere.radius * 2.0;
camera.updateProjectionMatrix();
orbitControls.target = bsphere.center;
orbitControls.update();
}
updateObjectUniforms(child, material, camera)
{
if (!child || !material || !camera) return;
const uniforms = material.uniforms;
if (!uniforms) return;
uniforms.u_worldMatrix.value = child.matrixWorld;
uniforms.u_viewProjectionMatrix.value = this.#_viewProjMat.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
if (uniforms.u_viewPosition)
uniforms.u_viewPosition.value = camera.getWorldPosition(this.#_worldViewPos);
if (uniforms.u_worldInverseTransposeMatrix)
uniforms.u_worldInverseTransposeMatrix.value =
new THREE.Matrix4().setFromMatrix3(this.#_normalMat.getNormalMatrix(child.matrixWorld));
material.uniformsNeedUpdate = true;
}
/**
* Update uniforms for all scene objects. This is called once per frame
* and updates time and frame count uniforms.
*/
updateTimeUniforms() {
this._frame++;
const scene = this.getScene();
const time = performance.now() / 1000.0;
const frame = this._frame;
scene.traverse((child) =>
{
if (child.isMesh && child.material && child.material.uniforms)
{
const uniforms = child.material.uniforms;
if (uniforms)
{
if (uniforms.u_time)
uniforms.u_time.value = time;
if (uniforms.u_frame)
uniforms.u_frame.value = frame;
}
}
});
}
// Determine string DAG path based on individual node names.
getDagPath(node)
{
const rootNode = this.#_rootNode;
let path = [node.userData?.name || node.name];
while (node.parent)
{
node = node.parent;
if (node)
{
// Stop at the root of the scene read in.
if (node == rootNode)
{
break;
}
path.unshift(node.userData?.name || node.name);
}
}
return path;
}
// Assign material shader to associated geometry
updateMaterial(matassign)
{
let assigned = 0;
const shader = matassign.getShader();
const material = matassign.getMaterial().getName();
const geometry = matassign.getGeometry();
const collection = matassign.getCollection();
const scene = this.getScene();
const camera = this.getCamera();
scene.traverse((child) =>
{
if (child.isMesh)
{
const dagPath = this.getDagPath(child).join('/');
// Note that this is a very simplistic
// assignment resolve and assumes basic
// regular expression name match.
let matches = (geometry == ALL_GEOMETRY_SPECIFIER);
if (!matches)
{
if (collection)
{
if (collection.matchesGeomString(dagPath))
{
matches = true;
}
}
else
{
if (geometry != NO_GEOMETRY_SPECIFIER)
{
const paths = geometry.split(',');
for (let path of paths)
{
if (dagPath.match(path))
{
matches = true;
break;
}
}
}
}
}
if (matches)
{
child.material = shader;
assigned++;
}
}
});
return assigned;
}
updateCamera()
{
const camera = this.getCamera();
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
}
getScene()
{
return this._scene;
}
getCamera()
{
return this._camera;
}
getGeometryURL()
{
return this._geometryURL;
}
setGeometryURL(url)
{
this._geometryURL = url;
}
setBackgroundTexture(texture)
{
this.#_backgroundTexture = texture;
}
getShowBackgroundTexture()
{
return this.#_showBackgroundTexture;
}
setShowBackgroundTexture(enable)
{
this.#_showBackgroundTexture = enable;
}
getBackground()
{
if (this.#_backgroundTexture && this.#_showBackgroundTexture)
{
return this.#_backgroundTexture;
}
var color = new THREE.Color(this.#_backgroundColor);
return color;
}
toggleBackgroundTexture()
{
this.#_showBackgroundTexture = !this.#_showBackgroundTexture;
this._scene.background = this.getBackground();
}
// Geometry file
#_geometryURL = '';
// Geometry loader
#_gltfLoader = null;
// Flip V coordinate of texture coordinates.
// Set to true to be consistent with desktop viewer.
#_flipV = true;
// Scene
#_scene = null;
// Camera
#_camera = null;
// Background color
#_backgroundColor = 0x4c4c52;
// Background texture
#_backgroundTexture = null;
#_showBackgroundTexture = true;
// Transform matrices
#_normalMat = new THREE.Matrix3();
#_viewProjMat = new THREE.Matrix4();
#_worldViewPos = new THREE.Vector3();
// Root node of imported scene
#_rootNode = null;
}
/*
Property editor
*/
export class Editor
{
// Initialize the editor, clearing any elements from previous materials.
initialize()
{
Array.from(document.getElementsByClassName('lil-gui')).forEach(
function (element, index, array)
{
if (element.className)
{
element.remove();
}
}
);
this._gui = new GUI({ title: "Property Editor" });
this._gui.close();
}
// Update ui properties
// - Hide close button
// - Update transparency so scene shows through if overlapping
updateProperties(targetOpacity = 1)
{
// Set opacity
Array.from(document.getElementsByClassName('dg')).forEach(
function (element, index, array)
{
element.style.opacity = targetOpacity;
}
);
}
getGUI()
{
return this._gui;
}
_gui = null;
}
class MaterialAssign
{
constructor(material, geometry, collection)
{
this._material = material;
this._geometry = geometry;
this._collection = collection;
this._shader = null;
this._materialUI = null;
}
setMaterialUI(value)
{
this._materialUI = value;
}
getMaterialUI()
{
return this._materialUI;
}
setShader(shader)
{
this._shader = shader;
}
getShader()
{
return this._shader;
}
getMaterial()
{
return this._material;
}
getGeometry()
{
return this._geometry;
}
setGeometry(value)
{
this._geometry = value;
}
getCollection()
{
return this._collection;
}
// MaterialX material node name
_material;
// MaterialX assignment geometry string
_geometry;
// MaterialX assignment collection
_collection;
// THREE.JS shader
_shader;
}
export class Material
{
constructor()
{
this._materials = [];
this._defaultMaterial = null;
this._soloMaterial = "";
}
clearMaterials()
{
this._materials.length = 0;
this._defaultMaterial = null;
this._soloMaterial = "";
}
setSoloMaterial(value)
{
this._soloMaterial = value;
}
getSoloMaterial()
{
return this._soloMaterial;
}
// If no material file is selected, we programmatically create a default material as a fallback
static createFallbackMaterial(doc)
{
let ssNode = doc.getChild('Generated_Default_Shader');
if (ssNode)
{
return ssNode;
}
const ssName = 'Generated_Default_Shader';
ssNode = doc.addChildOfCategory('standard_surface', ssName);
ssNode.setType('surfaceshader');
const smNode = doc.addChildOfCategory('surfacematerial', 'Default');
smNode.setType('material');
const shaderElement = smNode.addInput('surfaceshader');
shaderElement.setType('surfaceshader');
shaderElement.setNodeName(ssName);
return ssNode;
}
async loadMaterialFile(loader, materialFilename)
{
return new Promise((resolve, reject) =>
{
loader.load(materialFilename, data => resolve(data), null, reject);
});
}
async loadMaterials(viewer, materialFilename)
{
var startTime = performance.now();
const mx = viewer.getMx();
// Re-initialize document
var startDocTime = performance.now();
var doc = mx.createDocument();
doc.setDataLibrary(viewer.getLibrary());
viewer.setDocument(doc);
const fileloader = viewer.getFileLoader();
let mtlxMaterial = await viewer.getMaterial().loadMaterialFile(fileloader, materialFilename);
// Load lighting setup into document
doc.importLibrary(viewer.getLightRig());
console.log("- Material document load time: ", performance.now() - startDocTime, "ms.");
// Set search path. Assumes images are relative to current file
// location.
if (!materialFilename) materialFilename = "/";
const paths = materialFilename.split('/');
paths.pop();
const searchPath = paths.join('/');
// Load material
if (mtlxMaterial)
try {
await mx.readFromXmlString(doc, mtlxMaterial, searchPath);
}
catch (error) {
console.log('Error loading material file: ', error);
}
else
Material.createFallbackMaterial(doc);
// Check if there are any looks defined in the document
// If so then traverse the looks for all material assignments.
// Generate code and compile for any associated surface shader
// and assign to the associated geometry. If there are no looks
// then the first material is found and assignment to all the
// geometry.
this.clearMaterials();
var looks = doc.getLooks();
if (looks.length)
{
for (let look of looks)
{
const materialAssigns = look.getMaterialAssigns();
for (let materialAssign of materialAssigns)
{
let matName = materialAssign.getMaterial();
if (matName)
{
let mat = doc.getChild(matName);
var shader;
if (mat)
{
var shaders = mx.getShaderNodes(mat);
if (shaders.length)
{
shader = shaders[0];
}
}
let collection = materialAssign.getCollection();
let geom = materialAssign.getGeom();
let newAssignment;
if (collection || geom)
{
// Remove leading "/" from collection and geom for
// later assignment comparison checking
if (collection && collection.charAt(0) == "/")
{
collection = collection.slice(1);
}
if (geom && geom.charAt(0) == "/")
{
geom = geom.slice(1);
}
newAssignment = new MaterialAssign(shader, geom, collection);
}
else
{
newAssignment = new MaterialAssign(shader, NO_GEOMETRY_SPECIFIER, null);
}
if (newAssignment)
{
this._materials.push(newAssignment);
}
}
}
}
}
else
{
// Search for any surface shaders. The first found
// is assumed to be assigned to the entire scene
// The identifier used is "*" to mean the entire scene.
const materialNodes = doc.getMaterialNodes();
let shaderList = [];
let foundRenderable = false;
for (let i = 0; i < materialNodes.length; ++i)
{
let materialNode = materialNodes[i];
if (materialNode)
{
console.log('Scan material: ', materialNode.getNamePath());
let shaderNodes = mx.getShaderNodes(materialNode)
if (shaderNodes.length > 0)
{
let shaderNodePath = shaderNodes[0].getNamePath()
if (!shaderList.includes(shaderNodePath))
{
let assignment = NO_GEOMETRY_SPECIFIER;
if (foundRenderable == false)
{
assignment = ALL_GEOMETRY_SPECIFIER;
foundRenderable = true;
}
console.log('-- add shader: ', shaderNodePath);
shaderList.push(shaderNodePath);
this._materials.push(new MaterialAssign(shaderNodes[0], assignment));
}
}
}
}
const nodeGraphs = doc.getNodeGraphs();
for (let i = 0; i < nodeGraphs.length; ++i)
{
let nodeGraph = nodeGraphs[i];
if (nodeGraph)
{
if (nodeGraph.hasAttribute('nodedef') || nodeGraph.hasSourceUri())
{
continue;
}
// Skip any nodegraph that is connected to something downstream
if (nodeGraph.getDownstreamPorts().length > 0)
{
continue
}
let outputs = nodeGraph.getOutputs();
for (let j = 0; j < outputs.length; ++j)
{
let output = outputs[j];
{
let assignment = NO_GEOMETRY_SPECIFIER;
if (foundRenderable == false)
{
assignment = ALL_GEOMETRY_SPECIFIER;
foundRenderable = true;
}
let newMat = new MaterialAssign(output, assignment, null);
this._materials.push(newMat);
}
}
}
}
const outputs = doc.getOutputs();
for (let i = 0; i < outputs.length; ++i)
{
let output = outputs[i];
if (output)
{
let assignment = NO_GEOMETRY_SPECIFIER;
if (foundRenderable == false)
{
assignment = ALL_GEOMETRY_SPECIFIER;
foundRenderable = true;
}
this._materials.push(new MaterialAssign(output, assignment));
}
}
const shaderNodes = [];
for (let i = 0; i < shaderNodes.length; ++i)
{
let shaderNode = shaderNodes[i];
let shaderNodePath = shaderNode.getNamePath()
if (!shaderList.includes(shaderNodePath))
{
let assignment = NO_GEOMETRY_SPECIFIER;
if (foundRenderable == false)
{
assignment = ALL_GEOMETRY_SPECIFIER;
foundRenderable = true;
}
shaderList.push(shaderNodePath);
this._materials.push(new MaterialAssign(shaderNode, assignment));
}
}
}
// Assign to default material if none found
if (this._materials.length == 0)
{
const defaultNode = Material.createFallbackMaterial(doc);
this._materials.push(new MaterialAssign(defaultNode, ALL_GEOMETRY_SPECIFIER));
}
// Create a new shader for each material node.
// Only create the shader once even if assigned more than once.
var startGenTime = performance.now();
let shaderMap = new Map();
let closeUI = false;
for (let matassign of this._materials)
{
// Need to use path vs name to get a unique key.
let materialName = matassign.getMaterial().getNamePath();
let shader = shaderMap[materialName];
if (!shader)
{
shader = viewer.getMaterial().generateMaterial(matassign, viewer, searchPath, closeUI);
shaderMap[materialName] = shader;
}
matassign.setShader(shader);
closeUI = true;
}
console.log("- Generate (", this._materials.length, ") shader(s) time: ", performance.now() - startGenTime, " ms.",);
// Update scene shader assignments
this.updateMaterialAssignments(viewer, "");
console.log("Total material time: ", (performance.now() - startTime), "ms");
}
//
// Update the assignments for scene objects based on the
// material assignment information stored in the viewer.
// Note: If none of the MaterialX assignments match the geometry
// in the scene, then the first material assignment shader is assigned
// to the entire scene.
//
async updateMaterialAssignments(viewer, soloMaterial)
{
console.log("Update material assignments. Solo=", soloMaterial);
var startTime = performance.now();
let assigned = 0;
let assignedSolo = false;
for (let matassign of this._materials)
{
if (matassign.getShader())
{
if (soloMaterial.length)
{
if (matassign.getMaterial().getNamePath() == soloMaterial)
{
let temp = matassign.getGeometry();
matassign.setGeometry(ALL_GEOMETRY_SPECIFIER);
assigned += viewer.getScene().updateMaterial(matassign);
matassign.setGeometry(temp);
assignedSolo = true;
break;
}
}
else
{
assigned += viewer.getScene().updateMaterial(matassign);
}
}
}
if (assigned == 0 && this._materials.length)
{
this._defaultMaterial = new MaterialAssign(this._materials[0].getMaterial(), ALL_GEOMETRY_SPECIFIER);
this._defaultMaterial.setShader(this._materials[0].getShader());
viewer.getScene().updateMaterial(this._defaultMaterial);
}
if (assigned > 0)
{
console.log('Material assignment time: ', performance.now() - startTime, " ms.");
}
}
//
// Generate a new material for a given element
//
generateMaterial(matassign, viewer, searchPath, closeUI)
{
var elem = matassign.getMaterial();
var startGenerateMat = performance.now();
const mx = viewer.getMx();
const textureLoader = new THREE.TextureLoader();
const lights = viewer.getLights();
const lightData = viewer.getLightData();
const radianceTexture = viewer.getRadianceTexture();
const irradianceTexture = viewer.getIrradianceTexture();
const gen = viewer.getGenerator();
const genContext = viewer.getGenContext();
genContext.getOptions().hwSrgbEncodeOutput = true;
// Perform transparency check on renderable item
var startTranspCheckTime = performance.now();
const isTransparent = mx.isTransparentSurface(elem, gen.getTarget());
genContext.getOptions().hwTransparency = isTransparent;
// Always set to complete.
// Can consider option to set to reduced as the parsing of large numbers of uniforms (e.g. on shading models)
// can be quite expensive.
genContext.getOptions().shaderInterfaceType = mx.ShaderInterfaceType.SHADER_INTERFACE_COMPLETE;
if (logDetailedTime)
console.log(" - Transparency check time: ", performance.now() - startTranspCheckTime, "ms");
// Generate GLES code
var startMTLXGenTime = performance.now();
let shader = gen.generate(elem.getNamePath(), elem, genContext);
if (logDetailedTime)
console.log(" - MaterialX gen time: ", performance.now() - startMTLXGenTime, "ms");
var startUniformUpdate = performance.now();
// Get shaders and uniform values, removing version directives
// that are already managed by the Three.js runtime.
let vShader = shader.getSourceCode("vertex").replace(/^#version\s+.*\n/, '');
let fShader = shader.getSourceCode("pixel").replace(/^#version\s+.*\n/, '');
let theScene = viewer.getScene();
let flipV = theScene.getFlipGeometryV();
let uniforms = {
...getUniformValues(shader.getStage('vertex'), textureLoader, searchPath, flipV),
...getUniformValues(shader.getStage('pixel'), textureLoader, searchPath, flipV),
}
Object.assign(uniforms, {
u_numActiveLightSources: { value: lights.length },
u_lightData: { value: lightData },
u_envMatrix: { value: getLightRotation() },
u_envRadiance: { value: radianceTexture },
u_envRadianceMips: { value: Math.trunc(Math.log2(Math.max(radianceTexture.image.width, radianceTexture.image.height))) + 1 },
u_envRadianceSamples: { value: 16 },
u_envIrradiance: { value: irradianceTexture },
u_refractionEnv: { value: true }
});
// Create Three JS Material
let newMaterial = new THREE.RawShaderMaterial({
uniforms: uniforms,
vertexShader: vShader,
fragmentShader: fShader,
glslVersion: THREE.GLSL3,
transparent: isTransparent,
blendEquation: THREE.AddEquation,
blendSrc: THREE.OneMinusSrcAlphaFactor,
blendDst: THREE.SrcAlphaFactor,
side: THREE.DoubleSide,
name: elem.getName(),
});
if (logDetailedTime)
console.log(" - Three material update time: ", performance.now() - startUniformUpdate, "ms");
// Update property editor
const gui = viewer.getEditor().getGUI();
this.updateEditor(matassign, shader, newMaterial, gui, closeUI, viewer);
if (logDetailedTime)
console.log("- Per material generate time: ", performance.now() - startGenerateMat, "ms");
return newMaterial;
}
clearSoloMaterialUI()
{
for (let i = 0; i < this._materials.length; ++i)
{
let matassign = this._materials[i];
let matUI = matassign.getMaterialUI();
if (matUI)
{
let matTitle = matUI.domElement.getElementsByClassName('title')[0];
matTitle.classList.remove('peditor_material_assigned');
let img = matTitle.getElementsByTagName('img')[0];
img.src = 'public/shader_ball.svg';
}