TiledDeferredLighting.bsl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. #include "$ENGINE$\GBuffer.bslinc"
  2. #include "$ENGINE$\LightingCommon.bslinc"
  3. Parameters =
  4. {
  5. Sampler2D gGBufferASamp : alias("gGBufferATex");
  6. Sampler2D gGBufferBSamp : alias("gGBufferBTex");
  7. Sampler2D gDepthBufferSamp : alias("gDepthBufferTex");
  8. Texture2D gGBufferATex : auto("GBufferA");
  9. Texture2D gGBufferBTex : auto("GBufferB");
  10. Texture2D gDepthBufferTex : auto("GBufferDepth");
  11. };
  12. Technique
  13. : inherits("GBuffer")
  14. : inherits("LightingCommon") =
  15. {
  16. Language = "HLSL11";
  17. Pass =
  18. {
  19. Compute =
  20. {
  21. // Arbitrary limit, increase if needed
  22. #define MAX_SPOT_LIGHTS 512
  23. #define MAX_RADIAL_LIGHTS 512
  24. SamplerState gGBufferASamp : register(s0);
  25. SamplerState gGBufferBSamp : register(s1);
  26. SamplerState gDepthBufferSamp : register(s2);
  27. Texture2D gGBufferATex : register(t0);
  28. Texture2D gGBufferBTex : register(t1);
  29. Texture2D gDepthBufferTex : register(t2);
  30. SurfaceData decodeGBuffer(float4 GBufferAData, float4 GBufferBData, float deviceZ)
  31. {
  32. SurfaceData output;
  33. output.albedo.xyz = GBufferAData.xyz;
  34. output.albedo.w = 1.0f;
  35. output.worldNormal = GBufferBData * float4(2, 2, 2, 1) - float4(1, 1, 1, 0);
  36. output.worldNormal.xyz = normalize(output.worldNormal.xyz);
  37. output.depth = convertFromDeviceZ(deviceZ);
  38. return output;
  39. }
  40. SurfaceData getGBufferData(float2 uv)
  41. {
  42. float4 GBufferAData = gGBufferATex.SampleLevel(gGBufferASamp, uv, 0);
  43. float4 GBufferBData = gGBufferBTex.SampleLevel(gGBufferBSamp, uv, 0);
  44. float deviceZ = gDepthBufferTex.SampleLevel(gDepthBufferSamp, uv, 0).r;
  45. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  46. }
  47. SurfaceData getGBufferData(uint2 pixelPos)
  48. {
  49. float4 GBufferAData = gGBufferATex.Load(int3(pixelPos, 0));
  50. float4 GBufferBData = gGBufferBTex.Load(int3(pixelPos, 0));
  51. float deviceZ = gDepthBufferTex.Load(int3(pixelPos, 0)).r;
  52. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  53. }
  54. StructuredBuffer<LightData> gDirLights : register(t3);
  55. StructuredBuffer<LightData> gPointLights : register(t4);
  56. StructuredBuffer<LightData> gSpotLights : register(t5);
  57. RWTexture2D<float4> gOutput : register(u0);
  58. cbuffer Params : register(b0)
  59. {
  60. // x - directional, y - point, z - spot
  61. uint3 gNumLightsPerType;
  62. }
  63. groupshared uint sTileMinZ;
  64. groupshared uint sTileMaxZ;
  65. groupshared uint sNumRadialLights;
  66. groupshared uint sNumSpotLights;
  67. groupshared uint sRadialLightIndices[MAX_RADIAL_LIGHTS];
  68. groupshared uint sSpotLightIndices[MAX_SPOT_LIGHTS];
  69. [numthreads(TILE_SIZE, TILE_SIZE, 1)]
  70. void main(
  71. uint3 groupId : SV_GroupID,
  72. uint3 groupThreadId : SV_GroupThreadID,
  73. uint3 dispatchThreadId : SV_DispatchThreadID,
  74. uint threadIndex : SV_GroupIndex)
  75. {
  76. uint2 pixelPos = dispatchThreadId.xy + gViewportRectangle.xy;
  77. float deviceZ = gDepthBufferTex.Load(int3(pixelPos, 0)).r;
  78. float depth = convertFromDeviceZ(deviceZ);
  79. // Set initial values
  80. if(threadIndex == 0)
  81. {
  82. sTileMinZ = 0x7F7FFFFF;
  83. sTileMaxZ = 0;
  84. sNumRadialLights = 0;
  85. sNumSpotLights = 0;
  86. }
  87. GroupMemoryBarrierWithGroupSync();
  88. // Determine minimum and maximum depth values
  89. InterlockedMin(sTileMinZ, asuint(-depth));
  90. InterlockedMax(sTileMaxZ, asuint(-depth));
  91. GroupMemoryBarrierWithGroupSync();
  92. float minTileZ = asfloat(sTileMinZ);
  93. float maxTileZ = asfloat(sTileMaxZ);
  94. // Create a frustum for the current tile
  95. // First determine a scale of the tile compared to the viewport
  96. float2 tileScale = gViewportRectangle.zw / float2(TILE_SIZE, TILE_SIZE);
  97. // Now we need to use that scale to scale down the frustum.
  98. // Assume a projection matrix:
  99. // A, 0, C, 0
  100. // 0, B, D, 0
  101. // 0, 0, Q, QN
  102. // 0, 0, -1, 0
  103. //
  104. // Where A is = 2*n / (r - l)
  105. // and C = (r + l) / (r - l)
  106. //
  107. // Q & QN are used for Z value which we don't need to scale. B & D are equivalent for the
  108. // Y value, we'll only consider the X values (A & C) from now on.
  109. //
  110. // Both and A and C are inversely proportional to the size of the frustum (r - l). Larger scale mean that
  111. // tiles are that much smaller than the viewport. This means as our scale increases, (r - l) decreases,
  112. // which means A & C as a whole increase. Therefore:
  113. // A' = A * tileScale.x
  114. // C' = C * tileScale.x
  115. // Aside from scaling, we also need to offset the frustum to the center of the tile.
  116. // For this we calculate the bias value which we add to the C & D factors (which control
  117. // the offset in the projection matrix).
  118. float2 tileBias = tileScale - 1 - groupId.xy * 2;
  119. // This will yield a bias ranging from [-(tileScale - 1), tileScale - 1], with only odd
  120. // numbers (except for tile scale of 1). e.g.
  121. // tileScale = 1
  122. // - bias[0] = 0
  123. // tileScale = 2
  124. // - bias[0] = 1
  125. // - bias[1] = -1
  126. // tileScale = 4
  127. // - bias[0] = 3
  128. // - bias[1] = 1
  129. // - bias[2] = -1
  130. // - bias[3] = -3
  131. // etc.
  132. // We use only odd numbers as that ensures we get only the frustums centered on tiles,
  133. // and not those overlapping two tiles (centered on their boundary).
  134. float At = gMatProj[0][0] * tileScale.x;
  135. float Ctt = gMatProj[0][2] * tileScale.x - tileBias.x;
  136. float Bt = gMatProj[1][1] * tileScale.y;
  137. float Dtt = gMatProj[1][2] * tileScale.y + tileBias.y;
  138. // Extract left/right/top/bottom frustum planes from scaled projection matrix
  139. // Note: Do this on the CPU? Since they're shared among all entries in a tile. Plus they don't change across frames.
  140. float4 frustumPlanes[6];
  141. frustumPlanes[0] = float4(At, 0.0f, gMatProj[3][2] + Ctt, 0.0f);
  142. frustumPlanes[1] = float4(-At, 0.0f, gMatProj[3][2] - Ctt, 0.0f);
  143. frustumPlanes[2] = float4(0.0f, -Bt, gMatProj[3][2] - Dtt, 0.0f);
  144. frustumPlanes[3] = float4(0.0f, Bt, gMatProj[3][2] + Dtt, 0.0f);
  145. // Normalize
  146. [unroll]
  147. for (uint i = 0; i < 4; ++i)
  148. frustumPlanes[i] *= rcp(length(frustumPlanes[i].xyz));
  149. // Generate near/far frustum planes
  150. // Note: d gets negated in plane equation, this is why its in opposite direction than it intuitively should be
  151. frustumPlanes[4] = float4(0.0f, 0.0f, -1.0f, -minTileZ);
  152. frustumPlanes[5] = float4(0.0f, 0.0f, 1.0f, maxTileZ);
  153. // Generate world position
  154. float2 screenUv = ((float2)(gViewportRectangle.xy + pixelPos) + 0.5f) / (float2)gViewportRectangle.zw;
  155. float2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  156. // x, y are now in clip space, z, w are in view space
  157. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  158. // z, w eliminated (since they are already in view space)
  159. // Note: Multiply by depth should be avoided if using ortographic projection
  160. float4 mixedSpacePos = float4(clipSpacePos.xy * -depth, depth, 1);
  161. float4 worldPosition4D = mul(gMatScreenToWorld, mixedSpacePos);
  162. float3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  163. // Find lights overlapping the tile
  164. for (uint i = threadIndex; i < gNumLightsPerType.y && i < MAX_RADIAL_LIGHTS; i += TILE_SIZE)
  165. {
  166. float4 lightPosition = mul(gMatView, float4(gPointLights[i].position, 1.0f));
  167. float lightRadius = gPointLights[i].radius;
  168. // Note: The cull method can have false positives. In case of large light bounds and small tiles, it
  169. // can end up being quite a lot. Consider adding an extra heuristic to check a separating plane.
  170. bool lightInTile = true;
  171. // First check side planes as this will cull majority of the lights
  172. [unroll]
  173. for (uint j = 0; j < 4; ++j)
  174. {
  175. float dist = dot(frustumPlanes[j], lightPosition);
  176. lightInTile = lightInTile && (dist >= -lightRadius);
  177. }
  178. // Make sure to do an actual branch, since it's quite likely an entire warp will have the same value
  179. [branch]
  180. if (lightInTile)
  181. {
  182. bool inDepthRange = true;
  183. // Check near/far planes
  184. [unroll]
  185. for (uint j = 4; j < 6; ++j)
  186. {
  187. float dist = dot(frustumPlanes[j], lightPosition);
  188. inDepthRange = inDepthRange && (dist >= -lightRadius);
  189. }
  190. // In tile, add to branch
  191. [branch]
  192. if (inDepthRange)
  193. {
  194. uint idx;
  195. InterlockedAdd(sNumRadialLights, 1U, idx);
  196. sRadialLightIndices[idx] = i;
  197. }
  198. }
  199. }
  200. for (uint i = threadIndex; i < gNumLightsPerType.z && i < MAX_SPOT_LIGHTS; i += TILE_SIZE)
  201. {
  202. float4 lightPosition = mul(gMatView, float4(gSpotLights[i].position, 1.0f));
  203. float lightRadius = gSpotLights[i].radius;
  204. // Note: The cull method can have false positives. In case of large light bounds and small tiles, it
  205. // can end up being quite a lot. Consider adding an extra heuristic to check a separating plane.
  206. bool lightInTile = true;
  207. // First check side planes as this will cull majority of the lights
  208. [unroll]
  209. for (uint j = 0; j < 4; ++j)
  210. {
  211. float dist = dot(frustumPlanes[j], lightPosition);
  212. lightInTile = lightInTile && (dist >= -lightRadius);
  213. }
  214. // Make sure to do an actual branch, since it's quite likely an entire warp will have the same value
  215. [branch]
  216. if (lightInTile)
  217. {
  218. bool inDepthRange = true;
  219. // Check near/far planes
  220. [unroll]
  221. for (uint j = 4; j < 6; ++j)
  222. {
  223. float dist = dot(frustumPlanes[j], lightPosition);
  224. inDepthRange = inDepthRange && (dist >= -lightRadius);
  225. }
  226. // In tile, add to branch
  227. [branch]
  228. if (inDepthRange)
  229. {
  230. uint idx;
  231. InterlockedAdd(sNumSpotLights, 1U, idx);
  232. sSpotLightIndices[idx] = i;
  233. }
  234. }
  235. }
  236. GroupMemoryBarrierWithGroupSync();
  237. // Note: This unnecessarily samples depth again
  238. SurfaceData surfaceData = getGBufferData(pixelPos);
  239. float3 lightAccumulator = 0;
  240. float alpha = 0.0f;
  241. if(surfaceData.worldNormal.w > 0.0f)
  242. {
  243. for(uint i = 0; i < gNumLightsPerType.x; ++i)
  244. lightAccumulator += getDirLightContibution(surfaceData, gDirLights[i]);
  245. for (uint i = 0; i < sNumRadialLights; ++i)
  246. {
  247. uint lightIdx = sRadialLightIndices[i];
  248. lightAccumulator += getPointLightContribution(worldPosition, surfaceData, gPointLights[lightIdx]);
  249. }
  250. for(uint i = 0; i < sNumSpotLights; ++i)
  251. {
  252. uint lightIdx = sSpotLightIndices[i];
  253. lightAccumulator += getSpotLightContribution(worldPosition, surfaceData, gSpotLights[lightIdx]);
  254. }
  255. alpha = 1.0f;
  256. }
  257. float3 diffuse = surfaceData.albedo.xyz / PI; // TODO - Add better lighting model later
  258. uint2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  259. // Ignore pixels out of valid range
  260. if (all(dispatchThreadId.xy < viewportMax))
  261. gOutput[pixelPos] = float4(gOutput[pixelPos].xyz + diffuse * lightAccumulator, alpha);
  262. }
  263. };
  264. };
  265. };
  266. Technique
  267. : inherits("GBuffer")
  268. : inherits("LightingCommon") =
  269. {
  270. Language = "GLSL";
  271. Pass =
  272. {
  273. Compute =
  274. {
  275. layout (local_size_x = TILE_SIZE, local_size_y = TILE_SIZE) in;
  276. layout(binding = 0) uniform sampler2D gGBufferATex;
  277. layout(binding = 1) uniform sampler2D gGBufferBTex;
  278. layout(binding = 2) uniform sampler2D gDepthBufferTex;
  279. SurfaceData decodeGBuffer(vec4 GBufferAData, vec4 GBufferBData, float deviceZ)
  280. {
  281. SurfaceData surfaceData;
  282. surfaceData.albedo.xyz = GBufferAData.xyz;
  283. surfaceData.albedo.w = 1.0f;
  284. surfaceData.worldNormal = GBufferBData * vec4(2, 2, 2, 1) - vec4(1, 1, 1, 0);
  285. surfaceData.worldNormal.xyz = normalize(surfaceData.worldNormal.xyz);
  286. surfaceData.depth = convertFromDeviceZ(deviceZ);
  287. return surfaceData;
  288. }
  289. SurfaceData getGBufferData(vec2 uv)
  290. {
  291. vec4 GBufferAData = textureLod(gGBufferATex, uv, 0);
  292. vec4 GBufferBData = textureLod(gGBufferBTex, uv, 0);
  293. float deviceZ = textureLod(gDepthBufferTex, uv, 0).r;
  294. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  295. }
  296. SurfaceData getGBufferData(ivec2 pixelPos)
  297. {
  298. vec4 GBufferAData = texelFetch(gGBufferATex, pixelPos, 0);
  299. vec4 GBufferBData = texelFetch(gGBufferBTex, pixelPos, 0);
  300. float deviceZ = texelFetch(gDepthBufferTex, pixelPos, 0).r;
  301. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  302. }
  303. layout(std430, binding = 3) buffer gDirLights
  304. {
  305. LightData[] gDirLightsData;
  306. };
  307. layout(std430, binding = 4) buffer gPointLights
  308. {
  309. LightData[] gPointLightsData;
  310. };
  311. layout(std430, binding = 5) buffer gSpotLights
  312. {
  313. LightData[] gSpotLightsData;
  314. };
  315. layout(binding = 6, rgba16f) uniform image2D gOutput;
  316. layout(binding = 7, std140) uniform Params
  317. {
  318. // x - directional, y - point, z - spot
  319. uvec3 gNumLightsPerType;
  320. };
  321. void main()
  322. {
  323. ivec2 pixelPos = ivec2(gl_GlobalInvocationID.xy) + gViewportRectangle.xy;
  324. SurfaceData surfaceData = getGBufferData(pixelPos);
  325. float alpha = 0.0f;
  326. vec3 lightAccumulator = vec3(0, 0, 0);
  327. if(surfaceData.worldNormal.w > 0.0f)
  328. {
  329. vec2 screenUv = (vec2(gViewportRectangle.xy + pixelPos) + 0.5f) / vec2(gViewportRectangle.zw);
  330. vec2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  331. // x, y are now in clip space, z, w are in view space
  332. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  333. // z, w eliminated (since they are already in view space)
  334. // Note: Multiply by depth should be avoided if using ortographic projection
  335. vec4 mixedSpacePos = vec4(clipSpacePos.xy * -surfaceData.depth, surfaceData.depth, 1);
  336. vec4 worldPosition4D = gMatScreenToWorld * mixedSpacePos;
  337. vec3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  338. for(uint i = 0; i < gNumLightsPerType.x; i++)
  339. lightAccumulator += getDirLightContibution(surfaceData, gDirLightsData[i]);
  340. for(uint i = 0; i < gNumLightsPerType.y; i++)
  341. lightAccumulator += getPointLightContribution(worldPosition, surfaceData, gPointLightsData[i]);
  342. for(uint i = 0; i < gNumLightsPerType.z; i++)
  343. lightAccumulator += getSpotLightContribution(worldPosition, surfaceData, gSpotLightsData[i]);
  344. alpha = 1.0f;
  345. }
  346. vec3 diffuse = surfaceData.albedo.xyz / PI; // TODO - Add better lighting model later
  347. uvec2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  348. // Ignore pixels out of valid range
  349. if (all(lessThan(gl_GlobalInvocationID.xy, viewportMax)))
  350. {
  351. vec4 existingValue = imageLoad(gOutput, pixelPos);
  352. imageStore(gOutput, pixelPos, vec4(diffuse * lightAccumulator + existingValue.xyz, alpha));
  353. }
  354. }
  355. };
  356. };
  357. };