Debian Codegraph @

src/Diagrams/TwoD/Offset.hs

raw symbols SCIP
1 {-# LANGUAGE ConstraintKinds #-}
2 {-# LANGUAGE FlexibleContexts #-}
3 {-# LANGUAGE GADTs #-}
4 {-# LANGUAGE StandaloneDeriving #-}
5 {-# LANGUAGE TemplateHaskell #-}
6 {-# LANGUAGE TypeFamilies #-}
7 {-# LANGUAGE TypeOperators #-}
8 {-# LANGUAGE UndecidableInstances #-}
9 {-# LANGUAGE ViewPatterns #-}
10
11 {-# OPTIONS_GHC -fno-warn-unused-imports #-}
12 -- for Data.Semigroup
13
14 -----------------------------------------------------------------------------
15 -- |
16 -- Module : Diagrams.TwoD.Offset
17 -- Copyright : (c) 2013 diagrams-lib team (see LICENSE)
18 -- License : BSD-style (see LICENSE)
19 -- Maintainer : [email protected]
20 --
21 -- Compute offsets to segments in two dimensions. More details can be
22 -- found in the manual at
23 -- <https://diagrams.github.io/doc/manual.html#offsets-of-segments-trails-and-paths>.
24 --
25 -----------------------------------------------------------------------------
26 module Diagrams.TwoD.Offset
27 (
28 -- * Offsets
29
30 offsetSegment
31
32 , OffsetOpts(..), offsetJoin, offsetMiterLimit, offsetEpsilon
33 , offsetTrail
34 , offsetTrail'
35 , offsetPath
36 , offsetPath'
37
38 -- * Expansions
39
40 , ExpandOpts(..), expandJoin, expandMiterLimit, expandCap, expandEpsilon
41 , expandTrail
42 , expandTrail'
43 , expandPath
44 , expandPath'
45
46 ) where
47
48 import Control.Applicative
49 import Control.Lens hiding (at)
50 import Prelude
51
52 import Data.Maybe (catMaybes)
53 import Data.Monoid
54 import Data.Monoid.Inf
55
56 import Data.Default
57
58 import Diagrams.Core
59
60 import Diagrams.Attributes
61 import Diagrams.Direction
62 import Diagrams.Located
63 import Diagrams.Parametric
64 import Diagrams.Path
65 import Diagrams.Segment
66 import Diagrams.Trail hiding (isLoop, offset)
67 import Diagrams.TrailLike
68 import Diagrams.TwoD.Arc
69 import Diagrams.TwoD.Curvature
70 import Diagrams.TwoD.Path ()
71 import Diagrams.TwoD.Types
72 import Diagrams.TwoD.Vector hiding (e)
73
74 import Linear.Affine
75 import Linear.Metric
76 import Linear.Vector
77
78 unitPerp :: OrderedField n => V2 n -> V2 n
79 unitPerp = signorm . perp
80
81 perpAtParam :: OrderedField n => Segment Closed V2 n -> n -> V2 n
82 perpAtParam (Linear (OffsetClosed a)) _ = negated $ unitPerp a
83 perpAtParam cubic t = negated $ unitPerp a
84 where
85 (Cubic a _ _) = snd $ splitAtParam cubic t
86
87 -- | Compute the offset of a segment. Given a segment compute the offset
88 -- curve that is a fixed distance from the original curve. For linear
89 -- segments nothing special happens, the same linear segment is returned
90 -- with a point that is offset by a perpendicular vector of the given offset
91 -- length.
92 --
93 -- Cubic segments require a search for a subdivision of cubic segments that
94 -- gives an approximation of the offset within the given epsilon factor
95 -- (the given epsilon factor is applied to the radius giving a concrete epsilon
96 -- value).
97 -- We must do this because the offset of a cubic is not a cubic itself (the
98 -- degree of the curve increases). Cubics do, however, approach constant
99 -- curvature as we subdivide. In light of this we scale the handles of
100 -- the offset cubic segment in proportion to the radius of curvature difference
101 -- between the original subsegment and the offset which will have a radius
102 -- increased by the offset parameter.
103 --
104 -- In the following example the blue lines are the original segments and
105 -- the alternating green and red lines are the resulting offset trail segments.
106 --
107 -- <<diagrams/src_Diagrams_TwoD_Offset_cubicOffsetExample.svg#diagram=cubicOffsetExample&width=600>>
108 --
109 -- Note that when the original curve has a cusp, the offset curve forms a
110 -- radius around the cusp, and when there is a loop in the original curve,
111 -- there can be two cusps in the offset curve.
112 --
113
114 -- | Options for specifying line join and segment epsilon for an offset
115 -- involving multiple segments.
116 data OffsetOpts d = OffsetOpts
117 { _offsetJoin :: LineJoin
118 , _offsetMiterLimit :: d
119 , _offsetEpsilon :: d
120 }
121
122 deriving instance Eq d => Eq (OffsetOpts d)
123 deriving instance Show d => Show (OffsetOpts d)
124
125 makeLensesWith (lensRules & generateSignatures .~ False) ''OffsetOpts
126
127 -- | Specifies the style of join for between adjacent offset segments.
128 offsetJoin :: Lens' (OffsetOpts d) LineJoin
129
130 -- | Specifies the miter limit for the join.
131 offsetMiterLimit :: Lens' (OffsetOpts d) d
132
133 -- | Epsilon perimeter for 'offsetSegment'.
134 offsetEpsilon :: Lens' (OffsetOpts d) d
135
136 -- | The default offset options use the default 'LineJoin' ('LineJoinMiter'), a
137 -- miter limit of 10, and epsilon factor of 0.01.
138 instance Fractional d => Default (OffsetOpts d) where
139 def = OffsetOpts def 10 0.01
140
141 -- | Options for specifying how a 'Trail' should be expanded.
142 data ExpandOpts d = ExpandOpts
143 { _expandJoin :: LineJoin
144 , _expandMiterLimit :: d
145 , _expandCap :: LineCap
146 , _expandEpsilon :: d
147 } deriving (Eq, Show)
148
149 makeLensesWith (lensRules & generateSignatures .~ False) ''ExpandOpts
150
151 -- | Specifies the style of join for between adjacent offset segments.
152 expandJoin :: Lens' (ExpandOpts d) LineJoin
153
154 -- | Specifies the miter limit for the join.
155 expandMiterLimit :: Lens' (ExpandOpts d) d
156
157 -- | Specifies how the ends are handled.
158 expandCap :: Lens' (ExpandOpts d) LineCap
159
160 -- | Epsilon perimeter for 'offsetSegment'.
161 expandEpsilon :: Lens' (ExpandOpts d) d
162
163
164
165 -- | The default 'ExpandOpts' is the default 'LineJoin' ('LineJoinMiter'),
166 -- miter limit of 10, default 'LineCap' ('LineCapButt'), and epsilon factor
167 -- of 0.01.
168 instance (Fractional d) => Default (ExpandOpts d) where
169 def = ExpandOpts def 10 def 0.01
170
171 offsetSegment :: RealFloat n
172 => n -- ^ Epsilon factor that when multiplied to the
173 -- absolute value of the radius gives a
174 -- value that represents the maximum
175 -- allowed deviation from the true offset. In
176 -- the current implementation each result segment
177 -- should be bounded by arcs that are plus or
178 -- minus epsilon factor from the radius of curvature of
179 -- the offset.
180 -> n -- ^ Offset from the original segment, positive is
181 -- on the right of the curve, negative is on the
182 -- left.
183 -> Segment Closed V2 n -- ^ Original segment
184 -> Located (Trail V2 n) -- ^ Resulting located (at the offset) trail.
185 offsetSegment _ r s@(Linear (OffsetClosed a)) = trailFromSegments [s] `at` origin .+^ va
186 where va = (-r) *^ unitPerp a
187
188 offsetSegment epsilon r s@(Cubic a b (OffsetClosed c)) = t `at` origin .+^ va
189 where
190 t = trailFromSegments (go (radiusOfCurvature s 0.5))
191 -- Perpendiculars to handles.
192 va = (-r) *^ unitPerp a
193 vc = (-r) *^ unitPerp (c ^-^ b)
194 -- Split segments.
195 ss = (\(x,y) -> [x,y]) $ splitAtParam s 0.5
196 subdivided = concatMap (trailSegments . unLoc . offsetSegment epsilon r) ss
197
198 -- Offset with handles scaled based on curvature.
199 offset factor = bezier3 (a^*factor) ((b ^-^ c)^*factor ^+^ c ^+^ vc ^-^ va) (c ^+^ vc ^-^ va)
200
201 -- We observe a corner. Subdivide right away.
202 go (Finite 0) = subdivided
203 -- We have some curvature
204 go roc
205 | close = [o]
206 | otherwise = subdivided
207 where
208 -- We want the multiplicative factor that takes us from the original
209 -- segment's radius of curvature roc, to roc + r.
210 --
211 -- r + sr = x * sr
212 --
213 o = offset $ case roc of
214 Infinity -> 1 -- Do the right thing.
215 Finite sr -> 1 + r / sr
216
217 close = and [epsilon * abs r > norm (p o ^+^ va ^-^ p s ^-^ pp s)
218 | t' <- [0.25, 0.5, 0.75]
219 , let p = (`atParam` t')
220 , let pp = (r *^) . (`perpAtParam` t')
221 ]
222
223
224 -- > import Diagrams.TwoD.Offset
225 -- >
226 -- > showExample :: Segment Closed V2 Double -> Diagram SVG
227 -- > showExample s = pad 1.1 . centerXY $ d # lc blue # lw thick <> d' # lw thick
228 -- > where
229 -- > d = strokeP . fromSegments $ [s]
230 -- > d' = mconcat . zipWith lc colors . map strokeP . explodeTrail
231 -- > $ offsetSegment 0.1 (-1) s
232 -- >
233 -- > colors = cycle [green, red]
234 -- >
235 -- > cubicOffsetExample :: Diagram SVG
236 -- > cubicOffsetExample = hcat . map showExample $
237 -- > [ bezier3 (10 ^& 0) ( 5 ^& 18) (10 ^& 20)
238 -- > , bezier3 ( 0 ^& 20) ( 10 ^& 10) ( 5 ^& 10)
239 -- > , bezier3 (10 ^& 20) ( 0 ^& 10) (10 ^& 0)
240 -- > , bezier3 (10 ^& 20) ((-5) ^& 10) (10 ^& 0)
241 -- > ]
242
243 -- Similar to (=<<). This is when we want to map a function across something
244 -- located, but the result of the mapping will be transformable so we can
245 -- collapse the Located into the result. This assumes that Located has the
246 -- meaning of merely taking something that cannot be translated and lifting
247 -- it into a space with translation.
248 bindLoc :: (Transformable b, V a ~ V b, N a ~ N b, V a ~ V2, N a ~ n, Num n) => (a -> b) -> Located a -> b
249 bindLoc f = join' . mapLoc f
250 where
251 join' (viewLoc -> (p,a)) = translate (p .-. origin) a
252
253 -- While we build offsets and expansions we will use the [Located (Segment Closed v)]
254 -- and [Located (Trail V2 n)] intermediate representations.
255 locatedTrailSegments :: OrderedField n
256 => Located (Trail V2 n) -> [Located (Segment Closed V2 n)]
257 locatedTrailSegments t = zipWith at (trailSegments (unLoc t)) (trailPoints t)
258
259 -- | Offset a 'Trail' with options and by a given radius. This generates a new
260 -- trail that is always radius 'r' away from the given 'Trail' (depending on
261 -- the line join option) on the right.
262 --
263 -- The styles applied to an outside corner can be seen here (with the original
264 -- trail in blue and the result of 'offsetTrail'' in green):
265 --
266 -- <<diagrams/src_Diagrams_TwoD_Offset_offsetTrailExample.svg#diagram=offsetTrailExample&width=600>>
267 --
268 -- When a negative radius is given, the offset trail will be on the left:
269 --
270 -- <<diagrams/src_Diagrams_TwoD_Offset_offsetTrailLeftExample.svg#diagram=offsetTrailLeftExample&width=200>>
271 --
272 -- When offseting a counter-clockwise loop a positive radius gives an outer loop
273 -- while a negative radius gives an inner loop (both counter-clockwise).
274 --
275 -- <<diagrams/src_Diagrams_TwoD_Offset_offsetTrailOuterExample.svg#diagram=offsetTrailOuterExample&width=300>>
276 --
277 offsetTrail' :: RealFloat n
278 => OffsetOpts n
279 -> n -- ^ Radius of offset. A negative value gives an offset on
280 -- the left for a line and on the inside for a counter-clockwise
281 -- loop.
282 -> Located (Trail V2 n)
283 -> Located (Trail V2 n)
284 offsetTrail' opts r t = joinSegments eps j isLoop (opts^.offsetMiterLimit) r ends . offset $ t
285 where
286 eps = opts^.offsetEpsilon
287 offset = map (bindLoc (offsetSegment eps r)) . locatedTrailSegments
288 ends | isLoop = (\(a:as) -> as ++ [a]) . trailPoints $ t
289 | otherwise = tail . trailPoints $ t
290 j = fromLineJoin (opts^.offsetJoin)
291
292 isLoop = withTrail (const False) (const True) (unLoc t)
293
294 -- | Offset a 'Trail' with the default options and a given radius. See 'offsetTrail''.
295 offsetTrail :: RealFloat n => n -> Located (Trail V2 n) -> Located (Trail V2 n)
296 offsetTrail = offsetTrail' def
297
298 -- | Offset a 'Path' by applying 'offsetTrail'' to each trail in the path.
299 offsetPath' :: RealFloat n => OffsetOpts n -> n -> Path V2 n -> Path V2 n
300 offsetPath' opts r = mconcat
301 . map (bindLoc (trailLike . offsetTrail' opts r) . (`at` origin))
302 . op Path
303
304 -- | Offset a 'Path' with the default options and given radius. See 'offsetPath''.
305 offsetPath :: RealFloat n => n -> Path V2 n -> Path V2 n
306 offsetPath = offsetPath' def
307
308 -- TODO: Include arrowheads on examples to indicate direction so the "left" and
309 -- "right" make sense.
310 --
311 -- > import Diagrams.TwoD.Offset
312 -- > import Data.Default
313 -- >
314 -- > corner :: (OrderedField n) => Located (Trail V2 n)
315 -- > corner = fromVertices (map p2 [(0, 0), (10, 0), (5, 6)]) `at` origin
316 -- >
317 -- > offsetTrailExample :: Diagram SVG
318 -- > offsetTrailExample = pad 1.1 . centerXY . lwO 3 . hcat' (def & sep .~ 1 )
319 -- > . map (uncurry showStyle)
320 -- > $ [ (LineJoinMiter, "LineJoinMiter")
321 -- > , (LineJoinRound, "LineJoinRound")
322 -- > , (LineJoinBevel, "LineJoinBevel")
323 -- > ]
324 -- > where
325 -- > showStyle j s = centerXY (trailLike corner # lc blue
326 -- > <> trailLike (offsetTrail' (def & offsetJoin .~ j) 2 corner) # lc green)
327 -- > === (strutY 3 <> text s # font "Helvetica" # bold)
328 -- >
329 -- > offsetTrailLeftExample :: Diagram SVG
330 -- > offsetTrailLeftExample = pad 1.1 . centerXY . lwO 3
331 -- > $ (trailLike c # lc blue)
332 -- > <> (lc green . trailLike
333 -- > . offsetTrail' (def & offsetJoin .~ LineJoinRound) (-2) $ c)
334 -- > where
335 -- > c = reflectY corner
336 -- >
337 -- > offsetTrailOuterExample :: Diagram SVG
338 -- > offsetTrailOuterExample = pad 1.1 . centerXY . lwO 3
339 -- > $ (trailLike c # lc blue)
340 -- > <> (lc green . trailLike
341 -- > . offsetTrail' (def & offsetJoin .~ LineJoinRound) 2 $ c)
342 -- > where
343 -- > c = hexagon 5
344
345 withTrailL :: (Located (Trail' Line V2 n) -> r) -> (Located (Trail' Loop V2 n) -> r) -> Located (Trail V2 n) -> r
346 withTrailL f g l = withTrail (f . (`at` p)) (g . (`at` p)) (unLoc l)
347 where
348 p = loc l
349
350 -- | Expand a 'Trail' with the given options and radius 'r' around a given 'Trail'.
351 -- Expanding can be thought of as generating the loop that, when filled, represents
352 -- stroking the trail with a radius 'r' brush.
353 --
354 -- The cap styles applied to an outside corner can be seen here (with the original
355 -- trail in white and the result of 'expandTrail'' filled in green):
356 --
357 -- <<diagrams/src_Diagrams_TwoD_Offset_expandTrailExample.svg#diagram=expandTrailExample&width=600>>
358 --
359 -- Loops result in a path with an inner and outer loop:
360 --
361 -- <<diagrams/src_Diagrams_TwoD_Offset_expandLoopExample.svg#diagram=expandLoopExample&width=300>>
362 --
363 expandTrail' :: (OrderedField n, RealFloat n, RealFrac n)
364 => ExpandOpts n
365 -> n -- ^ Radius of offset. Only non-negative values allowed.
366 -- For a line this gives a loop of the offset. For a
367 -- loop this gives two loops, the outer counter-clockwise
368 -- and the inner clockwise.
369 -> Located (Trail V2 n)
370 -> Path V2 n
371 expandTrail' o r t
372 | r < 0 = error "expandTrail' with negative radius"
373 -- TODO: consider just reversing the path instead of this error.
374 | otherwise = withTrailL (pathFromLocTrail . expandLine o r) (expandLoop o r) t
375
376 expandLine :: RealFloat n => ExpandOpts n -> n -> Located (Trail' Line V2 n) -> Located (Trail V2 n)
377 expandLine opts r (mapLoc wrapLine -> t) = caps cap r s e (f r) (f $ -r)
378 where
379 eps = opts^.expandEpsilon
380 offset r' = map (bindLoc (offsetSegment eps r')) . locatedTrailSegments
381 f r' = joinSegments eps (fromLineJoin (opts^.expandJoin)) False (opts^.expandMiterLimit) r' ends
382 . offset r' $ t
383 ends = tail . trailPoints $ t
384 s = atStart t
385 e = atEnd t
386 cap = fromLineCap (opts^.expandCap)
387
388 expandLoop :: RealFloat n => ExpandOpts n -> n -> Located (Trail' Loop V2 n) -> Path V2 n
389 expandLoop opts r (mapLoc wrapLoop -> t) = trailLike (f r) <> (trailLike . reverseDomain . f $ -r)
390 where
391 eps = opts^.expandEpsilon
392 offset r' = map (bindLoc (offsetSegment eps r')) . locatedTrailSegments
393 f r' = joinSegments eps (fromLineJoin (opts^.expandJoin)) True (opts^.expandMiterLimit) r' ends
394 . offset r' $ t
395 ends = (\(a:as) -> as ++ [a]) . trailPoints $ t
396
397 -- | Expand a 'Trail' with the given radius and default options. See 'expandTrail''.
398 expandTrail :: RealFloat n => n -> Located (Trail V2 n) -> Path V2 n
399 expandTrail = expandTrail' def
400
401 -- | Expand a 'Path' using 'expandTrail'' on each trail in the path.
402 expandPath' :: RealFloat n => ExpandOpts n -> n -> Path V2 n -> Path V2 n
403 expandPath' opts r = mconcat
404 . map (bindLoc (expandTrail' opts r) . (`at` origin))
405 . op Path
406
407 -- | Expand a 'Path' with the given radius and default options. See 'expandPath''.
408 expandPath :: RealFloat n => n -> Path V2 n -> Path V2 n
409 expandPath = expandPath' def
410
411 -- > import Diagrams.TwoD.Offset
412 -- > import Data.Default
413 -- >
414 -- > expandTrailExample :: Diagram SVG
415 -- > expandTrailExample = pad 1.1 . centerXY . hcat' (def & sep .~ 1)
416 -- > . map (uncurry showStyle)
417 -- > $ [ (LineCapButt, "LineCapButt")
418 -- > , (LineCapRound, "LineCapRound")
419 -- > , (LineCapSquare, "LineCapSquare")
420 -- > ]
421 -- > where
422 -- > showStyle c s = centerXY (trailLike corner # lc white # lw veryThick
423 -- > <> stroke (expandTrail'
424 -- > (def & expandJoin .~ LineJoinRound
425 -- > & expandCap .~ c
426 -- > ) 2 corner)
427 -- > # lw none # fc green)
428 -- > === (strutY 3 <> text s # font "Helvetica" # bold)
429 -- >
430 -- > expandLoopExample :: Diagram SVG
431 -- > expandLoopExample = pad 1.1 . centerXY $ ((strokeLocT t # lw veryThick # lc white)
432 -- > <> (stroke t' # lw none # fc green))
433 -- > where
434 -- > t = mapLoc glueTrail $ fromVertices (map p2 [(0, 0), (5, 0), (10, 5), (10, 10), (0, 0)])
435 -- > t' = expandTrail' (def & expandJoin .~ LineJoinRound) 1 t
436
437
438 -- | When we expand a line (the original line runs through the center of offset
439 -- lines at r and -r) there is some choice in what the ends will look like.
440 -- If we are using a circle brush we should see a half circle at each end.
441 -- Similar caps could be made for square brushes or simply stopping exactly at
442 -- the end with a straight line (a perpendicular line brush).
443 --
444 -- caps takes the radius and the start and end points of the original line and
445 -- the offset trails going out and coming back. The result is a new list of
446 -- trails with the caps included.
447 caps :: RealFloat n => (n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n)
448 -> n -> Point V2 n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Located (Trail V2 n)
449 caps cap r s e fs bs = mapLoc glueTrail $ mconcat
450 [ cap r s (atStart bs) (atStart fs)
451 , unLoc fs
452 , cap r e (atEnd fs) (atEnd bs)
453 , reverseDomain (unLoc bs)
454 ] `at` atStart bs
455
456 -- | Take a LineCap style and give a function for building the cap from
457 fromLineCap :: RealFloat n => LineCap -> n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
458 fromLineCap c = case c of
459 LineCapButt -> capCut
460 LineCapRound -> capArc
461 LineCapSquare -> capSquare
462
463 -- | Builds a cap that directly connects the ends.
464 capCut :: RealFloat n => n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
465 capCut _r _c a b = fromSegments [straight (b .-. a)]
466
467 -- | Builds a cap with a square centered on the end.
468 capSquare :: RealFloat n => n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
469 capSquare _r c a b = unLoc $ fromVertices [ a, a .+^ v, b .+^ v, b ]
470 where
471 v = perp (a .-. c)
472
473 -- | Builds an arc to fit with a given radius, center, start, and end points.
474 -- A Negative r means a counter-clockwise arc
475 capArc :: RealFloat n => n -> Point V2 n -> Point V2 n -> Point V2 n -> Trail V2 n
476 capArc r c a b = trailLike . moveTo c $ fs
477 where
478 fs | r < 0 = scale (-r) $ arcCW (dirBetween c a) (dirBetween c b)
479 | otherwise = scale r $ arcCCW (dirBetween c a) (dirBetween c b)
480
481 -- | Join together a list of located trails with the given join style. The
482 -- style is given as a function to compute the join given the local information
483 -- of the original vertex, the previous trail, and the next trail. The result
484 -- is a single located trail. A join radius is also given to aid in arc joins.
485 --
486 -- Note: this is not a general purpose join and assumes that we are joining an
487 -- offset trail. For instance, a fixed radius arc will not fit between arbitrary
488 -- trails without trimming or extending.
489 joinSegments :: RealFloat n
490 => n
491 -> (n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n)
492 -> Bool
493 -> n
494 -> n
495 -> [Point V2 n]
496 -> [Located (Trail V2 n)]
497 -> Located (Trail V2 n)
498 joinSegments _ _ _ _ _ _ [] = mempty `at` origin
499 joinSegments _ _ _ _ _ [] _ = mempty `at` origin
500 joinSegments epsilon j isLoop ml r es ts@(t:_) = t'
501 where
502 t' | isLoop = mapLoc (glueTrail . (<> f (take (length ts * 2 - 1) $ ss es (ts ++ [t])))) t
503 | otherwise = mapLoc (<> f (ss es ts)) t
504 ss es' ts' = concat [[test a b $ j ml r e a b, Just $ unLoc b] | (e,(a,b)) <- zip es' . (zip <*> tail) $ ts']
505 test a b tj
506 | atStart b `distance` atEnd a > epsilon = Just tj
507 | otherwise = Nothing
508 f = mconcat . catMaybes
509
510 -- | Take a join style and give the join function to be used by joinSegments.
511 fromLineJoin
512 :: RealFloat n => LineJoin -> n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
513 fromLineJoin j = case j of
514 LineJoinMiter -> joinSegmentIntersect
515 LineJoinRound -> joinSegmentArc
516 LineJoinBevel -> joinSegmentClip
517
518 -- TODO: The joinSegmentCut option is not in our standard line joins. I don't know
519 -- how useful it is graphically, I mostly had it as it was useful for debugging
520 {-
521 -- | Join with segments going back to the original corner.
522 joinSegmentCut :: (OrderedField n) => n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
523 joinSegmentCut _ _ e a b = fromSegments
524 [ straight (e .-. atEnd a)
525 , straight (atStart b .-. e)
526 ]
527 -}
528
529 -- | Join by directly connecting the end points. On an inside corner this
530 -- creates negative space for even-odd fill. Here is where we would want to
531 -- use an arc or something else in the future.
532 joinSegmentClip :: RealFloat n
533 => n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
534 joinSegmentClip _ _ _ a b = fromSegments [straight $ atStart b .-. atEnd a]
535
536 -- | Join with a radius arc. On an inside corner this will loop around the interior
537 -- of the offset trail. With a winding fill this will not be visible.
538 joinSegmentArc :: RealFloat n
539 => n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
540 joinSegmentArc _ r e a b = capArc r e (atEnd a) (atStart b)
541
542 -- | Join to the intersection of the incoming trails projected tangent to their ends.
543 -- If the intersection is beyond the miter limit times the radius, stop at the limit.
544 joinSegmentIntersect
545 :: RealFloat n => n -> n -> Point V2 n -> Located (Trail V2 n) -> Located (Trail V2 n) -> Trail V2 n
546 joinSegmentIntersect miterLimit r e a b =
547 if cross < 0.000001
548 then clip
549 else case traceP pa va t of
550 -- clip join when we excede the miter limit. We could instead
551 -- Join at exactly the miter limit, but standard behavior seems
552 -- to be clipping.
553 Nothing -> clip
554 Just p
555 -- If trace gave us garbage...
556 | p `distance` pb > abs (miterLimit * r) -> clip
557 | otherwise -> unLoc $ fromVertices [ pa, p, pb ]
558 where
559 t = straight (miter vb) `at` pb
560 va = unitPerp (pa .-. e)
561 vb = negated $ unitPerp (pb .-. e)
562 pa = atEnd a
563 pb = atStart b
564 miter v = abs (miterLimit * r) *^ v
565 clip = joinSegmentClip miterLimit r e a b
566 cross = let (xa,ya) = unr2 va; (xb,yb) = unr2 vb in abs (xa * yb - xb * ya)