sceneManager.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. import { Scene, ArcRotateCamera, Engine, Light, ShadowLight, Vector3, ShadowGenerator, Tags, CubeTexture, Quaternion, SceneOptimizer, EnvironmentHelper, SceneOptimizerOptions, Color3, IEnvironmentHelperOptions, AbstractMesh, FramingBehavior, Behavior, Observable, Color4 } from 'babylonjs';
  2. import { AbstractViewer } from './viewer';
  3. import { ILightConfiguration, ISceneConfiguration, ISceneOptimizerConfiguration, ICameraConfiguration, ISkyboxConfiguration, ViewerConfiguration, IGroundConfiguration, IModelConfiguration } from '../configuration/configuration';
  4. import { ViewerModel } from '../model/viewerModel';
  5. import { extendClassWithConfig } from '../helper';
  6. import { CameraBehavior } from '../interfaces';
  7. import { ViewerLabs } from '../labs/viewerLabs';
  8. /**
  9. * This interface describes the structure of the variable sent with the configuration observables of the scene manager.
  10. * O - the type of object we are dealing with (Light, ArcRotateCamera, Scene, etc')
  11. * T - the configuration type
  12. */
  13. export interface IPostConfigurationCallback<OBJ, CONF> {
  14. newConfiguration: CONF;
  15. sceneManager: SceneManager;
  16. object: OBJ;
  17. model?: ViewerModel;
  18. }
  19. export class SceneManager {
  20. //Observers
  21. onSceneInitObservable: Observable<Scene>;
  22. onSceneConfiguredObservable: Observable<IPostConfigurationCallback<Scene, ISceneConfiguration>>;
  23. onSceneOptimizerConfiguredObservable: Observable<IPostConfigurationCallback<SceneOptimizer, ISceneOptimizerConfiguration | boolean>>;
  24. onCameraConfiguredObservable: Observable<IPostConfigurationCallback<ArcRotateCamera, ICameraConfiguration>>;
  25. onLightsConfiguredObservable: Observable<IPostConfigurationCallback<Array<Light>, { [name: string]: ILightConfiguration | boolean }>>;
  26. onModelsConfiguredObservable: Observable<IPostConfigurationCallback<Array<ViewerModel>, IModelConfiguration>>;
  27. onEnvironmentConfiguredObservable: Observable<IPostConfigurationCallback<EnvironmentHelper, { skybox?: ISkyboxConfiguration | boolean, ground?: IGroundConfiguration | boolean }>>;
  28. /**
  29. * The Babylon Scene of this viewer
  30. */
  31. public scene: Scene;
  32. /**
  33. * The camera used in this viewer
  34. */
  35. public camera: ArcRotateCamera;
  36. /**
  37. * Babylon's scene optimizer
  38. */
  39. public sceneOptimizer: SceneOptimizer;
  40. /**
  41. * Models displayed in this viewer.
  42. */
  43. public models: Array<ViewerModel>;
  44. /**
  45. * Babylon's environment helper of this viewer
  46. */
  47. public environmentHelper: EnvironmentHelper;
  48. //The following are configuration objects, default values.
  49. protected _defaultHighpTextureType: number;
  50. protected _shadowGeneratorBias: number;
  51. protected _defaultPipelineTextureType: number;
  52. /**
  53. * The maximum number of shadows supported by the curent viewer
  54. */
  55. protected _maxShadows: number;
  56. /**
  57. * is HDR supported?
  58. */
  59. private _hdrSupport: boolean;
  60. private _mainColor: Color3 = Color3.White();
  61. private readonly _white = Color3.White();
  62. //Labs!
  63. public labs: ViewerLabs;
  64. constructor(private _viewer: AbstractViewer) {
  65. this.models = [];
  66. this.onCameraConfiguredObservable = new Observable();
  67. this.onLightsConfiguredObservable = new Observable();
  68. this.onModelsConfiguredObservable = new Observable();
  69. this.onSceneConfiguredObservable = new Observable();
  70. this.onSceneInitObservable = new Observable();
  71. this.onSceneOptimizerConfiguredObservable = new Observable();
  72. this.onEnvironmentConfiguredObservable = new Observable();
  73. this._viewer.onEngineInitObservable.add(() => {
  74. this._handleHardwareLimitations();
  75. });
  76. this.labs = new ViewerLabs(this);
  77. }
  78. /**
  79. * Returns a boolean representing HDR support
  80. */
  81. public get isHdrSupported() {
  82. return this._hdrSupport;
  83. }
  84. /**
  85. * Return the main color defined in the configuration.
  86. */
  87. public get mainColor(): Color3 {
  88. return this._mainColor;
  89. }
  90. /**
  91. * Sets the engine flags to unlock all babylon features.
  92. */
  93. public unlockBabylonFeatures() {
  94. this.scene.shadowsEnabled = true;
  95. this.scene.particlesEnabled = true;
  96. this.scene.postProcessesEnabled = true;
  97. this.scene.collisionsEnabled = true;
  98. this.scene.lightsEnabled = true;
  99. this.scene.texturesEnabled = true;
  100. this.scene.lensFlaresEnabled = true;
  101. this.scene.proceduralTexturesEnabled = true;
  102. this.scene.renderTargetsEnabled = true;
  103. this.scene.spritesEnabled = true;
  104. this.scene.skeletonsEnabled = true;
  105. this.scene.audioEnabled = true;
  106. }
  107. /**
  108. * initialize the environment for a specific model.
  109. * Per default it will use the viewer's configuration.
  110. * @param model the model to use to configure the environment.
  111. * @returns a Promise that will resolve when the configuration is done.
  112. */
  113. protected _initEnvironment(model?: ViewerModel): Promise<Scene> {
  114. this._configureEnvironment(this._viewer.configuration.skybox, this._viewer.configuration.ground, model);
  115. return Promise.resolve(this.scene);
  116. }
  117. /**
  118. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  119. */
  120. public initScene(sceneConfiguration?: ISceneConfiguration, optimizerConfiguration?: boolean | ISceneOptimizerConfiguration): Promise<Scene> {
  121. // if the scen exists, dispose it.
  122. if (this.scene) {
  123. this.scene.dispose();
  124. }
  125. // create a new scene
  126. this.scene = new Scene(this._viewer.engine);
  127. var defaultMaterial = new BABYLON.PBRMaterial('default-material', this.scene);
  128. defaultMaterial.environmentBRDFTexture = null;
  129. defaultMaterial.usePhysicalLightFalloff = true;
  130. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  131. defaultMaterial.microSurface = 0.6;
  132. this.scene.defaultMaterial = defaultMaterial;
  133. this._mainColor = new Color3();
  134. if (sceneConfiguration) {
  135. this._configureScene(sceneConfiguration);
  136. // Scene optimizer
  137. if (optimizerConfiguration) {
  138. this._configureOptimizer(optimizerConfiguration);
  139. }
  140. }
  141. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  142. }
  143. public clearScene(clearModels: boolean = true, clearLights: boolean = false) {
  144. if (clearModels) {
  145. this.models.forEach(m => m.dispose());
  146. this.models.length = 0;
  147. }
  148. if (clearLights) {
  149. this.scene.lights.forEach(l => l.dispose());
  150. }
  151. }
  152. /**
  153. * This will update the scene's configuration, including camera, lights, environment.
  154. * @param newConfiguration the delta that should be configured. This includes only the changes
  155. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  156. */
  157. public updateConfiguration(newConfiguration: Partial<ViewerConfiguration>, globalConfiguration: ViewerConfiguration, model?: ViewerModel) {
  158. if (newConfiguration.lab) {
  159. if (newConfiguration.lab.environmentAssetsRootURL) {
  160. this.labs.environmentAssetsRootURL = newConfiguration.lab.environmentAssetsRootURL;
  161. }
  162. if (newConfiguration.lab.environmentMap) {
  163. let rot = newConfiguration.lab.environmentMap.rotationY;
  164. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, () => {
  165. this.labs.applyEnvironmentMapConfiguration(rot);
  166. });
  167. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  168. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  169. }
  170. }
  171. }
  172. // update scene configuration
  173. if (newConfiguration.scene) {
  174. this._configureScene(newConfiguration.scene);
  175. // process mainColor changes:
  176. if (newConfiguration.scene.mainColor) {
  177. let mc = newConfiguration.scene.mainColor;
  178. if (mc.r !== undefined) {
  179. this._mainColor.r = mc.r;
  180. }
  181. if (mc.g !== undefined) {
  182. this._mainColor.g = mc.g
  183. }
  184. if (mc.b !== undefined) {
  185. this._mainColor.b = mc.b
  186. }
  187. this._mainColor.toLinearSpaceToRef(this._mainColor);
  188. let exposure = Math.pow(2.0, -((globalConfiguration.camera && globalConfiguration.camera.exposure) || 0.75)) * Math.PI;
  189. this._mainColor.scaleToRef(1 / exposure, this._mainColor);
  190. let environmentTint = (globalConfiguration.lab && globalConfiguration.lab.environmentMap && globalConfiguration.lab.environmentMap.tintLevel) || 0;
  191. this._mainColor = BABYLON.Color3.Lerp(this._white, this._mainColor, environmentTint);
  192. }
  193. }
  194. // optimizer
  195. if (newConfiguration.optimizer) {
  196. this._configureOptimizer(newConfiguration.optimizer);
  197. }
  198. // configure model
  199. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  200. this._configureModel(newConfiguration.model);
  201. }
  202. // lights
  203. this._configureLights(newConfiguration.lights, model);
  204. // environment
  205. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  206. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground, model);
  207. }
  208. // camera
  209. this._configureCamera(newConfiguration.camera, model);
  210. }
  211. /**
  212. * internally configure the scene using the provided configuration.
  213. * The scene will not be recreated, but just updated.
  214. * @param sceneConfig the (new) scene configuration
  215. */
  216. protected _configureScene(sceneConfig: ISceneConfiguration) {
  217. // sanity check!
  218. if (!this.scene) {
  219. return;
  220. }
  221. if (sceneConfig.debug) {
  222. this.scene.debugLayer.show();
  223. } else {
  224. if (this.scene.debugLayer.isVisible()) {
  225. this.scene.debugLayer.hide();
  226. }
  227. }
  228. let cc = sceneConfig.clearColor || { r: 0.9, g: 0.9, b: 0.9, a: 1.0 };
  229. let oldcc = this.scene.clearColor;
  230. if (cc.r !== undefined) {
  231. oldcc.r = cc.r;
  232. }
  233. if (cc.g !== undefined) {
  234. oldcc.g = cc.g
  235. }
  236. if (cc.b !== undefined) {
  237. oldcc.b = cc.b
  238. }
  239. if (cc.a !== undefined) {
  240. oldcc.a = cc.a
  241. }
  242. // image processing configuration - optional.
  243. if (sceneConfig.imageProcessingConfiguration) {
  244. extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  245. }
  246. if (sceneConfig.environmentTexture) {
  247. if (this.scene.environmentTexture) {
  248. this.scene.environmentTexture.dispose();
  249. }
  250. const environmentTexture = CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  251. this.scene.environmentTexture = environmentTexture;
  252. }
  253. this.onSceneConfiguredObservable.notifyObservers({
  254. sceneManager: this,
  255. object: this.scene,
  256. newConfiguration: sceneConfig
  257. });
  258. }
  259. /**
  260. * Configure the scene optimizer.
  261. * The existing scene optimizer will be disposed and a new one will be created.
  262. * @param optimizerConfig the (new) optimizer configuration
  263. */
  264. protected _configureOptimizer(optimizerConfig: ISceneOptimizerConfiguration | boolean) {
  265. if (typeof optimizerConfig === 'boolean') {
  266. if (this.sceneOptimizer) {
  267. this.sceneOptimizer.stop();
  268. this.sceneOptimizer.dispose();
  269. delete this.sceneOptimizer;
  270. }
  271. if (optimizerConfig) {
  272. this.sceneOptimizer = new SceneOptimizer(this.scene);
  273. this.sceneOptimizer.start();
  274. }
  275. } else {
  276. let optimizerOptions: SceneOptimizerOptions = new SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  277. // check for degradation
  278. if (optimizerConfig.degradation) {
  279. switch (optimizerConfig.degradation) {
  280. case "low":
  281. optimizerOptions = SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  282. break;
  283. case "moderate":
  284. optimizerOptions = SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  285. break;
  286. case "hight":
  287. optimizerOptions = SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  288. break;
  289. }
  290. }
  291. if (this.sceneOptimizer) {
  292. this.sceneOptimizer.stop();
  293. this.sceneOptimizer.dispose()
  294. }
  295. this.sceneOptimizer = new SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  296. this.sceneOptimizer.start();
  297. }
  298. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  299. sceneManager: this,
  300. object: this.sceneOptimizer,
  301. newConfiguration: optimizerConfig
  302. });
  303. }
  304. /**
  305. * configure all models using the configuration.
  306. * @param modelConfiguration the configuration to use to reconfigure the models
  307. */
  308. protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  309. this.models.forEach(model => {
  310. model.updateConfiguration(modelConfiguration);
  311. });
  312. this.onModelsConfiguredObservable.notifyObservers({
  313. sceneManager: this,
  314. object: this.models,
  315. newConfiguration: modelConfiguration
  316. });
  317. }
  318. /**
  319. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  320. * @param cameraConfig the new camera configuration
  321. * @param model optionally use the model to configure the camera.
  322. */
  323. protected _configureCamera(cameraConfig: ICameraConfiguration = {}, model?: ViewerModel) {
  324. let focusMeshes = model ? model.meshes : this.scene.meshes;
  325. if (!this.scene.activeCamera) {
  326. this.scene.createDefaultCamera(true, true, true);
  327. this.camera = <ArcRotateCamera>this.scene.activeCamera!;
  328. this.camera.setTarget(Vector3.Zero());
  329. }
  330. if (cameraConfig.position) {
  331. let newPosition = this.camera.position.clone();
  332. extendClassWithConfig(newPosition, cameraConfig.position);
  333. this.camera.setPosition(newPosition);
  334. }
  335. if (cameraConfig.target) {
  336. let newTarget = this.camera.target.clone();
  337. extendClassWithConfig(newTarget, cameraConfig.target);
  338. this.camera.setTarget(newTarget);
  339. } else if (model && !cameraConfig.disableAutoFocus) {
  340. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  341. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  342. const halfSizeVec = sizeVec.scale(0.5);
  343. const center = boundingInfo.min.add(halfSizeVec);
  344. this.camera.setTarget(center);
  345. }
  346. if (cameraConfig.rotation) {
  347. this.camera.rotationQuaternion = new Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0)
  348. }
  349. extendClassWithConfig(this.camera, cameraConfig);
  350. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  351. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  352. if (cameraConfig.behaviors) {
  353. for (let name in cameraConfig.behaviors) {
  354. this._setCameraBehavior(cameraConfig.behaviors[name], focusMeshes);
  355. }
  356. };
  357. const sceneExtends = this.scene.getWorldExtends((mesh) => {
  358. return !this.environmentHelper || (mesh !== this.environmentHelper.ground && mesh !== this.environmentHelper.rootMesh && mesh !== this.environmentHelper.skybox);
  359. });
  360. const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  361. const sceneDiagonalLenght = sceneDiagonal.length();
  362. if (isFinite(sceneDiagonalLenght))
  363. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  364. this.onCameraConfiguredObservable.notifyObservers({
  365. sceneManager: this,
  366. object: this.camera,
  367. newConfiguration: cameraConfig,
  368. model
  369. });
  370. }
  371. protected _configureEnvironment(skyboxConifguration?: ISkyboxConfiguration | boolean, groundConfiguration?: IGroundConfiguration | boolean, model?: ViewerModel) {
  372. if (!skyboxConifguration && !groundConfiguration) {
  373. if (this.environmentHelper) {
  374. this.environmentHelper.dispose();
  375. delete this.environmentHelper;
  376. };
  377. return Promise.resolve(this.scene);
  378. }
  379. const options: Partial<IEnvironmentHelperOptions> = {
  380. createGround: !!groundConfiguration,
  381. createSkybox: !!skyboxConifguration,
  382. setupImageProcessing: false, // will be done at the scene level!,
  383. };
  384. if (model) {
  385. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  386. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  387. const halfSizeVec = sizeVec.scale(0.5);
  388. const center = boundingInfo.min.add(halfSizeVec);
  389. options.groundYBias = -center.y;
  390. }
  391. if (groundConfiguration) {
  392. let groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  393. let groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  394. if (groundSize) {
  395. options.groundSize = groundSize;
  396. }
  397. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  398. if (groundConfig.shadowLevel !== undefined) {
  399. options.groundShadowLevel = groundConfig.shadowLevel;
  400. }
  401. options.enableGroundMirror = !!groundConfig.mirror;
  402. if (groundConfig.texture) {
  403. options.groundTexture = groundConfig.texture;
  404. }
  405. if (groundConfig.color) {
  406. options.groundColor = new Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b)
  407. }
  408. if (groundConfig.opacity !== undefined) {
  409. options.groundOpacity = groundConfig.opacity;
  410. }
  411. if (groundConfig.mirror) {
  412. options.enableGroundMirror = true;
  413. // to prevent undefines
  414. if (typeof groundConfig.mirror === "object") {
  415. if (groundConfig.mirror.amount !== undefined)
  416. options.groundMirrorAmount = groundConfig.mirror.amount;
  417. if (groundConfig.mirror.sizeRatio !== undefined)
  418. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  419. if (groundConfig.mirror.blurKernel !== undefined)
  420. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  421. if (groundConfig.mirror.fresnelWeight !== undefined)
  422. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  423. if (groundConfig.mirror.fallOffDistance !== undefined)
  424. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  425. if (this._defaultPipelineTextureType !== undefined)
  426. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  427. }
  428. }
  429. }
  430. let postInitSkyboxMaterial = false;
  431. if (skyboxConifguration) {
  432. let conf = skyboxConifguration === true ? {} : skyboxConifguration;
  433. if (conf.material && conf.material.imageProcessingConfiguration) {
  434. options.setupImageProcessing = false; // will be configured later manually.
  435. }
  436. let skyboxSize = conf.scale;
  437. if (skyboxSize) {
  438. options.skyboxSize = skyboxSize;
  439. }
  440. options.sizeAuto = !options.skyboxSize;
  441. if (conf.color) {
  442. options.skyboxColor = new Color3(conf.color.r, conf.color.g, conf.color.b)
  443. }
  444. if (conf.cubeTexture && conf.cubeTexture.url) {
  445. if (typeof conf.cubeTexture.url === "string") {
  446. options.skyboxTexture = conf.cubeTexture.url;
  447. } else {
  448. // init later!
  449. postInitSkyboxMaterial = true;
  450. }
  451. }
  452. if (conf.material && conf.material.imageProcessingConfiguration) {
  453. postInitSkyboxMaterial = true;
  454. }
  455. }
  456. options.setupImageProcessing = false; // TMP
  457. if (!this.environmentHelper) {
  458. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  459. } else {
  460. // there might be a new scene! we need to dispose.
  461. // get the scene used by the envHelper
  462. let scene: Scene = this.environmentHelper.rootMesh.getScene();
  463. // is it a different scene? Oh no!
  464. if (scene !== this.scene) {
  465. this.environmentHelper.dispose();
  466. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  467. } else {
  468. this.environmentHelper.updateOptions(options)!;
  469. }
  470. }
  471. if (this.environmentHelper.rootMesh && this._viewer.configuration.scene && this._viewer.configuration.scene.environmentRotationY !== undefined) {
  472. this.environmentHelper.rootMesh.rotation.y = this._viewer.configuration.scene.environmentRotationY;
  473. }
  474. if (postInitSkyboxMaterial) {
  475. let skyboxMaterial = this.environmentHelper.skyboxMaterial;
  476. if (skyboxMaterial) {
  477. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  478. extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  479. }
  480. }
  481. }
  482. this.onEnvironmentConfiguredObservable.notifyObservers({
  483. sceneManager: this,
  484. object: this.environmentHelper,
  485. newConfiguration: {
  486. skybox: skyboxConifguration,
  487. ground: groundConfiguration
  488. },
  489. model
  490. });
  491. }
  492. /**
  493. * configure the lights.
  494. *
  495. * @param lightsConfiguration the (new) light(s) configuration
  496. * @param model optionally use the model to configure the camera.
  497. */
  498. protected _configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean } = {}, model?: ViewerModel) {
  499. let focusMeshes = model ? model.meshes : this.scene.meshes;
  500. // sanity check!
  501. if (!Object.keys(lightsConfiguration).length) {
  502. if (!this.scene.lights.length)
  503. this.scene.createDefaultLight(true);
  504. return;
  505. };
  506. let lightsAvailable: Array<string> = this.scene.lights.map(light => light.name);
  507. // compare to the global (!) configuration object and dispose unneeded:
  508. let lightsToConfigure = Object.keys(this._viewer.configuration.lights || []);
  509. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  510. lightsAvailable.forEach(lName => {
  511. if (lightsToConfigure.indexOf(lName) === -1) {
  512. this.scene.getLightByName(lName)!.dispose();
  513. }
  514. });
  515. }
  516. Object.keys(lightsConfiguration).forEach((name, idx) => {
  517. let lightConfig: ILightConfiguration = { type: 0 };
  518. if (typeof lightsConfiguration[name] === 'object') {
  519. lightConfig = <ILightConfiguration>lightsConfiguration[name];
  520. }
  521. lightConfig.name = name;
  522. let light: Light;
  523. // light is not already available
  524. if (lightsAvailable.indexOf(name) === -1) {
  525. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  526. if (!constructor) return;
  527. light = constructor();
  528. } else {
  529. // available? get it from the scene
  530. light = <Light>this.scene.getLightByName(name);
  531. lightsAvailable = lightsAvailable.filter(ln => ln !== name);
  532. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  533. light.dispose();
  534. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  535. if (!constructor) return;
  536. light = constructor();
  537. }
  538. }
  539. // if config set the light to false, dispose it.
  540. if (lightsConfiguration[name] === false) {
  541. light.dispose();
  542. return;
  543. }
  544. //enabled
  545. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  546. light.setEnabled(enabled);
  547. extendClassWithConfig(light, lightConfig);
  548. //position. Some lights don't support shadows
  549. if (light instanceof ShadowLight) {
  550. // set default values
  551. light.shadowMinZ = light.shadowMinZ || 0.2;
  552. light.shadowMaxZ = Math.min(10, light.shadowMaxZ); //large far clips reduce shadow depth precision
  553. if (lightConfig.target) {
  554. if (light.setDirectionToTarget) {
  555. let target = Vector3.Zero().copyFrom(lightConfig.target as Vector3);
  556. light.setDirectionToTarget(target);
  557. }
  558. } else if (lightConfig.direction) {
  559. let direction = Vector3.Zero().copyFrom(lightConfig.direction as Vector3);
  560. light.direction = direction;
  561. }
  562. let isShadowEnabled = false;
  563. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  564. (<BABYLON.DirectionalLight>light).shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  565. isShadowEnabled = true;
  566. }
  567. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  568. let spotLight: BABYLON.SpotLight = <BABYLON.SpotLight>light;
  569. if (lightConfig.spotAngle !== undefined) {
  570. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  571. }
  572. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  573. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  574. }
  575. isShadowEnabled = true;
  576. }
  577. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  578. if (lightConfig.shadowFieldOfView) {
  579. (<BABYLON.PointLight>light).shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  580. }
  581. isShadowEnabled = true;
  582. }
  583. let shadowGenerator = <BABYLON.ShadowGenerator>light.getShadowGenerator();
  584. if (isShadowEnabled && lightConfig.shadowEnabled && this._maxShadows) {
  585. if (!shadowGenerator) {
  586. shadowGenerator = new ShadowGenerator(512, light);
  587. // TODO blur kernel definition
  588. }
  589. extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  590. // add the focues meshes to the shadow list
  591. let shadownMap = shadowGenerator.getShadowMap();
  592. if (!shadownMap) return;
  593. let renderList = shadownMap.renderList;
  594. for (var index = 0; index < focusMeshes.length; index++) {
  595. if (Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  596. renderList && renderList.push(focusMeshes[index]);
  597. }
  598. }
  599. let bufferSize = lightConfig.shadowBufferSize || 256;
  600. var blurKernel = this.getBlurKernel(light, bufferSize);
  601. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  602. shadowGenerator.useKernelBlur = true;
  603. shadowGenerator.blurScale = 1.0;
  604. shadowGenerator.bias = this._shadowGeneratorBias;
  605. shadowGenerator.blurKernel = blurKernel;
  606. shadowGenerator.depthScale = 50 * (light.shadowMaxZ - light.shadowMinZ);
  607. } else if (shadowGenerator) {
  608. shadowGenerator.dispose();
  609. }
  610. }
  611. });
  612. // render priority
  613. let globalLightsConfiguration = this._viewer.configuration.lights || {};
  614. Object.keys(globalLightsConfiguration).sort().forEach((name, idx) => {
  615. let configuration = globalLightsConfiguration[name];
  616. let light = this.scene.getLightByName(name);
  617. // sanity check
  618. if (!light) return;
  619. light.renderPriority = -idx;
  620. });
  621. this.onLightsConfiguredObservable.notifyObservers({
  622. sceneManager: this,
  623. object: this.scene.lights,
  624. newConfiguration: lightsConfiguration,
  625. model
  626. });
  627. }
  628. /**
  629. * Gets the shadow map blur kernel according to the light configuration.
  630. * @param light The light used to generate the shadows
  631. * @param bufferSize The size of the shadow map
  632. * @return the kernel blur size
  633. */
  634. public getBlurKernel(light: BABYLON.IShadowLight, bufferSize: number): number {
  635. var normalizedBlurKernel = 0.03; // TODO Should come from the config.
  636. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  637. normalizedBlurKernel = normalizedBlurKernel / (<BABYLON.DirectionalLight>light).shadowFrustumSize;
  638. }
  639. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  640. normalizedBlurKernel = normalizedBlurKernel / (<BABYLON.PointLight>light).shadowAngle;
  641. }
  642. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  643. normalizedBlurKernel = normalizedBlurKernel / ((<BABYLON.SpotLight>light).angle * (<BABYLON.SpotLight>light).shadowAngleScale);
  644. }
  645. let minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  646. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  647. return blurKernel;
  648. }
  649. /**
  650. * Alters render settings to reduce features based on hardware feature limitations
  651. * @param enableHDR Allows the viewer to run in HDR mode.
  652. */
  653. protected _handleHardwareLimitations(enableHDR = true) {
  654. //flip rendering settings switches based on hardware support
  655. let maxVaryingRows = this._viewer.engine.getCaps().maxVaryingVectors;
  656. let maxFragmentSamplers = this._viewer.engine.getCaps().maxTexturesImageUnits;
  657. //shadows are disabled if there's not enough varyings for a single shadow
  658. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  659. this._maxShadows = 0;
  660. } else {
  661. this._maxShadows = 3;
  662. }
  663. //can we render to any >= 16-bit targets (required for HDR)
  664. let caps = this._viewer.engine.getCaps();
  665. let linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  666. let linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  667. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  668. if (linearHalfFloatTargets) {
  669. this._defaultHighpTextureType = Engine.TEXTURETYPE_HALF_FLOAT;
  670. this._shadowGeneratorBias = 0.002;
  671. } else if (linearFloatTargets) {
  672. this._defaultHighpTextureType = Engine.TEXTURETYPE_FLOAT;
  673. this._shadowGeneratorBias = 0.001;
  674. } else {
  675. this._defaultHighpTextureType = Engine.TEXTURETYPE_UNSIGNED_INT;
  676. this._shadowGeneratorBias = 0.001;
  677. }
  678. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : Engine.TEXTURETYPE_UNSIGNED_INT;
  679. }
  680. /**
  681. * Dispoe the entire viewer including the scene and the engine
  682. */
  683. public dispose() {
  684. // this.onCameraConfiguredObservable.clear();
  685. this.onEnvironmentConfiguredObservable.clear();
  686. this.onLightsConfiguredObservable.clear();
  687. this.onModelsConfiguredObservable.clear();
  688. this.onSceneConfiguredObservable.clear();
  689. this.onSceneInitObservable.clear();
  690. this.onSceneOptimizerConfiguredObservable.clear();
  691. if (this.sceneOptimizer) {
  692. this.sceneOptimizer.stop();
  693. this.sceneOptimizer.dispose();
  694. }
  695. if (this.environmentHelper) {
  696. this.environmentHelper.dispose();
  697. }
  698. this.models.forEach(model => {
  699. model.dispose();
  700. });
  701. this.models.length = 0;
  702. this.scene.dispose();
  703. }
  704. private _setCameraBehavior(behaviorConfig: number | {
  705. type: number;
  706. [propName: string]: any;
  707. }, payload: any) {
  708. let behavior: Behavior<ArcRotateCamera> | null;
  709. let type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  710. let config: { [propName: string]: any } = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  711. // constructing behavior
  712. switch (type) {
  713. case CameraBehavior.AUTOROTATION:
  714. this.camera.useAutoRotationBehavior = true;
  715. behavior = this.camera.autoRotationBehavior;
  716. break;
  717. case CameraBehavior.BOUNCING:
  718. this.camera.useBouncingBehavior = true;
  719. behavior = this.camera.bouncingBehavior;
  720. break;
  721. case CameraBehavior.FRAMING:
  722. this.camera.useFramingBehavior = true;
  723. behavior = this.camera.framingBehavior;
  724. break;
  725. default:
  726. behavior = null;
  727. break;
  728. }
  729. if (behavior) {
  730. if (typeof behaviorConfig === "object") {
  731. extendClassWithConfig(behavior, behaviorConfig);
  732. }
  733. }
  734. // post attach configuration. Some functionalities require the attached camera.
  735. switch (type) {
  736. case CameraBehavior.AUTOROTATION:
  737. break;
  738. case CameraBehavior.BOUNCING:
  739. break;
  740. case CameraBehavior.FRAMING:
  741. if (config.zoomOnBoundingInfo) {
  742. //payload is an array of meshes
  743. let meshes = <Array<AbstractMesh>>payload;
  744. let bounding = meshes[0].getHierarchyBoundingVectors();
  745. (<FramingBehavior>behavior).zoomOnBoundingInfo(bounding.min, bounding.max);
  746. }
  747. break;
  748. }
  749. }
  750. }