probeManager.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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 "platform/platform.h"
  23. #include "lighting/probeManager.h"
  24. #include "console/console.h"
  25. #include "console/consoleTypes.h"
  26. #include "core/util/safeDelete.h"
  27. #include "console/sim.h"
  28. #include "console/simSet.h"
  29. #include "scene/sceneManager.h"
  30. #include "materials/materialManager.h"
  31. #include "materials/sceneData.h"
  32. #include "lighting/lightInfo.h"
  33. #include "lighting/lightingInterfaces.h"
  34. #include "T3D/gameBase/gameConnection.h"
  35. #include "gfx/gfxStringEnumTranslate.h"
  36. #include "console/engineAPI.h"
  37. #include "renderInstance/renderDeferredMgr.h"
  38. #include "shaderGen/shaderGenVars.h"
  39. #include "math/util/sphereMesh.h"
  40. Signal<void(const char*,bool)> ProbeManager::smActivateSignal;
  41. ProbeManager *ProbeManager::smProbeManager = NULL;
  42. bool ProbeManager::smRenderReflectionProbes = true;
  43. //
  44. //
  45. ProbeRenderInst::ProbeRenderInst() : SystemInterface(),
  46. mTransform(true),
  47. mDirty(false),
  48. mAmbient(0.0f, 0.0f, 0.0f, 1.0f),
  49. mPriority(1.0f),
  50. mScore(0.0f),
  51. mDebugRender(false),
  52. mCubemap(NULL),
  53. mIrradianceCubemap(NULL),
  54. mBRDFTexture(NULL),
  55. mRadius(1.0f),
  56. mIntensity(1.0f),
  57. mProbePosOffset(0,0,0),
  58. numPrims(0)
  59. {
  60. for (U32 i = 0; i < 5; ++i)
  61. {
  62. mSHConstants[i] = 0;
  63. }
  64. }
  65. ProbeRenderInst::~ProbeRenderInst()
  66. {
  67. if (mCubemap && !mCubemap->isNull())
  68. {
  69. mCubemap->getPointer()->destroySelf();
  70. mCubemap->free();
  71. }
  72. if (mIrradianceCubemap && !mIrradianceCubemap->isNull())
  73. {
  74. mIrradianceCubemap->getPointer()->destroySelf();
  75. mIrradianceCubemap->free();
  76. }
  77. if (mBRDFTexture && !mBRDFTexture->isNull())
  78. {
  79. mBRDFTexture->getPointer()->destroySelf();
  80. mBRDFTexture->free();
  81. }
  82. }
  83. void ProbeRenderInst::set(const ProbeRenderInst *probeInfo)
  84. {
  85. mTransform = probeInfo->mTransform;
  86. mAmbient = probeInfo->mAmbient;
  87. mCubemap = probeInfo->mCubemap;
  88. mIrradianceCubemap = probeInfo->mIrradianceCubemap;
  89. mBRDFTexture = probeInfo->mBRDFTexture;
  90. mRadius = probeInfo->mRadius;
  91. mIntensity = probeInfo->mIntensity;
  92. mProbeShapeType = probeInfo->mProbeShapeType;
  93. numPrims = probeInfo->numPrims;
  94. numVerts = probeInfo->numVerts;
  95. numIndicesForPoly = probeInfo->numIndicesForPoly;
  96. mBounds = probeInfo->mBounds;
  97. for (U32 i = 0; i < 9; i++)
  98. {
  99. mSHTerms[i] = probeInfo->mSHTerms[i];
  100. }
  101. for (U32 i = 0; i < 5; i++)
  102. {
  103. mSHConstants[i] = probeInfo->mSHConstants[i];
  104. }
  105. }
  106. void ProbeRenderInst::getWorldToLightProj(MatrixF *outMatrix) const
  107. {
  108. *outMatrix = getTransform();
  109. outMatrix->inverse();
  110. }
  111. ProbeShaderConstants::ProbeShaderConstants()
  112. : mInit(false),
  113. mShader(NULL),
  114. mProbeParamsSC(NULL),
  115. mProbePositionSC(NULL),
  116. mProbeRadiusSC(NULL),
  117. mProbeBoxMinSC(NULL),
  118. mProbeBoxMaxSC(NULL),
  119. mProbeIsSphereSC(NULL),
  120. mProbeLocalPosSC(NULL),
  121. mProbeCubemapSC(NULL)
  122. {
  123. }
  124. ProbeShaderConstants::~ProbeShaderConstants()
  125. {
  126. if (mShader.isValid())
  127. {
  128. mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
  129. mShader = NULL;
  130. }
  131. }
  132. void ProbeShaderConstants::init(GFXShader* shader)
  133. {
  134. if (mShader.getPointer() != shader)
  135. {
  136. if (mShader.isValid())
  137. mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
  138. mShader = shader;
  139. mShader->getReloadSignal().notify(this, &ProbeShaderConstants::_onShaderReload);
  140. }
  141. mProbeParamsSC = shader->getShaderConstHandle("$probeParams");
  142. //Reflection Probes
  143. mProbePositionSC = shader->getShaderConstHandle(ShaderGenVars::probePosition);
  144. mProbeRadiusSC = shader->getShaderConstHandle(ShaderGenVars::probeRadius);
  145. mProbeBoxMinSC = shader->getShaderConstHandle(ShaderGenVars::probeBoxMin);
  146. mProbeBoxMaxSC = shader->getShaderConstHandle(ShaderGenVars::probeBoxMax);
  147. mProbeIsSphereSC = shader->getShaderConstHandle(ShaderGenVars::probeIsSphere);
  148. mProbeLocalPosSC = shader->getShaderConstHandle(ShaderGenVars::probeLocalPos);
  149. mProbeCubemapSC = shader->getShaderConstHandle(ShaderGenVars::probeCubemap);
  150. mInit = true;
  151. }
  152. void ProbeShaderConstants::_onShaderReload()
  153. {
  154. if (mShader.isValid())
  155. init(mShader);
  156. }
  157. ProbeManager::ProbeManager()
  158. : mSceneManager( NULL ),
  159. mCullPos( Point3F::Zero )
  160. {
  161. mLastShader = NULL;
  162. mLastConstants = NULL;
  163. mSkylightMaterial = nullptr;
  164. mReflectProbeMaterial = nullptr;
  165. }
  166. ProbeManager::~ProbeManager()
  167. {
  168. }
  169. ProbeRenderInst* ProbeManager::createProbeInfo(ProbeRenderInst* probe /* = NULL */)
  170. {
  171. ProbeRenderInst *outProbe = (probe != NULL) ? probe : new ProbeRenderInst;
  172. /*ProbeManagerMap &ProbeManagers = _getProbeManagers();
  173. ProbeManagerMap::Iterator iter = ProbeManagers.begin();
  174. for ( ; iter != ProbeManagers.end(); iter++ )
  175. {
  176. ProbeManager *lm = iter->value;
  177. lm->_addLightInfoEx( outLight );
  178. }*/
  179. return outProbe;
  180. }
  181. /*void ProbeManager::initLightFields()
  182. {
  183. ProbeManagerMap &ProbeManagers = _getProbeManagers();
  184. ProbeManagerMap::Iterator iter = ProbeManagers.begin();
  185. for ( ; iter != ProbeManagers.end(); iter++ )
  186. {
  187. ProbeManager *lm = iter->value;
  188. lm->_initLightFields();
  189. }
  190. }*/
  191. IMPLEMENT_GLOBAL_CALLBACK( onProbeManagerActivate, void, ( const char *name ), ( name ),
  192. "A callback called by the engine when a light manager is activated.\n"
  193. "@param name The name of the light manager being activated.\n"
  194. "@ingroup Lighting\n" );
  195. void ProbeManager::activate( SceneManager *sceneManager )
  196. {
  197. AssertFatal( sceneManager, "ProbeManager::activate() - Got null scene manager!" );
  198. //AssertFatal( mIsActive == false, "ProbeManager::activate() - Already activated!" );
  199. AssertFatal(smProbeManager == NULL, "ProbeManager::activate() - A previous ProbeManager is still active!" );
  200. mSceneManager = sceneManager;
  201. smProbeManager = this;
  202. }
  203. IMPLEMENT_GLOBAL_CALLBACK( onProbeManagerDeactivate, void, ( const char *name ), ( name ),
  204. "A callback called by the engine when a light manager is deactivated.\n"
  205. "@param name The name of the light manager being deactivated.\n"
  206. "@ingroup Lighting\n" );
  207. void ProbeManager::deactivate()
  208. {
  209. //AssertFatal( mIsActive == true, "ProbeManager::deactivate() - Already deactivated!" );
  210. AssertFatal( smProbeManager == this, "ProbeManager::activate() - This isn't the active light manager!" );
  211. //if( Sim::getRootGroup() ) // To protect against shutdown.
  212. // onProbeManagerDeactivate_callback( getName() );
  213. //mIsActive = false;
  214. mSceneManager = NULL;
  215. smProbeManager = NULL;
  216. }
  217. ProbeShaderConstants* ProbeManager::getProbeShaderConstants(GFXShaderConstBuffer* buffer)
  218. {
  219. if (!buffer)
  220. return NULL;
  221. PROFILE_SCOPE(ProbeManager_GetProbeShaderConstants);
  222. GFXShader* shader = buffer->getShader();
  223. // Check to see if this is the same shader, we'll get hit repeatedly by
  224. // the same one due to the render bin loops.
  225. if (mLastShader.getPointer() != shader)
  226. {
  227. ProbeConstantMap::Iterator iter = mConstantLookup.find(shader);
  228. if (iter != mConstantLookup.end())
  229. {
  230. mLastConstants = iter->value;
  231. }
  232. else
  233. {
  234. ProbeShaderConstants* psc = new ProbeShaderConstants();
  235. mConstantLookup[shader] = psc;
  236. mLastConstants = psc;
  237. }
  238. // Set our new shader
  239. mLastShader = shader;
  240. }
  241. mLastConstants = new ProbeShaderConstants();
  242. // Make sure that our current lighting constants are initialized
  243. if (!mLastConstants->mInit)
  244. mLastConstants->init(shader);
  245. return mLastConstants;
  246. }
  247. void ProbeManager::_update4ProbeConsts( const SceneData &sgData,
  248. MatrixSet &matSet,
  249. GFXShaderConstHandle *probePositionSC,
  250. GFXShaderConstHandle *probeRadiusSC,
  251. GFXShaderConstHandle *probeBoxMinSC,
  252. GFXShaderConstHandle *probeBoxMaxSC,
  253. GFXShaderConstHandle *probeCubemapSC,
  254. GFXShaderConstHandle *probeIsSphereSC,
  255. GFXShaderConstHandle *probeLocalPosSC,
  256. GFXShaderConstBuffer *shaderConsts )
  257. {
  258. PROFILE_SCOPE( ProbeManager_Update4ProbeConsts );
  259. // Skip over gathering lights if we don't have to!
  260. if (probePositionSC->isValid() ||
  261. probeRadiusSC->isValid() ||
  262. probeBoxMinSC->isValid() ||
  263. probeBoxMaxSC->isValid() ||
  264. probeCubemapSC->isValid() && (!ProbeRenderInst::all.empty()))
  265. {
  266. PROFILE_SCOPE(ProbeManager_Update4ProbeConsts_setProbes);
  267. static AlignedArray<Point3F> probePositions(4, sizeof(Point3F));
  268. static AlignedArray<F32> probeRadius(4, sizeof(F32));
  269. static AlignedArray<Point3F> probeBoxMins(4, sizeof(Point3F));
  270. static AlignedArray<Point3F> probeBoxMaxs(4, sizeof(Point3F));
  271. static AlignedArray<Point3F> probeLocalPositions(4, sizeof(Point3F));
  272. static AlignedArray<F32> probeIsSphere(4, sizeof(F32));
  273. //static AlignedArray<CubemapData> probeCubemap(4, sizeof(CubemapData));
  274. F32 range;
  275. // Need to clear the buffers so that we don't leak
  276. // lights from previous passes or have NaNs.
  277. dMemset(probePositions.getBuffer(), 0, probePositions.getBufferSize());
  278. dMemset(probeRadius.getBuffer(), 0, probeRadius.getBufferSize());
  279. dMemset(probeBoxMins.getBuffer(), 0, probeBoxMins.getBufferSize());
  280. dMemset(probeBoxMaxs.getBuffer(), 0, probeBoxMaxs.getBufferSize());
  281. dMemset(probeLocalPositions.getBuffer(), 0, probeLocalPositions.getBufferSize());
  282. dMemset(probeIsSphere.getBuffer(), 0, probeRadius.getBufferSize());
  283. //dMemset(probeCubemap.getBuffer(), 0, probeCubemap.getBufferSize());
  284. matSet.restoreSceneViewProjection();
  285. const MatrixF &worldToCameraXfm = matSet.getWorldToCamera();
  286. // Gather the data for the first 4 probes.
  287. const ProbeRenderInst *probe;
  288. for (U32 i = 0; i < 4; i++)
  289. {
  290. if (i >= ProbeRenderInst::all.size())
  291. break;
  292. probe = ProbeRenderInst::all[i];
  293. if (!probe)
  294. continue;
  295. // The light positions and spot directions are
  296. // in SoA order to make optimal use of the GPU.
  297. const Point3F &probePos = probe->getPosition();
  298. probePositions[i].x = probePos.x;
  299. probePositions[i].y = probePos.y;
  300. probePositions[i].z = probePos.z;
  301. probeRadius[i] = probe->mRadius;
  302. const Point3F &minExt = probe->mBounds.minExtents;
  303. probeBoxMins[i].x = minExt.x;
  304. probeBoxMins[i].y = minExt.y;
  305. probeBoxMins[i].z = minExt.z;
  306. const Point3F &maxExt = probe->mBounds.maxExtents;
  307. probeBoxMaxs[i].x = maxExt.x;
  308. probeBoxMaxs[i].y = maxExt.y;
  309. probeBoxMaxs[i].z = maxExt.z;
  310. probeIsSphere[i] = probe->mProbeShapeType == ProbeRenderInst::Sphere ? 1.0 : 0.0;
  311. Point3F localProbePos;
  312. worldToCameraXfm.mulP(probe->getPosition(), &localProbePos);
  313. probeLocalPositions[i].x = localProbePos.x;
  314. probeLocalPositions[i].y = localProbePos.y;
  315. probeLocalPositions[i].z = localProbePos.z;
  316. if (probe->mCubemap && !probe->mCubemap->isNull())
  317. {
  318. S32 samplerReg = probeCubemapSC->getSamplerRegister();
  319. if(samplerReg != -1)
  320. GFX->setCubeTexture(samplerReg + i, probe->mCubemap->getPointer());
  321. }
  322. }
  323. shaderConsts->setSafe(probePositionSC, probePositions);
  324. shaderConsts->setSafe(probeRadiusSC, probeRadius);
  325. shaderConsts->setSafe(probeBoxMinSC, probeBoxMins);
  326. shaderConsts->setSafe(probeBoxMaxSC, probeBoxMaxs);
  327. shaderConsts->setSafe(probeLocalPosSC, probeLocalPositions);
  328. shaderConsts->setSafe(probeIsSphereSC, probeIsSphere);
  329. //
  330. //shaderConsts->setSafe(lightSpotAngleSC, lightSpotAngle);
  331. //shaderConsts->setSafe(lightSpotFalloffSC, lightSpotFalloff);
  332. }
  333. else
  334. {
  335. /*if (probe->mCubemap && !probe->mCubemap->isNull())
  336. {
  337. GFX->setCubeTexture(1, probe->mCubemap->getPointer());
  338. }*/
  339. if (probeCubemapSC->isValid())
  340. {
  341. for(U32 i=0; i < 4; ++i)
  342. GFX->setCubeTexture(probeCubemapSC->getSamplerRegister() + i, NULL);
  343. }
  344. }
  345. }
  346. void ProbeManager::setProbeInfo(ProcessedMaterial *pmat,
  347. const Material *mat,
  348. const SceneData &sgData,
  349. const SceneRenderState *state,
  350. U32 pass,
  351. GFXShaderConstBuffer *shaderConsts)
  352. {
  353. // Skip this if we're rendering from the deferred bin.
  354. if ( sgData.binType == SceneData::DeferredBin )
  355. return;
  356. // if (mRegisteredProbes.empty())
  357. // return;
  358. PROFILE_SCOPE(ProbeManager_setProbeInfo);
  359. ProbeShaderConstants *psc = getProbeShaderConstants(shaderConsts);
  360. //ProbeInfo *probe;
  361. //probe = mRegisteredProbes[0];
  362. // NOTE: If you encounter a crash from this point forward
  363. // while setting a shader constant its probably because the
  364. // mConstantLookup has bad shaders/constants in it.
  365. //
  366. // This is a known crash bug that can occur if materials/shaders
  367. // are reloaded and the light manager is not reset.
  368. //
  369. // We should look to fix this by clearing the table.
  370. MatrixSet matSet = state->getRenderPass()->getMatrixSet();
  371. // Update the forward shading light constants.
  372. _update4ProbeConsts( sgData,
  373. matSet,
  374. psc->mProbePositionSC,
  375. psc->mProbeRadiusSC,
  376. psc->mProbeBoxMinSC,
  377. psc->mProbeBoxMaxSC,
  378. psc->mProbeCubemapSC,
  379. psc->mProbeIsSphereSC,
  380. psc->mProbeLocalPosSC,
  381. shaderConsts );
  382. // Static
  383. /*if (lsm && light->getCastShadows())
  384. {
  385. if (psc->mWorldToLightProjSC->isValid())
  386. shaderConsts->set(psc->mWorldToLightProjSC,
  387. lsm->getWorldToLightProj(),
  388. psc->mWorldToLightProjSC->getType());
  389. if (psc->mViewToLightProjSC->isValid())
  390. {
  391. // TODO: Should probably cache these results and
  392. // not do this mul here on every material that needs
  393. // this transform.
  394. shaderConsts->set(psc->mViewToLightProjSC,
  395. lsm->getWorldToLightProj() * state->getCameraTransform(),
  396. psc->mViewToLightProjSC->getType());
  397. }
  398. shaderConsts->setSafe(psc->mShadowMapSizeSC, 1.0f / (F32)lsm->getTexSize());
  399. // Do this last so that overrides can properly override parameters previously set
  400. lsm->setShaderParameters(shaderConsts, psc);
  401. }
  402. else
  403. {
  404. if (psc->mViewToLightProjSC->isValid())
  405. {
  406. // TODO: Should probably cache these results and
  407. // not do this mul here on every material that needs
  408. // this transform.
  409. MatrixF proj;
  410. light->getWorldToLightProj(&proj);
  411. shaderConsts->set(psc->mViewToLightProjSC,
  412. proj * state->getCameraTransform(),
  413. psc->mViewToLightProjSC->getType());
  414. }
  415. }
  416. // Dynamic
  417. if (dynamicShadowMap)
  418. {
  419. if (psc->mDynamicWorldToLightProjSC->isValid())
  420. shaderConsts->set(psc->mDynamicWorldToLightProjSC,
  421. dynamicShadowMap->getWorldToLightProj(),
  422. psc->mDynamicWorldToLightProjSC->getType());
  423. if (psc->mDynamicViewToLightProjSC->isValid())
  424. {
  425. // TODO: Should probably cache these results and
  426. // not do this mul here on every material that needs
  427. // this transform.
  428. shaderConsts->set(psc->mDynamicViewToLightProjSC,
  429. dynamicShadowMap->getWorldToLightProj() * state->getCameraTransform(),
  430. psc->mDynamicViewToLightProjSC->getType());
  431. }
  432. shaderConsts->setSafe(psc->mShadowMapSizeSC, 1.0f / (F32)dynamicShadowMap->getTexSize());
  433. // Do this last so that overrides can properly override parameters previously set
  434. dynamicShadowMap->setShaderParameters(shaderConsts, psc);
  435. }
  436. else
  437. {
  438. if (psc->mDynamicViewToLightProjSC->isValid())
  439. {
  440. // TODO: Should probably cache these results and
  441. // not do this mul here on every material that needs
  442. // this transform.
  443. MatrixF proj;
  444. light->getWorldToLightProj(&proj);
  445. shaderConsts->set(psc->mDynamicViewToLightProjSC,
  446. proj * state->getCameraTransform(),
  447. psc->mDynamicViewToLightProjSC->getType());
  448. }
  449. }*/
  450. }
  451. /// Allows us to set textures during the Material::setTextureStage call, return true if we've done work.
  452. bool ProbeManager::setTextureStage(const SceneData &sgData,
  453. const U32 currTexFlag,
  454. const U32 textureSlot,
  455. GFXShaderConstBuffer *shaderConsts,
  456. ShaderConstHandles *handles)
  457. {
  458. return false;
  459. }
  460. AvailableSLInterfaces* ProbeManager::getSceneLightingInterface()
  461. {
  462. //if ( !mAvailableSLInterfaces )
  463. // mAvailableSLInterfaces = new AvailableSLInterfaces();
  464. return NULL;
  465. }
  466. void ProbeManager::updateDirtyProbes()
  467. {
  468. for (U32 i = 0; i < ProbeRenderInst::all.size(); i++)
  469. {
  470. ProbeRenderInst* probe = ProbeRenderInst::all[i];
  471. if (probe->mDirty)
  472. {
  473. //make sure we have a fill-out on our primitives, materials, etc
  474. //so we don't have to always force an update when it's not needed
  475. if (probe->mIsSkylight)
  476. {
  477. setupSkylightProbe(probe);
  478. }
  479. else
  480. {
  481. if (probe->mProbeShapeType == ProbeRenderInst::Sphere)
  482. {
  483. setupSphereReflectionProbe(probe);
  484. }
  485. else if(probe->mProbeShapeType == ProbeRenderInst::Box)
  486. {
  487. setupConvexReflectionProbe(probe);
  488. }
  489. }
  490. probe->mDirty = false;
  491. }
  492. }
  493. }
  494. ProbeManager::SkylightMaterialInfo* ProbeManager::getSkylightMaterial()
  495. {
  496. PROFILE_SCOPE(AdvancedLightBinManager_getSkylightMaterial);
  497. //ReflectProbeMaterialInfo *info = NULL;
  498. if (!mSkylightMaterial)
  499. // Now create the material info object.
  500. mSkylightMaterial = new SkylightMaterialInfo("SklyightMaterial",
  501. getGFXVertexFormat<GFXVertexPC>());
  502. return mSkylightMaterial;
  503. }
  504. ProbeManager::ReflectProbeMaterialInfo* ProbeManager::getReflectProbeMaterial()
  505. {
  506. PROFILE_SCOPE(AdvancedLightBinManager_getReflectProbeMaterial);
  507. //ReflectProbeMaterialInfo *info = NULL;
  508. if (!mReflectProbeMaterial)
  509. // Now create the material info object.
  510. mReflectProbeMaterial = new ReflectProbeMaterialInfo("ReflectionProbeMaterial",
  511. getGFXVertexFormat<GFXVertexPC>());
  512. return mReflectProbeMaterial;
  513. }
  514. void ProbeManager::setupSkylightProbe(ProbeRenderInst *probeInfo)
  515. {
  516. probeInfo->vertBuffer = getSphereMesh(probeInfo->numPrims, probeInfo->primBuffer);
  517. if (!mSkylightMaterial)
  518. mSkylightMaterial = getSkylightMaterial();
  519. }
  520. void ProbeManager::setupSphereReflectionProbe(ProbeRenderInst *probeInfo)
  521. {
  522. probeInfo->vertBuffer = getSphereMesh(probeInfo->numPrims, probeInfo->primBuffer);
  523. if (!mReflectProbeMaterial)
  524. mReflectProbeMaterial = getReflectProbeMaterial();
  525. }
  526. void ProbeManager::setupConvexReflectionProbe(ProbeRenderInst *probeInfo)
  527. {
  528. static const Point3F cubePoints[8] =
  529. {
  530. Point3F(1, -1, -1), Point3F(1, -1, 1), Point3F(1, 1, -1), Point3F(1, 1, 1),
  531. Point3F(-1, -1, -1), Point3F(-1, 1, -1), Point3F(-1, -1, 1), Point3F(-1, 1, 1)
  532. };
  533. /*static const Point3F cubeNormals[6] =
  534. {
  535. Point3F(1, 0, 0), Point3F(-1, 0, 0), Point3F(0, 1, 0),
  536. Point3F(0, -1, 0), Point3F(0, 0, 1), Point3F(0, 0, -1)
  537. };*/
  538. /*static const Point2F cubeTexCoords[4] =
  539. {
  540. Point2F(0, 0), Point2F(0, -1),
  541. Point2F(1, 0), Point2F(1, -1)
  542. };*/
  543. static const U32 cubeFaces[36][3] =
  544. {
  545. { 3, 0, 3 },{ 0, 0, 0 },{ 1, 0, 1 },
  546. { 2, 0, 2 },{ 0, 0, 0 },{ 3, 0, 3 },
  547. { 7, 1, 1 },{ 4, 1, 2 },{ 5, 1, 0 },
  548. { 6, 1, 3 },{ 4, 1, 2 },{ 7, 1, 1 },
  549. { 3, 2, 1 },{ 5, 2, 2 },{ 2, 2, 0 },
  550. { 7, 2, 3 },{ 5, 2, 2 },{ 3, 2, 1 },
  551. { 1, 3, 3 },{ 4, 3, 0 },{ 6, 3, 1 },
  552. { 0, 3, 2 },{ 4, 3, 0 },{ 1, 3, 3 },
  553. { 3, 4, 3 },{ 6, 4, 0 },{ 7, 4, 1 },
  554. { 1, 4, 2 },{ 6, 4, 0 },{ 3, 4, 3 },
  555. { 2, 5, 1 },{ 4, 5, 2 },{ 0, 5, 0 },
  556. { 5, 5, 3 },{ 4, 5, 2 },{ 2, 5, 1 }
  557. };
  558. // Fill the vertex buffer
  559. GFXVertexPC *pVert = NULL;
  560. probeInfo->numVerts = 36;
  561. probeInfo->vertBuffer.set(GFX, 36, GFXBufferTypeStatic);
  562. pVert = probeInfo->vertBuffer.lock();
  563. Point3F halfSize = Point3F(probeInfo->mRadius, probeInfo->mRadius, probeInfo->mRadius);
  564. for (U32 i = 0; i < 36; i++)
  565. {
  566. const U32& vdx = cubeFaces[i][0];
  567. pVert[i].point = cubePoints[vdx] * halfSize;
  568. }
  569. probeInfo->vertBuffer.unlock();
  570. // Fill the primitive buffer
  571. U16 *pIdx = NULL;
  572. probeInfo->primBuffer.set(GFX, 36, 12, GFXBufferTypeStatic);
  573. probeInfo->primBuffer.lock(&pIdx);
  574. for (U16 i = 0; i < 36; i++)
  575. pIdx[i] = i;
  576. probeInfo->primBuffer.unlock();
  577. probeInfo->numPrims = 12;
  578. if (!mReflectProbeMaterial)
  579. mReflectProbeMaterial = getReflectProbeMaterial();
  580. //
  581. // mReflectProbeBin.push_back(pEntry);
  582. }
  583. GFXVertexBufferHandle<GFXVertexPC> ProbeManager::getSphereMesh(U32 &outNumPrimitives, GFXPrimitiveBufferHandle &outPrimitives)
  584. {
  585. static SphereMesh sSphereMesh;
  586. if (mSphereGeometry.isNull())
  587. {
  588. const SphereMesh::TriangleMesh * sphereMesh = sSphereMesh.getMesh(3);
  589. S32 numPoly = sphereMesh->numPoly;
  590. mSpherePrimitiveCount = 0;
  591. mSphereGeometry.set(GFX, numPoly * 3, GFXBufferTypeStatic);
  592. mSphereGeometry.lock();
  593. S32 vertexIndex = 0;
  594. for (S32 i = 0; i<numPoly; i++)
  595. {
  596. mSpherePrimitiveCount++;
  597. mSphereGeometry[vertexIndex].point = sphereMesh->poly[i].pnt[0];
  598. mSphereGeometry[vertexIndex].color = ColorI::WHITE;
  599. vertexIndex++;
  600. mSphereGeometry[vertexIndex].point = sphereMesh->poly[i].pnt[1];
  601. mSphereGeometry[vertexIndex].color = ColorI::WHITE;
  602. vertexIndex++;
  603. mSphereGeometry[vertexIndex].point = sphereMesh->poly[i].pnt[2];
  604. mSphereGeometry[vertexIndex].color = ColorI::WHITE;
  605. vertexIndex++;
  606. }
  607. mSphereGeometry.unlock();
  608. }
  609. outNumPrimitives = mSpherePrimitiveCount;
  610. outPrimitives = NULL; // For now
  611. return mSphereGeometry;
  612. }
  613. //
  614. //
  615. bool ReflectProbeMatInstance::init(const FeatureSet &features, const GFXVertexFormat *vertexFormat)
  616. {
  617. bool success = Parent::init(features, vertexFormat);
  618. // If the initialization failed don't continue.
  619. if (!success || !mProcessedMaterial || mProcessedMaterial->getNumPasses() == 0)
  620. return false;
  621. return true;
  622. }
  623. bool ReflectProbeMatInstance::setupPass(SceneRenderState *state, const SceneData &sgData)
  624. {
  625. // Go no further if the material failed to initialize properly.
  626. if (!mProcessedMaterial ||
  627. mProcessedMaterial->getNumPasses() == 0)
  628. return false;
  629. bool bRetVal = Parent::setupPass(state, sgData);;
  630. AssertFatal(mProcessedMaterial->getNumPasses() > 0, "No passes created! Ohnoes");
  631. const RenderPassData *rpd = mProcessedMaterial->getPass(0);
  632. AssertFatal(rpd, "No render pass data!");
  633. AssertFatal(rpd->mRenderStates[0], "No render state 0!");
  634. if (!mProjectionState)
  635. {
  636. GFXStateBlockDesc desc;
  637. desc.setZReadWrite(false);
  638. desc.zWriteEnable = false;
  639. desc.setCullMode(GFXCullNone);
  640. desc.setBlend(true, GFXBlendOne, GFXBlendOne);
  641. mProjectionState = GFX->createStateBlock(desc);
  642. }
  643. // Now override stateblock with our own
  644. GFX->setStateBlock(mProjectionState);
  645. return bRetVal;
  646. }
  647. //
  648. //
  649. ProbeManager::ReflectProbeMaterialInfo::ReflectProbeMaterialInfo(const String &matName,
  650. const GFXVertexFormat *vertexFormat)
  651. : matInstance(NULL),
  652. zNearFarInvNearFar(NULL),
  653. farPlane(NULL),
  654. vsFarPlane(NULL),
  655. negFarPlaneDotEye(NULL),
  656. probeWSPos(NULL),
  657. attenuation(NULL),
  658. radius(NULL),
  659. invViewMat(NULL),
  660. cubeMips(NULL)
  661. {
  662. Material *mat = MATMGR->getMaterialDefinitionByName(matName);
  663. if (!mat)
  664. return;
  665. matInstance = new ReflectProbeMatInstance(*mat);
  666. const Vector<GFXShaderMacro> &macros = Vector<GFXShaderMacro>();
  667. for (U32 i = 0; i < macros.size(); i++)
  668. matInstance->addShaderMacro(macros[i].name, macros[i].value);
  669. matInstance->init(MATMGR->getDefaultFeatures(), vertexFormat);
  670. attenuation = matInstance->getMaterialParameterHandle("$attenuation");
  671. radius = matInstance->getMaterialParameterHandle("$radius");
  672. probeLSPos = matInstance->getMaterialParameterHandle("$probeLSPos");
  673. probeWSPos = matInstance->getMaterialParameterHandle("$probeWSPos");
  674. farPlane = matInstance->getMaterialParameterHandle("$farPlane");
  675. vsFarPlane = matInstance->getMaterialParameterHandle("$vsFarPlane");
  676. negFarPlaneDotEye = matInstance->getMaterialParameterHandle("$negFarPlaneDotEye");
  677. zNearFarInvNearFar = matInstance->getMaterialParameterHandle("$zNearFarInvNearFar");
  678. invViewMat = matInstance->getMaterialParameterHandle("$invViewMat");
  679. useCubemap = matInstance->getMaterialParameterHandle("$useCubemap");
  680. cubemap = matInstance->getMaterialParameterHandle("$cubeMap");
  681. cubeMips = matInstance->getMaterialParameterHandle("$cubeMips");
  682. eyePosWorld = matInstance->getMaterialParameterHandle("$eyePosWorld");
  683. bbMin = matInstance->getMaterialParameterHandle("$bbMin");
  684. bbMax = matInstance->getMaterialParameterHandle("$bbMax");
  685. useSphereMode = matInstance->getMaterialParameterHandle("$useSphereMode");
  686. for (U32 i = 0; i < 9; i++)
  687. shTerms[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHTerms%d", i));
  688. for (U32 i = 0; i < 5; i++)
  689. shConsts[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHConsts%d", i));
  690. }
  691. ProbeManager::ReflectProbeMaterialInfo::~ReflectProbeMaterialInfo()
  692. {
  693. SAFE_DELETE(matInstance);
  694. }
  695. void ProbeManager::ReflectProbeMaterialInfo::setViewParameters(const F32 _zNear,
  696. const F32 _zFar,
  697. const Point3F &_eyePos,
  698. const PlaneF &_farPlane,
  699. const PlaneF &_vsFarPlane, const MatrixF &_inverseViewMatrix)
  700. {
  701. MaterialParameters *matParams = matInstance->getMaterialParameters();
  702. matParams->setSafe(farPlane, *((const Point4F *)&_farPlane));
  703. matParams->setSafe(vsFarPlane, *((const Point4F *)&_vsFarPlane));
  704. if (negFarPlaneDotEye->isValid())
  705. {
  706. // -dot( farPlane, eyePos )
  707. const F32 negFarPlaneDotEyeVal = -(mDot(*((const Point3F *)&_farPlane), _eyePos) + _farPlane.d);
  708. matParams->set(negFarPlaneDotEye, negFarPlaneDotEyeVal);
  709. }
  710. matParams->setSafe(zNearFarInvNearFar, Point4F(_zNear, _zFar, 1.0f / _zNear, 1.0f / _zFar));
  711. matParams->setSafe(invViewMat, _inverseViewMatrix);
  712. Point4F frPlane = *((const Point4F *)&_farPlane);
  713. Point4F vsFrPlane = *((const Point4F *)&_vsFarPlane);
  714. Point4F nearFarInvNearFar = Point4F(_zNear, _zFar, 1.0f / _zNear, 1.0f / _zFar);
  715. const F32 negFarPlaneDotEyeVal = -(mDot(*((const Point3F *)&_farPlane), _eyePos) + _farPlane.d);
  716. }
  717. void ProbeManager::ReflectProbeMaterialInfo::setProbeParameters(const ProbeRenderInst *probeInfo, const SceneRenderState* renderState, const MatrixF &worldViewOnly)
  718. {
  719. //Set up the params
  720. MaterialParameters *matParams = matInstance->getMaterialParameters();
  721. matParams->setSafe(radius, probeInfo->mRadius);
  722. Point3F probePos = probeInfo->getPosition() + probeInfo->mProbePosOffset;
  723. //worldViewOnly.mulP(probeInfo->getPosition(), &probePos);
  724. matParams->setSafe(probeWSPos, probePos);
  725. worldViewOnly.mulP(probeInfo->getPosition(), &probePos);
  726. matParams->setSafe(probeLSPos, probePos);
  727. // Get the attenuation falloff ratio and normalize it.
  728. Point3F attenRatio = Point3F(0.0f, 1.0f, 1.0f);
  729. F32 total = attenRatio.x + attenRatio.y + attenRatio.z;
  730. if (total > 0.0f)
  731. attenRatio /= total;
  732. F32 radius = probeInfo->mRadius;
  733. Point2F attenParams((1.0f / radius) * attenRatio.y,
  734. (1.0f / (radius * radius)) * attenRatio.z);
  735. matParams->setSafe(attenuation, attenParams);
  736. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  737. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  738. if (!deferredTexObject) return;
  739. GFX->setTexture(0, deferredTexObject);
  740. NamedTexTarget* matInfoTexTarget = NamedTexTarget::find("matinfo");
  741. GFXTextureObject *matInfoTexObject = matInfoTexTarget->getTexture();
  742. if (!matInfoTexObject) return;
  743. GFX->setTexture(1, matInfoTexObject);
  744. if (probeInfo->mCubemap && !probeInfo->mCubemap->isNull())
  745. {
  746. GFX->setCubeTexture(2, probeInfo->mCubemap->getPointer());
  747. }
  748. else
  749. {
  750. GFX->setCubeTexture(2, NULL);
  751. }
  752. if (probeInfo->mIrradianceCubemap && !probeInfo->mIrradianceCubemap->isNull())
  753. {
  754. GFX->setCubeTexture(3, probeInfo->mIrradianceCubemap->getPointer());
  755. }
  756. else
  757. {
  758. GFX->setCubeTexture(3, NULL);
  759. }
  760. if (probeInfo->mBRDFTexture && !probeInfo->mBRDFTexture->isNull())
  761. {
  762. GFX->setTexture(4, probeInfo->mBRDFTexture->getPointer());
  763. }
  764. else
  765. {
  766. GFX->setTexture(4, NULL);
  767. }
  768. if (probeInfo->mCubemap->isValid())
  769. matParams->setSafe(cubeMips, mPow(probeInfo->mCubemap->getPointer()->getMipMapLevels(), 2.0f));
  770. else
  771. matParams->setSafe(cubeMips, F32(0.0));
  772. matParams->setSafe(eyePosWorld, renderState->getCameraPosition());
  773. matParams->setSafe(bbMin, probeInfo->mBounds.minExtents);
  774. matParams->setSafe(bbMax, probeInfo->mBounds.maxExtents);
  775. matParams->setSafe(useSphereMode, probeInfo->mProbeShapeType == ProbeRenderInst::Sphere ? 1.0f : 0.0f);
  776. //SH Terms
  777. //static AlignedArray<Point3F> shTermsArray(9, sizeof(Point3F));
  778. //dMemset(shTermsArray.getBuffer(), 0, shTermsArray.getBufferSize());
  779. for (U32 i = 0; i < 9; i++)
  780. {
  781. matParams->setSafe(shTerms[i], probeInfo->mSHTerms[i]);
  782. }
  783. for (U32 i = 0; i < 5; i++)
  784. {
  785. matParams->setSafe(shConsts[i], probeInfo->mSHConstants[i]);
  786. }
  787. const MatrixF worldToObjectXfm = probeInfo->mTransform;
  788. MaterialParameterHandle *worldToObjMat = matInstance->getMaterialParameterHandle("$worldToObj");
  789. matParams->setSafe(worldToObjMat, worldToObjectXfm);
  790. }
  791. //
  792. //
  793. //
  794. ProbeManager::SkylightMaterialInfo::SkylightMaterialInfo(const String &matName,
  795. const GFXVertexFormat *vertexFormat)
  796. : ReflectProbeMaterialInfo(matName, vertexFormat)
  797. {
  798. Material *mat = MATMGR->getMaterialDefinitionByName(matName);
  799. if (!mat)
  800. return;
  801. matInstance = new SkylightMatInstance(*mat);
  802. const Vector<GFXShaderMacro> &macros = Vector<GFXShaderMacro>();
  803. for (U32 i = 0; i < macros.size(); i++)
  804. matInstance->addShaderMacro(macros[i].name, macros[i].value);
  805. matInstance->init(MATMGR->getDefaultFeatures(), vertexFormat);
  806. farPlane = matInstance->getMaterialParameterHandle("$farPlane");
  807. vsFarPlane = matInstance->getMaterialParameterHandle("$vsFarPlane");
  808. negFarPlaneDotEye = matInstance->getMaterialParameterHandle("$negFarPlaneDotEye");
  809. zNearFarInvNearFar = matInstance->getMaterialParameterHandle("$zNearFarInvNearFar");
  810. invViewMat = matInstance->getMaterialParameterHandle("$invViewMat");
  811. useCubemap = matInstance->getMaterialParameterHandle("$useCubemap");
  812. cubemap = matInstance->getMaterialParameterHandle("$cubeMap");
  813. eyePosWorld = matInstance->getMaterialParameterHandle("$eyePosWorld");
  814. for (U32 i = 0; i < 9; i++)
  815. shTerms[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHTerms%d", i));
  816. for (U32 i = 0; i < 5; i++)
  817. shConsts[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHConsts%d", i));
  818. }
  819. ProbeManager::SkylightMaterialInfo::~SkylightMaterialInfo()
  820. {
  821. SAFE_DELETE(matInstance);
  822. }
  823. /*bool ProbeManager::lightScene( const char* callback, const char* param )
  824. {
  825. BitSet32 flags = 0;
  826. if ( param )
  827. {
  828. if ( !dStricmp( param, "forceAlways" ) )
  829. flags.set( SceneLighting::ForceAlways );
  830. else if ( !dStricmp(param, "forceWritable" ) )
  831. flags.set( SceneLighting::ForceWritable );
  832. else if ( !dStricmp(param, "loadOnly" ) )
  833. flags.set( SceneLighting::LoadOnly );
  834. }
  835. // The SceneLighting object will delete itself
  836. // once the lighting process is complete.
  837. SceneLighting* sl = new SceneLighting( getSceneLightingInterface() );
  838. return sl->lightScene( callback, flags );
  839. }*/
  840. /*RenderDeferredMgr* ProbeManager::_findDeferredRenderBin()
  841. {
  842. RenderPassManager* rpm = getSceneManager()->getDefaultRenderPass();
  843. for( U32 i = 0; i < rpm->getManagerCount(); i++ )
  844. {
  845. RenderBinManager *bin = rpm->getManager( i );
  846. if( bin->getRenderInstType() == RenderDeferredMgr::RIT_Deferred )
  847. {
  848. return ( RenderDeferredMgr* ) bin;
  849. }
  850. }
  851. return NULL;
  852. }*/
  853. DefineEngineFunction( CreateProbeManager, bool, (),,
  854. "Finds and activates the named light manager.\n"
  855. "@return Returns true if the light manager is found and activated.\n"
  856. "@ingroup Lighting\n" )
  857. {
  858. ProbeManager* probeManager = new ProbeManager();
  859. if (probeManager != nullptr && gClientSceneGraph != nullptr)
  860. {
  861. probeManager->activate(gClientSceneGraph);
  862. return true;
  863. }
  864. return false;
  865. }
  866. DefineEngineFunction( resetProbeManager, void, (),,
  867. "@brief Deactivates and then activates the currently active light manager."
  868. "This causes most shaders to be regenerated and is often used when global "
  869. "rendering changes have occured.\n"
  870. "@ingroup Lighting\n" )
  871. {
  872. ProbeManager *pm = PROBEMGR;
  873. if ( !pm)
  874. return;
  875. /*SceneManager *sm = lm->getSceneManager();
  876. lm->deactivate();
  877. lm->activate( sm );*/
  878. }