ClusteredLightsNode.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. import { DataTexture, FloatType, RGBAFormat, Vector2, Vector3, LightsNode, NodeUpdateType } from 'three/webgpu';
  2. import {
  3. attributeArray, nodeProxy, int, float, vec3, vec4, ivec2, ivec4, uniform, Break, Loop, positionView,
  4. Fn, If, Return, textureLoad, instanceIndex, screenCoordinate, directPointLight,
  5. renderGroup,
  6. min, max, pow, log, clamp, dot
  7. } from 'three/tsl';
  8. const _vector3 = /*@__PURE__*/ new Vector3();
  9. const _size = /*@__PURE__*/ new Vector2();
  10. /**
  11. * A custom version of `LightsNode` implementing Forward+ clustered shading:
  12. * the view frustum is subdivided into a 3D grid of clusters (X × Y screen tiles
  13. * times an exponentially-spaced set of Z depth slices), and each cluster holds
  14. * only the point lights whose spheres intersect it. At shading time each fragment
  15. * looks up its cluster and loops over just that cluster's lights. Unlike 2D tiled
  16. * lighting, clustered shading culls lights that share screen pixels but lie at
  17. * different depths — suitable for 3D scenes with real depth complexity.
  18. *
  19. * @augments LightsNode
  20. * @three_import import { clusteredLights } from 'three/addons/tsl/lighting/ClusteredLightsNode.js';
  21. */
  22. class ClusteredLightsNode extends LightsNode {
  23. static get type() {
  24. return 'ClusteredLightsNode';
  25. }
  26. /**
  27. * Constructs a new clustered lights node.
  28. *
  29. * @param {number} [maxLights=1024] - Maximum number of point lights.
  30. * @param {number} [tileSize=32] - Screen tile size in pixels (cluster XY size).
  31. * @param {number} [zSlices=24] - Number of exponential depth slices.
  32. * @param {number} [maxLightsPerCluster=64] - Per-cluster light-list capacity.
  33. */
  34. constructor( maxLights = 1024, tileSize = 32, zSlices = 24, maxLightsPerCluster = 64 ) {
  35. super();
  36. this.materialLights = [];
  37. this.clusteredLights = [];
  38. this.maxLights = maxLights;
  39. this.tileSize = tileSize;
  40. this.zSlices = zSlices;
  41. this.maxLightsPerCluster = maxLightsPerCluster;
  42. this._chunksPerCluster = Math.ceil( maxLightsPerCluster / 4 );
  43. this._bufferSize = null;
  44. this._lightIndexes = null;
  45. this._screenClusterIndex = null;
  46. this._compute = null;
  47. this._lightsTexture = null;
  48. this._zSliceRangesTexture = null;
  49. this._zSliceRangesData = null;
  50. this._lightViewZ = new Float32Array( maxLights );
  51. this._lightSortOrder = [];
  52. this._lightsCount = uniform( 0, 'int' );
  53. // Render-group uniforms: shared between compute and fragment passes,
  54. // updated manually each frame in updateBefore (compute lacks a camera context).
  55. this._cameraNear = uniform( 0 ).setName( 'clusteredCameraNear' ).setGroup( renderGroup );
  56. this._cameraFar = uniform( 0 ).setName( 'clusteredCameraFar' ).setGroup( renderGroup );
  57. this._cameraViewMatrix = uniform( 'mat4' ).setName( 'clusteredCameraViewMatrix' ).setGroup( renderGroup );
  58. this._cameraProjectionMatrix = uniform( 'mat4' ).setName( 'clusteredCameraProjectionMatrix' ).setGroup( renderGroup );
  59. this._gridDimensions = uniform( new Vector2() );
  60. this.updateBeforeType = NodeUpdateType.RENDER;
  61. }
  62. customCacheKey() {
  63. return ( this._compute ? this._compute.getCacheKey() : 0 ) + super.customCacheKey();
  64. }
  65. updateLightsTexture( camera ) {
  66. const { _lightsTexture: lightsTexture, clusteredLights } = this;
  67. const data = lightsTexture.image.data;
  68. const lineSize = lightsTexture.image.width * 4;
  69. const count = clusteredLights.length;
  70. this._lightsCount.value = count;
  71. // Sort lights by view-space depth for Z-culling
  72. const viewZ = this._lightViewZ;
  73. const order = this._lightSortOrder;
  74. for ( let i = 0; i < count; i ++ ) {
  75. _vector3.setFromMatrixPosition( clusteredLights[ i ].matrixWorld );
  76. _vector3.applyMatrix4( camera.matrixWorldInverse );
  77. viewZ[ i ] = _vector3.z;
  78. order[ i ] = i;
  79. }
  80. order.length = count;
  81. order.sort( ( a, b ) => viewZ[ a ] - viewZ[ b ] );
  82. // Write sorted lights to texture
  83. for ( let i = 0; i < count; i ++ ) {
  84. const light = clusteredLights[ order[ i ] ];
  85. _vector3.setFromMatrixPosition( light.matrixWorld );
  86. const offset = i * 4;
  87. data[ offset + 0 ] = _vector3.x;
  88. data[ offset + 1 ] = _vector3.y;
  89. data[ offset + 2 ] = _vector3.z;
  90. data[ offset + 3 ] = light.distance;
  91. data[ lineSize + offset + 0 ] = light.color.r * light.intensity;
  92. data[ lineSize + offset + 1 ] = light.color.g * light.intensity;
  93. data[ lineSize + offset + 2 ] = light.color.b * light.intensity;
  94. data[ lineSize + offset + 3 ] = light.decay;
  95. }
  96. lightsTexture.needsUpdate = true;
  97. // Compute per Z-slice light ranges
  98. const zRanges = this._zSliceRangesData;
  99. if ( zRanges === null ) return;
  100. const near = camera.near;
  101. const far = camera.far;
  102. const NZ = this.zSlices;
  103. for ( let z = 0; z < NZ; z ++ ) {
  104. // Exponential Z-slice bounds (view-space, negative values)
  105. const sliceNear = - ( near * Math.pow( far / near, z / NZ ) );
  106. const sliceFar = - ( near * Math.pow( far / near, ( z + 1 ) / NZ ) );
  107. let rangeStart = count;
  108. let rangeEnd = 0;
  109. for ( let i = 0; i < count; i ++ ) {
  110. const vz = viewZ[ order[ i ] ];
  111. const r = clusteredLights[ order[ i ] ].distance;
  112. const radius = r > 0 ? r : far;
  113. // Light sphere Z: [vz - radius, vz + radius]
  114. // Slice Z: [sliceFar, sliceNear] (both negative, sliceFar < sliceNear)
  115. if ( vz + radius >= sliceFar && vz - radius <= sliceNear ) {
  116. if ( i < rangeStart ) rangeStart = i;
  117. if ( i + 1 > rangeEnd ) rangeEnd = i + 1;
  118. }
  119. }
  120. if ( rangeStart >= count ) {
  121. rangeStart = 0;
  122. rangeEnd = 0;
  123. }
  124. zRanges[ z * 4 ] = rangeStart;
  125. zRanges[ z * 4 + 1 ] = rangeEnd;
  126. }
  127. this._zSliceRangesTexture.needsUpdate = true;
  128. }
  129. updateBefore( frame ) {
  130. const { renderer, camera } = frame;
  131. this.updateProgram( renderer );
  132. this.updateLightsTexture( camera );
  133. this._cameraNear.value = camera.near;
  134. this._cameraFar.value = camera.far;
  135. this._cameraViewMatrix.value = camera.matrixWorldInverse;
  136. this._cameraProjectionMatrix.value = camera.projectionMatrix;
  137. renderer.compute( this._compute );
  138. }
  139. setLights( lights ) {
  140. const { clusteredLights, materialLights } = this;
  141. let materialIndex = 0;
  142. let clusteredIndex = 0;
  143. for ( const light of lights ) {
  144. if ( light.isPointLight === true && light.castShadow !== true ) {
  145. clusteredLights[ clusteredIndex ++ ] = light;
  146. } else {
  147. materialLights[ materialIndex ++ ] = light;
  148. }
  149. }
  150. materialLights.length = materialIndex;
  151. clusteredLights.length = clusteredIndex;
  152. return super.setLights( lights );
  153. }
  154. getBuiltinLights() {
  155. return this.materialLights;
  156. }
  157. getBlock() {
  158. return this._lightIndexes.element( this._screenClusterIndex.mul( int( this._chunksPerCluster ) ) );
  159. }
  160. getTile( element ) {
  161. element = int( element );
  162. const stride = int( 4 );
  163. const chunkOffset = element.div( stride );
  164. const idx = this._screenClusterIndex.mul( int( this._chunksPerCluster ) ).add( chunkOffset );
  165. return this._lightIndexes.element( idx ).element( element.mod( stride ) );
  166. }
  167. getClusterLightCount( zSliceNode ) {
  168. const getCount = Fn( ( [ zSliceNode ] ) => {
  169. const count = int( 0 ).toVar();
  170. const debugClusterIndex = this._screenClusterIndex.toVar();
  171. If( zSliceNode.greaterThanEqual( int( 0 ) ), () => {
  172. const tileSize = int( this.tileSize );
  173. const screenTile = screenCoordinate.div( tileSize ).floor();
  174. const NX = int( this._gridDimensions.x );
  175. const NY = int( this._gridDimensions.y );
  176. debugClusterIndex.assign(
  177. int( screenTile.x )
  178. .add( int( screenTile.y ).mul( NX ) )
  179. .add( zSliceNode.mul( NX.mul( NY ) ) )
  180. );
  181. } );
  182. Loop( this.maxLightsPerCluster, ( { i } ) => {
  183. const element = int( i );
  184. const stride = int( 4 );
  185. const chunkOffset = element.div( stride );
  186. const idx = debugClusterIndex.mul( int( this._chunksPerCluster ) ).add( chunkOffset );
  187. const lightIndex = this._lightIndexes.element( idx ).element( element.mod( stride ) );
  188. If( lightIndex.equal( int( 0 ) ), () => {
  189. Break();
  190. } );
  191. count.addAssign( int( 1 ) );
  192. } );
  193. return count;
  194. } );
  195. return getCount( zSliceNode );
  196. }
  197. getLightData( index ) {
  198. index = int( index );
  199. const dataA = textureLoad( this._lightsTexture, ivec2( index, 0 ) );
  200. const dataB = textureLoad( this._lightsTexture, ivec2( index, 1 ) );
  201. const position = dataA.xyz;
  202. const viewPosition = this._cameraViewMatrix.mul( vec4( position, 1.0 ) ).xyz;
  203. const distance = dataA.w;
  204. const color = dataB.rgb;
  205. const decay = dataB.w;
  206. return {
  207. position,
  208. viewPosition,
  209. distance,
  210. color,
  211. decay
  212. };
  213. }
  214. setupLights( builder, lightNodes ) {
  215. this.updateProgram( builder.renderer );
  216. //
  217. const lightingModel = builder.context.reflectedLight;
  218. lightingModel.directDiffuse.toStack();
  219. lightingModel.directSpecular.toStack();
  220. super.setupLights( builder, lightNodes );
  221. Fn( () => {
  222. Loop( this.maxLightsPerCluster, ( { i } ) => {
  223. const lightIndex = this.getTile( i );
  224. If( lightIndex.equal( int( 0 ) ), () => {
  225. Break();
  226. } );
  227. const { color, decay, viewPosition, distance } = this.getLightData( lightIndex.sub( 1 ) );
  228. const lightVector = viewPosition.sub( positionView );
  229. // Early-out: skip full BRDF if fragment is beyond the light's cutoff
  230. If( distance.equal( 0 ).or( dot( lightVector, lightVector ).lessThanEqual( distance.mul( distance ) ) ), () => {
  231. builder.lightsNode.setupDirectLight( builder, this, directPointLight( {
  232. color,
  233. lightVector,
  234. cutoffDistance: distance,
  235. decayExponent: decay
  236. } ) );
  237. } );
  238. } );
  239. }, 'void' )();
  240. }
  241. getBufferFitSize( value ) {
  242. const multiple = this.tileSize;
  243. return Math.ceil( value / multiple ) * multiple;
  244. }
  245. setSize( width, height ) {
  246. width = this.getBufferFitSize( width );
  247. height = this.getBufferFitSize( height );
  248. if ( ! this._bufferSize || this._bufferSize.width !== width || this._bufferSize.height !== height ) {
  249. this.create( width, height );
  250. }
  251. return this;
  252. }
  253. updateProgram( renderer ) {
  254. renderer.getDrawingBufferSize( _size );
  255. const width = this.getBufferFitSize( _size.width );
  256. const height = this.getBufferFitSize( _size.height );
  257. if ( this._bufferSize === null ) {
  258. this.create( width, height );
  259. } else if ( this._bufferSize.width !== width || this._bufferSize.height !== height ) {
  260. this.create( width, height );
  261. }
  262. }
  263. create( width, height ) {
  264. const { tileSize, maxLights, zSlices, maxLightsPerCluster, _chunksPerCluster: chunksPerCluster } = this;
  265. const bufferSize = new Vector2( width, height );
  266. const NX = Math.floor( bufferSize.width / tileSize );
  267. const NY = Math.floor( bufferSize.height / tileSize );
  268. const NZ = zSlices;
  269. const clusterCount = NX * NY * NZ;
  270. this._gridDimensions.value.set( NX, NY );
  271. // Lights data texture (same layout as TiledLightsNode)
  272. const lightsData = new Float32Array( maxLights * 4 * 2 );
  273. const lightsTexture = new DataTexture( lightsData, lightsData.length / 8, 2, RGBAFormat, FloatType );
  274. // Per Z-slice light range for Z-culling (CPU-sorted, uploaded each frame)
  275. const zSliceRangesData = new Float32Array( NZ * 4 );
  276. const zSliceRangesTexture = new DataTexture( zSliceRangesData, NZ, 1, RGBAFormat, FloatType );
  277. // Per-cluster light-index storage (ivec4 chunks)
  278. const lightIndexesArray = new Int32Array( clusterCount * chunksPerCluster * 4 );
  279. const lightIndexes = attributeArray( lightIndexesArray, 'ivec4' ).setName( 'lightIndexes' );
  280. // compute-side accessors (use instanceIndex)
  281. const getClusterChunk = ( chunkIdx ) => {
  282. const idx = instanceIndex.mul( int( chunksPerCluster ) ).add( int( chunkIdx ) );
  283. return lightIndexes.element( idx );
  284. };
  285. const getClusterSlot = ( slotIdx ) => {
  286. slotIdx = int( slotIdx );
  287. const stride = int( 4 );
  288. const chunkOffset = slotIdx.div( stride );
  289. const idx = instanceIndex.mul( int( chunksPerCluster ) ).add( chunkOffset );
  290. return lightIndexes.element( idx ).element( slotIdx.mod( stride ) );
  291. };
  292. // compute: one thread per cluster
  293. const compute = Fn( () => {
  294. // view-space scale factors derived from the projection matrix:
  295. // view_x = ndc_x * (-view_z) / focal_x = ndc_x * (-view_z) * invFocalX
  296. // view_y = ndc_y * (-view_z) / focal_y = ndc_y * (-view_z) * invFocalY
  297. // where focal_x = projMatrix[0][0] and focal_y = projMatrix[1][1].
  298. const invFocalX = float( 1 ).div( this._cameraProjectionMatrix.element( 0 ).element( 0 ) );
  299. const invFocalY = float( 1 ).div( this._cameraProjectionMatrix.element( 1 ).element( 1 ) );
  300. // 3D cluster coordinates from instanceIndex
  301. const cx = instanceIndex.mod( NX );
  302. const cy = instanceIndex.div( NX ).mod( NY );
  303. const cz = instanceIndex.div( NX * NY );
  304. // NDC X/Y bounds of the cluster.
  305. // Y is flipped: cy=0 is the top screen row (fragment y=0), which is NDC y=+1.
  306. const ndcXmin = float( cx ).mul( 2.0 / NX ).sub( 1.0 );
  307. const ndcXmax = float( cx.add( int( 1 ) ) ).mul( 2.0 / NX ).sub( 1.0 );
  308. const ndcYmax = float( 1 ).sub( float( cy ).mul( 2.0 / NY ) );
  309. const ndcYmin = float( 1 ).sub( float( cy.add( int( 1 ) ) ).mul( 2.0 / NY ) );
  310. // View-space Z bounds (negative, exponential slicing)
  311. const farOverNear = this._cameraFar.div( this._cameraNear );
  312. const zNearCluster = this._cameraNear.mul( pow( farOverNear, float( cz ).mul( 1.0 / NZ ) ) ).negate();
  313. const zFarCluster = this._cameraNear.mul( pow( farOverNear, float( cz.add( int( 1 ) ) ).mul( 1.0 / NZ ) ) ).negate();
  314. const scaleNearX = zNearCluster.negate().mul( invFocalX );
  315. const scaleFarX = zFarCluster.negate().mul( invFocalX );
  316. const scaleNearY = zNearCluster.negate().mul( invFocalY );
  317. const scaleFarY = zFarCluster.negate().mul( invFocalY );
  318. const xMinNear = ndcXmin.mul( scaleNearX );
  319. const xMaxNear = ndcXmax.mul( scaleNearX );
  320. const xMinFar = ndcXmin.mul( scaleFarX );
  321. const xMaxFar = ndcXmax.mul( scaleFarX );
  322. const yMinNear = ndcYmin.mul( scaleNearY );
  323. const yMaxNear = ndcYmax.mul( scaleNearY );
  324. const yMinFar = ndcYmin.mul( scaleFarY );
  325. const yMaxFar = ndcYmax.mul( scaleFarY );
  326. // AABB of the 8 view-space corners (tile boundaries can straddle the view axis)
  327. const aabbMinX = min( xMinNear, xMinFar );
  328. const aabbMaxX = max( xMaxNear, xMaxFar );
  329. const aabbMinY = min( yMinNear, yMinFar );
  330. const aabbMaxY = max( yMaxNear, yMaxFar );
  331. const aabbMin = vec3( aabbMinX, aabbMinY, zFarCluster );
  332. const aabbMax = vec3( aabbMaxX, aabbMaxY, zNearCluster );
  333. // clear stale data from previous frame
  334. Loop( chunksPerCluster, ( { i } ) => {
  335. getClusterChunk( i ).assign( ivec4( 0 ) );
  336. } );
  337. const index = int( 0 ).toVar();
  338. // Z-culling: only test lights that can reach this cluster's Z-slice
  339. const zRange = textureLoad( zSliceRangesTexture, ivec2( cz, 0 ) );
  340. const rangeStart = int( zRange.x );
  341. const rangeEnd = int( zRange.y );
  342. Loop( this.maxLights, ( { i } ) => {
  343. const lightIdx = rangeStart.add( i );
  344. If( index.greaterThanEqual( int( maxLightsPerCluster ) ).or( lightIdx.greaterThanEqual( rangeEnd ) ), () => {
  345. Return();
  346. } );
  347. const { viewPosition, distance } = this.getLightData( lightIdx );
  348. // sphere-AABB intersection in view space
  349. const pos = viewPosition.xyz;
  350. const closest = max( aabbMin, min( pos, aabbMax ) );
  351. const diff = pos.sub( closest );
  352. const distSq = dot( diff, diff );
  353. If( distSq.lessThanEqual( distance.mul( distance ) ), () => {
  354. getClusterSlot( index ).assign( lightIdx.add( int( 1 ) ) );
  355. index.addAssign( int( 1 ) );
  356. } );
  357. } );
  358. } )().compute( clusterCount ).setName( 'Update Clustered Lights' );
  359. // shading-side: fragment → cluster index
  360. const getScreenClusterIndex = Fn( () => {
  361. const screenTile = screenCoordinate.div( tileSize ).floor();
  362. // view-space depth from positionView (negative in front); take magnitude
  363. const viewDepth = positionView.z.negate();
  364. // exponential Z slice: tz = floor( log(depth/near) / log(far/near) * NZ )
  365. const invLogFarOverNear = float( 1 ).div( log( this._cameraFar.div( this._cameraNear ) ) );
  366. const sliceFloat = log( viewDepth.div( this._cameraNear ) ).mul( invLogFarOverNear ).mul( float( NZ ) );
  367. const zSlice = clamp( sliceFloat.floor(), float( 0 ), float( NZ - 1 ) );
  368. return int( screenTile.x )
  369. .add( int( screenTile.y ).mul( int( NX ) ) )
  370. .add( int( zSlice ).mul( int( NX * NY ) ) );
  371. } );
  372. const screenClusterIndex = getScreenClusterIndex().toVar();
  373. // assigns
  374. this._bufferSize = bufferSize;
  375. this._lightIndexes = lightIndexes;
  376. this._screenClusterIndex = screenClusterIndex;
  377. this._compute = compute;
  378. this._lightsTexture = lightsTexture;
  379. this._zSliceRangesTexture = zSliceRangesTexture;
  380. this._zSliceRangesData = zSliceRangesData;
  381. }
  382. }
  383. export default ClusteredLightsNode;
  384. /**
  385. * TSL function that creates a clustered lights node.
  386. *
  387. * @tsl
  388. * @function
  389. * @param {number} [maxLights=1024] - Maximum number of point lights.
  390. * @param {number} [tileSize=32] - Screen tile size in pixels.
  391. * @param {number} [zSlices=24] - Depth slice count.
  392. * @param {number} [maxLightsPerCluster=64] - Per-cluster light-list capacity.
  393. * @return {ClusteredLightsNode} The clustered lights node.
  394. */
  395. export const clusteredLights = /*@__PURE__*/ nodeProxy( ClusteredLightsNode );
粤ICP备19079148号