@combeenation/3d-viewer 6.5.0 → 7.0.0-beta2

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