viewer.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. import { Database, Effect, Engine, ISceneLoaderPlugin, ISceneLoaderPluginAsync, Observable, RenderingManager, Scene, SceneLoaderProgressEvent, TargetCamera, Tools, Vector3, Observer } from 'babylonjs';
  2. import { IModelConfiguration, IObserversConfiguration, ViewerConfiguration } from '../configuration/';
  3. import { processConfigurationCompatibility } from '../configuration/configurationCompatibility';
  4. import { ConfigurationContainer } from '../configuration/configurationContainer';
  5. import { viewerGlobals } from '../configuration/globals';
  6. import { ConfigurationLoader } from '../configuration/loader';
  7. import { deepmerge } from '../helper/';
  8. import { ModelLoader } from '../loader/modelLoader';
  9. import { ObservablesManager } from '../managers/observablesManager';
  10. import { SceneManager } from '../managers/sceneManager';
  11. import { telemetryManager } from '../managers/telemetryManager';
  12. import { ViewerModel } from '../model/viewerModel';
  13. import { TemplateManager } from '../templating/templateManager';
  14. import { viewerManager } from './viewerManager';
  15. /**
  16. * The AbstractViewr is the center of Babylon's viewer.
  17. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  18. */
  19. export abstract class AbstractViewer {
  20. /**
  21. * The corresponsing template manager of this viewer.
  22. */
  23. public templateManager: TemplateManager;
  24. // TODO get the template manager to the default viewer, if no one is extending the abstract viewer
  25. /**
  26. * Babylon Engine corresponding with this viewer
  27. */
  28. public engine: Engine;
  29. /**
  30. * The ID of this viewer. it will be generated randomly or use the HTML Element's ID.
  31. */
  32. public readonly baseId: string;
  33. /**
  34. * The last loader used to load a model.
  35. * @deprecated
  36. */
  37. public lastUsedLoader: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  38. /**
  39. * The ModelLoader instance connected with this viewer.
  40. */
  41. public modelLoader: ModelLoader;
  42. /**
  43. * A flag that controls whether or not the render loop should be executed
  44. */
  45. public runRenderLoop: boolean = true;
  46. /**
  47. * The scene manager connected with this viewer instance
  48. */
  49. public sceneManager: SceneManager;
  50. // observables
  51. /**
  52. * Will notify when the scene was initialized
  53. */
  54. public get onSceneInitObservable(): Observable<Scene> {
  55. return this.observablesManager.onSceneInitObservable;
  56. }
  57. /**
  58. * will notify when the engine was initialized
  59. */
  60. public get onEngineInitObservable(): Observable<Engine> {
  61. return this.observablesManager.onEngineInitObservable;
  62. }
  63. /**
  64. * Will notify when a new model was added to the scene.
  65. * Note that added does not neccessarily mean loaded!
  66. */
  67. public get onModelAddedObservable(): Observable<ViewerModel> {
  68. return this.observablesManager.onModelAddedObservable;
  69. }
  70. /**
  71. * will notify after every model load
  72. */
  73. public get onModelLoadedObservable(): Observable<ViewerModel> {
  74. return this.observablesManager.onModelLoadedObservable;
  75. }
  76. /**
  77. * will notify when any model notify of progress
  78. */
  79. public get onModelLoadProgressObservable(): Observable<SceneLoaderProgressEvent> {
  80. return this.observablesManager.onModelLoadProgressObservable;
  81. }
  82. /**
  83. * will notify when any model load failed.
  84. */
  85. public get onModelLoadErrorObservable(): Observable<{ message: string; exception: any }> {
  86. return this.observablesManager.onModelLoadErrorObservable;
  87. }
  88. /**
  89. * Will notify when a model was removed from the scene;
  90. */
  91. public get onModelRemovedObservable(): Observable<ViewerModel> {
  92. return this.observablesManager.onModelRemovedObservable;
  93. }
  94. /**
  95. * will notify when a new loader was initialized.
  96. * Used mainly to know when a model starts loading.
  97. */
  98. public get onLoaderInitObservable(): Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  99. return this.observablesManager.onLoaderInitObservable;
  100. }
  101. /**
  102. * Observers registered here will be executed when the entire load process has finished.
  103. */
  104. public get onInitDoneObservable(): Observable<AbstractViewer> {
  105. return this.observablesManager.onViewerInitDoneObservable;
  106. }
  107. /**
  108. * Functions added to this observable will be executed on each frame rendered.
  109. */
  110. public get onFrameRenderedObservable(): Observable<AbstractViewer> {
  111. return this.observablesManager.onFrameRenderedObservable;
  112. }
  113. /**
  114. * Observers registered here will be executed when VR more is entered.
  115. */
  116. public get onEnteringVRObservable(): Observable<AbstractViewer> {
  117. return this.observablesManager.onEnteringVRObservable;
  118. }
  119. /**
  120. * Observers registered here will be executed when VR mode is exited.
  121. */
  122. public get onExitingVRObservable(): Observable<AbstractViewer> {
  123. return this.observablesManager.onExitingVRObservable;
  124. }
  125. public observablesManager: ObservablesManager;
  126. /**
  127. * The canvas associated with this viewer
  128. */
  129. protected _canvas: HTMLCanvasElement;
  130. /**
  131. * The (single) canvas of this viewer
  132. */
  133. public get canvas(): HTMLCanvasElement {
  134. return this._canvas;
  135. }
  136. /**
  137. * is this viewer disposed?
  138. */
  139. protected _isDisposed: boolean = false;
  140. /**
  141. * registered onBeforeRender functions.
  142. * This functions are also registered at the native scene. The reference can be used to unregister them.
  143. */
  144. protected _registeredOnBeforeRenderFunctions: Array<() => void>;
  145. /**
  146. * The configuration loader of this viewer
  147. */
  148. protected _configurationLoader: ConfigurationLoader;
  149. /**
  150. * Is the viewer already initialized. for internal use.
  151. */
  152. protected _isInit: boolean;
  153. protected _configurationContainer: ConfigurationContainer;
  154. public get configurationContainer() {
  155. return this._configurationContainer;
  156. }
  157. constructor(public containerElement: HTMLElement, initialConfiguration: ViewerConfiguration = {}) {
  158. // if exists, use the container id. otherwise, generate a random string.
  159. if (containerElement.id) {
  160. this.baseId = containerElement.id;
  161. } else {
  162. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  163. }
  164. this._registeredOnBeforeRenderFunctions = [];
  165. this._configurationContainer = new ConfigurationContainer();
  166. this.observablesManager = new ObservablesManager();
  167. this.modelLoader = new ModelLoader(this.observablesManager, this._configurationContainer);
  168. RenderingManager.AUTOCLEAR = false;
  169. // extend the configuration
  170. this._configurationLoader = new ConfigurationLoader();
  171. this._configurationLoader.loadConfiguration(initialConfiguration, (configuration) => {
  172. this._onConfigurationLoaded(configuration);
  173. });
  174. this.onSceneInitObservable.add(() => {
  175. this.updateConfiguration();
  176. });
  177. this.onInitDoneObservable.add(() => {
  178. this._isInit = true;
  179. this.engine.runRenderLoop(this._render);
  180. });
  181. this._prepareContainerElement();
  182. // add this viewer to the viewer manager
  183. viewerManager.addViewer(this);
  184. }
  185. /**
  186. * get the baseId of this viewer
  187. */
  188. public getBaseId(): string {
  189. return this.baseId;
  190. }
  191. /**
  192. * Do we have a canvas to render on, and is it a part of the scene
  193. */
  194. public isCanvasInDOM(): boolean {
  195. return !!this._canvas && !!this._canvas.parentElement;
  196. }
  197. /**
  198. * Is the engine currently set to rende even when the page is in background
  199. */
  200. public get renderInBackground() {
  201. return this.engine && this.engine.renderEvenInBackground;
  202. }
  203. /**
  204. * Set the viewer's background rendering flag.
  205. */
  206. public set renderInBackground(value: boolean) {
  207. if (this.engine) {
  208. this.engine.renderEvenInBackground = value;
  209. }
  210. }
  211. /**
  212. * Get the configuration object. This is a reference only.
  213. * The configuration can ONLY be updated using the updateConfiguration function.
  214. * changing this object will have no direct effect on the scene.
  215. */
  216. public get configuration(): ViewerConfiguration {
  217. return this._configurationContainer.configuration;
  218. }
  219. /**
  220. * force resizing the engine.
  221. */
  222. public forceResize() {
  223. this._resize();
  224. }
  225. protected _hdToggled: boolean = false;
  226. public toggleHD() {
  227. this._hdToggled = !this._hdToggled;
  228. var scale = this._hdToggled ? Math.max(0.5, 1 / (window.devicePixelRatio || 2)) : 1;
  229. this.engine.setHardwareScalingLevel(scale);
  230. }
  231. protected _vrToggled: boolean = false;
  232. private _vrModelRepositioning: number = 0;
  233. protected _vrScale: number = 1;
  234. protected _vrInit: boolean = false;
  235. public toggleVR() {
  236. if (!this._vrInit) {
  237. this._initVR();
  238. }
  239. if (this.sceneManager.vrHelper && !this.sceneManager.vrHelper.isInVRMode) {
  240. // make sure the floor is set
  241. if (this.sceneManager.environmentHelper && this.sceneManager.environmentHelper.ground) {
  242. this.sceneManager.vrHelper.addFloorMesh(this.sceneManager.environmentHelper.ground);
  243. }
  244. this._vrToggled = true;
  245. this.sceneManager.vrHelper.enterVR();
  246. // position the vr camera to be in front of the object or wherever the user has configured it to be
  247. if (this.sceneManager.vrHelper.currentVRCamera && this.sceneManager.vrHelper.currentVRCamera !== this.sceneManager.camera) {
  248. if (this.configuration.vr && this.configuration.vr.cameraPosition !== undefined) {
  249. this.sceneManager.vrHelper.currentVRCamera.position.copyFrom(this.configuration.vr.cameraPosition as Vector3);
  250. } else {
  251. this.sceneManager.vrHelper.currentVRCamera.position.copyFromFloats(0, this.sceneManager.vrHelper.currentVRCamera.position.y, -1);
  252. }
  253. (<TargetCamera>this.sceneManager.vrHelper.currentVRCamera).rotationQuaternion && (<TargetCamera>this.sceneManager.vrHelper.currentVRCamera).rotationQuaternion.copyFromFloats(0, 0, 0, 1);
  254. // set the height of the model to be what the user has configured, or floating by default
  255. if (this.configuration.vr && this.configuration.vr.modelHeightCorrection !== undefined) {
  256. if (typeof this.configuration.vr.modelHeightCorrection === 'number') {
  257. this._vrModelRepositioning = this.configuration.vr.modelHeightCorrection
  258. } else if (this.configuration.vr.modelHeightCorrection) {
  259. this._vrModelRepositioning = this.sceneManager.vrHelper.currentVRCamera.position.y / 2;
  260. } else {
  261. this._vrModelRepositioning = 0;
  262. }
  263. }
  264. // scale the model
  265. if (this.sceneManager.models.length) {
  266. let boundingVectors = this.sceneManager.models[0].rootMesh.getHierarchyBoundingVectors();
  267. let sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  268. let maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  269. this._vrScale = (1 / maxDimension);
  270. if (this.configuration.vr && this.configuration.vr.objectScaleFactor) {
  271. this._vrScale *= this.configuration.vr.objectScaleFactor;
  272. }
  273. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(this._vrScale);
  274. // reposition the object to "float" in front of the user
  275. this.sceneManager.models[0].rootMesh.position.y += this._vrModelRepositioning;
  276. this.sceneManager.models[0].rootMesh.rotationQuaternion = null;
  277. }
  278. // scale the environment to match the model
  279. if (this.sceneManager.environmentHelper) {
  280. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(this._vrScale);
  281. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(this._vrScale);
  282. }
  283. // post processing
  284. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  285. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = false;
  286. this.sceneManager.defaultRenderingPipeline.prepare();
  287. }
  288. } else {
  289. this._vrModelRepositioning = 0;
  290. }
  291. } else {
  292. if (this.sceneManager.vrHelper) {
  293. this.sceneManager.vrHelper.exitVR();
  294. }
  295. }
  296. }
  297. protected _initVR() {
  298. if (this.sceneManager.vrHelper) {
  299. this.observablesManager.onExitingVRObservable.add(() => {
  300. if (this._vrToggled) {
  301. this._vrToggled = false;
  302. // undo the scaling of the model
  303. if (this.sceneManager.models.length) {
  304. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(1 / this._vrScale);
  305. this.sceneManager.models[0].rootMesh.position.y -= this._vrModelRepositioning;
  306. }
  307. // undo the scaling of the environment
  308. if (this.sceneManager.environmentHelper) {
  309. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(1 / this._vrScale);
  310. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(1 / this._vrScale);
  311. }
  312. // post processing
  313. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  314. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = true;
  315. this.sceneManager.defaultRenderingPipeline.prepare();
  316. }
  317. // clear set height and eidth
  318. this.canvas.removeAttribute("height");
  319. this.canvas.removeAttribute("width");
  320. this.engine.resize();
  321. }
  322. })
  323. }
  324. this._vrInit = true;
  325. }
  326. /**
  327. * The resize function that will be registered with the window object
  328. */
  329. protected _resize = (): void => {
  330. // Only resize if Canvas is in the DOM
  331. if (!this.isCanvasInDOM()) {
  332. return;
  333. }
  334. if (this.canvas.clientWidth <= 0 || this.canvas.clientHeight <= 0) {
  335. return;
  336. }
  337. if (this.configuration.engine && this.configuration.engine.disableResize) {
  338. return;
  339. }
  340. this.engine.resize();
  341. }
  342. protected _onConfigurationLoaded(configuration: ViewerConfiguration) {
  343. this._configurationContainer.configuration = deepmerge(this.configuration || {}, configuration);
  344. if (this.configuration.observers) {
  345. this._configureObservers(this.configuration.observers);
  346. }
  347. // TODO remove this after testing, as this is done in the updateConfiguration as well.
  348. if (this.configuration.loaderPlugins) {
  349. Object.keys(this.configuration.loaderPlugins).forEach((name => {
  350. if (this.configuration.loaderPlugins && this.configuration.loaderPlugins[name]) {
  351. this.modelLoader.addPlugin(name);
  352. }
  353. }))
  354. }
  355. this.templateManager = new TemplateManager(this.containerElement);
  356. this.observablesManager.onViewerInitStartedObservable.notifyObservers(this);
  357. }
  358. /**
  359. * Force a single render loop execution.
  360. */
  361. public forceRender() {
  362. this._render(true);
  363. }
  364. /**
  365. * render loop that will be executed by the engine
  366. */
  367. protected _render = (force: boolean = false): void => {
  368. if (force || (this.sceneManager.scene && this.sceneManager.scene.activeCamera)) {
  369. if (this.runRenderLoop || force) {
  370. this.engine.performanceMonitor.enable();
  371. this.sceneManager.scene.render();
  372. this.onFrameRenderedObservable.notifyObservers(this);
  373. } else {
  374. this.engine.performanceMonitor.disable();
  375. // update camera instead of rendering
  376. this.sceneManager.scene.activeCamera && this.sceneManager.scene.activeCamera.update();
  377. }
  378. }
  379. }
  380. /**
  381. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  382. * @param callback optional callback that will be triggered when screenshot is done.
  383. * @param width Optional screenshot width (default to 512).
  384. * @param height Optional screenshot height (default to 512).
  385. * @returns a promise with the screenshot data
  386. */
  387. public takeScreenshot(callback?: (data: string) => void, width = 0, height = 0): Promise<string> {
  388. width = width || this.canvas.clientWidth;
  389. height = height || this.canvas.clientHeight;
  390. // Create the screenshot
  391. return new Promise<string>((resolve, reject) => {
  392. try {
  393. BABYLON.Tools.CreateScreenshot(this.engine, this.sceneManager.camera, { width, height }, (data) => {
  394. if (callback) {
  395. callback(data);
  396. }
  397. resolve(data);
  398. });
  399. } catch (e) {
  400. reject(e);
  401. }
  402. });
  403. }
  404. /**
  405. * Update the current viewer configuration with new values.
  406. * Only provided information will be updated, old configuration values will be kept.
  407. * If this.configuration was manually changed, you can trigger this function with no parameters,
  408. * and the entire configuration will be updated.
  409. * @param newConfiguration the partial configuration to update or a URL to a JSON holding the updated configuration
  410. *
  411. */
  412. public updateConfiguration(newConfiguration: Partial<ViewerConfiguration> | string = this.configuration) {
  413. if (typeof newConfiguration === "string") {
  414. Tools.LoadFile(newConfiguration, (data) => {
  415. try {
  416. const newData = JSON.parse(data.toString()) as ViewerConfiguration;
  417. return this.updateConfiguration(newData);
  418. } catch (e) {
  419. console.log("Error parsing file " + newConfiguration);
  420. }
  421. }, undefined, undefined, undefined, (error) => {
  422. console.log("Error parsing file " + newConfiguration, error);
  423. });
  424. } else {
  425. //backcompat
  426. processConfigurationCompatibility(newConfiguration);
  427. // update this.configuration with the new data
  428. this._configurationContainer.configuration = deepmerge(this.configuration || {}, newConfiguration);
  429. this.sceneManager.updateConfiguration(newConfiguration);
  430. // observers in configuration
  431. if (newConfiguration.observers) {
  432. this._configureObservers(newConfiguration.observers);
  433. }
  434. if (newConfiguration.loaderPlugins) {
  435. Object.keys(newConfiguration.loaderPlugins).forEach((name => {
  436. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  437. this.modelLoader.addPlugin(name);
  438. }
  439. }));
  440. }
  441. }
  442. }
  443. /**
  444. * this is used to register native functions using the configuration object.
  445. * This will configure the observers.
  446. * @param observersConfiguration observers configuration
  447. */
  448. protected _configureObservers(observersConfiguration: IObserversConfiguration) {
  449. if (observersConfiguration.onEngineInit) {
  450. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  451. } else {
  452. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers!.onEngineInit) {
  453. this.onEngineInitObservable.removeCallback(window[this.configuration.observers!.onEngineInit!]);
  454. }
  455. }
  456. if (observersConfiguration.onSceneInit) {
  457. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  458. } else {
  459. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers!.onSceneInit) {
  460. this.onSceneInitObservable.removeCallback(window[this.configuration.observers!.onSceneInit!]);
  461. }
  462. }
  463. if (observersConfiguration.onModelLoaded) {
  464. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  465. } else {
  466. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers!.onModelLoaded) {
  467. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers!.onModelLoaded!]);
  468. }
  469. }
  470. }
  471. /**
  472. * Dispose the entire viewer including the scene and the engine
  473. */
  474. public dispose() {
  475. if (this._isDisposed) {
  476. return;
  477. }
  478. window.removeEventListener('resize', this._resize);
  479. if (this.sceneManager) {
  480. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  481. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  482. }
  483. this.sceneManager.dispose();
  484. }
  485. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  486. this.observablesManager.dispose();
  487. this.modelLoader.dispose();
  488. if (this.engine) {
  489. this.engine.dispose();
  490. }
  491. viewerManager.removeViewer(this);
  492. this._isDisposed = true;
  493. }
  494. /**
  495. * This will prepare the container element for the viewer
  496. */
  497. protected abstract _prepareContainerElement();
  498. /**
  499. * This function will execute when the HTML templates finished initializing.
  500. * It should initialize the engine and continue execution.
  501. *
  502. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  503. */
  504. protected _onTemplatesLoaded(): Promise<AbstractViewer> {
  505. return Promise.resolve(this);
  506. }
  507. /**
  508. * This will force the creation of an engine and a scene.
  509. * It will also load a model if preconfigured.
  510. * But first - it will load the extendible onTemplateLoaded()!
  511. */
  512. protected _onTemplateLoaded(): Promise<AbstractViewer> {
  513. // check if viewer was disposed right after created
  514. if (this._isDisposed) {
  515. return Promise.reject("viewer was disposed");
  516. }
  517. return this._onTemplatesLoaded().then(() => {
  518. let autoLoad = typeof this.configuration.model === 'string' || (this.configuration.model && this.configuration.model.url);
  519. return this._initEngine().then((engine) => {
  520. return this.onEngineInitObservable.notifyObserversWithPromise(engine);
  521. }).then(() => {
  522. this._initTelemetryEvents();
  523. if (autoLoad) {
  524. return this.loadModel(this.configuration.model!).catch(() => { }).then(() => { return this.sceneManager.scene });
  525. } else {
  526. return this.sceneManager.scene || this.sceneManager.initScene(this.configuration.scene);
  527. }
  528. }).then(() => {
  529. return this.onInitDoneObservable.notifyObserversWithPromise(this);
  530. }).catch(e => {
  531. Tools.Warn(e.toString());
  532. return this;
  533. });
  534. })
  535. }
  536. /**
  537. * Initialize the engine. Retruns a promise in case async calls are needed.
  538. *
  539. * @protected
  540. * @returns {Promise<Engine>}
  541. * @memberof Viewer
  542. */
  543. protected _initEngine(): Promise<Engine> {
  544. // init custom shaders
  545. this._injectCustomShaders();
  546. //let canvasElement = this.templateManager.getCanvas();
  547. if (!this.canvas) {
  548. return Promise.reject('Canvas element not found!');
  549. }
  550. let config = this.configuration.engine || {};
  551. // TDO enable further configuration
  552. // check for webgl2 support, force-disable if needed.
  553. if (viewerGlobals.disableWebGL2Support) {
  554. config.engineOptions = config.engineOptions || {};
  555. config.engineOptions.disableWebGL2Support = true;
  556. }
  557. this.engine = new Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  558. // Disable manifest checking
  559. Database.IDBStorageEnabled = false;
  560. if (!config.disableResize) {
  561. window.addEventListener('resize', this._resize);
  562. }
  563. if (this.configuration.engine) {
  564. if (this.configuration.engine.adaptiveQuality) {
  565. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  566. this.engine.setHardwareScalingLevel(scale);
  567. }
  568. if (this.configuration.engine.hdEnabled) {
  569. this.toggleHD();
  570. }
  571. }
  572. // create a new template manager for this viewer
  573. this.sceneManager = new SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  574. // this.observablesManager.onEnteringVRObservable.add(() => {
  575. // this.onEnteringVRObservable.notifyObservers(this);
  576. // });
  577. // this.observablesManager.onExitingVRObservable.add(() => {
  578. // this.onExitingVRObservable.notifyObservers(this);
  579. // });
  580. return Promise.resolve(this.engine);
  581. }
  582. private _isLoading: boolean;
  583. /**
  584. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  585. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  586. *
  587. * @param modelConfig model configuration to use when loading the model.
  588. * @param clearScene should the scene be cleared before loading this model
  589. * @returns a ViewerModel object that is not yet fully loaded.
  590. */
  591. public initModel(modelConfig: string | File | IModelConfiguration, clearScene: boolean = true): ViewerModel {
  592. let configuration: IModelConfiguration;
  593. if (typeof modelConfig === 'string') {
  594. configuration = {
  595. url: modelConfig
  596. }
  597. } else if (modelConfig instanceof File) {
  598. configuration = {
  599. file: modelConfig,
  600. root: "file:"
  601. }
  602. } else {
  603. configuration = modelConfig
  604. }
  605. if (!configuration.url && !configuration.file) {
  606. throw new Error("no model provided");
  607. }
  608. if (clearScene) {
  609. this.sceneManager.clearScene(true, false);
  610. }
  611. //merge the configuration for future models:
  612. if (this.configuration.model && typeof this.configuration.model === 'object') {
  613. let globalConfig = deepmerge({}, this.configuration.model)
  614. configuration = deepmerge(globalConfig, configuration);
  615. if (modelConfig instanceof File) {
  616. configuration.file = modelConfig;
  617. }
  618. } else {
  619. this.configuration.model = configuration;
  620. }
  621. this._isLoading = true;
  622. let model = this.modelLoader.load(configuration);
  623. this.lastUsedLoader = model.loader;
  624. model.onLoadErrorObservable.add((errorObject) => {
  625. this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  626. });
  627. model.onLoadProgressObservable.add((progressEvent) => {
  628. this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  629. });
  630. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  631. model.onLoadedObservable.add(() => {
  632. this._isLoading = false;
  633. });
  634. return model;
  635. }
  636. /**
  637. * load a model using the provided configuration.
  638. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  639. * If you want to attach to the observables of the model, use initModle instead.
  640. *
  641. * @param modelConfig the model configuration or URL to load.
  642. * @param clearScene Should the scene be cleared before loading the model
  643. * @returns a Promise the fulfills when the model finished loading successfully.
  644. */
  645. public loadModel(modelConfig: string | File | IModelConfiguration, clearScene: boolean = true): Promise<ViewerModel> {
  646. if (this._isLoading) {
  647. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  648. return Promise.reject("another model is curently being loaded.");
  649. }
  650. return Promise.resolve(this.sceneManager.scene).then((scene) => {
  651. if (!scene) return this.sceneManager.initScene(this.configuration.scene, this.configuration.optimizer);
  652. return scene;
  653. }).then(() => {
  654. let model = this.initModel(modelConfig, clearScene);
  655. return new Promise<ViewerModel>((resolve, reject) => {
  656. // at this point, configuration.model is an object, not a string
  657. model.onLoadedObservable.add(() => {
  658. resolve(model);
  659. });
  660. model.onLoadErrorObservable.add((error) => {
  661. reject(error);
  662. });
  663. });
  664. })
  665. }
  666. private _fpsTimeoutInterval: number;
  667. protected _initTelemetryEvents() {
  668. telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  669. telemetryManager.broadcast("Platform Details", this.baseId, {
  670. userAgent: navigator.userAgent,
  671. platform: navigator.platform
  672. });
  673. telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  674. let trackFPS: Function = () => {
  675. telemetryManager.broadcast("Current FPS", this.baseId, { fps: this.engine.getFps() });
  676. };
  677. trackFPS();
  678. // Track the FPS again after 60 seconds
  679. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  680. }
  681. /**
  682. * Injects all the spectre shader in the babylon shader store
  683. */
  684. protected _injectCustomShaders(): void {
  685. let customShaders = this.configuration.customShaders;
  686. // Inject all the spectre shader in the babylon shader store.
  687. if (!customShaders) {
  688. return;
  689. }
  690. if (customShaders.shaders) {
  691. Object.keys(customShaders.shaders).forEach(key => {
  692. // typescript considers a callback "unsafe", so... '!'
  693. Effect.ShadersStore[key] = customShaders!.shaders![key];
  694. });
  695. }
  696. if (customShaders.includes) {
  697. Object.keys(customShaders.includes).forEach(key => {
  698. // typescript considers a callback "unsafe", so... '!'
  699. Effect.IncludesShadersStore[key] = customShaders!.includes![key];
  700. });
  701. }
  702. }
  703. }