1 // Boost.Geometry (aka GGL, Generic Geometry Library)
2
3 // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
4 // Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
5 // Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
6
7 // Use, modification and distribution is subject to the Boost Software License,
8 // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
9 // http://www.boost.org/LICENSE_1_0.txt)
10 //
11 // Custom Triangle Example
12
13 #include <iostream>
14
15 #include <boost/array.hpp>
16
17 #include <boost/geometry/algorithms/area.hpp>
18 #include <boost/geometry/algorithms/centroid.hpp>
19 #include <boost/geometry/geometries/point_xy.hpp>
20 #include <boost/geometry/geometries/register/ring.hpp>
21 #include <boost/geometry/strategies/strategies.hpp>
22 #include <boost/geometry/io/dsv/write.hpp>
23
24
25 struct triangle : public boost::array<boost::geometry::model::d2::point_xy<double>, 4>
26 {
closetriangle27 inline void close()
28 {
29 (*this)[3] = (*this)[0];
30 }
31 };
32
33
34 // Register triangle as a ring
35 BOOST_GEOMETRY_REGISTER_RING(triangle)
36
37
38 // Specializations of algorithms, where useful. If not specialized the default ones
39 // (for linear rings) will be used for triangle. Which is OK as long as the triangle
40 // is closed, that means, has 4 points (the last one being the first).
41 namespace boost { namespace geometry {
42
43 template<>
area(const triangle & t)44 inline double area<triangle>(const triangle& t)
45 {
46 /* C
47 / \
48 / \
49 A-----B
50
51 ((Bx - Ax) * (Cy - Ay)) - ((Cx - Ax) * (By - Ay))
52 -------------------------------------------------
53 2
54 */
55
56 return 0.5 * ((t[1].x() - t[0].x()) * (t[2].y() - t[0].y())
57 - (t[2].x() - t[0].x()) * (t[1].y() - t[0].y()));
58 }
59
60 }} // namespace boost::geometry
61
main()62 int main()
63 {
64 triangle t;
65
66 t[0].x(0);
67 t[0].y(0);
68 t[1].x(5);
69 t[1].y(0);
70 t[2].x(2.5);
71 t[2].y(2.5);
72
73 t.close();
74
75 std::cout << "Triangle: " << boost::geometry::dsv(t) << std::endl;
76 std::cout << "Area: " << boost::geometry::area(t) << std::endl;
77
78 boost::geometry::model::d2::point_xy<double> c;
79 boost::geometry::centroid(t, c);
80 std::cout << "Centroid: " << boost::geometry::dsv(c) << std::endl;
81
82 return 0;
83 }
84