reflectionProbe.cpp 30 KB

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