reflectionProbe.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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 <string>
  39. #include "T3D/gameFunctions.h"
  40. #include "postFx/postEffect.h"
  41. #include "renderInstance/renderProbeMgr.h"
  42. #include "lighting/probeManager.h"
  43. #include "math/util/sphereMesh.h"
  44. #include "materials/materialManager.h"
  45. #include "math/util/matrixSet.h"
  46. #include "gfx/bitmap/cubemapSaver.h"
  47. #include "materials/materialFeatureTypes.h"
  48. #include "gfx/gfxTextureManager.h"
  49. #include "T3D/lighting/IBLUtilities.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(IndrectLightingModeEnum,
  71. "Type of mesh data available in a shape.\n"
  72. "@ingroup gameObjects")
  73. { ReflectionProbe::NoIndirect, "No Lighting", "This probe does not provide any local indirect lighting data" },
  74. { ReflectionProbe::AmbientColor, "Ambient Color", "Adds a flat color to act as the local indirect lighting" },
  75. { ReflectionProbe::SphericalHarmonics, "Spherical Harmonics", "Creates spherical harmonics data based off the reflection data" },
  76. EndImplementEnumType;
  77. ImplementEnumType(ReflectionModeEnum,
  78. "Type of mesh data available in a shape.\n"
  79. "@ingroup gameObjects")
  80. { ReflectionProbe::NoReflection, "No Reflections", "This probe does not provide any local reflection data"},
  81. { ReflectionProbe::StaticCubemap, "Static Cubemap", "Uses a static CubemapData" },
  82. { ReflectionProbe::BakedCubemap, "Baked Cubemap", "Uses a cubemap baked from the probe's current position" },
  83. //{ ReflectionProbe::DynamicCubemap, "Dynamic Cubemap", "Uses a cubemap baked from the probe's current position, updated at a set rate" },
  84. EndImplementEnumType;
  85. //-----------------------------------------------------------------------------
  86. // Object setup and teardown
  87. //-----------------------------------------------------------------------------
  88. ReflectionProbe::ReflectionProbe()
  89. {
  90. // Flag this object so that it will always
  91. // be sent across the network to clients
  92. mNetFlags.set(Ghostable | ScopeAlways);
  93. mTypeMask = LightObjectType | MarkerObjectType;
  94. mProbeShapeType = ProbeRenderInst::Box;
  95. mIndrectLightingModeType = NoIndirect;
  96. mReflectionModeType = BakedCubemap;
  97. mEnabled = true;
  98. mBake = false;
  99. mDirty = false;
  100. mRadius = 10;
  101. mUseCubemap = false;
  102. mUseHDRCaptures = false;
  103. mStaticCubemap = NULL;
  104. mReflectionPath = "";
  105. mProbeUniqueID = "";
  106. mEditorShapeInst = NULL;
  107. mEditorShape = NULL;
  108. mRefreshRateMS = 200;
  109. mDynamicLastBakeMS = 0;
  110. mMaxDrawDistance = 75;
  111. mResourcesCreated = false;
  112. mProbeInfo = nullptr;
  113. mPrefilterSize = 64;
  114. mPrefilterMipLevels = mLog2(F32(mPrefilterSize));
  115. mPrefilterMap = nullptr;
  116. mIrridianceMap = nullptr;
  117. mProbePosOffset = Point3F::Zero;
  118. mEditPosOffset = false;
  119. mProbeInfoIdx = -1;
  120. mCaptureMask = REFLECTION_PROBE_CAPTURE_TYPEMASK;
  121. }
  122. ReflectionProbe::~ReflectionProbe()
  123. {
  124. if (mEditorShapeInst)
  125. SAFE_DELETE(mEditorShapeInst);
  126. if (mProbeInfo)
  127. SAFE_DELETE(mProbeInfo);
  128. if (mReflectionModeType != StaticCubemap && mStaticCubemap)
  129. mStaticCubemap->deleteObject();
  130. }
  131. //-----------------------------------------------------------------------------
  132. // Object Editing
  133. //-----------------------------------------------------------------------------
  134. void ReflectionProbe::initPersistFields()
  135. {
  136. addGroup("Rendering");
  137. addProtectedField("enabled", TypeBool, Offset(mEnabled, ReflectionProbe),
  138. &_setEnabled, &defaultProtectedGetFn, "Regenerate Voxel Grid");
  139. addField("ProbeShape", TypeReflectProbeType, Offset(mProbeShapeType, ReflectionProbe),
  140. "The type of mesh data to use for collision queries.");
  141. addField("radius", TypeF32, Offset(mRadius, ReflectionProbe), "The name of the material used to render the mesh.");
  142. addField("posOffset", TypePoint3F, Offset(mProbePosOffset, ReflectionProbe), "");
  143. //addProtectedField("EditPosOffset", TypeBool, Offset(mEditPosOffset, ReflectionProbe),
  144. // &_toggleEditPosOffset, &defaultProtectedGetFn, "Toggle Edit Pos Offset Mode", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  145. endGroup("Rendering");
  146. addGroup("Reflection");
  147. addField("ReflectionMode", TypeReflectionModeEnum, Offset(mReflectionModeType, ReflectionProbe),
  148. "The type of mesh data to use for collision queries.");
  149. addField("reflectionPath", TypeImageFilename, Offset(mReflectionPath, ReflectionProbe),
  150. "The type of mesh data to use for collision queries.");
  151. addField("StaticCubemap", TypeCubemapName, Offset(mCubemapName, ReflectionProbe), "Cubemap used instead of reflection texture if fullReflect is off.");
  152. addProtectedField("Bake", TypeBool, Offset(mBake, ReflectionProbe),
  153. &_doBake, &defaultProtectedGetFn, "Regenerate Voxel Grid", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  154. endGroup("Reflection");
  155. Con::addVariable("$Light::renderReflectionProbes", TypeBool, &ProbeManager::smRenderReflectionProbes,
  156. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  157. "@note Only works for shadow mapped lights.\n\n"
  158. "@ingroup Lighting");
  159. Con::addVariable("$Light::renderPreviewProbes", TypeBool, &ReflectionProbe::smRenderPreviewProbes,
  160. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  161. "@note Only works for shadow mapped lights.\n\n"
  162. "@ingroup Lighting");
  163. // SceneObject already handles exposing the transform
  164. Parent::initPersistFields();
  165. }
  166. void ReflectionProbe::inspectPostApply()
  167. {
  168. Parent::inspectPostApply();
  169. mDirty = true;
  170. // Flag the network mask to send the updates
  171. // to the client object
  172. setMaskBits(-1);
  173. }
  174. bool ReflectionProbe::_setEnabled(void *object, const char *index, const char *data)
  175. {
  176. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  177. probe->mEnabled = dAtob(data);
  178. probe->setMaskBits(-1);
  179. return true;
  180. }
  181. bool ReflectionProbe::_doBake(void *object, const char *index, const char *data)
  182. {
  183. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  184. //if (probe->mDirty)
  185. // probe->bake(probe->mReflectionPath, 256);
  186. ReflectionProbe *clientProbe = (ReflectionProbe*)probe->getClientObject();
  187. if (clientProbe)
  188. {
  189. clientProbe->bake(clientProbe->mReflectionPath, 64);
  190. }
  191. return false;
  192. }
  193. bool ReflectionProbe::_toggleEditPosOffset(void *object, const char *index, const char *data)
  194. {
  195. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  196. probe->mEditPosOffset = !probe->mEditPosOffset;
  197. //if (probe->mDirty)
  198. // probe->bake(probe->mReflectionPath, 256);
  199. return false;
  200. }
  201. bool ReflectionProbe::onAdd()
  202. {
  203. if (!Parent::onAdd())
  204. return false;
  205. mEditPosOffset = false;
  206. mObjBox.minExtents.set(-1, -1, -1);
  207. mObjBox.maxExtents.set(1, 1, 1);
  208. //mObjScale.set(mRadius/2, mRadius/2, mRadius/2);
  209. // Skip our transform... it just dirties mask bits.
  210. Parent::setTransform(mObjToWorld);
  211. resetWorldBox();
  212. // Add this object to the scene
  213. addToScene();
  214. if (isServerObject())
  215. {
  216. if (!mPersistentId)
  217. mPersistentId = getOrCreatePersistentId();
  218. mProbeUniqueID = std::to_string(mPersistentId->getUUID().getHash()).c_str();
  219. }
  220. // Refresh this object's material (if any)
  221. if (isClientObject())
  222. {
  223. createGeometry();
  224. updateProbeParams();
  225. }
  226. setMaskBits(-1);
  227. return true;
  228. }
  229. void ReflectionProbe::onRemove()
  230. {
  231. // Remove this object from the scene
  232. removeFromScene();
  233. Parent::onRemove();
  234. }
  235. void ReflectionProbe::setTransform(const MatrixF & mat)
  236. {
  237. // Let SceneObject handle all of the matrix manipulation
  238. if (!mEditPosOffset)
  239. Parent::setTransform(mat);
  240. else
  241. mProbePosOffset = mat.getPosition();
  242. mDirty = true;
  243. // Dirty our network mask so that the new transform gets
  244. // transmitted to the client object
  245. setMaskBits(TransformMask);
  246. }
  247. U32 ReflectionProbe::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  248. {
  249. // Allow the Parent to get a crack at writing its info
  250. U32 retMask = Parent::packUpdate(conn, mask, stream);
  251. // Write our transform information
  252. if (stream->writeFlag(mask & TransformMask))
  253. {
  254. mathWrite(*stream, getTransform());
  255. mathWrite(*stream, getScale());
  256. mathWrite(*stream, mProbePosOffset);
  257. }
  258. if (stream->writeFlag(mask & ShapeTypeMask))
  259. {
  260. stream->write((U32)mProbeShapeType);
  261. }
  262. if (stream->writeFlag(mask & UpdateMask))
  263. {
  264. stream->write(mRadius);
  265. }
  266. if (stream->writeFlag(mask & BakeInfoMask))
  267. {
  268. stream->write(mReflectionPath);
  269. stream->write(mProbeUniqueID);
  270. }
  271. if (stream->writeFlag(mask & EnabledMask))
  272. {
  273. stream->writeFlag(mEnabled);
  274. }
  275. if (stream->writeFlag(mask & ModeMask))
  276. {
  277. stream->write((U32)mIndrectLightingModeType);
  278. stream->write((U32)mReflectionModeType);
  279. }
  280. if (stream->writeFlag(mask & CubemapMask))
  281. {
  282. stream->writeFlag(mUseCubemap);
  283. stream->write(mCubemapName);
  284. }
  285. return retMask;
  286. }
  287. void ReflectionProbe::unpackUpdate(NetConnection *conn, BitStream *stream)
  288. {
  289. // Let the Parent read any info it sent
  290. Parent::unpackUpdate(conn, stream);
  291. if (stream->readFlag()) // TransformMask
  292. {
  293. mathRead(*stream, &mObjToWorld);
  294. mathRead(*stream, &mObjScale);
  295. setTransform(mObjToWorld);
  296. mathRead(*stream, &mProbePosOffset);
  297. }
  298. if (stream->readFlag()) // ShapeTypeMask
  299. {
  300. U32 shapeType = ProbeRenderInst::Sphere;
  301. stream->read(&shapeType);
  302. mProbeShapeType = (ProbeRenderInst::ProbeShapeType)shapeType;
  303. createGeometry();
  304. }
  305. if (stream->readFlag()) // UpdateMask
  306. {
  307. stream->read(&mRadius);
  308. }
  309. if (stream->readFlag()) // BakeInfoMask
  310. {
  311. stream->read(&mReflectionPath);
  312. stream->read(&mProbeUniqueID);
  313. }
  314. if (stream->readFlag()) // EnabledMask
  315. {
  316. mEnabled = stream->readFlag();
  317. }
  318. bool isMaterialDirty = false;
  319. if (stream->readFlag()) // ModeMask
  320. {
  321. U32 indirectModeType = AmbientColor;
  322. stream->read(&indirectModeType);
  323. mIndrectLightingModeType = (IndrectLightingModeType)indirectModeType;
  324. U32 reflectModeType = BakedCubemap;
  325. stream->read(&reflectModeType);
  326. mReflectionModeType = (ReflectionModeType)reflectModeType;
  327. isMaterialDirty = true;
  328. }
  329. if (stream->readFlag()) // CubemapMask
  330. {
  331. mUseCubemap = stream->readFlag();
  332. stream->read(&mCubemapName);
  333. isMaterialDirty = true;
  334. }
  335. updateProbeParams();
  336. if (isMaterialDirty)
  337. {
  338. updateMaterial();
  339. }
  340. }
  341. void ReflectionProbe::createGeometry()
  342. {
  343. // Clean up our previous shape
  344. if (mEditorShapeInst)
  345. SAFE_DELETE(mEditorShapeInst);
  346. mEditorShape = NULL;
  347. String shapeFile = "tools/resources/ReflectProbeSphere.dae";
  348. // Attempt to get the resource from the ResourceManager
  349. mEditorShape = ResourceManager::get().load(shapeFile);
  350. if (mEditorShape)
  351. {
  352. mEditorShapeInst = new TSShapeInstance(mEditorShape, isClientObject());
  353. }
  354. }
  355. //-----------------------------------------------------------------------------
  356. // Object Rendering
  357. //-----------------------------------------------------------------------------
  358. void ReflectionProbe::updateProbeParams()
  359. {
  360. if (mProbeInfo == nullptr)
  361. {
  362. mProbeInfo = new ProbeRenderInst();
  363. mProbeInfoIdx = ProbeRenderInst::all.size() - 1;
  364. mProbeInfo->mIsEnabled = false;
  365. }
  366. updateMaterial();
  367. mProbeInfo->mAmbient = LinearColorF(0, 0, 0, 0);
  368. mProbeInfo->mProbeShapeType = mProbeShapeType;
  369. mProbeInfo->mTransform = getWorldTransform();
  370. mProbeInfo->mTransform.inverse();
  371. mProbeInfo->setPosition(getPosition());
  372. //Point3F pos = mProbeInfo->mTransform.getPosition();
  373. //Update the bounds
  374. //mObjBox.minExtents.set(-1, -1, -1);
  375. //mObjBox.maxExtents.set(1, 1, 1);
  376. mObjScale.set(mRadius, mRadius, mRadius);
  377. // Skip our transform... it just dirties mask bits.
  378. Parent::setTransform(mObjToWorld);
  379. resetWorldBox();
  380. mProbeInfo->mBounds = mWorldBox;
  381. mProbeInfo->mRadius = mRadius;
  382. mProbeInfo->mIsSkylight = false;
  383. mProbeInfo->mProbePosOffset = mProbePosOffset;
  384. mProbeInfo->mDirty = true;
  385. mProbeInfo->mScore = mMaxDrawDistance;
  386. }
  387. void ReflectionProbe::updateMaterial()
  388. {
  389. createClientResources();
  390. if (mReflectionModeType != DynamicCubemap)
  391. {
  392. if ((mReflectionModeType == BakedCubemap) && !mProbeUniqueID.isEmpty())
  393. {
  394. if (mPrefilterMap != nullptr && mPrefilterMap->mCubemap.isValid())
  395. {
  396. mProbeInfo->mCubemap = &mPrefilterMap->mCubemap;
  397. }
  398. if (mIrridianceMap != nullptr && mIrridianceMap->mCubemap.isValid())
  399. {
  400. mProbeInfo->mIrradianceCubemap = &mIrridianceMap->mCubemap;
  401. }
  402. if (mBrdfTexture.isValid())
  403. {
  404. mProbeInfo->mBRDFTexture = &mBrdfTexture;
  405. }
  406. }
  407. else if (mReflectionModeType == StaticCubemap && !mCubemapName.isEmpty())
  408. {
  409. Sim::findObject(mCubemapName, mStaticCubemap);
  410. if (!mStaticCubemap)
  411. {
  412. Con::errorf("ReflectionProbe::updateMaterial() - unable to find static cubemap file!");
  413. return;
  414. }
  415. if (mStaticCubemap->mCubemap == nullptr)
  416. {
  417. mStaticCubemap->createMap();
  418. mStaticCubemap->updateFaces();
  419. }
  420. //GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  421. //IBLUtilities::GenerateIrradianceMap(renderTarget, mStaticCubemap->mCubemap, mIrridianceMap->mCubemap);
  422. //IBLUtilities::GeneratePrefilterMap(renderTarget, mStaticCubemap->mCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  423. mProbeInfo->mCubemap = &mStaticCubemap->mCubemap;
  424. mProbeInfo->mIrradianceCubemap = &mStaticCubemap->mCubemap;
  425. /*if (mPrefilterMap != nullptr && mPrefilterMap->mCubemap.isValid())
  426. {
  427. mProbeInfo->mCubemap = &mPrefilterMap->mCubemap;
  428. }
  429. if (mIrridianceMap != nullptr && mIrridianceMap->mCubemap.isValid())
  430. {
  431. mProbeInfo->mIrradianceCubemap = &mIrridianceMap->mCubemap;
  432. }*/
  433. if (mBrdfTexture.isValid())
  434. {
  435. mProbeInfo->mBRDFTexture = &mBrdfTexture;
  436. }
  437. }
  438. }
  439. else if (mReflectionModeType == DynamicCubemap && !mDynamicCubemap.isNull())
  440. {
  441. mProbeInfo->mCubemap = &mDynamicCubemap;
  442. }
  443. //Make us ready to render
  444. if (mEnabled)
  445. mProbeInfo->mIsEnabled = true;
  446. else
  447. mProbeInfo->mIsEnabled = false;
  448. }
  449. bool ReflectionProbe::createClientResources()
  450. {
  451. //irridiance resources
  452. if (!mIrridianceMap)
  453. {
  454. mIrridianceMap = new CubemapData();
  455. mIrridianceMap->registerObject();
  456. mIrridianceMap->createMap();
  457. }
  458. if (!mUseHDRCaptures)
  459. {
  460. String irrPath = getIrradianceMapPath();
  461. if (Platform::isFile(irrPath))
  462. {
  463. mIrridianceMap->setCubemapFile(FileName(irrPath));
  464. mIrridianceMap->updateFaces();
  465. }
  466. if (mIrridianceMap->mCubemap.isNull())
  467. Con::errorf("ReflectionProbe::createClientResources() - Unable to load baked irradiance map at %s", getIrradianceMapPath().c_str());
  468. }
  469. //
  470. if (!mPrefilterMap)
  471. {
  472. mPrefilterMap = new CubemapData();
  473. mPrefilterMap->registerObject();
  474. mPrefilterMap->createMap();
  475. }
  476. if (!mUseHDRCaptures)
  477. {
  478. String prefilPath = getPrefilterMapPath();
  479. if (Platform::isFile(prefilPath))
  480. {
  481. mPrefilterMap->setCubemapFile(FileName(prefilPath));
  482. mPrefilterMap->updateFaces();
  483. }
  484. if (mPrefilterMap->mCubemap.isNull())
  485. Con::errorf("ReflectionProbe::createClientResources() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str());
  486. }
  487. //brdf lookup resources
  488. //make the brdf lookup texture the same size as the prefilter texture
  489. String brdfPath = Con::getVariable("$Core::BRDFTexture", "core/art/pbr/brdfTexture.dds");
  490. mBrdfTexture = TEXMGR->createTexture(brdfPath, &GFXTexturePersistentProfile);
  491. if (!mBrdfTexture)
  492. {
  493. mBrdfTexture = IBLUtilities::GenerateAndSaveBRDFTexture(brdfPath, 512);
  494. }
  495. mResourcesCreated = true;
  496. return true;
  497. }
  498. void ReflectionProbe::generateTextures()
  499. {
  500. }
  501. void ReflectionProbe::prepRenderImage(SceneRenderState *state)
  502. {
  503. if (!mEnabled || !ProbeManager::smRenderReflectionProbes)
  504. return;
  505. Point3F distVec = getRenderPosition() - state->getCameraPosition();
  506. F32 dist = distVec.len();
  507. //Culling distance. Can be adjusted for performance options considerations via the scalar
  508. if (dist > mMaxDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0))
  509. {
  510. mProbeInfo->mScore = mMaxDrawDistance;
  511. return;
  512. }
  513. if (mReflectionModeType == DynamicCubemap && mRefreshRateMS < (Platform::getRealMilliseconds() - mDynamicLastBakeMS))
  514. {
  515. bake("", 32);
  516. mDynamicLastBakeMS = Platform::getRealMilliseconds();
  517. }
  518. //Submit our probe to actually do the probe action
  519. // Get a handy pointer to our RenderPassmanager
  520. //RenderPassManager *renderPass = state->getRenderPass();
  521. //Update our score based on our radius, distance
  522. mProbeInfo->mScore = mProbeInfo->mRadius/mMax(dist,1.0f);
  523. Point3F vect = distVec;
  524. vect.normalizeSafe();
  525. mProbeInfo->mScore *= mMax(mAbs(mDot(vect, state->getCameraTransform().getForwardVector())),0.001f);
  526. //Register
  527. PROBEMGR->registerProbe(mProbeInfoIdx);
  528. if (ReflectionProbe::smRenderPreviewProbes && gEditingMission && mEditorShapeInst && mPrefilterMap != nullptr)
  529. {
  530. GFXTransformSaver saver;
  531. // Calculate the distance of this object from the camera
  532. Point3F cameraOffset;
  533. getRenderTransform().getColumn(3, &cameraOffset);
  534. cameraOffset -= state->getDiffuseCameraPosition();
  535. F32 dist = cameraOffset.len();
  536. if (dist < 0.01f)
  537. dist = 0.01f;
  538. // Set up the LOD for the shape
  539. F32 invScale = (1.0f / getMax(getMax(mObjScale.x, mObjScale.y), mObjScale.z));
  540. mEditorShapeInst->setDetailFromDistance(state, dist * invScale);
  541. // Make sure we have a valid level of detail
  542. if (mEditorShapeInst->getCurrentDetail() < 0)
  543. return;
  544. BaseMatInstance* probePrevMat = mEditorShapeInst->getMaterialList()->getMaterialInst(0);
  545. setPreviewMatParameters(state, probePrevMat);
  546. // GFXTransformSaver is a handy helper class that restores
  547. // the current GFX matrices to their original values when
  548. // it goes out of scope at the end of the function
  549. // Set up our TS render state
  550. TSRenderState rdata;
  551. rdata.setSceneState(state);
  552. rdata.setFadeOverride(1.0f);
  553. if(mReflectionModeType != DynamicCubemap)
  554. rdata.setCubemap(mPrefilterMap->mCubemap);
  555. else
  556. rdata.setCubemap(mDynamicCubemap);
  557. // We might have some forward lit materials
  558. // so pass down a query to gather lights.
  559. LightQuery query;
  560. query.init(getWorldSphere());
  561. rdata.setLightQuery(&query);
  562. // Set the world matrix to the objects render transform
  563. MatrixF mat = getRenderTransform();
  564. mat.scale(Point3F(1, 1, 1));
  565. Point3F centerPos = mat.getPosition();
  566. centerPos += mProbePosOffset;
  567. mat.setPosition(centerPos);
  568. GFX->setWorldMatrix(mat);
  569. // Animate the the shape
  570. mEditorShapeInst->animate();
  571. // Allow the shape to submit the RenderInst(s) for itself
  572. mEditorShapeInst->render(rdata);
  573. saver.restore();
  574. }
  575. // If the light is selected or light visualization
  576. // is enabled then register the callback.
  577. const bool isSelectedInEditor = (gEditingMission && isSelected());
  578. if (isSelectedInEditor)
  579. {
  580. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  581. ri->renderDelegate.bind(this, &ReflectionProbe::_onRenderViz);
  582. ri->type = RenderPassManager::RIT_Editor;
  583. state->getRenderPass()->addInst(ri);
  584. }
  585. }
  586. void ReflectionProbe::_onRenderViz(ObjectRenderInst *ri,
  587. SceneRenderState *state,
  588. BaseMatInstance *overrideMat)
  589. {
  590. if (!ProbeManager::smRenderReflectionProbes)
  591. return;
  592. GFXDrawUtil *draw = GFX->getDrawUtil();
  593. GFXStateBlockDesc desc;
  594. desc.setZReadWrite(true, false);
  595. desc.setCullMode(GFXCullNone);
  596. desc.setBlend(true);
  597. // Base the sphere color on the light color.
  598. ColorI color = ColorI::WHITE;
  599. color.alpha = 25;
  600. if (mProbeShapeType == ProbeRenderInst::Sphere)
  601. {
  602. draw->drawSphere(desc, mRadius, getPosition(), color);
  603. }
  604. else
  605. {
  606. const MatrixF worldToObjectXfm = getTransform();
  607. Box3F cube(-Point3F(mRadius, mRadius, mRadius),Point3F(mRadius, mRadius, mRadius));
  608. Box3F wb = getWorldBox();
  609. cube.setCenter(getPosition()+mProbePosOffset);
  610. wb.setCenter(getPosition() + mProbePosOffset);
  611. draw->drawCube(desc, cube, color, &worldToObjectXfm);
  612. draw->drawCube(desc, wb, color, &worldToObjectXfm);
  613. }
  614. }
  615. void ReflectionProbe::setPreviewMatParameters(SceneRenderState* renderState, BaseMatInstance* mat)
  616. {
  617. if (!mat->getFeatures().hasFeature(MFT_isDeferred))
  618. return;
  619. //Set up the params
  620. MaterialParameters *matParams = mat->getMaterialParameters();
  621. //Get the deferred render target
  622. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  623. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  624. if (!deferredTexObject)
  625. return;
  626. GFX->setTexture(0, deferredTexObject);
  627. //Set the cubemap
  628. GFX->setCubeTexture(1, mPrefilterMap->mCubemap);
  629. //Set the invViewMat
  630. MatrixSet &matrixSet = renderState->getRenderPass()->getMatrixSet();
  631. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  632. MaterialParameterHandle *invViewMat = mat->getMaterialParameterHandle("$invViewMat");
  633. matParams->setSafe(invViewMat, worldToCameraXfm);
  634. }
  635. DefineEngineMethod(ReflectionProbe, postApply, void, (), ,
  636. "A utility method for forcing a network update.\n")
  637. {
  638. object->inspectPostApply();
  639. }
  640. String ReflectionProbe::getPrefilterMapPath()
  641. {
  642. if (mReflectionPath.isEmpty() || mProbeUniqueID.isEmpty())
  643. {
  644. Con::errorf("ReflectionProbe::getPrefilterMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  645. return "";
  646. }
  647. char fileName[256];
  648. dSprintf(fileName, 256, "%s%s_Prefilter.DDS", mReflectionPath.c_str(), mProbeUniqueID.c_str());
  649. return fileName;
  650. }
  651. String ReflectionProbe::getIrradianceMapPath()
  652. {
  653. if (mReflectionPath.isEmpty() || mProbeUniqueID.isEmpty())
  654. {
  655. Con::errorf("ReflectionProbe::getIrradianceMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  656. return "";
  657. }
  658. char fileName[256];
  659. dSprintf(fileName, 256, "%s%s_Irradiance.DDS", mReflectionPath.c_str(), mProbeUniqueID.c_str());
  660. return fileName;
  661. }
  662. void ReflectionProbe::bake(String outputPath, S32 resolution, bool renderWithProbes)
  663. {
  664. GFXDEBUGEVENT_SCOPE(ReflectionProbe_Bake, ColorI::WHITE);
  665. Con::warnf("ReflectionProbe::bake() - Beginning bake!");
  666. U32 startMSTime = Platform::getRealMilliseconds();
  667. /*PostEffect *preCapture = dynamic_cast<PostEffect*>(Sim::findObject("AL_PreCapture"));
  668. PostEffect *deferredShading = dynamic_cast<PostEffect*>(Sim::findObject("AL_DeferredShading"));
  669. if (preCapture)
  670. {
  671. preCapture->setShaderConst("$radius",String::ToString(mRadius));
  672. preCapture->setShaderConst("$captureRez", String::ToString(F32(resolution)));
  673. preCapture->enable();
  674. }
  675. if (deferredShading)
  676. deferredShading->disable();*/
  677. GFXCubemapHandle sceneCaptureCubemap;
  678. if (mReflectionModeType == DynamicCubemap && mDynamicCubemap.isNull())
  679. {
  680. //mCubemap->createMap();
  681. mDynamicCubemap = GFX->createCubemap();
  682. if(mUseHDRCaptures)
  683. mDynamicCubemap->initDynamic(resolution, GFXFormatR16G16B16A16);
  684. else
  685. mDynamicCubemap->initDynamic(resolution, GFXFormatB8G8R8A8);
  686. sceneCaptureCubemap = mDynamicCubemap;
  687. }
  688. else if (mReflectionModeType != DynamicCubemap)
  689. {
  690. //Prep our bake path
  691. if (mReflectionPath.isEmpty())
  692. {
  693. Con::errorf("ReflectionProbe::bake() - Unable to bake our captures because probe doesn't have a path set");
  694. return;
  695. }
  696. if (mProbeUniqueID.isEmpty())
  697. {
  698. Con::errorf("ReflectionProbe::bake() - Unable to bake our captures because probe doesn't have a unique ID set");
  699. return;
  700. }
  701. sceneCaptureCubemap = GFX->createCubemap();
  702. if (mUseHDRCaptures)
  703. sceneCaptureCubemap->initDynamic(resolution, GFXFormatR16G16B16A16F);
  704. else
  705. sceneCaptureCubemap->initDynamic(resolution, GFXFormatR8G8B8A8);
  706. }
  707. bool validCubemap = true;
  708. // Save the current transforms so we can restore
  709. // it for child control rendering below.
  710. GFXTransformSaver saver;
  711. //bool saveEditingMission = gEditingMission;
  712. //gEditingMission = false;
  713. //Set this to true to use the prior method where it goes through the SPT_Reflect path for the bake
  714. bool probeRenderState = ProbeManager::smRenderReflectionProbes;
  715. if (!renderWithProbes)
  716. ProbeManager::smRenderReflectionProbes = false;
  717. for (U32 i = 0; i < 6; ++i)
  718. {
  719. GFXTexHandle blendTex;
  720. blendTex.set(resolution, resolution, GFXFormatR16G16B16A16, &GFXRenderTargetProfile, "");
  721. GFXTextureTargetRef baseTarget = GFX->allocRenderToTextureTarget();
  722. GFX->clearTextureStateImmediate(0);
  723. baseTarget->attachTexture(GFXTextureTarget::Color0, sceneCaptureCubemap, i);
  724. // Standard view that will be overridden below.
  725. VectorF vLookatPt(0.0f, 0.0f, 0.0f), vUpVec(0.0f, 0.0f, 0.0f), vRight(0.0f, 0.0f, 0.0f);
  726. switch (i)
  727. {
  728. case 0: // D3DCUBEMAP_FACE_POSITIVE_X:
  729. vLookatPt = VectorF(1.0f, 0.0f, 0.0f);
  730. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  731. break;
  732. case 1: // D3DCUBEMAP_FACE_NEGATIVE_X:
  733. vLookatPt = VectorF(-1.0f, 0.0f, 0.0f);
  734. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  735. break;
  736. case 2: // D3DCUBEMAP_FACE_POSITIVE_Y:
  737. vLookatPt = VectorF(0.0f, 1.0f, 0.0f);
  738. vUpVec = VectorF(0.0f, 0.0f, -1.0f);
  739. break;
  740. case 3: // D3DCUBEMAP_FACE_NEGATIVE_Y:
  741. vLookatPt = VectorF(0.0f, -1.0f, 0.0f);
  742. vUpVec = VectorF(0.0f, 0.0f, 1.0f);
  743. break;
  744. case 4: // D3DCUBEMAP_FACE_POSITIVE_Z:
  745. vLookatPt = VectorF(0.0f, 0.0f, 1.0f);
  746. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  747. break;
  748. case 5: // D3DCUBEMAP_FACE_NEGATIVE_Z:
  749. vLookatPt = VectorF(0.0f, 0.0f, -1.0f);
  750. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  751. break;
  752. }
  753. // create camera matrix
  754. VectorF cross = mCross(vUpVec, vLookatPt);
  755. cross.normalizeSafe();
  756. MatrixF matView(true);
  757. matView.setColumn(0, cross);
  758. matView.setColumn(1, vLookatPt);
  759. matView.setColumn(2, vUpVec);
  760. matView.setPosition(getPosition()+mProbePosOffset);
  761. matView.inverse();
  762. // set projection to 90 degrees vertical and horizontal
  763. F32 left, right, top, bottom;
  764. F32 nearPlane = 0.01f;
  765. F32 farDist = 1000.f;
  766. MathUtils::makeFrustum(&left, &right, &top, &bottom, M_HALFPI_F, 1.0f, nearPlane);
  767. Frustum frustum(false, left, right, top, bottom, nearPlane, farDist);
  768. renderFrame(&baseTarget, matView, frustum, mCaptureMask & EDITOR_RENDER_TYPEMASK, gCanvasClearColor);
  769. baseTarget->resolve();
  770. }
  771. if (sceneCaptureCubemap.isValid())
  772. {
  773. validCubemap = true;
  774. mDirty = false;
  775. }
  776. else
  777. {
  778. validCubemap = false;
  779. }
  780. //Now, save out the maps
  781. //create irridiance cubemap
  782. if (validCubemap)
  783. {
  784. bool se = isServerObject();
  785. //Just to ensure we're prepped for the generation
  786. createClientResources();
  787. //Prep it with whatever resolution we've dictated for our bake
  788. if (mUseHDRCaptures)
  789. {
  790. mIrridianceMap->mCubemap->initDynamic(resolution, GFXFormatR16G16B16A16);
  791. mPrefilterMap->mCubemap->initDynamic(resolution, GFXFormatR16G16B16A16);
  792. }
  793. else
  794. {
  795. mIrridianceMap->mCubemap->initDynamic(resolution, GFXFormatR8G8B8A8);
  796. mPrefilterMap->mCubemap->initDynamic(resolution, GFXFormatR8G8B8A8);
  797. }
  798. //IBLUtilities::GenerateAndSaveIrradianceMap(getIrradianceMapPath(), resolution, sceneCaptureCubemap, mIrridianceMap->mCubemap);
  799. //IBLUtilities::GenerateAndSavePrefilterMap(getPrefilterMapPath(), resolution, sceneCaptureCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  800. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  801. IBLUtilities::GenerateIrradianceMap(renderTarget, sceneCaptureCubemap, mIrridianceMap->mCubemap);
  802. IBLUtilities::GeneratePrefilterMap(renderTarget, sceneCaptureCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  803. //We can't save HDR captures at the moment
  804. if (!mUseHDRCaptures)
  805. {
  806. IBLUtilities::SaveCubeMap(getIrradianceMapPath(), mIrridianceMap->mCubemap);
  807. IBLUtilities::SaveCubeMap(getPrefilterMapPath(), mPrefilterMap->mCubemap);
  808. }
  809. }
  810. else
  811. {
  812. Con::errorf("ReflectionProbe::bake() - Didn't generate a valid scene capture cubemap, unable to generate prefilter and irradiance maps!");
  813. }
  814. if(!renderWithProbes)
  815. ProbeManager::smRenderReflectionProbes = probeRenderState;
  816. setMaskBits(-1);
  817. /*if (preCapture)
  818. preCapture->disable();
  819. if (deferredShading)
  820. deferredShading->enable();*/
  821. U32 endMSTime = Platform::getRealMilliseconds();
  822. F32 diffTime = F32(endMSTime - startMSTime);
  823. Con::warnf("ReflectionProbe::bake() - Finished bake! Took %g milliseconds", diffTime);
  824. }
  825. DefineEngineMethod(ReflectionProbe, Bake, void, (String outputPath, S32 resolution, bool renderWithProbes), ("", 64, false),
  826. "@brief returns true if control object is inside the fog\n\n.")
  827. {
  828. ReflectionProbe *clientProbe = (ReflectionProbe*)object->getClientObject();
  829. if (clientProbe)
  830. {
  831. clientProbe->bake(outputPath, resolution, renderWithProbes);
  832. }
  833. //object->bake(outputPath, resolution);
  834. }