reflectionProbe.cpp 32 KB

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