TiledDeferredLighting.bsl 23 KB

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