renderProbeMgr.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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 "console/consoleTypes.h"
  24. #include "scene/sceneObject.h"
  25. #include "materials/materialManager.h"
  26. #include "scene/sceneRenderState.h"
  27. #include "math/util/sphereMesh.h"
  28. #include "math/util/matrixSet.h"
  29. #include "materials/processedMaterial.h"
  30. #include "renderInstance/renderDeferredMgr.h"
  31. #include "math/mPolyhedron.impl.h"
  32. #include "gfx/gfxTransformSaver.h"
  33. #include "gfx/gfxDebugEvent.h"
  34. #include "shaderGen/shaderGenVars.h"
  35. #include "materials/shaderData.h"
  36. #include "gfx/gfxTextureManager.h"
  37. #include "postFx/postEffect.h"
  38. #include "T3D/lighting/reflectionProbe.h"
  39. #include "T3D/lighting/IBLUtilities.h"
  40. //For our cameraQuery setup
  41. #include "T3D/gameTSCtrl.h"
  42. #define TORQUE_GFX_VISUAL_DEBUG //renderdoc debugging
  43. IMPLEMENT_CONOBJECT(RenderProbeMgr);
  44. ConsoleDocClass( RenderProbeMgr,
  45. "@brief A render bin which uses object callbacks for rendering.\n\n"
  46. "This render bin gathers object render instances and calls its delegate "
  47. "method to perform rendering. It is used infrequently for specialized "
  48. "scene objects which perform custom rendering.\n\n"
  49. "@ingroup RenderBin\n" );
  50. RenderProbeMgr *RenderProbeMgr::smProbeManager = NULL;
  51. bool RenderProbeMgr::smRenderReflectionProbes = true;
  52. S32 QSORT_CALLBACK AscendingReflectProbeInfluence(const void* a, const void* b)
  53. {
  54. // Debug Profiling.
  55. PROFILE_SCOPE(AdvancedLightBinManager_AscendingReflectProbeInfluence);
  56. // Fetch asset definitions.
  57. const ProbeRenderInst* pReflectProbeA = (*(ProbeRenderInst**)a);
  58. const ProbeRenderInst* pReflectProbeB = (*(ProbeRenderInst**)b);
  59. //sort by score
  60. return pReflectProbeA->mScore - pReflectProbeB->mScore;
  61. }
  62. //
  63. //
  64. ProbeRenderInst::ProbeRenderInst() : SystemInterface(),
  65. mTransform(true),
  66. mDirty(false),
  67. mPriority(1.0f),
  68. mScore(0.0f),
  69. mPrefilterCubemap(NULL),
  70. mIrradianceCubemap(NULL),
  71. mRadius(1.0f),
  72. mProbeRefOffset(0, 0, 0),
  73. mProbeRefScale(1,1,1),
  74. mAtten(0.0),
  75. mCubemapIndex(0),
  76. mIsSkylight(false)
  77. {
  78. }
  79. ProbeRenderInst::~ProbeRenderInst()
  80. {
  81. if (mPrefilterCubemap && mPrefilterCubemap.isValid())
  82. {
  83. mPrefilterCubemap.free();
  84. }
  85. if (mIrradianceCubemap && mIrradianceCubemap.isValid())
  86. {
  87. mIrradianceCubemap.free();
  88. }
  89. }
  90. void ProbeRenderInst::set(const ProbeRenderInst *probeInfo)
  91. {
  92. mTransform = probeInfo->mTransform;
  93. mPrefilterCubemap = probeInfo->mPrefilterCubemap;
  94. mIrradianceCubemap = probeInfo->mIrradianceCubemap;
  95. mRadius = probeInfo->mRadius;
  96. mProbeShapeType = probeInfo->mProbeShapeType;
  97. mBounds = probeInfo->mBounds;
  98. mIsSkylight = probeInfo->mIsSkylight;
  99. mScore = probeInfo->mScore;
  100. mAtten = probeInfo->mAtten;
  101. }
  102. //
  103. //
  104. ProbeShaderConstants::ProbeShaderConstants()
  105. : mInit(false),
  106. mShader(NULL),
  107. mProbePositionSC(NULL),
  108. mProbeRefPosSC(NULL),
  109. mProbeBoxMinSC(NULL),
  110. mProbeBoxMaxSC(NULL),
  111. mProbeConfigDataSC(NULL),
  112. mProbeSpecularCubemapSC(NULL),
  113. mProbeIrradianceCubemapSC(NULL),
  114. mProbeCountSC(NULL),
  115. mBRDFTextureMap(NULL),
  116. mSkylightSpecularMap(NULL),
  117. mSkylightIrradMap(NULL),
  118. mHasSkylight(NULL)
  119. {
  120. }
  121. ProbeShaderConstants::~ProbeShaderConstants()
  122. {
  123. if (mShader.isValid())
  124. {
  125. mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
  126. mShader = NULL;
  127. }
  128. }
  129. void ProbeShaderConstants::init(GFXShader* shader)
  130. {
  131. if (mShader.getPointer() != shader)
  132. {
  133. if (mShader.isValid())
  134. mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
  135. mShader = shader;
  136. mShader->getReloadSignal().notify(this, &ProbeShaderConstants::_onShaderReload);
  137. }
  138. //Reflection Probes
  139. mProbePositionSC = shader->getShaderConstHandle(ShaderGenVars::probePosition);
  140. mProbeRefPosSC = shader->getShaderConstHandle(ShaderGenVars::probeRefPos);
  141. mProbeBoxMinSC = shader->getShaderConstHandle(ShaderGenVars::probeBoxMin);
  142. mProbeBoxMaxSC = shader->getShaderConstHandle(ShaderGenVars::probeBoxMax);
  143. mWorldToObjArraySC = shader->getShaderConstHandle(ShaderGenVars::worldToObjArray);
  144. mProbeConfigDataSC = shader->getShaderConstHandle(ShaderGenVars::probeConfigData);
  145. mProbeSpecularCubemapSC = shader->getShaderConstHandle(ShaderGenVars::specularCubemapAR);
  146. mProbeIrradianceCubemapSC = shader->getShaderConstHandle(ShaderGenVars::irradianceCubemapAR);
  147. mProbeCountSC = shader->getShaderConstHandle(ShaderGenVars::probeCount);
  148. mBRDFTextureMap = shader->getShaderConstHandle(ShaderGenVars::BRDFTextureMap);
  149. mSkylightSpecularMap = shader->getShaderConstHandle(ShaderGenVars::skylightPrefilterMap);
  150. mSkylightIrradMap = shader->getShaderConstHandle(ShaderGenVars::skylightIrradMap);
  151. mHasSkylight = shader->getShaderConstHandle(ShaderGenVars::hasSkylight);
  152. mInit = true;
  153. }
  154. bool ProbeShaderConstants::isValid()
  155. {
  156. if (mProbePositionSC->isValid() ||
  157. mProbeConfigDataSC->isValid() ||
  158. mProbeBoxMinSC->isValid() ||
  159. mProbeBoxMaxSC->isValid() ||
  160. mProbeSpecularCubemapSC->isValid() ||
  161. mProbeIrradianceCubemapSC->isValid())
  162. return true;
  163. return false;
  164. }
  165. void ProbeShaderConstants::_onShaderReload()
  166. {
  167. if (mShader.isValid())
  168. init(mShader);
  169. }
  170. //
  171. //
  172. RenderProbeMgr::RenderProbeMgr()
  173. : RenderBinManager(RenderPassManager::RIT_Probes, 1.0f, 1.0f),
  174. mLastShader(nullptr),
  175. mLastConstants(nullptr),
  176. mProbesDirty(false)
  177. {
  178. mEffectiveProbeCount = 0;
  179. mMipCount = 0;
  180. mProbeArrayEffect = nullptr;
  181. smProbeManager = this;
  182. mCubeMapCount = 0;
  183. for (U32 i = 0; i < PROBE_MAX_COUNT; i++)
  184. {
  185. mCubeMapSlots[i] = false;
  186. }
  187. }
  188. RenderProbeMgr::RenderProbeMgr(RenderInstType riType, F32 renderOrder, F32 processAddOrder)
  189. : RenderBinManager(riType, renderOrder, processAddOrder)
  190. {
  191. }
  192. RenderProbeMgr::~RenderProbeMgr()
  193. {
  194. mLastShader = NULL;
  195. mLastConstants = NULL;
  196. for (ProbeConstantMap::Iterator i = mConstantLookup.begin(); i != mConstantLookup.end(); i++)
  197. {
  198. if (i->value)
  199. SAFE_DELETE(i->value);
  200. }
  201. mConstantLookup.clear();
  202. }
  203. bool RenderProbeMgr::onAdd()
  204. {
  205. if (!Parent::onAdd())
  206. return false;
  207. mIrradianceArray = GFXCubemapArrayHandle(GFX->createCubemapArray());
  208. mPrefilterArray = GFXCubemapArrayHandle(GFX->createCubemapArray());
  209. //pre-allocate a few slots
  210. mIrradianceArray->init(PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_IRRAD_SIZE, PROBE_FORMAT);
  211. mPrefilterArray->init(PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_PREFILTER_SIZE, PROBE_FORMAT);
  212. mCubeSlotCount = PROBE_ARRAY_SLOT_BUFFER_SIZE;
  213. //create our own default default skylight
  214. mDefaultSkyLight = new ProbeRenderInst;
  215. mDefaultSkyLight->mProbeShapeType = ProbeRenderInst::Skylight;
  216. if (!mDefaultSkyLight->mIrradianceCubemap.set("core/art/pbr/default_irradiance.dds"))
  217. {
  218. Con::errorf("RenderProbeMgr::onAdd: Failed to load default irradiance cubemap");
  219. return false;
  220. }
  221. if (!mDefaultSkyLight->mPrefilterCubemap.set("core/art/pbr/default_prefilter.dds"))
  222. {
  223. Con::errorf("RenderProbeMgr::onAdd: Failed to load default prefilter cubemap");
  224. return false;
  225. }
  226. return true;
  227. }
  228. void RenderProbeMgr::onRemove()
  229. {
  230. Parent::onRemove();
  231. }
  232. void RenderProbeMgr::initPersistFields()
  233. {
  234. Parent::initPersistFields();
  235. }
  236. void RenderProbeMgr::addElement(RenderInst *inst)
  237. {
  238. // If this instance is translucent handle it in RenderTranslucentMgr
  239. //if (inst->translucentSort)
  240. return;
  241. //AssertFatal(inst->defaultKey != 0, "RenderMeshMgr::addElement() - Got null sort key... did you forget to set it?");
  242. /*internalAddElement(inst);
  243. ProbeRenderInst* probeInst = static_cast<ProbeRenderInst*>(inst);
  244. if (probeInst->mIsSkylight)
  245. {
  246. addSkylightProbe(probeInst);
  247. }
  248. else
  249. {
  250. if (probeInst->mProbeShapeType == ProbeInfo::Sphere)
  251. addSphereReflectionProbe(probeInst);
  252. else
  253. addConvexReflectionProbe(probeInst);
  254. }*/
  255. }
  256. void RenderProbeMgr::registerProbe(U32 probeIdx)
  257. {
  258. //Mostly for consolidation, but also lets us sanity check or prep any other data we need for rendering this in one place at time of flagging for render
  259. if (probeIdx >= ProbeRenderInst::all.size())
  260. return;
  261. mRegisteredProbes.push_back_unique(probeIdx);
  262. if (!ProbeRenderInst::all[probeIdx]->mIsSkylight)
  263. {
  264. const U32 cubeIndex = _findNextEmptyCubeSlot();
  265. if (cubeIndex == INVALID_CUBE_SLOT)
  266. {
  267. Con::warnf("RenderProbeMgr::addProbe: Invalid cubemap slot.");
  268. return;
  269. }
  270. //check if we need to resize the cubemap array
  271. if (cubeIndex >= mCubeSlotCount)
  272. {
  273. //alloc temp array handles
  274. GFXCubemapArrayHandle irr = GFXCubemapArrayHandle(GFX->createCubemapArray());
  275. GFXCubemapArrayHandle prefilter = GFXCubemapArrayHandle(GFX->createCubemapArray());
  276. irr->init(mCubeSlotCount + PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_IRRAD_SIZE, PROBE_FORMAT);
  277. prefilter->init(mCubeSlotCount + PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_PREFILTER_SIZE, PROBE_FORMAT);
  278. mIrradianceArray->copyTo(irr);
  279. mPrefilterArray->copyTo(prefilter);
  280. //assign the temp handles to the new ones, this will destroy the old ones as well
  281. mIrradianceArray = irr;
  282. mPrefilterArray = prefilter;
  283. mCubeSlotCount += PROBE_ARRAY_SLOT_BUFFER_SIZE;
  284. }
  285. ProbeRenderInst::all[probeIdx]->mCubemapIndex = cubeIndex;
  286. //mark cubemap slot as taken
  287. mCubeMapSlots[cubeIndex] = true;
  288. mCubeMapCount++;
  289. Con::warnf("RenderProbeMgr::registerProbe: Registered probe %u to cubeIndex %u", probeIdx, cubeIndex);
  290. }
  291. //rebuild our probe data
  292. _setupStaticParameters();
  293. }
  294. void RenderProbeMgr::unregisterProbe(U32 probeIdx)
  295. {
  296. //Mostly for consolidation, but also lets us sanity check or prep any other data we need for rendering this in one place at time of flagging for render
  297. if (probeIdx >= ProbeRenderInst::all.size())
  298. return;
  299. mRegisteredProbes.remove(probeIdx);
  300. if (ProbeRenderInst::all[probeIdx]->mCubemapIndex == INVALID_CUBE_SLOT)
  301. return;
  302. //mark cubemap slot as available now
  303. mCubeMapSlots[ProbeRenderInst::all[probeIdx]->mCubemapIndex] = false;
  304. mCubeMapCount--;
  305. //rebuild our probe data
  306. _setupStaticParameters();
  307. }
  308. //
  309. //
  310. PostEffect* RenderProbeMgr::getProbeArrayEffect()
  311. {
  312. if (!mProbeArrayEffect)
  313. {
  314. mProbeArrayEffect = dynamic_cast<PostEffect*>(Sim::findObject("reflectionProbeArrayPostFX"));
  315. if (!mProbeArrayEffect)
  316. return nullptr;
  317. }
  318. return mProbeArrayEffect;
  319. }
  320. //remove
  321. //Con::setIntVariable("lightMetrics::activeReflectionProbes", mReflectProbeBin.size());
  322. //Con::setIntVariable("lightMetrics::culledReflectProbes", 0/*mNumLightsCulled*/);
  323. //
  324. void RenderProbeMgr::updateProbes()
  325. {
  326. mProbesDirty = true;
  327. }
  328. void RenderProbeMgr::_setupStaticParameters()
  329. {
  330. //Array rendering
  331. U32 probeCount = ProbeRenderInst::all.size();
  332. mEffectiveProbeCount = 0;
  333. mMipCount = 0;
  334. if (probePositionsData.size() != MAXPROBECOUNT)
  335. {
  336. probePositionsData.setSize(MAXPROBECOUNT);
  337. probeRefPositionsData.setSize(MAXPROBECOUNT);
  338. probeWorldToObjData.setSize(MAXPROBECOUNT);
  339. probeBBMinData.setSize(MAXPROBECOUNT);
  340. probeBBMaxData.setSize(MAXPROBECOUNT);
  341. probeConfigData.setSize(MAXPROBECOUNT);
  342. }
  343. probePositionsData.fill(Point4F::Zero);
  344. probeRefPositionsData.fill(Point4F::Zero);
  345. probeWorldToObjData.fill(MatrixF::Identity);
  346. probeBBMinData.fill(Point4F::Zero);
  347. probeBBMaxData.fill(Point4F::Zero);
  348. probeConfigData.fill(Point4F::Zero);
  349. cubeMaps.clear();
  350. irradMaps.clear();
  351. Vector<U32> cubemapIdxes;
  352. if (probeCount != 0 && ProbeRenderInst::all[0]->mPrefilterCubemap != nullptr)
  353. {
  354. //Get our mipCount
  355. mMipCount = ProbeRenderInst::all[0]->mPrefilterCubemap.getPointer()->getMipMapLevels();
  356. }
  357. else
  358. {
  359. mMipCount = 1;
  360. }
  361. for (U32 i = 0; i < probeCount; i++)
  362. {
  363. if (mEffectiveProbeCount >= MAXPROBECOUNT)
  364. break;
  365. const ProbeRenderInst& curEntry = *ProbeRenderInst::all[i];
  366. if (!curEntry.mIsEnabled)
  367. continue;
  368. if (curEntry.mProbeShapeType == ProbeRenderInst::ProbeShapeType::Skylight || curEntry.mIsSkylight)
  369. {
  370. skylightPos = curEntry.getPosition();
  371. skylightPrefilterMap = curEntry.mPrefilterCubemap;
  372. skylightIrradMap = curEntry.mIrradianceCubemap;
  373. hasSkylight = true;
  374. continue;
  375. }
  376. //Setup
  377. Point3F probePos = curEntry.getPosition();
  378. Point3F refPos = curEntry.getPosition() +curEntry.mProbeRefOffset;
  379. probePositionsData[mEffectiveProbeCount] = Point4F(probePos.x, probePos.y, probePos.z,0);
  380. probeRefPositionsData[mEffectiveProbeCount] = Point4F(refPos.x, refPos.y, refPos.z, 0);
  381. probeWorldToObjData[mEffectiveProbeCount] = curEntry.getTransform();
  382. Point3F bbMin = refPos - curEntry.mProbeRefScale/2 * curEntry.getTransform().getScale();
  383. Point3F bbMax = refPos + curEntry.mProbeRefScale/2 * curEntry.getTransform().getScale();
  384. probeBBMinData[mEffectiveProbeCount] = Point4F(bbMin.x, bbMin.y, bbMin.z, 0);
  385. probeBBMaxData[mEffectiveProbeCount] = Point4F(bbMax.x, bbMax.y, bbMax.z, 0);
  386. probeConfigData[mEffectiveProbeCount] = Point4F(curEntry.mProbeShapeType,
  387. curEntry.mRadius,
  388. curEntry.mAtten,
  389. curEntry.mCubemapIndex);
  390. cubeMaps.push_back(curEntry.mPrefilterCubemap);
  391. irradMaps.push_back(curEntry.mIrradianceCubemap);
  392. cubemapIdxes.push_back(i);
  393. mEffectiveProbeCount++;
  394. }
  395. mProbesDirty = false;
  396. }
  397. void RenderProbeMgr::updateProbeTexture(ProbeRenderInst* probe)
  398. {
  399. //We don't stuff skylights into the array, so we can just skip out on this if it's a skylight
  400. if (probe->mIsSkylight)
  401. return;
  402. S32 probeIdx = ProbeRenderInst::all.find_next(probe);
  403. if (probeIdx != -1) //i mean, the opposite shouldn't even be possible
  404. updateProbeTexture(probeIdx);
  405. }
  406. void RenderProbeMgr::updateProbeTexture(U32 probeIdx)
  407. {
  408. if (probeIdx >= ProbeRenderInst::all.size())
  409. return;
  410. const U32 cubeIndex = ProbeRenderInst::all[probeIdx]->mCubemapIndex;
  411. mIrradianceArray->updateTexture(ProbeRenderInst::all[probeIdx]->mIrradianceCubemap, cubeIndex);
  412. mPrefilterArray->updateTexture(ProbeRenderInst::all[probeIdx]->mPrefilterCubemap, cubeIndex);
  413. Con::warnf("UpdatedProbeTexture - probeIdx: %u on cubeIndex %u, Irrad validity: %d, Prefilter validity: %d", probeIdx, cubeIndex,
  414. ProbeRenderInst::all[probeIdx]->mIrradianceCubemap->isInitialized(), ProbeRenderInst::all[probeIdx]->mPrefilterCubemap->isInitialized());
  415. }
  416. void RenderProbeMgr::_setupPerFrameParameters(const SceneRenderState *state)
  417. {
  418. PROFILE_SCOPE(RenderProbeMgr_SetupPerFrameParameters);
  419. }
  420. ProbeShaderConstants* RenderProbeMgr::getProbeShaderConstants(GFXShaderConstBuffer* buffer)
  421. {
  422. if (!buffer)
  423. return NULL;
  424. PROFILE_SCOPE(ProbeManager_GetProbeShaderConstants);
  425. GFXShader* shader = buffer->getShader();
  426. // Check to see if this is the same shader, we'll get hit repeatedly by
  427. // the same one due to the render bin loops.
  428. if (mLastShader.getPointer() != shader)
  429. {
  430. ProbeConstantMap::Iterator iter = mConstantLookup.find(shader);
  431. if (iter != mConstantLookup.end())
  432. {
  433. mLastConstants = iter->value;
  434. }
  435. else
  436. {
  437. ProbeShaderConstants* psc = new ProbeShaderConstants();
  438. mConstantLookup[shader] = psc;
  439. mLastConstants = psc;
  440. }
  441. // Set our new shader
  442. mLastShader = shader;
  443. }
  444. // Make sure that our current lighting constants are initialized
  445. if (mLastConstants && !mLastConstants->mInit)
  446. mLastConstants->init(shader);
  447. return mLastConstants;
  448. }
  449. void RenderProbeMgr::_update4ProbeConsts(const SceneData &sgData,
  450. MatrixSet &matSet,
  451. ProbeShaderConstants *probeShaderConsts,
  452. GFXShaderConstBuffer *shaderConsts)
  453. {
  454. PROFILE_SCOPE(ProbeManager_Update4ProbeConsts);
  455. // Skip over gathering lights if we don't have to!
  456. if (probeShaderConsts->isValid())
  457. {
  458. PROFILE_SCOPE(ProbeManager_Update4ProbeConsts_setProbes);
  459. const U32 MAX_FORWARD_PROBES = 4;
  460. static AlignedArray<Point4F> probePositionArray(MAX_FORWARD_PROBES, sizeof(Point4F));
  461. static AlignedArray<Point4F> probeBoxMinArray(MAX_FORWARD_PROBES, sizeof(Point4F));
  462. static AlignedArray<Point4F> probeBoxMaxArray(MAX_FORWARD_PROBES, sizeof(Point4F));
  463. static AlignedArray<Point4F> probeRefPositionArray(MAX_FORWARD_PROBES, sizeof(Point4F));
  464. static AlignedArray<Point4F> probeConfigArray(MAX_FORWARD_PROBES, sizeof(Point4F));
  465. Vector<MatrixF> probeWorldToObjArray;
  466. probeWorldToObjArray.setSize(MAX_FORWARD_PROBES);
  467. //static AlignedArray<CubemapData> probeCubemap(4, sizeof(CubemapData));
  468. //F32 range;
  469. // Need to clear the buffers so that we don't leak
  470. // lights from previous passes or have NaNs.
  471. dMemset(probePositionArray.getBuffer(), 0, probePositionArray.getBufferSize());
  472. dMemset(probeBoxMinArray.getBuffer(), 0, probeBoxMinArray.getBufferSize());
  473. dMemset(probeBoxMaxArray.getBuffer(), 0, probeBoxMaxArray.getBufferSize());
  474. dMemset(probeRefPositionArray.getBuffer(), 0, probeRefPositionArray.getBufferSize());
  475. dMemset(probeConfigArray.getBuffer(), 0, probeConfigArray.getBufferSize());
  476. matSet.restoreSceneViewProjection();
  477. //Array rendering
  478. U32 probeCount = ProbeRenderInst::all.size();
  479. S8 bestPickProbes[4] = { -1,-1,-1,-1 };
  480. U32 effectiveProbeCount = 0;
  481. bool hasSkylight = false;
  482. for (U32 i = 0; i < probeCount; i++)
  483. {
  484. //if (effectiveProbeCount >= MAX_FORWARD_PROBES)
  485. // break;
  486. const ProbeRenderInst& curEntry = *ProbeRenderInst::all[i];
  487. if (!curEntry.mIsEnabled)
  488. continue;
  489. if (!curEntry.mIsSkylight)
  490. {
  491. F32 dist = Point3F(sgData.objTrans->getPosition() - curEntry.getPosition()).len();
  492. if (dist > curEntry.mRadius || dist > curEntry.mExtents.len())
  493. continue;
  494. if(bestPickProbes[0] == -1 || (Point3F(sgData.objTrans->getPosition() - ProbeRenderInst::all[bestPickProbes[0]]->mPosition).len() > dist))
  495. bestPickProbes[0] = i;
  496. else if (bestPickProbes[1] == -1 || (Point3F(sgData.objTrans->getPosition() - ProbeRenderInst::all[bestPickProbes[1]]->mPosition).len() > dist))
  497. bestPickProbes[1] = i;
  498. else if (bestPickProbes[2] == -1 || (Point3F(sgData.objTrans->getPosition() - ProbeRenderInst::all[bestPickProbes[2]]->mPosition).len() > dist))
  499. bestPickProbes[2] = i;
  500. else if (bestPickProbes[3] == -1 || (Point3F(sgData.objTrans->getPosition() - ProbeRenderInst::all[bestPickProbes[3]]->mPosition).len() > dist))
  501. bestPickProbes[3] = i;
  502. }
  503. }
  504. //Grab our best probe picks
  505. for (U32 i = 0; i < 4; i++)
  506. {
  507. if (bestPickProbes[i] == -1)
  508. continue;
  509. const ProbeRenderInst& curEntry = *ProbeRenderInst::all[bestPickProbes[i]];
  510. probePositionArray[effectiveProbeCount] = curEntry.getPosition();
  511. probeRefPositionArray[effectiveProbeCount] = curEntry.mProbeRefOffset;
  512. probeWorldToObjArray[effectiveProbeCount] = curEntry.getTransform();
  513. probeWorldToObjData[mEffectiveProbeCount] = curEntry.getTransform();
  514. /*
  515. Point3F refPos = curEntry.getPosition() + curEntry.mProbeRefOffset;
  516. Point3F bbMin = refPos - curEntry.mProbeRefScale / 2 * curEntry.getTransform().getScale();
  517. Point3F bbMax = refPos + curEntry.mProbeRefScale / 2 * curEntry.getTransform().getScale();
  518. probeBoxMinArray[mEffectiveProbeCount] = Point4F(bbMin.x, bbMin.y, bbMin.z, 0);
  519. probeBoxMaxArray[mEffectiveProbeCount] = Point4F(bbMax.x, bbMax.y, bbMax.z, 0);*/
  520. probeBoxMinArray[effectiveProbeCount] = curEntry.mBounds.minExtents;
  521. probeBoxMaxArray[effectiveProbeCount] = curEntry.mBounds.maxExtents;
  522. probeConfigArray[effectiveProbeCount] = Point4F(curEntry.mProbeShapeType,
  523. curEntry.mRadius,
  524. curEntry.mAtten,
  525. curEntry.mCubemapIndex);
  526. effectiveProbeCount++;
  527. }
  528. shaderConsts->setSafe(probeShaderConsts->mProbeCountSC, (float)effectiveProbeCount);
  529. shaderConsts->setSafe(probeShaderConsts->mProbePositionSC, probePositionArray);
  530. shaderConsts->setSafe(probeShaderConsts->mProbeRefPosSC, probeRefPositionArray);
  531. shaderConsts->set(probeShaderConsts->mWorldToObjArraySC, probeWorldToObjArray.address(), effectiveProbeCount, GFXSCT_Float4x4);
  532. shaderConsts->setSafe(probeShaderConsts->mProbeBoxMinSC, probeBoxMinArray);
  533. shaderConsts->setSafe(probeShaderConsts->mProbeBoxMaxSC, probeBoxMaxArray);
  534. shaderConsts->setSafe(probeShaderConsts->mProbeConfigDataSC, probeConfigArray);
  535. GFX->setCubeArrayTexture(probeShaderConsts->mProbeSpecularCubemapSC->getSamplerRegister(), mPrefilterArray);
  536. GFX->setCubeArrayTexture(probeShaderConsts->mProbeIrradianceCubemapSC->getSamplerRegister(), mIrradianceArray);
  537. }
  538. if (probeShaderConsts->mBRDFTextureMap->isValid())
  539. {
  540. if (!mBRDFTexture.isValid())
  541. {
  542. //try to fetch it
  543. mBRDFTexture.set("core/art/pbr/brdfTexture.dds", &GFXStaticTextureSRGBProfile, "BRDF Texture");
  544. }
  545. GFX->setTexture(probeShaderConsts->mBRDFTextureMap->getSamplerRegister(), mBRDFTexture.getPointer());
  546. }
  547. //check for skylight action
  548. if (probeShaderConsts->mSkylightIrradMap->isValid()
  549. && probeShaderConsts->mSkylightSpecularMap->isValid())
  550. {
  551. //Array rendering
  552. U32 probeCount = ProbeRenderInst::all.size();
  553. bool hasSkylight = false;
  554. for (U32 i = 0; i < probeCount; i++)
  555. {
  556. const ProbeRenderInst& curEntry = *ProbeRenderInst::all[i];
  557. if (!curEntry.mIsEnabled)
  558. continue;
  559. if (curEntry.mIsSkylight)
  560. {
  561. if (curEntry.mPrefilterCubemap.isValid() && curEntry.mPrefilterCubemap.isValid())
  562. {
  563. GFX->setCubeTexture(probeShaderConsts->mSkylightSpecularMap->getSamplerRegister(), curEntry.mPrefilterCubemap);
  564. GFX->setCubeTexture(probeShaderConsts->mSkylightIrradMap->getSamplerRegister(), curEntry.mIrradianceCubemap);
  565. shaderConsts->setSafe(probeShaderConsts->mHasSkylight, 1.0f);
  566. hasSkylight = true;
  567. break;
  568. }
  569. }
  570. }
  571. if (!hasSkylight)
  572. shaderConsts->setSafe(probeShaderConsts->mHasSkylight, 0.0f);
  573. }
  574. /*else
  575. {
  576. if (probeCubemapSC->isValid())
  577. {
  578. for (U32 i = 0; i < 4; ++i)
  579. GFX->setCubeTexture(probeCubemapSC->getSamplerRegister() + i, NULL);
  580. }
  581. }*/
  582. }
  583. void RenderProbeMgr::setProbeInfo(ProcessedMaterial *pmat,
  584. const Material *mat,
  585. const SceneData &sgData,
  586. const SceneRenderState *state,
  587. U32 pass,
  588. GFXShaderConstBuffer *shaderConsts)
  589. {
  590. // Skip this if we're rendering from the deferred bin.
  591. if (sgData.binType == SceneData::DeferredBin)
  592. return;
  593. // if (mRegisteredProbes.empty())
  594. // return;
  595. PROFILE_SCOPE(ProbeManager_setProbeInfo);
  596. ProbeShaderConstants *psc = getProbeShaderConstants(shaderConsts);
  597. // NOTE: If you encounter a crash from this point forward
  598. // while setting a shader constant its probably because the
  599. // mConstantLookup has bad shaders/constants in it.
  600. //
  601. // This is a known crash bug that can occur if materials/shaders
  602. // are reloaded and the light manager is not reset.
  603. //
  604. // We should look to fix this by clearing the table.
  605. MatrixSet matSet = state->getRenderPass()->getMatrixSet();
  606. // Update the forward shading light constants.
  607. _update4ProbeConsts(sgData, matSet, psc, shaderConsts);
  608. }
  609. //-----------------------------------------------------------------------------
  610. // render objects
  611. //-----------------------------------------------------------------------------
  612. void RenderProbeMgr::render( SceneRenderState *state )
  613. {
  614. //PROFILE_SCOPE(RenderProbeMgr_render);
  615. if (getProbeArrayEffect() == nullptr)
  616. return;
  617. if (mProbesDirty)
  618. _setupStaticParameters();
  619. // Early out if nothing to draw.
  620. if (!RenderProbeMgr::smRenderReflectionProbes || !state->isDiffusePass() || (!ProbeRenderInst::all.size() || mEffectiveProbeCount == 0 || mCubeMapCount != 0 ) && !hasSkylight)
  621. {
  622. getProbeArrayEffect()->setSkip(true);
  623. return;
  624. }
  625. GFXTransformSaver saver;
  626. GFXDEBUGEVENT_SCOPE(RenderProbeMgr_render, ColorI::WHITE);
  627. // Initialize and set the per-frame parameters after getting
  628. // the vector light material as we use lazy creation.
  629. //_setupPerFrameParameters(state);
  630. //Visualization
  631. String useDebugAtten = Con::getVariable("$Probes::showAttenuation", "0");
  632. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_ATTENUATION", useDebugAtten);
  633. String useDebugSpecCubemap = Con::getVariable("$Probes::showSpecularCubemaps", "0");
  634. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_SPECCUBEMAP", useDebugSpecCubemap);
  635. String useDebugDiffuseCubemap = Con::getVariable("$Probes::showDiffuseCubemaps", "0");
  636. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_DIFFCUBEMAP", useDebugDiffuseCubemap);
  637. String useDebugContrib = Con::getVariable("$Probes::showProbeContrib", "0");
  638. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_CONTRIB", useDebugContrib);
  639. //Array rendering
  640. //U32 probeCount = ProbeRenderInst::all.size();
  641. mProbeArrayEffect->setShaderConst("$hasSkylight", (float)hasSkylight);
  642. if (hasSkylight)
  643. {
  644. mProbeArrayEffect->setCubemapTexture(6, skylightPrefilterMap);
  645. mProbeArrayEffect->setCubemapTexture(7, skylightIrradMap);
  646. }
  647. mProbeArrayEffect->setShaderConst("$numProbes", (float)mEffectiveProbeCount);
  648. mProbeArrayEffect->setShaderConst("$cubeMips", (float)mMipCount);
  649. if (mEffectiveProbeCount != 0)
  650. {
  651. mProbeArrayEffect->setCubemapArrayTexture(4, mPrefilterArray);
  652. mProbeArrayEffect->setCubemapArrayTexture(5, mIrradianceArray);
  653. if (useDebugContrib == String("1"))
  654. {
  655. MRandomLCG RandomGen;
  656. RandomGen.setSeed(mEffectiveProbeCount);
  657. //also set up some colors
  658. Vector<Point4F> contribColors;
  659. contribColors.setSize(MAXPROBECOUNT);
  660. for (U32 i = 0; i < mEffectiveProbeCount; i++)
  661. {
  662. //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
  663. if (i == 0)
  664. contribColors[i] = Point4F(1, 0, 0, 1);
  665. else if (i == 1)
  666. contribColors[i] = Point4F(0, 1, 0, 1);
  667. else if (i == 2)
  668. contribColors[i] = Point4F(0, 0, 1, 1);
  669. else
  670. contribColors[i] = Point4F(RandomGen.randF(0, 1), RandomGen.randF(0, 1), RandomGen.randF(0, 1), 1);
  671. }
  672. mProbeArrayEffect->setShaderConst("$probeContribColors", contribColors);
  673. }
  674. mProbeArrayEffect->setShaderConst("$inProbePosArray", probePositionsData);
  675. mProbeArrayEffect->setShaderConst("$inRefPosArray", probeRefPositionsData);
  676. mProbeArrayEffect->setShaderConst("$worldToObjArray", probeWorldToObjData);
  677. mProbeArrayEffect->setShaderConst("$bbMinArray", probeBBMinData);
  678. mProbeArrayEffect->setShaderConst("$bbMaxArray", probeBBMaxData);
  679. mProbeArrayEffect->setShaderConst("$probeConfigData", probeConfigData);
  680. }
  681. // Make sure the effect is gonna render.
  682. getProbeArrayEffect()->setSkip(false);
  683. //PROFILE_END();
  684. }
  685. void RenderProbeMgr::bakeProbe(ReflectionProbe *probe)
  686. {
  687. GFXDEBUGEVENT_SCOPE(RenderProbeMgr_Bake, ColorI::WHITE);
  688. Con::warnf("RenderProbeMgr::bakeProbe() - Beginning bake!");
  689. U32 startMSTime = Platform::getRealMilliseconds();
  690. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  691. U32 resolution = Con::getIntVariable("$pref::ReflectionProbes::BakeResolution", 64);
  692. U32 prefilterMipLevels = mLog2(F32(resolution));
  693. bool renderWithProbes = Con::getIntVariable("$pref::ReflectionProbes::RenderWithProbes", false);
  694. ReflectionProbe *clientProbe = static_cast<ReflectionProbe*>(probe->getClientObject());
  695. if (clientProbe == nullptr)
  696. return;
  697. String probePrefilterPath = clientProbe->getPrefilterMapPath();
  698. String probeIrradPath = clientProbe->getIrradianceMapPath();
  699. if (clientProbe->mReflectionModeType != ReflectionProbe::DynamicCubemap)
  700. {
  701. //Prep our bake path
  702. if (probePrefilterPath.isEmpty() || probeIrradPath.isEmpty())
  703. {
  704. Con::errorf("RenderProbeMgr::bake() - Unable to bake our captures because probe doesn't have a path set");
  705. return;
  706. }
  707. }
  708. // Save the current transforms so we can restore
  709. // it for child control rendering below.
  710. GFXTransformSaver saver;
  711. bool probeRenderState = RenderProbeMgr::smRenderReflectionProbes;
  712. F32 farPlane = 1000.0f;
  713. ReflectorDesc reflDesc;
  714. reflDesc.texSize = resolution;
  715. reflDesc.farDist = farPlane;
  716. reflDesc.detailAdjust = 1;
  717. reflDesc.objectTypeMask = -1;
  718. CubeReflector cubeRefl;
  719. cubeRefl.registerReflector(probe, &reflDesc);
  720. ReflectParams reflParams;
  721. //need to get the query somehow. Likely do some sort of get function to fetch from the guiTSControl that's active
  722. CameraQuery query; //need to get the last cameraQuery
  723. query.fov = 90; //90 degree slices for each of the 6 sides
  724. query.nearPlane = 0.1f;
  725. query.farPlane = farPlane;
  726. query.headMatrix = MatrixF();
  727. query.cameraMatrix = clientProbe->getTransform();
  728. Frustum culler;
  729. culler.set(false,
  730. query.fov,
  731. (F32)resolution / (F32)resolution,
  732. query.nearPlane,
  733. query.farPlane,
  734. query.cameraMatrix);
  735. S32 stereoTarget = GFX->getCurrentStereoTarget();
  736. Point2I maxRes(2048, 2048); //basically a boundary so we don't go over this and break stuff
  737. reflParams.culler = culler;
  738. reflParams.eyeId = stereoTarget;
  739. reflParams.query = &query;
  740. reflParams.startOfUpdateMs = startMSTime;
  741. reflParams.viewportExtent = maxRes;
  742. if (!renderWithProbes)
  743. RenderProbeMgr::smRenderReflectionProbes = false;
  744. cubeRefl.updateReflection(reflParams);
  745. //Now, save out the maps
  746. //create irridiance cubemap
  747. if (cubeRefl.getCubemap())
  748. {
  749. //Just to ensure we're prepped for the generation
  750. clientProbe->createClientResources();
  751. //Prep it with whatever resolution we've dictated for our bake
  752. if (clientProbe->mUseHDRCaptures)
  753. {
  754. clientProbe->mIrridianceMap->mCubemap->initDynamic(resolution, GFXFormatR16G16B16A16F);
  755. clientProbe->mPrefilterMap->mCubemap->initDynamic(resolution, GFXFormatR16G16B16A16F);
  756. }
  757. else
  758. {
  759. clientProbe->mIrridianceMap->mCubemap->initDynamic(resolution, GFXFormatR8G8B8A8);
  760. clientProbe->mPrefilterMap->mCubemap->initDynamic(resolution, GFXFormatR8G8B8A8);
  761. }
  762. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  763. IBLUtilities::GenerateIrradianceMap(renderTarget, cubeRefl.getCubemap(), clientProbe->mIrridianceMap->mCubemap);
  764. IBLUtilities::GeneratePrefilterMap(renderTarget, cubeRefl.getCubemap(), prefilterMipLevels, clientProbe->mPrefilterMap->mCubemap);
  765. U32 endMSTime = Platform::getRealMilliseconds();
  766. F32 diffTime = F32(endMSTime - startMSTime);
  767. Con::warnf("RenderProbeMgr::bake() - Finished Capture! Took %g milliseconds", diffTime);
  768. Con::warnf("RenderProbeMgr::bake() - Beginning save now!");
  769. IBLUtilities::SaveCubeMap(clientProbe->getIrradianceMapPath(), clientProbe->mIrridianceMap->mCubemap);
  770. IBLUtilities::SaveCubeMap(clientProbe->getPrefilterMapPath(), clientProbe->mPrefilterMap->mCubemap);
  771. }
  772. else
  773. {
  774. Con::errorf("RenderProbeMgr::bake() - Didn't generate a valid scene capture cubemap, unable to generate prefilter and irradiance maps!");
  775. }
  776. if (!renderWithProbes)
  777. RenderProbeMgr::smRenderReflectionProbes = probeRenderState;
  778. cubeRefl.unregisterReflector();
  779. U32 endMSTime = Platform::getRealMilliseconds();
  780. F32 diffTime = F32(endMSTime - startMSTime);
  781. Con::warnf("RenderProbeMgr::bake() - Finished bake! Took %g milliseconds", diffTime);
  782. }
  783. void RenderProbeMgr::bakeProbes()
  784. {
  785. //TODO: make this just find every probe in the current missionGroup and run the bake on it automagically
  786. }
  787. DefineEngineMethod(RenderProbeMgr, bakeProbe, void, (ReflectionProbe* probe), (nullAsType< ReflectionProbe*>()),
  788. "@brief returns true if control object is inside the fog\n\n.")
  789. {
  790. if(probe != nullptr)
  791. object->bakeProbe(probe);
  792. }