2 Translated by Leonardo Fantascienza, downloaded from http://codepad.org/xGDCS3KO
4 A D implementation of the Voronoi Olden benchmark. Voronoi
5 generates a random set of points and computes a Voronoi diagram for
8 L. Guibas and J. Stolfi. "General Subdivisions and Voronoi Diagrams"
9 ACM Trans. on Graphics 4(2):74-123, 1985.
11 The Java version of voronoi (slightly) differs from the C version
12 in several ways. The C version allocates an array of 4 edges and
13 uses pointer addition to implement quick rotate operations. The
14 Java version does not use pointer addition to implement these
18 time voronoi1_d -n 100000 -v
22 import tango.stdc.stdio: printf, fprintf, sprintf, stderr;
23 import tango.stdc.stdlib: exit;
24 import tango.math.Math: sqrt, exp, log;
25 import tango.stdc.time: CLOCKS_PER_SEC, clock;
26 import Integer = tango.text.convert.Integer;
27 alias Integer.parse toInt;
29 import std.c.stdio: printf, fprintf, sprintf, stderr;
30 import std.c.stdlib: exit;
31 import std.math: sqrt, exp, log;
32 import std.c.time: CLOCKS_PER_SEC, clock;
33 import std.conv: toInt;
38 return clock() / cast(double)CLOCKS_PER_SEC;
44 int length() { return data.length; }
45 bool empty() { return data.length == 0; }
46 void push(T item) { data ~= item; }
50 data.length = data.length - 1;
57 * A class that represents a wrapper around a double value so
58 * that we can use it as an 'out' parameter. The java.lang.Double
61 final class MyDouble {
68 public char* toCString() {
69 auto repr = new char[64];
70 sprintf(repr.ptr, "%f", value);
77 * Vector Routines from CMU vision library.
78 * They are used only for the Voronoi Diagram, not the Delaunay Triagulation.
79 * They are slow because of large call-by-value parameters.
87 this(double xx, double yy) {
93 final public double X() {
97 final public double Y() {
101 final public double Norm() {
105 final public void setNorm(double d) {
109 final public char* toCString() {
110 auto repr = new char[256];
111 sprintf(repr.ptr, "%f %f", x, y);
115 final Vec2 circle_center(Vec2 b, Vec2 c) {
117 double d1 = vv1.magn();
119 Vec2 vv2 = vv1.times(0.5);
121 // there is no intersection point, the bisectors coincide.
124 Vec2 vv3 = b.sub(this);
125 Vec2 vv4 = c.sub(this);
126 double d3 = vv3.cprod(vv4) ;
127 double d2 = -2.0 * d3 ;
129 double d4 = vv5.dot(vv4);
130 Vec2 vv6 = vv3.cross();
131 Vec2 vv7 = vv6.times(d4 / d2);
137 * cprod: forms triple scalar product of [u,v,k], where k = u cross v
138 * (returns the magnitude of u cross v in space)
140 final double cprod(Vec2 v) {
141 return x * v.y - y * v.x;
144 /* V2_dot: vector dot product */
145 final double dot(Vec2 v) {
146 return x * v.x + y * v.y;
149 /* V2_times: multiply a vector by a scalar */
150 final Vec2 times(double c) {
151 return new Vec2(c * x, c * y);
154 /* V2_sum, V2_sub: Vector addition and subtraction */
155 final Vec2 sum(Vec2 v) {
156 return new Vec2(x + v.x, y + v.y);
159 final Vec2 sub(Vec2 v) {
160 return new Vec2(x - v.x,y - v.y);
163 /* V2_magn: magnitude of vector */
164 final double magn() {
165 return sqrt(x * x + y * y);
168 /* returns k X v (cross product). this is a vector perpendicular to v */
170 return new Vec2(y, -x);
176 * A class that represents a voronoi diagram. The diagram is represnted
177 * as a binary tree of points.
179 final class Vertex : Vec2 {
181 * The left and right child of the tree that represents the voronoi diagram.
186 * Seed value used during tree creation.
192 this(double x, double y) {
198 public void setLeft(Vertex l) {
202 public void setRight(Vertex r) {
206 public Vertex getLeft() {
210 public Vertex getRight() {
215 * Generate a voronoi diagram
217 static Vertex createPoints(int n, MyDouble curmax, int i) {
221 Vertex cur = new Vertex();
222 Vertex right = Vertex.createPoints(n / 2, curmax, i);
224 cur.x = curmax.value * exp(log(Vertex.drand()) / i);
225 cur.y = Vertex.drand();
226 cur.norm = cur.x * cur.x + cur.y * cur.y;
228 curmax.value = cur.X();
229 Vertex left = Vertex.createPoints(n / 2, curmax, i - 1);
235 * Builds delaunay triangulation.
237 Edge buildDelaunayTriangulation(Vertex extra) {
238 EdgePair retVal = buildDelaunay(extra);
239 return retVal.getLeft();
243 * Recursive delaunay triangulation procedure
244 * Contains modifications for axis-switching division.
246 EdgePair buildDelaunay(Vertex extra) {
247 EdgePair retval = null;
248 if (getRight() !is null && getLeft() !is null) {
249 // more than three elements; do recursion
250 Vertex minx = getLow();
253 EdgePair delright = getRight().buildDelaunay(extra);
254 EdgePair delleft = getLeft().buildDelaunay(this);
256 retval = Edge.doMerge(delleft.getLeft(), delleft.getRight(),
257 delright.getLeft(), delright.getRight());
259 Edge ldo = retval.getLeft();
260 while (ldo.orig() != minx) {
263 Edge rdo = retval.getRight();
264 while (rdo.orig() != maxx) {
268 retval = new EdgePair(ldo, rdo);
270 } else if (getLeft() is null) {
272 Edge a = Edge.makeEdge(this, extra);
273 retval = new EdgePair(a, a.symmetric());
275 // left, !right three points
276 // 3 cases: triangles of 2 orientations, and 3 points on a line. */
277 Vertex s1 = getLeft();
280 Edge a = Edge.makeEdge(s1, s2);
281 Edge b = Edge.makeEdge(s2, s3);
282 a.symmetric().splice(b);
283 Edge c = b.connectLeft(a);
284 if (s1.ccw(s3, s2)) {
285 retval = new EdgePair(c.symmetric(), c);
287 retval = new EdgePair(a, b.symmetric());
300 Vertex tleft, tright;
302 printf("X=%f Y=%f\n", X(), Y());
314 * Traverse down the left child to the end
320 while ((temp=tree.getLeft()) !is null)
325 /****************************************************************/
326 /* Geometric primitives
327 ****************************************************************/
328 bool incircle(Vertex b, Vertex c, Vertex d) {
329 // incircle, as in the Guibas-Stolfi paper
330 double adx, ady, bdx, bdy, cdx, cdy, dx, dy, anorm, bnorm, cnorm, dnorm;
332 Vertex loc_a,loc_b,loc_c,loc_d;
334 int donedx,donedy,donednorm;
336 dx = loc_d.X(); dy = loc_d.Y(); dnorm = loc_d.Norm();
338 adx = loc_a.X() - dx; ady = loc_a.Y() - dy; anorm = loc_a.Norm();
340 bdx = loc_b.X() - dx; bdy = loc_b.Y() - dy; bnorm = loc_b.Norm();
342 cdx = loc_c.X() - dx; cdy = loc_c.Y() - dy; cnorm = loc_c.Norm();
343 dret = (anorm - dnorm) * (bdx * cdy - bdy * cdx);
344 dret += (bnorm - dnorm) * (cdx * ady - cdy * adx);
345 dret += (cnorm - dnorm) * (adx * bdy - ady * bdx);
346 return (0.0 < dret) ? true : false;
349 bool ccw(Vertex b, Vertex c) {
350 // TRUE iff this, B, C form a counterclockwise oriented triangle
352 double xa,ya, xb, yb, xc, yc;
353 Vertex loc_a, loc_b, loc_c;
354 int donexa, doneya, donexb, doneyb, donexc, doneyc;
365 dret = (xa-xc) * (yb-yc) - (xb-xc) * (ya-yc);
366 return (dret > 0.0)? true : false;
370 * A routine used by the random number generator
372 static int mult(int p,int q) {
374 int CONST_m1 = 10000;
376 p1 = p / CONST_m1; p0 = p % CONST_m1;
377 q1 = q / CONST_m1; q0 = q % CONST_m1;
378 return ((p0 * q1 + p1 * q0) % CONST_m1) * CONST_m1 + p0 * q0;
382 * Generate the nth random number
384 static int skiprand(int seed, int n) {
390 static int random(int seed) {
391 int CONST_b = 31415821;
393 seed = mult(seed, CONST_b) + 1;
397 static double drand() {
398 double retval = (cast(double)(Vertex.seed = Vertex.random(Vertex.seed))) /
399 cast(double)2147483647;
406 * A class that represents the quad edge data structure which implements
407 * the edge algebra as described in the algorithm.
409 * Each edge contains 4 parts, or other edges. Any edge in the group may
410 * be accessed using a series of rotate and flip operations. The 0th
411 * edge is the canonical representative of the group.
413 * The quad edge class does not contain separate information for vertice
414 * or faces; a vertex is implicitly defined as a ring of edges (the ring
415 * is created using the next field).
419 * Group of edges that describe the quad edge
424 * The position of this edge within the quad list
429 * The vertex that this edge represents
434 * Contains a reference to a connected quad edge
439 * Create a new edge which.
441 this(Vertex v, Edge[] ql, int pos) {
448 * Create a new edge which.
450 this(Edge[] ql, int pos) {
455 * Create a string representation of the edge
457 public char* toCString() {
459 return vertex.toCString();
464 public static Edge makeEdge(Vertex o, Vertex d) {
465 Edge ql[] = new Edge[4];
466 ql[0] = new Edge(ql, 0);
467 ql[1] = new Edge(ql, 1);
468 ql[2] = new Edge(ql, 2);
469 ql[3] = new Edge(ql, 3);
482 public void setNext(Edge n) {
487 * Initialize the data (vertex) for the edge's origin
489 public void setOrig(Vertex o) {
494 * Initialize the data (vertex) for the edge's destination
496 public void setDest(Vertex d) {
497 symmetric().setOrig(d);
505 return this.rotate().oNext().rotate();
509 return this.rotateInv().oNext().rotate();
513 return this.oNext().symmetric();
517 return this.rotate().oNext().rotateInv();
521 return this.symmetric().oNext();
525 return this.symmetric().oNext().symmetric();
529 return this.rotateInv().oNext().rotateInv();
537 return symmetric().orig();
541 * Return the symmetric of the edge. The symmetric is the same edge
542 * with the opposite direction.
543 * @return the symmetric of the edge
546 return quadList[(listPos + 2) % 4];
550 * Return the rotated version of the edge. The rotated version is a
551 * 90 degree counterclockwise turn.
552 * @return the rotated version of the edge
555 return quadList[(listPos + 1) % 4];
559 * Return the inverse rotated version of the edge. The inverse
560 * is a 90 degree clockwise turn.
561 * @return the inverse rotated edge.
564 return quadList[(listPos + 3) % 4];
567 Edge nextQuadEdge() {
568 return quadList[(listPos + 1) % 4];
571 Edge connectLeft(Edge b) {
578 ans = Edge.makeEdge(t1, t2);
580 ans.symmetric().splice(b);
584 Edge connectRight(Edge b) {
586 Edge ans, oprevb, q1;
592 ans = Edge.makeEdge(t1, t2);
593 ans.splice(symmetric());
594 ans.symmetric().splice(oprevb);
598 /****************************************************************/
599 /* Quad-edge manipulation primitives
600 ****************************************************************/
603 Edge syme = symmetric();
604 Edge b = syme.oPrev();
607 Edge lnexttmp = a.lNext();
609 lnexttmp = b.lNext();
610 syme.splice(lnexttmp);
611 Vertex a1 = a.dest();
612 Vertex b1 = b.dest();
617 void splice(Edge b) {
618 Edge alpha = oNext().rotate();
619 Edge beta = b.oNext().rotate();
620 Edge t1 = beta.oNext();
621 Edge temp = alpha.oNext();
630 bool valid(Edge basel) {
631 Vertex t1 = basel.orig();
632 Vertex t3 = basel.dest();
634 return t1.ccw(t2, t3);
640 f = symmetric().oPrev();
641 symmetric().splice(f);
644 static EdgePair doMerge(Edge ldo, Edge ldi, Edge rdi, Edge rdo) {
646 Vertex t3 = rdi.orig();
647 Vertex t1 = ldi.orig();
648 Vertex t2 = ldi.dest();
650 while (t1.ccw(t2, t3)) {
665 Edge basel = rdi.symmetric().connectLeft(ldi);
667 Edge lcand = basel.rPrev();
668 Edge rcand = basel.oPrev();
669 Vertex t1 = basel.orig();
670 Vertex t2 = basel.dest();
672 if (t1 == rdo.orig())
674 if (t2 == ldo.orig())
675 ldo = basel.symmetric();
678 Edge t = lcand.oNext();
679 if (t.valid(basel)) {
680 Vertex v4 = basel.orig();
682 Vertex v1 = lcand.dest();
683 Vertex v3 = lcand.orig();
684 Vertex v2 = t.dest();
685 while (v1.incircle(v2,v3,v4)){
697 if (t.valid(basel)) {
698 Vertex v4 = basel.dest();
699 Vertex v1 = t.dest();
700 Vertex v2 = rcand.dest();
701 Vertex v3 = rcand.orig();
702 while (v1.incircle(v2, v3, v4)) {
712 bool lvalid = lcand.valid(basel);
714 bool rvalid = rcand.valid(basel);
715 if ((!lvalid) && (!rvalid))
716 return new EdgePair(ldo, rdo);
718 Vertex v1 = lcand.dest();
719 Vertex v2 = lcand.orig();
720 Vertex v3 = rcand.orig();
721 Vertex v4 = rcand.dest();
722 if (!lvalid || (rvalid && v1.incircle(v2, v3, v4))) {
723 basel = rcand.connectLeft(basel.symmetric());
724 rcand = basel.symmetric().lNext();
726 basel = lcand.connectRight(basel).symmetric();
727 lcand = basel.rPrev();
736 * Print the voronoi diagram and its dual, the delaunay triangle for the
739 void outputVoronoiDiagram() {
741 // Plot voronoi diagram edges with one endpoint at infinity.
743 Vec2 v21 = nex.dest();
744 Vec2 v22 = nex.orig();
745 Edge tmp = nex.oNext();
746 Vec2 v23 = tmp.dest();
747 Vec2 cvxvec = v21.sub(v22);
748 Vec2 center = v22.circle_center(v21, v23);
751 Vec2 vv1 = v22.sum(v22);
752 Vec2 vv2 = vv1.times(0.5);
753 Vec2 vv3 = center.sub(vv2);
754 double ln = 1.0 + vv3.magn();
755 double d1 = ln / cvxvec.magn();
756 vv1 = cvxvec.cross();
757 vv2 = vv1.times(d1) ;
758 vv3 = center.sum(vv2);
759 printf("Vedge %s %s\n", center.toCString(), vv3.toCString());
761 } while (nex != this);
763 // plot delaunay triangle edges and finite VD edges.
764 Stack!(Edge) edges = new Stack!(Edge);
766 pushRing(edges, seen);
767 printf("no. of edges = %d\n", edges.length);
768 while (!edges.empty()) {
769 Edge edge = edges.pop();
770 if (edge in seen && seen[edge]) {
774 Vertex v1 = prev.orig();
776 Vertex v2 = prev.dest();
779 printf("Dedge %s %s\n", v1.toCString(), v2.toCString());
780 Edge sprev = prev.symmetric();
781 Edge snex = sprev.oNext();
784 Vertex v3 = nex.dest();
785 Vertex v4 = snex.dest();
786 if (v1.ccw(v2, v3) != v1.ccw(v2, v4)) {
787 Vec2 v21 = prev.orig();
788 Vec2 v22 = prev.dest();
789 Vec2 v23 = nex.dest();
790 Vec2 vv1 = v21.circle_center(v22, v23);
794 Vec2 vv2 = v21.circle_center(v22, v23);
795 printf("Vedge %s %s\n", vv1.toCString(), vv2.toCString());
801 } while (prev != edge);
803 edge.symmetric().pushRing(edges, seen);
807 void pushRing(Stack!(Edge) stack, ref bool[Edge] seen) {
809 while (nex != this) {
810 if (!(nex in seen)) {
818 void pushNonezeroRing(Stack!(Edge) stack, ref bool[Edge] seen) {
820 while (nex != this) {
832 * A class that represents an edge pair
834 final class EdgePair {
838 this(Edge l, Edge r) {
843 public Edge getLeft() {
847 public Edge getRight() {
855 * The number of points in the diagram
857 private static int points = 0;
860 * Set to true to print informative messages
862 private static bool printMsgs = false;
865 * Set to true to print the voronoi diagram and its dual,
866 * the delaunay diagram
868 private static bool printResults = false;
871 * The main routine which creates the points and then performs
872 * the delaunay triagulation.
873 * @param args the command line parameters
875 public static void main(char[][] args) {
879 printf("Getting %d points\n", points);
881 auto start0 = myclock();
883 Vertex extra = Vertex.createPoints(1, new MyDouble(1.0), points);
884 Vertex point = Vertex.createPoints(points-1, new MyDouble(extra.X()),
886 auto end0 = myclock();
889 printf("Doing voronoi on %d nodes\n", points);
891 auto start1 = myclock();
892 Edge edge = point.buildDelaunayTriangulation(extra);
893 auto end1 = myclock();
896 edge.outputVoronoiDiagram();
899 printf("Build time %f\n", end0 - start0);
900 printf("Compute time %f\n", end1 - start1);
901 printf("Total time %f\n", end1 - start0);
908 * Parse the command line options.
909 * @param args the command line options.
911 private static final void parseCmdLine(char[][] args) {
914 while (i < args.length && args[i][0] == '-') {
915 char[] arg = args[i++];
919 points = toInt(args[i++]);
921 throw new Exception("-n requires the number of points");
922 } else if (arg == "-p") {
924 } else if (arg == "-v") {
926 } else if (arg == "-h") {
936 * The usage routine which describes the program options.
938 private static final void usage() {
939 fprintf(stderr, "usage: voronoi_d -n <points> [-p] [-m] [-h]\n");
940 fprintf(stderr, " -n the number of points in the diagram\n");
941 fprintf(stderr, " -p (print detailed results/messages - the voronoi diagram>)\n");
942 fprintf(stderr, " -v (print informative message)\n");
943 fprintf(stderr, " -h (this message)\n");
949 void main(char[][] args) {