reflectionProbe.cpp 32 KB

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