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