Skip to content

Instantly share code, notes, and snippets.

@kayru
Created October 25, 2017 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kayru/b548a9e6c7fd64544031ca7660033b16 to your computer and use it in GitHub Desktop.
Save kayru/b548a9e6c7fd64544031ca7660033b16 to your computer and use it in GitHub Desktop.
TriangleBestFitPlane.cpp
bool calculate_best_fit_plane(const Vec3* points, u32 count, Vec3& out_center, Vec3& out_normal)
{
if (count < 3)
{
return false;
}
Vec3 center = Vec3(0.0f);
for (u32 i = 0; i < count; ++i)
{
center += points[i];
}
center /= (float)count;
out_center = center;
Vec3 normal = Vec3(0.0f);
const Vec3* prev = &points[count - 1];
for (u32 i = 0; i < count; ++i)
{
const Vec3* curr = &points[i];
normal.x += (prev->z + curr->z) * (prev->y - curr->y);
normal.y += (prev->x + curr->x) * (prev->z - curr->z);
normal.z += (prev->y + curr->y) * (prev->x - curr->x);
prev = curr;
}
out_normal = normalize(normal);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment