webgpu_compute_rasterizer_lighting.html 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - compute rasterizer lighting</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <meta property="og:title" content="three.js webgpu - compute rasterizer lighting">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgpu_compute_rasterizer_lighting.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgpu_compute_rasterizer_lighting.jpg">
  11. <link type="text/css" rel="stylesheet" href="example.css">
  12. </head>
  13. <body>
  14. <div id="info">
  15. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  16. <div class="title-wrapper">
  17. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>GPU-Driven Compute Rasterizer — Lighting</span>
  18. </div>
  19. <small>Rendering <span id="triangleCount"></span> triangles.<br/>Battle Damaged Sci-fi Helmet by <a href="https://sketchfab.com/theblueturtle_" target="_blank" rel="noopener">theblueturtle_</a></small>
  20. </div>
  21. <script type="importmap">
  22. {
  23. "imports": {
  24. "three": "../build/three.webgpu.js",
  25. "three/webgpu": "../build/three.webgpu.js",
  26. "three/tsl": "../build/three.tsl.js",
  27. "three/addons/": "./jsm/"
  28. }
  29. }
  30. </script>
  31. <script type="module">
  32. import * as THREE from 'three/webgpu';
  33. import { Fn, If, Loop, vec2, vec4, uvec2, uvec4, mat4, uint, float, int, min, max, clamp, ceil, log2, length, dFdx, dFdy, atomicMax, atomicAdd, atomicStore, atomicLoad, floor, cos, sin, dot, bool, storage, uniform, uniformArray, instanceIndex, vertexIndex, distance, screenSize, screenCoordinate, time, texture, varyingProperty, sqrt, normalize, cross, sign, positionGeometry, cameraViewMatrix, Discard, context } from 'three/tsl';
  34. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  35. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  36. import { UltraHDRLoader } from 'three/addons/loaders/UltraHDRLoader.js';
  37. import { MeshoptClusterizer } from 'three/addons/libs/meshopt_clusterizer.module.js';
  38. import { MeshoptSimplifier } from 'three/addons/libs/meshopt_simplifier.module.js';
  39. import { Inspector } from 'three/addons/inspector/Inspector.js';
  40. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  41. if ( WebGPU.isAvailable() === false ) {
  42. document.body.appendChild( WebGPU.getErrorMessage() );
  43. throw new Error( 'No WebGPU support' );
  44. }
  45. let camera, scene, renderer, controls;
  46. let computeRasterize, computeClear, computeFrustum, computeDispatch, computeHWArgs;
  47. let resolveMesh, hwMesh;
  48. let cameraPos, projScreenMatrixUniform, frustumPlanesUniform, cotHalfFovUniform;
  49. let prevProjScreenUniform;
  50. let outputModeUniform;
  51. let screenTriAttr, screenTriAtomic, screenTriRead;
  52. let screenInstAttr, screenInstAtomic, screenInstRead;
  53. let maxPixels;
  54. let sceneRT, blitQuad, blitTexNode;
  55. // Hierarchical Z pyramid (max depth per tile) for occlusion culling
  56. let depthSourceTexNode;
  57. let hzbBuffer, hzbRead, hzbLevelTable, hzbLevelCountUniform, hzbLevelCount = 0;
  58. let occlusionUniform, prevCameraPosUniform;
  59. const hzbKernels = [];
  60. const MAX_HZB_LEVELS = 16;
  61. const instanceCount = 129600; // 360x360 plane or 60x36x60 volume
  62. const MAX_RASTER_SIZE = 16;
  63. // Specular antialiasing — kernel roughness from normal variance, shared by
  64. // both rasterizer paths so their roughness matches at path boundaries
  65. const SPECULAR_AA_VARIANCE = 2.0;
  66. const SPECULAR_AA_MAX = 0.2;
  67. const options = { Output: 'Default', Rasterizer: 'Both', Occlusion: true, Grid: 'XZ' };
  68. // Buffer visibility packaging configuration — depth occupies the bits above each payload
  69. const TRIANGLE_INDEX_BITS = 15; // 2^15 = 32768 max triangles in the LOD mega buffer
  70. const INSTANCE_INDEX_BITS = 17; // 2^17 = 131072 max instances
  71. const TRIANGLE_INDEX_MASK = 2 ** TRIANGLE_INDEX_BITS - 1;
  72. const INSTANCE_INDEX_MASK = 2 ** INSTANCE_INDEX_BITS - 1;
  73. const DEPTH_TRI_MAX = 2 ** ( 32 - TRIANGLE_INDEX_BITS ) - 1; // 17-bit depth packed above the triangle index
  74. const DEPTH_INST_MAX = 2 ** ( 32 - INSTANCE_INDEX_BITS ) - 1; // 15-bit depth packed above the instance id
  75. const getVisColor = ( outputMode, normal, normalMap, uv, roughness, metalness, ao, emissive ) => {
  76. return Fn( () => {
  77. const result = vec4( 0.0 ).toVar();
  78. If( outputMode.equal( 1 ), () => {
  79. // Geometry Normal: map [-1, 1] to [0, 1]
  80. result.assign( vec4( normal.mul( 0.5 ).add( 0.5 ), 1.0 ) );
  81. } ).ElseIf( outputMode.equal( 2 ), () => {
  82. // Normal Map: map [-1, 1] to [0, 1]
  83. result.assign( vec4( normalMap.mul( 0.5 ).add( 0.5 ), 1.0 ) );
  84. } ).ElseIf( outputMode.equal( 3 ), () => {
  85. // UV
  86. result.assign( vec4( uv, 0.0, 1.0 ) );
  87. } ).ElseIf( outputMode.equal( 4 ), () => {
  88. // Roughness
  89. result.assign( vec4( roughness, roughness, roughness, 1.0 ) );
  90. } ).ElseIf( outputMode.equal( 5 ), () => {
  91. // Metalness
  92. result.assign( vec4( metalness, metalness, metalness, 1.0 ) );
  93. } ).ElseIf( outputMode.equal( 6 ), () => {
  94. // AO
  95. result.assign( vec4( ao, ao, ao, 1.0 ) );
  96. } ).ElseIf( outputMode.equal( 7 ), () => {
  97. // Emissive
  98. result.assign( vec4( emissive, 1.0 ) );
  99. } );
  100. return result;
  101. } )();
  102. };
  103. init();
  104. async function init() {
  105. renderer = new THREE.WebGPURenderer();
  106. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  107. renderer.setPixelRatio( window.devicePixelRatio );
  108. renderer.setSize( window.innerWidth, window.innerHeight );
  109. renderer.setAnimationLoop( animate );
  110. renderer.inspector = new Inspector();
  111. document.body.appendChild( renderer.domElement );
  112. await renderer.init();
  113. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, .25, 1000000 );
  114. controls = new OrbitControls( camera, renderer.domElement );
  115. controls.enableDamping = true;
  116. controls.zoomSpeed = .5;
  117. controls.maxDistance = 1000;
  118. // Load assets
  119. const [ gltf, envTexture ] = await Promise.all( [
  120. new GLTFLoader().loadAsync( 'models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf' ),
  121. new UltraHDRLoader().loadAsync( 'textures/equirectangular/royal_esplanade_2k.hdr.jpg' ),
  122. MeshoptClusterizer.ready,
  123. MeshoptSimplifier.ready
  124. ] );
  125. envTexture.mapping = THREE.EquirectangularReflectionMapping;
  126. let sourceMesh;
  127. gltf.scene.traverse( ( child ) => {
  128. if ( child.isMesh ) sourceMesh = child;
  129. } );
  130. const sourceMaterial = sourceMesh.material;
  131. // Bake the glTF node transform into the geometry (the helmet is authored z-up)
  132. gltf.scene.updateMatrixWorld( true );
  133. sourceMesh.geometry.applyMatrix4( sourceMesh.matrixWorld );
  134. // Generate LOD geometries and meshlets using Meshopt
  135. const lodTargets = [
  136. { ratio: 1.0, error: 0.0, weights: [ 0.25, 0.25, 0.25, 0.5, 0.5 ], flags: [] },
  137. { ratio: 0.12, error: 0.03, weights: [ 0.1, 0.1, 0.1, 0.15, 0.15 ], flags: [ 'RegularizeLight' ] },
  138. { ratio: 0.02, error: 0.15, weights: [ 0.02, 0.02, 0.02, 0.03, 0.03 ], flags: [ 'Regularize' ] }
  139. ];
  140. const geom = sourceMesh.geometry;
  141. geom.computeBoundingSphere();
  142. const boundingRadius = geom.boundingSphere.radius * 1.05;
  143. const posAttr = geom.attributes.position;
  144. const normAttr = geom.attributes.normal;
  145. const uvAttr = geom.attributes.uv;
  146. const vertexCount = posAttr.count;
  147. const simplifierAttributes = new Float32Array( vertexCount * 5 );
  148. for ( let i = 0; i < vertexCount; i ++ ) {
  149. simplifierAttributes[ i * 5 + 0 ] = normAttr.getX( i );
  150. simplifierAttributes[ i * 5 + 1 ] = normAttr.getY( i );
  151. simplifierAttributes[ i * 5 + 2 ] = normAttr.getZ( i );
  152. simplifierAttributes[ i * 5 + 3 ] = uvAttr.getX( i );
  153. simplifierAttributes[ i * 5 + 4 ] = uvAttr.getY( i );
  154. }
  155. const sourceIndices = geom.index ? new Uint32Array( geom.index.array ) : new Uint32Array( Array.from( { length: vertexCount }, ( _, i ) => i ) );
  156. const sourceScale = MeshoptSimplifier.getScale( posAttr.array, 3 );
  157. const lods = [];
  158. let totalChunks = 0;
  159. let indices = sourceIndices;
  160. let previousError = 0;
  161. for ( let i = 0; i < lodTargets.length; i ++ ) {
  162. let error = 0;
  163. if ( i > 0 ) {
  164. const target = lodTargets[ i ];
  165. const targetIndexCount = Math.max( 3, Math.floor( sourceIndices.length * target.ratio / 3 ) * 3 );
  166. const simplified = MeshoptSimplifier.simplifyWithAttributes(
  167. indices,
  168. posAttr.array,
  169. 3,
  170. simplifierAttributes,
  171. 5,
  172. target.weights,
  173. null,
  174. targetIndexCount,
  175. target.error,
  176. target.flags
  177. );
  178. if ( simplified[ 0 ].length >= 3 ) {
  179. indices = simplified[ 0 ];
  180. error = previousError + simplified[ 1 ] * sourceScale;
  181. } else {
  182. error = previousError;
  183. }
  184. }
  185. previousError = error;
  186. const meshletBuffers = MeshoptClusterizer.buildMeshlets(
  187. indices,
  188. posAttr.array,
  189. 3,
  190. 64,
  191. 64,
  192. 0.25
  193. );
  194. const bounds = MeshoptClusterizer.computeMeshletBounds( meshletBuffers, posAttr.array, 3 );
  195. const lod = {
  196. meshletBuffers,
  197. bounds,
  198. error,
  199. numChunks: meshletBuffers.meshletCount,
  200. numTriangles: meshletBuffers.meshletCount * 64, // Padded to exactly 64 triangles per chunk
  201. numVertices: vertexCount,
  202. vertexOffset: i * vertexCount,
  203. positions: posAttr,
  204. normals: normAttr,
  205. uvs: uvAttr
  206. };
  207. lods.push( lod );
  208. totalChunks += lod.numChunks;
  209. }
  210. console.info( 'LOD Meshlets count: ', lods.map( l => l.numChunks ) );
  211. const totalVertices = lods.length * vertexCount;
  212. const totalIndices = totalChunks * 64 * 3;
  213. if ( totalIndices / 3 > TRIANGLE_INDEX_MASK + 1 ) throw new Error( 'Triangle count exceeds payload bit budget' );
  214. if ( instanceCount > INSTANCE_INDEX_MASK + 1 ) throw new Error( 'Instance count exceeds payload bit budget' );
  215. const maxTrianglesPerInstance = lods[ 0 ].numTriangles;
  216. const totalTriangles = instanceCount * maxTrianglesPerInstance;
  217. document.getElementById( 'triangleCount' ).innerText = new Intl.NumberFormat().format( totalTriangles );
  218. const vertexArray = new Float32Array( totalVertices * 4 ); // vec4 padded
  219. const normalArray = new Float32Array( totalVertices * 4 ); // vec4 padded
  220. const uvArray = new Float32Array( totalVertices * 2 );
  221. const indexArray = new Uint32Array( totalIndices );
  222. const meshletTriangleArray = new Uint32Array( totalIndices / 3 ); // 1 meshlet ID per triangle
  223. const chunkBoundsData = new Float32Array( totalChunks * 4 ); // vec4: cx, cy, cz, radius
  224. let currentMeshletId = 1;
  225. let currentChunkId = 0;
  226. let currentIndexOffset = 0;
  227. for ( let i = 0; i < lods.length; i ++ ) {
  228. const lod = lods[ i ];
  229. lod.chunkStart = currentChunkId;
  230. lod.indexOffset = currentIndexOffset;
  231. // Fill vertex buffers for this LOD level
  232. for ( let v = 0; v < vertexCount; v ++ ) {
  233. const vIdx = lod.vertexOffset + v;
  234. vertexArray[ vIdx * 4 + 0 ] = lod.positions.getX( v );
  235. vertexArray[ vIdx * 4 + 1 ] = lod.positions.getY( v );
  236. vertexArray[ vIdx * 4 + 2 ] = lod.positions.getZ( v );
  237. vertexArray[ vIdx * 4 + 3 ] = 1.0;
  238. normalArray[ vIdx * 4 + 0 ] = lod.normals.getX( v );
  239. normalArray[ vIdx * 4 + 1 ] = lod.normals.getY( v );
  240. normalArray[ vIdx * 4 + 2 ] = lod.normals.getZ( v );
  241. uvArray[ vIdx * 2 + 0 ] = lod.uvs.getX( v );
  242. uvArray[ vIdx * 2 + 1 ] = lod.uvs.getY( v );
  243. }
  244. // Process and pack meshlets
  245. const meshletBuffers = lod.meshletBuffers;
  246. const bounds = lod.bounds;
  247. for ( let m = 0; m < lod.numChunks; m ++ ) {
  248. const meshlet = MeshoptClusterizer.extractMeshlet( meshletBuffers, m );
  249. const meshletTriangles = meshlet.triangles.length / 3;
  250. // Pack 64 triangles (with degenerate padding if needed)
  251. for ( let t = 0; t < 64; t ++ ) {
  252. const triIdx = ( lod.indexOffset / 3 ) + ( m * 64 ) + t;
  253. if ( t < meshletTriangles ) {
  254. const a_local = meshlet.triangles[ t * 3 + 0 ];
  255. const b_local = meshlet.triangles[ t * 3 + 1 ];
  256. const c_local = meshlet.triangles[ t * 3 + 2 ];
  257. indexArray[ triIdx * 3 + 0 ] = lod.vertexOffset + meshlet.vertices[ a_local ];
  258. indexArray[ triIdx * 3 + 1 ] = lod.vertexOffset + meshlet.vertices[ b_local ];
  259. indexArray[ triIdx * 3 + 2 ] = lod.vertexOffset + meshlet.vertices[ c_local ];
  260. } else {
  261. // Pad with degenerate triangle using the first vertex of the meshlet
  262. const a_local = meshlet.vertices[ 0 ];
  263. indexArray[ triIdx * 3 + 0 ] = lod.vertexOffset + a_local;
  264. indexArray[ triIdx * 3 + 1 ] = lod.vertexOffset + a_local;
  265. indexArray[ triIdx * 3 + 2 ] = lod.vertexOffset + a_local;
  266. }
  267. meshletTriangleArray[ triIdx ] = currentMeshletId;
  268. }
  269. currentMeshletId ++;
  270. // Bounding sphere
  271. chunkBoundsData[ currentChunkId * 4 + 0 ] = bounds[ m ].centerX;
  272. chunkBoundsData[ currentChunkId * 4 + 1 ] = bounds[ m ].centerY;
  273. chunkBoundsData[ currentChunkId * 4 + 2 ] = bounds[ m ].centerZ;
  274. chunkBoundsData[ currentChunkId * 4 + 3 ] = bounds[ m ].radius;
  275. currentChunkId ++;
  276. }
  277. currentIndexOffset += lod.numTriangles * 3;
  278. }
  279. // Upload LOD offsets to GPU (vec4: triangleStart, numTriangles, chunkStart, 0)
  280. const lodOffsetsUniform = uniformArray( lods.map( ( lod ) => new THREE.Vector4( lod.indexOffset / 3, lod.numTriangles, lod.chunkStart, 0 ) ), 'vec4' );
  281. const chunkBoundsBuffer = storage( new THREE.StorageBufferAttribute( chunkBoundsData, 4 ), 'vec4', totalChunks ).toReadOnly();
  282. // Storage Buffers
  283. const vertexBuffer = storage( new THREE.StorageBufferAttribute( vertexArray, 4 ), 'vec4', totalVertices ).toReadOnly();
  284. const normalBuffer = storage( new THREE.StorageBufferAttribute( normalArray, 4 ), 'vec4', totalVertices ).toReadOnly();
  285. const uvBuffer = storage( new THREE.StorageBufferAttribute( uvArray, 2 ), 'vec2', totalVertices ).toReadOnly();
  286. const indexBuffer = storage( new THREE.StorageBufferAttribute( indexArray, 1 ), 'uint', totalIndices ).toReadOnly();
  287. const meshletIdBuffer = storage( new THREE.StorageBufferAttribute( meshletTriangleArray, 1 ), 'uint', totalIndices / 3 ).toReadOnly();
  288. const timeScale = uniform( 1.0 );
  289. const parameterGroup = renderer.inspector.createParameters( 'Parameters' );
  290. parameterGroup.add( options, 'Output', {
  291. 'Default': 'Default',
  292. 'Meshlet Debug': 'Meshlet Debug',
  293. 'Geometry Normal': 'Geometry Normal',
  294. 'Normal Map': 'Normal Map',
  295. 'UV': 'UV',
  296. 'Roughness': 'Roughness',
  297. 'Metalness': 'Metalness',
  298. 'AO': 'AO',
  299. 'Emissive': 'Emissive'
  300. } ).addEventListener( 'change', updateMode );
  301. parameterGroup.add( options, 'Rasterizer', { 'SW Only': 'SW Only', 'HW Only': 'HW Only', 'Both': 'Both' } );
  302. parameterGroup.add( options, 'Occlusion' );
  303. parameterGroup.add( timeScale, 'value', 0.0, 1.0 ).name( 'Animation Speed' );
  304. // Packed visibility buffers — depth in the high bits, payload in the low bits,
  305. // so a single atomicMax resolves the depth test and the payload write together
  306. // and the winner is order-independent (no frame-to-frame flicker).
  307. // screenTri: depth(17) | megaTriangleIndex(15)
  308. // screenInst: depth(15) | instId(17)
  309. createScreenBuffers();
  310. const staticInstanceData = new Float32Array( instanceCount * 4 );
  311. const instanceDataAttr = new THREE.StorageBufferAttribute( staticInstanceData, 4 );
  312. const instanceDataBuffer = storage( instanceDataAttr, 'vec4', instanceCount );
  313. // Lay the instances out as a plane or a volume (same instance count)
  314. const updateGrid = () => {
  315. let dataIndex = 0;
  316. if ( options.Grid === 'XZ' ) {
  317. for ( let x = 0; x < 360; x ++ ) {
  318. for ( let z = 0; z < 360; z ++ ) {
  319. staticInstanceData[ dataIndex ++ ] = ( x - 180 ) * 4.0;
  320. staticInstanceData[ dataIndex ++ ] = - 1;
  321. staticInstanceData[ dataIndex ++ ] = ( z - 180 ) * 4.0;
  322. staticInstanceData[ dataIndex ++ ] = 1.0; // scale
  323. }
  324. }
  325. camera.position.set( 0, 8, 30 );
  326. controls.target.set( 0, - 1, 0 );
  327. } else {
  328. for ( let x = 0; x < 60; x ++ ) {
  329. for ( let y = 0; y < 36; y ++ ) {
  330. for ( let z = 0; z < 60; z ++ ) {
  331. staticInstanceData[ dataIndex ++ ] = ( x - 30 ) * 4.0;
  332. staticInstanceData[ dataIndex ++ ] = ( y - 18 ) * 4.0;
  333. staticInstanceData[ dataIndex ++ ] = ( z - 30 ) * 4.0;
  334. staticInstanceData[ dataIndex ++ ] = 1.0; // scale
  335. }
  336. }
  337. }
  338. camera.position.set( 2, 2, 40 );
  339. controls.target.set( 0, 0, 0 );
  340. }
  341. instanceDataAttr.needsUpdate = true;
  342. };
  343. updateGrid();
  344. parameterGroup.add( options, 'Grid', { 'XZ': 'XZ', 'XYZ': 'XYZ' } ).addEventListener( 'change', updateGrid );
  345. const instanceWorldData = new Float32Array( instanceCount * 16 );
  346. const instanceMvpData = new Float32Array( instanceCount * 16 );
  347. const instanceWorldAttr = new THREE.StorageBufferAttribute( instanceWorldData, 16 );
  348. const instanceMvpAttr = new THREE.StorageBufferAttribute( instanceMvpData, 16 );
  349. const instanceWorldBuffer = storage( instanceWorldAttr, 'mat4', instanceCount );
  350. const instanceMvpBuffer = storage( instanceMvpAttr, 'mat4', instanceCount );
  351. const instanceWorldRead = storage( instanceWorldAttr, 'mat4', instanceCount ).toReadOnly();
  352. // Previous frame world matrices for the occlusion test
  353. const instancePrevWorldAttr = new THREE.StorageBufferAttribute( new Float32Array( instanceCount * 16 ), 16 );
  354. const instancePrevWorldBuffer = storage( instancePrevWorldAttr, 'mat4', instanceCount );
  355. const workQueueCountData = new Uint32Array( 1 );
  356. const workQueueCountAttr = new THREE.StorageBufferAttribute( workQueueCountData, 1 );
  357. const workQueueCountAtomic = storage( workQueueCountAttr, 'uint', 1 ).toAtomic();
  358. const workQueueCountRead = storage( workQueueCountAttr, 'uint', 1 ).toReadOnly();
  359. const dispatchData = new Uint32Array( 3 );
  360. const dispatchAttr = new THREE.IndirectStorageBufferAttribute( dispatchData, 3 );
  361. const dispatchBuffer = storage( dispatchAttr, 'uint', 3 );
  362. // Work queue budget — one item is a 64-triangle chunk of one visible instance
  363. const MAX_WORK_ITEMS = 2820000;
  364. const workQueueData = new Uint32Array( MAX_WORK_ITEMS * 4 );
  365. const workQueueBuffer = storage( new THREE.StorageBufferAttribute( workQueueData, 4 ), 'uvec4', MAX_WORK_ITEMS );
  366. // HW Rasterizer Buffers (for large triangles that exceed SW raster budget)
  367. const MAX_HW_TRIANGLES = 100000;
  368. // HW queue: index 0 is atomic counter, indices 1..MAX store payload32
  369. const hwQueueData = new Uint32Array( MAX_HW_TRIANGLES + 1 );
  370. const hwQueueAttr = new THREE.StorageBufferAttribute( hwQueueData, 1 );
  371. const hwQueueAtomic = storage( hwQueueAttr, 'uint', MAX_HW_TRIANGLES + 1 ).toAtomic();
  372. const hwQueueRead = storage( hwQueueAttr, 'uint', MAX_HW_TRIANGLES + 1 ).toReadOnly();
  373. // Draw indirect buffer: vertexCount, instanceCount, firstVertex, firstInstance
  374. const hwDrawData = new Uint32Array( 4 );
  375. const hwDrawAttr = new THREE.IndirectStorageBufferAttribute( hwDrawData, 4 );
  376. const hwDrawBuffer = storage( hwDrawAttr, 'uint', 4 );
  377. projScreenMatrixUniform = uniform( new THREE.Matrix4() );
  378. prevProjScreenUniform = uniform( new THREE.Matrix4() );
  379. frustumPlanesUniform = uniformArray( [
  380. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(),
  381. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4()
  382. ], 'vec4' );
  383. cameraPos = uniform( new THREE.Vector3() );
  384. cotHalfFovUniform = uniform( 1.0 );
  385. const pixelErrorThresholdUniform = uniform( 1.0 );
  386. const maxRasterSizeUniform = uniform( MAX_RASTER_SIZE, 'int' ); // Max bounding box size in pixels for SW rasterizer
  387. occlusionUniform = uniform( 1, 'uint' );
  388. prevCameraPosUniform = uniform( new THREE.Vector3() );
  389. outputModeUniform = uniform( 0, 'uint' );
  390. depthSourceTexNode = texture( sceneRT.depthTexture );
  391. // One kernel per pyramid level — each texel keeps the max (farthest)
  392. // depth of the 2x2 it covers, so a sphere is occluded when its nearest
  393. // depth is farther than the stored value
  394. for ( let k = 0; k < MAX_HZB_LEVELS; k ++ ) {
  395. const initialInfo = hzbLevelTable.array[ Math.min( k, hzbLevelCount - 1 ) ];
  396. hzbKernels.push( Fn( () => {
  397. const info = hzbLevelTable.element( k );
  398. const levelWidth = uint( info.y );
  399. const levelHeight = uint( info.z );
  400. const levelOffset = uint( info.x );
  401. If( instanceIndex.lessThan( levelWidth.mul( levelHeight ) ), () => {
  402. const x = instanceIndex.mod( levelWidth );
  403. const y = instanceIndex.div( levelWidth );
  404. const sx = x.mul( 2 );
  405. const sy = y.mul( 2 );
  406. const depthMax = float( 0.0 ).toVar();
  407. if ( k === 0 ) {
  408. // Source: the full resolution scene depth
  409. const sw = uint( screenSize.x ).sub( 1 );
  410. const sh = uint( screenSize.y ).sub( 1 );
  411. for ( let dy = 0; dy < 2; dy ++ ) {
  412. for ( let dx = 0; dx < 2; dx ++ ) {
  413. depthMax.assign( max( depthMax, depthSourceTexNode.load( uvec2( min( sx.add( dx ), sw ), min( sy.add( dy ), sh ) ) ).r ) );
  414. }
  415. }
  416. } else {
  417. // Source: the previous pyramid level
  418. const src = hzbLevelTable.element( k - 1 );
  419. const srcWidth = uint( src.y );
  420. const srcOffset = uint( src.x );
  421. const swMax = srcWidth.sub( 1 );
  422. const shMax = uint( src.z ).sub( 1 );
  423. for ( let dy = 0; dy < 2; dy ++ ) {
  424. for ( let dx = 0; dx < 2; dx ++ ) {
  425. const tx = min( sx.add( dx ), swMax );
  426. const ty = min( sy.add( dy ), shMax );
  427. depthMax.assign( max( depthMax, hzbBuffer.element( srcOffset.add( ty.mul( srcWidth ) ).add( tx ) ) ) );
  428. }
  429. }
  430. }
  431. hzbBuffer.element( levelOffset.add( y.mul( levelWidth ) ).add( x ) ).assign( depthMax );
  432. } );
  433. } )().compute( initialInfo.y * initialInfo.z, [ 64 ] ).setName( `HZB Level ${ k }` ) );
  434. }
  435. // Conservative sphere vs pyramid test, using the previous frame's
  436. // depth and matrices (the helmets only rotate in place, so their
  437. // bounding spheres are identical between frames)
  438. const sphereOccluded = ( center, radius ) => {
  439. const toCamera = prevCameraPosUniform.sub( center );
  440. const dist = length( toCamera );
  441. // Closest point on the sphere toward the camera
  442. const nearPoint = center.add( toCamera.div( dist ).mul( radius ) );
  443. const nearClip = prevProjScreenUniform.mul( vec4( nearPoint, 1.0 ) );
  444. const centerClip = prevProjScreenUniform.mul( vec4( center, 1.0 ) );
  445. const nearestZ = nearClip.z.div( nearClip.w );
  446. const ndc = centerClip.xy.div( centerClip.w );
  447. // Footprint in half resolution pyramid texels picks the level where
  448. // the sphere's diameter fits one texel, so the 2x2 window always covers it.
  449. // The 4 combines the NDC half-screen factor with the half resolution pyramid.
  450. const radiusTexels = radius.mul( cotHalfFovUniform ).mul( float( screenSize.y ) ).div( 4.0 ).div( dist );
  451. const level = int( clamp( ceil( log2( max( radiusTexels.mul( 2.0 ), 1.0 ) ) ), 0.0, hzbLevelCountUniform.sub( 1.0 ) ) );
  452. const info = hzbLevelTable.element( level );
  453. const levelWidth = uint( info.y );
  454. const levelHeight = uint( info.z );
  455. const levelOffset = uint( info.x );
  456. const px = ndc.x.mul( 0.5 ).add( 0.5 ).mul( float( levelWidth ) );
  457. const py = float( 0.5 ).sub( ndc.y.mul( 0.5 ) ).mul( float( levelHeight ) );
  458. const x0 = uint( clamp( px.sub( 0.5 ), 0.0, float( levelWidth.sub( 1 ) ) ) );
  459. const y0 = uint( clamp( py.sub( 0.5 ), 0.0, float( levelHeight.sub( 1 ) ) ) );
  460. const x1 = min( x0.add( 1 ), levelWidth.sub( 1 ) );
  461. const y1 = min( y0.add( 1 ), levelHeight.sub( 1 ) );
  462. const maxZ = max(
  463. max( hzbRead.element( levelOffset.add( y0.mul( levelWidth ) ).add( x0 ) ), hzbRead.element( levelOffset.add( y0.mul( levelWidth ) ).add( x1 ) ) ),
  464. max( hzbRead.element( levelOffset.add( y1.mul( levelWidth ) ).add( x0 ) ), hzbRead.element( levelOffset.add( y1.mul( levelWidth ) ).add( x1 ) ) )
  465. );
  466. return dist.greaterThan( radius.mul( 2.0 ) ) // skip spheres close to the camera
  467. .and( nearClip.w.greaterThan( 0.0 ) )
  468. .and( centerClip.w.greaterThan( 0.0 ) )
  469. .and( nearestZ.greaterThan( maxZ ) );
  470. };
  471. // Compute Clear
  472. computeClear = Fn( () => {
  473. atomicStore( screenTriAtomic.element( instanceIndex ), uint( 0 ) );
  474. atomicStore( screenInstAtomic.element( instanceIndex ), uint( 0 ) );
  475. If( instanceIndex.equal( 0 ), () => {
  476. atomicStore( workQueueCountAtomic.element( 0 ), uint( 0 ) );
  477. atomicStore( hwQueueAtomic.element( 0 ), uint( 0 ) );
  478. } );
  479. } )().compute( maxPixels, [ 256 ] ).setName( 'Compute Clear' );
  480. // Compute Frustum (GPU Culling, LOD & Work Allocation)
  481. computeFrustum = Fn( () => {
  482. // Keep last frame's transform for motion vectors
  483. instancePrevWorldBuffer.element( instanceIndex ).assign( instanceWorldBuffer.element( instanceIndex ) );
  484. const data = instanceDataBuffer.element( instanceIndex );
  485. const pos = data.xyz;
  486. const scale = data.w;
  487. const i = float( instanceIndex );
  488. // Rotation
  489. const rotY = time.mul( timeScale ).add( i );
  490. const c = cos( rotY );
  491. const s = sin( rotY );
  492. // Compose MatrixWorld
  493. const matrixWorld = mat4(
  494. vec4( c.mul( scale ), 0.0, s.mul( scale ), 0.0 ),
  495. vec4( 0.0, scale, 0.0, 0.0 ),
  496. vec4( s.negate().mul( scale ), 0.0, c.mul( scale ), 0.0 ),
  497. vec4( pos, 1.0 )
  498. );
  499. const visible = bool( true ).toVar();
  500. const radius = scale.mul( boundingRadius ); // bounding sphere radius
  501. // Frustum culling using the 6 extracted world-space planes
  502. Loop( { start: 0, end: 6 }, ( { i: planeIndex } ) => {
  503. const plane = frustumPlanesUniform.element( planeIndex );
  504. const dist = dot( plane.xyz, pos ).add( plane.w );
  505. If( dist.lessThan( radius.negate() ), () => {
  506. visible.assign( false );
  507. } );
  508. } );
  509. // Occlusion cull the whole instance against the depth pyramid
  510. If( visible.and( occlusionUniform.equal( uint( 1 ) ) ), () => {
  511. visible.assign( sphereOccluded( pos, radius ).not() );
  512. } );
  513. If( visible, () => {
  514. const distToCamera = distance( cameraPos, pos );
  515. // Precompute projection factor once (Screen-Space Projected Error)
  516. // pixelError = cotHalfFov * errorWorld / dist * screenH / 2
  517. const pixelFactor = cotHalfFovUniform.div( max( 0.01, distToCamera ) ).mul( float( screenSize.y ) ).div( 2.0 );
  518. const lodLevel = uint( 0 ).toVar();
  519. let lodSelection = null;
  520. for ( let i = lods.length - 1; i > 0; i -- ) {
  521. const checkLod = float( lods[ i ].error ).mul( scale ).mul( pixelFactor ).lessThanEqual( pixelErrorThresholdUniform );
  522. if ( lodSelection === null ) {
  523. lodSelection = If( checkLod, () => {
  524. lodLevel.assign( i );
  525. } );
  526. } else {
  527. lodSelection = lodSelection.ElseIf( checkLod, () => {
  528. lodLevel.assign( i );
  529. } );
  530. }
  531. }
  532. const lodData = lodOffsetsUniform.element( lodLevel );
  533. const lodTriStart = uint( lodData.x );
  534. const lodNumTriangles = uint( lodData.y );
  535. const lodChunkStart = uint( lodData.z );
  536. // Calculate Work Items (64 triangles per item)
  537. const workItems = lodNumTriangles.add( 63 ).div( 64 );
  538. // Evaluate each Chunk (Cluster)
  539. Loop( { name: 'cIdx', type: 'uint', start: uint( 0 ), end: workItems, condition: '<' }, ( { cIdx: chunkIndex } ) => {
  540. const globalChunkId = lodChunkStart.add( uint( chunkIndex ) );
  541. const chunkBounds = chunkBoundsBuffer.element( globalChunkId );
  542. const chunkCenterLocal = chunkBounds.xyz;
  543. const chunkRadiusLocal = chunkBounds.w;
  544. // Transform chunk bounding sphere to world space and store as var to prevent inlining
  545. const chunkCenterWorld = matrixWorld.mul( vec4( chunkCenterLocal, 1.0 ) ).xyz.toVar();
  546. const chunkRadiusWorld = chunkRadiusLocal.mul( scale ).toVar();
  547. const chunkVisible = bool( true ).toVar();
  548. // Frustum cull the chunk
  549. Loop( { name: 'pIdx', start: 0, end: 6 }, ( { pIdx: planeIndex } ) => {
  550. const plane = frustumPlanesUniform.element( planeIndex );
  551. const chunkDist = dot( plane.xyz, chunkCenterWorld ).add( plane.w );
  552. If( chunkDist.lessThan( chunkRadiusWorld.negate() ), () => {
  553. chunkVisible.assign( false );
  554. } );
  555. } );
  556. // Occlusion cull the chunk, using its previous frame position
  557. // to stay consistent with the previous frame depth pyramid
  558. If( chunkVisible.and( occlusionUniform.equal( uint( 1 ) ) ), () => {
  559. const chunkCenterPrev = instancePrevWorldBuffer.element( instanceIndex ).mul( vec4( chunkCenterLocal, 1.0 ) ).xyz.toVar();
  560. chunkVisible.assign( sphereOccluded( chunkCenterPrev, chunkRadiusWorld ).not() );
  561. } );
  562. If( chunkVisible, () => {
  563. const itemIndex = atomicAdd( workQueueCountAtomic.element( 0 ), 1 );
  564. // uvec4( instanceIndex, triangleStart, lodNumTriangles, chunkIndex )
  565. workQueueBuffer.element( itemIndex ).assign(
  566. uvec4( instanceIndex, lodTriStart, lodNumTriangles, uint( chunkIndex ) )
  567. );
  568. } );
  569. } );
  570. // Store transform for this instance
  571. instanceWorldBuffer.element( instanceIndex ).assign( matrixWorld );
  572. instanceMvpBuffer.element( instanceIndex ).assign( projScreenMatrixUniform.mul( matrixWorld ) );
  573. } );
  574. } )().compute( instanceCount ).setName( 'Compute Frustum' );
  575. // Compute Dispatch (Indirect arguments)
  576. computeDispatch = Fn( () => {
  577. const totalWorkgroups = workQueueCountRead.element( 0 );
  578. const maxDim = uint( 65535 );
  579. // Split totalWorkgroups into 2D dispatch if it exceeds 65535
  580. const dispatchX = min( totalWorkgroups, maxDim );
  581. const dispatchY = totalWorkgroups.add( maxDim ).sub( 1 ).div( maxDim );
  582. dispatchBuffer.element( 0 ).assign( dispatchX );
  583. dispatchBuffer.element( 1 ).assign( dispatchY );
  584. dispatchBuffer.element( 2 ).assign( 1 );
  585. } )().compute( 1 ).setName( 'Compute Dispatch' );
  586. // Edge function for barycentric coordinates
  587. const edgeFunction = Fn( ( [ a, b, c ] ) => {
  588. // (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)
  589. return c.y.sub( a.y ).mul( b.x.sub( a.x ) ).sub( c.x.sub( a.x ).mul( b.y.sub( a.y ) ) );
  590. } );
  591. // Compute Rasterizer
  592. computeRasterize = Fn( () => {
  593. const totalWorkgroups = workQueueCountRead.element( 0 );
  594. const totalThreads = totalWorkgroups.mul( 64 );
  595. If( instanceIndex.lessThan( totalThreads ), () => {
  596. const workItemId = instanceIndex.div( 64 );
  597. const localTriangleIndex = instanceIndex.mod( 64 );
  598. const workItem = workQueueBuffer.element( workItemId );
  599. const instId = workItem.x;
  600. const lodTriStart = workItem.y;
  601. const lodNumTriangles = workItem.z;
  602. const chunkIndex = workItem.w;
  603. const globalTriangleIndex = chunkIndex.mul( 64 ).add( localTriangleIndex );
  604. If( globalTriangleIndex.lessThan( lodNumTriangles ), () => {
  605. const megaTriangleIndex = lodTriStart.add( globalTriangleIndex );
  606. const indexOffset = megaTriangleIndex.mul( 3 );
  607. const i0 = indexBuffer.element( indexOffset );
  608. const i1 = indexBuffer.element( indexOffset.add( 1 ) );
  609. const i2 = indexBuffer.element( indexOffset.add( 2 ) );
  610. const v0 = vertexBuffer.element( i0 );
  611. const v1 = vertexBuffer.element( i1 );
  612. const v2 = vertexBuffer.element( i2 );
  613. const instMvpMatrix = instanceMvpBuffer.element( instId );
  614. // MVP
  615. const p0 = instMvpMatrix.mul( v0 );
  616. const p1 = instMvpMatrix.mul( v1 );
  617. const p2 = instMvpMatrix.mul( v2 );
  618. // Near plane clipping
  619. If( p0.w.greaterThan( 0.0 ).and( p1.w.greaterThan( 0.0 ) ).and( p2.w.greaterThan( 0.0 ) ), () => {
  620. const ndc0 = p0.xyz.div( p0.w );
  621. const ndc1 = p1.xyz.div( p1.w );
  622. const ndc2 = p2.xyz.div( p2.w );
  623. // Early Backface Culling in NDC
  624. const areaNdc = edgeFunction( ndc0, ndc1, ndc2 );
  625. If( areaNdc.greaterThan( 0.0 ), () => {
  626. // NDC guard: skip triangles entirely outside clip volume
  627. const ndcMinX = min( ndc0.x, min( ndc1.x, ndc2.x ) );
  628. const ndcMaxX = max( ndc0.x, max( ndc1.x, ndc2.x ) );
  629. const ndcMinY = min( ndc0.y, min( ndc1.y, ndc2.y ) );
  630. const ndcMaxY = max( ndc0.y, max( ndc1.y, ndc2.y ) );
  631. If( ndcMaxX.greaterThan( - 1.0 ).and( ndcMinX.lessThan( 1.0 ) ).and( ndcMaxY.greaterThan( - 1.0 ) ).and( ndcMinY.lessThan( 1.0 ) ), () => {
  632. // Map to screen coordinates
  633. const w = screenSize.x;
  634. const h = screenSize.y;
  635. const s0 = ndc0.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  636. const s1 = ndc1.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  637. const s2 = ndc2.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  638. // Bounding Box
  639. const minX = max( 0.0, min( s0.x, min( s1.x, s2.x ) ) );
  640. const maxX = min( w.sub( 1.0 ), max( s0.x, max( s1.x, s2.x ) ) );
  641. const minY = max( 0.0, min( s0.y, min( s1.y, s2.y ) ) );
  642. const maxY = min( h.sub( 1.0 ), max( s0.y, max( s1.y, s2.y ) ) );
  643. const startX = int( floor( minX ) );
  644. const endX = int( floor( maxX ) );
  645. const startY = int( floor( minY ) );
  646. const endY = int( floor( maxY ) );
  647. // Big triangle guard: skip triangles larger than maxRasterSize
  648. // This is the key performance safeguard — software rasterizers
  649. // should only handle small triangles. Large triangles cause O(n²)
  650. // pixel iteration per thread, which kills performance when close.
  651. const bbWidth = endX.sub( startX );
  652. const bbHeight = endY.sub( startY );
  653. // Compute payload32 for HW path (full precision)
  654. // payload32: instId (17 bits) | megaTriangleIndex (15 bits)
  655. const payload32 = instId.shiftLeft( TRIANGLE_INDEX_BITS ).bitOr( megaTriangleIndex.bitAnd( TRIANGLE_INDEX_MASK ) );
  656. // Sub-pixel / Valid bounds rejection + big triangle guard
  657. If( startX.lessThanEqual( endX ).and( startY.lessThanEqual( endY ) ).and( bbWidth.lessThanEqual( maxRasterSizeUniform ) ).and( bbHeight.lessThanEqual( maxRasterSizeUniform ) ), () => {
  658. const area = edgeFunction( s0, s1, s2 );
  659. const stepX_w0 = s1.y.sub( s2.y );
  660. const stepY_w0 = s2.x.sub( s1.x );
  661. const stepX_w1 = s2.y.sub( s0.y );
  662. const stepY_w1 = s0.x.sub( s2.x );
  663. const stepX_w2 = s0.y.sub( s1.y );
  664. const stepY_w2 = s1.x.sub( s0.x );
  665. // Top-Left rule check for each edge to guarantee watertightness
  666. const isTopLeft0 = stepX_w0.lessThan( 0.0 ).or( stepX_w0.equal( 0.0 ).and( stepY_w0.greaterThan( 0.0 ) ) );
  667. const isTopLeft1 = stepX_w1.lessThan( 0.0 ).or( stepX_w1.equal( 0.0 ).and( stepY_w1.greaterThan( 0.0 ) ) );
  668. const isTopLeft2 = stepX_w2.lessThan( 0.0 ).or( stepX_w2.equal( 0.0 ).and( stepY_w2.greaterThan( 0.0 ) ) );
  669. const bias0 = isTopLeft0.select( 0.0, - 1e-5 );
  670. const bias1 = isTopLeft1.select( 0.0, - 1e-5 );
  671. const bias2 = isTopLeft2.select( 0.0, - 1e-5 );
  672. const pStart = vec2( float( startX ).add( 0.5 ), float( startY ).add( 0.5 ) );
  673. const row_w0 = edgeFunction( s1, s2, pStart ).toVar();
  674. const row_w1 = edgeFunction( s2, s0, pStart ).toVar();
  675. const row_w2 = edgeFunction( s0, s1, pStart ).toVar();
  676. row_w0.addAssign( bias0 );
  677. row_w1.addAssign( bias1 );
  678. row_w2.addAssign( bias2 );
  679. // Incremental Z Math (ALU Optimization)
  680. const b0_start = row_w0.div( area );
  681. const b1_start = row_w1.div( area );
  682. const b2_start = row_w2.div( area );
  683. const row_z = b0_start.mul( ndc0.z ).add( b1_start.mul( ndc1.z ) ).add( b2_start.mul( ndc2.z ) ).toVar();
  684. const stepX_z = stepX_w0.div( area ).mul( ndc0.z ).add( stepX_w1.div( area ).mul( ndc1.z ) ).add( stepX_w2.div( area ).mul( ndc2.z ) );
  685. const stepY_z = stepY_w0.div( area ).mul( ndc0.z ).add( stepY_w1.div( area ).mul( ndc1.z ) ).add( stepY_w2.div( area ).mul( ndc2.z ) );
  686. Loop( { name: 'y', type: 'int', start: startY, end: endY, condition: '<=' }, ( { y } ) => {
  687. const w0 = row_w0.toVar();
  688. const w1 = row_w1.toVar();
  689. const w2 = row_w2.toVar();
  690. const z = row_z.toVar();
  691. Loop( { name: 'x', type: 'int', start: startX, end: endX, condition: '<=' }, ( { x } ) => {
  692. If( w0.greaterThanEqual( 0.0 ).and( w1.greaterThanEqual( 0.0 ) ).and( w2.greaterThanEqual( 0.0 ) ), () => {
  693. If( z.greaterThanEqual( 0.0 ).and( z.lessThanEqual( 1.0 ) ), () => {
  694. // Depth (fourth-root distribution) packed above each payload's bits
  695. const zEncoded = sqrt( sqrt( float( 1.0 ).sub( z ) ) );
  696. const depthTri = uint( zEncoded.mul( DEPTH_TRI_MAX ) );
  697. const depthInst = uint( zEncoded.mul( DEPTH_INST_MAX ) );
  698. const packedTri = depthTri.shiftLeft( TRIANGLE_INDEX_BITS ).bitOr( megaTriangleIndex.bitAnd( TRIANGLE_INDEX_MASK ) );
  699. const packedInst = depthInst.shiftLeft( INSTANCE_INDEX_BITS ).bitOr( instId );
  700. const pixelIndex = uint( y ).mul( uint( screenSize.x ) ).add( uint( x ) );
  701. // Early depth pre-check: skip the atomics if the pixel already has a closer fragment
  702. const currentDepth = atomicLoad( screenTriAtomic.element( pixelIndex ) ).shiftRight( TRIANGLE_INDEX_BITS );
  703. If( depthTri.greaterThanEqual( currentDepth ), () => {
  704. // Depth occupies the high bits, so atomicMax resolves the depth
  705. // test and the payload write in one order-independent step
  706. atomicMax( screenTriAtomic.element( pixelIndex ), packedTri );
  707. atomicMax( screenInstAtomic.element( pixelIndex ), packedInst );
  708. } );
  709. } );
  710. } );
  711. w0.addAssign( stepX_w0 );
  712. w1.addAssign( stepX_w1 );
  713. w2.addAssign( stepX_w2 );
  714. z.addAssign( stepX_z );
  715. } );
  716. row_w0.addAssign( stepY_w0 );
  717. row_w1.addAssign( stepY_w1 );
  718. row_w2.addAssign( stepY_w2 );
  719. row_z.addAssign( stepY_z );
  720. } );
  721. } ).Else( () => {
  722. // Big triangle → enqueue for HW rasterization
  723. If( startX.lessThanEqual( endX ).and( startY.lessThanEqual( endY ) ), () => {
  724. const hwCount = atomicAdd( hwQueueAtomic.element( 0 ), 1 );
  725. const hwSlot = hwCount.add( 1 );
  726. atomicStore( hwQueueAtomic.element( hwSlot ), payload32 );
  727. } );
  728. } );
  729. } );
  730. } ); // End Early Backface Culling
  731. } ); // End Near Plane Clipping
  732. } ); // End globalTriangleIndex bounds check
  733. } ); // End instanceIndex bounds check
  734. } )().compute( dispatchAttr ).setName( 'Compute Rasterize' );
  735. // Compute HW Draw Indirect Args
  736. computeHWArgs = Fn( () => {
  737. const hwCount = atomicLoad( hwQueueAtomic.element( 0 ) );
  738. // Non-indexed draw: vertexCount = hwCount * 3 (3 verts per triangle)
  739. hwDrawBuffer.element( 0 ).assign( hwCount.mul( 3 ) ); // vertexCount
  740. hwDrawBuffer.element( 1 ).assign( uint( 1 ) ); // instanceCount
  741. hwDrawBuffer.element( 2 ).assign( uint( 0 ) ); // firstVertex
  742. hwDrawBuffer.element( 3 ).assign( uint( 0 ) ); // firstInstance
  743. } )().compute( 1 ).setName( 'Compute HW Args' );
  744. // Hash function for meshlet colors (shared between HW mesh and fullscreen resolve)
  745. const hashColor = Fn( ( [ id_in ] ) => {
  746. let id = uint( id_in ).toVar();
  747. id = id.mul( uint( 747796405 ) ).add( uint( 289559509 ) );
  748. id = id.shiftRight( 16 ).bitXor( id ).mul( uint( 277803737 ) );
  749. id = id.shiftRight( 16 ).bitXor( id );
  750. const r = float( id.bitAnd( uint( 255 ) ) ).div( 255.0 );
  751. const g = float( id.shiftRight( 8 ).bitAnd( uint( 255 ) ) ).div( 255.0 );
  752. const b = float( id.shiftRight( 16 ).bitAnd( uint( 255 ) ) ).div( 255.0 );
  753. return vec4( r.mul( 0.8 ).add( 0.2 ), g.mul( 0.8 ).add( 0.2 ), b.mul( 0.8 ).add( 0.2 ), 1.0 );
  754. } );
  755. // Tangent from the triangle's world-space edges and UVs,
  756. // for normal mapping without precomputed tangents
  757. const computeTangent = ( w0, w1, w2, uv0, uv1, uv2, normal ) => {
  758. const dp1 = w1.sub( w0 );
  759. const dp2 = w2.sub( w0 );
  760. const duv1 = uv1.sub( uv0 );
  761. const duv2 = uv2.sub( uv0 );
  762. const det = duv1.x.mul( duv2.y ).sub( duv1.y.mul( duv2.x ) );
  763. const tangentRaw = dp1.mul( duv2.y ).sub( dp2.mul( duv1.y ) ).mul( sign( det ) );
  764. // Orthonormalize against the (smooth) normal
  765. return normalize( tangentRaw.sub( normal.mul( dot( normal, tangentRaw ) ) ) );
  766. };
  767. const applyNormalMap = ( normal, tangent, mapSample ) => {
  768. const bitangent = cross( normal, tangent );
  769. const mapN = mapSample.xyz.mul( 2.0 ).sub( 1.0 );
  770. return normalize( tangent.mul( mapN.x ).add( bitangent.mul( mapN.y ) ).add( normal.mul( mapN.z ) ) );
  771. };
  772. // Scene — the resolve pass and the HW mesh share it, so both are lit
  773. // by the same environment through the standard material pipeline
  774. scene = new THREE.Scene();
  775. scene.background = envTexture;
  776. scene.backgroundBlurriness = 0.5;
  777. scene.environment = envTexture;
  778. // HW Rasterizer Mesh (renders big triangles via the GPU hardware pipeline)
  779. // Unlike the SW rasterizer which writes to an atomic screen buffer,
  780. // the HW mesh renders directly with hardware depth testing.
  781. // It renders AFTER the fullscreen resolve, overlaying HW-rasterized triangles.
  782. {
  783. // Geometry: dummy positions, vertex count driven by indirect draw
  784. const hwGeometry = new THREE.BufferGeometry();
  785. hwGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( new Float32Array( MAX_HW_TRIANGLES * 3 * 3 ), 3 ) );
  786. hwGeometry.setIndirect( hwDrawAttr );
  787. hwGeometry.boundingSphere = new THREE.Sphere().set( new THREE.Vector3(), Infinity );
  788. // Varyings from the vertex pulling stage
  789. const vPayload = varyingProperty( 'uint', 'vPayload' );
  790. const vUv = varyingProperty( 'vec2', 'vUv' );
  791. const vNormal = varyingProperty( 'vec3', 'vNormal' );
  792. const vTangent = varyingProperty( 'vec3', 'vTangent' );
  793. // Vertex pulling shared by both HW materials
  794. const hwPosition = Fn( () => {
  795. // vertexIndex: 0,1,2, 3,4,5, 6,7,8, ...
  796. const triIndex = vertexIndex.div( 3 ); // which triangle in HW queue
  797. const localVert = vertexIndex.mod( 3 ); // which vertex (0, 1, 2)
  798. const payload32 = hwQueueRead.element( triIndex.add( 1 ) );
  799. const instId = payload32.shiftRight( TRIANGLE_INDEX_BITS );
  800. const megaTriIdx = payload32.bitAnd( TRIANGLE_INDEX_MASK );
  801. const matrixWorld = instanceWorldRead.element( instId );
  802. const indexOffset = megaTriIdx.mul( 3 );
  803. const i0 = indexBuffer.element( indexOffset );
  804. const i1 = indexBuffer.element( indexOffset.add( 1 ) );
  805. const i2 = indexBuffer.element( indexOffset.add( 2 ) );
  806. // World-space corners for the tangent frame
  807. const w0 = matrixWorld.mul( vertexBuffer.element( i0 ) ).xyz;
  808. const w1 = matrixWorld.mul( vertexBuffer.element( i1 ) ).xyz;
  809. const w2 = matrixWorld.mul( vertexBuffer.element( i2 ) ).xyz;
  810. // This vertex's position, normal and uv
  811. const vertGlobalIdx = indexBuffer.element( indexOffset.add( localVert ) );
  812. const worldPos = localVert.equal( 1 ).select( w1, localVert.equal( 2 ).select( w2, w0 ) );
  813. const worldNormal = normalize( matrixWorld.mul( vec4( normalBuffer.element( vertGlobalIdx ).xyz, 0.0 ) ).xyz );
  814. const uv0 = uvBuffer.element( i0 );
  815. const uv1 = uvBuffer.element( i1 );
  816. const uv2 = uvBuffer.element( i2 );
  817. const uvVal = localVert.equal( 1 ).select( uv1, localVert.equal( 2 ).select( uv2, uv0 ) );
  818. vPayload.assign( payload32 );
  819. vUv.assign( uvVal );
  820. vNormal.assign( worldNormal );
  821. vTangent.assign( computeTangent( w0, w1, w2, uv0, uv1, uv2, worldNormal ) );
  822. return worldPos;
  823. } )();
  824. // Shaded: the standard material pipeline lights the pulled geometry
  825. const sampleMapHW = ( map ) => texture( map, vUv );
  826. // Specular antialiasing from hardware derivatives of the geometric normal
  827. const hwNormal = normalize( vNormal );
  828. const hwDNdx = dFdx( hwNormal );
  829. const hwDNdy = dFdy( hwNormal );
  830. const hwKernelRoughness = min( hwDNdx.dot( hwDNdx ).add( hwDNdy.dot( hwDNdy ) ).mul( SPECULAR_AA_VARIANCE ), SPECULAR_AA_MAX );
  831. const hwShadedMaterial = new THREE.MeshStandardNodeMaterial();
  832. hwShadedMaterial.positionNode = hwPosition;
  833. hwShadedMaterial.colorNode = sampleMapHW( sourceMaterial.map );
  834. hwShadedMaterial.normalNode = applyNormalMap( hwNormal, normalize( vTangent ), sampleMapHW( sourceMaterial.normalMap ) ).transformDirection( cameraViewMatrix );
  835. const metalRoughHW = sampleMapHW( sourceMaterial.roughnessMap ); // glTF packs roughness (g) and metalness (b) in one texture
  836. hwShadedMaterial.roughnessNode = sqrt( metalRoughHW.g.mul( metalRoughHW.g ).add( hwKernelRoughness ) );
  837. hwShadedMaterial.metalnessNode = metalRoughHW.b;
  838. hwShadedMaterial.aoNode = sampleMapHW( sourceMaterial.aoMap ).r;
  839. hwShadedMaterial.emissiveNode = sampleMapHW( sourceMaterial.emissiveMap ).rgb;
  840. // Meshlet debug: flat colors per cluster
  841. const hwDebugMaterial = new THREE.NodeMaterial();
  842. hwDebugMaterial.positionNode = hwPosition;
  843. hwDebugMaterial.fragmentNode = Fn( () => {
  844. const instId = vPayload.shiftRight( TRIANGLE_INDEX_BITS );
  845. const megaTriangleIndex = vPayload.bitAnd( TRIANGLE_INDEX_MASK );
  846. const meshletId = meshletIdBuffer.element( megaTriangleIndex ).add( instId.mul( 1000 ) );
  847. return hashColor( meshletId );
  848. } )();
  849. // Vis material: unlit visualization of channels
  850. const hwVisMaterial = new THREE.NodeMaterial();
  851. hwVisMaterial.positionNode = hwPosition;
  852. hwVisMaterial.fragmentNode = getVisColor(
  853. outputModeUniform,
  854. hwNormal,
  855. applyNormalMap( hwNormal, normalize( vTangent ), sampleMapHW( sourceMaterial.normalMap ) ),
  856. vUv,
  857. metalRoughHW.g,
  858. metalRoughHW.b,
  859. sampleMapHW( sourceMaterial.aoMap ).r,
  860. sampleMapHW( sourceMaterial.emissiveMap ).rgb
  861. );
  862. hwMesh = new THREE.Mesh( hwGeometry, hwShadedMaterial );
  863. hwMesh.userData.shadedMaterial = hwShadedMaterial;
  864. hwMesh.userData.debugMaterial = hwDebugMaterial;
  865. hwMesh.userData.visMaterial = hwVisMaterial;
  866. hwMesh.frustumCulled = false;
  867. hwMesh.renderOrder = 2;
  868. scene.add( hwMesh );
  869. }
  870. // Fullscreen Resolve Pass
  871. // A fullscreen triangle rendered through the scene camera. Using vertexNode
  872. // makes positionView reconstruct per fragment from clip space, so the standard
  873. // lighting pipeline (environment + lights) can shade the visibility buffer.
  874. {
  875. const resolveGeometry = new THREE.BufferGeometry();
  876. resolveGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( new Float32Array( [ - 1, - 1, 0, 3, - 1, 0, - 1, 3, 0 ] ), 3 ) );
  877. resolveGeometry.boundingSphere = new THREE.Sphere().set( new THREE.Vector3(), Infinity );
  878. // Shared reconstruction — built once, referenced by every material slot;
  879. // identical node instances are emitted only once in the final shader
  880. // The rasterizer addresses the screen bottom-up, screenCoordinate is top-down
  881. const flippedY = float( screenSize.y ).sub( screenCoordinate.y );
  882. const pixelIndex = uint( flippedY ).mul( uint( screenSize.x ) ).add( uint( screenCoordinate.x ) );
  883. const packedTri = screenTriRead.element( pixelIndex );
  884. const megaTriangleIndex = packedTri.bitAnd( TRIANGLE_INDEX_MASK );
  885. const instId = screenInstRead.element( pixelIndex ).bitAnd( INSTANCE_INDEX_MASK );
  886. // Visibility Buffer: Fetch exact vertices, normals and UVs
  887. const i0 = indexBuffer.element( megaTriangleIndex.mul( 3 ).add( 0 ) );
  888. const i1 = indexBuffer.element( megaTriangleIndex.mul( 3 ).add( 1 ) );
  889. const i2 = indexBuffer.element( megaTriangleIndex.mul( 3 ).add( 2 ) );
  890. const matrixWorld = instanceWorldRead.element( instId );
  891. const w0 = matrixWorld.mul( vertexBuffer.element( i0 ) ).xyz;
  892. const w1 = matrixWorld.mul( vertexBuffer.element( i1 ) ).xyz;
  893. const w2 = matrixWorld.mul( vertexBuffer.element( i2 ) ).xyz;
  894. const t_uv0 = uvBuffer.element( i0 );
  895. const t_uv1 = uvBuffer.element( i1 );
  896. const t_uv2 = uvBuffer.element( i2 );
  897. // Project Vertices to Screen Space
  898. const p0 = projScreenMatrixUniform.mul( vec4( w0, 1.0 ) );
  899. const p1 = projScreenMatrixUniform.mul( vec4( w1, 1.0 ) );
  900. const p2 = projScreenMatrixUniform.mul( vec4( w2, 1.0 ) );
  901. const ndc0 = p0.xyz.div( p0.w );
  902. const ndc1 = p1.xyz.div( p1.w );
  903. const ndc2 = p2.xyz.div( p2.w );
  904. const w = screenSize.x;
  905. const h = screenSize.y;
  906. const s0 = ndc0.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  907. const s1 = ndc1.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  908. const s2 = ndc2.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  909. const p = vec2( screenCoordinate.x, flippedY );
  910. // Compute Barycentrics
  911. const area = edgeFunction( s0, s1, s2 );
  912. const w0b = edgeFunction( s1, s2, p );
  913. const w1b = edgeFunction( s2, s0, p );
  914. const w2b = edgeFunction( s0, s1, p );
  915. // Guard against division by zero for safe execution
  916. const safeArea = area.equal( 0.0 ).select( 1.0, area );
  917. const b0 = w0b.div( safeArea );
  918. const b1 = w1b.div( safeArea );
  919. const b2 = w2b.div( safeArea );
  920. // Perspective correct interpolation (32-bit floats!)
  921. const z_inv = b0.div( p0.w ).add( b1.div( p1.w ) ).add( b2.div( p2.w ) );
  922. const safeZInv = z_inv.equal( 0.0 ).select( 1.0, z_inv );
  923. const b0_p = b0.div( p0.w ).div( safeZInv );
  924. const b1_p = b1.div( p1.w ).div( safeZInv );
  925. const b2_p = b2.div( p2.w ).div( safeZInv );
  926. const uv_interp = t_uv0.mul( b0_p ).add( t_uv1.mul( b1_p ) ).add( t_uv2.mul( b2_p ) );
  927. const n0 = matrixWorld.mul( vec4( normalBuffer.element( i0 ).xyz, 0.0 ) ).xyz;
  928. const n1 = matrixWorld.mul( vec4( normalBuffer.element( i1 ).xyz, 0.0 ) ).xyz;
  929. const n2 = matrixWorld.mul( vec4( normalBuffer.element( i2 ).xyz, 0.0 ) ).xyz;
  930. const normal_interp = normalize( n0.mul( b0_p ).add( n1.mul( b1_p ) ).add( n2.mul( b2_p ) ) );
  931. const worldPosition = w0.mul( b0_p ).add( w1.mul( b1_p ) ).add( w2.mul( b2_p ) );
  932. const positionViewHelmet = cameraViewMatrix.mul( vec4( worldPosition, 1.0 ) ).xyz;
  933. const positionViewDirectionHelmet = positionViewHelmet.negate().normalize();
  934. // Compute screen-space derivatives analytically (neighboring pixels can
  935. // belong to different triangles, so hardware derivatives are unusable)
  936. const dw0_dx = s2.y.sub( s1.y );
  937. const dw1_dx = s0.y.sub( s2.y );
  938. const dw2_dx = s1.y.sub( s0.y );
  939. const dw0_dy = s1.x.sub( s2.x );
  940. const dw1_dy = s2.x.sub( s0.x );
  941. const dw2_dy = s0.x.sub( s1.x );
  942. const q0 = float( 1.0 ).div( p0.w );
  943. const q1 = float( 1.0 ).div( p1.w );
  944. const q2 = float( 1.0 ).div( p2.w );
  945. const sum_w_q = w0b.mul( q0 ).add( w1b.mul( q1 ) ).add( w2b.mul( q2 ) );
  946. const safe_sum_w_q = sum_w_q.equal( 0.0 ).select( 1.0, sum_w_q );
  947. const dUvDx = (
  948. dw0_dx.mul( q0 ).mul( t_uv0.sub( uv_interp ) )
  949. .add( dw1_dx.mul( q1 ).mul( t_uv1.sub( uv_interp ) ) )
  950. .add( dw2_dx.mul( q2 ).mul( t_uv2.sub( uv_interp ) ) )
  951. ).div( safe_sum_w_q );
  952. const dUvDy = (
  953. dw0_dy.mul( q0 ).mul( t_uv0.sub( uv_interp ) )
  954. .add( dw1_dy.mul( q1 ).mul( t_uv1.sub( uv_interp ) ) )
  955. .add( dw2_dy.mul( q2 ).mul( t_uv2.sub( uv_interp ) ) )
  956. ).div( safe_sum_w_q );
  957. // Sample with explicit gradients
  958. const sampleMap = ( map ) => texture( map, uv_interp ).grad( dUvDx, dUvDy );
  959. // Specular antialiasing (Tokuyoshi & Kaplanyan) — widen roughness by the
  960. // normal's screen-space variance so sub-pixel geometry does not alias
  961. // into fireflies. The derivatives are analytic, like the UV gradients.
  962. const dNdx = (
  963. dw0_dx.mul( q0 ).mul( n0.sub( normal_interp ) )
  964. .add( dw1_dx.mul( q1 ).mul( n1.sub( normal_interp ) ) )
  965. .add( dw2_dx.mul( q2 ).mul( n2.sub( normal_interp ) ) )
  966. ).div( safe_sum_w_q );
  967. const dNdy = (
  968. dw0_dy.mul( q0 ).mul( n0.sub( normal_interp ) )
  969. .add( dw1_dy.mul( q1 ).mul( n1.sub( normal_interp ) ) )
  970. .add( dw2_dy.mul( q2 ).mul( n2.sub( normal_interp ) ) )
  971. ).div( safe_sum_w_q );
  972. const kernelRoughness = min( dNdx.dot( dNdx ).add( dNdy.dot( dNdy ) ).mul( SPECULAR_AA_VARIANCE ), SPECULAR_AA_MAX );
  973. // Discard pixels the rasterizer did not cover so the background shows through
  974. const coveredColor = ( colorNode ) => Fn( () => {
  975. If( packedTri.shiftRight( TRIANGLE_INDEX_BITS ).equal( 0 ), () => {
  976. Discard();
  977. } );
  978. return colorNode;
  979. } )();
  980. // Output depth so the HW mesh can depth test against the SW result
  981. const resolveDepth = Fn( () => {
  982. // Depth lives in the high 17 bits of the packed value
  983. const depthTri = packedTri.shiftRight( TRIANGLE_INDEX_BITS );
  984. // Reconstruct NDC Z from non-linear depth (fourth-root distribution)
  985. const y = float( depthTri ).div( DEPTH_TRI_MAX );
  986. const y2 = y.mul( y );
  987. const v = y2.mul( y2 ); // raise to the fourth power (y^4) to get original v
  988. return float( 1.0 ).sub( v );
  989. } )();
  990. const fullscreenVertex = vec4( positionGeometry.xy, 0.0, 1.0 );
  991. // Shaded: feed the reconstructed surface into the standard material pipeline
  992. const resolveShadedMaterial = new THREE.MeshStandardNodeMaterial();
  993. resolveShadedMaterial.contextNode = context( {
  994. positionView: positionViewHelmet,
  995. positionViewDirection: positionViewDirectionHelmet
  996. } );
  997. resolveShadedMaterial.vertexNode = fullscreenVertex;
  998. resolveShadedMaterial.depthNode = resolveDepth;
  999. resolveShadedMaterial.colorNode = coveredColor( sampleMap( sourceMaterial.map ) );
  1000. resolveShadedMaterial.normalNode = applyNormalMap(
  1001. normal_interp,
  1002. computeTangent( w0, w1, w2, t_uv0, t_uv1, t_uv2, normal_interp ),
  1003. sampleMap( sourceMaterial.normalMap )
  1004. ).transformDirection( cameraViewMatrix );
  1005. const metalRough = sampleMap( sourceMaterial.roughnessMap ); // glTF packs roughness (g) and metalness (b) in one texture
  1006. resolveShadedMaterial.roughnessNode = sqrt( metalRough.g.mul( metalRough.g ).add( kernelRoughness ) );
  1007. resolveShadedMaterial.metalnessNode = metalRough.b;
  1008. resolveShadedMaterial.aoNode = sampleMap( sourceMaterial.aoMap ).r;
  1009. resolveShadedMaterial.emissiveNode = sampleMap( sourceMaterial.emissiveMap ).rgb;
  1010. // Meshlet debug: flat colors per cluster
  1011. const resolveDebugMaterial = new THREE.NodeMaterial();
  1012. resolveDebugMaterial.vertexNode = fullscreenVertex;
  1013. resolveDebugMaterial.depthNode = resolveDepth;
  1014. resolveDebugMaterial.fragmentNode = coveredColor( hashColor( meshletIdBuffer.element( megaTriangleIndex ).add( instId.mul( 1000 ) ) ) );
  1015. // Vis material: unlit visualization of channels
  1016. const resolveVisMaterial = new THREE.NodeMaterial();
  1017. resolveVisMaterial.contextNode = context( {
  1018. positionView: positionViewHelmet,
  1019. positionViewDirection: positionViewDirectionHelmet
  1020. } );
  1021. resolveVisMaterial.vertexNode = fullscreenVertex;
  1022. resolveVisMaterial.depthNode = resolveDepth;
  1023. resolveVisMaterial.fragmentNode = coveredColor( getVisColor(
  1024. outputModeUniform,
  1025. normal_interp,
  1026. applyNormalMap( normal_interp, computeTangent( w0, w1, w2, t_uv0, t_uv1, t_uv2, normal_interp ), sampleMap( sourceMaterial.normalMap ) ),
  1027. uv_interp,
  1028. metalRough.g,
  1029. metalRough.b,
  1030. sampleMap( sourceMaterial.aoMap ).r,
  1031. sampleMap( sourceMaterial.emissiveMap ).rgb
  1032. ) );
  1033. resolveMesh = new THREE.Mesh( resolveGeometry, resolveShadedMaterial );
  1034. resolveMesh.userData.shadedMaterial = resolveShadedMaterial;
  1035. resolveMesh.userData.debugMaterial = resolveDebugMaterial;
  1036. resolveMesh.userData.visMaterial = resolveVisMaterial;
  1037. resolveMesh.frustumCulled = false;
  1038. resolveMesh.renderOrder = 1;
  1039. scene.add( resolveMesh );
  1040. // Presents the scene to the canvas (tone mapping applies here)
  1041. blitTexNode = texture( sceneRT.texture );
  1042. const blitMaterial = new THREE.NodeMaterial();
  1043. blitMaterial.colorNode = blitTexNode;
  1044. blitQuad = new THREE.QuadMesh( blitMaterial );
  1045. }
  1046. updateMode();
  1047. window.addEventListener( 'resize', onWindowResize );
  1048. }
  1049. function updateMode() {
  1050. const outputVal = options.Output;
  1051. const outputModes = {
  1052. 'Default': 0,
  1053. 'Geometry Normal': 1,
  1054. 'Normal Map': 2,
  1055. 'UV': 3,
  1056. 'Roughness': 4,
  1057. 'Metalness': 5,
  1058. 'AO': 6,
  1059. 'Emissive': 7
  1060. };
  1061. if ( outputVal === 'Meshlet Debug' ) {
  1062. resolveMesh.material = resolveMesh.userData.debugMaterial;
  1063. hwMesh.material = hwMesh.userData.debugMaterial;
  1064. } else if ( outputVal !== 'Default' ) {
  1065. outputModeUniform.value = outputModes[ outputVal ];
  1066. resolveMesh.material = resolveMesh.userData.visMaterial;
  1067. hwMesh.material = hwMesh.userData.visMaterial;
  1068. } else {
  1069. outputModeUniform.value = 0;
  1070. resolveMesh.material = resolveMesh.userData.shadedMaterial;
  1071. hwMesh.material = hwMesh.userData.shadedMaterial;
  1072. }
  1073. }
  1074. function createScreenBuffers() {
  1075. const size = new THREE.Vector2();
  1076. renderer.getDrawingBufferSize( size );
  1077. const newMaxPixels = size.x * size.y;
  1078. if ( newMaxPixels === maxPixels ) return;
  1079. maxPixels = newMaxPixels;
  1080. if ( screenTriAttr ) screenTriAttr.dispose();
  1081. if ( screenInstAttr ) screenInstAttr.dispose();
  1082. if ( hzbLevelTable === undefined ) {
  1083. hzbLevelTable = uniformArray( Array.from( { length: MAX_HZB_LEVELS }, () => new THREE.Vector4() ), 'vec4' );
  1084. hzbLevelCountUniform = uniform( 0.0 );
  1085. }
  1086. const screenTriData = new Uint32Array( maxPixels );
  1087. screenTriAttr = new THREE.StorageBufferAttribute( screenTriData, 1 );
  1088. const screenInstData = new Uint32Array( maxPixels );
  1089. screenInstAttr = new THREE.StorageBufferAttribute( screenInstData, 1 );
  1090. if ( screenTriAtomic === undefined ) {
  1091. screenTriAtomic = storage( screenTriAttr, 'uint', maxPixels ).toAtomic();
  1092. screenTriRead = storage( screenTriAttr, 'uint', maxPixels ).toReadOnly();
  1093. screenInstAtomic = storage( screenInstAttr, 'uint', maxPixels ).toAtomic();
  1094. screenInstRead = storage( screenInstAttr, 'uint', maxPixels ).toReadOnly();
  1095. } else {
  1096. screenTriAtomic.value = screenTriAttr;
  1097. screenTriAtomic.bufferCount = maxPixels;
  1098. screenTriRead.value = screenTriAttr;
  1099. screenTriRead.bufferCount = maxPixels;
  1100. screenInstAtomic.value = screenInstAttr;
  1101. screenInstAtomic.bufferCount = maxPixels;
  1102. screenInstRead.value = screenInstAttr;
  1103. screenInstRead.bufferCount = maxPixels;
  1104. computeClear.count = maxPixels;
  1105. computeClear.dispose();
  1106. computeRasterize.dispose();
  1107. computeFrustum.dispose();
  1108. computeDispatch.dispose();
  1109. computeHWArgs.dispose();
  1110. resolveMesh.userData.shadedMaterial.dispose();
  1111. resolveMesh.userData.debugMaterial.dispose();
  1112. resolveMesh.userData.visMaterial.dispose();
  1113. hwMesh.userData.shadedMaterial.dispose();
  1114. hwMesh.userData.debugMaterial.dispose();
  1115. hwMesh.userData.visMaterial.dispose();
  1116. }
  1117. // Scene render target (also provides the depth for the pyramid)
  1118. if ( sceneRT ) {
  1119. sceneRT.dispose();
  1120. }
  1121. sceneRT = new THREE.RenderTarget( size.x, size.y, { type: THREE.HalfFloatType } );
  1122. sceneRT.depthTexture = new THREE.DepthTexture( size.x, size.y );
  1123. sceneRT.depthTexture.type = THREE.FloatType;
  1124. if ( blitTexNode ) {
  1125. blitTexNode.value = sceneRT.texture;
  1126. depthSourceTexNode.value = sceneRT.depthTexture;
  1127. }
  1128. // HZB pyramid — all mip levels packed into one storage buffer,
  1129. // level 0 at half resolution, each level the max (farthest) of 2x2 below
  1130. let levelWidth = Math.ceil( size.x / 2 );
  1131. let levelHeight = Math.ceil( size.y / 2 );
  1132. let totalTexels = 0;
  1133. hzbLevelCount = 0;
  1134. while ( hzbLevelCount < MAX_HZB_LEVELS ) {
  1135. hzbLevelTable.array[ hzbLevelCount ].set( totalTexels, levelWidth, levelHeight, 0 );
  1136. totalTexels += levelWidth * levelHeight;
  1137. hzbLevelCount ++;
  1138. if ( levelWidth === 1 && levelHeight === 1 ) break;
  1139. levelWidth = Math.max( 1, Math.ceil( levelWidth / 2 ) );
  1140. levelHeight = Math.max( 1, Math.ceil( levelHeight / 2 ) );
  1141. }
  1142. hzbLevelCountUniform.value = hzbLevelCount;
  1143. const hzbData = new Float32Array( totalTexels ).fill( 1 ); // far plane — occludes nothing
  1144. const hzbAttr = new THREE.StorageBufferAttribute( hzbData, 1 );
  1145. if ( hzbBuffer === undefined ) {
  1146. hzbBuffer = storage( hzbAttr, 'float', totalTexels );
  1147. hzbRead = storage( hzbAttr, 'float', totalTexels ).toReadOnly();
  1148. } else {
  1149. hzbBuffer.value = hzbAttr;
  1150. hzbBuffer.bufferCount = totalTexels;
  1151. hzbRead.value = hzbAttr;
  1152. hzbRead.bufferCount = totalTexels;
  1153. }
  1154. for ( let k = 0; k < hzbKernels.length; k ++ ) {
  1155. const info = hzbLevelTable.array[ Math.min( k, hzbLevelCount - 1 ) ];
  1156. hzbKernels[ k ].count = info.y * info.z;
  1157. hzbKernels[ k ].dispose();
  1158. }
  1159. }
  1160. function onWindowResize() {
  1161. camera.aspect = window.innerWidth / window.innerHeight;
  1162. camera.updateProjectionMatrix();
  1163. renderer.setSize( window.innerWidth, window.innerHeight );
  1164. createScreenBuffers();
  1165. }
  1166. const frustum = new THREE.Frustum();
  1167. const projScreenMatrix = new THREE.Matrix4();
  1168. const prevProjScreen = new THREE.Matrix4();
  1169. const cameraInverse = new THREE.Matrix4();
  1170. const prevCameraPos = new THREE.Vector3();
  1171. let prevValid = false;
  1172. function animate() {
  1173. if ( resolveMesh === undefined ) return; // still loading
  1174. controls.update();
  1175. camera.updateMatrixWorld();
  1176. cameraInverse.copy( camera.matrixWorld ).invert();
  1177. projScreenMatrix.multiplyMatrices( camera.projectionMatrix, cameraInverse );
  1178. // Seed the previous frame state on the first frame
  1179. if ( prevValid === false ) {
  1180. prevProjScreen.copy( projScreenMatrix );
  1181. prevCameraPos.copy( camera.position );
  1182. prevValid = true;
  1183. }
  1184. // Last frame's matrices drive the occlusion test
  1185. prevProjScreenUniform.value.copy( prevProjScreen );
  1186. prevCameraPosUniform.value.copy( prevCameraPos );
  1187. prevProjScreen.copy( projScreenMatrix );
  1188. prevCameraPos.copy( camera.position );
  1189. occlusionUniform.value = options.Occlusion ? 1 : 0;
  1190. frustum.setFromProjectionMatrix( projScreenMatrix );
  1191. // Update GPU uniforms
  1192. projScreenMatrixUniform.value.copy( projScreenMatrix );
  1193. cameraPos.value.copy( camera.position );
  1194. cotHalfFovUniform.value = camera.projectionMatrix.elements[ 5 ];
  1195. // Pack frustum planes into the uniform array
  1196. const planes = frustum.planes;
  1197. const planesArray = frustumPlanesUniform.array;
  1198. for ( let i = 0; i < 6; i ++ ) {
  1199. const p = planes[ i ];
  1200. planesArray[ i ].set( p.normal.x, p.normal.y, p.normal.z, p.constant );
  1201. }
  1202. // Compute & Render
  1203. renderer.compute( computeClear );
  1204. renderer.compute( computeFrustum );
  1205. renderer.compute( computeDispatch );
  1206. renderer.compute( computeRasterize );
  1207. renderer.compute( computeHWArgs );
  1208. const rasterMode = options.Rasterizer;
  1209. resolveMesh.visible = ( rasterMode === 'SW Only' || rasterMode === 'Both' );
  1210. hwMesh.visible = ( rasterMode === 'HW Only' || rasterMode === 'Both' );
  1211. // Current frame in linear HDR
  1212. renderer.setRenderTarget( sceneRT );
  1213. renderer.render( scene, camera );
  1214. // Build the depth pyramid for next frame's occlusion culling
  1215. for ( let k = 0; k < hzbLevelCount; k ++ ) {
  1216. renderer.compute( hzbKernels[ k ] );
  1217. }
  1218. // Present (tone mapping + output color space apply on the canvas)
  1219. renderer.setRenderTarget( null );
  1220. blitQuad.render( renderer );
  1221. }
  1222. </script>
  1223. </body>
  1224. </html>
粤ICP备19079148号