blurPostProcess.ts 12 KB

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