reflectionProbe.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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 "T3D/lighting/reflectionProbe.h"
  23. #include "math/mathIO.h"
  24. #include "scene/sceneRenderState.h"
  25. #include "console/consoleTypes.h"
  26. #include "core/stream/bitStream.h"
  27. #include "materials/baseMatInstance.h"
  28. #include "console/engineAPI.h"
  29. #include "gfx/gfxDrawUtil.h"
  30. #include "gfx/gfxDebugEvent.h"
  31. #include "gfx/gfxTransformSaver.h"
  32. #include "math/mathUtils.h"
  33. #include "gfx/bitmap/gBitmap.h"
  34. #include "core/stream/fileStream.h"
  35. #include "core/fileObject.h"
  36. #include "core/resourceManager.h"
  37. #include "console/simPersistId.h"
  38. #include "T3D/gameFunctions.h"
  39. #include "postFx/postEffect.h"
  40. #include "renderInstance/renderProbeMgr.h"
  41. #include "renderInstance/renderProbeMgr.h"
  42. #include "math/util/sphereMesh.h"
  43. #include "materials/materialManager.h"
  44. #include "math/util/matrixSet.h"
  45. #include "gfx/bitmap/cubemapSaver.h"
  46. #include "materials/materialFeatureTypes.h"
  47. #include "gfx/gfxTextureManager.h"
  48. #include "T3D/lighting/IBLUtilities.h"
  49. #include "scene/reflector.h"
  50. extern bool gEditingMission;
  51. extern ColorI gCanvasClearColor;
  52. bool ReflectionProbe::smRenderPreviewProbes = true;
  53. IMPLEMENT_CO_NETOBJECT_V1(ReflectionProbe);
  54. ConsoleDocClass(ReflectionProbe,
  55. "@brief An example scene object which renders a mesh.\n\n"
  56. "This class implements a basic SceneObject that can exist in the world at a "
  57. "3D position and render itself. There are several valid ways to render an "
  58. "object in Torque. This class implements the preferred rendering method which "
  59. "is to submit a MeshRenderInst along with a Material, vertex buffer, "
  60. "primitive buffer, and transform and allow the RenderMeshMgr handle the "
  61. "actual setup and rendering for you.\n\n"
  62. "See the C++ code for implementation details.\n\n"
  63. "@ingroup Examples\n");
  64. ImplementEnumType(ReflectProbeType,
  65. "Type of mesh data available in a shape.\n"
  66. "@ingroup gameObjects")
  67. { ProbeRenderInst::Sphere, "Sphere", "Sphere shaped" },
  68. { ProbeRenderInst::Box, "Box", "Box shape" }
  69. EndImplementEnumType;
  70. ImplementEnumType(ReflectionModeEnum,
  71. "Type of mesh data available in a shape.\n"
  72. "@ingroup gameObjects")
  73. { ReflectionProbe::NoReflection, "No Reflections", "This probe does not provide any local reflection data"},
  74. { ReflectionProbe::StaticCubemap, "Static Cubemap", "Uses a static CubemapData" },
  75. { ReflectionProbe::BakedCubemap, "Baked Cubemap", "Uses a cubemap baked from the probe's current position" },
  76. //{ ReflectionProbe::DynamicCubemap, "Dynamic Cubemap", "Uses a cubemap baked from the probe's current position, updated at a set rate" },
  77. EndImplementEnumType;
  78. //-----------------------------------------------------------------------------
  79. // Object setup and teardown
  80. //-----------------------------------------------------------------------------
  81. ReflectionProbe::ReflectionProbe()
  82. {
  83. // Flag this object so that it will always
  84. // be sent across the network to clients
  85. mNetFlags.set(Ghostable | ScopeAlways);
  86. mTypeMask = LightObjectType | MarkerObjectType;
  87. mProbeShapeType = ProbeRenderInst::Box;
  88. mReflectionModeType = BakedCubemap;
  89. mEnabled = true;
  90. mBake = false;
  91. mDirty = false;
  92. mCubemapDirty = false;
  93. mRadius = 10;
  94. mObjScale = Point3F::One * 10;
  95. mProbeRefScale = Point3F::One*10;
  96. mUseHDRCaptures = true;
  97. mStaticCubemap = NULL;
  98. mProbeUniqueID = "";
  99. mEditorShapeInst = NULL;
  100. mEditorShape = NULL;
  101. mRefreshRateMS = 200;
  102. mDynamicLastBakeMS = 0;
  103. mMaxDrawDistance = 75;
  104. mResourcesCreated = false;
  105. mProbeInfo = nullptr;
  106. mPrefilterSize = 64;
  107. mPrefilterMipLevels = mLog2(F32(mPrefilterSize));
  108. mPrefilterMap = nullptr;
  109. mIrridianceMap = nullptr;
  110. mProbeRefOffset = Point3F::Zero;
  111. mEditPosOffset = false;
  112. mCaptureMask = REFLECTION_PROBE_CAPTURE_TYPEMASK;
  113. }
  114. ReflectionProbe::~ReflectionProbe()
  115. {
  116. if (mEditorShapeInst)
  117. SAFE_DELETE(mEditorShapeInst);
  118. if (mProbeInfo)
  119. SAFE_DELETE(mProbeInfo);
  120. if (mReflectionModeType != StaticCubemap && mStaticCubemap)
  121. mStaticCubemap->deleteObject();
  122. }
  123. //-----------------------------------------------------------------------------
  124. // Object Editing
  125. //-----------------------------------------------------------------------------
  126. void ReflectionProbe::initPersistFields()
  127. {
  128. addGroup("Rendering");
  129. addProtectedField("enabled", TypeBool, Offset(mEnabled, ReflectionProbe),
  130. &_setEnabled, &defaultProtectedGetFn, "Regenerate Voxel Grid");
  131. endGroup("Rendering");
  132. addGroup("Reflection");
  133. addProtectedField("radius", TypeF32, Offset(mRadius, ReflectionProbe), &_setRadius, &defaultProtectedGetFn,
  134. "The name of the material used to render the mesh.");
  135. addProtectedField("EditPosOffset", TypeBool, Offset(mEditPosOffset, ReflectionProbe),
  136. &_toggleEditPosOffset, &defaultProtectedGetFn, "Toggle Edit Pos Offset Mode", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  137. addField("refOffset", TypePoint3F, Offset(mProbeRefOffset, ReflectionProbe), "");
  138. addField("refScale", TypePoint3F, Offset(mProbeRefScale, ReflectionProbe), "");
  139. addProtectedField("ReflectionMode", TypeReflectionModeEnum, Offset(mReflectionModeType, ReflectionProbe), &_setReflectionMode, &defaultProtectedGetFn,
  140. "The type of mesh data to use for collision queries.");
  141. addField("StaticCubemap", TypeCubemapName, Offset(mCubemapName, ReflectionProbe), "Cubemap used instead of reflection texture if fullReflect is off.");
  142. addProtectedField("Bake", TypeBool, Offset(mBake, ReflectionProbe),
  143. &_doBake, &defaultProtectedGetFn, "Regenerate Voxel Grid", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  144. endGroup("Reflection");
  145. Con::addVariable("$Light::renderReflectionProbes", TypeBool, &RenderProbeMgr::smRenderReflectionProbes,
  146. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  147. "@note Only works for shadow mapped lights.\n\n"
  148. "@ingroup Lighting");
  149. Con::addVariable("$Light::renderPreviewProbes", TypeBool, &ReflectionProbe::smRenderPreviewProbes,
  150. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  151. "@note Only works for shadow mapped lights.\n\n"
  152. "@ingroup Lighting");
  153. // SceneObject already handles exposing the transform
  154. Parent::initPersistFields();
  155. }
  156. void ReflectionProbe::inspectPostApply()
  157. {
  158. Parent::inspectPostApply();
  159. mDirty = true;
  160. // Flag the network mask to send the updates
  161. // to the client object
  162. setMaskBits(-1);
  163. }
  164. bool ReflectionProbe::_setEnabled(void *object, const char *index, const char *data)
  165. {
  166. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  167. probe->mEnabled = dAtob(data);
  168. probe->setMaskBits(-1);
  169. return true;
  170. }
  171. bool ReflectionProbe::_doBake(void *object, const char *index, const char *data)
  172. {
  173. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  174. probe->bake();
  175. return false;
  176. }
  177. bool ReflectionProbe::_toggleEditPosOffset(void *object, const char *index, const char *data)
  178. {
  179. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  180. probe->mEditPosOffset = !probe->mEditPosOffset;
  181. return false;
  182. }
  183. bool ReflectionProbe::_setRadius(void *object, const char *index, const char *data)
  184. {
  185. ReflectionProbe* probe = reinterpret_cast<ReflectionProbe*>(object);
  186. if (probe->mProbeShapeType != ProbeRenderInst::Sphere)
  187. return false;
  188. probe->mObjScale = Point3F(probe->mRadius, probe->mRadius, probe->mRadius);
  189. return true;
  190. }
  191. bool ReflectionProbe::_setReflectionMode(void *object, const char *index, const char *data)
  192. {
  193. ReflectionProbe* probe = reinterpret_cast<ReflectionProbe*>(object);
  194. if (data == "Static Cubemap")
  195. {
  196. probe->mReflectionModeType = StaticCubemap;
  197. }
  198. else if (data == "Baked Cubemap")
  199. {
  200. //Clear our cubemap if we changed it to be baked, just for cleanliness
  201. probe->mReflectionModeType = BakedCubemap;
  202. probe->mCubemapName = "";
  203. }
  204. return true;
  205. }
  206. bool ReflectionProbe::onAdd()
  207. {
  208. if (!Parent::onAdd())
  209. return false;
  210. mEditPosOffset = false;
  211. mObjBox.minExtents.set(-0.5, -0.5, -0.5);
  212. mObjBox.maxExtents.set(0.5, 0.5, 0.5);
  213. // Skip our transform... it just dirties mask bits.
  214. Parent::setTransform(mObjToWorld);
  215. resetWorldBox();
  216. // Add this object to the scene
  217. addToScene();
  218. if (isServerObject())
  219. {
  220. if (!mPersistentId)
  221. mPersistentId = getOrCreatePersistentId();
  222. mProbeUniqueID = String::ToString(mPersistentId->getUUID().getHash());
  223. }
  224. // Refresh this object's material (if any)
  225. if (isClientObject())
  226. {
  227. if (!createClientResources())
  228. return false;
  229. updateProbeParams();
  230. }
  231. setMaskBits(-1);
  232. return true;
  233. }
  234. void ReflectionProbe::onRemove()
  235. {
  236. if (isClientObject())
  237. {
  238. PROBEMGR->unregisterProbe(mProbeInfo->mProbeIdx);
  239. }
  240. // Remove this object from the scene
  241. removeFromScene();
  242. Parent::onRemove();
  243. }
  244. void ReflectionProbe::handleDeleteAction()
  245. {
  246. //we're deleting it?
  247. //Then we need to clear out the processed cubemaps(if we have them)
  248. if (mReflectionModeType != StaticCubemap)
  249. {
  250. String prefilPath = getPrefilterMapPath();
  251. if (Platform::isFile(prefilPath))
  252. {
  253. Platform::fileDelete(prefilPath);
  254. }
  255. String irrPath = getIrradianceMapPath();
  256. if (Platform::isFile(irrPath))
  257. {
  258. Platform::fileDelete(irrPath);
  259. }
  260. }
  261. Parent::handleDeleteAction();
  262. }
  263. void ReflectionProbe::setTransform(const MatrixF & mat)
  264. {
  265. // Let SceneObject handle all of the matrix manipulation
  266. if (!mEditPosOffset)
  267. Parent::setTransform(mat);
  268. else
  269. mProbeRefOffset = mat.getPosition();
  270. mDirty = true;
  271. // Dirty our network mask so that the new transform gets
  272. // transmitted to the client object
  273. setMaskBits(TransformMask);
  274. }
  275. const MatrixF& ReflectionProbe::getTransform() const
  276. {
  277. if (!mEditPosOffset)
  278. return mObjToWorld;
  279. else
  280. {
  281. MatrixF transformMat = MatrixF::Identity;
  282. transformMat.setPosition(mProbeRefOffset);
  283. return transformMat;
  284. }
  285. }
  286. void ReflectionProbe::setScale(const VectorF &scale)
  287. {
  288. if (!mEditPosOffset)
  289. Parent::setScale(scale);
  290. else
  291. mProbeRefScale = scale;
  292. mDirty = true;
  293. // Dirty our network mask so that the new transform gets
  294. // transmitted to the client object
  295. setMaskBits(TransformMask);
  296. }
  297. const VectorF& ReflectionProbe::getScale() const
  298. {
  299. if (!mEditPosOffset)
  300. return mObjScale;
  301. else
  302. return mProbeRefScale;
  303. }
  304. bool ReflectionProbe::writeField(StringTableEntry fieldname, const char *value)
  305. {
  306. if (fieldname == StringTable->insert("Bake") || fieldname == StringTable->insert("EditPosOffset"))
  307. return false;
  308. return Parent::writeField(fieldname, value);
  309. }
  310. U32 ReflectionProbe::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  311. {
  312. // Allow the Parent to get a crack at writing its info
  313. U32 retMask = Parent::packUpdate(conn, mask, stream);
  314. // Write our transform information
  315. if (stream->writeFlag(mask & TransformMask))
  316. {
  317. stream->writeFlag(mEditPosOffset);
  318. mathWrite(*stream, mObjToWorld);
  319. mathWrite(*stream, mObjScale);
  320. mathWrite(*stream, mProbeRefOffset);
  321. mathWrite(*stream, mProbeRefScale);
  322. }
  323. if (stream->writeFlag(mask & StaticDataMask))
  324. {
  325. stream->write((U32)mProbeShapeType);
  326. stream->write(mRadius);
  327. stream->write(mProbeUniqueID);
  328. stream->write((U32)mReflectionModeType);
  329. stream->write(mCubemapName);
  330. }
  331. if (stream->writeFlag(mask & EnabledMask))
  332. {
  333. stream->writeFlag(mEnabled);
  334. }
  335. return retMask;
  336. }
  337. void ReflectionProbe::unpackUpdate(NetConnection *conn, BitStream *stream)
  338. {
  339. // Let the Parent read any info it sent
  340. Parent::unpackUpdate(conn, stream);
  341. if (stream->readFlag()) // TransformMask
  342. {
  343. mEditPosOffset = stream->readFlag();
  344. mathRead(*stream, &mObjToWorld);
  345. mathRead(*stream, &mObjScale);
  346. Parent::setTransform(mObjToWorld);
  347. resetWorldBox();
  348. mathRead(*stream, &mProbeRefOffset);
  349. mathRead(*stream, &mProbeRefScale);
  350. mDirty = true;
  351. }
  352. if (stream->readFlag()) // StaticDataMask
  353. {
  354. U32 shapeType = ProbeRenderInst::Sphere;
  355. stream->read(&shapeType);
  356. mProbeShapeType = (ProbeRenderInst::ProbeShapeType)shapeType;
  357. stream->read(&mRadius);
  358. stream->read(&mProbeUniqueID);
  359. U32 oldReflectModeType = mReflectionModeType;
  360. U32 reflectModeType = BakedCubemap;
  361. stream->read(&reflectModeType);
  362. mReflectionModeType = (ReflectionModeType)reflectModeType;
  363. String oldCubemapName = mCubemapName;
  364. stream->read(&mCubemapName);
  365. if(oldReflectModeType != mReflectionModeType || oldCubemapName != mCubemapName)
  366. mCubemapDirty = true;
  367. mDirty = true;
  368. }
  369. if (stream->readFlag()) // EnabledMask
  370. {
  371. mEnabled = stream->readFlag();
  372. mDirty = true;
  373. }
  374. if (mDirty)
  375. {
  376. updateProbeParams();
  377. }
  378. }
  379. //-----------------------------------------------------------------------------
  380. // Object Rendering
  381. //-----------------------------------------------------------------------------
  382. void ReflectionProbe::updateProbeParams()
  383. {
  384. if (!mProbeInfo)
  385. return;
  386. mProbeInfo->mProbeShapeType = mProbeShapeType;
  387. if (mProbeShapeType == ProbeRenderInst::Sphere)
  388. mObjScale.set(mRadius, mRadius, mRadius);
  389. Box3F bounds;
  390. if (mProbeShapeType == ProbeRenderInst::Skylight)
  391. {
  392. mProbeInfo->mPosition = Point3F::Zero;
  393. mProbeInfo->mTransform = MatrixF::Identity;
  394. mProbeInfo->mIsSkylight = true;
  395. F32 visDist = gClientSceneGraph->getVisibleDistance();
  396. Box3F skylightBounds = Box3F(visDist * 2);
  397. skylightBounds.setCenter(Point3F::Zero);
  398. bounds = skylightBounds;
  399. setGlobalBounds();
  400. mProbeInfo->mScore = -1.0f;
  401. }
  402. else
  403. {
  404. MatrixF transform = getTransform();
  405. mProbeInfo->mPosition = getPosition();
  406. transform.scale(getScale());
  407. mProbeInfo->mTransform = transform.inverse();
  408. mProbeInfo->mIsSkylight = false;
  409. bounds = mWorldBox;
  410. mProbeInfo->mScore = mMaxDrawDistance;
  411. }
  412. // Skip our transform... it just dirties mask bits.
  413. Parent::setTransform(mObjToWorld);
  414. resetWorldBox();
  415. mProbeInfo->mBounds = bounds;
  416. mProbeInfo->mExtents = getScale();
  417. mProbeInfo->mRadius = mRadius;
  418. mProbeInfo->mProbeRefOffset = mProbeRefOffset;
  419. mProbeInfo->mProbeRefScale = mProbeRefScale;
  420. mProbeInfo->mDirty = true;
  421. if (mCubemapDirty)
  422. {
  423. if (mReflectionModeType == StaticCubemap)
  424. processStaticCubemap();
  425. else
  426. processDynamicCubemap();
  427. }
  428. PROBEMGR->updateProbes();
  429. }
  430. void ReflectionProbe::processDynamicCubemap()
  431. {
  432. if (!mProbeInfo)
  433. return;
  434. mEnabled = false;
  435. if (mReflectionModeType != DynamicCubemap)
  436. {
  437. mProbeInfo->mCubeReflector.unregisterReflector();
  438. if ((mReflectionModeType == BakedCubemap) && !mProbeUniqueID.isEmpty())
  439. {
  440. String irrPath = getIrradianceMapPath();
  441. if (Platform::isFile(irrPath))
  442. {
  443. mIrridianceMap->setCubemapFile(FileName(irrPath));
  444. //mIrridianceMap->updateFaces();
  445. }
  446. if (mIrridianceMap == nullptr || mIrridianceMap->mCubemap.isNull())
  447. {
  448. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked irradiance map at %s", getIrradianceMapPath().c_str());
  449. return;
  450. }
  451. String prefilPath = getPrefilterMapPath();
  452. if (Platform::isFile(prefilPath))
  453. {
  454. mPrefilterMap->setCubemapFile(FileName(prefilPath));
  455. //mPrefilterMap->updateFaces();
  456. }
  457. if (mPrefilterMap == nullptr || mPrefilterMap->mCubemap.isNull())
  458. {
  459. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str());
  460. return;
  461. }
  462. //mProbeInfo->mPrefilterCubemap = mPrefilterMap->mCubemap;
  463. //mProbeInfo->mIrradianceCubemap = mIrridianceMap->mCubemap;
  464. mEnabled = true;
  465. }
  466. }
  467. else
  468. {
  469. if (mReflectionModeType == DynamicCubemap && !mDynamicCubemap.isNull())
  470. {
  471. mProbeInfo->mPrefilterCubemap = mDynamicCubemap;
  472. mProbeInfo->mCubeReflector.registerReflector(this, reflectorDesc); //need to decide how we wanna do the reflectorDesc. static name or a field
  473. }
  474. else
  475. {
  476. mEnabled = false;
  477. }
  478. }
  479. if (mEnabled)
  480. mProbeInfo->mIsEnabled = true;
  481. else
  482. mProbeInfo->mIsEnabled = false;
  483. //Update the probe manager with our new texture!
  484. //if (!mProbeInfo->mIsSkylight && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  485. // PROBEMGR->updateProbeTexture(mProbeInfo->mProbeIdx);
  486. }
  487. void ReflectionProbe::processStaticCubemap()
  488. {
  489. if (!mProbeInfo)
  490. return;
  491. mEnabled = false;
  492. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  493. char irradFileName[256];
  494. dSprintf(irradFileName, 256, "%s_Irradiance.dds", path.c_str(), mCubemapName.c_str());
  495. if (Platform::isFile(irradFileName))
  496. {
  497. mIrridianceMap->setCubemapFile(FileName(irradFileName));
  498. mIrridianceMap->updateFaces();
  499. }
  500. if (mIrridianceMap == nullptr || mIrridianceMap->mCubemap.isNull())
  501. {
  502. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked irradiance map at %s", irradFileName);
  503. return;
  504. }
  505. char prefilterFileName[256];
  506. dSprintf(prefilterFileName, 256, "%s%s_Prefilter.dds", path.c_str(), mCubemapName.c_str());
  507. if (Platform::isFile(prefilterFileName))
  508. {
  509. mPrefilterMap->setCubemapFile(FileName(prefilterFileName));
  510. mPrefilterMap->updateFaces();
  511. }
  512. if (mPrefilterMap == nullptr || mPrefilterMap->mCubemap.isNull())
  513. {
  514. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked prefilter map at %s", prefilterFileName);
  515. return;
  516. }
  517. if (!Platform::isFile(prefilterFileName) || !Platform::isFile(irradFileName))
  518. {
  519. //If we are missing either of the files, just re-run the bake
  520. Sim::findObject(mCubemapName, mStaticCubemap);
  521. if (!mStaticCubemap)
  522. {
  523. Con::errorf("ReflectionProbe::updateMaterial() - unable to find static cubemap file!");
  524. return;
  525. }
  526. if (mStaticCubemap->mCubemap == nullptr)
  527. {
  528. mStaticCubemap->createMap();
  529. mStaticCubemap->updateFaces();
  530. }
  531. if (mUseHDRCaptures)
  532. {
  533. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  534. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  535. }
  536. else
  537. {
  538. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  539. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  540. }
  541. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  542. IBLUtilities::GenerateIrradianceMap(renderTarget, mStaticCubemap->mCubemap, mIrridianceMap->mCubemap);
  543. IBLUtilities::GeneratePrefilterMap(renderTarget, mStaticCubemap->mCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  544. IBLUtilities::SaveCubeMap(irradFileName, mIrridianceMap->mCubemap);
  545. IBLUtilities::SaveCubeMap(prefilterFileName, mPrefilterMap->mCubemap);
  546. }
  547. if ((mIrridianceMap != nullptr || !mIrridianceMap->mCubemap.isNull()) && (mPrefilterMap != nullptr || !mPrefilterMap->mCubemap.isNull()))
  548. {
  549. mProbeInfo->mPrefilterCubemap = mPrefilterMap->mCubemap;
  550. mProbeInfo->mIrradianceCubemap = mIrridianceMap->mCubemap;
  551. mEnabled = true;
  552. }
  553. if (mEnabled)
  554. mProbeInfo->mIsEnabled = true;
  555. else
  556. mProbeInfo->mIsEnabled = false;
  557. //Update the probe manager with our new texture!
  558. if (!mProbeInfo->mIsSkylight && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  559. PROBEMGR->updateProbeTexture(mProbeInfo->mProbeIdx);
  560. }
  561. bool ReflectionProbe::createClientResources()
  562. {
  563. if (mProbeInfo == nullptr)
  564. {
  565. mProbeInfo = PROBEMGR->registerProbe(mProbeShapeType == ProbeRenderInst::Skylight);
  566. if (!mProbeInfo)
  567. return false;
  568. mProbeInfo->mIsEnabled = false;
  569. }
  570. //irridiance resources
  571. if (!mIrridianceMap)
  572. {
  573. mIrridianceMap = new CubemapData();
  574. mIrridianceMap->registerObject();
  575. mIrridianceMap->createMap();
  576. }
  577. //
  578. if (!mPrefilterMap)
  579. {
  580. mPrefilterMap = new CubemapData();
  581. mPrefilterMap->registerObject();
  582. mPrefilterMap->createMap();
  583. }
  584. mResourcesCreated = true;
  585. mCubemapDirty = true;
  586. return true;
  587. }
  588. String ReflectionProbe::getPrefilterMapPath()
  589. {
  590. if (mProbeUniqueID.isEmpty())
  591. {
  592. Con::errorf("ReflectionProbe::getPrefilterMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  593. return "";
  594. }
  595. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  596. char fileName[256];
  597. dSprintf(fileName, 256, "%s%s_Prefilter.dds", path.c_str(), mProbeUniqueID.c_str());
  598. return fileName;
  599. }
  600. String ReflectionProbe::getIrradianceMapPath()
  601. {
  602. if (mProbeUniqueID.isEmpty())
  603. {
  604. Con::errorf("ReflectionProbe::getIrradianceMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  605. return "";
  606. }
  607. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  608. char fileName[256];
  609. dSprintf(fileName, 256, "%s%s_Irradiance.dds", path.c_str(), mProbeUniqueID.c_str());
  610. return fileName;
  611. }
  612. void ReflectionProbe::bake()
  613. {
  614. if (mReflectionModeType == DynamicCubemap)
  615. return;
  616. PROBEMGR->bakeProbe(this);
  617. setMaskBits(StaticDataMask);
  618. }
  619. //-----------------------------------------------------------------------------
  620. //Rendering of editing/debug stuff
  621. //-----------------------------------------------------------------------------
  622. void ReflectionProbe::createGeometry()
  623. {
  624. // Clean up our previous shape
  625. if (mEditorShapeInst)
  626. SAFE_DELETE(mEditorShapeInst);
  627. mEditorShape = NULL;
  628. String shapeFile = "tools/resources/ReflectProbeSphere.dae";
  629. // Attempt to get the resource from the ResourceManager
  630. mEditorShape = ResourceManager::get().load(shapeFile);
  631. if (mEditorShape)
  632. {
  633. mEditorShapeInst = new TSShapeInstance(mEditorShape, isClientObject());
  634. }
  635. }
  636. void ReflectionProbe::prepRenderImage(SceneRenderState *state)
  637. {
  638. if (!mEnabled || !RenderProbeMgr::smRenderReflectionProbes)
  639. return;
  640. Point3F distVec = getRenderPosition() - state->getCameraPosition();
  641. F32 dist = distVec.len();
  642. //Culling distance. Can be adjusted for performance options considerations via the scalar
  643. if (dist > mMaxDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0))
  644. {
  645. mProbeInfo->mScore = mMaxDrawDistance;
  646. return;
  647. }
  648. if (mReflectionModeType == DynamicCubemap && mRefreshRateMS < (Platform::getRealMilliseconds() - mDynamicLastBakeMS))
  649. {
  650. bake();
  651. mDynamicLastBakeMS = Platform::getRealMilliseconds();
  652. }
  653. //Submit our probe to actually do the probe action
  654. // Get a handy pointer to our RenderPassmanager
  655. //RenderPassManager *renderPass = state->getRenderPass();
  656. //Update our score based on our radius, distance
  657. mProbeInfo->mScore = mProbeInfo->mRadius/mMax(dist,1.0f);
  658. Point3F vect = distVec;
  659. vect.normalizeSafe();
  660. mProbeInfo->mScore *= mMax(mAbs(mDot(vect, state->getCameraTransform().getForwardVector())),0.001f);
  661. //Register
  662. //PROBEMGR->registerProbe(mProbeInfoIdx);
  663. if (ReflectionProbe::smRenderPreviewProbes && gEditingMission && mPrefilterMap != nullptr)
  664. {
  665. if(!mEditorShapeInst)
  666. createGeometry();
  667. GFXTransformSaver saver;
  668. // Calculate the distance of this object from the camera
  669. Point3F cameraOffset;
  670. getRenderTransform().getColumn(3, &cameraOffset);
  671. cameraOffset -= state->getDiffuseCameraPosition();
  672. dist = cameraOffset.len();
  673. if (dist < 0.01f)
  674. dist = 0.01f;
  675. // Set up the LOD for the shape
  676. F32 invScale = (1.0f / getMax(getMax(mObjScale.x, mObjScale.y), mObjScale.z));
  677. mEditorShapeInst->setDetailFromDistance(state, dist * invScale);
  678. // Make sure we have a valid level of detail
  679. if (mEditorShapeInst->getCurrentDetail() < 0)
  680. return;
  681. BaseMatInstance* probePrevMat = mEditorShapeInst->getMaterialList()->getMaterialInst(0);
  682. setPreviewMatParameters(state, probePrevMat);
  683. // GFXTransformSaver is a handy helper class that restores
  684. // the current GFX matrices to their original values when
  685. // it goes out of scope at the end of the function
  686. // Set up our TS render state
  687. TSRenderState rdata;
  688. rdata.setSceneState(state);
  689. rdata.setFadeOverride(1.0f);
  690. if(mReflectionModeType != DynamicCubemap)
  691. rdata.setCubemap(mPrefilterMap->mCubemap);
  692. else
  693. rdata.setCubemap(mDynamicCubemap);
  694. // We might have some forward lit materials
  695. // so pass down a query to gather lights.
  696. LightQuery query;
  697. query.init(getWorldSphere());
  698. rdata.setLightQuery(&query);
  699. // Set the world matrix to the objects render transform
  700. MatrixF mat = getRenderTransform();
  701. GFX->setWorldMatrix(mat);
  702. // Animate the the shape
  703. mEditorShapeInst->animate();
  704. // Allow the shape to submit the RenderInst(s) for itself
  705. mEditorShapeInst->render(rdata);
  706. saver.restore();
  707. }
  708. // If the light is selected or light visualization
  709. // is enabled then register the callback.
  710. const bool isSelectedInEditor = (gEditingMission && isSelected());
  711. if (isSelectedInEditor)
  712. {
  713. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  714. ri->renderDelegate.bind(this, &ReflectionProbe::_onRenderViz);
  715. ri->type = RenderPassManager::RIT_Editor;
  716. state->getRenderPass()->addInst(ri);
  717. }
  718. }
  719. void ReflectionProbe::_onRenderViz(ObjectRenderInst *ri,
  720. SceneRenderState *state,
  721. BaseMatInstance *overrideMat)
  722. {
  723. if (!RenderProbeMgr::smRenderReflectionProbes)
  724. return;
  725. GFXDrawUtil *draw = GFX->getDrawUtil();
  726. GFXStateBlockDesc desc;
  727. desc.setZReadWrite(true, false);
  728. desc.setCullMode(GFXCullNone);
  729. desc.setBlend(true);
  730. desc.fillMode = GFXFillWireframe;
  731. // Base the sphere color on the light color.
  732. ColorI color = ColorI(255, 0, 255, 63);
  733. const MatrixF worldToObjectXfm = mObjToWorld;
  734. if (mProbeShapeType == ProbeRenderInst::Sphere)
  735. {
  736. draw->drawSphere(desc, mRadius, getPosition(), color);
  737. }
  738. else
  739. {
  740. Point3F tscl = worldToObjectXfm.getScale();
  741. Box3F projCube(-mObjScale/2, mObjScale / 2);
  742. projCube.setCenter(getPosition());
  743. draw->drawCube(desc, projCube, color, &worldToObjectXfm);
  744. }
  745. Point3F renderPos = getRenderTransform().getPosition();
  746. Box3F refCube = Box3F(-mProbeRefScale / 2, mProbeRefScale / 2);
  747. refCube.setCenter(renderPos + mProbeRefOffset);
  748. color = ColorI(0, 255, 255, 63);
  749. draw->drawCube(desc, refCube, color, &worldToObjectXfm);
  750. }
  751. void ReflectionProbe::setPreviewMatParameters(SceneRenderState* renderState, BaseMatInstance* mat)
  752. {
  753. if (!mat->getFeatures().hasFeature(MFT_isDeferred))
  754. return;
  755. //Set up the params
  756. MaterialParameters *matParams = mat->getMaterialParameters();
  757. //Get the deferred render target
  758. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  759. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  760. if (!deferredTexObject)
  761. return;
  762. GFX->setTexture(0, deferredTexObject);
  763. //Set the cubemap
  764. GFX->setCubeTexture(1, mPrefilterMap->mCubemap);
  765. //Set the invViewMat
  766. MatrixSet &matrixSet = renderState->getRenderPass()->getMatrixSet();
  767. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  768. MaterialParameterHandle *invViewMat = mat->getMaterialParameterHandle("$invViewMat");
  769. matParams->setSafe(invViewMat, worldToCameraXfm);
  770. }
  771. DefineEngineMethod(ReflectionProbe, postApply, void, (), ,
  772. "A utility method for forcing a network update.\n")
  773. {
  774. object->inspectPostApply();
  775. }
  776. DefineEngineMethod(ReflectionProbe, Bake, void, (), ,
  777. "@brief returns true if control object is inside the fog\n\n.")
  778. {
  779. ReflectionProbe *clientProbe = (ReflectionProbe*)object->getClientObject();
  780. if (clientProbe)
  781. {
  782. clientProbe->bake();
  783. }
  784. }