Add polygon area & inertia computation functions
This commit is contained in:
parent
b8ac384770
commit
4439218141
1 changed files with 43 additions and 0 deletions
43
libs/cg/include/psemek/cg/area.hpp
Normal file
43
libs/cg/include/psemek/cg/area.hpp
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
#pragma once
|
||||
|
||||
#include <psemek/geom/point.hpp>
|
||||
#include <psemek/geom/vector.hpp>
|
||||
|
||||
namespace psemek::cg
|
||||
{
|
||||
|
||||
template <typename Iterator>
|
||||
auto polygon_area(Iterator begin, Iterator end)
|
||||
{
|
||||
using scalar_type = std::remove_cvref_t<decltype((*begin)[0])>;
|
||||
scalar_type result{};
|
||||
|
||||
using point_type = std::remove_cvref_t<decltype(*begin)>;
|
||||
auto origin = point_type::zero();
|
||||
|
||||
for (auto it = begin, prev = std::prev(end); it != end; prev = it++)
|
||||
{
|
||||
result += geom::volume(origin, *prev, *it);
|
||||
}
|
||||
|
||||
return result / scalar_type{2};
|
||||
}
|
||||
|
||||
template <typename Iterator, typename Point>
|
||||
auto polygon_inertia(Iterator begin, Iterator end, Point const & origin)
|
||||
{
|
||||
using scalar_type = std::remove_cvref_t<decltype((*begin)[0])>;
|
||||
scalar_type result{};
|
||||
|
||||
for (auto it = begin, prev = std::prev(end); it != end; prev = it++)
|
||||
{
|
||||
auto const v0 = *prev - origin;
|
||||
auto const v1 = *it - origin;
|
||||
result += (v1[1] - v0[1]) * (v0[0] * v0[0] * v0[0] + v0[0] * v0[0] * v1[0] + v0[0] * v1[0] * v1[0] + v1[0] * v1[0] * v1[0]);
|
||||
result -= (v1[0] - v0[0]) * (v0[1] * v0[1] * v0[1] + v0[1] * v0[1] * v1[1] + v0[1] * v1[1] * v1[1] + v1[1] * v1[1] * v1[1]);
|
||||
}
|
||||
|
||||
return result / scalar_type{12};
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue