Debian Codegraph @

src/Diagrams/TwoD/Segment.hs

raw symbols SCIP
1 {-# LANGUAGE ConstraintKinds #-}
2 {-# LANGUAGE FlexibleContexts #-}
3 {-# LANGUAGE FlexibleInstances #-}
4 {-# LANGUAGE TypeFamilies #-}
5 {-# LANGUAGE ViewPatterns #-}
6 {-# LANGUAGE UndecidableInstances #-}
7
8 {-# OPTIONS_GHC -fno-warn-orphans #-}
9 -- Orphan Traced instances for Segment Closed V2 and FixedSegment V2.
10 -- They can't go in Traced; but they shouldn't really go in
11 -- Diagrams.Segment either because we only have Traced instances for
12 -- the special case of R2.
13 -----------------------------------------------------------------------------
14 -- |
15 -- Module : Diagrams.TwoD.Segment
16 -- Copyright : (c) 2012 diagrams-lib team (see LICENSE)
17 -- License : BSD-style (see LICENSE)
18 -- Maintainer : [email protected]
19 --
20 -- Segments in two dimensions are special since we may meaningfully
21 -- compute their point of intersection with a ray.
22 --
23 -----------------------------------------------------------------------------
24
25 module Diagrams.TwoD.Segment
26 ( -- * Segment intersections
27
28 intersectPointsS
29 , intersectPointsS'
30
31 -- * Closest point on a segment
32
33 , closestPoint
34 , closestPoint'
35 , closestDistance
36 , closestDistance'
37 , closestParam
38 , closestParam'
39
40 -- ** Low level functions
41 , segmentSegment
42 , lineSegment
43 )
44 where
45
46 import Control.Lens hiding (at, contains, transform, ( # ))
47 import Data.Maybe
48
49 import Diagrams.Core
50
51 import Diagrams.Direction
52 import Diagrams.Located
53 import Diagrams.Parametric
54 import Diagrams.Segment
55 import Diagrams.TwoD.Points
56 import Diagrams.TwoD.Segment.Bernstein
57 import Diagrams.TwoD.Transform
58 import Diagrams.TwoD.Types hiding (p2)
59 import Diagrams.TwoD.Vector
60
61 import Linear.Affine
62 import Linear.Metric
63
64 {- All instances of Traced should maintain the invariant that the list of
65 traces is sorted in increasing order.
66 -}
67
68 instance OrderedField n => Traced (Segment Closed V2 n) where
69 getTrace = getTrace . mkFixedSeg . (`at` origin)
70
71 instance OrderedField n => Traced (FixedSegment V2 n) where
72 getTrace seg = mkTrace $ \p v ->
73 mkSortedList . map (view _1) $ lineSegment defEps (v `at` p) seg
74
75 defEps :: Fractional n => n
76 defEps = 1e-8
77
78 -- | Compute the intersections between two fixed segments.
79 intersectPointsS :: OrderedField n => FixedSegment V2 n -> FixedSegment V2 n -> [P2 n]
80 intersectPointsS = intersectPointsS' defEps
81
82 -- | Compute the intersections between two segments using the given tolerance.
83 intersectPointsS' :: OrderedField n => n -> FixedSegment V2 n -> FixedSegment V2 n -> [P2 n]
84 intersectPointsS' eps s1 s2 = map (view _3) $ segmentSegment eps s1 s2
85
86 -- | Get the closest distance(s) from a point to a 'FixedSegment'.
87 closestDistance :: OrderedField n => FixedSegment V2 n -> P2 n -> [n]
88 closestDistance = closestDistance' defEps
89
90 -- | Get the closest distance(s) from a point to a 'FixedSegment' within given
91 -- tolerance.
92 closestDistance' :: OrderedField n => n -> FixedSegment V2 n -> P2 n -> [n]
93 closestDistance' eps seg p = map (distanceA p) $ closestPoint' eps seg p
94
95 -- | Get the closest point(s) on a 'FixedSegment' from a point.
96 closestPoint :: OrderedField n => FixedSegment V2 n -> P2 n -> [P2 n]
97 closestPoint = closestPoint' defEps
98
99 -- | Get the closest point(s) on a 'FixedSegment' from a point within given
100 -- tolerance.
101 closestPoint' :: OrderedField n => n -> FixedSegment V2 n -> P2 n -> [P2 n]
102 closestPoint' eps seg = map (seg `atParam`) . closestParam' eps seg
103
104 -- | Find the closest value(s) on the Bêzier to the given point.
105 closestParam :: OrderedField n => FixedSegment V2 n -> P2 n -> [n]
106 closestParam = closestParam' defEps
107
108 -- | Find the closest value(s) on the Bêzier to the given point within given
109 -- tolerance.
110 closestParam' :: OrderedField n => n -> FixedSegment V2 n -> P2 n -> [n]
111 closestParam' _ (FLinear p0 p1) p
112 | t < 0 = [0]
113 | t > 1 = [1]
114 | otherwise = [t]
115 where
116 vp = p .-. p0
117 v = p1 .-. p0
118 dp = vp `dot` v
119 t = dp / quadrance v
120 closestParam' eps cb (P (V2 px py)) = bezierFindRoot eps poly 0 1
121 where
122 (bx, by) = bezierToBernstein cb
123 bx' = bernsteinDeriv bx
124 by' = bernsteinDeriv by
125 poly = (bx - listToBernstein [px, px, px, px]) * bx'
126 + (by - listToBernstein [py, py, py, py]) * by'
127
128 ------------------------------------------------------------------------
129 -- Low level
130 ------------------------------------------------------------------------
131
132 -- | Return the intersection points with the parameters at which each segment
133 -- intersects.
134 segmentSegment :: OrderedField n => n -> FixedSegment V2 n -> FixedSegment V2 n -> [(n, n, P2 n)]
135 segmentSegment eps s1 s2 =
136 case (s1,s2) of
137 (FCubic{}, FCubic{}) -> map (\(t1,t2) -> (t1,t2, s1 `atParam` t1))
138 $ bezierClip eps s1 s2
139 (FCubic{}, FLinear{}) -> map flip12 $ linearSeg (segLine s2) s1
140 _ -> linearSeg (segLine s1) s2 -- s1 is linear
141 where
142 linearSeg l s = filter (inRange . view _1) $ lineSegment eps l s
143 flip12 (a,b,c) = (b,a,c)
144
145 -- | Return the intersection points with the parameters at which the line and segment
146 -- intersect.
147 lineSegment :: OrderedField n => n -> Located (V2 n) -> FixedSegment V2 n -> [(n, n, P2 n)]
148 lineSegment _ l1 p@(FLinear p0 p1)
149 = map (\(tl,tp) -> (tl, tp, p `atParam` tp))
150 . filter (inRange . snd) . maybeToList $ lineLine l1 (mkLine p0 p1)
151 lineSegment eps (viewLoc -> (p,r)) cb = map addPoint params
152 where
153 params = bezierFindRoot eps (listToBernstein $ cb' ^.. each . _y) 0 1
154 cb' = transform (inv (rotationTo $ dir r)) . moveOriginTo p $ cb
155 --
156 addPoint bt = (lt, bt, intersect)
157 where
158 intersect = cb `atParam` bt
159 lt = (cb' `atParam` bt) ^. _x / norm r
160
161 -- Adapted from from kuribas's cubicbezier package https://github.com/kuribas/cubicbezier
162
163 -- | Use the Bêzier clipping algorithm to return the parameters at which the
164 -- Bêzier curves intersect.
165 bezierClip :: OrderedField n => n -> FixedSegment V2 n -> FixedSegment V2 n -> [(n, n)]
166 bezierClip eps p_ q_ = filter (allOf both inRange) -- sometimes this returns NaN
167 $ go p_ q_ 0 1 0 1 0 False
168 where
169 go p q tmin tmax umin umax clip revCurves
170 | isNothing chopInterval = []
171
172 -- This check happens before the subdivision
173 -- test to avoid non-termination as values
174 -- transition to within epsilon.
175 | max (umax - umin) (tmax' - tmin') < eps =
176 if revCurves -- return parameters in correct order
177 then [ (avg umin umax, avg tmin' tmax') ]
178 else [ (avg tmin' tmax', avg umin umax ) ]
179
180 -- split the curve if there isn't enough reduction
181 | clip > 0.8 && clip' > 0.8 =
182 if tmax' - tmin' > umax - umin -- split the longest segment
183 then let (pl, pr) = p' `splitAtParam` 0.5
184 tmid = avg tmin' tmax'
185 in go q pl umin umax tmin' tmid clip' (not revCurves) ++
186 go q pr umin umax tmid tmax' clip' (not revCurves)
187 else let (ql, qr) = q `splitAtParam` 0.5
188 umid = avg umin umax
189 in go ql p' umin umid tmin' tmax' clip' (not revCurves) ++
190 go qr p' umid umax tmin' tmax' clip' (not revCurves)
191
192 -- iterate with the curves reversed.
193 | otherwise = go q p' umin umax tmin' tmax' clip' (not revCurves)
194 where
195 chopInterval = chopCubics p q
196 Just (tminChop, tmaxChop) = chopInterval
197 p' = section p tminChop tmaxChop
198 clip' = tmaxChop - tminChop
199 tmin' = tmax * tminChop + tmin * (1 - tminChop)
200 tmax' = tmax * tmaxChop + tmin * (1 - tmaxChop)
201
202 -- | Find the zero of a 1D Bêzier curve of any degree. Note that this
203 -- can be used as a Bernstein polynomial root solver by converting from
204 -- the power basis to the Bernstein basis.
205 bezierFindRoot :: OrderedField n
206 => n -- ^ The accuracy
207 -> BernsteinPoly n -- ^ the Bernstein coefficients of the polynomial
208 -> n -- ^ The lower bound of the interval
209 -> n -- ^ The upper bound of the interval
210 -> [n] -- ^ The roots found
211 bezierFindRoot eps p tmin tmax
212 -- If we generated the max number of roots and tmax is also a root
213 -- (which is not among the generated ones), there must in fact be an
214 -- infinite number of roots, so just include tmax.
215 | length roots == bernsteinDegree p && last roots /= tmax && abs (evaluateBernstein p tmax) <= eps
216 = roots ++ [tmax]
217 | otherwise = roots
218 where
219 -- Lazily take a number of roots at most the degree of the bernstein
220 -- polynomial, to avoid generating a ton of roots in the case of a
221 -- straight Bezier segment along the x-axis. See https://github.com/diagrams/diagrams-contrib/issues/91 .
222 roots = take (bernsteinDegree p) $ go p tmin tmax
223 go p tmin tmax
224 | isNothing chopInterval = []
225 | tmax' - tmin' < eps = [avg tmin' tmax']
226 | clip > 0.8 = let (p1, p2) = splitAtParam newP 0.5
227 tmid = tmin' + (tmax' - tmin') / 2
228 in go p1 tmin' tmid ++
229 go p2 tmid tmax'
230 | otherwise = bezierFindRoot eps newP tmin' tmax'
231 where
232 chopInterval = chopYs (bernsteinCoeffs p)
233 Just (tminChop, tmaxChop) = chopInterval
234 newP = section p tminChop tmaxChop
235 clip = tmaxChop - tminChop
236 tmin' = tmax * tminChop + tmin * (1 - tminChop)
237 tmax' = tmax * tmaxChop + tmin * (1 - tmaxChop)
238
239 ------------------------------------------------------------------------
240 -- Internal
241 ------------------------------------------------------------------------
242
243 -- | An approximation of the fat line for a cubic Bêzier segment. Returns
244 -- @(0,0)@ for a linear segment.
245 fatLine :: OrderedField n => FixedSegment V2 n -> (n,n)
246 fatLine (FCubic p0 p1 p2 p3)
247 = case (d1 > 0, d2 > 0) of
248 (True, True) -> (0, 0.75 * max d1 d2)
249 (False, False) -> (0.75 * min d1 d2, 0 )
250 (True, False) -> (4/9 * d2, 4/9 * d1 )
251 (False, True) -> (4/9 * d1, 4/9 * d2 )
252 where
253 d = lineDistance p0 p3
254 d1 = d p1; d2 = d p2
255 fatLine _ = (0,0)
256
257 chopYs :: OrderedField n => [n] -> Maybe (n, n)
258 chopYs ds = chopHull 0 0 points
259 where
260 points = zipWith mkP2 [fromIntegral i / fromIntegral n | i <- [0..n]] ds
261 n = length ds - 1
262
263 chopCubics :: OrderedField n => FixedSegment V2 n -> FixedSegment V2 n -> Maybe (n,n)
264 chopCubics p q@(FCubic q0 _ _ q3)
265 = chopHull dmin dmax dps
266 where
267 dps = zipWith mkP2 [0, 1/3, 2/3, 1] ds
268 ds = p ^.. each . to d
269 d = lineDistance q0 q3
270 --
271 (dmin,dmax) = fatLine q
272 chopCubics _ _ = Nothing
273
274 -- Reduce the interval which the intersection is known to lie in using the fat
275 -- line of one curve and convex hull of the points formed from the distance to
276 -- the thin line of the other
277 chopHull :: OrderedField n => n -> n -> [P2 n] -> Maybe (n, n)
278 chopHull dmin dmax dps = do
279 tL <- testBelow upper $ testBetween (head upper) $ testAbove lower
280 tR <- testBelow (reverse upper) $ testBetween (last upper) $ testAbove (reverse lower)
281 Just (tL, tR)
282 where
283 (upper, lower) = sortedConvexHull dps
284
285 testBelow (p1@(P (V2 _ y1)) : p2@(P (V2 _ y2)) : ps) continue
286 | y1 >= dmin = continue
287 | y1 > y2 = Nothing
288 | y2 < dmin = testBelow (p2:ps) continue
289 | otherwise = Just $ intersectPt dmin p1 p2
290 testBelow _ _ = Nothing
291
292 testBetween (P (V2 x y)) continue
293 | y <= dmax = Just x
294 | otherwise = continue
295
296 testAbove (p1@(P (V2 _ y1)) : p2@(P (V2 _ y2)) : ps)
297 | y1 < y2 = Nothing
298 | y2 > dmax = testAbove (p2:ps)
299 | y2 - y1 == 0 = Nothing -- Check this condition to prevent
300 -- division by zero in `intersectPt`.
301 | otherwise = Just $ intersectPt dmax p1 p2
302 testAbove _ = Nothing
303
304 -- find the x value where the line through the two points
305 -- intersect the line y=d. Note that `y2 - y1 != 0` due
306 -- to checks above.
307 intersectPt d (P (V2 x1 y1)) (P (V2 x2 y2)) =
308 x1 + (d - y1) * (x2 - x1) / (y2 - y1)
309
310
311
312 bezierToBernstein :: Fractional n => FixedSegment V2 n -> (BernsteinPoly n, BernsteinPoly n)
313 bezierToBernstein seg =
314 (listToBernstein $ map (view _x) coeffs, listToBernstein $ map (view _y) coeffs)
315 where coeffs = toListOf each seg
316
317 ------------------------------------------------------------------------
318 -- Lines
319 ------------------------------------------------------------------------
320
321 -- Could split this into a separate module.
322
323 -- | Returns @(a, b, c, d)@ such that @ax + by + c = 0@ is the line going through
324 -- @p1@ and @p2@ with @(a^2)/d + (b^2)/d = 1@. We delay the division by
325 -- @d@ as it may not be needed in all cases and @d@ may be zero.
326 lineEquation :: Floating n => P2 n -> P2 n -> (n, n, n, n)
327 lineEquation (P (V2 x1 y1)) (P (V2 x2 y2)) = (a, b, c, d)
328 where
329 c = -(x1*a + y1*b)
330 a = y1 - y2
331 b = x2 - x1
332 d = a*a + b*b
333
334 -- | Return the distance from a point to the line.
335 lineDistance :: (Ord n, Floating n) => P2 n -> P2 n -> P2 n -> n
336 lineDistance p1 p2 p3@(P (V2 x y))
337 -- I have included the check that d' <= 0 in case
338 -- there exists some d > 0 where sqrt d == 0. I don't
339 -- think this can happen as sqrt is at least recommended
340 -- to be within one value of correct for sqrt and near
341 -- zero values get bigger.
342 | d <= 0 || d' <= 0 = norm (p1 .-. p3)
343 | otherwise = (a*x + b*y + c) / d'
344 where
345 (a, b, c, d) = lineEquation p1 p2
346 d' = sqrt d
347
348 -- clockwise :: (Num n, Ord n) => V2 n -> V2 n -> Bool
349 -- clockwise a b = a `cross2` b <= 0
350
351 avg :: Fractional n => n -> n -> n
352 avg a b = (a + b)/2
353
354 lineLine :: (Fractional n, Eq n) => Located (V2 n) -> Located (V2 n) -> Maybe (n,n)
355 lineLine (viewLoc -> (p,r)) (viewLoc -> (q,s))
356 | x1 == 0 && x2 /= 0 = Nothing -- parallel
357 | otherwise = Just (x3 / x1, x2 / x1) -- intersecting or collinear
358 where
359 x1 = r × s
360 x2 = v × r
361 x3 = v × s
362 v = q .-. p
363
364 (×) :: Num n => V2 n -> V2 n -> n
365 (×) = cross2
366
367 mkLine :: InSpace v n (v n) => Point v n -> Point v n -> Located (v n)
368 mkLine p0 p1 = (p1 .-. p0) `at` p0
369
370 segLine :: InSpace v n (v n) => FixedSegment v n -> Located (v n)
371 segLine (FLinear p0 p1) = mkLine p0 p1
372 segLine (FCubic p0 _ _ p3) = mkLine p0 p3
373
374 -- This function uses `defEps`, but is used in functions
375 -- above that take an epsilon parameter. It would be nice
376 -- to clearify the meaning of each of these epsilons.
377 inRange :: (Fractional n, Ord n) => n -> Bool
378 inRange x = x < (1+defEps) && x > (-defEps)
379