@combeenation/3d-viewer 9.3.0 → 10.0.0-alpha3

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 (111) hide show
  1. package/README.md +9 -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 +666 -667
  8. package/dist/lib-cjs/api/classes/element.js.map +1 -1
  9. package/dist/lib-cjs/api/classes/event.d.ts +401 -401
  10. package/dist/lib-cjs/api/classes/event.js +424 -424
  11. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  12. package/dist/lib-cjs/api/classes/eventBroadcaster.js +49 -49
  13. package/dist/lib-cjs/api/classes/fuzzyMap.d.ts +7 -7
  14. package/dist/lib-cjs/api/classes/fuzzyMap.js +21 -21
  15. package/dist/lib-cjs/api/classes/parameter.d.ts +410 -410
  16. package/dist/lib-cjs/api/classes/parameter.js +642 -642
  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 +871 -871
  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 +211 -213
  30. package/dist/lib-cjs/api/classes/viewer.js +736 -717
  31. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  32. package/dist/lib-cjs/api/classes/viewerError.d.ts +43 -43
  33. package/dist/lib-cjs/api/classes/viewerError.js +55 -55
  34. package/dist/lib-cjs/api/classes/viewerLight.d.ts +66 -66
  35. package/dist/lib-cjs/api/classes/viewerLight.js +344 -348
  36. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  37. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  38. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  39. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +13 -13
  40. package/dist/lib-cjs/api/internal/sceneSetup.js +224 -226
  41. package/dist/lib-cjs/api/internal/sceneSetup.js.map +1 -1
  42. package/dist/lib-cjs/api/manager/animationManager.d.ts +30 -30
  43. package/dist/lib-cjs/api/manager/animationManager.js +126 -126
  44. package/dist/lib-cjs/api/manager/gltfExportManager.d.ts +102 -102
  45. package/dist/lib-cjs/api/manager/gltfExportManager.js +322 -322
  46. package/dist/lib-cjs/api/manager/sceneManager.d.ts +33 -33
  47. package/dist/lib-cjs/api/manager/sceneManager.js +128 -128
  48. package/dist/lib-cjs/api/manager/tagManager.d.ts +118 -118
  49. package/dist/lib-cjs/api/manager/tagManager.js +535 -535
  50. package/dist/lib-cjs/api/manager/textureLoadManager.d.ts +22 -22
  51. package/dist/lib-cjs/api/manager/textureLoadManager.js +98 -98
  52. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +106 -106
  53. package/dist/lib-cjs/api/manager/variantInstanceManager.js +290 -290
  54. package/dist/lib-cjs/api/store/specStorage.d.ts +32 -32
  55. package/dist/lib-cjs/api/store/specStorage.js +65 -65
  56. package/dist/lib-cjs/api/util/babylonHelper.d.ts +238 -238
  57. package/dist/lib-cjs/api/util/babylonHelper.js +826 -826
  58. package/dist/lib-cjs/api/util/geometryHelper.d.ts +7 -7
  59. package/dist/lib-cjs/api/util/geometryHelper.js +115 -115
  60. package/dist/lib-cjs/api/util/globalTypes.d.ts +484 -484
  61. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  62. package/dist/lib-cjs/api/util/resourceHelper.d.ts +58 -58
  63. package/dist/lib-cjs/api/util/resourceHelper.js +214 -214
  64. package/dist/lib-cjs/api/util/sceneLoaderHelper.d.ts +44 -44
  65. package/dist/lib-cjs/api/util/sceneLoaderHelper.js +175 -175
  66. package/dist/lib-cjs/api/util/stringHelper.d.ts +13 -13
  67. package/dist/lib-cjs/api/util/stringHelper.js +32 -32
  68. package/dist/lib-cjs/api/util/structureHelper.d.ts +9 -9
  69. package/dist/lib-cjs/api/util/structureHelper.js +64 -64
  70. package/dist/lib-cjs/buildinfo.json +3 -3
  71. package/dist/lib-cjs/commonjs.tsconfig.tsbuildinfo +1 -1
  72. package/dist/lib-cjs/index.d.ts +54 -54
  73. package/dist/lib-cjs/index.js +117 -117
  74. package/package.json +84 -82
  75. package/src/api/classes/animationInterface.ts +10 -10
  76. package/src/api/classes/dottedPath.ts +181 -181
  77. package/src/api/classes/element.ts +723 -723
  78. package/src/api/classes/event.ts +457 -457
  79. package/src/api/classes/eventBroadcaster.ts +52 -52
  80. package/src/api/classes/fuzzyMap.ts +21 -21
  81. package/src/api/classes/parameter.ts +686 -686
  82. package/src/api/classes/parameterObservable.ts +73 -73
  83. package/src/api/classes/parameterizable.ts +87 -87
  84. package/src/api/classes/placementAnimation.ts +162 -162
  85. package/src/api/classes/variant.ts +964 -964
  86. package/src/api/classes/variantInstance.ts +123 -123
  87. package/src/api/classes/variantParameterizable.ts +83 -83
  88. package/src/api/classes/viewer.ts +786 -770
  89. package/src/api/classes/viewerError.ts +63 -63
  90. package/src/api/classes/viewerLight.ts +335 -339
  91. package/src/api/internal/debugViewer.ts +90 -90
  92. package/src/api/internal/lensRendering.ts +9 -9
  93. package/src/api/internal/sceneSetup.ts +203 -205
  94. package/src/api/manager/animationManager.ts +143 -143
  95. package/src/api/manager/gltfExportManager.ts +312 -312
  96. package/src/api/manager/sceneManager.ts +134 -134
  97. package/src/api/manager/tagManager.ts +576 -576
  98. package/src/api/manager/textureLoadManager.ts +96 -96
  99. package/src/api/manager/variantInstanceManager.ts +306 -306
  100. package/src/api/store/specStorage.ts +68 -68
  101. package/src/api/util/babylonHelper.ts +915 -915
  102. package/src/api/util/geometryHelper.ts +140 -140
  103. package/src/api/util/globalTypes.ts +560 -560
  104. package/src/api/util/resourceHelper.ts +201 -201
  105. package/src/api/util/sceneLoaderHelper.ts +170 -170
  106. package/src/api/util/stringHelper.ts +30 -30
  107. package/src/api/util/structureHelper.ts +63 -63
  108. package/src/buildinfo.json +3 -3
  109. package/src/dev.ts +70 -62
  110. package/src/index.ts +103 -103
  111. package/src/types.d.ts +49 -38
@@ -1,964 +1,964 @@
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.assetContainer.skeletons.forEach(skeleton => this.viewer.scene.skeletons.push(skeleton));
693
- this.broadcastEvent(Event.ASSET_LOADING_END, this);
694
- resolve(this);
695
- },
696
- // on progress
697
- undefined,
698
- // on error
699
- (scene, msg, exc) => {
700
- this.broadcastEvent(Event.ASSET_LOADING_END, this);
701
-
702
- /**
703
- * @preserve (4 webpack terser plugin)
704
- * If you're here and the shown error doesn't seem to make any sense:
705
- * BJS "swallows" all exceptions within our success callback above and reports some generic error like
706
- * "Unable to load from https://some/url.babylon" etc.
707
- * -> The real reason for the error **could** be that some of our code within the above success callback has
708
- * thrown.
709
- */
710
- const error = new ViewerError({
711
- id: ViewerErrorIds.AssetLoadingFailed,
712
- message: `Error loading assets for variant "${this.id}": ${msg}.`,
713
- });
714
- reject(error);
715
- }
716
- );
717
- });
718
- }
719
-
720
- /**
721
- * Commits given parameters to all {@link Element}s.
722
- */
723
- protected async commitParametersToElements(parameters: ParameterBag) {
724
- await Promise.all(
725
- this.elements.map(element => this.commitParametersToVariantParameterizable(parameters, element, 'elements'))
726
- );
727
- }
728
-
729
- /**
730
- * Commits given parameters to all {@link ViewerLight}s.
731
- */
732
- protected async commitParametersToViewerLights(parameters: ParameterBag) {
733
- await Promise.all(
734
- this.viewerLights.map(viewerLight =>
735
- this.commitParametersToVariantParameterizable(parameters, viewerLight, 'lights')
736
- )
737
- );
738
- }
739
-
740
- /**
741
- * Commits given parameters to a {@link VariantParameterizable} and updates the according definition with given
742
- * key in the {@link StructureJson}. The `definitionKey` "elements" for example will update the definition in
743
- * `this.structureJson.elements`.
744
- */
745
- protected async commitParametersToVariantParameterizable(
746
- parameters: ParameterBag,
747
- parameterizable: VariantParameterizable,
748
- definitionKey: string
749
- ): Promise<ParameterObservable> {
750
- const initialDefinition = get(this._structureJson, definitionKey)[parameterizable.name];
751
- let initialDefinitionStr = JSON.stringify(initialDefinition);
752
- const _parameters: ParameterBag = {};
753
- for (const parameter in parameters) {
754
- const dpp = DottedPath.create(parameter);
755
- if (dpp.shiftPart() !== parameterizable.name) {
756
- continue;
757
- }
758
- // we got a parameterizable ("element") parameter
759
- let parameterValue = parameters[parameter];
760
- const parameterizableParameter = dpp.path;
761
- // If the variant is explicitly hidden, we must not override the visibility with element parameters. We need
762
- // an exception for visibility to avoid overloading already applied element parameters with element parameters
763
- // defined in the variant spec ("dotted parameters").
764
- // @see https://github.com/Combeenation/3d-viewer/issues/44
765
- const visibleParamValue = parameters[Parameter.VISIBLE];
766
- const isVisible = undefined === visibleParamValue || Parameter.parseBoolean(visibleParamValue);
767
- if (parameterizableParameter === Parameter.VISIBLE && !isVisible) {
768
- parameterValue = false;
769
- }
770
- _parameters[parameterizableParameter] = parameterValue;
771
- const search = new RegExp(`\\$\\{${parameterizableParameter}\\}`, 'g');
772
- initialDefinitionStr = initialDefinitionStr.replace(search, parameterValue.toString());
773
- }
774
- const definition = get(this.structureJson, definitionKey);
775
- definition[this.name] = JSON.parse(initialDefinitionStr);
776
- set(this.structureJson, definitionKey, definition);
777
- return await parameterizable.commitParameters(_parameters);
778
- }
779
-
780
- /**
781
- * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
782
- */
783
- protected async commitParameterToElements(parameter: string, value: ParameterValue): Promise<Variant> {
784
- const promises = [];
785
- for (const element of this.elements) {
786
- const paramShowsVariant = Parameter.VISIBLE === parameter && value;
787
-
788
- // Fixes https://combeenation.youtrack.cloud/issue/CB-7773
789
- // Don't enable/show the variants element if it is explicitly hidden via its element parameters.
790
- // E.g. via spec:
791
- // ```
792
- // variants: {
793
- // theVariant: {
794
- // elements: {
795
- // Main: ['root.main'],
796
- // Secondary: ['root.secondary'],
797
- // },
798
- // parameters: {
799
- // // !!! The element `Secondary` should **not** be enabled when its containing variant is enabled !!!
800
- // 'Secondary.visible': false,
801
- // }
802
- // }
803
- // }
804
- // ```
805
- const elVisibleParamPath = DottedPath.create([element.name, Parameter.VISIBLE]).toString();
806
- const elVisibleParamValue = this.inheritedParameters[elVisibleParamPath];
807
- const elVisibleParamValueParsed = elVisibleParamValue && Parameter.parseBoolean(elVisibleParamValue);
808
- const elIsHiddenViaParams = elVisibleParamValueParsed === false;
809
- if (paramShowsVariant && elIsHiddenViaParams) continue;
810
-
811
- // Fixes https://combeenation.youtrack.cloud/issue/CB-7809
812
- // Apply element material before showing the element to prevent loading of the elements "original" material which
813
- // is never shown when "overwritten" by elements material param.
814
- const elMaterialParamPath = DottedPath.create([element.name, Parameter.MATERIAL]).toString();
815
- const elMaterialParamValue = this.inheritedParameters[elMaterialParamPath];
816
- if (paramShowsVariant && elMaterialParamValue) {
817
- await element.commitParameter(Parameter.MATERIAL, elMaterialParamValue);
818
- }
819
-
820
- promises.push(element.commitParameter(parameter, value));
821
- }
822
- await Promise.all(promises);
823
- return this;
824
- }
825
-
826
- /**
827
- * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
828
- */
829
- protected async commitParameterToViewerLights(parameter: string, value: ParameterValue): Promise<Variant> {
830
- const promises = [];
831
- for (const viewerLight of this.viewerLights) {
832
- promises.push(viewerLight.commitParameter(parameter, value));
833
- }
834
- await Promise.all(promises);
835
- return this;
836
- }
837
-
838
- /**
839
- * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
840
- */
841
- protected addParameterObservers(): Variant {
842
- this._parameterObservers.set(Parameter.VISIBLE, [
843
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
844
- await variant.commitParameterToElements(Parameter.VISIBLE, newValue);
845
- await variant.commitParameterToViewerLights(Parameter.VISIBLE, newValue);
846
- },
847
- ]);
848
- this._parameterObservers.set(Parameter.SCALING, [
849
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
850
- await variant.commitParameterToElements(Parameter.SCALING, newValue);
851
- await variant.commitParameterToViewerLights(Parameter.SCALING, newValue);
852
- },
853
- ]);
854
- this._parameterObservers.set(Parameter.MATERIAL, [
855
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
856
- await variant.commitParameterToElements(Parameter.MATERIAL, newValue);
857
- },
858
- ]);
859
- this._parameterObservers.set(Parameter.MATERIAL_COLOR, [
860
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
861
- await variant.commitParameterToElements(Parameter.MATERIAL_COLOR, newValue);
862
- },
863
- ]);
864
- this._parameterObservers.set(Parameter.MATERIAL_METALLNESS, [
865
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
866
- await variant.commitParameterToElements(Parameter.MATERIAL_METALLNESS, newValue);
867
- },
868
- ]);
869
- this._parameterObservers.set(Parameter.MATERIAL_ROUGHNESS, [
870
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
871
- await variant.commitParameterToElements(Parameter.MATERIAL_ROUGHNESS, newValue);
872
- },
873
- ]);
874
- this._parameterObservers.set(Parameter.HIGHLIGHT_COLOR, [
875
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
876
- await variant.commitParameterToElements(Parameter.HIGHLIGHT_COLOR, newValue);
877
- },
878
- ]);
879
- this._parameterObservers.set(Parameter.HIGHLIGHTED, [
880
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
881
- await variant.commitParameterToElements(Parameter.HIGHLIGHTED, newValue);
882
- },
883
- ]);
884
- this._parameterObservers.set(Parameter.POSITION, [
885
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
886
- await variant.commitParameterToElements(Parameter.POSITION, newValue);
887
- await variant.commitParameterToViewerLights(Parameter.POSITION, newValue);
888
- },
889
- ]);
890
- this._parameterObservers.set(Parameter.ROTATION, [
891
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
892
- await variant.commitParameterToElements(Parameter.ROTATION, newValue);
893
- await variant.commitParameterToViewerLights(Parameter.ROTATION, newValue);
894
- },
895
- ]);
896
- this._parameterObservers.set(Parameter.CAST_SHADOW, [
897
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
898
- await variant.commitParameterToElements(Parameter.CAST_SHADOW, newValue);
899
- },
900
- ]);
901
- this._parameterObservers.set(Parameter.CAST_SHADOW_FROM_LIGHTS, [
902
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
903
- await variant.commitParameterToElements(Parameter.CAST_SHADOW_FROM_LIGHTS, newValue);
904
- },
905
- ]);
906
- this._parameterObservers.set(Parameter.RECEIVE_SHADOWS, [
907
- async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
908
- await variant.commitParameterToElements(Parameter.RECEIVE_SHADOWS, newValue);
909
- },
910
- ]);
911
- return this;
912
- }
913
-
914
- /**
915
- * Creates {@link Element}s and clones nodes into them.
916
- */
917
- protected async createElements(forInstance?: string): Promise<Variant> {
918
- this.createElementDefinitionsIfNotExist();
919
- for (const name in this.structureJson.elements || {}) {
920
- this.elements.push(await Element.create(this, name));
921
- }
922
- // inject node meta to all inherited elements
923
- // we do this to inject the deepest and most concrete variant information to all cloned nodes in the tree
924
- this.inheritedElements.forEach(element =>
925
- element.nodes.forEach(node => injectMetadata(node, { variant: this, variantParameterizable: element }))
926
- );
927
- return this;
928
- }
929
-
930
- /**
931
- * Creates {@link ViewerLight}s.
932
- */
933
- protected async createViewerLights(): Promise<Variant> {
934
- for (const name in this.structureJson.lights || {}) {
935
- this.viewerLights.push(await ViewerLight.create(this, name));
936
- }
937
- this.inheritedViewerLights.forEach(viewerLight => {
938
- injectMetadata(viewerLight.light, { variant: this, variantParameterizable: viewerLight });
939
- });
940
- return this;
941
- }
942
-
943
- /**
944
- * Bootstrapping for parameters. It sets the `parametersInitialized` to true for all ancestors.
945
- */
946
- protected async bootstrapParameters(parameters?: ParameterBag): Promise<Variant> {
947
- await this.commitParameters(merge(cloneDeep(this.parameters), parameters));
948
- concat(this.ancestors, this).forEach(ancestor => (ancestor.parametersInitialized = true));
949
- return this;
950
- }
951
-
952
- /**
953
- * Ensures there is at least one "Main" {@link Element} for the {@link Variant} with all "root nodes" defined in path.
954
- */
955
- protected createElementDefinitionsIfNotExist() {
956
- if (this._structureJson.elements || this.inheritedNodes.length === 0) {
957
- return;
958
- }
959
- this._structureJson.elements = {
960
- Main: { paths: { include: this.inheritedNodes.map(node => node.metadata.dottedPath.path) } },
961
- };
962
- this.structureJson.elements = cloneDeep(this._structureJson.elements);
963
- }
964
- }
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.assetContainer.skeletons.forEach(skeleton => this.viewer.scene.skeletons.push(skeleton));
693
+ this.broadcastEvent(Event.ASSET_LOADING_END, this);
694
+ resolve(this);
695
+ },
696
+ // on progress
697
+ undefined,
698
+ // on error
699
+ (scene, msg, exc) => {
700
+ this.broadcastEvent(Event.ASSET_LOADING_END, this);
701
+
702
+ /**
703
+ * @preserve (4 webpack terser plugin)
704
+ * If you're here and the shown error doesn't seem to make any sense:
705
+ * BJS "swallows" all exceptions within our success callback above and reports some generic error like
706
+ * "Unable to load from https://some/url.babylon" etc.
707
+ * -> The real reason for the error **could** be that some of our code within the above success callback has
708
+ * thrown.
709
+ */
710
+ const error = new ViewerError({
711
+ id: ViewerErrorIds.AssetLoadingFailed,
712
+ message: `Error loading assets for variant "${this.id}": ${msg}.`,
713
+ });
714
+ reject(error);
715
+ }
716
+ );
717
+ });
718
+ }
719
+
720
+ /**
721
+ * Commits given parameters to all {@link Element}s.
722
+ */
723
+ protected async commitParametersToElements(parameters: ParameterBag) {
724
+ await Promise.all(
725
+ this.elements.map(element => this.commitParametersToVariantParameterizable(parameters, element, 'elements'))
726
+ );
727
+ }
728
+
729
+ /**
730
+ * Commits given parameters to all {@link ViewerLight}s.
731
+ */
732
+ protected async commitParametersToViewerLights(parameters: ParameterBag) {
733
+ await Promise.all(
734
+ this.viewerLights.map(viewerLight =>
735
+ this.commitParametersToVariantParameterizable(parameters, viewerLight, 'lights')
736
+ )
737
+ );
738
+ }
739
+
740
+ /**
741
+ * Commits given parameters to a {@link VariantParameterizable} and updates the according definition with given
742
+ * key in the {@link StructureJson}. The `definitionKey` "elements" for example will update the definition in
743
+ * `this.structureJson.elements`.
744
+ */
745
+ protected async commitParametersToVariantParameterizable(
746
+ parameters: ParameterBag,
747
+ parameterizable: VariantParameterizable,
748
+ definitionKey: string
749
+ ): Promise<ParameterObservable> {
750
+ const initialDefinition = get(this._structureJson, definitionKey)[parameterizable.name];
751
+ let initialDefinitionStr = JSON.stringify(initialDefinition);
752
+ const _parameters: ParameterBag = {};
753
+ for (const parameter in parameters) {
754
+ const dpp = DottedPath.create(parameter);
755
+ if (dpp.shiftPart() !== parameterizable.name) {
756
+ continue;
757
+ }
758
+ // we got a parameterizable ("element") parameter
759
+ let parameterValue = parameters[parameter];
760
+ const parameterizableParameter = dpp.path;
761
+ // If the variant is explicitly hidden, we must not override the visibility with element parameters. We need
762
+ // an exception for visibility to avoid overloading already applied element parameters with element parameters
763
+ // defined in the variant spec ("dotted parameters").
764
+ // @see https://github.com/Combeenation/3d-viewer/issues/44
765
+ const visibleParamValue = parameters[Parameter.VISIBLE];
766
+ const isVisible = undefined === visibleParamValue || Parameter.parseBoolean(visibleParamValue);
767
+ if (parameterizableParameter === Parameter.VISIBLE && !isVisible) {
768
+ parameterValue = false;
769
+ }
770
+ _parameters[parameterizableParameter] = parameterValue;
771
+ const search = new RegExp(`\\$\\{${parameterizableParameter}\\}`, 'g');
772
+ initialDefinitionStr = initialDefinitionStr.replace(search, parameterValue.toString());
773
+ }
774
+ const definition = get(this.structureJson, definitionKey);
775
+ definition[this.name] = JSON.parse(initialDefinitionStr);
776
+ set(this.structureJson, definitionKey, definition);
777
+ return await parameterizable.commitParameters(_parameters);
778
+ }
779
+
780
+ /**
781
+ * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
782
+ */
783
+ protected async commitParameterToElements(parameter: string, value: ParameterValue): Promise<Variant> {
784
+ const promises = [];
785
+ for (const element of this.elements) {
786
+ const paramShowsVariant = Parameter.VISIBLE === parameter && value;
787
+
788
+ // Fixes https://combeenation.youtrack.cloud/issue/CB-7773
789
+ // Don't enable/show the variants element if it is explicitly hidden via its element parameters.
790
+ // E.g. via spec:
791
+ // ```
792
+ // variants: {
793
+ // theVariant: {
794
+ // elements: {
795
+ // Main: ['root.main'],
796
+ // Secondary: ['root.secondary'],
797
+ // },
798
+ // parameters: {
799
+ // // !!! The element `Secondary` should **not** be enabled when its containing variant is enabled !!!
800
+ // 'Secondary.visible': false,
801
+ // }
802
+ // }
803
+ // }
804
+ // ```
805
+ const elVisibleParamPath = DottedPath.create([element.name, Parameter.VISIBLE]).toString();
806
+ const elVisibleParamValue = this.inheritedParameters[elVisibleParamPath];
807
+ const elVisibleParamValueParsed = elVisibleParamValue && Parameter.parseBoolean(elVisibleParamValue);
808
+ const elIsHiddenViaParams = elVisibleParamValueParsed === false;
809
+ if (paramShowsVariant && elIsHiddenViaParams) continue;
810
+
811
+ // Fixes https://combeenation.youtrack.cloud/issue/CB-7809
812
+ // Apply element material before showing the element to prevent loading of the elements "original" material which
813
+ // is never shown when "overwritten" by elements material param.
814
+ const elMaterialParamPath = DottedPath.create([element.name, Parameter.MATERIAL]).toString();
815
+ const elMaterialParamValue = this.inheritedParameters[elMaterialParamPath];
816
+ if (paramShowsVariant && elMaterialParamValue) {
817
+ await element.commitParameter(Parameter.MATERIAL, elMaterialParamValue);
818
+ }
819
+
820
+ promises.push(element.commitParameter(parameter, value));
821
+ }
822
+ await Promise.all(promises);
823
+ return this;
824
+ }
825
+
826
+ /**
827
+ * Commits given {@link Parameter} to the {@link Variant}'s {@link Element}s.
828
+ */
829
+ protected async commitParameterToViewerLights(parameter: string, value: ParameterValue): Promise<Variant> {
830
+ const promises = [];
831
+ for (const viewerLight of this.viewerLights) {
832
+ promises.push(viewerLight.commitParameter(parameter, value));
833
+ }
834
+ await Promise.all(promises);
835
+ return this;
836
+ }
837
+
838
+ /**
839
+ * Adds the default {@link ParameterObserver}s which are called every time {@link commitParameters} is called.
840
+ */
841
+ protected addParameterObservers(): Variant {
842
+ this._parameterObservers.set(Parameter.VISIBLE, [
843
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
844
+ await variant.commitParameterToElements(Parameter.VISIBLE, newValue);
845
+ await variant.commitParameterToViewerLights(Parameter.VISIBLE, newValue);
846
+ },
847
+ ]);
848
+ this._parameterObservers.set(Parameter.SCALING, [
849
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
850
+ await variant.commitParameterToElements(Parameter.SCALING, newValue);
851
+ await variant.commitParameterToViewerLights(Parameter.SCALING, newValue);
852
+ },
853
+ ]);
854
+ this._parameterObservers.set(Parameter.MATERIAL, [
855
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
856
+ await variant.commitParameterToElements(Parameter.MATERIAL, newValue);
857
+ },
858
+ ]);
859
+ this._parameterObservers.set(Parameter.MATERIAL_COLOR, [
860
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
861
+ await variant.commitParameterToElements(Parameter.MATERIAL_COLOR, newValue);
862
+ },
863
+ ]);
864
+ this._parameterObservers.set(Parameter.MATERIAL_METALLNESS, [
865
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
866
+ await variant.commitParameterToElements(Parameter.MATERIAL_METALLNESS, newValue);
867
+ },
868
+ ]);
869
+ this._parameterObservers.set(Parameter.MATERIAL_ROUGHNESS, [
870
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
871
+ await variant.commitParameterToElements(Parameter.MATERIAL_ROUGHNESS, newValue);
872
+ },
873
+ ]);
874
+ this._parameterObservers.set(Parameter.HIGHLIGHT_COLOR, [
875
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
876
+ await variant.commitParameterToElements(Parameter.HIGHLIGHT_COLOR, newValue);
877
+ },
878
+ ]);
879
+ this._parameterObservers.set(Parameter.HIGHLIGHTED, [
880
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
881
+ await variant.commitParameterToElements(Parameter.HIGHLIGHTED, newValue);
882
+ },
883
+ ]);
884
+ this._parameterObservers.set(Parameter.POSITION, [
885
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
886
+ await variant.commitParameterToElements(Parameter.POSITION, newValue);
887
+ await variant.commitParameterToViewerLights(Parameter.POSITION, newValue);
888
+ },
889
+ ]);
890
+ this._parameterObservers.set(Parameter.ROTATION, [
891
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
892
+ await variant.commitParameterToElements(Parameter.ROTATION, newValue);
893
+ await variant.commitParameterToViewerLights(Parameter.ROTATION, newValue);
894
+ },
895
+ ]);
896
+ this._parameterObservers.set(Parameter.CAST_SHADOW, [
897
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
898
+ await variant.commitParameterToElements(Parameter.CAST_SHADOW, newValue);
899
+ },
900
+ ]);
901
+ this._parameterObservers.set(Parameter.CAST_SHADOW_FROM_LIGHTS, [
902
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
903
+ await variant.commitParameterToElements(Parameter.CAST_SHADOW_FROM_LIGHTS, newValue);
904
+ },
905
+ ]);
906
+ this._parameterObservers.set(Parameter.RECEIVE_SHADOWS, [
907
+ async (variant: Variant, oldValue: Undefinable<ParameterValue>, newValue: ParameterValue) => {
908
+ await variant.commitParameterToElements(Parameter.RECEIVE_SHADOWS, newValue);
909
+ },
910
+ ]);
911
+ return this;
912
+ }
913
+
914
+ /**
915
+ * Creates {@link Element}s and clones nodes into them.
916
+ */
917
+ protected async createElements(forInstance?: string): Promise<Variant> {
918
+ this.createElementDefinitionsIfNotExist();
919
+ for (const name in this.structureJson.elements || {}) {
920
+ this.elements.push(await Element.create(this, name));
921
+ }
922
+ // inject node meta to all inherited elements
923
+ // we do this to inject the deepest and most concrete variant information to all cloned nodes in the tree
924
+ this.inheritedElements.forEach(element =>
925
+ element.nodes.forEach(node => injectMetadata(node, { variant: this, variantParameterizable: element }))
926
+ );
927
+ return this;
928
+ }
929
+
930
+ /**
931
+ * Creates {@link ViewerLight}s.
932
+ */
933
+ protected async createViewerLights(): Promise<Variant> {
934
+ for (const name in this.structureJson.lights || {}) {
935
+ this.viewerLights.push(await ViewerLight.create(this, name));
936
+ }
937
+ this.inheritedViewerLights.forEach(viewerLight => {
938
+ injectMetadata(viewerLight.light, { variant: this, variantParameterizable: viewerLight });
939
+ });
940
+ return this;
941
+ }
942
+
943
+ /**
944
+ * Bootstrapping for parameters. It sets the `parametersInitialized` to true for all ancestors.
945
+ */
946
+ protected async bootstrapParameters(parameters?: ParameterBag): Promise<Variant> {
947
+ await this.commitParameters(merge(cloneDeep(this.parameters), parameters));
948
+ concat(this.ancestors, this).forEach(ancestor => (ancestor.parametersInitialized = true));
949
+ return this;
950
+ }
951
+
952
+ /**
953
+ * Ensures there is at least one "Main" {@link Element} for the {@link Variant} with all "root nodes" defined in path.
954
+ */
955
+ protected createElementDefinitionsIfNotExist() {
956
+ if (this._structureJson.elements || this.inheritedNodes.length === 0) {
957
+ return;
958
+ }
959
+ this._structureJson.elements = {
960
+ Main: { paths: { include: this.inheritedNodes.map(node => node.metadata.dottedPath.path) } },
961
+ };
962
+ this.structureJson.elements = cloneDeep(this._structureJson.elements);
963
+ }
964
+ }