babylon.postProcess.ts 25 KB

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