@combeenation/3d-viewer 9.0.0 → 9.0.1

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