reflectionProbe.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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. cubeDescId(0),
  83. reflectorDesc(nullptr),
  84. mSphereVertCount(0),
  85. mSpherePrimitiveCount(0)
  86. {
  87. // Flag this object so that it will always
  88. // be sent across the network to clients
  89. mNetFlags.set(Ghostable | ScopeAlways);
  90. mTypeMask = LightObjectType | MarkerObjectType;
  91. mProbeShapeType = ProbeRenderInst::Box;
  92. mReflectionModeType = BakedCubemap;
  93. mEnabled = true;
  94. mBake = false;
  95. mDirty = false;
  96. mCubemapDirty = false;
  97. mRadius = 10;
  98. mObjScale = Point3F::One * 10;
  99. mProbeRefScale = Point3F::One*10;
  100. mUseHDRCaptures = true;
  101. mStaticCubemap = NULL;
  102. mProbeUniqueID = "";
  103. mEditorShapeInst = NULL;
  104. mEditorShape = NULL;
  105. mRefreshRateMS = 500;
  106. mDynamicLastBakeMS = 0;
  107. mMaxDrawDistance = 75;
  108. mResourcesCreated = false;
  109. mProbeInfo = nullptr;
  110. mPrefilterSize = 64;
  111. mPrefilterMipLevels = mLog2(F32(mPrefilterSize))+1;
  112. mPrefilterMap = nullptr;
  113. mIrridianceMap = nullptr;
  114. mProbeRefOffset = Point3F::Zero;
  115. mEditPosOffset = false;
  116. mCaptureMask = REFLECTION_PROBE_CAPTURE_TYPEMASK;
  117. }
  118. ReflectionProbe::~ReflectionProbe()
  119. {
  120. if (mEditorShapeInst)
  121. SAFE_DELETE(mEditorShapeInst);
  122. if (mReflectionModeType == StaticCubemap && mStaticCubemap)
  123. mStaticCubemap->deleteObject();
  124. }
  125. //-----------------------------------------------------------------------------
  126. // Object Editing
  127. //-----------------------------------------------------------------------------
  128. void ReflectionProbe::initPersistFields()
  129. {
  130. addGroup("Rendering");
  131. addProtectedField("enabled", TypeBool, Offset(mEnabled, ReflectionProbe),
  132. &_setEnabled, &defaultProtectedGetFn, "Regenerate Voxel Grid");
  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), "");
  140. addField("refScale", TypePoint3F, Offset(mProbeRefScale, ReflectionProbe), "");
  141. addProtectedField("ReflectionMode", TypeReflectionModeEnum, Offset(mReflectionModeType, ReflectionProbe), &_setReflectionMode, &defaultProtectedGetFn,
  142. "The type of mesh data to use for collision queries.");
  143. addField("StaticCubemap", TypeCubemapName, Offset(mCubemapName, ReflectionProbe), "Cubemap used instead of reflection texture if fullReflect is off.");
  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(mBake, ReflectionProbe),
  146. &_doBake, &defaultProtectedGetFn, "Regenerate Voxel Grid", 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 != ProbeRenderInst::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 = "";
  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 = String::ToString(mPersistentId->getUUID().getHash());
  234. }
  235. // Refresh this object's material (if any)
  236. if (isClientObject())
  237. {
  238. if (!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->mProbeIdx);
  250. mProbeInfo = nullptr;
  251. }
  252. // Remove this object from the scene
  253. removeFromScene();
  254. Parent::onRemove();
  255. }
  256. void ReflectionProbe::handleDeleteAction()
  257. {
  258. //we're deleting it?
  259. //Then we need to clear out the processed cubemaps(if we have them)
  260. if (mReflectionModeType != StaticCubemap)
  261. {
  262. String prefilPath = getPrefilterMapPath();
  263. if (Platform::isFile(prefilPath))
  264. {
  265. Platform::fileDelete(prefilPath);
  266. }
  267. String irrPath = getIrradianceMapPath();
  268. if (Platform::isFile(irrPath))
  269. {
  270. Platform::fileDelete(irrPath);
  271. }
  272. }
  273. Parent::handleDeleteAction();
  274. }
  275. void ReflectionProbe::setTransform(const MatrixF & mat)
  276. {
  277. // Let SceneObject handle all of the matrix manipulation
  278. if (!mEditPosOffset)
  279. {
  280. Parent::setTransform(mat);
  281. setMaskBits(TransformMask);
  282. }
  283. else
  284. {
  285. mProbeRefOffset = mat.getPosition();
  286. setMaskBits(StaticDataMask);
  287. }
  288. mDirty = true;
  289. }
  290. const MatrixF& ReflectionProbe::getTransform() const
  291. {
  292. if (!mEditPosOffset)
  293. return mObjToWorld;
  294. else
  295. {
  296. MatrixF transformMat = MatrixF::Identity;
  297. transformMat.setPosition(mProbeRefOffset);
  298. return transformMat;
  299. }
  300. }
  301. void ReflectionProbe::setScale(const VectorF &scale)
  302. {
  303. if (!mEditPosOffset)
  304. {
  305. Parent::setScale(scale);
  306. setMaskBits(TransformMask);
  307. }
  308. else
  309. {
  310. mProbeRefScale = scale;
  311. setMaskBits(StaticDataMask);
  312. }
  313. mDirty = true;
  314. }
  315. const VectorF& ReflectionProbe::getScale() const
  316. {
  317. if (!mEditPosOffset)
  318. return mObjScale;
  319. else
  320. return mProbeRefScale;
  321. }
  322. bool ReflectionProbe::writeField(StringTableEntry fieldname, const char *value)
  323. {
  324. if (fieldname == StringTable->insert("Bake") || fieldname == StringTable->insert("EditPosOffset"))
  325. return false;
  326. return Parent::writeField(fieldname, value);
  327. }
  328. U32 ReflectionProbe::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  329. {
  330. // Allow the Parent to get a crack at writing its info
  331. U32 retMask = Parent::packUpdate(conn, mask, stream);
  332. // Write our transform information
  333. if (stream->writeFlag(mask & TransformMask))
  334. {
  335. stream->writeFlag(mEditPosOffset);
  336. mathWrite(*stream, mObjToWorld);
  337. mathWrite(*stream, mObjScale);
  338. mathWrite(*stream, mProbeRefOffset);
  339. mathWrite(*stream, mProbeRefScale);
  340. }
  341. if (stream->writeFlag(mask & StaticDataMask))
  342. {
  343. stream->write((U32)mProbeShapeType);
  344. stream->write(mRadius);
  345. stream->write(mProbeUniqueID);
  346. stream->write((U32)mReflectionModeType);
  347. stream->write(mCubemapName);
  348. stream->write(mRefreshRateMS);
  349. }
  350. if (stream->writeFlag(mask & EnabledMask))
  351. {
  352. stream->writeFlag(mEnabled);
  353. }
  354. return retMask;
  355. }
  356. void ReflectionProbe::unpackUpdate(NetConnection *conn, BitStream *stream)
  357. {
  358. // Let the Parent read any info it sent
  359. Parent::unpackUpdate(conn, stream);
  360. if (stream->readFlag()) // TransformMask
  361. {
  362. mEditPosOffset = stream->readFlag();
  363. mathRead(*stream, &mObjToWorld);
  364. mathRead(*stream, &mObjScale);
  365. Parent::setTransform(mObjToWorld);
  366. resetWorldBox();
  367. mathRead(*stream, &mProbeRefOffset);
  368. mathRead(*stream, &mProbeRefScale);
  369. mDirty = true;
  370. }
  371. if (stream->readFlag()) // StaticDataMask
  372. {
  373. U32 shapeType = ProbeRenderInst::Sphere;
  374. stream->read(&shapeType);
  375. mProbeShapeType = (ProbeRenderInst::ProbeShapeType)shapeType;
  376. stream->read(&mRadius);
  377. stream->read(&mProbeUniqueID);
  378. U32 oldReflectModeType = mReflectionModeType;
  379. U32 reflectModeType = BakedCubemap;
  380. stream->read(&reflectModeType);
  381. mReflectionModeType = (ReflectionModeType)reflectModeType;
  382. String oldCubemapName = mCubemapName;
  383. stream->read(&mCubemapName);
  384. if(oldReflectModeType != mReflectionModeType || oldCubemapName != mCubemapName)
  385. mCubemapDirty = true;
  386. stream->read(&mRefreshRateMS);
  387. mDirty = true;
  388. }
  389. if (stream->readFlag()) // EnabledMask
  390. {
  391. mEnabled = stream->readFlag();
  392. mDirty = true;
  393. }
  394. if (mDirty)
  395. {
  396. updateProbeParams();
  397. }
  398. }
  399. //-----------------------------------------------------------------------------
  400. // Object Rendering
  401. //-----------------------------------------------------------------------------
  402. void ReflectionProbe::updateProbeParams()
  403. {
  404. if (!mProbeInfo)
  405. return;
  406. mProbeInfo->mIsEnabled = mEnabled;
  407. mProbeInfo->mProbeShapeType = mProbeShapeType;
  408. if (mProbeShapeType == ProbeRenderInst::Sphere)
  409. mObjScale.set(mRadius, mRadius, mRadius);
  410. Box3F bounds;
  411. if (mProbeShapeType == ProbeRenderInst::Skylight)
  412. {
  413. mProbeInfo->mPosition = Point3F::Zero;
  414. mProbeInfo->mTransform = MatrixF::Identity;
  415. mProbeInfo->mIsSkylight = true;
  416. F32 visDist = gClientSceneGraph->getVisibleDistance();
  417. Box3F skylightBounds = Box3F(visDist * 2);
  418. skylightBounds.setCenter(Point3F::Zero);
  419. bounds = skylightBounds;
  420. setGlobalBounds();
  421. mProbeInfo->mScore = -1.0f;
  422. }
  423. else
  424. {
  425. MatrixF transform = getTransform();
  426. mProbeInfo->mPosition = getPosition();
  427. transform.scale(getScale());
  428. mProbeInfo->mTransform = transform.inverse();
  429. mProbeInfo->mIsSkylight = false;
  430. bounds = mWorldBox;
  431. mProbeInfo->mScore = mMaxDrawDistance;
  432. }
  433. // Skip our transform... it just dirties mask bits.
  434. Parent::setTransform(mObjToWorld);
  435. resetWorldBox();
  436. mProbeInfo->mBounds = bounds;
  437. mProbeInfo->mExtents = getScale();
  438. mProbeInfo->mRadius = mRadius;
  439. mProbeInfo->mProbeRefOffset = mProbeRefOffset;
  440. mProbeInfo->mProbeRefScale = mProbeRefScale;
  441. mProbeInfo->mDirty = true;
  442. if (mCubemapDirty)
  443. {
  444. if (mReflectionModeType == StaticCubemap)
  445. processStaticCubemap();
  446. else if (mReflectionModeType == BakedCubemap)
  447. processBakedCubemap();
  448. else
  449. processDynamicCubemap();
  450. }
  451. PROBEMGR->updateProbes();
  452. }
  453. void ReflectionProbe::processDynamicCubemap()
  454. {
  455. /*if (!mProbeInfo)
  456. return;
  457. mEnabled = false;
  458. if (mReflectionModeType == DynamicCubemap && !mDynamicCubemap.isNull())
  459. {
  460. mProbeInfo->mPrefilterCubemap = mDynamicCubemap;
  461. if (reflectorDesc == nullptr)
  462. {
  463. //find it
  464. if (!Sim::findObject("DefaultCubeDesc", reflectorDesc))
  465. {
  466. mProbeInfo->mIsEnabled = false;
  467. return;
  468. }
  469. }
  470. mCubeReflector.unregisterReflector();
  471. mCubeReflector.registerReflector(this, reflectorDesc); //need to decide how we wanna do the reflectorDesc. static name or a field
  472. }
  473. if (mEnabled)
  474. mProbeInfo->mIsEnabled = true;
  475. else
  476. mProbeInfo->mIsEnabled = false;
  477. mCubemapDirty = false;
  478. //Update the probe manager with our new texture!
  479. //if (!mProbeInfo->mIsSkylight && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  480. // PROBEMGR->updateProbeTexture(mProbeInfo->mProbeIdx);*/
  481. if (!mProbeInfo)
  482. return;
  483. mProbeInfo->mIsEnabled = false;
  484. if (mReflectionModeType != DynamicCubemap)
  485. return;
  486. if (reflectorDesc == nullptr)
  487. {
  488. //find it
  489. if (!Sim::findObject("DefaultCubeDesc", reflectorDesc))
  490. {
  491. mProbeInfo->mIsEnabled = false;
  492. return;
  493. }
  494. mCubeReflector.unregisterReflector();
  495. mCubeReflector.registerReflector(this, reflectorDesc); //need to decide how we wanna do the reflectorDesc. static name or a field
  496. }
  497. if (mCubeReflector.getCubemap())
  498. {
  499. U32 resolution = Con::getIntVariable("$pref::ReflectionProbes::BakeResolution", 64);
  500. U32 prefilterMipLevels = mLog2(F32(resolution))+1;
  501. //Prep it with whatever resolution we've dictated for our bake
  502. mIrridianceMap->mCubemap->initDynamic(resolution, PROBEMGR->PROBE_FORMAT);
  503. mPrefilterMap->mCubemap->initDynamic(resolution, PROBEMGR->PROBE_FORMAT);
  504. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  505. IBLUtilities::GenerateIrradianceMap(renderTarget, mCubeReflector.getCubemap(), mIrridianceMap->mCubemap);
  506. IBLUtilities::GeneratePrefilterMap(renderTarget, mCubeReflector.getCubemap(), prefilterMipLevels, mPrefilterMap->mCubemap);
  507. }
  508. if (mIrridianceMap == nullptr || mIrridianceMap->mCubemap.isNull())
  509. {
  510. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked irradiance map at %s", getIrradianceMapPath().c_str());
  511. return;
  512. }
  513. if (mPrefilterMap == nullptr || mPrefilterMap->mCubemap.isNull())
  514. {
  515. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str());
  516. return;
  517. }
  518. mProbeInfo->mPrefilterCubemap = mPrefilterMap->mCubemap;
  519. mProbeInfo->mIrradianceCubemap = mIrridianceMap->mCubemap;
  520. if (mEnabled && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  521. {
  522. mProbeInfo->mIsEnabled = true;
  523. mCubemapDirty = false;
  524. //Update the probe manager with our new texture!
  525. PROBEMGR->updateProbeTexture(mProbeInfo);
  526. }
  527. }
  528. void ReflectionProbe::processBakedCubemap()
  529. {
  530. if (!mProbeInfo)
  531. return;
  532. mProbeInfo->mIsEnabled = false;
  533. if ((mReflectionModeType != BakedCubemap) || mProbeUniqueID.isEmpty())
  534. return;
  535. String irrPath = getIrradianceMapPath();
  536. if (Platform::isFile(irrPath))
  537. {
  538. mIrridianceMap->setCubemapFile(FileName(irrPath));
  539. mIrridianceMap->updateFaces();
  540. }
  541. if (mIrridianceMap == nullptr || !mIrridianceMap->mCubemap->isInitialized())
  542. {
  543. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked irradiance map at %s", getIrradianceMapPath().c_str());
  544. return;
  545. }
  546. String prefilPath = getPrefilterMapPath();
  547. if (Platform::isFile(prefilPath))
  548. {
  549. mPrefilterMap->setCubemapFile(FileName(prefilPath));
  550. mPrefilterMap->updateFaces();
  551. }
  552. if (mPrefilterMap == nullptr || !mPrefilterMap->mCubemap->isInitialized())
  553. {
  554. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str());
  555. return;
  556. }
  557. mProbeInfo->mPrefilterCubemap = mPrefilterMap->mCubemap;
  558. mProbeInfo->mIrradianceCubemap = mIrridianceMap->mCubemap;
  559. if (mEnabled && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  560. {
  561. mProbeInfo->mIsEnabled = true;
  562. mCubemapDirty = false;
  563. //Update the probe manager with our new texture!
  564. PROBEMGR->updateProbeTexture(mProbeInfo);
  565. }
  566. }
  567. void ReflectionProbe::processStaticCubemap()
  568. {
  569. if (!mProbeInfo)
  570. return;
  571. mProbeInfo->mIsEnabled = false;
  572. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  573. char irradFileName[256];
  574. dSprintf(irradFileName, 256, "%s_Irradiance.dds", path.c_str(), mCubemapName.c_str());
  575. if (Platform::isFile(irradFileName))
  576. {
  577. if (mIrridianceMap == nullptr)
  578. {
  579. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked irradiance map at %s", irradFileName);
  580. return;
  581. }
  582. mIrridianceMap->setCubemapFile(FileName(irradFileName));
  583. if (mIrridianceMap->mCubemap.isNull())
  584. {
  585. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked irradiance map at %s", irradFileName);
  586. return;
  587. }
  588. mIrridianceMap->updateFaces();
  589. }
  590. char prefilterFileName[256];
  591. dSprintf(prefilterFileName, 256, "%s%s_Prefilter.dds", path.c_str(), mCubemapName.c_str());
  592. if (Platform::isFile(prefilterFileName))
  593. {
  594. if (mPrefilterMap == nullptr)
  595. {
  596. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked prefilter map at %s", prefilterFileName);
  597. return;
  598. }
  599. mPrefilterMap->setCubemapFile(FileName(prefilterFileName));
  600. if (mPrefilterMap->mCubemap.isNull())
  601. {
  602. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked prefilter map at %s", prefilterFileName);
  603. return;
  604. }
  605. mPrefilterMap->updateFaces();
  606. }
  607. if (!Platform::isFile(prefilterFileName) || !Platform::isFile(irradFileName))
  608. {
  609. //If we are missing either of the files, just re-run the bake
  610. Sim::findObject(mCubemapName, mStaticCubemap);
  611. if (!mStaticCubemap)
  612. {
  613. Con::errorf("ReflectionProbe::updateMaterial() - unable to find static cubemap file!");
  614. return;
  615. }
  616. if (mStaticCubemap->mCubemap == nullptr)
  617. {
  618. mStaticCubemap->createMap();
  619. mStaticCubemap->updateFaces();
  620. }
  621. if (mUseHDRCaptures)
  622. {
  623. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  624. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  625. }
  626. else
  627. {
  628. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  629. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  630. }
  631. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  632. IBLUtilities::GenerateIrradianceMap(renderTarget, mStaticCubemap->mCubemap, mIrridianceMap->mCubemap);
  633. IBLUtilities::GeneratePrefilterMap(renderTarget, mStaticCubemap->mCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  634. IBLUtilities::SaveCubeMap(irradFileName, mIrridianceMap->mCubemap);
  635. IBLUtilities::SaveCubeMap(prefilterFileName, mPrefilterMap->mCubemap);
  636. }
  637. if ((mIrridianceMap != nullptr && !mIrridianceMap->mCubemap.isNull()) && (mPrefilterMap != nullptr && !mPrefilterMap->mCubemap.isNull()))
  638. {
  639. mProbeInfo->mPrefilterCubemap = mPrefilterMap->mCubemap;
  640. mProbeInfo->mIrradianceCubemap = mIrridianceMap->mCubemap;
  641. }
  642. if (mEnabled && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  643. {
  644. mProbeInfo->mIsEnabled = true;
  645. mCubemapDirty = false;
  646. //Update the probe manager with our new texture!
  647. PROBEMGR->updateProbeTexture(mProbeInfo);
  648. }
  649. }
  650. bool ReflectionProbe::createClientResources()
  651. {
  652. if (mProbeInfo == nullptr)
  653. {
  654. mProbeInfo = PROBEMGR->registerProbe();
  655. if (!mProbeInfo)
  656. return false;
  657. mProbeInfo->mIsEnabled = false;
  658. }
  659. //irridiance resources
  660. if (!mIrridianceMap)
  661. {
  662. mIrridianceMap = new CubemapData();
  663. mIrridianceMap->registerObject();
  664. mIrridianceMap->createMap();
  665. }
  666. //
  667. if (!mPrefilterMap)
  668. {
  669. mPrefilterMap = new CubemapData();
  670. mPrefilterMap->registerObject();
  671. mPrefilterMap->createMap();
  672. }
  673. mResourcesCreated = true;
  674. mCubemapDirty = true;
  675. return true;
  676. }
  677. String ReflectionProbe::getPrefilterMapPath()
  678. {
  679. if (mProbeUniqueID.isEmpty())
  680. {
  681. Con::errorf("ReflectionProbe::getPrefilterMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  682. return "";
  683. }
  684. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  685. char fileName[256];
  686. dSprintf(fileName, 256, "%s%s_Prefilter.dds", path.c_str(), mProbeUniqueID.c_str());
  687. return fileName;
  688. }
  689. String ReflectionProbe::getIrradianceMapPath()
  690. {
  691. if (mProbeUniqueID.isEmpty())
  692. {
  693. Con::errorf("ReflectionProbe::getIrradianceMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  694. return "";
  695. }
  696. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  697. char fileName[256];
  698. dSprintf(fileName, 256, "%s%s_Irradiance.dds", path.c_str(), mProbeUniqueID.c_str());
  699. return fileName;
  700. }
  701. void ReflectionProbe::bake()
  702. {
  703. bool writeFile = mReflectionModeType == BakedCubemap ? true : false;
  704. if (mReflectionModeType == StaticCubemap)
  705. return;
  706. PROBEMGR->bakeProbe(this, writeFile);
  707. setMaskBits(-1);
  708. }
  709. //-----------------------------------------------------------------------------
  710. //Rendering of editing/debug stuff
  711. //-----------------------------------------------------------------------------
  712. void ReflectionProbe::createGeometry()
  713. {
  714. // Clean up our previous shape
  715. if (mEditorShapeInst)
  716. SAFE_DELETE(mEditorShapeInst);
  717. mEditorShape = NULL;
  718. String shapeFile = "tools/resources/ReflectProbeSphere.dae";
  719. // Attempt to get the resource from the ResourceManager
  720. mEditorShape = ResourceManager::get().load(shapeFile);
  721. if (mEditorShape)
  722. {
  723. mEditorShapeInst = new TSShapeInstance(mEditorShape, isClientObject());
  724. }
  725. }
  726. void ReflectionProbe::prepRenderImage(SceneRenderState *state)
  727. {
  728. if (!mEnabled || !RenderProbeMgr::smRenderReflectionProbes)
  729. return;
  730. Point3F distVec = getRenderPosition() - state->getCameraPosition();
  731. F32 dist = distVec.len();
  732. //Culling distance. Can be adjusted for performance options considerations via the scalar
  733. if (dist > mMaxDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0))
  734. {
  735. mProbeInfo->mScore = mMaxDrawDistance;
  736. return;
  737. }
  738. if (mReflectionModeType == DynamicCubemap && mRefreshRateMS < (Platform::getRealMilliseconds() - mDynamicLastBakeMS))
  739. {
  740. //bake();
  741. mDynamicLastBakeMS = Platform::getRealMilliseconds();
  742. processDynamicCubemap();
  743. }
  744. //Submit our probe to actually do the probe action
  745. // Get a handy pointer to our RenderPassmanager
  746. //RenderPassManager *renderPass = state->getRenderPass();
  747. //Update our score based on our radius, distance
  748. mProbeInfo->mScore = mProbeInfo->mRadius/mMax(dist,1.0f);
  749. Point3F vect = distVec;
  750. vect.normalizeSafe();
  751. mProbeInfo->mScore *= mMax(mAbs(mDot(vect, state->getCameraTransform().getForwardVector())),0.001f);
  752. //Register
  753. //PROBEMGR->registerProbe(mProbeInfoIdx);
  754. if (ReflectionProbe::smRenderPreviewProbes && gEditingMission && mPrefilterMap != nullptr)
  755. {
  756. if(!mEditorShapeInst)
  757. createGeometry();
  758. GFXTransformSaver saver;
  759. // Calculate the distance of this object from the camera
  760. Point3F cameraOffset;
  761. getRenderTransform().getColumn(3, &cameraOffset);
  762. cameraOffset -= state->getDiffuseCameraPosition();
  763. dist = cameraOffset.len();
  764. if (dist < 0.01f)
  765. dist = 0.01f;
  766. // Set up the LOD for the shape
  767. F32 invScale = (1.0f / getMax(getMax(mObjScale.x, mObjScale.y), mObjScale.z));
  768. mEditorShapeInst->setDetailFromDistance(state, dist * invScale);
  769. // Make sure we have a valid level of detail
  770. if (mEditorShapeInst->getCurrentDetail() < 0)
  771. return;
  772. BaseMatInstance* probePrevMat = mEditorShapeInst->getMaterialList()->getMaterialInst(0);
  773. setPreviewMatParameters(state, probePrevMat);
  774. // GFXTransformSaver is a handy helper class that restores
  775. // the current GFX matrices to their original values when
  776. // it goes out of scope at the end of the function
  777. // Set up our TS render state
  778. TSRenderState rdata;
  779. rdata.setSceneState(state);
  780. rdata.setFadeOverride(1.0f);
  781. if(mReflectionModeType != DynamicCubemap)
  782. rdata.setCubemap(mPrefilterMap->mCubemap);
  783. else
  784. rdata.setCubemap(mDynamicCubemap);
  785. // We might have some forward lit materials
  786. // so pass down a query to gather lights.
  787. LightQuery query;
  788. query.init(getWorldSphere());
  789. rdata.setLightQuery(&query);
  790. // Set the world matrix to the objects render transform
  791. MatrixF mat = getRenderTransform();
  792. GFX->setWorldMatrix(mat);
  793. // Animate the the shape
  794. mEditorShapeInst->animate();
  795. // Allow the shape to submit the RenderInst(s) for itself
  796. mEditorShapeInst->render(rdata);
  797. saver.restore();
  798. }
  799. // If the light is selected or light visualization
  800. // is enabled then register the callback.
  801. const bool isSelectedInEditor = (gEditingMission && isSelected());
  802. if (isSelectedInEditor)
  803. {
  804. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  805. ri->renderDelegate.bind(this, &ReflectionProbe::_onRenderViz);
  806. ri->type = RenderPassManager::RIT_Editor;
  807. state->getRenderPass()->addInst(ri);
  808. }
  809. }
  810. void ReflectionProbe::_onRenderViz(ObjectRenderInst *ri,
  811. SceneRenderState *state,
  812. BaseMatInstance *overrideMat)
  813. {
  814. if (!RenderProbeMgr::smRenderReflectionProbes)
  815. return;
  816. GFXDrawUtil *draw = GFX->getDrawUtil();
  817. GFXStateBlockDesc desc;
  818. desc.setZReadWrite(true, false);
  819. desc.setCullMode(GFXCullNone);
  820. desc.setBlend(true);
  821. //desc.fillMode = GFXFillWireframe;
  822. // Base the sphere color on the light color.
  823. ColorI color = ColorI(255, 0, 255, 63);
  824. const MatrixF worldToObjectXfm = mObjToWorld;
  825. if (mProbeShapeType == ProbeRenderInst::Sphere)
  826. {
  827. draw->drawSphere(desc, mRadius, getPosition(), color);
  828. }
  829. else
  830. {
  831. Point3F tscl = worldToObjectXfm.getScale();
  832. Box3F projCube(-mObjScale/2, mObjScale / 2);
  833. projCube.setCenter(getPosition());
  834. draw->drawCube(desc, projCube, color, &worldToObjectXfm);
  835. }
  836. Point3F renderPos = getRenderTransform().getPosition();
  837. Box3F refCube = Box3F(-mProbeRefScale / 2, mProbeRefScale / 2);
  838. refCube.setCenter(renderPos + mProbeRefOffset);
  839. color = ColorI(0, 255, 255, 63);
  840. draw->drawCube(desc, refCube, color, &worldToObjectXfm);
  841. }
  842. void ReflectionProbe::setPreviewMatParameters(SceneRenderState* renderState, BaseMatInstance* mat)
  843. {
  844. if (!mat->getFeatures().hasFeature(MFT_isDeferred))
  845. return;
  846. //Set up the params
  847. MaterialParameters *matParams = mat->getMaterialParameters();
  848. //Get the deferred render target
  849. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  850. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  851. if (!deferredTexObject)
  852. return;
  853. GFX->setTexture(0, deferredTexObject);
  854. //Set the cubemap
  855. GFX->setCubeTexture(1, mPrefilterMap->mCubemap);
  856. //Set the invViewMat
  857. MatrixSet &matrixSet = renderState->getRenderPass()->getMatrixSet();
  858. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  859. MaterialParameterHandle *invViewMat = mat->getMaterialParameterHandle("$invViewMat");
  860. matParams->setSafe(invViewMat, worldToCameraXfm);
  861. }
  862. DefineEngineMethod(ReflectionProbe, postApply, void, (), ,
  863. "A utility method for forcing a network update.\n")
  864. {
  865. object->inspectPostApply();
  866. }
  867. DefineEngineMethod(ReflectionProbe, Bake, void, (), ,
  868. "@brief returns true if control object is inside the fog\n\n.")
  869. {
  870. ReflectionProbe *clientProbe = (ReflectionProbe*)object->getClientObject();
  871. if (clientProbe)
  872. {
  873. clientProbe->bake();
  874. }
  875. }