IBLUtilities.cpp 22 KB

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