reflectionProbe.cpp 32 KB

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