@combeenation/3d-viewer 4.0.0-beta4 → 4.0.1-alpha1

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 (106) hide show
  1. package/README.md +114 -112
  2. package/dist/lib-cjs/api/classes/animationInterface.d.ts +8 -8
  3. package/dist/lib-cjs/api/classes/animationInterface.js +1 -1
  4. package/dist/lib-cjs/api/classes/dottedPath.d.ts +79 -79
  5. package/dist/lib-cjs/api/classes/dottedPath.js +190 -190
  6. package/dist/lib-cjs/api/classes/element.d.ts +130 -125
  7. package/dist/lib-cjs/api/classes/element.js +743 -682
  8. package/dist/lib-cjs/api/classes/element.js.map +1 -1
  9. package/dist/lib-cjs/api/classes/elementParameterizable.d.ts +14 -14
  10. package/dist/lib-cjs/api/classes/elementParameterizable.js +134 -134
  11. package/dist/lib-cjs/api/classes/event.d.ts +326 -312
  12. package/dist/lib-cjs/api/classes/event.js +371 -357
  13. package/dist/lib-cjs/api/classes/event.js.map +1 -1
  14. package/dist/lib-cjs/api/classes/eventBroadcaster.d.ts +26 -26
  15. package/dist/lib-cjs/api/classes/eventBroadcaster.js +53 -53
  16. package/dist/lib-cjs/api/classes/parameter.d.ts +259 -165
  17. package/dist/lib-cjs/api/classes/parameter.js +387 -267
  18. package/dist/lib-cjs/api/classes/parameter.js.map +1 -1
  19. package/dist/lib-cjs/api/classes/parameterObservable.d.ts +36 -36
  20. package/dist/lib-cjs/api/classes/parameterObservable.js +101 -126
  21. package/dist/lib-cjs/api/classes/parameterObservable.js.map +1 -1
  22. package/dist/lib-cjs/api/classes/parameterizable.d.ts +15 -15
  23. package/dist/lib-cjs/api/classes/parameterizable.js +149 -149
  24. package/dist/lib-cjs/api/classes/placementAnimation.d.ts +43 -38
  25. package/dist/lib-cjs/api/classes/placementAnimation.js +160 -138
  26. package/dist/lib-cjs/api/classes/placementAnimation.js.map +1 -1
  27. package/dist/lib-cjs/api/classes/variant.d.ts +234 -190
  28. package/dist/lib-cjs/api/classes/variant.js +1147 -873
  29. package/dist/lib-cjs/api/classes/variant.js.map +1 -1
  30. package/dist/lib-cjs/api/classes/variantInstance.d.ts +45 -41
  31. package/dist/lib-cjs/api/classes/variantInstance.js +108 -98
  32. package/dist/lib-cjs/api/classes/variantInstance.js.map +1 -1
  33. package/dist/lib-cjs/api/classes/variantParameterizable.d.ts +17 -17
  34. package/dist/lib-cjs/api/classes/variantParameterizable.js +92 -92
  35. package/dist/lib-cjs/api/classes/viewer.d.ts +131 -128
  36. package/dist/lib-cjs/api/classes/viewer.js +567 -486
  37. package/dist/lib-cjs/api/classes/viewer.js.map +1 -1
  38. package/dist/lib-cjs/api/classes/viewerLight.d.ts +66 -65
  39. package/dist/lib-cjs/api/classes/viewerLight.js +389 -322
  40. package/dist/lib-cjs/api/classes/viewerLight.js.map +1 -1
  41. package/dist/lib-cjs/api/internal/debugViewer.d.ts +13 -13
  42. package/dist/lib-cjs/api/internal/debugViewer.js +87 -87
  43. package/dist/lib-cjs/api/internal/lensRendering.d.ts +8 -8
  44. package/dist/lib-cjs/api/internal/lensRendering.js +11 -11
  45. package/dist/lib-cjs/api/internal/sceneSetup.d.ts +10 -6
  46. package/dist/lib-cjs/api/internal/sceneSetup.js +231 -227
  47. package/dist/lib-cjs/api/internal/sceneSetup.js.map +1 -1
  48. package/dist/lib-cjs/api/manager/animationManager.d.ts +29 -29
  49. package/dist/lib-cjs/api/manager/animationManager.js +121 -121
  50. package/dist/lib-cjs/api/manager/sceneManager.d.ts +32 -32
  51. package/dist/lib-cjs/api/manager/sceneManager.js +132 -132
  52. package/dist/lib-cjs/api/manager/variantInstanceManager.d.ts +90 -90
  53. package/dist/lib-cjs/api/manager/variantInstanceManager.js +321 -321
  54. package/dist/lib-cjs/api/store/specStorage.d.ts +24 -24
  55. package/dist/lib-cjs/api/store/specStorage.js +51 -51
  56. package/dist/lib-cjs/api/util/babylonHelper.d.ts +175 -125
  57. package/dist/lib-cjs/api/util/babylonHelper.js +520 -368
  58. package/dist/lib-cjs/api/util/babylonHelper.js.map +1 -1
  59. package/dist/lib-cjs/api/util/globalTypes.d.ts +333 -279
  60. package/dist/lib-cjs/api/util/globalTypes.js +1 -1
  61. package/dist/lib-cjs/api/util/resourceHelper.d.ts +53 -51
  62. package/dist/lib-cjs/api/util/resourceHelper.js +240 -243
  63. package/dist/lib-cjs/api/util/resourceHelper.js.map +1 -1
  64. package/dist/lib-cjs/api/util/stringHelper.d.ts +9 -9
  65. package/dist/lib-cjs/api/util/stringHelper.js +25 -25
  66. package/dist/lib-cjs/buildinfo.json +3 -3
  67. package/dist/lib-cjs/index.d.ts +48 -46
  68. package/dist/lib-cjs/index.js +86 -82
  69. package/dist/lib-cjs/index.js.map +1 -1
  70. package/package.json +83 -83
  71. package/src/api/classes/animationInterface.ts +11 -11
  72. package/src/api/classes/dottedPath.ts +189 -189
  73. package/src/api/classes/element.ts +644 -617
  74. package/src/api/classes/event.ts +370 -355
  75. package/src/api/classes/eventBroadcaster.ts +54 -54
  76. package/src/api/classes/parameter.ts +408 -277
  77. package/src/api/classes/parameterObservable.ts +99 -121
  78. package/src/api/classes/{elementParameterizable.ts → parameterizable.ts} +89 -78
  79. package/src/api/classes/placementAnimation.ts +157 -133
  80. package/src/api/classes/variant.ts +817 -670
  81. package/src/api/classes/variantInstance.ts +88 -81
  82. package/src/api/classes/variantParameterizable.ts +73 -0
  83. package/src/api/classes/viewer.ts +487 -421
  84. package/src/api/classes/viewerLight.ts +330 -0
  85. package/src/api/internal/debugViewer.ts +81 -81
  86. package/src/api/internal/lensRendering.ts +10 -10
  87. package/src/api/internal/sceneSetup.ts +194 -204
  88. package/src/api/manager/animationManager.ts +116 -116
  89. package/src/api/manager/sceneManager.ts +105 -105
  90. package/src/api/manager/variantInstanceManager.ts +236 -236
  91. package/src/api/store/specStorage.ts +53 -53
  92. package/src/api/util/babylonHelper.ts +555 -392
  93. package/src/api/util/globalTypes.ts +380 -319
  94. package/src/api/util/resourceHelper.ts +184 -187
  95. package/src/api/util/stringHelper.ts +26 -0
  96. package/src/buildinfo.json +2 -2
  97. package/src/commonjs.tsconfig.json +13 -13
  98. package/src/declaration.tsconfig.json +10 -10
  99. package/src/dev.ts +42 -46
  100. package/src/es6.tsconfig.json +13 -13
  101. package/src/index.ts +91 -87
  102. package/src/pagesconfig.json +61 -57
  103. package/src/tsconfig.json +43 -43
  104. package/src/tsconfig.types.json +9 -9
  105. package/src/types.d.ts +4 -4
  106. package/dist/webpack-stats.json +0 -0
@@ -1,422 +1,488 @@
1
- import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera';
2
- import { PickingInfo } from '@babylonjs/core/Collisions/pickingInfo';
3
- import { BoundingInfo } from '@babylonjs/core/Culling/boundingInfo';
4
- import { Engine } from '@babylonjs/core/Engines/engine';
5
- import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
6
- import { Vector3 } from '@babylonjs/core/Maths/math.vector';
7
- import { Mesh } from '@babylonjs/core/Meshes/mesh';
8
- import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
9
- import { ScreenshotTools } from '@babylonjs/core/Misc/screenshotTools';
10
- import { Scene } from '@babylonjs/core/scene';
11
- import { isString } from 'lodash-es';
12
- import { version } from '../../buildinfo.json';
13
- import { sceneSetup } from '../internal/sceneSetup';
14
- import { AnimationManager } from '../manager/animationManager';
15
- import { SceneManager } from '../manager/sceneManager';
16
- import { VariantInstanceManager } from '../manager/variantInstanceManager';
17
- import { SpecStorage } from '../store/specStorage';
18
- import { debounce, loadJson } from '../util/resourceHelper';
19
- import { Event } from './event';
20
- import { EventBroadcaster } from './eventBroadcaster';
21
- import { Parameter } from './parameter';
22
- import { Variant } from './variant';
23
- import { VariantInstance } from './variantInstance';
24
-
25
-
26
- /**
27
- * The main exposed object. This is the entry point into the application
28
- *
29
- * ```js
30
- * const canvas = document.getElementById( 'babylon-canvas' );
31
- * const viewer = Viewer( canvas, '/path/to/index.json' );
32
- * ```
33
- * The class does nothing on its own and needs to {@link bootstrap}
34
- */
35
- export class Viewer extends EventBroadcaster {
36
-
37
- protected _scene: Scene | null = null;
38
-
39
- protected _animationManager: AnimationManager | null = null;
40
-
41
- protected _sceneManager: SceneManager | null = null;
42
-
43
- protected _variantInstances: VariantInstanceManager | null = null;
44
-
45
- static version = version;
46
-
47
- /**
48
- * Constructor
49
- */
50
- public constructor( public readonly canvas: HTMLCanvasElement, protected structureJson: string | StructureJson ) {
51
- super();
52
- }
53
-
54
- /**
55
- * Gets the BabylonJS Scene that is attached to the instance.
56
- *
57
- * @throws Error if the `scene` has not been initialized.
58
- */
59
- get scene(): Scene {
60
- if( !this._scene ) {
61
- throw new Error( `Scene has not been initialized.` );
62
- }
63
- return this._scene;
64
- }
65
-
66
- get sceneManager(): SceneManager {
67
- if( !this._sceneManager ) {
68
- throw new Error( `Environment has not been initialized.` );
69
- }
70
- return this._sceneManager;
71
- }
72
-
73
- /**
74
- * Gets the BabylonJS Engine that is attached to the viewer.
75
- */
76
- get engine(): Engine {
77
- return this.scene.getEngine();
78
- }
79
-
80
- /**
81
- * Gets the {@link VariantInstanceManager} attached to the viewer.
82
- *
83
- * @throws Error if the {@link VariantInstanceManager} has not been initialized.
84
- */
85
- get variantInstances(): VariantInstanceManager {
86
- if( !this._variantInstances ) {
87
- throw Error( `There is no variantInstanceManager.` );
88
- }
89
- return this._variantInstances;
90
- }
91
-
92
- /**
93
- * Gets the {@link AnimationManager} attached to the viewer.
94
- *
95
- * @throws Error if the {@link AnimationManager} has not been initialized.
96
- */
97
- get animationManager(): AnimationManager {
98
- if( !this._animationManager ) {
99
- throw new Error( `There is no animationManager instance.` );
100
- }
101
- return this._animationManager;
102
- }
103
-
104
- /**
105
- * Starts the application. This will
106
- * * load the given "index" JSON file
107
- * * setup the scene with the "scene" JSON file
108
- * * create an (optional) default setup with different variant settings
109
- * * sets up resizing by attaching a debounced version of {@link resize}
110
- *
111
- * @throws Error if any of the files is not found/valid
112
- *
113
- * @emits {@link Event.BOOTSTRAP_START}
114
- * @emits {@link Event.BOOTSTRAP_END}
115
- */
116
- public async bootstrap(): Promise<Viewer> {
117
- this.broadcastEvent( Event.BOOTSTRAP_START, this );
118
- let indexJson;
119
- if( isString( this.structureJson ) ) {
120
- indexJson = await loadJson<StructureJson>( this.structureJson );
121
- } else {
122
- indexJson = this.structureJson;
123
- }
124
- if( !indexJson.scene ) {
125
- throw new Error( `No "scene" property found for bootstrapping.` );
126
- }
127
- // fill spec store
128
- SpecStorage.createFromSpec( indexJson );
129
- // load scene
130
- if( isString( indexJson.scene ) ) {
131
- const sceneJson = await loadJson<SceneJson>( indexJson.scene );
132
- indexJson.scene = sceneJson;
133
- }
134
- this._scene = await this.initScene();
135
- // create instance manager
136
- const rootVariant = await Variant.create( '_', indexJson, this );
137
- this._variantInstances = await VariantInstanceManager.create( rootVariant );
138
- // create optional default instances
139
- if( indexJson.setup ) {
140
- if( isString( indexJson.setup ) ) {
141
- const setupJson = await loadJson<SetupJson>( indexJson.setup );
142
- indexJson.setup = setupJson;
143
- }
144
- await this.createVariantInstances();
145
- }
146
- // resize handler
147
- window.addEventListener( 'resize', debounce( this.resize.bind( this ), 100 ) );
148
- // event broadcasting
149
- this.broadcastEvent( Event.BOOTSTRAP_END, this );
150
- return this;
151
- }
152
-
153
- // Disabled for now to decrease bundle size.
154
- // See https://github.com/Combeenation/3d-viewer/issues/37
155
- // /**
156
- // * Enables the BabylonJS DebugLayer. If you pass options, be sure to pass an Object of type `IInspectorOptions`.
157
- // */
158
- // public async enableDebugLayer(options?: any) {
159
- // // @ts-ignore
160
- // await import(/* webpackChunkName: "debug-inspector" */'@babylonjs/inspector');
161
- // await this.scene.debugLayer.show(options);
162
- // return this;
163
- // }
164
-
165
- /**
166
- * Destroys all registered {@link VariantInstance}s that are registered
167
- */
168
- public destroyVariantInstances(): Viewer {
169
- this.variantInstances.all.forEach( variantInstance => {
170
- this.variantInstances.destroy( variantInstance.name );
171
- } );
172
- return this;
173
- }
174
-
175
- /**
176
- * Trigger a resize event for the `Engine`
177
- */
178
- public resize(): Viewer {
179
- this.engine.resize();
180
- return this;
181
- }
182
-
183
- /**
184
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
185
- * {@link DottedPath}s.
186
- */
187
- public async getNode( variantInstanceName: string,
188
- elementDottedPath: DottedPathArgument,
189
- nodeDottedPath: DottedPathArgument ): Promise<TransformNode> {
190
- const variantInstance = await this.variantInstances.get(variantInstanceName);
191
- return variantInstance.getNode( elementDottedPath, nodeDottedPath );
192
- }
193
-
194
- /**
195
- * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
196
- * {@link DottedPath}s.
197
- */
198
- public async getMesh( variantInstanceName: string,
199
- elementDottedPath: DottedPathArgument,
200
- meshDottedPath: DottedPathArgument ): Promise<Mesh|null> {
201
- const variantInstance = await this.variantInstances.get(variantInstanceName);
202
- return variantInstance.getMesh( elementDottedPath, meshDottedPath );
203
- }
204
-
205
- /**
206
- * Switches the camera
207
- *
208
- * @emits {@link Event.CAMERA_SWITCHED}
209
- */
210
- public switchCamera( newCamera: string, reset: boolean = true ): Viewer {
211
- const camera = this.scene.getCameraByName( newCamera );
212
- if( camera ) {
213
- const activeCamera = this.scene.activeCamera;
214
- if( activeCamera ) {
215
- activeCamera.detachControl( this.engine.getRenderingCanvas()! );
216
- }
217
- if( reset ) {
218
- camera.restoreState();
219
- }
220
- this.scene.setActiveCameraByName( newCamera );
221
- camera.attachControl( this.engine.getRenderingCanvas()! );
222
- this.broadcastEvent( Event.CAMERA_SWITCHED, camera );
223
- } else {
224
- throw new Error( `Given camera "${newCamera}" not found.` );
225
- }
226
- // TODO: put traceable observers to new camera (@see element)
227
- return this;
228
- }
229
-
230
- /**
231
- * Moves or animates the active camera to given `placement`.
232
- */
233
- public async moveActiveCameraTo( placement: string | PlacementDefinition,
234
- animation?: string | AnimationDefinition ): Promise<AnimationInterface> {
235
- return this.animationManager.animateToPlacement( this.sceneManager.activeCamera, placement, animation );
236
- }
237
-
238
- /**
239
- * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
240
- */
241
- public screenshot( settings?: ScreenshotSettings ): Promise<string> {
242
- return new Promise( ( resolve, reject ) => {
243
- if( !this.engine ) {
244
- return reject( 'Engine is null' );
245
- }
246
- if( !this.scene ) {
247
- return reject( 'Scene is null' );
248
- }
249
- this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
250
- ScreenshotTools.CreateScreenshotUsingRenderTarget(
251
- this.engine,
252
- this.sceneManager.activeCamera,
253
- settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
254
- resolve,
255
- settings?.mimeType ?? 'image/png',
256
- settings?.samples ?? 1,
257
- settings?.antialiasing ?? false,
258
- settings?.fileName ?? 'screenshot.png',
259
- settings?.renderSprites ?? false
260
- );
261
- } );
262
- }
263
-
264
- /**
265
- * Calculates the bounding box from all visible meshes on the scene.
266
- */
267
- public calculateBoundingBox(): Mesh {
268
- if( this.scene.meshes.length === 0 ) {
269
- throw new Error( 'There are currently no meshes on the scene.' );
270
- }
271
- let max = new Vector3( 0, 0, 0 );
272
- let min = new Vector3( 0, 0, 0 );
273
- this.scene.meshes.filter( mesh => mesh.isVisible ).forEach( mesh => {
274
- max = Vector3.Maximize( max, mesh.getBoundingInfo().boundingBox.maximumWorld );
275
- min = Vector3.Minimize( min, mesh.getBoundingInfo().boundingBox.minimumWorld );
276
- } );
277
- let boundingBox = this.scene.getMeshByName( '__bounding_box__' ) as Mesh;
278
- if( !boundingBox ) {
279
- boundingBox = new Mesh( '__bounding_box__', this.scene );
280
- }
281
- boundingBox.setBoundingInfo( new BoundingInfo( min, max ) );
282
- //boundingBox.showBoundingBox = true;
283
- return boundingBox;
284
- }
285
-
286
- /**
287
- * Focuses the camera to see every visible mesh in scene and tries to optimize wheel precision and panning.
288
- */
289
- public autofocusActiveCamera( settings?: AutofocusSettings ) {
290
- const activeCamera = this.scene.activeCamera;
291
- if( !activeCamera ) {
292
- throw new Error( 'No active camera found when using autofocus feature.' );
293
- }
294
- if( activeCamera instanceof ArcRotateCamera ) {
295
- // calculate some values
296
- const boundingBox = this.calculateBoundingBox();
297
- const size = boundingBox.getBoundingInfo().maximum.subtract( boundingBox.getBoundingInfo().minimum );
298
- let radius = size.length() * (settings?.radiusFactor ?? 1.5);
299
- if( !isFinite( radius ) ) {
300
- radius = 1;
301
- }
302
- // use helper camera to get some default values
303
- const helperCamera = new ArcRotateCamera(
304
- '__helper_camera__',
305
- Math.PI / -2,
306
- Math.PI / 2,
307
- radius,
308
- Vector3.Zero(),
309
- this.scene
310
- );
311
- helperCamera.useFramingBehavior = true;
312
- helperCamera.setTarget( boundingBox );
313
- // translate values from helper to active camera
314
- activeCamera.setTarget( Mesh.Center( [boundingBox] ) );
315
- activeCamera.alpha = helperCamera.alpha;
316
- activeCamera.beta = helperCamera.beta;
317
- activeCamera.minZ = helperCamera.minZ;
318
- activeCamera.maxZ = helperCamera.maxZ;
319
- activeCamera.radius = helperCamera.radius;
320
- activeCamera.lowerRadiusLimit = helperCamera.lowerRadiusLimit;
321
- activeCamera.upperRadiusLimit = helperCamera.upperRadiusLimit;
322
- if( settings?.adjustWheelPrecision !== false ) {
323
- activeCamera.wheelPrecision = helperCamera.wheelPrecision;
324
- }
325
- if( settings?.adjustPanningSensibility !== false ) {
326
- activeCamera.panningSensibility = helperCamera.panningSensibility;
327
- }
328
- if( settings?.adjustPinchPrecision !== false ) {
329
- activeCamera.pinchPrecision = helperCamera.pinchPrecision;
330
- }
331
- // remove the helper camera
332
- helperCamera.dispose();
333
- } else {
334
- const cameraClsName = activeCamera.getClassName();
335
- throw new Error( `Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.` );
336
- }
337
- }
338
-
339
- /**
340
- * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
341
- * environment
342
- */
343
- public async reset(): Promise<Viewer> {
344
- await this.destroy();
345
- return this.bootstrap();
346
- }
347
-
348
- /**
349
- * Destroys
350
- *
351
- * * all {@link VariantInstance}s using {@link destroyVariantInstances}
352
- * * calling `dispose` on the `Engine` and `Scene`
353
- */
354
- public destroy(): Viewer {
355
- this.destroyVariantInstances();
356
- this.scene.dispose();
357
- SpecStorage.destroy();
358
- return this;
359
- }
360
-
361
- /**
362
- * @emits {@link Event.SCENE_PROCESSING_START}
363
- * @emits {@link Event.SCENE_PROCESSING_END}
364
- */
365
- protected async initScene(): Promise<Scene> {
366
- const sceneJson = SpecStorage.get<SceneJson>( 'scene' );
367
- this.broadcastEvent( Event.SCENE_PROCESSING_START, sceneJson );
368
- const engine = new Engine(
369
- this.canvas as HTMLCanvasElement,
370
- sceneJson.engine?.antialiasing ?? false,
371
- sceneJson.engine?.options
372
- );
373
- const scene = await sceneSetup( engine, sceneJson );
374
- if( sceneJson.meshPicking ) {
375
- new HighlightLayer( 'default', scene );
376
- scene.onPointerPick = ( pointerEvent: PointerEvent, pickInfo: PickingInfo ) => {
377
- if( !pickInfo.hit ) {
378
- return;
379
- }
380
- const mesh = pickInfo.pickedMesh;
381
- this.broadcastEvent( Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant );
382
- if( mesh?.metadata.element ) {
383
- this.broadcastEvent( Event.ELEMENT_PICKED, mesh.metadata.element );
384
- }
385
- if( mesh?.metadata.variant ) {
386
- if( mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED] ) {
387
- mesh.metadata.variant.toggleHighlight();
388
- }
389
- this.broadcastEvent( Event.VARIANT_PICKED, mesh.metadata.variant );
390
- }
391
- };
392
- }
393
- this._sceneManager = await SceneManager.create( scene );
394
- this._animationManager = await AnimationManager.create( scene );
395
- this.broadcastEvent( Event.SCENE_PROCESSING_END, scene );
396
- engine.runRenderLoop( () => {
397
- scene.render();
398
- } );
399
- return scene;
400
- }
401
-
402
- /**
403
- * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
404
- */
405
- protected async createVariantInstances(): Promise<VariantInstance[]> {
406
- const setupJson = SpecStorage.get<SetupJson>( 'setup' );
407
- const instances = [];
408
- for( const instanceDefinition of setupJson.instances ) {
409
- if( instanceDefinition.lazy ) {
410
- this.variantInstances.register( instanceDefinition );
411
- continue;
412
- }
413
- instances.push( await this.variantInstances.create(
414
- instanceDefinition.variant,
415
- instanceDefinition.name,
416
- instanceDefinition.parameters
417
- ) );
418
- }
419
- return instances;
420
- }
421
-
1
+ import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera';
2
+ import { PickingInfo } from '@babylonjs/core/Collisions/pickingInfo';
3
+ import { BoundingInfo } from '@babylonjs/core/Culling/boundingInfo';
4
+ import { Engine } from '@babylonjs/core/Engines/engine';
5
+ import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';
6
+ import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
7
+ import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';
8
+ import { Color3 } from '@babylonjs/core/Maths/math.color';
9
+ import { Vector3 } from '@babylonjs/core/Maths/math.vector';
10
+ import { Mesh } from '@babylonjs/core/Meshes/mesh';
11
+ import { ScreenshotTools } from '@babylonjs/core/Misc/screenshotTools';
12
+ import { Scene } from '@babylonjs/core/scene';
13
+ import { isString } from 'lodash-es';
14
+ import { version } from '../../buildinfo.json';
15
+ import { sceneSetup } from '../internal/sceneSetup';
16
+ import { AnimationManager } from '../manager/animationManager';
17
+ import { SceneManager } from '../manager/sceneManager';
18
+ import { VariantInstanceManager } from '../manager/variantInstanceManager';
19
+ import { SpecStorage } from '../store/specStorage';
20
+ import { debounce, loadJson, sleep } from '../util/resourceHelper';
21
+ import { Event } from './event';
22
+ import { EventBroadcaster } from './eventBroadcaster';
23
+ import { Parameter } from './parameter';
24
+ import { Variant } from './variant';
25
+ import { VariantInstance } from './variantInstance';
26
+
27
+
28
+ /**
29
+ * The main exposed object. This is the entry point into the application
30
+ *
31
+ * ```js
32
+ * const canvas = document.getElementById( 'babylon-canvas' );
33
+ * const viewer = Viewer( canvas, '/path/to/index.json' );
34
+ * ```
35
+ * The class does nothing on its own and needs to {@link bootstrap}
36
+ */
37
+ export class Viewer extends EventBroadcaster {
38
+
39
+ protected _scene: Scene | null = null;
40
+
41
+ protected _animationManager: AnimationManager | null = null;
42
+
43
+ protected _sceneManager: SceneManager | null = null;
44
+
45
+ protected _variantInstances: VariantInstanceManager | null = null;
46
+
47
+ static version = version;
48
+
49
+ /**
50
+ * Constructor
51
+ */
52
+ public constructor( public readonly canvas: HTMLCanvasElement, protected structureJson: string | StructureJson ) {
53
+ super();
54
+ }
55
+
56
+ /**
57
+ * Gets the BabylonJS Scene that is attached to the instance.
58
+ *
59
+ * @throws Error if the `scene` has not been initialized.
60
+ */
61
+ get scene(): Scene {
62
+ if( !this._scene ) {
63
+ throw new Error( `Scene has not been initialized.` );
64
+ }
65
+ return this._scene;
66
+ }
67
+
68
+ get sceneManager(): SceneManager {
69
+ if( !this._sceneManager ) {
70
+ throw new Error( `Environment has not been initialized.` );
71
+ }
72
+ return this._sceneManager;
73
+ }
74
+
75
+ /**
76
+ * Gets the BabylonJS Engine that is attached to the viewer.
77
+ */
78
+ get engine(): Engine {
79
+ return this.scene.getEngine();
80
+ }
81
+
82
+ /**
83
+ * Gets the {@link VariantInstanceManager} attached to the viewer.
84
+ *
85
+ * @throws Error if the {@link VariantInstanceManager} has not been initialized.
86
+ */
87
+ get variantInstances(): VariantInstanceManager {
88
+ if( !this._variantInstances ) {
89
+ throw Error( `There is no variantInstanceManager.` );
90
+ }
91
+ return this._variantInstances;
92
+ }
93
+
94
+ /**
95
+ * Gets the {@link AnimationManager} attached to the viewer.
96
+ *
97
+ * @throws Error if the {@link AnimationManager} has not been initialized.
98
+ */
99
+ get animationManager(): AnimationManager {
100
+ if( !this._animationManager ) {
101
+ throw new Error( `There is no animationManager instance.` );
102
+ }
103
+ return this._animationManager;
104
+ }
105
+
106
+ /**
107
+ * Starts the application. This will
108
+ * * load the given "index" JSON file
109
+ * * setup the scene with the "scene" JSON file
110
+ * * create an (optional) default setup with different variant settings
111
+ * * sets up resizing by attaching a debounced version of {@link resize}
112
+ *
113
+ * @throws Error if any of the files is not found/valid
114
+ *
115
+ * @emits {@link Event.BOOTSTRAP_START}
116
+ * @emits {@link Event.BOOTSTRAP_END}
117
+ */
118
+ public async bootstrap(): Promise<Viewer> {
119
+ this.broadcastEvent( Event.BOOTSTRAP_START, this );
120
+ let indexJson;
121
+ if( isString( this.structureJson ) ) {
122
+ indexJson = await loadJson<StructureJson>( this.structureJson );
123
+ } else {
124
+ indexJson = this.structureJson;
125
+ }
126
+ if( !indexJson.scene ) {
127
+ throw new Error( `No "scene" property found for bootstrapping.` );
128
+ }
129
+ // fill spec store
130
+ SpecStorage.createFromSpec( indexJson );
131
+ // load scene
132
+ if( isString( indexJson.scene ) ) {
133
+ const sceneJson = await loadJson<SceneJson>( indexJson.scene );
134
+ indexJson.scene = sceneJson;
135
+ }
136
+ this._scene = await this.initScene();
137
+ // create instance manager
138
+ const rootVariant = await Variant.create( '_', indexJson, this );
139
+ this._variantInstances = await VariantInstanceManager.create( rootVariant );
140
+ // create optional default instances
141
+ if( indexJson.setup ) {
142
+ if( isString( indexJson.setup ) ) {
143
+ const setupJson = await loadJson<SetupJson>( indexJson.setup );
144
+ indexJson.setup = setupJson;
145
+ }
146
+ await this.createVariantInstances();
147
+ }
148
+ // resize handler
149
+ window.addEventListener( 'resize', debounce( this.resize.bind( this ), 100 ) );
150
+ // wait until scene is completely ready
151
+ await this.scene.whenReadyAsync();
152
+ // event broadcasting
153
+ this.broadcastEvent( Event.BOOTSTRAP_END, this );
154
+ // render loop
155
+ this.engine.runRenderLoop( () => {
156
+ this.scene.render();
157
+ } );
158
+ return this;
159
+ }
160
+
161
+ // Disabled for now to decrease bundle size.
162
+ // See https://github.com/Combeenation/3d-viewer/issues/37
163
+ // /**
164
+ // * Enables the BabylonJS DebugLayer. If you pass options, be sure to pass an Object of type `IInspectorOptions`.
165
+ // */
166
+ // public async enableDebugLayer(options?: any) {
167
+ // // @ts-ignore
168
+ // await import(/* webpackChunkName: "debug-inspector" */'@babylonjs/inspector');
169
+ // await this.scene.debugLayer.show(options);
170
+ // return this;
171
+ // }
172
+
173
+ /**
174
+ * Destroys all registered {@link VariantInstance}s that are registered
175
+ */
176
+ public destroyVariantInstances(): Viewer {
177
+ this.variantInstances.all.forEach( variantInstance => {
178
+ this.variantInstances.destroy( variantInstance.name );
179
+ } );
180
+ return this;
181
+ }
182
+
183
+ /**
184
+ * Trigger a resize event for the `Engine`
185
+ */
186
+ public resize(): Viewer {
187
+ this.engine.resize();
188
+ return this;
189
+ }
190
+
191
+ /**
192
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
193
+ * {@link DottedPath}s.
194
+ */
195
+ public async getNode( variantInstanceName: string,
196
+ elementDottedPath: DottedPathArgument,
197
+ nodeDottedPath: DottedPathArgument ): Promise<TransformNode> {
198
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
199
+ return variantInstance.getNode( elementDottedPath, nodeDottedPath );
200
+ }
201
+
202
+ /**
203
+ * A convenience method for directly getting a Node from a {@link VariantInstance} and an {@link Element} by its
204
+ * {@link DottedPath}s.
205
+ */
206
+ public async getMesh( variantInstanceName: string,
207
+ elementDottedPath: DottedPathArgument,
208
+ meshDottedPath: DottedPathArgument ): Promise<Mesh|null> {
209
+ const variantInstance = await this.variantInstances.get(variantInstanceName);
210
+ return variantInstance.getMesh( elementDottedPath, meshDottedPath );
211
+ }
212
+
213
+ /**
214
+ * Switches the camera
215
+ *
216
+ * @emits {@link Event.CAMERA_SWITCHED}
217
+ */
218
+ public switchCamera( newCamera: string, reset: boolean = true ): Viewer {
219
+ const camera = this.scene.getCameraByName( newCamera );
220
+ if( camera ) {
221
+ const activeCamera = this.scene.activeCamera;
222
+ if( activeCamera ) {
223
+ activeCamera.detachControl( this.engine.getRenderingCanvas()! );
224
+ }
225
+ if( reset ) {
226
+ camera.restoreState();
227
+ }
228
+ this.scene.setActiveCameraByName( newCamera );
229
+ camera.attachControl( this.engine.getRenderingCanvas()! );
230
+ this.broadcastEvent( Event.CAMERA_SWITCHED, camera );
231
+ } else {
232
+ throw new Error( `Given camera "${newCamera}" not found.` );
233
+ }
234
+ // TODO: put traceable observers to new camera (@see element)
235
+ return this;
236
+ }
237
+
238
+ /**
239
+ * Moves or animates the active camera to given `placement`.
240
+ */
241
+ public async moveActiveCameraTo( placement: string | PlacementDefinition,
242
+ animation?: string | AnimationDefinition ): Promise<AnimationInterface> {
243
+ return this.animationManager.animateToPlacement( this.sceneManager.activeCamera, placement, animation );
244
+ }
245
+
246
+ /**
247
+ * Takes a sceenshot the the current scene. The result is a string containing a base64 encoded image
248
+ */
249
+ public screenshot( settings?: ScreenshotSettings ): Promise<string> {
250
+ return new Promise( ( resolve, reject ) => {
251
+ if( !this.engine ) {
252
+ return reject( 'Engine is null' );
253
+ }
254
+ if( !this.scene ) {
255
+ return reject( 'Scene is null' );
256
+ }
257
+ this.scene.render(); // in combination with a render target, we need to refresh the scene manually to get the latest view
258
+ ScreenshotTools.CreateScreenshotUsingRenderTarget(
259
+ this.engine,
260
+ this.sceneManager.activeCamera,
261
+ settings?.size ?? { width: this.canvas.clientWidth, height: this.canvas.clientHeight },
262
+ resolve,
263
+ settings?.mimeType ?? 'image/png',
264
+ settings?.samples ?? 1,
265
+ settings?.antialiasing ?? false,
266
+ settings?.fileName ?? 'screenshot.png',
267
+ settings?.renderSprites ?? false
268
+ );
269
+ } );
270
+ }
271
+
272
+ /**
273
+ * Calculates the bounding box from all visible meshes on the scene.
274
+ */
275
+ public async calculateBoundingBox(): Promise<Mesh> {
276
+ if( this.scene.meshes.length === 0 ) {
277
+ throw new Error( 'There are currently no meshes on the scene.' );
278
+ }
279
+ this.scene.render(); // XXX: workaround for BoundingBox not respecting render loop
280
+ const bbName = '__bounding_box__';
281
+
282
+ const { max, min } = this.scene.meshes.filter( mesh => {
283
+ const isEnabled = mesh.isEnabled();
284
+ // ignore the existing bounding box mesh for calculating the current one
285
+ const isNotBBoxMesh = bbName !== mesh.id;
286
+ // ignore meshes with invalid bounding infos
287
+ const hasValidBBoxInfo = mesh.getBoundingInfo().boundingSphere.radius > 0;
288
+ return isEnabled && isNotBBoxMesh && hasValidBBoxInfo;
289
+ } ).reduce( ( accBBoxMinMax, curMesh, idx ) => {
290
+ const bBox = curMesh.getBoundingInfo().boundingBox;
291
+ // use the first entry in the array as default value and get the resulting maximum/minimum values
292
+ const max = ( idx === 0 ) ? bBox.maximumWorld : Vector3.Maximize( accBBoxMinMax.max, bBox.maximumWorld )
293
+ const min = ( idx === 0 ) ? bBox.minimumWorld : Vector3.Minimize( accBBoxMinMax.min, bBox.minimumWorld )
294
+ return { max, min }
295
+ }, { max: new Vector3(), min: new Vector3() } );
296
+
297
+ let boundingBox = this.scene.getMeshByName( bbName ) as Mesh;
298
+ if( !boundingBox ) {
299
+ boundingBox = new Mesh( bbName, this.scene );
300
+ }
301
+ boundingBox.setBoundingInfo( new BoundingInfo( min, max ) );
302
+ return boundingBox;
303
+ }
304
+
305
+ /**
306
+ * Focuses the camera to see every visible mesh in scene and tries to optimize wheel precision and panning.
307
+ */
308
+ public async autofocusActiveCamera( settings?: AutofocusSettings ) {
309
+ const activeCamera = this.scene.activeCamera;
310
+ if( !activeCamera ) {
311
+ throw new Error( 'No active camera found when using autofocus feature.' );
312
+ }
313
+ if( activeCamera instanceof ArcRotateCamera ) {
314
+ // calculate some values
315
+ const boundingBox = await this.calculateBoundingBox();
316
+ const size = boundingBox.getBoundingInfo().maximum.subtract( boundingBox.getBoundingInfo().minimum );
317
+ let radius = size.length() * (settings?.radiusFactor ?? 1.5);
318
+ if( !isFinite( radius ) ) {
319
+ radius = 1;
320
+ }
321
+ // use helper camera to get some default values
322
+ const helperCamera = new ArcRotateCamera(
323
+ '__helper_camera__',
324
+ Math.PI / -2,
325
+ Math.PI / 2,
326
+ radius,
327
+ Vector3.Zero(),
328
+ this.scene
329
+ );
330
+ helperCamera.useFramingBehavior = true;
331
+ helperCamera.setTarget( boundingBox );
332
+ // translate values from helper to active camera
333
+ activeCamera.setTarget( Mesh.Center( [boundingBox] ) );
334
+ activeCamera.alpha = helperCamera.alpha;
335
+ activeCamera.beta = helperCamera.beta;
336
+ activeCamera.minZ = helperCamera.minZ;
337
+ activeCamera.maxZ = helperCamera.maxZ;
338
+ activeCamera.radius = helperCamera.radius;
339
+ activeCamera.lowerRadiusLimit = helperCamera.lowerRadiusLimit;
340
+ activeCamera.upperRadiusLimit = helperCamera.upperRadiusLimit;
341
+ if( settings?.adjustWheelPrecision !== false ) {
342
+ activeCamera.wheelPrecision = helperCamera.wheelPrecision;
343
+ }
344
+ if( settings?.adjustPanningSensibility !== false ) {
345
+ activeCamera.panningSensibility = helperCamera.panningSensibility;
346
+ }
347
+ if( settings?.adjustPinchPrecision !== false ) {
348
+ activeCamera.pinchPrecision = helperCamera.pinchPrecision;
349
+ }
350
+ // remove the helper camera
351
+ helperCamera.dispose();
352
+ } else {
353
+ const cameraClsName = activeCamera.getClassName();
354
+ throw new Error( `Camera of type "${cameraClsName}" is not implemented yet to use autofocus feature.` );
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Resets everything by calling {@link destroy} to clear all references and {@link bootstrap} to setup a clean
360
+ * environment
361
+ */
362
+ public async reset(): Promise<Viewer> {
363
+ await this.destroy();
364
+ return this.bootstrap();
365
+ }
366
+
367
+ /**
368
+ * Destroys
369
+ *
370
+ * * all {@link VariantInstance}s using {@link destroyVariantInstances}
371
+ * * calling `dispose` on the `Engine` and `Scene`
372
+ */
373
+ public destroy(): Viewer {
374
+ this.destroyVariantInstances();
375
+ this.scene.dispose();
376
+ SpecStorage.destroy();
377
+ return this;
378
+ }
379
+
380
+ /**
381
+ * Show coordinate system with given dimension (for debugging purpose).
382
+ */
383
+ public showWorldCoordinates( dimension: number ) {
384
+ const scene = this.scene;
385
+ const makeTextPlane = function( text: string, color: string, size: number ) {
386
+ const dynamicTexture = new DynamicTexture( 'DynamicTexture', 50, scene, true );
387
+ dynamicTexture.hasAlpha = true;
388
+ dynamicTexture.drawText( text, 5, 40, 'bold 36px Arial', color, 'transparent', true );
389
+ const plane = Mesh.CreatePlane( 'TextPlane', size, scene, true );
390
+ plane.material = new StandardMaterial( 'TextPlaneMaterial', scene );
391
+ plane.material.backFaceCulling = false;
392
+ // @ts-ignore
393
+ plane.material.specularColor = new Color3( 0, 0, 0 );
394
+ // @ts-ignore
395
+ plane.material.diffuseTexture = dynamicTexture;
396
+ return plane;
397
+ };
398
+ const axisX = Mesh.CreateLines( 'axisX', [
399
+ Vector3.Zero(),
400
+ new Vector3( dimension, 0, 0 ),
401
+ new Vector3( dimension * 0.95, 0.05 * dimension, 0 ),
402
+ new Vector3( dimension, 0, 0 ),
403
+ new Vector3( dimension * 0.95, -0.05 * dimension, 0 )
404
+ ], scene );
405
+ axisX.color = new Color3( 1, 0, 0 );
406
+ const xChar = makeTextPlane( 'X', 'red', dimension / 10 );
407
+ xChar.position = new Vector3( 0.9 * dimension, -0.05 * dimension, 0 );
408
+ const axisY = Mesh.CreateLines( 'axisY', [
409
+ Vector3.Zero(),
410
+ new Vector3( 0, dimension, 0 ),
411
+ new Vector3( -0.05 * dimension, dimension * 0.95, 0 ),
412
+ new Vector3( 0, dimension, 0 ),
413
+ new Vector3( 0.05 * dimension, dimension * 0.95, 0 )
414
+ ], scene );
415
+ axisY.color = new Color3( 0, 1, 0 );
416
+ const yChar = makeTextPlane( 'Y', 'green', dimension / 10 );
417
+ yChar.position = new Vector3( 0, 0.9 * dimension, -0.05 * dimension );
418
+ const axisZ = Mesh.CreateLines( 'axisZ', [
419
+ Vector3.Zero(),
420
+ new Vector3( 0, 0, dimension ),
421
+ new Vector3( 0, -0.05 * dimension, dimension * 0.95 ),
422
+ new Vector3( 0, 0, dimension ),
423
+ new Vector3( 0, 0.05 * dimension, dimension * 0.95 )
424
+ ], scene );
425
+ axisZ.color = new Color3( 0, 0, 1 );
426
+ const zChar = makeTextPlane( 'Z', 'blue', dimension / 10 );
427
+ zChar.position = new Vector3( 0, 0.05 * dimension, 0.9 * dimension );
428
+ }
429
+
430
+ /**
431
+ * @emits {@link Event.SCENE_PROCESSING_START}
432
+ * @emits {@link Event.SCENE_PROCESSING_END}
433
+ */
434
+ protected async initScene(): Promise<Scene> {
435
+ const sceneJson = SpecStorage.get<SceneJson>( 'scene' );
436
+ this.broadcastEvent( Event.SCENE_PROCESSING_START, sceneJson );
437
+ const engine = new Engine(
438
+ this.canvas as HTMLCanvasElement,
439
+ sceneJson.engine?.antialiasing ?? false,
440
+ sceneJson.engine?.options
441
+ );
442
+ const scene = await sceneSetup( engine, sceneJson );
443
+ if( sceneJson.meshPicking ) {
444
+ new HighlightLayer( 'default', scene );
445
+ scene.onPointerPick = ( pointerEvent: PointerEvent, pickInfo: PickingInfo ) => {
446
+ if( !pickInfo.hit ) {
447
+ return;
448
+ }
449
+ const mesh = pickInfo.pickedMesh;
450
+ this.broadcastEvent( Event.MESH_PICKED, mesh, mesh?.metadata.element, mesh?.metadata.variant );
451
+ if( mesh?.metadata.element ) {
452
+ this.broadcastEvent( Event.ELEMENT_PICKED, mesh.metadata.element );
453
+ }
454
+ if( mesh?.metadata.variant ) {
455
+ if( mesh.metadata.variant.inheritedParameters[Parameter.HIGHLIGHT_ENABLED] ) {
456
+ mesh.metadata.variant.toggleHighlight();
457
+ }
458
+ this.broadcastEvent( Event.VARIANT_PICKED, mesh.metadata.variant );
459
+ }
460
+ };
461
+ }
462
+ this._sceneManager = await SceneManager.create( scene );
463
+ this._animationManager = await AnimationManager.create( scene );
464
+ this.broadcastEvent( Event.SCENE_PROCESSING_END, scene );
465
+ return scene;
466
+ }
467
+
468
+ /**
469
+ * Batch creation of multiple {@link VariantInstance} objects with a {@link SetupJson} object passed
470
+ */
471
+ protected async createVariantInstances(): Promise<VariantInstance[]> {
472
+ const setupJson = SpecStorage.get<SetupJson>( 'setup' );
473
+ const instances = [];
474
+ for( const instanceDefinition of setupJson.instances ) {
475
+ if( instanceDefinition.lazy ) {
476
+ this.variantInstances.register( instanceDefinition );
477
+ continue;
478
+ }
479
+ instances.push( await this.variantInstances.create(
480
+ instanceDefinition.variant,
481
+ instanceDefinition.name,
482
+ instanceDefinition.parameters
483
+ ) );
484
+ }
485
+ return instances;
486
+ }
487
+
422
488
  }