BsLightRendering.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsLightRendering.h"
  4. #include "Material/BsMaterial.h"
  5. #include "Material/BsShader.h"
  6. #include "BsRenderBeast.h"
  7. #include "RenderAPI/BsGpuParams.h"
  8. #include "Material/BsGpuParamsSet.h"
  9. #include "RenderAPI/BsGpuBuffer.h"
  10. #include "Renderer/BsLight.h"
  11. #include "Renderer/BsRendererUtility.h"
  12. #include "BsStandardDeferredLighting.h"
  13. namespace bs { namespace ct
  14. {
  15. static const UINT32 BUFFER_INCREMENT = 16 * sizeof(LightData);
  16. TiledLightingParamDef gTiledLightingParamDef;
  17. RendererLight::RendererLight(Light* light)
  18. :internal(light)
  19. { }
  20. void RendererLight::getParameters(LightData& output) const
  21. {
  22. Radian spotAngle = Math::clamp(internal->getSpotAngle() * 0.5f, Degree(0), Degree(89));
  23. Radian spotFalloffAngle = Math::clamp(internal->getSpotFalloffAngle() * 0.5f, Degree(0), (Degree)spotAngle);
  24. Color color = internal->getColor();
  25. const Transform& tfrm = internal->getTransform();
  26. output.position = tfrm.getPosition();
  27. output.attRadius = internal->getBounds().getRadius();
  28. output.srcRadius = internal->getSourceRadius();
  29. output.direction = -tfrm.getRotation().zAxis();
  30. output.luminance = internal->getLuminance();
  31. output.spotAngles.x = spotAngle.valueRadians();
  32. output.spotAngles.y = Math::cos(output.spotAngles.x);
  33. output.spotAngles.z = 1.0f / std::max(Math::cos(spotFalloffAngle) - output.spotAngles.y, 0.001f);
  34. output.attRadiusSqrdInv = 1.0f / (output.attRadius * output.attRadius);
  35. output.color = Vector3(color.r, color.g, color.b);
  36. // If directional lights, convert angular radius in degrees to radians
  37. if (internal->getType() == LightType::Directional)
  38. output.srcRadius *= Math::DEG2RAD;
  39. output.shiftedLightPosition = getShiftedLightPosition();
  40. }
  41. void RendererLight::getParameters(SPtr<GpuParamBlockBuffer>& buffer) const
  42. {
  43. LightData lightData;
  44. getParameters(lightData);
  45. float type = 0.0f;
  46. switch (internal->getType())
  47. {
  48. case LightType::Directional:
  49. type = 0;
  50. break;
  51. case LightType::Radial:
  52. type = 0.3f;
  53. break;
  54. case LightType::Spot:
  55. type = 0.8f;
  56. break;
  57. default:
  58. break;
  59. }
  60. gPerLightParamDef.gLightPositionAndSrcRadius.set(buffer, Vector4(lightData.position, lightData.srcRadius));
  61. gPerLightParamDef.gLightColorAndLuminance.set(buffer, Vector4(lightData.color, lightData.luminance));
  62. gPerLightParamDef.gLightSpotAnglesAndSqrdInvAttRadius.set(buffer, Vector4(lightData.spotAngles, lightData.attRadiusSqrdInv));
  63. gPerLightParamDef.gLightDirectionAndAttRadius.set(buffer, Vector4(lightData.direction, lightData.attRadius));
  64. gPerLightParamDef.gShiftedLightPositionAndType.set(buffer, Vector4(lightData.shiftedLightPosition, type));
  65. Vector4 lightGeometry;
  66. lightGeometry.x = internal->getType() == LightType::Spot ? (float)Light::LIGHT_CONE_NUM_SIDES : 0;
  67. lightGeometry.y = (float)Light::LIGHT_CONE_NUM_SLICES;
  68. lightGeometry.z = internal->getBounds().getRadius();
  69. float extraRadius = lightData.srcRadius / Math::tan(lightData.spotAngles.x * 0.5f);
  70. float coneRadius = Math::sin(lightData.spotAngles.x) * (internal->getAttenuationRadius() + extraRadius);
  71. lightGeometry.w = coneRadius;
  72. gPerLightParamDef.gLightGeometry.set(buffer, lightGeometry);
  73. const Transform& tfrm = internal->getTransform();
  74. Quaternion lightRotation(BsIdentity);
  75. lightRotation.lookRotation(-tfrm.getRotation().zAxis());
  76. Matrix4 transform = Matrix4::TRS(lightData.shiftedLightPosition, lightRotation, Vector3::ONE);
  77. gPerLightParamDef.gMatConeTransform.set(buffer, transform);
  78. }
  79. Vector3 RendererLight::getShiftedLightPosition() const
  80. {
  81. const Transform& tfrm = internal->getTransform();
  82. Vector3 direction = -tfrm.getRotation().zAxis();
  83. // Create position for fake attenuation for area spot lights (with disc center)
  84. if (internal->getType() == LightType::Spot)
  85. return tfrm.getPosition() - direction * (internal->getSourceRadius() / Math::tan(internal->getSpotAngle() * 0.5f));
  86. else
  87. return tfrm.getPosition();
  88. }
  89. GBufferParams::GBufferParams(GpuProgramType type, const SPtr<GpuParams>& gpuParams)
  90. : mParams(gpuParams)
  91. {
  92. if(mParams->hasTexture(type, "gGBufferATex"))
  93. mParams->getTextureParam(type, "gGBufferATex", mGBufferA);
  94. if(mParams->hasTexture(type, "gGBufferBTex"))
  95. mParams->getTextureParam(type, "gGBufferBTex", mGBufferB);
  96. if(mParams->hasTexture(type, "gGBufferCTex"))
  97. mParams->getTextureParam(type, "gGBufferCTex", mGBufferC);
  98. if(mParams->hasTexture(type, "gDepthBufferTex"))
  99. mParams->getTextureParam(type, "gDepthBufferTex", mGBufferDepth);
  100. if(mParams->hasSamplerState(type, "gDepthBufferSamp"))
  101. {
  102. GpuParamSampState samplerStateParam;
  103. mParams->getSamplerStateParam(type, "gDepthBufferSamp", samplerStateParam);
  104. SAMPLER_STATE_DESC desc;
  105. desc.minFilter = FO_POINT;
  106. desc.magFilter = FO_POINT;
  107. desc.mipFilter = FO_POINT;
  108. SPtr<SamplerState> ss = SamplerState::create(desc);
  109. samplerStateParam.set(ss);
  110. }
  111. }
  112. void GBufferParams::bind(const GBufferTextures& gbuffer)
  113. {
  114. mGBufferA.set(gbuffer.albedo);
  115. mGBufferB.set(gbuffer.normals);
  116. mGBufferC.set(gbuffer.roughMetal);
  117. mGBufferDepth.set(gbuffer.depth);
  118. }
  119. VisibleLightData::VisibleLightData()
  120. :mNumLights{}, mNumShadowedLights{}
  121. { }
  122. void VisibleLightData::update(const SceneInfo& sceneInfo, const RendererViewGroup& viewGroup)
  123. {
  124. const VisibilityInfo& visibility = viewGroup.getVisibilityInfo();
  125. for (UINT32 i = 0; i < (UINT32)LightType::Count; i++)
  126. mVisibleLights[i].clear();
  127. // Generate a list of lights and their GPU buffers
  128. UINT32 numDirLights = (UINT32)sceneInfo.directionalLights.size();
  129. for (UINT32 i = 0; i < numDirLights; i++)
  130. mVisibleLights[(UINT32)LightType::Directional].push_back(&sceneInfo.directionalLights[i]);
  131. UINT32 numRadialLights = (UINT32)sceneInfo.radialLights.size();
  132. for(UINT32 i = 0; i < numRadialLights; i++)
  133. {
  134. if (!visibility.radialLights[i])
  135. continue;
  136. mVisibleLights[(UINT32)LightType::Radial].push_back(&sceneInfo.radialLights[i]);
  137. }
  138. UINT32 numSpotLights = (UINT32)sceneInfo.spotLights.size();
  139. for (UINT32 i = 0; i < numSpotLights; i++)
  140. {
  141. if (!visibility.spotLights[i])
  142. continue;
  143. mVisibleLights[(UINT32)LightType::Spot].push_back(&sceneInfo.spotLights[i]);
  144. }
  145. for (UINT32 i = 0; i < (UINT32)LightType::Count; i++)
  146. mNumLights[i] = (UINT32)mVisibleLights[i].size();
  147. // Partition all visible lights so that unshadowed ones come first
  148. auto partition = [](Vector<const RendererLight*>& entries)
  149. {
  150. UINT32 numUnshadowed = 0;
  151. int first = -1;
  152. for (UINT32 i = 0; i < (UINT32)entries.size(); ++i)
  153. {
  154. if(entries[i]->internal->getCastsShadow())
  155. {
  156. first = i;
  157. break;
  158. }
  159. else
  160. ++numUnshadowed;
  161. }
  162. if(first != -1)
  163. {
  164. for(UINT32 i = first + 1; i < (UINT32)entries.size(); ++i)
  165. {
  166. if(!entries[i]->internal->getCastsShadow())
  167. {
  168. std::swap(entries[i], entries[first]);
  169. ++numUnshadowed;
  170. }
  171. }
  172. }
  173. return numUnshadowed;
  174. };
  175. for (UINT32 i = 0; i < (UINT32)LightType::Count; i++)
  176. mNumShadowedLights[i] = mNumLights[i] - partition(mVisibleLights[i]);
  177. // Generate light data to initialize the GPU buffer with
  178. mVisibleLightData.clear();
  179. for(auto& lightsPerType : mVisibleLights)
  180. {
  181. for(auto& entry : lightsPerType)
  182. {
  183. mVisibleLightData.push_back(LightData());
  184. entry->getParameters(mVisibleLightData.back());
  185. }
  186. }
  187. UINT32 size = (UINT32)mVisibleLightData.size() * sizeof(LightData);
  188. UINT32 curBufferSize;
  189. if (mLightBuffer != nullptr)
  190. curBufferSize = mLightBuffer->getSize();
  191. else
  192. curBufferSize = 0;
  193. if (size > curBufferSize || curBufferSize == 0)
  194. {
  195. // Allocate at least one block even if no lights, to avoid issues with null buffers
  196. UINT32 bufferSize = std::max(1, Math::ceilToInt(size / (float)BUFFER_INCREMENT)) * BUFFER_INCREMENT;
  197. GPU_BUFFER_DESC bufferDesc;
  198. bufferDesc.type = GBT_STRUCTURED;
  199. bufferDesc.elementCount = bufferSize / sizeof(LightData);
  200. bufferDesc.elementSize = sizeof(LightData);
  201. bufferDesc.format = BF_UNKNOWN;
  202. mLightBuffer = GpuBuffer::create(bufferDesc);
  203. }
  204. if (size > 0)
  205. mLightBuffer->writeData(0, size, mVisibleLightData.data(), BWT_DISCARD);
  206. }
  207. void VisibleLightData::gatherInfluencingLights(const Bounds& bounds,
  208. const LightData* (&output)[STANDARD_FORWARD_MAX_NUM_LIGHTS], Vector3I& counts) const
  209. {
  210. UINT32 outputIndices[STANDARD_FORWARD_MAX_NUM_LIGHTS];
  211. UINT32 numInfluencingLights = 0;
  212. UINT32 numDirLights = getNumDirLights();
  213. for(UINT32 i = 0; i < numDirLights; i++)
  214. {
  215. if (numInfluencingLights >= STANDARD_FORWARD_MAX_NUM_LIGHTS)
  216. return;
  217. outputIndices[numInfluencingLights] = i;
  218. numInfluencingLights++;
  219. }
  220. UINT32 pointLightOffset = numInfluencingLights;
  221. float distances[STANDARD_FORWARD_MAX_NUM_LIGHTS];
  222. for(UINT32 i = 0; i < STANDARD_FORWARD_MAX_NUM_LIGHTS; i++)
  223. distances[i] = std::numeric_limits<float>::max();
  224. // Note: This is an ad-hoc way of evaluating light influence, a better way might be wanted
  225. UINT32 numLights = (UINT32)mVisibleLightData.size();
  226. UINT32 furthestLightIdx = (UINT32)-1;
  227. float furthestDistance = 0.0f;
  228. for (UINT32 j = numDirLights; j < numLights; j++)
  229. {
  230. const LightData* lightData = &mVisibleLightData[j];
  231. Sphere lightSphere(lightData->position, lightData->attRadius);
  232. if (bounds.getSphere().intersects(lightSphere))
  233. {
  234. float distance = bounds.getSphere().getCenter().squaredDistance(lightData->position);
  235. // See where in the array can we fit the light
  236. if (numInfluencingLights < STANDARD_FORWARD_MAX_NUM_LIGHTS)
  237. {
  238. outputIndices[numInfluencingLights] = j;
  239. distances[numInfluencingLights] = distance;
  240. if (distance > furthestDistance)
  241. {
  242. furthestLightIdx = numInfluencingLights;
  243. furthestDistance = distance;
  244. }
  245. numInfluencingLights++;
  246. }
  247. else if (distance < furthestDistance)
  248. {
  249. outputIndices[furthestLightIdx] = j;
  250. distances[furthestLightIdx] = distance;
  251. furthestDistance = distance;
  252. for (UINT32 k = 0; k < STANDARD_FORWARD_MAX_NUM_LIGHTS; k++)
  253. {
  254. if (distances[k] > furthestDistance)
  255. {
  256. furthestDistance = distances[k];
  257. furthestLightIdx = k;
  258. }
  259. }
  260. }
  261. }
  262. }
  263. // Output actual light data, sorted by type
  264. counts = Vector3I(0, 0, 0);
  265. for(UINT32 i = 0; i < pointLightOffset; i++)
  266. {
  267. output[i] = &mVisibleLightData[outputIndices[i]];
  268. counts.x += 1;
  269. }
  270. UINT32 outputIdx = pointLightOffset;
  271. UINT32 spotLightIdx = getNumDirLights() + getNumRadialLights();
  272. for(UINT32 i = pointLightOffset; i < numInfluencingLights; i++)
  273. {
  274. bool isSpot = outputIndices[i] >= spotLightIdx;
  275. if(isSpot)
  276. continue;
  277. output[outputIdx++] = &mVisibleLightData[outputIndices[i]];
  278. counts.y += 1;
  279. }
  280. for(UINT32 i = pointLightOffset; i < numInfluencingLights; i++)
  281. {
  282. bool isSpot = outputIndices[i] >= spotLightIdx;
  283. if(!isSpot)
  284. continue;
  285. output[outputIdx++] = &mVisibleLightData[outputIndices[i]];
  286. counts.z += 1;
  287. }
  288. }
  289. const UINT32 TiledDeferredLightingMat::TILE_SIZE = 16;
  290. TiledDeferredLightingMat::TiledDeferredLightingMat()
  291. :mGBufferParams(GPT_COMPUTE_PROGRAM, mParams)
  292. {
  293. mSampleCount = mVariation.getUInt("MSAA_COUNT");
  294. mParams->getBufferParam(GPT_COMPUTE_PROGRAM, "gLights", mLightBufferParam);
  295. if (mParams->hasLoadStoreTexture(GPT_COMPUTE_PROGRAM, "gOutput"))
  296. mParams->getLoadStoreTextureParam(GPT_COMPUTE_PROGRAM, "gOutput", mOutputTextureParam);
  297. if (mParams->hasBuffer(GPT_COMPUTE_PROGRAM, "gOutput"))
  298. mParams->getBufferParam(GPT_COMPUTE_PROGRAM, "gOutput", mOutputBufferParam);
  299. if (mSampleCount > 1)
  300. mParams->getTextureParam(GPT_COMPUTE_PROGRAM, "gMSAACoverage", mMSAACoverageTexParam);
  301. mParamBuffer = gTiledLightingParamDef.createBuffer();
  302. mParams->setParamBlockBuffer("Params", mParamBuffer);
  303. }
  304. void TiledDeferredLightingMat::_initDefines(ShaderDefines& defines)
  305. {
  306. defines.set("TILE_SIZE", TILE_SIZE);
  307. }
  308. void TiledDeferredLightingMat::execute(const RendererView& view, const VisibleLightData& lightData,
  309. const GBufferTextures& gbuffer, const SPtr<Texture>& lightAccumTex, const SPtr<GpuBuffer>& lightAccumBuffer,
  310. const SPtr<Texture>& msaaCoverage)
  311. {
  312. const RendererViewProperties& viewProps = view.getProperties();
  313. const RenderSettings& settings = view.getRenderSettings();
  314. mLightBufferParam.set(lightData.getLightBuffer());
  315. UINT32 width = viewProps.viewRect.width;
  316. UINT32 height = viewProps.viewRect.height;
  317. Vector2I framebufferSize;
  318. framebufferSize[0] = width;
  319. framebufferSize[1] = height;
  320. gTiledLightingParamDef.gFramebufferSize.set(mParamBuffer, framebufferSize);
  321. if (!settings.enableLighting)
  322. {
  323. Vector4I lightCounts;
  324. lightCounts[0] = 0;
  325. lightCounts[1] = 0;
  326. lightCounts[2] = 0;
  327. lightCounts[3] = 0;
  328. Vector2I lightStrides;
  329. lightStrides[0] = 0;
  330. lightStrides[1] = 0;
  331. gTiledLightingParamDef.gLightCounts.set(mParamBuffer, lightCounts);
  332. gTiledLightingParamDef.gLightStrides.set(mParamBuffer, lightStrides);
  333. }
  334. else
  335. {
  336. Vector4I unshadowedLightCounts;
  337. unshadowedLightCounts[0] = lightData.getNumUnshadowedLights(LightType::Directional);
  338. unshadowedLightCounts[1] = lightData.getNumUnshadowedLights(LightType::Radial);
  339. unshadowedLightCounts[2] = lightData.getNumUnshadowedLights(LightType::Spot);
  340. unshadowedLightCounts[3] = unshadowedLightCounts[0] + unshadowedLightCounts[1] + unshadowedLightCounts[2];
  341. Vector4I lightCounts;
  342. lightCounts[0] = lightData.getNumLights(LightType::Directional);
  343. lightCounts[1] = lightData.getNumLights(LightType::Radial);
  344. lightCounts[2] = lightData.getNumLights(LightType::Spot);
  345. lightCounts[3] = lightCounts[0] + lightCounts[1] + lightCounts[2];
  346. Vector2I lightStrides;
  347. lightStrides[0] = lightCounts[0];
  348. lightStrides[1] = lightStrides[0] + lightCounts[1];
  349. if(!settings.enableShadows)
  350. gTiledLightingParamDef.gLightCounts.set(mParamBuffer, lightCounts);
  351. else
  352. gTiledLightingParamDef.gLightCounts.set(mParamBuffer, unshadowedLightCounts);
  353. gTiledLightingParamDef.gLightStrides.set(mParamBuffer, lightStrides);
  354. }
  355. mParamBuffer->flushToGPU();
  356. mGBufferParams.bind(gbuffer);
  357. mParams->setParamBlockBuffer("PerCamera", view.getPerViewBuffer());
  358. if (mSampleCount > 1)
  359. {
  360. mOutputBufferParam.set(lightAccumBuffer);
  361. mMSAACoverageTexParam.set(msaaCoverage);
  362. }
  363. else
  364. mOutputTextureParam.set(lightAccumTex);
  365. UINT32 numTilesX = (UINT32)Math::ceilToInt(width / (float)TILE_SIZE);
  366. UINT32 numTilesY = (UINT32)Math::ceilToInt(height / (float)TILE_SIZE);
  367. bind();
  368. RenderAPI::instance().dispatchCompute(numTilesX, numTilesY);
  369. }
  370. TiledDeferredLightingMat* TiledDeferredLightingMat::getVariation(UINT32 msaaCount)
  371. {
  372. switch(msaaCount)
  373. {
  374. case 1:
  375. return get(getVariation<1>());
  376. case 2:
  377. return get(getVariation<2>());
  378. case 4:
  379. return get(getVariation<4>());
  380. case 8:
  381. default:
  382. return get(getVariation<8>());
  383. }
  384. }
  385. FlatFramebufferToTextureParamDef gFlatFramebufferToTextureParamDef;
  386. FlatFramebufferToTextureMat::FlatFramebufferToTextureMat()
  387. {
  388. mParams->getBufferParam(GPT_FRAGMENT_PROGRAM, "gInput", mInputParam);
  389. mParamBuffer = gTiledLightingParamDef.createBuffer();
  390. mParams->setParamBlockBuffer("Params", mParamBuffer);
  391. }
  392. void FlatFramebufferToTextureMat::execute(const SPtr<GpuBuffer>& flatFramebuffer, const SPtr<Texture>& target)
  393. {
  394. const TextureProperties& props = target->getProperties();
  395. Vector2I framebufferSize;
  396. framebufferSize[0] = props.getWidth();
  397. framebufferSize[1] = props.getHeight();
  398. gFlatFramebufferToTextureParamDef.gFramebufferSize.set(mParamBuffer, framebufferSize);
  399. gFlatFramebufferToTextureParamDef.gSampleCount.set(mParamBuffer, props.getNumSamples());
  400. mParamBuffer->flushToGPU();
  401. mInputParam.set(flatFramebuffer);
  402. bind();
  403. Rect2 area(0.0f, 0.0f, (float)props.getWidth(), (float)props.getHeight());
  404. gRendererUtility().drawScreenQuad(area);
  405. }
  406. LightsParamDef gLightsParamDef;
  407. LightAndReflProbeParamsParamDef gLightAndReflProbeParamsParamDef;
  408. }}