sceneManager.ts 42 KB

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