reflectionProbe.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "T3D/lighting/reflectionProbe.h"
  23. #include "math/mathIO.h"
  24. #include "scene/sceneRenderState.h"
  25. #include "console/consoleTypes.h"
  26. #include "core/stream/bitStream.h"
  27. #include "materials/baseMatInstance.h"
  28. #include "console/engineAPI.h"
  29. #include "gfx/gfxDrawUtil.h"
  30. #include "gfx/gfxDebugEvent.h"
  31. #include "gfx/gfxTransformSaver.h"
  32. #include "math/mathUtils.h"
  33. #include "gfx/bitmap/gBitmap.h"
  34. #include "core/stream/fileStream.h"
  35. #include "core/fileObject.h"
  36. #include "core/resourceManager.h"
  37. #include "console/simPersistID.h"
  38. #include "T3D/gameFunctions.h"
  39. #include "postFx/postEffect.h"
  40. #include "renderInstance/renderProbeMgr.h"
  41. #include "renderInstance/renderProbeMgr.h"
  42. #include "math/util/sphereMesh.h"
  43. #include "materials/materialManager.h"
  44. #include "math/util/matrixSet.h"
  45. #include "gfx/bitmap/cubemapSaver.h"
  46. #include "materials/materialFeatureTypes.h"
  47. #include "gfx/gfxTextureManager.h"
  48. #include "T3D/lighting/IBLUtilities.h"
  49. #include "scene/reflector.h"
  50. extern bool gEditingMission;
  51. extern ColorI gCanvasClearColor;
  52. bool ReflectionProbe::smRenderPreviewProbes = true;
  53. IMPLEMENT_CO_NETOBJECT_V1(ReflectionProbe);
  54. ConsoleDocClass(ReflectionProbe,
  55. "@brief An example scene object which renders a mesh.\n\n"
  56. "This class implements a basic SceneObject that can exist in the world at a "
  57. "3D position and render itself. There are several valid ways to render an "
  58. "object in Torque. This class implements the preferred rendering method which "
  59. "is to submit a MeshRenderInst along with a Material, vertex buffer, "
  60. "primitive buffer, and transform and allow the RenderMeshMgr handle the "
  61. "actual setup and rendering for you.\n\n"
  62. "See the C++ code for implementation details.\n\n"
  63. "@ingroup Examples\n");
  64. ImplementEnumType(ReflectProbeType,
  65. "Type of mesh data available in a shape.\n"
  66. "@ingroup gameObjects")
  67. { ProbeRenderInst::Sphere, "Sphere", "Sphere shaped" },
  68. { ProbeRenderInst::Box, "Box", "Box shape" }
  69. EndImplementEnumType;
  70. ImplementEnumType(ReflectionModeEnum,
  71. "Type of mesh data available in a shape.\n"
  72. "@ingroup gameObjects")
  73. { ReflectionProbe::NoReflection, "No Reflections", "This probe does not provide any local reflection data"},
  74. { ReflectionProbe::StaticCubemap, "Static Cubemap", "Uses a static CubemapData" },
  75. { ReflectionProbe::BakedCubemap, "Baked Cubemap", "Uses a cubemap baked from the probe's current position" },
  76. //{ ReflectionProbe::DynamicCubemap, "Dynamic Cubemap", "Uses a cubemap baked from the probe's current position, updated at a set rate" },
  77. EndImplementEnumType;
  78. //-----------------------------------------------------------------------------
  79. // Object setup and teardown
  80. //-----------------------------------------------------------------------------
  81. ReflectionProbe::ReflectionProbe()
  82. {
  83. // Flag this object so that it will always
  84. // be sent across the network to clients
  85. mNetFlags.set(Ghostable | ScopeAlways);
  86. mTypeMask = LightObjectType | MarkerObjectType;
  87. mProbeShapeType = ProbeRenderInst::Box;
  88. mReflectionModeType = BakedCubemap;
  89. mEnabled = true;
  90. mBakeReflections = false;
  91. mCubemapDirty = false;
  92. mRadius = 10;
  93. mObjScale = Point3F::One * 10;
  94. mProbeRefScale = Point3F::One*10;
  95. mUseHDRCaptures = true;
  96. mStaticCubemap = NULL;
  97. mProbeUniqueID = "";
  98. mEditorShapeInst = NULL;
  99. mEditorShape = NULL;
  100. mRefreshRateMS = 200;
  101. mDynamicLastBakeMS = 0;
  102. mMaxDrawDistance = 75;
  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 != ProbeRenderInst::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 = "";
  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 = String::ToString(mPersistentId->getUUID().getHash());
  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.mProbeIdx);
  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->write(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 = ProbeRenderInst::Sphere;
  366. stream->read(&shapeType);
  367. mProbeShapeType = (ProbeRenderInst::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. String oldCubemapName = mCubemapName;
  375. stream->read(&mCubemapName);
  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. if (!mResourcesCreated)
  392. {
  393. if (!createClientResources())
  394. return;
  395. }
  396. mProbeInfo.mIsEnabled = mEnabled;
  397. mProbeInfo.mProbeShapeType = mProbeShapeType;
  398. if (mProbeShapeType == ProbeRenderInst::Sphere)
  399. mObjScale.set(mRadius, mRadius, mRadius);
  400. Box3F bounds;
  401. if (mProbeShapeType == ProbeRenderInst::Skylight)
  402. {
  403. mProbeInfo.mPosition = Point3F::Zero;
  404. mProbeInfo.mTransform = MatrixF::Identity;
  405. F32 visDist = gClientSceneGraph->getVisibleDistance();
  406. Box3F skylightBounds = Box3F(visDist * 2);
  407. skylightBounds.setCenter(Point3F::Zero);
  408. bounds = skylightBounds;
  409. setGlobalBounds();
  410. mProbeInfo.mScore = 10000.0f;
  411. }
  412. else
  413. {
  414. MatrixF transform = getTransform();
  415. mProbeInfo.mPosition = getPosition();
  416. transform.scale(getScale());
  417. mProbeInfo.mTransform = transform.inverse();
  418. bounds = mWorldBox;
  419. mProbeInfo.mScore = 1;
  420. }
  421. // Skip our transform... it just dirties mask bits.
  422. Parent::setTransform(mObjToWorld);
  423. resetWorldBox();
  424. mProbeInfo.mBounds = bounds;
  425. mProbeInfo.mExtents = getScale();
  426. mProbeInfo.mRadius = mRadius;
  427. mProbeInfo.mProbeRefOffset = mProbeRefOffset;
  428. mProbeInfo.mProbeRefScale = mProbeRefScale;
  429. mProbeInfo.mDirty = true;
  430. if (mCubemapDirty)
  431. {
  432. if (mReflectionModeType == StaticCubemap)
  433. processStaticCubemap();
  434. else if (mReflectionModeType == BakedCubemap)
  435. processBakedCubemap();
  436. else
  437. processDynamicCubemap();
  438. }
  439. PROBEMGR->updateProbes();
  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. }
  484. void ReflectionProbe::processStaticCubemap()
  485. {
  486. mProbeInfo.mIsEnabled = false;
  487. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  488. char irradFileName[256];
  489. dSprintf(irradFileName, 256, "%s%s_Irradiance.dds", path.c_str(), mCubemapName.c_str());
  490. if (Platform::isFile(irradFileName))
  491. {
  492. mIrridianceMap->setCubemapFile(FileName(irradFileName));
  493. mIrridianceMap->updateFaces();
  494. }
  495. if (mIrridianceMap == nullptr || mIrridianceMap->mCubemap.isNull())
  496. {
  497. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked irradiance map at %s", irradFileName);
  498. return;
  499. }
  500. char prefilterFileName[256];
  501. dSprintf(prefilterFileName, 256, "%s%s_Prefilter.dds", path.c_str(), mCubemapName.c_str());
  502. if (Platform::isFile(prefilterFileName))
  503. {
  504. mPrefilterMap->setCubemapFile(FileName(prefilterFileName));
  505. mPrefilterMap->updateFaces();
  506. }
  507. if (mPrefilterMap == nullptr || mPrefilterMap->mCubemap.isNull())
  508. {
  509. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked prefilter map at %s", prefilterFileName);
  510. return;
  511. }
  512. if (!Platform::isFile(prefilterFileName) || !Platform::isFile(irradFileName))
  513. {
  514. //If we are missing either of the files, just re-run the bake
  515. Sim::findObject(mCubemapName, mStaticCubemap);
  516. if (!mStaticCubemap)
  517. {
  518. Con::errorf("ReflectionProbe::updateMaterial() - unable to find static cubemap file!");
  519. return;
  520. }
  521. if (mStaticCubemap->mCubemap == nullptr)
  522. {
  523. mStaticCubemap->createMap();
  524. mStaticCubemap->updateFaces();
  525. }
  526. if (mUseHDRCaptures)
  527. {
  528. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  529. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  530. }
  531. else
  532. {
  533. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  534. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  535. }
  536. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  537. IBLUtilities::GenerateIrradianceMap(renderTarget, mStaticCubemap->mCubemap, mIrridianceMap->mCubemap);
  538. IBLUtilities::GeneratePrefilterMap(renderTarget, mStaticCubemap->mCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  539. IBLUtilities::SaveCubeMap(irradFileName, mIrridianceMap->mCubemap);
  540. IBLUtilities::SaveCubeMap(prefilterFileName, mPrefilterMap->mCubemap);
  541. }
  542. if ((mIrridianceMap != nullptr || !mIrridianceMap->mCubemap.isNull()) && (mPrefilterMap != nullptr || !mPrefilterMap->mCubemap.isNull()))
  543. {
  544. mProbeInfo.mPrefilterCubemap = mPrefilterMap->mCubemap;
  545. mProbeInfo.mIrradianceCubemap = mIrridianceMap->mCubemap;
  546. }
  547. if (mEnabled && mProbeInfo.mPrefilterCubemap->isInitialized() && mProbeInfo.mIrradianceCubemap->isInitialized())
  548. {
  549. mProbeInfo.mIsEnabled = true;
  550. mCubemapDirty = false;
  551. //Update the probe manager with our new texture!
  552. PROBEMGR->updateProbeTexture(&mProbeInfo);
  553. }
  554. }
  555. bool ReflectionProbe::createClientResources()
  556. {
  557. PROBEMGR->registerProbe(&mProbeInfo);
  558. mProbeInfo.mIsEnabled = false;
  559. //irridiance resources
  560. if (!mIrridianceMap)
  561. {
  562. mIrridianceMap = new CubemapData();
  563. mIrridianceMap->registerObject();
  564. mIrridianceMap->createMap();
  565. }
  566. //
  567. if (!mPrefilterMap)
  568. {
  569. mPrefilterMap = new CubemapData();
  570. mPrefilterMap->registerObject();
  571. mPrefilterMap->createMap();
  572. }
  573. mResourcesCreated = true;
  574. mCubemapDirty = true;
  575. return true;
  576. }
  577. String ReflectionProbe::getPrefilterMapPath()
  578. {
  579. if (mProbeUniqueID.isEmpty())
  580. {
  581. Con::errorf("ReflectionProbe::getPrefilterMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  582. return "";
  583. }
  584. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  585. char fileName[256];
  586. dSprintf(fileName, 256, "%s%s_Prefilter.dds", path.c_str(), mProbeUniqueID.c_str());
  587. return fileName;
  588. }
  589. String ReflectionProbe::getIrradianceMapPath()
  590. {
  591. if (mProbeUniqueID.isEmpty())
  592. {
  593. Con::errorf("ReflectionProbe::getIrradianceMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  594. return "";
  595. }
  596. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  597. char fileName[256];
  598. dSprintf(fileName, 256, "%s%s_Irradiance.dds", path.c_str(), mProbeUniqueID.c_str());
  599. return fileName;
  600. }
  601. void ReflectionProbe::bake()
  602. {
  603. if (mReflectionModeType != BakedCubemap)
  604. return;
  605. PROBEMGR->bakeProbe(this);
  606. setMaskBits(-1);
  607. }
  608. //-----------------------------------------------------------------------------
  609. //Rendering of editing/debug stuff
  610. //-----------------------------------------------------------------------------
  611. void ReflectionProbe::createEditorResources()
  612. {
  613. #ifdef TORQUE_TOOLS
  614. // Clean up our previous shape
  615. if (mEditorShapeInst)
  616. SAFE_DELETE(mEditorShapeInst);
  617. mEditorShape = NULL;
  618. String shapeFile = "tools/resources/ReflectProbeSphere.dae";
  619. // Attempt to get the resource from the ResourceManager
  620. mEditorShape = ResourceManager::get().load(shapeFile);
  621. if (mEditorShape)
  622. {
  623. mEditorShapeInst = new TSShapeInstance(mEditorShape, isClientObject());
  624. }
  625. #endif
  626. }
  627. void ReflectionProbe::prepRenderImage(SceneRenderState *state)
  628. {
  629. if (!mEnabled || !RenderProbeMgr::smRenderReflectionProbes)
  630. return;
  631. Point3F distVec = getRenderPosition() - state->getCameraPosition();
  632. F32 dist = distVec.len();
  633. //Culling distance. Can be adjusted for performance options considerations via the scalar
  634. if (dist > mMaxDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0))
  635. {
  636. mProbeInfo.mScore = mMaxDrawDistance;
  637. return;
  638. }
  639. if (mReflectionModeType == DynamicCubemap && mRefreshRateMS < (Platform::getRealMilliseconds() - mDynamicLastBakeMS))
  640. {
  641. bake();
  642. mDynamicLastBakeMS = Platform::getRealMilliseconds();
  643. }
  644. //Submit our probe to actually do the probe action
  645. // Get a handy pointer to our RenderPassmanager
  646. //RenderPassManager *renderPass = state->getRenderPass();
  647. //Update our score based on our radius, distance
  648. mProbeInfo.mScore = mMax(dist, 1.0f);
  649. Point3F vect = distVec;
  650. vect.normalizeSafe();
  651. //mProbeInfo.mScore *= mMax(mAbs(mDot(vect, state->getCameraTransform().getForwardVector())),0.001f);
  652. PROBEMGR->submitProbe(mProbeInfo);
  653. #ifdef TORQUE_TOOLS
  654. if (ReflectionProbe::smRenderPreviewProbes && gEditingMission && mPrefilterMap != nullptr)
  655. {
  656. if(!mEditorShapeInst)
  657. createEditorResources();
  658. GFXTransformSaver saver;
  659. // Calculate the distance of this object from the camera
  660. Point3F cameraOffset;
  661. getRenderTransform().getColumn(3, &cameraOffset);
  662. cameraOffset -= state->getDiffuseCameraPosition();
  663. dist = cameraOffset.len();
  664. if (dist < 0.01f)
  665. dist = 0.01f;
  666. // Set up the LOD for the shape
  667. F32 invScale = (1.0f / getMax(getMax(mObjScale.x, mObjScale.y), mObjScale.z));
  668. mEditorShapeInst->setDetailFromDistance(state, dist * invScale);
  669. // Make sure we have a valid level of detail
  670. if (mEditorShapeInst->getCurrentDetail() < 0)
  671. return;
  672. BaseMatInstance* probePrevMat = mEditorShapeInst->getMaterialList()->getMaterialInst(0);
  673. setPreviewMatParameters(state, probePrevMat);
  674. // GFXTransformSaver is a handy helper class that restores
  675. // the current GFX matrices to their original values when
  676. // it goes out of scope at the end of the function
  677. // Set up our TS render state
  678. TSRenderState rdata;
  679. rdata.setSceneState(state);
  680. rdata.setFadeOverride(1.0f);
  681. if(mReflectionModeType != DynamicCubemap)
  682. rdata.setCubemap(mPrefilterMap->mCubemap);
  683. else
  684. rdata.setCubemap(mDynamicCubemap);
  685. // We might have some forward lit materials
  686. // so pass down a query to gather lights.
  687. LightQuery query;
  688. query.init(getWorldSphere());
  689. rdata.setLightQuery(&query);
  690. // Set the world matrix to the objects render transform
  691. MatrixF mat = getRenderTransform();
  692. GFX->setWorldMatrix(mat);
  693. // Animate the the shape
  694. mEditorShapeInst->animate();
  695. // Allow the shape to submit the RenderInst(s) for itself
  696. mEditorShapeInst->render(rdata);
  697. saver.restore();
  698. }
  699. // If the probe is selected or probe visualization
  700. // is enabled then register the callback.
  701. const bool isSelectedInEditor = (gEditingMission && isSelected());
  702. if (isSelectedInEditor)
  703. {
  704. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  705. ri->renderDelegate.bind(this, &ReflectionProbe::_onRenderViz);
  706. ri->type = RenderPassManager::RIT_Editor;
  707. state->getRenderPass()->addInst(ri);
  708. }
  709. #endif
  710. }
  711. void ReflectionProbe::_onRenderViz(ObjectRenderInst *ri,
  712. SceneRenderState *state,
  713. BaseMatInstance *overrideMat)
  714. {
  715. if (!RenderProbeMgr::smRenderReflectionProbes)
  716. return;
  717. GFXDrawUtil *draw = GFX->getDrawUtil();
  718. GFXStateBlockDesc desc;
  719. desc.setZReadWrite(true, false);
  720. desc.setCullMode(GFXCullNone);
  721. desc.setBlend(true);
  722. //desc.fillMode = GFXFillWireframe;
  723. // Base the sphere color on the light color.
  724. ColorI color = ColorI(255, 0, 255, 63);
  725. const MatrixF worldToObjectXfm = mObjToWorld;
  726. if (mProbeShapeType == ProbeRenderInst::Sphere)
  727. {
  728. draw->drawSphere(desc, mRadius, getPosition(), color);
  729. }
  730. else
  731. {
  732. Point3F tscl = worldToObjectXfm.getScale();
  733. Box3F projCube(-mObjScale/2, mObjScale / 2);
  734. projCube.setCenter(getPosition());
  735. draw->drawCube(desc, projCube, color, &worldToObjectXfm);
  736. }
  737. Point3F renderPos = getRenderTransform().getPosition();
  738. Box3F refCube = Box3F(-mProbeRefScale / 2, mProbeRefScale / 2);
  739. refCube.setCenter(renderPos + mProbeRefOffset);
  740. color = ColorI(0, 255, 255, 63);
  741. draw->drawCube(desc, refCube, color, &worldToObjectXfm);
  742. }
  743. void ReflectionProbe::setPreviewMatParameters(SceneRenderState* renderState, BaseMatInstance* mat)
  744. {
  745. if (!mat->getFeatures().hasFeature(MFT_isDeferred))
  746. return;
  747. //Set up the params
  748. MaterialParameters *matParams = mat->getMaterialParameters();
  749. //Get the deferred render target
  750. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  751. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  752. if (!deferredTexObject)
  753. return;
  754. GFX->setTexture(0, deferredTexObject);
  755. //Set the cubemap
  756. GFX->setCubeTexture(1, mPrefilterMap->mCubemap);
  757. //Set the invViewMat
  758. MatrixSet &matrixSet = renderState->getRenderPass()->getMatrixSet();
  759. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  760. MaterialParameterHandle *invViewMat = mat->getMaterialParameterHandle("$invViewMat");
  761. matParams->setSafe(invViewMat, worldToCameraXfm);
  762. }
  763. DefineEngineMethod(ReflectionProbe, postApply, void, (), ,
  764. "A utility method for forcing a network update.\n")
  765. {
  766. object->inspectPostApply();
  767. }
  768. DefineEngineMethod(ReflectionProbe, Bake, void, (), ,
  769. "@brief Bakes the cubemaps for a reflection probe\n\n.")
  770. {
  771. ReflectionProbe *clientProbe = (ReflectionProbe*)object->getClientObject();
  772. if (clientProbe)
  773. {
  774. clientProbe->bake();
  775. }
  776. }