BsLightProbes.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsLightProbes.h"
  4. #include "Renderer/BsLightProbeVolume.h"
  5. #include "RenderAPI/BsGpuBuffer.h"
  6. #include "BsRendererView.h"
  7. #include "BsRenderBeastIBLUtility.h"
  8. #include "Mesh/BsMesh.h"
  9. #include "RenderAPI/BsVertexDataDesc.h"
  10. #include "Material/BsGpuParamsSet.h"
  11. #include "Renderer/BsRendererUtility.h"
  12. #include "Renderer/BsSkybox.h"
  13. #include "BsRendererTextures.h"
  14. namespace bs { namespace ct
  15. {
  16. ShaderVariation TetrahedraRenderMat::VAR_FullMSAA = ShaderVariation({
  17. ShaderVariation::Param("MSAA", true)
  18. });
  19. ShaderVariation TetrahedraRenderMat::VAR_SingleMSAA = ShaderVariation({
  20. ShaderVariation::Param("MSAA", true),
  21. ShaderVariation::Param("MSAA_RESOLVE_0TH", true)
  22. });
  23. ShaderVariation TetrahedraRenderMat::VAR_NoMSAA = ShaderVariation({
  24. });
  25. TetrahedraRenderMat::TetrahedraRenderMat()
  26. {
  27. SPtr<GpuParams> params = mParamsSet->getGpuParams();
  28. params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gDepthBufferTex", mDepthBufferTex);
  29. if(params->hasSamplerState(GPT_FRAGMENT_PROGRAM, "gDepthBufferSamp"))
  30. {
  31. SAMPLER_STATE_DESC pointSampDesc;
  32. pointSampDesc.minFilter = FO_POINT;
  33. pointSampDesc.magFilter = FO_POINT;
  34. pointSampDesc.mipFilter = FO_POINT;
  35. pointSampDesc.addressMode.u = TAM_CLAMP;
  36. pointSampDesc.addressMode.v = TAM_CLAMP;
  37. pointSampDesc.addressMode.w = TAM_CLAMP;
  38. SPtr<SamplerState> pointSampState = SamplerState::create(pointSampDesc);
  39. params->setSamplerState(GPT_FRAGMENT_PROGRAM, "gDepthBufferSamp", pointSampState);
  40. }
  41. }
  42. void TetrahedraRenderMat::_initVariations(ShaderVariations& variations)
  43. {
  44. variations.add(VAR_FullMSAA);
  45. variations.add(VAR_SingleMSAA);
  46. variations.add(VAR_NoMSAA);
  47. }
  48. void TetrahedraRenderMat::execute(const RendererView& view, const SPtr<Texture>& sceneDepth, const SPtr<Mesh>& mesh,
  49. const SPtr<RenderTexture>& output)
  50. {
  51. mDepthBufferTex.set(sceneDepth);
  52. mParamsSet->setParamBlockBuffer("PerCamera", view.getPerViewBuffer(), true);
  53. RenderAPI& rapi = RenderAPI::instance();
  54. rapi.setRenderTarget(output);
  55. gRendererUtility().setPass(mMaterial);
  56. gRendererUtility().setPassParams(mParamsSet);
  57. gRendererUtility().draw(mesh);
  58. }
  59. void TetrahedraRenderMat::getOutputDesc(const RendererView& view, POOLED_RENDER_TEXTURE_DESC& colorDesc,
  60. POOLED_RENDER_TEXTURE_DESC& depthDesc)
  61. {
  62. const RendererViewProperties& viewProps = view.getProperties();
  63. UINT32 width = viewProps.viewRect.width;
  64. UINT32 height = viewProps.viewRect.height;
  65. UINT32 numSamples = viewProps.numSamples;
  66. colorDesc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_R16U, width, height, TU_RENDERTARGET, numSamples);
  67. depthDesc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_D32, width, height, TU_DEPTHSTENCIL, numSamples);
  68. }
  69. TetrahedraRenderMat* TetrahedraRenderMat::getVariation(bool msaa, bool singleSampleMSAA)
  70. {
  71. if (msaa)
  72. {
  73. if (singleSampleMSAA)
  74. return get(VAR_SingleMSAA);
  75. return get(VAR_FullMSAA);
  76. }
  77. return get(VAR_NoMSAA);
  78. }
  79. IrradianceEvaluateParamDef gIrradianceEvaluateParamDef;
  80. ShaderVariation IrradianceEvaluateMat::VAR_FullMSAA_Probes = ShaderVariation({
  81. ShaderVariation::Param("MSAA_COUNT", 2),
  82. ShaderVariation::Param("MSAA", true),
  83. ShaderVariation::Param("SKY_ONLY", false)
  84. });
  85. ShaderVariation IrradianceEvaluateMat::VAR_SingleMSAA_Probes = ShaderVariation({
  86. ShaderVariation::Param("MSAA_COUNT", 2),
  87. ShaderVariation::Param("MSAA", true),
  88. ShaderVariation::Param("MSAA_RESOLVE_0TH", true),
  89. ShaderVariation::Param("SKY_ONLY", false)
  90. });
  91. ShaderVariation IrradianceEvaluateMat::VAR_NoMSAA_Probes = ShaderVariation({
  92. ShaderVariation::Param("MSAA_COUNT", 1),
  93. ShaderVariation::Param("SKY_ONLY", false)
  94. });
  95. ShaderVariation IrradianceEvaluateMat::VAR_FullMSAA_Sky = ShaderVariation({
  96. ShaderVariation::Param("MSAA_COUNT", 2),
  97. ShaderVariation::Param("MSAA", true),
  98. ShaderVariation::Param("SKY_ONLY", true)
  99. });
  100. ShaderVariation IrradianceEvaluateMat::VAR_SingleMSAA_Sky = ShaderVariation({
  101. ShaderVariation::Param("MSAA_COUNT", 2),
  102. ShaderVariation::Param("MSAA", true),
  103. ShaderVariation::Param("MSAA_RESOLVE_0TH", true),
  104. ShaderVariation::Param("SKY_ONLY", true)
  105. });
  106. ShaderVariation IrradianceEvaluateMat::VAR_NoMSAA_Sky = ShaderVariation({
  107. ShaderVariation::Param("MSAA_COUNT", 1),
  108. ShaderVariation::Param("SKY_ONLY", true)
  109. });
  110. IrradianceEvaluateMat::IrradianceEvaluateMat()
  111. :mGBufferParams(mMaterial, mParamsSet)
  112. {
  113. mSkyOnly = mVariation.getBool("SKY_ONLY");
  114. SPtr<GpuParams> params = mParamsSet->getGpuParams();
  115. params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gSkyIrradianceTex", mParamSkyIrradianceTex);
  116. params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gAmbientOcclusionTex", mParamAmbientOcclusionTex);
  117. if(!mSkyOnly)
  118. {
  119. params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gInputTex", mParamInputTex);
  120. params->getBufferParam(GPT_FRAGMENT_PROGRAM, "gSHCoeffs", mParamSHCoeffsBuffer);
  121. params->getBufferParam(GPT_FRAGMENT_PROGRAM, "gTetrahedra", mParamTetrahedraBuffer);
  122. params->getBufferParam(GPT_FRAGMENT_PROGRAM, "gTetFaces", mParamTetFacesBuffer);
  123. }
  124. mParamBuffer = gIrradianceEvaluateParamDef.createBuffer();
  125. mParamsSet->setParamBlockBuffer("Params", mParamBuffer, true);
  126. }
  127. void IrradianceEvaluateMat::_initVariations(ShaderVariations& variations)
  128. {
  129. variations.add(VAR_FullMSAA_Probes);
  130. variations.add(VAR_FullMSAA_Sky);
  131. variations.add(VAR_SingleMSAA_Probes);
  132. variations.add(VAR_SingleMSAA_Sky);
  133. variations.add(VAR_NoMSAA_Probes);
  134. variations.add(VAR_NoMSAA_Sky);
  135. }
  136. void IrradianceEvaluateMat::execute(const RendererView& view, const GBufferTextures& gbuffer,
  137. const SPtr<Texture>& lightProbeIndices, const LightProbesInfo& lightProbesInfo, const Skybox* skybox,
  138. const SPtr<Texture>& ambientOcclusion, const SPtr<RenderTexture>& output)
  139. {
  140. const RendererViewProperties& viewProps = view.getProperties();
  141. mGBufferParams.bind(gbuffer);
  142. float skyBrightness = 1.0f;
  143. SPtr<Texture> skyIrradiance;
  144. if (skybox != nullptr)
  145. {
  146. skyIrradiance = skybox->getIrradiance();
  147. skyBrightness = skybox->getBrightness();
  148. }
  149. if(skyIrradiance == nullptr)
  150. skyIrradiance = RendererTextures::defaultIndirect;
  151. mParamSkyIrradianceTex.set(skyIrradiance);
  152. mParamAmbientOcclusionTex.set(ambientOcclusion);
  153. if(!mSkyOnly)
  154. {
  155. mParamInputTex.set(lightProbeIndices);
  156. mParamSHCoeffsBuffer.set(lightProbesInfo.shCoefficients);
  157. mParamTetrahedraBuffer.set(lightProbesInfo.tetrahedra);
  158. mParamTetFacesBuffer.set(lightProbesInfo.faces);
  159. }
  160. gIrradianceEvaluateParamDef.gSkyBrightness.set(mParamBuffer, skyBrightness);
  161. gIrradianceEvaluateParamDef.gNumTetrahedra.set(mParamBuffer, lightProbesInfo.numTetrahedra);
  162. mParamBuffer->flushToGPU();
  163. mParamsSet->setParamBlockBuffer("PerCamera", view.getPerViewBuffer(), true);
  164. // Render
  165. RenderAPI& rapi = RenderAPI::instance();
  166. rapi.setRenderTarget(output, FBT_DEPTH | FBT_STENCIL, RT_COLOR0);
  167. gRendererUtility().setPass(mMaterial);
  168. gRendererUtility().setPassParams(mParamsSet);
  169. gRendererUtility().drawScreenQuad(Rect2(0.0f, 0.0f, (float)viewProps.viewRect.width,
  170. (float)viewProps.viewRect.height));
  171. rapi.setRenderTarget(nullptr);
  172. }
  173. IrradianceEvaluateMat* IrradianceEvaluateMat::getVariation(bool msaa, bool singleSampleMSAA, bool skyOnly)
  174. {
  175. if(skyOnly)
  176. {
  177. if (msaa)
  178. {
  179. if (singleSampleMSAA)
  180. return get(VAR_SingleMSAA_Sky);
  181. return get(VAR_FullMSAA_Sky);
  182. }
  183. return get(VAR_NoMSAA_Sky);
  184. }
  185. else
  186. {
  187. if (msaa)
  188. {
  189. if (singleSampleMSAA)
  190. return get(VAR_SingleMSAA_Probes);
  191. return get(VAR_FullMSAA_Probes);
  192. }
  193. return get(VAR_NoMSAA_Probes);
  194. }
  195. }
  196. /** Hash value generator for std::pair<INT32, INT32>. */
  197. struct pair_hash
  198. {
  199. size_t operator()(const std::pair<INT32, INT32>& key) const
  200. {
  201. size_t hash = 0;
  202. bs::hash_combine(hash, key.first);
  203. bs::hash_combine(hash, key.second);
  204. return hash;
  205. }
  206. };
  207. /** Information about a single tetrahedron, for use on the GPU. */
  208. struct TetrahedronDataGPU
  209. {
  210. UINT32 indices[4];
  211. Matrix3x4 transform;
  212. };
  213. /** Information about a single tetrahedron face, for use on the GPU. */
  214. struct TetrahedronFaceDataGPU
  215. {
  216. Vector3 corners[3];
  217. Vector3 normals[3];
  218. UINT32 isQuadratic;
  219. };
  220. LightProbes::LightProbes()
  221. :mTetrahedronVolumeDirty(false), mMaxCoefficients(0), mMaxTetrahedra(0), mMaxFaces(0), mNumValidTetrahedra(0)
  222. { }
  223. void LightProbes::notifyAdded(LightProbeVolume* volume)
  224. {
  225. UINT32 handle = (UINT32)mVolumes.size();
  226. VolumeInfo info;
  227. info.volume = volume;
  228. info.isDirty = true;
  229. mVolumes.push_back(info);
  230. volume->setRendererId(handle);
  231. notifyDirty(volume);
  232. }
  233. void LightProbes::notifyDirty(LightProbeVolume* volume)
  234. {
  235. UINT32 handle = volume->getRendererId();
  236. mVolumes[handle].isDirty = true;
  237. mTetrahedronVolumeDirty = true;
  238. }
  239. void LightProbes::notifyRemoved(LightProbeVolume* volume)
  240. {
  241. UINT32 handle = volume->getRendererId();
  242. LightProbeVolume* lastVolume = mVolumes.back().volume;
  243. UINT32 lastHandle = lastVolume->getRendererId();
  244. if (handle != lastHandle)
  245. {
  246. // Swap current last element with the one we want to erase
  247. std::swap(mVolumes[handle], mVolumes[lastHandle]);
  248. lastVolume->setRendererId(handle);
  249. }
  250. // Erase last (empty) element
  251. mVolumes.erase(mVolumes.end() - 1);
  252. mTetrahedronVolumeDirty = true;
  253. }
  254. void LightProbes::updateProbes()
  255. {
  256. if (!mTetrahedronVolumeDirty)
  257. return;
  258. // Move all coefficients into the global buffer
  259. UINT32 numCoeffs = 0;
  260. for(auto& entry : mVolumes)
  261. {
  262. UINT32 numProbes = (UINT32)entry.volume->getLightProbePositions().size();
  263. numCoeffs += numProbes;
  264. }
  265. if(numCoeffs > mMaxCoefficients)
  266. {
  267. UINT32 newSize = Math::divideAndRoundUp(numCoeffs, 32U) * 32U;
  268. resizeCoefficientBuffer(newSize);
  269. }
  270. UINT32 writePos = 0;
  271. for(auto& entry : mVolumes)
  272. {
  273. UINT32 numProbes = (UINT32)entry.volume->getLightProbePositions().size();
  274. UINT32 size = numProbes * sizeof(LightProbeSHCoefficients);
  275. SPtr<GpuBuffer> localBuffer = entry.volume->getCoefficientsBuffer();
  276. // Note: Some of the coefficients might still be dirty (unrendered). Check for this and write them as black?
  277. mProbeCoefficientsGPU->copyData(*localBuffer, 0, writePos, size);
  278. writePos += size;
  279. }
  280. // Gather all positions
  281. UINT32 bufferOffset = 0;
  282. for(auto& entry : mVolumes)
  283. {
  284. const Vector<LightProbeInfo>& infos = entry.volume->getLightProbeInfos();
  285. const Vector<Vector3>& positions = entry.volume->getLightProbePositions();
  286. UINT32 numProbes = entry.volume->getNumActiveProbes();
  287. if (numProbes == 0)
  288. continue;
  289. Vector3 offset = entry.volume->getPosition();
  290. Quaternion rotation = entry.volume->getRotation();
  291. for(UINT32 i = 0; i < numProbes; i++)
  292. {
  293. Vector3 localPos = positions[i];
  294. Vector3 transformedPos = rotation.rotate(localPos) + offset;
  295. mTempTetrahedronPositions.push_back(transformedPos);
  296. mTempTetrahedronBufferIndices.push_back(bufferOffset + infos[i].bufferIdx);
  297. }
  298. bufferOffset += (UINT32)positions.size();
  299. }
  300. mTetrahedronInfos.clear();
  301. Vector<TetrahedronFaceData> outerFaces;
  302. generateTetrahedronData(mTempTetrahedronPositions, mTetrahedronInfos, outerFaces, true);
  303. // Find valid tetrahedrons
  304. UINT32 numTetrahedra = (UINT32)mTetrahedronInfos.size();
  305. bool* validTets = (bool*)bs_stack_alloc(sizeof(bool) * numTetrahedra);
  306. mNumValidTetrahedra = 0;
  307. for (UINT32 i = 0; i < (UINT32)mTetrahedronInfos.size(); i++)
  308. {
  309. const TetrahedronData& entry = mTetrahedronInfos[i];
  310. const Vector3& P1 = mTempTetrahedronPositions[entry.volume.vertices[0]];
  311. const Vector3& P2 = mTempTetrahedronPositions[entry.volume.vertices[1]];
  312. const Vector3& P3 = mTempTetrahedronPositions[entry.volume.vertices[2]];
  313. const Vector3& P4 = mTempTetrahedronPositions[entry.volume.vertices[3]];
  314. Vector3 E1 = P1 - P4;
  315. Vector3 E2 = P2 - P4;
  316. Vector3 E3 = P3 - P4;
  317. // If tetrahedron is co-planar just ignore it, shader will use some other nearby one instead. We can't
  318. // handle coplanar tetrahedrons because the matrix is not invertible, and for nearly co-planar ones the
  319. // math breaks down because of precision issues.
  320. validTets[i] = fabs(Vector3::dot(Vector3::normalize(Vector3::cross(E1, E2)), E3)) > 0.0001f;
  321. if (validTets[i])
  322. mNumValidTetrahedra++;
  323. }
  324. UINT32 numValidFaces = 0;
  325. for(auto& entry : outerFaces)
  326. {
  327. if (validTets[entry.tetrahedron])
  328. numValidFaces++;
  329. }
  330. // Generate a mesh out of all the tetrahedron triangles
  331. // Note: Currently the entire volume is rendered as a single large mesh, which will isn't optimal as we can't
  332. // perform frustum culling. A better option would be to split the mesh into multiple smaller volumes, do
  333. // frustum culling and possibly even sort by distance from camera.
  334. UINT32 numVertices = mNumValidTetrahedra * 4 * 3 + numValidFaces * 9 * 3;
  335. SPtr<VertexDataDesc> vertexDesc = bs_shared_ptr_new<VertexDataDesc>();
  336. vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION);
  337. vertexDesc->addVertElem(VET_UINT1, VES_TEXCOORD);
  338. SPtr<MeshData> meshData = MeshData::create(numVertices, numVertices, vertexDesc);
  339. auto posIter = meshData->getVec3DataIter(VES_POSITION);
  340. auto idIter = meshData->getDWORDDataIter(VES_TEXCOORD);
  341. UINT32* indices = meshData->getIndices32();
  342. // Insert inner tetrahedron triangles
  343. UINT32 tetIdx = 0;
  344. for (UINT32 i = 0; i < (UINT32)mTetrahedronInfos.size(); i++)
  345. {
  346. if (!validTets[i])
  347. continue;
  348. const Tetrahedron& volume = mTetrahedronInfos[i].volume;
  349. Vector3 center(BsZero);
  350. for(UINT32 j = 0; j < 4; j++)
  351. center += mTempTetrahedronPositions[volume.vertices[j]];
  352. center /= 4.0f;
  353. static const UINT32 Permutations[4][3] =
  354. {
  355. { 0, 1, 2 },
  356. { 0, 1, 3 },
  357. { 0, 2, 3 },
  358. { 1, 2, 3 }
  359. };
  360. for(UINT32 j = 0; j < 4; j++)
  361. {
  362. Vector3 A = mTempTetrahedronPositions[volume.vertices[Permutations[j][0]]];
  363. Vector3 B = mTempTetrahedronPositions[volume.vertices[Permutations[j][1]]];
  364. Vector3 C = mTempTetrahedronPositions[volume.vertices[Permutations[j][2]]];
  365. // Make sure the triangle is clockwise, facing away from the center
  366. Vector3 e0 = A - C;
  367. Vector3 e1 = B - C;
  368. Vector3 normal = e0.cross(e1);
  369. if (normal.dot(A - center) > 0.0f)
  370. std::swap(B, C);
  371. posIter.addValue(A);
  372. posIter.addValue(B);
  373. posIter.addValue(C);
  374. idIter.addValue(tetIdx);
  375. idIter.addValue(tetIdx);
  376. idIter.addValue(tetIdx);
  377. indices[0] = tetIdx * 4 * 3 + j * 3 + 0;
  378. indices[1] = tetIdx * 4 * 3 + j * 3 + 1;
  379. indices[2] = tetIdx * 4 * 3 + j * 3 + 2;
  380. indices += 3;
  381. }
  382. tetIdx++;
  383. }
  384. // Generate an edge map for outer faces (required for step below)
  385. struct Edge
  386. {
  387. UINT32 vertInner[2];
  388. UINT32 vertOuter[2];
  389. UINT32 face[2];
  390. };
  391. FrameUnorderedMap<std::pair<INT32, INT32>, Edge, pair_hash> edgeMap;
  392. for(UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  393. {
  394. if (!validTets[outerFaces[i].tetrahedron])
  395. continue;
  396. for (UINT32 j = 0; j < 3; ++j)
  397. {
  398. UINT32 v0 = outerFaces[i].innerVertices[j];
  399. UINT32 v1 = outerFaces[i].innerVertices[(j + 1) % 3];
  400. // Keep the same ordering so other faces can find the same edge
  401. if (v0 > v1)
  402. std::swap(v0, v1);
  403. auto iterFind = edgeMap.find(std::make_pair((INT32)v0, (INT32)v1));
  404. if (iterFind != edgeMap.end())
  405. {
  406. iterFind->second.face[1] = i;
  407. }
  408. else
  409. {
  410. Edge edge;
  411. edge.vertInner[0] = outerFaces[i].innerVertices[j];
  412. edge.vertInner[1] = outerFaces[i].innerVertices[(j + 1) % 3];
  413. edge.vertOuter[0] = outerFaces[i].outerVertices[j];
  414. edge.vertOuter[1] = outerFaces[i].outerVertices[(j + 1) % 3];
  415. edge.face[0] = i;
  416. edge.face[1] = -1;
  417. edgeMap.insert(std::make_pair(std::make_pair((INT32)v0, (INT32)v1), edge));
  418. }
  419. }
  420. }
  421. // Generate front and back triangles for extruded outer faces
  422. UINT32 faceIdx = 0;
  423. for(UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  424. {
  425. if (!validTets[outerFaces[i].tetrahedron])
  426. continue;
  427. const TetrahedronFaceData& entry = outerFaces[i];
  428. static const UINT32 Permutations[2][3] = { {0, 1, 2 }, { 3, 4, 5} };
  429. // Make sure the triangle is clockwise, facing away from the center
  430. Vector3 center(BsZero);
  431. for (UINT32 k = 0; k < 3; k++)
  432. {
  433. center += mTempTetrahedronPositions[entry.innerVertices[k]];
  434. center += mTempTetrahedronPositions[entry.outerVertices[k]];
  435. }
  436. center /= 6.0f;
  437. for(UINT32 j = 0; j < 2; ++j)
  438. {
  439. UINT32 idxA = Permutations[j][0];
  440. UINT32 idxB = Permutations[j][1];
  441. UINT32 idxC = Permutations[j][2];
  442. idxA = idxA > 2 ? entry.outerVertices[idxA - 3] : entry.innerVertices[idxA];
  443. idxB = idxB > 2 ? entry.outerVertices[idxB - 3] : entry.innerVertices[idxB];
  444. idxC = idxC > 2 ? entry.outerVertices[idxC - 3] : entry.innerVertices[idxC];
  445. Vector3 A = mTempTetrahedronPositions[idxA];
  446. Vector3 B = mTempTetrahedronPositions[idxB];
  447. Vector3 C = mTempTetrahedronPositions[idxC];
  448. Vector3 e0 = A - C;
  449. Vector3 e1 = B - C;
  450. Vector3 normal = e0.cross(e1);
  451. if (normal.dot(A - center) > 0.0f)
  452. std::swap(A, B);
  453. posIter.addValue(A);
  454. posIter.addValue(B);
  455. posIter.addValue(C);
  456. idIter.addValue(tetIdx + faceIdx);
  457. idIter.addValue(tetIdx + faceIdx);
  458. idIter.addValue(tetIdx + faceIdx);
  459. indices[0] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + j * 3 + 0;
  460. indices[1] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + j * 3 + 1;
  461. indices[2] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + j * 3 + 2;
  462. indices += 3;
  463. }
  464. faceIdx++;
  465. }
  466. // Generate sides for extruded outer faces
  467. UINT32 sideIdx = 0;
  468. for(auto& entry : edgeMap)
  469. {
  470. const Edge& edge = entry.second;
  471. for (UINT32 i = 0; i < 2; i++)
  472. {
  473. const TetrahedronFaceData& face = outerFaces[edge.face[i]];
  474. // Make sure the triangle is clockwise, facing away from the center
  475. Vector3 center(BsZero);
  476. for (UINT32 k = 0; k < 3; k++)
  477. {
  478. center += mTempTetrahedronPositions[face.innerVertices[k]];
  479. center += mTempTetrahedronPositions[face.outerVertices[k]];
  480. }
  481. center /= 6.0f;
  482. static const UINT32 Permutations[2][3] = { {0, 1, 2 }, { 1, 2, 3} };
  483. for(UINT32 j = 0; j < 2; ++j)
  484. {
  485. UINT32 idxA = Permutations[j][0];
  486. UINT32 idxB = Permutations[j][1];
  487. UINT32 idxC = Permutations[j][2];
  488. idxA = idxA > 1 ? edge.vertOuter[idxA - 2] : edge.vertInner[idxA];
  489. idxB = idxB > 1 ? edge.vertOuter[idxB - 2] : edge.vertInner[idxB];
  490. idxC = idxC > 1 ? edge.vertOuter[idxC - 2] : edge.vertInner[idxC];
  491. Vector3 A = mTempTetrahedronPositions[idxA];
  492. Vector3 B = mTempTetrahedronPositions[idxB];
  493. Vector3 C = mTempTetrahedronPositions[idxC];
  494. Vector3 e0 = A - C;
  495. Vector3 e1 = B - C;
  496. Vector3 normal = e0.cross(e1);
  497. if (normal.dot(A - center) > 0.0f)
  498. std::swap(A, B);
  499. posIter.addValue(A);
  500. posIter.addValue(B);
  501. posIter.addValue(C);
  502. idIter.addValue(tetIdx + edge.face[i]);
  503. idIter.addValue(tetIdx + edge.face[i]);
  504. idIter.addValue(tetIdx + edge.face[i]);
  505. indices[0] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + sideIdx * 2 * 3 + j * 3 + 0;
  506. indices[1] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + sideIdx * 2 * 3 + j * 3 + 1;
  507. indices[2] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + sideIdx * 2 * 3 + j * 3 + 2;
  508. indices += 3;
  509. }
  510. sideIdx++;
  511. }
  512. }
  513. // Generate "caps" on the end of the extruded volume
  514. UINT32 capIdx = 0;
  515. for(UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  516. {
  517. if (!validTets[outerFaces[i].tetrahedron])
  518. continue;
  519. const TetrahedronFaceData& entry = outerFaces[i];
  520. Vector3 A = mTempTetrahedronPositions[entry.outerVertices[0]];
  521. Vector3 B = mTempTetrahedronPositions[entry.outerVertices[1]];
  522. Vector3 C = mTempTetrahedronPositions[entry.outerVertices[2]];
  523. // Make sure the triangle is clockwise, facing toward the center
  524. const Tetrahedron& tet = mTetrahedronInfos[entry.tetrahedron].volume;
  525. Vector3 center(BsZero);
  526. for(UINT32 j = 0; j < 4; j++)
  527. center += mTempTetrahedronPositions[tet.vertices[j]];
  528. center /= 4.0f;
  529. Vector3 e0 = A - C;
  530. Vector3 e1 = B - C;
  531. Vector3 normal = e0.cross(e1);
  532. if (normal.dot(A - center) < 0.0f)
  533. std::swap(B, C);
  534. posIter.addValue(A);
  535. posIter.addValue(B);
  536. posIter.addValue(C);
  537. idIter.addValue(-1);
  538. idIter.addValue(-1);
  539. idIter.addValue(-1);
  540. indices[0] = tetIdx * 4 * 3 + faceIdx * 8 * 3 + capIdx * 3 + 0;
  541. indices[1] = tetIdx * 4 * 3 + faceIdx * 8 * 3 + capIdx * 3 + 1;
  542. indices[2] = tetIdx * 4 * 3 + faceIdx * 8 * 3 + capIdx * 3 + 2;
  543. indices += 3;
  544. capIdx++;
  545. }
  546. mVolumeMesh = Mesh::create(meshData);
  547. // Map vertices to actual SH coefficient indices, and write GPU buffer with tetrahedron information
  548. if ((mNumValidTetrahedra + numValidFaces) > mMaxTetrahedra)
  549. {
  550. UINT32 newSize = Math::divideAndRoundUp(mNumValidTetrahedra + numValidFaces, 64U) * 64U;
  551. resizeTetrahedronBuffer(newSize);
  552. }
  553. TetrahedronDataGPU* dst = (TetrahedronDataGPU*)mTetrahedronInfosGPU->lock(0, mTetrahedronInfosGPU->getSize(),
  554. GBL_WRITE_ONLY_DISCARD);
  555. // Write inner tetrahedron data
  556. for (UINT32 i = 0; i < (UINT32)mTetrahedronInfos.size(); i++)
  557. {
  558. if (!validTets[i])
  559. continue;
  560. TetrahedronData& entry = mTetrahedronInfos[i];
  561. for(UINT32 j = 0; j < 4; ++j)
  562. entry.volume.vertices[j] = mTempTetrahedronBufferIndices[entry.volume.vertices[j]];
  563. memcpy(dst->indices, entry.volume.vertices, sizeof(UINT32) * 4);
  564. memcpy(&dst->transform, &entry.transform, sizeof(float) * 12);
  565. dst++;
  566. }
  567. // Write extruded face data
  568. for (UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  569. {
  570. if (!validTets[outerFaces[i].tetrahedron])
  571. continue;
  572. const TetrahedronFaceData& entry = outerFaces[i];
  573. UINT32 indices[4];
  574. indices[0] = mTempTetrahedronBufferIndices[entry.innerVertices[0]];
  575. indices[1] = mTempTetrahedronBufferIndices[entry.innerVertices[1]];
  576. indices[2] = mTempTetrahedronBufferIndices[entry.innerVertices[2]];
  577. indices[3] = -1;
  578. memcpy(dst->indices, indices, sizeof(UINT32) * 4);
  579. memcpy(&dst->transform, &entry.transform, sizeof(float) * 12);
  580. dst++;
  581. }
  582. mTetrahedronInfosGPU->unlock();
  583. // Write data specific to faces
  584. if (numValidFaces > mMaxFaces)
  585. {
  586. UINT32 newSize = Math::divideAndRoundUp(numValidFaces, 64U) * 64U;
  587. resizeTetrahedronFaceBuffer(newSize);
  588. }
  589. TetrahedronFaceDataGPU* faceDst = (TetrahedronFaceDataGPU*)mTetrahedronFaceInfosGPU->lock(0,
  590. mTetrahedronFaceInfosGPU->getSize(), GBL_WRITE_ONLY_DISCARD);
  591. for (UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  592. {
  593. if (!validTets[outerFaces[i].tetrahedron])
  594. continue;
  595. const TetrahedronFaceData& entry = outerFaces[i];
  596. for (UINT32 j = 0; j < 3; j++)
  597. {
  598. faceDst->corners[j] = mTempTetrahedronPositions[entry.innerVertices[j]];
  599. faceDst->normals[j] = entry.normals[j];
  600. }
  601. faceDst->isQuadratic = entry.quadratic ? 1 : 0;
  602. faceDst++;
  603. }
  604. mTetrahedronFaceInfosGPU->unlock();
  605. bs_stack_free(validTets);
  606. mTempTetrahedronPositions.clear();
  607. mTempTetrahedronBufferIndices.clear();
  608. mTetrahedronVolumeDirty = false;
  609. }
  610. bool LightProbes::hasAnyProbes() const
  611. {
  612. for(auto& entry : mVolumes)
  613. {
  614. UINT32 numProbes = entry.volume->getNumActiveProbes();
  615. if (numProbes > 0)
  616. return true;
  617. }
  618. return false;
  619. }
  620. LightProbesInfo LightProbes::getInfo() const
  621. {
  622. LightProbesInfo info;
  623. info.shCoefficients = mProbeCoefficientsGPU;
  624. info.tetrahedra = mTetrahedronInfosGPU;
  625. info.faces = mTetrahedronFaceInfosGPU;
  626. info.tetrahedraVolume = mVolumeMesh;
  627. info.numTetrahedra = mNumValidTetrahedra;
  628. return info;
  629. }
  630. void LightProbes::resizeTetrahedronBuffer(UINT32 count)
  631. {
  632. GPU_BUFFER_DESC desc;
  633. desc.type = GBT_STRUCTURED;
  634. desc.elementSize = sizeof(TetrahedronDataGPU);
  635. desc.elementCount = count;
  636. desc.usage = GBU_STATIC;
  637. desc.format = BF_UNKNOWN;
  638. mTetrahedronInfosGPU = GpuBuffer::create(desc);
  639. mMaxTetrahedra = count;
  640. }
  641. void LightProbes::resizeTetrahedronFaceBuffer(UINT32 count)
  642. {
  643. GPU_BUFFER_DESC desc;
  644. desc.type = GBT_STRUCTURED;
  645. desc.elementSize = sizeof(TetrahedronFaceDataGPU);
  646. desc.elementCount = count;
  647. desc.usage = GBU_STATIC;
  648. desc.format = BF_UNKNOWN;
  649. mTetrahedronFaceInfosGPU = GpuBuffer::create(desc);
  650. mMaxFaces = count;
  651. }
  652. void LightProbes::resizeCoefficientBuffer(UINT32 count)
  653. {
  654. GPU_BUFFER_DESC desc;
  655. desc.type = GBT_STRUCTURED;
  656. desc.elementSize = sizeof(LightProbeSHCoefficients);
  657. desc.elementCount = count;
  658. desc.usage = GBU_STATIC;
  659. desc.format = BF_UNKNOWN;
  660. mProbeCoefficientsGPU = GpuBuffer::create(desc);
  661. mMaxCoefficients = count;
  662. }
  663. void LightProbes::generateTetrahedronData(Vector<Vector3>& positions, Vector<TetrahedronData>& tetrahedra,
  664. Vector<TetrahedronFaceData>& faces, bool generateExtrapolationVolume)
  665. {
  666. bs_frame_mark();
  667. {
  668. TetrahedronVolume volume = Triangulation::tetrahedralize(positions);
  669. if (generateExtrapolationVolume)
  670. {
  671. // Add geometry so we can handle the case when the interpolation position falls outside of the tetrahedra
  672. // volume. We use this geometry to project the position to the nearest face.
  673. UINT32 numOuterFaces = (UINT32)volume.outerFaces.size();
  674. // Calculate face normals for outer faces
  675. //// Make an edge map
  676. struct Edge
  677. {
  678. INT32 faces[2];
  679. INT32 oppositeVerts[2];
  680. };
  681. FrameUnorderedMap<std::pair<INT32, INT32>, Edge, pair_hash> edgeMap;
  682. for (UINT32 i = 0; i < numOuterFaces; ++i)
  683. {
  684. for (UINT32 j = 0; j < 3; ++j)
  685. {
  686. INT32 v0 = volume.outerFaces[i].vertices[j];
  687. INT32 v1 = volume.outerFaces[i].vertices[(j + 1) % 3];
  688. // Keep the same ordering so other faces can find the same edge
  689. if (v0 > v1)
  690. std::swap(v0, v1);
  691. auto iterFind = edgeMap.find(std::make_pair(v0, v1));
  692. if (iterFind != edgeMap.end())
  693. {
  694. iterFind->second.faces[1] = i;
  695. iterFind->second.oppositeVerts[1] = (j + 2) % 3;
  696. }
  697. else
  698. {
  699. Edge edge;
  700. edge.faces[0] = i;
  701. edge.oppositeVerts[0] = (j + 2) % 3;
  702. edgeMap.insert(std::make_pair(std::make_pair(v0, v1), edge));
  703. }
  704. }
  705. }
  706. //// Generate face normals
  707. struct FaceVertex
  708. {
  709. Vector3 normal = Vector3::ZERO;
  710. UINT32 outerIdx = -1;
  711. };
  712. FrameVector<Vector3> faceNormals(volume.outerFaces.size());
  713. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  714. {
  715. const Vector3& v0 = positions[volume.outerFaces[i].vertices[0]];
  716. const Vector3& v1 = positions[volume.outerFaces[i].vertices[1]];
  717. const Vector3& v2 = positions[volume.outerFaces[i].vertices[2]];
  718. Vector3 e0 = v1 - v0;
  719. Vector3 e1 = v2 - v0;
  720. // Make sure the normal is facing away from the center
  721. const Tetrahedron& tet = volume.tetrahedra[volume.outerFaces[i].tetrahedron];
  722. Vector3 center(BsZero);
  723. for(UINT32 j = 0; j < 4; j++)
  724. center += positions[tet.vertices[j]];
  725. center /= 4.0f;
  726. Vector3 normal = Vector3::normalize(e0.cross(e1));
  727. if (normal.dot(v0 - center) < 0.0f)
  728. normal = -normal;
  729. faceNormals[i] = normal;
  730. }
  731. //// Generate vertex normals
  732. FrameUnorderedMap<INT32, FaceVertex> faceVertices;
  733. for (auto& entry : edgeMap)
  734. {
  735. const Edge& edge = entry.second;
  736. auto accumulateNormalForEdgeVertex = [&](UINT32 v0Idx, UINT32 v1Idx)
  737. {
  738. auto iter = faceVertices.insert(std::make_pair(v0Idx, FaceVertex()));
  739. FaceVertex& accum = iter.first->second;
  740. const Vector3& v0 = positions[v0Idx];
  741. auto accumulateNormalForFace = [&](INT32 faceIdx, INT32 v2LocIdx)
  742. {
  743. const TetrahedronFace& face = volume.outerFaces[faceIdx];
  744. // Vertices on the face, that aren't the vertex we're calculating the normal for
  745. const Vector3& v1 = positions[v1Idx];
  746. const Vector3& v2 = positions[face.vertices[v2LocIdx]];
  747. // Weight the contribution to the normal based on the angle spanned by the triangle
  748. Vector3 e0 = Vector3::normalize(v1 - v0);
  749. Vector3 e1 = Vector3::normalize(v2 - v0);
  750. float weight = acos(e0.dot(e1));
  751. accum.normal += weight * faceNormals[faceIdx];
  752. };
  753. accumulateNormalForFace(edge.faces[0], entry.second.oppositeVerts[0]);
  754. accumulateNormalForFace(edge.faces[1], entry.second.oppositeVerts[1]);
  755. };
  756. accumulateNormalForEdgeVertex(entry.first.first, entry.first.second);
  757. accumulateNormalForEdgeVertex(entry.first.second, entry.first.first);
  758. }
  759. for (auto& entry : faceVertices)
  760. entry.second.normal.normalize();
  761. // For each face vertex, generate an outer vertex along its normal
  762. static const float ExtrapolationDistance = 5.0f;
  763. for(auto& entry : faceVertices)
  764. {
  765. entry.second.outerIdx = (UINT32)positions.size();
  766. Vector3 outerPos = positions[entry.first] + entry.second.normal * ExtrapolationDistance;
  767. positions.push_back(outerPos);
  768. }
  769. // Generate face data
  770. for (UINT32 i = 0; i < numOuterFaces; ++i)
  771. {
  772. const TetrahedronFace& face = volume.outerFaces[i];
  773. TetrahedronFaceData faceData;
  774. faceData.tetrahedron = face.tetrahedron;
  775. for (UINT32 j = 0; j < 3; j++)
  776. {
  777. const FaceVertex& faceVertex = faceVertices[face.vertices[j]];
  778. faceData.innerVertices[j] = face.vertices[j];
  779. faceData.outerVertices[j] = faceVertex.outerIdx;
  780. faceData.normals[j] = faceVertex.normal;
  781. }
  782. // Add a link on the source tetrahedron to the face data
  783. Tetrahedron& innerTet = volume.tetrahedra[face.tetrahedron];
  784. for(UINT32 j = 0; j < 4; j++)
  785. {
  786. if (innerTet.neighbors[j] == -1)
  787. {
  788. // Note: Not searching for opposite neighbor here. If tet. has multiple free faces then we
  789. // can't just pick the first one
  790. innerTet.neighbors[j] = (UINT32)volume.tetrahedra.size() + (UINT32)faces.size();
  791. break;
  792. }
  793. }
  794. // We need a way to project a point outside the tetrahedron volume onto an outer face, then calculate
  795. // triangle's barycentric coordinates. Use use the per-vertex normals to extrude the triangle face into
  796. // infinity.
  797. // Our point can be represented as:
  798. // p == a (p0 + t*v0) + b (p1 + t*v1) + c (p2 + t*v2)
  799. //
  800. // where a, b and c are barycentric coordinates,
  801. // p0, p1, p2 are the corners of the face
  802. // v0, v1, v2 are the vertex normals, per corner
  803. // t is the distance from the triangle to the point
  804. //
  805. // Essentially we're calculating the corners of a bigger triangle that's "t" units away from the
  806. // face, and its corners lie along the per-vertex normals. Point "p" will lie on that triangle, for which
  807. // we can then calculate barycentric coordinates normally.
  808. //
  809. // First we substitute: c = 1 - a - b
  810. // p == a (p0 + t v0) + b (p1 + t v1) + (1 - a - b) (p2 + t v2)
  811. // p == a (p0 + t v0) + b (p1 + t v1) + (p2 + t v2) - a (p2 + t v2) - b (p2 + t v2)
  812. // p == a (p0 - p2 + t v0 - t v2) + b (p1 - p2 + t v1 - t v2) + (p2 + t v2)
  813. //
  814. // And move everything to one side:
  815. // p - p2 - t v2 == a (p0 - p2 + t ( v0 - v2)) + b (p1 - p2 + t ( v1 - v2))
  816. // a (p0 - p2 + t ( v0 - v2)) + b (p1 - p2 + t ( v1 - v2)) - (p - p2 - t v2) == 0
  817. //
  818. // We rewrite it using:
  819. // Ap = p0 - p2
  820. // Av = v0 - v2
  821. // Bp = p1 - p2
  822. // Bv = v1 - v2
  823. // Cp = p - p2
  824. // Cv = -v2
  825. //
  826. // Which yields:
  827. // a (Ap + t Av) + b (Bp + t Bv) - (Cp + t Cv) == 0
  828. //
  829. // Which can be written in matrix form:
  830. //
  831. // M = {Ap + t Av, Bp + t Bv, Cp + t Cv}
  832. // a 0
  833. // M * [ b ] = [0]
  834. // -1 0
  835. //
  836. // From that we can tell that matrix M cannot be inverted, because if we multiply the zero vector with the
  837. // inverted matrix the result would be zero, and not [a, b, -1]. Since the matrix cannot be inverted
  838. // det(M) == 0.
  839. //
  840. // We can use that fact to calculate "t". After we have "t" we can calculate barycentric coordinates
  841. // normally.
  842. //
  843. // Solving equation det(M) == 0 yields a cubic in form:
  844. // p t^3 + q t^2 + r t + s = 0
  845. //
  846. // We'll convert this to monic form, by dividing by p:
  847. // t^3 + q/p t^2 + r/p t + s/p = 0
  848. //
  849. // Or if p ends up being zero, we end up with a quadratic instead:
  850. // q t^2 + r t + s = 0
  851. //
  852. // We want to create a matrix that when multiplied with the position, yields us the three coefficients,
  853. // which we can then use to solve for "t". For this we create a 4x3 matrix, where each row represents
  854. // a solution for one of the coefficients. We factor contributons to each coefficient whether they depend on
  855. // position x, y, z, or don't depend on position (row columns, in that order respectively).
  856. const Vector3& p0 = positions[faceData.innerVertices[0]];
  857. const Vector3& p1 = positions[faceData.innerVertices[1]];
  858. const Vector3& p2 = positions[faceData.innerVertices[2]];
  859. const Vector3& v0 = faceVertices[faceData.innerVertices[0]].normal;
  860. const Vector3& v1 = faceVertices[faceData.innerVertices[1]].normal;
  861. const Vector3& v2 = faceVertices[faceData.innerVertices[2]].normal;
  862. float p =
  863. v2.x * v1.y * v0.z -
  864. v1.x * v2.y * v0.z -
  865. v2.x * v0.y * v1.z +
  866. v0.x * v2.y * v1.z +
  867. v1.x * v0.y * v2.z -
  868. v0.x * v1.y * v2.z;
  869. float qx = -v1.y * v0.z + v2.y * v0.z + v0.y * v1.z - v2.y * v1.z - v0.y * v2.z + v1.y * v2.z;
  870. float qy = v1.x * v0.z - v2.x * v0.z - v0.x * v1.z + v2.x * v1.z + v0.x * v2.z - v1.x * v2.z;
  871. float qz = -v1.x * v0.y + v2.x * v0.y + v0.x * v1.y - v2.x * v1.y - v0.x * v2.y + v1.x * v2.y;
  872. float qw = v2.y * v1.z * p0.x - v1.y * v2.z * p0.x - v2.y * v0.z * p1.x + v0.y * v2.z * p1.x +
  873. v1.y * v0.z * p2.x - v0.y * v1.z * p2.x - v2.x * v1.z * p0.y + v1.x * v2.z * p0.y +
  874. v2.x * v0.z * p1.y - v0.x * v2.z * p1.y - v1.x * v0.z * p2.y + v0.x * v1.z * p2.y +
  875. v2.x * v1.y * p0.z - v1.x * v2.y * p0.z - v2.x * v0.y * p1.z + v0.x * v2.y * p1.z +
  876. v1.x * v0.y * p2.z - v0.x * v1.y * p2.z;
  877. float rx = v1.z * p0.y - v2.z * p0.y - v0.z * p1.y + v2.z * p1.y + v0.z * p2.y - v1.z * p2.y -
  878. v1.y * p0.z + v2.y * p0.z + v0.y * p1.z - v2.y * p1.z - v0.y * p2.z + v1.y * p2.z;
  879. float ry = -v1.z * p0.x + v2.z * p0.x + v0.z * p1.x - v2.z * p1.x - v0.z * p2.x + v1.z * p2.x +
  880. v1.x * p0.z - v2.x * p0.z - v0.x * p1.z + v2.x * p1.z + v0.x * p2.z - v1.x * p2.z;
  881. float rz = v1.y * p0.x - v2.y * p0.x - v0.y * p1.x + v2.y * p1.x + v0.y * p2.x - v1.y * p2.x -
  882. v1.x * p0.y + v2.x * p0.y + v0.x * p1.y - v2.x * p1.y - v0.x * p2.y + v1.x * p2.y;
  883. float rw = v2.z * p1.x * p0.y - v1.z * p2.x * p0.y - v2.z * p0.x * p1.y + v0.z * p2.x * p1.y +
  884. v1.z * p0.x * p2.y - v0.z * p1.x * p2.y - v2.y * p1.x * p0.z + v1.y * p2.x * p0.z +
  885. v2.x * p1.y * p0.z - v1.x * p2.y * p0.z + v2.y * p0.x * p1.z - v0.y * p2.x * p1.z -
  886. v2.x * p0.y * p1.z + v0.x * p2.y * p1.z - v1.y * p0.x * p2.z + v0.y * p1.x * p2.z +
  887. v1.x * p0.y * p2.z - v0.x * p1.y * p2.z;
  888. float sx = -p1.y * p0.z + p2.y * p0.z + p0.y * p1.z - p2.y * p1.z - p0.y * p2.z + p1.y * p2.z;
  889. float sy = p1.x * p0.z - p2.x * p0.z - p0.x * p1.z + p2.x * p1.z + p0.x * p2.z - p1.x * p2.z;
  890. float sz = -p1.x * p0.y + p2.x * p0.y + p0.x * p1.y - p2.x * p1.y - p0.x * p2.y + p1.x * p2.y;
  891. float sw = p2.x * p1.y * p0.z - p1.x * p2.y * p0.z - p2.x * p0.y * p1.z +
  892. p0.x * p2.y * p1.z + p1.x * p0.y * p2.z - p0.x * p1.y * p2.z;
  893. faceData.transform[0][0] = qx;
  894. faceData.transform[0][1] = qy;
  895. faceData.transform[0][2] = qz;
  896. faceData.transform[0][3] = qw;
  897. faceData.transform[1][0] = rx;
  898. faceData.transform[1][1] = ry;
  899. faceData.transform[1][2] = rz;
  900. faceData.transform[1][3] = rw;
  901. faceData.transform[2][0] = sx;
  902. faceData.transform[2][1] = sy;
  903. faceData.transform[2][2] = sz;
  904. faceData.transform[2][3] = sw;
  905. // Unused
  906. faceData.transform[3][0] = 0.0f;
  907. faceData.transform[3][1] = 0.0f;
  908. faceData.transform[3][2] = 0.0f;
  909. faceData.transform[3][3] = 0.0f;
  910. if (fabs(p) > 0.00001f)
  911. {
  912. faceData.transform = faceData.transform * (1.0f / p);
  913. faceData.quadratic = false;
  914. }
  915. else // Quadratic
  916. {
  917. faceData.quadratic = true;
  918. }
  919. faces.push_back(faceData);
  920. }
  921. }
  922. else
  923. {
  924. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  925. {
  926. const TetrahedronFace& face = volume.outerFaces[i];
  927. TetrahedronFaceData faceData;
  928. for (UINT32 j = 0; j < 3; j++)
  929. {
  930. faceData.innerVertices[j] = face.vertices[j];
  931. faceData.outerVertices[j] = -1;
  932. faceData.normals[j] = Vector3::ZERO;
  933. }
  934. faceData.tetrahedron = face.tetrahedron;
  935. faceData.transform = Matrix4::IDENTITY;
  936. faceData.quadratic = false;
  937. faces.push_back(faceData);
  938. }
  939. }
  940. // Generate matrices
  941. UINT32 numOutputTets = (UINT32)volume.tetrahedra.size();
  942. tetrahedra.reserve(numOutputTets);
  943. //// For inner tetrahedrons
  944. for(UINT32 i = 0; i < (UINT32)numOutputTets; ++i)
  945. {
  946. TetrahedronData entry;
  947. entry.volume = volume.tetrahedra[i];
  948. // Generate a matrix that can be used for calculating barycentric coordinates
  949. // To determine a point within a tetrahedron, using barycentric coordinates, we use:
  950. // P = (P1 - P4) * a + (P2 - P4) * b + (P3 - P4) * c + P4
  951. //
  952. // Where P1, P2, P3, P4 are the corners of the tetrahedron.
  953. //
  954. // Expanded for each coordinate this is:
  955. // x = (x1 - x4) * a + (x2 - x4) * b + (x3 - x4) * c + x4
  956. // y = (y1 - y4) * a + (y2 - y4) * b + (y3 - y4) * c + y4
  957. // z = (z1 - z4) * a + (z2 - z4) * b + (z3 - z4) * c + z4
  958. //
  959. // In matrix form this is:
  960. // a
  961. // P = [P1 - P4, P2 - P4, P3 - P4, P4] [b]
  962. // c
  963. // 1
  964. //
  965. // Solved for barycentric coordinates:
  966. // a
  967. // [b] = Minv * P
  968. // c
  969. // 1
  970. //
  971. // Where Minv is the inverse of the matrix above.
  972. const Vector3& P1 = positions[volume.tetrahedra[i].vertices[0]];
  973. const Vector3& P2 = positions[volume.tetrahedra[i].vertices[1]];
  974. const Vector3& P3 = positions[volume.tetrahedra[i].vertices[2]];
  975. const Vector3& P4 = positions[volume.tetrahedra[i].vertices[3]];
  976. Vector3 E1 = P1 - P4;
  977. Vector3 E2 = P2 - P4;
  978. Vector3 E3 = P3 - P4;
  979. Matrix4 mat;
  980. mat.setColumn(0, Vector4(E1, 0.0f));
  981. mat.setColumn(1, Vector4(E2, 0.0f));
  982. mat.setColumn(2, Vector4(E3, 0.0f));
  983. mat.setColumn(3, Vector4(P4, 1.0f));
  984. entry.transform = mat.inverse();
  985. tetrahedra.push_back(entry);
  986. }
  987. }
  988. bs_frame_clear();
  989. }
  990. }}