@combeenation/3d-viewer 9.2.1-alpha1 → 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 (113) 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 -870
  25. package/dist/lib-cjs/api/classes/variant.js.map +1 -1
  26. package/dist/lib-cjs/api/classes/variantInstance.d.ts +53 -53
  27. package/dist/lib-cjs/api/classes/variantInstance.js +125 -125
  28. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  29. package/dist/lib-cjs/api/classes/variantParameterizable.js +86 -86
  30. package/dist/lib-cjs/api/classes/viewer.d.ts +211 -213
  31. package/dist/lib-cjs/api/classes/viewer.js +736 -717
  32. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  33. package/dist/lib-cjs/api/classes/viewerError.d.ts +43 -43
  34. package/dist/lib-cjs/api/classes/viewerError.js +55 -55
  35. package/dist/lib-cjs/api/classes/viewerLight.d.ts +66 -66
  36. package/dist/lib-cjs/api/classes/viewerLight.js +344 -348
  37. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  38. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  39. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  40. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +13 -13
  41. package/dist/lib-cjs/api/internal/sceneSetup.js +224 -226
  42. package/dist/lib-cjs/api/internal/sceneSetup.js.map +1 -1
  43. package/dist/lib-cjs/api/manager/animationManager.d.ts +30 -30
  44. package/dist/lib-cjs/api/manager/animationManager.js +126 -126
  45. package/dist/lib-cjs/api/manager/gltfExportManager.d.ts +102 -102
  46. package/dist/lib-cjs/api/manager/gltfExportManager.js +322 -316
  47. package/dist/lib-cjs/api/manager/gltfExportManager.js.map +1 -1
  48. package/dist/lib-cjs/api/manager/sceneManager.d.ts +33 -33
  49. package/dist/lib-cjs/api/manager/sceneManager.js +128 -128
  50. package/dist/lib-cjs/api/manager/tagManager.d.ts +118 -118
  51. package/dist/lib-cjs/api/manager/tagManager.js +535 -535
  52. package/dist/lib-cjs/api/manager/textureLoadManager.d.ts +22 -22
  53. package/dist/lib-cjs/api/manager/textureLoadManager.js +98 -98
  54. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +106 -106
  55. package/dist/lib-cjs/api/manager/variantInstanceManager.js +290 -290
  56. package/dist/lib-cjs/api/store/specStorage.d.ts +32 -32
  57. package/dist/lib-cjs/api/store/specStorage.js +65 -65
  58. package/dist/lib-cjs/api/util/babylonHelper.d.ts +238 -238
  59. package/dist/lib-cjs/api/util/babylonHelper.js +826 -826
  60. package/dist/lib-cjs/api/util/geometryHelper.d.ts +7 -7
  61. package/dist/lib-cjs/api/util/geometryHelper.js +115 -115
  62. package/dist/lib-cjs/api/util/globalTypes.d.ts +484 -484
  63. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  64. package/dist/lib-cjs/api/util/resourceHelper.d.ts +58 -58
  65. package/dist/lib-cjs/api/util/resourceHelper.js +214 -214
  66. package/dist/lib-cjs/api/util/sceneLoaderHelper.d.ts +44 -44
  67. package/dist/lib-cjs/api/util/sceneLoaderHelper.js +175 -175
  68. package/dist/lib-cjs/api/util/stringHelper.d.ts +13 -13
  69. package/dist/lib-cjs/api/util/stringHelper.js +32 -32
  70. package/dist/lib-cjs/api/util/structureHelper.d.ts +9 -9
  71. package/dist/lib-cjs/api/util/structureHelper.js +64 -64
  72. package/dist/lib-cjs/buildinfo.json +3 -3
  73. package/dist/lib-cjs/commonjs.tsconfig.tsbuildinfo +1 -1
  74. package/dist/lib-cjs/index.d.ts +54 -54
  75. package/dist/lib-cjs/index.js +117 -117
  76. package/package.json +84 -82
  77. package/src/api/classes/animationInterface.ts +10 -10
  78. package/src/api/classes/dottedPath.ts +181 -181
  79. package/src/api/classes/element.ts +723 -723
  80. package/src/api/classes/event.ts +457 -457
  81. package/src/api/classes/eventBroadcaster.ts +52 -52
  82. package/src/api/classes/fuzzyMap.ts +21 -21
  83. package/src/api/classes/parameter.ts +686 -686
  84. package/src/api/classes/parameterObservable.ts +73 -73
  85. package/src/api/classes/parameterizable.ts +87 -87
  86. package/src/api/classes/placementAnimation.ts +162 -162
  87. package/src/api/classes/variant.ts +964 -963
  88. package/src/api/classes/variantInstance.ts +123 -123
  89. package/src/api/classes/variantParameterizable.ts +83 -83
  90. package/src/api/classes/viewer.ts +786 -770
  91. package/src/api/classes/viewerError.ts +63 -63
  92. package/src/api/classes/viewerLight.ts +335 -339
  93. package/src/api/internal/debugViewer.ts +90 -90
  94. package/src/api/internal/lensRendering.ts +9 -9
  95. package/src/api/internal/sceneSetup.ts +203 -205
  96. package/src/api/manager/animationManager.ts +143 -143
  97. package/src/api/manager/gltfExportManager.ts +312 -306
  98. package/src/api/manager/sceneManager.ts +134 -134
  99. package/src/api/manager/tagManager.ts +576 -576
  100. package/src/api/manager/textureLoadManager.ts +96 -96
  101. package/src/api/manager/variantInstanceManager.ts +306 -306
  102. package/src/api/store/specStorage.ts +68 -68
  103. package/src/api/util/babylonHelper.ts +915 -915
  104. package/src/api/util/geometryHelper.ts +140 -140
  105. package/src/api/util/globalTypes.ts +560 -560
  106. package/src/api/util/resourceHelper.ts +201 -201
  107. package/src/api/util/sceneLoaderHelper.ts +170 -170
  108. package/src/api/util/stringHelper.ts +30 -30
  109. package/src/api/util/structureHelper.ts +63 -63
  110. package/src/buildinfo.json +3 -3
  111. package/src/dev.ts +70 -62
  112. package/src/index.ts +103 -103
  113. package/src/types.d.ts +49 -38
@@ -1,306 +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
- }
169
-
170
- return { scene: copiedScene, sceneCopied: true };
171
- }
172
-
173
- /**
174
- * Create a copy of the viewer scene, which can be further processed and optimized for the GLB export.
175
- * There is no "scene.clone" function, therefore the scene is serialized and loaded again to achieve this result.
176
- */
177
- protected async copyViewerScene(limitTextureSize: boolean): Promise<Scene> {
178
- // required by the scene serializer
179
- await import(/* webpackChunkName: "physicsenginecomponent" */ '@babylonjs/core/Physics/physicsEngineComponent');
180
-
181
- // copy scene function uses scene serializer, which can't handle "complex" data like classes, function or recursive
182
- // data structures in metadata
183
- // it basically does a `JSON.stringify` on the metadata
184
- // therefore the metadata has to be removed from the nodes before the copy process
185
- const metadataArr = this.extractMetadataOfAllNodes();
186
-
187
- // serialize the scene
188
- const serializedScene = await SceneSerializer.SerializeAsync(this.viewer.scene);
189
-
190
- // set the cropped metadata back to the viewer scene nodes
191
- this.restoreMetadataOfAllNodes(metadataArr);
192
-
193
- // load the scene into an invisible "dummy" canvas
194
- const dummyCanvas = document.createElement('canvas');
195
- const engine = new Engine(dummyCanvas);
196
-
197
- if (limitTextureSize) {
198
- // according to some tests iOS devices break when exporting a scene with textures above 1024
199
- // this only affects the scene clone for the export
200
- engine.getCaps().maxTextureSize = 1024;
201
- }
202
-
203
- // overwritting _LastCreatedScene to fix issue: https://combeenation.youtrack.cloud/issue/CB-8972
204
- // In short: dummy scene erroneously interacts with original viewer scene
205
- // setting viewer scene as fallback again (`_LastCreatedScene`) resolves that issue
206
- const curLastScene = EngineStore._LastCreatedScene;
207
- const newScene = new Scene(engine);
208
- EngineStore._LastCreatedScene = curLastScene;
209
-
210
- SceneLoader.ShowLoadingScreen = false;
211
- await SceneLoader.AppendAsync('', 'data:' + JSON.stringify(serializedScene), newScene, undefined, '.babylon');
212
-
213
- return newScene;
214
- }
215
-
216
- /**
217
- * Stuff to be done after the GLTF export
218
- */
219
- protected exportPostProcess(scene: Scene, disposeScene: boolean) {
220
- if (disposeScene) {
221
- // copied scene for GLB export is not needed anymore, therefore it can be removed
222
- scene.getEngine().dispose();
223
- }
224
- }
225
-
226
- /**
227
- * Remove all node metadata and return them in a map
228
- */
229
- protected extractMetadataOfAllNodes(): MetadataMap {
230
- return this.viewer.scene.getNodes().reduce((accMetadataObj, curNode) => {
231
- const metadata = curNode.metadata;
232
- delete curNode.metadata;
233
- return { ...accMetadataObj, [curNode.uniqueId.toString()]: metadata };
234
- }, {});
235
- }
236
-
237
- /**
238
- * Restore node metadata from previously cropped metadata map
239
- */
240
- protected restoreMetadataOfAllNodes(metadataMap: MetadataMap) {
241
- this.viewer.scene.getNodes().forEach(node => {
242
- const metadata = metadataMap[node.uniqueId.toString()];
243
- if (metadata) {
244
- node.metadata = metadata;
245
- }
246
- });
247
- }
248
-
249
- /**
250
- * Materials with refraction set are not exported properly.
251
- * Exchange all such (relevant) materials with a more export-friendly version
252
- */
253
- protected exchangeRefractionMaterials(scene: Scene) {
254
- for (const n of scene.getNodes()) {
255
- if (!(n instanceof AbstractMesh)) continue;
256
- if (!(n.material instanceof PBRMaterial)) continue;
257
- if (!(n.material as PBRMaterial).subSurface.isRefractionEnabled) continue;
258
- if ((n.material as PBRMaterial).transparencyMode !== PBRMaterial.PBRMATERIAL_OPAQUE) continue;
259
- // if we're here, we have a node holding a material with set refraction whose transparencyMode is set to
260
- // PBRMATERIAL_OPAQUE
261
- n.material = this.createRefractionMaterialReplacement(n.material);
262
- }
263
- }
264
-
265
- /**
266
- * Create an export-friendly replacement material for a material using refraction.
267
- * @param mat Material to be replaced
268
- */
269
- protected createRefractionMaterialReplacement(mat: PBRMaterial): PBRMaterial {
270
- // if we're dealing with a clone already, return it instead of cloning
271
- if (this.isMaterialClonedForExport(mat)) return mat;
272
-
273
- // change material according to https://www.notion.so/combeenation/Glas-materials-don-t-look-glasy-after-export-d5fda2c6515e4420a8772744d3e6b460
274
- const clonedMaterial = mat.clone(mat.name); // clone material. clone uses same name
275
- 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
276
- clonedMaterial.refractionTexture = null;
277
- clonedMaterial.metallicReflectanceTexture = null; // is this the correct one for metallic roughness?
278
- clonedMaterial.alpha = 0.7;
279
- clonedMaterial.albedoColor = new Color3(0.3, 0.3, 0.3);
280
- clonedMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
281
- clonedMaterial.metallic = 0.65;
282
- clonedMaterial.roughness = 0.15;
283
-
284
- return clonedMaterial;
285
- }
286
-
287
- /**
288
- * Inspect if a material was temporarily cloned for GLB export
289
- * @param mat Material to be inspected
290
- */
291
- protected isMaterialClonedForExport(mat: PBRMaterial): boolean {
292
- return has(mat.metadata, GltfExportManager._CLONED_FROM_MAT_METADATA_PROPERTY);
293
- }
294
-
295
- /**
296
- * Set unique mesh names for GLB export.
297
- * Duplicate names lead to problems in AR on iOS devices.
298
- */
299
- protected setUniqueMeshNames(scene: Scene): void {
300
- const allNodes = scene.getNodes().filter(node => node instanceof TransformNode) as TransformNode[];
301
- allNodes.forEach(currMesh => {
302
- injectMetadata(currMesh, { [GltfExportManager.NAME_BEFORE_EXPORT_METADATA_PROPERTY]: currMesh.name }, false);
303
- currMesh.name = `${currMesh.name}_${currMesh.uniqueId}`;
304
- });
305
- }
306
- }
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
+ }