BsLightProbes.cpp 39 KB

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