sceneManager.ts 46 KB

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