MeshTools.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Include own header
  2. #include "MeshTools.hpp"
  3. // Include dependencies
  4. #include <math.h>
  5. void MeshTools::calculateNormals(const std::vector<Lib3MF::sPosition> verticesBuffer, const std::vector<Lib3MF::sTriangle> triangleBuffer, osg::ref_ptr<osg::Vec3Array> vertices, osg::ref_ptr<osg::Vec3Array> normals) {
  6. for (const Lib3MF::sTriangle triangle: triangleBuffer) {
  7. // Create osg vectors
  8. osg::Vec3 vertex[3] = {};
  9. for (char i = 0; i < 3; i++) {
  10. vertex[i] = osg::Vec3(verticesBuffer[triangle.m_Indices[i]].m_Coordinates[0], verticesBuffer[triangle.m_Indices[i]].m_Coordinates[1], verticesBuffer[triangle.m_Indices[i]].m_Coordinates[2]);
  11. }
  12. // Calculate normal
  13. osg::Vec3 edgeOne = vertex[1].operator-(vertex[0]);
  14. osg::Vec3 edgeTwo = vertex[2].operator-(vertex[0]);
  15. osg::Vec3 normal = edgeOne.operator^(edgeTwo);
  16. normal.normalize();
  17. // Store them
  18. for (int i = 0; i < 3; i++) {
  19. vertices->push_back(vertex[i]);
  20. normals->push_back(normal);
  21. }
  22. }
  23. }
  24. float MeshTools::angleBetween(osg::Vec3 a, osg::Vec3 b) {
  25. float normA = a.length();
  26. float normB = b.length();
  27. float dotProduct = a.operator*(b);
  28. return acos(dotProduct / (normA * normB));
  29. }
  30. float MeshTools::compensationLength(osg::Vec3 a, osg::Vec3 b, float length) {
  31. osg::Matrix modifierRotation = osg::Matrix::rotate(b.x() * M_PI / 180, osg::Vec3(1.0f, 0.0f, 0.0f), b.y() * M_PI / 180, osg::Vec3(0.0f, 1.0f, 0.0f), b.z() * M_PI / 180, osg::Vec3(0.0f, 0.0f, 1.0f));
  32. osg::Vec3 newNormal = modifierRotation.preMult(a);
  33. newNormal.normalize();
  34. float angle = MeshTools::angleBetween(a, newNormal);
  35. return isnan(tan(angle) * length) ? 0.0f : tan(angle) * length;
  36. }