blurPostProcess.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import { Vector2 } from "../Maths/math";
  2. import { Nullable } from "../types";
  3. import { PostProcess, PostProcessOptions } from "./postProcess";
  4. import { Camera } from "../Cameras/camera";
  5. import { Effect } from "../Materials/effect";
  6. import { Texture } from "../Materials/Textures/texture";
  7. import { Engine } from "../Engines/engine";
  8. import { Constants } from "../Engines/constants";
  9. import "../Shaders/kernelBlur.fragment";
  10. import "../Shaders/kernelBlur.vertex";
  11. /**
  12. * The Blur Post Process which blurs an image based on a kernel and direction.
  13. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  14. */
  15. export class BlurPostProcess extends PostProcess {
  16. protected _kernel: number;
  17. protected _idealKernel: number;
  18. protected _packedFloat: boolean = false;
  19. private _staticDefines: string = "";
  20. /**
  21. * Sets the length in pixels of the blur sample region
  22. */
  23. public set kernel(v: number) {
  24. if (this._idealKernel === v) {
  25. return;
  26. }
  27. v = Math.max(v, 1);
  28. this._idealKernel = v;
  29. this._kernel = this._nearestBestKernel(v);
  30. if (!this.blockCompilation) {
  31. this._updateParameters();
  32. }
  33. }
  34. /**
  35. * Gets the length in pixels of the blur sample region
  36. */
  37. public get kernel(): number {
  38. return this._idealKernel;
  39. }
  40. /**
  41. * Sets wether or not the blur needs to unpack/repack floats
  42. */
  43. public set packedFloat(v: boolean) {
  44. if (this._packedFloat === v) {
  45. return;
  46. }
  47. this._packedFloat = v;
  48. if (!this.blockCompilation) {
  49. this._updateParameters();
  50. }
  51. }
  52. /**
  53. * Gets wether or not the blur is unpacking/repacking floats
  54. */
  55. public get packedFloat(): boolean {
  56. return this._packedFloat;
  57. }
  58. /**
  59. * Creates a new instance BlurPostProcess
  60. * @param name The name of the effect.
  61. * @param direction The direction in which to blur the image.
  62. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  63. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64. * @param camera The camera to apply the render pass to.
  65. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66. * @param engine The engine which the post process will be applied. (default: current engine)
  67. * @param reusable If the post process can be reused on the same frame. (default: false)
  68. * @param textureType Type of textures used when performing the post process. (default: 0)
  69. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70. */
  71. constructor(name: string,
  72. /** The direction in which to blur the image. */
  73. public direction: Vector2,
  74. kernel: number, options: number | PostProcessOptions, camera: Nullable<Camera>, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT, defines = "", private blockCompilation = false) {
  75. super(name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true);
  76. this._staticDefines = defines;
  77. this.onApplyObservable.add((effect: Effect) => {
  78. if (this._outputTexture) {
  79. effect.setFloat2('delta', (1 / this._outputTexture.width) * this.direction.x, (1 / this._outputTexture.height) * this.direction.y);
  80. } else {
  81. effect.setFloat2('delta', (1 / this.width) * this.direction.x, (1 / this.height) * this.direction.y);
  82. }
  83. });
  84. this.kernel = kernel;
  85. }
  86. /**
  87. * Updates the effect with the current post process compile time values and recompiles the shader.
  88. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  89. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  90. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  91. * @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
  92. * @param onCompiled Called when the shader has been compiled.
  93. * @param onError Called if there is an error when compiling a shader.
  94. */
  95. public updateEffect(defines: Nullable<string> = null, uniforms: Nullable<string[]> = null, samplers: Nullable<string[]> = null, indexParameters?: any,
  96. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void) {
  97. this._updateParameters(onCompiled, onError);
  98. }
  99. protected _updateParameters(onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): void {
  100. // Generate sampling offsets and weights
  101. let N = this._kernel;
  102. let centerIndex = (N - 1) / 2;
  103. // Generate Gaussian sampling weights over kernel
  104. let offsets = [];
  105. let weights = [];
  106. let totalWeight = 0;
  107. for (let i = 0; i < N; i++) {
  108. let u = i / (N - 1);
  109. let w = this._gaussianWeight(u * 2.0 - 1);
  110. offsets[i] = (i - centerIndex);
  111. weights[i] = w;
  112. totalWeight += w;
  113. }
  114. // Normalize weights
  115. for (let i = 0; i < weights.length; i++) {
  116. weights[i] /= totalWeight;
  117. }
  118. // Optimize: combine samples to take advantage of hardware linear sampling
  119. // Walk from left to center, combining pairs (symmetrically)
  120. let linearSamplingWeights = [];
  121. let linearSamplingOffsets = [];
  122. let linearSamplingMap = [];
  123. for (let i = 0; i <= centerIndex; i += 2) {
  124. let j = Math.min(i + 1, Math.floor(centerIndex));
  125. let singleCenterSample = i === j;
  126. if (singleCenterSample) {
  127. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  128. } else {
  129. let sharedCell = j === centerIndex;
  130. let weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  131. let offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  132. if (offsetLinear === 0) {
  133. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  134. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  135. } else {
  136. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  137. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  138. }
  139. }
  140. }
  141. for (let i = 0; i < linearSamplingMap.length; i++) {
  142. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  143. linearSamplingWeights[i] = linearSamplingMap[i].w;
  144. }
  145. // Replace with optimized
  146. offsets = linearSamplingOffsets;
  147. weights = linearSamplingWeights;
  148. // Generate shaders
  149. let maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  150. let freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  151. let varyingCount = Math.min(offsets.length, freeVaryingVec2);
  152. let defines = "";
  153. defines += this._staticDefines;
  154. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  155. if (this._staticDefines.indexOf("DOF") != -1) {
  156. defines += `#define CENTER_WEIGHT ${this._glslFloat(weights[varyingCount - 1])}\r\n`;
  157. varyingCount--;
  158. }
  159. for (let i = 0; i < varyingCount; i++) {
  160. defines += `#define KERNEL_OFFSET${i} ${this._glslFloat(offsets[i])}\r\n`;
  161. defines += `#define KERNEL_WEIGHT${i} ${this._glslFloat(weights[i])}\r\n`;
  162. }
  163. let depCount = 0;
  164. for (let i = freeVaryingVec2; i < offsets.length; i++) {
  165. defines += `#define KERNEL_DEP_OFFSET${depCount} ${this._glslFloat(offsets[i])}\r\n`;
  166. defines += `#define KERNEL_DEP_WEIGHT${depCount} ${this._glslFloat(weights[i])}\r\n`;
  167. depCount++;
  168. }
  169. if (this.packedFloat) {
  170. defines += `#define PACKEDFLOAT 1`;
  171. }
  172. this.blockCompilation = false;
  173. super.updateEffect(defines, null, null, {
  174. varyingCount: varyingCount,
  175. depCount: depCount
  176. }, onCompiled, onError);
  177. }
  178. /**
  179. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  180. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  181. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  182. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  183. * The gaps between physical kernels are compensated for in the weighting of the samples
  184. * @param idealKernel Ideal blur kernel.
  185. * @return Nearest best kernel.
  186. */
  187. protected _nearestBestKernel(idealKernel: number): number {
  188. let v = Math.round(idealKernel);
  189. for (let k of [v, v - 1, v + 1, v - 2, v + 2]) {
  190. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  191. return Math.max(k, 3);
  192. }
  193. }
  194. return Math.max(v, 3);
  195. }
  196. /**
  197. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  198. * @param x The point on the Gaussian distribution to sample.
  199. * @return the value of the Gaussian function at x.
  200. */
  201. protected _gaussianWeight(x: number): number {
  202. //reference: Engines/ImageProcessingBlur.cpp #dcc760
  203. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  204. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  205. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  206. // truncated at around 1.3% of peak strength.
  207. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  208. let sigma = (1 / 3);
  209. let denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  210. let exponent = -((x * x) / (2.0 * sigma * sigma));
  211. let weight = (1.0 / denominator) * Math.exp(exponent);
  212. return weight;
  213. }
  214. /**
  215. * Generates a string that can be used as a floating point number in GLSL.
  216. * @param x Value to print.
  217. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  218. * @return GLSL float string.
  219. */
  220. protected _glslFloat(x: number, decimalFigures = 8) {
  221. return x.toFixed(decimalFigures).replace(/0+$/, '');
  222. }
  223. }