sceneManager.ts 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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, Nullable, Mesh } from 'babylonjs';
  2. import { AbstractViewer } from './viewer';
  3. import { ILightConfiguration, ISceneConfiguration, ISceneOptimizerConfiguration, ICameraConfiguration, ISkyboxConfiguration, ViewerConfiguration, IGroundConfiguration, IModelConfiguration, getConfigurationKey, IDefaultRenderingPipelineConfiguration } from '../configuration/configuration';
  4. import { ViewerModel, ModelState } from '../model/viewerModel';
  5. import { extendClassWithConfig } from '../helper';
  6. import { CameraBehavior } from '../interfaces';
  7. import { ViewerLabs } from '../labs/viewerLabs';
  8. import { getCustomOptimizerByName } from '../optimizer/custom/';
  9. /**
  10. * This interface describes the structure of the variable sent with the configuration observables of the scene manager.
  11. * O - the type of object we are dealing with (Light, ArcRotateCamera, Scene, etc')
  12. * T - the configuration type
  13. */
  14. export interface IPostConfigurationCallback<OBJ, CONF> {
  15. newConfiguration: CONF;
  16. sceneManager: SceneManager;
  17. object: OBJ;
  18. model?: ViewerModel;
  19. }
  20. export class SceneManager {
  21. //Observers
  22. /**
  23. * Will notify when the scene was initialized
  24. */
  25. onSceneInitObservable: Observable<Scene>;
  26. /**
  27. * Will notify after the scene was configured. Can be used to further configure the scene
  28. */
  29. onSceneConfiguredObservable: Observable<IPostConfigurationCallback<Scene, ISceneConfiguration>>;
  30. /**
  31. * Will notify after the scene optimized was configured. Can be used to further configure the scene optimizer
  32. */
  33. onSceneOptimizerConfiguredObservable: Observable<IPostConfigurationCallback<SceneOptimizer, ISceneOptimizerConfiguration | boolean>>;
  34. /**
  35. * Will notify after the camera was configured. Can be used to further configure the camera
  36. */
  37. onCameraConfiguredObservable: Observable<IPostConfigurationCallback<ArcRotateCamera, ICameraConfiguration>>;
  38. /**
  39. * Will notify after the lights were configured. Can be used to further configure lights
  40. */
  41. onLightsConfiguredObservable: Observable<IPostConfigurationCallback<Array<Light>, { [name: string]: ILightConfiguration | boolean }>>;
  42. /**
  43. * Will notify after the model(s) were configured. Can be used to further configure models
  44. */
  45. onModelsConfiguredObservable: Observable<IPostConfigurationCallback<Array<ViewerModel>, IModelConfiguration>>;
  46. /**
  47. * Will notify after the envirnoment was configured. Can be used to further configure the environment
  48. */
  49. onEnvironmentConfiguredObservable: Observable<IPostConfigurationCallback<EnvironmentHelper, { skybox?: ISkyboxConfiguration | boolean, ground?: IGroundConfiguration | boolean }>>;
  50. /**
  51. * The Babylon Scene of this viewer
  52. */
  53. public scene: Scene;
  54. /**
  55. * The camera used in this viewer
  56. */
  57. public camera: ArcRotateCamera;
  58. /**
  59. * Babylon's scene optimizer
  60. */
  61. public sceneOptimizer: SceneOptimizer;
  62. /**
  63. * Models displayed in this viewer.
  64. */
  65. public models: Array<ViewerModel>;
  66. /**
  67. * Babylon's environment helper of this viewer
  68. */
  69. public environmentHelper: EnvironmentHelper;
  70. private _animationBlendingEnabled: boolean = true;
  71. //The following are configuration objects, default values.
  72. protected _defaultHighpTextureType: number;
  73. protected _shadowGeneratorBias: number;
  74. protected _defaultPipelineTextureType: number;
  75. /**
  76. * The maximum number of shadows supported by the curent viewer
  77. */
  78. protected _maxShadows: number;
  79. /**
  80. * is HDR supported?
  81. */
  82. private _hdrSupport: boolean;
  83. private _mainColor: Color3 = Color3.White();
  84. private _reflectionColor = Color3.White();
  85. private readonly _white = Color3.White();
  86. /**
  87. * The labs variable consists of objects that will have their API change.
  88. * Please be careful when using labs in production.
  89. */
  90. public labs: ViewerLabs;
  91. private _defaultRenderingPipeline: Nullable<DefaultRenderingPipeline>;
  92. public get defaultRenderingPipeline() {
  93. return this._defaultRenderingPipeline;
  94. }
  95. constructor(private _viewer: AbstractViewer) {
  96. this.models = [];
  97. this.onCameraConfiguredObservable = new Observable();
  98. this.onLightsConfiguredObservable = new Observable();
  99. this.onModelsConfiguredObservable = new Observable();
  100. this.onSceneConfiguredObservable = new Observable();
  101. this.onSceneInitObservable = new Observable();
  102. this.onSceneOptimizerConfiguredObservable = new Observable();
  103. this.onEnvironmentConfiguredObservable = new Observable();
  104. this._viewer.onEngineInitObservable.add(() => {
  105. this._handleHardwareLimitations();
  106. });
  107. this.labs = new ViewerLabs(this);
  108. this.onSceneInitObservable.add((scene) => {
  109. scene.registerBeforeRender(() => {
  110. if (this.models.length && scene.animatables && scene.animatables.length > 0) {
  111. // make sure all models are loaded
  112. if (this.models.every((model) => model.state === ModelState.COMPLETE && !model.currentAnimation)) return;
  113. for (let light of this.scene.lights) {
  114. let generator = light.getShadowGenerator();
  115. if (generator) {
  116. // Processing shadows if animates
  117. let shadowMap = generator.getShadowMap();
  118. if (shadowMap) {
  119. shadowMap.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  120. }
  121. }
  122. }
  123. }
  124. });
  125. return this._viewer.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  126. });
  127. this._viewer.onModelLoadedObservable.add((model) => {
  128. for (let light of this.scene.lights) {
  129. let generator = light.getShadowGenerator();
  130. if (generator) {
  131. // Processing shadows if animates
  132. let shadowMap = generator.getShadowMap();
  133. if (shadowMap) {
  134. shadowMap.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  135. }
  136. }
  137. }
  138. this._focusOnModel(model);
  139. });
  140. }
  141. /**
  142. * Returns a boolean representing HDR support
  143. */
  144. public get isHdrSupported() {
  145. return this._hdrSupport;
  146. }
  147. /**
  148. * Return the main color defined in the configuration.
  149. */
  150. public get mainColor(): Color3 {
  151. return this._mainColor;
  152. }
  153. public get reflectionColor(): Color3 {
  154. return this._reflectionColor;
  155. }
  156. public get animationBlendingEnabled() {
  157. return this._animationBlendingEnabled;
  158. }
  159. public set animationBlendingEnabled(value: boolean) {
  160. this.scene.animationPropertiesOverride = this.scene.animationPropertiesOverride || new AnimationPropertiesOverride();
  161. this.scene.animationPropertiesOverride.enableBlending = value;
  162. this._animationBlendingEnabled = value;
  163. }
  164. private _processShadows: boolean = true;
  165. /**
  166. * The flag defining whether shadows are rendered constantly or once.
  167. */
  168. public get processShadows() {
  169. return this._processShadows;
  170. }
  171. /**
  172. * Should shadows be rendered every frame, or only once and stop.
  173. * This can be used to optimize a scene.
  174. *
  175. * Not that the shadows will NOT disapear but will remain in place.
  176. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  177. */
  178. public set processShadows(process: boolean) {
  179. let refreshType = process ? RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  180. for (let light of this.scene.lights) {
  181. let generator = light.getShadowGenerator();
  182. if (generator) {
  183. let shadowMap = generator.getShadowMap();
  184. if (shadowMap) {
  185. shadowMap.refreshRate = refreshType;
  186. }
  187. }
  188. }
  189. this._processShadows = process;
  190. }
  191. private _groundEnabled: boolean = true;
  192. public get groundEnabled() {
  193. return this._groundEnabled;
  194. }
  195. public set groundEnabled(newValue: boolean) {
  196. if (newValue === this._groundEnabled) return;
  197. this._groundEnabled = newValue;
  198. if (this.environmentHelper && this.environmentHelper.ground) {
  199. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  200. }
  201. }
  202. private _groundMirrorEnabled = false;
  203. /**
  204. * gets wether the reflection is disabled.
  205. */
  206. public get groundMirrorEnabled(): boolean {
  207. return this._groundMirrorEnabled;
  208. }
  209. /**
  210. * sets wether the reflection is disabled.
  211. */
  212. public set groundMirrorEnabled(value: boolean) {
  213. if (this._groundMirrorEnabled === value) {
  214. return;
  215. }
  216. this._groundMirrorEnabled = value;
  217. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  218. if (value) {
  219. this.environmentHelper.groundMaterial.reflectionTexture = null;
  220. } else {
  221. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  222. }
  223. }
  224. }
  225. private _defaultRenderingPipelineEnabled: boolean = false;
  226. public get defaultRenderingPipelineEnabled() {
  227. return this._defaultRenderingPipelineEnabled;
  228. }
  229. public set defaultRenderingPipelineEnabled(value: boolean) {
  230. if (value === this._defaultRenderingPipelineEnabled) {
  231. return;
  232. }
  233. this._defaultRenderingPipelineEnabled = value;
  234. this._rebuildPostprocesses();
  235. if (this._defaultRenderingPipeline) {
  236. this._defaultRenderingPipelineShouldBuild = false;
  237. this._defaultRenderingPipeline.prepare();
  238. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  239. }
  240. }
  241. /**
  242. * Sets the engine flags to unlock all babylon features.
  243. * Can also be configured using the scene.flags configuration object
  244. */
  245. public unlockBabylonFeatures() {
  246. this.scene.shadowsEnabled = true;
  247. this.scene.particlesEnabled = true;
  248. this.scene.postProcessesEnabled = true;
  249. this.scene.collisionsEnabled = true;
  250. this.scene.lightsEnabled = true;
  251. this.scene.texturesEnabled = true;
  252. this.scene.lensFlaresEnabled = true;
  253. this.scene.proceduralTexturesEnabled = true;
  254. this.scene.renderTargetsEnabled = true;
  255. this.scene.spritesEnabled = true;
  256. this.scene.skeletonsEnabled = true;
  257. this.scene.audioEnabled = true;
  258. }
  259. /**
  260. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  261. */
  262. public initScene(sceneConfiguration: ISceneConfiguration = {}, optimizerConfiguration?: boolean | ISceneOptimizerConfiguration): Promise<Scene> {
  263. // if the scen exists, dispose it.
  264. if (this.scene) {
  265. this.scene.dispose();
  266. }
  267. // create a new scene
  268. this.scene = new Scene(this._viewer.engine);
  269. // TODO - is this needed, now that Babylon is integrated?
  270. // set a default PBR material
  271. if (!sceneConfiguration.defaultMaterial) {
  272. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  273. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  274. defaultMaterial.microSurface = 0.6;
  275. if (this.scene.defaultMaterial) {
  276. this.scene.defaultMaterial.dispose();
  277. }
  278. this.scene.defaultMaterial = defaultMaterial;
  279. }
  280. this.scene.animationPropertiesOverride = new AnimationPropertiesOverride();
  281. Animation.AllowMatricesInterpolation = true;
  282. this._mainColor = Color3.White();
  283. if (sceneConfiguration.glow) {
  284. let options: Partial<IGlowLayerOptions> = {
  285. mainTextureFixedSize: 512
  286. };
  287. if (typeof sceneConfiguration.glow === 'object') {
  288. options = sceneConfiguration.glow
  289. }
  290. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  291. }
  292. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  293. }
  294. public clearScene(clearModels: boolean = true, clearLights: boolean = false) {
  295. if (clearModels) {
  296. this.models.forEach(m => m.dispose());
  297. this.models.length = 0;
  298. }
  299. if (clearLights) {
  300. this.scene.lights.forEach(l => l.dispose());
  301. }
  302. }
  303. /**
  304. * This will update the scene's configuration, including camera, lights, environment.
  305. * @param newConfiguration the delta that should be configured. This includes only the changes
  306. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  307. */
  308. public updateConfiguration(newConfiguration: Partial<ViewerConfiguration>, globalConfiguration: ViewerConfiguration, model?: ViewerModel) {
  309. if (newConfiguration.lab) {
  310. if (newConfiguration.lab.assetsRootURL) {
  311. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  312. }
  313. }
  314. // update scene configuration
  315. if (newConfiguration.scene) {
  316. this._configureScene(newConfiguration.scene);
  317. }
  318. // optimizer
  319. if (newConfiguration.optimizer) {
  320. this._configureOptimizer(newConfiguration.optimizer);
  321. }
  322. // configure model
  323. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  324. this._configureModel(newConfiguration.model);
  325. }*/
  326. // lights
  327. this._configureLights(newConfiguration.lights, model);
  328. // environment
  329. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  330. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground, model);
  331. }
  332. // camera
  333. this._configureCamera(newConfiguration.camera, model);
  334. if (newConfiguration.lab) {
  335. if (newConfiguration.lab.environmentMap) {
  336. let rot = newConfiguration.lab.environmentMap.rotationY;
  337. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, () => {
  338. this.labs.applyEnvironmentMapConfiguration(rot);
  339. });
  340. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  341. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  342. }
  343. }
  344. // rendering piplines
  345. if (newConfiguration.lab.defaultRenderingPipelines) {
  346. let pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  347. if (typeof pipelineConfig === 'boolean') {
  348. this.defaultRenderingPipelineEnabled = pipelineConfig;
  349. } else {
  350. this.defaultRenderingPipelineEnabled = true;
  351. }
  352. }
  353. }
  354. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  355. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  356. }
  357. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  358. this._defaultRenderingPipelineShouldBuild = false;
  359. this._defaultRenderingPipeline.prepare();
  360. }
  361. }
  362. private _defaultRenderingPipelineShouldBuild: boolean = true;
  363. private _rebuildPostprocesses(configuration?: IDefaultRenderingPipelineConfiguration): void {
  364. if (!this.defaultRenderingPipelineEnabled || !getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._viewer.configuration)) {
  365. if (this._defaultRenderingPipeline) {
  366. this._defaultRenderingPipeline.dispose();
  367. this._defaultRenderingPipeline = null;
  368. this.scene.autoClearDepthAndStencil = true;
  369. this.scene.autoClear = true;
  370. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  371. }
  372. return;
  373. }
  374. let pipelineConfig = configuration || (this._viewer.configuration.lab && this._viewer.configuration.lab.defaultRenderingPipelines);
  375. if (pipelineConfig) {
  376. if (!this._defaultRenderingPipeline) {
  377. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  378. this._defaultRenderingPipeline = new DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  379. }
  380. this.scene.autoClear = false;
  381. this.scene.autoClearDepthAndStencil = false;
  382. this._defaultRenderingPipelineShouldBuild = true;
  383. let bloomEnabled = this._bloomEnabled;
  384. if (typeof pipelineConfig !== 'boolean') {
  385. extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  386. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  387. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  388. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  389. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  390. }
  391. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  392. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  393. }
  394. }
  395. // default from rendering pipeline
  396. private _bloomEnabled: boolean = false;
  397. public get bloomEnabled() {
  398. return this._bloomEnabled;
  399. }
  400. public set bloomEnabled(value: boolean) {
  401. if (this._bloomEnabled === value) {
  402. return;
  403. }
  404. this._bloomEnabled = value;
  405. this._rebuildPostprocesses();
  406. if (this._defaultRenderingPipeline) {
  407. this._defaultRenderingPipelineShouldBuild = false;
  408. this._defaultRenderingPipeline.prepare();
  409. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  410. }
  411. }
  412. // default from rendering pipeline
  413. private _fxaaEnabled: boolean = false;
  414. public get fxaaEnabled() {
  415. return this._fxaaEnabled;
  416. }
  417. public set fxaaEnabled(value: boolean) {
  418. if (this._fxaaEnabled === value) {
  419. return;
  420. }
  421. this._fxaaEnabled = value;
  422. this._rebuildPostprocesses();
  423. if (this._defaultRenderingPipeline) {
  424. this._defaultRenderingPipelineShouldBuild = false;
  425. this._defaultRenderingPipeline.prepare();
  426. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  427. }
  428. }
  429. /**
  430. * internally configure the scene using the provided configuration.
  431. * The scene will not be recreated, but just updated.
  432. * @param sceneConfig the (new) scene configuration
  433. */
  434. protected _configureScene(sceneConfig: ISceneConfiguration) {
  435. // sanity check!
  436. if (!this.scene) {
  437. return;
  438. }
  439. let cc = sceneConfig.clearColor;
  440. let oldcc = this.scene.clearColor;
  441. if (cc) {
  442. if (cc.r !== undefined) {
  443. oldcc.r = cc.r;
  444. }
  445. if (cc.g !== undefined) {
  446. oldcc.g = cc.g
  447. }
  448. if (cc.b !== undefined) {
  449. oldcc.b = cc.b
  450. }
  451. if (cc.a !== undefined) {
  452. oldcc.a = cc.a
  453. }
  454. }
  455. // image processing configuration - optional.
  456. if (sceneConfig.imageProcessingConfiguration) {
  457. extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  458. }
  459. //animation properties override
  460. if (sceneConfig.animationPropertiesOverride) {
  461. extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  462. }
  463. if (sceneConfig.environmentTexture) {
  464. if (!(this.scene.environmentTexture && (<CubeTexture>this.scene.environmentTexture).url === sceneConfig.environmentTexture)) {
  465. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  466. this.scene.environmentTexture.dispose();
  467. }
  468. const environmentTexture = CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  469. this.scene.environmentTexture = environmentTexture;
  470. }
  471. }
  472. if (sceneConfig.debug) {
  473. this.scene.debugLayer.show();
  474. } else {
  475. if (this.scene.debugLayer.isVisible()) {
  476. this.scene.debugLayer.hide();
  477. }
  478. }
  479. if (sceneConfig.disableHdr) {
  480. this._handleHardwareLimitations(false);
  481. } else {
  482. this._handleHardwareLimitations(true);
  483. }
  484. if (sceneConfig.renderInBackground !== undefined) {
  485. this._viewer.renderInBackground = !!sceneConfig.renderInBackground;
  486. }
  487. if (this.camera && sceneConfig.disableCameraControl) {
  488. this.camera.detachControl(this._viewer.canvas);
  489. } else if (this.camera && sceneConfig.disableCameraControl === false) {
  490. this.camera.attachControl(this._viewer.canvas);
  491. }
  492. // process mainColor changes:
  493. if (sceneConfig.mainColor) {
  494. this._mainColor = this._mainColor || Color3.White();
  495. let mc = sceneConfig.mainColor;
  496. if (mc.r !== undefined) {
  497. this._mainColor.r = mc.r;
  498. }
  499. if (mc.g !== undefined) {
  500. this._mainColor.g = mc.g
  501. }
  502. if (mc.b !== undefined) {
  503. this._mainColor.b = mc.b
  504. }
  505. this._reflectionColor.copyFrom(this.mainColor);
  506. if (this._viewer.configuration.camera && this._viewer.configuration.camera.exposure) {
  507. let environmentTint = getConfigurationKey("lab.environmentMap.tintLevel", this._viewer.configuration) || 0;
  508. /*this._mainColor.toLinearSpaceToRef(this._mainColor);
  509. let exposure = Math.pow(2.0, -(this._viewer.configuration.camera.exposure) * Math.PI);
  510. this._mainColor.scaleToRef(1 / exposure, this._mainColor);
  511. let tmpColor = Color3.Lerp(this._white, this._mainColor, environmentTint);
  512. this._mainColor.copyFrom(tmpColor);*/
  513. // reflection color
  514. this._reflectionColor.toLinearSpaceToRef(this._reflectionColor);
  515. this._reflectionColor.scaleToRef(1 / this._viewer.configuration.camera.exposure, this._reflectionColor);
  516. let tmpColor3 = Color3.Lerp(this._white, this._reflectionColor, environmentTint);
  517. this._reflectionColor.copyFrom(tmpColor3);
  518. }
  519. //update the environment, if exists
  520. if (this.environmentHelper) {
  521. if (this.environmentHelper.groundMaterial) {
  522. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  523. }
  524. if (this.environmentHelper.skyboxMaterial) {
  525. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  526. }
  527. }
  528. }
  529. if (sceneConfig.defaultMaterial) {
  530. let conf = sceneConfig.defaultMaterial;
  531. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  532. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  533. this.scene.defaultMaterial.dispose();
  534. if (conf.materialType === 'standard') {
  535. this.scene.defaultMaterial = new StandardMaterial("defaultMaterial", this.scene);
  536. } else {
  537. this.scene.defaultMaterial = new PBRMaterial("defaultMaterial", this.scene);
  538. }
  539. }
  540. extendClassWithConfig(this.scene.defaultMaterial, conf);
  541. }
  542. if (sceneConfig.flags) {
  543. extendClassWithConfig(this.scene, sceneConfig.flags);
  544. }
  545. this.onSceneConfiguredObservable.notifyObservers({
  546. sceneManager: this,
  547. object: this.scene,
  548. newConfiguration: sceneConfig
  549. });
  550. }
  551. /**
  552. * Configure the scene optimizer.
  553. * The existing scene optimizer will be disposed and a new one will be created.
  554. * @param optimizerConfig the (new) optimizer configuration
  555. */
  556. protected _configureOptimizer(optimizerConfig: ISceneOptimizerConfiguration | boolean) {
  557. if (typeof optimizerConfig === 'boolean') {
  558. if (this.sceneOptimizer) {
  559. this.sceneOptimizer.stop();
  560. this.sceneOptimizer.dispose();
  561. delete this.sceneOptimizer;
  562. }
  563. if (optimizerConfig) {
  564. this.sceneOptimizer = new SceneOptimizer(this.scene);
  565. this.sceneOptimizer.start();
  566. }
  567. } else {
  568. let optimizerOptions: SceneOptimizerOptions = new SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  569. // check for degradation
  570. if (optimizerConfig.degradation) {
  571. switch (optimizerConfig.degradation) {
  572. case "low":
  573. optimizerOptions = SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  574. break;
  575. case "moderate":
  576. optimizerOptions = SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  577. break;
  578. case "hight":
  579. optimizerOptions = SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  580. break;
  581. }
  582. }
  583. if (this.sceneOptimizer) {
  584. this.sceneOptimizer.stop();
  585. this.sceneOptimizer.dispose()
  586. }
  587. if (optimizerConfig.custom) {
  588. let customOptimizer = getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  589. if (customOptimizer) {
  590. optimizerOptions.addCustomOptimization(() => {
  591. return customOptimizer(this._viewer);
  592. }, () => {
  593. return `Babylon Viewer ${optimizerConfig.custom} custom optimization`;
  594. });
  595. }
  596. }
  597. this.sceneOptimizer = new SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  598. this.sceneOptimizer.start();
  599. }
  600. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  601. sceneManager: this,
  602. object: this.sceneOptimizer,
  603. newConfiguration: optimizerConfig
  604. });
  605. }
  606. /**
  607. * configure all models using the configuration.
  608. * @param modelConfiguration the configuration to use to reconfigure the models
  609. */
  610. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  611. this.models.forEach(model => {
  612. model.updateConfiguration(modelConfiguration);
  613. });
  614. this.onModelsConfiguredObservable.notifyObservers({
  615. sceneManager: this,
  616. object: this.models,
  617. newConfiguration: modelConfiguration
  618. });
  619. }*/
  620. /**
  621. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  622. * @param cameraConfig the new camera configuration
  623. * @param model optionally use the model to configure the camera.
  624. */
  625. protected _configureCamera(cameraConfig: ICameraConfiguration = {}, model?: ViewerModel) {
  626. if (!this.scene.activeCamera) {
  627. let attachControl = true;
  628. if (this._viewer.configuration.scene && this._viewer.configuration.scene.disableCameraControl) {
  629. attachControl = false;
  630. }
  631. this.scene.createDefaultCamera(true, true, attachControl);
  632. this.camera = <ArcRotateCamera>this.scene.activeCamera!;
  633. this.camera.setTarget(Vector3.Zero());
  634. }
  635. if (cameraConfig.position) {
  636. let newPosition = this.camera.position.clone();
  637. extendClassWithConfig(newPosition, cameraConfig.position);
  638. this.camera.setPosition(newPosition);
  639. }
  640. if (cameraConfig.target) {
  641. let newTarget = this.camera.target.clone();
  642. extendClassWithConfig(newTarget, cameraConfig.target);
  643. this.camera.setTarget(newTarget);
  644. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  645. this._focusOnModel(this.models[0]);
  646. }*/
  647. if (cameraConfig.rotation) {
  648. this.camera.rotationQuaternion = new Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0)
  649. }
  650. if (cameraConfig.behaviors) {
  651. for (let name in cameraConfig.behaviors) {
  652. if (cameraConfig.behaviors[name]) {
  653. this._setCameraBehavior(cameraConfig.behaviors[name]);
  654. }
  655. }
  656. };
  657. const sceneExtends = this.scene.getWorldExtends((mesh) => {
  658. return !this.environmentHelper || (mesh !== this.environmentHelper.ground && mesh !== this.environmentHelper.rootMesh && mesh !== this.environmentHelper.skybox);
  659. });
  660. const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  661. const sceneDiagonalLenght = sceneDiagonal.length();
  662. if (isFinite(sceneDiagonalLenght))
  663. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  664. else {
  665. this.camera.upperRadiusLimit = 10;
  666. }
  667. // sanity check!
  668. if (this.scene.imageProcessingConfiguration) {
  669. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  670. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  671. if (cameraConfig.contrast !== undefined)
  672. this.scene.imageProcessingConfiguration.contrast = cameraConfig.contrast;
  673. if (cameraConfig.exposure !== undefined)
  674. this.scene.imageProcessingConfiguration.exposure = cameraConfig.exposure;
  675. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!cameraConfig.toneMappingEnabled;
  676. }
  677. extendClassWithConfig(this.camera, cameraConfig);
  678. this.onCameraConfiguredObservable.notifyObservers({
  679. sceneManager: this,
  680. object: this.camera,
  681. newConfiguration: cameraConfig,
  682. model
  683. });
  684. }
  685. private _focusOnModel = (model: ViewerModel) => {
  686. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  687. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  688. const halfSizeVec = sizeVec.scale(0.5);
  689. const center = boundingInfo.min.add(halfSizeVec);
  690. this.camera.setTarget(center);
  691. this.camera.alpha = (this._viewer.configuration.camera && this._viewer.configuration.camera.alpha) || this.camera.alpha;
  692. this.camera.beta = (this._viewer.configuration.camera && this._viewer.configuration.camera.beta) || this.camera.beta;
  693. this.camera.radius = (this._viewer.configuration.camera && this._viewer.configuration.camera.radius) || this.camera.radius;
  694. }
  695. protected _configureEnvironment(skyboxConifguration?: ISkyboxConfiguration | boolean, groundConfiguration?: IGroundConfiguration | boolean, model?: ViewerModel) {
  696. if (!skyboxConifguration && !groundConfiguration) {
  697. if (this.environmentHelper) {
  698. this.environmentHelper.dispose();
  699. delete this.environmentHelper;
  700. };
  701. return Promise.resolve(this.scene);
  702. }
  703. const options: Partial<IEnvironmentHelperOptions> = {
  704. createGround: !!groundConfiguration && this._groundEnabled,
  705. createSkybox: !!skyboxConifguration,
  706. setupImageProcessing: false, // will be done at the scene level!,
  707. };
  708. // will that cause problems with model ground configuration?
  709. /*if (model) {
  710. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  711. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  712. const halfSizeVec = sizeVec.scale(0.5);
  713. const center = boundingInfo.min.add(halfSizeVec);
  714. options.groundYBias = -center.y;
  715. }*/
  716. if (groundConfiguration) {
  717. let groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  718. let groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  719. if (groundSize) {
  720. options.groundSize = groundSize;
  721. }
  722. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  723. if (groundConfig.shadowLevel !== undefined) {
  724. options.groundShadowLevel = groundConfig.shadowLevel;
  725. }
  726. options.enableGroundMirror = !!groundConfig.mirror && this.groundMirrorEnabled;
  727. if (groundConfig.texture) {
  728. options.groundTexture = this.labs.getAssetUrl(groundConfig.texture);
  729. }
  730. if (groundConfig.color) {
  731. options.groundColor = new Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b)
  732. }
  733. if (groundConfig.opacity !== undefined) {
  734. options.groundOpacity = groundConfig.opacity;
  735. }
  736. if (groundConfig.mirror) {
  737. options.enableGroundMirror = true;
  738. // to prevent undefines
  739. if (typeof groundConfig.mirror === "object") {
  740. if (groundConfig.mirror.amount !== undefined)
  741. options.groundMirrorAmount = groundConfig.mirror.amount;
  742. if (groundConfig.mirror.sizeRatio !== undefined)
  743. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  744. if (groundConfig.mirror.blurKernel !== undefined)
  745. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  746. if (groundConfig.mirror.fresnelWeight !== undefined)
  747. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  748. if (groundConfig.mirror.fallOffDistance !== undefined)
  749. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  750. if (this._defaultPipelineTextureType !== undefined)
  751. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  752. }
  753. }
  754. }
  755. let postInitSkyboxMaterial = false;
  756. if (skyboxConifguration) {
  757. let conf = skyboxConifguration === true ? {} : skyboxConifguration;
  758. if (conf.material && conf.material.imageProcessingConfiguration) {
  759. options.setupImageProcessing = false; // will be configured later manually.
  760. }
  761. let skyboxSize = conf.scale;
  762. if (skyboxSize) {
  763. options.skyboxSize = skyboxSize;
  764. }
  765. options.sizeAuto = !options.skyboxSize;
  766. if (conf.color) {
  767. options.skyboxColor = new Color3(conf.color.r, conf.color.g, conf.color.b)
  768. }
  769. if (conf.cubeTexture && conf.cubeTexture.url) {
  770. if (typeof conf.cubeTexture.url === "string") {
  771. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  772. } else {
  773. // init later!
  774. postInitSkyboxMaterial = true;
  775. }
  776. }
  777. if (conf.material) {
  778. postInitSkyboxMaterial = true;
  779. }
  780. }
  781. options.setupImageProcessing = false; // TMP
  782. if (!this.environmentHelper) {
  783. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  784. } else {
  785. // there might be a new scene! we need to dispose.
  786. // get the scene used by the envHelper
  787. let scene: Scene = this.environmentHelper.rootMesh.getScene();
  788. // is it a different scene? Oh no!
  789. if (scene !== this.scene) {
  790. this.environmentHelper.dispose();
  791. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  792. } else {
  793. this.environmentHelper.updateOptions(options)!;
  794. }
  795. }
  796. if (this.environmentHelper.rootMesh && this._viewer.configuration.scene && this._viewer.configuration.scene.environmentRotationY !== undefined) {
  797. this.environmentHelper.rootMesh.rotation.y = this._viewer.configuration.scene.environmentRotationY;
  798. }
  799. if (this._viewer.configuration.scene && this._viewer.configuration.scene.environmentMainColor) {
  800. let mainColor = new Color3().copyFrom(this._viewer.configuration.scene.environmentMainColor as Color3);
  801. this.environmentHelper.setMainColor(mainColor);
  802. }
  803. let groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  804. if (this.environmentHelper.groundMaterial && groundConfig && groundConfig.material) {
  805. //if (!this.environmentHelper.groundMaterial._perceptualColor) {
  806. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  807. //}
  808. //this.environmentHelper.groundMaterial._perceptualColor.copyFrom(this.mainColor);
  809. // to be configured using the configuration object
  810. /*this.environmentHelper.groundMaterial.primaryColorHighlightLevel = groundConfig.material.highlightLevel;
  811. this.environmentHelper.groundMaterial.primaryColorShadowLevel = groundConfig.material.shadowLevel;
  812. this.environmentHelper.groundMaterial.enableNoise = true;
  813. if (this.environmentHelper.groundMaterial.diffuseTexture) {
  814. this.environmentHelper.groundMaterial.diffuseTexture.gammaSpace = true;
  815. }
  816. this.environmentHelper.groundMaterial.useRGBColor = false;
  817. this.environmentHelper.groundMaterial.maxSimultaneousLights = 1;*/
  818. extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  819. if (this.environmentHelper.groundMirror) {
  820. const mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  821. //let exposure = Math.pow(2.0, -this.configuration.camera.exposure) * Math.PI;
  822. //mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  823. // TODO use highlight if required
  824. this.environmentHelper.groundMirror.clearColor.r = Scalar.Clamp(mirrorClearColor.r);
  825. this.environmentHelper.groundMirror.clearColor.g = Scalar.Clamp(mirrorClearColor.g);
  826. this.environmentHelper.groundMirror.clearColor.b = Scalar.Clamp(mirrorClearColor.b);
  827. this.environmentHelper.groundMirror.clearColor.a = 1;
  828. if (!this.groundMirrorEnabled) {
  829. this.environmentHelper.groundMaterial.reflectionTexture = null;
  830. }
  831. }
  832. }
  833. let skyboxMaterial = this.environmentHelper.skyboxMaterial;
  834. if (skyboxMaterial) {
  835. skyboxMaterial._perceptualColor = this.mainColor;
  836. if (postInitSkyboxMaterial) {
  837. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  838. extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  839. }
  840. }
  841. }
  842. this._viewer.onModelLoadedObservable.add((model) => {
  843. this._updateGroundMirrorRenderList(model);
  844. });
  845. this.onEnvironmentConfiguredObservable.notifyObservers({
  846. sceneManager: this,
  847. object: this.environmentHelper,
  848. newConfiguration: {
  849. skybox: skyboxConifguration,
  850. ground: groundConfiguration
  851. },
  852. model
  853. });
  854. }
  855. /**
  856. * configure the lights.
  857. *
  858. * @param lightsConfiguration the (new) light(s) configuration
  859. * @param model optionally use the model to configure the camera.
  860. */
  861. protected _configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean } = {}, model?: ViewerModel) {
  862. // sanity check!
  863. if (!Object.keys(lightsConfiguration).length) {
  864. if (!this.scene.lights.length)
  865. this.scene.createDefaultLight(true);
  866. return;
  867. };
  868. let lightsAvailable: Array<string> = this.scene.lights.map(light => light.name);
  869. // compare to the global (!) configuration object and dispose unneeded:
  870. let lightsToConfigure = Object.keys(this._viewer.configuration.lights || []);
  871. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  872. lightsAvailable.forEach(lName => {
  873. if (lightsToConfigure.indexOf(lName) === -1) {
  874. this.scene.getLightByName(lName)!.dispose();
  875. }
  876. });
  877. }
  878. Object.keys(lightsConfiguration).forEach((name, idx) => {
  879. let lightConfig: ILightConfiguration = { type: 0 };
  880. if (typeof lightsConfiguration[name] === 'object') {
  881. lightConfig = <ILightConfiguration>lightsConfiguration[name];
  882. }
  883. lightConfig.name = name;
  884. let light: Light;
  885. // light is not already available
  886. if (lightsAvailable.indexOf(name) === -1) {
  887. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  888. if (!constructor) return;
  889. light = constructor();
  890. } else {
  891. // available? get it from the scene
  892. light = <Light>this.scene.getLightByName(name);
  893. lightsAvailable = lightsAvailable.filter(ln => ln !== name);
  894. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  895. light.dispose();
  896. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  897. if (!constructor) return;
  898. light = constructor();
  899. }
  900. }
  901. // if config set the light to false, dispose it.
  902. if (lightsConfiguration[name] === false) {
  903. light.dispose();
  904. return;
  905. }
  906. //enabled
  907. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  908. light.setEnabled(enabled);
  909. extendClassWithConfig(light, lightConfig);
  910. //position. Some lights don't support shadows
  911. if (light instanceof ShadowLight) {
  912. // set default values
  913. light.shadowMinZ = light.shadowMinZ || 0.2;
  914. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  915. if (lightConfig.target) {
  916. if (light.setDirectionToTarget) {
  917. let target = Vector3.Zero().copyFrom(lightConfig.target as Vector3);
  918. light.setDirectionToTarget(target);
  919. }
  920. } else if (lightConfig.direction) {
  921. let direction = Vector3.Zero().copyFrom(lightConfig.direction as Vector3);
  922. light.direction = direction;
  923. }
  924. let isShadowEnabled = false;
  925. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  926. (<BABYLON.DirectionalLight>light).shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  927. isShadowEnabled = true;
  928. }
  929. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  930. let spotLight: BABYLON.SpotLight = <BABYLON.SpotLight>light;
  931. if (lightConfig.spotAngle !== undefined) {
  932. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  933. }
  934. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  935. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  936. }
  937. isShadowEnabled = true;
  938. }
  939. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  940. if (lightConfig.shadowFieldOfView) {
  941. (<BABYLON.PointLight>light).shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  942. }
  943. isShadowEnabled = true;
  944. }
  945. let shadowGenerator = <BABYLON.ShadowGenerator>light.getShadowGenerator();
  946. if (isShadowEnabled && lightConfig.shadowEnabled && this._maxShadows) {
  947. let bufferSize = lightConfig.shadowBufferSize || 256;
  948. if (!shadowGenerator) {
  949. shadowGenerator = new ShadowGenerator(bufferSize, light);
  950. // TODO blur kernel definition ?
  951. }
  952. var blurKernel = this.getBlurKernel(light, bufferSize);
  953. shadowGenerator.bias = this._shadowGeneratorBias;
  954. shadowGenerator.blurKernel = blurKernel;
  955. //override defaults
  956. extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  957. // add the focues meshes to the shadow list
  958. this._viewer.onModelLoadedObservable.add((model) => {
  959. this._updateShadowRenderList(shadowGenerator, model);
  960. });
  961. //if (model) {
  962. this._updateShadowRenderList(shadowGenerator, model);
  963. //}
  964. } else if (shadowGenerator) {
  965. shadowGenerator.dispose();
  966. }
  967. }
  968. });
  969. // render priority
  970. let globalLightsConfiguration = this._viewer.configuration.lights || {};
  971. Object.keys(globalLightsConfiguration).sort().forEach((name, idx) => {
  972. let configuration = globalLightsConfiguration[name];
  973. let light = this.scene.getLightByName(name);
  974. // sanity check
  975. if (!light) return;
  976. light.renderPriority = -idx;
  977. });
  978. this.onLightsConfiguredObservable.notifyObservers({
  979. sceneManager: this,
  980. object: this.scene.lights,
  981. newConfiguration: lightsConfiguration,
  982. model
  983. });
  984. }
  985. private _shadowGroundPlane: Nullable<AbstractMesh>;
  986. private _updateShadowRenderList(shadowGenerator: ShadowGenerator, model?: ViewerModel, resetList?: boolean) {
  987. let focusMeshes = model ? model.meshes : this.scene.meshes;
  988. // add the focues meshes to the shadow list
  989. let shadownMap = shadowGenerator.getShadowMap();
  990. if (!shadownMap) return;
  991. if (resetList && shadownMap.renderList) {
  992. shadownMap.renderList.length = 0;
  993. } else {
  994. shadownMap.renderList = shadownMap.renderList || []
  995. }
  996. for (var index = 0; index < focusMeshes.length; index++) {
  997. let mesh = focusMeshes[index];
  998. if (Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  999. shadownMap.renderList.push(mesh);
  1000. }
  1001. }
  1002. if (!this._shadowGroundPlane) {
  1003. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  1004. let shadowGroundPlane = Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  1005. shadowGroundPlane.useVertexColors = false;
  1006. //material isn't ever used in rendering, just used to set back face culling
  1007. shadowGroundPlane.material = new StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  1008. shadowGroundPlane.material.backFaceCulling = false;
  1009. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  1010. shadowGroundPlane.freezeWorldMatrix();
  1011. this._shadowGroundPlane = shadowGroundPlane;
  1012. this.scene.removeMesh(shadowGroundPlane);
  1013. }
  1014. } else {
  1015. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  1016. this._shadowGroundPlane.dispose();
  1017. this._shadowGroundPlane = null;
  1018. }
  1019. }
  1020. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  1021. shadownMap.renderList.push(this._shadowGroundPlane);
  1022. }
  1023. }
  1024. private _updateGroundMirrorRenderList(model?: ViewerModel, resetList?: boolean) {
  1025. if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  1026. let focusMeshes = model ? model.meshes : this.scene.meshes;
  1027. let renderList = this.environmentHelper.groundMirror.renderList;
  1028. if (resetList) {
  1029. renderList.length = 0;
  1030. }
  1031. for (var index = 0; index < focusMeshes.length; index++) {
  1032. let mesh = focusMeshes[index];
  1033. if (renderList.indexOf(mesh) === -1) {
  1034. renderList.push(mesh);
  1035. }
  1036. }
  1037. }
  1038. }
  1039. /**
  1040. * Gets the shadow map blur kernel according to the light configuration.
  1041. * @param light The light used to generate the shadows
  1042. * @param bufferSize The size of the shadow map
  1043. * @return the kernel blur size
  1044. */
  1045. public getBlurKernel(light: BABYLON.IShadowLight, bufferSize: number): number {
  1046. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  1047. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  1048. normalizedBlurKernel = normalizedBlurKernel / (<BABYLON.DirectionalLight>light).shadowFrustumSize;
  1049. }
  1050. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  1051. normalizedBlurKernel = normalizedBlurKernel / (<BABYLON.PointLight>light).shadowAngle;
  1052. }
  1053. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  1054. normalizedBlurKernel = normalizedBlurKernel / ((<BABYLON.SpotLight>light).angle * (<BABYLON.SpotLight>light).shadowAngleScale);
  1055. }
  1056. let minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  1057. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  1058. return blurKernel;
  1059. }
  1060. /**
  1061. * Alters render settings to reduce features based on hardware feature limitations
  1062. * @param enableHDR Allows the viewer to run in HDR mode.
  1063. */
  1064. protected _handleHardwareLimitations(enableHDR = true) {
  1065. //flip rendering settings switches based on hardware support
  1066. let maxVaryingRows = this._viewer.engine.getCaps().maxVaryingVectors;
  1067. let maxFragmentSamplers = this._viewer.engine.getCaps().maxTexturesImageUnits;
  1068. //shadows are disabled if there's not enough varyings for a single shadow
  1069. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  1070. this._maxShadows = 0;
  1071. } else {
  1072. this._maxShadows = 3;
  1073. }
  1074. //can we render to any >= 16-bit targets (required for HDR)
  1075. let caps = this._viewer.engine.getCaps();
  1076. let linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  1077. let linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  1078. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  1079. if (linearHalfFloatTargets) {
  1080. this._defaultHighpTextureType = Engine.TEXTURETYPE_HALF_FLOAT;
  1081. this._shadowGeneratorBias = 0.002;
  1082. } else if (linearFloatTargets) {
  1083. this._defaultHighpTextureType = Engine.TEXTURETYPE_FLOAT;
  1084. this._shadowGeneratorBias = 0.001;
  1085. } else {
  1086. this._defaultHighpTextureType = Engine.TEXTURETYPE_UNSIGNED_INT;
  1087. this._shadowGeneratorBias = 0.001;
  1088. }
  1089. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : Engine.TEXTURETYPE_UNSIGNED_INT;
  1090. }
  1091. /**
  1092. * Dispoe the entire viewer including the scene and the engine
  1093. */
  1094. public dispose() {
  1095. // this.onCameraConfiguredObservable.clear();
  1096. this.onEnvironmentConfiguredObservable.clear();
  1097. this.onLightsConfiguredObservable.clear();
  1098. this.onModelsConfiguredObservable.clear();
  1099. this.onSceneConfiguredObservable.clear();
  1100. this.onSceneInitObservable.clear();
  1101. this.onSceneOptimizerConfiguredObservable.clear();
  1102. if (this.sceneOptimizer) {
  1103. this.sceneOptimizer.stop();
  1104. this.sceneOptimizer.dispose();
  1105. }
  1106. if (this.environmentHelper) {
  1107. this.environmentHelper.dispose();
  1108. }
  1109. this.models.forEach(model => {
  1110. model.dispose();
  1111. });
  1112. if (this._defaultRenderingPipeline) {
  1113. this._defaultRenderingPipeline.dispose();
  1114. }
  1115. this.models.length = 0;
  1116. this.scene.dispose();
  1117. }
  1118. private _setCameraBehavior(behaviorConfig: number | {
  1119. type: number;
  1120. [propName: string]: any;
  1121. }, payload?: any) {
  1122. let behavior: Behavior<ArcRotateCamera> | null;
  1123. let type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  1124. let config: { [propName: string]: any } = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  1125. // constructing behavior
  1126. switch (type) {
  1127. case CameraBehavior.AUTOROTATION:
  1128. this.camera.useAutoRotationBehavior = true;
  1129. behavior = this.camera.autoRotationBehavior;
  1130. break;
  1131. case CameraBehavior.BOUNCING:
  1132. this.camera.useBouncingBehavior = true;
  1133. behavior = this.camera.bouncingBehavior;
  1134. break;
  1135. case CameraBehavior.FRAMING:
  1136. this.camera.useFramingBehavior = true;
  1137. behavior = this.camera.framingBehavior;
  1138. break;
  1139. default:
  1140. behavior = null;
  1141. break;
  1142. }
  1143. if (behavior) {
  1144. if (typeof behaviorConfig === "object") {
  1145. extendClassWithConfig(behavior, behaviorConfig);
  1146. }
  1147. }
  1148. // post attach configuration. Some functionalities require the attached camera.
  1149. switch (type) {
  1150. case CameraBehavior.AUTOROTATION:
  1151. break;
  1152. case CameraBehavior.BOUNCING:
  1153. break;
  1154. case CameraBehavior.FRAMING:
  1155. this._viewer.onModelLoadedObservable.add((model) => {
  1156. if (config.zoomOnBoundingInfo) {
  1157. (<FramingBehavior>behavior).zoomOnMeshHierarchy(model.rootMesh);
  1158. }
  1159. });
  1160. break;
  1161. }
  1162. }
  1163. }