viewer.ts 32 KB

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