BsLightProbes.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  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. GPU_BUFFER_DESC desc;
  594. desc.type = GBT_STRUCTURED;
  595. desc.elementSize = sizeof(TetrahedronDataGPU);
  596. desc.elementCount = count;
  597. desc.usage = GBU_STATIC;
  598. desc.format = BF_UNKNOWN;
  599. mTetrahedronInfosGPU = GpuBuffer::create(desc);
  600. mMaxTetrahedra = count;
  601. }
  602. void LightProbes::resizeTetrahedronFaceBuffer(UINT32 count)
  603. {
  604. GPU_BUFFER_DESC desc;
  605. desc.type = GBT_STRUCTURED;
  606. desc.elementSize = sizeof(TetrahedronFaceDataGPU);
  607. desc.elementCount = count;
  608. desc.usage = GBU_STATIC;
  609. desc.format = BF_UNKNOWN;
  610. mTetrahedronFaceInfosGPU = GpuBuffer::create(desc);
  611. mMaxFaces = count;
  612. }
  613. void LightProbes::resizeCoefficientTexture(UINT32 numRows)
  614. {
  615. TEXTURE_DESC desc;
  616. desc.width = 4096;
  617. desc.height = numRows;
  618. desc.usage = TU_LOADSTORE | TU_RENDERTARGET;
  619. desc.format = PF_RGBA32F;
  620. SPtr<Texture> newTexture = Texture::create(desc);
  621. if (mProbeCoefficientsGPU)
  622. mProbeCoefficientsGPU->copy(newTexture);
  623. mProbeCoefficientsGPU = newTexture;
  624. mMaxCoefficientRows = numRows;
  625. }
  626. void LightProbes::generateTetrahedronData(Vector<Vector3>& positions, Vector<TetrahedronData>& tetrahedra,
  627. Vector<TetrahedronFaceData>& faces, bool generateExtrapolationVolume)
  628. {
  629. bs_frame_mark();
  630. {
  631. TetrahedronVolume volume = Triangulation::tetrahedralize(positions);
  632. if (generateExtrapolationVolume)
  633. {
  634. // Add geometry so we can handle the case when the interpolation position falls outside of the tetrahedra
  635. // volume. We use this geometry to project the position to the nearest face.
  636. UINT32 numOuterFaces = (UINT32)volume.outerFaces.size();
  637. // Calculate face normals for outer faces
  638. //// Make an edge map
  639. struct Edge
  640. {
  641. INT32 faces[2];
  642. INT32 oppositeVerts[2];
  643. };
  644. FrameUnorderedMap<std::pair<INT32, INT32>, Edge, pair_hash> edgeMap;
  645. for (UINT32 i = 0; i < numOuterFaces; ++i)
  646. {
  647. for (UINT32 j = 0; j < 3; ++j)
  648. {
  649. INT32 v0 = volume.outerFaces[i].vertices[j];
  650. INT32 v1 = volume.outerFaces[i].vertices[(j + 1) % 3];
  651. // Keep the same ordering so other faces can find the same edge
  652. if (v0 > v1)
  653. std::swap(v0, v1);
  654. auto iterFind = edgeMap.find(std::make_pair(v0, v1));
  655. if (iterFind != edgeMap.end())
  656. {
  657. iterFind->second.faces[1] = i;
  658. iterFind->second.oppositeVerts[1] = (j + 2) % 3;
  659. }
  660. else
  661. {
  662. Edge edge;
  663. edge.faces[0] = i;
  664. edge.oppositeVerts[0] = (j + 2) % 3;
  665. edgeMap.insert(std::make_pair(std::make_pair(v0, v1), edge));
  666. }
  667. }
  668. }
  669. //// Generate face normals
  670. struct FaceVertex
  671. {
  672. Vector3 normal = Vector3::ZERO;
  673. UINT32 outerIdx = -1;
  674. };
  675. FrameVector<Vector3> faceNormals(volume.outerFaces.size());
  676. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  677. {
  678. const Vector3& v0 = positions[volume.outerFaces[i].vertices[0]];
  679. const Vector3& v1 = positions[volume.outerFaces[i].vertices[1]];
  680. const Vector3& v2 = positions[volume.outerFaces[i].vertices[2]];
  681. Vector3 e0 = v1 - v0;
  682. Vector3 e1 = v2 - v0;
  683. // Make sure the normal is facing away from the center
  684. const Tetrahedron& tet = volume.tetrahedra[volume.outerFaces[i].tetrahedron];
  685. Vector3 center(BsZero);
  686. for(UINT32 j = 0; j < 4; j++)
  687. center += positions[tet.vertices[j]];
  688. center /= 4.0f;
  689. Vector3 normal = Vector3::normalize(e0.cross(e1));
  690. if (normal.dot(v0 - center) < 0.0f)
  691. normal = -normal;
  692. faceNormals[i] = normal;
  693. }
  694. //// Generate vertex normals
  695. FrameUnorderedMap<INT32, FaceVertex> faceVertices;
  696. for (auto& entry : edgeMap)
  697. {
  698. const Edge& edge = entry.second;
  699. auto accumulateNormalForEdgeVertex = [&](UINT32 v0Idx, UINT32 v1Idx)
  700. {
  701. auto iter = faceVertices.insert(std::make_pair(v0Idx, FaceVertex()));
  702. FaceVertex& accum = iter.first->second;
  703. const Vector3& v0 = positions[v0Idx];
  704. auto accumulateNormalForFace = [&](INT32 faceIdx, INT32 v2LocIdx)
  705. {
  706. const TetrahedronFace& face = volume.outerFaces[faceIdx];
  707. // Vertices on the face, that aren't the vertex we're calculating the normal for
  708. const Vector3& v1 = positions[v1Idx];
  709. const Vector3& v2 = positions[face.vertices[v2LocIdx]];
  710. // Weight the contribution to the normal based on the angle spanned by the triangle
  711. Vector3 e0 = Vector3::normalize(v1 - v0);
  712. Vector3 e1 = Vector3::normalize(v2 - v0);
  713. float weight = acos(e0.dot(e1));
  714. accum.normal += weight * faceNormals[faceIdx];
  715. };
  716. accumulateNormalForFace(edge.faces[0], entry.second.oppositeVerts[0]);
  717. accumulateNormalForFace(edge.faces[1], entry.second.oppositeVerts[1]);
  718. };
  719. accumulateNormalForEdgeVertex(entry.first.first, entry.first.second);
  720. accumulateNormalForEdgeVertex(entry.first.second, entry.first.first);
  721. }
  722. for (auto& entry : faceVertices)
  723. entry.second.normal.normalize();
  724. // For each face vertex, generate an outer vertex along its normal
  725. static const float ExtrapolationDistance = 5.0f;
  726. for(auto& entry : faceVertices)
  727. {
  728. entry.second.outerIdx = (UINT32)positions.size();
  729. Vector3 outerPos = positions[entry.first] + entry.second.normal * ExtrapolationDistance;
  730. positions.push_back(outerPos);
  731. }
  732. // Generate face data
  733. for (UINT32 i = 0; i < numOuterFaces; ++i)
  734. {
  735. const TetrahedronFace& face = volume.outerFaces[i];
  736. TetrahedronFaceData faceData;
  737. faceData.tetrahedron = face.tetrahedron;
  738. for (UINT32 j = 0; j < 3; j++)
  739. {
  740. const FaceVertex& faceVertex = faceVertices[face.vertices[j]];
  741. faceData.innerVertices[j] = face.vertices[j];
  742. faceData.outerVertices[j] = faceVertex.outerIdx;
  743. faceData.normals[j] = faceVertex.normal;
  744. }
  745. // Add a link on the source tetrahedron to the face data
  746. Tetrahedron& innerTet = volume.tetrahedra[face.tetrahedron];
  747. for(UINT32 j = 0; j < 4; j++)
  748. {
  749. if (innerTet.neighbors[j] == -1)
  750. {
  751. // Note: Not searching for opposite neighbor here. If tet. has multiple free faces then we
  752. // can't just pick the first one
  753. innerTet.neighbors[j] = (UINT32)volume.tetrahedra.size() + (UINT32)faces.size();
  754. break;
  755. }
  756. }
  757. // We need a way to project a point outside the tetrahedron volume onto an outer face, then calculate
  758. // triangle's barycentric coordinates. Use use the per-vertex normals to extrude the triangle face into
  759. // infinity.
  760. // Our point can be represented as:
  761. // p == a (p0 + t*v0) + b (p1 + t*v1) + c (p2 + t*v2)
  762. //
  763. // where a, b and c are barycentric coordinates,
  764. // p0, p1, p2 are the corners of the face
  765. // v0, v1, v2 are the vertex normals, per corner
  766. // t is the distance from the triangle to the point
  767. //
  768. // Essentially we're calculating the corners of a bigger triangle that's "t" units away from the
  769. // face, and its corners lie along the per-vertex normals. Point "p" will lie on that triangle, for which
  770. // we can then calculate barycentric coordinates normally.
  771. //
  772. // First we substitute: c = 1 - a - b
  773. // p == a (p0 + t v0) + b (p1 + t v1) + (1 - a - b) (p2 + t v2)
  774. // p == a (p0 + t v0) + b (p1 + t v1) + (p2 + t v2) - a (p2 + t v2) - b (p2 + t v2)
  775. // p == a (p0 - p2 + t v0 - t v2) + b (p1 - p2 + t v1 - t v2) + (p2 + t v2)
  776. //
  777. // And move everything to one side:
  778. // p - p2 - t v2 == a (p0 - p2 + t ( v0 - v2)) + b (p1 - p2 + t ( v1 - v2))
  779. // a (p0 - p2 + t ( v0 - v2)) + b (p1 - p2 + t ( v1 - v2)) - (p - p2 - t v2) == 0
  780. //
  781. // We rewrite it using:
  782. // Ap = p0 - p2
  783. // Av = v0 - v2
  784. // Bp = p1 - p2
  785. // Bv = v1 - v2
  786. // Cp = p - p2
  787. // Cv = -v2
  788. //
  789. // Which yields:
  790. // a (Ap + t Av) + b (Bp + t Bv) - (Cp + t Cv) == 0
  791. //
  792. // Which can be written in matrix form:
  793. //
  794. // M = {Ap + t Av, Bp + t Bv, Cp + t Cv}
  795. // a 0
  796. // M * [ b ] = [0]
  797. // -1 0
  798. //
  799. // From that we can tell that matrix M cannot be inverted, because if we multiply the zero vector with the
  800. // inverted matrix the result would be zero, and not [a, b, -1]. Since the matrix cannot be inverted
  801. // det(M) == 0.
  802. //
  803. // We can use that fact to calculate "t". After we have "t" we can calculate barycentric coordinates
  804. // normally.
  805. //
  806. // Solving equation det(M) == 0 yields a cubic in form:
  807. // p t^3 + q t^2 + r t + s = 0
  808. //
  809. // We'll convert this to monic form, by dividing by p:
  810. // t^3 + q/p t^2 + r/p t + s/p = 0
  811. //
  812. // Or if p ends up being zero, we end up with a quadratic instead:
  813. // q t^2 + r t + s = 0
  814. //
  815. // We want to create a matrix that when multiplied with the position, yields us the three coefficients,
  816. // which we can then use to solve for "t". For this we create a 4x3 matrix, where each row represents
  817. // a solution for one of the coefficients. We factor contributons to each coefficient whether they depend on
  818. // position x, y, z, or don't depend on position (row columns, in that order respectively).
  819. const Vector3& p0 = positions[faceData.innerVertices[0]];
  820. const Vector3& p1 = positions[faceData.innerVertices[1]];
  821. const Vector3& p2 = positions[faceData.innerVertices[2]];
  822. const Vector3& v0 = faceVertices[faceData.innerVertices[0]].normal;
  823. const Vector3& v1 = faceVertices[faceData.innerVertices[1]].normal;
  824. const Vector3& v2 = faceVertices[faceData.innerVertices[2]].normal;
  825. float p =
  826. v2.x * v1.y * v0.z -
  827. v1.x * v2.y * v0.z -
  828. v2.x * v0.y * v1.z +
  829. v0.x * v2.y * v1.z +
  830. v1.x * v0.y * v2.z -
  831. v0.x * v1.y * v2.z;
  832. 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;
  833. 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;
  834. 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;
  835. 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 +
  836. v1.y * v0.z * p2.x - v0.y * v1.z * p2.x - v2.x * v1.z * p0.y + v1.x * v2.z * p0.y +
  837. v2.x * v0.z * p1.y - v0.x * v2.z * p1.y - v1.x * v0.z * p2.y + v0.x * v1.z * p2.y +
  838. v2.x * v1.y * p0.z - v1.x * v2.y * p0.z - v2.x * v0.y * p1.z + v0.x * v2.y * p1.z +
  839. v1.x * v0.y * p2.z - v0.x * v1.y * p2.z;
  840. 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 -
  841. v1.y * p0.z + v2.y * p0.z + v0.y * p1.z - v2.y * p1.z - v0.y * p2.z + v1.y * p2.z;
  842. 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 +
  843. v1.x * p0.z - v2.x * p0.z - v0.x * p1.z + v2.x * p1.z + v0.x * p2.z - v1.x * p2.z;
  844. 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 -
  845. v1.x * p0.y + v2.x * p0.y + v0.x * p1.y - v2.x * p1.y - v0.x * p2.y + v1.x * p2.y;
  846. 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 +
  847. v1.z * p0.x * p2.y - v0.z * p1.x * p2.y - v2.y * p1.x * p0.z + v1.y * p2.x * p0.z +
  848. v2.x * p1.y * p0.z - v1.x * p2.y * p0.z + v2.y * p0.x * p1.z - v0.y * p2.x * p1.z -
  849. v2.x * p0.y * p1.z + v0.x * p2.y * p1.z - v1.y * p0.x * p2.z + v0.y * p1.x * p2.z +
  850. v1.x * p0.y * p2.z - v0.x * p1.y * p2.z;
  851. 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;
  852. 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;
  853. 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;
  854. float sw = p2.x * p1.y * p0.z - p1.x * p2.y * p0.z - p2.x * p0.y * p1.z +
  855. p0.x * p2.y * p1.z + p1.x * p0.y * p2.z - p0.x * p1.y * p2.z;
  856. faceData.transform[0][0] = qx;
  857. faceData.transform[0][1] = qy;
  858. faceData.transform[0][2] = qz;
  859. faceData.transform[0][3] = qw;
  860. faceData.transform[1][0] = rx;
  861. faceData.transform[1][1] = ry;
  862. faceData.transform[1][2] = rz;
  863. faceData.transform[1][3] = rw;
  864. faceData.transform[2][0] = sx;
  865. faceData.transform[2][1] = sy;
  866. faceData.transform[2][2] = sz;
  867. faceData.transform[2][3] = sw;
  868. // Unused
  869. faceData.transform[3][0] = 0.0f;
  870. faceData.transform[3][1] = 0.0f;
  871. faceData.transform[3][2] = 0.0f;
  872. faceData.transform[3][3] = 0.0f;
  873. if (fabs(p) > 0.00001f)
  874. {
  875. faceData.transform = faceData.transform * (1.0f / p);
  876. faceData.quadratic = false;
  877. }
  878. else // Quadratic
  879. {
  880. faceData.quadratic = true;
  881. }
  882. faces.push_back(faceData);
  883. }
  884. }
  885. else
  886. {
  887. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  888. {
  889. const TetrahedronFace& face = volume.outerFaces[i];
  890. TetrahedronFaceData faceData;
  891. for (UINT32 j = 0; j < 3; j++)
  892. {
  893. faceData.innerVertices[j] = face.vertices[j];
  894. faceData.outerVertices[j] = -1;
  895. faceData.normals[j] = Vector3::ZERO;
  896. }
  897. faceData.tetrahedron = face.tetrahedron;
  898. faceData.transform = Matrix4::IDENTITY;
  899. faceData.quadratic = false;
  900. faces.push_back(faceData);
  901. }
  902. }
  903. // Generate matrices
  904. UINT32 numOutputTets = (UINT32)volume.tetrahedra.size();
  905. tetrahedra.reserve(numOutputTets);
  906. //// For inner tetrahedrons
  907. for(UINT32 i = 0; i < (UINT32)numOutputTets; ++i)
  908. {
  909. TetrahedronData entry;
  910. entry.volume = volume.tetrahedra[i];
  911. // Generate a matrix that can be used for calculating barycentric coordinates
  912. // To determine a point within a tetrahedron, using barycentric coordinates, we use:
  913. // P = (P1 - P4) * a + (P2 - P4) * b + (P3 - P4) * c + P4
  914. //
  915. // Where P1, P2, P3, P4 are the corners of the tetrahedron.
  916. //
  917. // Expanded for each coordinate this is:
  918. // x = (x1 - x4) * a + (x2 - x4) * b + (x3 - x4) * c + x4
  919. // y = (y1 - y4) * a + (y2 - y4) * b + (y3 - y4) * c + y4
  920. // z = (z1 - z4) * a + (z2 - z4) * b + (z3 - z4) * c + z4
  921. //
  922. // In matrix form this is:
  923. // a
  924. // P = [P1 - P4, P2 - P4, P3 - P4, P4] [b]
  925. // c
  926. // 1
  927. //
  928. // Solved for barycentric coordinates:
  929. // a
  930. // [b] = Minv * P
  931. // c
  932. // 1
  933. //
  934. // Where Minv is the inverse of the matrix above.
  935. const Vector3& P1 = positions[volume.tetrahedra[i].vertices[0]];
  936. const Vector3& P2 = positions[volume.tetrahedra[i].vertices[1]];
  937. const Vector3& P3 = positions[volume.tetrahedra[i].vertices[2]];
  938. const Vector3& P4 = positions[volume.tetrahedra[i].vertices[3]];
  939. Vector3 E1 = P1 - P4;
  940. Vector3 E2 = P2 - P4;
  941. Vector3 E3 = P3 - P4;
  942. Matrix4 mat;
  943. mat.setColumn(0, Vector4(E1, 0.0f));
  944. mat.setColumn(1, Vector4(E2, 0.0f));
  945. mat.setColumn(2, Vector4(E3, 0.0f));
  946. mat.setColumn(3, Vector4(P4, 1.0f));
  947. entry.transform = mat.inverse();
  948. tetrahedra.push_back(entry);
  949. }
  950. }
  951. bs_frame_clear();
  952. }
  953. }}