sceneManager.ts 65 KB

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