Fawkes API Fawkes Development Version
triangle.h
1
2/***************************************************************************
3 * triangle.h - triangle related utility methods
4 *
5 * Created: Sat Jul 11 18:04:19 2015
6 * Copyright 2015 Tim Niemueller [www.niemueller.de]
7 *
8 ****************************************************************************/
9
10/* This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version. A runtime exception applies to
14 * this software (see LICENSE.GPL_WRE file mentioned below for details).
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Library General Public License for more details.
20 *
21 * Read the full text in the LICENSE.GPL_WRE file in the doc directory.
22 */
23
24#ifndef _UTILS_MATH_TRIANGLE_H_
25#define _UTILS_MATH_TRIANGLE_H_
26
27namespace fawkes {
28
29/** Calculate triangle area.
30 * @param p0 first point of triangle
31 * @param p1 second point of triangle
32 * @param p2 third point of triangle
33 * @return area of triangle
34 */
35double
36triangle_area(const Eigen::Vector2f &p0, const Eigen::Vector2f &p1, const Eigen::Vector2f &p2)
37{
38 return 1.f / 2.f
39 * (-p1[1] * p2[0] + p0[1] * (-p1[0] + p2[0]) + p0[0] * (p1[1] - p2[1]) + p1[0] * p2[1]);
40}
41
42/** Check if a triangle contains a point.
43 * A point is also considered to be contained if it is on the boundary
44 * of the triangle.
45 * @param p0 first point of triangle
46 * @param p1 second point of triangle
47 * @param p2 third point of triangle
48 * @param p point to check with respect to the given triangle
49 * @return true if the point is within or on the triangle boundaries
50 */
51bool
52triangle_contains(const Eigen::Vector2f &p0,
53 const Eigen::Vector2f &p1,
54 const Eigen::Vector2f &p2,
55 const Eigen::Vector2f &p)
56{
57 double area_2 = 2. * triangle_area(p0, p1, p2);
58
59 double s =
60 1. / area_2 * (p0[1] * p2[0] - p0[0] * p2[1] + (p2[1] - p0[1]) * p[0] + (p0[0] - p2[0]) * p[1]);
61 if (s < 0)
62 return false;
63
64 double t =
65 1. / area_2 * (p0[0] * p1[1] - p0[1] * p1[0] + (p0[1] - p1[1]) * p[0] + (p1[0] - p0[0]) * p[1]);
66 if (t < 0)
67 return false;
68
69 return s + t <= 1.;
70}
71
72} // end namespace fawkes
73
74#endif
Fawkes library namespace.
double triangle_area(const Eigen::Vector2f &p0, const Eigen::Vector2f &p1, const Eigen::Vector2f &p2)
Calculate triangle area.
Definition: triangle.h:36
bool triangle_contains(const Eigen::Vector2f &p0, const Eigen::Vector2f &p1, const Eigen::Vector2f &p2, const Eigen::Vector2f &p)
Check if a triangle contains a point.
Definition: triangle.h:52