viewer.ts 31 KB

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