BlueNoise.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import { DataTexture, MathUtils, RedFormat, RGFormat, RGBAFormat, UnsignedByteType, RepeatWrapping, TempNode } from 'three/webgpu';
  2. import { texture, screenCoordinate, uniform, fract, float, vec2, vec4 } from 'three/tsl';
  3. /**
  4. * @module BlueNoise
  5. * @three_import import { blueNoise } from 'three/addons/tsl/math/BlueNoise.js';
  6. */
  7. // Per-channel increments from the R1/R2/R4 quasirandom sequences (Roberts 2018, "The Unreasonable
  8. // Effectiveness of Quasirandom Sequences"). Each channel advances by its own irrational step so
  9. // the channels stay jointly well distributed over time.
  10. const R1 = [ 0.6180339887498949 ];
  11. const R2 = [ 0.7548776662466927, 0.5698402909980532 ];
  12. const R4 = [ 0.8566748838545029, 0.7338918566271260, 0.6287067210378086, 0.5385972572236101 ];
  13. /**
  14. * Generates tileable blue-noise dither arrays via Ulichney's void-and-cluster method.
  15. *
  16. * The algorithm builds a per-pixel rank in `[0, size² − 1]` that, when interpreted as a
  17. * threshold map, has a flat spectrum at low frequencies (no clustering) and concentrated
  18. * energy at high frequencies — the defining property of blue noise.
  19. *
  20. * ```js
  21. * const generator = new BlueNoiseGenerator();
  22. * generator.size = 64;
  23. * const { data, maxValue } = generator.generate();
  24. * ```
  25. *
  26. * Reference: [Robert Ulichney, "The void-and-cluster method for dither array generation" (1993)](http://cv.ulichney.com/papers/1993-void-cluster.pdf).
  27. */
  28. class BlueNoiseGenerator {
  29. /**
  30. * Constructs a new blue-noise generator with default parameters.
  31. */
  32. constructor() {
  33. /**
  34. * Output dimension. The generated dither array is `size × size` and tiles seamlessly.
  35. *
  36. * @type {number}
  37. * @default 64
  38. */
  39. this.size = 64;
  40. /**
  41. * Standard deviation (in pixels) of the Gaussian energy filter used to score
  42. * voids and clusters. Smaller σ → higher-frequency / sharper blue noise; larger
  43. * σ → smoother. Ulichney recommends `1.5`.
  44. *
  45. * @type {number}
  46. * @default 1.5
  47. */
  48. this.sigma = 1.5;
  49. /**
  50. * Fraction of pixels seeded as 1s in the initial random pattern. The
  51. * void-and-cluster step equilibrates this into the Initial Binary Pattern (IBP).
  52. *
  53. * @type {number}
  54. * @default 0.1
  55. */
  56. this.majorityPointsRatio = 0.1;
  57. /**
  58. * Seed of the random initial pattern, for reproducible output.
  59. *
  60. * @type {number}
  61. * @default 1
  62. */
  63. this.seed = 1;
  64. }
  65. /**
  66. * Run the void-and-cluster algorithm.
  67. *
  68. * @return {{ data: Uint32Array, maxValue: number }} `data` holds per-pixel ranks
  69. * in row-major order; `maxValue` is `size² − 1` (the highest rank).
  70. */
  71. generate() {
  72. const size = this.size;
  73. const total = size * size;
  74. const sigma = this.sigma;
  75. const sigma2 = sigma * sigma;
  76. // Toroidal Gaussian filter, truncated to ±5σ (or ±size/2, whichever is smaller).
  77. // Beyond ~5σ the weight is < 4e-6 and contributes nothing measurable.
  78. const halfSize = ( size / 2 ) | 0;
  79. const cutoff = Math.min( halfSize, Math.ceil( sigma * 5 ) );
  80. const filterSize = cutoff * 2 + 1;
  81. const weights = new Float32Array( filterSize * filterSize );
  82. for ( let dy = - cutoff; dy <= cutoff; dy ++ ) {
  83. for ( let dx = - cutoff; dx <= cutoff; dx ++ ) {
  84. weights[ ( dy + cutoff ) * filterSize + ( dx + cutoff ) ] = Math.exp( - ( dx * dx + dy * dy ) / ( 2 * sigma2 ) );
  85. }
  86. }
  87. // Working state.
  88. const binaryPattern = new Uint8Array( total );
  89. const energy = new Float32Array( total );
  90. MathUtils.seededRandom( this.seed );
  91. const random = () => MathUtils.seededRandom();
  92. // Place `targetOnes` 1s at random positions via Fisher–Yates.
  93. const targetOnes = Math.max( 1, Math.floor( total * this.majorityPointsRatio ) );
  94. const shuffled = new Int32Array( total );
  95. for ( let i = 0; i < total; i ++ ) shuffled[ i ] = i;
  96. for ( let i = total - 1; i > 0; i -- ) {
  97. const j = Math.floor( random() * ( i + 1 ) );
  98. const tmp = shuffled[ i ];
  99. shuffled[ i ] = shuffled[ j ];
  100. shuffled[ j ] = tmp;
  101. }
  102. for ( let i = 0; i < targetOnes; i ++ ) {
  103. binaryPattern[ shuffled[ i ] ] = 1;
  104. }
  105. // Add or remove a 1 at (x, y), splatting the Gaussian into the energy buffer.
  106. const splatEnergy = ( x, y, sign ) => {
  107. for ( let dy = - cutoff; dy <= cutoff; dy ++ ) {
  108. const sy = ( ( y + dy ) % size + size ) % size;
  109. const wRow = ( dy + cutoff ) * filterSize;
  110. const eRow = sy * size;
  111. for ( let dx = - cutoff; dx <= cutoff; dx ++ ) {
  112. const sx = ( ( x + dx ) % size + size ) % size;
  113. energy[ eRow + sx ] += sign * weights[ wRow + ( dx + cutoff ) ];
  114. }
  115. }
  116. };
  117. // Tightest cluster: 1-pixel with the highest filter response.
  118. const findTightestCluster = () => {
  119. let maxE = - Infinity;
  120. let idx = - 1;
  121. for ( let i = 0; i < total; i ++ ) {
  122. if ( binaryPattern[ i ] === 1 && energy[ i ] > maxE ) {
  123. maxE = energy[ i ];
  124. idx = i;
  125. }
  126. }
  127. return idx;
  128. };
  129. // Largest void: 0-pixel with the lowest filter response.
  130. const findLargestVoid = () => {
  131. let minE = Infinity;
  132. let idx = - 1;
  133. for ( let i = 0; i < total; i ++ ) {
  134. if ( binaryPattern[ i ] === 0 && energy[ i ] < minE ) {
  135. minE = energy[ i ];
  136. idx = i;
  137. }
  138. }
  139. return idx;
  140. };
  141. // Initial energy from the random seed pattern.
  142. for ( let i = 0; i < total; i ++ ) {
  143. if ( binaryPattern[ i ] === 1 ) splatEnergy( i % size, ( i / size ) | 0, + 1 );
  144. }
  145. // Step 1: Equilibrate to the Initial Binary Pattern (IBP). Repeatedly move the
  146. // tightest cluster's 1 into the largest void; converges when the same pixel is
  147. // chosen on both sides.
  148. while ( true ) {
  149. const clusterIdx = findTightestCluster();
  150. binaryPattern[ clusterIdx ] = 0;
  151. splatEnergy( clusterIdx % size, ( clusterIdx / size ) | 0, - 1 );
  152. const voidIdx = findLargestVoid();
  153. binaryPattern[ voidIdx ] = 1;
  154. splatEnergy( voidIdx % size, ( voidIdx / size ) | 0, + 1 );
  155. if ( clusterIdx === voidIdx ) break;
  156. }
  157. // Snapshot the IBP — we'll restore it before the forward pass.
  158. const ibpBinary = binaryPattern.slice();
  159. const ibpEnergy = energy.slice();
  160. const ranks = new Uint32Array( total );
  161. // Phase 1: Reverse-rank the ones in the IBP. Repeatedly remove the tightest
  162. // cluster, assigning ranks `targetOnes − 1` down to `0`.
  163. for ( let rank = targetOnes - 1; rank >= 0; rank -- ) {
  164. const idx = findTightestCluster();
  165. ranks[ idx ] = rank;
  166. binaryPattern[ idx ] = 0;
  167. splatEnergy( idx % size, ( idx / size ) | 0, - 1 );
  168. }
  169. // Restore IBP.
  170. binaryPattern.set( ibpBinary );
  171. energy.set( ibpEnergy );
  172. // Phase 2 + 3: Forward-rank the zeros. Repeatedly fill the largest void,
  173. // assigning ranks `targetOnes` up to `total − 1`. The same operation works
  174. // past the 50 % mark — picking the 0-pixel with the smallest filter response
  175. // is equivalent to picking the tightest cluster on the inverted pattern.
  176. for ( let rank = targetOnes; rank < total; rank ++ ) {
  177. const idx = findLargestVoid();
  178. ranks[ idx ] = rank;
  179. binaryPattern[ idx ] = 1;
  180. splatEnergy( idx % size, ( idx / size ) | 0, + 1 );
  181. }
  182. return { data: ranks, maxValue: total - 1 };
  183. }
  184. }
  185. /**
  186. * Generates a blue-noise DataTexture.
  187. *
  188. * Returns an 8-bit texture with repeat wrapping and nearest filtering, suitable for
  189. * sampling in shaders as a tileable noise source. Each channel is an independent
  190. * blue-noise pattern, generated with a distinct seed so consumers can read
  191. * decorrelated values from a single texture fetch.
  192. *
  193. * Generation runs on the CPU (roughly 50 ms per channel at `64`) and the cost grows
  194. * with the fourth power of `size`, so prefer small textures — a tileable `64` is
  195. * plenty for screen-space jitter.
  196. *
  197. * @param {number} [size=64] - Texture dimension in pixels (the noise is square).
  198. * @param {number} [channels=1] - Number of independent noise channels. Must be `1`
  199. * (RedFormat), `2` (RGFormat), or `4` (RGBAFormat). Generation cost scales linearly.
  200. * @return {DataTexture} The generated blue-noise texture.
  201. */
  202. export function generateBlueNoiseTexture( size = 64, channels = 1 ) {
  203. if ( channels !== 1 && channels !== 2 && channels !== 4 ) {
  204. throw new Error( 'generateBlueNoiseTexture: channels must be 1, 2, or 4.' );
  205. }
  206. const format = channels === 1 ? RedFormat : channels === 2 ? RGFormat : RGBAFormat;
  207. const generator = new BlueNoiseGenerator();
  208. generator.size = size;
  209. const pixels = new Uint8Array( size * size * channels );
  210. // Each channel is regenerated with a distinct seed for an independent pattern.
  211. for ( let c = 0; c < channels; c ++ ) {
  212. generator.seed = c + 1;
  213. const { data, maxValue } = generator.generate();
  214. for ( let i = 0, l = data.length; i < l; i ++ ) {
  215. pixels[ i * channels + c ] = ( data[ i ] / maxValue ) * 255;
  216. }
  217. }
  218. const texture = new DataTexture( pixels, size, size, format, UnsignedByteType );
  219. texture.wrapS = RepeatWrapping;
  220. texture.wrapT = RepeatWrapping;
  221. texture.needsUpdate = true;
  222. return texture;
  223. }
  224. /**
  225. * A node that supplies per-pixel blue-noise values for screen-space sampling jitter.
  226. *
  227. * The node lazily generates its own tileable blue-noise texture (see
  228. * {@link generateBlueNoiseTexture}) and point-samples it at the fragment's screen
  229. * coordinate. When `animated` is enabled, the values are scrolled along a per-channel
  230. * quasirandom (R-sequence) increment each frame: every frame keeps the spatial
  231. * blue-noise distribution while each pixel follows a low-discrepancy temporal
  232. * sequence — ideal input jitter for effects resolved by temporal accumulation
  233. * (e.g. `TRAANode`).
  234. *
  235. * ```js
  236. * const giPass = ssgi( scenePassColor, scenePassDepth, sceneNormal, camera );
  237. * giPass.noiseNode = blueNoise( 2 );
  238. * ```
  239. *
  240. * @augments TempNode
  241. */
  242. class BlueNoiseNode extends TempNode {
  243. static get type() {
  244. return 'BlueNoiseNode';
  245. }
  246. /**
  247. * Constructs a new blue-noise node.
  248. *
  249. * @param {number} [channels=1] - Number of decorrelated noise channels. Must be `1`
  250. * (float output), `2` (vec2) or `4` (vec4).
  251. * @param {number} [size=64] - The edge length of the internal noise texture.
  252. */
  253. constructor( channels = 1, size = 64 ) {
  254. super( channels === 1 ? 'float' : channels === 2 ? 'vec2' : 'vec4' );
  255. /**
  256. * Number of decorrelated noise channels.
  257. *
  258. * @type {number}
  259. * @default 1
  260. */
  261. this.channels = channels;
  262. /**
  263. * The edge length of the internal noise texture.
  264. *
  265. * @type {number}
  266. * @default 64
  267. */
  268. this.size = size;
  269. /**
  270. * Whether the noise is decorrelated over time for temporal accumulation. When
  271. * `false`, the pattern is static — use this when no temporal filtering is in
  272. * place, otherwise the noise would visibly crawl.
  273. *
  274. * @type {boolean}
  275. * @default true
  276. */
  277. this.animated = true;
  278. /**
  279. * Length of the animation loop in frames. A short loop lets temporally accumulated
  280. * results converge to a stable image instead of drifting, while still providing
  281. * enough decorrelated patterns for typical accumulation windows.
  282. *
  283. * @type {number}
  284. * @default 12
  285. */
  286. this.cycle = 12;
  287. /**
  288. * The lazily generated blue-noise texture.
  289. *
  290. * @private
  291. * @type {?DataTexture}
  292. */
  293. this._texture = null;
  294. }
  295. /**
  296. * This method is used to set up the node's TSL code.
  297. *
  298. * @return {Node} The per-pixel noise value.
  299. */
  300. setup() {
  301. if ( this._texture === null ) {
  302. this._texture = generateBlueNoiseTexture( this.size, this.channels );
  303. }
  304. const noise = texture( this._texture, screenCoordinate.div( this.size ) );
  305. const value = ( this.channels === 1 ) ? noise.r : ( this.channels === 2 ) ? noise.rg : noise;
  306. const steps = ( this.channels === 1 ) ? float( R1[ 0 ] ) : ( this.channels === 2 ) ? vec2( ...R2 ) : vec4( ...R4 );
  307. const frame = uniform( 0, 'float' ).onRenderUpdate( ( nodeFrame ) => ( this.animated === true ) ? nodeFrame.frameId % this.cycle : 0 );
  308. return fract( value.add( frame.mul( steps ) ) );
  309. }
  310. /**
  311. * Frees internal resources. This method should be called
  312. * when the node is no longer required.
  313. */
  314. dispose() {
  315. super.dispose();
  316. if ( this._texture !== null ) this._texture.dispose();
  317. }
  318. }
  319. export default BlueNoiseNode;
  320. /**
  321. * TSL function for creating a blue-noise node.
  322. *
  323. * @tsl
  324. * @function
  325. * @param {number} [channels=1] - Number of decorrelated noise channels. Must be `1`
  326. * (float output), `2` (vec2) or `4` (vec4).
  327. * @param {number} [size=64] - The edge length of the internal noise texture.
  328. * @returns {BlueNoiseNode}
  329. */
  330. export const blueNoise = ( channels, size ) => new BlueNoiseNode( channels, size );
  331. export { BlueNoiseGenerator };
粤ICP备19079148号