babylon.postProcess.ts 24 KB

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