babylon.postProcess.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. module BABYLON {
  2. export type PostProcessOptions = { width: number, height: number };
  3. export class PostProcess
  4. {
  5. public width = -1;
  6. public height = -1;
  7. public renderTargetSamplingMode: number;
  8. public clearColor: Color4;
  9. public autoClear = true;
  10. public alphaMode = Engine.ALPHA_DISABLE;
  11. public alphaConstants: Color4;
  12. /*
  13. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  14. Can only be used on a single postprocess or on the last one of a chain.
  15. */
  16. public enablePixelPerfectMode = false;
  17. public scaleMode = Engine.SCALEMODE_FLOOR;
  18. public alwaysForcePOT = false;
  19. public samples = 1;
  20. private _camera: Camera;
  21. private _scene: Scene;
  22. private _engine: Engine;
  23. private _options: number | PostProcessOptions;
  24. private _reusable = false;
  25. private _textureType: number;
  26. public _textures = new SmartArray<WebGLTexture>(2);
  27. public _currentRenderTextureInd = 0;
  28. private _effect: Effect;
  29. private _samplers: string[];
  30. private _fragmentUrl: string;
  31. private _vertexUrl: string;
  32. private _parameters: string[];
  33. private _scaleRatio = new Vector2(1, 1);
  34. protected _indexParameters: any;
  35. private _shareOutputWithPostProcess: PostProcess;
  36. private _texelSize = Vector2.Zero();
  37. private _forcedOutputTexture: WebGLTexture;
  38. // Events
  39. /**
  40. * An event triggered when the postprocess is activated.
  41. * @type {BABYLON.Observable}
  42. */
  43. public onActivateObservable = new Observable<Camera>();
  44. private _onActivateObserver: Observer<Camera>;
  45. public set onActivate(callback: (camera: Camera) => void) {
  46. if (this._onActivateObserver) {
  47. this.onActivateObservable.remove(this._onActivateObserver);
  48. }
  49. this._onActivateObserver = this.onActivateObservable.add(callback);
  50. }
  51. /**
  52. * An event triggered when the postprocess changes its size.
  53. * @type {BABYLON.Observable}
  54. */
  55. public onSizeChangedObservable = new Observable<PostProcess>();
  56. private _onSizeChangedObserver: Observer<PostProcess>;
  57. public set onSizeChanged(callback: (postProcess: PostProcess) => void) {
  58. if (this._onSizeChangedObserver) {
  59. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60. }
  61. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  62. }
  63. /**
  64. * An event triggered when the postprocess applies its effect.
  65. * @type {BABYLON.Observable}
  66. */
  67. public onApplyObservable = new Observable<Effect>();
  68. private _onApplyObserver: Observer<Effect>;
  69. public set onApply(callback: (effect: Effect) => void) {
  70. if (this._onApplyObserver) {
  71. this.onApplyObservable.remove(this._onApplyObserver);
  72. }
  73. this._onApplyObserver = this.onApplyObservable.add(callback);
  74. }
  75. /**
  76. * An event triggered before rendering the postprocess
  77. * @type {BABYLON.Observable}
  78. */
  79. public onBeforeRenderObservable = new Observable<Effect>();
  80. private _onBeforeRenderObserver: Observer<Effect>;
  81. public set onBeforeRender(callback: (effect: Effect) => void) {
  82. if (this._onBeforeRenderObserver) {
  83. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  84. }
  85. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86. }
  87. /**
  88. * An event triggered after rendering the postprocess
  89. * @type {BABYLON.Observable}
  90. */
  91. public onAfterRenderObservable = new Observable<Effect>();
  92. private _onAfterRenderObserver: Observer<Effect>;
  93. public set onAfterRender(callback: (efect: Effect) => void) {
  94. if (this._onAfterRenderObserver) {
  95. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96. }
  97. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  98. }
  99. public get outputTexture(): WebGLTexture {
  100. return this._textures.data[this._currentRenderTextureInd];
  101. }
  102. public set outputTexture(value: WebGLTexture) {
  103. this._forcedOutputTexture = value;
  104. }
  105. public getCamera(): Camera {
  106. return this._camera;
  107. }
  108. public get texelSize(): Vector2 {
  109. if (this._shareOutputWithPostProcess) {
  110. return this._shareOutputWithPostProcess.texelSize;
  111. }
  112. if (this._forcedOutputTexture) {
  113. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  114. }
  115. return this._texelSize;
  116. }
  117. constructor(public name: string, fragmentUrl: string, parameters: string[], samplers: string[], options: number | PostProcessOptions, camera: Camera, samplingMode: number = Texture.NEAREST_SAMPLINGMODE, engine?: Engine, reusable?: boolean, defines?: string, textureType: number = Engine.TEXTURETYPE_UNSIGNED_INT, vertexUrl: string = "postprocess", indexParameters?: any, blockCompilation = false) {
  118. if (camera != null) {
  119. this._camera = camera;
  120. this._scene = camera.getScene();
  121. camera.attachPostProcess(this);
  122. this._engine = this._scene.getEngine();
  123. }
  124. else {
  125. this._engine = engine;
  126. }
  127. this._options = options;
  128. this.renderTargetSamplingMode = samplingMode ? samplingMode : Texture.NEAREST_SAMPLINGMODE;
  129. this._reusable = reusable || false;
  130. this._textureType = textureType;
  131. this._samplers = samplers || [];
  132. this._samplers.push("textureSampler");
  133. this._fragmentUrl = fragmentUrl;
  134. this._vertexUrl = vertexUrl;
  135. this._parameters = parameters || [];
  136. this._parameters.push("scale");
  137. this._indexParameters = indexParameters;
  138. if (!blockCompilation) {
  139. this.updateEffect(defines);
  140. }
  141. }
  142. public getEngine(): Engine {
  143. return this._engine;
  144. }
  145. public getEffect(): Effect {
  146. return this._effect;
  147. }
  148. public shareOutputWith(postProcess: PostProcess): PostProcess {
  149. this._disposeTextures();
  150. this._shareOutputWithPostProcess = postProcess;
  151. return this;
  152. }
  153. public updateEffect(defines?: string, uniforms?: string[], samplers?: string[], indexParameters?: any,
  154. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void) {
  155. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl },
  156. ["position"],
  157. uniforms || this._parameters,
  158. samplers || this._samplers,
  159. defines !== undefined ? defines : "",
  160. null,
  161. onCompiled,
  162. onError,
  163. indexParameters || this._indexParameters
  164. );
  165. }
  166. public isReusable(): boolean {
  167. return this._reusable;
  168. }
  169. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  170. public markTextureDirty() : void{
  171. this.width = -1;
  172. }
  173. public activate(camera: Camera, sourceTexture?: WebGLTexture, forceDepthStencil?: boolean): void {
  174. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  175. camera = camera || this._camera;
  176. var scene = camera.getScene();
  177. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  178. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * <number>this._options) | 0;
  179. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * <number>this._options) | 0;
  180. var desiredWidth = (<PostProcessOptions>this._options).width || requiredWidth;
  181. var desiredHeight = (<PostProcessOptions>this._options).height || requiredHeight;
  182. if (this.renderTargetSamplingMode === Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  183. if (!(<PostProcessOptions>this._options).width) {
  184. desiredWidth = Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  185. }
  186. if (!(<PostProcessOptions>this._options).height) {
  187. desiredHeight = Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  188. }
  189. }
  190. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  191. if (this._textures.length > 0) {
  192. for (var i = 0; i < this._textures.length; i++) {
  193. this._engine._releaseTexture(this._textures.data[i]);
  194. }
  195. this._textures.reset();
  196. }
  197. this.width = desiredWidth;
  198. this.height = desiredHeight;
  199. let textureSize = { width: this.width, height: this.height };
  200. let textureOptions = {
  201. generateMipMaps: false,
  202. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  203. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  204. samplingMode: this.renderTargetSamplingMode,
  205. type: this._textureType
  206. };
  207. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  208. if (this._reusable) {
  209. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  210. }
  211. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  212. this.onSizeChangedObservable.notifyObservers(this);
  213. }
  214. this._textures.forEach(texture => {
  215. if (texture.samples !== this.samples) {
  216. this._engine.updateRenderTargetTextureSampleCount(texture, this.samples);
  217. }
  218. });
  219. }
  220. var target: WebGLTexture;
  221. if (this._shareOutputWithPostProcess) {
  222. target = this._shareOutputWithPostProcess.outputTexture;
  223. } else if (this._forcedOutputTexture) {
  224. target = this._forcedOutputTexture;
  225. this.width = this._forcedOutputTexture._width;
  226. this.height = this._forcedOutputTexture._height;
  227. } else {
  228. target = this.outputTexture;
  229. }
  230. if (this.enablePixelPerfectMode) {
  231. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  232. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  233. }
  234. else {
  235. this._scaleRatio.copyFromFloats(1, 1);
  236. this._engine.bindFramebuffer(target);
  237. }
  238. this.onActivateObservable.notifyObservers(camera);
  239. // Clear
  240. if (this.autoClear && this.alphaMode === Engine.ALPHA_DISABLE) {
  241. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  242. }
  243. if (this._reusable) {
  244. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  245. }
  246. }
  247. public get isSupported(): boolean {
  248. return this._effect.isSupported;
  249. }
  250. public get aspectRatio(): number {
  251. if (this._shareOutputWithPostProcess) {
  252. return this._shareOutputWithPostProcess.aspectRatio;
  253. }
  254. if (this._forcedOutputTexture) {
  255. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  256. }
  257. return this.width / this.height;
  258. }
  259. public apply(): Effect {
  260. // Check
  261. if (!this._effect || !this._effect.isReady())
  262. return null;
  263. // States
  264. this._engine.enableEffect(this._effect);
  265. this._engine.setState(false);
  266. this._engine.setDepthBuffer(false);
  267. this._engine.setDepthWrite(false);
  268. // Alpha
  269. this._engine.setAlphaMode(this.alphaMode);
  270. if (this.alphaConstants) {
  271. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  272. }
  273. // Texture
  274. var source: WebGLTexture;
  275. if (this._shareOutputWithPostProcess) {
  276. source = this._shareOutputWithPostProcess.outputTexture;
  277. } else if (this._forcedOutputTexture) {
  278. source = this._forcedOutputTexture;
  279. } else {
  280. source = this.outputTexture;
  281. }
  282. this._effect._bindTexture("textureSampler", source);
  283. // Parameters
  284. this._effect.setVector2("scale", this._scaleRatio);
  285. this.onApplyObservable.notifyObservers(this._effect);
  286. return this._effect;
  287. }
  288. private _disposeTextures() {
  289. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  290. return;
  291. }
  292. if (this._textures.length > 0) {
  293. for (var i = 0; i < this._textures.length; i++) {
  294. this._engine._releaseTexture(this._textures.data[i]);
  295. }
  296. }
  297. this._textures.dispose();
  298. }
  299. public dispose(camera?: Camera): void {
  300. camera = camera || this._camera;
  301. this._disposeTextures();
  302. if (!camera) {
  303. return;
  304. }
  305. camera.detachPostProcess(this);
  306. var index = camera._postProcesses.indexOf(this);
  307. if (index === 0 && camera._postProcesses.length > 0) {
  308. this._camera._postProcesses[0].markTextureDirty();
  309. }
  310. this.onActivateObservable.clear();
  311. this.onAfterRenderObservable.clear();
  312. this.onApplyObservable.clear();
  313. this.onBeforeRenderObservable.clear();
  314. this.onSizeChangedObservable.clear();
  315. }
  316. }
  317. }