1 package nl.tudelft.simulation.language.d2;
2
3 import java.awt.geom.Point2D;
4
5 /**
6 * The Circle class presents a number of mathematical utility functions for circles. For now, the class only implements static
7 * helper methods. No instances of the class should be made.
8 * <p>
9 * Copyright (c) 2003-2023 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
10 * for project information <a href="https://simulation.tudelft.nl/" target="_blank"> https://simulation.tudelft.nl</a>. The DSOL
11 * project is distributed under a three-clause BSD-style license, which can be found at
12 * <a href="https://https://simulation.tudelft.nl/dsol/docs/latest/license.html" target="_blank">
13 * https://https://simulation.tudelft.nl/dsol/docs/latest/license.html</a>.
14 * </p>
15 * @author <a href="http://tudelft.nl/averbraeck">Alexander Verbraeck</a>
16 */
17 public final class Circle
18 {
19 /**
20 * constructs a new Circle.
21 */
22 private Circle()
23 {
24 // unreachable code
25 }
26
27 /**
28 * Elegant intersection algorithm from http://astronomy.swin.edu.au/~pbourke/geometry/2circle/.
29 * @param center0 Point2D; the center of the first circle
30 * @param radius0 double; the radius of the first circle
31 * @param center1 Point2D; the center of the second circle
32 * @param radius1 double; the radius of the second circle
33 * @return the intersection
34 */
35 public static Point2D[] intersection(final Point2D center0, final double radius0, final Point2D center1,
36 final double radius1)
37 {
38 double distance = center0.distance(center1);
39 double x0 = center0.getX();
40 double x1 = center1.getX();
41 double y0 = center0.getY();
42 double y1 = center1.getY();
43 Point2D[] result;
44 if ((distance > radius0 + radius1) || (distance < Math.abs(radius0 - radius1)))
45 {
46 return new Point2D.Double[0];
47 }
48 double a = (radius0 * radius0 - radius1 * radius1 + distance * distance) / (2 * distance);
49 double h = Math.sqrt(radius0 * radius0 - a * a);
50 double x2 = x0 + ((a / distance) * (x1 - x0));
51 double y2 = y0 + ((a / distance) * (y1 - y0));
52 if (distance == radius0 + radius1)
53 {
54 result = new Point2D.Double[1];
55 result[0] = new Point2D.Double(x2, y2);
56 }
57 else
58 {
59 result = new Point2D.Double[2];
60 result[0] = new Point2D.Double(x2 + h * (y1 - y0) / distance, y2 - h * (x1 - x0) / distance);
61 result[1] = new Point2D.Double(x2 - h * (y1 - y0) / distance, y2 + h * (x1 - x0) / distance);
62 }
63 return result;
64 }
65 }