How to generate delaunay by some 3D coplanar vertices By CGAL - c++

I'm new in developing with cgal library,I have tried the following code to generate delaunay in 2D.
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Constrained_Delaunay_triangulation_2.h>
#include <CGAL/Delaunay_triangulation_2.h>
#include <cassert>
#include <iostream>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Delaunay_triangulation_2<K> Triangulation;
typedef Triangulation::Point Point;
int main()
{
std::vector<Point> PL;
PL.push_back(Point(0, 0));
PL.push_back(Point(1, 0));
PL.push_back(Point(1, 1));
PL.push_back(Point(0, 1));
auto a = PL.begin();
Triangulation T;
T.insert(PL.begin(),PL.end());
Triangulation::Finite_faces_iterator Finite_face_iterator;
for (Finite_face_iterator = T.finite_faces_begin(); Finite_face_iterator != T.finite_faces_end(); ++Finite_face_iterator)
{
std::cerr << T.triangle(Finite_face_iterator) << std::endl;
}
return 0;
}
those code output two faces,and if the vertices change to 3D like
Point(0,0,0),
Point(1,0,0),
Point(1,1,0),
Point(0,1,0)
those four vertices are in the same plane,how can I output two faces not intersected by CGAL?

You can use the Delaunay_triangulation_3 class for this purpose. It handles coplanar points as a special case of dimension 2. All your points must be exactly coplanar, then.
Another option is to use Delaunay_triangulation_2, by projecting your points to the plane they belong. This would handle points that are almost coplanar.

Related

Shrink/Expand the outline of a polygon with holes

I want to expand/shrink a polygon with holes using boost::polygon. So to clarify that a bit, I have a single data structure
boost::polygon::polygon_with_holes_data<int> inPoly
where inPoly contains data that describe a rectangular outline and a triangle which forms the hole within this rectangle (in picture below this is the left, black drawing).
Now I want to
a) expand the whole stuff so that the rectangle becomes bigger and the hole becomes smaller (resulting in the red polygon in image below) or
b) shrink it so that the rectangle becomes smaller and the hole bigger (resulting in the green image below).
The corners don't necessarily need to be straight, the also can be rounded or somehow "rough".
My question: how can this be done using boost::polygon?
Thanks!
I answered this Expand polygons with boost::geometry?
And yes you can teach Boost Geometry to act on Boost Polygon types:
#include <boost/geometry/geometries/adapted/boost_polygon.hpp>
I came up with a test polygon like you described:
boost::polygon::polygon_with_holes_data<int> inPoly;
bg::read_wkt("POLYGON ((0 0,0 1000,1000 1000,1000 0,0 0),(100 100,900 100,500 700,100 100))", inPoly);
Now, apparently we can't just buffer on the adapted polygon, nor can we bg::assign or bg::convert directly. So, I came up with an ugly workaround of converting to WKT and back. And then you can do the buffer, and conver back similarly.
It's not very elegant, but it does work:
poly in;
bg::read_wkt(boost::lexical_cast<std::string>(bg::wkt(inPoly)), in);
Full Demo
Include SVG output:
Live On Coliru
#include <boost/polygon/polygon.hpp>
#include <boost/polygon/polygon_set_data.hpp>
#include <boost/polygon/polygon_with_holes_data.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/strategies/buffer.hpp>
#include <boost/geometry/algorithms/buffer.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/geometry/geometries/multi_polygon.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/adapted/boost_polygon.hpp>
#include <fstream>
namespace bp = boost::polygon;
namespace bg = boost::geometry;
using P = bp::polygon_with_holes_data<int>;
using PS = bp::polygon_set_data<int>;
using coordinate_type = bg::coordinate_type<P>::type;
int main() {
P inPoly, grow, shrink;
bg::read_wkt("POLYGON ((0 0,0 1000,1000 1000,1000 0,0 0),(100 100,900 100,500 700,100 100))", inPoly);
{
// define our boost geometry types
namespace bs = bg::strategy::buffer;
namespace bgm = bg::model;
using pt = bgm::d2::point_xy<coordinate_type>;
using poly = bgm::polygon<pt>;
using mpoly = bgm::multi_polygon<poly>;
// define our buffering strategies
using dist = bs::distance_symmetric<coordinate_type>;
bs::side_straight side_strategy;
const int points_per_circle = 12;
bs::join_round join_strategy(points_per_circle);
bs::end_round end_strategy(points_per_circle);
bs::point_circle point_strategy(points_per_circle);
poly in;
bg::read_wkt(boost::lexical_cast<std::string>(bg::wkt(inPoly)), in);
for (auto [offset, output_p] : { std::tuple(+15, &grow), std::tuple(-15, &shrink) }) {
mpoly out;
bg::buffer(in, out, dist(offset), side_strategy, join_strategy, end_strategy, point_strategy);
assert(out.size() == 1);
bg::read_wkt(boost::lexical_cast<std::string>(bg::wkt(out.front())), *output_p);
}
}
{
std::ofstream svg("output.svg");
using pt = bg::model::d2::point_xy<coordinate_type>;
boost::geometry::svg_mapper<pt> mapper(svg, 400, 400);
mapper.add(inPoly);
mapper.add(grow);
mapper.add(shrink);
mapper.map(inPoly, "fill-opacity:0.3;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2");
mapper.map(grow, "fill-opacity:0.05;fill:rgb(255,0,0);stroke:rgb(255,0,0);stroke-width:2");
mapper.map(shrink, "fill-opacity:0.05;fill:rgb(0,0,255);stroke:rgb(0,0,255);stroke-width:2");
}
}
The output.svg written:
More or less accidentally I found boost::polygon also provides a single function for that which is quite easy to use: boost::polygon::polygon_set_data offers a function resize() which is doing exactly what is described above. Using the additional, parameters corner_fill_arc and num_segments rounded corners can be created.
No idea why this function is located in boost::polygon::polygon_set_data and not in boost::polygon::polygon_with_holes_data which in my opinion would be the more logically place for such a function...

shortest path to all points of mesh

I am working on watertight meshes and what I am trying is to get the shortest path on the surface of the mesh from every vertex in the mesh to every other vertex in the mesh.
E.g. when there are 100 vertices in the mesh i would get 100X100 distances and I want to store those in an 100x100 distance Matrix.
I use CGAL (and therefore also BOOST) and I have nearly no experience in both of them.
This is what i have so far:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iterator>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Random.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/Polyhedron_items_with_id_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/Surface_mesh_shortest_path.h>
#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>
#include <CGAL/boost/graph/iterator.h>
#include "boost/multi_array.hpp"
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Polyhedron_3<Kernel, CGAL::Polyhedron_items_with_id_3> Polyhedron_3;
typedef CGAL::Surface_mesh_shortest_path_traits<Kernel, Polyhedron_3> Traits;
typedef CGAL::Surface_mesh_shortest_path<Traits> Surface_mesh_shortest_path;
typedef Surface_mesh_shortest_path::Shortest_path_result Shortest_path_result;
typedef boost::graph_traits<Polyhedron_3> Graph_traits;
typedef Graph_traits::vertex_iterator vertex_iterator;
typedef Graph_traits::vertex_descriptor vertex_desc;
typedef Graph_traits::face_iterator face_iterator;
typedef boost::multi_array<double, 2> distArray;
typedef distArray::index distArrayIndex;
class DistanceMeasure {
public:
static distArray getDistances(Polyhedron_3 p);
};
as my header file and:
#include "DistanceMeasure.h"
distArray DistanceMeasure::getDistances(Polyhedron_3 p) {
distArray dists(boost::extents[p.size_of_vertices()][p.size_of_vertices()]);
// pick up a random face
CGAL::set_halfedgeds_items_id(p);
vertex_iterator pit = vertices(p).first;
// construct a shortest path query object and add a source point
Surface_mesh_shortest_path shortest_paths(p);
//add all points from p to the source points
for ( pit = vertices(p).first; pit != vertices(p).end(); pit++)
shortest_paths.add_source_point(*pit);
//for all points in p get distance to all the other points
vertex_iterator vit, vit_end;
for ( boost::tie(vit, vit_end) = vertices(p);
vit != vit_end; ++vit)
{
//get distances
Shortest_path_result res = shortest_paths.shortest_distance_to_source_points(*vit);
//iterate over all query results
Surface_mesh_shortest_path::Source_point_iterator spit;
int count = 0;
for(spit = res.second; spit != shortest_paths.source_points_end(); spit++) {
count++;
}
}
return dists;
}
for my source file.
In my unterstanding i woult get the distances to all the other points in res and can iterate over them in
for(spit = res.second; spit != shortest_paths.source_points_end(); spit++) {
count++;
}
Therefore i got 2 questions:
First:
Am I getting this right? Do i have all the distances in res?
And second:
How do I get the id's of the vertices and distances to them in my result (and also from spit) to be able to identify them and store their distance in the dists array.
What I thought so far is, that maybe the order is in the order I put the points into the source points.
When I run it with e.g. 100 vertices and use count to count the number of vertices in res I woult get.
100
99
98
97
96
95
..
2
1
I thought that this might be because CGAL does not compute a distance twice.
Still I am not sure about the indexes.
Thank you for your Answers
Steffen
For everybody with a similar Problem:
I can't give a solution for the first Problem I stated but the Intersection Problem might be computed in CGAL with something like this:
http://doc.cgal.org/latest/AABB_tree/index.html

CGAL triangulation fails

I am starting to use CGAL to triangulate a set of points using the following code
#include <iostream>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Delaunay_triangulation_2.h>
#include <CGAL/Triangulation_vertex_base_with_info_2.h>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Triangulation_vertex_base_2<K> Vb;
typedef CGAL::Triangulation_face_base_2<K> Fb;
typedef CGAL::Triangulation_data_structure_2<Vb,Fb> Tds;
typedef CGAL::Delaunay_triangulation_2<K,Tds> Triangulation;
typedef Triangulation::Point Point;
typedef Triangulation::Triangulation_data_structure tds;
using namespace std;
void main()
{
Triangulation t;
t.insert(Point(0,0));
t.insert(Point(0,20));
t.insert(Point(30,15));
t.insert(Point(30,-15));
Triangulation::Finite_faces_iterator fib = t.finite_faces_begin(), it;
Triangulation::Finite_faces_iterator fie = t.finite_faces_end();
Triangulation::Triangle tri;
std::cout << "Triangular faces"<<endl;
for (it=fib; it!=fie; ++it)
{
tri = t.triangle(it);
std::cout<<tri[0]<<" "<<tri[1]<<" "<<tri[2]<<" "<<endl;
}
char c;
std::cin>>c;
}
This prints the faces as 0,20 0,0 30,15 and 0,0 30,-15 30,15. I am not satisfied with this output as the first triangle is completely inside the second. As I understand triangulation it should return 3 triangles and not just 2 covering the complex hull of my 4 input points, and there should be no overlapping triangles. Could someone explain what I am doing wrong ?
My ultimate goal is to triangulate a convex polygon under a minimum angle constraint (and by addin additional points to the set). Any CGAL code sample would be appreciated.
Thanks,
I don't think you quite understand the geometry going on here, or triangulation, so I've drawn up some pictures.
Here's your setup:
Here's the first triangle that the Delaunay_Triangulation_2 generated:
(0,20), (0,0), (30, 15)
And here's the second triangle generated:
(0,0) (30,-15) (30,15)
Clearly, neither triangle is contained within the other. Also, the union of the triangles, removing the shared edge, perfectly creates the convex hull of the points.
Also, given that you only have four points total, it is impossible to construct a triangulation of 3 triangles where none overlap, hence only 2 are created.

How to convert a voronoi diagram cropped by a rectangle (boundaing box) to a set of polygons?

I am very new to CGAL and recently I have been trying to use CGAL to compute Voronoi diagram cropped by a bounding box (rectangle) in a C++ code and I was successful with that. I took advantage of an available example code in CGAL documentation. Here is the code:
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Delaunay_triangulation_2.h>
#include <iterator>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::Point_2 Point_2;
typedef K::Iso_rectangle_2 Iso_rectangle_2;
typedef K::Segment_2 Segment_2;
typedef K::Ray_2 Ray_2;
typedef K::Line_2 Line_2;
typedef CGAL::Delaunay_triangulation_2<K> Delaunay_triangulation_2;
//A class to recover Voronoi diagram from stream.
//Rays, lines and segments are cropped to a rectangle
//so that only segments are stored
struct Cropped_voronoi_from_delaunay{
std::list<Segment_2> m_cropped_vd;
Iso_rectangle_2 m_bbox;
Cropped_voronoi_from_delaunay(const Iso_rectangle_2& bbox):m_bbox(bbox){}
template <class RSL>
void crop_and_extract_segment(const RSL& rsl){
CGAL::Object obj = CGAL::intersection(rsl,m_bbox);
const Segment_2* s=CGAL::object_cast<Segment_2>(&obj);
if (s) m_cropped_vd.push_back(*s);
}
void operator<<(const Ray_2& ray) { crop_and_extract_segment(ray); }
void operator<<(const Line_2& line) { crop_and_extract_segment(line); }
void operator<<(const Segment_2& seg){ crop_and_extract_segment(seg); }
};
int main(){
//consider some points
std::vector<Point_2> points;
points.push_back(Point_2(0,0));
points.push_back(Point_2(1,1));
points.push_back(Point_2(0,1));
Delaunay_triangulation_2 dt2;
//insert points into the triangulation
dt2.insert(points.begin(),points.end());
//construct a rectangle
Iso_rectangle_2 bbox(-1,-1,2,2);
Cropped_voronoi_from_delaunay vor(bbox);
//extract the cropped Voronoi diagram
dt2.draw_dual(vor);
//print the cropped Voronoi diagram as segments
std::copy(vor.m_cropped_vd.begin(),vor.m_cropped_vd.end(),
std::ostream_iterator<Segment_2>(std::cout,"\n"));
}
Now I intend to generate the voronoi faces and convert them to polygons in order to use CGAL::intersection boolean operations on polygons. A similar question have been previously asked but no CGAL solution was provided.
Two sets of polygons need to be considered; first a set of complete voronoi cells within the bounding box that have no intersections with the cropping rectangle. Second set would consist of voronoi cells that are actually clipped by the bounding box.
Any comments or hints would be really appreciated.
There is some experimental code here: http://code.google.com/p/cgal-voronoi-cropping that crop a voronoi diagram to a rectangle, the result being a HDS. See main.cpp in the test directory.
The following will generate a random point cloud, find its Voronoi diagram, crop that diagram to the cloud's bounding box, and generate well-known text polygons.
//Finds the cropped Voronoi diagram of a set of points and saves it as WKT
//Compile with: g++ main.cpp -Wall -lCGAL -lgmp
//Author: Richard Barnes (rbarnes.org)
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/Regular_triangulation_filtered_traits_2.h>
#include <CGAL/Regular_triangulation_adaptation_traits_2.h>
#include <CGAL/Regular_triangulation_adaptation_policies_2.h>
#include <CGAL/Regular_triangulation_2.h>
#include <CGAL/Voronoi_diagram_2.h>
#include <CGAL/Boolean_set_operations_2.h>
#include <CGAL/bounding_box.h>
#include <CGAL/Polygon_2.h>
#include <iostream>
#include <cstdint>
//Used to convert otherwise infinite rays into looooong line segments
const int RAY_LENGTH = 1000;
typedef CGAL::Exact_predicates_exact_constructions_kernel K;
typedef CGAL::Regular_triangulation_filtered_traits_2<K> Traits;
typedef CGAL::Regular_triangulation_2<Traits> RT2;
typedef CGAL::Regular_triangulation_adaptation_traits_2<RT2> AT;
typedef CGAL::Regular_triangulation_degeneracy_removal_policy_2<RT2> DRP;
typedef CGAL::Voronoi_diagram_2<RT2, AT, DRP> VD;
int main(int argc, char **argv){
std::vector<RT2::Weighted_point> wpoints;
std::cout.precision(4);
std::cout.setf(std::ios::fixed);
//Generated random points
for(int i=0;i<100;i++)
//Weight of 0 gives a Voronoi diagram. Non-zero weight gives a power diagram
wpoints.push_back(RT2::Weighted_point(K::Point_2(rand()%100,rand()%100), 0));
//Find the bounding box of the points. This will be used to crop the Voronoi
//diagram later.
const K::Iso_rectangle_2 bbox = CGAL::bounding_box(wpoints.begin(), wpoints.end());
//Create a Regular Triangulation from the points
RT2 rt(wpoints.begin(), wpoints.end());
rt.is_valid();
//Wrap the triangulation with a Voronoi diagram adaptor. This is necessary to
//get the Voronoi faces.
VD vd(rt);
//CGAL often returns objects that are either segments or rays. This converts
//these objects into segments. If the object would have resolved into a ray,
//that ray is intersected with the bounding box defined above and returned as
//a segment.
const auto ConvertToSeg = [&](const CGAL::Object seg_obj, bool outgoing) -> K::Segment_2 {
//One of these will succeed and one will have a NULL pointer
const K::Segment_2 *dseg = CGAL::object_cast<K::Segment_2>(&seg_obj);
const K::Ray_2 *dray = CGAL::object_cast<K::Ray_2>(&seg_obj);
if (dseg) { //Okay, we have a segment
return *dseg;
} else { //Must be a ray
const auto &source = dray->source();
const auto dsx = source.x();
const auto dsy = source.y();
const auto &dir = dray->direction();
const auto tpoint = K::Point_2(dsx+RAY_LENGTH*dir.dx(),dsy+RAY_LENGTH*dir.dy());
if(outgoing)
return K::Segment_2(
dray->source(),
tpoint
);
else
return K::Segment_2(
tpoint,
dray->source()
);
}
};
//First line of WKT CSV output
std::cout<<"\"id\",\"geom\"\n";
int fnum = 0;
//Loop over the faces of the Voronoi diagram in some arbitrary order
for(VD::Face_iterator fit = vd.faces_begin(); fit!=vd.faces_end();++fit,fnum++){
CGAL::Polygon_2<K> pgon;
//Edge circulators traverse endlessly around a face. Make a note of the
//starting point so we know when to quit.
VD::Face::Ccb_halfedge_circulator ec_start = fit->ccb();
//Current location of the edge circulator
VD::Face::Ccb_halfedge_circulator ec = ec_start;
do {
//A half edge circulator representing a ray doesn't carry direction
//information. To get it, we take the dual of the dual of the half-edge.
//The dual of a half-edge circulator is the edge of a Delaunay triangle.
//The dual of the edge of Delaunay triangle is either a segment or a ray.
// const CGAL::Object seg_dual = rt.dual(ec->dual());
const CGAL::Object seg_dual = vd.dual().dual(ec->dual());
//Convert the segment/ray into a segment
const auto this_seg = ConvertToSeg(seg_dual, ec->has_target());
pgon.push_back(this_seg.source());
//If the segment has no target, it's a ray. This means that the next
//segment will also be a ray. We need to connect those two rays with a
//segment. The following accomplishes this.
if(!ec->has_target()){
const CGAL::Object nseg_dual = vd.dual().dual(ec->next()->dual());
const auto next_seg = ConvertToSeg(nseg_dual, ec->next()->has_target());
pgon.push_back(next_seg.target());
}
} while ( ++ec != ec_start ); //Loop until we get back to the beginning
//In order to crop the Voronoi diagram, we need to convert the bounding box
//into a polygon. You'd think there'd be an easy way to do this. But there
//isn't (or I haven't found it).
CGAL::Polygon_2<K> bpoly;
bpoly.push_back(K::Point_2(bbox.xmin(),bbox.ymin()));
bpoly.push_back(K::Point_2(bbox.xmax(),bbox.ymin()));
bpoly.push_back(K::Point_2(bbox.xmax(),bbox.ymax()));
bpoly.push_back(K::Point_2(bbox.xmin(),bbox.ymax()));
//Perform the intersection. Since CGAL is very general, it believes the
//result might be multiple polygons with holes.
std::list<CGAL::Polygon_with_holes_2<K>> isect;
CGAL::intersection(pgon, bpoly, std::back_inserter(isect));
//But we know better. The intersection of a convex polygon and a box is
//always a single polygon without holes. Let's assert this.
assert(isect.size()==1);
//And recover the polygon of interest
auto &poly_w_holes = isect.front();
auto &poly_outer = poly_w_holes.outer_boundary();
//Print the polygon as a WKT polygon
std::cout<<fnum<<", "
"\"POLYGON ((";
for(auto v=poly_outer.vertices_begin();v!=poly_outer.vertices_end();v++)
std::cout<<v->x()<<" "<<v->y()<<", ";
std::cout<<poly_outer.vertices_begin()->x()<<" "<<poly_outer.vertices_begin()->y()<<"))\"\n";
}
return 0;
}

CGAL 2D Delaunay Triangulation: How to get edges as vertex id pairs

I have a set of 2D points each with an associated id. (e.g. if the points are stored in an array, the id is the index into each point 0,....,n-1 ).
Now I create a Delaunay triangulation of these points and want to list down all the finite edges. For each edge, I would like to have the ids of the points represented by corresponding 2 vertices. Example: if there's an edge between point 0 and point 2 then (0,2). Is this possible?
#include <vector>
#include <CGAL\Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL\Delaunay_triangulation_2.h>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Delaunay_triangulation_2<K> Delaunay;
typedef K::Point_2 Point;
void load_points(std::vector<Point>& rPoints)
{
rPoints.push_back(Point(10,10)); // first point
rPoints.push_back(Point(60,10)); // second point
rPoints.push_back(Point(30,40)); // third point
rPoints.push_back(Point(40,80)); // fourth point
}
void main()
{
std::vector<Point> points;
load_points(points);
Delaunay dt;
dt.insert(points.begin(),points.end());
for(Delaunay::Finite_edges_iterator it = dt.finite_edges_begin(); it != dt.finite_edges_end(); ++it)
{
}
}
First you need to use a vertex type with info as in these examples. Then an edge is a pair containing a handle to a face as well as the index of the vertex in the face that is opposite to the edge.
if you have:
Delaunay::Edge e=*it;
indices you are looking for are:
int i1= e.first->vertex( (e.second+1)%3 )->info();
int i2= e.first->vertex( (e.second+2)%3 )->info();