BsLightProbes.cpp 38 KB

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