reflectionProbe.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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::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. String irrPath = getIrradianceMapPath();
  458. if (Platform::isFile(irrPath))
  459. {
  460. mIrridianceMap->setCubemapFile(FileName(irrPath));
  461. mIrridianceMap->updateFaces();
  462. }
  463. if (mIrridianceMap->mCubemap.isNull())
  464. Con::errorf("ReflectionProbe::createClientResources() - Unable to load baked irradiance map at %s", getIrradianceMapPath().c_str());
  465. //
  466. if (!mPrefilterMap)
  467. {
  468. mPrefilterMap = new CubemapData();
  469. mPrefilterMap->registerObject();
  470. mPrefilterMap->createMap();
  471. }
  472. String prefilPath = getPrefilterMapPath();
  473. if (Platform::isFile(prefilPath))
  474. {
  475. mPrefilterMap->setCubemapFile(FileName(prefilPath));
  476. mPrefilterMap->updateFaces();
  477. }
  478. if (mPrefilterMap->mCubemap.isNull())
  479. Con::errorf("ReflectionProbe::createClientResources() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str());
  480. //brdf lookup texture
  481. String brdfPath = Con::getVariable("$Core::BRDFTexture", "core/art/pbr/brdfTexture.dds");
  482. mBrdfTexture = TEXMGR->createTexture(brdfPath, &GFXTexturePersistentProfile);
  483. if (!mBrdfTexture)
  484. {
  485. return false;
  486. }
  487. mResourcesCreated = true;
  488. return true;
  489. }
  490. void ReflectionProbe::generateTextures()
  491. {
  492. }
  493. void ReflectionProbe::prepRenderImage(SceneRenderState *state)
  494. {
  495. if (!mEnabled || !ProbeManager::smRenderReflectionProbes)
  496. return;
  497. Point3F distVec = getRenderPosition() - state->getCameraPosition();
  498. F32 dist = distVec.len();
  499. //Culling distance. Can be adjusted for performance options considerations via the scalar
  500. if (dist > mMaxDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0))
  501. {
  502. mProbeInfo->mScore = mMaxDrawDistance;
  503. return;
  504. }
  505. if (mReflectionModeType == DynamicCubemap && mRefreshRateMS < (Platform::getRealMilliseconds() - mDynamicLastBakeMS))
  506. {
  507. bake("", 32);
  508. mDynamicLastBakeMS = Platform::getRealMilliseconds();
  509. }
  510. //Submit our probe to actually do the probe action
  511. // Get a handy pointer to our RenderPassmanager
  512. //RenderPassManager *renderPass = state->getRenderPass();
  513. //Update our score based on our radius, distance
  514. mProbeInfo->mScore = mProbeInfo->mRadius/mMax(dist,1.0f);
  515. Point3F vect = distVec;
  516. vect.normalizeSafe();
  517. mProbeInfo->mScore *= mMax(mAbs(mDot(vect, state->getCameraTransform().getForwardVector())),0.001f);
  518. //Register
  519. PROBEMGR->registerProbe(mProbeInfoIdx);
  520. if (ReflectionProbe::smRenderPreviewProbes && gEditingMission && mEditorShapeInst && mPrefilterMap != nullptr)
  521. {
  522. GFXTransformSaver saver;
  523. // Calculate the distance of this object from the camera
  524. Point3F cameraOffset;
  525. getRenderTransform().getColumn(3, &cameraOffset);
  526. cameraOffset -= state->getDiffuseCameraPosition();
  527. dist = cameraOffset.len();
  528. if (dist < 0.01f)
  529. dist = 0.01f;
  530. // Set up the LOD for the shape
  531. F32 invScale = (1.0f / getMax(getMax(mObjScale.x, mObjScale.y), mObjScale.z));
  532. mEditorShapeInst->setDetailFromDistance(state, dist * invScale);
  533. // Make sure we have a valid level of detail
  534. if (mEditorShapeInst->getCurrentDetail() < 0)
  535. return;
  536. BaseMatInstance* probePrevMat = mEditorShapeInst->getMaterialList()->getMaterialInst(0);
  537. setPreviewMatParameters(state, probePrevMat);
  538. // GFXTransformSaver is a handy helper class that restores
  539. // the current GFX matrices to their original values when
  540. // it goes out of scope at the end of the function
  541. // Set up our TS render state
  542. TSRenderState rdata;
  543. rdata.setSceneState(state);
  544. rdata.setFadeOverride(1.0f);
  545. if(mReflectionModeType != DynamicCubemap)
  546. rdata.setCubemap(mPrefilterMap->mCubemap);
  547. else
  548. rdata.setCubemap(mDynamicCubemap);
  549. // We might have some forward lit materials
  550. // so pass down a query to gather lights.
  551. LightQuery query;
  552. query.init(getWorldSphere());
  553. rdata.setLightQuery(&query);
  554. // Set the world matrix to the objects render transform
  555. MatrixF mat = getRenderTransform();
  556. mat.scale(Point3F(1, 1, 1));
  557. Point3F centerPos = mat.getPosition();
  558. centerPos += mProbePosOffset;
  559. mat.setPosition(centerPos);
  560. GFX->setWorldMatrix(mat);
  561. // Animate the the shape
  562. mEditorShapeInst->animate();
  563. // Allow the shape to submit the RenderInst(s) for itself
  564. mEditorShapeInst->render(rdata);
  565. saver.restore();
  566. }
  567. // If the light is selected or light visualization
  568. // is enabled then register the callback.
  569. const bool isSelectedInEditor = (gEditingMission && isSelected());
  570. if (isSelectedInEditor)
  571. {
  572. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  573. ri->renderDelegate.bind(this, &ReflectionProbe::_onRenderViz);
  574. ri->type = RenderPassManager::RIT_Editor;
  575. state->getRenderPass()->addInst(ri);
  576. }
  577. }
  578. void ReflectionProbe::_onRenderViz(ObjectRenderInst *ri,
  579. SceneRenderState *state,
  580. BaseMatInstance *overrideMat)
  581. {
  582. if (!ProbeManager::smRenderReflectionProbes)
  583. return;
  584. GFXDrawUtil *draw = GFX->getDrawUtil();
  585. GFXStateBlockDesc desc;
  586. desc.setZReadWrite(true, false);
  587. desc.setCullMode(GFXCullNone);
  588. desc.setBlend(true);
  589. // Base the sphere color on the light color.
  590. ColorI color = ColorI::WHITE;
  591. color.alpha = 25;
  592. if (mProbeShapeType == ProbeRenderInst::Sphere)
  593. {
  594. draw->drawSphere(desc, mRadius, getPosition(), color);
  595. }
  596. else
  597. {
  598. const MatrixF worldToObjectXfm = getTransform();
  599. Box3F cube(-Point3F(mRadius, mRadius, mRadius),Point3F(mRadius, mRadius, mRadius));
  600. Box3F wb = getWorldBox();
  601. cube.setCenter(getPosition()+mProbePosOffset);
  602. wb.setCenter(getPosition() + mProbePosOffset);
  603. draw->drawCube(desc, cube, color, &worldToObjectXfm);
  604. draw->drawCube(desc, wb, color, &worldToObjectXfm);
  605. }
  606. }
  607. void ReflectionProbe::setPreviewMatParameters(SceneRenderState* renderState, BaseMatInstance* mat)
  608. {
  609. if (!mat->getFeatures().hasFeature(MFT_isDeferred))
  610. return;
  611. //Set up the params
  612. MaterialParameters *matParams = mat->getMaterialParameters();
  613. //Get the deferred render target
  614. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  615. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  616. if (!deferredTexObject)
  617. return;
  618. GFX->setTexture(0, deferredTexObject);
  619. //Set the cubemap
  620. GFX->setCubeTexture(1, mPrefilterMap->mCubemap);
  621. //Set the invViewMat
  622. MatrixSet &matrixSet = renderState->getRenderPass()->getMatrixSet();
  623. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  624. MaterialParameterHandle *invViewMat = mat->getMaterialParameterHandle("$invViewMat");
  625. matParams->setSafe(invViewMat, worldToCameraXfm);
  626. }
  627. DefineEngineMethod(ReflectionProbe, postApply, void, (), ,
  628. "A utility method for forcing a network update.\n")
  629. {
  630. object->inspectPostApply();
  631. }
  632. String ReflectionProbe::getPrefilterMapPath()
  633. {
  634. if (mReflectionPath.isEmpty() || mProbeUniqueID.isEmpty())
  635. {
  636. Con::errorf("ReflectionProbe::getPrefilterMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  637. return "";
  638. }
  639. char fileName[256];
  640. dSprintf(fileName, 256, "%s%s_Prefilter.dds", mReflectionPath.c_str(), mProbeUniqueID.c_str());
  641. return fileName;
  642. }
  643. String ReflectionProbe::getIrradianceMapPath()
  644. {
  645. if (mReflectionPath.isEmpty() || mProbeUniqueID.isEmpty())
  646. {
  647. Con::errorf("ReflectionProbe::getIrradianceMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  648. return "";
  649. }
  650. char fileName[256];
  651. dSprintf(fileName, 256, "%s%s_Irradiance.dds", mReflectionPath.c_str(), mProbeUniqueID.c_str());
  652. return fileName;
  653. }
  654. void ReflectionProbe::bake(String outputPath, S32 resolution, bool renderWithProbes)
  655. {
  656. GFXDEBUGEVENT_SCOPE(ReflectionProbe_Bake, ColorI::WHITE);
  657. Con::warnf("ReflectionProbe::bake() - Beginning bake!");
  658. U32 startMSTime = Platform::getRealMilliseconds();
  659. /*PostEffect *preCapture = dynamic_cast<PostEffect*>(Sim::findObject("AL_PreCapture"));
  660. PostEffect *deferredShading = dynamic_cast<PostEffect*>(Sim::findObject("AL_DeferredShading"));
  661. if (preCapture)
  662. {
  663. preCapture->setShaderConst("$radius",String::ToString(mRadius));
  664. preCapture->setShaderConst("$captureRez", String::ToString(F32(resolution)));
  665. preCapture->enable();
  666. }
  667. if (deferredShading)
  668. deferredShading->disable();*/
  669. GFXCubemapHandle sceneCaptureCubemap;
  670. if (mReflectionModeType == DynamicCubemap && mDynamicCubemap.isNull())
  671. {
  672. //mCubemap->createMap();
  673. mDynamicCubemap = GFX->createCubemap();
  674. if(mUseHDRCaptures)
  675. mDynamicCubemap->initDynamic(resolution, GFXFormatR16G16B16A16F);
  676. else
  677. mDynamicCubemap->initDynamic(resolution, GFXFormatB8G8R8A8);
  678. sceneCaptureCubemap = mDynamicCubemap;
  679. }
  680. else if (mReflectionModeType != DynamicCubemap)
  681. {
  682. //Prep our bake path
  683. if (mReflectionPath.isEmpty())
  684. {
  685. Con::errorf("ReflectionProbe::bake() - Unable to bake our captures because probe doesn't have a path set");
  686. return;
  687. }
  688. if (mProbeUniqueID.isEmpty())
  689. {
  690. Con::errorf("ReflectionProbe::bake() - Unable to bake our captures because probe doesn't have a unique ID set");
  691. return;
  692. }
  693. sceneCaptureCubemap = GFX->createCubemap();
  694. if (mUseHDRCaptures)
  695. sceneCaptureCubemap->initDynamic(resolution, GFXFormatR16G16B16A16F);
  696. else
  697. sceneCaptureCubemap->initDynamic(resolution, GFXFormatR8G8B8A8);
  698. }
  699. bool validCubemap = true;
  700. // Save the current transforms so we can restore
  701. // it for child control rendering below.
  702. GFXTransformSaver saver;
  703. //bool saveEditingMission = gEditingMission;
  704. //gEditingMission = false;
  705. //Set this to true to use the prior method where it goes through the SPT_Reflect path for the bake
  706. bool probeRenderState = ProbeManager::smRenderReflectionProbes;
  707. if (!renderWithProbes)
  708. ProbeManager::smRenderReflectionProbes = false;
  709. for (U32 i = 0; i < 6; ++i)
  710. {
  711. GFXTexHandle blendTex;
  712. blendTex.set(resolution, resolution, GFXFormatR16G16B16A16F, &GFXRenderTargetProfile, "");
  713. GFXTextureTargetRef baseTarget = GFX->allocRenderToTextureTarget();
  714. GFX->clearTextureStateImmediate(0);
  715. baseTarget->attachTexture(GFXTextureTarget::Color0, sceneCaptureCubemap, i);
  716. // Standard view that will be overridden below.
  717. VectorF vLookatPt(0.0f, 0.0f, 0.0f), vUpVec(0.0f, 0.0f, 0.0f), vRight(0.0f, 0.0f, 0.0f);
  718. switch (i)
  719. {
  720. case 0: // D3DCUBEMAP_FACE_POSITIVE_X:
  721. vLookatPt = VectorF(1.0f, 0.0f, 0.0f);
  722. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  723. break;
  724. case 1: // D3DCUBEMAP_FACE_NEGATIVE_X:
  725. vLookatPt = VectorF(-1.0f, 0.0f, 0.0f);
  726. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  727. break;
  728. case 2: // D3DCUBEMAP_FACE_POSITIVE_Y:
  729. vLookatPt = VectorF(0.0f, 1.0f, 0.0f);
  730. vUpVec = VectorF(0.0f, 0.0f, -1.0f);
  731. break;
  732. case 3: // D3DCUBEMAP_FACE_NEGATIVE_Y:
  733. vLookatPt = VectorF(0.0f, -1.0f, 0.0f);
  734. vUpVec = VectorF(0.0f, 0.0f, 1.0f);
  735. break;
  736. case 4: // D3DCUBEMAP_FACE_POSITIVE_Z:
  737. vLookatPt = VectorF(0.0f, 0.0f, 1.0f);
  738. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  739. break;
  740. case 5: // D3DCUBEMAP_FACE_NEGATIVE_Z:
  741. vLookatPt = VectorF(0.0f, 0.0f, -1.0f);
  742. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  743. break;
  744. }
  745. // create camera matrix
  746. VectorF cross = mCross(vUpVec, vLookatPt);
  747. cross.normalizeSafe();
  748. MatrixF matView(true);
  749. matView.setColumn(0, cross);
  750. matView.setColumn(1, vLookatPt);
  751. matView.setColumn(2, vUpVec);
  752. matView.setPosition(getPosition()+mProbePosOffset);
  753. matView.inverse();
  754. // set projection to 90 degrees vertical and horizontal
  755. F32 left, right, top, bottom;
  756. F32 nearPlane = 0.01f;
  757. F32 farDist = 1000.f;
  758. MathUtils::makeFrustum(&left, &right, &top, &bottom, M_HALFPI_F, 1.0f, nearPlane);
  759. Frustum frustum(false, left, right, top, bottom, nearPlane, farDist);
  760. F32 detailAdjustBackup = TSShapeInstance::smDetailAdjust;
  761. TSShapeInstance::smDetailAdjust *= getNextPow2(resolution);
  762. renderFrame(&baseTarget, matView, frustum, mCaptureMask & EDITOR_RENDER_TYPEMASK, gCanvasClearColor);
  763. TSShapeInstance::smDetailAdjust = detailAdjustBackup;
  764. baseTarget->resolve();
  765. }
  766. if (sceneCaptureCubemap.isValid())
  767. {
  768. validCubemap = true;
  769. mDirty = false;
  770. }
  771. else
  772. {
  773. validCubemap = false;
  774. }
  775. //Now, save out the maps
  776. //create irridiance cubemap
  777. if (validCubemap)
  778. {
  779. bool se = isServerObject();
  780. //Just to ensure we're prepped for the generation
  781. createClientResources();
  782. //Prep it with whatever resolution we've dictated for our bake
  783. if (mUseHDRCaptures)
  784. {
  785. mIrridianceMap->mCubemap->initDynamic(resolution, GFXFormatR16G16B16A16F);
  786. mPrefilterMap->mCubemap->initDynamic(resolution, GFXFormatR16G16B16A16F);
  787. }
  788. else
  789. {
  790. mIrridianceMap->mCubemap->initDynamic(resolution, GFXFormatR8G8B8A8);
  791. mPrefilterMap->mCubemap->initDynamic(resolution, GFXFormatR8G8B8A8);
  792. }
  793. //IBLUtilities::GenerateAndSaveIrradianceMap(getIrradianceMapPath(), resolution, sceneCaptureCubemap, mIrridianceMap->mCubemap);
  794. //IBLUtilities::GenerateAndSavePrefilterMap(getPrefilterMapPath(), resolution, sceneCaptureCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  795. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  796. IBLUtilities::GenerateIrradianceMap(renderTarget, sceneCaptureCubemap, mIrridianceMap->mCubemap);
  797. IBLUtilities::GeneratePrefilterMap(renderTarget, sceneCaptureCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  798. IBLUtilities::SaveCubeMap(getIrradianceMapPath(), mIrridianceMap->mCubemap);
  799. IBLUtilities::SaveCubeMap(getPrefilterMapPath(), mPrefilterMap->mCubemap);
  800. }
  801. else
  802. {
  803. Con::errorf("ReflectionProbe::bake() - Didn't generate a valid scene capture cubemap, unable to generate prefilter and irradiance maps!");
  804. }
  805. if(!renderWithProbes)
  806. ProbeManager::smRenderReflectionProbes = probeRenderState;
  807. setMaskBits(-1);
  808. /*if (preCapture)
  809. preCapture->disable();
  810. if (deferredShading)
  811. deferredShading->enable();*/
  812. U32 endMSTime = Platform::getRealMilliseconds();
  813. F32 diffTime = F32(endMSTime - startMSTime);
  814. Con::warnf("ReflectionProbe::bake() - Finished bake! Took %g milliseconds", diffTime);
  815. }
  816. DefineEngineMethod(ReflectionProbe, Bake, void, (String outputPath, S32 resolution, bool renderWithProbes), ("", 64, false),
  817. "@brief returns true if control object is inside the fog\n\n.")
  818. {
  819. ReflectionProbe *clientProbe = (ReflectionProbe*)object->getClientObject();
  820. if (clientProbe)
  821. {
  822. clientProbe->bake(outputPath, resolution, renderWithProbes);
  823. }
  824. //object->bake(outputPath, resolution);
  825. }