reflectionProbe.cpp 30 KB

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