reflectionProbe.cpp 30 KB

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