@combeenation/3d-viewer 7.0.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +111 -111
  2. package/dist/lib-cjs/api/classes/animationInterface.d.ts +8 -8
  3. package/dist/lib-cjs/api/classes/animationInterface.js +2 -2
  4. package/dist/lib-cjs/api/classes/dottedPath.d.ts +79 -79
  5. package/dist/lib-cjs/api/classes/dottedPath.js +166 -166
  6. package/dist/lib-cjs/api/classes/element.d.ts +153 -153
  7. package/dist/lib-cjs/api/classes/element.js +670 -670
  8. package/dist/lib-cjs/api/classes/event.d.ts +396 -396
  9. package/dist/lib-cjs/api/classes/event.js +419 -419
  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 +351 -351
  15. package/dist/lib-cjs/api/classes/parameter.js +517 -517
  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 +253 -253
  23. package/dist/lib-cjs/api/classes/variant.js +843 -843
  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 +88 -88
  28. package/dist/lib-cjs/api/classes/viewer.d.ts +199 -200
  29. package/dist/lib-cjs/api/classes/viewer.js +670 -671
  30. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  31. package/dist/lib-cjs/api/classes/viewerLight.d.ts +66 -66
  32. package/dist/lib-cjs/api/classes/viewerLight.js +348 -348
  33. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  34. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  35. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +13 -13
  36. package/dist/lib-cjs/api/internal/sceneSetup.js +226 -226
  37. package/dist/lib-cjs/api/manager/animationManager.d.ts +30 -30
  38. package/dist/lib-cjs/api/manager/animationManager.js +126 -126
  39. package/dist/lib-cjs/api/manager/gltfExportManager.d.ts +78 -78
  40. package/dist/lib-cjs/api/manager/gltfExportManager.js +241 -241
  41. package/dist/lib-cjs/api/manager/sceneManager.d.ts +33 -33
  42. package/dist/lib-cjs/api/manager/sceneManager.js +130 -130
  43. package/dist/lib-cjs/api/manager/tagManager.d.ts +108 -108
  44. package/dist/lib-cjs/api/manager/tagManager.js +419 -419
  45. package/dist/lib-cjs/api/manager/textureLoadManager.d.ts +22 -22
  46. package/dist/lib-cjs/api/manager/textureLoadManager.js +97 -97
  47. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +102 -103
  48. package/dist/lib-cjs/api/manager/variantInstanceManager.js +284 -285
  49. package/dist/lib-cjs/api/manager/variantInstanceManager.js.map +1 -1
  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 +235 -235
  53. package/dist/lib-cjs/api/util/babylonHelper.js +753 -750
  54. package/dist/lib-cjs/api/util/babylonHelper.js.map +1 -1
  55. package/dist/lib-cjs/api/util/globalTypes.d.ts +436 -436
  56. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  57. package/dist/lib-cjs/api/util/resourceHelper.d.ts +58 -58
  58. package/dist/lib-cjs/api/util/resourceHelper.js +203 -203
  59. package/dist/lib-cjs/api/util/sceneLoaderHelper.d.ts +44 -44
  60. package/dist/lib-cjs/api/util/sceneLoaderHelper.js +175 -173
  61. package/dist/lib-cjs/api/util/sceneLoaderHelper.js.map +1 -1
  62. package/dist/lib-cjs/api/util/stringHelper.d.ts +13 -13
  63. package/dist/lib-cjs/api/util/stringHelper.js +32 -32
  64. package/dist/lib-cjs/api/util/structureHelper.d.ts +9 -9
  65. package/dist/lib-cjs/api/util/structureHelper.js +48 -48
  66. package/dist/lib-cjs/buildinfo.json +3 -3
  67. package/dist/lib-cjs/commonjs.tsconfig.tsbuildinfo +1 -1
  68. package/dist/lib-cjs/index.d.ts +53 -53
  69. package/dist/lib-cjs/index.js +114 -114
  70. package/package.json +81 -81
  71. package/src/api/classes/animationInterface.ts +10 -10
  72. package/src/api/classes/dottedPath.ts +181 -181
  73. package/src/api/classes/element.ts +731 -731
  74. package/src/api/classes/event.ts +452 -452
  75. package/src/api/classes/eventBroadcaster.ts +52 -52
  76. package/src/api/classes/fuzzyMap.ts +21 -21
  77. package/src/api/classes/parameter.ts +554 -554
  78. package/src/api/classes/parameterObservable.ts +73 -73
  79. package/src/api/classes/parameterizable.ts +87 -87
  80. package/src/api/classes/placementAnimation.ts +162 -162
  81. package/src/api/classes/variant.ts +933 -933
  82. package/src/api/classes/variantInstance.ts +123 -123
  83. package/src/api/classes/variantParameterizable.ts +85 -85
  84. package/src/api/classes/viewer.ts +743 -744
  85. package/src/api/classes/viewerLight.ts +339 -339
  86. package/src/api/internal/debugViewer.ts +90 -90
  87. package/src/api/internal/lensRendering.ts +9 -9
  88. package/src/api/internal/sceneSetup.ts +205 -205
  89. package/src/api/manager/animationManager.ts +143 -143
  90. package/src/api/manager/gltfExportManager.ts +236 -236
  91. package/src/api/manager/sceneManager.ts +136 -136
  92. package/src/api/manager/tagManager.ts +451 -451
  93. package/src/api/manager/textureLoadManager.ts +95 -95
  94. package/src/api/manager/variantInstanceManager.ts +297 -298
  95. package/src/api/store/specStorage.ts +68 -68
  96. package/src/api/util/babylonHelper.ts +823 -822
  97. package/src/api/util/globalTypes.ts +503 -503
  98. package/src/api/util/resourceHelper.ts +191 -191
  99. package/src/api/util/sceneLoaderHelper.ts +170 -170
  100. package/src/api/util/stringHelper.ts +30 -30
  101. package/src/api/util/structureHelper.ts +49 -49
  102. package/src/buildinfo.json +3 -3
  103. package/src/dev.ts +62 -62
  104. package/src/index.ts +100 -100
  105. package/src/types.d.ts +38 -35
@@ -1,822 +1,823 @@
1
- import { DottedPath } from '../classes/dottedPath';
2
- import { Event, emitter } from '../classes/event';
3
- import { defaultEnvHelperColor, defaultSceneClearColor } from '../internal/sceneSetup';
4
- import {
5
- addMissingMaterialObserver,
6
- createMaterialFromCbnAssets,
7
- missingMaterialMetadataName,
8
- } from './sceneLoaderHelper';
9
- import { EnvironmentHelper } from '@babylonjs/core/Helpers/environmentHelper';
10
- import { PhotoDome } from '@babylonjs/core/Helpers/photoDome';
11
- import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
12
- import { ShadowGenerator } from '@babylonjs/core/Lights/Shadows/shadowGenerator';
13
- import { Light } from '@babylonjs/core/Lights/light';
14
- import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';
15
- import { BaseTexture } from '@babylonjs/core/Materials/Textures/baseTexture';
16
- import { CubeTexture } from '@babylonjs/core/Materials/Textures/cubeTexture';
17
- import { Material } from '@babylonjs/core/Materials/material';
18
- import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
19
- import { Axis } from '@babylonjs/core/Maths/math.axis';
20
- import { Color3, Color4 } from '@babylonjs/core/Maths/math.color';
21
- import { Quaternion, Vector3 } from '@babylonjs/core/Maths/math.vector';
22
- import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
23
- import { InstancedMesh } from '@babylonjs/core/Meshes/instancedMesh';
24
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
25
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
26
- import { Observable } from '@babylonjs/core/Misc/observable';
27
- import { Tags } from '@babylonjs/core/Misc/tags';
28
- import { Tools } from '@babylonjs/core/Misc/tools';
29
- import { Node } from '@babylonjs/core/node';
30
- import { Scene } from '@babylonjs/core/scene';
31
- import { Nullable } from '@babylonjs/core/types';
32
- import { cloneDeep, get, has, merge, uniq } from 'lodash-es';
33
-
34
- const backgroundDomeName = 'BackgroundDome_ViewerGenerated';
35
- const envHelperMetadataName = 'viewerEnvHelper';
36
- const materialWaitingToBeSetMetadataName = 'materialWaitingToBeSet';
37
-
38
- /**
39
- * @param node
40
- * @return Node
41
- */
42
- const getRootNode = function (node: Node): Node {
43
- let _node = node;
44
- while (_node.parent) {
45
- _node = _node.parent;
46
- }
47
- return _node;
48
- };
49
-
50
- /**
51
- * @param nodes
52
- * @param predicate
53
- * @return Map<DottedPath, T>
54
- */
55
- const mapToDottedNodes = function <T>(nodes: Node[], predicate?: (node: Node) => boolean): Map<DottedPath, T> {
56
- const map = new Map<DottedPath, T>();
57
- const addNodes = function (_node: Node) {
58
- if (predicate && predicate(_node)) {
59
- map.set(_node.metadata.dottedPath, _node as any);
60
- }
61
- _node.getChildren().forEach(child => {
62
- addNodes(child);
63
- });
64
- };
65
- nodes.forEach(node => {
66
- addNodes(node);
67
- });
68
- return map;
69
- };
70
-
71
- /**
72
- * @param node
73
- * @return DottedPath
74
- */
75
- const getDottedPathForNode = function (node: Node): DottedPath {
76
- const dottedPath = DottedPath.create(node.name);
77
- let _parent = node;
78
- while (_parent.parent) {
79
- _parent = _parent.parent;
80
- dottedPath.unshiftPart(_parent.name);
81
- }
82
- return dottedPath;
83
- };
84
-
85
- /**
86
- * @param node
87
- * @param nodeNamingStrategy
88
- * @param predicate
89
- * @param deep
90
- * @return TransformNode | null
91
- */
92
- const cloneTransformNode = function (
93
- node: TransformNode,
94
- nodeNamingStrategy: NodeNamingStrategy,
95
- predicate?: (node: TransformNode) => boolean,
96
- deep: boolean = true
97
- ): TransformNode | null {
98
- if (predicate && !predicate(node)) {
99
- return null;
100
- }
101
- const newName = nodeNamingStrategy.handler(node, nodeNamingStrategy.payload);
102
- const clone = node.clone(newName, node.parent, true);
103
- if (clone) {
104
- clone.id = newName;
105
- clone.metadata = cloneDeep(node.metadata);
106
- injectNodeMetadata(clone, { cloneSource: node }, false);
107
- // if the cloned node is of type InstancedMesh, due to a bug(?),
108
- // the InstancedMesh.isEnabled state may have changed after cloning.
109
- // in that case, set the clone's enabled state to the original's state
110
- if (node.constructor.name === 'InstancedMesh') {
111
- clone.setEnabled(node.isEnabled(false));
112
- }
113
- // copying tags is a temporary workaround, as it doesn't work for TransformNodes ATM
114
- // see https://forum.babylonjs.com/t/transformnode-clone-doesnt-contain-original-tags/38429/1
115
- if (Tags?.HasTags(node)) {
116
- Tags.AddTagsTo(clone, Tags.GetTags(node, true));
117
- }
118
- }
119
- if (deep) {
120
- const children = node.getChildTransformNodes(true);
121
- children.forEach(child => {
122
- const clonedChild = cloneTransformNode(child, nodeNamingStrategy, predicate, deep);
123
- if (clonedChild) {
124
- clonedChild.parent = clone;
125
- }
126
- });
127
- }
128
- return clone;
129
- };
130
-
131
- /**
132
- * @param node
133
- */
134
- const cloneNodeWithParents = function (node: Node | null): Node | null {
135
- let clone = null;
136
- if (node instanceof TransformNode) {
137
- clone = node.clone(node.name, cloneNodeWithParents(node.parent) as Nullable<Node>, true);
138
- } else if (node instanceof Light) {
139
- clone = node.clone(node.name, cloneNodeWithParents(node.parent) as Nullable<Node>);
140
- } else if (node) {
141
- throw new Error(`Cloning of "${node?.constructor.name}" is not implemented (yet).`);
142
- }
143
- return clone;
144
- };
145
-
146
- /**
147
- * @param node
148
- * @param deep
149
- * @param prefix
150
- * @return TransformNode
151
- */
152
- const cloneTransformNodeMaterial = function (
153
- node: TransformNode,
154
- prefix: DottedPathArgument = '',
155
- deep: boolean = true
156
- ): TransformNode {
157
- if (node instanceof AbstractMesh && node.material) {
158
- const newMatName = DottedPath.create(prefix).addParts([node.material.name, 'clone', node.uniqueId.toString()]);
159
- node.material = node.material.clone(newMatName.path);
160
- }
161
- if (deep) {
162
- const children = node.getChildTransformNodes(true);
163
- children.forEach(child => cloneTransformNodeMaterial(child, prefix, deep));
164
- }
165
- return node;
166
- };
167
-
168
- /**
169
- * @param node
170
- * @param deep
171
- * @param metadata
172
- */
173
- const injectNodeMetadata = function (node: Node, metadata: {}, deep: boolean = true) {
174
- node.metadata = merge({}, node.metadata, metadata);
175
- if (deep && node instanceof TransformNode) {
176
- const children = node.getChildTransformNodes(true);
177
- children.forEach(child => injectNodeMetadata(child, metadata, deep));
178
- }
179
- };
180
-
181
- /**
182
- * @param node
183
- * @param assertCallable
184
- * @param callableParameters
185
- * @param deep
186
- */
187
- const assertTransformNode = function (
188
- node: TransformNode,
189
- assertCallable: (node: TransformNode, ...args: any[]) => void,
190
- callableParameters: any[] = [],
191
- deep: boolean = true
192
- ) {
193
- assertCallable(node, ...callableParameters);
194
- if (deep) {
195
- const children = node.getChildTransformNodes(true);
196
- children.forEach(child => assertTransformNode(child, assertCallable, callableParameters, deep));
197
- }
198
- };
199
-
200
- /**
201
- * @param node
202
- * @param parameter
203
- */
204
- const assertMeshCapability = function (node: TransformNode, parameter: string) {
205
- if (!(node instanceof AbstractMesh)) {
206
- const cls = node.getClassName();
207
- throw new Error(
208
- `Changing parameter "${parameter}" of a(n) ${cls} is not supported. Tried to change node "${node.id}".`
209
- );
210
- }
211
- if (node instanceof InstancedMesh) {
212
- throw new Error(
213
- `Changing parameter "${parameter}" of an InstancedMesh is not supported. Tried to change node "${node.id}".`
214
- );
215
- }
216
- };
217
-
218
- /**
219
- * @param node
220
- * @param deep
221
- */
222
- const activateTransformNode = function (node: TransformNode, deep: boolean = true) {
223
- node.setEnabled(true);
224
- /*
225
- if( node instanceof AbstractMesh ) {
226
- node.visibility = 1;
227
- node.isPickable = true;
228
- }
229
- */
230
- if (deep) {
231
- node.getChildTransformNodes(true).forEach(child => activateTransformNode(child, deep));
232
- }
233
- };
234
-
235
- /**
236
- * @param node
237
- * @param deep
238
- */
239
- const deactivateTransformNode = function (node: TransformNode, deep: boolean = true) {
240
- node.setEnabled(false);
241
- /*
242
- if( node instanceof AbstractMesh ) {
243
- node.visibility = 0;
244
- node.isPickable = false;
245
- }
246
- */
247
- if (deep) {
248
- node.getChildTransformNodes(true).forEach(child => deactivateTransformNode(child, deep));
249
- }
250
- };
251
-
252
- /**
253
- * @param node
254
- */
255
- const enableNodeWithParents = function (node: Node) {
256
- node.setEnabled(true);
257
- if (node.parent) {
258
- enableNodeWithParents(node.parent);
259
- }
260
- };
261
-
262
- /**
263
- * @param node
264
- */
265
- const disableNodeWithParents = function (node: Node) {
266
- node.setEnabled(false);
267
- if (node.parent) {
268
- disableNodeWithParents(node.parent);
269
- }
270
- };
271
-
272
- /**
273
- * Applies a {@link TransformationDefinition} consecutively to ensure dependencies in positioning etc.
274
- * @param node
275
- * @param transformation
276
- */
277
- const transformTransformNode = function (node: TransformNode, transformation: TransformationDefinition) {
278
- // scaling
279
- if (!has(node.metadata, 'scaling.initial')) {
280
- injectNodeMetadata(node, { 'scaling.initial': node.scaling }, false);
281
- }
282
- const initialScaling = get(node.metadata, 'scaling.initial') as Vector3;
283
- node.scaling = initialScaling.multiply(transformation.scaling);
284
- // position
285
- if (!has(node.metadata, 'position.initial')) {
286
- injectNodeMetadata(node, { 'position.initial': node.absolutePosition.clone() }, false);
287
- }
288
- const initialPosition = get(node.metadata, 'position.initial') as Vector3;
289
- node.setAbsolutePosition(initialPosition.add(transformation.position).multiply(transformation.scaling));
290
- // rotation
291
- if (!has(node.metadata, 'rotation.initial')) {
292
- let rotationQuaternion = node.rotationQuaternion;
293
- if (!rotationQuaternion) {
294
- rotationQuaternion = Quaternion.RotationYawPitchRoll(node.rotation.x, node.rotation.y, node.rotation.z);
295
- }
296
- injectNodeMetadata(node, { 'rotation.initial': rotationQuaternion.asArray() }, false);
297
- }
298
- const initialRotationQuaternion = Quaternion.FromArray(get(node.metadata, 'rotation.initial') as []);
299
- node.rotationQuaternion = initialRotationQuaternion;
300
- node.rotateAround(Vector3.Zero(), Axis.X, transformation.rotation.x);
301
- node.rotateAround(Vector3.Zero(), Axis.Y, transformation.rotation.y);
302
- node.rotateAround(Vector3.Zero(), Axis.Z, transformation.rotation.z);
303
- node.computeWorldMatrix(true);
304
- };
305
-
306
- /**
307
- * Apply changes of environment (background texture, etc.) consecutively in order to avoid dependency related issues.
308
- * @param scene
309
- * @param envDef
310
- */
311
- const changeEnvironment = function (scene: Scene, envDef: EnvironmentDefinition) {
312
- // issue warning if both background texture and usedefault are set
313
- if (envDef.environmentUseDefault && envDef.environmentBackground) {
314
- console.warn(
315
- `!!! Warning !!! Spec parameter 'environment.usedefault' is being overruled by 'environment.background'.`
316
- );
317
- }
318
-
319
- const useDefaultEnv = envDef.environmentUseDefault && !envDef.environmentBackground;
320
-
321
- // 1) set ENVIRONMENT_COLOR
322
- const clearColorBefore = scene.clearColor.toString();
323
- scene.clearColor = envDef.environmentColor
324
- ? Color4.FromColor3(envDef.environmentColor)
325
- : useDefaultEnv
326
- ? defaultEnvHelperColor
327
- : defaultSceneClearColor;
328
- const clearColorChanged = clearColorBefore !== scene.clearColor.toString();
329
-
330
- // 2) dispose existing & set new ENVIRONMENT (==texture)
331
- const curEnvTexture = scene.environmentTexture as Nullable<CubeTexture>;
332
- const envTextureChanged = envDef.environment !== curEnvTexture?.url;
333
-
334
- if (curEnvTexture && (!envDef.environment || envTextureChanged)) {
335
- curEnvTexture.dispose();
336
- }
337
-
338
- const rotation = envDef.environmentRotation !== undefined ? Tools.ToRadians(envDef.environmentRotation) : 0;
339
- if (envDef.environment && envTextureChanged) {
340
- const envTexture = CubeTexture.CreateFromPrefilteredData(envDef.environment, scene);
341
- envTexture.rotationY = rotation;
342
- scene.environmentTexture = envTexture;
343
- } else if (curEnvTexture && curEnvTexture.rotationY !== rotation) {
344
- curEnvTexture.rotationY = rotation;
345
- }
346
-
347
- // 3) dispose existing & set new ENVIRONMENT_BACKGROUND
348
- const curDome = scene.getNodeByName(backgroundDomeName) as undefined | PhotoDome;
349
- const backgroundUrlChanged = envDef.environmentBackground !== curDome?.texture.url;
350
-
351
- if (curDome && (!envDef.environmentBackground || backgroundUrlChanged)) {
352
- curDome.dispose();
353
- }
354
-
355
- const rotationPhotoDome = -1 * rotation;
356
- if (envDef.environmentBackground && backgroundUrlChanged) {
357
- const textureUrl = envDef.environmentBackground;
358
- const dome = new PhotoDome(backgroundDomeName, textureUrl, { resolution: 32, size: 450 }, scene);
359
- // Rotate submesh to get them in line with environment texture
360
- dome.getChildMeshes(true)[0].rotation.y = Tools.ToRadians(90);
361
- dome.rotation.y = rotationPhotoDome;
362
- } else if (curDome && curDome.rotation.y !== rotationPhotoDome) {
363
- curDome.rotation.y = rotationPhotoDome;
364
- }
365
-
366
- // 4) dispose existing & set new ENVIRONMENT_USEDEFAULT (only if no background is set)
367
- const curEnvHelper = scene.metadata?.[envHelperMetadataName] as undefined | EnvironmentHelper;
368
-
369
- if (curEnvHelper && !useDefaultEnv) {
370
- curEnvHelper.dispose();
371
- delete scene.metadata[envHelperMetadataName];
372
- }
373
-
374
- const envHelperMainColor = Color3.FromArray(scene.clearColor.asArray());
375
- if (useDefaultEnv && !curEnvHelper) {
376
- const envHelper = scene.createDefaultEnvironment({ sizeAuto: true });
377
- envHelper?.setMainColor(envHelperMainColor);
378
- if (envHelper) {
379
- scene.metadata = merge({}, scene.metadata, { [envHelperMetadataName]: envHelper });
380
- }
381
- } else if (curEnvHelper && useDefaultEnv && clearColorChanged) {
382
- curEnvHelper.setMainColor(envHelperMainColor);
383
- }
384
-
385
- // 5) set ENVIRONMENT_INTENSITY
386
- if (envDef.environmentIntensity !== undefined) {
387
- scene.environmentIntensity = envDef.environmentIntensity;
388
- }
389
- };
390
-
391
- /**
392
- * Sets a material by a given material id as material property on the given node.
393
- *
394
- * If the material is not already available in the scene, the viewer tries to create a material based on a Combeenation
395
- * [material asset](https://docs.combeenation.com/docs/howto-create-and-use-babylon-and-material-asset).
396
- * This of course only works if the viewer is used inside a Combeenation configurator.
397
- *
398
- * Furthermore this function also defers the material creation if the node is not visible yet to improve network &
399
- * viewer bootstrap performance as textures are automatically being lazy loaded only when they are actually visible in
400
- * the scene.
401
- *
402
- * Finally the material will not be applied before all its textures have been loaded. In this way "flickering" effects
403
- * will be avoided, since the material would be incomplete without its loaded textures.
404
- */
405
- const setMaterial = function (node: TransformNode, materialId: string, deep: boolean = true, variant?: Variant) {
406
- if (node instanceof AbstractMesh) {
407
- const materialExists = node.getScene().getMaterialById(materialId);
408
- const hasMissingMaterial = has(node.metadata, missingMaterialMetadataName);
409
- const deferMaterialCreation = !materialExists && !node.isEnabled();
410
- if (deferMaterialCreation) {
411
- // do not set the material
412
- injectNodeMetadata(node, { [missingMaterialMetadataName]: materialId }, false);
413
- // if it already had the missing material flag before, there already exists an observer...
414
- if (!hasMissingMaterial) {
415
- addMissingMaterialObserver(node);
416
- }
417
- } else {
418
- // create material and apply it when textures have been loaded
419
- const material = getOrCreateMaterial(node.getScene(), materialId, variant);
420
- applyMaterial(material, node).then(() => emitter.emit(Event.MESH_MATERIAL_APPLIED, node, material));
421
-
422
- if (hasMissingMaterial) {
423
- delete node.metadata[missingMaterialMetadataName];
424
- }
425
- }
426
- }
427
- // recursively set materials on children (if desired)
428
- if (deep) {
429
- for (const child of node.getChildTransformNodes(true)) {
430
- setMaterial(child, materialId, deep, variant);
431
- }
432
- }
433
- };
434
-
435
- /**
436
- * Gets the Material either from the given {@link Variant}, the given scene or tries to create it from an Combeenation
437
- * material asset when inside a Combeenation configurator.
438
- */
439
- const getOrCreateMaterial = function (scene: Scene, materialId: string, variant?: Variant): Material {
440
- let chosenMaterial: Material | undefined | null;
441
- chosenMaterial = variant?.inheritedMaterials.find(mat => mat.id === materialId);
442
- chosenMaterial = chosenMaterial || scene.materials.find(mat => mat.id === materialId);
443
- chosenMaterial = chosenMaterial || createMaterialFromCbnAssets(materialId, scene);
444
- if (chosenMaterial) {
445
- return chosenMaterial as Material;
446
- }
447
- // reject when material was not found
448
- let rejectMessage = `Material with id "${materialId}" does not exist on scene.`;
449
- if (variant) {
450
- rejectMessage = `Material with id "${materialId}" does not exist for variant "${variant.id}".`;
451
- }
452
- throw new Error(rejectMessage);
453
- };
454
-
455
- /**
456
- * Waits until the materials textures are loaded and shaders are compiled.
457
- * Then sets the material on the node if there is no newer "set material" request
458
- */
459
- const applyMaterial = async function (material: Material, node: AbstractMesh) {
460
- // set current material id as last valid id, in this case all previously set materials on the node will be invalidated
461
- injectNodeMetadata(node, { [materialWaitingToBeSetMetadataName]: material.id }, false);
462
-
463
- const promTexturesReady = new Promise<void>(resolve =>
464
- BaseTexture.WhenAllReady(material.getActiveTextures(), resolve)
465
- );
466
- // this promise should only take some time on the first call of the corresponding shader (eg: PBRMaterial shader)
467
- // on each other call of the same material/shader type there should be not be a waiting time, or at maximum one frame
468
- // https://forum.babylonjs.com/t/mesh-flickering-when-setting-material-initially/37312
469
- const promMaterialCompiled = material.forceCompilationAsync(node);
470
-
471
- // material needs to fulfill 2 criterias before it's ready to use
472
- // - textures need to be "ready" => downloaded
473
- // - dedicated shader needs to be compiled
474
- // if this would not be the case you can see some "flickering" when setting the material
475
- await Promise.all([promTexturesReady, promMaterialCompiled]);
476
-
477
- // textures ready, now check if the material is still up-to-date
478
- if (material.id === node.metadata?.[materialWaitingToBeSetMetadataName]) {
479
- node.material = material;
480
- delete node.metadata[materialWaitingToBeSetMetadataName];
481
- }
482
- };
483
-
484
- /**
485
- * !!! Warning !!!
486
- * This function is not public API. Whilst it can help solving certain problems, it only works reliably in well defined
487
- * situations and can cause unwanted side effects under some conditions. Use carefully at your own risk!
488
- *
489
- * See https://combeenation.myjetbrains.com/youtrack/issue/CB-5906 for further details regarding this warning.
490
- *
491
- * Set material of an instanced meshes source mesh.
492
- * Changes the material of all instanced meshes which have the same source mesh.
493
- *
494
- * @param node
495
- * @param material
496
- * @param deep
497
- *
498
- * @ignore
499
- */
500
- const setSourceNodeMaterial = function (node: TransformNode, material: Material, deep: boolean = true) {
501
- const warn = ` You're using "setSourceNodeMaterial" which is not public API.
502
- Whilst it can help solving certain problems, it only works reliably in well defined situations and can cause unwanted side effects under some conditions.
503
- Use carefully at your own risk!`;
504
- console.warn(`!!! Warning !!!\n${warn}`);
505
-
506
- if (node instanceof InstancedMesh) {
507
- node.sourceMesh.material = material;
508
- }
509
- if (deep) {
510
- node.getChildTransformNodes(true).forEach(child => setSourceNodeMaterial(child, material, deep));
511
- }
512
- };
513
-
514
- /**
515
- * @param node
516
- * @param color
517
- * @param deep
518
- */
519
- const setMaterialColor = function (node: TransformNode, color: Color3, deep: boolean = true) {
520
- if (node instanceof AbstractMesh && node.material) {
521
- const materialCls = node.material.getClassName();
522
- switch (materialCls) {
523
- case 'PBRMaterial':
524
- (node.material as PBRMaterial).albedoColor = color.toLinearSpace();
525
- break;
526
- case 'StandardMaterial':
527
- (node.material as StandardMaterial).diffuseColor = color;
528
- break;
529
- default:
530
- throw new Error(`Setting color for material of instance "${materialCls}" not implemented (yet).`);
531
- }
532
- setMaterial(node, node.material.id, false);
533
- }
534
- if (deep) {
535
- node.getChildTransformNodes(true).forEach(child => setMaterialColor(child, color, deep));
536
- }
537
- };
538
-
539
- /**
540
- * @param node
541
- * @param texture
542
- * @param deep
543
- */
544
- const setMaterialTexture = function (node: TransformNode, texture: Texture, deep: boolean = true) {
545
- if (node instanceof AbstractMesh && node.material) {
546
- const materialCls = node.material.getClassName();
547
- switch (materialCls) {
548
- case 'PBRMaterial':
549
- (node.material as PBRMaterial).albedoTexture = texture;
550
- break;
551
- case 'StandardMaterial':
552
- (node.material as StandardMaterial).diffuseTexture = texture;
553
- break;
554
- default:
555
- throw new Error(`Setting texture for material of instance "${materialCls}" not implemented (yet).`);
556
- }
557
- setMaterial(node, node.material.id, false);
558
- }
559
- if (deep) {
560
- node.getChildTransformNodes(true).forEach(child => setMaterialTexture(child, texture, deep));
561
- }
562
- };
563
-
564
- /**
565
- * @param node
566
- * @param metallness
567
- * @param deep
568
- */
569
- const setMaterialMetallness = function (node: TransformNode, metallness: number, deep: boolean = true) {
570
- if (node instanceof AbstractMesh && node.material) {
571
- const materialCls = node.material.getClassName();
572
- switch (materialCls) {
573
- case 'PBRMaterial':
574
- (node.material as PBRMaterial).metallic = metallness;
575
- break;
576
- default:
577
- throw new Error(`Setting metallness for material of instance "${materialCls}" not implemented (yet).`);
578
- }
579
- setMaterial(node, node.material.id, false);
580
- }
581
- if (deep) {
582
- node.getChildTransformNodes(true).forEach(child => setMaterialMetallness(child, metallness, deep));
583
- }
584
- };
585
-
586
- /**
587
- * @param node
588
- * @param roughness
589
- * @param deep
590
- */
591
- const setMaterialRoughness = function (node: TransformNode, roughness: number, deep: boolean = true) {
592
- if (node instanceof AbstractMesh && node.material) {
593
- const materialCls = node.material.getClassName();
594
- switch (materialCls) {
595
- case 'PBRMaterial':
596
- (node.material as PBRMaterial).roughness = roughness;
597
- break;
598
- case 'StandardMaterial':
599
- (node.material as StandardMaterial).roughness = roughness;
600
- break;
601
- default:
602
- throw new Error(`Setting roughness for material of instance "${materialCls}" not implemented (yet).`);
603
- }
604
- setMaterial(node, node.material.id, false);
605
- }
606
- if (deep) {
607
- node.getChildTransformNodes(true).forEach(child => setMaterialRoughness(child, roughness, deep));
608
- }
609
- };
610
-
611
- /**
612
- * @param node
613
- * @param layer
614
- * @param color
615
- * @param deep
616
- */
617
- const addToHighlightLayer = function (layer: HighlightLayer, color: Color3, node: TransformNode, deep: boolean = true) {
618
- if (node instanceof AbstractMesh) {
619
- layer.addMesh(node as Mesh, color);
620
- }
621
- if (deep) {
622
- node.getChildTransformNodes(true).forEach(child => addToHighlightLayer(layer, color, child, deep));
623
- }
624
- };
625
-
626
- /**
627
- * @param node
628
- * @param layer
629
- * @param deep
630
- */
631
- const removeFromHighlightLayer = function (layer: HighlightLayer, node: TransformNode, deep: boolean = true) {
632
- if (node instanceof AbstractMesh) {
633
- layer.removeMesh(node as Mesh);
634
- }
635
- if (deep) {
636
- node.getChildTransformNodes(true).forEach(child => removeFromHighlightLayer(layer, child, deep));
637
- }
638
- };
639
-
640
- /**
641
- * @param node
642
- * @param receiveShadows
643
- * @param deep
644
- */
645
- const setReceiveShadows = function (node: TransformNode, receiveShadows: boolean, deep: boolean = true) {
646
- if (node instanceof AbstractMesh) {
647
- node.receiveShadows = receiveShadows;
648
- }
649
- if (deep) {
650
- node.getChildTransformNodes(true).forEach(child => setReceiveShadows(child, receiveShadows, deep));
651
- }
652
- };
653
-
654
- /**
655
- * @param node
656
- * @param generator
657
- * @param deep
658
- */
659
- const addToShadowGenerator = function (generator: ShadowGenerator, node: TransformNode, deep: boolean = true) {
660
- if (node instanceof AbstractMesh) {
661
- // We have to remove the node because there's no duplicate check in babylon
662
- generator.removeShadowCaster(node, false);
663
- generator.addShadowCaster(node, false);
664
- }
665
- if (deep) {
666
- node.getChildTransformNodes(true).forEach(child => addToShadowGenerator(generator, child, deep));
667
- }
668
- };
669
-
670
- /**
671
- * @param node
672
- * @param generator
673
- * @param deep
674
- */
675
- const removeFromShadowGenerator = function (generator: ShadowGenerator, node: TransformNode, deep: boolean = true) {
676
- if (node instanceof AbstractMesh) {
677
- generator.removeShadowCaster(node, false);
678
- }
679
- if (deep) {
680
- node.getChildTransformNodes(true).forEach(child => removeFromShadowGenerator(generator, child, deep));
681
- }
682
- };
683
-
684
- /**
685
- * https://forum.babylonjs.com/t/get-mesh-bounding-box-position-and-size-in-2d-screen-coordinates/1058/3
686
- * @param mesh
687
- * @param scene
688
- * @param canvas
689
- */
690
- const getClientRectFromMesh = function (mesh: AbstractMesh, scene: Scene, canvas: HTMLCanvasElement): ClientRect {
691
- // get bounding box of the mesh
692
- const meshVectors = mesh.getBoundingInfo().boundingBox.vectors;
693
- // get the matrix and viewport needed to project the vectors onto the screen
694
- const worldMatrix = mesh.getWorldMatrix();
695
- const transformMatrix = scene.getTransformMatrix();
696
- const viewport = scene.activeCamera!.viewport;
697
- // loop though all the vectors and project them against the current camera viewport to get a set of coordinates
698
- const coordinates = meshVectors.map(vector => {
699
- const projection = Vector3.Project(vector, worldMatrix, transformMatrix, viewport);
700
- projection.x = projection.x * canvas.clientWidth;
701
- projection.y = projection.y * canvas.clientHeight;
702
- return projection;
703
- });
704
- // get the min and max for all the coordinates so we can calculate the largest possible screen size
705
- const maxX = Math.max(...coordinates.map(o => o.x));
706
- const minX = Math.min(...coordinates.map(o => o.x));
707
- const maxY = Math.max(...coordinates.map(o => o.y));
708
- const minY = Math.min(...coordinates.map(o => o.y));
709
- // return a ClientRect from this
710
- return {
711
- width: maxX - minX,
712
- height: maxY - minY,
713
- left: minX,
714
- top: minY,
715
- right: maxX,
716
- bottom: maxY,
717
- } as ClientRect;
718
- };
719
-
720
- type BaseTextureWithOnLoadObservable = BaseTexture & {
721
- onLoadObservable: Observable<BaseTexture>;
722
- };
723
-
724
- /**
725
- * This type guard checks whether the given `BaseTextures` is any of its subtypes which comes with an
726
- * `onLoadObservable`.
727
- *
728
- * !!! Timing of when this function is called is important !!!
729
- * See the following for more details: https://forum.babylonjs.com/t/basetexture-whenallready-returns-too-early/34501/6
730
- */
731
- const isTextureWithOnLoadObservable = function (texture: BaseTexture): texture is BaseTextureWithOnLoadObservable {
732
- return !!(texture as BaseTextureWithOnLoadObservable).onLoadObservable;
733
- };
734
-
735
- /**
736
- * @param objects
737
- * @param tagMapping
738
- */
739
- const mapTags = function (objects: object[], tagMapping: TagMapping): string[] {
740
- let affectedTags: string[] = [];
741
- for (const object of objects) {
742
- const oldTags = Object.keys(Tags.GetTags(object, false) ?? {});
743
- const mappedTags = oldTags.map(t => tagMapping[t] || t);
744
- Tags.RemoveTagsFrom(object, oldTags.join(' '));
745
- Tags.AddTagsTo(object, mappedTags.join(' '));
746
- affectedTags = [...affectedTags, ...mappedTags];
747
- }
748
- return uniq(affectedTags);
749
- };
750
-
751
- /**
752
- * Gets an array of ids for nodeIds that exist in both TransformNode arrays.
753
- * @param nodes1
754
- * @param nodes2
755
- * @param predicate
756
- */
757
- const intersectingNodeNames = function (nodes1: Node[], nodes2: Node[], predicate?: (node: Node) => boolean): string[] {
758
- const nodeNames1 = nodes1.filter(n => !predicate || predicate(n)).map(n => n.name);
759
- const nodesNames2 = nodes2.filter(n => !predicate || predicate(n)).map(n => n.name);
760
- return nodeNames1.filter(n1 => nodesNames2.includes(n1));
761
- };
762
-
763
- /**
764
- * Gets an array of ids for duplicate nodeIds in given node array.
765
- * @param nodes
766
- * @param predicate
767
- */
768
- const duplicateNodeNames = function (nodes: Node[], predicate?: (node: Node) => boolean): string[] {
769
- const nodeNames = nodes.filter(n => !predicate || predicate(n)).map(n => n.name);
770
- return nodeNames.filter((v, i, self) => self.indexOf(v) !== i);
771
- };
772
-
773
- /**
774
- * Reports duplicate nodeIds.
775
- * @param nodeNames
776
- */
777
- const reportDuplicateNodeNames = function (nodeNames: string[]): void {
778
- if (nodeNames.length > 0) {
779
- const warn = `There are duplicate nodeNames: ${nodeNames.join(', ')}`;
780
- console.warn(`!!! Warning !!!\n${warn}`);
781
- window.Cbn?.Assets.reportDuplicateNodeName(nodeNames);
782
- }
783
- };
784
-
785
- export {
786
- getRootNode,
787
- isTextureWithOnLoadObservable,
788
- mapToDottedNodes,
789
- getDottedPathForNode,
790
- cloneTransformNode,
791
- cloneNodeWithParents,
792
- cloneTransformNodeMaterial,
793
- getOrCreateMaterial,
794
- applyMaterial,
795
- injectNodeMetadata,
796
- assertTransformNode,
797
- assertMeshCapability,
798
- activateTransformNode,
799
- deactivateTransformNode,
800
- enableNodeWithParents,
801
- disableNodeWithParents,
802
- transformTransformNode,
803
- setMaterial,
804
- setSourceNodeMaterial,
805
- setMaterialColor,
806
- setMaterialTexture,
807
- setMaterialMetallness,
808
- setMaterialRoughness,
809
- addToHighlightLayer,
810
- removeFromHighlightLayer,
811
- setReceiveShadows,
812
- addToShadowGenerator,
813
- removeFromShadowGenerator,
814
- getClientRectFromMesh,
815
- changeEnvironment,
816
- backgroundDomeName,
817
- envHelperMetadataName,
818
- mapTags,
819
- intersectingNodeNames,
820
- duplicateNodeNames,
821
- reportDuplicateNodeNames,
822
- };
1
+ import { DottedPath } from '../classes/dottedPath';
2
+ import { Event, emitter } from '../classes/event';
3
+ import { defaultEnvHelperColor, defaultSceneClearColor } from '../internal/sceneSetup';
4
+ import {
5
+ addMissingMaterialObserver,
6
+ createMaterialFromCbnAssets,
7
+ missingMaterialMetadataName,
8
+ } from './sceneLoaderHelper';
9
+ import { EnvironmentHelper } from '@babylonjs/core/Helpers/environmentHelper';
10
+ import { PhotoDome } from '@babylonjs/core/Helpers/photoDome';
11
+ import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
12
+ import { ShadowGenerator } from '@babylonjs/core/Lights/Shadows/shadowGenerator';
13
+ import { Light } from '@babylonjs/core/Lights/light';
14
+ import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';
15
+ import { BaseTexture } from '@babylonjs/core/Materials/Textures/baseTexture';
16
+ import { CubeTexture } from '@babylonjs/core/Materials/Textures/cubeTexture';
17
+ import { Material } from '@babylonjs/core/Materials/material';
18
+ import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
19
+ import { Axis } from '@babylonjs/core/Maths/math.axis';
20
+ import { Color3, Color4 } from '@babylonjs/core/Maths/math.color';
21
+ import { Quaternion, Vector3 } from '@babylonjs/core/Maths/math.vector';
22
+ import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
23
+ import { InstancedMesh } from '@babylonjs/core/Meshes/instancedMesh';
24
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
25
+ import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
26
+ import { Observable } from '@babylonjs/core/Misc/observable';
27
+ import { Tags } from '@babylonjs/core/Misc/tags';
28
+ import { Tools } from '@babylonjs/core/Misc/tools';
29
+ import { Node } from '@babylonjs/core/node';
30
+ import { Scene } from '@babylonjs/core/scene';
31
+ import { Nullable } from '@babylonjs/core/types';
32
+ import { cloneDeep, get, has, merge, uniq } from 'lodash-es';
33
+
34
+ const backgroundDomeName = 'BackgroundDome_ViewerGenerated';
35
+ const envHelperMetadataName = 'viewerEnvHelper';
36
+ const materialWaitingToBeSetMetadataName = 'materialWaitingToBeSet';
37
+
38
+ /**
39
+ * @param node
40
+ * @return Node
41
+ */
42
+ const getRootNode = function (node: Node): Node {
43
+ let _node = node;
44
+ while (_node.parent) {
45
+ _node = _node.parent;
46
+ }
47
+ return _node;
48
+ };
49
+
50
+ /**
51
+ * @param nodes
52
+ * @param predicate
53
+ * @return Map<DottedPath, T>
54
+ */
55
+ const mapToDottedNodes = function <T>(nodes: Node[], predicate?: (node: Node) => boolean): Map<DottedPath, T> {
56
+ const map = new Map<DottedPath, T>();
57
+ const addNodes = function (_node: Node) {
58
+ if (predicate && predicate(_node)) {
59
+ map.set(_node.metadata.dottedPath, _node as any);
60
+ }
61
+ _node.getChildren().forEach(child => {
62
+ addNodes(child);
63
+ });
64
+ };
65
+ nodes.forEach(node => {
66
+ addNodes(node);
67
+ });
68
+ return map;
69
+ };
70
+
71
+ /**
72
+ * @param node
73
+ * @return DottedPath
74
+ */
75
+ const getDottedPathForNode = function (node: Node): DottedPath {
76
+ const dottedPath = DottedPath.create(node.name);
77
+ let _parent = node;
78
+ while (_parent.parent) {
79
+ _parent = _parent.parent;
80
+ dottedPath.unshiftPart(_parent.name);
81
+ }
82
+ return dottedPath;
83
+ };
84
+
85
+ /**
86
+ * @param node
87
+ * @param nodeNamingStrategy
88
+ * @param predicate
89
+ * @param deep
90
+ * @return TransformNode | null
91
+ */
92
+ const cloneTransformNode = function (
93
+ node: TransformNode,
94
+ nodeNamingStrategy: NodeNamingStrategy,
95
+ predicate?: (node: TransformNode) => boolean,
96
+ deep: boolean = true
97
+ ): TransformNode | null {
98
+ if (predicate && !predicate(node)) {
99
+ return null;
100
+ }
101
+ const newName = nodeNamingStrategy.handler(node, nodeNamingStrategy.payload);
102
+ const clone = node.clone(newName, node.parent, true);
103
+ if (clone) {
104
+ clone.id = newName;
105
+ clone.metadata = cloneDeep(node.metadata);
106
+ injectNodeMetadata(clone, { cloneSource: node }, false);
107
+ // if the cloned node is of type InstancedMesh, due to a bug(?),
108
+ // the InstancedMesh.isEnabled state may have changed after cloning.
109
+ // in that case, set the clone's enabled state to the original's state
110
+ if (node.constructor.name === 'InstancedMesh') {
111
+ clone.setEnabled(node.isEnabled(false));
112
+ }
113
+ // copying tags is a temporary workaround, as it doesn't work for TransformNodes ATM
114
+ // see https://forum.babylonjs.com/t/transformnode-clone-doesnt-contain-original-tags/38429/1
115
+ if (Tags?.HasTags(node)) {
116
+ Tags.AddTagsTo(clone, Tags.GetTags(node, true));
117
+ }
118
+ }
119
+ if (deep) {
120
+ const children = node.getChildTransformNodes(true);
121
+ children.forEach(child => {
122
+ const clonedChild = cloneTransformNode(child, nodeNamingStrategy, predicate, deep);
123
+ if (clonedChild) {
124
+ clonedChild.parent = clone;
125
+ }
126
+ });
127
+ }
128
+ return clone;
129
+ };
130
+
131
+ /**
132
+ * @param node
133
+ */
134
+ const cloneNodeWithParents = function (node: Node | null): Node | null {
135
+ let clone = null;
136
+ if (node instanceof TransformNode) {
137
+ clone = node.clone(node.name, cloneNodeWithParents(node.parent) as Nullable<Node>, true);
138
+ } else if (node instanceof Light) {
139
+ clone = node.clone(node.name, cloneNodeWithParents(node.parent) as Nullable<Node>);
140
+ } else if (node) {
141
+ throw new Error(`Cloning of "${node?.constructor.name}" is not implemented (yet).`);
142
+ }
143
+ return clone;
144
+ };
145
+
146
+ /**
147
+ * @param node
148
+ * @param deep
149
+ * @param prefix
150
+ * @return TransformNode
151
+ */
152
+ const cloneTransformNodeMaterial = function (
153
+ node: TransformNode,
154
+ prefix: DottedPathArgument = '',
155
+ deep: boolean = true
156
+ ): TransformNode {
157
+ if (node instanceof AbstractMesh && node.material) {
158
+ const newMatName = DottedPath.create(prefix).addParts([node.material.name, 'clone', node.uniqueId.toString()]);
159
+ node.material = node.material.clone(newMatName.path);
160
+ }
161
+ if (deep) {
162
+ const children = node.getChildTransformNodes(true);
163
+ children.forEach(child => cloneTransformNodeMaterial(child, prefix, deep));
164
+ }
165
+ return node;
166
+ };
167
+
168
+ /**
169
+ * @param node
170
+ * @param deep
171
+ * @param metadata
172
+ */
173
+ const injectNodeMetadata = function (node: Node, metadata: {}, deep: boolean = true) {
174
+ node.metadata = merge({}, node.metadata, metadata);
175
+ if (deep && node instanceof TransformNode) {
176
+ const children = node.getChildTransformNodes(true);
177
+ children.forEach(child => injectNodeMetadata(child, metadata, deep));
178
+ }
179
+ };
180
+
181
+ /**
182
+ * @param node
183
+ * @param assertCallable
184
+ * @param callableParameters
185
+ * @param deep
186
+ */
187
+ const assertTransformNode = function (
188
+ node: TransformNode,
189
+ assertCallable: (node: TransformNode, ...args: any[]) => void,
190
+ callableParameters: any[] = [],
191
+ deep: boolean = true
192
+ ) {
193
+ assertCallable(node, ...callableParameters);
194
+ if (deep) {
195
+ const children = node.getChildTransformNodes(true);
196
+ children.forEach(child => assertTransformNode(child, assertCallable, callableParameters, deep));
197
+ }
198
+ };
199
+
200
+ /**
201
+ * @param node
202
+ * @param parameter
203
+ */
204
+ const assertMeshCapability = function (node: TransformNode, parameter: string) {
205
+ if (!(node instanceof AbstractMesh)) {
206
+ const cls = node.getClassName();
207
+ throw new Error(
208
+ `Changing parameter "${parameter}" of a(n) ${cls} is not supported. Tried to change node "${node.id}".`
209
+ );
210
+ }
211
+ if (node instanceof InstancedMesh) {
212
+ throw new Error(
213
+ `Changing parameter "${parameter}" of an InstancedMesh is not supported. Tried to change node "${node.id}".`
214
+ );
215
+ }
216
+ };
217
+
218
+ /**
219
+ * @param node
220
+ * @param deep
221
+ */
222
+ const activateTransformNode = function (node: TransformNode, deep: boolean = true) {
223
+ node.setEnabled(true);
224
+ /*
225
+ if( node instanceof AbstractMesh ) {
226
+ node.visibility = 1;
227
+ node.isPickable = true;
228
+ }
229
+ */
230
+ if (deep) {
231
+ node.getChildTransformNodes(true).forEach(child => activateTransformNode(child, deep));
232
+ }
233
+ };
234
+
235
+ /**
236
+ * @param node
237
+ * @param deep
238
+ */
239
+ const deactivateTransformNode = function (node: TransformNode, deep: boolean = true) {
240
+ node.setEnabled(false);
241
+ /*
242
+ if( node instanceof AbstractMesh ) {
243
+ node.visibility = 0;
244
+ node.isPickable = false;
245
+ }
246
+ */
247
+ if (deep) {
248
+ node.getChildTransformNodes(true).forEach(child => deactivateTransformNode(child, deep));
249
+ }
250
+ };
251
+
252
+ /**
253
+ * @param node
254
+ */
255
+ const enableNodeWithParents = function (node: Node) {
256
+ node.setEnabled(true);
257
+ if (node.parent) {
258
+ enableNodeWithParents(node.parent);
259
+ }
260
+ };
261
+
262
+ /**
263
+ * @param node
264
+ */
265
+ const disableNodeWithParents = function (node: Node) {
266
+ node.setEnabled(false);
267
+ if (node.parent) {
268
+ disableNodeWithParents(node.parent);
269
+ }
270
+ };
271
+
272
+ /**
273
+ * Applies a {@link TransformationDefinition} consecutively to ensure dependencies in positioning etc.
274
+ * @param node
275
+ * @param transformation
276
+ */
277
+ const transformTransformNode = function (node: TransformNode, transformation: TransformationDefinition) {
278
+ // scaling
279
+ if (!has(node.metadata, 'scaling.initial')) {
280
+ injectNodeMetadata(node, { 'scaling.initial': node.scaling }, false);
281
+ }
282
+ const initialScaling = get(node.metadata, 'scaling.initial') as Vector3;
283
+ node.scaling = initialScaling.multiply(transformation.scaling);
284
+ // position
285
+ if (!has(node.metadata, 'position.initial')) {
286
+ injectNodeMetadata(node, { 'position.initial': node.absolutePosition.clone() }, false);
287
+ }
288
+ const initialPosition = get(node.metadata, 'position.initial') as Vector3;
289
+ node.setAbsolutePosition(initialPosition.add(transformation.position).multiply(transformation.scaling));
290
+ // rotation
291
+ if (!has(node.metadata, 'rotation.initial')) {
292
+ let rotationQuaternion = node.rotationQuaternion;
293
+ if (!rotationQuaternion) {
294
+ rotationQuaternion = Quaternion.RotationYawPitchRoll(node.rotation.x, node.rotation.y, node.rotation.z);
295
+ }
296
+ injectNodeMetadata(node, { 'rotation.initial': rotationQuaternion.asArray() }, false);
297
+ }
298
+ const initialRotationQuaternion = Quaternion.FromArray(get(node.metadata, 'rotation.initial') as []);
299
+ node.rotationQuaternion = initialRotationQuaternion;
300
+ node.rotateAround(Vector3.Zero(), Axis.X, transformation.rotation.x);
301
+ node.rotateAround(Vector3.Zero(), Axis.Y, transformation.rotation.y);
302
+ node.rotateAround(Vector3.Zero(), Axis.Z, transformation.rotation.z);
303
+ node.computeWorldMatrix(true);
304
+ };
305
+
306
+ /**
307
+ * Apply changes of environment (background texture, etc.) consecutively in order to avoid dependency related issues.
308
+ * @param scene
309
+ * @param envDef
310
+ */
311
+ const changeEnvironment = function (scene: Scene, envDef: EnvironmentDefinition) {
312
+ // issue warning if both background texture and usedefault are set
313
+ if (envDef.environmentUseDefault && envDef.environmentBackground) {
314
+ console.warn(
315
+ `!!! Warning !!! Spec parameter 'environment.usedefault' is being overruled by 'environment.background'.`
316
+ );
317
+ }
318
+
319
+ const useDefaultEnv = envDef.environmentUseDefault && !envDef.environmentBackground;
320
+
321
+ // 1) set ENVIRONMENT_COLOR
322
+ const clearColorBefore = scene.clearColor.toString();
323
+ scene.clearColor = envDef.environmentColor
324
+ ? Color4.FromColor3(envDef.environmentColor)
325
+ : useDefaultEnv
326
+ ? defaultEnvHelperColor
327
+ : defaultSceneClearColor;
328
+ const clearColorChanged = clearColorBefore !== scene.clearColor.toString();
329
+
330
+ // 2) dispose existing & set new ENVIRONMENT (==texture)
331
+ const curEnvTexture = scene.environmentTexture as Nullable<CubeTexture>;
332
+ const envTextureChanged = envDef.environment !== curEnvTexture?.url;
333
+
334
+ if (curEnvTexture && (!envDef.environment || envTextureChanged)) {
335
+ curEnvTexture.dispose();
336
+ }
337
+
338
+ const rotation = envDef.environmentRotation !== undefined ? Tools.ToRadians(envDef.environmentRotation) : 0;
339
+ if (envDef.environment && envTextureChanged) {
340
+ const envTexture = CubeTexture.CreateFromPrefilteredData(envDef.environment, scene);
341
+ envTexture.rotationY = rotation;
342
+ scene.environmentTexture = envTexture;
343
+ } else if (curEnvTexture && curEnvTexture.rotationY !== rotation) {
344
+ curEnvTexture.rotationY = rotation;
345
+ }
346
+
347
+ // 3) dispose existing & set new ENVIRONMENT_BACKGROUND
348
+ const curDome = scene.getNodeByName(backgroundDomeName) as undefined | PhotoDome;
349
+ const backgroundUrlChanged = envDef.environmentBackground !== curDome?.texture.url;
350
+
351
+ if (curDome && (!envDef.environmentBackground || backgroundUrlChanged)) {
352
+ curDome.dispose();
353
+ }
354
+
355
+ const rotationPhotoDome = -1 * rotation;
356
+ if (envDef.environmentBackground && backgroundUrlChanged) {
357
+ const textureUrl = envDef.environmentBackground;
358
+ const dome = new PhotoDome(backgroundDomeName, textureUrl, { resolution: 32, size: 450 }, scene);
359
+ // Rotate submesh to get them in line with environment texture
360
+ dome.getChildMeshes(true)[0].rotation.y = Tools.ToRadians(90);
361
+ dome.rotation.y = rotationPhotoDome;
362
+ } else if (curDome && curDome.rotation.y !== rotationPhotoDome) {
363
+ curDome.rotation.y = rotationPhotoDome;
364
+ }
365
+
366
+ // 4) dispose existing & set new ENVIRONMENT_USEDEFAULT (only if no background is set)
367
+ const curEnvHelper = scene.metadata?.[envHelperMetadataName] as undefined | EnvironmentHelper;
368
+
369
+ if (curEnvHelper && !useDefaultEnv) {
370
+ curEnvHelper.dispose();
371
+ delete scene.metadata[envHelperMetadataName];
372
+ }
373
+
374
+ const envHelperMainColor = Color3.FromArray(scene.clearColor.asArray());
375
+ if (useDefaultEnv && !curEnvHelper) {
376
+ const envHelper = scene.createDefaultEnvironment({ sizeAuto: true });
377
+ envHelper?.setMainColor(envHelperMainColor);
378
+ if (envHelper) {
379
+ scene.metadata = merge({}, scene.metadata, { [envHelperMetadataName]: envHelper });
380
+ }
381
+ } else if (curEnvHelper && useDefaultEnv && clearColorChanged) {
382
+ curEnvHelper.setMainColor(envHelperMainColor);
383
+ }
384
+
385
+ // 5) set ENVIRONMENT_INTENSITY
386
+ if (envDef.environmentIntensity !== undefined) {
387
+ scene.environmentIntensity = envDef.environmentIntensity;
388
+ }
389
+ };
390
+
391
+ /**
392
+ * Sets a material by a given material id as material property on the given node.
393
+ *
394
+ * If the material is not already available in the scene, the viewer tries to create a material based on a Combeenation
395
+ * [material asset](https://docs.combeenation.com/docs/howto-create-and-use-babylon-and-material-asset).
396
+ * This of course only works if the viewer is used inside a Combeenation configurator.
397
+ *
398
+ * Furthermore this function also defers the material creation if the node is not visible yet to improve network &
399
+ * viewer bootstrap performance as textures are automatically being lazy loaded only when they are actually visible in
400
+ * the scene.
401
+ *
402
+ * Finally the material will not be applied before all its textures have been loaded. In this way "flickering" effects
403
+ * will be avoided, since the material would be incomplete without its loaded textures.
404
+ */
405
+ const setMaterial = function (node: TransformNode, materialId: string, deep: boolean = true, variant?: Variant) {
406
+ if (node instanceof AbstractMesh) {
407
+ const materialExists = node.getScene().getMaterialById(materialId);
408
+ const hasMissingMaterial = has(node.metadata, missingMaterialMetadataName);
409
+ const deferMaterialCreation = !materialExists && !node.isEnabled();
410
+ if (deferMaterialCreation) {
411
+ // do not set the material
412
+ injectNodeMetadata(node, { [missingMaterialMetadataName]: materialId }, false);
413
+ // if it already had the missing material flag before, there already exists an observer...
414
+ if (!hasMissingMaterial) {
415
+ addMissingMaterialObserver(node);
416
+ }
417
+ } else {
418
+ // create material and apply it when textures have been loaded
419
+ getOrCreateMaterial(node.getScene(), materialId, variant).then(material => {
420
+ applyMaterial(material, node).then(() => emitter.emit(Event.MESH_MATERIAL_APPLIED, node, material));
421
+
422
+ if (hasMissingMaterial) {
423
+ delete node.metadata[missingMaterialMetadataName];
424
+ }
425
+ });
426
+ }
427
+ }
428
+ // recursively set materials on children (if desired)
429
+ if (deep) {
430
+ for (const child of node.getChildTransformNodes(true)) {
431
+ setMaterial(child, materialId, deep, variant);
432
+ }
433
+ }
434
+ };
435
+
436
+ /**
437
+ * Gets the Material either from the given {@link Variant}, the given scene or tries to create it from an Combeenation
438
+ * material asset when inside a Combeenation configurator.
439
+ */
440
+ const getOrCreateMaterial = async function (scene: Scene, materialId: string, variant?: Variant): Promise<Material> {
441
+ let chosenMaterial: Material | undefined | null;
442
+ chosenMaterial = variant?.inheritedMaterials.find(mat => mat.id === materialId);
443
+ chosenMaterial = chosenMaterial || scene.materials.find(mat => mat.id === materialId);
444
+ chosenMaterial = chosenMaterial || (await createMaterialFromCbnAssets(materialId, scene));
445
+ if (chosenMaterial) {
446
+ return chosenMaterial as Material;
447
+ }
448
+ // reject when material was not found
449
+ let rejectMessage = `Material with id "${materialId}" does not exist on scene.`;
450
+ if (variant) {
451
+ rejectMessage = `Material with id "${materialId}" does not exist for variant "${variant.id}".`;
452
+ }
453
+ throw new Error(rejectMessage);
454
+ };
455
+
456
+ /**
457
+ * Waits until the materials textures are loaded and shaders are compiled.
458
+ * Then sets the material on the node if there is no newer "set material" request
459
+ */
460
+ const applyMaterial = async function (material: Material, node: AbstractMesh) {
461
+ // set current material id as last valid id, in this case all previously set materials on the node will be invalidated
462
+ injectNodeMetadata(node, { [materialWaitingToBeSetMetadataName]: material.id }, false);
463
+
464
+ const promTexturesReady = new Promise<void>(resolve =>
465
+ BaseTexture.WhenAllReady(material.getActiveTextures(), resolve)
466
+ );
467
+ // this promise should only take some time on the first call of the corresponding shader (eg: PBRMaterial shader)
468
+ // on each other call of the same material/shader type there should be not be a waiting time, or at maximum one frame
469
+ // https://forum.babylonjs.com/t/mesh-flickering-when-setting-material-initially/37312
470
+ const promMaterialCompiled = material.forceCompilationAsync(node);
471
+
472
+ // material needs to fulfill 2 criterias before it's ready to use
473
+ // - textures need to be "ready" => downloaded
474
+ // - dedicated shader needs to be compiled
475
+ // if this would not be the case you can see some "flickering" when setting the material
476
+ await Promise.all([promTexturesReady, promMaterialCompiled]);
477
+
478
+ // textures ready, now check if the material is still up-to-date
479
+ if (material.id === node.metadata?.[materialWaitingToBeSetMetadataName]) {
480
+ node.material = material;
481
+ delete node.metadata[materialWaitingToBeSetMetadataName];
482
+ }
483
+ };
484
+
485
+ /**
486
+ * !!! Warning !!!
487
+ * This function is not public API. Whilst it can help solving certain problems, it only works reliably in well defined
488
+ * situations and can cause unwanted side effects under some conditions. Use carefully at your own risk!
489
+ *
490
+ * See https://combeenation.myjetbrains.com/youtrack/issue/CB-5906 for further details regarding this warning.
491
+ *
492
+ * Set material of an instanced meshes source mesh.
493
+ * Changes the material of all instanced meshes which have the same source mesh.
494
+ *
495
+ * @param node
496
+ * @param material
497
+ * @param deep
498
+ *
499
+ * @ignore
500
+ */
501
+ const setSourceNodeMaterial = function (node: TransformNode, material: Material, deep: boolean = true) {
502
+ const warn = ` You're using "setSourceNodeMaterial" which is not public API.
503
+ Whilst it can help solving certain problems, it only works reliably in well defined situations and can cause unwanted side effects under some conditions.
504
+ Use carefully at your own risk!`;
505
+ console.warn(`!!! Warning !!!\n${warn}`);
506
+
507
+ if (node instanceof InstancedMesh) {
508
+ node.sourceMesh.material = material;
509
+ }
510
+ if (deep) {
511
+ node.getChildTransformNodes(true).forEach(child => setSourceNodeMaterial(child, material, deep));
512
+ }
513
+ };
514
+
515
+ /**
516
+ * @param node
517
+ * @param color
518
+ * @param deep
519
+ */
520
+ const setMaterialColor = function (node: TransformNode, color: Color3, deep: boolean = true) {
521
+ if (node instanceof AbstractMesh && node.material) {
522
+ const materialCls = node.material.getClassName();
523
+ switch (materialCls) {
524
+ case 'PBRMaterial':
525
+ (node.material as PBRMaterial).albedoColor = color.toLinearSpace();
526
+ break;
527
+ case 'StandardMaterial':
528
+ (node.material as StandardMaterial).diffuseColor = color;
529
+ break;
530
+ default:
531
+ throw new Error(`Setting color for material of instance "${materialCls}" not implemented (yet).`);
532
+ }
533
+ setMaterial(node, node.material.id, false);
534
+ }
535
+ if (deep) {
536
+ node.getChildTransformNodes(true).forEach(child => setMaterialColor(child, color, deep));
537
+ }
538
+ };
539
+
540
+ /**
541
+ * @param node
542
+ * @param texture
543
+ * @param deep
544
+ */
545
+ const setMaterialTexture = function (node: TransformNode, texture: Texture, deep: boolean = true) {
546
+ if (node instanceof AbstractMesh && node.material) {
547
+ const materialCls = node.material.getClassName();
548
+ switch (materialCls) {
549
+ case 'PBRMaterial':
550
+ (node.material as PBRMaterial).albedoTexture = texture;
551
+ break;
552
+ case 'StandardMaterial':
553
+ (node.material as StandardMaterial).diffuseTexture = texture;
554
+ break;
555
+ default:
556
+ throw new Error(`Setting texture for material of instance "${materialCls}" not implemented (yet).`);
557
+ }
558
+ setMaterial(node, node.material.id, false);
559
+ }
560
+ if (deep) {
561
+ node.getChildTransformNodes(true).forEach(child => setMaterialTexture(child, texture, deep));
562
+ }
563
+ };
564
+
565
+ /**
566
+ * @param node
567
+ * @param metallness
568
+ * @param deep
569
+ */
570
+ const setMaterialMetallness = function (node: TransformNode, metallness: number, deep: boolean = true) {
571
+ if (node instanceof AbstractMesh && node.material) {
572
+ const materialCls = node.material.getClassName();
573
+ switch (materialCls) {
574
+ case 'PBRMaterial':
575
+ (node.material as PBRMaterial).metallic = metallness;
576
+ break;
577
+ default:
578
+ throw new Error(`Setting metallness for material of instance "${materialCls}" not implemented (yet).`);
579
+ }
580
+ setMaterial(node, node.material.id, false);
581
+ }
582
+ if (deep) {
583
+ node.getChildTransformNodes(true).forEach(child => setMaterialMetallness(child, metallness, deep));
584
+ }
585
+ };
586
+
587
+ /**
588
+ * @param node
589
+ * @param roughness
590
+ * @param deep
591
+ */
592
+ const setMaterialRoughness = function (node: TransformNode, roughness: number, deep: boolean = true) {
593
+ if (node instanceof AbstractMesh && node.material) {
594
+ const materialCls = node.material.getClassName();
595
+ switch (materialCls) {
596
+ case 'PBRMaterial':
597
+ (node.material as PBRMaterial).roughness = roughness;
598
+ break;
599
+ case 'StandardMaterial':
600
+ (node.material as StandardMaterial).roughness = roughness;
601
+ break;
602
+ default:
603
+ throw new Error(`Setting roughness for material of instance "${materialCls}" not implemented (yet).`);
604
+ }
605
+ setMaterial(node, node.material.id, false);
606
+ }
607
+ if (deep) {
608
+ node.getChildTransformNodes(true).forEach(child => setMaterialRoughness(child, roughness, deep));
609
+ }
610
+ };
611
+
612
+ /**
613
+ * @param node
614
+ * @param layer
615
+ * @param color
616
+ * @param deep
617
+ */
618
+ const addToHighlightLayer = function (layer: HighlightLayer, color: Color3, node: TransformNode, deep: boolean = true) {
619
+ if (node instanceof AbstractMesh) {
620
+ layer.addMesh(node as Mesh, color);
621
+ }
622
+ if (deep) {
623
+ node.getChildTransformNodes(true).forEach(child => addToHighlightLayer(layer, color, child, deep));
624
+ }
625
+ };
626
+
627
+ /**
628
+ * @param node
629
+ * @param layer
630
+ * @param deep
631
+ */
632
+ const removeFromHighlightLayer = function (layer: HighlightLayer, node: TransformNode, deep: boolean = true) {
633
+ if (node instanceof AbstractMesh) {
634
+ layer.removeMesh(node as Mesh);
635
+ }
636
+ if (deep) {
637
+ node.getChildTransformNodes(true).forEach(child => removeFromHighlightLayer(layer, child, deep));
638
+ }
639
+ };
640
+
641
+ /**
642
+ * @param node
643
+ * @param receiveShadows
644
+ * @param deep
645
+ */
646
+ const setReceiveShadows = function (node: TransformNode, receiveShadows: boolean, deep: boolean = true) {
647
+ if (node instanceof AbstractMesh) {
648
+ node.receiveShadows = receiveShadows;
649
+ }
650
+ if (deep) {
651
+ node.getChildTransformNodes(true).forEach(child => setReceiveShadows(child, receiveShadows, deep));
652
+ }
653
+ };
654
+
655
+ /**
656
+ * @param node
657
+ * @param generator
658
+ * @param deep
659
+ */
660
+ const addToShadowGenerator = function (generator: ShadowGenerator, node: TransformNode, deep: boolean = true) {
661
+ if (node instanceof AbstractMesh) {
662
+ // We have to remove the node because there's no duplicate check in babylon
663
+ generator.removeShadowCaster(node, false);
664
+ generator.addShadowCaster(node, false);
665
+ }
666
+ if (deep) {
667
+ node.getChildTransformNodes(true).forEach(child => addToShadowGenerator(generator, child, deep));
668
+ }
669
+ };
670
+
671
+ /**
672
+ * @param node
673
+ * @param generator
674
+ * @param deep
675
+ */
676
+ const removeFromShadowGenerator = function (generator: ShadowGenerator, node: TransformNode, deep: boolean = true) {
677
+ if (node instanceof AbstractMesh) {
678
+ generator.removeShadowCaster(node, false);
679
+ }
680
+ if (deep) {
681
+ node.getChildTransformNodes(true).forEach(child => removeFromShadowGenerator(generator, child, deep));
682
+ }
683
+ };
684
+
685
+ /**
686
+ * https://forum.babylonjs.com/t/get-mesh-bounding-box-position-and-size-in-2d-screen-coordinates/1058/3
687
+ * @param mesh
688
+ * @param scene
689
+ * @param canvas
690
+ */
691
+ const getClientRectFromMesh = function (mesh: AbstractMesh, scene: Scene, canvas: HTMLCanvasElement): ClientRect {
692
+ // get bounding box of the mesh
693
+ const meshVectors = mesh.getBoundingInfo().boundingBox.vectors;
694
+ // get the matrix and viewport needed to project the vectors onto the screen
695
+ const worldMatrix = mesh.getWorldMatrix();
696
+ const transformMatrix = scene.getTransformMatrix();
697
+ const viewport = scene.activeCamera!.viewport;
698
+ // loop though all the vectors and project them against the current camera viewport to get a set of coordinates
699
+ const coordinates = meshVectors.map(vector => {
700
+ const projection = Vector3.Project(vector, worldMatrix, transformMatrix, viewport);
701
+ projection.x = projection.x * canvas.clientWidth;
702
+ projection.y = projection.y * canvas.clientHeight;
703
+ return projection;
704
+ });
705
+ // get the min and max for all the coordinates so we can calculate the largest possible screen size
706
+ const maxX = Math.max(...coordinates.map(o => o.x));
707
+ const minX = Math.min(...coordinates.map(o => o.x));
708
+ const maxY = Math.max(...coordinates.map(o => o.y));
709
+ const minY = Math.min(...coordinates.map(o => o.y));
710
+ // return a ClientRect from this
711
+ return {
712
+ width: maxX - minX,
713
+ height: maxY - minY,
714
+ left: minX,
715
+ top: minY,
716
+ right: maxX,
717
+ bottom: maxY,
718
+ } as ClientRect;
719
+ };
720
+
721
+ type BaseTextureWithOnLoadObservable = BaseTexture & {
722
+ onLoadObservable: Observable<BaseTexture>;
723
+ };
724
+
725
+ /**
726
+ * This type guard checks whether the given `BaseTextures` is any of its subtypes which comes with an
727
+ * `onLoadObservable`.
728
+ *
729
+ * !!! Timing of when this function is called is important !!!
730
+ * See the following for more details: https://forum.babylonjs.com/t/basetexture-whenallready-returns-too-early/34501/6
731
+ */
732
+ const isTextureWithOnLoadObservable = function (texture: BaseTexture): texture is BaseTextureWithOnLoadObservable {
733
+ return !!(texture as BaseTextureWithOnLoadObservable).onLoadObservable;
734
+ };
735
+
736
+ /**
737
+ * @param objects
738
+ * @param tagMapping
739
+ */
740
+ const mapTags = function (objects: object[], tagMapping: TagMapping): string[] {
741
+ let affectedTags: string[] = [];
742
+ for (const object of objects) {
743
+ const oldTags = Object.keys(Tags.GetTags(object, false) ?? {});
744
+ const mappedTags = oldTags.map(t => tagMapping[t] || t);
745
+ Tags.RemoveTagsFrom(object, oldTags.join(' '));
746
+ Tags.AddTagsTo(object, mappedTags.join(' '));
747
+ affectedTags = [...affectedTags, ...mappedTags];
748
+ }
749
+ return uniq(affectedTags);
750
+ };
751
+
752
+ /**
753
+ * Gets an array of ids for nodeIds that exist in both TransformNode arrays.
754
+ * @param nodes1
755
+ * @param nodes2
756
+ * @param predicate
757
+ */
758
+ const intersectingNodeNames = function (nodes1: Node[], nodes2: Node[], predicate?: (node: Node) => boolean): string[] {
759
+ const nodeNames1 = nodes1.filter(n => !predicate || predicate(n)).map(n => n.name);
760
+ const nodesNames2 = nodes2.filter(n => !predicate || predicate(n)).map(n => n.name);
761
+ return nodeNames1.filter(n1 => nodesNames2.includes(n1));
762
+ };
763
+
764
+ /**
765
+ * Gets an array of ids for duplicate nodeIds in given node array.
766
+ * @param nodes
767
+ * @param predicate
768
+ */
769
+ const duplicateNodeNames = function (nodes: Node[], predicate?: (node: Node) => boolean): string[] {
770
+ const nodeNames = nodes.filter(n => !predicate || predicate(n)).map(n => n.name);
771
+ return nodeNames.filter((v, i, self) => self.indexOf(v) !== i);
772
+ };
773
+
774
+ /**
775
+ * Reports duplicate nodeIds.
776
+ * @param nodeNames
777
+ */
778
+ const reportDuplicateNodeNames = function (nodeNames: string[]): void {
779
+ if (nodeNames.length > 0) {
780
+ const warn = `There are duplicate nodeNames: ${nodeNames.join(', ')}`;
781
+ console.warn(`!!! Warning !!!\n${warn}`);
782
+ window.Cbn?.Assets.reportDuplicateNodeName(nodeNames);
783
+ }
784
+ };
785
+
786
+ export {
787
+ getRootNode,
788
+ isTextureWithOnLoadObservable,
789
+ mapToDottedNodes,
790
+ getDottedPathForNode,
791
+ cloneTransformNode,
792
+ cloneNodeWithParents,
793
+ cloneTransformNodeMaterial,
794
+ getOrCreateMaterial,
795
+ applyMaterial,
796
+ injectNodeMetadata,
797
+ assertTransformNode,
798
+ assertMeshCapability,
799
+ activateTransformNode,
800
+ deactivateTransformNode,
801
+ enableNodeWithParents,
802
+ disableNodeWithParents,
803
+ transformTransformNode,
804
+ setMaterial,
805
+ setSourceNodeMaterial,
806
+ setMaterialColor,
807
+ setMaterialTexture,
808
+ setMaterialMetallness,
809
+ setMaterialRoughness,
810
+ addToHighlightLayer,
811
+ removeFromHighlightLayer,
812
+ setReceiveShadows,
813
+ addToShadowGenerator,
814
+ removeFromShadowGenerator,
815
+ getClientRectFromMesh,
816
+ changeEnvironment,
817
+ backgroundDomeName,
818
+ envHelperMetadataName,
819
+ mapTags,
820
+ intersectingNodeNames,
821
+ duplicateNodeNames,
822
+ reportDuplicateNodeNames,
823
+ };