reflectionProbe.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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. { ReflectionProbe::ProbeInfo::Sphere, "Sphere", "Sphere shaped" },
  68. { ReflectionProbe::ProbeInfo::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 = ProbeInfo::Box;
  88. mReflectionModeType = BakedCubemap;
  89. mEnabled = true;
  90. mBakeReflections = false;
  91. mCubemapDirty = false;
  92. mRadius = 10;
  93. mObjScale = Point3F::One * 10;
  94. mProbeRefScale = Point3F::One*10;
  95. mUseHDRCaptures = true;
  96. mCubemapName = StringTable->EmptyString();
  97. mStaticCubemap = NULL;
  98. mProbeUniqueID = "";
  99. #ifdef TORQUE_TOOLS
  100. mEditorShapeInst = NULL;
  101. mEditorShape = NULL;
  102. #endif
  103. mRefreshRateMS = 200;
  104. mDynamicLastBakeMS = 0;
  105. mResourcesCreated = false;
  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. #ifdef TORQUE_TOOLS
  117. if (mEditorShapeInst)
  118. SAFE_DELETE(mEditorShapeInst);
  119. #endif
  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, "Is the probe enabled or not");
  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), "The reference positional offset for the probe. This is used for adjusting the perceived center and area of influence.\nHelpful in adjusting parallax issues");
  138. addField("refScale", TypePoint3F, Offset(mProbeRefScale, ReflectionProbe), "The reference scale for the probe. This is used for adjusting the perceived center and area of influence.\nHelpful in adjusting parallax issues");
  139. addProtectedField("ReflectionMode", TypeReflectionModeEnum, Offset(mReflectionModeType, ReflectionProbe), &_setReflectionMode, &defaultProtectedGetFn,
  140. "Used to dictate what sort of cubemap the probes use when using IBL.");
  141. addField("StaticCubemap", TypeCubemapName, Offset(mCubemapName, ReflectionProbe), "This is used when a static cubemap is used. The name of the cubemap is looked up and loaded for the IBL calculations.");
  142. //addField("DynamicReflectionRefreshMS", TypeS32, Offset(mRefreshRateMS, ReflectionProbe), "How often the dynamic cubemap is refreshed in milliseconds. Only works when the ReflectionMode is set to DynamicCubemap.");
  143. addProtectedField("Bake", TypeBool, Offset(mBakeReflections, ReflectionProbe),
  144. &_doBake, &defaultProtectedGetFn, "Bake Probe Reflections", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  145. endGroup("Reflection");
  146. Con::addVariable("$Light::renderReflectionProbes", TypeBool, &RenderProbeMgr::smRenderReflectionProbes,
  147. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  148. "@note Only works for shadow mapped lights.\n\n"
  149. "@ingroup Lighting");
  150. Con::addVariable("$Light::renderPreviewProbes", TypeBool, &ReflectionProbe::smRenderPreviewProbes,
  151. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  152. "@note Only works for shadow mapped lights.\n\n"
  153. "@ingroup Lighting");
  154. // SceneObject already handles exposing the transform
  155. Parent::initPersistFields();
  156. }
  157. void ReflectionProbe::inspectPostApply()
  158. {
  159. Parent::inspectPostApply();
  160. mDirty = true;
  161. bool liveUpdates = Con::getBoolVariable("$Probes::liveUpdates", false);
  162. if (liveUpdates)
  163. {
  164. bake();
  165. }
  166. // Flag the network mask to send the updates
  167. // to the client object
  168. setMaskBits(-1);
  169. }
  170. bool ReflectionProbe::_setEnabled(void *object, const char *index, const char *data)
  171. {
  172. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  173. probe->mEnabled = dAtob(data);
  174. probe->setMaskBits(EnabledMask);
  175. return true;
  176. }
  177. bool ReflectionProbe::_doBake(void *object, const char *index, const char *data)
  178. {
  179. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  180. probe->bake();
  181. probe->setMaskBits(StaticDataMask);
  182. return false;
  183. }
  184. bool ReflectionProbe::_toggleEditPosOffset(void *object, const char *index, const char *data)
  185. {
  186. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  187. probe->mEditPosOffset = !probe->mEditPosOffset;
  188. return false;
  189. }
  190. bool ReflectionProbe::_setRadius(void *object, const char *index, const char *data)
  191. {
  192. ReflectionProbe* probe = reinterpret_cast<ReflectionProbe*>(object);
  193. if (probe->mProbeShapeType != ProbeInfo::Sphere)
  194. return false;
  195. probe->mObjScale = Point3F(probe->mRadius, probe->mRadius, probe->mRadius);
  196. probe->setMaskBits(StaticDataMask);
  197. return true;
  198. }
  199. bool ReflectionProbe::_setReflectionMode(void *object, const char *index, const char *data)
  200. {
  201. ReflectionProbe* probe = reinterpret_cast<ReflectionProbe*>(object);
  202. if (!String::compare(data,"Static Cubemap"))
  203. {
  204. probe->mReflectionModeType = StaticCubemap;
  205. }
  206. else if (!String::compare(data, "Baked Cubemap"))
  207. {
  208. //Clear our cubemap if we changed it to be baked, just for cleanliness
  209. probe->mReflectionModeType = BakedCubemap;
  210. probe->mCubemapName = StringTable->EmptyString();
  211. }
  212. probe->setMaskBits(StaticDataMask);
  213. return true;
  214. }
  215. bool ReflectionProbe::onAdd()
  216. {
  217. if (!Parent::onAdd())
  218. return false;
  219. mEditPosOffset = false;
  220. mObjBox.minExtents.set(-0.5, -0.5, -0.5);
  221. mObjBox.maxExtents.set(0.5, 0.5, 0.5);
  222. // Skip our transform... it just dirties mask bits.
  223. Parent::setTransform(mObjToWorld);
  224. resetWorldBox();
  225. // Add this object to the scene
  226. addToScene();
  227. if (isServerObject())
  228. {
  229. if (!mPersistentId)
  230. mPersistentId = getOrCreatePersistentId();
  231. mProbeUniqueID = mPersistentId->getUUID().toString();
  232. }
  233. // Refresh this object's material (if any)
  234. if (isClientObject())
  235. {
  236. if (!mResourcesCreated && !createClientResources())
  237. return false;
  238. updateProbeParams();
  239. }
  240. setMaskBits(-1);
  241. return true;
  242. }
  243. void ReflectionProbe::onRemove()
  244. {
  245. if (isClientObject())
  246. {
  247. PROBEMGR->unregisterProbe(&mProbeInfo);
  248. }
  249. // Remove this object from the scene
  250. removeFromScene();
  251. Parent::onRemove();
  252. }
  253. void ReflectionProbe::handleDeleteAction()
  254. {
  255. //we're deleting it?
  256. //Then we need to clear out the processed cubemaps(if we have them)
  257. if (mReflectionModeType != StaticCubemap)
  258. {
  259. String prefilPath = getPrefilterMapPath();
  260. if (Torque::FS::IsFile(prefilPath))
  261. {
  262. Torque::FS::Remove(prefilPath);
  263. }
  264. String irrPath = getIrradianceMapPath();
  265. if (Torque::FS::IsFile(irrPath))
  266. {
  267. Torque::FS::Remove(irrPath);
  268. }
  269. }
  270. Parent::handleDeleteAction();
  271. }
  272. void ReflectionProbe::setTransform(const MatrixF & mat)
  273. {
  274. // Let SceneObject handle all of the matrix manipulation
  275. if (!mEditPosOffset)
  276. {
  277. Parent::setTransform(mat);
  278. setMaskBits(TransformMask);
  279. }
  280. else
  281. {
  282. mProbeRefOffset = mat.getPosition();
  283. setMaskBits(StaticDataMask);
  284. }
  285. mDirty = true;
  286. }
  287. const MatrixF& ReflectionProbe::getTransform() const
  288. {
  289. if (!mEditPosOffset)
  290. return mObjToWorld;
  291. else
  292. {
  293. MatrixF transformMat = MatrixF::Identity;
  294. transformMat.setPosition(mProbeRefOffset);
  295. return transformMat;
  296. }
  297. }
  298. void ReflectionProbe::setScale(const VectorF &scale)
  299. {
  300. if (!mEditPosOffset)
  301. {
  302. Parent::setScale(scale);
  303. setMaskBits(TransformMask);
  304. }
  305. else
  306. {
  307. mProbeRefScale = scale;
  308. setMaskBits(StaticDataMask);
  309. }
  310. mDirty = true;
  311. }
  312. const VectorF& ReflectionProbe::getScale() const
  313. {
  314. if (!mEditPosOffset)
  315. return mObjScale;
  316. else
  317. return mProbeRefScale;
  318. }
  319. bool ReflectionProbe::writeField(StringTableEntry fieldname, const char *value)
  320. {
  321. if (fieldname == StringTable->insert("Bake") || fieldname == StringTable->insert("EditPosOffset"))
  322. return false;
  323. return Parent::writeField(fieldname, value);
  324. }
  325. U32 ReflectionProbe::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  326. {
  327. // Allow the Parent to get a crack at writing its info
  328. U32 retMask = Parent::packUpdate(conn, mask, stream);
  329. // Write our transform information
  330. if (stream->writeFlag(mask & TransformMask))
  331. {
  332. stream->writeFlag(mEditPosOffset);
  333. mathWrite(*stream, mObjToWorld);
  334. mathWrite(*stream, mObjScale);
  335. mathWrite(*stream, mProbeRefOffset);
  336. mathWrite(*stream, mProbeRefScale);
  337. }
  338. if (stream->writeFlag(mask & StaticDataMask))
  339. {
  340. stream->write((U32)mProbeShapeType);
  341. stream->write(mRadius);
  342. stream->write(mProbeUniqueID);
  343. stream->write((U32)mReflectionModeType);
  344. stream->writeString(mCubemapName);
  345. }
  346. if (stream->writeFlag(mask & EnabledMask))
  347. {
  348. stream->writeFlag(mEnabled);
  349. }
  350. return retMask;
  351. }
  352. void ReflectionProbe::unpackUpdate(NetConnection *conn, BitStream *stream)
  353. {
  354. // Let the Parent read any info it sent
  355. Parent::unpackUpdate(conn, stream);
  356. if (stream->readFlag()) // TransformMask
  357. {
  358. mEditPosOffset = stream->readFlag();
  359. mathRead(*stream, &mObjToWorld);
  360. mathRead(*stream, &mObjScale);
  361. Parent::setTransform(mObjToWorld);
  362. resetWorldBox();
  363. mathRead(*stream, &mProbeRefOffset);
  364. mathRead(*stream, &mProbeRefScale);
  365. mDirty = true;
  366. }
  367. if (stream->readFlag()) // StaticDataMask
  368. {
  369. U32 shapeType = ProbeInfo::Sphere;
  370. stream->read(&shapeType);
  371. mProbeShapeType = (ProbeInfo::ProbeShapeType)shapeType;
  372. stream->read(&mRadius);
  373. stream->read(&mProbeUniqueID);
  374. U32 oldReflectModeType = mReflectionModeType;
  375. U32 reflectModeType = BakedCubemap;
  376. stream->read(&reflectModeType);
  377. mReflectionModeType = (ReflectionModeType)reflectModeType;
  378. StringTableEntry oldCubemapName = mCubemapName;
  379. mCubemapName = stream->readSTString();
  380. if(oldReflectModeType != mReflectionModeType || oldCubemapName != mCubemapName)
  381. mCubemapDirty = true;
  382. mDirty = true;
  383. }
  384. if (stream->readFlag()) // EnabledMask
  385. {
  386. mEnabled = stream->readFlag();
  387. mDirty = true;
  388. }
  389. }
  390. //-----------------------------------------------------------------------------
  391. // Object Rendering
  392. //-----------------------------------------------------------------------------
  393. void ReflectionProbe::updateProbeParams()
  394. {
  395. mProbeInfo.mObject = this;
  396. if (!mResourcesCreated)
  397. {
  398. if (!createClientResources())
  399. return;
  400. }
  401. mProbeInfo.mIsEnabled = mEnabled;
  402. mProbeInfo.mProbeShapeType = mProbeShapeType;
  403. if (mProbeShapeType == ProbeInfo::Sphere)
  404. mObjScale.set(mRadius, mRadius, mRadius);
  405. Box3F bounds;
  406. if (mProbeShapeType == ProbeInfo::Skylight)
  407. {
  408. mProbeInfo.mPosition = Point3F::Zero;
  409. mProbeInfo.mTransform = MatrixF::Identity;
  410. F32 visDist = gClientSceneGraph->getVisibleDistance();
  411. Box3F skylightBounds = Box3F(visDist * 2);
  412. skylightBounds.setCenter(Point3F::Zero);
  413. bounds = skylightBounds;
  414. setGlobalBounds();
  415. mProbeInfo.mScore = 10000.0f;
  416. }
  417. else
  418. {
  419. MatrixF transform = getTransform();
  420. mProbeInfo.mPosition = getPosition();
  421. transform.scale(getScale());
  422. mProbeInfo.mTransform = transform.inverse();
  423. bounds = mWorldBox;
  424. mProbeInfo.mScore = 1;
  425. }
  426. // Skip our transform... it just dirties mask bits.
  427. Parent::setTransform(mObjToWorld);
  428. resetWorldBox();
  429. mProbeInfo.mBounds = bounds;
  430. mProbeInfo.mExtents = getScale();
  431. mProbeInfo.mRadius = mRadius;
  432. mProbeInfo.mProbeRefOffset = mProbeRefOffset;
  433. mProbeInfo.mProbeRefScale = mProbeRefScale;
  434. mProbeInfo.mDirty = true;
  435. if (mCubemapDirty)
  436. {
  437. if (mReflectionModeType == StaticCubemap)
  438. processStaticCubemap();
  439. else if (mReflectionModeType == BakedCubemap)
  440. processBakedCubemap();
  441. else
  442. processDynamicCubemap();
  443. }
  444. }
  445. void ReflectionProbe::processDynamicCubemap()
  446. {
  447. }
  448. void ReflectionProbe::processBakedCubemap()
  449. {
  450. //mProbeInfo.mIsEnabled = false;
  451. if ((mReflectionModeType != BakedCubemap) || mProbeUniqueID.isEmpty())
  452. return;
  453. String irrPath = getIrradianceMapPath();
  454. if (Platform::isFile(irrPath))
  455. {
  456. mIrridianceMap->setCubemapFile(FileName(irrPath));
  457. mIrridianceMap->updateFaces();
  458. }
  459. if (mIrridianceMap == nullptr || mIrridianceMap->mCubemap.isNull())
  460. {
  461. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked irradiance map at %s", getIrradianceMapPath().c_str());
  462. return;
  463. }
  464. String prefilPath = getPrefilterMapPath();
  465. if (Platform::isFile(prefilPath))
  466. {
  467. mPrefilterMap->setCubemapFile(FileName(prefilPath));
  468. mPrefilterMap->updateFaces();
  469. }
  470. if (mPrefilterMap == nullptr || mPrefilterMap->mCubemap.isNull())
  471. {
  472. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str());
  473. return;
  474. }
  475. mProbeInfo.mPrefilterCubemap = mPrefilterMap->mCubemap;
  476. mProbeInfo.mIrradianceCubemap = mIrridianceMap->mCubemap;
  477. if (mEnabled && mProbeInfo.mPrefilterCubemap->isInitialized() && mProbeInfo.mIrradianceCubemap->isInitialized())
  478. {
  479. //mProbeInfo.mIsEnabled = true;
  480. mCubemapDirty = false;
  481. //Update the probe manager with our new texture!
  482. PROBEMGR->updateProbeTexture(&mProbeInfo);
  483. //now, cleanup
  484. mProbeInfo.mPrefilterCubemap.free();
  485. mProbeInfo.mIrradianceCubemap.free();
  486. }
  487. else
  488. {
  489. //if we failed, disable
  490. mProbeInfo.mIsEnabled = false;
  491. }
  492. }
  493. void ReflectionProbe::processStaticCubemap()
  494. {
  495. mProbeInfo.mIsEnabled = false;
  496. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  497. char irradFileName[256];
  498. dSprintf(irradFileName, 256, "%s%s_Irradiance.dds", path.c_str(), mCubemapName);
  499. if (Platform::isFile(irradFileName))
  500. {
  501. mIrridianceMap->setCubemapFile(FileName(irradFileName));
  502. mIrridianceMap->updateFaces();
  503. }
  504. if (mIrridianceMap == nullptr || mIrridianceMap->mCubemap.isNull())
  505. {
  506. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked irradiance map at %s", irradFileName);
  507. return;
  508. }
  509. char prefilterFileName[256];
  510. dSprintf(prefilterFileName, 256, "%s%s_Prefilter.dds", path.c_str(), mCubemapName);
  511. if (Platform::isFile(prefilterFileName))
  512. {
  513. mPrefilterMap->setCubemapFile(FileName(prefilterFileName));
  514. mPrefilterMap->updateFaces();
  515. }
  516. if (mPrefilterMap == nullptr || mPrefilterMap->mCubemap.isNull())
  517. {
  518. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked prefilter map at %s", prefilterFileName);
  519. return;
  520. }
  521. if (!Platform::isFile(prefilterFileName) || !Platform::isFile(irradFileName))
  522. {
  523. //If we are missing either of the files, just re-run the bake
  524. Sim::findObject(mCubemapName, mStaticCubemap);
  525. if (!mStaticCubemap)
  526. {
  527. Con::errorf("ReflectionProbe::updateMaterial() - unable to find static cubemap file!");
  528. return;
  529. }
  530. if (mStaticCubemap->mCubemap == nullptr)
  531. {
  532. mStaticCubemap->createMap();
  533. mStaticCubemap->updateFaces();
  534. }
  535. if (mUseHDRCaptures)
  536. {
  537. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  538. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  539. }
  540. else
  541. {
  542. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  543. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  544. }
  545. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  546. IBLUtilities::GenerateIrradianceMap(renderTarget, mStaticCubemap->mCubemap, mIrridianceMap->mCubemap);
  547. IBLUtilities::GeneratePrefilterMap(renderTarget, mStaticCubemap->mCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  548. IBLUtilities::SaveCubeMap(irradFileName, mIrridianceMap->mCubemap);
  549. IBLUtilities::SaveCubeMap(prefilterFileName, mPrefilterMap->mCubemap);
  550. }
  551. if ((mIrridianceMap != nullptr || !mIrridianceMap->mCubemap.isNull()) && (mPrefilterMap != nullptr || !mPrefilterMap->mCubemap.isNull()))
  552. {
  553. mProbeInfo.mPrefilterCubemap = mPrefilterMap->mCubemap;
  554. mProbeInfo.mIrradianceCubemap = mIrridianceMap->mCubemap;
  555. }
  556. if (mEnabled && mProbeInfo.mPrefilterCubemap->isInitialized() && mProbeInfo.mIrradianceCubemap->isInitialized())
  557. {
  558. mProbeInfo.mIsEnabled = true;
  559. mCubemapDirty = false;
  560. //Update the probe manager with our new texture!
  561. PROBEMGR->updateProbeTexture(&mProbeInfo);
  562. }
  563. }
  564. bool ReflectionProbe::createClientResources()
  565. {
  566. PROBEMGR->registerProbe(&mProbeInfo);
  567. mProbeInfo.mIsEnabled = false;
  568. //irridiance resources
  569. if (!mIrridianceMap)
  570. {
  571. mIrridianceMap = new CubemapData();
  572. mIrridianceMap->registerObject();
  573. mIrridianceMap->createMap();
  574. }
  575. //
  576. if (!mPrefilterMap)
  577. {
  578. mPrefilterMap = new CubemapData();
  579. mPrefilterMap->registerObject();
  580. mPrefilterMap->createMap();
  581. }
  582. mResourcesCreated = true;
  583. mCubemapDirty = true;
  584. return true;
  585. }
  586. String ReflectionProbe::getPrefilterMapPath()
  587. {
  588. if (mProbeUniqueID.isEmpty())
  589. {
  590. Con::errorf("ReflectionProbe::getPrefilterMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  591. return "";
  592. }
  593. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  594. char fileName[256];
  595. dSprintf(fileName, 256, "%s%s_Prefilter.dds", path.c_str(), mProbeUniqueID.c_str());
  596. return fileName;
  597. }
  598. String ReflectionProbe::getIrradianceMapPath()
  599. {
  600. if (mProbeUniqueID.isEmpty())
  601. {
  602. Con::errorf("ReflectionProbe::getIrradianceMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  603. return "";
  604. }
  605. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  606. char fileName[256];
  607. dSprintf(fileName, 256, "%s%s_Irradiance.dds", path.c_str(), mProbeUniqueID.c_str());
  608. return fileName;
  609. }
  610. void ReflectionProbe::bake()
  611. {
  612. if (mReflectionModeType != BakedCubemap)
  613. return;
  614. PROBEMGR->bakeProbe(this);
  615. setMaskBits(-1);
  616. }
  617. //-----------------------------------------------------------------------------
  618. //Rendering of editing/debug stuff
  619. //-----------------------------------------------------------------------------
  620. void ReflectionProbe::createEditorResources()
  621. {
  622. #ifdef TORQUE_TOOLS
  623. // Clean up our previous shape
  624. if (mEditorShapeInst)
  625. SAFE_DELETE(mEditorShapeInst);
  626. mEditorShape = NULL;
  627. String shapeFile = "tools/resources/previewSphereShape.dae";
  628. // Attempt to get the resource from the ResourceManager
  629. mEditorShape = ResourceManager::get().load(shapeFile);
  630. if (mEditorShape)
  631. {
  632. mEditorShapeInst = new TSShapeInstance(mEditorShape, isClientObject());
  633. }
  634. #endif
  635. }
  636. void ReflectionProbe::prepRenderImage(SceneRenderState *state)
  637. {
  638. if (!mEnabled || (!RenderProbeMgr::smRenderReflectionProbes && !dStrcmp(Con::getVariable("$Probes::Capturing", "0"),"1")))
  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 > RenderProbeMgr::smMaxProbeDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0))
  644. {
  645. mProbeInfo.mScore = RenderProbeMgr::smMaxProbeDrawDistance;
  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 = mMax(dist, 1.0f);
  658. Point3F vect = distVec;
  659. vect.normalizeSafe();
  660. //mProbeInfo.mScore *= mMax(mAbs(mDot(vect, state->getCameraTransform().getForwardVector())),0.001f);
  661. PROBEMGR->submitProbe(&mProbeInfo);
  662. #ifdef TORQUE_TOOLS
  663. if (ReflectionProbe::smRenderPreviewProbes && gEditingMission && mPrefilterMap != nullptr)
  664. {
  665. if(!mEditorShapeInst)
  666. createEditorResources();
  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 probe is selected or probe 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. #endif
  719. }
  720. void ReflectionProbe::_onRenderViz(ObjectRenderInst *ri,
  721. SceneRenderState *state,
  722. BaseMatInstance *overrideMat)
  723. {
  724. if (!RenderProbeMgr::smRenderReflectionProbes)
  725. return;
  726. GFXDrawUtil *draw = GFX->getDrawUtil();
  727. GFXStateBlockDesc desc;
  728. desc.setZReadWrite(true, false);
  729. desc.setCullMode(GFXCullNone);
  730. desc.setBlend(true);
  731. //desc.fillMode = GFXFillWireframe;
  732. // Base the sphere color on the light color.
  733. ColorI color = ColorI(255, 0, 255, 63);
  734. const MatrixF worldToObjectXfm = mObjToWorld;
  735. if (mProbeShapeType == ProbeInfo::Sphere)
  736. {
  737. draw->drawSphere(desc, mRadius, getPosition(), color);
  738. }
  739. else
  740. {
  741. Point3F tscl = worldToObjectXfm.getScale();
  742. Box3F projCube(-mObjScale/2, mObjScale / 2);
  743. projCube.setCenter(getPosition());
  744. draw->drawCube(desc, projCube, color, &worldToObjectXfm);
  745. }
  746. Point3F renderPos = getRenderTransform().getPosition();
  747. Box3F refCube = Box3F(-mProbeRefScale / 2, mProbeRefScale / 2);
  748. refCube.setCenter(renderPos + mProbeRefOffset);
  749. color = ColorI(0, 255, 255, 63);
  750. draw->drawCube(desc, refCube, color, &worldToObjectXfm);
  751. }
  752. void ReflectionProbe::setPreviewMatParameters(SceneRenderState* renderState, BaseMatInstance* mat)
  753. {
  754. if (!mat->getFeatures().hasFeature(MFT_isDeferred))
  755. return;
  756. //Set up the params
  757. MaterialParameters *matParams = mat->getMaterialParameters();
  758. //Get the deferred render target
  759. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  760. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  761. if (!deferredTexObject)
  762. return;
  763. GFX->setTexture(0, deferredTexObject);
  764. //Set the cubemap
  765. GFX->setCubeTexture(1, mPrefilterMap->mCubemap);
  766. //Set the invViewMat
  767. MatrixSet &matrixSet = renderState->getRenderPass()->getMatrixSet();
  768. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  769. MaterialParameterHandle *invViewMat = mat->getMaterialParameterHandle("$invViewMat");
  770. matParams->setSafe(invViewMat, worldToCameraXfm);
  771. }
  772. DefineEngineMethod(ReflectionProbe, postApply, void, (), ,
  773. "A utility method for forcing a network update.\n")
  774. {
  775. object->inspectPostApply();
  776. }
  777. DefineEngineMethod(ReflectionProbe, Bake, void, (), ,
  778. "@brief Bakes the cubemaps for a reflection probe\n\n.")
  779. {
  780. ReflectionProbe *clientProbe = (ReflectionProbe*)object->getClientObject();
  781. if (clientProbe)
  782. {
  783. clientProbe->bake();
  784. }
  785. }