Inkscape
Vector Graphics Editor
Loading...
Searching...
No Matches
circle.cpp
Go to the documentation of this file.
1/*
4 * Authors:
5 * Marco Cecchetti <mrcekets at gmail.com>
6 * Krzysztof KosiƄski <tweenk.pl@gmail.com>
7 *
8 * Copyright 2008-2014 Authors
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it either under the terms of the GNU Lesser General Public
12 * License version 2.1 as published by the Free Software Foundation
13 * (the "LGPL") or, at your option, under the terms of the Mozilla
14 * Public License Version 1.1 (the "MPL"). If you do not alter this
15 * notice, a recipient may use your version of this file under either
16 * the MPL or the LGPL.
17 *
18 * You should have received a copy of the LGPL along with this library
19 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * You should have received a copy of the MPL along with this library
22 * in the file COPYING-MPL-1.1
23 *
24 * The contents of this file are subject to the Mozilla Public License
25 * Version 1.1 (the "License"); you may not use this file except in
26 * compliance with the License. You may obtain a copy of the License at
27 * http://www.mozilla.org/MPL/
28 *
29 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
30 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
31 * the specific language governing rights and limitations.
32 */
33
34#include <2geom/circle.h>
35#include <2geom/ellipse.h>
39
40namespace Geom {
41
43{
45 Rect bbox(_center - rr, _center + rr);
46 return bbox;
47}
48
50{
51 if (A == 0) {
52 THROW_RANGEERROR("square term coefficient == 0");
53 }
54
55 //std::cerr << "B = " << B << " C = " << C << " D = " << D << std::endl;
56
57 Coord b = B / A;
58 Coord c = C / A;
59 Coord d = D / A;
60
61 _center[X] = -b/2;
62 _center[Y] = -c/2;
63 Coord r2 = _center[X] * _center[X] + _center[Y] * _center[Y] - d;
64
65 if (r2 < 0) {
66 THROW_RANGEERROR("ray^2 < 0");
67 }
68
69 _radius = std::sqrt(r2);
70}
71
72void Circle::coefficients(Coord &A, Coord &B, Coord &C, Coord &D) const
73{
74 A = 1;
75 B = -2 * _center[X];
76 C = -2 * _center[Y];
78}
79
80std::vector<Coord> Circle::coefficients() const
81{
82 std::vector<Coord> c(4);
83 coefficients(c[0], c[1], c[2], c[3]);
84 return c;
85}
86
87
89{
91 return ret;
92}
93
95{
96 if (_radius == 0) {
97 THROW_RANGEERROR("degenerate circle does not have an inverse unit circle transform");
98 }
99
100 Zoom ret(1/_radius, Translate(-_center));
101 return ret;
102}
103
105{
106 Point p(_center);
107 p[X] += _radius;
108 return p;
109}
110
112 return _center + Point::polar(t) * _radius;
113}
114
116 Coord delta = (d == X ? std::cos(t) : std::sin(t));
117 return _center[d] + delta * _radius;
118}
119
120Coord Circle::timeAt(Point const &p) const {
121 if (_center == p) return 0;
122 return atan2(p - _center);
123}
124
126 return timeAt(p);
127}
128
129bool Circle::contains(Rect const &r) const
130{
131 for (unsigned i = 0; i < 4; ++i) {
132 if (!contains(r.corner(i))) return false;
133 }
134 return true;
135}
136
137bool Circle::contains(Circle const &other) const
138{
139 Coord cdist = distance(_center, other._center);
140 Coord rdist = fabs(_radius - other._radius);
141 return cdist <= rdist;
142}
143
144bool Circle::intersects(Line const &l) const
145{
146 // http://mathworld.wolfram.com/Circle-LineIntersection.html
147 Coord dr = l.vector().length();
148 Coord r = _radius;
149 Coord D = cross(l.initialPoint(), l.finalPoint());
150 Coord delta = r*r * dr*dr - D*D;
151 if (delta >= 0) return true;
152 return false;
153}
154
155bool Circle::intersects(Circle const &other) const
156{
157 Coord cdist = distance(_center, other._center);
158 Coord rsum = _radius + other._radius;
159 return cdist <= rsum;
160}
161
162
163std::vector<ShapeIntersection> Circle::intersect(Line const &l) const
164{
165 // http://mathworld.wolfram.com/Circle-LineIntersection.html
166 Coord dr = l.vector().length();
167 Coord dx = l.vector().x();
168 Coord dy = l.vector().y();
170 Coord delta = _radius*_radius * dr*dr - D*D;
171
172 std::vector<ShapeIntersection> result;
173 if (delta < 0) return result;
174 if (delta == 0) {
175 Coord ix = (D*dy) / (dr*dr);
176 Coord iy = (-D*dx) / (dr*dr);
177 Point ip(ix, iy); ip += _center;
178 result.emplace_back(timeAt(ip), l.timeAt(ip), ip);
179 return result;
180 }
181
182 Coord sqrt_delta = std::sqrt(delta);
183 Coord signmod = dy < 0 ? -1 : 1;
184
185 Coord i1x = (D*dy + signmod * dx * sqrt_delta) / (dr*dr);
186 Coord i1y = (-D*dx + fabs(dy) * sqrt_delta) / (dr*dr);
187 Point i1p(i1x, i1y); i1p += _center;
188
189 Coord i2x = (D*dy - signmod * dx * sqrt_delta) / (dr*dr);
190 Coord i2y = (-D*dx - fabs(dy) * sqrt_delta) / (dr*dr);
191 Point i2p(i2x, i2y); i2p += _center;
192
193 result.emplace_back(timeAt(i1p), l.timeAt(i1p), i1p);
194 result.emplace_back(timeAt(i2p), l.timeAt(i2p), i2p);
195 return result;
196}
197
198std::vector<ShapeIntersection> Circle::intersect(LineSegment const &l) const
199{
200 std::vector<ShapeIntersection> result = intersect(Line(l));
202 return result;
203}
204
205std::vector<ShapeIntersection> Circle::intersect(Circle const &other) const
206{
207 std::vector<ShapeIntersection> result;
208
209 if (*this == other) {
210 THROW_INFINITESOLUTIONS();
211 }
212 if (contains(other)) return result;
213 if (!intersects(other)) return result;
214
215 // See e.g. http://mathworld.wolfram.com/Circle-CircleIntersection.html
216 // Basically, we figure out where is the third point of a triangle
217 // with two points in the centers and with edge lengths equal to radii
218 Point cv = other._center - _center;
219 Coord d = cv.length();
220 Coord R = radius(), r = other.radius();
221
222 if (d == R + r) {
223 Point px = lerp(R / d, _center, other._center);
224 Coord T = timeAt(px), t = other.timeAt(px);
225 result.emplace_back(T, t, px);
226 return result;
227 }
228
229 // q is the distance along the line between centers to the perpendicular line
230 // that goes through both intersections.
231 Coord q = (d*d - r*r + R*R) / (2*d);
232 Point qp = lerp(q/d, _center, other._center);
233
234 // The triangle given by the points:
235 // _center, qp, intersection
236 // is a right triangle. Determine the distance between qp and intersection
237 // using the Pythagorean theorem.
238 Coord h = std::sqrt(R*R - q*q);
239 Point qd = (h/d) * cv.cw();
240
241 // now compute the intersection points
242 Point x1 = qp + qd;
243 Point x2 = qp - qd;
244
245 result.emplace_back(timeAt(x1), other.timeAt(x1), x1);
246 result.emplace_back(timeAt(x2), other.timeAt(x2), x2);
247 return result;
248}
249
254Circle::arc(Point const& initial, Point const& inner, Point const& final) const
255{
256 // TODO native implementation!
258 return e.arc(initial, inner, final);
259}
260
261bool Circle::operator==(Circle const &other) const
262{
263 if (_center != other._center) return false;
264 if (_radius != other._radius) return false;
265 return true;
266}
267
269{
270 D2<SBasis> B;
271 Linear bo = Linear(0, 2 * M_PI);
272
273 B[0] = cos(bo,4);
274 B[1] = sin(bo,4);
275
276 B = B * _radius + _center;
277
278 return B;
279}
280
281
282void Circle::fit(std::vector<Point> const& points)
283{
284 size_t sz = points.size();
285 if (sz < 2) {
286 THROW_RANGEERROR("fitting error: too few points passed");
287 }
288 if (sz == 2) {
289 _center = points[0] * 0.5 + points[1] * 0.5;
290 _radius = distance(points[0], points[1]) / 2;
291 return;
292 }
293
294 NL::LFMCircle model;
296
297 for (size_t i = 0; i < sz; ++i) {
298 fitter.append(points[i]);
299 }
300 fitter.update();
301
302 NL::Vector z(sz, 0.0);
303 model.instance(*this, fitter.result(z));
304}
305
306
307bool are_near(Circle const &a, Circle const &b, Coord eps)
308{
309 // to check whether no point on a is further than eps from b,
310 // we check two things:
311 // 1. if radii differ by more than eps, there is definitely a point that fails
312 // 2. if they differ by less, we check the centers. They have to be closer
313 // together if the radius differs, since the maximum distance will be
314 // equal to sum of radius difference and distance between centers.
315 if (!are_near(a.radius(), b.radius(), eps)) return false;
316 Coord adjusted_eps = eps - fabs(a.radius() - b.radius());
317 return are_near(a.center(), b.center(), adjusted_eps);
318}
319
320std::ostream &operator<<(std::ostream &out, Circle const &c)
321{
322 out << "Circle(" << c.center() << ", " << format_coord_nice(c.radius()) << ")";
323 return out;
324}
325
326} // end namespace Geom
327
328/*
329 Local Variables:
330 mode:c++
331 c-file-style:"stroustrup"
332 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
333 indent-tabs-mode:nil
334 fill-column:99
335 End:
336*/
337// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :
Circle shape.
Set of all points at a fixed distance from the center.
Definition circle.h:55
Point center() const
Definition circle.h:75
Point initialPoint() const
Definition circle.cpp:104
bool operator==(Circle const &other) const
Definition circle.cpp:261
bool intersects(Line const &l) const
Definition circle.cpp:144
EllipticalArc * arc(Point const &initial, Point const &inner, Point const &final) const
Definition circle.cpp:254
Zoom inverseUnitCircleTransform() const
Definition circle.cpp:94
std::vector< ShapeIntersection > intersect(Line const &other) const
Definition circle.cpp:163
Coord _radius
Definition circle.h:57
Coord valueAt(Coord t, Dim2 d) const
Definition circle.cpp:115
D2< SBasis > toSBasis() const
Definition circle.cpp:268
Point _center
Definition circle.h:56
Coord timeAt(Point const &p) const
Definition circle.cpp:120
Zoom unitCircleTransform() const
Definition circle.cpp:88
void fit(std::vector< Point > const &points)
Fit the circle to the passed points using the least squares method.
Definition circle.cpp:282
bool contains(Point const &p) const
Definition circle.h:94
Coord nearestTime(Point const &p) const
Definition circle.cpp:125
Coord radius() const
Definition circle.h:77
std::vector< Coord > coefficients() const
Definition circle.cpp:80
void setCoefficients(Coord A, Coord B, Coord C, Coord D)
Definition circle.cpp:49
Rect boundsFast() const
Definition circle.cpp:42
Point pointAt(Coord t) const
Definition circle.cpp:111
Adaptor that creates 2D functions from 1D ones.
Definition d2.h:55
Set of points with a constant sum of distances from two foci.
Definition ellipse.h:68
EllipticalArc * arc(Point const &ip, Point const &inner, Point const &fp)
Create an elliptical arc from a section of the ellipse.
Definition ellipse.cpp:226
Elliptical arc curve.
CPoint corner(unsigned i) const
Return the n-th corner of the rectangle.
Infinite line on a plane.
Definition line.h:53
Coord timeAt(Point const &p) const
Get a time value corresponding to a point.
Definition line.cpp:223
Point vector() const
Get the line's raw direction vector.
Definition line.h:132
Point finalPoint() const
Definition line.h:228
Point initialPoint() const
Definition line.h:225
Function that interpolates linearly between two values.
Definition linear.h:55
void instance(Circle &c, ConstVectorView const &coeff) const
Two-dimensional point that doubles as a vector.
Definition point.h:66
Coord length() const
Compute the distance from origin.
Definition point.h:118
constexpr Coord y() const noexcept
Definition point.h:106
constexpr Coord x() const noexcept
Definition point.h:104
constexpr Point cw() const
Return a point like this point but rotated +90 degrees.
Definition point.h:137
Axis aligned, non-empty rectangle.
Definition rect.h:92
Translation by a vector.
Definition transforms.h:115
Combination of a translation and uniform scale.
Definition transforms.h:292
double inner(valarray< double > const &x, valarray< double > const &y)
Css & result
double c[8][4]
Ellipse shape.
Elliptical arc curve.
constexpr Coord lerp(Coord t, Coord a, Coord b)
Numerically stable linear interpolation.
Definition coord.h:97
Dim2
2D axis enumeration (X or Y).
Definition coord.h:48
double Coord
Floating point type used to store coordinates.
Definition coord.h:76
@ Y
Definition coord.h:48
@ X
Definition coord.h:48
Various utility functions.
Definition affine.h:22
SBasisN< n > cos(LinearN< n > bo, int k)
std::ostream & operator<<(std::ostream &os, const Bezier &b)
Definition bezier.h:372
Angle distance(Angle const &a, Angle const &b)
Definition angle.h:163
double atan2(Point const &p)
@ intersects
Definition geom.cpp:16
std::string format_coord_nice(Coord x)
Definition coord.cpp:89
void filter_line_segment_intersections(std::vector< ShapeIntersection > &xs, bool a=false, bool b=true)
Removes intersections outside of the unit interval.
Definition line.cpp:287
Piecewise< SBasis > cross(Piecewise< D2< SBasis > > const &a, Piecewise< D2< SBasis > > const &b)
SBasisN< n > sin(LinearN< n > bo, int k)
bool are_near(Affine const &a1, Affine const &a2, Coord eps=EPSILON)
int delta