TiledDeferredLighting.bsl 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. #include "$ENGINE$\GBuffer.bslinc"
  2. #include "$ENGINE$\PerCameraData.bslinc"
  3. #include "$ENGINE$\LightingCommon.bslinc"
  4. Parameters =
  5. {
  6. Sampler2D gGBufferASamp : alias("gGBufferATex");
  7. Sampler2D gGBufferBSamp : alias("gGBufferBTex");
  8. Sampler2D gDepthBufferSamp : alias("gDepthBufferTex");
  9. Texture2D gGBufferATex : auto("GBufferA");
  10. Texture2D gGBufferBTex : auto("GBufferB");
  11. Texture2D gDepthBufferTex : auto("GBufferDepth");
  12. };
  13. Blocks =
  14. {
  15. Block PerCamera : auto("PerCamera");
  16. };
  17. Technique
  18. : inherits("GBuffer")
  19. : inherits("PerCameraData")
  20. : inherits("LightingCommon") =
  21. {
  22. Language = "HLSL11";
  23. Pass =
  24. {
  25. Compute =
  26. {
  27. // Arbitrary limit, increase if needed
  28. #define MAX_LIGHTS 512
  29. SamplerState gGBufferASamp : register(s0);
  30. SamplerState gGBufferBSamp : register(s1);
  31. SamplerState gDepthBufferSamp : register(s2);
  32. #if MSAA_COUNT > 1
  33. Texture2DMS<float4, MSAA_COUNT> gGBufferATex : register(t0);
  34. Texture2DMS<float4, MSAA_COUNT> gGBufferBTex : register(t1);
  35. Texture2DMS<float4, MSAA_COUNT> gDepthBufferTex : register(t2);
  36. #else
  37. Texture2D gGBufferATex : register(t0);
  38. Texture2D gGBufferBTex : register(t1);
  39. Texture2D gDepthBufferTex : register(t2);
  40. #endif
  41. SurfaceData decodeGBuffer(float4 GBufferAData, float4 GBufferBData, float deviceZ)
  42. {
  43. SurfaceData output;
  44. output.albedo.xyz = GBufferAData.xyz;
  45. output.albedo.w = 1.0f;
  46. output.worldNormal = GBufferBData * float4(2, 2, 2, 1) - float4(1, 1, 1, 0);
  47. output.worldNormal.xyz = normalize(output.worldNormal.xyz);
  48. output.depth = convertFromDeviceZ(deviceZ);
  49. return output;
  50. }
  51. StructuredBuffer<LightData> gLights : register(t3);
  52. cbuffer Params : register(b0)
  53. {
  54. // Offsets at which specific light types begin in gLights buffer
  55. // Assumed directional lights start at 0
  56. // x - offset to point lights, y - offset to spot lights, z - total number of lights
  57. uint3 gLightOffsets;
  58. uint2 gFramebufferSize;
  59. }
  60. #if MSAA_COUNT > 1
  61. RWBuffer<float4> gOutput : register(u0);
  62. uint getLinearAddress(uint2 coord, uint sampleIndex)
  63. {
  64. return (coord.y * gFramebufferSize.x + coord.x) * MSAA_COUNT + sampleIndex;
  65. }
  66. void writeBufferSample(uint2 coord, uint sampleIndex, float4 color)
  67. {
  68. uint idx = getLinearAddress(coord, sampleIndex);
  69. gOutput[idx] = color;
  70. }
  71. bool needsPerSampleShading(SurfaceData samples[MSAA_COUNT])
  72. {
  73. float3 albedo = samples[0].albedo.xyz;
  74. float3 normal = samples[0].worldNormal.xyz;
  75. float depth = samples[0].depth;
  76. [unroll]
  77. for(int i = 1; i < MSAA_COUNT; i++)
  78. {
  79. float3 otherAlbedo = samples[i].albedo.xyz;
  80. float3 otherNormal = samples[i].worldNormal.xyz;
  81. float otherDepth = samples[i].depth;
  82. [branch]
  83. 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)
  84. {
  85. return true;
  86. }
  87. }
  88. return false;
  89. }
  90. SurfaceData getGBufferData(uint2 pixelPos, uint sampleIndex)
  91. {
  92. float4 GBufferAData = gGBufferATex.Load(pixelPos, sampleIndex);
  93. float4 GBufferBData = gGBufferBTex.Load(pixelPos, sampleIndex);
  94. float deviceZ = gDepthBufferTex.Load(pixelPos, sampleIndex).r;
  95. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  96. }
  97. #else
  98. RWTexture2D<float4> gOutput : register(u0);
  99. SurfaceData getGBufferData(uint2 pixelPos)
  100. {
  101. float4 GBufferAData = gGBufferATex.Load(int3(pixelPos, 0));
  102. float4 GBufferBData = gGBufferBTex.Load(int3(pixelPos, 0));
  103. float deviceZ = gDepthBufferTex.Load(int3(pixelPos, 0)).r;
  104. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  105. }
  106. #endif
  107. groupshared uint sTileMinZ;
  108. groupshared uint sTileMaxZ;
  109. groupshared uint sNumLightsPerType[2];
  110. groupshared uint sTotalNumLights;
  111. groupshared uint sLightIndices[MAX_LIGHTS];
  112. float4 getLighting(float2 clipSpacePos, SurfaceData surfaceData)
  113. {
  114. // x, y are now in clip space, z, w are in view space
  115. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  116. // z, w eliminated (since they are already in view space)
  117. // Note: Multiply by depth should be avoided if using ortographic projection
  118. float4 mixedSpacePos = float4(clipSpacePos * -surfaceData.depth, surfaceData.depth, 1);
  119. float4 worldPosition4D = mul(gMatScreenToWorld, mixedSpacePos);
  120. float3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  121. float3 lightAccumulator = 0;
  122. float alpha = 0.0f;
  123. if(surfaceData.worldNormal.w > 0.0f)
  124. {
  125. for(uint i = 0; i < gLightOffsets[0]; ++i)
  126. lightAccumulator += getDirLightContibution(surfaceData, gLights[i]);
  127. for (uint i = 0; i < sNumLightsPerType[0]; ++i)
  128. {
  129. uint lightIdx = sLightIndices[i];
  130. lightAccumulator += getPointLightContribution(worldPosition, surfaceData, gLights[lightIdx]);
  131. }
  132. for(uint i = sNumLightsPerType[0]; i < sTotalNumLights; ++i)
  133. {
  134. uint lightIdx = sLightIndices[i];
  135. lightAccumulator += getSpotLightContribution(worldPosition, surfaceData, gLights[lightIdx]);
  136. }
  137. lightAccumulator += surfaceData.albedo * gAmbientFactor;
  138. alpha = 1.0f;
  139. }
  140. float3 diffuse = surfaceData.albedo.xyz / PI; // TODO - Add better lighting model later
  141. return float4(lightAccumulator * diffuse, alpha);
  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[0] = 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. sLightIndices[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 gDepthBufferTex;
  326. #else
  327. layout(binding = 1) uniform sampler2D gGBufferATex;
  328. layout(binding = 2) uniform sampler2D gGBufferBTex;
  329. layout(binding = 3) uniform sampler2D gDepthBufferTex;
  330. #endif
  331. SurfaceData decodeGBuffer(vec4 GBufferAData, vec4 GBufferBData, float deviceZ)
  332. {
  333. SurfaceData surfaceData;
  334. surfaceData.albedo.xyz = GBufferAData.xyz;
  335. surfaceData.albedo.w = 1.0f;
  336. surfaceData.worldNormal = GBufferBData * vec4(2, 2, 2, 1) - vec4(1, 1, 1, 0);
  337. surfaceData.worldNormal.xyz = normalize(surfaceData.worldNormal.xyz);
  338. surfaceData.depth = convertFromDeviceZ(deviceZ);
  339. return surfaceData;
  340. }
  341. #if MSAA_COUNT > 1
  342. layout(binding = 5, rgba16f) uniform image2DMS gOutput;
  343. bool needsPerSampleShading(SurfaceData samples[MSAA_COUNT])
  344. {
  345. vec3 albedo = samples[0].albedo.xyz;
  346. vec3 normal = samples[0].worldNormal.xyz;
  347. float depth = samples[0].depth;
  348. for(int i = 1; i < MSAA_COUNT; i++)
  349. {
  350. vec3 otherAlbedo = samples[i].albedo.xyz;
  351. vec3 otherNormal = samples[i].worldNormal.xyz;
  352. float otherDepth = samples[i].depth;
  353. 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)
  354. {
  355. return true;
  356. }
  357. }
  358. return false;
  359. }
  360. SurfaceData getGBufferData(ivec2 pixelPos, int sampleIndex)
  361. {
  362. vec4 GBufferAData = texelFetch(gGBufferATex, pixelPos, sampleIndex);
  363. vec4 GBufferBData = texelFetch(gGBufferBTex, pixelPos, sampleIndex);
  364. float deviceZ = texelFetch(gDepthBufferTex, pixelPos, sampleIndex).r;
  365. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  366. }
  367. #else
  368. layout(binding = 5, rgba16f) uniform image2D gOutput;
  369. SurfaceData getGBufferData(ivec2 pixelPos)
  370. {
  371. vec4 GBufferAData = texelFetch(gGBufferATex, pixelPos, 0);
  372. vec4 GBufferBData = texelFetch(gGBufferBTex, pixelPos, 0);
  373. float deviceZ = texelFetch(gDepthBufferTex, pixelPos, 0).r;
  374. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  375. }
  376. #endif
  377. layout(std430, binding = 4) readonly buffer gLights
  378. {
  379. LightData[] gLightsData;
  380. };
  381. layout(binding = 6, std140) uniform Params
  382. {
  383. // Offsets at which specific light types begin in gLights buffer
  384. // Assumed directional lights start at 0
  385. // x - offset to point lights, y - offset to spot lights, z - total number of lights
  386. uvec3 gLightOffsets;
  387. uvec2 gFramebufferSize;
  388. };
  389. shared uint sTileMinZ;
  390. shared uint sTileMaxZ;
  391. shared uint sNumLightsPerType[2];
  392. shared uint sTotalNumLights;
  393. shared uint sLightIndices[MAX_LIGHTS];
  394. vec4 getLighting(vec2 clipSpacePos, SurfaceData surfaceData)
  395. {
  396. // x, y are now in clip space, z, w are in view space
  397. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  398. // z, w eliminated (since they are already in view space)
  399. // Note: Multiply by depth should be avoided if using ortographic projection
  400. vec4 mixedSpacePos = vec4(clipSpacePos.xy * -surfaceData.depth, surfaceData.depth, 1);
  401. vec4 worldPosition4D = gMatScreenToWorld * mixedSpacePos;
  402. vec3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  403. float alpha = 0.0f;
  404. vec3 lightAccumulator = vec3(0, 0, 0);
  405. if(surfaceData.worldNormal.w > 0.0f)
  406. {
  407. for(uint i = 0; i < gLightOffsets[0]; ++i)
  408. {
  409. LightData lightData = gLightsData[i];
  410. lightAccumulator += getDirLightContibution(surfaceData, lightData);
  411. }
  412. for (uint i = 0; i < sNumLightsPerType[0]; ++i)
  413. {
  414. uint lightIdx = sLightIndices[i];
  415. LightData lightData = gLightsData[lightIdx];
  416. lightAccumulator += getPointLightContribution(worldPosition, surfaceData, lightData);
  417. }
  418. for(uint i = sNumLightsPerType[0]; i < sTotalNumLights; ++i)
  419. {
  420. uint lightIdx = sLightIndices[i];
  421. LightData lightData = gLightsData[lightIdx];
  422. lightAccumulator += getSpotLightContribution(worldPosition, surfaceData, lightData);
  423. }
  424. lightAccumulator += surfaceData.albedo.rgb * gAmbientFactor;
  425. alpha = 1.0f;
  426. }
  427. vec3 diffuse = surfaceData.albedo.xyz / PI; // TODO - Add better lighting model later
  428. return vec4(lightAccumulator * diffuse, alpha);
  429. }
  430. void main()
  431. {
  432. uint threadIndex = gl_LocalInvocationID.y * TILE_SIZE + gl_LocalInvocationID.x;
  433. ivec2 pixelPos = ivec2(gl_GlobalInvocationID.xy) + gViewportRectangle.xy;
  434. // Get data for all samples, and determine per-pixel minimum and maximum depth values
  435. SurfaceData surfaceData[MSAA_COUNT];
  436. uint sampleMinZ = 0x7F7FFFFF;
  437. uint sampleMaxZ = 0;
  438. #if MSAA_COUNT > 1
  439. for(int i = 0; i < MSAA_COUNT; ++i)
  440. {
  441. surfaceData[i] = getGBufferData(pixelPos, i);
  442. sampleMinZ = min(sampleMinZ, floatBitsToUint(-surfaceData[i].depth));
  443. sampleMaxZ = max(sampleMaxZ, floatBitsToUint(-surfaceData[i].depth));
  444. }
  445. #else
  446. surfaceData[0] = getGBufferData(pixelPos);
  447. sampleMinZ = floatBitsToUint(-surfaceData[0].depth);
  448. sampleMaxZ = floatBitsToUint(-surfaceData[0].depth);
  449. #endif
  450. // Set initial values
  451. if(threadIndex == 0)
  452. {
  453. sTileMinZ = 0x7F7FFFFF;
  454. sTileMaxZ = 0;
  455. sNumLightsPerType[0] = 0;
  456. sNumLightsPerType[0] = 0;
  457. sTotalNumLights = 0;
  458. }
  459. groupMemoryBarrier();
  460. barrier();
  461. atomicMin(sTileMinZ, sampleMinZ);
  462. atomicMax(sTileMaxZ, sampleMaxZ);
  463. groupMemoryBarrier();
  464. barrier();
  465. float minTileZ = uintBitsToFloat(sTileMinZ);
  466. float maxTileZ = uintBitsToFloat(sTileMaxZ);
  467. // Create a frustum for the current tile
  468. // See HLSL version for an explanation of the math
  469. vec2 tileScale = gViewportRectangle.zw / vec2(TILE_SIZE, TILE_SIZE);
  470. vec2 tileBias = tileScale - 1 - gl_WorkGroupID.xy * 2;
  471. float At = gMatProj[0][0] * tileScale.x;
  472. float Ctt = gMatProj[2][0] * tileScale.x - tileBias.x;
  473. float Bt = gMatProj[1][1] * tileScale.y;
  474. float Dtt = gMatProj[2][1] * tileScale.y + tileBias.y;
  475. // Extract left/right/top/bottom frustum planes from scaled projection matrix
  476. vec4 frustumPlanes[6];
  477. frustumPlanes[0] = vec4(At, 0.0f, gMatProj[2][3] + Ctt, 0.0f);
  478. frustumPlanes[1] = vec4(-At, 0.0f, gMatProj[2][3] - Ctt, 0.0f);
  479. frustumPlanes[2] = vec4(0.0f, -Bt, gMatProj[2][3] - Dtt, 0.0f);
  480. frustumPlanes[3] = vec4(0.0f, Bt, gMatProj[2][3] + Dtt, 0.0f);
  481. // Normalize
  482. for (uint i = 0; i < 4; ++i)
  483. frustumPlanes[i] /= length(frustumPlanes[i].xyz);
  484. // Generate near/far frustum planes
  485. frustumPlanes[4] = vec4(0.0f, 0.0f, -1.0f, -minTileZ);
  486. frustumPlanes[5] = vec4(0.0f, 0.0f, 1.0f, maxTileZ);
  487. // Find radial & spot lights overlapping the tile
  488. for(uint type = 0; type < 2; type++)
  489. {
  490. uint lightOffset = threadIndex + gLightOffsets[type];
  491. uint lightsEnd = gLightOffsets[type + 1];
  492. for (uint i = lightOffset; i < lightsEnd && i < MAX_LIGHTS; i += TILE_SIZE)
  493. {
  494. vec4 lightPosition = gMatView * vec4(gLightsData[i].position, 1.0f);
  495. float lightRadius = gLightsData[i].radius;
  496. bool lightInTile = true;
  497. // First check side planes as this will cull majority of the lights
  498. for (uint j = 0; j < 4; ++j)
  499. {
  500. float dist = dot(frustumPlanes[j], lightPosition);
  501. lightInTile = lightInTile && (dist >= -lightRadius);
  502. }
  503. if (lightInTile)
  504. {
  505. bool inDepthRange = true;
  506. // Check near/far planes
  507. for (uint j = 4; j < 6; ++j)
  508. {
  509. float dist = dot(frustumPlanes[j], lightPosition);
  510. inDepthRange = inDepthRange && (dist >= -lightRadius);
  511. }
  512. // In tile, add to branch
  513. if (inDepthRange)
  514. {
  515. atomicAdd(sNumLightsPerType[type], 1U);
  516. uint idx = atomicAdd(sTotalNumLights, 1U);
  517. sLightIndices[idx] = i;
  518. }
  519. }
  520. }
  521. }
  522. groupMemoryBarrier();
  523. barrier();
  524. vec2 screenUv = (vec2(gViewportRectangle.xy + pixelPos) + 0.5f) / vec2(gViewportRectangle.zw);
  525. vec2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  526. uvec2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  527. // Ignore pixels out of valid range
  528. if (all(lessThan(gl_GlobalInvocationID.xy, viewportMax)))
  529. {
  530. #if MSAA_COUNT > 1
  531. vec4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  532. imageStore(gOutput, pixelPos, 0, lighting);
  533. bool doPerSampleShading = needsPerSampleShading(surfaceData);
  534. if(doPerSampleShading)
  535. {
  536. for(int i = 1; i < MSAA_COUNT; ++i)
  537. {
  538. lighting = getLighting(clipSpacePos.xy, surfaceData[i]);
  539. imageStore(gOutput, pixelPos, i, lighting);
  540. }
  541. }
  542. else // Splat same information to all samples
  543. {
  544. for(int i = 1; i < MSAA_COUNT; ++i)
  545. imageStore(gOutput, pixelPos, i, lighting);
  546. }
  547. #else
  548. vec4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  549. imageStore(gOutput, pixelPos, lighting);
  550. #endif
  551. }
  552. }
  553. };
  554. };
  555. };