reflectionProbe.cpp 29 KB

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