@combeenation/3d-viewer 4.0.0-alpha9 → 4.0.0-beta4

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 (105) hide show
  1. package/README.md +112 -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 -130
  7. package/dist/lib-cjs/api/classes/element.js +682 -739
  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 -326
  12. package/dist/lib-cjs/api/classes/event.js +357 -371
  13. package/dist/lib-cjs/api/classes/event.js.map +1 -1
  14. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  15. package/dist/lib-cjs/api/classes/eventBroadcaster.js +53 -53
  16. package/dist/lib-cjs/api/classes/parameter.d.ts +165 -259
  17. package/dist/lib-cjs/api/classes/parameter.js +267 -387
  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 +126 -101
  21. package/dist/lib-cjs/api/classes/parameterObservable.js.map +1 -1
  22. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  23. package/dist/lib-cjs/api/classes/parameterizable.js +149 -149
  24. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +38 -38
  25. package/dist/lib-cjs/api/classes/placementAnimation.js +138 -138
  26. package/dist/lib-cjs/api/classes/variant.d.ts +190 -224
  27. package/dist/lib-cjs/api/classes/variant.js +873 -1137
  28. package/dist/lib-cjs/api/classes/variant.js.map +1 -1
  29. package/dist/lib-cjs/api/classes/variantInstance.d.ts +41 -45
  30. package/dist/lib-cjs/api/classes/variantInstance.js +98 -108
  31. package/dist/lib-cjs/api/classes/variantInstance.js.map +1 -1
  32. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  33. package/dist/lib-cjs/api/classes/variantParameterizable.js +92 -92
  34. package/dist/lib-cjs/api/classes/viewer.d.ts +128 -131
  35. package/dist/lib-cjs/api/classes/viewer.js +486 -538
  36. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  37. package/dist/lib-cjs/api/classes/viewerLight.d.ts +65 -66
  38. package/dist/lib-cjs/api/classes/viewerLight.js +322 -389
  39. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  40. package/dist/lib-cjs/api/internal/debugViewer.d.ts +13 -13
  41. package/dist/lib-cjs/api/internal/debugViewer.js +87 -87
  42. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  43. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  44. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +6 -10
  45. package/dist/lib-cjs/api/internal/sceneSetup.js +227 -231
  46. package/dist/lib-cjs/api/internal/sceneSetup.js.map +1 -1
  47. package/dist/lib-cjs/api/manager/animationManager.d.ts +29 -29
  48. package/dist/lib-cjs/api/manager/animationManager.js +121 -121
  49. package/dist/lib-cjs/api/manager/sceneManager.d.ts +32 -32
  50. package/dist/lib-cjs/api/manager/sceneManager.js +132 -132
  51. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +90 -90
  52. package/dist/lib-cjs/api/manager/variantInstanceManager.js +321 -321
  53. package/dist/lib-cjs/api/store/specStorage.d.ts +24 -24
  54. package/dist/lib-cjs/api/store/specStorage.js +51 -51
  55. package/dist/lib-cjs/api/util/babylonHelper.d.ts +125 -175
  56. package/dist/lib-cjs/api/util/babylonHelper.js +368 -520
  57. package/dist/lib-cjs/api/util/babylonHelper.js.map +1 -1
  58. package/dist/lib-cjs/api/util/globalTypes.d.ts +279 -321
  59. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  60. package/dist/lib-cjs/api/util/resourceHelper.d.ts +51 -26
  61. package/dist/lib-cjs/api/util/resourceHelper.js +243 -237
  62. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  63. package/dist/lib-cjs/api/util/stringHelper.d.ts +9 -9
  64. package/dist/lib-cjs/api/util/stringHelper.js +25 -25
  65. package/dist/lib-cjs/buildinfo.json +3 -3
  66. package/dist/lib-cjs/index.d.ts +46 -48
  67. package/dist/lib-cjs/index.js +82 -86
  68. package/dist/lib-cjs/index.js.map +1 -1
  69. package/dist/webpack-stats.json +0 -0
  70. package/package.json +83 -83
  71. package/src/api/classes/animationInterface.ts +11 -11
  72. package/src/api/classes/dottedPath.ts +189 -189
  73. package/src/api/classes/element.ts +617 -635
  74. package/src/api/classes/{parameterizable.ts → elementParameterizable.ts} +78 -89
  75. package/src/api/classes/event.ts +355 -370
  76. package/src/api/classes/eventBroadcaster.ts +54 -54
  77. package/src/api/classes/parameter.ts +277 -408
  78. package/src/api/classes/parameterObservable.ts +121 -99
  79. package/src/api/classes/placementAnimation.ts +133 -133
  80. package/src/api/classes/variant.ts +670 -806
  81. package/src/api/classes/variantInstance.ts +81 -88
  82. package/src/api/classes/viewer.ts +421 -473
  83. package/src/api/internal/debugViewer.ts +81 -81
  84. package/src/api/internal/lensRendering.ts +10 -10
  85. package/src/api/internal/sceneSetup.ts +204 -194
  86. package/src/api/manager/animationManager.ts +116 -116
  87. package/src/api/manager/sceneManager.ts +105 -105
  88. package/src/api/manager/variantInstanceManager.ts +236 -236
  89. package/src/api/store/specStorage.ts +53 -53
  90. package/src/api/util/babylonHelper.ts +392 -553
  91. package/src/api/util/globalTypes.ts +318 -369
  92. package/src/api/util/resourceHelper.ts +187 -157
  93. package/src/buildinfo.json +2 -2
  94. package/src/commonjs.tsconfig.json +13 -13
  95. package/src/declaration.tsconfig.json +10 -10
  96. package/src/dev.ts +46 -44
  97. package/src/es6.tsconfig.json +13 -13
  98. package/src/index.ts +87 -91
  99. package/src/pagesconfig.json +57 -52
  100. package/src/tsconfig.json +43 -43
  101. package/src/tsconfig.types.json +9 -9
  102. package/src/types.d.ts +4 -4
  103. package/src/api/classes/variantParameterizable.ts +0 -73
  104. package/src/api/classes/viewerLight.ts +0 -330
  105. package/src/api/util/stringHelper.ts +0 -26
@@ -1,806 +1,670 @@
1
- import { AssetContainer } from '@babylonjs/core/assetContainer';
2
- import { Light } from '@babylonjs/core/Lights/light';
3
- import '@babylonjs/core/Loading/Plugins/babylonFileLoader';
4
- import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
5
- import { Material } from '@babylonjs/core/Materials/material';
6
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
7
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
8
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_draco_mesh_compression';
9
- import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_transform';
10
- import '@babylonjs/loaders/glTF/2.0/glTFLoader';
11
- import { cloneDeep, concat, get, isEmpty, isEqual, isString, merge, set } from 'lodash-es';
12
- import { deactivateTransformNode, getDottedPathForNode, injectNodeMetadata } from '../util/babylonHelper';
13
- import { loadJson, mergeMaps } from '../util/resourceHelper';
14
- import { DottedPath } from './dottedPath';
15
- import { Element } from './element';
16
- import { Event } from './event';
17
- import { Parameter } from './parameter';
18
- import { Parameterizable } from './parameterizable';
19
- import { ParameterObservable } from './parameterObservable';
20
- import { VariantParameterizable } from './variantParameterizable';
21
- import { Viewer } from './viewer';
22
- import { ViewerLight } from './viewerLight';
23
-
24
- /**
25
- * A concrete "Variant". Most of these are handled by either the {@link Viewer} or {@link VariantInstance}.
26
- */
27
- export class Variant extends Parameterizable {
28
-
29
- public assetContainer: AssetContainer;
30
-
31
- public readonly elements: Element[] = [];
32
-
33
- public readonly viewerLights: ViewerLight[] = [];
34
-
35
- public structureJson: StructureJson;
36
-
37
- protected _dottedNodes: Map<DottedPath, TransformNode> | undefined;
38
-
39
- protected readonly _children: Map<string, Variant> = new Map();
40
-
41
- protected readonly _parameterObservers: Map<string, ParameterObserver[]> = new Map();
42
-
43
- /**
44
- * @internal
45
- */
46
- private parametersInitialized: boolean = false;
47
-
48
- /**
49
- * Constructor.
50
- */
51
- protected constructor( public readonly name: string,
52
- protected readonly _structureJson: StructureJson,
53
- public readonly viewer: Viewer,
54
- public readonly parent?: Variant ) {
55
- super(
56
- cloneDeep( _structureJson.parameterDeclaration ),
57
- cloneDeep( _structureJson.parameters )
58
- );
59
- for( const parameter in _structureJson.parameterDeclaration ) {
60
- if( !(parameter in (_structureJson.parameters || [])) ) {
61
- throw new Error( `No default value for parameter "${parameter}" defined.` );
62
- }
63
- }
64
- this.assetContainer = new AssetContainer( viewer.scene );
65
- this.structureJson = cloneDeep( _structureJson );
66
- }
67
-
68
- /**
69
- * Creates a {@link Variant} based on given parameters.
70
- *
71
- * @throws Error if "gltf" property is provided without a filename
72
- */
73
- public static async create( name: string,
74
- structureJson: StructureJson,
75
- viewer: Viewer,
76
- parent?: Variant ): Promise<Variant> {
77
- const variant = new Variant( name, structureJson, viewer, parent );
78
- await variant.loadAssets();
79
- return variant;
80
- }
81
-
82
- /**
83
- * The ancestor {@link Variant}s ordered from top to bottom in the built tree.
84
- */
85
- get ancestors(): Variant[] {
86
- const ancestors = [];
87
- let variant: Variant = this;
88
- while( variant.parent ) {
89
- ancestors.unshift( variant.parent );
90
- variant = variant.parent;
91
- }
92
- return ancestors;
93
- }
94
-
95
- /**
96
- * The root {@link Variant}.
97
- */
98
- get root(): Variant {
99
- return this.ancestors[0] ?? this;
100
- }
101
-
102
- /**
103
- * The {@link DottedPath} in the built tree of {@link Variant}s.
104
- * E.g. "_.top-1.sub-2.sub-sub-3"
105
- */
106
- get dottedPath(): DottedPath {
107
- const parentIds = this.ancestors.map( ancestor => {
108
- return ancestor.name;
109
- } );
110
- return DottedPath.createFromParts( parentIds ).addPart( this.name );
111
- }
112
-
113
- /**
114
- * The id representing a {@link DottedPath}.
115
- */
116
- get id(): string {
117
- const dottedPath = DottedPath.create( this.dottedPath );
118
- dottedPath.shiftPart(); // remove root
119
- return dottedPath.path || '_';
120
- }
121
-
122
- /**
123
- * The defined glTF Asset.
124
- */
125
- get glTF(): Asset | undefined {
126
- if( this.structureJson.glTF ) {
127
- if( isString( this.structureJson.glTF ) ) {
128
- return {
129
- rootUrl: this.structureJson.glTF,
130
- fileName: undefined
131
- };
132
- }
133
- if( isEmpty( this.structureJson.glTF.rootUrl ) ) {
134
- throw new Error( `No "rootUrl" defined in "glTF" definition for variant "${this.id}".` );
135
- }
136
- return this.structureJson.glTF;
137
- }
138
- }
139
-
140
- /**
141
- * The defined glTF URI.
142
- */
143
- get glTFUri(): string | undefined {
144
- if( this.glTF ) {
145
- return [this.glTF.rootUrl, this.glTF.fileName].join( '' );
146
- }
147
- }
148
-
149
- /**
150
- * The inherited defined glTF URI.
151
- */
152
- get inheritedGlTFUri(): string | undefined {
153
- if( !this.glTFUri && this.parent ) {
154
- return this.parent.inheritedGlTFUri;
155
- }
156
- return this.glTFUri;
157
- }
158
-
159
- /**
160
- * The TransformNodes of the {@link Variant}.
161
- */
162
- get nodes(): TransformNode[] {
163
- const rootNodes = this.assetContainer.getNodes().filter(
164
- n => n instanceof TransformNode && !n.parent
165
- ) as TransformNode[];
166
- return rootNodes;
167
- }
168
-
169
- /**
170
- * The {@link ViewerLight}s of the {@link Variant}.
171
- */
172
- get lights(): Light[] {
173
- return this.assetContainer.lights;
174
- }
175
-
176
- /**
177
- * All TransformNodes of the {@link Variant} mapped flat with a {@link DottedPath}.
178
- */
179
- get dottedNodes(): Map<DottedPath, TransformNode> {
180
- if( ! this._dottedNodes ) {
181
- const nodes = this.assetContainer.getNodes().filter( n => n instanceof TransformNode );
182
- const dottedNodes = new Map();
183
- nodes.forEach( node => {
184
- dottedNodes.set( node.metadata.dottedPath, node );
185
- } );
186
- this._dottedNodes = dottedNodes;
187
- }
188
- return this._dottedNodes;
189
- }
190
-
191
- /**
192
- * The Materials of the {@link Variant}.
193
- */
194
- get materials(): Material[] {
195
- return this.assetContainer.materials;
196
- }
197
-
198
- /**
199
- * All {@link Element}s from this {@link Variant}'s parents.
200
- */
201
- get inheritedElements(): Element[] {
202
- let elements: Element[] = [];
203
- this.ancestors.forEach( ancestor => {
204
- elements = concat( elements, ancestor.elements );
205
- } );
206
- return concat( elements, this.elements );
207
- }
208
-
209
- /**
210
- * All {@link ViewerLight}s inherited from this {@link Variant}'s parents.
211
- */
212
- get inheritedViewerLights(): ViewerLight[] {
213
- let viewerLights: ViewerLight[] = [];
214
- this.ancestors.forEach( ancestor => {
215
- viewerLights = concat( viewerLights, ancestor.viewerLights );
216
- } );
217
- return concat( viewerLights, this.viewerLights );
218
- }
219
-
220
- /**
221
- * All TransformNodes inherited from this {@link Variant}'s parents.
222
- */
223
- get inheritedNodes(): TransformNode[] {
224
- let nodes: TransformNode[] = [];
225
- this.ancestors.forEach( ancestor => {
226
- nodes = concat( nodes, ancestor.nodes );
227
- } );
228
- return concat( nodes, this.nodes );
229
- }
230
-
231
- /**
232
- * All TransformNodes inherited from this {@link Variant}'s parents mapped flat with a {@link DottedPath}.
233
- */
234
- get inheritedDottedNodes(): Map<DottedPath, TransformNode> {
235
- let dottedNodes = this.dottedNodes;
236
- this.ancestors.forEach( ancestor => {
237
- dottedNodes = mergeMaps( dottedNodes, ancestor.dottedNodes );
238
- } );
239
- return dottedNodes;
240
- }
241
-
242
- /**
243
- * All Lights inherited from this {@link Variant}'s parents.
244
- */
245
- get inheritedLights(): Light[] {
246
- let lights: Light[] = [];
247
- this.ancestors.forEach( ancestor => {
248
- lights = concat( lights, ancestor.lights );
249
- } );
250
- return concat( lights, this.lights );
251
- }
252
-
253
- /**
254
- * The {@link ParameterDeclarations} inherited from this {@link Variant}'s parents.
255
- */
256
- get inheritedParameterDeclaration(): ParameterDeclarations {
257
- let declaration = {};
258
- this.ancestors.forEach( ancestor => {
259
- merge( declaration, ancestor.parameterDeclaration );
260
- } );
261
- return merge( declaration, this.parameterDeclaration );
262
- }
263
-
264
- /**
265
- * The {@link ParameterBag} inherited from this {@link Variant}'s parents.
266
- */
267
- get inheritedParameters(): ParameterBag {
268
- let parameters = {};
269
- this.ancestors.forEach( ancestor => {
270
- merge( parameters, ancestor.parameters );
271
- } );
272
- return merge( parameters, this.parameters );
273
- }
274
-
275
- /**
276
- * All Materials from this {@link Variant}'s parents.
277
- */
278
- get inheritedMaterials(): Material[] {
279
- let materials: Material[] = [];
280
- this.ancestors.forEach( ancestor => {
281
- materials = concat( materials, ancestor.materials );
282
- } );
283
- return concat( materials, this.materials );
284
- }
285
-
286
- /**
287
- * Gets the direct children of the current {@link Variant}.
288
- */
289
- public async getChildren(): Promise<Variant[]> {
290
- const children: Variant[] = [];
291
- for( const name in this.structureJson.variants ) {
292
- children.push( await this.getDescendant( name ) );
293
- }
294
- return children;
295
- }
296
-
297
- /**
298
- * Gets a descendant {@link Variant} of the current {@link Variant} relative to its {@link DottedPath}.
299
- * If you have the dotted path `_.product_x.variant_blue.with_yellow_highlight` in a tree and you operate on the
300
- * `product_x`, you can call `this.getDescendant('variant_blue.with_yellow_highlight')` to get the lowermost
301
- * {@link Variant}.
302
- */
303
- public async getDescendant( dottedPath: DottedPathArgument ): Promise<Variant> {
304
- const _dottedPath = DottedPath.create( dottedPath );
305
- const [name, ...descendantParts] = _dottedPath.parts;
306
- let variant;
307
- if( this._children.has( name ) ) {
308
- variant = this._children.get( name );
309
- } else {
310
- if( !this.structureJson.variants ) {
311
- throw new Error( `Missing key "variants" in JSON structure for variant "${this.id}".` );
312
- }
313
- if( !this.structureJson.variants[name] ) {
314
- throw new Error( `Variant "${_dottedPath.path}" not defined in JSON structure for variant "${this.id}".` );
315
- }
316
- if( this.structureJson.variants[name].file ) {
317
- const file = this.structureJson.variants[name].file as string;
318
- variant = await Variant.create( name, await loadJson<StructureJson>( file ), this.viewer, this );
319
- } else {
320
- variant = await Variant.create( name, this.structureJson.variants[name], this.viewer, this );
321
- }
322
- this._children.set( name, variant );
323
- }
324
- if( !variant ) {
325
- throw new Error( `Variant "${_dottedPath.path}" was not created.` );
326
- }
327
- if( descendantParts.length > 0 ) {
328
- return await variant.getDescendant( DottedPath.createFromParts( descendantParts ) );
329
- }
330
- return variant;
331
- }
332
-
333
- /**
334
- * Gets the desired {@link Element} of the current {@link Variant} relative to its {@link DottedPath}.
335
- * Uses the mechanism of {@link getDescendant} to resolve the appropriate variant in tree.
336
- */
337
- public async getElement( dottedPath: DottedPathArgument ): Promise<Element> {
338
- const _dottedPath = DottedPath.create( dottedPath );
339
- const elementName = _dottedPath.popPart();
340
- let variant: Variant = this;
341
- if( _dottedPath.parts.length > 0 ) {
342
- variant = await this.getDescendant( _dottedPath );
343
- }
344
- if( variant.inheritedElements.length === 0 ) {
345
- throw new Error( `No elements for variant "${variant.id}" found. ` +
346
- `Either none are defined or they are not initialized (are you operating on the appropriate living?).` );
347
- }
348
- let element;
349
- variant.inheritedElements.forEach( _element => {
350
- if( _element.name === elementName ) {
351
- element = _element;
352
- }
353
- } );
354
- if( !element ) {
355
- throw new Error( `Element with name "${elementName}" does not exist for variant "${variant.id}".` );
356
- }
357
- return element;
358
- }
359
-
360
- /**
361
- * Gets the desired {@link ViewerLight} of the current {@link Variant} relative to its {@link DottedPath}.
362
- * Uses the mechanism of {@link getDescendant} to resolve the appropriate variant in tree.
363
- */
364
- public async getViewerLight( dottedPath: DottedPathArgument ): Promise<ViewerLight> {
365
- const _dottedPath = DottedPath.create( dottedPath );
366
- const viewerLightName = _dottedPath.popPart();
367
- let variant: Variant = this;
368
- if( _dottedPath.parts.length > 0 ) {
369
- variant = await this.getDescendant( _dottedPath );
370
- }
371
- if( variant.inheritedViewerLights.length === 0 ) {
372
- throw new Error( `No viewerLights for variant "${variant.id}" found. ` +
373
- `Either none are defined or they are not initialized (are you operating on the appropriate living?).` );
374
- }
375
- let viewerLight;
376
- variant.inheritedViewerLights.forEach( _viewerLight => {
377
- if( _viewerLight.name === viewerLightName ) {
378
- viewerLight = _viewerLight;
379
- }
380
- } );
381
- if( !viewerLight ) {
382
- throw new Error( `ViewerLight with name "${viewerLightName}" does not exist for variant "${variant.id}".` );
383
- }
384
- return viewerLight;
385
- }
386
-
387
- /**
388
- * A proxy for directly getting a Node from an {@link Element} by its {@link DottedPath}s.
389
- */
390
- public async getNode( elementDottedPath: DottedPathArgument, nodeDottedPath: DottedPathArgument ): Promise<TransformNode> {
391
- const element = await this.getElement( elementDottedPath );
392
- return element.getNode( nodeDottedPath );
393
- }
394
-
395
- /**
396
- * A proxy for directly getting a Mesh from an {@link Element} by its {@link DottedPath}s.
397
- */
398
- public async getMesh( elementDottedPath: DottedPathArgument, meshDottedPath: DottedPathArgument ): Promise<Mesh|null> {
399
- const element = await this.getElement( elementDottedPath );
400
- return element.getMesh( meshDottedPath );
401
- }
402
-
403
- /**
404
- * Gets the Material defined in one of the variants glTFs by its id.
405
- */
406
- public getMaterial( id: string ): Material {
407
- for( const material of this.inheritedMaterials ) {
408
- if( material.id === id ) {
409
- return material;
410
- }
411
- }
412
- // fallback to dynamically created materials on scene
413
- for( const material of this.viewer.scene.materials ) {
414
- if( material.id === id ) {
415
- return material;
416
- }
417
- }
418
- throw new Error( `Material with id "${id}" does not exist for variant "${this.id}".` );
419
- }
420
-
421
- /**
422
- * Creates a living clone of this {@link Variant}. Will clone all parent {@link Variant}s in tree.
423
- *
424
- * @emit {@link Event.VARIANT_CREATED}
425
- * @ignore
426
- */
427
- public async createLiving( parameters?: ParameterBag ): Promise<Variant> {
428
- const parent = await this.parent?.createLiving();
429
- const variant = new Variant( this.name, this._structureJson, this.viewer, parent );
430
- parent?._children.set( variant.name, variant );
431
- variant.assetContainer = this.assetContainer;
432
- variant.parameterObservers = cloneDeep( this.parameterObservers );
433
- await variant.createElements();
434
- await variant.createViewerLights();
435
- variant.addParameterObservers();
436
- await variant.bootstrapParameters( parameters );
437
- this.broadcastEvent( Event.VARIANT_CREATED, variant );
438
- return variant;
439
- }
440
-
441
- /**
442
- * Destroys this {@link Variant}, all parents and destroy the {@link Element}s.
443
- */
444
- public destroy(): Variant {
445
- this.elements.forEach( element => element.destroy() );
446
- if( this.parent ) {
447
- this.parent.destroy();
448
- }
449
- this.broadcastEvent( Event.VARIANT_DESTROYED, this );
450
- return this;
451
- }
452
-
453
- /**
454
- * Places the given {@link ParameterBag} in the {@link Variant}'s parameters, replaces all patterns in the
455
- * {@link StructureJson}, broadcasts all {@link ParameterObserver}s and delegates them to its {@link Element}s.
456
- *
457
- * @emit {@link Event.VARIANT_PARAMETER_COMMITTED}
458
- */
459
- public async commitParameters( parameters?: ParameterBag ): Promise<Variant> {
460
- parameters = merge( {}, parameters );
461
-
462
- // remember old parameter values for later comparison
463
- const oldParameters = cloneDeep( this.inheritedParameters );
464
-
465
- // replace patterns in given parameters
466
- let _parameters = JSON.stringify( parameters );
467
- for( const parameter in this.inheritedParameters ) {
468
- const value = this.inheritedParameters[parameter];
469
- const search = new RegExp( `\\$\\{${parameter}\\}`, 'g' );
470
- _parameters = _parameters.replace( search, value.toString() );
471
- }
472
- merge( parameters, JSON.parse( _parameters ) );
473
-
474
- // merge inherited parameters and replaced given parameters
475
- const mergedParameters = merge( {}, this.inheritedParameters, parameters );
476
-
477
- // replace patterns in structure parameters
478
- const structureParameters = this._structureJson.parameters || {};
479
- let _structureParameters = JSON.stringify( structureParameters );
480
- for( const parameter in mergedParameters ) {
481
- const value = mergedParameters[parameter];
482
- const search = new RegExp( `\\$\\{${parameter}\\}`, 'g' );
483
- _structureParameters = _structureParameters.replace( search, value.toString() );
484
- }
485
- const replacedStructureParameters = JSON.parse( _structureParameters );
486
-
487
- // calculate which replaced structure parameters have changed and should overload given parameters
488
- const differentStructureParameters: ParameterBag = {};
489
- for( const parameter in replacedStructureParameters ) {
490
- if( !isEqual(structureParameters[parameter], replacedStructureParameters[parameter]) ) {
491
- differentStructureParameters[parameter] = replacedStructureParameters[parameter];
492
- }
493
- }
494
-
495
- // merge replaced structure parameters and given inherited parameters to structure parameters
496
- merge( this.parameters, mergedParameters, differentStructureParameters );
497
-
498
- // inherited parameters are now the new parameters to process
499
- const newParameters = this.inheritedParameters;
500
-
501
- // replace all parameter patterns in structure json
502
- let structure = JSON.stringify( this._structureJson );
503
- for( const parameter in newParameters ) {
504
- const value = newParameters[parameter];
505
- const search = new RegExp( `\\$\\{${parameter}\\}`, 'g' );
506
- structure = structure.replace( search, value.toString() );
507
- }
508
- this.structureJson = JSON.parse( structure );
509
-
510
- // handle parameter observers
511
- let observerPromises: Promise<void | ParameterObserver>[] = [];
512
- for( const parameter in newParameters ) {
513
- const oldParameterValue = oldParameters[parameter];
514
- const newParameterValue = newParameters[parameter];
515
- this.assertParameter( this.inheritedParameterDeclaration, parameter, newParameterValue );
516
- if( oldParameterValue === newParameterValue && this.parametersInitialized ) {
517
- continue;
518
- }
519
- // parameter changed
520
- const parameterObservers = mergeMaps( this._parameterObservers, this.parameterObservers );
521
- if( parameterObservers.has( parameter ) ) {
522
- const observers = parameterObservers.get( parameter )!;
523
- observerPromises = concat(observerPromises, observers.map( observer => {
524
- const observerResult = observer( this, oldParameterValue, newParameterValue );
525
- return Promise.resolve( observerResult ).then( () => {
526
- if( this.parametersInitialized ) {
527
- this.broadcastEvent( Event.VARIANT_PARAMETER_COMMITTED,
528
- this, parameter, oldParameterValue, newParameterValue );
529
- }
530
- } );
531
- } ) );
532
- }
533
- }
534
- await Promise.all( observerPromises );
535
-
536
- // broadcast that bag has been committed
537
- this.broadcastEvent(Event.VARIANT_PARAMETER_BAG_COMMITTED, this, oldParameters, newParameters);
538
-
539
- // commit parameters to elements
540
- await this.commitParametersToElements( newParameters );
541
-
542
- // commit parameters to lights
543
- await this.commitParametersToViewerLights( newParameters );
544
-
545
- // propagate parameters to parent
546
- if( this.parent ) {
547
- await this.parent.commitParameters( this.parameters );
548
- }
549
-
550
- return this;
551
- }
552
-
553
- /**
554
- * Adds an observer function for camera matrix changes for given `dottedPath` representing the {@link Element}
555
- * and the `traceable`. The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
556
- */
557
- public async addTraceableObserver( dottedPath: DottedPathArgument,
558
- observer: CallableFunction,
559
- payload?: any ): Promise<Element> {
560
- const _dottedPath = DottedPath.create( dottedPath );
561
- const traceableName = _dottedPath.popPart();
562
- if( !traceableName ) {
563
- throw new Error( `The dottedPath must consist of the element and the name of the defined corresponding ` +
564
- `traceable ("${_dottedPath.path}" given).` );
565
- }
566
- const element = await this.getElement( _dottedPath );
567
- return element.addTraceableObserver( traceableName, observer, payload );
568
- }
569
-
570
- /**
571
- * Loads {@link glTFUri} with assets, adds them to the {@link Variant}'s `assetContainer` and deactivates the meshes.
572
- * (for further processing).
573
- * @emits {@link Event.ASSET_LOADING_START}
574
- * @emits {@link Event.ASSET_LOADING_END}
575
- */
576
- protected async loadAssets(): Promise<Variant> {
577
- this.broadcastEvent( Event.ASSET_LOADING_START, this );
578
- return new Promise( resolve => {
579
- if( !this.structureJson ) {
580
- this.broadcastEvent( Event.ASSET_LOADING_END, this );
581
- return resolve( this );
582
- }
583
- if( !this.glTF ) {
584
- this.broadcastEvent( Event.ASSET_LOADING_END, this );
585
- return resolve( this );
586
- }
587
- SceneLoader.LoadAssetContainerAsync( this.glTF.rootUrl, this.glTF.fileName, this.viewer.scene ).then( container => {
588
- this.assetContainer = container;
589
- const nodes = this.assetContainer.getNodes().filter( n => n instanceof TransformNode ) as TransformNode[];
590
- nodes.forEach( node => {
591
- deactivateTransformNode( node, false );
592
- injectNodeMetadata( node, { dottedPath: getDottedPathForNode( node ) }, false );
593
- } );
594
- this.assetContainer.lights.forEach( light => {
595
- light.setEnabled( false );
596
- injectNodeMetadata( light, { dottedPath: getDottedPathForNode( light ) }, false );
597
- this.viewer.scene.addLight( light );
598
- } );
599
- this.assetContainer.cameras.forEach( camera => {
600
- camera.setEnabled( false );
601
- injectNodeMetadata( camera, { dottedPath: getDottedPathForNode( camera ) }, false );
602
- this.viewer.scene.addCamera( camera );
603
- } );
604
- this.broadcastEvent( Event.ASSET_LOADING_END, this );
605
- resolve( this );
606
- } ).catch( reason => {
607
- this.broadcastEvent( Event.ASSET_LOADING_END, this );
608
- throw new Error( `Error loading assets for variant "${this.id}": ${reason}.` );
609
- } );
610
- } );
611
- }
612
-
613
- /**
614
- * Commits given parameters to all {@link Element}s.
615
- */
616
- protected async commitParametersToElements( parameters: ParameterBag ) {
617
- await Promise.all( this.elements.map(
618
- element => this.commitParametersToVariantParameterizable(parameters, element, 'elements')
619
- ) );
620
- }
621
-
622
- /**
623
- * Commits given parameters to all {@link ViewerLight}s.
624
- */
625
- protected async commitParametersToViewerLights( parameters: ParameterBag ) {
626
- await Promise.all( this.viewerLights.map(
627
- viewerLight => this.commitParametersToVariantParameterizable(parameters, viewerLight, 'lights')
628
- ) );
629
- }
630
-
631
- /**
632
- * Commits given parameters to a {@link VariantParameterizable} and updates the according definition with given
633
- * key in the {@link StructureJson}. The `definitionKey` "elements" for example will update the definition in
634
- * `this.structureJson.elements`.
635
- */
636
- protected async commitParametersToVariantParameterizable( parameters: ParameterBag,
637
- parameterizable: VariantParameterizable,
638
- definitionKey: string ): Promise<ParameterObservable> {
639
- const initialDefinition = get( this._structureJson, definitionKey )[parameterizable.name];
640
- let initialDefinitionStr = JSON.stringify( initialDefinition );
641
- const _parameters: ParameterBag = {};
642
- for( const parameter in parameters ) {
643
- const dpp = DottedPath.create( parameter );
644
- if( dpp.shiftPart() !== parameterizable.name ) {
645
- continue;
646
- }
647
- // we got a parameterizable ("element") parameter
648
- let parameterValue = parameters[parameter];
649
- const parameterizableParameter = dpp.path;
650
- // If the variant is explicitly hidden, we must not override the visibility with element parameters. We need
651
- // an exception for visibility to avoid overloading already applied element parameters with element parameters
652
- // defined in the variant spec ("dotted parameters").
653
- // @see https://github.com/Combeenation/3d-viewer/issues/44
654
- if( parameterizableParameter === Parameter.VISIBLE && parameters[Parameter.VISIBLE] === false ) {
655
- parameterValue = false;
656
- }
657
- _parameters[parameterizableParameter] = parameterValue;
658
- const search = new RegExp( `\\$\\{${parameterizableParameter}\\}`, 'g' );
659
- initialDefinitionStr = initialDefinitionStr.replace( search, parameterValue.toString() );
660
- }
661
- const definition = get( this.structureJson, definitionKey );
662
- definition[this.name] = JSON.parse( initialDefinitionStr );
663
- set( this.structureJson, definitionKey, definition );
664
- return await parameterizable.commitParameters( _parameters );
665
- }
666
-
667
- /**
668
- * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
669
- */
670
- protected async commitParameterToElements( parameter: string, value: ParameterValue ): Promise<Variant> {
671
- const promises = [];
672
- for( const element of this.elements ) {
673
- promises.push( element.commitParameter( parameter, value ) );
674
- }
675
- await Promise.all( promises );
676
- return this;
677
- }
678
-
679
- /**
680
- * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
681
- */
682
- protected async commitParameterToViewerLights( parameter: string, value: ParameterValue ): Promise<Variant> {
683
- const promises = [];
684
- for( const viewerLight of this.viewerLights ) {
685
- promises.push( viewerLight.commitParameter( parameter, value ) );
686
- }
687
- await Promise.all( promises );
688
- return this;
689
- }
690
-
691
- /**
692
- * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
693
- */
694
- protected addParameterObservers(): Variant {
695
- this._parameterObservers.set( Parameter.VISIBLE, [
696
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
697
- await variant.commitParameterToElements( Parameter.VISIBLE, newValue );
698
- await variant.commitParameterToViewerLights( Parameter.VISIBLE, newValue );
699
- }
700
- ] );
701
- this._parameterObservers.set( Parameter.SCALING, [
702
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
703
- await variant.commitParameterToElements( Parameter.SCALING, newValue );
704
- await variant.commitParameterToViewerLights( Parameter.SCALING, newValue );
705
- }
706
- ] );
707
- this._parameterObservers.set( Parameter.MATERIAL, [
708
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
709
- await variant.commitParameterToElements( Parameter.MATERIAL, newValue );
710
- }
711
- ] );
712
- this._parameterObservers.set( Parameter.MATERIAL_COLOR, [
713
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
714
- await variant.commitParameterToElements( Parameter.MATERIAL_COLOR, newValue );
715
- }
716
- ] );
717
- this._parameterObservers.set( Parameter.MATERIAL_METALLNESS, [
718
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
719
- await variant.commitParameterToElements( Parameter.MATERIAL_METALLNESS, newValue );
720
- }
721
- ] );
722
- this._parameterObservers.set( Parameter.MATERIAL_ROUGHNESS, [
723
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
724
- await variant.commitParameterToElements( Parameter.MATERIAL_ROUGHNESS, newValue );
725
- }
726
- ] );
727
- this._parameterObservers.set( Parameter.HIGHLIGHT_COLOR, [
728
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
729
- await variant.commitParameterToElements( Parameter.HIGHLIGHT_COLOR, newValue );
730
- }
731
- ] );
732
- this._parameterObservers.set( Parameter.HIGHLIGHTED, [
733
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
734
- await variant.commitParameterToElements( Parameter.HIGHLIGHTED, newValue );
735
- }
736
- ] );
737
- this._parameterObservers.set( Parameter.POSITION, [
738
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
739
- await variant.commitParameterToElements( Parameter.POSITION, newValue );
740
- await variant.commitParameterToViewerLights( Parameter.POSITION, newValue );
741
- }
742
- ] );
743
- this._parameterObservers.set( Parameter.ROTATION, [
744
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
745
- await variant.commitParameterToElements( Parameter.ROTATION, newValue );
746
- await variant.commitParameterToViewerLights( Parameter.ROTATION, newValue );
747
- }
748
- ] );
749
- this._parameterObservers.set( Parameter.CAST_SHADOW, [
750
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
751
- await variant.commitParameterToElements( Parameter.CAST_SHADOW, newValue );
752
- }
753
- ] );
754
- this._parameterObservers.set( Parameter.CAST_SHADOW_FROM_LIGHTS, [
755
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
756
- await variant.commitParameterToElements( Parameter.CAST_SHADOW_FROM_LIGHTS, newValue );
757
- }
758
- ] );
759
- this._parameterObservers.set( Parameter.RECEIVE_SHADOWS, [
760
- async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
761
- await variant.commitParameterToElements( Parameter.RECEIVE_SHADOWS, newValue );
762
- }
763
- ] );
764
- return this;
765
- }
766
-
767
- /**
768
- * Creates {@link Element}s and clones nodes into them.
769
- */
770
- protected async createElements(): Promise<Variant> {
771
- for( const name in this.structureJson.elements || {} ) {
772
- this.elements.push( await Element.create( this, name ) );
773
- }
774
- // inject node meta to all inherited elements
775
- // we do this to inject the deepest and most concrete variant information to all cloned nodes in the tree
776
- this.inheritedElements.forEach( element => {
777
- element.nodes.forEach( node => {
778
- injectNodeMetadata( node, { variant: this, variantParameterizable: element } );
779
- } );
780
- } );
781
- return this;
782
- }
783
-
784
- /**
785
- * Creates {@link ViewerLight}s.
786
- */
787
- protected async createViewerLights(): Promise<Variant> {
788
- for( const name in this.structureJson.lights || {} ) {
789
- this.viewerLights.push( await ViewerLight.create( this, name ) );
790
- }
791
- this.inheritedViewerLights.forEach( viewerLight => {
792
- injectNodeMetadata( viewerLight.light, { variant: this, variantParameterizable: viewerLight } );
793
- } );
794
- return this;
795
- }
796
-
797
- /**
798
- * Bootstrapping for parameters. It sets the `parametersInitialized` to true for all ancestors.
799
- */
800
- protected async bootstrapParameters( parameters?: ParameterBag ): Promise<Variant> {
801
- await this.commitParameters( merge( cloneDeep( this.parameters ), parameters ) );
802
- concat( this.ancestors, this ).forEach( ancestor => ancestor.parametersInitialized = true );
803
- return this;
804
- }
805
-
806
- }
1
+ import { AssetContainer } from '@babylonjs/core/assetContainer';
2
+ import '@babylonjs/core/Loading/Plugins/babylonFileLoader';
3
+ import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
4
+ import { Material } from '@babylonjs/core/Materials/material';
5
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
6
+ import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
7
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_draco_mesh_compression';
8
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_transform';
9
+ import '@babylonjs/loaders/glTF/2.0/glTFLoader';
10
+ import { cloneDeep, concat, isEmpty, isEqual, isString, merge } from 'lodash-es';
11
+ import {
12
+ deactivateTransformNode,
13
+ getDottedPathForTransformNode,
14
+ injectTransformNodeMetadata
15
+ } from '../util/babylonHelper';
16
+ import { loadJson, mergeMaps } from '../util/resourceHelper';
17
+ import { DottedPath } from './dottedPath';
18
+ import { Element } from './element';
19
+ import { ElementParameterizable } from './elementParameterizable';
20
+ import { Event } from './event';
21
+ import { Parameter } from './parameter';
22
+ import { Viewer } from './viewer';
23
+
24
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_basisu';
25
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_clearcoat';
26
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_sheen';
27
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_ior';
28
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness';
29
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_specular';
30
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_translucency';
31
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_transmission';
32
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_unlit';
33
+ import '@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_variants';
34
+
35
+ /**
36
+ * A concrete "Variant". Most of these are handled by either the {@link Viewer} or {@link VariantInstance}.
37
+ */
38
+ export class Variant extends ElementParameterizable {
39
+
40
+ public assetContainer: AssetContainer;
41
+
42
+ public readonly elements: Element[] = [];
43
+
44
+ public structureJson: StructureJson;
45
+
46
+ protected _dottedNodes: Map<DottedPath, TransformNode> | undefined;
47
+
48
+ protected readonly _children: Map<string, Variant> = new Map();
49
+
50
+ protected readonly _parameterObservers: Map<string, ParameterObserver[]> = new Map();
51
+
52
+ /**
53
+ * @internal
54
+ */
55
+ private parametersInitialized: boolean = false;
56
+
57
+ /**
58
+ * Constructor.
59
+ */
60
+ protected constructor( public readonly name: string,
61
+ protected readonly _structureJson: StructureJson,
62
+ public readonly viewer: Viewer,
63
+ public readonly parent?: Variant ) {
64
+ super(
65
+ cloneDeep( _structureJson.parameterDeclaration ),
66
+ cloneDeep( _structureJson.parameters )
67
+ );
68
+ for( const parameter in _structureJson.parameterDeclaration ) {
69
+ if( !(parameter in (_structureJson.parameters || [])) ) {
70
+ throw new Error( `No default value for parameter "${parameter}" defined.` );
71
+ }
72
+ }
73
+ this.assetContainer = new AssetContainer( viewer.scene );
74
+ this.structureJson = cloneDeep( _structureJson );
75
+ }
76
+
77
+ /**
78
+ * Creates a {@link Variant} based on given parameters.
79
+ *
80
+ * @throws Error if "gltf" property is provided without a filename
81
+ */
82
+ public static async create( name: string,
83
+ structureJson: StructureJson,
84
+ viewer: Viewer,
85
+ parent?: Variant ): Promise<Variant> {
86
+ const variant = new Variant( name, structureJson, viewer, parent );
87
+ await variant.loadAssets();
88
+ return variant;
89
+ }
90
+
91
+ /**
92
+ * The ancestor {@link Variant}s ordered from top to bottom in the built tree.
93
+ */
94
+ get ancestors(): Variant[] {
95
+ const ancestors = [];
96
+ let variant: Variant = this;
97
+ while( variant.parent ) {
98
+ ancestors.unshift( variant.parent );
99
+ variant = variant.parent;
100
+ }
101
+ return ancestors;
102
+ }
103
+
104
+ /**
105
+ * The root {@link Variant}.
106
+ */
107
+ get root(): Variant {
108
+ return this.ancestors[0] ?? this;
109
+ }
110
+
111
+ /**
112
+ * The {@link DottedPath} in the built tree of {@link Variant}s.
113
+ * E.g. "_.top-1.sub-2.sub-sub-3"
114
+ */
115
+ get dottedPath(): DottedPath {
116
+ const parentIds = this.ancestors.map( ancestor => {
117
+ return ancestor.name;
118
+ } );
119
+ return DottedPath.createFromParts( parentIds ).addPart( this.name );
120
+ }
121
+
122
+ /**
123
+ * The id representing a {@link DottedPath}.
124
+ */
125
+ get id(): string {
126
+ const dottedPath = DottedPath.create( this.dottedPath );
127
+ dottedPath.shiftPart(); // remove root
128
+ return dottedPath.path || '_';
129
+ }
130
+
131
+ /**
132
+ * The defined glTF Asset.
133
+ */
134
+ get glTF(): Asset | undefined {
135
+ if( this.structureJson.glTF ) {
136
+ if( isString( this.structureJson.glTF ) ) {
137
+ return {
138
+ rootUrl: this.structureJson.glTF,
139
+ fileName: undefined
140
+ };
141
+ }
142
+ if( isEmpty( this.structureJson.glTF.rootUrl ) ) {
143
+ throw new Error( `No "rootUrl" defined in "glTF" definition for variant "${this.id}".` );
144
+ }
145
+ return this.structureJson.glTF;
146
+ }
147
+ }
148
+
149
+ /**
150
+ * The defined glTF URI.
151
+ */
152
+ get glTFUri(): string | undefined {
153
+ if( this.glTF ) {
154
+ return [this.glTF.rootUrl, this.glTF.fileName].join( '' );
155
+ }
156
+ }
157
+
158
+ /**
159
+ * The inherited defined glTF URI.
160
+ */
161
+ get inheritedGlTFUri(): string | undefined {
162
+ if( !this.glTFUri && this.parent ) {
163
+ return this.parent.inheritedGlTFUri;
164
+ }
165
+ return this.glTFUri;
166
+ }
167
+
168
+ /**
169
+ * The TransformNodes of the {@link Variant}.
170
+ */
171
+ get nodes(): TransformNode[] {
172
+ const rootNodes = this.assetContainer.getNodes().filter(
173
+ n => n instanceof TransformNode && !n.parent
174
+ ) as TransformNode[];
175
+ return rootNodes;
176
+ }
177
+
178
+ /**
179
+ * All TransformNodes of the {@link Variant} mapped flat with a {@link DottedPath}.
180
+ */
181
+ get dottedNodes(): Map<DottedPath, TransformNode> {
182
+ if( ! this._dottedNodes ) {
183
+ const nodes = this.assetContainer.getNodes().filter( n => n instanceof TransformNode );
184
+ const dottedNodes = new Map();
185
+ nodes.forEach( node => {
186
+ dottedNodes.set( node.metadata.dottedPath, node );
187
+ } );
188
+ this._dottedNodes = dottedNodes;
189
+ }
190
+ return this._dottedNodes;
191
+ }
192
+
193
+ /**
194
+ * The Materials of the {@link Variant}.
195
+ */
196
+ get materials(): Material[] {
197
+ return this.assetContainer.materials;
198
+ }
199
+
200
+ /**
201
+ * All {@link Element}s from this {@link Variant}'s parents.
202
+ */
203
+ get inheritedElements(): Element[] {
204
+ let elements: Element[] = [];
205
+ this.ancestors.forEach( ancestor => {
206
+ elements = concat( elements, ancestor.elements );
207
+ } );
208
+ return concat( elements, this.elements );
209
+ }
210
+
211
+ /**
212
+ * All TransformNodes inherited from this {@link Variant}'s parents.
213
+ */
214
+ get inheritedNodes(): TransformNode[] {
215
+ let nodes: TransformNode[] = [];
216
+ this.ancestors.forEach( ancestor => {
217
+ nodes = concat( nodes, ancestor.nodes );
218
+ } );
219
+ return concat( nodes, this.nodes );
220
+ }
221
+
222
+ /**
223
+ * All TransformNodes inherited from this {@link Variant}'s parents mapped flat with a {@link DottedPath}.
224
+ */
225
+ get inheritedDottedNodes(): Map<DottedPath, TransformNode> {
226
+ let dottedNodes = this.dottedNodes;
227
+ this.ancestors.forEach( ancestor => {
228
+ dottedNodes = mergeMaps( dottedNodes, ancestor.dottedNodes );
229
+ } );
230
+ return dottedNodes;
231
+ }
232
+
233
+ /**
234
+ * The {@link ParameterDeclarations} inherited from this {@link Variant}'s parents.
235
+ */
236
+ get inheritedParameterDeclaration(): ParameterDeclarations {
237
+ let declaration = {};
238
+ this.ancestors.forEach( ancestor => {
239
+ merge( declaration, ancestor.parameterDeclaration );
240
+ } );
241
+ return merge( declaration, this.parameterDeclaration );
242
+ }
243
+
244
+ /**
245
+ * The {@link ParameterBag} inherited from this {@link Variant}'s parents.
246
+ */
247
+ get inheritedParameters(): ParameterBag {
248
+ let parameters = {};
249
+ this.ancestors.forEach( ancestor => {
250
+ merge( parameters, ancestor.parameters );
251
+ } );
252
+ return merge( parameters, this.parameters );
253
+ }
254
+
255
+ /**
256
+ * All Materials from this {@link Variant}'s parents.
257
+ */
258
+ get inheritedMaterials(): Material[] {
259
+ let materials: Material[] = [];
260
+ this.ancestors.forEach( ancestor => {
261
+ materials = concat( materials, ancestor.materials );
262
+ } );
263
+ return concat( materials, this.materials );
264
+ }
265
+
266
+ /**
267
+ * Gets the direct children of the current {@link Variant}.
268
+ */
269
+ public async getChildren(): Promise<Variant[]> {
270
+ const children: Variant[] = [];
271
+ for( const name in this.structureJson.variants ) {
272
+ children.push( await this.getDescendant( name ) );
273
+ }
274
+ return children;
275
+ }
276
+
277
+ /**
278
+ * Gets a descendant {@link Variant} of the current {@link Variant} relative to its {@link DottedPath}.
279
+ * If you have the dotted path `_.product_x.variant_blue.with_yellow_highlight` in a tree and you operate on the
280
+ * `product_x`, you can call `this.getDescendant('variant_blue.with_yellow_highlight')` to get the lowermost
281
+ * {@link Variant}.
282
+ */
283
+ public async getDescendant( dottedPath: DottedPathArgument ): Promise<Variant> {
284
+ const _dottedPath = DottedPath.create( dottedPath );
285
+ const [name, ...descendantParts] = _dottedPath.parts;
286
+ let variant;
287
+ if( this._children.has( name ) ) {
288
+ variant = this._children.get( name );
289
+ } else {
290
+ if( !this.structureJson.variants ) {
291
+ throw new Error( `Missing key "variants" in JSON structure for variant "${this.id}".` );
292
+ }
293
+ if( !this.structureJson.variants[name] ) {
294
+ throw new Error( `Variant "${_dottedPath.path}" not defined in JSON structure for variant "${this.id}".` );
295
+ }
296
+ if( this.structureJson.variants[name].file ) {
297
+ const file = this.structureJson.variants[name].file as string;
298
+ variant = await Variant.create( name, await loadJson<StructureJson>( file ), this.viewer, this );
299
+ } else {
300
+ variant = await Variant.create( name, this.structureJson.variants[name], this.viewer, this );
301
+ }
302
+ this._children.set( name, variant );
303
+ }
304
+ if( !variant ) {
305
+ throw new Error( `Variant "${_dottedPath.path}" was not created.` );
306
+ }
307
+ if( descendantParts.length > 0 ) {
308
+ return await variant.getDescendant( DottedPath.createFromParts( descendantParts ) );
309
+ }
310
+ return variant;
311
+ }
312
+
313
+ /**
314
+ * Gets the desired {@link Element} of the current {@link Variant} relative to its {@link DottedPath}.
315
+ * Uses the mechanism of {@link getDescendant} to resolve the appropriate variant in tree.
316
+ */
317
+ public async getElement( dottedPath: DottedPathArgument ): Promise<Element> {
318
+ const _dottedPath = DottedPath.create( dottedPath );
319
+ const elementName = _dottedPath.popPart();
320
+ let variant: Variant = this;
321
+ if( _dottedPath.parts.length > 0 ) {
322
+ variant = await this.getDescendant( _dottedPath );
323
+ }
324
+ if( variant.inheritedElements.length === 0 ) {
325
+ throw new Error( `No elements for variant "${variant.id}" found. ` +
326
+ `Either none are defined or they are not initialized (are you operating on the appropriate living?).` );
327
+ }
328
+ let element;
329
+ variant.inheritedElements.forEach( _element => {
330
+ if( _element.name === elementName ) {
331
+ element = _element;
332
+ }
333
+ } );
334
+ if( !element ) {
335
+ throw new Error( `Element with name "${elementName}" does not exist for variant "${variant.id}".` );
336
+ }
337
+ return element;
338
+ }
339
+
340
+ /**
341
+ * A proxy for directly getting a Node from an {@link Element} by its {@link DottedPath}s.
342
+ */
343
+ public async getNode( elementDottedPath: DottedPathArgument, nodeDottedPath: DottedPathArgument ): Promise<TransformNode> {
344
+ const element = await this.getElement( elementDottedPath );
345
+ return element.getNode( nodeDottedPath );
346
+ }
347
+
348
+ /**
349
+ * A proxy for directly getting a Mesh from an {@link Element} by its {@link DottedPath}s.
350
+ */
351
+ public async getMesh( elementDottedPath: DottedPathArgument, meshDottedPath: DottedPathArgument ): Promise<Mesh|null> {
352
+ const element = await this.getElement( elementDottedPath );
353
+ return element.getMesh( meshDottedPath );
354
+ }
355
+
356
+ /**
357
+ * Gets the Material defined in one of the variants glTFs by its id.
358
+ */
359
+ public getMaterial( id: string ): Material {
360
+ for( const material of this.inheritedMaterials ) {
361
+ if( material.id === id ) {
362
+ return material;
363
+ }
364
+ }
365
+ // fallback to dynamically created materials on scene
366
+ for( const material of this.viewer.scene.materials ) {
367
+ if( material.id === id ) {
368
+ return material;
369
+ }
370
+ }
371
+ throw new Error( `Material with id "${id}" does not exist for variant "${this.id}".` );
372
+ }
373
+
374
+ /**
375
+ * Creates a living clone of this {@link Variant}. Will clone all parent {@link Variant}s in tree.
376
+ *
377
+ * @emit {@link Event.VARIANT_CREATED}
378
+ * @ignore
379
+ */
380
+ public async createLiving( parameters?: ParameterBag ): Promise<Variant> {
381
+ const parent = await this.parent?.createLiving();
382
+ const variant = new Variant( this.name, this._structureJson, this.viewer, parent );
383
+ parent?._children.set( variant.name, variant );
384
+ variant.assetContainer = this.assetContainer;
385
+ variant.parameterObservers = cloneDeep( this.parameterObservers );
386
+ variant.createElements();
387
+ variant.addParameterObservers();
388
+ await variant.bootstrapParameters( parameters );
389
+ this.broadcastEvent( Event.VARIANT_CREATED, variant );
390
+ return variant;
391
+ }
392
+
393
+ /**
394
+ * Destroys this {@link Variant}, all parents and destroy the {@link Element}s.
395
+ */
396
+ public destroy(): Variant {
397
+ this.elements.forEach( element => element.destroy() );
398
+ if( this.parent ) {
399
+ this.parent.destroy();
400
+ }
401
+ this.broadcastEvent( Event.VARIANT_DESTROYED, this );
402
+ return this;
403
+ }
404
+
405
+ /**
406
+ * Places the given {@link ParameterBag} in the {@link Variant}'s parameters, replaces all patterns in the
407
+ * {@link StructureJson}, broadcasts all {@link ParameterObserver}s and delegates them to its {@link Element}s.
408
+ *
409
+ * @emit {@link Event.VARIANT_PARAMETER_COMMITTED}
410
+ */
411
+ public async commitParameters( parameters?: ParameterBag ): Promise<Variant> {
412
+ parameters = merge( {}, parameters );
413
+
414
+ // remember old parameter values for later comparison
415
+ const oldParameters = cloneDeep( this.inheritedParameters );
416
+
417
+ // replace patterns in given parameters
418
+ let _parameters = JSON.stringify( parameters );
419
+ for( const parameter in this.inheritedParameters ) {
420
+ const value = this.inheritedParameters[parameter];
421
+ const search = new RegExp( `\\$\\{${parameter}\\}`, 'g' );
422
+ _parameters = _parameters.replace( search, value.toString() );
423
+ }
424
+ merge( parameters, JSON.parse( _parameters ) );
425
+
426
+ // merge inherited parameters and replaced given parameters
427
+ const mergedParameters = merge( {}, this.inheritedParameters, parameters );
428
+
429
+ // replace patterns in structure parameters
430
+ const structureParameters = this._structureJson.parameters || {};
431
+ let _structureParameters = JSON.stringify( structureParameters );
432
+ for( const parameter in mergedParameters ) {
433
+ const value = mergedParameters[parameter];
434
+ const search = new RegExp( `\\$\\{${parameter}\\}`, 'g' );
435
+ _structureParameters = _structureParameters.replace( search, value.toString() );
436
+ }
437
+ const replacedStructureParameters = JSON.parse( _structureParameters );
438
+
439
+ // calculate which replaced structure parameters have changed and should overload given parameters
440
+ const differentStructureParameters: ParameterBag = {};
441
+ for( const parameter in replacedStructureParameters ) {
442
+ if( !isEqual(structureParameters[parameter], replacedStructureParameters[parameter]) ) {
443
+ differentStructureParameters[parameter] = replacedStructureParameters[parameter];
444
+ }
445
+ }
446
+
447
+ // merge replaced structure parameters and given inherited parameters to structure parameters
448
+ merge( this.parameters, mergedParameters, differentStructureParameters );
449
+
450
+ // inherited parameters are now the new parameters to process
451
+ const newParameters = this.inheritedParameters;
452
+
453
+ // replace all parameter patterns in structure json
454
+ let structure = JSON.stringify( this._structureJson );
455
+ for( const parameter in newParameters ) {
456
+ const value = newParameters[parameter];
457
+ const search = new RegExp( `\\$\\{${parameter}\\}`, 'g' );
458
+ structure = structure.replace( search, value.toString() );
459
+ }
460
+ this.structureJson = JSON.parse( structure );
461
+
462
+ // handle parameter observers
463
+ let observerPromises: Promise<void | ParameterObserver>[] = [];
464
+ for( const parameter in newParameters ) {
465
+ const oldParameterValue = oldParameters[parameter];
466
+ const newParameterValue = newParameters[parameter];
467
+ this.assertParameter( this.inheritedParameterDeclaration, parameter, newParameterValue );
468
+ if( oldParameterValue === newParameterValue && this.parametersInitialized ) {
469
+ continue;
470
+ }
471
+ // parameter changed
472
+ const parameterObservers = mergeMaps( this._parameterObservers, this.parameterObservers );
473
+ if( parameterObservers.has( parameter ) ) {
474
+ const observers = parameterObservers.get( parameter )!;
475
+ observerPromises = concat(observerPromises, observers.map( observer => {
476
+ const observerResult = observer( this, oldParameterValue, newParameterValue );
477
+ return Promise.resolve( observerResult ).then( () => {
478
+ if( this.parametersInitialized ) {
479
+ this.broadcastEvent( Event.VARIANT_PARAMETER_COMMITTED,
480
+ this, parameter, oldParameterValue, newParameterValue );
481
+ }
482
+ } );
483
+ } ) );
484
+ }
485
+ }
486
+ await Promise.all( observerPromises );
487
+
488
+ // broadcast that bag has been committed
489
+ this.broadcastEvent(Event.VARIANT_PARAMETER_BAG_COMMITTED, this, oldParameters, newParameters);
490
+
491
+ // commit parameters to elements
492
+ const elementPromises: Promise<Element>[] = this.elements.map( element => {
493
+ let _elementDefinition = JSON.stringify( this._structureJson.elements![element.name] );
494
+ const elementParameters: ParameterBag = {};
495
+ for( const parameter in newParameters ) {
496
+ if( DottedPath.create( parameter ).firstPart !== element.name ) {
497
+ continue;
498
+ }
499
+ // we got an element parameter
500
+ let newParameterValue = newParameters[parameter];
501
+ const elementParameter = parameter.replace( `${element.name}.`, '' );
502
+ // If the variant is explicitly hidden, we must not override the visibility with element parameters. We need
503
+ // an exception for visibility to avoid overloading already applied element parameters with element parameters
504
+ // defined in the variant spec ("dotted parameters").
505
+ // @see https://github.com/Combeenation/3d-viewer/issues/44
506
+ if( elementParameter === Parameter.VISIBLE && newParameters[Parameter.VISIBLE] === false ) {
507
+ newParameterValue = false;
508
+ }
509
+ elementParameters[elementParameter] = newParameterValue;
510
+ const search = new RegExp( `\\$\\{${elementParameter}\\}`, 'g' );
511
+ _elementDefinition = _elementDefinition.replace( search, newParameterValue.toString() );
512
+ }
513
+ this.structureJson.elements![this.name] = JSON.parse( _elementDefinition );
514
+ return element.commitParameters( elementParameters );
515
+ } );
516
+ await Promise.all( elementPromises );
517
+
518
+ // propagate parameters to parent
519
+ if( this.parent ) {
520
+ await this.parent.commitParameters( this.parameters );
521
+ }
522
+
523
+ return this;
524
+ }
525
+
526
+ /**
527
+ * Adds an observer function for camera matrix changes for given `dottedPath` representing the {@link Element}
528
+ * and the `traceable`. The `observer` gets 2 parameters: the `AbstractMesh` and a `ClientRect` object.
529
+ */
530
+ public async addTraceableObserver( dottedPath: DottedPathArgument,
531
+ observer: CallableFunction,
532
+ payload?: any ): Promise<Element> {
533
+ const _dottedPath = DottedPath.create( dottedPath );
534
+ const traceableName = _dottedPath.popPart();
535
+ if( !traceableName ) {
536
+ throw new Error( `The dottedPath must consist of the element and the name of the defined corresponding ` +
537
+ `traceable ("${_dottedPath.path}" given).` );
538
+ }
539
+ const element = await this.getElement( _dottedPath );
540
+ return element.addTraceableObserver( traceableName, observer, payload );
541
+ }
542
+
543
+ /**
544
+ * Loads {@link glTFUri} with assets, adds them to the {@link Variant}'s `assetContainer` and deactivates the meshes.
545
+ * (for further processing).
546
+ * @emits {@link Event.ASSET_LOADING_START}
547
+ * @emits {@link Event.ASSET_LOADING_END}
548
+ */
549
+ protected async loadAssets(): Promise<Variant> {
550
+ this.broadcastEvent( Event.ASSET_LOADING_START, this );
551
+ return new Promise( resolve => {
552
+ if( !this.structureJson ) {
553
+ this.broadcastEvent( Event.ASSET_LOADING_END, this );
554
+ return resolve( this );
555
+ }
556
+ if( !this.glTF ) {
557
+ this.broadcastEvent( Event.ASSET_LOADING_END, this );
558
+ return resolve( this );
559
+ }
560
+ SceneLoader.LoadAssetContainerAsync( this.glTF.rootUrl, this.glTF.fileName, this.viewer.scene ).then( container => {
561
+ this.assetContainer = container;
562
+ const nodes = this.assetContainer.getNodes().filter( n => n instanceof TransformNode ) as TransformNode[];
563
+ nodes.forEach( node => {
564
+ deactivateTransformNode( node, false );
565
+ injectTransformNodeMetadata( node, { dottedPath: getDottedPathForTransformNode( node ) }, false );
566
+ } );
567
+ this.broadcastEvent( Event.ASSET_LOADING_END, this );
568
+ resolve( this );
569
+ } ).catch( reason => {
570
+ this.broadcastEvent( Event.ASSET_LOADING_END, this );
571
+ throw new Error( `Error loading assets for variant "${this.id}": ${reason}.` );
572
+ } );
573
+ } );
574
+ }
575
+
576
+ /**
577
+ * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
578
+ */
579
+ protected async commitParameterToElements( parameter: string, value: ParameterValue ) {
580
+ const promises = [];
581
+ for( const element of this.elements ) {
582
+ promises.push( element.commitParameter( parameter, value ) );
583
+ }
584
+ await Promise.all( promises );
585
+ }
586
+
587
+ /**
588
+ * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
589
+ */
590
+ protected addParameterObservers(): Variant {
591
+ this._parameterObservers.set( Parameter.VISIBLE, [
592
+ async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
593
+ await variant.commitParameterToElements( Parameter.VISIBLE, newValue );
594
+ }
595
+ ] );
596
+ this._parameterObservers.set( Parameter.SCALING, [
597
+ async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
598
+ await variant.commitParameterToElements( Parameter.SCALING, newValue );
599
+ }
600
+ ] );
601
+ this._parameterObservers.set( Parameter.MATERIAL, [
602
+ async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
603
+ await variant.commitParameterToElements( Parameter.MATERIAL, newValue );
604
+ }
605
+ ] );
606
+ this._parameterObservers.set( Parameter.MATERIAL_COLOR, [
607
+ async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
608
+ await variant.commitParameterToElements( Parameter.MATERIAL_COLOR, newValue );
609
+ }
610
+ ] );
611
+ this._parameterObservers.set( Parameter.MATERIAL_METALLNESS, [
612
+ async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
613
+ await variant.commitParameterToElements( Parameter.MATERIAL_METALLNESS, newValue );
614
+ }
615
+ ] );
616
+ this._parameterObservers.set( Parameter.MATERIAL_ROUGHNESS, [
617
+ async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
618
+ await variant.commitParameterToElements( Parameter.MATERIAL_ROUGHNESS, newValue );
619
+ }
620
+ ] );
621
+ this._parameterObservers.set( Parameter.HIGHLIGHT_COLOR, [
622
+ async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
623
+ await variant.commitParameterToElements( Parameter.HIGHLIGHT_COLOR, newValue );
624
+ }
625
+ ] );
626
+ this._parameterObservers.set( Parameter.HIGHLIGHTED, [
627
+ async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
628
+ await variant.commitParameterToElements( Parameter.HIGHLIGHTED, newValue );
629
+ }
630
+ ] );
631
+ this._parameterObservers.set( Parameter.POSITION, [
632
+ async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
633
+ await variant.commitParameterToElements( Parameter.POSITION, newValue );
634
+ }
635
+ ] );
636
+ this._parameterObservers.set( Parameter.ROTATION, [
637
+ async ( variant: Variant, oldValue: ParameterValue, newValue: ParameterValue ) => {
638
+ await variant.commitParameterToElements( Parameter.ROTATION, newValue );
639
+ }
640
+ ] );
641
+ return this;
642
+ }
643
+
644
+ /**
645
+ * Creates {@link Element}s and clones nodes into them.
646
+ */
647
+ protected createElements(): Variant {
648
+ for( const elementName in this.structureJson.elements || {} ) {
649
+ this.elements.push( new Element( this, elementName ) );
650
+ }
651
+ // inject node meta to all inherited elements
652
+ // we do this to inject the deepest and most concrete variant information to all cloned nodes in the tree
653
+ this.inheritedElements.forEach( element => {
654
+ element.nodes.forEach( node => {
655
+ injectTransformNodeMetadata( node, { variant: this, element: element } );
656
+ } );
657
+ } );
658
+ return this;
659
+ }
660
+
661
+ /**
662
+ * Bootstrapping for parameters. It sets the `parametersInitialized` to true for all ancestors.
663
+ */
664
+ protected async bootstrapParameters( parameters?: ParameterBag ): Promise<Variant> {
665
+ await this.commitParameters( merge( cloneDeep( this.parameters ), parameters ) );
666
+ concat( this.ancestors, this ).forEach( ancestor => ancestor.parametersInitialized = true );
667
+ return this;
668
+ }
669
+
670
+ }