postProcess.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. import { Nullable } from "../types";
  2. import { SmartArray } from "../Misc/smartArray";
  3. import { Observable, Observer } from "../Misc/observable";
  4. import { Vector2 } from "../Maths/math.vector";
  5. import { Camera } from "../Cameras/camera";
  6. import { Effect } from "../Materials/effect";
  7. import { Constants } from "../Engines/constants";
  8. import "../Shaders/postprocess.vertex";
  9. import { IInspectable } from '../Misc/iInspectable';
  10. import { Engine } from '../Engines/engine';
  11. import { Color4 } from '../Maths/math.color';
  12. import "../Engines/Extensions/engine.renderTarget";
  13. declare type Scene = import("../scene").Scene;
  14. declare type InternalTexture = import("../Materials/Textures/internalTexture").InternalTexture;
  15. declare type WebVRFreeCamera = import("../Cameras/VR/webVRCamera").WebVRFreeCamera;
  16. declare type Animation = import("../Animations/animation").Animation;
  17. /**
  18. * Size options for a post process
  19. */
  20. export type PostProcessOptions = { width: number, height: number };
  21. /**
  22. * PostProcess can be used to apply a shader to a texture after it has been rendered
  23. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  24. */
  25. export class PostProcess {
  26. /**
  27. * Gets or sets the unique id of the post process
  28. */
  29. public uniqueId: number;
  30. /**
  31. * Width of the texture to apply the post process on
  32. */
  33. public width = -1;
  34. /**
  35. * Height of the texture to apply the post process on
  36. */
  37. public height = -1;
  38. /**
  39. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  40. * @hidden
  41. */
  42. public _outputTexture: Nullable<InternalTexture> = null;
  43. /**
  44. * Sampling mode used by the shader
  45. * See https://doc.babylonjs.com/classes/3.1/texture
  46. */
  47. public renderTargetSamplingMode: number;
  48. /**
  49. * Clear color to use when screen clearing
  50. */
  51. public clearColor: Color4;
  52. /**
  53. * If the buffer needs to be cleared before applying the post process. (default: true)
  54. * Should be set to false if shader will overwrite all previous pixels.
  55. */
  56. public autoClear = true;
  57. /**
  58. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59. */
  60. public alphaMode = Constants.ALPHA_DISABLE;
  61. /**
  62. * Sets the setAlphaBlendConstants of the babylon engine
  63. */
  64. public alphaConstants: Color4;
  65. /**
  66. * Animations to be used for the post processing
  67. */
  68. public animations = new Array<Animation>();
  69. /**
  70. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  71. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  72. */
  73. public enablePixelPerfectMode = false;
  74. /**
  75. * Force the postprocess to be applied without taking in account viewport
  76. */
  77. public forceFullscreenViewport = true;
  78. /**
  79. * List of inspectable custom properties (used by the Inspector)
  80. * @see https://doc.babylonjs.com/how_to/debug_layer#extensibility
  81. */
  82. public inspectableCustomProperties: IInspectable[];
  83. /**
  84. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  85. *
  86. * | Value | Type | Description |
  87. * | ----- | ----------------------------------- | ----------- |
  88. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  89. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  90. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  91. *
  92. */
  93. public scaleMode = Constants.SCALEMODE_FLOOR;
  94. /**
  95. * Force textures to be a power of two (default: false)
  96. */
  97. public alwaysForcePOT = false;
  98. private _samples = 1;
  99. /**
  100. * Number of sample textures (default: 1)
  101. */
  102. public get samples() {
  103. return this._samples;
  104. }
  105. public set samples(n: number) {
  106. this._samples = Math.min(n, this._engine.getCaps().maxMSAASamples);
  107. this._textures.forEach((texture) => {
  108. if (texture.samples !== this._samples) {
  109. this._engine.updateRenderTargetTextureSampleCount(texture, this._samples);
  110. }
  111. });
  112. }
  113. /**
  114. * Modify the scale of the post process to be the same as the viewport (default: false)
  115. */
  116. public adaptScaleToCurrentViewport = false;
  117. private _camera: Camera;
  118. private _scene: Scene;
  119. private _engine: Engine;
  120. private _options: number | PostProcessOptions;
  121. private _reusable = false;
  122. private _textureType: number;
  123. private _textureFormat: number;
  124. /**
  125. * Smart array of input and output textures for the post process.
  126. * @hidden
  127. */
  128. public _textures = new SmartArray<InternalTexture>(2);
  129. /**
  130. * The index in _textures that corresponds to the output texture.
  131. * @hidden
  132. */
  133. public _currentRenderTextureInd = 0;
  134. private _effect: Effect;
  135. private _samplers: string[];
  136. private _fragmentUrl: string;
  137. private _vertexUrl: string;
  138. private _parameters: string[];
  139. private _scaleRatio = new Vector2(1, 1);
  140. protected _indexParameters: any;
  141. private _shareOutputWithPostProcess: Nullable<PostProcess>;
  142. private _texelSize = Vector2.Zero();
  143. private _forcedOutputTexture: InternalTexture;
  144. /**
  145. * Returns the fragment url or shader name used in the post process.
  146. * @returns the fragment url or name in the shader store.
  147. */
  148. public getEffectName(): string {
  149. return this._fragmentUrl;
  150. }
  151. // Events
  152. /**
  153. * An event triggered when the postprocess is activated.
  154. */
  155. public onActivateObservable = new Observable<Camera>();
  156. private _onActivateObserver: Nullable<Observer<Camera>>;
  157. /**
  158. * A function that is added to the onActivateObservable
  159. */
  160. public set onActivate(callback: Nullable<(camera: Camera) => void>) {
  161. if (this._onActivateObserver) {
  162. this.onActivateObservable.remove(this._onActivateObserver);
  163. }
  164. if (callback) {
  165. this._onActivateObserver = this.onActivateObservable.add(callback);
  166. }
  167. }
  168. /**
  169. * An event triggered when the postprocess changes its size.
  170. */
  171. public onSizeChangedObservable = new Observable<PostProcess>();
  172. private _onSizeChangedObserver: Nullable<Observer<PostProcess>>;
  173. /**
  174. * A function that is added to the onSizeChangedObservable
  175. */
  176. public set onSizeChanged(callback: (postProcess: PostProcess) => void) {
  177. if (this._onSizeChangedObserver) {
  178. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  179. }
  180. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  181. }
  182. /**
  183. * An event triggered when the postprocess applies its effect.
  184. */
  185. public onApplyObservable = new Observable<Effect>();
  186. private _onApplyObserver: Nullable<Observer<Effect>>;
  187. /**
  188. * A function that is added to the onApplyObservable
  189. */
  190. public set onApply(callback: (effect: Effect) => void) {
  191. if (this._onApplyObserver) {
  192. this.onApplyObservable.remove(this._onApplyObserver);
  193. }
  194. this._onApplyObserver = this.onApplyObservable.add(callback);
  195. }
  196. /**
  197. * An event triggered before rendering the postprocess
  198. */
  199. public onBeforeRenderObservable = new Observable<Effect>();
  200. private _onBeforeRenderObserver: Nullable<Observer<Effect>>;
  201. /**
  202. * A function that is added to the onBeforeRenderObservable
  203. */
  204. public set onBeforeRender(callback: (effect: Effect) => void) {
  205. if (this._onBeforeRenderObserver) {
  206. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  207. }
  208. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  209. }
  210. /**
  211. * An event triggered after rendering the postprocess
  212. */
  213. public onAfterRenderObservable = new Observable<Effect>();
  214. private _onAfterRenderObserver: Nullable<Observer<Effect>>;
  215. /**
  216. * A function that is added to the onAfterRenderObservable
  217. */
  218. public set onAfterRender(callback: (efect: Effect) => void) {
  219. if (this._onAfterRenderObserver) {
  220. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  221. }
  222. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  223. }
  224. /**
  225. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  226. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  227. */
  228. public get inputTexture(): InternalTexture {
  229. return this._textures.data[this._currentRenderTextureInd];
  230. }
  231. public set inputTexture(value: InternalTexture) {
  232. this._forcedOutputTexture = value;
  233. }
  234. /**
  235. * Gets the camera which post process is applied to.
  236. * @returns The camera the post process is applied to.
  237. */
  238. public getCamera(): Camera {
  239. return this._camera;
  240. }
  241. /**
  242. * Gets the texel size of the postprocess.
  243. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  244. */
  245. public get texelSize(): Vector2 {
  246. if (this._shareOutputWithPostProcess) {
  247. return this._shareOutputWithPostProcess.texelSize;
  248. }
  249. if (this._forcedOutputTexture) {
  250. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  251. }
  252. return this._texelSize;
  253. }
  254. /**
  255. * Creates a new instance PostProcess
  256. * @param name The name of the PostProcess.
  257. * @param fragmentUrl The url of the fragment shader to be used.
  258. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  259. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  260. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  261. * @param camera The camera to apply the render pass to.
  262. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  263. * @param engine The engine which the post process will be applied. (default: current engine)
  264. * @param reusable If the post process can be reused on the same frame. (default: false)
  265. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  266. * @param textureType Type of textures used when performing the post process. (default: 0)
  267. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  268. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  269. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  270. * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA)
  271. */
  272. constructor(
  273. /** Name of the PostProcess. */
  274. public name: string,
  275. fragmentUrl: string, parameters: Nullable<string[]>, samplers: Nullable<string[]>, options: number | PostProcessOptions, camera: Nullable<Camera>,
  276. samplingMode: number = Constants.TEXTURE_NEAREST_SAMPLINGMODE, engine?: Engine, reusable?: boolean, defines: Nullable<string> = null, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT, vertexUrl: string = "postprocess",
  277. indexParameters?: any, blockCompilation = false, textureFormat = Constants.TEXTUREFORMAT_RGBA) {
  278. if (camera != null) {
  279. this._camera = camera;
  280. this._scene = camera.getScene();
  281. camera.attachPostProcess(this);
  282. this._engine = this._scene.getEngine();
  283. this._scene.postProcesses.push(this);
  284. this.uniqueId = this._scene.getUniqueId();
  285. }
  286. else if (engine) {
  287. this._engine = engine;
  288. this._engine.postProcesses.push(this);
  289. }
  290. this._options = options;
  291. this.renderTargetSamplingMode = samplingMode ? samplingMode : Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  292. this._reusable = reusable || false;
  293. this._textureType = textureType;
  294. this._textureFormat = textureFormat;
  295. this._samplers = samplers || [];
  296. this._samplers.push("textureSampler");
  297. this._fragmentUrl = fragmentUrl;
  298. this._vertexUrl = vertexUrl;
  299. this._parameters = parameters || [];
  300. this._parameters.push("scale");
  301. this._indexParameters = indexParameters;
  302. if (!blockCompilation) {
  303. this.updateEffect(defines);
  304. }
  305. }
  306. /**
  307. * Gets a string idenfifying the name of the class
  308. * @returns "PostProcess" string
  309. */
  310. public getClassName(): string {
  311. return "PostProcess";
  312. }
  313. /**
  314. * Gets the engine which this post process belongs to.
  315. * @returns The engine the post process was enabled with.
  316. */
  317. public getEngine(): Engine {
  318. return this._engine;
  319. }
  320. /**
  321. * The effect that is created when initializing the post process.
  322. * @returns The created effect corresponding the the postprocess.
  323. */
  324. public getEffect(): Effect {
  325. return this._effect;
  326. }
  327. /**
  328. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  329. * @param postProcess The post process to share the output with.
  330. * @returns This post process.
  331. */
  332. public shareOutputWith(postProcess: PostProcess): PostProcess {
  333. this._disposeTextures();
  334. this._shareOutputWithPostProcess = postProcess;
  335. return this;
  336. }
  337. /**
  338. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  339. * This should be called if the post process that shares output with this post process is disabled/disposed.
  340. */
  341. public useOwnOutput() {
  342. if (this._textures.length == 0) {
  343. this._textures = new SmartArray<InternalTexture>(2);
  344. }
  345. this._shareOutputWithPostProcess = null;
  346. }
  347. /**
  348. * Updates the effect with the current post process compile time values and recompiles the shader.
  349. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  350. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  351. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  352. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  353. * @param onCompiled Called when the shader has been compiled.
  354. * @param onError Called if there is an error when compiling a shader.
  355. * @param vertexUrl The url of the vertex shader to be used (default: the one given at construction time)
  356. * @param fragmentUrl The url of the fragment shader to be used (default: the one given at construction time)
  357. */
  358. public updateEffect(defines: Nullable<string> = null, uniforms: Nullable<string[]> = null, samplers: Nullable<string[]> = null, indexParameters?: any,
  359. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, vertexUrl?: string, fragmentUrl?: string) {
  360. this._effect = this._engine.createEffect({ vertex: vertexUrl ?? this._vertexUrl, fragment: fragmentUrl ?? this._fragmentUrl },
  361. ["position"],
  362. uniforms || this._parameters,
  363. samplers || this._samplers,
  364. defines !== null ? defines : "",
  365. undefined,
  366. onCompiled,
  367. onError,
  368. indexParameters || this._indexParameters
  369. );
  370. }
  371. /**
  372. * The post process is reusable if it can be used multiple times within one frame.
  373. * @returns If the post process is reusable
  374. */
  375. public isReusable(): boolean {
  376. return this._reusable;
  377. }
  378. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  379. public markTextureDirty(): void {
  380. this.width = -1;
  381. }
  382. /**
  383. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  384. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  385. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  386. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  387. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  388. * @returns The target texture that was bound to be written to.
  389. */
  390. public activate(camera: Nullable<Camera>, sourceTexture: Nullable<InternalTexture> = null, forceDepthStencil?: boolean): InternalTexture {
  391. camera = camera || this._camera;
  392. var scene = camera.getScene();
  393. var engine = scene.getEngine();
  394. var maxSize = engine.getCaps().maxTextureSize;
  395. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * <number>this._options) | 0;
  396. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * <number>this._options) | 0;
  397. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  398. var webVRCamera = (<WebVRFreeCamera>camera.parent);
  399. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  400. requiredWidth /= 2;
  401. }
  402. var desiredWidth = ((<PostProcessOptions>this._options).width || requiredWidth);
  403. var desiredHeight = (<PostProcessOptions>this._options).height || requiredHeight;
  404. const needMipMaps =
  405. this.renderTargetSamplingMode !== Constants.TEXTURE_NEAREST_LINEAR &&
  406. this.renderTargetSamplingMode !== Constants.TEXTURE_NEAREST_NEAREST &&
  407. this.renderTargetSamplingMode !== Constants.TEXTURE_LINEAR_LINEAR;
  408. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  409. if (this.adaptScaleToCurrentViewport) {
  410. let currentViewport = engine.currentViewport;
  411. if (currentViewport) {
  412. desiredWidth *= currentViewport.width;
  413. desiredHeight *= currentViewport.height;
  414. }
  415. }
  416. if (needMipMaps || this.alwaysForcePOT) {
  417. if (!(<PostProcessOptions>this._options).width) {
  418. desiredWidth = engine.needPOTTextures ? Engine.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  419. }
  420. if (!(<PostProcessOptions>this._options).height) {
  421. desiredHeight = engine.needPOTTextures ? Engine.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  422. }
  423. }
  424. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  425. if (this._textures.length > 0) {
  426. for (var i = 0; i < this._textures.length; i++) {
  427. this._engine._releaseTexture(this._textures.data[i]);
  428. }
  429. this._textures.reset();
  430. }
  431. this.width = desiredWidth;
  432. this.height = desiredHeight;
  433. let textureSize = { width: this.width, height: this.height };
  434. let textureOptions = {
  435. generateMipMaps: needMipMaps,
  436. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  437. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  438. samplingMode: this.renderTargetSamplingMode,
  439. type: this._textureType,
  440. format: this._textureFormat
  441. };
  442. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  443. if (this._reusable) {
  444. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  445. }
  446. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  447. this.onSizeChangedObservable.notifyObservers(this);
  448. }
  449. this._textures.forEach((texture) => {
  450. if (texture.samples !== this.samples) {
  451. this._engine.updateRenderTargetTextureSampleCount(texture, this.samples);
  452. }
  453. });
  454. }
  455. var target: InternalTexture;
  456. if (this._shareOutputWithPostProcess) {
  457. target = this._shareOutputWithPostProcess.inputTexture;
  458. } else if (this._forcedOutputTexture) {
  459. target = this._forcedOutputTexture;
  460. this.width = this._forcedOutputTexture.width;
  461. this.height = this._forcedOutputTexture.height;
  462. } else {
  463. target = this.inputTexture;
  464. }
  465. // Bind the input of this post process to be used as the output of the previous post process.
  466. if (this.enablePixelPerfectMode) {
  467. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  468. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  469. }
  470. else {
  471. this._scaleRatio.copyFromFloats(1, 1);
  472. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  473. }
  474. this.onActivateObservable.notifyObservers(camera);
  475. // Clear
  476. if (this.autoClear && this.alphaMode === Constants.ALPHA_DISABLE) {
  477. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  478. }
  479. if (this._reusable) {
  480. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  481. }
  482. return target;
  483. }
  484. /**
  485. * If the post process is supported.
  486. */
  487. public get isSupported(): boolean {
  488. return this._effect.isSupported;
  489. }
  490. /**
  491. * The aspect ratio of the output texture.
  492. */
  493. public get aspectRatio(): number {
  494. if (this._shareOutputWithPostProcess) {
  495. return this._shareOutputWithPostProcess.aspectRatio;
  496. }
  497. if (this._forcedOutputTexture) {
  498. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  499. }
  500. return this.width / this.height;
  501. }
  502. /**
  503. * Get a value indicating if the post-process is ready to be used
  504. * @returns true if the post-process is ready (shader is compiled)
  505. */
  506. public isReady(): boolean {
  507. return this._effect && this._effect.isReady();
  508. }
  509. /**
  510. * Binds all textures and uniforms to the shader, this will be run on every pass.
  511. * @returns the effect corresponding to this post process. Null if not compiled or not ready.
  512. */
  513. public apply(): Nullable<Effect> {
  514. // Check
  515. if (!this._effect || !this._effect.isReady()) {
  516. return null;
  517. }
  518. // States
  519. this._engine.enableEffect(this._effect);
  520. this._engine.setState(false);
  521. this._engine.setDepthBuffer(false);
  522. this._engine.setDepthWrite(false);
  523. // Alpha
  524. this._engine.setAlphaMode(this.alphaMode);
  525. if (this.alphaConstants) {
  526. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  527. }
  528. // Bind the output texture of the preivous post process as the input to this post process.
  529. var source: InternalTexture;
  530. if (this._shareOutputWithPostProcess) {
  531. source = this._shareOutputWithPostProcess.inputTexture;
  532. } else if (this._forcedOutputTexture) {
  533. source = this._forcedOutputTexture;
  534. } else {
  535. source = this.inputTexture;
  536. }
  537. this._effect._bindTexture("textureSampler", source);
  538. // Parameters
  539. this._effect.setVector2("scale", this._scaleRatio);
  540. this.onApplyObservable.notifyObservers(this._effect);
  541. return this._effect;
  542. }
  543. private _disposeTextures() {
  544. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  545. return;
  546. }
  547. if (this._textures.length > 0) {
  548. for (var i = 0; i < this._textures.length; i++) {
  549. this._engine._releaseTexture(this._textures.data[i]);
  550. }
  551. }
  552. this._textures.dispose();
  553. }
  554. /**
  555. * Disposes the post process.
  556. * @param camera The camera to dispose the post process on.
  557. */
  558. public dispose(camera?: Camera): void {
  559. camera = camera || this._camera;
  560. this._disposeTextures();
  561. if (this._scene) {
  562. let index = this._scene.postProcesses.indexOf(this);
  563. if (index !== -1) {
  564. this._scene.postProcesses.splice(index, 1);
  565. }
  566. } else {
  567. let index = this._engine.postProcesses.indexOf(this);
  568. if (index !== -1) {
  569. this._engine.postProcesses.splice(index, 1);
  570. }
  571. }
  572. if (!camera) {
  573. return;
  574. }
  575. camera.detachPostProcess(this);
  576. var index = camera._postProcesses.indexOf(this);
  577. if (index === 0 && camera._postProcesses.length > 0) {
  578. var firstPostProcess = this._camera._getFirstPostProcess();
  579. if (firstPostProcess) {
  580. firstPostProcess.markTextureDirty();
  581. }
  582. }
  583. this.onActivateObservable.clear();
  584. this.onAfterRenderObservable.clear();
  585. this.onApplyObservable.clear();
  586. this.onBeforeRenderObservable.clear();
  587. this.onSizeChangedObservable.clear();
  588. }
  589. }