IBLUtilities.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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/IBLUtilities.h"
  23. #include "console/engineAPI.h"
  24. #include "materials/shaderData.h"
  25. #include "gfx/gfxTextureManager.h"
  26. #include "gfx/gfxTransformSaver.h"
  27. #include "gfx/bitmap/cubemapSaver.h"
  28. #include "core/stream/fileStream.h"
  29. #include "gfx/bitmap/imageUtils.h"
  30. namespace IBLUtilities
  31. {
  32. void GenerateIrradianceMap(GFXTextureTargetRef renderTarget, GFXCubemapHandle cubemap, GFXCubemapHandle &cubemapOut)
  33. {
  34. GFXTransformSaver saver;
  35. GFXStateBlockRef irrStateBlock;
  36. ShaderData *irrShaderData;
  37. GFXShaderRef irrShader = Sim::findObject("IrradianceShader", irrShaderData) ? irrShaderData->getShader() : NULL;
  38. if (!irrShader)
  39. {
  40. Con::errorf("IBLUtilities::GenerateIrradianceMap() - could not find IrradianceShader");
  41. return;
  42. }
  43. GFXShaderConstBufferRef irrConsts = irrShader->allocConstBuffer();
  44. GFXShaderConstHandle* irrEnvMapSC = irrShader->getShaderConstHandle("$environmentMap");
  45. GFXShaderConstHandle* irrFaceSC = irrShader->getShaderConstHandle("$face");
  46. GFXStateBlockDesc desc;
  47. desc.zEnable = false;
  48. desc.samplersDefined = true;
  49. desc.samplers[0].addressModeU = GFXAddressClamp;
  50. desc.samplers[0].addressModeV = GFXAddressClamp;
  51. desc.samplers[0].addressModeW = GFXAddressClamp;
  52. desc.samplers[0].magFilter = GFXTextureFilterLinear;
  53. desc.samplers[0].minFilter = GFXTextureFilterLinear;
  54. desc.samplers[0].mipFilter = GFXTextureFilterLinear;
  55. irrStateBlock = GFX->createStateBlock(desc);
  56. GFX->pushActiveRenderTarget();
  57. GFX->setShader(irrShader);
  58. GFX->setShaderConstBuffer(irrConsts);
  59. GFX->setStateBlock(irrStateBlock);
  60. GFX->setVertexBuffer(NULL);
  61. GFX->setCubeTexture(0, cubemap);
  62. for (U32 i = 0; i < 6; i++)
  63. {
  64. renderTarget->attachTexture(GFXTextureTarget::Color0, cubemapOut, i);
  65. irrConsts->setSafe(irrFaceSC, (S32)i);
  66. GFX->setActiveRenderTarget(renderTarget);
  67. GFX->clear(GFXClearTarget, LinearColorF::BLACK, 1.0f, 0);
  68. GFX->drawPrimitive(GFXTriangleList, 0, 3);
  69. renderTarget->resolve();
  70. }
  71. GFX->popActiveRenderTarget();
  72. }
  73. void GenerateAndSaveIrradianceMap(String outputPath, S32 resolution, GFXCubemapHandle cubemap, GFXCubemapHandle &cubemapOut)
  74. {
  75. if (outputPath.isEmpty())
  76. {
  77. Con::errorf("IBLUtilities::GenerateAndSaveIrradianceMap - Cannot save to an empty path!");
  78. return;
  79. }
  80. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  81. IBLUtilities::GenerateIrradianceMap(renderTarget, cubemap, cubemapOut);
  82. //Write it out
  83. CubemapSaver::save(cubemapOut, outputPath);
  84. if (!Platform::isFile(outputPath))
  85. {
  86. Con::errorf("IBLUtilities::GenerateAndSaveIrradianceMap - Failed to properly save out the baked irradiance!");
  87. }
  88. }
  89. void SaveCubeMap(String outputPath, GFXCubemapHandle &cubemap)
  90. {
  91. if (outputPath.isEmpty())
  92. {
  93. Con::errorf("IBLUtilities::SaveCubeMap - Cannot save to an empty path!");
  94. return;
  95. }
  96. //Write it out
  97. CubemapSaver::save(cubemap, outputPath);
  98. if (!Platform::isFile(outputPath))
  99. {
  100. Con::errorf("IBLUtilities::SaveCubeMap - Failed to properly save out the baked irradiance!");
  101. }
  102. }
  103. void GeneratePrefilterMap(GFXTextureTargetRef renderTarget, GFXCubemapHandle cubemap, U32 mipLevels, GFXCubemapHandle &cubemapOut)
  104. {
  105. GFXTransformSaver saver;
  106. ShaderData *prefilterShaderData;
  107. GFXShaderRef prefilterShader = Sim::findObject("PrefiterCubemapShader", prefilterShaderData) ? prefilterShaderData->getShader() : NULL;
  108. if (!prefilterShader)
  109. {
  110. Con::errorf("IBLUtilities::GeneratePrefilterMap() - could not find PrefiterCubemapShader");
  111. return;
  112. }
  113. GFXShaderConstBufferRef prefilterConsts = prefilterShader->allocConstBuffer();
  114. GFXShaderConstHandle* prefilterEnvMapSC = prefilterShader->getShaderConstHandle("$environmentMap");
  115. GFXShaderConstHandle* prefilterFaceSC = prefilterShader->getShaderConstHandle("$face");
  116. GFXShaderConstHandle* prefilterRoughnessSC = prefilterShader->getShaderConstHandle("$roughness");
  117. GFXShaderConstHandle* prefilterMipSizeSC = prefilterShader->getShaderConstHandle("$mipSize");
  118. GFXShaderConstHandle* prefilterResolutionSC = prefilterShader->getShaderConstHandle("$resolution");
  119. GFX->pushActiveRenderTarget();
  120. GFX->setShader(prefilterShader);
  121. GFX->setShaderConstBuffer(prefilterConsts);
  122. GFX->setCubeTexture(0, cubemap);
  123. U32 prefilterSize = cubemapOut->getSize();
  124. U32 resolutionSize = prefilterSize;
  125. for (U32 face = 0; face < 6; face++)
  126. {
  127. prefilterConsts->setSafe(prefilterFaceSC, (S32)face);
  128. prefilterConsts->setSafe(prefilterResolutionSC, (S32)resolutionSize);
  129. for (U32 mip = 0; mip < mipLevels; mip++)
  130. {
  131. S32 mipSize = prefilterSize >> mip;
  132. F32 roughness = (float)mip / (float)(mipLevels - 1);
  133. prefilterConsts->setSafe(prefilterRoughnessSC, roughness);
  134. prefilterConsts->setSafe(prefilterMipSizeSC, mipSize);
  135. U32 size = prefilterSize * mPow(0.5f, mip);
  136. renderTarget->attachTexture(GFXTextureTarget::Color0, cubemapOut, face, mip);
  137. GFX->setActiveRenderTarget(renderTarget, false);//we set the viewport ourselves
  138. GFX->setViewport(RectI(0, 0, size, size));
  139. GFX->clear(GFXClearTarget, LinearColorF::BLACK, 1.0f, 0);
  140. GFX->drawPrimitive(GFXTriangleList, 0, 3);
  141. renderTarget->resolve();
  142. }
  143. }
  144. GFX->popActiveRenderTarget();
  145. }
  146. void GenerateAndSavePrefilterMap(String outputPath, S32 resolution, GFXCubemapHandle cubemap, U32 mipLevels, GFXCubemapHandle &cubemapOut)
  147. {
  148. if (outputPath.isEmpty())
  149. {
  150. Con::errorf("IBLUtilities::GenerateAndSavePrefilterMap - Cannot save to an empty path!");
  151. return;
  152. }
  153. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  154. IBLUtilities::GeneratePrefilterMap(renderTarget, cubemap, mipLevels, cubemapOut);
  155. //Write it out
  156. CubemapSaver::save(cubemapOut, outputPath);
  157. if (!Platform::isFile(outputPath))
  158. {
  159. Con::errorf("IBLUtilities::GenerateAndSavePrefilterMap - Failed to properly save out the baked irradiance!");
  160. }
  161. }
  162. void bakeReflection(String outputPath, S32 resolution)
  163. {
  164. //GFXDEBUGEVENT_SCOPE(ReflectionProbe_Bake, ColorI::WHITE);
  165. /*PostEffect *preCapture = dynamic_cast<PostEffect*>(Sim::findObject("AL_PreCapture"));
  166. PostEffect *deferredShading = dynamic_cast<PostEffect*>(Sim::findObject("AL_DeferredShading"));
  167. if (preCapture)
  168. preCapture->enable();
  169. if (deferredShading)
  170. deferredShading->disable();
  171. //if (mReflectionModeType == StaticCubemap || mReflectionModeType == BakedCubemap || mReflectionModeType == SkyLight)
  172. {
  173. if (!mCubemap)
  174. {
  175. mCubemap = new CubemapData();
  176. mCubemap->registerObject();
  177. }
  178. }
  179. if (mReflectionModeType == DynamicCubemap && mDynamicCubemap.isNull())
  180. {
  181. //mCubemap->createMap();
  182. mDynamicCubemap = GFX->createCubemap();
  183. mDynamicCubemap->initDynamic(resolution, GFXFormatR8G8B8);
  184. }
  185. else if (mReflectionModeType != DynamicCubemap)
  186. {
  187. if (mReflectionPath.isEmpty() || !mPersistentId)
  188. {
  189. if (!mPersistentId)
  190. mPersistentId = getOrCreatePersistentId();
  191. mReflectionPath = outputPath.c_str();
  192. mProbeUniqueID = std::to_string(mPersistentId->getUUID().getHash()).c_str();
  193. }
  194. }
  195. bool validCubemap = true;
  196. // Save the current transforms so we can restore
  197. // it for child control rendering below.
  198. GFXTransformSaver saver;
  199. //bool saveEditingMission = gEditingMission;
  200. //gEditingMission = false;
  201. //Set this to true to use the prior method where it goes through the SPT_Reflect path for the bake
  202. bool probeRenderState = ReflectionProbe::smRenderReflectionProbes;
  203. ReflectionProbe::smRenderReflectionProbes = false;
  204. for (U32 i = 0; i < 6; ++i)
  205. {
  206. GFXTexHandle blendTex;
  207. blendTex.set(resolution, resolution, GFXFormatR8G8B8A8, &GFXRenderTargetProfile, "");
  208. GFXTextureTargetRef mBaseTarget = GFX->allocRenderToTextureTarget();
  209. GFX->clearTextureStateImmediate(0);
  210. if (mReflectionModeType == DynamicCubemap)
  211. mBaseTarget->attachTexture(GFXTextureTarget::Color0, mDynamicCubemap, i);
  212. else
  213. mBaseTarget->attachTexture(GFXTextureTarget::Color0, blendTex);
  214. // Standard view that will be overridden below.
  215. VectorF vLookatPt(0.0f, 0.0f, 0.0f), vUpVec(0.0f, 0.0f, 0.0f), vRight(0.0f, 0.0f, 0.0f);
  216. switch (i)
  217. {
  218. case 0: // D3DCUBEMAP_FACE_POSITIVE_X:
  219. vLookatPt = VectorF(1.0f, 0.0f, 0.0f);
  220. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  221. break;
  222. case 1: // D3DCUBEMAP_FACE_NEGATIVE_X:
  223. vLookatPt = VectorF(-1.0f, 0.0f, 0.0f);
  224. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  225. break;
  226. case 2: // D3DCUBEMAP_FACE_POSITIVE_Y:
  227. vLookatPt = VectorF(0.0f, 1.0f, 0.0f);
  228. vUpVec = VectorF(0.0f, 0.0f, -1.0f);
  229. break;
  230. case 3: // D3DCUBEMAP_FACE_NEGATIVE_Y:
  231. vLookatPt = VectorF(0.0f, -1.0f, 0.0f);
  232. vUpVec = VectorF(0.0f, 0.0f, 1.0f);
  233. break;
  234. case 4: // D3DCUBEMAP_FACE_POSITIVE_Z:
  235. vLookatPt = VectorF(0.0f, 0.0f, 1.0f);
  236. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  237. break;
  238. case 5: // D3DCUBEMAP_FACE_NEGATIVE_Z:
  239. vLookatPt = VectorF(0.0f, 0.0f, -1.0f);
  240. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  241. break;
  242. }
  243. // create camera matrix
  244. VectorF cross = mCross(vUpVec, vLookatPt);
  245. cross.normalizeSafe();
  246. MatrixF matView(true);
  247. matView.setColumn(0, cross);
  248. matView.setColumn(1, vLookatPt);
  249. matView.setColumn(2, vUpVec);
  250. matView.setPosition(getPosition());
  251. matView.inverse();
  252. // set projection to 90 degrees vertical and horizontal
  253. F32 left, right, top, bottom;
  254. F32 nearPlane = 0.01f;
  255. F32 farDist = 1000.f;
  256. MathUtils::makeFrustum(&left, &right, &top, &bottom, M_HALFPI_F, 1.0f, nearPlane);
  257. Frustum frustum(false, left, right, top, bottom, nearPlane, farDist);
  258. renderFrame(&mBaseTarget, matView, frustum, StaticObjectType | StaticShapeObjectType & EDITOR_RENDER_TYPEMASK, gCanvasClearColor);
  259. mBaseTarget->resolve();
  260. mCubemap->setCubeFaceTexture(i, blendTex);
  261. }
  262. if (mReflectionModeType != DynamicCubemap && validCubemap)
  263. {
  264. if (mCubemap->mCubemap)
  265. mCubemap->updateFaces();
  266. else
  267. mCubemap->createMap();
  268. char fileName[256];
  269. dSprintf(fileName, 256, "%s%s.DDS", mReflectionPath.c_str(), mProbeUniqueID.c_str());
  270. CubemapSaver::save(mCubemap->mCubemap, fileName);
  271. if (!Platform::isFile(fileName))
  272. {
  273. validCubemap = false; //if we didn't save right, just
  274. Con::errorf("Failed to properly save out the skylight baked cubemap!");
  275. }
  276. mDirty = false;
  277. }
  278. //calculateSHTerms();
  279. ReflectionProbe::smRenderReflectionProbes = probeRenderState;
  280. setMaskBits(-1);
  281. if (preCapture)
  282. preCapture->disable();
  283. if (deferredShading)
  284. deferredShading->enable();*/
  285. }
  286. LinearColorF decodeSH(Point3F normal, const LinearColorF SHTerms[9], const F32 SHConstants[5])
  287. {
  288. float x = normal.x;
  289. float y = normal.y;
  290. float z = normal.z;
  291. LinearColorF l00 = SHTerms[0];
  292. LinearColorF l10 = SHTerms[1];
  293. LinearColorF l11 = SHTerms[2];
  294. LinearColorF l12 = SHTerms[3];
  295. LinearColorF l20 = SHTerms[4];
  296. LinearColorF l21 = SHTerms[5];
  297. LinearColorF l22 = SHTerms[6];
  298. LinearColorF l23 = SHTerms[7];
  299. LinearColorF l24 = SHTerms[8];
  300. LinearColorF result = (
  301. l00 * SHConstants[0] +
  302. l12 * SHConstants[1] * x +
  303. l10 * SHConstants[1] * y +
  304. l11 * SHConstants[1] * z +
  305. l20 * SHConstants[2] * x*y +
  306. l21 * SHConstants[2] * y*z +
  307. l22 * SHConstants[3] * (3.0*z*z - 1.0) +
  308. l23 * SHConstants[2] * x*z +
  309. l24 * SHConstants[4] * (x*x - y * y)
  310. );
  311. return LinearColorF(mMax(result.red, 0), mMax(result.green, 0), mMax(result.blue, 0));
  312. }
  313. MatrixF getSideMatrix(U32 side)
  314. {
  315. // Standard view that will be overridden below.
  316. VectorF vLookatPt(0.0f, 0.0f, 0.0f), vUpVec(0.0f, 0.0f, 0.0f), vRight(0.0f, 0.0f, 0.0f);
  317. switch (side)
  318. {
  319. case 0: // D3DCUBEMAP_FACE_POSITIVE_X:
  320. vLookatPt = VectorF(1.0f, 0.0f, 0.0f);
  321. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  322. break;
  323. case 1: // D3DCUBEMAP_FACE_NEGATIVE_X:
  324. vLookatPt = VectorF(-1.0f, 0.0f, 0.0f);
  325. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  326. break;
  327. case 2: // D3DCUBEMAP_FACE_POSITIVE_Y:
  328. vLookatPt = VectorF(0.0f, 1.0f, 0.0f);
  329. vUpVec = VectorF(0.0f, 0.0f, -1.0f);
  330. break;
  331. case 3: // D3DCUBEMAP_FACE_NEGATIVE_Y:
  332. vLookatPt = VectorF(0.0f, -1.0f, 0.0f);
  333. vUpVec = VectorF(0.0f, 0.0f, 1.0f);
  334. break;
  335. case 4: // D3DCUBEMAP_FACE_POSITIVE_Z:
  336. vLookatPt = VectorF(0.0f, 0.0f, 1.0f);
  337. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  338. break;
  339. case 5: // D3DCUBEMAP_FACE_NEGATIVE_Z:
  340. vLookatPt = VectorF(0.0f, 0.0f, -1.0f);
  341. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  342. break;
  343. }
  344. // create camera matrix
  345. VectorF cross = mCross(vUpVec, vLookatPt);
  346. cross.normalizeSafe();
  347. MatrixF rotMat(true);
  348. rotMat.setColumn(0, cross);
  349. rotMat.setColumn(1, vLookatPt);
  350. rotMat.setColumn(2, vUpVec);
  351. //rotMat.inverse();
  352. return rotMat;
  353. }
  354. F32 harmonics(U32 termId, Point3F normal)
  355. {
  356. F32 x = normal.x;
  357. F32 y = normal.y;
  358. F32 z = normal.z;
  359. switch (termId)
  360. {
  361. case 0:
  362. return 1.0;
  363. case 1:
  364. return y;
  365. case 2:
  366. return z;
  367. case 3:
  368. return x;
  369. case 4:
  370. return x * y;
  371. case 5:
  372. return y * z;
  373. case 6:
  374. return 3.0*z*z - 1.0;
  375. case 7:
  376. return x * z;
  377. default:
  378. return x * x - y * y;
  379. }
  380. }
  381. LinearColorF sampleSide(GBitmap* cubeFaceBitmaps[6], const U32& cubemapResolution, const U32& termindex, const U32& sideIndex)
  382. {
  383. MatrixF sideRot = getSideMatrix(sideIndex);
  384. LinearColorF result = LinearColorF::ZERO;
  385. F32 divider = 0;
  386. for (int y = 0; y<cubemapResolution; y++)
  387. {
  388. for (int x = 0; x<cubemapResolution; x++)
  389. {
  390. Point2F sidecoord = ((Point2F(x, y) + Point2F(0.5, 0.5)) / Point2F(cubemapResolution, cubemapResolution))*2.0 - Point2F(1.0, 1.0);
  391. Point3F normal = Point3F(sidecoord.x, sidecoord.y, -1.0);
  392. normal.normalize();
  393. F32 minBrightness = Con::getFloatVariable("$pref::GI::Cubemap_Sample_MinBrightness", 0.001f);
  394. LinearColorF texel = cubeFaceBitmaps[sideIndex]->sampleTexel(y, x);
  395. texel = LinearColorF(mMax(texel.red, minBrightness), mMax(texel.green, minBrightness), mMax(texel.blue, minBrightness)) * Con::getFloatVariable("$pref::GI::Cubemap_Gain", 1.5);
  396. Point3F dir;
  397. sideRot.mulP(normal, &dir);
  398. result += texel * harmonics(termindex, dir) * -normal.z;
  399. divider += -normal.z;
  400. }
  401. }
  402. result /= divider;
  403. return result;
  404. }
  405. //
  406. //SH Calculations
  407. // From http://sunandblackcat.com/tipFullView.php?l=eng&topicid=32&topic=Spherical-Harmonics-From-Cube-Texture
  408. // With shader decode logic from https://github.com/nicknikolov/cubemap-sh
  409. void calculateSHTerms(GFXCubemapHandle cubemap, LinearColorF SHTerms[9], F32 SHConstants[5])
  410. {
  411. if (!cubemap)
  412. return;
  413. const VectorF cubemapFaceNormals[6] =
  414. {
  415. // D3DCUBEMAP_FACE_POSITIVE_X:
  416. VectorF(1.0f, 0.0f, 0.0f),
  417. // D3DCUBEMAP_FACE_NEGATIVE_X:
  418. VectorF(-1.0f, 0.0f, 0.0f),
  419. // D3DCUBEMAP_FACE_POSITIVE_Y:
  420. VectorF(0.0f, 1.0f, 0.0f),
  421. // D3DCUBEMAP_FACE_NEGATIVE_Y:
  422. VectorF(0.0f, -1.0f, 0.0f),
  423. // D3DCUBEMAP_FACE_POSITIVE_Z:
  424. VectorF(0.0f, 0.0f, 1.0f),
  425. // D3DCUBEMAP_FACE_NEGATIVE_Z:
  426. VectorF(0.0f, 0.0f, -1.0f),
  427. };
  428. U32 cubemapResolution = cubemap->getSize();
  429. GBitmap* cubeFaceBitmaps[6];
  430. for (U32 i = 0; i < 6; i++)
  431. {
  432. cubeFaceBitmaps[i] = new GBitmap(cubemapResolution, cubemapResolution, false, GFXFormatR16G16B16A16F);
  433. }
  434. //If we fail to parse the cubemap for whatever reason, we really can't continue
  435. if (!CubemapSaver::getBitmaps(cubemap, GFXFormatR8G8B8A8, cubeFaceBitmaps))
  436. return;
  437. //Set up our constants
  438. F32 L0 = Con::getFloatVariable("$pref::GI::SH_Term_L0", 1.0f);
  439. F32 L1 = Con::getFloatVariable("$pref::GI::SH_Term_L1", 1.8f);
  440. F32 L2 = Con::getFloatVariable("$pref::GI::SH_Term_L2", 0.83f);
  441. F32 L2m2_L2m1_L21 = Con::getFloatVariable("$pref::GI::SH_Term_L2m2", 2.9f);
  442. F32 L20 = Con::getFloatVariable("$pref::GI::SH_Term_L20", 0.58f);
  443. F32 L22 = Con::getFloatVariable("$pref::GI::SH_Term_L22", 1.1f);
  444. SHConstants[0] = L0;
  445. SHConstants[1] = L1;
  446. SHConstants[2] = L2 * L2m2_L2m1_L21;
  447. SHConstants[3] = L2 * L20;
  448. SHConstants[4] = L2 * L22;
  449. for (U32 i = 0; i < 9; i++)
  450. {
  451. //Clear it, just to be sure
  452. SHTerms[i] = LinearColorF(0.f, 0.f, 0.f);
  453. //Now, encode for each side
  454. SHTerms[i] = sampleSide(cubeFaceBitmaps, cubemapResolution, i, 0); //POS_X
  455. SHTerms[i] += sampleSide(cubeFaceBitmaps, cubemapResolution, i, 1); //NEG_X
  456. SHTerms[i] += sampleSide(cubeFaceBitmaps, cubemapResolution, i, 2); //POS_Y
  457. SHTerms[i] += sampleSide(cubeFaceBitmaps, cubemapResolution, i, 3); //NEG_Y
  458. SHTerms[i] += sampleSide(cubeFaceBitmaps, cubemapResolution, i, 4); //POS_Z
  459. SHTerms[i] += sampleSide(cubeFaceBitmaps, cubemapResolution, i, 5); //NEG_Z
  460. //Average
  461. SHTerms[i] /= 6;
  462. }
  463. for (U32 i = 0; i < 6; i++)
  464. SAFE_DELETE(cubeFaceBitmaps[i]);
  465. /*bool mExportSHTerms = false;
  466. if (mExportSHTerms)
  467. {
  468. for (U32 f = 0; f < 6; f++)
  469. {
  470. char fileName[256];
  471. dSprintf(fileName, 256, "%s%s_DecodedFaces_%d.png", mReflectionPath.c_str(),
  472. mProbeUniqueID.c_str(), f);
  473. LinearColorF color = decodeSH(cubemapFaceNormals[f]);
  474. FileStream stream;
  475. if (stream.open(fileName, Torque::FS::File::Write))
  476. {
  477. GBitmap bitmap(mCubemapResolution, mCubemapResolution, false, GFXFormatR8G8B8);
  478. bitmap.fill(color.toColorI());
  479. bitmap.writeBitmap("png", stream);
  480. }
  481. }
  482. for (U32 f = 0; f < 9; f++)
  483. {
  484. char fileName[256];
  485. dSprintf(fileName, 256, "%s%s_SHTerms_%d.png", mReflectionPath.c_str(),
  486. mProbeUniqueID.c_str(), f);
  487. LinearColorF color = mProbeInfo->SHTerms[f];
  488. FileStream stream;
  489. if (stream.open(fileName, Torque::FS::File::Write))
  490. {
  491. GBitmap bitmap(mCubemapResolution, mCubemapResolution, false, GFXFormatR8G8B8);
  492. bitmap.fill(color.toColorI());
  493. bitmap.writeBitmap("png", stream);
  494. }
  495. }
  496. }*/
  497. }
  498. F32 areaElement(F32 x, F32 y)
  499. {
  500. return mAtan2(x * y, (F32)mSqrt(x * x + y * y + 1.0));
  501. }
  502. F32 texelSolidAngle(F32 aU, F32 aV, U32 width, U32 height)
  503. {
  504. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  505. // ( 0.5 is for texel center addressing)
  506. const F32 U = (2.0 * (aU + 0.5) / width) - 1.0;
  507. const F32 V = (2.0 * (aV + 0.5) / height) - 1.0;
  508. // shift from a demi texel, mean 1.0 / size with U and V in [-1..1]
  509. const F32 invResolutionW = 1.0 / width;
  510. const F32 invResolutionH = 1.0 / height;
  511. // U and V are the -1..1 texture coordinate on the current face.
  512. // get projected area for this texel
  513. const F32 x0 = U - invResolutionW;
  514. const F32 y0 = V - invResolutionH;
  515. const F32 x1 = U + invResolutionW;
  516. const F32 y1 = V + invResolutionH;
  517. const F32 angle = areaElement(x0, y0) - areaElement(x0, y1) - areaElement(x1, y0) + areaElement(x1, y1);
  518. return angle;
  519. }
  520. };