reflectionProbe.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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. mEditorShapeInst = NULL;
  100. mEditorShape = NULL;
  101. mRefreshRateMS = 200;
  102. mDynamicLastBakeMS = 0;
  103. mResourcesCreated = false;
  104. mPrefilterSize = 64;
  105. mPrefilterMipLevels = mLog2(F32(mPrefilterSize));
  106. mPrefilterMap = nullptr;
  107. mIrridianceMap = nullptr;
  108. mProbeRefOffset = Point3F::Zero;
  109. mEditPosOffset = false;
  110. mCaptureMask = REFLECTION_PROBE_CAPTURE_TYPEMASK;
  111. }
  112. ReflectionProbe::~ReflectionProbe()
  113. {
  114. if (mEditorShapeInst)
  115. SAFE_DELETE(mEditorShapeInst);
  116. if (mReflectionModeType == StaticCubemap && mStaticCubemap)
  117. mStaticCubemap->deleteObject();
  118. }
  119. //-----------------------------------------------------------------------------
  120. // Object Editing
  121. //-----------------------------------------------------------------------------
  122. void ReflectionProbe::initPersistFields()
  123. {
  124. addGroup("Rendering");
  125. addProtectedField("enabled", TypeBool, Offset(mEnabled, ReflectionProbe),
  126. &_setEnabled, &defaultProtectedGetFn, "Is the probe enabled or not");
  127. endGroup("Rendering");
  128. addGroup("Reflection");
  129. addProtectedField("radius", TypeF32, Offset(mRadius, ReflectionProbe), &_setRadius, &defaultProtectedGetFn,
  130. "The name of the material used to render the mesh.");
  131. addProtectedField("EditPosOffset", TypeBool, Offset(mEditPosOffset, ReflectionProbe),
  132. &_toggleEditPosOffset, &defaultProtectedGetFn, "Toggle Edit Pos Offset Mode", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  133. 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");
  134. 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");
  135. addProtectedField("ReflectionMode", TypeReflectionModeEnum, Offset(mReflectionModeType, ReflectionProbe), &_setReflectionMode, &defaultProtectedGetFn,
  136. "Used to dictate what sort of cubemap the probes use when using IBL.");
  137. 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.");
  138. //addField("DynamicReflectionRefreshMS", TypeS32, Offset(mRefreshRateMS, ReflectionProbe), "How often the dynamic cubemap is refreshed in milliseconds. Only works when the ReflectionMode is set to DynamicCubemap.");
  139. addProtectedField("Bake", TypeBool, Offset(mBakeReflections, ReflectionProbe),
  140. &_doBake, &defaultProtectedGetFn, "Bake Probe Reflections", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  141. endGroup("Reflection");
  142. Con::addVariable("$Light::renderReflectionProbes", TypeBool, &RenderProbeMgr::smRenderReflectionProbes,
  143. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  144. "@note Only works for shadow mapped lights.\n\n"
  145. "@ingroup Lighting");
  146. Con::addVariable("$Light::renderPreviewProbes", TypeBool, &ReflectionProbe::smRenderPreviewProbes,
  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. // SceneObject already handles exposing the transform
  151. Parent::initPersistFields();
  152. }
  153. void ReflectionProbe::inspectPostApply()
  154. {
  155. Parent::inspectPostApply();
  156. mDirty = true;
  157. bool liveUpdates = Con::getBoolVariable("$Probes::liveUpdates", false);
  158. if (liveUpdates)
  159. {
  160. bake();
  161. }
  162. // Flag the network mask to send the updates
  163. // to the client object
  164. setMaskBits(-1);
  165. }
  166. bool ReflectionProbe::_setEnabled(void *object, const char *index, const char *data)
  167. {
  168. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  169. probe->mEnabled = dAtob(data);
  170. probe->setMaskBits(EnabledMask);
  171. return true;
  172. }
  173. bool ReflectionProbe::_doBake(void *object, const char *index, const char *data)
  174. {
  175. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  176. probe->bake();
  177. probe->setMaskBits(StaticDataMask);
  178. return false;
  179. }
  180. bool ReflectionProbe::_toggleEditPosOffset(void *object, const char *index, const char *data)
  181. {
  182. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  183. probe->mEditPosOffset = !probe->mEditPosOffset;
  184. return false;
  185. }
  186. bool ReflectionProbe::_setRadius(void *object, const char *index, const char *data)
  187. {
  188. ReflectionProbe* probe = reinterpret_cast<ReflectionProbe*>(object);
  189. if (probe->mProbeShapeType != ProbeInfo::Sphere)
  190. return false;
  191. probe->mObjScale = Point3F(probe->mRadius, probe->mRadius, probe->mRadius);
  192. probe->setMaskBits(StaticDataMask);
  193. return true;
  194. }
  195. bool ReflectionProbe::_setReflectionMode(void *object, const char *index, const char *data)
  196. {
  197. ReflectionProbe* probe = reinterpret_cast<ReflectionProbe*>(object);
  198. if (!String::compare(data,"Static Cubemap"))
  199. {
  200. probe->mReflectionModeType = StaticCubemap;
  201. }
  202. else if (!String::compare(data, "Baked Cubemap"))
  203. {
  204. //Clear our cubemap if we changed it to be baked, just for cleanliness
  205. probe->mReflectionModeType = BakedCubemap;
  206. probe->mCubemapName = StringTable->EmptyString();
  207. }
  208. probe->setMaskBits(StaticDataMask);
  209. return true;
  210. }
  211. bool ReflectionProbe::onAdd()
  212. {
  213. if (!Parent::onAdd())
  214. return false;
  215. mEditPosOffset = false;
  216. mObjBox.minExtents.set(-0.5, -0.5, -0.5);
  217. mObjBox.maxExtents.set(0.5, 0.5, 0.5);
  218. // Skip our transform... it just dirties mask bits.
  219. Parent::setTransform(mObjToWorld);
  220. resetWorldBox();
  221. // Add this object to the scene
  222. addToScene();
  223. if (isServerObject())
  224. {
  225. if (!mPersistentId)
  226. mPersistentId = getOrCreatePersistentId();
  227. mProbeUniqueID = mPersistentId->getUUID().toString();
  228. }
  229. // Refresh this object's material (if any)
  230. if (isClientObject())
  231. {
  232. if (!mResourcesCreated && !createClientResources())
  233. return false;
  234. updateProbeParams();
  235. }
  236. setMaskBits(-1);
  237. return true;
  238. }
  239. void ReflectionProbe::onRemove()
  240. {
  241. if (isClientObject())
  242. {
  243. PROBEMGR->unregisterProbe(&mProbeInfo);
  244. }
  245. // Remove this object from the scene
  246. removeFromScene();
  247. Parent::onRemove();
  248. }
  249. void ReflectionProbe::handleDeleteAction()
  250. {
  251. //we're deleting it?
  252. //Then we need to clear out the processed cubemaps(if we have them)
  253. if (mReflectionModeType != StaticCubemap)
  254. {
  255. String prefilPath = getPrefilterMapPath();
  256. if (Platform::isFile(prefilPath))
  257. {
  258. Platform::fileDelete(prefilPath);
  259. }
  260. String irrPath = getIrradianceMapPath();
  261. if (Platform::isFile(irrPath))
  262. {
  263. Platform::fileDelete(irrPath);
  264. }
  265. }
  266. Parent::handleDeleteAction();
  267. }
  268. void ReflectionProbe::setTransform(const MatrixF & mat)
  269. {
  270. // Let SceneObject handle all of the matrix manipulation
  271. if (!mEditPosOffset)
  272. {
  273. Parent::setTransform(mat);
  274. setMaskBits(TransformMask);
  275. }
  276. else
  277. {
  278. mProbeRefOffset = mat.getPosition();
  279. setMaskBits(StaticDataMask);
  280. }
  281. mDirty = true;
  282. }
  283. const MatrixF& ReflectionProbe::getTransform() const
  284. {
  285. if (!mEditPosOffset)
  286. return mObjToWorld;
  287. else
  288. {
  289. MatrixF transformMat = MatrixF::Identity;
  290. transformMat.setPosition(mProbeRefOffset);
  291. return transformMat;
  292. }
  293. }
  294. void ReflectionProbe::setScale(const VectorF &scale)
  295. {
  296. if (!mEditPosOffset)
  297. {
  298. Parent::setScale(scale);
  299. setMaskBits(TransformMask);
  300. }
  301. else
  302. {
  303. mProbeRefScale = scale;
  304. setMaskBits(StaticDataMask);
  305. }
  306. mDirty = true;
  307. }
  308. const VectorF& ReflectionProbe::getScale() const
  309. {
  310. if (!mEditPosOffset)
  311. return mObjScale;
  312. else
  313. return mProbeRefScale;
  314. }
  315. bool ReflectionProbe::writeField(StringTableEntry fieldname, const char *value)
  316. {
  317. if (fieldname == StringTable->insert("Bake") || fieldname == StringTable->insert("EditPosOffset"))
  318. return false;
  319. return Parent::writeField(fieldname, value);
  320. }
  321. U32 ReflectionProbe::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  322. {
  323. // Allow the Parent to get a crack at writing its info
  324. U32 retMask = Parent::packUpdate(conn, mask, stream);
  325. // Write our transform information
  326. if (stream->writeFlag(mask & TransformMask))
  327. {
  328. stream->writeFlag(mEditPosOffset);
  329. mathWrite(*stream, mObjToWorld);
  330. mathWrite(*stream, mObjScale);
  331. mathWrite(*stream, mProbeRefOffset);
  332. mathWrite(*stream, mProbeRefScale);
  333. }
  334. if (stream->writeFlag(mask & StaticDataMask))
  335. {
  336. stream->write((U32)mProbeShapeType);
  337. stream->write(mRadius);
  338. stream->write(mProbeUniqueID);
  339. stream->write((U32)mReflectionModeType);
  340. stream->writeString(mCubemapName);
  341. }
  342. if (stream->writeFlag(mask & EnabledMask))
  343. {
  344. stream->writeFlag(mEnabled);
  345. }
  346. return retMask;
  347. }
  348. void ReflectionProbe::unpackUpdate(NetConnection *conn, BitStream *stream)
  349. {
  350. // Let the Parent read any info it sent
  351. Parent::unpackUpdate(conn, stream);
  352. if (stream->readFlag()) // TransformMask
  353. {
  354. mEditPosOffset = stream->readFlag();
  355. mathRead(*stream, &mObjToWorld);
  356. mathRead(*stream, &mObjScale);
  357. Parent::setTransform(mObjToWorld);
  358. resetWorldBox();
  359. mathRead(*stream, &mProbeRefOffset);
  360. mathRead(*stream, &mProbeRefScale);
  361. mDirty = true;
  362. }
  363. if (stream->readFlag()) // StaticDataMask
  364. {
  365. U32 shapeType = ProbeInfo::Sphere;
  366. stream->read(&shapeType);
  367. mProbeShapeType = (ProbeInfo::ProbeShapeType)shapeType;
  368. stream->read(&mRadius);
  369. stream->read(&mProbeUniqueID);
  370. U32 oldReflectModeType = mReflectionModeType;
  371. U32 reflectModeType = BakedCubemap;
  372. stream->read(&reflectModeType);
  373. mReflectionModeType = (ReflectionModeType)reflectModeType;
  374. StringTableEntry oldCubemapName = mCubemapName;
  375. mCubemapName = stream->readSTString();
  376. if(oldReflectModeType != mReflectionModeType || oldCubemapName != mCubemapName)
  377. mCubemapDirty = true;
  378. mDirty = true;
  379. }
  380. if (stream->readFlag()) // EnabledMask
  381. {
  382. mEnabled = stream->readFlag();
  383. mDirty = true;
  384. }
  385. }
  386. //-----------------------------------------------------------------------------
  387. // Object Rendering
  388. //-----------------------------------------------------------------------------
  389. void ReflectionProbe::updateProbeParams()
  390. {
  391. mProbeInfo.mObject = this;
  392. if (!mResourcesCreated)
  393. {
  394. if (!createClientResources())
  395. return;
  396. }
  397. mProbeInfo.mIsEnabled = mEnabled;
  398. mProbeInfo.mProbeShapeType = mProbeShapeType;
  399. if (mProbeShapeType == ProbeInfo::Sphere)
  400. mObjScale.set(mRadius, mRadius, mRadius);
  401. Box3F bounds;
  402. if (mProbeShapeType == ProbeInfo::Skylight)
  403. {
  404. mProbeInfo.mPosition = Point3F::Zero;
  405. mProbeInfo.mTransform = MatrixF::Identity;
  406. F32 visDist = gClientSceneGraph->getVisibleDistance();
  407. Box3F skylightBounds = Box3F(visDist * 2);
  408. skylightBounds.setCenter(Point3F::Zero);
  409. bounds = skylightBounds;
  410. setGlobalBounds();
  411. mProbeInfo.mScore = 10000.0f;
  412. }
  413. else
  414. {
  415. MatrixF transform = getTransform();
  416. mProbeInfo.mPosition = getPosition();
  417. transform.scale(getScale());
  418. mProbeInfo.mTransform = transform.inverse();
  419. bounds = mWorldBox;
  420. mProbeInfo.mScore = 1;
  421. }
  422. // Skip our transform... it just dirties mask bits.
  423. Parent::setTransform(mObjToWorld);
  424. resetWorldBox();
  425. mProbeInfo.mBounds = bounds;
  426. mProbeInfo.mExtents = getScale();
  427. mProbeInfo.mRadius = mRadius;
  428. mProbeInfo.mProbeRefOffset = mProbeRefOffset;
  429. mProbeInfo.mProbeRefScale = mProbeRefScale;
  430. mProbeInfo.mDirty = true;
  431. if (mCubemapDirty)
  432. {
  433. if (mReflectionModeType == StaticCubemap)
  434. processStaticCubemap();
  435. else if (mReflectionModeType == BakedCubemap)
  436. processBakedCubemap();
  437. else
  438. processDynamicCubemap();
  439. }
  440. }
  441. void ReflectionProbe::processDynamicCubemap()
  442. {
  443. }
  444. void ReflectionProbe::processBakedCubemap()
  445. {
  446. //mProbeInfo.mIsEnabled = false;
  447. if ((mReflectionModeType != BakedCubemap) || mProbeUniqueID.isEmpty())
  448. return;
  449. String irrPath = getIrradianceMapPath();
  450. if (Platform::isFile(irrPath))
  451. {
  452. mIrridianceMap->setCubemapFile(FileName(irrPath));
  453. mIrridianceMap->updateFaces();
  454. }
  455. if (mIrridianceMap == nullptr || mIrridianceMap->mCubemap.isNull())
  456. {
  457. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked irradiance map at %s", getIrradianceMapPath().c_str());
  458. return;
  459. }
  460. String prefilPath = getPrefilterMapPath();
  461. if (Platform::isFile(prefilPath))
  462. {
  463. mPrefilterMap->setCubemapFile(FileName(prefilPath));
  464. mPrefilterMap->updateFaces();
  465. }
  466. if (mPrefilterMap == nullptr || mPrefilterMap->mCubemap.isNull())
  467. {
  468. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str());
  469. return;
  470. }
  471. mProbeInfo.mPrefilterCubemap = mPrefilterMap->mCubemap;
  472. mProbeInfo.mIrradianceCubemap = mIrridianceMap->mCubemap;
  473. if (mEnabled && mProbeInfo.mPrefilterCubemap->isInitialized() && mProbeInfo.mIrradianceCubemap->isInitialized())
  474. {
  475. //mProbeInfo.mIsEnabled = true;
  476. mCubemapDirty = false;
  477. //Update the probe manager with our new texture!
  478. PROBEMGR->updateProbeTexture(&mProbeInfo);
  479. //now, cleanup
  480. mProbeInfo.mPrefilterCubemap.free();
  481. mProbeInfo.mIrradianceCubemap.free();
  482. }
  483. else
  484. {
  485. //if we failed, disable
  486. mProbeInfo.mIsEnabled = false;
  487. }
  488. }
  489. void ReflectionProbe::processStaticCubemap()
  490. {
  491. mProbeInfo.mIsEnabled = false;
  492. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  493. char irradFileName[256];
  494. dSprintf(irradFileName, 256, "%s%s_Irradiance.dds", path.c_str(), mCubemapName);
  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);
  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. }
  552. if (mEnabled && mProbeInfo.mPrefilterCubemap->isInitialized() && mProbeInfo.mIrradianceCubemap->isInitialized())
  553. {
  554. mProbeInfo.mIsEnabled = true;
  555. mCubemapDirty = false;
  556. //Update the probe manager with our new texture!
  557. PROBEMGR->updateProbeTexture(&mProbeInfo);
  558. }
  559. }
  560. bool ReflectionProbe::createClientResources()
  561. {
  562. PROBEMGR->registerProbe(&mProbeInfo);
  563. mProbeInfo.mIsEnabled = false;
  564. //irridiance resources
  565. if (!mIrridianceMap)
  566. {
  567. mIrridianceMap = new CubemapData();
  568. mIrridianceMap->registerObject();
  569. mIrridianceMap->createMap();
  570. }
  571. //
  572. if (!mPrefilterMap)
  573. {
  574. mPrefilterMap = new CubemapData();
  575. mPrefilterMap->registerObject();
  576. mPrefilterMap->createMap();
  577. }
  578. mResourcesCreated = true;
  579. mCubemapDirty = true;
  580. return true;
  581. }
  582. String ReflectionProbe::getPrefilterMapPath()
  583. {
  584. if (mProbeUniqueID.isEmpty())
  585. {
  586. Con::errorf("ReflectionProbe::getPrefilterMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  587. return "";
  588. }
  589. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  590. char fileName[256];
  591. dSprintf(fileName, 256, "%s%s_Prefilter.dds", path.c_str(), mProbeUniqueID.c_str());
  592. return fileName;
  593. }
  594. String ReflectionProbe::getIrradianceMapPath()
  595. {
  596. if (mProbeUniqueID.isEmpty())
  597. {
  598. Con::errorf("ReflectionProbe::getIrradianceMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  599. return "";
  600. }
  601. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  602. char fileName[256];
  603. dSprintf(fileName, 256, "%s%s_Irradiance.dds", path.c_str(), mProbeUniqueID.c_str());
  604. return fileName;
  605. }
  606. void ReflectionProbe::bake()
  607. {
  608. if (mReflectionModeType != BakedCubemap)
  609. return;
  610. PROBEMGR->bakeProbe(this);
  611. setMaskBits(-1);
  612. }
  613. //-----------------------------------------------------------------------------
  614. //Rendering of editing/debug stuff
  615. //-----------------------------------------------------------------------------
  616. void ReflectionProbe::createEditorResources()
  617. {
  618. #ifdef TORQUE_TOOLS
  619. // Clean up our previous shape
  620. if (mEditorShapeInst)
  621. SAFE_DELETE(mEditorShapeInst);
  622. mEditorShape = NULL;
  623. String shapeFile = "tools/resources/previewSphereShape.dae";
  624. // Attempt to get the resource from the ResourceManager
  625. mEditorShape = ResourceManager::get().load(shapeFile);
  626. if (mEditorShape)
  627. {
  628. mEditorShapeInst = new TSShapeInstance(mEditorShape, isClientObject());
  629. }
  630. #endif
  631. }
  632. void ReflectionProbe::prepRenderImage(SceneRenderState *state)
  633. {
  634. if (!mEnabled || (!RenderProbeMgr::smRenderReflectionProbes && Con::getVariable("$Probes::Capturing", "0") == "0"))
  635. return;
  636. Point3F distVec = getRenderPosition() - state->getCameraPosition();
  637. F32 dist = distVec.len();
  638. //Culling distance. Can be adjusted for performance options considerations via the scalar
  639. if (dist > RenderProbeMgr::smMaxProbeDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0))
  640. {
  641. mProbeInfo.mScore = RenderProbeMgr::smMaxProbeDrawDistance;
  642. return;
  643. }
  644. if (mReflectionModeType == DynamicCubemap && mRefreshRateMS < (Platform::getRealMilliseconds() - mDynamicLastBakeMS))
  645. {
  646. bake();
  647. mDynamicLastBakeMS = Platform::getRealMilliseconds();
  648. }
  649. //Submit our probe to actually do the probe action
  650. // Get a handy pointer to our RenderPassmanager
  651. //RenderPassManager *renderPass = state->getRenderPass();
  652. //Update our score based on our radius, distance
  653. mProbeInfo.mScore = mMax(dist, 1.0f);
  654. Point3F vect = distVec;
  655. vect.normalizeSafe();
  656. //mProbeInfo.mScore *= mMax(mAbs(mDot(vect, state->getCameraTransform().getForwardVector())),0.001f);
  657. PROBEMGR->submitProbe(&mProbeInfo);
  658. #ifdef TORQUE_TOOLS
  659. if (ReflectionProbe::smRenderPreviewProbes && gEditingMission && mPrefilterMap != nullptr)
  660. {
  661. if(!mEditorShapeInst)
  662. createEditorResources();
  663. GFXTransformSaver saver;
  664. // Calculate the distance of this object from the camera
  665. Point3F cameraOffset;
  666. getRenderTransform().getColumn(3, &cameraOffset);
  667. cameraOffset -= state->getDiffuseCameraPosition();
  668. dist = cameraOffset.len();
  669. if (dist < 0.01f)
  670. dist = 0.01f;
  671. // Set up the LOD for the shape
  672. F32 invScale = (1.0f / getMax(getMax(mObjScale.x, mObjScale.y), mObjScale.z));
  673. mEditorShapeInst->setDetailFromDistance(state, dist * invScale);
  674. // Make sure we have a valid level of detail
  675. if (mEditorShapeInst->getCurrentDetail() < 0)
  676. return;
  677. BaseMatInstance* probePrevMat = mEditorShapeInst->getMaterialList()->getMaterialInst(0);
  678. setPreviewMatParameters(state, probePrevMat);
  679. // GFXTransformSaver is a handy helper class that restores
  680. // the current GFX matrices to their original values when
  681. // it goes out of scope at the end of the function
  682. // Set up our TS render state
  683. TSRenderState rdata;
  684. rdata.setSceneState(state);
  685. rdata.setFadeOverride(1.0f);
  686. if(mReflectionModeType != DynamicCubemap)
  687. rdata.setCubemap(mPrefilterMap->mCubemap);
  688. else
  689. rdata.setCubemap(mDynamicCubemap);
  690. // We might have some forward lit materials
  691. // so pass down a query to gather lights.
  692. LightQuery query;
  693. query.init(getWorldSphere());
  694. rdata.setLightQuery(&query);
  695. // Set the world matrix to the objects render transform
  696. MatrixF mat = getRenderTransform();
  697. GFX->setWorldMatrix(mat);
  698. // Animate the the shape
  699. mEditorShapeInst->animate();
  700. // Allow the shape to submit the RenderInst(s) for itself
  701. mEditorShapeInst->render(rdata);
  702. saver.restore();
  703. }
  704. // If the probe is selected or probe visualization
  705. // is enabled then register the callback.
  706. const bool isSelectedInEditor = (gEditingMission && isSelected());
  707. if (isSelectedInEditor)
  708. {
  709. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  710. ri->renderDelegate.bind(this, &ReflectionProbe::_onRenderViz);
  711. ri->type = RenderPassManager::RIT_Editor;
  712. state->getRenderPass()->addInst(ri);
  713. }
  714. #endif
  715. }
  716. void ReflectionProbe::_onRenderViz(ObjectRenderInst *ri,
  717. SceneRenderState *state,
  718. BaseMatInstance *overrideMat)
  719. {
  720. if (!RenderProbeMgr::smRenderReflectionProbes)
  721. return;
  722. GFXDrawUtil *draw = GFX->getDrawUtil();
  723. GFXStateBlockDesc desc;
  724. desc.setZReadWrite(true, false);
  725. desc.setCullMode(GFXCullNone);
  726. desc.setBlend(true);
  727. //desc.fillMode = GFXFillWireframe;
  728. // Base the sphere color on the light color.
  729. ColorI color = ColorI(255, 0, 255, 63);
  730. const MatrixF worldToObjectXfm = mObjToWorld;
  731. if (mProbeShapeType == ProbeInfo::Sphere)
  732. {
  733. draw->drawSphere(desc, mRadius, getPosition(), color);
  734. }
  735. else
  736. {
  737. Point3F tscl = worldToObjectXfm.getScale();
  738. Box3F projCube(-mObjScale/2, mObjScale / 2);
  739. projCube.setCenter(getPosition());
  740. draw->drawCube(desc, projCube, color, &worldToObjectXfm);
  741. }
  742. Point3F renderPos = getRenderTransform().getPosition();
  743. Box3F refCube = Box3F(-mProbeRefScale / 2, mProbeRefScale / 2);
  744. refCube.setCenter(renderPos + mProbeRefOffset);
  745. color = ColorI(0, 255, 255, 63);
  746. draw->drawCube(desc, refCube, color, &worldToObjectXfm);
  747. }
  748. void ReflectionProbe::setPreviewMatParameters(SceneRenderState* renderState, BaseMatInstance* mat)
  749. {
  750. if (!mat->getFeatures().hasFeature(MFT_isDeferred))
  751. return;
  752. //Set up the params
  753. MaterialParameters *matParams = mat->getMaterialParameters();
  754. //Get the deferred render target
  755. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  756. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  757. if (!deferredTexObject)
  758. return;
  759. GFX->setTexture(0, deferredTexObject);
  760. //Set the cubemap
  761. GFX->setCubeTexture(1, mPrefilterMap->mCubemap);
  762. //Set the invViewMat
  763. MatrixSet &matrixSet = renderState->getRenderPass()->getMatrixSet();
  764. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  765. MaterialParameterHandle *invViewMat = mat->getMaterialParameterHandle("$invViewMat");
  766. matParams->setSafe(invViewMat, worldToCameraXfm);
  767. }
  768. DefineEngineMethod(ReflectionProbe, postApply, void, (), ,
  769. "A utility method for forcing a network update.\n")
  770. {
  771. object->inspectPostApply();
  772. }
  773. DefineEngineMethod(ReflectionProbe, Bake, void, (), ,
  774. "@brief Bakes the cubemaps for a reflection probe\n\n.")
  775. {
  776. ReflectionProbe *clientProbe = (ReflectionProbe*)object->getClientObject();
  777. if (clientProbe)
  778. {
  779. clientProbe->bake();
  780. }
  781. }