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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +9 -111
  2. package/dist/lib-cjs/api/classes/animationInterface.d.ts +8 -8
  3. package/dist/lib-cjs/api/classes/animationInterface.js +2 -2
  4. package/dist/lib-cjs/api/classes/dottedPath.d.ts +79 -79
  5. package/dist/lib-cjs/api/classes/dottedPath.js +166 -166
  6. package/dist/lib-cjs/api/classes/element.d.ts +153 -153
  7. package/dist/lib-cjs/api/classes/element.js +666 -667
  8. package/dist/lib-cjs/api/classes/element.js.map +1 -1
  9. package/dist/lib-cjs/api/classes/event.d.ts +401 -401
  10. package/dist/lib-cjs/api/classes/event.js +424 -424
  11. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  12. package/dist/lib-cjs/api/classes/eventBroadcaster.js +49 -49
  13. package/dist/lib-cjs/api/classes/fuzzyMap.d.ts +7 -7
  14. package/dist/lib-cjs/api/classes/fuzzyMap.js +21 -21
  15. package/dist/lib-cjs/api/classes/parameter.d.ts +410 -410
  16. package/dist/lib-cjs/api/classes/parameter.js +642 -642
  17. package/dist/lib-cjs/api/classes/parameterObservable.d.ts +36 -36
  18. package/dist/lib-cjs/api/classes/parameterObservable.js +72 -72
  19. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  20. package/dist/lib-cjs/api/classes/parameterizable.js +102 -102
  21. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +45 -45
  22. package/dist/lib-cjs/api/classes/placementAnimation.js +176 -176
  23. package/dist/lib-cjs/api/classes/variant.d.ts +261 -261
  24. package/dist/lib-cjs/api/classes/variant.js +871 -871
  25. package/dist/lib-cjs/api/classes/variantInstance.d.ts +53 -53
  26. package/dist/lib-cjs/api/classes/variantInstance.js +125 -125
  27. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  28. package/dist/lib-cjs/api/classes/variantParameterizable.js +86 -86
  29. package/dist/lib-cjs/api/classes/viewer.d.ts +211 -213
  30. package/dist/lib-cjs/api/classes/viewer.js +736 -717
  31. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  32. package/dist/lib-cjs/api/classes/viewerError.d.ts +43 -43
  33. package/dist/lib-cjs/api/classes/viewerError.js +55 -55
  34. package/dist/lib-cjs/api/classes/viewerLight.d.ts +66 -66
  35. package/dist/lib-cjs/api/classes/viewerLight.js +344 -348
  36. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  37. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  38. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  39. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +13 -13
  40. package/dist/lib-cjs/api/internal/sceneSetup.js +224 -226
  41. package/dist/lib-cjs/api/internal/sceneSetup.js.map +1 -1
  42. package/dist/lib-cjs/api/manager/animationManager.d.ts +30 -30
  43. package/dist/lib-cjs/api/manager/animationManager.js +126 -126
  44. package/dist/lib-cjs/api/manager/gltfExportManager.d.ts +102 -102
  45. package/dist/lib-cjs/api/manager/gltfExportManager.js +322 -322
  46. package/dist/lib-cjs/api/manager/sceneManager.d.ts +33 -33
  47. package/dist/lib-cjs/api/manager/sceneManager.js +128 -128
  48. package/dist/lib-cjs/api/manager/tagManager.d.ts +118 -118
  49. package/dist/lib-cjs/api/manager/tagManager.js +535 -535
  50. package/dist/lib-cjs/api/manager/textureLoadManager.d.ts +22 -22
  51. package/dist/lib-cjs/api/manager/textureLoadManager.js +98 -98
  52. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +106 -106
  53. package/dist/lib-cjs/api/manager/variantInstanceManager.js +290 -290
  54. package/dist/lib-cjs/api/store/specStorage.d.ts +32 -32
  55. package/dist/lib-cjs/api/store/specStorage.js +65 -65
  56. package/dist/lib-cjs/api/util/babylonHelper.d.ts +238 -238
  57. package/dist/lib-cjs/api/util/babylonHelper.js +826 -826
  58. package/dist/lib-cjs/api/util/geometryHelper.d.ts +7 -7
  59. package/dist/lib-cjs/api/util/geometryHelper.js +115 -115
  60. package/dist/lib-cjs/api/util/globalTypes.d.ts +484 -484
  61. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  62. package/dist/lib-cjs/api/util/resourceHelper.d.ts +58 -58
  63. package/dist/lib-cjs/api/util/resourceHelper.js +214 -214
  64. package/dist/lib-cjs/api/util/sceneLoaderHelper.d.ts +44 -44
  65. package/dist/lib-cjs/api/util/sceneLoaderHelper.js +175 -175
  66. package/dist/lib-cjs/api/util/stringHelper.d.ts +13 -13
  67. package/dist/lib-cjs/api/util/stringHelper.js +32 -32
  68. package/dist/lib-cjs/api/util/structureHelper.d.ts +9 -9
  69. package/dist/lib-cjs/api/util/structureHelper.js +64 -64
  70. package/dist/lib-cjs/buildinfo.json +3 -3
  71. package/dist/lib-cjs/commonjs.tsconfig.tsbuildinfo +1 -1
  72. package/dist/lib-cjs/index.d.ts +54 -54
  73. package/dist/lib-cjs/index.js +117 -117
  74. package/package.json +84 -82
  75. package/src/api/classes/animationInterface.ts +10 -10
  76. package/src/api/classes/dottedPath.ts +181 -181
  77. package/src/api/classes/element.ts +723 -723
  78. package/src/api/classes/event.ts +457 -457
  79. package/src/api/classes/eventBroadcaster.ts +52 -52
  80. package/src/api/classes/fuzzyMap.ts +21 -21
  81. package/src/api/classes/parameter.ts +686 -686
  82. package/src/api/classes/parameterObservable.ts +73 -73
  83. package/src/api/classes/parameterizable.ts +87 -87
  84. package/src/api/classes/placementAnimation.ts +162 -162
  85. package/src/api/classes/variant.ts +964 -964
  86. package/src/api/classes/variantInstance.ts +123 -123
  87. package/src/api/classes/variantParameterizable.ts +83 -83
  88. package/src/api/classes/viewer.ts +786 -770
  89. package/src/api/classes/viewerError.ts +63 -63
  90. package/src/api/classes/viewerLight.ts +335 -339
  91. package/src/api/internal/debugViewer.ts +90 -90
  92. package/src/api/internal/lensRendering.ts +9 -9
  93. package/src/api/internal/sceneSetup.ts +203 -205
  94. package/src/api/manager/animationManager.ts +143 -143
  95. package/src/api/manager/gltfExportManager.ts +312 -312
  96. package/src/api/manager/sceneManager.ts +134 -134
  97. package/src/api/manager/tagManager.ts +576 -576
  98. package/src/api/manager/textureLoadManager.ts +96 -96
  99. package/src/api/manager/variantInstanceManager.ts +306 -306
  100. package/src/api/store/specStorage.ts +68 -68
  101. package/src/api/util/babylonHelper.ts +915 -915
  102. package/src/api/util/geometryHelper.ts +140 -140
  103. package/src/api/util/globalTypes.ts +560 -560
  104. package/src/api/util/resourceHelper.ts +201 -201
  105. package/src/api/util/sceneLoaderHelper.ts +170 -170
  106. package/src/api/util/stringHelper.ts +30 -30
  107. package/src/api/util/structureHelper.ts +63 -63
  108. package/src/buildinfo.json +3 -3
  109. package/src/dev.ts +70 -62
  110. package/src/index.ts +103 -103
  111. package/src/types.d.ts +49 -38
@@ -1,312 +1,312 @@
1
- import { bakeGeometryOfAllMeshes } from '..//util/geometryHelper';
2
- import { Viewer } from '../classes/viewer';
3
- import { injectMetadata } from '../util/babylonHelper';
4
- import { isNodeIncludedInExclusionList } from '../util/structureHelper';
5
- import { Engine } from '@babylonjs/core/Engines/engine';
6
- import { EngineStore } from '@babylonjs/core/Engines/engineStore';
7
- import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
8
- import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';
9
- import { Color3 } from '@babylonjs/core/Maths/math.color';
10
- import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
11
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
12
- import { SceneSerializer } from '@babylonjs/core/Misc/sceneSerializer';
13
- import { Scene } from '@babylonjs/core/scene';
14
- import { GLTF2Export, IExportOptions } from '@babylonjs/serializers/glTF/2.0';
15
- import { has, merge } from 'lodash-es';
16
-
17
- type MetadataMap = { [key: string]: any };
18
- export class GltfExportManager {
19
- protected static readonly _CLONED_FROM_MAT_METADATA_PROPERTY = 'clonedFrom';
20
- public static readonly NAME_BEFORE_EXPORT_METADATA_PROPERTY = 'nameBeforeExport';
21
-
22
- /**
23
- * Constructor.
24
- */
25
- protected constructor(protected viewer: Viewer) {}
26
-
27
- /**
28
- * Creates an {@link GltfExportManager}.
29
- */
30
- public static async create(viewer: Viewer): Promise<GltfExportManager> {
31
- return new GltfExportManager(viewer);
32
- }
33
-
34
- /**
35
- * Exports selected nodes to a file.
36
- * @param filename optional name of the exported .GLB file.
37
- * @param exportOptions export options to be merged with default options.\
38
- * `exportOptions.exchangeRefractionMaterials` and `exportOptions.limitTextureSize`
39
- * default to `true` if not given.
40
- * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
41
- * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
42
- */
43
- public async exportGlb(
44
- filename = 'glb-export.glb',
45
- { exchangeRefractionMaterials = true, limitTextureSize = true, ...exportOptions }: IExportOptionsExtended = {},
46
- optimizeForAR: boolean = false,
47
- excluded?: ExcludedGeometryList
48
- ): Promise<File | undefined> {
49
- const { scene, sceneCopied } = await this.exportPreProcess(
50
- exchangeRefractionMaterials,
51
- limitTextureSize,
52
- optimizeForAR
53
- );
54
- const glbData = await GLTF2Export.GLBAsync(scene, 'dummy', this.gltfExportOptions(exportOptions, excluded));
55
- this.exportPostProcess(scene, sceneCopied);
56
-
57
- const resBlob = glbData.glTFFiles['dummy.glb'];
58
- // check if result is valid, according to the typings this could also be a string
59
- if (resBlob instanceof Blob) {
60
- if (!filename.endsWith('.glb')) {
61
- filename += '.glb';
62
- }
63
- return new File([resBlob], filename);
64
- } else {
65
- // result was not a valid blob
66
- return undefined;
67
- }
68
- }
69
-
70
- /**
71
- * Exports selected nodes to GLTF. This may result in more than one file, since textures are exported separately.
72
- * @param filename name of the main (text-based) .GLTF file referring to separate texture files.
73
- * @param exportOptions export options to be merged with default options.\
74
- * `exportOptions.exchangeRefractionMaterials` and `exportOptions.limitTextureSize`
75
- * default to `true` if not given.
76
- * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
77
- * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
78
- */
79
- public async exportGltfToFile(
80
- filename: string,
81
- { exchangeRefractionMaterials = true, limitTextureSize = true, ...exportOptions }: IExportOptionsExtended = {},
82
- optimizeForAR: boolean = false,
83
- excluded?: ExcludedGeometryList
84
- ) {
85
- const { scene, sceneCopied } = await this.exportPreProcess(
86
- exchangeRefractionMaterials,
87
- limitTextureSize,
88
- optimizeForAR
89
- );
90
- const gltf = await GLTF2Export.GLTFAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
91
- gltf.downloadFiles();
92
- this.exportPostProcess(scene, sceneCopied);
93
- }
94
-
95
- /**
96
- * Exports selected nodes to GLB. This results in one binary file.
97
- * @param filename name of the .GLB file.
98
- * @param exportOptions export options to be merged with default options.\
99
- * `exportOptions.exchangeRefractionMaterials` and `exportOptions.limitTextureSize`
100
- * default to `true` if not given.
101
- * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
102
- * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
103
- */
104
- public async exportGlbToFile(
105
- filename: string,
106
- { exchangeRefractionMaterials = true, limitTextureSize = true, ...exportOptions }: IExportOptionsExtended = {},
107
- optimizeForAR: boolean = false,
108
- excluded?: ExcludedGeometryList
109
- ) {
110
- const { scene, sceneCopied } = await this.exportPreProcess(
111
- exchangeRefractionMaterials,
112
- limitTextureSize,
113
- optimizeForAR
114
- );
115
- const glb = await GLTF2Export.GLBAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
116
- glb.downloadFiles();
117
- this.exportPostProcess(scene, sceneCopied);
118
- }
119
-
120
- /**
121
- * Gets predefined {@link IExportOptions } merged with given ones.
122
- */
123
- protected gltfExportOptions(mergeWithOptions: IExportOptions = {}, excluded?: ExcludedGeometryList): IExportOptions {
124
- const defaultOptions: IExportOptions = {
125
- shouldExportNode: function (node: any) {
126
- if (!node.isEnabled()) {
127
- return false;
128
- }
129
- if ((node.name as string).startsWith(Viewer.BOUNDING_BOX_NAME)) {
130
- return false;
131
- }
132
- if (excluded && node instanceof TransformNode && isNodeIncludedInExclusionList(node, excluded)) {
133
- return false;
134
- }
135
- return true;
136
- },
137
- };
138
- return merge({}, defaultOptions, mergeWithOptions);
139
- }
140
-
141
- /**
142
- * Stuff to be done before exporting to GLTF
143
- *
144
- * @returns Either the original scene if no adjustments have been made or a copied scene (which can be disposed after
145
- * the export) if adjustments have been made
146
- */
147
- protected async exportPreProcess(
148
- exchangeRefractionMaterials: boolean,
149
- limitTextureSize: boolean,
150
- optimizeForAR: boolean
151
- ): Promise<{ scene: Scene; sceneCopied: boolean }> {
152
- if (!exchangeRefractionMaterials && !optimizeForAR && !limitTextureSize) {
153
- // no need to copy the scene if no adjustments have to be made
154
- return { scene: this.viewer.scene, sceneCopied: false };
155
- }
156
-
157
- // copy the scene for the GLB export improvements, so that the original viewer scene remains untouched
158
- const copiedScene = await this.copyViewerScene(limitTextureSize);
159
-
160
- if (exchangeRefractionMaterials) {
161
- this.exchangeRefractionMaterials(copiedScene);
162
- }
163
-
164
- if (optimizeForAR) {
165
- this.setUniqueMeshNames(copiedScene);
166
- // get rid of negative scalings and morph targets, since iOS can't handle it in the QuickLook app
167
- bakeGeometryOfAllMeshes(copiedScene);
168
- // certain devices can't load models with skeletons, just remove them since animations are not supported in the AR
169
- // scene anyway
170
- while (copiedScene.skeletons.length) {
171
- const skeleton = copiedScene.skeletons.pop();
172
- skeleton!.dispose();
173
- }
174
- }
175
-
176
- return { scene: copiedScene, sceneCopied: true };
177
- }
178
-
179
- /**
180
- * Create a copy of the viewer scene, which can be further processed and optimized for the GLB export.
181
- * There is no "scene.clone" function, therefore the scene is serialized and loaded again to achieve this result.
182
- */
183
- protected async copyViewerScene(limitTextureSize: boolean): Promise<Scene> {
184
- // required by the scene serializer
185
- await import(/* webpackChunkName: "physicsenginecomponent" */ '@babylonjs/core/Physics/physicsEngineComponent');
186
-
187
- // copy scene function uses scene serializer, which can't handle "complex" data like classes, function or recursive
188
- // data structures in metadata
189
- // it basically does a `JSON.stringify` on the metadata
190
- // therefore the metadata has to be removed from the nodes before the copy process
191
- const metadataArr = this.extractMetadataOfAllNodes();
192
-
193
- // serialize the scene
194
- const serializedScene = await SceneSerializer.SerializeAsync(this.viewer.scene);
195
-
196
- // set the cropped metadata back to the viewer scene nodes
197
- this.restoreMetadataOfAllNodes(metadataArr);
198
-
199
- // load the scene into an invisible "dummy" canvas
200
- const dummyCanvas = document.createElement('canvas');
201
- const engine = new Engine(dummyCanvas);
202
-
203
- if (limitTextureSize) {
204
- // according to some tests iOS devices break when exporting a scene with textures above 1024
205
- // this only affects the scene clone for the export
206
- engine.getCaps().maxTextureSize = 1024;
207
- }
208
-
209
- // overwritting _LastCreatedScene to fix issue: https://combeenation.youtrack.cloud/issue/CB-8972
210
- // In short: dummy scene erroneously interacts with original viewer scene
211
- // setting viewer scene as fallback again (`_LastCreatedScene`) resolves that issue
212
- const curLastScene = EngineStore._LastCreatedScene;
213
- const newScene = new Scene(engine);
214
- EngineStore._LastCreatedScene = curLastScene;
215
-
216
- SceneLoader.ShowLoadingScreen = false;
217
- await SceneLoader.AppendAsync('', 'data:' + JSON.stringify(serializedScene), newScene, undefined, '.babylon');
218
-
219
- return newScene;
220
- }
221
-
222
- /**
223
- * Stuff to be done after the GLTF export
224
- */
225
- protected exportPostProcess(scene: Scene, disposeScene: boolean) {
226
- if (disposeScene) {
227
- // copied scene for GLB export is not needed anymore, therefore it can be removed
228
- scene.getEngine().dispose();
229
- }
230
- }
231
-
232
- /**
233
- * Remove all node metadata and return them in a map
234
- */
235
- protected extractMetadataOfAllNodes(): MetadataMap {
236
- return this.viewer.scene.getNodes().reduce((accMetadataObj, curNode) => {
237
- const metadata = curNode.metadata;
238
- delete curNode.metadata;
239
- return { ...accMetadataObj, [curNode.uniqueId.toString()]: metadata };
240
- }, {});
241
- }
242
-
243
- /**
244
- * Restore node metadata from previously cropped metadata map
245
- */
246
- protected restoreMetadataOfAllNodes(metadataMap: MetadataMap) {
247
- this.viewer.scene.getNodes().forEach(node => {
248
- const metadata = metadataMap[node.uniqueId.toString()];
249
- if (metadata) {
250
- node.metadata = metadata;
251
- }
252
- });
253
- }
254
-
255
- /**
256
- * Materials with refraction set are not exported properly.
257
- * Exchange all such (relevant) materials with a more export-friendly version
258
- */
259
- protected exchangeRefractionMaterials(scene: Scene) {
260
- for (const n of scene.getNodes()) {
261
- if (!(n instanceof AbstractMesh)) continue;
262
- if (!(n.material instanceof PBRMaterial)) continue;
263
- if (!(n.material as PBRMaterial).subSurface.isRefractionEnabled) continue;
264
- if ((n.material as PBRMaterial).transparencyMode !== PBRMaterial.PBRMATERIAL_OPAQUE) continue;
265
- // if we're here, we have a node holding a material with set refraction whose transparencyMode is set to
266
- // PBRMATERIAL_OPAQUE
267
- n.material = this.createRefractionMaterialReplacement(n.material);
268
- }
269
- }
270
-
271
- /**
272
- * Create an export-friendly replacement material for a material using refraction.
273
- * @param mat Material to be replaced
274
- */
275
- protected createRefractionMaterialReplacement(mat: PBRMaterial): PBRMaterial {
276
- // if we're dealing with a clone already, return it instead of cloning
277
- if (this.isMaterialClonedForExport(mat)) return mat;
278
-
279
- // change material according to https://www.notion.so/combeenation/Glas-materials-don-t-look-glasy-after-export-d5fda2c6515e4420a8772744d3e6b460
280
- const clonedMaterial = mat.clone(mat.name); // clone material. clone uses same name
281
- clonedMaterial.metadata = { ...mat.metadata, [GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY]: mat.uniqueId }; // create shallow copy of metadata on clone. see https://forum.babylonjs.com/t/the-metadata-of-the-mesh-cloned-by-the-instantiatemodelstoscene-method-is-a-shallow-copy/21563
282
- clonedMaterial.refractionTexture = null;
283
- clonedMaterial.metallicReflectanceTexture = null; // is this the correct one for metallic roughness?
284
- clonedMaterial.alpha = 0.7;
285
- clonedMaterial.albedoColor = new Color3(0.3, 0.3, 0.3);
286
- clonedMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
287
- clonedMaterial.metallic = 0.65;
288
- clonedMaterial.roughness = 0.15;
289
-
290
- return clonedMaterial;
291
- }
292
-
293
- /**
294
- * Inspect if a material was temporarily cloned for GLB export
295
- * @param mat Material to be inspected
296
- */
297
- protected isMaterialClonedForExport(mat: PBRMaterial): boolean {
298
- return has(mat.metadata, GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY);
299
- }
300
-
301
- /**
302
- * Set unique mesh names for GLB export.
303
- * Duplicate names lead to problems in AR on iOS devices.
304
- */
305
- protected setUniqueMeshNames(scene: Scene): void {
306
- const allNodes = scene.getNodes().filter(node => node instanceof TransformNode) as TransformNode[];
307
- allNodes.forEach(currMesh => {
308
- injectMetadata(currMesh, { [GltfExportManager.NAME_BEFORE_EXPORT_METADATA_PROPERTY]: currMesh.name }, false);
309
- currMesh.name = `${currMesh.name}_${currMesh.uniqueId}`;
310
- });
311
- }
312
- }
1
+ import { bakeGeometryOfAllMeshes } from '..//util/geometryHelper';
2
+ import { Viewer } from '../classes/viewer';
3
+ import { injectMetadata } from '../util/babylonHelper';
4
+ import { isNodeIncludedInExclusionList } from '../util/structureHelper';
5
+ import { Engine } from '@babylonjs/core/Engines/engine';
6
+ import { EngineStore } from '@babylonjs/core/Engines/engineStore';
7
+ import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
8
+ import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';
9
+ import { Color3 } from '@babylonjs/core/Maths/math.color';
10
+ import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';
11
+ import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
12
+ import { SceneSerializer } from '@babylonjs/core/Misc/sceneSerializer';
13
+ import { Scene } from '@babylonjs/core/scene';
14
+ import { GLTF2Export, IExportOptions } from '@babylonjs/serializers/glTF/2.0';
15
+ import { has, merge } from 'lodash-es';
16
+
17
+ type MetadataMap = { [key: string]: any };
18
+ export class GltfExportManager {
19
+ protected static readonly _CLONED_FROM_MAT_METADATA_PROPERTY = 'clonedFrom';
20
+ public static readonly NAME_BEFORE_EXPORT_METADATA_PROPERTY = 'nameBeforeExport';
21
+
22
+ /**
23
+ * Constructor.
24
+ */
25
+ protected constructor(protected viewer: Viewer) {}
26
+
27
+ /**
28
+ * Creates an {@link GltfExportManager}.
29
+ */
30
+ public static async create(viewer: Viewer): Promise<GltfExportManager> {
31
+ return new GltfExportManager(viewer);
32
+ }
33
+
34
+ /**
35
+ * Exports selected nodes to a file.
36
+ * @param filename optional name of the exported .GLB file.
37
+ * @param exportOptions export options to be merged with default options.\
38
+ * `exportOptions.exchangeRefractionMaterials` and `exportOptions.limitTextureSize`
39
+ * default to `true` if not given.
40
+ * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
41
+ * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
42
+ */
43
+ public async exportGlb(
44
+ filename = 'glb-export.glb',
45
+ { exchangeRefractionMaterials = true, limitTextureSize = true, ...exportOptions }: IExportOptionsExtended = {},
46
+ optimizeForAR: boolean = false,
47
+ excluded?: ExcludedGeometryList
48
+ ): Promise<File | undefined> {
49
+ const { scene, sceneCopied } = await this.exportPreProcess(
50
+ exchangeRefractionMaterials,
51
+ limitTextureSize,
52
+ optimizeForAR
53
+ );
54
+ const glbData = await GLTF2Export.GLBAsync(scene, 'dummy', this.gltfExportOptions(exportOptions, excluded));
55
+ this.exportPostProcess(scene, sceneCopied);
56
+
57
+ const resBlob = glbData.glTFFiles['dummy.glb'];
58
+ // check if result is valid, according to the typings this could also be a string
59
+ if (resBlob instanceof Blob) {
60
+ if (!filename.endsWith('.glb')) {
61
+ filename += '.glb';
62
+ }
63
+ return new File([resBlob], filename);
64
+ } else {
65
+ // result was not a valid blob
66
+ return undefined;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Exports selected nodes to GLTF. This may result in more than one file, since textures are exported separately.
72
+ * @param filename name of the main (text-based) .GLTF file referring to separate texture files.
73
+ * @param exportOptions export options to be merged with default options.\
74
+ * `exportOptions.exchangeRefractionMaterials` and `exportOptions.limitTextureSize`
75
+ * default to `true` if not given.
76
+ * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
77
+ * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
78
+ */
79
+ public async exportGltfToFile(
80
+ filename: string,
81
+ { exchangeRefractionMaterials = true, limitTextureSize = true, ...exportOptions }: IExportOptionsExtended = {},
82
+ optimizeForAR: boolean = false,
83
+ excluded?: ExcludedGeometryList
84
+ ) {
85
+ const { scene, sceneCopied } = await this.exportPreProcess(
86
+ exchangeRefractionMaterials,
87
+ limitTextureSize,
88
+ optimizeForAR
89
+ );
90
+ const gltf = await GLTF2Export.GLTFAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
91
+ gltf.downloadFiles();
92
+ this.exportPostProcess(scene, sceneCopied);
93
+ }
94
+
95
+ /**
96
+ * Exports selected nodes to GLB. This results in one binary file.
97
+ * @param filename name of the .GLB file.
98
+ * @param exportOptions export options to be merged with default options.\
99
+ * `exportOptions.exchangeRefractionMaterials` and `exportOptions.limitTextureSize`
100
+ * default to `true` if not given.
101
+ * @param optimizeForAR adjusts the exported GLB so that known AR issues get fixed automatically
102
+ * @param excluded optional list of geometry (meshes, elements, variants, variantInstances) to be excluded from export
103
+ */
104
+ public async exportGlbToFile(
105
+ filename: string,
106
+ { exchangeRefractionMaterials = true, limitTextureSize = true, ...exportOptions }: IExportOptionsExtended = {},
107
+ optimizeForAR: boolean = false,
108
+ excluded?: ExcludedGeometryList
109
+ ) {
110
+ const { scene, sceneCopied } = await this.exportPreProcess(
111
+ exchangeRefractionMaterials,
112
+ limitTextureSize,
113
+ optimizeForAR
114
+ );
115
+ const glb = await GLTF2Export.GLBAsync(scene, filename, this.gltfExportOptions(exportOptions, excluded));
116
+ glb.downloadFiles();
117
+ this.exportPostProcess(scene, sceneCopied);
118
+ }
119
+
120
+ /**
121
+ * Gets predefined {@link IExportOptions } merged with given ones.
122
+ */
123
+ protected gltfExportOptions(mergeWithOptions: IExportOptions = {}, excluded?: ExcludedGeometryList): IExportOptions {
124
+ const defaultOptions: IExportOptions = {
125
+ shouldExportNode: function (node: any) {
126
+ if (!node.isEnabled()) {
127
+ return false;
128
+ }
129
+ if ((node.name as string).startsWith(Viewer.BOUNDING_BOX_NAME)) {
130
+ return false;
131
+ }
132
+ if (excluded && node instanceof TransformNode && isNodeIncludedInExclusionList(node, excluded)) {
133
+ return false;
134
+ }
135
+ return true;
136
+ },
137
+ };
138
+ return merge({}, defaultOptions, mergeWithOptions);
139
+ }
140
+
141
+ /**
142
+ * Stuff to be done before exporting to GLTF
143
+ *
144
+ * @returns Either the original scene if no adjustments have been made or a copied scene (which can be disposed after
145
+ * the export) if adjustments have been made
146
+ */
147
+ protected async exportPreProcess(
148
+ exchangeRefractionMaterials: boolean,
149
+ limitTextureSize: boolean,
150
+ optimizeForAR: boolean
151
+ ): Promise<{ scene: Scene; sceneCopied: boolean }> {
152
+ if (!exchangeRefractionMaterials && !optimizeForAR && !limitTextureSize) {
153
+ // no need to copy the scene if no adjustments have to be made
154
+ return { scene: this.viewer.scene, sceneCopied: false };
155
+ }
156
+
157
+ // copy the scene for the GLB export improvements, so that the original viewer scene remains untouched
158
+ const copiedScene = await this.copyViewerScene(limitTextureSize);
159
+
160
+ if (exchangeRefractionMaterials) {
161
+ this.exchangeRefractionMaterials(copiedScene);
162
+ }
163
+
164
+ if (optimizeForAR) {
165
+ this.setUniqueMeshNames(copiedScene);
166
+ // get rid of negative scalings and morph targets, since iOS can't handle it in the QuickLook app
167
+ bakeGeometryOfAllMeshes(copiedScene);
168
+ // certain devices can't load models with skeletons, just remove them since animations are not supported in the AR
169
+ // scene anyway
170
+ while (copiedScene.skeletons.length) {
171
+ const skeleton = copiedScene.skeletons.pop();
172
+ skeleton!.dispose();
173
+ }
174
+ }
175
+
176
+ return { scene: copiedScene, sceneCopied: true };
177
+ }
178
+
179
+ /**
180
+ * Create a copy of the viewer scene, which can be further processed and optimized for the GLB export.
181
+ * There is no "scene.clone" function, therefore the scene is serialized and loaded again to achieve this result.
182
+ */
183
+ protected async copyViewerScene(limitTextureSize: boolean): Promise<Scene> {
184
+ // required by the scene serializer
185
+ await import(/* webpackChunkName: "physicsenginecomponent" */ '@babylonjs/core/Physics/physicsEngineComponent');
186
+
187
+ // copy scene function uses scene serializer, which can't handle "complex" data like classes, function or recursive
188
+ // data structures in metadata
189
+ // it basically does a `JSON.stringify` on the metadata
190
+ // therefore the metadata has to be removed from the nodes before the copy process
191
+ const metadataArr = this.extractMetadataOfAllNodes();
192
+
193
+ // serialize the scene
194
+ const serializedScene = await SceneSerializer.SerializeAsync(this.viewer.scene);
195
+
196
+ // set the cropped metadata back to the viewer scene nodes
197
+ this.restoreMetadataOfAllNodes(metadataArr);
198
+
199
+ // load the scene into an invisible "dummy" canvas
200
+ const dummyCanvas = document.createElement('canvas');
201
+ const engine = new Engine(dummyCanvas);
202
+
203
+ if (limitTextureSize) {
204
+ // according to some tests iOS devices break when exporting a scene with textures above 1024
205
+ // this only affects the scene clone for the export
206
+ engine.getCaps().maxTextureSize = 1024;
207
+ }
208
+
209
+ // overwritting _LastCreatedScene to fix issue: https://combeenation.youtrack.cloud/issue/CB-8972
210
+ // In short: dummy scene erroneously interacts with original viewer scene
211
+ // setting viewer scene as fallback again (`_LastCreatedScene`) resolves that issue
212
+ const curLastScene = EngineStore._LastCreatedScene;
213
+ const newScene = new Scene(engine);
214
+ EngineStore._LastCreatedScene = curLastScene;
215
+
216
+ SceneLoader.ShowLoadingScreen = false;
217
+ await SceneLoader.AppendAsync('', 'data:' + JSON.stringify(serializedScene), newScene, undefined, '.babylon');
218
+
219
+ return newScene;
220
+ }
221
+
222
+ /**
223
+ * Stuff to be done after the GLTF export
224
+ */
225
+ protected exportPostProcess(scene: Scene, disposeScene: boolean) {
226
+ if (disposeScene) {
227
+ // copied scene for GLB export is not needed anymore, therefore it can be removed
228
+ scene.getEngine().dispose();
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Remove all node metadata and return them in a map
234
+ */
235
+ protected extractMetadataOfAllNodes(): MetadataMap {
236
+ return this.viewer.scene.getNodes().reduce((accMetadataObj, curNode) => {
237
+ const metadata = curNode.metadata;
238
+ delete curNode.metadata;
239
+ return { ...accMetadataObj, [curNode.uniqueId.toString()]: metadata };
240
+ }, {});
241
+ }
242
+
243
+ /**
244
+ * Restore node metadata from previously cropped metadata map
245
+ */
246
+ protected restoreMetadataOfAllNodes(metadataMap: MetadataMap) {
247
+ this.viewer.scene.getNodes().forEach(node => {
248
+ const metadata = metadataMap[node.uniqueId.toString()];
249
+ if (metadata) {
250
+ node.metadata = metadata;
251
+ }
252
+ });
253
+ }
254
+
255
+ /**
256
+ * Materials with refraction set are not exported properly.
257
+ * Exchange all such (relevant) materials with a more export-friendly version
258
+ */
259
+ protected exchangeRefractionMaterials(scene: Scene) {
260
+ for (const n of scene.getNodes()) {
261
+ if (!(n instanceof AbstractMesh)) continue;
262
+ if (!(n.material instanceof PBRMaterial)) continue;
263
+ if (!(n.material as PBRMaterial).subSurface.isRefractionEnabled) continue;
264
+ if ((n.material as PBRMaterial).transparencyMode !== PBRMaterial.PBRMATERIAL_OPAQUE) continue;
265
+ // if we're here, we have a node holding a material with set refraction whose transparencyMode is set to
266
+ // PBRMATERIAL_OPAQUE
267
+ n.material = this.createRefractionMaterialReplacement(n.material);
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Create an export-friendly replacement material for a material using refraction.
273
+ * @param mat Material to be replaced
274
+ */
275
+ protected createRefractionMaterialReplacement(mat: PBRMaterial): PBRMaterial {
276
+ // if we're dealing with a clone already, return it instead of cloning
277
+ if (this.isMaterialClonedForExport(mat)) return mat;
278
+
279
+ // change material according to https://www.notion.so/combeenation/Glas-materials-don-t-look-glasy-after-export-d5fda2c6515e4420a8772744d3e6b460
280
+ const clonedMaterial = mat.clone(mat.name); // clone material. clone uses same name
281
+ clonedMaterial.metadata = { ...mat.metadata, [GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY]: mat.uniqueId }; // create shallow copy of metadata on clone. see https://forum.babylonjs.com/t/the-metadata-of-the-mesh-cloned-by-the-instantiatemodelstoscene-method-is-a-shallow-copy/21563
282
+ clonedMaterial.refractionTexture = null;
283
+ clonedMaterial.metallicReflectanceTexture = null; // is this the correct one for metallic roughness?
284
+ clonedMaterial.alpha = 0.7;
285
+ clonedMaterial.albedoColor = new Color3(0.3, 0.3, 0.3);
286
+ clonedMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
287
+ clonedMaterial.metallic = 0.65;
288
+ clonedMaterial.roughness = 0.15;
289
+
290
+ return clonedMaterial;
291
+ }
292
+
293
+ /**
294
+ * Inspect if a material was temporarily cloned for GLB export
295
+ * @param mat Material to be inspected
296
+ */
297
+ protected isMaterialClonedForExport(mat: PBRMaterial): boolean {
298
+ return has(mat.metadata, GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY);
299
+ }
300
+
301
+ /**
302
+ * Set unique mesh names for GLB export.
303
+ * Duplicate names lead to problems in AR on iOS devices.
304
+ */
305
+ protected setUniqueMeshNames(scene: Scene): void {
306
+ const allNodes = scene.getNodes().filter(node => node instanceof TransformNode) as TransformNode[];
307
+ allNodes.forEach(currMesh => {
308
+ injectMetadata(currMesh, { [GltfExportManager.NAME_BEFORE_EXPORT_METADATA_PROPERTY]: currMesh.name }, false);
309
+ currMesh.name = `${currMesh.name}_${currMesh.uniqueId}`;
310
+ });
311
+ }
312
+ }