TiledDeferredLighting.bsl 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. #include "$ENGINE$\GBuffer.bslinc"
  2. #include "$ENGINE$\PerCameraData.bslinc"
  3. #define USE_COMPUTE_INDICES
  4. #include "$ENGINE$\LightingCommon.bslinc"
  5. #include "$ENGINE$\ReflectionCubemapCommon.bslinc"
  6. #include "$ENGINE$\ReflectionCubemapSampling.bslinc"
  7. Parameters =
  8. {
  9. Sampler2D gGBufferASamp : alias("gGBufferATex");
  10. Sampler2D gGBufferBSamp : alias("gGBufferBTex");
  11. Sampler2D gGBufferCSamp : alias("gGBufferCTex");
  12. Sampler2D gDepthBufferSamp : alias("gDepthBufferTex");
  13. Texture2D gGBufferATex : auto("GBufferA");
  14. Texture2D gGBufferBTex : auto("GBufferB");
  15. Texture2D gGBufferCTex : auto("GBufferC");
  16. Texture2D gDepthBufferTex : auto("GBufferDepth");
  17. };
  18. Blocks =
  19. {
  20. Block PerCamera : auto("PerCamera");
  21. };
  22. Technique
  23. : inherits("GBuffer")
  24. : inherits("PerCameraData")
  25. : inherits("LightingCommon")
  26. : inherits("ReflectionCubemapCommon")
  27. : inherits("ReflectionCubemapSampling") =
  28. {
  29. Language = "HLSL11";
  30. Pass =
  31. {
  32. Compute =
  33. {
  34. SamplerState gGBufferASamp : register(s0);
  35. SamplerState gGBufferBSamp : register(s1);
  36. SamplerState gGBufferCSamp : register(s2);
  37. SamplerState gDepthBufferSamp : register(s3);
  38. #if MSAA_COUNT > 1
  39. Texture2DMS<float4, MSAA_COUNT> gGBufferATex : register(t0);
  40. Texture2DMS<float4, MSAA_COUNT> gGBufferBTex : register(t1);
  41. Texture2DMS<float2, MSAA_COUNT> gGBufferCTex : register(t2);
  42. Texture2DMS<float4, MSAA_COUNT> gDepthBufferTex : register(t3);
  43. #else
  44. Texture2D gGBufferATex : register(t0);
  45. Texture2D gGBufferBTex : register(t1);
  46. Texture2D gGBufferCTex : register(t2);
  47. Texture2D gDepthBufferTex : register(t3);
  48. #endif
  49. SurfaceData decodeGBuffer(float4 GBufferAData, float4 GBufferBData, float2 GBufferCData, float deviceZ)
  50. {
  51. SurfaceData output;
  52. output.albedo.xyz = GBufferAData.xyz;
  53. output.albedo.w = 1.0f;
  54. output.worldNormal = GBufferBData * float4(2, 2, 2, 1) - float4(1, 1, 1, 0);
  55. output.worldNormal.xyz = normalize(output.worldNormal.xyz);
  56. output.depth = convertFromDeviceZ(deviceZ);
  57. output.roughness = GBufferCData.x;
  58. output.metalness = GBufferCData.y;
  59. return output;
  60. }
  61. cbuffer Params : register(b0)
  62. {
  63. // Offsets at which specific light types begin in gLights buffer
  64. // Assumed directional lights start at 0
  65. // x - offset to point lights, y - offset to spot lights, z - total number of lights
  66. uint3 gLightOffsets;
  67. uint2 gFramebufferSize;
  68. }
  69. #if MSAA_COUNT > 1
  70. RWBuffer<float4> gOutput : register(u0);
  71. uint getLinearAddress(uint2 coord, uint sampleIndex)
  72. {
  73. return (coord.y * gFramebufferSize.x + coord.x) * MSAA_COUNT + sampleIndex;
  74. }
  75. void writeBufferSample(uint2 coord, uint sampleIndex, float4 color)
  76. {
  77. uint idx = getLinearAddress(coord, sampleIndex);
  78. gOutput[idx] = color;
  79. }
  80. bool needsPerSampleShading(SurfaceData samples[MSAA_COUNT])
  81. {
  82. float3 albedo = samples[0].albedo.xyz;
  83. float3 normal = samples[0].worldNormal.xyz;
  84. float depth = samples[0].depth;
  85. [unroll]
  86. for(int i = 1; i < MSAA_COUNT; i++)
  87. {
  88. float3 otherAlbedo = samples[i].albedo.xyz;
  89. float3 otherNormal = samples[i].worldNormal.xyz;
  90. float otherDepth = samples[i].depth;
  91. [branch]
  92. if(abs(depth - otherDepth) > 0.1f || abs(dot(abs(normal - otherNormal), float3(1, 1, 1))) > 0.1f || abs(dot(albedo - otherAlbedo, float3(1, 1, 1))) > 0.1f)
  93. {
  94. return true;
  95. }
  96. }
  97. return false;
  98. }
  99. SurfaceData getGBufferData(uint2 pixelPos, uint sampleIndex)
  100. {
  101. float4 GBufferAData = gGBufferATex.Load(pixelPos, sampleIndex);
  102. float4 GBufferBData = gGBufferBTex.Load(pixelPos, sampleIndex);
  103. float2 GBufferCData = gGBufferCTex.Load(pixelPos, sampleIndex).rg;
  104. float deviceZ = gDepthBufferTex.Load(pixelPos, sampleIndex).r;
  105. return decodeGBuffer(GBufferAData, GBufferBData, GBufferCData, deviceZ);
  106. }
  107. #else
  108. RWTexture2D<float4> gOutput : register(u0);
  109. SurfaceData getGBufferData(uint2 pixelPos)
  110. {
  111. float4 GBufferAData = gGBufferATex.Load(int3(pixelPos, 0));
  112. float4 GBufferBData = gGBufferBTex.Load(int3(pixelPos, 0));
  113. float2 GBufferCData = gGBufferCTex.Load(int3(pixelPos, 0)).rg;
  114. float deviceZ = gDepthBufferTex.Load(int3(pixelPos, 0)).r;
  115. return decodeGBuffer(GBufferAData, GBufferBData, GBufferCData, deviceZ);
  116. }
  117. #endif
  118. groupshared uint sTileMinZ;
  119. groupshared uint sTileMaxZ;
  120. groupshared uint sNumLightsPerType[2];
  121. groupshared uint sTotalNumLights;
  122. float4 getLighting(float2 clipSpacePos, SurfaceData surfaceData)
  123. {
  124. // x, y are now in clip space, z, w are in view space
  125. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  126. // z, w eliminated (since they are already in view space)
  127. // Note: Multiply by depth should be avoided if using ortographic projection
  128. float4 mixedSpacePos = float4(clipSpacePos * -surfaceData.depth, surfaceData.depth, 1);
  129. float4 worldPosition4D = mul(gMatScreenToWorld, mixedSpacePos);
  130. float3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  131. uint4 lightOffsets;
  132. lightOffsets.x = gLightOffsets[0];
  133. lightOffsets.y = 0;
  134. lightOffsets.z = sNumLightsPerType[0];
  135. lightOffsets.w = sTotalNumLights;
  136. float3 V = normalize(gViewOrigin - worldPosition);
  137. float3 N = surfaceData.worldNormal.xyz;
  138. float3 R = 2 * dot(V, N) * N - V;
  139. float3 specR = getSpecularDominantDir(N, R, surfaceData.roughness);
  140. float4 directLighting = getDirectLighting(worldPosition, V, specR, surfaceData, lightOffsets);
  141. float3 indirectDiffuse = getSkyIndirectDiffuse(surfaceData.worldNormal) * surfaceData.albedo;
  142. float3 imageBasedSpecular = getImageBasedSpecular(worldPosition, V, specR, surfaceData);
  143. float4 totalLighting = directLighting;
  144. totalLighting.rgb += indirectDiffuse;
  145. totalLighting.rgb += imageBasedSpecular;
  146. return totalLighting;
  147. }
  148. [numthreads(TILE_SIZE, TILE_SIZE, 1)]
  149. void main(
  150. uint3 groupId : SV_GroupID,
  151. uint3 groupThreadId : SV_GroupThreadID,
  152. uint3 dispatchThreadId : SV_DispatchThreadID)
  153. {
  154. uint threadIndex = groupThreadId.y * TILE_SIZE + groupThreadId.x;
  155. uint2 pixelPos = dispatchThreadId.xy + gViewportRectangle.xy;
  156. // Get data for all samples, and determine per-pixel minimum and maximum depth values
  157. SurfaceData surfaceData[MSAA_COUNT];
  158. uint sampleMinZ = 0x7F7FFFFF;
  159. uint sampleMaxZ = 0;
  160. #if MSAA_COUNT > 1
  161. [unroll]
  162. for(uint i = 0; i < MSAA_COUNT; ++i)
  163. {
  164. surfaceData[i] = getGBufferData(pixelPos, i);
  165. sampleMinZ = min(sampleMinZ, asuint(-surfaceData[i].depth));
  166. sampleMaxZ = max(sampleMaxZ, asuint(-surfaceData[i].depth));
  167. }
  168. #else
  169. surfaceData[0] = getGBufferData(pixelPos);
  170. sampleMinZ = asuint(-surfaceData[0].depth);
  171. sampleMaxZ = asuint(-surfaceData[0].depth);
  172. #endif
  173. // Set initial values
  174. if(threadIndex == 0)
  175. {
  176. sTileMinZ = 0x7F7FFFFF;
  177. sTileMaxZ = 0;
  178. sNumLightsPerType[0] = 0;
  179. sNumLightsPerType[1] = 0;
  180. sTotalNumLights = 0;
  181. }
  182. GroupMemoryBarrierWithGroupSync();
  183. // Determine minimum and maximum depth values for a tile
  184. InterlockedMin(sTileMinZ, sampleMinZ);
  185. InterlockedMax(sTileMaxZ, sampleMaxZ);
  186. GroupMemoryBarrierWithGroupSync();
  187. float minTileZ = asfloat(sTileMinZ);
  188. float maxTileZ = asfloat(sTileMaxZ);
  189. // Create a frustum for the current tile
  190. // First determine a scale of the tile compared to the viewport
  191. float2 tileScale = gViewportRectangle.zw * rcp(float2(TILE_SIZE, TILE_SIZE));
  192. // Now we need to use that scale to scale down the frustum.
  193. // Assume a projection matrix:
  194. // A, 0, C, 0
  195. // 0, B, D, 0
  196. // 0, 0, Q, QN
  197. // 0, 0, -1, 0
  198. //
  199. // Where A is = 2*n / (r - l)
  200. // and C = (r + l) / (r - l)
  201. //
  202. // Q & QN are used for Z value which we don't need to scale. B & D are equivalent for the
  203. // Y value, we'll only consider the X values (A & C) from now on.
  204. //
  205. // Both and A and C are inversely proportional to the size of the frustum (r - l). Larger scale mean that
  206. // tiles are that much smaller than the viewport. This means as our scale increases, (r - l) decreases,
  207. // which means A & C as a whole increase. Therefore:
  208. // A' = A * tileScale.x
  209. // C' = C * tileScale.x
  210. // Aside from scaling, we also need to offset the frustum to the center of the tile.
  211. // For this we calculate the bias value which we add to the C & D factors (which control
  212. // the offset in the projection matrix).
  213. float2 tileBias = tileScale - 1 - groupId.xy * 2;
  214. // This will yield a bias ranging from [-(tileScale - 1), tileScale - 1]. Every second bias is skipped as
  215. // corresponds to a point in-between two tiles, overlapping existing frustums.
  216. float At = gMatProj[0][0] * tileScale.x;
  217. float Ctt = gMatProj[0][2] * tileScale.x - tileBias.x;
  218. float Bt = gMatProj[1][1] * tileScale.y;
  219. float Dtt = gMatProj[1][2] * tileScale.y + tileBias.y;
  220. // Extract left/right/top/bottom frustum planes from scaled projection matrix
  221. // Note: Do this on the CPU? Since they're shared among all entries in a tile. Plus they don't change across frames.
  222. float4 frustumPlanes[6];
  223. frustumPlanes[0] = float4(At, 0.0f, gMatProj[3][2] + Ctt, 0.0f);
  224. frustumPlanes[1] = float4(-At, 0.0f, gMatProj[3][2] - Ctt, 0.0f);
  225. frustumPlanes[2] = float4(0.0f, -Bt, gMatProj[3][2] - Dtt, 0.0f);
  226. frustumPlanes[3] = float4(0.0f, Bt, gMatProj[3][2] + Dtt, 0.0f);
  227. // Normalize
  228. [unroll]
  229. for (uint i = 0; i < 4; ++i)
  230. frustumPlanes[i] *= rcp(length(frustumPlanes[i].xyz));
  231. // Generate near/far frustum planes
  232. // Note: d gets negated in plane equation, this is why its in opposite direction than it intuitively should be
  233. frustumPlanes[4] = float4(0.0f, 0.0f, -1.0f, -minTileZ);
  234. frustumPlanes[5] = float4(0.0f, 0.0f, 1.0f, maxTileZ);
  235. // Find radial & spot lights overlapping the tile
  236. for(uint type = 0; type < 2; type++)
  237. {
  238. uint lightOffset = threadIndex + gLightOffsets[type];
  239. uint lightsEnd = gLightOffsets[type + 1];
  240. for (uint i = lightOffset; i < lightsEnd && i < MAX_LIGHTS; i += TILE_SIZE)
  241. {
  242. float4 lightPosition = mul(gMatView, float4(gLights[i].position, 1.0f));
  243. float lightRadius = gLights[i].attRadius;
  244. // Note: The cull method can have false positives. In case of large light bounds and small tiles, it
  245. // can end up being quite a lot. Consider adding an extra heuristic to check a separating plane.
  246. bool lightInTile = true;
  247. // First check side planes as this will cull majority of the lights
  248. [unroll]
  249. for (uint j = 0; j < 4; ++j)
  250. {
  251. float dist = dot(frustumPlanes[j], lightPosition);
  252. lightInTile = lightInTile && (dist >= -lightRadius);
  253. }
  254. // Make sure to do an actual branch, since it's quite likely an entire warp will have the same value
  255. [branch]
  256. if (lightInTile)
  257. {
  258. bool inDepthRange = true;
  259. // Check near/far planes
  260. [unroll]
  261. for (uint j = 4; j < 6; ++j)
  262. {
  263. float dist = dot(frustumPlanes[j], lightPosition);
  264. inDepthRange = inDepthRange && (dist >= -lightRadius);
  265. }
  266. // In tile, add to branch
  267. [branch]
  268. if (inDepthRange)
  269. {
  270. InterlockedAdd(sNumLightsPerType[type], 1U);
  271. uint idx;
  272. InterlockedAdd(sTotalNumLights, 1U, idx);
  273. gLightIndices[idx] = i;
  274. }
  275. }
  276. }
  277. }
  278. GroupMemoryBarrierWithGroupSync();
  279. // Generate world position
  280. float2 screenUv = ((float2)(gViewportRectangle.xy + pixelPos) + 0.5f) / (float2)gViewportRectangle.zw;
  281. float2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  282. uint2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  283. // Ignore pixels out of valid range
  284. if (all(dispatchThreadId.xy < viewportMax))
  285. {
  286. #if MSAA_COUNT > 1
  287. float4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  288. writeBufferSample(pixelPos, 0, lighting);
  289. bool doPerSampleShading = needsPerSampleShading(surfaceData);
  290. if(doPerSampleShading)
  291. {
  292. [unroll]
  293. for(uint i = 1; i < MSAA_COUNT; ++i)
  294. {
  295. lighting = getLighting(clipSpacePos.xy, surfaceData[i]);
  296. writeBufferSample(pixelPos, i, lighting);
  297. }
  298. }
  299. else // Splat same information to all samples
  300. {
  301. [unroll]
  302. for(uint i = 1; i < MSAA_COUNT; ++i)
  303. writeBufferSample(pixelPos, i, lighting);
  304. }
  305. #else
  306. float4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  307. gOutput[pixelPos] = lighting;
  308. #endif
  309. }
  310. }
  311. };
  312. };
  313. };
  314. Technique
  315. : inherits("GBuffer")
  316. : inherits("PerCameraData")
  317. : inherits("LightingCommon") =
  318. {
  319. Language = "GLSL";
  320. Pass =
  321. {
  322. Compute =
  323. {
  324. // Arbitrary limit, increase if needed
  325. #define MAX_LIGHTS 512
  326. layout (local_size_x = TILE_SIZE, local_size_y = TILE_SIZE) in;
  327. #if MSAA_COUNT > 1
  328. layout(binding = 1) uniform sampler2DMS gGBufferATex;
  329. layout(binding = 2) uniform sampler2DMS gGBufferBTex;
  330. layout(binding = 3) uniform sampler2DMS gGBufferCTex;
  331. layout(binding = 4) uniform sampler2DMS gDepthBufferTex;
  332. #else
  333. layout(binding = 1) uniform sampler2D gGBufferATex;
  334. layout(binding = 2) uniform sampler2D gGBufferBTex;
  335. layout(binding = 3) uniform sampler2D gGBufferCTex;
  336. layout(binding = 4) uniform sampler2D gDepthBufferTex;
  337. #endif
  338. SurfaceData decodeGBuffer(vec4 GBufferAData, vec4 GBufferBData, vec2 GBufferCData, float deviceZ)
  339. {
  340. SurfaceData surfaceData;
  341. surfaceData.albedo.xyz = GBufferAData.xyz;
  342. surfaceData.albedo.w = 1.0f;
  343. surfaceData.worldNormal = GBufferBData * vec4(2, 2, 2, 1) - vec4(1, 1, 1, 0);
  344. surfaceData.worldNormal.xyz = normalize(surfaceData.worldNormal.xyz);
  345. surfaceData.depth = convertFromDeviceZ(deviceZ);
  346. surfaceData.roughness = GBufferCData.x;
  347. surfaceData.metalness = GBufferCData.y;
  348. return surfaceData;
  349. }
  350. #if MSAA_COUNT > 1
  351. layout(binding = 5, rgba16f) uniform image2DMS gOutput;
  352. bool needsPerSampleShading(SurfaceData samples[MSAA_COUNT])
  353. {
  354. vec3 albedo = samples[0].albedo.xyz;
  355. vec3 normal = samples[0].worldNormal.xyz;
  356. float depth = samples[0].depth;
  357. for(int i = 1; i < MSAA_COUNT; i++)
  358. {
  359. vec3 otherAlbedo = samples[i].albedo.xyz;
  360. vec3 otherNormal = samples[i].worldNormal.xyz;
  361. float otherDepth = samples[i].depth;
  362. if(abs(depth - otherDepth) > 0.1f || abs(dot(abs(normal - otherNormal), vec3(1, 1, 1))) > 0.1f || abs(dot(albedo - otherAlbedo, vec3(1, 1, 1))) > 0.1f)
  363. {
  364. return true;
  365. }
  366. }
  367. return false;
  368. }
  369. SurfaceData getGBufferData(ivec2 pixelPos, int sampleIndex)
  370. {
  371. vec4 GBufferAData = texelFetch(gGBufferATex, pixelPos, sampleIndex);
  372. vec4 GBufferBData = texelFetch(gGBufferBTex, pixelPos, sampleIndex);
  373. vec2 GBufferCData = texelFetch(gGBufferCTex, pixelPos, sampleIndex).rg;
  374. float deviceZ = texelFetch(gDepthBufferTex, pixelPos, sampleIndex).r;
  375. return decodeGBuffer(GBufferAData, GBufferBData, GBufferCData, deviceZ);
  376. }
  377. #else
  378. layout(binding = 5, rgba16f) uniform image2D gOutput;
  379. SurfaceData getGBufferData(ivec2 pixelPos)
  380. {
  381. vec4 GBufferAData = texelFetch(gGBufferATex, pixelPos, 0);
  382. vec4 GBufferBData = texelFetch(gGBufferBTex, pixelPos, 0);
  383. vec2 GBufferCData = texelFetch(gGBufferCTex, pixelPos, 0).rg;
  384. float deviceZ = texelFetch(gDepthBufferTex, pixelPos, 0).r;
  385. return decodeGBuffer(GBufferAData, GBufferBData, GBufferCData, deviceZ);
  386. }
  387. #endif
  388. layout(std430, binding = 6) readonly buffer gLights
  389. {
  390. LightData gLightsData[];
  391. };
  392. layout(binding = 7, std140) uniform Params
  393. {
  394. // Offsets at which specific light types begin in gLights buffer
  395. // Assumed directional lights start at 0
  396. // x - offset to point lights, y - offset to spot lights, z - total number of lights
  397. uvec3 gLightOffsets;
  398. uvec2 gFramebufferSize;
  399. };
  400. shared uint sTileMinZ;
  401. shared uint sTileMaxZ;
  402. shared uint sNumLightsPerType[2];
  403. shared uint sTotalNumLights;
  404. shared uint sLightIndices[MAX_LIGHTS];
  405. vec4 getLighting(vec2 clipSpacePos, SurfaceData surfaceData)
  406. {
  407. // x, y are now in clip space, z, w are in view space
  408. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  409. // z, w eliminated (since they are already in view space)
  410. // Note: Multiply by depth should be avoided if using ortographic projection
  411. vec4 mixedSpacePos = vec4(clipSpacePos.xy * -surfaceData.depth, surfaceData.depth, 1);
  412. vec4 worldPosition4D = gMatScreenToWorld * mixedSpacePos;
  413. vec3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  414. float alpha = 0.0f;
  415. vec3 lightAccumulator = vec3(0, 0, 0);
  416. if(surfaceData.worldNormal.w > 0.0f)
  417. {
  418. for(uint i = 0; i < gLightOffsets[0]; ++i)
  419. {
  420. LightData lightData = gLightsData[i];
  421. lightAccumulator += getDirLightContibution(surfaceData, lightData);
  422. }
  423. for (uint i = 0; i < sNumLightsPerType[0]; ++i)
  424. {
  425. uint lightIdx = sLightIndices[i];
  426. LightData lightData = gLightsData[lightIdx];
  427. lightAccumulator += getPointLightContribution(worldPosition, surfaceData, lightData);
  428. }
  429. for(uint i = sNumLightsPerType[0]; i < sTotalNumLights; ++i)
  430. {
  431. uint lightIdx = sLightIndices[i];
  432. LightData lightData = gLightsData[lightIdx];
  433. lightAccumulator += getSpotLightContribution(worldPosition, surfaceData, lightData);
  434. }
  435. lightAccumulator += surfaceData.albedo.rgb * gAmbientFactor;
  436. alpha = 1.0f;
  437. }
  438. vec3 diffuse = surfaceData.albedo.xyz / PI; // TODO - Add better lighting model later
  439. return vec4(lightAccumulator * diffuse, alpha);
  440. }
  441. void main()
  442. {
  443. uint threadIndex = gl_LocalInvocationID.y * TILE_SIZE + gl_LocalInvocationID.x;
  444. ivec2 pixelPos = ivec2(gl_GlobalInvocationID.xy) + gViewportRectangle.xy;
  445. // Get data for all samples, and determine per-pixel minimum and maximum depth values
  446. SurfaceData surfaceData[MSAA_COUNT];
  447. uint sampleMinZ = 0x7F7FFFFF;
  448. uint sampleMaxZ = 0;
  449. #if MSAA_COUNT > 1
  450. for(int i = 0; i < MSAA_COUNT; ++i)
  451. {
  452. surfaceData[i] = getGBufferData(pixelPos, i);
  453. sampleMinZ = min(sampleMinZ, floatBitsToUint(-surfaceData[i].depth));
  454. sampleMaxZ = max(sampleMaxZ, floatBitsToUint(-surfaceData[i].depth));
  455. }
  456. #else
  457. surfaceData[0] = getGBufferData(pixelPos);
  458. sampleMinZ = floatBitsToUint(-surfaceData[0].depth);
  459. sampleMaxZ = floatBitsToUint(-surfaceData[0].depth);
  460. #endif
  461. // Set initial values
  462. if(threadIndex == 0)
  463. {
  464. sTileMinZ = 0x7F7FFFFF;
  465. sTileMaxZ = 0;
  466. sNumLightsPerType[0] = 0;
  467. sNumLightsPerType[1] = 0;
  468. sTotalNumLights = 0;
  469. }
  470. groupMemoryBarrier();
  471. barrier();
  472. atomicMin(sTileMinZ, sampleMinZ);
  473. atomicMax(sTileMaxZ, sampleMaxZ);
  474. groupMemoryBarrier();
  475. barrier();
  476. float minTileZ = uintBitsToFloat(sTileMinZ);
  477. float maxTileZ = uintBitsToFloat(sTileMaxZ);
  478. // Create a frustum for the current tile
  479. // See HLSL version for an explanation of the math
  480. vec2 tileScale = gViewportRectangle.zw / vec2(TILE_SIZE, TILE_SIZE);
  481. vec2 tileBias = tileScale - 1 - gl_WorkGroupID.xy * 2;
  482. float At = gMatProj[0][0] * tileScale.x;
  483. float Ctt = gMatProj[2][0] * tileScale.x - tileBias.x;
  484. float Bt = gMatProj[1][1] * tileScale.y;
  485. float Dtt = gMatProj[2][1] * tileScale.y + tileBias.y;
  486. // Extract left/right/top/bottom frustum planes from scaled projection matrix
  487. vec4 frustumPlanes[6];
  488. frustumPlanes[0] = vec4(At, 0.0f, gMatProj[2][3] + Ctt, 0.0f);
  489. frustumPlanes[1] = vec4(-At, 0.0f, gMatProj[2][3] - Ctt, 0.0f);
  490. frustumPlanes[2] = vec4(0.0f, -Bt, gMatProj[2][3] - Dtt, 0.0f);
  491. frustumPlanes[3] = vec4(0.0f, Bt, gMatProj[2][3] + Dtt, 0.0f);
  492. // Normalize
  493. for (uint i = 0; i < 4; ++i)
  494. frustumPlanes[i] /= length(frustumPlanes[i].xyz);
  495. // Generate near/far frustum planes
  496. frustumPlanes[4] = vec4(0.0f, 0.0f, -1.0f, -minTileZ);
  497. frustumPlanes[5] = vec4(0.0f, 0.0f, 1.0f, maxTileZ);
  498. // Find radial & spot lights overlapping the tile
  499. for(uint type = 0; type < 2; type++)
  500. {
  501. uint lightOffset = threadIndex + gLightOffsets[type];
  502. uint lightsEnd = gLightOffsets[type + 1];
  503. for (uint i = lightOffset; i < lightsEnd && i < MAX_LIGHTS; i += TILE_SIZE)
  504. {
  505. LightData lightData = gLightsData[i];
  506. vec4 lightPosition = gMatView * vec4(lightData.position, 1.0f);
  507. float lightRadius = lightData.attRadius;
  508. bool lightInTile = true;
  509. // First check side planes as this will cull majority of the lights
  510. for (uint j = 0; j < 4; ++j)
  511. {
  512. float dist = dot(frustumPlanes[j], lightPosition);
  513. lightInTile = lightInTile && (dist >= -lightRadius);
  514. }
  515. if (lightInTile)
  516. {
  517. bool inDepthRange = true;
  518. // Check near/far planes
  519. for (uint j = 4; j < 6; ++j)
  520. {
  521. float dist = dot(frustumPlanes[j], lightPosition);
  522. inDepthRange = inDepthRange && (dist >= -lightRadius);
  523. }
  524. // In tile, add to branch
  525. if (inDepthRange)
  526. {
  527. atomicAdd(sNumLightsPerType[type], 1U);
  528. uint idx = atomicAdd(sTotalNumLights, 1U);
  529. sLightIndices[idx] = i;
  530. }
  531. }
  532. }
  533. }
  534. groupMemoryBarrier();
  535. barrier();
  536. vec2 screenUv = (vec2(gViewportRectangle.xy + pixelPos) + 0.5f) / vec2(gViewportRectangle.zw);
  537. vec2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  538. uvec2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  539. // Ignore pixels out of valid range
  540. if (all(lessThan(gl_GlobalInvocationID.xy, viewportMax)))
  541. {
  542. #if MSAA_COUNT > 1
  543. vec4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  544. imageStore(gOutput, pixelPos, 0, lighting);
  545. bool doPerSampleShading = needsPerSampleShading(surfaceData);
  546. if(doPerSampleShading)
  547. {
  548. for(int i = 1; i < MSAA_COUNT; ++i)
  549. {
  550. lighting = getLighting(clipSpacePos.xy, surfaceData[i]);
  551. imageStore(gOutput, pixelPos, i, lighting);
  552. }
  553. }
  554. else // Splat same information to all samples
  555. {
  556. for(int i = 1; i < MSAA_COUNT; ++i)
  557. imageStore(gOutput, pixelPos, i, lighting);
  558. }
  559. #else
  560. vec4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  561. imageStore(gOutput, pixelPos, lighting);
  562. #endif
  563. }
  564. }
  565. };
  566. };
  567. };