TiledDeferredLighting.bsl 22 KB

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