renderProbeMgr.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  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. //pre-allocate a few slots
  190. mIrradianceArray->init(PROBE_ARRAY_SLOT_BUFFER_SIZE, RenderProbeMgr::smProbeBakeResolution, PROBE_FORMAT);
  191. mPrefilterArray->init(PROBE_ARRAY_SLOT_BUFFER_SIZE, RenderProbeMgr::smProbeBakeResolution, PROBE_FORMAT);
  192. mCubeSlotCount = PROBE_ARRAY_SLOT_BUFFER_SIZE;
  193. String brdfTexturePath = GFXTextureManager::getBRDFTexturePath();
  194. if (!mBRDFTexture.set(brdfTexturePath, &GFXTexturePersistentProfile, "BRDFTexture"))
  195. {
  196. Con::errorf("RenderProbeMgr::onAdd: Failed to load BRDF Texture");
  197. return false;
  198. }
  199. return true;
  200. }
  201. void RenderProbeMgr::onRemove()
  202. {
  203. Parent::onRemove();
  204. }
  205. void RenderProbeMgr::initPersistFields()
  206. {
  207. Parent::initPersistFields();
  208. }
  209. void RenderProbeMgr::consoleInit()
  210. {
  211. Parent::consoleInit();
  212. // Vars for debug rendering while the RoadEditor is open, only used if smEditorOpen is true.
  213. Con::addVariable("$pref::maxProbeDrawDistance", TypeF32, &RenderProbeMgr::smMaxProbeDrawDistance, "Max distance for reflection probes to render.\n");
  214. Con::addVariable("$pref::MaxProbesPerFrame", TypeS32, &RenderProbeMgr::smMaxProbesPerFrame, "Max number of Environment Probes that can be rendered per-frame.\n");
  215. Con::addVariable("$pref::ReflectionProbes::BakeResolution", TypeS32, &RenderProbeMgr::smProbeBakeResolution, "");
  216. }
  217. //=============================================================================
  218. // Utility functions for processing and setting up the probes for rendering
  219. //=============================================================================
  220. S32 QSORT_CALLBACK RenderProbeMgr::_probeScoreCmp(const ProbeRenderInst* a, const ProbeRenderInst* b)
  221. {
  222. F32 diff = a->mProbeInfo->mScore - b->mProbeInfo->mScore;
  223. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  224. }
  225. void RenderProbeMgr::getBestProbes(const Point3F& objPosition, ProbeDataSet* probeDataSet)
  226. {
  227. PROFILE_SCOPE(ProbeManager_getBestProbes);
  228. //Array rendering
  229. U32 probeCount = mActiveProbes.size();
  230. Vector<S8> bestPickProbes;
  231. bestPickProbes.setSize(probeDataSet->maxProbeCount);
  232. bestPickProbes.fill(-1);
  233. mHasSkylight = false;
  234. probeDataSet->skyLightIdx = -1;
  235. probeDataSet->effectiveProbeCount = 0;
  236. for (U32 i = 0; i < probeCount; i++)
  237. {
  238. //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
  239. if (mHasSkylight && probeDataSet->effectiveProbeCount >= probeDataSet->maxProbeCount)
  240. break;
  241. const ProbeRenderInst& curEntry = mActiveProbes[i];
  242. //Obviously, if the probe is marked as not enabled, we skip
  243. if (!curEntry.mProbeInfo->mIsEnabled)
  244. continue;
  245. if (curEntry.mProbeInfo->mProbeShapeType != ReflectionProbe::ProbeInfo::Skylight)
  246. {
  247. if (probeDataSet->effectiveProbeCount < probeDataSet->maxProbeCount)
  248. {
  249. bestPickProbes[probeDataSet->effectiveProbeCount] = i;
  250. probeDataSet->effectiveProbeCount++;
  251. }
  252. }
  253. else
  254. {
  255. probeDataSet->skyLightIdx = curEntry.mCubemapIndex;
  256. mHasSkylight = true;
  257. }
  258. }
  259. //If we, for whatever reason, have nothing, bail now
  260. if (mHasSkylight == false && probeDataSet->effectiveProbeCount == 0)
  261. return;
  262. //Grab our best probe picks
  263. for (U32 i = 0; i < bestPickProbes.size(); i++)
  264. {
  265. if (bestPickProbes[i] == -1)
  266. continue;
  267. const ProbeRenderInst& curEntry = mActiveProbes[bestPickProbes[i]];
  268. probeDataSet->probeConfigArray[i] = Point4F(curEntry.mProbeInfo->mProbeShapeType,
  269. curEntry.mProbeInfo->mRadius,
  270. curEntry.mProbeInfo->mAtten,
  271. curEntry.mCubemapIndex);
  272. MatrixF p2A = curEntry.mProbeInfo->mTransform;
  273. probeDataSet->probeWorldToObjArray[i] = p2A;
  274. p2A.inverse();
  275. probeDataSet->refScaleArray[i] = curEntry.mProbeInfo->mProbeRefScale / (p2A.getScale()*2);
  276. Point3F probePos = curEntry.mProbeInfo->mObject->getPosition();
  277. Point3F refPos = probePos + curEntry.mProbeInfo->mProbeRefOffset * probeDataSet->refScaleArray[i].asPoint3F();
  278. probeDataSet->probePositionArray[i] = Point4F(probePos.x, probePos.y, probePos.z, 0);
  279. probeDataSet->probeRefPositionArray[i] = Point4F(refPos.x, refPos.y, refPos.z, 0);
  280. }
  281. }
  282. void RenderProbeMgr::registerProbe(ReflectionProbe::ProbeInfo* newProbe)
  283. {
  284. //Can't have over the probe limit
  285. if (mRegisteredProbes.size() + 1 >= PROBE_MAX_COUNT)
  286. return;
  287. ProbeRenderInst newProbeRenderInst;
  288. newProbeRenderInst.mProbeInfo = newProbe;
  289. const U32 cubeIndex = _findNextEmptyCubeSlot();
  290. if (cubeIndex == INVALID_CUBE_SLOT)
  291. {
  292. Con::warnf("RenderProbeMgr::registerProbe() - Invalid cubemap slot.");
  293. return;
  294. }
  295. //check if we need to resize the cubemap array
  296. if (cubeIndex >= mCubeSlotCount)
  297. {
  298. //alloc temp array handles
  299. GFXCubemapArrayHandle irr = GFXCubemapArrayHandle(GFX->createCubemapArray());
  300. GFXCubemapArrayHandle prefilter = GFXCubemapArrayHandle(GFX->createCubemapArray());
  301. irr->init(mCubeSlotCount + PROBE_ARRAY_SLOT_BUFFER_SIZE, RenderProbeMgr::smProbeBakeResolution, PROBE_FORMAT);
  302. prefilter->init(mCubeSlotCount + PROBE_ARRAY_SLOT_BUFFER_SIZE, RenderProbeMgr::smProbeBakeResolution, PROBE_FORMAT);
  303. mIrradianceArray->copyTo(irr);
  304. mPrefilterArray->copyTo(prefilter);
  305. //assign the temp handles to the new ones, this will destroy the old ones as well
  306. mIrradianceArray = irr;
  307. mPrefilterArray = prefilter;
  308. mCubeSlotCount += PROBE_ARRAY_SLOT_BUFFER_SIZE;
  309. }
  310. newProbeRenderInst.mCubemapIndex = cubeIndex;
  311. //mark cubemap slot as taken
  312. mCubeMapSlots[cubeIndex] = true;
  313. mCubeMapCount++;
  314. mRegisteredProbes.push_back(newProbeRenderInst);
  315. #ifdef TORQUE_DEBUG
  316. Con::warnf("RenderProbeMgr::registerProbe() - Registered probe %u to cubeIndex %u", newProbe->mObject->getId(), cubeIndex);
  317. #endif
  318. }
  319. void RenderProbeMgr::unregisterProbe(ReflectionProbe::ProbeInfo* probeInfo)
  320. {
  321. ProbeRenderInst* probe = findProbeInst(probeInfo);
  322. if (probe == nullptr)
  323. return;
  324. if (probe->mCubemapIndex == INVALID_CUBE_SLOT)
  325. return;
  326. //mark cubemap slot as available now
  327. mCubeMapSlots[probe->mCubemapIndex] = false;
  328. mCubeMapCount--;
  329. mRegisteredProbes.erase(probe);
  330. }
  331. void RenderProbeMgr::submitProbe(ReflectionProbe::ProbeInfo* probe)
  332. {
  333. ProbeRenderInst* probeInst = findProbeInst(probe);
  334. mActiveProbes.push_back(*probeInst);
  335. }
  336. PostEffect* RenderProbeMgr::getProbeArrayEffect()
  337. {
  338. if (!mProbeArrayEffect)
  339. {
  340. mProbeArrayEffect = dynamic_cast<PostEffect*>(Sim::findObject("reflectionProbeArrayPostFX"));
  341. if (!mProbeArrayEffect)
  342. return nullptr;
  343. mProbeArrayEffect->setShaderConst("$numProbes", (S32)0);
  344. mProbeArrayEffect->setShaderConst("$skylightCubemapIdx", (S32)-1);
  345. mProbeArrayEffect->setShaderConst("$cubeMips", (float)0);
  346. mProbeArrayEffect->setShaderConst("$maxProbeDrawDistance", smMaxProbeDrawDistance);
  347. }
  348. return mProbeArrayEffect;
  349. }
  350. void RenderProbeMgr::updateProbeTexture(ReflectionProbe::ProbeInfo* probeInfo)
  351. {
  352. //If we don't have a registered probe, there's no point in updating the cubemap array for it
  353. ProbeRenderInst* probe = findProbeInst(probeInfo);
  354. if (probe == nullptr)
  355. return;
  356. //Some basic sanity checking that we have valid cubemaps to work with
  357. if (probeInfo->mIrradianceCubemap.isNull() || !probeInfo->mIrradianceCubemap->isInitialized() ||
  358. probeInfo->mIrradianceCubemap->getSize() != RenderProbeMgr::smProbeBakeResolution)
  359. {
  360. Con::errorf("RenderProbeMgr::updateProbeTexture() - tried to update a probe's texture with an invalid or uninitialized irradiance map!");
  361. return;
  362. }
  363. if (probeInfo->mPrefilterCubemap.isNull() || !probeInfo->mPrefilterCubemap->isInitialized() ||
  364. probeInfo->mPrefilterCubemap->getSize() != RenderProbeMgr::smProbeBakeResolution)
  365. {
  366. Con::errorf("RenderProbeMgr::updateProbeTexture() - tried to update a probe's texture with an invalid or uninitialized specular map!");
  367. return;
  368. }
  369. //Run the update on the array pair with the probe's cubemaps and index
  370. const U32 cubeIndex = probe->mCubemapIndex;
  371. mIrradianceArray->updateTexture(probeInfo->mIrradianceCubemap, cubeIndex);
  372. mPrefilterArray->updateTexture(probeInfo->mPrefilterCubemap, cubeIndex);
  373. #ifdef TORQUE_DEBUG
  374. Con::warnf("UpdatedProbeTexture - probe id: %u on cubeIndex %u, Irrad validity: %d, Prefilter validity: %d", probeInfo->mObject->getId(), cubeIndex,
  375. probeInfo->mIrradianceCubemap->isInitialized(), probeInfo->mPrefilterCubemap->isInitialized());
  376. #endif
  377. }
  378. void RenderProbeMgr::reloadTextures()
  379. {
  380. U32 probeCount = mRegisteredProbes.size();
  381. for (U32 i = 0; i < probeCount; i++)
  382. {
  383. updateProbeTexture(mRegisteredProbes[i].mProbeInfo);
  384. }
  385. }
  386. void RenderProbeMgr::bakeProbe(ReflectionProbe* probe)
  387. {
  388. GFXDEBUGEVENT_SCOPE(RenderProbeMgr_Bake, ColorI::WHITE);
  389. Con::warnf("RenderProbeMgr::bakeProbe() - Beginning bake!");
  390. U32 startMSTime = Platform::getRealMilliseconds();
  391. Con::setVariable("$Probes::Capturing", "1");
  392. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  393. U32 resolution = Con::getIntVariable("$pref::ReflectionProbes::BakeResolution", 64);
  394. U32 prefilterMipLevels = mLog2(F32(resolution)) + 1;
  395. bool renderWithProbes = Con::getIntVariable("$pref::ReflectionProbes::RenderWithProbes", false);
  396. ReflectionProbe* clientProbe = nullptr;
  397. if (probe->isServerObject())
  398. clientProbe = static_cast<ReflectionProbe*>(probe->getClientObject());
  399. else
  400. return;
  401. if (clientProbe == nullptr)
  402. return;
  403. String probePrefilterPath = clientProbe->getPrefilterMapPath();
  404. String probeIrradPath = clientProbe->getIrradianceMapPath();
  405. if (clientProbe->mReflectionModeType != ReflectionProbe::DynamicCubemap)
  406. {
  407. //Prep our bake path
  408. if (probePrefilterPath.isEmpty() || probeIrradPath.isEmpty())
  409. {
  410. Con::errorf("RenderProbeMgr::bake() - Unable to bake our captures because probe doesn't have a path set");
  411. return;
  412. }
  413. }
  414. // Save the current transforms so we can restore
  415. // it for child control rendering below.
  416. GFXTransformSaver saver;
  417. bool probeRenderState = RenderProbeMgr::smRenderReflectionProbes;
  418. F32 farPlane = 1000.0f;
  419. ReflectorDesc reflDesc;
  420. reflDesc.texSize = resolution;
  421. reflDesc.farDist = farPlane;
  422. reflDesc.detailAdjust = 1;
  423. reflDesc.objectTypeMask = probe->mProbeShapeType == ReflectionProbe::ProbeInfo::Skylight ? SKYLIGHT_CAPTURE_TYPEMASK : REFLECTION_PROBE_CAPTURE_TYPEMASK;
  424. CubeReflector cubeRefl;
  425. cubeRefl.registerReflector(probe, &reflDesc);
  426. ReflectParams reflParams;
  427. //need to get the query somehow. Likely do some sort of get function to fetch from the guiTSControl that's active
  428. CameraQuery query; //need to get the last cameraQuery
  429. query.fov = 90; //90 degree slices for each of the 6 sides
  430. query.nearPlane = 0.1f;
  431. query.farPlane = farPlane;
  432. query.headMatrix = MatrixF();
  433. query.cameraMatrix = clientProbe->getTransform();
  434. Frustum culler;
  435. culler.set(false,
  436. query.fov,
  437. 1.0f,
  438. query.nearPlane,
  439. query.farPlane,
  440. query.cameraMatrix);
  441. S32 stereoTarget = GFX->getCurrentStereoTarget();
  442. Point2I maxRes(2048, 2048); //basically a boundary so we don't go over this and break stuff
  443. reflParams.culler = culler;
  444. reflParams.eyeId = stereoTarget;
  445. reflParams.query = &query;
  446. reflParams.startOfUpdateMs = startMSTime;
  447. reflParams.viewportExtent = maxRes;
  448. if (!renderWithProbes)
  449. RenderProbeMgr::smRenderReflectionProbes = false;
  450. GFXFormat reflectFormat;
  451. if (mUseHDRCaptures)
  452. reflectFormat = GFXFormatR16G16B16A16F;
  453. else
  454. reflectFormat = GFXFormatR8G8B8A8;
  455. const GFXFormat oldRefFmt = REFLECTMGR->getReflectFormat();
  456. REFLECTMGR->setReflectFormat(reflectFormat);
  457. cubeRefl.updateReflection(reflParams, clientProbe->getTransform().getPosition() + clientProbe->mProbeRefOffset);
  458. //Now, save out the maps
  459. //create irridiance cubemap
  460. if (cubeRefl.getCubemap())
  461. {
  462. //Just to ensure we're prepped for the generation
  463. clientProbe->createClientResources();
  464. //Prep it with whatever resolution we've dictated for our bake
  465. clientProbe->mIrridianceMap->mCubemap->initDynamic(resolution, reflectFormat);
  466. clientProbe->mPrefilterMap->mCubemap->initDynamic(resolution, reflectFormat);
  467. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  468. IBLUtilities::GenerateIrradianceMap(renderTarget, cubeRefl.getCubemap(), clientProbe->mIrridianceMap->mCubemap);
  469. IBLUtilities::GeneratePrefilterMap(renderTarget, cubeRefl.getCubemap(), prefilterMipLevels, clientProbe->mPrefilterMap->mCubemap);
  470. U32 endMSTime = Platform::getRealMilliseconds();
  471. F32 diffTime = F32(endMSTime - startMSTime);
  472. Con::warnf("RenderProbeMgr::bake() - Finished Capture! Took %g milliseconds", diffTime);
  473. Con::warnf("RenderProbeMgr::bake() - Beginning save now!");
  474. IBLUtilities::SaveCubeMap(clientProbe->getIrradianceMapPath(), clientProbe->mIrridianceMap->mCubemap);
  475. IBLUtilities::SaveCubeMap(clientProbe->getPrefilterMapPath(), clientProbe->mPrefilterMap->mCubemap);
  476. }
  477. else
  478. {
  479. Con::errorf("RenderProbeMgr::bake() - Didn't generate a valid scene capture cubemap, unable to generate prefilter and irradiance maps!");
  480. }
  481. if (!renderWithProbes)
  482. RenderProbeMgr::smRenderReflectionProbes = probeRenderState;
  483. Con::setVariable("$Probes::Capturing", "0");
  484. cubeRefl.unregisterReflector();
  485. U32 endMSTime = Platform::getRealMilliseconds();
  486. F32 diffTime = F32(endMSTime - startMSTime);
  487. probe->setMaskBits(-1);
  488. Con::warnf("RenderProbeMgr::bake() - Finished bake! Took %g milliseconds", diffTime);
  489. REFLECTMGR->setReflectFormat(oldRefFmt);
  490. }
  491. void RenderProbeMgr::bakeProbes()
  492. {
  493. Vector<ReflectionProbe*> probes;
  494. Scene::getRootScene()->findObjectByType<ReflectionProbe>(probes);
  495. for (U32 i = 0; i < probes.size(); i++)
  496. {
  497. if (probes[i]->isClientObject())
  498. continue;
  499. bakeProbe(probes[i]);
  500. }
  501. }
  502. //=============================================================================
  503. // Forward Rendering functions
  504. //=============================================================================
  505. ProbeShaderConstants* RenderProbeMgr::getProbeShaderConstants(GFXShaderConstBuffer* buffer)
  506. {
  507. if (!buffer)
  508. return NULL;
  509. PROFILE_SCOPE(ProbeManager_GetProbeShaderConstants);
  510. GFXShader* shader = buffer->getShader();
  511. // Check to see if this is the same shader, we'll get hit repeatedly by
  512. // the same one due to the render bin loops.
  513. if (mLastShader.getPointer() != shader)
  514. {
  515. ProbeConstantMap::Iterator iter = mConstantLookup.find(shader);
  516. if (iter != mConstantLookup.end())
  517. {
  518. mLastConstants = iter->value;
  519. }
  520. else
  521. {
  522. ProbeShaderConstants* psc = new ProbeShaderConstants();
  523. mConstantLookup[shader] = psc;
  524. mLastConstants = psc;
  525. }
  526. // Set our new shader
  527. mLastShader = shader;
  528. }
  529. /*if (mLastConstants == nullptr)
  530. {
  531. ProbeShaderConstants* psc = new ProbeShaderConstants();
  532. mConstantLookup[shader] = psc;
  533. mLastConstants = psc;
  534. }*/
  535. // Make sure that our current lighting constants are initialized
  536. if (mLastConstants && !mLastConstants->mInit)
  537. mLastConstants->init(shader);
  538. return mLastConstants;
  539. }
  540. void RenderProbeMgr::setProbeInfo(ProcessedMaterial *pmat,
  541. const Material *mat,
  542. const SceneData &sgData,
  543. const SceneRenderState *state,
  544. U32 pass,
  545. GFXShaderConstBuffer *shaderConsts)
  546. {
  547. // Skip this if we're rendering from the deferred bin.
  548. if (sgData.binType == SceneData::DeferredBin)
  549. return;
  550. PROFILE_SCOPE(ProbeManager_setProbeInfo);
  551. ProbeShaderConstants *psc = getProbeShaderConstants(shaderConsts);
  552. // NOTE: If you encounter a crash from this point forward
  553. // while setting a shader constant its probably because the
  554. // mConstantLookup has bad shaders/constants in it.
  555. //
  556. // This is a known crash bug that can occur if materials/shaders
  557. // are reloaded and the light manager is not reset.
  558. //
  559. // We should look to fix this by clearing the table.
  560. MatrixSet matSet = state->getRenderPass()->getMatrixSet();
  561. // Update the forward shading light constants.
  562. _update4ProbeConsts(sgData, matSet, psc, shaderConsts);
  563. }
  564. void RenderProbeMgr::setupSGData(SceneData& data, const SceneRenderState* state, LightInfo* light)
  565. {
  566. //ensure they're sorted for forward rendering
  567. mActiveProbes.sort(_probeScoreCmp);
  568. }
  569. void RenderProbeMgr::_update4ProbeConsts(const SceneData& sgData,
  570. MatrixSet& matSet,
  571. ProbeShaderConstants* probeShaderConsts,
  572. GFXShaderConstBuffer* shaderConsts)
  573. {
  574. PROFILE_SCOPE(ProbeManager_Update4ProbeConsts);
  575. // Skip over gathering lights if we don't have to!
  576. if (probeShaderConsts->isValid())
  577. {
  578. PROFILE_SCOPE(ProbeManager_Update4ProbeConsts_setProbes);
  579. const U32 MAX_FORWARD_PROBES = 4;
  580. ProbeDataSet probeSet(MAX_FORWARD_PROBES);
  581. matSet.restoreSceneViewProjection();
  582. getBestProbes(sgData.objTrans->getPosition(), &probeSet);
  583. static AlignedArray<Point4F> probePositionAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  584. static AlignedArray<Point4F> refScaleAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  585. static AlignedArray<Point4F> probeRefPositionAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  586. static AlignedArray<Point4F> probeConfigAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  587. for (U32 i = 0; i < probeSet.maxProbeCount; i++)
  588. {
  589. probePositionAlignedArray[i] = probeSet.probePositionArray[i];
  590. probeRefPositionAlignedArray[i] = probeSet.probeRefPositionArray[i];
  591. refScaleAlignedArray[i] = probeSet.refScaleArray[i];
  592. probeConfigAlignedArray[i] = probeSet.probeConfigArray[i];
  593. }
  594. if (probeSet.effectiveProbeCount != 0)
  595. {
  596. shaderConsts->setSafe(probeShaderConsts->mProbeCountSC, (S32)probeSet.effectiveProbeCount);
  597. shaderConsts->setSafe(probeShaderConsts->mProbePositionArraySC, probePositionAlignedArray);
  598. shaderConsts->setSafe(probeShaderConsts->mProbeRefPosArraySC, probeRefPositionAlignedArray);
  599. if (probeShaderConsts->isValid())
  600. shaderConsts->set(probeShaderConsts->mWorldToObjArraySC, probeSet.probeWorldToObjArray.address(), probeSet.probeWorldToObjArray.size(), GFXSCT_Float4x4);
  601. shaderConsts->setSafe(probeShaderConsts->mRefScaleArraySC, refScaleAlignedArray);
  602. shaderConsts->setSafe(probeShaderConsts->mProbeConfigDataArraySC, probeConfigAlignedArray);
  603. }
  604. if (probeShaderConsts->mBRDFTextureMap->getSamplerRegister() != -1 && mBRDFTexture.isValid())
  605. GFX->setTexture(probeShaderConsts->mBRDFTextureMap->getSamplerRegister(), mBRDFTexture);
  606. shaderConsts->setSafe(probeShaderConsts->mSkylightCubemapIdxSC, (float)probeSet.skyLightIdx);
  607. if (probeShaderConsts->mProbeSpecularCubemapArraySC->getSamplerRegister() != -1)
  608. GFX->setCubeArrayTexture(probeShaderConsts->mProbeSpecularCubemapArraySC->getSamplerRegister(), mPrefilterArray);
  609. if (probeShaderConsts->mProbeIrradianceCubemapArraySC->getSamplerRegister() != -1)
  610. GFX->setCubeArrayTexture(probeShaderConsts->mProbeIrradianceCubemapArraySC->getSamplerRegister(), mIrradianceArray);
  611. shaderConsts->setSafe(probeShaderConsts->mMaxProbeDrawDistanceSC, smMaxProbeDrawDistance);
  612. }
  613. }
  614. //=============================================================================
  615. // Deferred Rendering Functions
  616. //=============================================================================
  617. void RenderProbeMgr::_setupPerFrameParameters(const SceneRenderState* state)
  618. {
  619. PROFILE_SCOPE(RenderProbeMgr_SetupPerFrameParameters);
  620. mProbeData = ProbeDataSet(smMaxProbesPerFrame);
  621. getBestProbes(state->getCameraPosition(), &mProbeData);
  622. }
  623. void RenderProbeMgr::render( SceneRenderState *state )
  624. {
  625. if (getProbeArrayEffect() == nullptr)
  626. {
  627. mActiveProbes.clear();
  628. return;
  629. }
  630. GFXDEBUGEVENT_SCOPE(RenderProbeMgr_render, ColorI::WHITE);
  631. //Sort the active probes
  632. mActiveProbes.sort(_probeScoreCmp);
  633. // Initialize and set the per-frame data
  634. _setupPerFrameParameters(state);
  635. // Early out if nothing to draw.
  636. if ((!RenderProbeMgr::smRenderReflectionProbes && dStrcmp(Con::getVariable("$Probes::Capturing", "0"), "1")) || (!mHasSkylight && mProbeData.effectiveProbeCount == 0))
  637. {
  638. getProbeArrayEffect()->setSkip(true);
  639. mActiveProbes.clear();
  640. return;
  641. }
  642. GFXTransformSaver saver;
  643. //Visualization
  644. String useDebugAtten = Con::getVariable("$Probes::showAttenuation", "0");
  645. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_ATTENUATION", useDebugAtten);
  646. String useDebugSpecCubemap = Con::getVariable("$Probes::showSpecularCubemaps", "0");
  647. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_SPECCUBEMAP", useDebugSpecCubemap);
  648. String useDebugDiffuseCubemap = Con::getVariable("$Probes::showDiffuseCubemaps", "0");
  649. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_DIFFCUBEMAP", useDebugDiffuseCubemap);
  650. String useDebugContrib = Con::getVariable("$Probes::showProbeContrib", "0");
  651. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_CONTRIB", useDebugContrib);
  652. if(mHasSkylight && mProbeData.effectiveProbeCount == 0)
  653. mProbeArrayEffect->setShaderMacro("SKYLIGHT_ONLY", "1");
  654. else
  655. mProbeArrayEffect->setShaderMacro("SKYLIGHT_ONLY", "0");
  656. String probePerFrame = Con::getVariable("$pref::MaxProbesPerFrame", "8");
  657. mProbeArrayEffect->setShaderMacro("MAX_PROBES", probePerFrame);
  658. String probeCapturing = Con::getVariable("$Probes::Capturing", "0");
  659. mProbeArrayEffect->setShaderMacro("CAPTURING", probeCapturing);
  660. //ssao mask
  661. if (AdvancedLightBinManager::smUseSSAOMask)
  662. {
  663. //find ssaoMask
  664. NamedTexTargetRef ssaoTarget = NamedTexTarget::find("ssaoMask");
  665. GFXTextureObject* pTexObj = ssaoTarget->getTexture();
  666. if (pTexObj)
  667. {
  668. mProbeArrayEffect->setShaderMacro("USE_SSAO_MASK");
  669. mProbeArrayEffect->setTexture(6, pTexObj);
  670. }
  671. }
  672. else
  673. {
  674. mProbeArrayEffect->setTexture(6, GFXTexHandle(NULL));
  675. }
  676. mProbeArrayEffect->setTexture(3, mBRDFTexture);
  677. mProbeArrayEffect->setCubemapArrayTexture(4, mPrefilterArray);
  678. mProbeArrayEffect->setCubemapArrayTexture(5, mIrradianceArray);
  679. mProbeArrayEffect->setShaderConst("$numProbes", (S32)mProbeData.effectiveProbeCount);
  680. mProbeArrayEffect->setShaderConst("$skylightCubemapIdx", (S32)mProbeData.skyLightIdx);
  681. mProbeArrayEffect->setShaderConst("$cubeMips", (float)mPrefilterArray->getMipMapLevels());
  682. //also set up some colors
  683. Vector<Point4F> contribColors;
  684. contribColors.setSize(mProbeData.effectiveProbeCount);
  685. if (mProbeData.effectiveProbeCount != 0)
  686. {
  687. if (useDebugContrib == String("1"))
  688. {
  689. MRandomLCG RandomGen;
  690. RandomGen.setSeed(mProbeData.effectiveProbeCount);
  691. for (U32 i = 0; i < mProbeData.effectiveProbeCount; i++)
  692. {
  693. //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
  694. if (i == 0)
  695. contribColors[i] = Point4F(1, 0, 0, 1);
  696. else if (i == 1)
  697. contribColors[i] = Point4F(0, 1, 0, 1);
  698. else if (i == 2)
  699. contribColors[i] = Point4F(0, 0, 1, 1);
  700. else
  701. contribColors[i] = Point4F(RandomGen.randF(0, 1), RandomGen.randF(0, 1), RandomGen.randF(0, 1), 1);
  702. }
  703. }
  704. }
  705. mProbeArrayEffect->setShaderConst("$probeContribColors", contribColors);
  706. mProbeArrayEffect->setShaderConst("$probePosArray", mProbeData.probePositionArray);
  707. mProbeArrayEffect->setShaderConst("$refPosArray", mProbeData.probeRefPositionArray);
  708. mProbeArrayEffect->setShaderConst("$worldToObjArray", mProbeData.probeWorldToObjArray);
  709. mProbeArrayEffect->setShaderConst("$refScaleArray", mProbeData.refScaleArray);
  710. mProbeArrayEffect->setShaderConst("$probeConfigData", mProbeData.probeConfigArray);
  711. mProbeArrayEffect->setShaderConst("$maxProbeDrawDistance", smMaxProbeDrawDistance);
  712. // Make sure the effect is gonna render.
  713. getProbeArrayEffect()->setSkip(false);
  714. }
  715. //=============================================================================
  716. // Console functions
  717. //=============================================================================
  718. DefineEngineMethod(RenderProbeMgr, bakeProbe, void, (ReflectionProbe* probe), (nullAsType< ReflectionProbe*>()),
  719. "@brief Bakes the cubemaps for a reflection probe\n\n.")
  720. {
  721. if(probe != nullptr)
  722. object->bakeProbe(probe);
  723. }
  724. DefineEngineMethod(RenderProbeMgr, bakeProbes, void, (),, "@brief Iterates over all reflection probes in the scene and bakes their cubemaps\n\n.")
  725. {
  726. object->bakeProbes();
  727. }