@combeenation/3d-viewer 12.4.3 → 12.4.4

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