viewer.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. import { viewerManager } from './viewerManager';
  2. import { TemplateManager } from './../templateManager';
  3. import configurationLoader from './../configuration/loader';
  4. import { 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 } 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 { CameraBehavior } from 'src/interfaces';
  8. import { ViewerModel } from '../model/viewerModel';
  9. export abstract class AbstractViewer {
  10. public templateManager: TemplateManager;
  11. public engine: Engine;
  12. public scene: Scene;
  13. public camera: ArcRotateCamera;
  14. public sceneOptimizer: SceneOptimizer;
  15. public baseId: string;
  16. public models: Array<ViewerModel>;
  17. /**
  18. * The last loader used to load a model.
  19. */
  20. public lastUsedLoader: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  21. protected configuration: ViewerConfiguration;
  22. public environmentHelper: EnvironmentHelper;
  23. protected defaultHighpTextureType: number;
  24. protected shadowGeneratorBias: number;
  25. protected defaultPipelineTextureType: number;
  26. protected maxShadows: number;
  27. private _hdrSupport: boolean;
  28. public get isHdrSupported() {
  29. return this._hdrSupport;
  30. }
  31. // observables
  32. public onSceneInitObservable: Observable<Scene>;
  33. public onEngineInitObservable: Observable<Engine>;
  34. public onModelLoadedObservable: Observable<ViewerModel>;
  35. public onModelLoadProgressObservable: Observable<SceneLoaderProgressEvent>;
  36. public onModelLoadErrorObservable: Observable<{ message: string; exception: any }>;
  37. public onLoaderInitObservable: Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>;
  38. public onInitDoneObservable: Observable<AbstractViewer>;
  39. public canvas: HTMLCanvasElement;
  40. protected registeredOnBeforerenderFunctions: Array<() => void>;
  41. constructor(public containerElement: HTMLElement, initialConfiguration: ViewerConfiguration = {}) {
  42. // if exists, use the container id. otherwise, generate a random string.
  43. if (containerElement.id) {
  44. this.baseId = containerElement.id;
  45. } else {
  46. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  47. }
  48. this.onSceneInitObservable = new Observable();
  49. this.onEngineInitObservable = new Observable();
  50. this.onModelLoadedObservable = new Observable();
  51. this.onModelLoadProgressObservable = new Observable();
  52. this.onModelLoadErrorObservable = new Observable();
  53. this.onInitDoneObservable = new Observable();
  54. this.onLoaderInitObservable = new Observable();
  55. this.registeredOnBeforerenderFunctions = [];
  56. this.models = [];
  57. // add this viewer to the viewer manager
  58. viewerManager.addViewer(this);
  59. // create a new template manager. TODO - singleton?
  60. this.templateManager = new TemplateManager(containerElement);
  61. this.prepareContainerElement();
  62. // extend the configuration
  63. configurationLoader.loadConfiguration(initialConfiguration, (configuration) => {
  64. this.configuration = deepmerge(this.configuration || {}, configuration);
  65. if (this.configuration.observers) {
  66. this.configureObservers(this.configuration.observers);
  67. }
  68. //this.updateConfiguration(configuration);
  69. // initialize the templates
  70. let templateConfiguration = this.configuration.templates || {};
  71. this.templateManager.initTemplate(templateConfiguration);
  72. // when done, execute onTemplatesLoaded()
  73. this.templateManager.onAllLoaded.add(() => {
  74. let canvas = this.templateManager.getCanvas();
  75. if (canvas) {
  76. this.canvas = canvas;
  77. }
  78. this._onTemplateLoaded();
  79. });
  80. });
  81. //this.onModelLoadedObservable.add(this.initEnvironment.bind(this));
  82. }
  83. public getBaseId(): string {
  84. return this.baseId;
  85. }
  86. public isCanvasInDOM(): boolean {
  87. return !!this.canvas && !!this.canvas.parentElement;
  88. }
  89. protected resize = (): void => {
  90. // Only resize if Canvas is in the DOM
  91. if (!this.isCanvasInDOM()) {
  92. return;
  93. }
  94. if (this.canvas.clientWidth <= 0 || this.canvas.clientHeight <= 0) {
  95. return;
  96. }
  97. this.engine.resize();
  98. }
  99. protected render = (): void => {
  100. this.scene && this.scene.activeCamera && this.scene.render();
  101. }
  102. /**
  103. * Update the current viewer configuration with new values.
  104. * Only provided information will be updated, old configuration values will be kept.
  105. * If this.configuration was manually changed, you can trigger this function with no parameters,
  106. * and the entire configuration will be updated.
  107. * @param newConfiguration
  108. */
  109. public updateConfiguration(newConfiguration: Partial<ViewerConfiguration> = this.configuration) {
  110. // update this.configuration with the new data
  111. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  112. // update scene configuration
  113. if (newConfiguration.scene) {
  114. this.configureScene(newConfiguration.scene);
  115. }
  116. // optimizer
  117. if (newConfiguration.optimizer) {
  118. this.configureOptimizer(newConfiguration.optimizer);
  119. }
  120. // observers in configuration
  121. if (newConfiguration.observers) {
  122. this.configureObservers(newConfiguration.observers);
  123. }
  124. // configure model
  125. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  126. this.configureModel(newConfiguration.model);
  127. }
  128. // lights
  129. if (newConfiguration.lights) {
  130. this.configureLights(newConfiguration.lights);
  131. }
  132. // environment
  133. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  134. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  135. }
  136. // camera
  137. if (newConfiguration.camera) {
  138. this.configureCamera(newConfiguration.camera);
  139. }
  140. }
  141. protected configureEnvironment(skyboxConifguration?: ISkyboxConfiguration | boolean, groundConfiguration?: IGroundConfiguration | boolean) {
  142. if (!skyboxConifguration && !groundConfiguration) {
  143. if (this.environmentHelper) {
  144. this.environmentHelper.dispose();
  145. delete this.environmentHelper;
  146. };
  147. return Promise.resolve(this.scene);
  148. }
  149. const options: Partial<IEnvironmentHelperOptions> = {
  150. createGround: !!groundConfiguration,
  151. createSkybox: !!skyboxConifguration,
  152. setupImageProcessing: false // will be done at the scene level!
  153. };
  154. if (groundConfiguration) {
  155. let groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  156. let groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  157. if (groundSize) {
  158. options.groundSize = groundSize;
  159. }
  160. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  161. if (groundConfig.shadowLevel !== undefined) {
  162. options.groundShadowLevel = groundConfig.shadowLevel;
  163. }
  164. options.enableGroundMirror = !!groundConfig.mirror;
  165. if (groundConfig.texture) {
  166. options.groundTexture = groundConfig.texture;
  167. }
  168. if (groundConfig.color) {
  169. options.groundColor = new Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b)
  170. }
  171. if (groundConfig.opacity !== undefined) {
  172. options.groundOpacity = groundConfig.opacity;
  173. }
  174. if (groundConfig.mirror) {
  175. options.enableGroundMirror = true;
  176. // to prevent undefines
  177. if (typeof groundConfig.mirror === "object") {
  178. if (groundConfig.mirror.amount !== undefined)
  179. options.groundMirrorAmount = groundConfig.mirror.amount;
  180. if (groundConfig.mirror.sizeRatio !== undefined)
  181. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  182. if (groundConfig.mirror.blurKernel !== undefined)
  183. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  184. if (groundConfig.mirror.fresnelWeight !== undefined)
  185. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  186. if (groundConfig.mirror.fallOffDistance !== undefined)
  187. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  188. if (this.defaultPipelineTextureType !== undefined)
  189. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  190. }
  191. }
  192. }
  193. let postInitSkyboxMaterial = false;
  194. if (skyboxConifguration) {
  195. let conf = skyboxConifguration === true ? {} : skyboxConifguration;
  196. if (conf.material && conf.material.imageProcessingConfiguration) {
  197. options.setupImageProcessing = false; // will be configured later manually.
  198. }
  199. let skyboxSize = conf.scale;
  200. if (skyboxSize) {
  201. options.skyboxSize = skyboxSize;
  202. }
  203. options.sizeAuto = !options.skyboxSize;
  204. if (conf.color) {
  205. options.skyboxColor = new Color3(conf.color.r, conf.color.g, conf.color.b)
  206. }
  207. if (conf.cubeTexture && conf.cubeTexture.url) {
  208. if (typeof conf.cubeTexture.url === "string") {
  209. options.skyboxTexture = conf.cubeTexture.url;
  210. } else {
  211. // init later!
  212. postInitSkyboxMaterial = true;
  213. }
  214. }
  215. if (conf.material && conf.material.imageProcessingConfiguration) {
  216. postInitSkyboxMaterial = true;
  217. }
  218. }
  219. options.setupImageProcessing = false; // TMP
  220. if (!this.environmentHelper) {
  221. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  222. } else {
  223. // there might be a new scene! we need to dispose.
  224. // get the scene used by the envHelper
  225. let scene: Scene = this.environmentHelper.rootMesh.getScene();
  226. // is it a different scene? Oh no!
  227. if (scene !== this.scene) {
  228. this.environmentHelper.dispose();
  229. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  230. } else {
  231. this.environmentHelper.updateOptions(options)!;
  232. }
  233. }
  234. if (postInitSkyboxMaterial) {
  235. let skyboxMaterial = this.environmentHelper.skyboxMaterial;
  236. if (skyboxMaterial) {
  237. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  238. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  239. }
  240. }
  241. }
  242. }
  243. protected configureScene(sceneConfig: ISceneConfiguration, optimizerConfig?: ISceneOptimizerConfiguration) {
  244. // sanity check!
  245. if (!this.scene) {
  246. return;
  247. }
  248. if (sceneConfig.debug) {
  249. this.scene.debugLayer.show();
  250. } else {
  251. if (this.scene.debugLayer.isVisible()) {
  252. this.scene.debugLayer.hide();
  253. }
  254. }
  255. if (sceneConfig.clearColor) {
  256. let cc = sceneConfig.clearColor;
  257. let oldcc = this.scene.clearColor;
  258. if (cc.r !== undefined) {
  259. oldcc.r = cc.r;
  260. }
  261. if (cc.g !== undefined) {
  262. oldcc.g = cc.g
  263. }
  264. if (cc.b !== undefined) {
  265. oldcc.b = cc.b
  266. }
  267. if (cc.a !== undefined) {
  268. oldcc.a = cc.a
  269. }
  270. }
  271. // image processing configuration - optional.
  272. if (sceneConfig.imageProcessingConfiguration) {
  273. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  274. }
  275. if (sceneConfig.environmentTexture) {
  276. if (this.scene.environmentTexture) {
  277. this.scene.environmentTexture.dispose();
  278. }
  279. const environmentTexture = CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  280. this.scene.environmentTexture = environmentTexture;
  281. }
  282. if (sceneConfig.autoRotate) {
  283. this.camera.useAutoRotationBehavior = true;
  284. }
  285. }
  286. protected configureOptimizer(optimizerConfig: ISceneOptimizerConfiguration | boolean) {
  287. if (typeof optimizerConfig === 'boolean') {
  288. if (this.sceneOptimizer) {
  289. this.sceneOptimizer.stop();
  290. this.sceneOptimizer.dispose();
  291. delete this.sceneOptimizer;
  292. }
  293. if (optimizerConfig) {
  294. this.sceneOptimizer = new SceneOptimizer(this.scene);
  295. this.sceneOptimizer.start();
  296. }
  297. } else {
  298. let optimizerOptions: SceneOptimizerOptions = new SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  299. // check for degradation
  300. if (optimizerConfig.degradation) {
  301. switch (optimizerConfig.degradation) {
  302. case "low":
  303. optimizerOptions = SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  304. break;
  305. case "moderate":
  306. optimizerOptions = SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  307. break;
  308. case "hight":
  309. optimizerOptions = SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  310. break;
  311. }
  312. }
  313. if (this.sceneOptimizer) {
  314. this.sceneOptimizer.stop();
  315. this.sceneOptimizer.dispose()
  316. }
  317. this.sceneOptimizer = new SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  318. this.sceneOptimizer.start();
  319. }
  320. }
  321. protected configureObservers(observersConfiguration: IObserversConfiguration) {
  322. if (observersConfiguration.onEngineInit) {
  323. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  324. } else {
  325. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers!.onEngineInit) {
  326. this.onEngineInitObservable.removeCallback(window[this.configuration.observers!.onEngineInit!]);
  327. }
  328. }
  329. if (observersConfiguration.onSceneInit) {
  330. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  331. } else {
  332. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers!.onSceneInit) {
  333. this.onSceneInitObservable.removeCallback(window[this.configuration.observers!.onSceneInit!]);
  334. }
  335. }
  336. if (observersConfiguration.onModelLoaded) {
  337. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  338. } else {
  339. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers!.onModelLoaded) {
  340. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers!.onModelLoaded!]);
  341. }
  342. }
  343. }
  344. protected configureCamera(cameraConfig: ICameraConfiguration, model?: ViewerModel) {
  345. let focusMeshes = model ? model.meshes : this.scene.meshes;
  346. if (!this.scene.activeCamera) {
  347. this.scene.createDefaultCamera(true, true, true);
  348. this.camera = <ArcRotateCamera>this.scene.activeCamera!;
  349. }
  350. if (cameraConfig.position) {
  351. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  352. }
  353. if (cameraConfig.rotation) {
  354. this.camera.rotationQuaternion = new Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0)
  355. }
  356. this.extendClassWithConfig(this.camera, cameraConfig);
  357. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  358. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  359. if (cameraConfig.behaviors) {
  360. for (let name in cameraConfig.behaviors) {
  361. this.setCameraBehavior(cameraConfig.behaviors[name], focusMeshes);
  362. }
  363. };
  364. const sceneExtends = this.scene.getWorldExtends((mesh) => {
  365. return !this.environmentHelper || (mesh !== this.environmentHelper.ground && mesh !== this.environmentHelper.rootMesh && mesh !== this.environmentHelper.skybox);
  366. });
  367. const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  368. const sceneDiagonalLenght = sceneDiagonal.length();
  369. if (isFinite(sceneDiagonalLenght))
  370. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  371. }
  372. protected configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean } = {}, model?: ViewerModel) {
  373. let focusMeshes = model ? model.meshes : this.scene.meshes;
  374. // sanity check!
  375. if (!Object.keys(lightsConfiguration).length) return;
  376. let lightsAvailable: Array<string> = this.scene.lights.map(light => light.name);
  377. // compare to the global (!) configuration object and dispose unneeded:
  378. let lightsToConfigure = Object.keys(this.configuration.lights || []);
  379. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  380. lightsAvailable.forEach(lName => {
  381. if (lightsToConfigure.indexOf(lName) === -1) {
  382. this.scene.getLightByName(lName)!.dispose()
  383. }
  384. });
  385. }
  386. Object.keys(lightsConfiguration).forEach((name, idx) => {
  387. let lightConfig: ILightConfiguration = { type: 0 };
  388. if (typeof lightsConfiguration[name] === 'object') {
  389. lightConfig = <ILightConfiguration>lightsConfiguration[name];
  390. }
  391. lightConfig.name = name;
  392. let light: Light;
  393. // light is not already available
  394. if (lightsAvailable.indexOf(name) === -1) {
  395. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  396. if (!constructor) return;
  397. light = constructor();
  398. } else {
  399. // available? get it from the scene
  400. light = <Light>this.scene.getLightByName(name);
  401. lightsAvailable = lightsAvailable.filter(ln => ln !== name);
  402. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  403. light.dispose();
  404. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  405. if (!constructor) return;
  406. light = constructor();
  407. }
  408. }
  409. // if config set the light to false, dispose it.
  410. if (lightsConfiguration[name] === false) {
  411. light.dispose();
  412. return;
  413. }
  414. //enabled
  415. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  416. light.setEnabled(enabled);
  417. this.extendClassWithConfig(light, lightConfig);
  418. //position. Some lights don't support shadows
  419. if (light instanceof ShadowLight) {
  420. if (lightConfig.target) {
  421. if (light.setDirectionToTarget) {
  422. let target = Vector3.Zero().copyFrom(lightConfig.target as Vector3);
  423. light.setDirectionToTarget(target);
  424. }
  425. } else if (lightConfig.direction) {
  426. let direction = Vector3.Zero().copyFrom(lightConfig.direction as Vector3);
  427. light.direction = direction;
  428. }
  429. let shadowGenerator = light.getShadowGenerator();
  430. if (lightConfig.shadowEnabled && this.maxShadows) {
  431. if (!shadowGenerator) {
  432. shadowGenerator = new ShadowGenerator(512, light);
  433. // TODO blur kernel definition
  434. }
  435. this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  436. // add the focues meshes to the shadow list
  437. let shadownMap = shadowGenerator.getShadowMap();
  438. if (!shadownMap) return;
  439. let renderList = shadownMap.renderList;
  440. for (var index = 0; index < focusMeshes.length; index++) {
  441. if (Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  442. renderList && renderList.push(focusMeshes[index]);
  443. }
  444. }
  445. } else if (shadowGenerator) {
  446. shadowGenerator.dispose();
  447. }
  448. }
  449. });
  450. }
  451. protected configureModel(modelConfiguration: Partial<IModelConfiguration>, model?: ViewerModel) {
  452. let focusMeshes = model ? model.meshes : this.scene.meshes;
  453. let meshesWithNoParent: Array<AbstractMesh> = focusMeshes.filter(m => !m.parent);
  454. let updateMeshesWithNoParent = (variable: string, value: any, param?: string) => {
  455. meshesWithNoParent.forEach(mesh => {
  456. if (param) {
  457. mesh[variable][param] = value;
  458. } else {
  459. mesh[variable] = value;
  460. }
  461. });
  462. }
  463. let updateXYZ = (variable: string, configValues: { x: number, y: number, z: number, w?: number }) => {
  464. if (configValues.x !== undefined) {
  465. updateMeshesWithNoParent(variable, configValues.x, 'x');
  466. }
  467. if (configValues.y !== undefined) {
  468. updateMeshesWithNoParent(variable, configValues.y, 'y');
  469. }
  470. if (configValues.z !== undefined) {
  471. updateMeshesWithNoParent(variable, configValues.z, 'z');
  472. }
  473. if (configValues.w !== undefined) {
  474. updateMeshesWithNoParent(variable, configValues.w, 'w');
  475. }
  476. }
  477. // position?
  478. if (modelConfiguration.position) {
  479. updateXYZ('position', modelConfiguration.position);
  480. }
  481. if (modelConfiguration.rotation) {
  482. if (modelConfiguration.rotation.w) {
  483. meshesWithNoParent.forEach(mesh => {
  484. if (!mesh.rotationQuaternion) {
  485. mesh.rotationQuaternion = new Quaternion();
  486. }
  487. })
  488. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  489. } else {
  490. updateXYZ('rotation', modelConfiguration.rotation);
  491. }
  492. }
  493. if (modelConfiguration.scaling) {
  494. updateXYZ('scaling', modelConfiguration.scaling);
  495. }
  496. if (modelConfiguration.castShadow) {
  497. focusMeshes.forEach(mesh => {
  498. Tags.AddTagsTo(mesh, 'castShadow');
  499. });
  500. }
  501. if (modelConfiguration.normalize) {
  502. let center = false;
  503. let unitSize = false;
  504. let parentIndex;
  505. if (modelConfiguration.normalize === true) {
  506. center = true;
  507. unitSize = true;
  508. parentIndex = 0;
  509. } else {
  510. center = !!modelConfiguration.normalize.center;
  511. unitSize = !!modelConfiguration.normalize.unitSize;
  512. parentIndex = modelConfiguration.normalize.parentIndex;
  513. }
  514. let meshesToNormalize: Array<AbstractMesh> = [];
  515. if (parentIndex !== undefined) {
  516. meshesToNormalize.push(focusMeshes[parentIndex]);
  517. } else {
  518. meshesToNormalize = meshesWithNoParent;
  519. }
  520. if (unitSize) {
  521. meshesToNormalize.forEach(mesh => {
  522. mesh.normalizeToUnitCube(true);
  523. mesh.computeWorldMatrix(true);
  524. });
  525. }
  526. if (center) {
  527. meshesToNormalize.forEach(mesh => {
  528. const boundingInfo = mesh.getHierarchyBoundingVectors(true);
  529. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  530. const halfSizeVec = sizeVec.scale(0.5);
  531. const center = boundingInfo.min.add(halfSizeVec);
  532. mesh.position = center.scale(-1);
  533. // Set on ground.
  534. mesh.position.y += halfSizeVec.y;
  535. // Recompute Info.
  536. mesh.computeWorldMatrix(true);
  537. });
  538. }
  539. }
  540. }
  541. public dispose() {
  542. window.removeEventListener('resize', this.resize);
  543. if (this.sceneOptimizer) {
  544. this.sceneOptimizer.stop();
  545. this.sceneOptimizer.dispose();
  546. }
  547. if (this.scene.activeCamera) {
  548. this.scene.activeCamera.detachControl(this.canvas);
  549. }
  550. this.scene.dispose();
  551. this.engine.dispose();
  552. this.templateManager.dispose();
  553. }
  554. protected abstract prepareContainerElement();
  555. /**
  556. * This function will execute when the HTML templates finished initializing.
  557. * It should initialize the engine and continue execution.
  558. *
  559. * @protected
  560. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  561. * @memberof AbstractViewer
  562. */
  563. protected onTemplatesLoaded(): Promise<AbstractViewer> {
  564. return Promise.resolve(this);
  565. }
  566. /**
  567. * This will force the creation of an engine and a scene.
  568. * It will also load a model if preconfigured.
  569. * But first - it will load the extendible onTemplateLoaded()!
  570. */
  571. private _onTemplateLoaded(): Promise<AbstractViewer> {
  572. return this.onTemplatesLoaded().then(() => {
  573. let autoLoadModel = !!this.configuration.model;
  574. return this.initEngine().then((engine) => {
  575. return this.onEngineInitObservable.notifyObserversWithPromise(engine);
  576. }).then(() => {
  577. if (autoLoadModel) {
  578. return this.loadModel();
  579. } else {
  580. return this.scene || this.initScene();
  581. }
  582. }).then((scene) => {
  583. return this.onSceneInitObservable.notifyObserversWithPromise(scene);
  584. }).then(() => {
  585. return this.onInitDoneObservable.notifyObserversWithPromise(this);
  586. }).then(() => {
  587. return this;
  588. });
  589. })
  590. }
  591. /**
  592. * Initialize the engine. Retruns a promise in case async calls are needed.
  593. *
  594. * @protected
  595. * @returns {Promise<Engine>}
  596. * @memberof Viewer
  597. */
  598. protected initEngine(): Promise<Engine> {
  599. // init custom shaders
  600. this.injectCustomShaders();
  601. let canvasElement = this.templateManager.getCanvas();
  602. if (!canvasElement) {
  603. return Promise.reject('Canvas element not found!');
  604. }
  605. let config = this.configuration.engine || {};
  606. // TDO enable further configuration
  607. this.engine = new Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  608. // Disable manifest checking
  609. Database.IDBStorageEnabled = false;
  610. if (!config.disableResize) {
  611. window.addEventListener('resize', this.resize);
  612. }
  613. this.engine.runRenderLoop(this.render);
  614. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  615. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  616. this.engine.setHardwareScalingLevel(scale);
  617. }
  618. // set hardware limitations for scene initialization
  619. this.handleHardwareLimitations();
  620. return Promise.resolve(this.engine);
  621. }
  622. protected initScene(): Promise<Scene> {
  623. // if the scen exists, dispose it.
  624. if (this.scene) {
  625. this.scene.dispose();
  626. }
  627. // create a new scene
  628. this.scene = new Scene(this.engine);
  629. // make sure there is a default camera and light.
  630. this.scene.createDefaultLight(true);
  631. if (this.configuration.scene) {
  632. this.configureScene(this.configuration.scene);
  633. // Scene optimizer
  634. if (this.configuration.optimizer) {
  635. this.configureOptimizer(this.configuration.optimizer);
  636. }
  637. }
  638. return Promise.resolve(this.scene);
  639. }
  640. private isLoading: boolean;
  641. private nextLoading: Function;
  642. public loadModel(modelConfig: any = this.configuration.model, clearScene: boolean = true): Promise<Scene> {
  643. // no model was provided? Do nothing!
  644. let modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  645. if (!modelUrl) {
  646. return Promise.resolve(this.scene);
  647. }
  648. if (this.isLoading) {
  649. //another model is being model. Wait for it to finish, trigger the load afterwards
  650. this.nextLoading = () => {
  651. delete this.nextLoading;
  652. this.loadModel(modelConfig, clearScene);
  653. }
  654. return Promise.resolve(this.scene);
  655. }
  656. this.isLoading = true;
  657. if ((typeof modelConfig === 'string')) {
  658. if (this.configuration.model && typeof this.configuration.model === 'object') {
  659. this.configuration.model.url = modelConfig;
  660. }
  661. } else {
  662. if (this.configuration.model) {
  663. deepmerge(this.configuration.model, modelConfig)
  664. } else {
  665. this.configuration.model = modelConfig;
  666. }
  667. }
  668. return Promise.resolve(this.scene).then((scene) => {
  669. if (!scene) return this.initScene();
  670. if (clearScene) {
  671. this.models.forEach(m => m.dispose());
  672. this.models.length = 0;
  673. }
  674. return scene;
  675. }).then(() => {
  676. return new Promise<ViewerModel>((resolve, reject) => {
  677. // at this point, configuration.model is an object, not a string
  678. let model = new ViewerModel(<IModelConfiguration>this.configuration.model, this.scene);
  679. this.models.push(model);
  680. this.lastUsedLoader = model.loader;
  681. model.onLoadedObservable.add((model) => {
  682. resolve(model);
  683. });
  684. model.onLoadErrorObservable.add((errorObject) => {
  685. this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject).then(() => {
  686. reject(errorObject.exception);
  687. });
  688. });
  689. model.onLoadProgressObservable.add((progressEvent) => {
  690. return this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  691. });
  692. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  693. });
  694. }).then((model: ViewerModel) => {
  695. return this.onModelLoadedObservable.notifyObserversWithPromise(model)
  696. .then(() => {
  697. // update the models' configuration
  698. this.configureModel(this.configuration.model || modelConfig, model);
  699. this.configureLights(this.configuration.lights);
  700. if (this.configuration.camera) {
  701. this.configureCamera(this.configuration.camera, model);
  702. }
  703. return this.initEnvironment(model.meshes);
  704. }).then(() => {
  705. this.isLoading = false;
  706. if (this.nextLoading) {
  707. return this.nextLoading();
  708. }
  709. return this.scene;
  710. });
  711. });
  712. }
  713. protected initEnvironment(focusMeshes: Array<AbstractMesh> = this.scene.meshes): Promise<Scene> {
  714. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  715. return Promise.resolve(this.scene);
  716. }
  717. /**
  718. * Alters render settings to reduce features based on hardware feature limitations
  719. * @param options Viewer options to modify
  720. */
  721. protected handleHardwareLimitations() {
  722. //flip rendering settings switches based on hardware support
  723. let maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  724. let maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  725. //shadows are disabled if there's not enough varyings for a single shadow
  726. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  727. this.maxShadows = 0;
  728. } else {
  729. this.maxShadows = 3;
  730. }
  731. //can we render to any >= 16-bit targets (required for HDR)
  732. let caps = this.engine.getCaps();
  733. let linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  734. let linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  735. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  736. if (linearHalfFloatTargets) {
  737. this.defaultHighpTextureType = Engine.TEXTURETYPE_HALF_FLOAT;
  738. this.shadowGeneratorBias = 0.002;
  739. } else if (linearFloatTargets) {
  740. this.defaultHighpTextureType = Engine.TEXTURETYPE_FLOAT;
  741. this.shadowGeneratorBias = 0.001;
  742. } else {
  743. this.defaultHighpTextureType = Engine.TEXTURETYPE_UNSIGNED_INT;
  744. this.shadowGeneratorBias = 0.001;
  745. }
  746. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : Engine.TEXTURETYPE_UNSIGNED_INT;
  747. }
  748. /**
  749. * Injects all the spectre shader in the babylon shader store
  750. */
  751. protected injectCustomShaders(): void {
  752. let customShaders = this.configuration.customShaders;
  753. // Inject all the spectre shader in the babylon shader store.
  754. if (!customShaders) {
  755. return;
  756. }
  757. if (customShaders.shaders) {
  758. Object.keys(customShaders.shaders).forEach(key => {
  759. // typescript considers a callback "unsafe", so... '!'
  760. Effect.ShadersStore[key] = customShaders!.shaders![key];
  761. });
  762. }
  763. if (customShaders.includes) {
  764. Object.keys(customShaders.includes).forEach(key => {
  765. // typescript considers a callback "unsafe", so... '!'
  766. Effect.IncludesShadersStore[key] = customShaders!.includes![key];
  767. });
  768. }
  769. }
  770. protected extendClassWithConfig(object: any, config: any) {
  771. if (!config) return;
  772. Object.keys(config).forEach(key => {
  773. if (key in object && typeof object[key] !== 'function') {
  774. // if (typeof object[key] === 'function') return;
  775. // if it is an object, iterate internally until reaching basic types
  776. if (typeof object[key] === 'object') {
  777. this.extendClassWithConfig(object[key], config[key]);
  778. } else {
  779. if (config[key] !== undefined) {
  780. object[key] = config[key];
  781. }
  782. }
  783. }
  784. });
  785. }
  786. private setCameraBehavior(behaviorConfig: number | {
  787. type: number;
  788. [propName: string]: any;
  789. }, payload: any) {
  790. let behavior: Behavior<ArcRotateCamera> | null;
  791. let type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  792. let config: { [propName: string]: any } = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  793. // constructing behavior
  794. switch (type) {
  795. case CameraBehavior.AUTOROTATION:
  796. this.camera.useAutoRotationBehavior = true;
  797. behavior = this.camera.autoRotationBehavior;
  798. break;
  799. case CameraBehavior.BOUNCING:
  800. this.camera.useBouncingBehavior = true;
  801. behavior = this.camera.bouncingBehavior;
  802. break;
  803. case CameraBehavior.FRAMING:
  804. this.camera.useFramingBehavior = true;
  805. behavior = this.camera.framingBehavior;
  806. break;
  807. default:
  808. behavior = null;
  809. break;
  810. }
  811. if (behavior) {
  812. if (typeof behaviorConfig === "object") {
  813. this.extendClassWithConfig(behavior, behaviorConfig);
  814. }
  815. }
  816. // post attach configuration. Some functionalities require the attached camera.
  817. switch (type) {
  818. case CameraBehavior.AUTOROTATION:
  819. break;
  820. case CameraBehavior.BOUNCING:
  821. break;
  822. case CameraBehavior.FRAMING:
  823. if (config.zoomOnBoundingInfo) {
  824. //payload is an array of meshes
  825. let meshes = <Array<AbstractMesh>>payload;
  826. let bounding = meshes[0].getHierarchyBoundingVectors();
  827. (<FramingBehavior>behavior).zoomOnBoundingInfo(bounding.min, bounding.max);
  828. }
  829. break;
  830. }
  831. }
  832. }