BsLightProbes.cpp 37 KB

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