TiledDeferredLighting.bsl 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #include "$ENGINE$\GBufferInput.bslinc"
  2. #include "$ENGINE$\PerCameraData.bslinc"
  3. #define USE_COMPUTE_INDICES
  4. #include "$ENGINE$\LightingCommon.bslinc"
  5. #include "$ENGINE$\ReflectionCubemapCommon.bslinc"
  6. #include "$ENGINE$\ImageBasedLighting.bslinc"
  7. technique TiledDeferredLighting
  8. {
  9. mixin GBufferInput;
  10. mixin PerCameraData;
  11. mixin LightingCommon;
  12. mixin ReflectionCubemapCommon;
  13. mixin ImageBasedLighting;
  14. code
  15. {
  16. [internal]
  17. cbuffer Params : register(b0)
  18. {
  19. // Offsets at which specific light types begin in gLights buffer
  20. // Assumed directional lights start at 0
  21. // x - offset to point lights, y - offset to spot lights, z - total number of lights
  22. uint3 gLightOffsets;
  23. uint2 gFramebufferSize;
  24. }
  25. #if MSAA_COUNT > 1
  26. RWBuffer<float4> gOutput : register(u0);
  27. uint getLinearAddress(uint2 coord, uint sampleIndex)
  28. {
  29. return (coord.y * gFramebufferSize.x + coord.x) * MSAA_COUNT + sampleIndex;
  30. }
  31. void writeBufferSample(uint2 coord, uint sampleIndex, float4 color)
  32. {
  33. uint idx = getLinearAddress(coord, sampleIndex);
  34. gOutput[idx] = color;
  35. }
  36. #else
  37. RWTexture2D<float4> gOutput : register(u0);
  38. #endif
  39. groupshared uint sTileMinZ;
  40. groupshared uint sTileMaxZ;
  41. groupshared uint sNumLightsPerType[2];
  42. groupshared uint sTotalNumLights;
  43. float4 getLighting(float2 clipSpacePos, SurfaceData surfaceData)
  44. {
  45. // x, y are now in clip space, z, w are in view space
  46. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  47. // z, w eliminated (since they are already in view space)
  48. // Note: Multiply by depth should be avoided if using ortographic projection
  49. float4 mixedSpacePos = float4(clipSpacePos * -surfaceData.depth, surfaceData.depth, 1);
  50. float4 worldPosition4D = mul(gMatScreenToWorld, mixedSpacePos);
  51. float3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  52. uint4 lightOffsets;
  53. lightOffsets.x = gLightOffsets[0];
  54. lightOffsets.y = 0;
  55. lightOffsets.z = sNumLightsPerType[0];
  56. lightOffsets.w = sTotalNumLights;
  57. float3 V = normalize(gViewOrigin - worldPosition);
  58. float3 N = surfaceData.worldNormal.xyz;
  59. float3 R = 2 * dot(V, N) * N - V;
  60. float3 specR = getSpecularDominantDir(N, R, surfaceData.roughness);
  61. return getDirectLighting(worldPosition, V, specR, surfaceData, lightOffsets);
  62. }
  63. [numthreads(TILE_SIZE, TILE_SIZE, 1)]
  64. void csmain(
  65. uint3 groupId : SV_GroupID,
  66. uint3 groupThreadId : SV_GroupThreadID,
  67. uint3 dispatchThreadId : SV_DispatchThreadID)
  68. {
  69. uint threadIndex = groupThreadId.y * TILE_SIZE + groupThreadId.x;
  70. uint2 pixelPos = dispatchThreadId.xy + gViewportRectangle.xy;
  71. // Note: To improve performance perhaps:
  72. // - Use halfZ (split depth range into two regions for better culling)
  73. // - Use parallel reduction instead of atomics
  74. // - Use AABB instead of frustum (no false positives)
  75. // - Increase tile size to 32x32 to amortize the cost of AABB calc (2x if using halfZ)
  76. // Get data for all samples, and determine per-pixel minimum and maximum depth values
  77. SurfaceData surfaceData[MSAA_COUNT];
  78. uint sampleMinZ = 0x7F7FFFFF;
  79. uint sampleMaxZ = 0;
  80. #if MSAA_COUNT > 1
  81. [unroll]
  82. for(uint i = 0; i < MSAA_COUNT; ++i)
  83. {
  84. surfaceData[i] = getGBufferData(pixelPos, i);
  85. sampleMinZ = min(sampleMinZ, asuint(-surfaceData[i].depth));
  86. sampleMaxZ = max(sampleMaxZ, asuint(-surfaceData[i].depth));
  87. }
  88. #else
  89. surfaceData[0] = getGBufferData(pixelPos);
  90. sampleMinZ = asuint(-surfaceData[0].depth);
  91. sampleMaxZ = asuint(-surfaceData[0].depth);
  92. #endif
  93. // Set initial values
  94. if(threadIndex == 0)
  95. {
  96. sTileMinZ = 0x7F7FFFFF;
  97. sTileMaxZ = 0;
  98. sNumLightsPerType[0] = 0;
  99. sNumLightsPerType[1] = 0;
  100. sTotalNumLights = 0;
  101. }
  102. GroupMemoryBarrierWithGroupSync();
  103. // Determine minimum and maximum depth values for a tile
  104. InterlockedMin(sTileMinZ, sampleMinZ);
  105. InterlockedMax(sTileMaxZ, sampleMaxZ);
  106. GroupMemoryBarrierWithGroupSync();
  107. float minTileZ = asfloat(sTileMinZ);
  108. float maxTileZ = asfloat(sTileMaxZ);
  109. // Create a frustum for the current tile
  110. // First determine a scale of the tile compared to the viewport
  111. float2 tileScale = gViewportRectangle.zw * rcp(float2(TILE_SIZE, TILE_SIZE));
  112. // Now we need to use that scale to scale down the frustum.
  113. // Assume a projection matrix:
  114. // A, 0, C, 0
  115. // 0, B, D, 0
  116. // 0, 0, Q, QN
  117. // 0, 0, -1, 0
  118. //
  119. // Where A is = 2*n / (r - l)
  120. // and C = (r + l) / (r - l)
  121. //
  122. // Q & QN are used for Z value which we don't need to scale. B & D are equivalent for the
  123. // Y value, we'll only consider the X values (A & C) from now on.
  124. //
  125. // Both and A and C are inversely proportional to the size of the frustum (r - l). Larger scale mean that
  126. // tiles are that much smaller than the viewport. This means as our scale increases, (r - l) decreases,
  127. // which means A & C as a whole increase. Therefore:
  128. // A' = A * tileScale.x
  129. // C' = C * tileScale.x
  130. // Aside from scaling, we also need to offset the frustum to the center of the tile.
  131. // For this we calculate the bias value which we add to the C & D factors (which control
  132. // the offset in the projection matrix).
  133. float2 tileBias = tileScale - 1 - groupId.xy * 2;
  134. // This will yield a bias ranging from [-(tileScale - 1), tileScale - 1]. Every second bias is skipped as
  135. // corresponds to a point in-between two tiles, overlapping existing frustums.
  136. float flipSign = 1.0f;
  137. // Adjust for OpenGL's upside down texture system
  138. #if OPENGL
  139. flipSign = -1;
  140. #endif
  141. float At = gMatProj[0][0] * tileScale.x;
  142. float Ctt = gMatProj[0][2] * tileScale.x - tileBias.x;
  143. float Bt = gMatProj[1][1] * tileScale.y * flipSign;
  144. float Dtt = (gMatProj[1][2] * tileScale.y + flipSign * tileBias.y) * flipSign;
  145. // Extract left/right/top/bottom frustum planes from scaled projection matrix
  146. // Note: Do this on the CPU? Since they're shared among all entries in a tile. Plus they don't change across frames.
  147. float4 frustumPlanes[6];
  148. frustumPlanes[0] = float4(At, 0.0f, gMatProj[3][2] + Ctt, 0.0f);
  149. frustumPlanes[1] = float4(-At, 0.0f, gMatProj[3][2] - Ctt, 0.0f);
  150. frustumPlanes[2] = float4(0.0f, -Bt, gMatProj[3][2] - Dtt, 0.0f);
  151. frustumPlanes[3] = float4(0.0f, Bt, gMatProj[3][2] + Dtt, 0.0f);
  152. // Normalize
  153. [unroll]
  154. for (uint i = 0; i < 4; ++i)
  155. frustumPlanes[i] *= rcp(length(frustumPlanes[i].xyz));
  156. // Generate near/far frustum planes
  157. // Note: d gets negated in plane equation, this is why its in opposite direction than it intuitively should be
  158. frustumPlanes[4] = float4(0.0f, 0.0f, -1.0f, -minTileZ);
  159. frustumPlanes[5] = float4(0.0f, 0.0f, 1.0f, maxTileZ);
  160. // Find radial & spot lights overlapping the tile
  161. for(uint type = 0; type < 2; type++)
  162. {
  163. uint lightOffset = threadIndex + gLightOffsets[type];
  164. uint lightsEnd = gLightOffsets[type + 1];
  165. for (uint i = lightOffset; i < lightsEnd && i < MAX_LIGHTS; i += TILE_SIZE)
  166. {
  167. float4 lightPosition = mul(gMatView, float4(gLights[i].position, 1.0f));
  168. float lightRadius = gLights[i].attRadius;
  169. // Note: The cull method can have false positives. In case of large light bounds and small tiles, it
  170. // can end up being quite a lot. Consider adding an extra heuristic to check a separating plane.
  171. bool lightInTile = true;
  172. // First check side planes as this will cull majority of the lights
  173. [unroll]
  174. for (uint j = 0; j < 4; ++j)
  175. {
  176. float dist = dot(frustumPlanes[j], lightPosition);
  177. lightInTile = lightInTile && (dist >= -lightRadius);
  178. }
  179. // Make sure to do an actual branch, since it's quite likely an entire warp will have the same value
  180. [branch]
  181. if (lightInTile)
  182. {
  183. bool inDepthRange = true;
  184. // Check near/far planes
  185. [unroll]
  186. for (uint j = 4; j < 6; ++j)
  187. {
  188. float dist = dot(frustumPlanes[j], lightPosition);
  189. inDepthRange = inDepthRange && (dist >= -lightRadius);
  190. }
  191. // In tile, add to branch
  192. [branch]
  193. if (inDepthRange)
  194. {
  195. InterlockedAdd(sNumLightsPerType[type], 1U);
  196. uint idx;
  197. InterlockedAdd(sTotalNumLights, 1U, idx);
  198. gLightIndices[idx] = i;
  199. }
  200. }
  201. }
  202. }
  203. GroupMemoryBarrierWithGroupSync();
  204. // Generate world position
  205. float2 screenUv = ((float2)(gViewportRectangle.xy + pixelPos) + 0.5f) / (float2)gViewportRectangle.zw;
  206. float2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  207. uint2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  208. // Ignore pixels out of valid range
  209. if (all(dispatchThreadId.xy < viewportMax))
  210. {
  211. #if MSAA_COUNT > 1
  212. float4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  213. writeBufferSample(pixelPos, 0, lighting);
  214. bool doPerSampleShading = needsPerSampleShading(surfaceData);
  215. if(doPerSampleShading)
  216. {
  217. [unroll]
  218. for(uint i = 1; i < MSAA_COUNT; ++i)
  219. {
  220. lighting = getLighting(clipSpacePos.xy, surfaceData[i]);
  221. writeBufferSample(pixelPos, i, lighting);
  222. }
  223. }
  224. else // Splat same information to all samples
  225. {
  226. [unroll]
  227. for(uint i = 1; i < MSAA_COUNT; ++i)
  228. writeBufferSample(pixelPos, i, lighting);
  229. }
  230. #else
  231. float4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  232. gOutput[pixelPos] = lighting;
  233. #endif
  234. }
  235. }
  236. };
  237. };