c04_a_custom_triangle_example.cpp 2.2 KB

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