viewer.ts 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. import { viewerManager } from './viewerManager';
  2. import { TemplateManager } from './../templateManager';
  3. import { ConfigurationLoader } from './../configuration/loader';
  4. import { Skeleton, AnimationGroup, ParticleSystem, CubeTexture, Color3, IEnvironmentHelperOptions, EnvironmentHelper, Effect, SceneOptimizer, SceneOptimizerOptions, Observable, Engine, Scene, ArcRotateCamera, Vector3, SceneLoader, AbstractMesh, Mesh, HemisphericLight, Database, SceneLoaderProgressEvent, ISceneLoaderPlugin, ISceneLoaderPluginAsync, Quaternion, Light, ShadowLight, ShadowGenerator, Tags, AutoRotationBehavior, BouncingBehavior, FramingBehavior, Behavior, Tools } from 'babylonjs';
  5. import { ViewerConfiguration, ISceneConfiguration, ISceneOptimizerConfiguration, IObserversConfiguration, IModelConfiguration, ISkyboxConfiguration, IGroundConfiguration, ILightConfiguration, ICameraConfiguration } from '../configuration/configuration';
  6. import * as deepmerge from '../../assets/deepmerge.min.js';
  7. import { ViewerModel } from '../model/viewerModel';
  8. import { GroupModelAnimation } from '../model/modelAnimation';
  9. import { ModelLoader } from '../model/modelLoader';
  10. import { CameraBehavior } from '../interfaces';
  11. import { viewerGlobals } from '..';
  12. /**
  13. * The AbstractViewr is the center of Babylon's viewer.
  14. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  15. */
  16. export abstract class AbstractViewer {
  17. /**
  18. * The corresponsing template manager of this viewer.
  19. */
  20. public templateManager: TemplateManager;
  21. /**
  22. * Babylon Engine corresponding with this viewer
  23. */
  24. public engine: Engine;
  25. /**
  26. * The Babylon Scene of this viewer
  27. */
  28. public scene: Scene;
  29. /**
  30. * The camera used in this viewer
  31. */
  32. public camera: ArcRotateCamera;
  33. /**
  34. * Babylon's scene optimizer
  35. */
  36. public sceneOptimizer: SceneOptimizer;
  37. /**
  38. * The ID of this viewer. it will be generated randomly or use the HTML Element's ID.
  39. */
  40. public readonly baseId: string;
  41. /**
  42. * Models displayed in this viewer.
  43. */
  44. public models: Array<ViewerModel>;
  45. /**
  46. * The last loader used to load a model.
  47. */
  48. public lastUsedLoader: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  49. /**
  50. * The ModelLoader instance connected with this viewer.
  51. */
  52. public modelLoader: ModelLoader;
  53. public runRenderLoop: boolean = true;
  54. /**
  55. * the viewer configuration object
  56. */
  57. protected _configuration: ViewerConfiguration;
  58. /**
  59. * Babylon's environment helper of this viewer
  60. */
  61. public environmentHelper: EnvironmentHelper;
  62. //The following are configuration objects, default values.
  63. protected _defaultHighpTextureType: number;
  64. protected _shadowGeneratorBias: number;
  65. protected _defaultPipelineTextureType: number;
  66. /**
  67. * The maximum number of shadows supported by the curent viewer
  68. */
  69. protected _maxShadows: number;
  70. /**
  71. * is HDR supported?
  72. */
  73. private _hdrSupport: boolean;
  74. /**
  75. * is this viewer disposed?
  76. */
  77. protected _isDisposed: boolean = false;
  78. /**
  79. * Returns a boolean representing HDR support
  80. */
  81. public get isHdrSupported() {
  82. return this._hdrSupport;
  83. }
  84. // observables
  85. /**
  86. * Will notify when the scene was initialized
  87. */
  88. public onSceneInitObservable: Observable<Scene>;
  89. /**
  90. * will notify when the engine was initialized
  91. */
  92. public onEngineInitObservable: Observable<Engine>;
  93. /**
  94. * Will notify when a new model was added to the scene.
  95. * Note that added does not neccessarily mean loaded!
  96. */
  97. public onModelAddedObservable: Observable<ViewerModel>;
  98. /**
  99. * will notify after every model load
  100. */
  101. public onModelLoadedObservable: Observable<ViewerModel>;
  102. /**
  103. * will notify when any model notify of progress
  104. */
  105. public onModelLoadProgressObservable: Observable<SceneLoaderProgressEvent>;
  106. /**
  107. * will notify when any model load failed.
  108. */
  109. public onModelLoadErrorObservable: Observable<{ message: string; exception: any }>;
  110. /**
  111. * Will notify when a model was removed from the scene;
  112. */
  113. public onModelRemovedObservable: Observable<ViewerModel>;
  114. /**
  115. * will notify when a new loader was initialized.
  116. * Used mainly to know when a model starts loading.
  117. */
  118. public onLoaderInitObservable: Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>;
  119. /**
  120. * Observers registered here will be executed when the entire load process has finished.
  121. */
  122. public onInitDoneObservable: Observable<AbstractViewer>;
  123. /**
  124. * Functions added to this observable will be executed on each frame rendered.
  125. */
  126. public onFrameRenderedObservable: Observable<AbstractViewer>;
  127. /**
  128. * The canvas associated with this viewer
  129. */
  130. protected _canvas: HTMLCanvasElement;
  131. /**
  132. * The (single) canvas of this viewer
  133. */
  134. public get canvas(): HTMLCanvasElement {
  135. return this._canvas;
  136. }
  137. /**
  138. * registered onBeforeRender functions.
  139. * This functions are also registered at the native scene. The reference can be used to unregister them.
  140. */
  141. protected _registeredOnBeforeRenderFunctions: Array<() => void>;
  142. /**
  143. * The configuration loader of this viewer
  144. */
  145. protected _configurationLoader: ConfigurationLoader;
  146. constructor(public containerElement: HTMLElement, initialConfiguration: ViewerConfiguration = {}) {
  147. // if exists, use the container id. otherwise, generate a random string.
  148. if (containerElement.id) {
  149. this.baseId = containerElement.id;
  150. } else {
  151. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  152. }
  153. this.onSceneInitObservable = new Observable();
  154. this.onEngineInitObservable = new Observable();
  155. this.onModelLoadedObservable = new Observable();
  156. this.onModelLoadProgressObservable = new Observable();
  157. this.onModelLoadErrorObservable = new Observable();
  158. this.onModelAddedObservable = new Observable();
  159. this.onModelRemovedObservable = new Observable();
  160. this.onInitDoneObservable = new Observable();
  161. this.onLoaderInitObservable = new Observable();
  162. this.onFrameRenderedObservable = new Observable();
  163. this._registeredOnBeforeRenderFunctions = [];
  164. this.models = [];
  165. this.modelLoader = new ModelLoader(this);
  166. // add this viewer to the viewer manager
  167. viewerManager.addViewer(this);
  168. // create a new template manager. TODO - singleton?
  169. this.templateManager = new TemplateManager(containerElement);
  170. this._prepareContainerElement();
  171. // extend the configuration
  172. this._configurationLoader = new ConfigurationLoader();
  173. this._configurationLoader.loadConfiguration(initialConfiguration, (configuration) => {
  174. this._configuration = deepmerge(this._configuration || {}, configuration);
  175. if (this._configuration.observers) {
  176. this._configureObservers(this._configuration.observers);
  177. }
  178. //this.updateConfiguration(configuration);
  179. // initialize the templates
  180. let templateConfiguration = this._configuration.templates || {};
  181. this.templateManager.initTemplate(templateConfiguration);
  182. // when done, execute onTemplatesLoaded()
  183. this.templateManager.onAllLoaded.add(() => {
  184. let canvas = this.templateManager.getCanvas();
  185. if (canvas) {
  186. this._canvas = canvas;
  187. }
  188. this._onTemplateLoaded();
  189. });
  190. });
  191. }
  192. /**
  193. * The viewer's version corresponds to the engine's version
  194. */
  195. public static readonly Version = Engine.Version;
  196. /**
  197. * get the baseId of this viewer
  198. */
  199. public getBaseId(): string {
  200. return this.baseId;
  201. }
  202. /**
  203. * Do we have a canvas to render on, and is it a part of the scene
  204. */
  205. public isCanvasInDOM(): boolean {
  206. return !!this._canvas && !!this._canvas.parentElement;
  207. }
  208. /**
  209. * Is the engine currently set to rende even when the page is in background
  210. */
  211. public get renderInBackground() {
  212. return this.engine.renderEvenInBackground;
  213. }
  214. /**
  215. * Set the viewer's background rendering flag.
  216. */
  217. public set renderInBackground(value: boolean) {
  218. this.engine.renderEvenInBackground = value;
  219. }
  220. /**
  221. * force resizing the engine.
  222. */
  223. public forceResize() {
  224. this._resize();
  225. }
  226. /**
  227. * The resize function that will be registered with the window object
  228. */
  229. protected _resize = (): void => {
  230. // Only resize if Canvas is in the DOM
  231. if (!this.isCanvasInDOM()) {
  232. return;
  233. }
  234. if (this.canvas.clientWidth <= 0 || this.canvas.clientHeight <= 0) {
  235. return;
  236. }
  237. this.engine.resize();
  238. }
  239. /**
  240. * Force a single render loop execution.
  241. */
  242. public forceRender() {
  243. this._render(true);
  244. }
  245. /**
  246. * render loop that will be executed by the engine
  247. */
  248. protected _render = (force: boolean = false): void => {
  249. if (force || (this.runRenderLoop && this.scene && this.scene.activeCamera)) {
  250. this.scene.render();
  251. this.onFrameRenderedObservable.notifyObservers(this);
  252. }
  253. }
  254. /**
  255. * Update the current viewer configuration with new values.
  256. * Only provided information will be updated, old configuration values will be kept.
  257. * If this.configuration was manually changed, you can trigger this function with no parameters,
  258. * and the entire configuration will be updated.
  259. * @param newConfiguration
  260. */
  261. public updateConfiguration(newConfiguration: Partial<ViewerConfiguration> = this._configuration) {
  262. // update this.configuration with the new data
  263. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  264. // update scene configuration
  265. if (newConfiguration.scene) {
  266. this._configureScene(newConfiguration.scene);
  267. }
  268. // optimizer
  269. if (newConfiguration.optimizer) {
  270. this._configureOptimizer(newConfiguration.optimizer);
  271. }
  272. // observers in configuration
  273. if (newConfiguration.observers) {
  274. this._configureObservers(newConfiguration.observers);
  275. }
  276. // configure model
  277. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  278. this._configureModel(newConfiguration.model);
  279. }
  280. // lights
  281. if (newConfiguration.lights) {
  282. this._configureLights(newConfiguration.lights);
  283. }
  284. // environment
  285. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  286. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  287. }
  288. // camera
  289. if (newConfiguration.camera) {
  290. this._configureCamera(newConfiguration.camera);
  291. }
  292. }
  293. protected _configureEnvironment(skyboxConifguration?: ISkyboxConfiguration | boolean, groundConfiguration?: IGroundConfiguration | boolean) {
  294. if (!skyboxConifguration && !groundConfiguration) {
  295. if (this.environmentHelper) {
  296. this.environmentHelper.dispose();
  297. delete this.environmentHelper;
  298. };
  299. return Promise.resolve(this.scene);
  300. }
  301. const options: Partial<IEnvironmentHelperOptions> = {
  302. createGround: !!groundConfiguration,
  303. createSkybox: !!skyboxConifguration,
  304. setupImageProcessing: false // will be done at the scene level!
  305. };
  306. if (groundConfiguration) {
  307. let groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  308. let groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  309. if (groundSize) {
  310. options.groundSize = groundSize;
  311. }
  312. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  313. if (groundConfig.shadowLevel !== undefined) {
  314. options.groundShadowLevel = groundConfig.shadowLevel;
  315. }
  316. options.enableGroundMirror = !!groundConfig.mirror;
  317. if (groundConfig.texture) {
  318. options.groundTexture = groundConfig.texture;
  319. }
  320. if (groundConfig.color) {
  321. options.groundColor = new Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b)
  322. }
  323. if (groundConfig.opacity !== undefined) {
  324. options.groundOpacity = groundConfig.opacity;
  325. }
  326. if (groundConfig.mirror) {
  327. options.enableGroundMirror = true;
  328. // to prevent undefines
  329. if (typeof groundConfig.mirror === "object") {
  330. if (groundConfig.mirror.amount !== undefined)
  331. options.groundMirrorAmount = groundConfig.mirror.amount;
  332. if (groundConfig.mirror.sizeRatio !== undefined)
  333. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  334. if (groundConfig.mirror.blurKernel !== undefined)
  335. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  336. if (groundConfig.mirror.fresnelWeight !== undefined)
  337. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  338. if (groundConfig.mirror.fallOffDistance !== undefined)
  339. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  340. if (this._defaultPipelineTextureType !== undefined)
  341. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  342. }
  343. }
  344. }
  345. let postInitSkyboxMaterial = false;
  346. if (skyboxConifguration) {
  347. let conf = skyboxConifguration === true ? {} : skyboxConifguration;
  348. if (conf.material && conf.material.imageProcessingConfiguration) {
  349. options.setupImageProcessing = false; // will be configured later manually.
  350. }
  351. let skyboxSize = conf.scale;
  352. if (skyboxSize) {
  353. options.skyboxSize = skyboxSize;
  354. }
  355. options.sizeAuto = !options.skyboxSize;
  356. if (conf.color) {
  357. options.skyboxColor = new Color3(conf.color.r, conf.color.g, conf.color.b)
  358. }
  359. if (conf.cubeTexture && conf.cubeTexture.url) {
  360. if (typeof conf.cubeTexture.url === "string") {
  361. options.skyboxTexture = conf.cubeTexture.url;
  362. } else {
  363. // init later!
  364. postInitSkyboxMaterial = true;
  365. }
  366. }
  367. if (conf.material && conf.material.imageProcessingConfiguration) {
  368. postInitSkyboxMaterial = true;
  369. }
  370. }
  371. options.setupImageProcessing = false; // TMP
  372. if (!this.environmentHelper) {
  373. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  374. } else {
  375. // there might be a new scene! we need to dispose.
  376. // get the scene used by the envHelper
  377. let scene: Scene = this.environmentHelper.rootMesh.getScene();
  378. // is it a different scene? Oh no!
  379. if (scene !== this.scene) {
  380. this.environmentHelper.dispose();
  381. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  382. } else {
  383. this.environmentHelper.updateOptions(options)!;
  384. }
  385. }
  386. if (postInitSkyboxMaterial) {
  387. let skyboxMaterial = this.environmentHelper.skyboxMaterial;
  388. if (skyboxMaterial) {
  389. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  390. this._extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  391. }
  392. }
  393. }
  394. }
  395. /**
  396. * internally configure the scene using the provided configuration.
  397. * The scene will not be recreated, but just updated.
  398. * @param sceneConfig the (new) scene configuration
  399. */
  400. protected _configureScene(sceneConfig: ISceneConfiguration) {
  401. // sanity check!
  402. if (!this.scene) {
  403. return;
  404. }
  405. if (sceneConfig.debug) {
  406. this.scene.debugLayer.show();
  407. } else {
  408. if (this.scene.debugLayer.isVisible()) {
  409. this.scene.debugLayer.hide();
  410. }
  411. }
  412. if (sceneConfig.clearColor) {
  413. let cc = sceneConfig.clearColor;
  414. let oldcc = this.scene.clearColor;
  415. if (cc.r !== undefined) {
  416. oldcc.r = cc.r;
  417. }
  418. if (cc.g !== undefined) {
  419. oldcc.g = cc.g
  420. }
  421. if (cc.b !== undefined) {
  422. oldcc.b = cc.b
  423. }
  424. if (cc.a !== undefined) {
  425. oldcc.a = cc.a
  426. }
  427. }
  428. // image processing configuration - optional.
  429. if (sceneConfig.imageProcessingConfiguration) {
  430. this._extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  431. }
  432. if (sceneConfig.environmentTexture) {
  433. if (this.scene.environmentTexture) {
  434. this.scene.environmentTexture.dispose();
  435. }
  436. const environmentTexture = CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  437. this.scene.environmentTexture = environmentTexture;
  438. }
  439. if (sceneConfig.autoRotate) {
  440. this.camera.useAutoRotationBehavior = true;
  441. }
  442. }
  443. /**
  444. * Configure the scene optimizer.
  445. * The existing scene optimizer will be disposed and a new one will be created.
  446. * @param optimizerConfig the (new) optimizer configuration
  447. */
  448. protected _configureOptimizer(optimizerConfig: ISceneOptimizerConfiguration | boolean) {
  449. if (typeof optimizerConfig === 'boolean') {
  450. if (this.sceneOptimizer) {
  451. this.sceneOptimizer.stop();
  452. this.sceneOptimizer.dispose();
  453. delete this.sceneOptimizer;
  454. }
  455. if (optimizerConfig) {
  456. this.sceneOptimizer = new SceneOptimizer(this.scene);
  457. this.sceneOptimizer.start();
  458. }
  459. } else {
  460. let optimizerOptions: SceneOptimizerOptions = new SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  461. // check for degradation
  462. if (optimizerConfig.degradation) {
  463. switch (optimizerConfig.degradation) {
  464. case "low":
  465. optimizerOptions = SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  466. break;
  467. case "moderate":
  468. optimizerOptions = SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  469. break;
  470. case "hight":
  471. optimizerOptions = SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  472. break;
  473. }
  474. }
  475. if (this.sceneOptimizer) {
  476. this.sceneOptimizer.stop();
  477. this.sceneOptimizer.dispose()
  478. }
  479. this.sceneOptimizer = new SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  480. this.sceneOptimizer.start();
  481. }
  482. }
  483. /**
  484. * this is used to register native functions using the configuration object.
  485. * This will configure the observers.
  486. * @param observersConfiguration observers configuration
  487. */
  488. protected _configureObservers(observersConfiguration: IObserversConfiguration) {
  489. if (observersConfiguration.onEngineInit) {
  490. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  491. } else {
  492. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers!.onEngineInit) {
  493. this.onEngineInitObservable.removeCallback(window[this._configuration.observers!.onEngineInit!]);
  494. }
  495. }
  496. if (observersConfiguration.onSceneInit) {
  497. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  498. } else {
  499. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers!.onSceneInit) {
  500. this.onSceneInitObservable.removeCallback(window[this._configuration.observers!.onSceneInit!]);
  501. }
  502. }
  503. if (observersConfiguration.onModelLoaded) {
  504. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  505. } else {
  506. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers!.onModelLoaded) {
  507. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers!.onModelLoaded!]);
  508. }
  509. }
  510. }
  511. /**
  512. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  513. * @param cameraConfig the new camera configuration
  514. * @param model optionally use the model to configure the camera.
  515. */
  516. protected _configureCamera(cameraConfig: ICameraConfiguration = {}, model?: ViewerModel) {
  517. let focusMeshes = model ? model.meshes : this.scene.meshes;
  518. if (!this.scene.activeCamera) {
  519. this.scene.createDefaultCamera(true, true, true);
  520. this.camera = <ArcRotateCamera>this.scene.activeCamera!;
  521. }
  522. if (cameraConfig.position) {
  523. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  524. }
  525. if (cameraConfig.rotation) {
  526. this.camera.rotationQuaternion = new Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0)
  527. }
  528. this._extendClassWithConfig(this.camera, cameraConfig);
  529. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  530. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  531. if (cameraConfig.behaviors) {
  532. for (let name in cameraConfig.behaviors) {
  533. this._setCameraBehavior(cameraConfig.behaviors[name], focusMeshes);
  534. }
  535. };
  536. const sceneExtends = this.scene.getWorldExtends((mesh) => {
  537. return !this.environmentHelper || (mesh !== this.environmentHelper.ground && mesh !== this.environmentHelper.rootMesh && mesh !== this.environmentHelper.skybox);
  538. });
  539. const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  540. const sceneDiagonalLenght = sceneDiagonal.length();
  541. if (isFinite(sceneDiagonalLenght))
  542. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  543. }
  544. /**
  545. * configure the lights.
  546. *
  547. * @param lightsConfiguration the (new) light(s) configuration
  548. * @param model optionally use the model to configure the camera.
  549. */
  550. protected _configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean } = {}, model?: ViewerModel) {
  551. let focusMeshes = model ? model.meshes : this.scene.meshes;
  552. // sanity check!
  553. if (!Object.keys(lightsConfiguration).length) return;
  554. let lightsAvailable: Array<string> = this.scene.lights.map(light => light.name);
  555. // compare to the global (!) configuration object and dispose unneeded:
  556. let lightsToConfigure = Object.keys(this._configuration.lights || []);
  557. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  558. lightsAvailable.forEach(lName => {
  559. if (lightsToConfigure.indexOf(lName) === -1) {
  560. this.scene.getLightByName(lName)!.dispose()
  561. }
  562. });
  563. }
  564. Object.keys(lightsConfiguration).forEach((name, idx) => {
  565. let lightConfig: ILightConfiguration = { type: 0 };
  566. if (typeof lightsConfiguration[name] === 'object') {
  567. lightConfig = <ILightConfiguration>lightsConfiguration[name];
  568. }
  569. lightConfig.name = name;
  570. let light: Light;
  571. // light is not already available
  572. if (lightsAvailable.indexOf(name) === -1) {
  573. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  574. if (!constructor) return;
  575. light = constructor();
  576. } else {
  577. // available? get it from the scene
  578. light = <Light>this.scene.getLightByName(name);
  579. lightsAvailable = lightsAvailable.filter(ln => ln !== name);
  580. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  581. light.dispose();
  582. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  583. if (!constructor) return;
  584. light = constructor();
  585. }
  586. }
  587. // if config set the light to false, dispose it.
  588. if (lightsConfiguration[name] === false) {
  589. light.dispose();
  590. return;
  591. }
  592. //enabled
  593. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  594. light.setEnabled(enabled);
  595. this._extendClassWithConfig(light, lightConfig);
  596. //position. Some lights don't support shadows
  597. if (light instanceof ShadowLight) {
  598. if (lightConfig.target) {
  599. if (light.setDirectionToTarget) {
  600. let target = Vector3.Zero().copyFrom(lightConfig.target as Vector3);
  601. light.setDirectionToTarget(target);
  602. }
  603. } else if (lightConfig.direction) {
  604. let direction = Vector3.Zero().copyFrom(lightConfig.direction as Vector3);
  605. light.direction = direction;
  606. }
  607. let shadowGenerator = light.getShadowGenerator();
  608. if (lightConfig.shadowEnabled && this._maxShadows) {
  609. if (!shadowGenerator) {
  610. shadowGenerator = new ShadowGenerator(512, light);
  611. // TODO blur kernel definition
  612. }
  613. this._extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  614. // add the focues meshes to the shadow list
  615. let shadownMap = shadowGenerator.getShadowMap();
  616. if (!shadownMap) return;
  617. let renderList = shadownMap.renderList;
  618. for (var index = 0; index < focusMeshes.length; index++) {
  619. if (Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  620. renderList && renderList.push(focusMeshes[index]);
  621. }
  622. }
  623. } else if (shadowGenerator) {
  624. shadowGenerator.dispose();
  625. }
  626. }
  627. });
  628. }
  629. /**
  630. * configure all models using the configuration.
  631. * @param modelConfiguration the configuration to use to reconfigure the models
  632. */
  633. protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  634. this.models.forEach(model => {
  635. model.updateConfiguration(modelConfiguration);
  636. })
  637. }
  638. /**
  639. * Dispoe the entire viewer including the scene and the engine
  640. */
  641. public dispose() {
  642. if (this._isDisposed) {
  643. return;
  644. }
  645. window.removeEventListener('resize', this._resize);
  646. if (this.sceneOptimizer) {
  647. this.sceneOptimizer.stop();
  648. this.sceneOptimizer.dispose();
  649. }
  650. if (this.environmentHelper) {
  651. this.environmentHelper.dispose();
  652. }
  653. if (this._configurationLoader) {
  654. this._configurationLoader.dispose();
  655. }
  656. //observers
  657. this.onEngineInitObservable.clear();
  658. delete this.onEngineInitObservable;
  659. this.onInitDoneObservable.clear();
  660. delete this.onInitDoneObservable;
  661. this.onLoaderInitObservable.clear();
  662. delete this.onLoaderInitObservable;
  663. this.onModelLoadedObservable.clear();
  664. delete this.onModelLoadedObservable;
  665. this.onModelLoadErrorObservable.clear();
  666. delete this.onModelLoadErrorObservable;
  667. this.onModelLoadProgressObservable.clear();
  668. delete this.onModelLoadProgressObservable;
  669. this.onSceneInitObservable.clear();
  670. delete this.onSceneInitObservable;
  671. this.onFrameRenderedObservable.clear();
  672. delete this.onFrameRenderedObservable;
  673. if (this.scene.activeCamera) {
  674. this.scene.activeCamera.detachControl(this.canvas);
  675. }
  676. this.modelLoader.dispose();
  677. this.models.forEach(model => {
  678. model.dispose();
  679. });
  680. this.models.length = 0;
  681. this.scene.dispose();
  682. this.engine.dispose();
  683. this.templateManager.dispose();
  684. viewerManager.removeViewer(this);
  685. this._isDisposed = true;
  686. }
  687. /**
  688. * This will prepare the container element for the viewer
  689. */
  690. protected abstract _prepareContainerElement();
  691. /**
  692. * This function will execute when the HTML templates finished initializing.
  693. * It should initialize the engine and continue execution.
  694. *
  695. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  696. */
  697. protected _onTemplatesLoaded(): Promise<AbstractViewer> {
  698. return Promise.resolve(this);
  699. }
  700. /**
  701. * This will force the creation of an engine and a scene.
  702. * It will also load a model if preconfigured.
  703. * But first - it will load the extendible onTemplateLoaded()!
  704. */
  705. private _onTemplateLoaded(): Promise<AbstractViewer> {
  706. return this._onTemplatesLoaded().then(() => {
  707. let modelConfiguration = this._configuration.model;
  708. return this._initEngine().then((engine) => {
  709. return this.onEngineInitObservable.notifyObserversWithPromise(engine);
  710. }).then(() => {
  711. if (modelConfiguration) {
  712. return this.loadModel(modelConfiguration).catch(e => { }).then(() => { return this.scene });
  713. } else {
  714. return this.scene || this._initScene();
  715. }
  716. }).then((scene) => {
  717. return this.onSceneInitObservable.notifyObserversWithPromise(scene);
  718. }).then(() => {
  719. return this.onInitDoneObservable.notifyObserversWithPromise(this);
  720. }).catch(e => {
  721. Tools.Warn(e.toString());
  722. return this;
  723. });
  724. })
  725. }
  726. /**
  727. * Initialize the engine. Retruns a promise in case async calls are needed.
  728. *
  729. * @protected
  730. * @returns {Promise<Engine>}
  731. * @memberof Viewer
  732. */
  733. protected _initEngine(): Promise<Engine> {
  734. // init custom shaders
  735. this._injectCustomShaders();
  736. let canvasElement = this.templateManager.getCanvas();
  737. if (!canvasElement) {
  738. return Promise.reject('Canvas element not found!');
  739. }
  740. let config = this._configuration.engine || {};
  741. // TDO enable further configuration
  742. // check for webgl2 support, force-disable if needed.
  743. if (viewerGlobals.disableWebGL2Support) {
  744. config.engineOptions = config.engineOptions || {};
  745. config.engineOptions.disableWebGL2Support = true;
  746. }
  747. this.engine = new Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  748. // Disable manifest checking
  749. Database.IDBStorageEnabled = false;
  750. if (!config.disableResize) {
  751. window.addEventListener('resize', this._resize);
  752. }
  753. this.engine.runRenderLoop(this._render);
  754. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  755. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  756. this.engine.setHardwareScalingLevel(scale);
  757. }
  758. // set hardware limitations for scene initialization
  759. this._handleHardwareLimitations();
  760. return Promise.resolve(this.engine);
  761. }
  762. /**
  763. * initialize the scene. Calling thsi function again will dispose the old scene, if exists.
  764. */
  765. protected _initScene(): Promise<Scene> {
  766. // if the scen exists, dispose it.
  767. if (this.scene) {
  768. this.scene.dispose();
  769. }
  770. // create a new scene
  771. this.scene = new Scene(this.engine);
  772. // make sure there is a default camera and light.
  773. this.scene.createDefaultLight(true);
  774. if (this._configuration.scene) {
  775. this._configureScene(this._configuration.scene);
  776. // Scene optimizer
  777. if (this._configuration.optimizer) {
  778. this._configureOptimizer(this._configuration.optimizer);
  779. }
  780. }
  781. return Promise.resolve(this.scene);
  782. }
  783. private _isLoading: boolean;
  784. private _nextLoading: Function;
  785. /**
  786. * Initialize a model loading. The returns object (a ViewerModel object) will be loaded in the background.
  787. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  788. *
  789. * @param modelConfig model configuration to use when loading the model.
  790. * @param clearScene should the scene be cleared before loading this model
  791. * @returns a ViewerModel object that is not yet fully loaded.
  792. */
  793. public initModel(modelConfig: string | IModelConfiguration, clearScene: boolean = true): ViewerModel {
  794. let modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  795. if (!modelUrl) {
  796. throw new Error("no model configuration provided");
  797. }
  798. if (clearScene) {
  799. this.models.forEach(m => m.dispose());
  800. this.models.length = 0;
  801. }
  802. let configuration: IModelConfiguration;
  803. if (typeof modelConfig === 'string') {
  804. configuration = {
  805. url: modelConfig
  806. }
  807. } else {
  808. configuration = modelConfig
  809. }
  810. //merge the configuration for future models:
  811. if (this._configuration.model && typeof this._configuration.model === 'object') {
  812. deepmerge(this._configuration.model, configuration)
  813. } else {
  814. this._configuration.model = configuration;
  815. }
  816. this._isLoading = true;
  817. let model = this.modelLoader.load(configuration);
  818. this.lastUsedLoader = model.loader;
  819. model.onLoadErrorObservable.add((errorObject) => {
  820. this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  821. });
  822. model.onLoadProgressObservable.add((progressEvent) => {
  823. this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  824. });
  825. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  826. model.onLoadedObservable.add(() => {
  827. Promise.resolve().then(() => {
  828. this._configureLights(this._configuration.lights, model);
  829. if (this._configuration.camera || !this.scene.activeCamera) {
  830. this._configureCamera(this._configuration.camera || {}, model);
  831. }
  832. return this._initEnvironment(model);
  833. }).then(() => {
  834. this._isLoading = false;
  835. return this.onModelLoadedObservable.notifyObserversWithPromise(model);
  836. });
  837. });
  838. return model;
  839. }
  840. /**
  841. * load a model using the provided configuration
  842. *
  843. * @param modelConfig the model configuration or URL to load.
  844. * @param clearScene Should the scene be cleared before loading the model
  845. * @returns a Promise the fulfills when the model finished loading successfully.
  846. */
  847. public loadModel(modelConfig: string | IModelConfiguration, clearScene: boolean = true): Promise<ViewerModel> {
  848. if (this._isLoading) {
  849. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  850. return Promise.reject("another model is curently being loaded.");
  851. }
  852. return Promise.resolve(this.scene).then((scene) => {
  853. if (!scene) return this._initScene();
  854. return scene;
  855. }).then(() => {
  856. let model = this.initModel(modelConfig, clearScene);
  857. return new Promise<ViewerModel>((resolve, reject) => {
  858. // at this point, configuration.model is an object, not a string
  859. model.onLoadedObservable.add(() => {
  860. resolve(model);
  861. });
  862. model.onLoadErrorObservable.add((error) => {
  863. reject(error);
  864. });
  865. });
  866. })
  867. }
  868. /**
  869. * initialize the environment for a specific model.
  870. * Per default it will use the viewer'S configuration.
  871. * @param model the model to use to configure the environment.
  872. * @returns a Promise that will resolve when the configuration is done.
  873. */
  874. protected _initEnvironment(model?: ViewerModel): Promise<Scene> {
  875. this._configureEnvironment(this._configuration.skybox, this._configuration.ground);
  876. return Promise.resolve(this.scene);
  877. }
  878. /**
  879. * Alters render settings to reduce features based on hardware feature limitations
  880. * @param enableHDR Allows the viewer to run in HDR mode.
  881. */
  882. protected _handleHardwareLimitations(enableHDR = true) {
  883. //flip rendering settings switches based on hardware support
  884. let maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  885. let maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  886. //shadows are disabled if there's not enough varyings for a single shadow
  887. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  888. this._maxShadows = 0;
  889. } else {
  890. this._maxShadows = 3;
  891. }
  892. //can we render to any >= 16-bit targets (required for HDR)
  893. let caps = this.engine.getCaps();
  894. let linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  895. let linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  896. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  897. if (linearHalfFloatTargets) {
  898. this._defaultHighpTextureType = Engine.TEXTURETYPE_HALF_FLOAT;
  899. this._shadowGeneratorBias = 0.002;
  900. } else if (linearFloatTargets) {
  901. this._defaultHighpTextureType = Engine.TEXTURETYPE_FLOAT;
  902. this._shadowGeneratorBias = 0.001;
  903. } else {
  904. this._defaultHighpTextureType = Engine.TEXTURETYPE_UNSIGNED_INT;
  905. this._shadowGeneratorBias = 0.001;
  906. }
  907. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : Engine.TEXTURETYPE_UNSIGNED_INT;
  908. }
  909. /**
  910. * Injects all the spectre shader in the babylon shader store
  911. */
  912. protected _injectCustomShaders(): void {
  913. let customShaders = this._configuration.customShaders;
  914. // Inject all the spectre shader in the babylon shader store.
  915. if (!customShaders) {
  916. return;
  917. }
  918. if (customShaders.shaders) {
  919. Object.keys(customShaders.shaders).forEach(key => {
  920. // typescript considers a callback "unsafe", so... '!'
  921. Effect.ShadersStore[key] = customShaders!.shaders![key];
  922. });
  923. }
  924. if (customShaders.includes) {
  925. Object.keys(customShaders.includes).forEach(key => {
  926. // typescript considers a callback "unsafe", so... '!'
  927. Effect.IncludesShadersStore[key] = customShaders!.includes![key];
  928. });
  929. }
  930. }
  931. /**
  932. * This will extend an object with configuration values.
  933. * What it practically does it take the keys from the configuration and set them on the object.
  934. * I the configuration is a tree, it will traverse into the tree.
  935. * @param object the object to extend
  936. * @param config the configuration object that will extend the object
  937. */
  938. protected _extendClassWithConfig(object: any, config: any) {
  939. if (!config) return;
  940. Object.keys(config).forEach(key => {
  941. if (key in object && typeof object[key] !== 'function') {
  942. // if (typeof object[key] === 'function') return;
  943. // if it is an object, iterate internally until reaching basic types
  944. if (typeof object[key] === 'object') {
  945. this._extendClassWithConfig(object[key], config[key]);
  946. } else {
  947. if (config[key] !== undefined) {
  948. object[key] = config[key];
  949. }
  950. }
  951. }
  952. });
  953. }
  954. private _setCameraBehavior(behaviorConfig: number | {
  955. type: number;
  956. [propName: string]: any;
  957. }, payload: any) {
  958. let behavior: Behavior<ArcRotateCamera> | null;
  959. let type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  960. let config: { [propName: string]: any } = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  961. // constructing behavior
  962. switch (type) {
  963. case CameraBehavior.AUTOROTATION:
  964. this.camera.useAutoRotationBehavior = true;
  965. behavior = this.camera.autoRotationBehavior;
  966. break;
  967. case CameraBehavior.BOUNCING:
  968. this.camera.useBouncingBehavior = true;
  969. behavior = this.camera.bouncingBehavior;
  970. break;
  971. case CameraBehavior.FRAMING:
  972. this.camera.useFramingBehavior = true;
  973. behavior = this.camera.framingBehavior;
  974. break;
  975. default:
  976. behavior = null;
  977. break;
  978. }
  979. if (behavior) {
  980. if (typeof behaviorConfig === "object") {
  981. this._extendClassWithConfig(behavior, behaviorConfig);
  982. }
  983. }
  984. // post attach configuration. Some functionalities require the attached camera.
  985. switch (type) {
  986. case CameraBehavior.AUTOROTATION:
  987. break;
  988. case CameraBehavior.BOUNCING:
  989. break;
  990. case CameraBehavior.FRAMING:
  991. if (config.zoomOnBoundingInfo) {
  992. //payload is an array of meshes
  993. let meshes = <Array<AbstractMesh>>payload;
  994. let bounding = meshes[0].getHierarchyBoundingVectors();
  995. (<FramingBehavior>behavior).zoomOnBoundingInfo(bounding.min, bounding.max);
  996. }
  997. break;
  998. }
  999. }
  1000. }