@combeenation/3d-viewer 7.1.1 → 7.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +111 -111
  2. package/dist/lib-cjs/api/classes/animationInterface.d.ts +8 -8
  3. package/dist/lib-cjs/api/classes/animationInterface.js +2 -2
  4. package/dist/lib-cjs/api/classes/dottedPath.d.ts +79 -79
  5. package/dist/lib-cjs/api/classes/dottedPath.js +166 -166
  6. package/dist/lib-cjs/api/classes/element.d.ts +153 -153
  7. package/dist/lib-cjs/api/classes/element.js +672 -670
  8. package/dist/lib-cjs/api/classes/element.js.map +1 -1
  9. package/dist/lib-cjs/api/classes/event.d.ts +401 -396
  10. package/dist/lib-cjs/api/classes/event.js +424 -419
  11. package/dist/lib-cjs/api/classes/event.js.map +1 -1
  12. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  13. package/dist/lib-cjs/api/classes/eventBroadcaster.js +49 -49
  14. package/dist/lib-cjs/api/classes/fuzzyMap.d.ts +7 -7
  15. package/dist/lib-cjs/api/classes/fuzzyMap.js +21 -21
  16. package/dist/lib-cjs/api/classes/parameter.d.ts +351 -351
  17. package/dist/lib-cjs/api/classes/parameter.js +524 -517
  18. package/dist/lib-cjs/api/classes/parameter.js.map +1 -1
  19. package/dist/lib-cjs/api/classes/parameterObservable.d.ts +36 -36
  20. package/dist/lib-cjs/api/classes/parameterObservable.js +72 -72
  21. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  22. package/dist/lib-cjs/api/classes/parameterizable.js +102 -102
  23. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +45 -45
  24. package/dist/lib-cjs/api/classes/placementAnimation.js +176 -176
  25. package/dist/lib-cjs/api/classes/variant.d.ts +253 -253
  26. package/dist/lib-cjs/api/classes/variant.js +858 -843
  27. package/dist/lib-cjs/api/classes/variant.js.map +1 -1
  28. package/dist/lib-cjs/api/classes/variantInstance.d.ts +53 -53
  29. package/dist/lib-cjs/api/classes/variantInstance.js +125 -125
  30. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  31. package/dist/lib-cjs/api/classes/variantParameterizable.js +86 -88
  32. package/dist/lib-cjs/api/classes/variantParameterizable.js.map +1 -1
  33. package/dist/lib-cjs/api/classes/viewer.d.ts +204 -200
  34. package/dist/lib-cjs/api/classes/viewer.js +682 -670
  35. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  36. package/dist/lib-cjs/api/classes/viewerError.d.ts +43 -0
  37. package/dist/lib-cjs/api/classes/viewerError.js +56 -0
  38. package/dist/lib-cjs/api/classes/viewerError.js.map +1 -0
  39. package/dist/lib-cjs/api/classes/viewerLight.d.ts +66 -66
  40. package/dist/lib-cjs/api/classes/viewerLight.js +348 -348
  41. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  42. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  43. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +13 -13
  44. package/dist/lib-cjs/api/internal/sceneSetup.js +226 -226
  45. package/dist/lib-cjs/api/manager/animationManager.d.ts +30 -30
  46. package/dist/lib-cjs/api/manager/animationManager.js +126 -126
  47. package/dist/lib-cjs/api/manager/gltfExportManager.d.ts +79 -79
  48. package/dist/lib-cjs/api/manager/gltfExportManager.js +242 -242
  49. package/dist/lib-cjs/api/manager/sceneManager.d.ts +33 -33
  50. package/dist/lib-cjs/api/manager/sceneManager.js +128 -130
  51. package/dist/lib-cjs/api/manager/sceneManager.js.map +1 -1
  52. package/dist/lib-cjs/api/manager/tagManager.d.ts +116 -109
  53. package/dist/lib-cjs/api/manager/tagManager.js +444 -425
  54. package/dist/lib-cjs/api/manager/tagManager.js.map +1 -1
  55. package/dist/lib-cjs/api/manager/textureLoadManager.d.ts +22 -22
  56. package/dist/lib-cjs/api/manager/textureLoadManager.js +97 -97
  57. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +106 -106
  58. package/dist/lib-cjs/api/manager/variantInstanceManager.js +292 -292
  59. package/dist/lib-cjs/api/store/specStorage.d.ts +32 -32
  60. package/dist/lib-cjs/api/store/specStorage.js +65 -65
  61. package/dist/lib-cjs/api/util/babylonHelper.d.ts +235 -235
  62. package/dist/lib-cjs/api/util/babylonHelper.js +753 -753
  63. package/dist/lib-cjs/api/util/globalTypes.d.ts +441 -437
  64. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  65. package/dist/lib-cjs/api/util/resourceHelper.d.ts +58 -58
  66. package/dist/lib-cjs/api/util/resourceHelper.js +203 -203
  67. package/dist/lib-cjs/api/util/sceneLoaderHelper.d.ts +44 -44
  68. package/dist/lib-cjs/api/util/sceneLoaderHelper.js +175 -175
  69. package/dist/lib-cjs/api/util/stringHelper.d.ts +13 -13
  70. package/dist/lib-cjs/api/util/stringHelper.js +32 -32
  71. package/dist/lib-cjs/api/util/structureHelper.d.ts +9 -9
  72. package/dist/lib-cjs/api/util/structureHelper.js +57 -48
  73. package/dist/lib-cjs/api/util/structureHelper.js.map +1 -1
  74. package/dist/lib-cjs/buildinfo.json +3 -3
  75. package/dist/lib-cjs/commonjs.tsconfig.tsbuildinfo +1 -1
  76. package/dist/lib-cjs/index.d.ts +54 -53
  77. package/dist/lib-cjs/index.js +117 -114
  78. package/dist/lib-cjs/index.js.map +1 -1
  79. package/package.json +81 -81
  80. package/src/api/classes/animationInterface.ts +10 -10
  81. package/src/api/classes/dottedPath.ts +181 -181
  82. package/src/api/classes/element.ts +733 -731
  83. package/src/api/classes/event.ts +457 -452
  84. package/src/api/classes/eventBroadcaster.ts +52 -52
  85. package/src/api/classes/fuzzyMap.ts +21 -21
  86. package/src/api/classes/parameter.ts +561 -554
  87. package/src/api/classes/parameterObservable.ts +73 -73
  88. package/src/api/classes/parameterizable.ts +87 -87
  89. package/src/api/classes/placementAnimation.ts +162 -162
  90. package/src/api/classes/variant.ts +949 -933
  91. package/src/api/classes/variantInstance.ts +123 -123
  92. package/src/api/classes/variantParameterizable.ts +83 -85
  93. package/src/api/classes/viewer.ts +760 -744
  94. package/src/api/classes/viewerError.ts +63 -0
  95. package/src/api/classes/viewerLight.ts +339 -339
  96. package/src/api/internal/debugViewer.ts +90 -90
  97. package/src/api/internal/lensRendering.ts +9 -9
  98. package/src/api/internal/sceneSetup.ts +205 -205
  99. package/src/api/manager/animationManager.ts +143 -143
  100. package/src/api/manager/gltfExportManager.ts +237 -237
  101. package/src/api/manager/sceneManager.ts +134 -136
  102. package/src/api/manager/tagManager.ts +477 -457
  103. package/src/api/manager/textureLoadManager.ts +95 -95
  104. package/src/api/manager/variantInstanceManager.ts +309 -309
  105. package/src/api/store/specStorage.ts +68 -68
  106. package/src/api/util/babylonHelper.ts +823 -823
  107. package/src/api/util/globalTypes.ts +508 -504
  108. package/src/api/util/resourceHelper.ts +191 -191
  109. package/src/api/util/sceneLoaderHelper.ts +170 -170
  110. package/src/api/util/stringHelper.ts +30 -30
  111. package/src/api/util/structureHelper.ts +58 -49
  112. package/src/buildinfo.json +3 -3
  113. package/src/dev.ts +62 -62
  114. package/src/index.ts +103 -100
  115. package/src/types.d.ts +38 -38
@@ -1,731 +1,733 @@
1
- import {
2
- activateTransformNode as activate,
3
- addToHighlightLayer,
4
- addToShadowGenerator,
5
- assertMeshCapability,
6
- assertTransformNode,
7
- cloneTransformNode,
8
- cloneTransformNodeMaterial,
9
- deactivateTransformNode as deactivate,
10
- getClientRectFromMesh,
11
- injectNodeMetadata,
12
- mapToDottedNodes,
13
- removeFromHighlightLayer,
14
- removeFromShadowGenerator,
15
- setMaterial,
16
- setMaterialColor,
17
- setMaterialMetallness,
18
- setMaterialRoughness,
19
- setMaterialTexture,
20
- setReceiveShadows,
21
- transformTransformNode,
22
- } from '../util/babylonHelper';
23
- import { createImageFromImgSrc, createImageFromSvg } from '../util/resourceHelper';
24
- import { addMissingMaterialObserver } from '../util/sceneLoaderHelper';
25
- import { VariantParameterizable } from './../classes/variantParameterizable';
26
- import { DottedPath } from './dottedPath';
27
- import { Event } from './event';
28
- import { Parameter } from './parameter';
29
- import { Variant } from './variant';
30
- import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
31
- import { ShadowGenerator } from '@babylonjs/core/Lights/Shadows/shadowGenerator';
32
- import { Light } from '@babylonjs/core/Lights/light';
33
- import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';
34
- import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
35
- import { Material } from '@babylonjs/core/Materials/material';
36
- import { Color3 } from '@babylonjs/core/Maths/math.color';
37
- import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
38
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
39
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
40
- import { has, isArray, isNumber, isPlainObject, merge, union } from 'lodash-es';
41
-
42
- /**
43
- * An {@link Element} of a {@link Variant}. Acts as a container for diverse definitions. Lives only in the context of a
44
- * {@link Variant}.
45
- *
46
- * When used in typings, refer to via its alias {@link VariantElement} to prevent name clashes with the web APIs
47
- * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) class
48
- */
49
- export class Element extends VariantParameterizable {
50
- public readonly nodes: TransformNode[] = [];
51
-
52
- protected readonly _dottedNodes: Map<DottedPath, TransformNode> = new Map();
53
-
54
- protected _highlightLayer?: HighlightLayer;
55
-
56
- /**
57
- * Constructor.
58
- */
59
- protected constructor(public readonly variant: Variant, public readonly name: string) {
60
- super(variant, name);
61
- if (process.env.NODE_ENV?.toLowerCase().includes('dev')) {
62
- this.assertPathDefinitions();
63
- }
64
- const nodes = this.variant.inheritedNodes.map(node => {
65
- const nodeNamingStrategy = {
66
- handler: variant.viewer.nodeNamingStrategyHandler,
67
- payload: {
68
- variantInstance: variant.variantInstance!,
69
- variant: variant,
70
- variantParameterizable: this,
71
- },
72
- };
73
- return cloneTransformNode(node, nodeNamingStrategy, this.filterNode.bind(this), true);
74
- });
75
- this.nodes = nodes.filter(node => !!node) as TransformNode[];
76
- this._dottedNodes = mapToDottedNodes<TransformNode>(this.nodes, node => node instanceof TransformNode);
77
- variant.broadcastEvent(Event.ELEMENT_NODES_CLONED, this);
78
- this.addMissingMaterialObservers();
79
- this.addParameterObservers();
80
- }
81
-
82
- /**
83
- * Creates an {@link Element} with given name.
84
- */
85
- public static async create(variant: Variant, name: string): Promise<Element> {
86
- const element = new Element(variant, name);
87
- variant.broadcastEvent(Event.ELEMENT_CREATED, element);
88
- return element;
89
- }
90
-
91
- /**
92
- * The {@link DottedPath} in the built tree of {@link Element}s.
93
- * E.g. "_.top-1.sub-2.sub-sub-3.el-1"
94
- */
95
- get dottedPath(): DottedPath {
96
- return DottedPath.create(this.variant.dottedPath).addPart(this.name);
97
- }
98
-
99
- /**
100
- * The id representing a {@link DottedPath}.
101
- */
102
- get id(): string {
103
- const dottedPath = DottedPath.create(this.dottedPath);
104
- dottedPath.shiftPart(); // remove root
105
- return dottedPath.path;
106
- }
107
-
108
- /**
109
- * The {@link ElementDefinition} of the {@link Element}.
110
- */
111
- get definition(): ElementDefinition {
112
- const definition = this.variant.structureJson.elements![this.name];
113
- if (isArray(definition)) {
114
- return {
115
- paths: {
116
- include: definition,
117
- },
118
- } as ElementDefinition;
119
- }
120
- return definition as ElementDefinition;
121
- }
122
-
123
- /**
124
- * The {@link PathDefinitions} of the {@link Element}.
125
- */
126
- get pathDefinitions(): PathDefinitions {
127
- return this.definition.paths;
128
- }
129
-
130
- /**
131
- * The {@link TraceableDefinitions} of the {@link Element}.
132
- */
133
- get traceableDefinitions(): TraceableDefinitions {
134
- return this.definition.traceables || {};
135
- }
136
-
137
- /**
138
- * The {@link PaintableDefinition} of the {@link Element}.
139
- */
140
- get paintableDefinitions(): PaintableDefinitions {
141
- return this.definition.paintables || {};
142
- }
143
-
144
- /**
145
- * The inherited {@link ParameterBag}.
146
- * Merges the {@link Variant}'s parameters and those from the {@link Element}.
147
- */
148
- get inheritedParameters(): ParameterBag {
149
- return merge({}, this.variant.inheritedParameters, this.parameters);
150
- }
151
-
152
- /**
153
- * The actual {@link TransformNode}s that make up this {@link Element}.
154
- */
155
- get nodesFlat(): TransformNode[] {
156
- return this.nodes.reduce(
157
- (acc, cur) => [...acc, ...(cur.getChildren(n => n instanceof TransformNode, false) as TransformNode[])],
158
- this.nodes
159
- );
160
- }
161
-
162
- /**
163
- * The actual {@link Mesh}es that make up this {@link Element}.
164
- * Handy for e.g. creating a bounding box around an entire element.
165
- */
166
- get meshesFlat(): Mesh[] {
167
- return this.nodes.reduce(
168
- (acc, cur) => [...acc, ...(cur.getChildren(n => n instanceof Mesh, false) as Mesh[])],
169
- this.nodes.filter(n => n instanceof Mesh) as Mesh[]
170
- );
171
- }
172
-
173
- /**
174
- * The actual {@link AbstractMesh}es that make up this {@link Element}.
175
- * I.e. (real) Meshes as well as InstancedMeshes.
176
- */
177
- get abstractMeshesFlat(): AbstractMesh[] {
178
- return this.nodes.reduce(
179
- (acc, cur) => [...acc, ...(cur.getChildren(n => n instanceof AbstractMesh, false) as AbstractMesh[])],
180
- this.nodes.filter(n => n instanceof AbstractMesh) as AbstractMesh[]
181
- );
182
- }
183
-
184
- /**
185
- * The meshes of this {@link Element}.
186
- */
187
- get meshes(): Mesh[] {
188
- return this.nodes.filter(node => node instanceof Mesh) as Mesh[];
189
- }
190
-
191
- /**
192
- * @protected
193
- */
194
- set highlightLayer(layer: HighlightLayer | undefined) {
195
- this._highlightLayer = layer;
196
- }
197
-
198
- get highlightLayer(): HighlightLayer | undefined {
199
- return this._highlightLayer;
200
- }
201
-
202
- /**
203
- * Destroys this {@link Element} and dispose all nodes.
204
- */
205
- public destroy(): Element {
206
- this.nodes.forEach(node => {
207
- node.dispose();
208
- });
209
- return this;
210
- }
211
-
212
- /**
213
- * Gets a node by its {@link DottedPath}.
214
- */
215
- public getNode(dottedPath: DottedPathArgument): TransformNode {
216
- const _dottedPath = DottedPath.create(dottedPath);
217
- const keys = Array.from(this._dottedNodes.keys()).map(dp => dp.path);
218
- const values = Array.from(this._dottedNodes.values());
219
- const node = values[keys.indexOf(_dottedPath.path)];
220
- if (!node) {
221
- throw new Error(`Node with path "${_dottedPath.path}" does not exist for element "${this.id}".`);
222
- }
223
- return node;
224
- }
225
-
226
- /**
227
- * Gets a mesh by its {@link DottedPath}.
228
- */
229
- public async getMesh(dottedPath: DottedPathArgument): Promise<Mesh | null> {
230
- const node = await this.getNode(dottedPath);
231
- if (node instanceof Mesh) {
232
- return node;
233
- }
234
- return null;
235
- }
236
-
237
- /**
238
- * Gets a {@link PaintableDefinition} by its name.
239
- */
240
- public getPaintableDefinition(name: string): PaintableDefinition {
241
- if (!this.paintableDefinitions || !this.paintableDefinitions[name]) {
242
- throw new Error(`No paintable "${name}" defined for element "${this.id}".`);
243
- }
244
- return this.paintableDefinitions[name];
245
- }
246
-
247
- /**
248
- * Gets a {@link TraceableDefinition} by its name.
249
- */
250
- public getTraceableDefinition(name: string): TraceableDefinition {
251
- if (!this.traceableDefinitions || !this.traceableDefinitions[name]) {
252
- throw new Error(`No traceable "${name}" defined to add observer in element "${this.id}".`);
253
- }
254
- return this.traceableDefinitions[name];
255
- }
256
-
257
- /**
258
- * Gets the paintable Node by its name.
259
- */
260
- public getPaintableNode(name: string): TransformNode {
261
- return this.getNode(this.getPaintableDefinition(name).path);
262
- }
263
-
264
- /**
265
- * Gets the traceable Node by its name.
266
- */
267
- public getTraceableNode(name: string): TransformNode {
268
- return this.getNode(this.getTraceableDefinition(name).path);
269
- }
270
-
271
- /**
272
- * @see {@link VariantParameterizable.commitParameters}
273
- * @emit {@link Event.ELEMENT_PARAMETER_COMMITTED}
274
- */
275
- public async commitParameters(parameters?: ParameterBag): Promise<VariantParameterizable> {
276
- return super.commitParameters(parameters);
277
- }
278
-
279
- /**
280
- * Adds an observer function for camera matrix changes.
281
- * The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
282
- */
283
- public addTraceableObserver(traceable: string, observer: CallableFunction, payload?: any): Element {
284
- if (payload && !(payload instanceof HTMLElement)) {
285
- throw new Error(`Payload for camera observer must be an instance of "HTMLElement" in element "${this.id}".`);
286
- }
287
- if (!this.traceableDefinitions || !this.traceableDefinitions[traceable]) {
288
- throw new Error(`No traceable "${traceable}" defined to add observer in element "${this.id}".`);
289
- }
290
- const node = this.getTraceableNode(traceable);
291
- if (!(node instanceof AbstractMesh)) {
292
- throw new Error(`The path must be an instance of "AbstractMesh" for camera observer in element "${this.id}".`);
293
- }
294
- this.variant.viewer.sceneManager.activeCamera.onViewMatrixChangedObservable.add((eventData, eventState) => {
295
- const position = getClientRectFromMesh(node, this.variant.viewer.scene, this.variant.viewer.canvas);
296
- if (payload) {
297
- payload.style.top = `${position.top}px`;
298
- payload.style.left = `${position.left}px`;
299
- }
300
- observer(node, position);
301
- });
302
- return this;
303
- }
304
-
305
- /**
306
- * Draws a `ImageBitmap` or `OffscreenCanvas` onto a `paintable` defined via {@link PaintableDefinition}.
307
- */
308
- public drawPaintable(paintable: string, imageSource: CanvasImageSource): Element {
309
- // node and material checks and preperation
310
- const node = this.getPaintableNode(paintable);
311
- if (!(node instanceof AbstractMesh)) {
312
- throw new Error(
313
- `The path must be an instance of "AbstractMesh" for paintable "${paintable}" ` + `in element "${this.id}".`
314
- );
315
- }
316
-
317
- if (node.material && this.variant.viewer.cloneMaterialsOnMutation) {
318
- if (node.material && !has(node.metadata, 'dirty.material')) {
319
- cloneTransformNodeMaterial(node);
320
- }
321
- if (!has(node.metadata, 'dirty.material.texture')) {
322
- // inject initial value and mark as dirty
323
- injectNodeMetadata(node, { dirty: { material: { texture: true } } });
324
- }
325
- } else if (!node.material) {
326
- // paintables should also work if no material is assigned to the node per default
327
- // in this case a certain fallback material with fitting default values is defined
328
- const pbrMat = new PBRMaterial(`${this.id}.${paintable}.material`, this.variant.viewer.scene);
329
- pbrMat.roughness = 1.0;
330
- pbrMat.metallic = 1.0;
331
- node.material = pbrMat;
332
- }
333
-
334
- // TODO: Not sure if this really should be overwritten every time the paintable is redrawn.
335
- // Maybe the 3D artist had something in mind when setting a certain transparency mode, which would get overwritten
336
- // in this case.
337
- // Applying it as a default if no material is set is fine though (see roughness/metallic some lines above).
338
- // Removing this line will most likely break existing configurators, so be cautios!
339
- node.material.transparencyMode = Material.MATERIAL_ALPHATESTANDBLEND;
340
-
341
- // consider width and height of the paintable
342
- const widthAndHeight = {
343
- width: imageSource.width,
344
- height: imageSource.height,
345
- };
346
- const paintableDefinition = this.getPaintableDefinition(paintable);
347
- if (isNumber(paintableDefinition.textureOptions)) {
348
- widthAndHeight.width = paintableDefinition.textureOptions;
349
- widthAndHeight.height = paintableDefinition.textureOptions;
350
- } else if (isPlainObject(paintableDefinition.textureOptions)) {
351
- widthAndHeight.width = paintableDefinition.textureOptions.width;
352
- widthAndHeight.height = paintableDefinition.textureOptions.height;
353
- }
354
-
355
- // create dynamic texture on which the image can be drawn
356
- const texture = new DynamicTexture(
357
- `${this.id}.${paintable}.texture`,
358
- widthAndHeight,
359
- this.variant.viewer.scene,
360
- false
361
- );
362
-
363
- // draw image on texture
364
- const ctx = texture.getContext();
365
- ctx.drawImage(imageSource, 0, 0);
366
- texture.update(false);
367
-
368
- // finally apply the texture on the desired node material
369
- setMaterialTexture(node, texture, false);
370
-
371
- return this;
372
- }
373
-
374
- /**
375
- * Draws a SVG string onto a `paintable` defined via {@link PaintableDefinition}.
376
- */
377
- public async drawPaintableFromSvg(paintable: string, svgSource: string): Promise<Element> {
378
- const image = await createImageFromSvg(svgSource);
379
- return this.drawPaintable(paintable, image);
380
- }
381
-
382
- /**
383
- * Draws an Image from source (URL/URI) onto a `paintable` defined via {@link PaintableDefinition}.
384
- */
385
- public async drawPaintableFromImgSrc(paintable: string, imgSource: string): Promise<Element> {
386
- const image = await createImageFromImgSrc(imgSource);
387
- return this.drawPaintable(paintable, image);
388
- }
389
-
390
- /**
391
- * Adds observers for loading missing materials where needed
392
- */
393
- protected addMissingMaterialObservers() {
394
- for (const abstractMesh of this.abstractMeshesFlat) {
395
- addMissingMaterialObserver(abstractMesh);
396
- }
397
- }
398
-
399
- /**
400
- * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
401
- */
402
- protected addParameterObservers(): Element {
403
- this._parameterObservers.set(Parameter.VISIBLE, [
404
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
405
- let visible;
406
- try {
407
- visible = Parameter.parseBoolean(newValue);
408
- } catch (e) {
409
- return;
410
- }
411
- if (visible === true) {
412
- // Override visible state and materials if tag manager is in use to support texture lazy loading
413
- if (element.variant.viewer.tagManager.parameters.size > 0) {
414
- const hiddenNodeNames: string[] = [];
415
- element.variant.viewer.tagManager.parameters.forEach((parameterBag, subject) => {
416
- const nodes = element.variant.viewer.tagManager.getNodesBySubject(subject);
417
- if (parameterBag[Parameter.VISIBLE] === false) {
418
- hiddenNodeNames.push(...nodes.map(node => node.name));
419
- }
420
- // overwrite materials immediatly, so that original material of node doesn't get loaded, since it could
421
- // be exchanged by the tag manager
422
- if (parameterBag[Parameter.MATERIAL]) {
423
- nodes.forEach(node => setMaterial(node, parameterBag[Parameter.MATERIAL], false));
424
- }
425
- });
426
- // enable all nodes that are not explicitely hidden by the tag manager
427
- element.nodesFlat.map(node => {
428
- if (!hiddenNodeNames.includes(node.name)) {
429
- node.setEnabled(true);
430
- }
431
- });
432
- return;
433
- }
434
- // The default behaviour.
435
- element.nodes.forEach(node => {
436
- injectNodeMetadata(node, { visibility: node.isEnabled() });
437
- activate(node);
438
- });
439
- } else if (visible === false) {
440
- element.nodes.forEach(node => {
441
- injectNodeMetadata(node, { visibility: node.isEnabled() });
442
- deactivate(node);
443
- });
444
- }
445
- },
446
- ]);
447
- this._parameterObservers.set(Parameter.SCALING, [
448
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
449
- // we have to deal just with root nodes here due to relative impacts in a node tree
450
- element.nodes.forEach(node =>
451
- transformTransformNode(node, {
452
- scaling: Parameter.parseVector(newValue),
453
- position: Parameter.parseVector(
454
- element.inheritedParameters[Parameter.POSITION] || Parameter.getDefaultValue(Parameter.POSITION)
455
- ),
456
- rotation: Parameter.parseRotation(
457
- element.inheritedParameters[Parameter.ROTATION] || Parameter.getDefaultValue(Parameter.ROTATION)
458
- ),
459
- })
460
- );
461
- },
462
- ]);
463
- this._parameterObservers.set(Parameter.POSITION, [
464
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
465
- // we have to deal just with root nodes here due to relative impacts in a node tree
466
- element.nodes.forEach(node =>
467
- transformTransformNode(node, {
468
- scaling: Parameter.parseVector(
469
- element.inheritedParameters[Parameter.SCALING] || Parameter.getDefaultValue(Parameter.SCALING)
470
- ),
471
- position: Parameter.parseVector(newValue),
472
- rotation: Parameter.parseRotation(
473
- element.inheritedParameters[Parameter.ROTATION] || Parameter.getDefaultValue(Parameter.ROTATION)
474
- ),
475
- })
476
- );
477
- },
478
- ]);
479
- this._parameterObservers.set(Parameter.ROTATION, [
480
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
481
- // we have to deal just with root nodes here due to relative impacts in a node tree
482
- element.nodes.forEach(node =>
483
- transformTransformNode(node, {
484
- scaling: Parameter.parseVector(
485
- element.inheritedParameters[Parameter.SCALING] || Parameter.getDefaultValue(Parameter.SCALING)
486
- ),
487
- position: Parameter.parseVector(
488
- element.inheritedParameters[Parameter.POSITION] || Parameter.getDefaultValue(Parameter.POSITION)
489
- ),
490
- rotation: Parameter.parseRotation(newValue),
491
- })
492
- );
493
- },
494
- ]);
495
- this._parameterObservers.set(Parameter.MATERIAL, [
496
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
497
- const materialName = newValue.toString();
498
- for (const node of element.nodes) {
499
- assertTransformNode(node, node => assertMeshCapability(node, Parameter.MATERIAL));
500
- setMaterial(node, materialName, true, element.variant);
501
- }
502
- },
503
- ]);
504
- this._parameterObservers.set(Parameter.MATERIAL_COLOR, [
505
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
506
- const color = Parameter.parseColor(newValue);
507
- element.nodes.forEach(node => {
508
- assertTransformNode(node, node => assertMeshCapability(node, Parameter.MATERIAL_COLOR));
509
- if (this.variant.viewer.cloneMaterialsOnMutation) {
510
- if (!has(node.metadata, 'dirty.material')) {
511
- cloneTransformNodeMaterial(node);
512
- }
513
- if (!has(node.metadata, 'dirty.material.color')) {
514
- // inject initial value and mark as dirty
515
- injectNodeMetadata(node, { dirty: { material: { color: oldValue } } });
516
- }
517
- }
518
- setMaterialColor(node, color);
519
- });
520
- },
521
- ]);
522
- this._parameterObservers.set(Parameter.MATERIAL_METALLNESS, [
523
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
524
- const metallness = Parameter.parseNumber(newValue);
525
- element.nodes.forEach(node => {
526
- assertTransformNode(node, node => assertMeshCapability(node, Parameter.MATERIAL_METALLNESS));
527
- if (this.variant.viewer.cloneMaterialsOnMutation) {
528
- if (!has(node.metadata, 'dirty.material')) {
529
- cloneTransformNodeMaterial(node);
530
- }
531
- if (!has(node.metadata, 'dirty.material.metallness')) {
532
- // inject initial value and mark as dirty
533
- injectNodeMetadata(node, { dirty: { material: { metallness: oldValue } } });
534
- }
535
- }
536
- setMaterialMetallness(node, metallness);
537
- });
538
- },
539
- ]);
540
- this._parameterObservers.set(Parameter.MATERIAL_ROUGHNESS, [
541
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
542
- const roughness = Parameter.parseNumber(newValue);
543
- element.nodes.forEach(node => {
544
- assertTransformNode(node, node => assertMeshCapability(node, Parameter.MATERIAL_ROUGHNESS));
545
- if (this.variant.viewer.cloneMaterialsOnMutation) {
546
- if (!has(node.metadata, 'dirty.material')) {
547
- cloneTransformNodeMaterial(node);
548
- }
549
- if (!has(node.metadata, 'dirty.material.roughness')) {
550
- // inject initial value and mark as dirty
551
- injectNodeMetadata(node, { dirty: { material: { roughness: oldValue } } });
552
- }
553
- }
554
- setMaterialRoughness(node, roughness);
555
- });
556
- },
557
- ]);
558
- this._parameterObservers.set(Parameter.HIGHLIGHT_COLOR, [
559
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
560
- // trigger Parameter.HIGHLIGHTED observers
561
- this._parameterObservers.get(Parameter.HIGHLIGHTED)?.forEach(observer => {
562
- observer(element, !!element.highlighted, !!element.highlighted);
563
- });
564
- },
565
- ]);
566
- this._parameterObservers.set(Parameter.HIGHLIGHT_ENABLED, [
567
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
568
- let curr;
569
- try {
570
- curr = Parameter.parseBoolean(newValue);
571
- } catch (e) {
572
- return;
573
- }
574
- switch (curr) {
575
- case true:
576
- if (element._highlightLayer) {
577
- break;
578
- }
579
- element.highlightLayer = new HighlightLayer(
580
- DottedPath.create(element.id).addPart('highlight').path,
581
- element.variant.viewer.scene
582
- );
583
- break;
584
- case false:
585
- element.highlightLayer?.dispose();
586
- break;
587
- }
588
- },
589
- ]);
590
- this._parameterObservers.set(Parameter.HIGHLIGHTED, [
591
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
592
- if (!element.inheritedParameters[Parameter.HIGHLIGHT_ENABLED]) {
593
- return;
594
- }
595
- // trigger Parameter.HIGHLIGHT_ENABLED observers to ensure HighlightLayer
596
- this._parameterObservers.get(Parameter.HIGHLIGHT_ENABLED)?.forEach(observer => {
597
- observer(element, this.parameters[Parameter.HIGHLIGHT_ENABLED], true);
598
- });
599
- let highlighted;
600
- try {
601
- highlighted = Parameter.parseBoolean(newValue);
602
- } catch (e) {
603
- return;
604
- }
605
- // Add/Remove meshes to previously created highlight layers.
606
- if (highlighted === true) {
607
- element.nodes.forEach(node => {
608
- assertTransformNode(node, node => assertMeshCapability(node, Parameter.HIGHLIGHTED));
609
- let color = Color3.Green();
610
- if (element.inheritedParameters[Parameter.HIGHLIGHT_COLOR]) {
611
- color = Parameter.parseColor(element.inheritedParameters[Parameter.HIGHLIGHT_COLOR]);
612
- }
613
- if (typeof element._highlightLayer !== 'undefined') {
614
- addToHighlightLayer(element._highlightLayer, color, node);
615
- }
616
- });
617
- } else if (highlighted === false) {
618
- element.nodes.forEach(node => {
619
- if (typeof element._highlightLayer !== 'undefined') {
620
- removeFromHighlightLayer(element._highlightLayer, node);
621
- }
622
- });
623
- }
624
- },
625
- ]);
626
- this._parameterObservers.set(Parameter.CAST_SHADOW, [
627
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
628
- let castShadow;
629
- try {
630
- castShadow = Parameter.parseBoolean(newValue);
631
- } catch (e) {
632
- return;
633
- }
634
- let lightCsl = element.inheritedParameters[Parameter.CAST_SHADOW_FROM_LIGHTS];
635
- if (!lightCsl) {
636
- lightCsl = element.variant.inheritedViewerLights.map(l => l.name).join(',');
637
- }
638
- if (castShadow === true) {
639
- await this.castShadowValueHandler(lightCsl, addToShadowGenerator);
640
- }
641
- if (castShadow === false) {
642
- await this.castShadowValueHandler(lightCsl, removeFromShadowGenerator);
643
- }
644
- },
645
- ]);
646
- this._parameterObservers.set(Parameter.CAST_SHADOW_FROM_LIGHTS, [
647
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
648
- // TODO: Possible performance issue in combination with CAST_SHADOW, since both observers are initially called
649
- // when CAST_SHADOW and CAST_SHADOW_FROM_LIGHTS are defined in the spec.
650
- const lightCsl = element.variant.inheritedViewerLights.map(l => l.name).join(',');
651
- // cleanup all shadow generators
652
- await this.castShadowValueHandler(lightCsl, removeFromShadowGenerator);
653
- if (element.castShadow === true) {
654
- // if newValue is undefined or '' then set newValue to lightCsl (use all lights)
655
- if (!newValue) {
656
- newValue = lightCsl;
657
- }
658
- await this.castShadowValueHandler(newValue, addToShadowGenerator);
659
- }
660
- },
661
- ]);
662
- this._parameterObservers.set(Parameter.RECEIVE_SHADOWS, [
663
- async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
664
- element.nodes.forEach(node => setReceiveShadows(node, Parameter.parseBoolean(newValue)));
665
- },
666
- ]);
667
- return this;
668
- }
669
-
670
- /**
671
- * Filter for nodes that are not defined or excluded in the `pathDefinitions`.
672
- */
673
- protected filterNode(node: TransformNode): boolean {
674
- let includeTokens: string[] = [];
675
- this.pathDefinitions.include.forEach(dottedPath => {
676
- includeTokens = union(includeTokens, DottedPath.create(dottedPath).leafTokens);
677
- });
678
- const shallKeep = (dp: DottedPath) => {
679
- const isDirectlyIncluded = !!includeTokens.find(_dp => _dp === dp.path);
680
- const isSubOfIncluded = !!this.pathDefinitions.include.find(_dp => {
681
- return dp.path.startsWith(`${_dp}${DottedPath.DELIMITER}`);
682
- });
683
- return isDirectlyIncluded || isSubOfIncluded;
684
- };
685
- const shallExclude = (dp: DottedPath) => {
686
- if (!this.pathDefinitions.exclude) {
687
- return false;
688
- }
689
- return !!this.pathDefinitions.exclude.find(_dp => dp.path === _dp);
690
- };
691
- return shallKeep(node.metadata.dottedPath) && !shallExclude(node.metadata.dottedPath);
692
- }
693
-
694
- /**
695
- * Asserts whether all {@link pathDefinitions} link to a valid `Node` path.
696
- * @protected
697
- */
698
- protected assertPathDefinitions() {
699
- const dottedNodes = this.variant.inheritedDottedNodes;
700
- if (dottedNodes.size === 0) {
701
- throw new Error(`There are no mapped nodes for element "${this.id}".`);
702
- }
703
- const include = this.pathDefinitions.include.map(path => DottedPath.create(path).path);
704
- const exclude = this.pathDefinitions.exclude?.map(path => DottedPath.create(path).path);
705
- const keys = Array.from(dottedNodes.keys()).map(dottedPath => dottedPath.path);
706
- union<string>(include, exclude).forEach(path => {
707
- if (keys.indexOf(path) === -1) {
708
- throw new Error(`Node with path "${path}" does not exist for element "${this.id}".`);
709
- }
710
- });
711
- }
712
-
713
- /**
714
- * Handles callback for given light parameter.
715
- */
716
- private async castShadowValueHandler(lightCsl: ParameterValue, mutator: CallableFunction) {
717
- const lights: Light[] = [];
718
- for (const lightName of Parameter.parseCommaSeparatedList(lightCsl)) {
719
- const viewerLight = await this.variant.getViewerLight(lightName);
720
- if (viewerLight) {
721
- lights.push(viewerLight.light);
722
- }
723
- }
724
- const shadowGenerators = lights.map(light => light?.getShadowGenerator() as ShadowGenerator).filter(Boolean);
725
- shadowGenerators.forEach(generator => {
726
- this.nodes.forEach(node => {
727
- mutator(generator, node);
728
- });
729
- });
730
- }
731
- }
1
+ import {
2
+ activateTransformNode as activate,
3
+ addToHighlightLayer,
4
+ addToShadowGenerator,
5
+ assertMeshCapability,
6
+ assertTransformNode,
7
+ cloneTransformNode,
8
+ cloneTransformNodeMaterial,
9
+ deactivateTransformNode as deactivate,
10
+ getClientRectFromMesh,
11
+ injectNodeMetadata,
12
+ mapToDottedNodes,
13
+ removeFromHighlightLayer,
14
+ removeFromShadowGenerator,
15
+ setMaterial,
16
+ setMaterialColor,
17
+ setMaterialMetallness,
18
+ setMaterialRoughness,
19
+ setMaterialTexture,
20
+ setReceiveShadows,
21
+ transformTransformNode,
22
+ } from '../util/babylonHelper';
23
+ import { createImageFromImgSrc, createImageFromSvg } from '../util/resourceHelper';
24
+ import { addMissingMaterialObserver } from '../util/sceneLoaderHelper';
25
+ import { VariantParameterizable } from './../classes/variantParameterizable';
26
+ import { DottedPath } from './dottedPath';
27
+ import { Event } from './event';
28
+ import { Parameter } from './parameter';
29
+ import { Variant } from './variant';
30
+ import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
31
+ import { ShadowGenerator } from '@babylonjs/core/Lights/Shadows/shadowGenerator';
32
+ import { Light } from '@babylonjs/core/Lights/light';
33
+ import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';
34
+ import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
35
+ import { Material } from '@babylonjs/core/Materials/material';
36
+ import { Color3 } from '@babylonjs/core/Maths/math.color';
37
+ import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
38
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
39
+ import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
40
+ import { has, isArray, isNumber, isPlainObject, merge, union } from 'lodash-es';
41
+
42
+ /**
43
+ * An {@link Element} of a {@link Variant}. Acts as a container for diverse definitions. Lives only in the context of a
44
+ * {@link Variant}.
45
+ *
46
+ * When used in typings, refer to via its alias {@link VariantElement} to prevent name clashes with the web APIs
47
+ * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) class
48
+ */
49
+ export class Element extends VariantParameterizable {
50
+ public readonly nodes: TransformNode[] = [];
51
+
52
+ protected readonly _dottedNodes: Map<DottedPath, TransformNode> = new Map();
53
+
54
+ protected _highlightLayer?: HighlightLayer;
55
+
56
+ /**
57
+ * Constructor.
58
+ */
59
+ protected constructor(public readonly variant: Variant, public readonly name: string) {
60
+ super(variant, name);
61
+ if (process.env.NODE_ENV?.toLowerCase().includes('dev')) {
62
+ this.assertPathDefinitions();
63
+ }
64
+ const nodes = this.variant.inheritedNodes.map(node => {
65
+ const nodeNamingStrategy = {
66
+ handler: variant.viewer.nodeNamingStrategyHandler,
67
+ payload: {
68
+ variantInstance: variant.variantInstance!,
69
+ variant: variant,
70
+ variantParameterizable: this,
71
+ },
72
+ };
73
+ return cloneTransformNode(node, nodeNamingStrategy, this.filterNode.bind(this), true);
74
+ });
75
+ this.nodes = nodes.filter(node => !!node) as TransformNode[];
76
+ this._dottedNodes = mapToDottedNodes<TransformNode>(this.nodes, node => node instanceof TransformNode);
77
+ variant.broadcastEvent(Event.ELEMENT_NODES_CLONED, this);
78
+ this.addMissingMaterialObservers();
79
+ this.addParameterObservers();
80
+ }
81
+
82
+ /**
83
+ * Creates an {@link Element} with given name.
84
+ */
85
+ public static async create(variant: Variant, name: string): Promise<Element> {
86
+ const element = new Element(variant, name);
87
+ variant.broadcastEvent(Event.ELEMENT_CREATED, element);
88
+ return element;
89
+ }
90
+
91
+ /**
92
+ * The {@link DottedPath} in the built tree of {@link Element}s.
93
+ * E.g. "_.top-1.sub-2.sub-sub-3.el-1"
94
+ */
95
+ get dottedPath(): DottedPath {
96
+ return DottedPath.create(this.variant.dottedPath).addPart(this.name);
97
+ }
98
+
99
+ /**
100
+ * The id representing a {@link DottedPath}.
101
+ */
102
+ get id(): string {
103
+ const dottedPath = DottedPath.create(this.dottedPath);
104
+ dottedPath.shiftPart(); // remove root
105
+ return dottedPath.path;
106
+ }
107
+
108
+ /**
109
+ * The {@link ElementDefinition} of the {@link Element}.
110
+ */
111
+ get definition(): ElementDefinition {
112
+ const definition = this.variant.structureJson.elements![this.name];
113
+ if (isArray(definition)) {
114
+ return {
115
+ paths: {
116
+ include: definition,
117
+ },
118
+ } as ElementDefinition;
119
+ }
120
+ return definition as ElementDefinition;
121
+ }
122
+
123
+ /**
124
+ * The {@link PathDefinitions} of the {@link Element}.
125
+ */
126
+ get pathDefinitions(): PathDefinitions {
127
+ return this.definition.paths;
128
+ }
129
+
130
+ /**
131
+ * The {@link TraceableDefinitions} of the {@link Element}.
132
+ */
133
+ get traceableDefinitions(): TraceableDefinitions {
134
+ return this.definition.traceables || {};
135
+ }
136
+
137
+ /**
138
+ * The {@link PaintableDefinition} of the {@link Element}.
139
+ */
140
+ get paintableDefinitions(): PaintableDefinitions {
141
+ return this.definition.paintables || {};
142
+ }
143
+
144
+ /**
145
+ * The inherited {@link ParameterBag}.
146
+ * Merges the {@link Variant}'s parameters and those from the {@link Element}.
147
+ */
148
+ get inheritedParameters(): ParameterBag {
149
+ return merge({}, this.variant.inheritedParameters, this.parameters);
150
+ }
151
+
152
+ /**
153
+ * The actual {@link TransformNode}s that make up this {@link Element}.
154
+ */
155
+ get nodesFlat(): TransformNode[] {
156
+ return this.nodes.reduce(
157
+ (acc, cur) => [...acc, ...(cur.getChildren(n => n instanceof TransformNode, false) as TransformNode[])],
158
+ this.nodes
159
+ );
160
+ }
161
+
162
+ /**
163
+ * The actual {@link Mesh}es that make up this {@link Element}.
164
+ * Handy for e.g. creating a bounding box around an entire element.
165
+ */
166
+ get meshesFlat(): Mesh[] {
167
+ return this.nodes.reduce(
168
+ (acc, cur) => [...acc, ...(cur.getChildren(n => n instanceof Mesh, false) as Mesh[])],
169
+ this.nodes.filter(n => n instanceof Mesh) as Mesh[]
170
+ );
171
+ }
172
+
173
+ /**
174
+ * The actual {@link AbstractMesh}es that make up this {@link Element}.
175
+ * I.e. (real) Meshes as well as InstancedMeshes.
176
+ */
177
+ get abstractMeshesFlat(): AbstractMesh[] {
178
+ return this.nodes.reduce(
179
+ (acc, cur) => [...acc, ...(cur.getChildren(n => n instanceof AbstractMesh, false) as AbstractMesh[])],
180
+ this.nodes.filter(n => n instanceof AbstractMesh) as AbstractMesh[]
181
+ );
182
+ }
183
+
184
+ /**
185
+ * The meshes of this {@link Element}.
186
+ */
187
+ get meshes(): Mesh[] {
188
+ return this.nodes.filter(node => node instanceof Mesh) as Mesh[];
189
+ }
190
+
191
+ /**
192
+ * @protected
193
+ */
194
+ set highlightLayer(layer: HighlightLayer | undefined) {
195
+ this._highlightLayer = layer;
196
+ }
197
+
198
+ get highlightLayer(): HighlightLayer | undefined {
199
+ return this._highlightLayer;
200
+ }
201
+
202
+ /**
203
+ * Destroys this {@link Element} and dispose all nodes.
204
+ */
205
+ public destroy(): Element {
206
+ this.nodes.forEach(node => {
207
+ node.dispose();
208
+ });
209
+ return this;
210
+ }
211
+
212
+ /**
213
+ * Gets a node by its {@link DottedPath}.
214
+ */
215
+ public getNode(dottedPath: DottedPathArgument): TransformNode {
216
+ const _dottedPath = DottedPath.create(dottedPath);
217
+ const keys = Array.from(this._dottedNodes.keys()).map(dp => dp.path);
218
+ const values = Array.from(this._dottedNodes.values());
219
+ const node = values[keys.indexOf(_dottedPath.path)];
220
+ if (!node) {
221
+ throw new Error(`Node with path "${_dottedPath.path}" does not exist for element "${this.id}".`);
222
+ }
223
+ return node;
224
+ }
225
+
226
+ /**
227
+ * Gets a mesh by its {@link DottedPath}.
228
+ */
229
+ public async getMesh(dottedPath: DottedPathArgument): Promise<Mesh | null> {
230
+ const node = await this.getNode(dottedPath);
231
+ if (node instanceof Mesh) {
232
+ return node;
233
+ }
234
+ return null;
235
+ }
236
+
237
+ /**
238
+ * Gets a {@link PaintableDefinition} by its name.
239
+ */
240
+ public getPaintableDefinition(name: string): PaintableDefinition {
241
+ if (!this.paintableDefinitions || !this.paintableDefinitions[name]) {
242
+ throw new Error(`No paintable "${name}" defined for element "${this.id}".`);
243
+ }
244
+ return this.paintableDefinitions[name];
245
+ }
246
+
247
+ /**
248
+ * Gets a {@link TraceableDefinition} by its name.
249
+ */
250
+ public getTraceableDefinition(name: string): TraceableDefinition {
251
+ if (!this.traceableDefinitions || !this.traceableDefinitions[name]) {
252
+ throw new Error(`No traceable "${name}" defined to add observer in element "${this.id}".`);
253
+ }
254
+ return this.traceableDefinitions[name];
255
+ }
256
+
257
+ /**
258
+ * Gets the paintable Node by its name.
259
+ */
260
+ public getPaintableNode(name: string): TransformNode {
261
+ return this.getNode(this.getPaintableDefinition(name).path);
262
+ }
263
+
264
+ /**
265
+ * Gets the traceable Node by its name.
266
+ */
267
+ public getTraceableNode(name: string): TransformNode {
268
+ return this.getNode(this.getTraceableDefinition(name).path);
269
+ }
270
+
271
+ /**
272
+ * @see {@link VariantParameterizable.commitParameters}
273
+ * @emit {@link Event.ELEMENT_PARAMETER_COMMITTED}
274
+ */
275
+ public async commitParameters(parameters?: ParameterBag): Promise<VariantParameterizable> {
276
+ return super.commitParameters(parameters);
277
+ }
278
+
279
+ /**
280
+ * Adds an observer function for camera matrix changes.
281
+ * The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
282
+ */
283
+ public addTraceableObserver(traceable: string, observer: CallableFunction, payload?: any): Element {
284
+ if (payload && !(payload instanceof HTMLElement)) {
285
+ throw new Error(`Payload for camera observer must be an instance of "HTMLElement" in element "${this.id}".`);
286
+ }
287
+ if (!this.traceableDefinitions || !this.traceableDefinitions[traceable]) {
288
+ throw new Error(`No traceable "${traceable}" defined to add observer in element "${this.id}".`);
289
+ }
290
+ const node = this.getTraceableNode(traceable);
291
+ if (!(node instanceof AbstractMesh)) {
292
+ throw new Error(`The path must be an instance of "AbstractMesh" for camera observer in element "${this.id}".`);
293
+ }
294
+ this.variant.viewer.sceneManager.activeCamera.onViewMatrixChangedObservable.add((eventData, eventState) => {
295
+ const position = getClientRectFromMesh(node, this.variant.viewer.scene, this.variant.viewer.canvas);
296
+ if (payload) {
297
+ payload.style.top = `${position.top}px`;
298
+ payload.style.left = `${position.left}px`;
299
+ }
300
+ observer(node, position);
301
+ });
302
+ return this;
303
+ }
304
+
305
+ /**
306
+ * Draws a `ImageBitmap` or `OffscreenCanvas` onto a `paintable` defined via {@link PaintableDefinition}.
307
+ */
308
+ public drawPaintable(paintable: string, imageSource: CanvasImageSource): Element {
309
+ // node and material checks and preperation
310
+ const node = this.getPaintableNode(paintable);
311
+ if (!(node instanceof AbstractMesh)) {
312
+ throw new Error(
313
+ `The path must be an instance of "AbstractMesh" for paintable "${paintable}" ` + `in element "${this.id}".`
314
+ );
315
+ }
316
+
317
+ if (node.material && this.variant.viewer.cloneMaterialsOnMutation) {
318
+ if (node.material && !has(node.metadata, 'dirty.material')) {
319
+ cloneTransformNodeMaterial(node);
320
+ }
321
+ if (!has(node.metadata, 'dirty.material.texture')) {
322
+ // inject initial value and mark as dirty
323
+ injectNodeMetadata(node, { dirty: { material: { texture: true } } });
324
+ }
325
+ } else if (!node.material) {
326
+ // paintables should also work if no material is assigned to the node per default
327
+ // in this case a certain fallback material with fitting default values is defined
328
+ const pbrMat = new PBRMaterial(`${this.id}.${paintable}.material`, this.variant.viewer.scene);
329
+ pbrMat.roughness = 1.0;
330
+ pbrMat.metallic = 1.0;
331
+ node.material = pbrMat;
332
+ }
333
+
334
+ // TODO: Not sure if this really should be overwritten every time the paintable is redrawn.
335
+ // Maybe the 3D artist had something in mind when setting a certain transparency mode, which would get overwritten
336
+ // in this case.
337
+ // Applying it as a default if no material is set is fine though (see roughness/metallic some lines above).
338
+ // Removing this line will most likely break existing configurators, so be cautios!
339
+ node.material.transparencyMode = Material.MATERIAL_ALPHATESTANDBLEND;
340
+
341
+ // consider width and height of the paintable
342
+ const widthAndHeight = {
343
+ width: imageSource.width,
344
+ height: imageSource.height,
345
+ };
346
+ const paintableDefinition = this.getPaintableDefinition(paintable);
347
+ if (isNumber(paintableDefinition.textureOptions)) {
348
+ widthAndHeight.width = paintableDefinition.textureOptions;
349
+ widthAndHeight.height = paintableDefinition.textureOptions;
350
+ } else if (isPlainObject(paintableDefinition.textureOptions)) {
351
+ widthAndHeight.width = paintableDefinition.textureOptions.width;
352
+ widthAndHeight.height = paintableDefinition.textureOptions.height;
353
+ }
354
+
355
+ // create dynamic texture on which the image can be drawn
356
+ const texture = new DynamicTexture(
357
+ `${this.id}.${paintable}.texture`,
358
+ widthAndHeight,
359
+ this.variant.viewer.scene,
360
+ false
361
+ );
362
+
363
+ // draw image on texture
364
+ const ctx = texture.getContext();
365
+ ctx.drawImage(imageSource, 0, 0);
366
+ texture.update(false);
367
+
368
+ // finally apply the texture on the desired node material
369
+ setMaterialTexture(node, texture, false);
370
+
371
+ return this;
372
+ }
373
+
374
+ /**
375
+ * Draws a SVG string onto a `paintable` defined via {@link PaintableDefinition}.
376
+ */
377
+ public async drawPaintableFromSvg(paintable: string, svgSource: string): Promise<Element> {
378
+ const image = await createImageFromSvg(svgSource);
379
+ return this.drawPaintable(paintable, image);
380
+ }
381
+
382
+ /**
383
+ * Draws an Image from source (URL/URI) onto a `paintable` defined via {@link PaintableDefinition}.
384
+ */
385
+ public async drawPaintableFromImgSrc(paintable: string, imgSource: string): Promise<Element> {
386
+ const image = await createImageFromImgSrc(imgSource);
387
+ return this.drawPaintable(paintable, image);
388
+ }
389
+
390
+ /**
391
+ * Adds observers for loading missing materials where needed
392
+ */
393
+ protected addMissingMaterialObservers() {
394
+ for (const abstractMesh of this.abstractMeshesFlat) {
395
+ addMissingMaterialObserver(abstractMesh);
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
401
+ */
402
+ protected addParameterObservers(): Element {
403
+ this._parameterObservers.set(Parameter.VISIBLE, [
404
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
405
+ let visible;
406
+ try {
407
+ visible = Parameter.parseBoolean(newValue);
408
+ } catch (e) {
409
+ return;
410
+ }
411
+ if (visible === true) {
412
+ // Override visible state and materials if tag manager is in use to support texture lazy loading
413
+ if (element.variant.viewer.tagManager.parameters.size > 0) {
414
+ const hiddenNodeNames: string[] = [];
415
+ element.variant.viewer.tagManager.parameters.forEach((parameterBag, subject) => {
416
+ const nodes = element.variant.viewer.tagManager.getNodesBySubject(subject);
417
+ const visibleParamValue = parameterBag[Parameter.VISIBLE];
418
+ const isVisible = undefined === visibleParamValue || Parameter.parseBoolean(visibleParamValue);
419
+ if (!isVisible) {
420
+ hiddenNodeNames.push(...nodes.map(node => node.name));
421
+ }
422
+ // overwrite materials immediatly, so that original material of node doesn't get loaded, since it could
423
+ // be exchanged by the tag manager
424
+ if (parameterBag[Parameter.MATERIAL]) {
425
+ nodes.forEach(node => setMaterial(node, parameterBag[Parameter.MATERIAL], false));
426
+ }
427
+ });
428
+ // enable all nodes that are not explicitely hidden by the tag manager
429
+ element.nodesFlat.map(node => {
430
+ if (!hiddenNodeNames.includes(node.name)) {
431
+ node.setEnabled(true);
432
+ }
433
+ });
434
+ return;
435
+ }
436
+ // The default behaviour.
437
+ element.nodes.forEach(node => {
438
+ injectNodeMetadata(node, { visibility: node.isEnabled() });
439
+ activate(node);
440
+ });
441
+ } else if (visible === false) {
442
+ element.nodes.forEach(node => {
443
+ injectNodeMetadata(node, { visibility: node.isEnabled() });
444
+ deactivate(node);
445
+ });
446
+ }
447
+ },
448
+ ]);
449
+ this._parameterObservers.set(Parameter.SCALING, [
450
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
451
+ // we have to deal just with root nodes here due to relative impacts in a node tree
452
+ element.nodes.forEach(node =>
453
+ transformTransformNode(node, {
454
+ scaling: Parameter.parseVector(newValue),
455
+ position: Parameter.parseVector(
456
+ element.inheritedParameters[Parameter.POSITION] || Parameter.getDefaultValue(Parameter.POSITION)
457
+ ),
458
+ rotation: Parameter.parseRotation(
459
+ element.inheritedParameters[Parameter.ROTATION] || Parameter.getDefaultValue(Parameter.ROTATION)
460
+ ),
461
+ })
462
+ );
463
+ },
464
+ ]);
465
+ this._parameterObservers.set(Parameter.POSITION, [
466
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
467
+ // we have to deal just with root nodes here due to relative impacts in a node tree
468
+ element.nodes.forEach(node =>
469
+ transformTransformNode(node, {
470
+ scaling: Parameter.parseVector(
471
+ element.inheritedParameters[Parameter.SCALING] || Parameter.getDefaultValue(Parameter.SCALING)
472
+ ),
473
+ position: Parameter.parseVector(newValue),
474
+ rotation: Parameter.parseRotation(
475
+ element.inheritedParameters[Parameter.ROTATION] || Parameter.getDefaultValue(Parameter.ROTATION)
476
+ ),
477
+ })
478
+ );
479
+ },
480
+ ]);
481
+ this._parameterObservers.set(Parameter.ROTATION, [
482
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
483
+ // we have to deal just with root nodes here due to relative impacts in a node tree
484
+ element.nodes.forEach(node =>
485
+ transformTransformNode(node, {
486
+ scaling: Parameter.parseVector(
487
+ element.inheritedParameters[Parameter.SCALING] || Parameter.getDefaultValue(Parameter.SCALING)
488
+ ),
489
+ position: Parameter.parseVector(
490
+ element.inheritedParameters[Parameter.POSITION] || Parameter.getDefaultValue(Parameter.POSITION)
491
+ ),
492
+ rotation: Parameter.parseRotation(newValue),
493
+ })
494
+ );
495
+ },
496
+ ]);
497
+ this._parameterObservers.set(Parameter.MATERIAL, [
498
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
499
+ const materialName = newValue.toString();
500
+ for (const node of element.nodes) {
501
+ assertTransformNode(node, node => assertMeshCapability(node, Parameter.MATERIAL));
502
+ setMaterial(node, materialName, true, element.variant);
503
+ }
504
+ },
505
+ ]);
506
+ this._parameterObservers.set(Parameter.MATERIAL_COLOR, [
507
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
508
+ const color = Parameter.parseColor(newValue);
509
+ element.nodes.forEach(node => {
510
+ assertTransformNode(node, node => assertMeshCapability(node, Parameter.MATERIAL_COLOR));
511
+ if (this.variant.viewer.cloneMaterialsOnMutation) {
512
+ if (!has(node.metadata, 'dirty.material')) {
513
+ cloneTransformNodeMaterial(node);
514
+ }
515
+ if (!has(node.metadata, 'dirty.material.color')) {
516
+ // inject initial value and mark as dirty
517
+ injectNodeMetadata(node, { dirty: { material: { color: oldValue } } });
518
+ }
519
+ }
520
+ setMaterialColor(node, color);
521
+ });
522
+ },
523
+ ]);
524
+ this._parameterObservers.set(Parameter.MATERIAL_METALLNESS, [
525
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
526
+ const metallness = Parameter.parseNumber(newValue);
527
+ element.nodes.forEach(node => {
528
+ assertTransformNode(node, node => assertMeshCapability(node, Parameter.MATERIAL_METALLNESS));
529
+ if (this.variant.viewer.cloneMaterialsOnMutation) {
530
+ if (!has(node.metadata, 'dirty.material')) {
531
+ cloneTransformNodeMaterial(node);
532
+ }
533
+ if (!has(node.metadata, 'dirty.material.metallness')) {
534
+ // inject initial value and mark as dirty
535
+ injectNodeMetadata(node, { dirty: { material: { metallness: oldValue } } });
536
+ }
537
+ }
538
+ setMaterialMetallness(node, metallness);
539
+ });
540
+ },
541
+ ]);
542
+ this._parameterObservers.set(Parameter.MATERIAL_ROUGHNESS, [
543
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
544
+ const roughness = Parameter.parseNumber(newValue);
545
+ element.nodes.forEach(node => {
546
+ assertTransformNode(node, node => assertMeshCapability(node, Parameter.MATERIAL_ROUGHNESS));
547
+ if (this.variant.viewer.cloneMaterialsOnMutation) {
548
+ if (!has(node.metadata, 'dirty.material')) {
549
+ cloneTransformNodeMaterial(node);
550
+ }
551
+ if (!has(node.metadata, 'dirty.material.roughness')) {
552
+ // inject initial value and mark as dirty
553
+ injectNodeMetadata(node, { dirty: { material: { roughness: oldValue } } });
554
+ }
555
+ }
556
+ setMaterialRoughness(node, roughness);
557
+ });
558
+ },
559
+ ]);
560
+ this._parameterObservers.set(Parameter.HIGHLIGHT_COLOR, [
561
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
562
+ // trigger Parameter.HIGHLIGHTED observers
563
+ this._parameterObservers.get(Parameter.HIGHLIGHTED)?.forEach(observer => {
564
+ observer(element, !!element.highlighted, !!element.highlighted);
565
+ });
566
+ },
567
+ ]);
568
+ this._parameterObservers.set(Parameter.HIGHLIGHT_ENABLED, [
569
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
570
+ let curr;
571
+ try {
572
+ curr = Parameter.parseBoolean(newValue);
573
+ } catch (e) {
574
+ return;
575
+ }
576
+ switch (curr) {
577
+ case true:
578
+ if (element._highlightLayer) {
579
+ break;
580
+ }
581
+ element.highlightLayer = new HighlightLayer(
582
+ DottedPath.create(element.id).addPart('highlight').path,
583
+ element.variant.viewer.scene
584
+ );
585
+ break;
586
+ case false:
587
+ element.highlightLayer?.dispose();
588
+ break;
589
+ }
590
+ },
591
+ ]);
592
+ this._parameterObservers.set(Parameter.HIGHLIGHTED, [
593
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
594
+ if (!element.inheritedParameters[Parameter.HIGHLIGHT_ENABLED]) {
595
+ return;
596
+ }
597
+ // trigger Parameter.HIGHLIGHT_ENABLED observers to ensure HighlightLayer
598
+ this._parameterObservers.get(Parameter.HIGHLIGHT_ENABLED)?.forEach(observer => {
599
+ observer(element, this.parameters[Parameter.HIGHLIGHT_ENABLED], true);
600
+ });
601
+ let highlighted;
602
+ try {
603
+ highlighted = Parameter.parseBoolean(newValue);
604
+ } catch (e) {
605
+ return;
606
+ }
607
+ // Add/Remove meshes to previously created highlight layers.
608
+ if (highlighted === true) {
609
+ element.nodes.forEach(node => {
610
+ assertTransformNode(node, node => assertMeshCapability(node, Parameter.HIGHLIGHTED));
611
+ let color = Color3.Green();
612
+ if (element.inheritedParameters[Parameter.HIGHLIGHT_COLOR]) {
613
+ color = Parameter.parseColor(element.inheritedParameters[Parameter.HIGHLIGHT_COLOR]);
614
+ }
615
+ if (typeof element._highlightLayer !== 'undefined') {
616
+ addToHighlightLayer(element._highlightLayer, color, node);
617
+ }
618
+ });
619
+ } else if (highlighted === false) {
620
+ element.nodes.forEach(node => {
621
+ if (typeof element._highlightLayer !== 'undefined') {
622
+ removeFromHighlightLayer(element._highlightLayer, node);
623
+ }
624
+ });
625
+ }
626
+ },
627
+ ]);
628
+ this._parameterObservers.set(Parameter.CAST_SHADOW, [
629
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
630
+ let castShadow;
631
+ try {
632
+ castShadow = Parameter.parseBoolean(newValue);
633
+ } catch (e) {
634
+ return;
635
+ }
636
+ let lightCsl = element.inheritedParameters[Parameter.CAST_SHADOW_FROM_LIGHTS];
637
+ if (!lightCsl) {
638
+ lightCsl = element.variant.inheritedViewerLights.map(l => l.name).join(',');
639
+ }
640
+ if (castShadow === true) {
641
+ await this.castShadowValueHandler(lightCsl, addToShadowGenerator);
642
+ }
643
+ if (castShadow === false) {
644
+ await this.castShadowValueHandler(lightCsl, removeFromShadowGenerator);
645
+ }
646
+ },
647
+ ]);
648
+ this._parameterObservers.set(Parameter.CAST_SHADOW_FROM_LIGHTS, [
649
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
650
+ // TODO: Possible performance issue in combination with CAST_SHADOW, since both observers are initially called
651
+ // when CAST_SHADOW and CAST_SHADOW_FROM_LIGHTS are defined in the spec.
652
+ const lightCsl = element.variant.inheritedViewerLights.map(l => l.name).join(',');
653
+ // cleanup all shadow generators
654
+ await this.castShadowValueHandler(lightCsl, removeFromShadowGenerator);
655
+ if (element.castShadow === true) {
656
+ // if newValue is undefined or '' then set newValue to lightCsl (use all lights)
657
+ if (!newValue) {
658
+ newValue = lightCsl;
659
+ }
660
+ await this.castShadowValueHandler(newValue, addToShadowGenerator);
661
+ }
662
+ },
663
+ ]);
664
+ this._parameterObservers.set(Parameter.RECEIVE_SHADOWS, [
665
+ async (element: Element, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
666
+ element.nodes.forEach(node => setReceiveShadows(node, Parameter.parseBoolean(newValue)));
667
+ },
668
+ ]);
669
+ return this;
670
+ }
671
+
672
+ /**
673
+ * Filter for nodes that are not defined or excluded in the `pathDefinitions`.
674
+ */
675
+ protected filterNode(node: TransformNode): boolean {
676
+ let includeTokens: string[] = [];
677
+ this.pathDefinitions.include.forEach(dottedPath => {
678
+ includeTokens = union(includeTokens, DottedPath.create(dottedPath).leafTokens);
679
+ });
680
+ const shallKeep = (dp: DottedPath) => {
681
+ const isDirectlyIncluded = !!includeTokens.find(_dp => _dp === dp.path);
682
+ const isSubOfIncluded = !!this.pathDefinitions.include.find(_dp => {
683
+ return dp.path.startsWith(`${_dp}${DottedPath.DELIMITER}`);
684
+ });
685
+ return isDirectlyIncluded || isSubOfIncluded;
686
+ };
687
+ const shallExclude = (dp: DottedPath) => {
688
+ if (!this.pathDefinitions.exclude) {
689
+ return false;
690
+ }
691
+ return !!this.pathDefinitions.exclude.find(_dp => dp.path === _dp);
692
+ };
693
+ return shallKeep(node.metadata.dottedPath) && !shallExclude(node.metadata.dottedPath);
694
+ }
695
+
696
+ /**
697
+ * Asserts whether all {@link pathDefinitions} link to a valid `Node` path.
698
+ * @protected
699
+ */
700
+ protected assertPathDefinitions() {
701
+ const dottedNodes = this.variant.inheritedDottedNodes;
702
+ if (dottedNodes.size === 0) {
703
+ throw new Error(`There are no mapped nodes for element "${this.id}".`);
704
+ }
705
+ const include = this.pathDefinitions.include.map(path => DottedPath.create(path).path);
706
+ const exclude = this.pathDefinitions.exclude?.map(path => DottedPath.create(path).path);
707
+ const keys = Array.from(dottedNodes.keys()).map(dottedPath => dottedPath.path);
708
+ union<string>(include, exclude).forEach(path => {
709
+ if (keys.indexOf(path) === -1) {
710
+ throw new Error(`Node with path "${path}" does not exist for element "${this.id}".`);
711
+ }
712
+ });
713
+ }
714
+
715
+ /**
716
+ * Handles callback for given light parameter.
717
+ */
718
+ private async castShadowValueHandler(lightCsl: ParameterValue, mutator: CallableFunction) {
719
+ const lights: Light[] = [];
720
+ for (const lightName of Parameter.parseCommaSeparatedList(lightCsl)) {
721
+ const viewerLight = await this.variant.getViewerLight(lightName);
722
+ if (viewerLight) {
723
+ lights.push(viewerLight.light);
724
+ }
725
+ }
726
+ const shadowGenerators = lights.map(light => light?.getShadowGenerator() as ShadowGenerator).filter(Boolean);
727
+ shadowGenerators.forEach(generator => {
728
+ this.nodes.forEach(node => {
729
+ mutator(generator, node);
730
+ });
731
+ });
732
+ }
733
+ }