BlueNoise.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import { DataTexture, RedFormat, RGFormat, RGBAFormat, UnsignedByteType, RepeatWrapping } from 'three';
  2. /**
  3. * Generates tileable blue-noise dither arrays via Ulichney's void-and-cluster method.
  4. *
  5. * The algorithm builds a per-pixel rank in `[0, size² − 1]` that, when interpreted as a
  6. * threshold map, has a flat spectrum at low frequencies (no clustering) and concentrated
  7. * energy at high frequencies — the defining property of blue noise.
  8. *
  9. * ```js
  10. * const generator = new BlueNoiseGenerator();
  11. * generator.size = 64;
  12. * const { data, maxValue } = generator.generate();
  13. * ```
  14. *
  15. * Reference: [Robert Ulichney, "The void-and-cluster method for dither array generation" (1993)](http://cv.ulichney.com/papers/1993-void-cluster.pdf).
  16. *
  17. * @three_import import { BlueNoiseGenerator } from 'three/addons/math/BlueNoise.js';
  18. */
  19. class BlueNoiseGenerator {
  20. /**
  21. * Constructs a new blue-noise generator with default parameters.
  22. */
  23. constructor() {
  24. /**
  25. * Output dimension. The generated dither array is `size × size` and tiles seamlessly.
  26. *
  27. * @type {number}
  28. * @default 64
  29. */
  30. this.size = 64;
  31. /**
  32. * Standard deviation (in pixels) of the Gaussian energy filter used to score
  33. * voids and clusters. Smaller σ → higher-frequency / sharper blue noise; larger
  34. * σ → smoother. Ulichney recommends `1.5`.
  35. *
  36. * @type {number}
  37. * @default 1.5
  38. */
  39. this.sigma = 1.5;
  40. /**
  41. * Fraction of pixels seeded as 1s in the initial random pattern. The
  42. * void-and-cluster step equilibrates this into the Initial Binary Pattern (IBP).
  43. *
  44. * @type {number}
  45. * @default 0.1
  46. */
  47. this.majorityPointsRatio = 0.1;
  48. /**
  49. * Seed for the internal LCG, for reproducible output.
  50. *
  51. * @type {number}
  52. * @default 1
  53. */
  54. this.seed = 1;
  55. }
  56. /**
  57. * Run the void-and-cluster algorithm.
  58. *
  59. * @return {{ data: Uint32Array, maxValue: number }} `data` holds per-pixel ranks
  60. * in row-major order; `maxValue` is `size² − 1` (the highest rank).
  61. */
  62. generate() {
  63. const size = this.size;
  64. const total = size * size;
  65. const sigma = this.sigma;
  66. const sigma2 = sigma * sigma;
  67. // Toroidal Gaussian filter, truncated to ±5σ (or ±size/2, whichever is smaller).
  68. // Beyond ~5σ the weight is < 4e-6 and contributes nothing measurable.
  69. const halfSize = ( size / 2 ) | 0;
  70. const cutoff = Math.min( halfSize, Math.ceil( sigma * 5 ) );
  71. const filterSize = cutoff * 2 + 1;
  72. const weights = new Float32Array( filterSize * filterSize );
  73. for ( let dy = - cutoff; dy <= cutoff; dy ++ ) {
  74. for ( let dx = - cutoff; dx <= cutoff; dx ++ ) {
  75. weights[ ( dy + cutoff ) * filterSize + ( dx + cutoff ) ] = Math.exp( - ( dx * dx + dy * dy ) / ( 2 * sigma2 ) );
  76. }
  77. }
  78. // Working state.
  79. const binaryPattern = new Uint8Array( total );
  80. const energy = new Float32Array( total );
  81. // Linear-congruential PRNG, seeded for reproducibility.
  82. let rngState = ( this.seed | 0 ) || 1;
  83. const random = () => {
  84. rngState = ( Math.imul( rngState, 1664525 ) + 1013904223 ) | 0;
  85. return ( rngState >>> 0 ) / 0x100000000;
  86. };
  87. // Place `targetOnes` 1s at random positions via Fisher–Yates.
  88. const targetOnes = Math.max( 1, Math.floor( total * this.majorityPointsRatio ) );
  89. const shuffled = new Int32Array( total );
  90. for ( let i = 0; i < total; i ++ ) shuffled[ i ] = i;
  91. for ( let i = total - 1; i > 0; i -- ) {
  92. const j = Math.floor( random() * ( i + 1 ) );
  93. const tmp = shuffled[ i ];
  94. shuffled[ i ] = shuffled[ j ];
  95. shuffled[ j ] = tmp;
  96. }
  97. for ( let i = 0; i < targetOnes; i ++ ) {
  98. binaryPattern[ shuffled[ i ] ] = 1;
  99. }
  100. // Add or remove a 1 at (x, y), splatting the Gaussian into the energy buffer.
  101. const splatEnergy = ( x, y, sign ) => {
  102. for ( let dy = - cutoff; dy <= cutoff; dy ++ ) {
  103. const sy = ( ( y + dy ) % size + size ) % size;
  104. const wRow = ( dy + cutoff ) * filterSize;
  105. const eRow = sy * size;
  106. for ( let dx = - cutoff; dx <= cutoff; dx ++ ) {
  107. const sx = ( ( x + dx ) % size + size ) % size;
  108. energy[ eRow + sx ] += sign * weights[ wRow + ( dx + cutoff ) ];
  109. }
  110. }
  111. };
  112. // Tightest cluster: 1-pixel with the highest filter response.
  113. const findTightestCluster = () => {
  114. let maxE = - Infinity;
  115. let idx = - 1;
  116. for ( let i = 0; i < total; i ++ ) {
  117. if ( binaryPattern[ i ] === 1 && energy[ i ] > maxE ) {
  118. maxE = energy[ i ];
  119. idx = i;
  120. }
  121. }
  122. return idx;
  123. };
  124. // Largest void: 0-pixel with the lowest filter response.
  125. const findLargestVoid = () => {
  126. let minE = Infinity;
  127. let idx = - 1;
  128. for ( let i = 0; i < total; i ++ ) {
  129. if ( binaryPattern[ i ] === 0 && energy[ i ] < minE ) {
  130. minE = energy[ i ];
  131. idx = i;
  132. }
  133. }
  134. return idx;
  135. };
  136. // Initial energy from the random seed pattern.
  137. for ( let i = 0; i < total; i ++ ) {
  138. if ( binaryPattern[ i ] === 1 ) splatEnergy( i % size, ( i / size ) | 0, + 1 );
  139. }
  140. // Step 1: Equilibrate to the Initial Binary Pattern (IBP). Repeatedly move the
  141. // tightest cluster's 1 into the largest void; converges when the same pixel is
  142. // chosen on both sides.
  143. while ( true ) {
  144. const clusterIdx = findTightestCluster();
  145. binaryPattern[ clusterIdx ] = 0;
  146. splatEnergy( clusterIdx % size, ( clusterIdx / size ) | 0, - 1 );
  147. const voidIdx = findLargestVoid();
  148. binaryPattern[ voidIdx ] = 1;
  149. splatEnergy( voidIdx % size, ( voidIdx / size ) | 0, + 1 );
  150. if ( clusterIdx === voidIdx ) break;
  151. }
  152. // Snapshot the IBP — we'll restore it before the forward pass.
  153. const ibpBinary = binaryPattern.slice();
  154. const ibpEnergy = energy.slice();
  155. const ranks = new Uint32Array( total );
  156. // Phase 1: Reverse-rank the ones in the IBP. Repeatedly remove the tightest
  157. // cluster, assigning ranks `targetOnes − 1` down to `0`.
  158. for ( let rank = targetOnes - 1; rank >= 0; rank -- ) {
  159. const idx = findTightestCluster();
  160. ranks[ idx ] = rank;
  161. binaryPattern[ idx ] = 0;
  162. splatEnergy( idx % size, ( idx / size ) | 0, - 1 );
  163. }
  164. // Restore IBP.
  165. binaryPattern.set( ibpBinary );
  166. energy.set( ibpEnergy );
  167. // Phase 2 + 3: Forward-rank the zeros. Repeatedly fill the largest void,
  168. // assigning ranks `targetOnes` up to `total − 1`. The same operation works
  169. // past the 50 % mark — picking the 0-pixel with the smallest filter response
  170. // is equivalent to picking the tightest cluster on the inverted pattern.
  171. for ( let rank = targetOnes; rank < total; rank ++ ) {
  172. const idx = findLargestVoid();
  173. ranks[ idx ] = rank;
  174. binaryPattern[ idx ] = 1;
  175. splatEnergy( idx % size, ( idx / size ) | 0, + 1 );
  176. }
  177. return { data: ranks, maxValue: total - 1 };
  178. }
  179. }
  180. /**
  181. * Generate a blue noise DataTexture.
  182. * Returns an 8-bit texture with RepeatWrapping, suitable for sampling in shaders
  183. * as a tileable noise source. Each channel is an independent blue-noise pattern,
  184. * generated with a distinct seed so consumers can read decorrelated values from
  185. * a single texture fetch.
  186. *
  187. * @param {number} [size=64] Texture dimension in pixels (the noise is square).
  188. * @param {number} [channels=1] Number of independent noise channels. Must be `1`
  189. * (RedFormat), `2` (RGFormat), or `4` (RGBAFormat). Generation cost scales linearly.
  190. * @return {DataTexture} The generated blue-noise DataTexture.
  191. */
  192. export function generateBlueNoiseTexture( size = 64, channels = 1 ) {
  193. if ( channels !== 1 && channels !== 2 && channels !== 4 ) {
  194. throw new Error( 'generateBlueNoiseTexture: channels must be 1, 2, or 4.' );
  195. }
  196. const format = channels === 1 ? RedFormat : channels === 2 ? RGFormat : RGBAFormat;
  197. const generator = new BlueNoiseGenerator();
  198. generator.size = size;
  199. const pixels = new Uint8Array( size * size * channels );
  200. // Each channel is regenerated with a distinct seed for an independent pattern.
  201. for ( let c = 0; c < channels; c ++ ) {
  202. generator.seed = c + 1;
  203. const { data, maxValue } = generator.generate();
  204. for ( let i = 0, l = data.length; i < l; i ++ ) {
  205. pixels[ i * channels + c ] = ( data[ i ] / maxValue ) * 255;
  206. }
  207. }
  208. const texture = new DataTexture( pixels, size, size, format, UnsignedByteType );
  209. texture.wrapS = RepeatWrapping;
  210. texture.wrapT = RepeatWrapping;
  211. texture.needsUpdate = true;
  212. return texture;
  213. }
  214. export { BlueNoiseGenerator };
粤ICP备19079148号