renderProbeMgr.cpp 31 KB

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