renderProbeMgr.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "renderProbeMgr.h"
  23. #include "math/util/sphereMesh.h"
  24. #include "math/util/matrixSet.h"
  25. #include "renderInstance/renderDeferredMgr.h"
  26. #include "math/mPolyhedron.impl.h"
  27. #include "gfx/gfxTransformSaver.h"
  28. #include "lighting/advanced/advancedLightBinManager.h" //for ssao
  29. #include "gfx/gfxDebugEvent.h"
  30. #include "shaderGen/shaderGenVars.h"
  31. #include "materials/shaderData.h"
  32. #include "scene/reflectionManager.h"
  33. #include "postFx/postEffect.h"
  34. #include "T3D/lighting/reflectionProbe.h"
  35. #include "T3D/lighting/IBLUtilities.h"
  36. #include "T3D/Scene.h"
  37. //For our cameraQuery setup
  38. #include "T3D/gameTSCtrl.h"
  39. #define TORQUE_GFX_VISUAL_DEBUG //renderdoc debugging
  40. IMPLEMENT_CONOBJECT(RenderProbeMgr);
  41. ConsoleDocClass( RenderProbeMgr,
  42. "@brief This render bin handles the rendering of reflection probes to provide IBL\n"
  43. "lighting for PBR\n\n"
  44. "Probes when added to the scene, are registered to the Manager, and then during the steps\n"
  45. "leading up to the frame being rendered, the probes submit to the Manager that they are ready to be rendered\n"
  46. "resulting in them being added to the active list.\n"
  47. "When the manager is invoked to render, it processes the active probe list and finds the best probes based on\n"
  48. "settings like max probes per frame, probe score, etc to get the final list of probes to be submitted to the shader.\n\n"
  49. "@ingroup RenderBin\n" );
  50. RenderProbeMgr *RenderProbeMgr::smProbeManager = NULL;
  51. // This variable is a global toggle on if reflection probes should be rendered or not
  52. bool RenderProbeMgr::smRenderReflectionProbes = true;
  53. // This variable defines the maximum draw distance of a probe.
  54. F32 RenderProbeMgr::smMaxProbeDrawDistance = 100;
  55. // This variable defines the maximum number of probes that can be rendered in a single frame in deferred
  56. S32 RenderProbeMgr::smMaxProbesPerFrame = 8;
  57. S32 RenderProbeMgr::smProbeBakeResolution = 64;
  58. //
  59. //
  60. ProbeRenderInst::ProbeRenderInst() :
  61. mCubemapIndex(0),
  62. mProbeInfo(nullptr)
  63. {
  64. }
  65. ProbeRenderInst::~ProbeRenderInst()
  66. {
  67. }
  68. void ProbeRenderInst::set(const ProbeRenderInst *probe)
  69. {
  70. mCubemapIndex = probe->mCubemapIndex;
  71. mProbeInfo = probe->mProbeInfo;
  72. }
  73. //
  74. //
  75. ProbeShaderConstants::ProbeShaderConstants()
  76. : mInit(false),
  77. mShader(NULL),
  78. mProbePositionArraySC(NULL),
  79. mProbeRefPosArraySC(NULL),
  80. mRefScaleArraySC(NULL),
  81. mProbeConfigDataArraySC(NULL),
  82. mProbeSpecularCubemapArraySC(NULL),
  83. mProbeIrradianceCubemapArraySC(NULL),
  84. mProbeCountSC(NULL),
  85. mBRDFTextureMap(NULL),
  86. mSkylightCubemapIdxSC(NULL),
  87. mWorldToObjArraySC(NULL),
  88. mMaxProbeDrawDistanceSC(NULL)
  89. {
  90. }
  91. ProbeShaderConstants::~ProbeShaderConstants()
  92. {
  93. if (mShader.isValid())
  94. {
  95. mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
  96. mShader = NULL;
  97. }
  98. }
  99. void ProbeShaderConstants::init(GFXShader* shader)
  100. {
  101. if (mShader.getPointer() != shader)
  102. {
  103. if (mShader.isValid())
  104. mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
  105. mShader = shader;
  106. mShader->getReloadSignal().notify(this, &ProbeShaderConstants::_onShaderReload);
  107. }
  108. //Reflection Probes
  109. mProbePositionArraySC = shader->getShaderConstHandle(ShaderGenVars::probePositionArray);
  110. mProbeRefPosArraySC = shader->getShaderConstHandle(ShaderGenVars::probeRefPosArray);
  111. mRefScaleArraySC = shader->getShaderConstHandle(ShaderGenVars::refScaleArray);
  112. mWorldToObjArraySC = shader->getShaderConstHandle(ShaderGenVars::worldToObjArray);
  113. mProbeConfigDataArraySC = shader->getShaderConstHandle(ShaderGenVars::probeConfigDataArray);
  114. mProbeSpecularCubemapArraySC = shader->getShaderConstHandle(ShaderGenVars::specularCubemapAR);
  115. mProbeIrradianceCubemapArraySC = shader->getShaderConstHandle(ShaderGenVars::irradianceCubemapAR);
  116. mProbeCountSC = shader->getShaderConstHandle(ShaderGenVars::probeCount);
  117. mBRDFTextureMap = shader->getShaderConstHandle(ShaderGenVars::BRDFTextureMap);
  118. mSkylightCubemapIdxSC = shader->getShaderConstHandle(ShaderGenVars::skylightCubemapIdx);
  119. mMaxProbeDrawDistanceSC = shader->getShaderConstHandle(ShaderGenVars::maxProbeDrawDistance);
  120. mInit = true;
  121. }
  122. bool ProbeShaderConstants::isValid()
  123. {
  124. if (mProbePositionArraySC->isValid() ||
  125. mProbeConfigDataArraySC->isValid() ||
  126. mRefScaleArraySC->isValid() ||
  127. mProbeSpecularCubemapArraySC->isValid() ||
  128. mProbeIrradianceCubemapArraySC->isValid())
  129. return true;
  130. return false;
  131. }
  132. void ProbeShaderConstants::_onShaderReload()
  133. {
  134. if (mShader.isValid())
  135. init(mShader);
  136. }
  137. //
  138. //
  139. RenderProbeMgr::RenderProbeMgr()
  140. : RenderBinManager(RenderPassManager::RIT_Probes, 1.0f, 1.0f),
  141. mLastShader(nullptr),
  142. mLastConstants(nullptr),
  143. mHasSkylight(false),
  144. mSkylightCubemapIdx(-1),
  145. mCubeMapCount(0),
  146. mUseHDRCaptures(true)
  147. {
  148. mEffectiveProbeCount = 0;
  149. mMipCount = 0;
  150. mProbeArrayEffect = nullptr;
  151. smProbeManager = this;
  152. mCubeMapCount = 0;
  153. mCubeSlotCount = PROBE_ARRAY_SLOT_BUFFER_SIZE;
  154. for (U32 i = 0; i < PROBE_MAX_COUNT; i++)
  155. {
  156. mCubeMapSlots[i] = false;
  157. }
  158. }
  159. RenderProbeMgr::RenderProbeMgr(RenderInstType riType, F32 renderOrder, F32 processAddOrder)
  160. : RenderBinManager(riType, renderOrder, processAddOrder)
  161. {
  162. mCubeMapCount = 0;
  163. dMemset(mCubeMapSlots, false, sizeof(mCubeMapSlots));
  164. mCubeSlotCount = PROBE_ARRAY_SLOT_BUFFER_SIZE;
  165. mEffectiveProbeCount = 0;
  166. mHasSkylight = false;
  167. mSkylightCubemapIdx = -1;
  168. mLastConstants = nullptr;
  169. mMipCount = 0;
  170. mUseHDRCaptures = true;
  171. }
  172. RenderProbeMgr::~RenderProbeMgr()
  173. {
  174. mLastShader = NULL;
  175. mLastConstants = NULL;
  176. for (ProbeConstantMap::Iterator i = mConstantLookup.begin(); i != mConstantLookup.end(); i++)
  177. {
  178. if (i->value)
  179. SAFE_DELETE(i->value);
  180. }
  181. mConstantLookup.clear();
  182. }
  183. bool RenderProbeMgr::onAdd()
  184. {
  185. if (!Parent::onAdd())
  186. return false;
  187. mIrradianceArray = GFXCubemapArrayHandle(GFX->createCubemapArray());
  188. mPrefilterArray = GFXCubemapArrayHandle(GFX->createCubemapArray());
  189. U32 scaledSize = getProbeTexSize();
  190. //pre-allocate a few slots
  191. mIrradianceArray->init(PROBE_ARRAY_SLOT_BUFFER_SIZE, scaledSize, PROBE_FORMAT);
  192. mPrefilterArray->init(PROBE_ARRAY_SLOT_BUFFER_SIZE, scaledSize, PROBE_FORMAT);
  193. mCubeSlotCount = PROBE_ARRAY_SLOT_BUFFER_SIZE;
  194. String brdfTexturePath = GFXTextureManager::getBRDFTexturePath();
  195. if (!mBRDFTexture.set(brdfTexturePath, &GFXTexturePersistentProfile, "BRDFTexture"))
  196. {
  197. Con::errorf("RenderProbeMgr::onAdd: Failed to load BRDF Texture");
  198. return false;
  199. }
  200. return true;
  201. }
  202. void RenderProbeMgr::onRemove()
  203. {
  204. Parent::onRemove();
  205. }
  206. void RenderProbeMgr::initPersistFields()
  207. {
  208. Parent::initPersistFields();
  209. }
  210. void RenderProbeMgr::consoleInit()
  211. {
  212. Parent::consoleInit();
  213. // Vars for debug rendering while the RoadEditor is open, only used if smEditorOpen is true.
  214. Con::addVariable("$pref::maxProbeDrawDistance", TypeF32, &RenderProbeMgr::smMaxProbeDrawDistance, "Max distance for reflection probes to render.\n");
  215. Con::addVariable("$pref::MaxProbesPerFrame", TypeS32, &RenderProbeMgr::smMaxProbesPerFrame, "Max number of Environment Probes that can be rendered per-frame.\n");
  216. Con::addVariable("$pref::ReflectionProbes::BakeResolution", TypeS32, &RenderProbeMgr::smProbeBakeResolution, "");
  217. }
  218. //=============================================================================
  219. // Utility functions for processing and setting up the probes for rendering
  220. //=============================================================================
  221. S32 QSORT_CALLBACK RenderProbeMgr::_probeScoreCmp(const ProbeRenderInst* a, const ProbeRenderInst* b)
  222. {
  223. F32 diff = a->mProbeInfo->mScore - b->mProbeInfo->mScore;
  224. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  225. }
  226. void RenderProbeMgr::getBestProbes(const Point3F& objPosition, ProbeDataSet* probeDataSet)
  227. {
  228. PROFILE_SCOPE(ProbeManager_getBestProbes);
  229. //Array rendering
  230. U32 probeCount = mActiveProbes.size();
  231. Vector<S8> bestPickProbes;
  232. bestPickProbes.setSize(probeDataSet->maxProbeCount);
  233. bestPickProbes.fill(-1);
  234. mHasSkylight = false;
  235. probeDataSet->skyLightIdx = -1;
  236. probeDataSet->effectiveProbeCount = 0;
  237. for (U32 i = 0; i < probeCount; i++)
  238. {
  239. //Check if we've already got a skylight. If we do and we've otherwise filled to our max amounto of probes alloewed, then bail
  240. if (mHasSkylight && probeDataSet->effectiveProbeCount >= probeDataSet->maxProbeCount)
  241. break;
  242. const ProbeRenderInst& curEntry = mActiveProbes[i];
  243. //Obviously, if the probe is marked as not enabled, we skip
  244. if (!curEntry.mProbeInfo->mIsEnabled)
  245. continue;
  246. if (curEntry.mProbeInfo->mProbeShapeType != ReflectionProbe::ProbeInfo::Skylight)
  247. {
  248. if (probeDataSet->effectiveProbeCount < probeDataSet->maxProbeCount)
  249. {
  250. bestPickProbes[probeDataSet->effectiveProbeCount] = i;
  251. probeDataSet->effectiveProbeCount++;
  252. }
  253. }
  254. else
  255. {
  256. probeDataSet->skyLightIdx = curEntry.mCubemapIndex;
  257. mHasSkylight = true;
  258. }
  259. }
  260. //If we, for whatever reason, have nothing, bail now
  261. if (mHasSkylight == false && probeDataSet->effectiveProbeCount == 0)
  262. return;
  263. //Grab our best probe picks
  264. for (U32 i = 0; i < bestPickProbes.size(); i++)
  265. {
  266. if (bestPickProbes[i] == -1)
  267. continue;
  268. const ProbeRenderInst& curEntry = mActiveProbes[bestPickProbes[i]];
  269. probeDataSet->probeConfigArray[i] = Point4F(curEntry.mProbeInfo->mProbeShapeType,
  270. curEntry.mProbeInfo->mRadius,
  271. curEntry.mProbeInfo->mAtten,
  272. curEntry.mCubemapIndex);
  273. MatrixF p2A = curEntry.mProbeInfo->mTransform;
  274. probeDataSet->probeWorldToObjArray[i] = p2A;
  275. p2A.inverse();
  276. probeDataSet->refScaleArray[i] = curEntry.mProbeInfo->mProbeRefScale / (p2A.getScale()*2);
  277. Point3F probePos = curEntry.mProbeInfo->mObject->getPosition();
  278. Point3F refPos = probePos + curEntry.mProbeInfo->mProbeRefOffset * probeDataSet->refScaleArray[i].asPoint3F();
  279. probeDataSet->probePositionArray[i] = Point4F(probePos.x, probePos.y, probePos.z, 0);
  280. probeDataSet->probeRefPositionArray[i] = Point4F(refPos.x, refPos.y, refPos.z, 0);
  281. }
  282. }
  283. void RenderProbeMgr::registerProbe(ReflectionProbe::ProbeInfo* newProbe)
  284. {
  285. //Can't have over the probe limit
  286. if (mRegisteredProbes.size() + 1 >= PROBE_MAX_COUNT)
  287. return;
  288. ProbeRenderInst newProbeRenderInst;
  289. newProbeRenderInst.mProbeInfo = newProbe;
  290. const U32 cubeIndex = _findNextEmptyCubeSlot();
  291. if (cubeIndex == INVALID_CUBE_SLOT)
  292. {
  293. Con::warnf("RenderProbeMgr::registerProbe() - Invalid cubemap slot.");
  294. return;
  295. }
  296. //check if we need to resize the cubemap array
  297. if (cubeIndex >= mCubeSlotCount)
  298. {
  299. //alloc temp array handles
  300. GFXCubemapArrayHandle irr = GFXCubemapArrayHandle(GFX->createCubemapArray());
  301. GFXCubemapArrayHandle prefilter = GFXCubemapArrayHandle(GFX->createCubemapArray());
  302. U32 scaledSize = getProbeTexSize();
  303. irr->init(mCubeSlotCount + PROBE_ARRAY_SLOT_BUFFER_SIZE, scaledSize, PROBE_FORMAT);
  304. prefilter->init(mCubeSlotCount + PROBE_ARRAY_SLOT_BUFFER_SIZE, scaledSize, PROBE_FORMAT);
  305. mIrradianceArray->copyTo(irr);
  306. mPrefilterArray->copyTo(prefilter);
  307. //assign the temp handles to the new ones, this will destroy the old ones as well
  308. mIrradianceArray = irr;
  309. mPrefilterArray = prefilter;
  310. mCubeSlotCount += PROBE_ARRAY_SLOT_BUFFER_SIZE;
  311. }
  312. newProbeRenderInst.mCubemapIndex = cubeIndex;
  313. //mark cubemap slot as taken
  314. mCubeMapSlots[cubeIndex] = true;
  315. mCubeMapCount++;
  316. mRegisteredProbes.push_back(newProbeRenderInst);
  317. #ifdef TORQUE_DEBUG
  318. Con::warnf("RenderProbeMgr::registerProbe() - Registered probe %u to cubeIndex %u", newProbe->mObject->getId(), cubeIndex);
  319. #endif
  320. }
  321. void RenderProbeMgr::unregisterProbe(ReflectionProbe::ProbeInfo* probeInfo)
  322. {
  323. ProbeRenderInst* probe = findProbeInst(probeInfo);
  324. if (probe == nullptr)
  325. return;
  326. if (probe->mCubemapIndex == INVALID_CUBE_SLOT)
  327. return;
  328. //mark cubemap slot as available now
  329. mCubeMapSlots[probe->mCubemapIndex] = false;
  330. mCubeMapCount--;
  331. mRegisteredProbes.erase(probe);
  332. }
  333. void RenderProbeMgr::submitProbe(ReflectionProbe::ProbeInfo* probe)
  334. {
  335. ProbeRenderInst* probeInst = findProbeInst(probe);
  336. mActiveProbes.push_back(*probeInst);
  337. }
  338. PostEffect* RenderProbeMgr::getProbeArrayEffect()
  339. {
  340. if (!mProbeArrayEffect)
  341. {
  342. mProbeArrayEffect = dynamic_cast<PostEffect*>(Sim::findObject("reflectionProbeArrayPostFX"));
  343. if (!mProbeArrayEffect)
  344. return nullptr;
  345. mProbeArrayEffect->setShaderConst("$numProbes", (S32)0);
  346. mProbeArrayEffect->setShaderConst("$skylightCubemapIdx", (S32)-1);
  347. mProbeArrayEffect->setShaderConst("$cubeMips", (float)0);
  348. mProbeArrayEffect->setShaderConst("$maxProbeDrawDistance", smMaxProbeDrawDistance);
  349. }
  350. return mProbeArrayEffect;
  351. }
  352. U32 RenderProbeMgr::getProbeTexSize()
  353. {
  354. U32 scaledSize = RenderProbeMgr::smProbeBakeResolution;
  355. U32 downscalePower = 0;// GFXTextureManager::smTextureReductionLevel;
  356. if (downscalePower != 0)
  357. {
  358. // Otherwise apply the appropriate scale...
  359. scaledSize >>= downscalePower;
  360. }
  361. return scaledSize;
  362. }
  363. void RenderProbeMgr::updateProbeTexture(ReflectionProbe::ProbeInfo* probeInfo)
  364. {
  365. //If we don't have a registered probe, there's no point in updating the cubemap array for it
  366. ProbeRenderInst* probe = findProbeInst(probeInfo);
  367. if (probe == nullptr)
  368. return;
  369. U32 scaledSize = getProbeTexSize();
  370. //Some basic sanity checking that we have valid cubemaps to work with
  371. if (probeInfo->mIrradianceCubemap.isNull() || !probeInfo->mIrradianceCubemap->isInitialized() ||
  372. probeInfo->mIrradianceCubemap->getSize() != scaledSize)
  373. {
  374. Con::errorf("RenderProbeMgr::updateProbeTexture() - tried to update a probe's texture with an invalid or uninitialized irradiance map!");
  375. return;
  376. }
  377. if (probeInfo->mPrefilterCubemap.isNull() || !probeInfo->mPrefilterCubemap->isInitialized() ||
  378. probeInfo->mPrefilterCubemap->getSize() != scaledSize)
  379. {
  380. Con::errorf("RenderProbeMgr::updateProbeTexture() - tried to update a probe's texture with an invalid or uninitialized specular map!");
  381. return;
  382. }
  383. //Run the update on the array pair with the probe's cubemaps and index
  384. const U32 cubeIndex = probe->mCubemapIndex;
  385. mIrradianceArray->updateTexture(probeInfo->mIrradianceCubemap, cubeIndex);
  386. mPrefilterArray->updateTexture(probeInfo->mPrefilterCubemap, cubeIndex);
  387. #ifdef TORQUE_DEBUG
  388. Con::warnf("UpdatedProbeTexture - probe id: %u on cubeIndex %u, Irrad validity: %d, Prefilter validity: %d", probeInfo->mObject->getId(), cubeIndex,
  389. probeInfo->mIrradianceCubemap->isInitialized(), probeInfo->mPrefilterCubemap->isInitialized());
  390. #endif
  391. }
  392. void RenderProbeMgr::reloadTextures()
  393. {
  394. U32 probeCount = mRegisteredProbes.size();
  395. for (U32 i = 0; i < probeCount; i++)
  396. {
  397. updateProbeTexture(mRegisteredProbes[i].mProbeInfo);
  398. }
  399. }
  400. void RenderProbeMgr::preBake()
  401. {
  402. Con::setVariable("$Probes::Capturing", "1");
  403. mRenderMaximumNumOfLights = AdvancedLightBinManager::smMaximumNumOfLights;
  404. mRenderUseLightFade = AdvancedLightBinManager::smUseLightFade;
  405. AdvancedLightBinManager::smMaximumNumOfLights = -1;
  406. AdvancedLightBinManager::smUseLightFade = false;
  407. }
  408. void RenderProbeMgr::postBake()
  409. {
  410. Con::setVariable("$Probes::Capturing", "0");
  411. AdvancedLightBinManager::smMaximumNumOfLights = mRenderMaximumNumOfLights;
  412. AdvancedLightBinManager::smUseLightFade = mRenderUseLightFade;
  413. }
  414. void RenderProbeMgr::bakeProbe(ReflectionProbe* probe)
  415. {
  416. GFXDEBUGEVENT_SCOPE(RenderProbeMgr_Bake, ColorI::WHITE);
  417. Con::warnf("RenderProbeMgr::bakeProbe() - Beginning bake!");
  418. U32 startMSTime = Platform::getRealMilliseconds();
  419. preBake();
  420. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  421. U32 resolution = Con::getIntVariable("$pref::ReflectionProbes::BakeResolution", 64);
  422. U32 prefilterMipLevels = mLog2(F32(resolution)) + 1;
  423. bool renderWithProbes = Con::getIntVariable("$pref::ReflectionProbes::RenderWithProbes", false);
  424. ReflectionProbe* clientProbe = nullptr;
  425. if (probe->isServerObject())
  426. clientProbe = static_cast<ReflectionProbe*>(probe->getClientObject());
  427. else
  428. return;
  429. if (clientProbe == nullptr)
  430. return;
  431. String probePrefilterPath = clientProbe->getPrefilterMapPath();
  432. String probeIrradPath = clientProbe->getIrradianceMapPath();
  433. if (clientProbe->mReflectionModeType != ReflectionProbe::DynamicCubemap)
  434. {
  435. //Prep our bake path
  436. if (probePrefilterPath.isEmpty() || probeIrradPath.isEmpty())
  437. {
  438. Con::errorf("RenderProbeMgr::bake() - Unable to bake our captures because probe doesn't have a path set");
  439. return;
  440. }
  441. }
  442. // Save the current transforms so we can restore
  443. // it for child control rendering below.
  444. GFXTransformSaver saver;
  445. bool probeRenderState = RenderProbeMgr::smRenderReflectionProbes;
  446. F32 farPlane = 1000.0f;
  447. ReflectorDesc reflDesc;
  448. reflDesc.texSize = resolution;
  449. reflDesc.farDist = farPlane;
  450. reflDesc.detailAdjust = 1;
  451. reflDesc.objectTypeMask = probe->mProbeShapeType == ReflectionProbe::ProbeInfo::Skylight ? SKYLIGHT_CAPTURE_TYPEMASK : REFLECTION_PROBE_CAPTURE_TYPEMASK;
  452. CubeReflector cubeRefl;
  453. cubeRefl.registerReflector(probe, &reflDesc);
  454. ReflectParams reflParams;
  455. //need to get the query somehow. Likely do some sort of get function to fetch from the guiTSControl that's active
  456. CameraQuery query; //need to get the last cameraQuery
  457. query.fov = 90; //90 degree slices for each of the 6 sides
  458. query.nearPlane = 0.1f;
  459. query.farPlane = farPlane;
  460. query.headMatrix = MatrixF();
  461. query.cameraMatrix = clientProbe->getTransform();
  462. Frustum culler;
  463. culler.set(false,
  464. query.fov,
  465. 1.0f,
  466. query.nearPlane,
  467. query.farPlane,
  468. query.cameraMatrix);
  469. S32 stereoTarget = GFX->getCurrentStereoTarget();
  470. Point2I maxRes(2048, 2048); //basically a boundary so we don't go over this and break stuff
  471. reflParams.culler = culler;
  472. reflParams.eyeId = stereoTarget;
  473. reflParams.query = &query;
  474. reflParams.startOfUpdateMs = startMSTime;
  475. reflParams.viewportExtent = maxRes;
  476. if (!renderWithProbes)
  477. RenderProbeMgr::smRenderReflectionProbes = false;
  478. GFXFormat reflectFormat;
  479. if (mUseHDRCaptures)
  480. reflectFormat = GFXFormatR16G16B16A16F;
  481. else
  482. reflectFormat = GFXFormatR8G8B8A8;
  483. const GFXFormat oldRefFmt = REFLECTMGR->getReflectFormat();
  484. REFLECTMGR->setReflectFormat(reflectFormat);
  485. cubeRefl.updateReflection(reflParams, clientProbe->getTransform().getPosition() + clientProbe->mProbeRefOffset);
  486. //Now, save out the maps
  487. //create irridiance cubemap
  488. if (cubeRefl.getCubemap())
  489. {
  490. //Just to ensure we're prepped for the generation
  491. clientProbe->createClientResources();
  492. //Prep it with whatever resolution we've dictated for our bake
  493. clientProbe->mIrridianceMap->mCubemap->initDynamic(resolution, reflectFormat);
  494. clientProbe->mPrefilterMap->mCubemap->initDynamic(resolution, reflectFormat);
  495. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  496. IBLUtilities::GenerateIrradianceMap(renderTarget, cubeRefl.getCubemap(), clientProbe->mIrridianceMap->mCubemap);
  497. IBLUtilities::GeneratePrefilterMap(renderTarget, cubeRefl.getCubemap(), prefilterMipLevels, clientProbe->mPrefilterMap->mCubemap);
  498. U32 endMSTime = Platform::getRealMilliseconds();
  499. F32 diffTime = F32(endMSTime - startMSTime);
  500. Con::warnf("RenderProbeMgr::bake() - Finished Capture! Took %g milliseconds", diffTime);
  501. Con::warnf("RenderProbeMgr::bake() - Beginning save now!");
  502. IBLUtilities::SaveCubeMap(clientProbe->getIrradianceMapPath(), clientProbe->mIrridianceMap->mCubemap);
  503. IBLUtilities::SaveCubeMap(clientProbe->getPrefilterMapPath(), clientProbe->mPrefilterMap->mCubemap);
  504. }
  505. else
  506. {
  507. Con::errorf("RenderProbeMgr::bake() - Didn't generate a valid scene capture cubemap, unable to generate prefilter and irradiance maps!");
  508. }
  509. if (!renderWithProbes)
  510. RenderProbeMgr::smRenderReflectionProbes = probeRenderState;
  511. postBake();
  512. cubeRefl.unregisterReflector();
  513. U32 endMSTime = Platform::getRealMilliseconds();
  514. F32 diffTime = F32(endMSTime - startMSTime);
  515. probe->setMaskBits(-1);
  516. Con::warnf("RenderProbeMgr::bake() - Finished bake! Took %g milliseconds", diffTime);
  517. REFLECTMGR->setReflectFormat(oldRefFmt);
  518. }
  519. void RenderProbeMgr::bakeProbes()
  520. {
  521. Vector<ReflectionProbe*> probes;
  522. Scene::getRootScene()->findObjectByType<ReflectionProbe>(probes);
  523. for (U32 i = 0; i < probes.size(); i++)
  524. {
  525. if (probes[i]->isClientObject())
  526. continue;
  527. bakeProbe(probes[i]);
  528. }
  529. }
  530. //=============================================================================
  531. // Forward Rendering functions
  532. //=============================================================================
  533. ProbeShaderConstants* RenderProbeMgr::getProbeShaderConstants(GFXShaderConstBuffer* buffer)
  534. {
  535. if (!buffer)
  536. return NULL;
  537. PROFILE_SCOPE(ProbeManager_GetProbeShaderConstants);
  538. GFXShader* shader = buffer->getShader();
  539. // Check to see if this is the same shader, we'll get hit repeatedly by
  540. // the same one due to the render bin loops.
  541. if (mLastShader.getPointer() != shader)
  542. {
  543. ProbeConstantMap::Iterator iter = mConstantLookup.find(shader);
  544. if (iter != mConstantLookup.end())
  545. {
  546. mLastConstants = iter->value;
  547. }
  548. else
  549. {
  550. ProbeShaderConstants* psc = new ProbeShaderConstants();
  551. mConstantLookup[shader] = psc;
  552. mLastConstants = psc;
  553. }
  554. // Set our new shader
  555. mLastShader = shader;
  556. }
  557. /*if (mLastConstants == nullptr)
  558. {
  559. ProbeShaderConstants* psc = new ProbeShaderConstants();
  560. mConstantLookup[shader] = psc;
  561. mLastConstants = psc;
  562. }*/
  563. // Make sure that our current lighting constants are initialized
  564. if (mLastConstants && !mLastConstants->mInit)
  565. mLastConstants->init(shader);
  566. return mLastConstants;
  567. }
  568. void RenderProbeMgr::setProbeInfo(ProcessedMaterial *pmat,
  569. const Material *mat,
  570. const SceneData &sgData,
  571. const SceneRenderState *state,
  572. U32 pass,
  573. GFXShaderConstBuffer *shaderConsts)
  574. {
  575. // Skip this if we're rendering from the deferred bin.
  576. if (sgData.binType == SceneData::DeferredBin)
  577. return;
  578. PROFILE_SCOPE(ProbeManager_setProbeInfo);
  579. ProbeShaderConstants *psc = getProbeShaderConstants(shaderConsts);
  580. // NOTE: If you encounter a crash from this point forward
  581. // while setting a shader constant its probably because the
  582. // mConstantLookup has bad shaders/constants in it.
  583. //
  584. // This is a known crash bug that can occur if materials/shaders
  585. // are reloaded and the light manager is not reset.
  586. //
  587. // We should look to fix this by clearing the table.
  588. MatrixSet matSet = state->getRenderPass()->getMatrixSet();
  589. // Update the forward shading light constants.
  590. _update4ProbeConsts(sgData, matSet, psc, shaderConsts);
  591. }
  592. void RenderProbeMgr::setupSGData(SceneData& data, const SceneRenderState* state, LightInfo* light)
  593. {
  594. //ensure they're sorted for forward rendering
  595. mActiveProbes.sort(_probeScoreCmp);
  596. }
  597. void RenderProbeMgr::_update4ProbeConsts(const SceneData& sgData,
  598. MatrixSet& matSet,
  599. ProbeShaderConstants* probeShaderConsts,
  600. GFXShaderConstBuffer* shaderConsts)
  601. {
  602. PROFILE_SCOPE(ProbeManager_Update4ProbeConsts);
  603. // Skip over gathering lights if we don't have to!
  604. if (probeShaderConsts->isValid())
  605. {
  606. PROFILE_SCOPE(ProbeManager_Update4ProbeConsts_setProbes);
  607. const U32 MAX_FORWARD_PROBES = 4;
  608. ProbeDataSet probeSet(MAX_FORWARD_PROBES);
  609. matSet.restoreSceneViewProjection();
  610. getBestProbes(sgData.objTrans->getPosition(), &probeSet);
  611. static AlignedArray<Point4F> probePositionAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  612. static AlignedArray<Point4F> refScaleAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  613. static AlignedArray<Point4F> probeRefPositionAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  614. static AlignedArray<Point4F> probeConfigAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  615. for (U32 i = 0; i < probeSet.maxProbeCount; i++)
  616. {
  617. probePositionAlignedArray[i] = probeSet.probePositionArray[i];
  618. probeRefPositionAlignedArray[i] = probeSet.probeRefPositionArray[i];
  619. refScaleAlignedArray[i] = probeSet.refScaleArray[i];
  620. probeConfigAlignedArray[i] = probeSet.probeConfigArray[i];
  621. }
  622. if (probeSet.effectiveProbeCount != 0)
  623. {
  624. shaderConsts->setSafe(probeShaderConsts->mProbeCountSC, (S32)probeSet.effectiveProbeCount);
  625. shaderConsts->setSafe(probeShaderConsts->mProbePositionArraySC, probePositionAlignedArray);
  626. shaderConsts->setSafe(probeShaderConsts->mProbeRefPosArraySC, probeRefPositionAlignedArray);
  627. if (probeShaderConsts->isValid())
  628. shaderConsts->set(probeShaderConsts->mWorldToObjArraySC, probeSet.probeWorldToObjArray.address(), probeSet.probeWorldToObjArray.size(), GFXSCT_Float4x4);
  629. shaderConsts->setSafe(probeShaderConsts->mRefScaleArraySC, refScaleAlignedArray);
  630. shaderConsts->setSafe(probeShaderConsts->mProbeConfigDataArraySC, probeConfigAlignedArray);
  631. }
  632. if (probeShaderConsts->mBRDFTextureMap->getSamplerRegister() != -1 && mBRDFTexture.isValid())
  633. GFX->setTexture(probeShaderConsts->mBRDFTextureMap->getSamplerRegister(), mBRDFTexture);
  634. shaderConsts->setSafe(probeShaderConsts->mSkylightCubemapIdxSC, (float)probeSet.skyLightIdx);
  635. if (probeShaderConsts->mProbeSpecularCubemapArraySC->getSamplerRegister() != -1)
  636. GFX->setCubeArrayTexture(probeShaderConsts->mProbeSpecularCubemapArraySC->getSamplerRegister(), mPrefilterArray);
  637. if (probeShaderConsts->mProbeIrradianceCubemapArraySC->getSamplerRegister() != -1)
  638. GFX->setCubeArrayTexture(probeShaderConsts->mProbeIrradianceCubemapArraySC->getSamplerRegister(), mIrradianceArray);
  639. shaderConsts->setSafe(probeShaderConsts->mMaxProbeDrawDistanceSC, smMaxProbeDrawDistance);
  640. }
  641. }
  642. //=============================================================================
  643. // Deferred Rendering Functions
  644. //=============================================================================
  645. void RenderProbeMgr::_setupPerFrameParameters(const SceneRenderState* state)
  646. {
  647. PROFILE_SCOPE(RenderProbeMgr_SetupPerFrameParameters);
  648. mProbeData = ProbeDataSet(smMaxProbesPerFrame);
  649. getBestProbes(state->getCameraPosition(), &mProbeData);
  650. }
  651. void RenderProbeMgr::render( SceneRenderState *state )
  652. {
  653. if (getProbeArrayEffect() == nullptr)
  654. {
  655. mActiveProbes.clear();
  656. return;
  657. }
  658. GFXDEBUGEVENT_SCOPE(RenderProbeMgr_render, ColorI::WHITE);
  659. //Sort the active probes
  660. mActiveProbes.sort(_probeScoreCmp);
  661. // Initialize and set the per-frame data
  662. _setupPerFrameParameters(state);
  663. // Early out if nothing to draw.
  664. if ((!RenderProbeMgr::smRenderReflectionProbes && !dStrcmp(Con::getVariable("$Probes::Capturing", "0"), "1")) || (!mHasSkylight && mProbeData.effectiveProbeCount == 0))
  665. {
  666. getProbeArrayEffect()->setSkip(true);
  667. mActiveProbes.clear();
  668. return;
  669. }
  670. GFXTransformSaver saver;
  671. //Visualization
  672. String useDebugAtten = Con::getVariable("$Probes::showAttenuation", "0");
  673. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_ATTENUATION", useDebugAtten);
  674. String useDebugSpecCubemap = Con::getVariable("$Probes::showSpecularCubemaps", "0");
  675. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_SPECCUBEMAP", useDebugSpecCubemap);
  676. String useDebugDiffuseCubemap = Con::getVariable("$Probes::showDiffuseCubemaps", "0");
  677. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_DIFFCUBEMAP", useDebugDiffuseCubemap);
  678. String useDebugContrib = Con::getVariable("$Probes::showProbeContrib", "0");
  679. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_CONTRIB", useDebugContrib);
  680. if(mHasSkylight && mProbeData.effectiveProbeCount == 0)
  681. mProbeArrayEffect->setShaderMacro("SKYLIGHT_ONLY", "1");
  682. else
  683. mProbeArrayEffect->setShaderMacro("SKYLIGHT_ONLY", "0");
  684. String probePerFrame = Con::getVariable("$pref::MaxProbesPerFrame", "8");
  685. mProbeArrayEffect->setShaderMacro("MAX_PROBES", probePerFrame);
  686. String probeCapturing = Con::getVariable("$Probes::Capturing", "0");
  687. mProbeArrayEffect->setShaderMacro("CAPTURING", probeCapturing);
  688. //ssao mask
  689. if (AdvancedLightBinManager::smUseSSAOMask)
  690. {
  691. //find ssaoMask
  692. NamedTexTargetRef ssaoTarget = NamedTexTarget::find("ssaoMask");
  693. GFXTextureObject* pTexObj = ssaoTarget->getTexture();
  694. if (pTexObj)
  695. {
  696. mProbeArrayEffect->setShaderMacro("USE_SSAO_MASK");
  697. mProbeArrayEffect->setTexture(6, pTexObj);
  698. }
  699. }
  700. else
  701. {
  702. mProbeArrayEffect->setTexture(6, GFXTexHandle(NULL));
  703. }
  704. mProbeArrayEffect->setTexture(3, mBRDFTexture);
  705. mProbeArrayEffect->setCubemapArrayTexture(4, mPrefilterArray);
  706. mProbeArrayEffect->setCubemapArrayTexture(5, mIrradianceArray);
  707. mProbeArrayEffect->setShaderConst("$numProbes", (S32)mProbeData.effectiveProbeCount);
  708. mProbeArrayEffect->setShaderConst("$skylightCubemapIdx", (S32)mProbeData.skyLightIdx);
  709. mProbeArrayEffect->setShaderConst("$cubeMips", (float)mPrefilterArray->getMipMapLevels());
  710. //also set up some colors
  711. Vector<Point4F> contribColors;
  712. contribColors.setSize(mProbeData.effectiveProbeCount);
  713. if (mProbeData.effectiveProbeCount != 0)
  714. {
  715. if (useDebugContrib == String("1"))
  716. {
  717. MRandomLCG RandomGen;
  718. RandomGen.setSeed(mProbeData.effectiveProbeCount);
  719. for (U32 i = 0; i < mProbeData.effectiveProbeCount; i++)
  720. {
  721. //we're going to cheat here a little for consistent debugging behavior. The first 3 probes will always have R G and then B for their colors, every other will be random
  722. if (i == 0)
  723. contribColors[i] = Point4F(1, 0, 0, 1);
  724. else if (i == 1)
  725. contribColors[i] = Point4F(0, 1, 0, 1);
  726. else if (i == 2)
  727. contribColors[i] = Point4F(0, 0, 1, 1);
  728. else
  729. contribColors[i] = Point4F(RandomGen.randF(0, 1), RandomGen.randF(0, 1), RandomGen.randF(0, 1), 1);
  730. }
  731. }
  732. }
  733. mProbeArrayEffect->setShaderConst("$probeContribColors", contribColors);
  734. mProbeArrayEffect->setShaderConst("$probePosArray", mProbeData.probePositionArray);
  735. mProbeArrayEffect->setShaderConst("$refPosArray", mProbeData.probeRefPositionArray);
  736. mProbeArrayEffect->setShaderConst("$worldToObjArray", mProbeData.probeWorldToObjArray);
  737. mProbeArrayEffect->setShaderConst("$refScaleArray", mProbeData.refScaleArray);
  738. mProbeArrayEffect->setShaderConst("$probeConfigData", mProbeData.probeConfigArray);
  739. mProbeArrayEffect->setShaderConst("$maxProbeDrawDistance", smMaxProbeDrawDistance);
  740. // Make sure the effect is gonna render.
  741. getProbeArrayEffect()->setSkip(false);
  742. }
  743. //=============================================================================
  744. // Console functions
  745. //=============================================================================
  746. DefineEngineMethod(RenderProbeMgr, bakeProbe, void, (ReflectionProbe* probe), (nullAsType< ReflectionProbe*>()),
  747. "@brief Bakes the cubemaps for a reflection probe\n\n.")
  748. {
  749. if(probe != nullptr)
  750. object->bakeProbe(probe);
  751. }
  752. DefineEngineMethod(RenderProbeMgr, bakeProbes, void, (),, "@brief Iterates over all reflection probes in the scene and bakes their cubemaps\n\n.")
  753. {
  754. object->bakeProbes();
  755. }