@combeenation/3d-viewer 3.1.1-alpha7 → 3.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 (94) 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 +1 -1
  4. package/dist/lib-cjs/api/classes/dottedPath.d.ts +79 -79
  5. package/dist/lib-cjs/api/classes/dottedPath.js +190 -190
  6. package/dist/lib-cjs/api/classes/element.d.ts +125 -126
  7. package/dist/lib-cjs/api/classes/element.js +678 -674
  8. package/dist/lib-cjs/api/classes/element.js.map +1 -1
  9. package/dist/lib-cjs/api/classes/elementParameterizable.d.ts +14 -14
  10. package/dist/lib-cjs/api/classes/elementParameterizable.js +134 -134
  11. package/dist/lib-cjs/api/classes/event.d.ts +312 -312
  12. package/dist/lib-cjs/api/classes/event.js +357 -357
  13. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  14. package/dist/lib-cjs/api/classes/eventBroadcaster.js +53 -53
  15. package/dist/lib-cjs/api/classes/parameter.d.ts +165 -165
  16. package/dist/lib-cjs/api/classes/parameter.js +267 -267
  17. package/dist/lib-cjs/api/classes/parameterObservable.d.ts +36 -36
  18. package/dist/lib-cjs/api/classes/parameterObservable.js +126 -126
  19. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  20. package/dist/lib-cjs/api/classes/parameterizable.js +149 -149
  21. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +38 -38
  22. package/dist/lib-cjs/api/classes/placementAnimation.js +138 -138
  23. package/dist/lib-cjs/api/classes/variant.d.ts +180 -190
  24. package/dist/lib-cjs/api/classes/variant.js +863 -873
  25. package/dist/lib-cjs/api/classes/variant.js.map +1 -1
  26. package/dist/lib-cjs/api/classes/variantInstance.d.ts +41 -41
  27. package/dist/lib-cjs/api/classes/variantInstance.js +98 -98
  28. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  29. package/dist/lib-cjs/api/classes/variantParameterizable.js +92 -92
  30. package/dist/lib-cjs/api/classes/viewer.d.ts +128 -128
  31. package/dist/lib-cjs/api/classes/viewer.js +486 -486
  32. package/dist/lib-cjs/api/classes/viewerLight.d.ts +65 -66
  33. package/dist/lib-cjs/api/classes/viewerLight.js +322 -389
  34. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  35. package/dist/lib-cjs/api/internal/debugViewer.d.ts +13 -13
  36. package/dist/lib-cjs/api/internal/debugViewer.js +87 -87
  37. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  38. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  39. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +6 -6
  40. package/dist/lib-cjs/api/internal/sceneSetup.js +227 -227
  41. package/dist/lib-cjs/api/manager/animationManager.d.ts +29 -29
  42. package/dist/lib-cjs/api/manager/animationManager.js +121 -121
  43. package/dist/lib-cjs/api/manager/sceneManager.d.ts +32 -32
  44. package/dist/lib-cjs/api/manager/sceneManager.js +132 -132
  45. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +90 -90
  46. package/dist/lib-cjs/api/manager/variantInstanceManager.js +321 -321
  47. package/dist/lib-cjs/api/store/specStorage.d.ts +24 -24
  48. package/dist/lib-cjs/api/store/specStorage.js +51 -51
  49. package/dist/lib-cjs/api/util/babylonHelper.d.ts +125 -125
  50. package/dist/lib-cjs/api/util/babylonHelper.js +368 -368
  51. package/dist/lib-cjs/api/util/globalTypes.d.ts +275 -275
  52. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  53. package/dist/lib-cjs/api/util/resourceHelper.d.ts +30 -30
  54. package/dist/lib-cjs/api/util/resourceHelper.js +247 -203
  55. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  56. package/dist/lib-cjs/api/util/stringHelper.d.ts +9 -9
  57. package/dist/lib-cjs/api/util/stringHelper.js +25 -25
  58. package/dist/lib-cjs/buildinfo.json +3 -3
  59. package/dist/lib-cjs/index.d.ts +46 -46
  60. package/dist/lib-cjs/index.js +82 -82
  61. package/dist/webpack-stats.json +0 -0
  62. package/package.json +83 -83
  63. package/src/api/classes/animationInterface.ts +11 -11
  64. package/src/api/classes/dottedPath.ts +189 -189
  65. package/src/api/classes/element.ts +608 -606
  66. package/src/api/classes/elementParameterizable.ts +78 -78
  67. package/src/api/classes/event.ts +355 -355
  68. package/src/api/classes/eventBroadcaster.ts +54 -54
  69. package/src/api/classes/parameter.ts +277 -277
  70. package/src/api/classes/parameterObservable.ts +121 -121
  71. package/src/api/classes/placementAnimation.ts +133 -133
  72. package/src/api/classes/variant.ts +659 -670
  73. package/src/api/classes/variantInstance.ts +81 -81
  74. package/src/api/classes/viewer.ts +421 -421
  75. package/src/api/internal/debugViewer.ts +81 -81
  76. package/src/api/internal/lensRendering.ts +10 -10
  77. package/src/api/internal/sceneSetup.ts +203 -203
  78. package/src/api/manager/animationManager.ts +116 -116
  79. package/src/api/manager/sceneManager.ts +105 -105
  80. package/src/api/manager/variantInstanceManager.ts +236 -236
  81. package/src/api/store/specStorage.ts +53 -53
  82. package/src/api/util/babylonHelper.ts +392 -392
  83. package/src/api/util/globalTypes.ts +314 -314
  84. package/src/api/util/resourceHelper.ts +168 -155
  85. package/src/buildinfo.json +2 -2
  86. package/src/commonjs.tsconfig.json +13 -13
  87. package/src/declaration.tsconfig.json +10 -10
  88. package/src/dev.ts +44 -46
  89. package/src/es6.tsconfig.json +13 -13
  90. package/src/index.ts +87 -87
  91. package/src/pagesconfig.json +47 -47
  92. package/src/tsconfig.json +43 -43
  93. package/src/tsconfig.types.json +9 -9
  94. package/src/types.d.ts +4 -4
@@ -1,606 +1,608 @@
1
- import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
2
- import { Material } from '@babylonjs/core/Materials/material';
3
- import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
4
- import { Axis, Space } from '@babylonjs/core/Maths/math.axis';
5
- import { Color3 } from '@babylonjs/core/Maths/math.color';
6
- import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
7
- import { InstancedMesh } from '@babylonjs/core/Meshes/instancedMesh';
8
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
9
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
10
- import { Texture } from '@babylonjs/core/Materials/Textures/texture';
11
- import { cloneDeep, concat, get, isArray, merge, union } from 'lodash-es';
12
- import {
13
- activateTransformNode as activate,
14
- addToHighlightLayer,
15
- assertTransformNode,
16
- cloneTransformNode,
17
- cloneTransformNodeMaterial,
18
- deactivateTransformNode as deactivate,
19
- getClientRectFromMesh,
20
- injectTransformNodeMetadata,
21
- mapToDottedNodes,
22
- removeFromHighlightLayer,
23
- setMaterial,
24
- setMaterialColor,
25
- setMaterialMetallness,
26
- setMaterialRoughness,
27
- setMaterialTexture
28
- } from '../util/babylonHelper';
29
- import { createImageUrlFromSvg, mergeMaps } from '../util/resourceHelper';
30
- import { DottedPath } from './dottedPath';
31
- import { ElementParameterizable } from './elementParameterizable';
32
- import { Event } from './event';
33
- import { Parameter } from './parameter';
34
- import { Variant } from './variant';
35
-
36
- /**
37
- * An {@link Element} of a {@link Variant}. Acts as a container for diverse definitions. Lives only in the context of a
38
- * {@link Variant}.
39
- *
40
- * When used in typings, refer to via its alias {@link VariantElement} to prevent name clashes with the web APIs
41
- * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) class
42
- */
43
- export class Element extends ElementParameterizable {
44
-
45
- protected readonly _dottedNodes: Map<DottedPath, TransformNode> = new Map();
46
-
47
- protected readonly _parameterObservers: Map<string, ParameterObserver[]> = new Map();
48
-
49
- protected _highlightLayer?: HighlightLayer;
50
-
51
- protected _paintableTextureId: number = 0;
52
-
53
- public readonly nodes: TransformNode[] = [];
54
-
55
- /**
56
- * Constructor.
57
- */
58
- public constructor( public readonly variant: Variant,
59
- public readonly name: string ) {
60
- super();
61
- if ( process.env.NODE_ENV?.toLowerCase().includes('dev')) {
62
- this.assertPathDefinitions();
63
- }
64
- const nodes = this.variant.inheritedNodes.map(
65
- node => cloneTransformNode( node, this.filterNode.bind(this) )
66
- );
67
- this.nodes = nodes.filter( node => !!node ) as TransformNode[];
68
- this._dottedNodes = mapToDottedNodes<TransformNode>(
69
- this.nodes,
70
- node => node instanceof TransformNode
71
- );
72
- this.addParameterObservers();
73
- }
74
-
75
- /**
76
- * The {@link DottedPath} in the built tree of {@link Element}s.
77
- * E.g. "_.top-1.sub-2.sub-sub-3.el-1"
78
- */
79
- get dottedPath(): DottedPath {
80
- return DottedPath.create( this.variant.dottedPath ).addPart( this.name );
81
- }
82
-
83
- /**
84
- * The id representing a {@link DottedPath}.
85
- */
86
- get id(): string {
87
- const dottedPath = DottedPath.create( this.dottedPath );
88
- dottedPath.shiftPart(); // remove root
89
- return dottedPath.path;
90
- }
91
-
92
- /**
93
- * The {@link ElementDefinition} of the {@link Element}.
94
- */
95
- get definition(): ElementDefinition {
96
- const definition = this.variant.structureJson.elements![this.name];
97
- if( isArray( definition ) ) {
98
- return {
99
- paths: {
100
- include: definition
101
- }
102
- } as ElementDefinition;
103
- }
104
- return definition as ElementDefinition;
105
- }
106
-
107
- /**
108
- * The {@link PathDefinitions} of the {@link Element}.
109
- */
110
- get pathDefinitions(): PathDefinitions {
111
- return this.definition.paths;
112
- }
113
-
114
- /**
115
- * The {@link TraceableDefinitions} of the {@link Element}.
116
- */
117
- get traceableDefinitions(): TraceableDefinitions {
118
- return this.definition.traceables || {};
119
- }
120
-
121
- /**
122
- * The {@link PaintableDefinition} of the {@link Element}.
123
- */
124
- get paintableDefinitions(): PaintableDefinitions {
125
- return this.definition.paintables || {};
126
- }
127
-
128
- /**
129
- * The inherited {@link ParameterBag}.
130
- * Merges the {@link Variant}'s parameters and those from the {@link Element}.
131
- */
132
- get inheritedParameters(): ParameterBag {
133
- return merge( {}, this.variant.inheritedParameters, this.parameters );
134
- }
135
-
136
- /**
137
- * @protected
138
- */
139
- set highlightLayer(layer: HighlightLayer | undefined) {
140
- this._highlightLayer = layer;
141
- }
142
-
143
- get highlightLayer(): HighlightLayer | undefined {
144
- return this._highlightLayer;
145
- }
146
-
147
- /**
148
- * Destroys this {@link Element} and dispose all nodes.
149
- */
150
- public destroy(): Element {
151
- this.nodes.forEach( node => {
152
- node.dispose();
153
- } );
154
- return this;
155
- }
156
-
157
- /**
158
- * Gets a node by its {@link DottedPath}.
159
- */
160
- public getNode( dottedPath: DottedPathArgument ): TransformNode {
161
- const _dottedPath = DottedPath.create( dottedPath );
162
- const keys = Array.from( this._dottedNodes.keys() ).map( dp => dp.path );
163
- const values = Array.from( this._dottedNodes.values() );
164
- const node = values[keys.indexOf( _dottedPath.path )];
165
- if( !node ) {
166
- throw new Error( `Node with path "${_dottedPath.path}" does not exist for element "${this.id}".` );
167
- }
168
- return node;
169
- }
170
-
171
- /**
172
- * Gets a mesh by its {@link DottedPath}.
173
- */
174
- public async getMesh( dottedPath: DottedPathArgument ): Promise<Mesh|null> {
175
- const node = await this.getNode( dottedPath );
176
- if( node instanceof Mesh ) {
177
- return node;
178
- }
179
- return null;
180
- }
181
-
182
- /**
183
- * Gets a {@link PaintableDefinition} by its name.
184
- */
185
- public getPaintableDefinition( name: string ): PaintableDefinition {
186
- if( !this.paintableDefinitions || !this.paintableDefinitions[name] ) {
187
- throw new Error( `No paintable "${name}" defined for element "${this.id}".` );
188
- }
189
- return this.paintableDefinitions[name];
190
- }
191
-
192
- /**
193
- * Gets a {@link TraceableDefinition} by its name.
194
- */
195
- public getTraceableDefinition( name: string ): TraceableDefinition {
196
- if( !this.traceableDefinitions || !this.traceableDefinitions[name] ) {
197
- throw new Error( `No traceable "${name}" defined to add observer in element "${this.id}".` );
198
- }
199
- return this.traceableDefinitions[name];
200
- }
201
-
202
- /**
203
- * Gets the paintable Node by its name.
204
- */
205
- public getPaintableNode( name: string ): TransformNode {
206
- return this.getNode( this.getPaintableDefinition( name ).path );
207
- }
208
-
209
- /**
210
- * Gets the traceable Node by its name.
211
- */
212
- public getTraceableNode( name: string ): TransformNode {
213
- return this.getNode( this.getTraceableDefinition( name ).path );
214
- }
215
-
216
- /**
217
- * Places the given {@link ParameterBag} in the {@link Element}'s parameters, replaces all patterns in the
218
- * {@link StructureJson} and broadcasts all {@link ParameterObserver}s.
219
- *
220
- * @emit {@link Event.ELEMENT_PARAMETER_COMMITTED}
221
- */
222
- public async commitParameters( parameters?: ParameterBag ): Promise<Element> {
223
- if( !parameters ) {
224
- parameters = {};
225
- }
226
- const oldParameters = cloneDeep( this.parameters );
227
- merge( this.parameters, parameters );
228
- // handle parameter observers
229
- let observerPromises: Promise<void | ParameterObserver>[] = [];
230
- for( const parameter in this.parameters ) {
231
- const oldParameterValue = oldParameters[parameter];
232
- const newParameterValue = this.parameters[parameter];
233
- this.variant.assertParameter( this.variant.inheritedParameterDeclaration, parameter, newParameterValue );
234
- if( oldParameterValue === newParameterValue ) {
235
- continue;
236
- }
237
- // parameter changed
238
- const parameterObservers = mergeMaps( this._parameterObservers, this.parameterObservers );
239
- if( parameterObservers.has( parameter ) ) {
240
- const observers = parameterObservers.get( parameter )!;
241
- observerPromises = concat(observerPromises, observers.map( observer => {
242
- const observerResult = observer( this, oldParameterValue, newParameterValue );
243
- return Promise.resolve( observerResult ).then( () => {
244
- this.broadcastEvent( Event.ELEMENT_PARAMETER_COMMITTED,
245
- this, parameter, oldParameterValue, newParameterValue );
246
- } );
247
- } ) );
248
- }
249
- }
250
- await Promise.all( observerPromises );
251
- return this;
252
- }
253
-
254
- /**
255
- * Adds an observer function for camera matrix changes.
256
- * The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
257
- */
258
- public addTraceableObserver( traceable: string, observer: CallableFunction, payload?: any ): Element {
259
- if( payload && !(payload instanceof HTMLElement) ) {
260
- throw new Error( `Payload for camera observer must be an instance of "HTMLElement" in element "${this.id}".` );
261
- }
262
- if( !this.traceableDefinitions || !this.traceableDefinitions[traceable] ) {
263
- throw new Error( `No traceable "${traceable}" defined to add observer in element "${this.id}".` );
264
- }
265
- const node = this.getTraceableNode( traceable );
266
- if( !(node instanceof AbstractMesh) ) {
267
- throw new Error( `The path must be an instance of "AbstractMesh" for camera observer in element "${this.id}".` );
268
- }
269
- this.variant.viewer.sceneManager.activeCamera.onViewMatrixChangedObservable.add(
270
- ( eventData, eventState ) => {
271
- const position = getClientRectFromMesh( node, this.variant.viewer.scene, this.variant.viewer.canvas );
272
- if( payload ) {
273
- payload.style.top = `${position.top}px`;
274
- payload.style.left = `${position.left}px`;
275
- }
276
- observer( node, position );
277
- }
278
- );
279
- return this;
280
- }
281
-
282
- /**
283
- * Draws a image onto a `paintable` defined via {@link PaintableDefinition}.
284
- */
285
- public async drawPaintable( paintable: string, imageSource: string ): Promise<Element> {
286
- const node = this.getPaintableNode( paintable );
287
- if( !(node instanceof AbstractMesh) ) {
288
- throw new Error( `The path must be an instance of "AbstractMesh" for paintable "${paintable}" ` +
289
- `in element "${this.id}".` );
290
- }
291
- if( node.material && !get( node.metadata, 'dirty.material' ) ) {
292
- cloneTransformNodeMaterial( node );
293
- }
294
- if( !node.material ) {
295
- node.material = new StandardMaterial( `${this.id}.${paintable}.material`, this.variant.viewer.scene );
296
- }
297
- node.material.transparencyMode = Material.MATERIAL_ALPHATESTANDBLEND;
298
- if( !get( node.metadata, 'dirty.material.texture' ) ) {
299
- // inject initial value and mark as dirty
300
- injectTransformNodeMetadata( node, { dirty: { material: { texture: true } } }, false );
301
- }
302
-
303
- await new Promise<void>(resolve => {
304
- const paintableTexture = Texture.CreateFromBase64String(
305
- imageSource,
306
- `${this.id}.${paintable}.texture.${this._paintableTextureId}`,
307
- this.variant.viewer.scene,
308
- undefined,
309
- false,
310
- undefined,
311
- () => {
312
- setMaterialTexture( node, paintableTexture, false );
313
- resolve();
314
- }
315
- );
316
-
317
- // NOTE: Paintable texture need an individual id, otherwise the already existing texture on this id does not get overwritten
318
- // Maybe think of a disposal logic here in the future
319
- this._paintableTextureId++;
320
- });
321
-
322
- return this;
323
- }
324
-
325
- /**
326
- * Draws a SVG string onto a `paintable` defined via {@link PaintableDefinition}.
327
- */
328
- public async drawPaintableFromSvg( paintable: string, svgSource: string ): Promise<Element> {
329
- const imageUrl = await createImageUrlFromSvg( svgSource );
330
- return this.drawPaintable( paintable, imageUrl );
331
- }
332
-
333
- /**
334
- * Draws an Image from source (URL/URI) onto a `paintable` defined via {@link PaintableDefinition}.
335
- */
336
- public async drawPaintableFromImgSrc( paintable: string, imgSource: string ): Promise<Element> {
337
- return this.drawPaintable( paintable, imgSource );
338
- }
339
-
340
- /**
341
- * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
342
- */
343
- protected addParameterObservers(): Element {
344
- this._parameterObservers.set( Parameter.VISIBLE, [
345
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
346
- let visible;
347
- try {
348
- visible = Parameter.parseBoolean( newValue );
349
- } catch( e ) {
350
- return;
351
- }
352
- if( visible === true ) {
353
- element.nodes.forEach( node => {
354
- injectTransformNodeMetadata( node, { visibility: node.isEnabled() } );
355
- activate( node );
356
- } );
357
- } else if( visible === false ) {
358
- element.nodes.forEach( node => {
359
- injectTransformNodeMetadata( node, { visibility: node.isEnabled() } );
360
- deactivate( node );
361
- } );
362
- }
363
- }
364
- ] );
365
- this._parameterObservers.set( Parameter.SCALING, [
366
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
367
- // we have to deal just with root nodes here due to relative impacts in a node tree
368
- element.nodes.forEach( node => node.scaling = Parameter.parseScaling( newValue ) );
369
- }
370
- ] );
371
- this._parameterObservers.set( Parameter.MATERIAL, [
372
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
373
- const material = element.variant.getMaterial( newValue.toString() );
374
- element.nodes.forEach( node => {
375
- assertTransformNode(node, (node: TransformNode) => {
376
- if( node instanceof InstancedMesh ) {
377
- throw new Error( `Changing parameter "${Parameter.MATERIAL}" ` +
378
- `of an InstancedMesh is not supported. ` +
379
- `Tried to change node "${node.id}" on element "${element.id}".` );
380
- }
381
- });
382
- setMaterial( node, material );
383
- } );
384
- }
385
- ] );
386
- this._parameterObservers.set( Parameter.MATERIAL_COLOR, [
387
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
388
- const color = Parameter.parseColor( newValue );
389
- element.nodes.forEach( node => {
390
- assertTransformNode(node, (node: TransformNode) => {
391
- if( node instanceof InstancedMesh ) {
392
- throw new Error( `Changing parameter "${Parameter.MATERIAL_COLOR}" ` +
393
- `of an InstancedMesh is not supported. ` +
394
- `Tried to change node "${node.id}" on element "${element.id}".` );
395
- }
396
- });
397
- if( !get( node.metadata, 'dirty.material' ) ) {
398
- cloneTransformNodeMaterial( node );
399
- }
400
- if( !get( node.metadata, 'dirty.material.color' ) ) {
401
- // inject initial value and mark as dirty
402
- injectTransformNodeMetadata( node, { dirty: { material: { color: oldValue } } } );
403
- }
404
- setMaterialColor( node, color );
405
- } );
406
- }
407
- ] );
408
- this._parameterObservers.set( Parameter.MATERIAL_METALLNESS, [
409
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
410
- const metallness = Parameter.parseNumber( newValue );
411
- element.nodes.forEach( node => {
412
- assertTransformNode(node, (node: TransformNode) => {
413
- if( node instanceof InstancedMesh ) {
414
- throw new Error( `Changing parameter "${Parameter.MATERIAL_METALLNESS}" ` +
415
- `of an InstancedMesh is not supported. ` +
416
- `Tried to change node "${node.id}" on element "${element.id}".` );
417
- }
418
- });
419
- if( !get( node.metadata, 'dirty.material' ) ) {
420
- cloneTransformNodeMaterial( node );
421
- }
422
- if( !get( node.metadata, 'dirty.material.metallness' ) ) {
423
- // inject initial value and mark as dirty
424
- injectTransformNodeMetadata( node, { dirty: { material: { metallness: oldValue } } } );
425
- }
426
- setMaterialMetallness( node, metallness );
427
- } );
428
- }
429
- ] );
430
- this._parameterObservers.set( Parameter.MATERIAL_ROUGHNESS, [
431
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
432
- const roughness = Parameter.parseNumber( newValue );
433
- element.nodes.forEach( node => {
434
- assertTransformNode(node, (node: TransformNode) => {
435
- if( node instanceof InstancedMesh ) {
436
- throw new Error( `Changing parameter "${Parameter.MATERIAL_ROUGHNESS}" ` +
437
- `of an InstancedMesh is not supported. ` +
438
- `Tried to change node "${node.id}" on element "${element.id}".` );
439
- }
440
- });
441
- if( !get( node.metadata, 'dirty.material' ) ) {
442
- cloneTransformNodeMaterial( node );
443
- }
444
- if( !get( node.metadata, 'dirty.material.roughness' ) ) {
445
- // inject initial value and mark as dirty
446
- injectTransformNodeMetadata( node, { dirty: { material: { roughness: oldValue } } } );
447
- }
448
- setMaterialRoughness( node, roughness );
449
- } );
450
- }
451
- ] );
452
- this._parameterObservers.set( Parameter.HIGHLIGHT_COLOR, [
453
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
454
- // trigger Parameter.HIGHLIGHTED observers
455
- this._parameterObservers.get( Parameter.HIGHLIGHTED )?.forEach( observer => {
456
- observer( element, !!element.highlighted, !!element.highlighted );
457
- } );
458
- }
459
- ] );
460
- this._parameterObservers.set( Parameter.HIGHLIGHT_ENABLED, [
461
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
462
- let curr;
463
- try {
464
- curr = Parameter.parseBoolean( newValue );
465
- } catch( e ) {
466
- return;
467
- }
468
- switch( curr ) {
469
- case true:
470
- if( element._highlightLayer ) {
471
- break;
472
- }
473
- element.highlightLayer = new HighlightLayer(
474
- DottedPath.create( element.id ).addPart( 'highlight' ).path,
475
- element.variant.viewer.scene
476
- );
477
- break;
478
- case false:
479
- element.highlightLayer?.dispose();
480
- break;
481
- }
482
- }
483
- ] );
484
- this._parameterObservers.set( Parameter.HIGHLIGHTED, [
485
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
486
- if( !element.inheritedParameters[Parameter.HIGHLIGHT_ENABLED] ) {
487
- return;
488
- }
489
- // trigger Parameter.HIGHLIGHT_ENABLED observers to ensure HighlightLayer
490
- this._parameterObservers.get( Parameter.HIGHLIGHT_ENABLED )?.forEach( observer => {
491
- observer( element, this.parameters[Parameter.HIGHLIGHT_ENABLED], true );
492
- } );
493
- let highlighted;
494
- try {
495
- highlighted = Parameter.parseBoolean( newValue );
496
- } catch( e ) {
497
- return;
498
- }
499
- // Add/Remove meshes to previously created highlight layers.
500
- if( highlighted === true ) {
501
- element.nodes.forEach( node => {
502
- assertTransformNode(node, (node: TransformNode) => {
503
- if( node instanceof InstancedMesh ) {
504
- throw new Error( `Changing parameter "${Parameter.HIGHLIGHTED}" ` +
505
- `of an InstancedMesh is not supported. ` +
506
- `Tried to change node "${node.id}" on element "${element.id}".` );
507
- }
508
- });
509
- let color = Color3.Green();
510
- if( element.inheritedParameters[Parameter.HIGHLIGHT_COLOR] ) {
511
- color = Parameter.parseColor( element.inheritedParameters[Parameter.HIGHLIGHT_COLOR] );
512
- }
513
- if ( typeof element._highlightLayer !== "undefined" ) {
514
- addToHighlightLayer( element._highlightLayer, color, node );
515
- }
516
- } );
517
- } else if( highlighted === false ) {
518
- element.nodes.forEach( node => {
519
- if ( typeof element._highlightLayer !== "undefined" ) {
520
- removeFromHighlightLayer( element._highlightLayer, node );
521
- }
522
- } );
523
- }
524
- }
525
- ] );
526
- this._parameterObservers.set( Parameter.POSITION, [
527
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
528
- // we have to deal just with root nodes here due to relative impacts in a node tree
529
- element.nodes.forEach( node => {
530
- // remember absolute position and reset it before translating
531
- if( !get( node.metadata, 'position' ) ) {
532
- node.metadata.position = node.absolutePosition.clone();
533
- }
534
- node.setAbsolutePosition( node.metadata.position );
535
- // move
536
- const distance = Parameter.parseVector( newValue );
537
- node.translate( Axis.X, distance.x, Space.WORLD );
538
- node.translate( Axis.Y, distance.y, Space.WORLD );
539
- node.translate( Axis.Z, distance.z, Space.WORLD );
540
- } );
541
- }
542
- ] );
543
- this._parameterObservers.set( Parameter.ROTATION, [
544
- async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
545
- // we have to deal just with root nodes here due to relative impacts in a node tree
546
- element.nodes.forEach( node => {
547
- // remember absolute rotation and reset it before translating
548
- if(!get( node.metadata, 'rotation' ) ) {
549
- node.metadata.rotation = node.rotation.clone();
550
- }
551
- node.rotation = node.metadata.rotation;
552
- // rotate
553
- const rotation = Parameter.parseRotation( newValue );
554
- node.rotate( Axis.X, rotation.x, Space.WORLD );
555
- node.rotate( Axis.Y, rotation.y, Space.WORLD );
556
- node.rotate( Axis.Z, rotation.z, Space.WORLD );
557
- } );
558
- }
559
- ] );
560
- return this;
561
- }
562
-
563
- /**
564
- * Filter for nodes that are not defined or excluded in the `pathDefinitions`.
565
- */
566
- protected filterNode( node: TransformNode ): boolean {
567
- let includeTokens: string[] = [];
568
- this.pathDefinitions.include.forEach( dottedPath => {
569
- includeTokens = union( includeTokens, DottedPath.create( dottedPath ).leafTokens );
570
- } );
571
- const shallKeep = ( dp: DottedPath ) => {
572
- const isDirectlyIncluded = !!includeTokens.find( _dp => _dp === dp.path );
573
- const isSubOfIncluded = !!this.pathDefinitions.include.find( _dp => {
574
- return dp.path.startsWith( `${_dp}${DottedPath.DELIMITER}` );
575
- } );
576
- return isDirectlyIncluded || isSubOfIncluded;
577
- };
578
- const shallExclude = ( dp: DottedPath ) => {
579
- if( !this.pathDefinitions.exclude ) {
580
- return false;
581
- }
582
- return !!this.pathDefinitions.exclude.find( _dp => dp.path === _dp );
583
- };
584
- return shallKeep( node.metadata.dottedPath ) && !shallExclude( node.metadata.dottedPath );
585
- }
586
-
587
- /**
588
- * Asserts whether all {@link pathDefinitions} link to a valid `Node` path.
589
- * @protected
590
- */
591
- protected assertPathDefinitions() {
592
- const dottedNodes = this.variant.inheritedDottedNodes;
593
- if( dottedNodes.size === 0 ) {
594
- throw new Error( `There are no mapped nodes for element "${this.id}".` );
595
- }
596
- const include = this.pathDefinitions.include.map( path => DottedPath.create( path ).path );
597
- const exclude = this.pathDefinitions.exclude?.map( path => DottedPath.create( path ).path );
598
- const keys = Array.from( dottedNodes.keys() ).map( dottedPath => dottedPath.path );
599
- union<string>( include, exclude ).forEach( path => {
600
- if( keys.indexOf( path ) === -1 ) {
601
- throw new Error( `Node with path "${path}" does not exist for element "${this.id}".` );
602
- }
603
- } );
604
- }
605
-
606
- }
1
+ import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
2
+ import { Material } from '@babylonjs/core/Materials/material';
3
+ import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
4
+ import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
5
+ import { Axis, Space } from '@babylonjs/core/Maths/math.axis';
6
+ import { Color3 } from '@babylonjs/core/Maths/math.color';
7
+ import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
8
+ import { InstancedMesh } from '@babylonjs/core/Meshes/instancedMesh';
9
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
10
+ import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
11
+ import { cloneDeep, concat, get, isArray, isNumber, isPlainObject, merge, union } from 'lodash-es';
12
+ import {
13
+ activateTransformNode as activate,
14
+ addToHighlightLayer,
15
+ assertTransformNode,
16
+ cloneTransformNode,
17
+ cloneTransformNodeMaterial,
18
+ deactivateTransformNode as deactivate,
19
+ getClientRectFromMesh,
20
+ injectTransformNodeMetadata,
21
+ mapToDottedNodes,
22
+ removeFromHighlightLayer,
23
+ setMaterial,
24
+ setMaterialColor,
25
+ setMaterialMetallness,
26
+ setMaterialRoughness,
27
+ setMaterialTexture
28
+ } from '../util/babylonHelper';
29
+ import { createImageBitmapFromImgSrc, createImageBitmapFromSvg, mergeMaps } from '../util/resourceHelper';
30
+ import { DottedPath } from './dottedPath';
31
+ import { ElementParameterizable } from './elementParameterizable';
32
+ import { Event } from './event';
33
+ import { Parameter } from './parameter';
34
+ import { Variant } from './variant';
35
+
36
+ /**
37
+ * An {@link Element} of a {@link Variant}. Acts as a container for diverse definitions. Lives only in the context of a
38
+ * {@link Variant}.
39
+ *
40
+ * When used in typings, refer to via its alias {@link VariantElement} to prevent name clashes with the web APIs
41
+ * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) class
42
+ */
43
+ export class Element extends ElementParameterizable {
44
+
45
+ protected readonly _dottedNodes: Map<DottedPath, TransformNode> = new Map();
46
+
47
+ protected readonly _parameterObservers: Map<string, ParameterObserver[]> = new Map();
48
+
49
+ protected _highlightLayer?: HighlightLayer;
50
+
51
+ public readonly nodes: TransformNode[] = [];
52
+
53
+ /**
54
+ * Constructor.
55
+ */
56
+ public constructor( public readonly variant: Variant,
57
+ public readonly name: string ) {
58
+ super();
59
+ if ( process.env.NODE_ENV?.toLowerCase().includes('dev')) {
60
+ this.assertPathDefinitions();
61
+ }
62
+ const nodes = this.variant.inheritedNodes.map(
63
+ node => cloneTransformNode( node, this.filterNode.bind(this) )
64
+ );
65
+ this.nodes = nodes.filter( node => !!node ) as TransformNode[];
66
+ this._dottedNodes = mapToDottedNodes<TransformNode>(
67
+ this.nodes,
68
+ node => node instanceof TransformNode
69
+ );
70
+ this.addParameterObservers();
71
+ }
72
+
73
+ /**
74
+ * The {@link DottedPath} in the built tree of {@link Element}s.
75
+ * E.g. "_.top-1.sub-2.sub-sub-3.el-1"
76
+ */
77
+ get dottedPath(): DottedPath {
78
+ return DottedPath.create( this.variant.dottedPath ).addPart( this.name );
79
+ }
80
+
81
+ /**
82
+ * The id representing a {@link DottedPath}.
83
+ */
84
+ get id(): string {
85
+ const dottedPath = DottedPath.create( this.dottedPath );
86
+ dottedPath.shiftPart(); // remove root
87
+ return dottedPath.path;
88
+ }
89
+
90
+ /**
91
+ * The {@link ElementDefinition} of the {@link Element}.
92
+ */
93
+ get definition(): ElementDefinition {
94
+ const definition = this.variant.structureJson.elements![this.name];
95
+ if( isArray( definition ) ) {
96
+ return {
97
+ paths: {
98
+ include: definition
99
+ }
100
+ } as ElementDefinition;
101
+ }
102
+ return definition as ElementDefinition;
103
+ }
104
+
105
+ /**
106
+ * The {@link PathDefinitions} of the {@link Element}.
107
+ */
108
+ get pathDefinitions(): PathDefinitions {
109
+ return this.definition.paths;
110
+ }
111
+
112
+ /**
113
+ * The {@link TraceableDefinitions} of the {@link Element}.
114
+ */
115
+ get traceableDefinitions(): TraceableDefinitions {
116
+ return this.definition.traceables || {};
117
+ }
118
+
119
+ /**
120
+ * The {@link PaintableDefinition} of the {@link Element}.
121
+ */
122
+ get paintableDefinitions(): PaintableDefinitions {
123
+ return this.definition.paintables || {};
124
+ }
125
+
126
+ /**
127
+ * The inherited {@link ParameterBag}.
128
+ * Merges the {@link Variant}'s parameters and those from the {@link Element}.
129
+ */
130
+ get inheritedParameters(): ParameterBag {
131
+ return merge( {}, this.variant.inheritedParameters, this.parameters );
132
+ }
133
+
134
+ /**
135
+ * @protected
136
+ */
137
+ set highlightLayer(layer: HighlightLayer | undefined) {
138
+ this._highlightLayer = layer;
139
+ }
140
+
141
+ get highlightLayer(): HighlightLayer | undefined {
142
+ return this._highlightLayer;
143
+ }
144
+
145
+ /**
146
+ * Destroys this {@link Element} and dispose all nodes.
147
+ */
148
+ public destroy(): Element {
149
+ this.nodes.forEach( node => {
150
+ node.dispose();
151
+ } );
152
+ return this;
153
+ }
154
+
155
+ /**
156
+ * Gets a node by its {@link DottedPath}.
157
+ */
158
+ public getNode( dottedPath: DottedPathArgument ): TransformNode {
159
+ const _dottedPath = DottedPath.create( dottedPath );
160
+ const keys = Array.from( this._dottedNodes.keys() ).map( dp => dp.path );
161
+ const values = Array.from( this._dottedNodes.values() );
162
+ const node = values[keys.indexOf( _dottedPath.path )];
163
+ if( !node ) {
164
+ throw new Error( `Node with path "${_dottedPath.path}" does not exist for element "${this.id}".` );
165
+ }
166
+ return node;
167
+ }
168
+
169
+ /**
170
+ * Gets a mesh by its {@link DottedPath}.
171
+ */
172
+ public async getMesh( dottedPath: DottedPathArgument ): Promise<Mesh|null> {
173
+ const node = await this.getNode( dottedPath );
174
+ if( node instanceof Mesh ) {
175
+ return node;
176
+ }
177
+ return null;
178
+ }
179
+
180
+ /**
181
+ * Gets a {@link PaintableDefinition} by its name.
182
+ */
183
+ public getPaintableDefinition( name: string ): PaintableDefinition {
184
+ if( !this.paintableDefinitions || !this.paintableDefinitions[name] ) {
185
+ throw new Error( `No paintable "${name}" defined for element "${this.id}".` );
186
+ }
187
+ return this.paintableDefinitions[name];
188
+ }
189
+
190
+ /**
191
+ * Gets a {@link TraceableDefinition} by its name.
192
+ */
193
+ public getTraceableDefinition( name: string ): TraceableDefinition {
194
+ if( !this.traceableDefinitions || !this.traceableDefinitions[name] ) {
195
+ throw new Error( `No traceable "${name}" defined to add observer in element "${this.id}".` );
196
+ }
197
+ return this.traceableDefinitions[name];
198
+ }
199
+
200
+ /**
201
+ * Gets the paintable Node by its name.
202
+ */
203
+ public getPaintableNode( name: string ): TransformNode {
204
+ return this.getNode( this.getPaintableDefinition( name ).path );
205
+ }
206
+
207
+ /**
208
+ * Gets the traceable Node by its name.
209
+ */
210
+ public getTraceableNode( name: string ): TransformNode {
211
+ return this.getNode( this.getTraceableDefinition( name ).path );
212
+ }
213
+
214
+ /**
215
+ * Places the given {@link ParameterBag} in the {@link Element}'s parameters, replaces all patterns in the
216
+ * {@link StructureJson} and broadcasts all {@link ParameterObserver}s.
217
+ *
218
+ * @emit {@link Event.ELEMENT_PARAMETER_COMMITTED}
219
+ */
220
+ public async commitParameters( parameters?: ParameterBag ): Promise<Element> {
221
+ if( !parameters ) {
222
+ parameters = {};
223
+ }
224
+ const oldParameters = cloneDeep( this.parameters );
225
+ merge( this.parameters, parameters );
226
+ // handle parameter observers
227
+ let observerPromises: Promise<void | ParameterObserver>[] = [];
228
+ for( const parameter in this.parameters ) {
229
+ const oldParameterValue = oldParameters[parameter];
230
+ const newParameterValue = this.parameters[parameter];
231
+ this.variant.assertParameter( this.variant.inheritedParameterDeclaration, parameter, newParameterValue );
232
+ if( oldParameterValue === newParameterValue ) {
233
+ continue;
234
+ }
235
+ // parameter changed
236
+ const parameterObservers = mergeMaps( this._parameterObservers, this.parameterObservers );
237
+ if( parameterObservers.has( parameter ) ) {
238
+ const observers = parameterObservers.get( parameter )!;
239
+ observerPromises = concat(observerPromises, observers.map( observer => {
240
+ const observerResult = observer( this, oldParameterValue, newParameterValue );
241
+ return Promise.resolve( observerResult ).then( () => {
242
+ this.broadcastEvent( Event.ELEMENT_PARAMETER_COMMITTED,
243
+ this, parameter, oldParameterValue, newParameterValue );
244
+ } );
245
+ } ) );
246
+ }
247
+ }
248
+ await Promise.all( observerPromises );
249
+ return this;
250
+ }
251
+
252
+ /**
253
+ * Adds an observer function for camera matrix changes.
254
+ * The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
255
+ */
256
+ public addTraceableObserver( traceable: string, observer: CallableFunction, payload?: any ): Element {
257
+ if( payload && !(payload instanceof HTMLElement) ) {
258
+ throw new Error( `Payload for camera observer must be an instance of "HTMLElement" in element "${this.id}".` );
259
+ }
260
+ if( !this.traceableDefinitions || !this.traceableDefinitions[traceable] ) {
261
+ throw new Error( `No traceable "${traceable}" defined to add observer in element "${this.id}".` );
262
+ }
263
+ const node = this.getTraceableNode( traceable );
264
+ if( !(node instanceof AbstractMesh) ) {
265
+ throw new Error( `The path must be an instance of "AbstractMesh" for camera observer in element "${this.id}".` );
266
+ }
267
+ this.variant.viewer.sceneManager.activeCamera.onViewMatrixChangedObservable.add(
268
+ ( eventData, eventState ) => {
269
+ const position = getClientRectFromMesh( node, this.variant.viewer.scene, this.variant.viewer.canvas );
270
+ if( payload ) {
271
+ payload.style.top = `${position.top}px`;
272
+ payload.style.left = `${position.left}px`;
273
+ }
274
+ observer( node, position );
275
+ }
276
+ );
277
+ return this;
278
+ }
279
+
280
+ /**
281
+ * Draws a `ImageBitmap` or `OffscreenCanvas` onto a `paintable` defined via {@link PaintableDefinition}.
282
+ */
283
+ public drawPaintable( paintable: string, imageSource: CanvasImageSource ): Element {
284
+ const paintableDefinition = this.getPaintableDefinition( paintable );
285
+ const node = this.getPaintableNode( paintable );
286
+ if( !(node instanceof AbstractMesh) ) {
287
+ throw new Error( `The path must be an instance of "AbstractMesh" for paintable "${paintable}" ` +
288
+ `in element "${this.id}".` );
289
+ }
290
+ if( node.material && !get( node.metadata, 'dirty.material' ) ) {
291
+ cloneTransformNodeMaterial( node );
292
+ }
293
+ if( !node.material ) {
294
+ node.material = new StandardMaterial( `${this.id}.${paintable}.material`, this.variant.viewer.scene );
295
+ }
296
+ node.material.transparencyMode = Material.MATERIAL_ALPHATESTANDBLEND;
297
+ if( !get( node.metadata, 'dirty.material.texture' ) ) {
298
+ // inject initial value and mark as dirty
299
+ injectTransformNodeMetadata( node, { dirty: { material: { texture: true } } } );
300
+ }
301
+ const widthAndHeight = {
302
+ width: imageSource.width,
303
+ height: imageSource.height
304
+ };
305
+ if( isNumber( paintableDefinition.textureOptions ) ) {
306
+ widthAndHeight.width = paintableDefinition.textureOptions;
307
+ widthAndHeight.height = paintableDefinition.textureOptions;
308
+ } else if( isPlainObject( paintableDefinition.textureOptions ) ) {
309
+ widthAndHeight.width = paintableDefinition.textureOptions.width;
310
+ widthAndHeight.height = paintableDefinition.textureOptions.height;
311
+ }
312
+ const texture = new DynamicTexture(
313
+ `${this.id}.${paintable}.texture`,
314
+ widthAndHeight,
315
+ this.variant.viewer.scene,
316
+ false
317
+ );
318
+ setMaterialTexture( node, texture, false );
319
+ const ctx = texture.getContext();
320
+ // flip texture context horizontal with translate and scale
321
+ ctx.drawImage( imageSource, 0, 0);
322
+ texture.update( false );
323
+ return this;
324
+ }
325
+
326
+ /**
327
+ * Draws a SVG string onto a `paintable` defined via {@link PaintableDefinition}.
328
+ */
329
+ public async drawPaintableFromSvg( paintable: string, svgSource: string ): Promise<Element> {
330
+ const source = await createImageBitmapFromSvg( svgSource );
331
+ return this.drawPaintable( paintable, source );
332
+ }
333
+
334
+ /**
335
+ * Draws an Image from source (URL/URI) onto a `paintable` defined via {@link PaintableDefinition}.
336
+ */
337
+ public async drawPaintableFromImgSrc( paintable: string, imgSource: string ): Promise<Element> {
338
+ const source = await createImageBitmapFromImgSrc( imgSource );
339
+ return this.drawPaintable( paintable, source );
340
+ }
341
+
342
+ /**
343
+ * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
344
+ */
345
+ protected addParameterObservers(): Element {
346
+ this._parameterObservers.set( Parameter.VISIBLE, [
347
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
348
+ let visible;
349
+ try {
350
+ visible = Parameter.parseBoolean( newValue );
351
+ } catch( e ) {
352
+ return;
353
+ }
354
+ if( visible === true ) {
355
+ element.nodes.forEach( node => {
356
+ injectTransformNodeMetadata( node, { visibility: node.isEnabled() } );
357
+ activate( node );
358
+ } );
359
+ } else if( visible === false ) {
360
+ element.nodes.forEach( node => {
361
+ injectTransformNodeMetadata( node, { visibility: node.isEnabled() } );
362
+ deactivate( node );
363
+ } );
364
+ }
365
+ }
366
+ ] );
367
+ this._parameterObservers.set( Parameter.SCALING, [
368
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
369
+ // we have to deal just with root nodes here due to relative impacts in a node tree
370
+ element.nodes.forEach( node => node.scaling = Parameter.parseScaling( newValue ) );
371
+ }
372
+ ] );
373
+ this._parameterObservers.set( Parameter.MATERIAL, [
374
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
375
+ const material = element.variant.getMaterial( newValue.toString() );
376
+ element.nodes.forEach( node => {
377
+ assertTransformNode(node, (node: TransformNode) => {
378
+ if( node instanceof InstancedMesh ) {
379
+ throw new Error( `Changing parameter "${Parameter.MATERIAL}" ` +
380
+ `of an InstancedMesh is not supported. ` +
381
+ `Tried to change node "${node.id}" on element "${element.id}".` );
382
+ }
383
+ });
384
+ setMaterial( node, material );
385
+ } );
386
+ }
387
+ ] );
388
+ this._parameterObservers.set( Parameter.MATERIAL_COLOR, [
389
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
390
+ const color = Parameter.parseColor( newValue );
391
+ element.nodes.forEach( node => {
392
+ assertTransformNode(node, (node: TransformNode) => {
393
+ if( node instanceof InstancedMesh ) {
394
+ throw new Error( `Changing parameter "${Parameter.MATERIAL_COLOR}" ` +
395
+ `of an InstancedMesh is not supported. ` +
396
+ `Tried to change node "${node.id}" on element "${element.id}".` );
397
+ }
398
+ });
399
+ if( !get( node.metadata, 'dirty.material' ) ) {
400
+ cloneTransformNodeMaterial( node );
401
+ }
402
+ if( !get( node.metadata, 'dirty.material.color' ) ) {
403
+ // inject initial value and mark as dirty
404
+ injectTransformNodeMetadata( node, { dirty: { material: { color: oldValue } } } );
405
+ }
406
+ setMaterialColor( node, color );
407
+ } );
408
+ }
409
+ ] );
410
+ this._parameterObservers.set( Parameter.MATERIAL_METALLNESS, [
411
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
412
+ const metallness = Parameter.parseNumber( newValue );
413
+ element.nodes.forEach( node => {
414
+ assertTransformNode(node, (node: TransformNode) => {
415
+ if( node instanceof InstancedMesh ) {
416
+ throw new Error( `Changing parameter "${Parameter.MATERIAL_METALLNESS}" ` +
417
+ `of an InstancedMesh is not supported. ` +
418
+ `Tried to change node "${node.id}" on element "${element.id}".` );
419
+ }
420
+ });
421
+ if( !get( node.metadata, 'dirty.material' ) ) {
422
+ cloneTransformNodeMaterial( node );
423
+ }
424
+ if( !get( node.metadata, 'dirty.material.metallness' ) ) {
425
+ // inject initial value and mark as dirty
426
+ injectTransformNodeMetadata( node, { dirty: { material: { metallness: oldValue } } } );
427
+ }
428
+ setMaterialMetallness( node, metallness );
429
+ } );
430
+ }
431
+ ] );
432
+ this._parameterObservers.set( Parameter.MATERIAL_ROUGHNESS, [
433
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
434
+ const roughness = Parameter.parseNumber( newValue );
435
+ element.nodes.forEach( node => {
436
+ assertTransformNode(node, (node: TransformNode) => {
437
+ if( node instanceof InstancedMesh ) {
438
+ throw new Error( `Changing parameter "${Parameter.MATERIAL_ROUGHNESS}" ` +
439
+ `of an InstancedMesh is not supported. ` +
440
+ `Tried to change node "${node.id}" on element "${element.id}".` );
441
+ }
442
+ });
443
+ if( !get( node.metadata, 'dirty.material' ) ) {
444
+ cloneTransformNodeMaterial( node );
445
+ }
446
+ if( !get( node.metadata, 'dirty.material.roughness' ) ) {
447
+ // inject initial value and mark as dirty
448
+ injectTransformNodeMetadata( node, { dirty: { material: { roughness: oldValue } } } );
449
+ }
450
+ setMaterialRoughness( node, roughness );
451
+ } );
452
+ }
453
+ ] );
454
+ this._parameterObservers.set( Parameter.HIGHLIGHT_COLOR, [
455
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
456
+ // trigger Parameter.HIGHLIGHTED observers
457
+ this._parameterObservers.get( Parameter.HIGHLIGHTED )?.forEach( observer => {
458
+ observer( element, !!element.highlighted, !!element.highlighted );
459
+ } );
460
+ }
461
+ ] );
462
+ this._parameterObservers.set( Parameter.HIGHLIGHT_ENABLED, [
463
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
464
+ let curr;
465
+ try {
466
+ curr = Parameter.parseBoolean( newValue );
467
+ } catch( e ) {
468
+ return;
469
+ }
470
+ switch( curr ) {
471
+ case true:
472
+ if( element._highlightLayer ) {
473
+ break;
474
+ }
475
+ element.highlightLayer = new HighlightLayer(
476
+ DottedPath.create( element.id ).addPart( 'highlight' ).path,
477
+ element.variant.viewer.scene
478
+ );
479
+ break;
480
+ case false:
481
+ element.highlightLayer?.dispose();
482
+ break;
483
+ }
484
+ }
485
+ ] );
486
+ this._parameterObservers.set( Parameter.HIGHLIGHTED, [
487
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
488
+ if( !element.inheritedParameters[Parameter.HIGHLIGHT_ENABLED] ) {
489
+ return;
490
+ }
491
+ // trigger Parameter.HIGHLIGHT_ENABLED observers to ensure HighlightLayer
492
+ this._parameterObservers.get( Parameter.HIGHLIGHT_ENABLED )?.forEach( observer => {
493
+ observer( element, this.parameters[Parameter.HIGHLIGHT_ENABLED], true );
494
+ } );
495
+ let highlighted;
496
+ try {
497
+ highlighted = Parameter.parseBoolean( newValue );
498
+ } catch( e ) {
499
+ return;
500
+ }
501
+ // Add/Remove meshes to previously created highlight layers.
502
+ if( highlighted === true ) {
503
+ element.nodes.forEach( node => {
504
+ assertTransformNode(node, (node: TransformNode) => {
505
+ if( node instanceof InstancedMesh ) {
506
+ throw new Error( `Changing parameter "${Parameter.HIGHLIGHTED}" ` +
507
+ `of an InstancedMesh is not supported. ` +
508
+ `Tried to change node "${node.id}" on element "${element.id}".` );
509
+ }
510
+ });
511
+ let color = Color3.Green();
512
+ if( element.inheritedParameters[Parameter.HIGHLIGHT_COLOR] ) {
513
+ color = Parameter.parseColor( element.inheritedParameters[Parameter.HIGHLIGHT_COLOR] );
514
+ }
515
+ if ( typeof element._highlightLayer !== "undefined" ) {
516
+ addToHighlightLayer( element._highlightLayer, color, node );
517
+ }
518
+ } );
519
+ } else if( highlighted === false ) {
520
+ element.nodes.forEach( node => {
521
+ if ( typeof element._highlightLayer !== "undefined" ) {
522
+ removeFromHighlightLayer( element._highlightLayer, node );
523
+ }
524
+ } );
525
+ }
526
+ }
527
+ ] );
528
+ this._parameterObservers.set( Parameter.POSITION, [
529
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
530
+ // we have to deal just with root nodes here due to relative impacts in a node tree
531
+ element.nodes.forEach( node => {
532
+ // remember absolute position and reset it before translating
533
+ if( !get( node.metadata, 'position' ) ) {
534
+ node.metadata.position = node.absolutePosition.clone();
535
+ }
536
+ node.setAbsolutePosition( node.metadata.position );
537
+ // move
538
+ const distance = Parameter.parseVector( newValue );
539
+ node.translate( Axis.X, distance.x, Space.WORLD );
540
+ node.translate( Axis.Y, distance.y, Space.WORLD );
541
+ node.translate( Axis.Z, distance.z, Space.WORLD );
542
+ } );
543
+ }
544
+ ] );
545
+ this._parameterObservers.set( Parameter.ROTATION, [
546
+ async ( element: Element, oldValue: ParameterValue, newValue: ParameterValue ) => {
547
+ // we have to deal just with root nodes here due to relative impacts in a node tree
548
+ element.nodes.forEach( node => {
549
+ // remember absolute rotation and reset it before translating
550
+ if(!get( node.metadata, 'rotation' ) ) {
551
+ node.metadata.rotation = node.rotation.clone();
552
+ }
553
+ node.rotation = node.metadata.rotation;
554
+ // rotate
555
+ const rotation = Parameter.parseRotation( newValue );
556
+ node.rotate( Axis.X, rotation.x, Space.WORLD );
557
+ node.rotate( Axis.Y, rotation.y, Space.WORLD );
558
+ node.rotate( Axis.Z, rotation.z, Space.WORLD );
559
+ } );
560
+ }
561
+ ] );
562
+ return this;
563
+ }
564
+
565
+ /**
566
+ * Filter for nodes that are not defined or excluded in the `pathDefinitions`.
567
+ */
568
+ protected filterNode( node: TransformNode ): boolean {
569
+ let includeTokens: string[] = [];
570
+ this.pathDefinitions.include.forEach( dottedPath => {
571
+ includeTokens = union( includeTokens, DottedPath.create( dottedPath ).leafTokens );
572
+ } );
573
+ const shallKeep = ( dp: DottedPath ) => {
574
+ const isDirectlyIncluded = !!includeTokens.find( _dp => _dp === dp.path );
575
+ const isSubOfIncluded = !!this.pathDefinitions.include.find( _dp => {
576
+ return dp.path.startsWith( `${_dp}${DottedPath.DELIMITER}` );
577
+ } );
578
+ return isDirectlyIncluded || isSubOfIncluded;
579
+ };
580
+ const shallExclude = ( dp: DottedPath ) => {
581
+ if( !this.pathDefinitions.exclude ) {
582
+ return false;
583
+ }
584
+ return !!this.pathDefinitions.exclude.find( _dp => dp.path === _dp );
585
+ };
586
+ return shallKeep( node.metadata.dottedPath ) && !shallExclude( node.metadata.dottedPath );
587
+ }
588
+
589
+ /**
590
+ * Asserts whether all {@link pathDefinitions} link to a valid `Node` path.
591
+ * @protected
592
+ */
593
+ protected assertPathDefinitions() {
594
+ const dottedNodes = this.variant.inheritedDottedNodes;
595
+ if( dottedNodes.size === 0 ) {
596
+ throw new Error( `There are no mapped nodes for element "${this.id}".` );
597
+ }
598
+ const include = this.pathDefinitions.include.map( path => DottedPath.create( path ).path );
599
+ const exclude = this.pathDefinitions.exclude?.map( path => DottedPath.create( path ).path );
600
+ const keys = Array.from( dottedNodes.keys() ).map( dottedPath => dottedPath.path );
601
+ union<string>( include, exclude ).forEach( path => {
602
+ if( keys.indexOf( path ) === -1 ) {
603
+ throw new Error( `Node with path "${path}" does not exist for element "${this.id}".` );
604
+ }
605
+ } );
606
+ }
607
+
608
+ }