nano-ui-0.2.0.0: lib/NanoUI/Internal/Path.hs
{-# OPTIONS_HADDOCK not-home #-}
-- | Paths, affine transforms, and the geometry that turns them into draw ops:
-- curve flattening, SVG arc conversion, nesting rings into polygons with
-- holes, triangulation for 'FillPolygon', dashes, miters and gradients.
-- Shared by the canvas ("NanoUI.Path", "NanoUI.Widgets.Custom"), the SVG
-- rasterizer ("NanoUI.Svg") and nano-ui-diagrams.
module NanoUI.Internal.Path
( -- * Paths
Path (..)
, Segment (..)
, moveTo
, lineTo
, quadTo
, cubicTo
, arc
, ellipticalArc
, arcTo
, close
-- * Shapes
, rect
, roundedRect
, roundedRectCorners
, circle
, ellipse
, polygon
, polyline
-- * Transforms
, Transform (..)
, applyTransform
, translate
, rotate
, rotateAround
, scale
, affine
, transformPoint
, invert
, transformFinite
, averageStretch
-- * Strokes, fills and paints
, Stroke (..)
, stroke
, LineCap (..)
, LineJoin (..)
, miterOffset
, FillRule (..)
, fillsWinding
, ringBox
, Paint (..)
, Shade (..)
-- * Rings
, Rings (..)
, ringCount
, shoelace
, buildRings
, cleanRings
-- * Flattening
, curveTolerance
, flattenPath
, idealArcSteps
-- * Draw ops
, fillPathOps
, strokePathOps
, transformOp
) where
import Control.Monad (forM_, unless, when)
import Control.Monad.ST (ST, runST)
import Data.Fixed (mod')
import Data.List (minimumBy, sort, sortBy, sortOn, unsnoc)
import Data.List.NonEmpty qualified as NE
import Data.Ord (comparing)
import Data.Primitive.PrimArray
( PrimArray
, emptyPrimArray
, generatePrimArray
, indexPrimArray
, newPrimArray
, primArrayFromList
, primArrayFromListN
, readPrimArray
, runPrimArray
, setPrimArray
, shrinkMutablePrimArray
, sizeofPrimArray
, thawPrimArray
, unsafeFreezePrimArray
, writePrimArray
)
import Data.Primitive.SmallArray (indexSmallArray, newSmallArray, readSmallArray, runSmallArray, smallArrayFromListN, writeSmallArray)
import Data.Word (Word32)
import NanoUI.Internal.Draw.Types (DrawOp (..), LineCap (..), LineJoin (..), Shade (..), defaultTextFont, quadPolygon)
import NanoUI.Internal.Types (Color (..), Rect (..), V2 (..), bucketOffsets, colorA, colorB, colorG, colorR, finite, lerpColor, newZeroedPrimArray)
--------------------------------------------------------------------------------
-- Paths
--------------------------------------------------------------------------------
-- | A sequence of subpaths made of lines, curves and arcs, in the drawing's
-- coordinates. Paths concatenate with '<>'.
newtype Path = Path [Segment]
deriving (Eq, Show)
deriving newtype (Semigroup, Monoid)
-- | One step of a 'Path'. A line, curve or 'SegArcTo' with no open subpath
-- starts one at the current point (where the last subpath closed, or the
-- origin).
data Segment
= SegMove {-# UNPACK #-} !Float {-# UNPACK #-} !Float
-- ^ Start a subpath at a point.
| SegLine {-# UNPACK #-} !Float {-# UNPACK #-} !Float
-- ^ A straight line to a point.
| SegQuad
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
-- ^ A quadratic Bezier: control point, end.
| SegCubic
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
-- ^ A cubic Bezier: two control points, end.
| SegArc
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
-- ^ An elliptical arc in centre form: centre, radii, rotation, start angle
-- and sweep, in radians. With a subpath open, a line joins the arc's
-- start; otherwise the arc starts a new subpath.
| SegArcTo
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
!Bool
!Bool
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
-- ^ An SVG arc to a point: radii, rotation in radians, large-arc and sweep
-- flags, end.
| SegClose
-- ^ Close the subpath back to where it started.
deriving (Eq, Show)
-- | Start a subpath at a point.
moveTo :: V2 -> Path
moveTo (V2 x y) = Path [SegMove x y]
-- | A straight line to a point.
lineTo :: V2 -> Path
lineTo (V2 x y) = Path [SegLine x y]
-- | A quadratic Bezier curve: control point, then end point.
quadTo :: V2 -> V2 -> Path
quadTo (V2 qx qy) (V2 x y) = Path [SegQuad qx qy x y]
-- | A cubic Bezier curve: two control points, then end point.
cubicTo :: V2 -> V2 -> V2 -> Path
cubicTo (V2 x1 y1) (V2 x2 y2) (V2 x y) = Path [SegCubic x1 y1 x2 y2 x y]
-- | A circular arc: centre, radius, start angle and sweep. With a subpath
-- open, a line joins the current point to the arc's start; otherwise the arc
-- starts a new subpath. A sweep of a full turn or more draws the whole
-- circle, and a negative sweep goes anticlockwise. A negative radius is
-- treated as its absolute value.
--
-- > P.moveTo c <> P.arc c r 0 (pi / 3) <> P.close -- a pie slice
arc :: V2 -> Float -> Float -> Float -> Path
arc c r = ellipticalArc c (V2 r r) 0
-- | An elliptical arc: centre, x and y radii, the ellipse's rotation, start
-- angle and sweep. The angles are measured before the ellipse is stretched
-- and rotated. Joins the current subpath like 'arc'.
ellipticalArc :: V2 -> V2 -> Float -> Float -> Float -> Path
ellipticalArc (V2 cx cy) (V2 rx ry) rot start sweep = Path [SegArc cx cy rx ry rot start sweep]
-- | An arc to a point, like SVG's @A@ command: x and y radii, the ellipse's
-- rotation, whether to take the larger of the two possible arcs, whether to
-- go clockwise on screen, and the end point. Radii too small to reach the
-- end are scaled up; a zero radius draws a straight line. This is not HTML
-- canvas's @arcTo@, which rounds the corner between two lines; draw that
-- with 'arc' around the corner's centre.
arcTo :: V2 -> Float -> Bool -> Bool -> V2 -> Path
arcTo (V2 rx ry) rot large clockwise (V2 x y) = Path [SegArcTo rx ry rot large clockwise x y]
-- | Close the subpath with a line back to its start. A stroke joins a
-- closed subpath's ends instead of capping them.
close :: Path
close = Path [SegClose]
--------------------------------------------------------------------------------
-- Shapes
--------------------------------------------------------------------------------
-- | A rectangle's outline, clockwise on screen from its top left corner.
rect :: Rect -> Path
rect (Rect x y w h) =
Path [SegMove x y, SegLine (x + w) y, SegLine (x + w) (y + h), SegLine x (y + h), SegClose]
-- | A rectangle with rounded corners, the radius clamped to half the shorter
-- side. Runs clockwise on screen from the end of the top left corner.
roundedRect :: Rect -> Float -> Path
roundedRect box radius = roundedRectCorners box radius radius radius radius
-- | A rectangle with a radius per corner, in CSS @border-radius@ order: top
-- left, top right, bottom right, bottom left. If two corners on a side would
-- overlap, all radii shrink by the same factor, as in CSS. A negative radius
-- gives a square corner. A rectangle with a negative width or height is
-- the one it spans, with the radii on its corners as seen on screen.
roundedRectCorners :: Rect -> Float -> Float -> Float -> Float -> Path
roundedRectCorners box@(Rect x0 y0 w h) tl0 tr0 br0 bl0
| tl <= 0 && tr <= 0 && br <= 0 && bl <= 0 = rect box
| otherwise =
Path
[ SegMove (x + tl) y
, corner (x + aw - tr) (y + tr) tr (-pi / 2)
, corner (x + aw - br) (y + ah - br) br 0
, corner (x + bl) (y + ah - bl) bl (pi / 2)
, corner (x + tl) (y + tl) tl pi
, SegClose
]
where
-- Capped, so an infinite radius shrinks to fit like a huge one, not to NaN.
positive r = if r > 0 then min r 1e30 else 0
x = min x0 (x0 + w)
y = min y0 (y0 + h)
aw = abs w
ah = abs h
-- The factor that fits a side's two radii within its length.
fitSide side a b = let both = positive a + positive b in if both > side then side / both else 1
shrink = min (min (fitSide aw tl0 tr0) (fitSide ah tr0 br0)) (min (fitSide aw br0 bl0) (fitSide ah bl0 tl0))
fit r = positive r * shrink
tl = fit tl0
tr = fit tr0
br = fit br0
bl = fit bl0
-- A quarter arc about the corner's centre, or a line for a square corner.
corner cx cy r a0
| r > 0 = SegArc cx cy r r 0 a0 (pi / 2)
| otherwise = SegLine cx cy
-- | A circle: its centre and radius.
circle :: V2 -> Float -> Path
circle c r = ellipse c (V2 r r)
-- | An axis-aligned ellipse: centre and x and y radii. For a rotated one use
-- 'ellipticalArc' or a transform.
ellipse :: V2 -> V2 -> Path
ellipse (V2 cx cy) (V2 rx ry) = Path [SegMove (cx + abs rx) cy, SegArc cx cy rx ry 0 0 (2 * pi), SegClose]
-- | A closed polygon through the points.
polygon :: [V2] -> Path
polygon pts = polyline pts <> if null pts then mempty else close
-- | An open line through the points.
polyline :: [V2] -> Path
polyline [] = mempty
polyline (V2 x y : rest) = Path (SegMove x y : [SegLine px py | V2 px py <- rest])
--------------------------------------------------------------------------------
-- Strokes, fills and paints
--------------------------------------------------------------------------------
-- | Stroke settings. Start from 'stroke' and change the rest with a record
-- update:
--
-- > (P.stroke 3) {P.strokeCap = P.RoundCap, P.strokeDash = [6, 4]}
data Stroke = StrokeStyle
{ strokeWidth :: !Float
-- ^ Line width. A transform scales it along with the path.
, strokeCap :: !LineCap
-- ^ Cap for the ends of open subpaths and of every dash (default
-- 'ButtCap'). A subpath of zero length, such as a move and a line to the
-- same point, is a dot with 'RoundCap' or 'SquareCap'.
, strokeJoin :: !LineJoin
-- ^ Corner join (default 'MiterJoin').
, strokeMiterLimit :: !Float
-- ^ Longest allowed miter, as a multiple of the width; longer corners are
-- beveled (default 4, like SVG's @stroke-miterlimit@).
, strokeDash :: ![Float]
-- ^ Alternating dash and gap lengths, repeated along each subpath. An odd
-- count is repeated twice (default @[]@, solid). A zero-length dash with
-- round or square caps draws a dot. Negative or all-zero lengths draw a
-- solid line, as does a pattern that would cut a subpath into more than
-- 4096 dashes. A transform scales the lengths along with the width.
, strokeDashOffset :: !Float
-- ^ Distance into the dash pattern at which each subpath starts
-- (default 0).
}
deriving (Eq, Show)
-- | A solid stroke of the given width, with butt caps and miter joins.
stroke :: Float -> Stroke
stroke w = StrokeStyle w ButtCap MiterJoin 4 [] 0
-- | The miter at a corner between edges with unit normals @(ax, ay)@ and
-- @(bx, by)@: moving the corner by this offset moves both edges out by one.
-- Its length is the miter length relative to the line width. 'Nothing' past
-- @limit@, where the corner is beveled. Used by canvas strokes and the SVG
-- rasterizer.
{-# INLINE miterOffset #-}
miterOffset :: Float -> Float -> Float -> Float -> Float -> Maybe (Float, Float)
miterOffset limit ax ay bx by
| not (d2 * limit * limit >= 1) = Nothing
| otherwise = Just (mx / d2, my / d2)
where
mx = (ax + bx) / 2
my = (ay + by) / 2
d2 = mx * mx + my * my
-- | Which points a fill covers, based on the path's winding number around
-- them (+1 for each turn one way, -1 for the other).
data FillRule
= NonZero
-- ^ Points with a nonzero winding number. A subpath inside another is
-- filled too, unless it runs the opposite way, which cuts it out.
| EvenOdd
-- ^ Points with an odd winding number. A subpath inside another is cut
-- out, and one inside that is filled again.
deriving (Eq, Ord, Show, Enum, Bounded)
-- | Whether a point with winding number @w@ is inside the fill. Used by
-- canvas fills and the SVG rasterizer.
{-# INLINE fillsWinding #-}
fillsWinding :: FillRule -> Int -> Bool
fillsWinding NonZero w = w /= 0
fillsWinding EvenOdd w = odd w
-- | The paint for a fill or stroke.
data Paint
= Solid !Color
-- ^ One colour.
| Linear !V2 !V2 ![(Float, Color)]
-- ^ A linear gradient from its first point (offset 0) to its second
-- (offset 1), with colour stops at offsets. Beyond the first and last
-- stops it keeps their colours. Offsets are clamped to 0..1, and an
-- offset below the previous one is raised to it, so two stops at the same
-- offset give a hard edge. The gradient is in drawing coordinates, so
-- transforms rotate and scale it. A stroke uses the colour at its centre
-- line across its whole width.
deriving (Eq, Show)
--------------------------------------------------------------------------------
-- Transforms
--------------------------------------------------------------------------------
-- | An affine transform, laid out like SVG's @matrix(a b c d e f)@: @(x, y)@
-- maps to @(a x + c y + e, b x + d y + f)@. @s <> t@ applies @t@ first, like
-- function composition; 'mempty' is the identity.
data Transform
= Transform
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
{-# UNPACK #-} !Float
deriving (Eq, Show)
instance Semigroup Transform where
Transform a b c d e f <> Transform a' b' c' d' e' f' =
Transform
(a * a' + c * b')
(b * a' + d * b')
(a * c' + c * d')
(b * c' + d * d')
(a * e' + c * f' + e)
(b * e' + d * f' + f)
instance Monoid Transform where
mempty = Transform 1 0 0 1 0 0
-- | Map a point through a transform.
{-# INLINE applyTransform #-}
applyTransform :: Transform -> Float -> Float -> (Float, Float)
applyTransform (Transform a b c d e f) x y = (a * x + c * y + e, b * x + d * y + f)
-- | Move by an offset.
translate :: Float -> Float -> Transform
translate dx dy = Transform 1 0 0 1 dx dy
-- | Rotate about the origin. A positive angle turns clockwise on screen.
rotate :: Float -> Transform
rotate a =
let s = sin a
c = cos a
in Transform c s (negate s) c 0 0
-- | Rotate about a point.
rotateAround :: V2 -> Float -> Transform
rotateAround (V2 x y) a = translate x y <> rotate a <> translate (negate x) (negate y)
-- | Scale about the origin by separate x and y factors. A negative factor
-- flips that axis.
scale :: Float -> Float -> Transform
scale sx sy = Transform sx 0 0 sy 0 0
-- | A transform from its matrix entries, in SVG @matrix(a b c d e f)@
-- order: @(x, y)@ maps to @(a x + c y + e, b x + d y + f)@.
affine :: Float -> Float -> Float -> Float -> Float -> Float -> Transform
affine = Transform
-- | Apply a transform to a point.
transformPoint :: Transform -> V2 -> V2
transformPoint t (V2 x y) = let (x', y') = applyTransform t x y in V2 x' y'
-- | The inverse transform, e.g. to map a pointer position back into a
-- drawing's coordinates. 'Nothing' if the transform collapses the plane to
-- a line or point, or has a NaN or infinite entry.
invert :: Transform -> Maybe Transform
invert (Transform a b c d e f)
| det == 0 || not (transformFinite inv) = Nothing
| otherwise = Just inv
where
det = a * d - b * c
inv = Transform (d / det) (negate b / det) (negate c / det) (a / det) ((c * f - d * e) / det) ((b * e - a * f) / det)
-- | No entry is NaN or infinite.
transformFinite :: Transform -> Bool
transformFinite (Transform a b c d e f) = all finite [a, b, c, d, e, f]
-- | The most the transform lengthens any vector: the larger singular value
-- of its linear part.
maxStretch :: Transform -> Float
maxStretch (Transform a b c d _ _) =
let s = a * a + b * b + c * c + d * d
det = a * d - b * c
in sqrt ((s + sqrt (max 0 (s * s - 4 * det * det))) / 2)
-- | The square root of the transform's area scale. For a uniform scale this
-- is the scale factor; in general, the geometric mean of the singular values.
averageStretch :: Transform -> Float
averageStretch (Transform a b c d _ _) = sqrt (abs (a * d - b * c))
--------------------------------------------------------------------------------
-- Rings
--------------------------------------------------------------------------------
-- | Rings of points in flat arrays: interleaved x/y coordinates, start
-- offsets (ring @i@ is points @starts[i]@ up to @starts[i + 1]@), and one
-- builder-assigned tag per ring.
data Rings = Rings !(PrimArray Float) !(PrimArray Int) !(PrimArray Int)
-- | The number of rings.
ringCount :: Rings -> Int
ringCount (Rings _ starts _) = sizeofPrimArray starts - 1
-- | Build 'Rings' from a walk that calls @point x y@ per point and @end tag@
-- after each ring. The walk runs twice (once to size the arrays, once to
-- fill them), so both runs must emit the same points.
{-# INLINE buildRings #-}
buildRings :: (forall s. (Float -> Float -> ST s ()) -> (Int -> ST s ()) -> ST s ()) -> Rings
buildRings walk = runST $ do
counts <- newZeroedPrimArray 2
let bump k = readPrimArray counts k >>= writePrimArray counts k . (+ 1)
walk (\_ _ -> bump 0) (\_ -> bump 1)
nPoints <- readPrimArray counts 0
nRings <- readPrimArray counts 1
points <- newPrimArray (2 * nPoints)
starts <- newPrimArray (nRings + 1)
tags <- newPrimArray nRings
writePrimArray starts 0 0
setPrimArray counts 0 2 0
walk
( \x y -> do
k <- readPrimArray counts 0
writePrimArray points (2 * k) x
writePrimArray points (2 * k + 1) y
writePrimArray counts 0 (k + 1)
)
( \tag -> do
r <- readPrimArray counts 1
readPrimArray counts 0 >>= writePrimArray starts (r + 1)
writePrimArray tags r tag
writePrimArray counts 1 (r + 1)
)
Rings <$> unsafeFreezePrimArray points <*> unsafeFreezePrimArray starts <*> unsafeFreezePrimArray tags
--------------------------------------------------------------------------------
-- Flattening
--------------------------------------------------------------------------------
-- | Flattening tolerance in logical pixels for a display with @s@ device
-- pixels per logical pixel: a quarter of a device pixel.
curveTolerance :: Float -> Float
curveTolerance s
| s > 0 && s < 1 / 0 = 0.25 / s
| otherwise = 0.25
-- | Flatten a path through a transform into rings, tagging a ring 1 if
-- 'SegClose' ended it. Curves are subdivided until they are within @tol@ of
-- their chords after transforming, so scaled-up curves get more points. An
-- arc gets @steps r sweep@ chords, where @r@ is its larger transformed
-- radius (the canvas passes a count that keeps chords within @tol@ of the
-- arc). Segments with a NaN or infinite
-- coordinate are skipped; a transform with one yields no rings.
flattenPath :: Float -> (Float -> Float -> Int) -> Transform -> Path -> Rings
flattenPath tol steps t (Path segs)
| transformFinite t = buildRings (pathWalk tol steps t segs)
| otherwise = buildRings (\_ _ -> pure ())
{-# INLINE pathWalk #-}
pathWalk :: Float -> (Float -> Float -> Int) -> Transform -> [Segment] -> (Float -> Float -> ST s ()) -> (Int -> ST s ()) -> ST s ()
pathWalk tol steps t segs0 point end = go segs0 False 0 0 0 0
where
emit x y = let (x', y') = applyTransform t x y in point x' y'
finish open closed = when open (end (if closed then 1 else 0))
-- A drawing segment with no subpath open starts one at the current point.
begin open cx cy = unless open (emit cx cy)
stretch = maxStretch t
-- An elliptical arc's points after its start. The last is exactly
-- @(x1, y1)@, so a full turn closes on its start.
arcPoints ax ay rx ry rot a0 sweep x1 y1 = do
let n = steps (stretch * max (abs rx) (abs ry)) sweep
forM_ [1 .. n - 1] $ \i ->
uncurry emit (ellipsePoint ax ay rx ry rot (a0 + sweep * fromIntegral i / fromIntegral n))
emit x1 y1
cubic x0 y0 x1 y1 x2 y2 x3 y3 = do
let (tx0, ty0) = applyTransform t x0 y0
(tx1, ty1) = applyTransform t x1 y1
(tx2, ty2) = applyTransform t x2 y2
(tx3, ty3) = applyTransform t x3 y3
cubicPoints tol point tx0 ty0 tx1 ty1 tx2 ty2 tx3 ty3
go [] open _ _ _ _ = finish open False
go (seg : rest) open cx cy sx sy
| not (segmentFinite seg) = go rest open cx cy sx sy
| otherwise = case seg of
SegMove x y -> finish open False >> emit x y >> go rest True x y x y
SegLine x y -> begin open cx cy >> emit x y >> go rest True x y sx sy
SegQuad qx qy x y -> do
begin open cx cy
-- The quadratic as a cubic: each control point is two thirds of
-- the way from an end to the quadratic's control point.
cubic cx cy (cx + 2 / 3 * (qx - cx)) (cy + 2 / 3 * (qy - cy)) (x + 2 / 3 * (qx - x)) (y + 2 / 3 * (qy - y)) x y
go rest True x y sx sy
SegCubic x1 y1 x2 y2 x y -> do
begin open cx cy
cubic cx cy x1 y1 x2 y2 x y
go rest True x y sx sy
SegArc ax ay rx ry rot a0 sweep0 -> do
-- A sweep past a whole turn draws the whole ellipse once.
let sweep = max (-2 * pi) (min (2 * pi) sweep0)
(x0, y0) = ellipsePoint ax ay rx ry rot a0
(x1, y1)
| abs sweep >= 2 * pi = (x0, y0)
| otherwise = ellipsePoint ax ay rx ry rot (a0 + sweep)
-- A line to the arc's start, or the first point of a new subpath.
emit x0 y0
arcPoints ax ay rx ry rot a0 sweep x1 y1
if open then go rest True x1 y1 sx sy else go rest True x1 y1 x0 y0
SegArcTo rx ry rot large sweepFlag x y -> do
begin open cx cy
case arcCentre cx cy rx ry rot large sweepFlag x y of
Nothing -> emit x y
Just (ax, ay, arx, ary, a0, sweep) -> arcPoints ax ay arx ary rot a0 sweep x y
go rest True x y sx sy
SegClose -> finish open True >> go rest False sx sy sx sy
-- | No coordinate of the segment is NaN or infinite.
segmentFinite :: Segment -> Bool
segmentFinite seg = case seg of
SegMove x y -> finite x && finite y
SegLine x y -> finite x && finite y
SegQuad a b x y -> all finite [a, b, x, y]
SegCubic a b c d x y -> all finite [a, b, c, d, x, y]
SegArc a b c d e f g -> all finite [a, b, c, d, e, f, g]
SegArcTo a b c _ _ x y -> all finite [a, b, c, x, y]
SegClose -> True
-- | The point at angle @a@ on an ellipse with the given centre, radii
-- (negative ones taken as absolute) and rotation.
{-# INLINE ellipsePoint #-}
ellipsePoint :: Float -> Float -> Float -> Float -> Float -> Float -> (Float, Float)
ellipsePoint cx cy rx ry rot a =
let ex = abs rx * cos a
ey = abs ry * sin a
cr = cos rot
sr = sin rot
in (cx + cr * ex - sr * ey, cy + sr * ex + cr * ey)
-- | The number of chords for @sweep@ radians of an ellipse with larger
-- transformed radius @r@, so each chord stays within @tol@ of the curve. At
-- least one per quarter turn, at most 'maxArcSteps'.
arcSteps :: Float -> Float -> Float -> Int
arcSteps tol r sweep
| not (abs sweep <= 4 * pi) = maxArcSteps
| r > tol && ideal < fromIntegral maxArcSteps = max quarters (ceiling ideal)
| r > tol = maxArcSteps
| otherwise = quarters
where
quarters = max 1 (ceiling (abs sweep / (pi / 2)))
ideal = idealArcSteps tol r sweep
-- | The unrounded number of equal chords that keep @sweep@ radians of a
-- circle of radius @r@ within @tol@ of it, for @r > tol@. Grows without
-- bound as @tol / r@ shrinks, so bound it before rounding to an 'Int'.
--
-- A chord of angle @da@ strays @r (1 - cos (da / 2)) = 2 r sin (da / 4) ^ 2@
-- from the circle. Solved in the sine form because @1 - tol / r@ rounds to 1
-- for huge radii, which would give a nearly straight arc as many chords as
-- the caller allows.
{-# INLINE idealArcSteps #-}
idealArcSteps :: Float -> Float -> Float -> Float
idealArcSteps tol r sweep = abs sweep / (4 * asin (sqrt (tol / (2 * r))))
-- | The most chords one arc is split into.
maxArcSteps :: Int
maxArcSteps = 1024
-- | Emit the points after the start of a cubic Bezier from @(x0, y0)@ via
-- @(x1, y1)@ and @(x2, y2)@ to @(x3, y3)@. Splits in halves until each
-- piece's control points keep it within @tol@ of its chord, at most ten
-- levels deep.
{-# INLINE cubicPoints #-}
cubicPoints :: Monad m => Float -> (Float -> Float -> m ()) -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> m ()
cubicPoints tol point = go (0 :: Int)
where
go depth x0 y0 x1 y1 x2 y2 x3 y3
| depth >= 10 || flat = point x3 y3
| otherwise = do
let mx01 = (x0 + x1) / 2
my01 = (y0 + y1) / 2
mx12 = (x1 + x2) / 2
my12 = (y1 + y2) / 2
mx23 = (x2 + x3) / 2
my23 = (y2 + y3) / 2
mx012 = (mx01 + mx12) / 2
my012 = (my01 + my12) / 2
mx123 = (mx12 + mx23) / 2
my123 = (my12 + my23) / 2
mx = (mx012 + mx123) / 2
my = (my012 + my123) / 2
go (depth + 1) x0 y0 mx01 my01 mx012 my012 mx my
go (depth + 1) mx my mx123 my123 mx23 my23 x3 y3
where
ux = 3 * x1 - 2 * x0 - x3
uy = 3 * y1 - 2 * y0 - y3
vx = 3 * x2 - 2 * x3 - x0
vy = 3 * y2 - 2 * y3 - y0
flat = max (ux * ux) (vx * vx) + max (uy * uy) (vy * vy) <= 16 * tol * tol
-- | Convert an SVG arc from @(x1, y1)@ to @(x2, y2)@ (radii @rx0@ and @ry0@,
-- rotation @phi@) to centre form, per the SVG specification: centre, radii
-- (scaled up if too small to reach), start angle and sweep. 'Nothing' when a
-- radius is zero or the ends coincide (SVG draws a line or nothing), or when
-- extreme radii make the centre NaN or infinite. Callers draw 'Nothing' as a
-- straight line, which a huge-radius arc nearly is.
arcCentre :: Float -> Float -> Float -> Float -> Float -> Bool -> Bool -> Float -> Float -> Maybe (Float, Float, Float, Float, Float, Float)
arcCentre x1 y1 rx0 ry0 phi large sweep x2 y2
| rx0 == 0 || ry0 == 0 || (x1 == x2 && y1 == y2) = Nothing
| not (all finite [cx, cy, rx, ry, theta1, dtheta]) = Nothing
| otherwise = Just (cx, cy, rx, ry, theta1, dtheta)
where
cosP = cos phi
sinP = sin phi
dx = (x1 - x2) / 2
dy = (y1 - y2) / 2
x1' = cosP * dx + sinP * dy
y1' = negate sinP * dx + cosP * dy
lambda = (x1' * x1') / (rx0 * rx0) + (y1' * y1') / (ry0 * ry0)
grow = if lambda > 1 then sqrt lambda else 1
rx = abs rx0 * grow
ry = abs ry0 * grow
-- The specification's (rx² ry² - rx² y1'² - ry² x1'²) / (rx² y1'² +
-- ry² x1'²), divided through by rx² ry² so large radii don't overflow.
reach = (x1' / rx) * (x1' / rx) + (y1' / ry) * (y1' / ry)
coef = (if large == sweep then -1 else 1) * sqrt (max 0 (1 / reach - 1))
cx' = coef * rx * y1' / ry
cy' = coef * negate (ry * x1' / rx)
cx = cosP * cx' - sinP * cy' + (x1 + x2) / 2
cy = sinP * cx' + cosP * cy' + (y1 + y2) / 2
angle ux uy vx vy = atan2 (ux * vy - uy * vx) (ux * vx + uy * vy)
theta1 = angle 1 0 ((x1' - cx') / rx) ((y1' - cy') / ry)
dtheta0 = angle ((x1' - cx') / rx) ((y1' - cy') / ry) ((negate x1' - cx') / rx) ((negate y1' - cy') / ry)
dtheta
| not sweep && dtheta0 > 0 = dtheta0 - 2 * pi
| sweep && dtheta0 < 0 = dtheta0 + 2 * pi
| otherwise = dtheta0
--------------------------------------------------------------------------------
-- Triangulation
--------------------------------------------------------------------------------
-- | Triangle index triples covering a simple polygon given as x/y pairs
-- (either winding, first point not repeated). Convex polygons are fanned
-- from the first point; others are ear clipped. Fewer than three points give
-- no triangles. Holes and self-intersections are unsupported and may leave
-- gaps.
triangulate :: PrimArray Float -> PrimArray Int
triangulate vs
| n < 3 = emptyPrimArray
| convexRing vs = generatePrimArray (3 * (n - 2)) fan
| otherwise = earClip vs (generatePrimArray n id)
where
n = sizeofPrimArray vs `div` 2
fan k = case k `mod` 3 of
0 -> 0
1 -> k `div` 3 + 1
_ -> k `div` 3 + 2
-- | Triangle index triples covering a polygon with holes. @vs@ holds every
-- ring's points back to back; @rings@ holds each ring's start plus the end
-- of the last. The first ring is the outline; the rest are holes inside it
-- that touch neither it nor each other. A lone outline may wind either way.
-- With holes, the outline must have a positive 'ringArea' and the holes a
-- negative one, as 'fillPathOps' produces. Each hole is bridged to a visible
-- outline point (as in Eberly's \"Triangulation by Ear Clipping\" and
-- mapbox's earcut), and the merged ring is ear clipped.
triangulateRings :: PrimArray Float -> PrimArray Int -> PrimArray Int
triangulateRings vs rings
| sizeofPrimArray rings <= 2 = triangulate vs
| otherwise = earClip vs (primArrayFromList (bridgeHoles vs (ringAt 0) (map ringAt [1 .. sizeofPrimArray rings - 2])))
where
ringAt r = [indexPrimArray rings r .. indexPrimArray rings (r + 1) - 1]
-- | The outline's point indices with each hole spliced in, leftmost hole
-- first. A splice runs from the outline point bridged to the hole's leftmost
-- point, around the hole, and back along the bridge. A hole with no visible
-- outline point is dropped.
bridgeHoles :: PrimArray Float -> [Int] -> [[Int]] -> [Int]
bridgeHoles vs outline holes = foldl' join outline (map snd (sortOn fst (map leftmostFirst (filter (not . null) holes))))
where
at = pointAt vs
-- The hole rotated to start at its leftmost point, keyed by that point.
leftmostFirst h =
let (p, m) = minimum [(at i, k) | (k, i) <- zip [0 :: Int ..] h]
in (p, drop m h ++ take m h)
join ring h@(hi : _) = case bridgeFrom ring (at hi) of
Nothing -> ring
Just k ->
let (before, after) = splitAt (k + 1) ring
in before ++ h ++ [hi, ring !! k] ++ after
join ring [] = ring
-- The ring position to bridge @(hx, hy)@ to. A ray cast left hits the
-- nearest edge, and the bridge goes to that edge's left end, unless
-- ring points inside the triangle it forms with the ray block the view;
-- then it goes to the one at the smallest angle to the ray.
bridgeFrom ring (hx, hy) =
let n = length ring
ix = primArrayFromListN n ring
node k = indexPrimArray ix (k `mod` n)
pt k = at (node k)
hits =
[ (x, k')
| k <- [0 .. n - 1]
, let (ax, ay) = pt k
(bx, by) = pt (k + 1)
, hy <= ay && hy >= by && by /= ay
, let x = ax + (hy - ay) * (bx - ax) / (by - ay)
, x <= hx
, let k' = if ax < bx then k else (k + 1) `mod` n
]
in case hits of
[] -> Nothing
_ ->
let (qx, m) = maximum hits
(mx, my) = pt m
-- The bridge from the hole point to ring point @k@ enters
-- the ring's interior at that corner.
locallyInside k =
let a = pt k
prev = pt (k - 1)
next = pt (k + 1)
h = (hx, hy)
in if turn prev a next < 0
then turn a h next >= 0 && turn a prev h >= 0
else turn a h prev < 0 || turn a next h < 0
better (tanBest, kBest) k =
let (px, py) = pt k
t = abs (hy - py) / (hx - px)
in if hx >= px && px >= mx && hx /= px && pointInTri (px, py) (hx, hy) (qx, hy) (mx, my) && locallyInside k
&& (t < tanBest || (t == tanBest && px > fst (pt kBest)))
then (t, k)
else (tanBest, kBest)
in if qx == hx then Just m else Just (snd (foldl' better (1 / 0, m) [0 .. n - 1]))
-- | Twice a triangle's signed area, with earcut's sign: negative at a convex
-- corner of a ring with positive 'signedArea'. The negated 'cross' of its
-- edges, which 'isConvex' tests.
turn :: (Float, Float) -> (Float, Float) -> (Float, Float) -> Float
turn p q r = negate (cross (diff p q) (diff q r))
-- | Whether the ring is convex: every corner turns the same way (straight
-- ones aside) and it winds once. Winding once is checked by the x and y
-- directions each reversing at most twice, which a doubly wound star fails.
convexRing :: PrimArray Float -> Bool
convexRing vs = go 0 0 0 0 0 0
where
n = sizeofPrimArray vs `div` 2
go :: Int -> Int -> Int -> Int -> Int -> Int -> Bool
go !i !turn' !xs !ys !lastX !lastY
| i >= n = True
| otherwise =
-- Strict coordinates: lazily bound point tuples cost a thunk and
-- boxes per point. 'triangulate' calls this with n >= 3, so one
-- subtraction wraps an index.
let !i1 = if i + 1 >= n then i + 1 - n else i + 1
!i2 = if i1 + 1 >= n then i1 + 1 - n else i1 + 1
!x0 = indexPrimArray vs (2 * i)
!y0 = indexPrimArray vs (2 * i + 1)
!x1 = indexPrimArray vs (2 * i1)
!y1 = indexPrimArray vs (2 * i1 + 1)
!x2 = indexPrimArray vs (2 * i2)
!y2 = indexPrimArray vs (2 * i2 + 1)
!c = (x1 - x0) * (y2 - y1) - (x2 - x1) * (y1 - y0)
!turn'' = if c > 0 then 1 else if c < 0 then -1 else turn'
!sx = signum' (x1 - x0)
!sy = signum' (y1 - y0)
!xs' = if sx /= 0 && lastX /= 0 && sx /= lastX then xs + 1 else xs
!ys' = if sy /= 0 && lastY /= 0 && sy /= lastY then ys + 1 else ys
in if turn' /= 0 && turn'' /= turn' || xs' > 2 || ys' > 2
then False
else go (i + 1) turn'' xs' ys' (if sx /= 0 then sx else lastX) (if sy /= 0 then sy else lastY)
signum' v = if v > 0 then 1 else if v < 0 then -1 else 0 :: Int
{-# INLINE pointAt #-}
pointAt :: PrimArray Float -> Int -> (Float, Float)
pointAt vs i =
let !x = indexPrimArray vs (2 * i)
!y = indexPrimArray vs (2 * i + 1)
in (x, y)
-- | The shoelace area of the points of @vs@ listed by @ix@, in order.
-- Positive for a ring clockwise on screen.
signedArea :: PrimArray Float -> PrimArray Int -> Float
signedArea vs ix = shoelace (sizeofPrimArray ix) (pointAt vs . indexPrimArray ix)
-- | 'signedArea' of a ring's points in their own order.
ringArea :: PrimArray Float -> Float
ringArea vs = shoelace (sizeofPrimArray vs `div` 2) (pointAt vs)
-- | The shoelace area of @n@ points, point @k@ being @at k@. Positive for a
-- ring clockwise on screen; the polygon emitter uses the sign for winding.
{-# INLINE shoelace #-}
shoelace :: Int -> (Int -> (Float, Float)) -> Float
shoelace n at = go 0 0
where
go !k !acc
| k >= n = acc / 2
| otherwise = go (k + 1) (acc + cross (at k) (at (if k + 1 >= n then 0 else k + 1)))
cross :: (Float, Float) -> (Float, Float) -> Float
cross (x0, y0) (x1, y1) = x0 * y1 - x1 * y0
diff :: (Float, Float) -> (Float, Float) -> (Float, Float)
diff (x0, y0) (x1, y1) = (x1 - x0, y1 - y0)
isConvex :: Bool -> (Float, Float) -> (Float, Float) -> (Float, Float) -> Bool
isConvex ccw a b c =
let ab = diff a b
bc = diff b c
in if ccw then cross ab bc >= 0 else cross ab bc <= 0
pointInTri :: (Float, Float) -> (Float, Float) -> (Float, Float) -> (Float, Float) -> Bool
pointInTri p a b c =
let sign (p1, p2, p3) = cross (diff p1 p3) (diff p2 p3)
d1 = sign (p, a, b)
d2 = sign (p, b, c)
d3 = sign (p, c, a)
in not ((d1 < 0 || d2 < 0 || d3 < 0) && (d1 > 0 || d2 > 0 || d3 > 0))
-- | Triangle index triples into @vs@ covering the ring listed by @ix@. A
-- hole bridge lists its end points twice, so a point on an ear's corner does
-- not block the ear.
--
-- After an ear is cut the scan goes on from its next corner, and the points
-- that could block an ear are looked up in a grid of the remaining points,
-- so a typical ring costs about linear time rather than a full pass of
-- every point per ear.
earClip :: PrimArray Float -> PrimArray Int -> PrimArray Int
earClip vs ix = runPrimArray $ do
let !ccw = signedArea vs ix >= 0
-- Remove an ear by relinking its neighbours instead of copying the
-- remaining points at every step.
prevs <- newPrimArray n
nexts <- newPrimArray n
forM_ [0 .. n - 1] $ \i -> do
writePrimArray prevs i (if i == 0 then n - 1 else i - 1)
writePrimArray nexts i (if i + 1 == n then 0 else i + 1)
-- The remaining points by cell: cell @c@ holds the first @lens c@ entries
-- of its span of @members@, and @slots@ says where each point is.
members <- thawPrimArray (gridItems grid) 0 n
lens <- newPrimArray cellCount
forM_ [0 .. cellCount - 1] $ \c -> writePrimArray lens c (start (c + 1) - start c)
slots <- newPrimArray n
forM_ [0 .. n - 1] $ \k -> readPrimArray members k >>= \i -> writePrimArray slots i k
out <- newPrimArray (3 * max 0 (n - 2))
let remove i = do
let !c = cellOf (at i)
len <- readPrimArray lens c
slot <- readPrimArray slots i
moved <- readPrimArray members (start c + len - 1)
writePrimArray members slot moved
writePrimArray slots moved slot
writePrimArray lens c (len - 1)
-- Whether a remaining point lies in the ear @p i q@. One on a corner
-- (the other end of a hole bridge) does not block it. The loops only
-- tail call each other, so they compile to jumps, not closures.
blocked p i q a@(ax, ay) b@(bx, by) c@(cx, cy) = cell r0 c0
where
!c0 = gridCol grid (min ax (min bx cx))
!c1 = gridCol grid (max ax (max bx cx))
!r0 = gridRow grid (min ay (min by cy))
!r1 = gridRow grid (max ay (max by cy))
cell !r !col
| r > r1 = pure False
| col > c1 = cell (r + 1) c0
| otherwise = do
let !k = r * gridCols grid + col
len <- readPrimArray lens k
scan r col (start k) (start k + len)
scan !r !col !k !end
| k >= end = cell r (col + 1)
| otherwise = do
j <- readPrimArray members k
let !pj = at j
if j /= p && j /= i && j /= q && pointInTri pj a b c && pj /= a && pj /= b && pj /= c
then pure True
else scan r col (k + 1) end
emit !m p i q = do
writePrimArray out m (indexPrimArray ix p)
writePrimArray out (m + 1) (indexPrimArray ix i)
writePrimArray out (m + 2) (indexPrimArray ix q)
pure (m + 3)
convex !_ 0 = pure True
convex !i !left = do
p <- readPrimArray prevs i
q <- readPrimArray nexts i
if isConvex ccw (at p) (at i) (at q) then convex q (left - 1) else pure False
fan !m !origin !i !left
| left <= 0 = pure m
| otherwise = do
q <- readPrimArray nexts i
m' <- emit m origin i q
fan m' origin q (left - 1)
go !m !count !i !tries
| count < 3 = pure m
| count == 3 = do
p <- readPrimArray prevs i
q <- readPrimArray nexts i
emit m p i q
| tries >= count = do
-- A whole pass found no ear: fan a convex remainder, else stop.
isConvexRing <- convex i count
if isConvexRing then readPrimArray nexts i >>= \q -> fan m i q (count - 2) else pure m
| otherwise = do
p <- readPrimArray prevs i
q <- readPrimArray nexts i
let !a = at p
!b = at i
!c = at q
ear <- if isConvex ccw a b c then not <$> blocked p i q a b c else pure False
if ear
then do
writePrimArray nexts p q
writePrimArray prevs q p
remove i
m' <- emit m p i q
go m' (count - 1) q 0
else go m count q (tries + 1)
m <- go 0 n 0 0
shrinkMutablePrimArray out m
pure out
where
n = sizeofPrimArray ix
at k = pointAt vs (indexPrimArray ix k)
-- About four points per cell. A point that is not finite could block
-- any ear, so then every point shares one cell.
(x0, y0, x1, y1) = ringBox vs
cells = if all (finite . indexPrimArray vs) [0 .. sizeofPrimArray vs - 1] then n `div` 4 else 1
grid = gridOf cells x0 y0 x1 y1 n (\k -> let (x, y) = at k in (x, y, x, y))
cellCount = gridCols grid * gridRows grid
start = indexPrimArray (gridStarts grid)
cellOf (x, y) = gridRow grid y * gridCols grid + gridCol grid x
--------------------------------------------------------------------------------
-- Grids
--------------------------------------------------------------------------------
-- | Items bucketed by a uniform grid of about square cells over a box. Cell
-- @c@, counted along rows, lists the items whose boxes overlap it, in item
-- order: 'gridItems' from @'gridStarts' c@ up to @'gridStarts' (c + 1)@.
data Grid = Grid
{ gridCols :: !Int
, gridRows :: !Int
, gridX :: !Float
, gridY :: !Float
, gridScaleX :: !Float
-- ^ Columns per unit of x (0 with one column).
, gridScaleY :: !Float
, gridStarts :: !(PrimArray Int)
, gridItems :: !(PrimArray Int)
}
-- | The column of the cells holding an x coordinate, clamped to the grid.
{-# INLINE gridCol #-}
gridCol :: Grid -> Float -> Int
gridCol g = cellAlong (gridCols g) (gridX g) (gridScaleX g)
-- | The row of the cells holding a y coordinate, clamped to the grid.
{-# INLINE gridRow #-}
gridRow :: Grid -> Float -> Int
gridRow g = cellAlong (gridRows g) (gridY g) (gridScaleY g)
-- | The cell along one axis holding a coordinate, clamped to @0 .. cells - 1@.
-- Monotonic, so the cells a box's corners fall in bound the cells of every
-- point in the box.
{-# INLINE cellAlong #-}
cellAlong :: Int -> Float -> Float -> Float -> Int
cellAlong cells origin perUnit v = max 0 (min (cells - 1) (truncate ((v - origin) * perUnit)))
-- | A grid of about @cells@ cells over the box from @(x0, y0)@ to @(x1, y1)@,
-- holding items @0 .. count - 1@; item @k@ covers @boxOf k@. A box that is
-- not finite gets one cell, and a side under 1e-20 a single row or column.
{-# INLINE gridOf #-}
gridOf :: Int -> Float -> Float -> Float -> Float -> Int -> (Int -> (Float, Float, Float, Float)) -> Grid
gridOf cells x0 y0 x1 y1 count boxOf = runST $ do
-- Explicit loops: list ranges here are shared across iterations rather
-- than fused, and cost a cell per step.
let forCells f = item 0
where
item !k
| k >= count = pure ()
| otherwise = do
let (bx0, by0, bx1, by1) = boxOf k
!c0 = cellAlong cols x0 sx bx0
!c1 = cellAlong cols x0 sx bx1
!r1 = cellAlong rows y0 sy by1
cell !r !c
| r > r1 = item (k + 1)
| c > c1 = cell (r + 1) c0
| otherwise = f k (r * cols + c) >> cell r (c + 1)
cell (cellAlong rows y0 sy by0) c0
(starts, fill) <- bucketOffsets total (\emit -> forCells (\_ c -> emit c))
size <- readPrimArray starts total
items <- newPrimArray size
forCells $ \k c -> do
slot <- readPrimArray fill c
writePrimArray items slot k
writePrimArray fill c (slot + 1)
Grid cols rows x0 y0 sx sy <$> unsafeFreezePrimArray starts <*> unsafeFreezePrimArray items
where
w = x1 - x0
h = y1 - y0
target = max 1 cells
usable s = s > 1e-20 && finite s
(cols, rows)
| not (finite w && finite h) = (1, 1)
| usable w && usable h =
let side = sqrt w * sqrt h / sqrt (fromIntegral target)
in (fit (w / side), fit (h / side))
| otherwise = (if usable w then target else 1, if usable h then target else 1)
fit v = max 1 (ceiling (min (fromIntegral target) v))
total = cols * rows
sx = if cols > 1 then fromIntegral cols / w else 0
sy = if rows > 1 then fromIntegral rows / h else 0
-- | A ring's bounding box: its least and greatest x and y.
ringBox :: PrimArray Float -> (Float, Float, Float, Float)
ringBox r = go 0 (1 / 0) (1 / 0) (-1 / 0) (-1 / 0)
where
go !k !x0 !y0 !x1 !y1
| k + 1 >= sizeofPrimArray r = (x0, y0, x1, y1)
| otherwise =
let !x = indexPrimArray r k
!y = indexPrimArray r (k + 1)
in go (k + 2) (min x0 x) (min y0 y) (max x1 x) (max y1 y)
--------------------------------------------------------------------------------
-- Draw ops
--------------------------------------------------------------------------------
-- | Each ring's points with near-duplicates dropped, and whether it was
-- closed. Rings with a NaN or infinite coordinate are skipped. A point
-- within 1e-4 px of the previous one is a duplicate; with @closing@, or for
-- a closed ring, so is a last point on the first. A lone move, one point
-- that is not closed, is left out: it draws nothing, even with caps.
cleanRings :: Bool -> Rings -> [(PrimArray Float, Bool)]
cleanRings closing rings@(Rings pts starts tags) =
[ (kept, closed)
| r <- [0 .. ringCount rings - 1]
, let from = indexPrimArray starts r
to = indexPrimArray starts (r + 1)
closed = indexPrimArray tags r /= 0
, closed || to - from > 1
, all (\k -> finite (indexPrimArray pts k)) [2 * from .. 2 * to - 1]
, let kept = dedupe (closing || closed) from to
]
where
near ax ay bx by = let dx = ax - bx; dy = ay - by in dx * dx + dy * dy < 1e-8
dedupe wrap from to = runPrimArray $ do
out <- newPrimArray (2 * (to - from))
let copy !k !m
| k >= to = pure m
| otherwise = do
let x = indexPrimArray pts (2 * k)
y = indexPrimArray pts (2 * k + 1)
repeated <-
if m == 0
then pure False
else near x y <$> readPrimArray out (2 * m - 2) <*> readPrimArray out (2 * m - 1)
if repeated
then copy (k + 1) m
else do
writePrimArray out (2 * m) x
writePrimArray out (2 * m + 1) y
copy (k + 1) (m + 1)
m <- copy from 0
m' <-
if wrap && m > 1
then do
onFirst <- near <$> readPrimArray out 0 <*> readPrimArray out 1 <*> readPrimArray out (2 * m - 2) <*> readPrimArray out (2 * m - 1)
pure (if onFirst then m - 1 else m)
else pure m
shrinkMutablePrimArray out (2 * m')
pure out
-- | Draw ops that fill a path, flattened through @t@ within @tol@: one
-- 'FillPolygon' per outline (open subpaths are filled as closed), with the
-- holes the fill rule makes cut out. A subpath is a hole when the rule
-- leaves it unfilled. Crossing subpaths fill independently, and a
-- self-intersecting one may fill only partly.
fillPathOps :: Float -> Transform -> FillRule -> Path -> Paint -> [DrawOp]
fillPathOps tol t rule path paint = concatMap polygonOp (fillComponents rule rings)
where
rings =
[ pts
| (pts, _) <- cleanRings True (flattenPath tol (arcSteps tol) t path)
, abs (ringArea pts) > 1e-6
]
polygonOp (outline, holes) = case devicePaint t paint of
DeviceSolid col ->
let pts = concatPoints (outline : holes)
starts = ringStarts (outline : holes)
tris = triangulateRings pts starts
in [FillPolygon pts starts tris (Flat col) | nonEmpty tris]
DeviceRamp ramp ->
-- Split ring edges and triangles at every stop, so each piece's
-- colour interpolates linearly between its corners.
let rs = map (\r -> splitEdges (rampAt ramp) (rampSplits ramp) True r) (outline : holes)
outlinePts = concatPoints rs
starts = ringStarts rs
(pts, tris) = splitTriangles (rampAt ramp) (rampSplits ramp) outlinePts (triangulateRings outlinePts starts)
in [FillPolygon pts starts tris (Shaded (rampShades ramp pts)) | nonEmpty tris]
nonEmpty a = sizeofPrimArray a > 0
-- | Draw ops that stroke a path, flattened through @t@ within @tol@: one
-- 'StrokePolyline' per subpath or per dash. Width and dash lengths scale by
-- the square root of the transform's area scale.
strokePathOps :: Float -> Transform -> Stroke -> Path -> Paint -> [DrawOp]
strokePathOps tol t st path paint
| not (width > 0) = []
| otherwise = concatMap ring (cleanRings False (flattenPath tol (arcSteps tol) t path))
where
k = averageStretch t
width = strokeWidth st * k
shade = devicePaint t paint
ring (pts, closed)
-- A subpath of zero length is a dot for round and square caps, a
-- square one aligned with the x axis, as in SVG.
| n == 1 = [line False (strokeCap st) (dot pts) | strokeCap st /= ButtCap]
| n < 2 = []
| not (null (strokeDash st))
, Just pieces <- dashes (strokeCap st /= ButtCap) (map (* k) (strokeDash st)) (strokeDashOffset st * k) closed pts =
map (line False (strokeCap st)) pieces
-- A closed subpath of two points is a line that turns back on itself
-- at each end: a round join rounds the ends, and a miter (past any
-- limit) or bevel at a half turn is flat.
| closed && n == 2 = [line False (if strokeJoin st == RoundJoin then RoundCap else ButtCap) pts]
| otherwise = [line closed (strokeCap st) pts]
where
n = sizeofPrimArray pts `div` 2
-- The point and another a hair along the transformed x axis, so its
-- caps have a direction.
dot pts =
let x = indexPrimArray pts 0
y = indexPrimArray pts 1
Transform a b _ _ _ _ = t
len = sqrt (a * a + b * b)
(ux, uy) = if len > 0 && finite len then (a / len, b / len) else (1, 0)
in primArrayFromListN 4 [x, y, x + 1e-3 * ux, y + 1e-3 * uy]
line closed cap pts = case shade of
DeviceSolid col -> StrokePolyline pts width closed cap (strokeJoin st) (strokeMiterLimit st) (Flat col)
DeviceRamp ramp ->
let pts' = splitEdges (rampAt ramp) (rampSplits ramp) closed pts
in StrokePolyline pts' width closed cap (strokeJoin st) (strokeMiterLimit st) (Shaded (rampShades ramp pts'))
-- | All rings' points, back to back.
concatPoints :: [PrimArray Float] -> PrimArray Float
concatPoints [r] = r
concatPoints rs = mconcat rs
-- | Where each ring starts in 'concatPoints', and where the last ends.
ringStarts :: [PrimArray Float] -> PrimArray Int
ringStarts [r] = primArrayFromListN 2 [0, sizeofPrimArray r `div` 2]
ringStarts rs = primArrayFromList (scanl (+) 0 [sizeofPrimArray r `div` 2 | r <- rs])
-- | Group rings into outlines with their holes under the fill rule. Where
-- there are holes, the outline gets a positive 'ringArea' and the holes a
-- negative one. A ring is inside another when all its points are. Crossing
-- a ring inward changes the winding number by one, with the sign of the
-- ring's orientation, and the rule decides which regions fill. A filled
-- ring with no filled parent is an outline. An unfilled ring directly inside
-- it, or inside filled rings within it, is one of its holes. Crossing rings
-- are not nested, so each fills on its own. Copies of one loop, in either
-- direction, nest in turn like rings a hair apart, and an outline whose
-- hole is its own copy encloses nothing, so it draws nothing.
--
-- A ring's parent is the smallest larger ring holding all its points. The
-- rings whose boxes hold its box are found through a grid of the boxes and
-- tried smallest first, so mostly only the parent is tested point by point.
fillComponents :: FillRule -> [PrimArray Float] -> [(PrimArray Float, [PrimArray Float])]
fillComponents _ [r] = [(r, [])]
fillComponents rule rs =
[ (orient True i, map (orient False) hs)
| i <- ids
, outline i
, let hs = holesOf i
, not (any (sameLoop (ring i) . ring) hs)
]
where
count = length rs
ids = [0 .. count - 1]
rings = smallArrayFromListN count rs
ring = indexSmallArray rings
areas = primArrayFromListN count (map ringArea rs)
areaOf i = indexPrimArray areas i
-- No area is NaN: 'fillPathOps' keeps only rings whose area is over 1e-6.
size i = abs (areaOf i)
boxes = smallArrayFromListN count (map ringBox rs)
boxOf = indexSmallArray boxes
-- Ring ids smallest first (the sort is stable, so equal sizes stay in id
-- order), and a grid of their boxes in that order, so each cell lists its
-- rings smallest first.
bySize = primArrayFromListN count (sortBy (comparing size) ids)
-- Each ring's place in 'bySize'.
rank = indexPrimArray $ runPrimArray $ do
out <- newPrimArray count
forM_ [0 .. count - 1] $ \k -> writePrimArray out (indexPrimArray bySize k) k
pure out
grid =
let (x0, y0, x1, y1) = foldl' union (1 / 0, 1 / 0, -1 / 0, -1 / 0) boxes
union (!a, !b, !c, !d) (bx0, by0, bx1, by1) = (min a bx0, min b by0, max c bx1, max d by1)
in gridOf count x0 y0 x1 y1 count (boxOf . indexPrimArray bySize)
-- The smallest ring enclosing ring @i@. A box holding @i@'s box holds
-- its corner, so the corner's cell lists every candidate. A copy of
-- @i@'s loop later in 'bySize' encloses it too, so copies chain and the
-- rings inside them find the first copy.
parents = generatePrimArray count parentOf
parentOf i = candidate (indexPrimArray (gridStarts grid) cell)
where
box@(bx0, by0, _, _) = boxOf i
cell = gridRow grid by0 * gridCols grid + gridCol grid bx0
end = indexPrimArray (gridStarts grid) (cell + 1)
candidate !k
| k >= end = -1
| size j > size i && boxInside box (boxOf j) && encloses (ring j) (ring i) = j
| rank j > rank i && sameLoop (ring j) (ring i) = j
| otherwise = candidate (k + 1)
where
j = indexPrimArray bySize (indexPrimArray (gridItems grid) k)
parent i = let p = indexPrimArray parents i in if p < 0 then Nothing else Just p
-- The winding number just inside ring @i@: its parent's plus or minus
-- one. Boxed and lazy so each ring can read its parent's.
windings = smallArrayFromListN count (map windingOf ids)
windingOf i = maybe 0 (indexSmallArray windings) (parent i) + (if areaOf i > 0 then 1 else -1) :: Int
filled i = fillsWinding rule (indexSmallArray windings i)
outline i = filled i && maybe True (not . filled) (parent i)
-- Each ring's children in id order, gathered in one pass.
children = indexSmallArray $ runSmallArray $ do
kids <- newSmallArray count []
forM_ [count - 1, count - 2 .. 0] $ \j -> do
let p = indexPrimArray parents j
when (p >= 0) (readSmallArray kids p >>= writeSmallArray kids p . (j :))
pure kids
holesOf i = concat [if filled c then holesOf c else [c] | c <- children i]
orient positive i
| (areaOf i >= 0) == positive = ring i
| otherwise = reversePoints (ring i)
boxInside (ax0, ay0, ax1, ay1) (bx0, by0, bx1, by1) = ax0 >= bx0 && ay0 >= by0 && ax1 <= bx1 && ay1 <= by1
-- | Whether every point of ring @q@ is inside ring @r@, by ray crossing
-- parity. A point on @r@'s outline may count either way: on a rect's left or
-- top edge it is inside, on its right or bottom edge outside.
encloses :: PrimArray Float -> PrimArray Float -> Bool
encloses r q = every 0
where
every !k
| k + 1 >= sizeofPrimArray q = True
| otherwise = inside (indexPrimArray q k) (indexPrimArray q (k + 1)) && every (k + 2)
m = sizeofPrimArray r `div` 2
inside px py = walk 0 False
where
walk !k !odd'
| k >= m = odd'
| otherwise =
let !k' = if k + 1 >= m then 0 else k + 1
!ax = indexPrimArray r (2 * k)
!ay = indexPrimArray r (2 * k + 1)
!bx = indexPrimArray r (2 * k')
!by = indexPrimArray r (2 * k' + 1)
crosses = (ay > py) /= (by > py) && px < ax + (py - ay) * (bx - ax) / (by - ay)
in walk (k + 1) (if crosses then not odd' else odd')
-- | Whether two rings list the same points around the same loop, from any
-- start and in either direction.
sameLoop :: PrimArray Float -> PrimArray Float -> Bool
sameLoop r q = sizeofPrimArray r == sizeofPrimArray q && m > 0 && any from [s | s <- [0 .. m - 1], pointAt r s == pointAt q 0]
where
m = sizeofPrimArray r `div` 2
from s = all (\k -> pointAt r ((s + k) `mod` m) == pointAt q k) [1 .. m - 1] || all (\k -> pointAt r ((s - k) `mod` m) == pointAt q k) [1 .. m - 1]
-- | A ring's points in reverse order.
reversePoints :: PrimArray Float -> PrimArray Float
reversePoints r =
let m = sizeofPrimArray r `div` 2
in generatePrimArray (2 * m) (\i -> indexPrimArray r (2 * (m - 1 - i `div` 2) + i `mod` 2))
--------------------------------------------------------------------------------
-- Gradients
--------------------------------------------------------------------------------
-- | A paint in device coordinates.
data DevicePaint
= DeviceSolid !Color
| DeviceRamp !Ramp
-- | A linear gradient in device coordinates: its value at @(x, y)@ is
-- @gx x + gy y + g0@. Stop offsets are non-decreasing within 0..1.
data Ramp = Ramp !Float !Float !Float ![(Float, Color)]
-- | Map a paint from drawing coordinates to device coordinates. A
-- gradient's device value at a point is its value at the inverse-transformed
-- point, which is still linear in the point.
devicePaint :: Transform -> Paint -> DevicePaint
devicePaint _ (Solid c) = DeviceSolid c
devicePaint t@(Transform a b c d _ _) (Linear (V2 x0 y0) (V2 x1 y1) stops0) = case stops of
[] -> DeviceSolid (Color 0)
[(_, col)] -> DeviceSolid col
_
| len2 > 0 && det /= 0 && all finite [gx, gy, g0] -> DeviceRamp (Ramp gx gy g0 stops)
| otherwise -> DeviceSolid (snd (last stops))
where
stops = rising 0 stops0
rising lo ((o, col) : rest) = let o' = max lo (min 1 o) in (o', col) : rising o' rest
rising _ [] = []
dx = x1 - x0
dy = y1 - y0
len2 = dx * dx + dy * dy
det = a * d - b * c
-- The gradient's direction over its length squared, through the
-- inverse transpose of the transform's linear part.
gx = (d * dx - b * dy) / det / len2
gy = (a * dy - c * dx) / det / len2
(px, py) = applyTransform t x0 y0
g0 = negate (gx * px + gy * py)
-- | A gradient's value at a point.
{-# INLINE rampAt #-}
rampAt :: Ramp -> Float -> Float -> Float
rampAt (Ramp gx gy g0 _) x y = gx * x + gy * y + g0
-- | The gradient values where the colour changes slope: its distinct stop
-- offsets, ascending. A hard edge (stops at one offset in different
-- colours) splits half a pixel either side of it instead, so the pieces
-- beside it keep their own colours and only the pixel across it blends.
rampSplits :: Ramp -> [Float]
rampSplits (Ramp gx gy _ stops) = nubAsc (sort (concatMap around (nubAsc (map fst stops))))
where
half = 0.5 * sqrt (gx * gx + gy * gy)
around v = case [c | (o, c) <- stops, o == v] of
c0 : rest | any (/= c0) rest -> [v - half, v + half]
_ -> [v]
nubAsc = map NE.head . NE.group
-- | The gradient's colour at each point.
rampShades :: Ramp -> PrimArray Float -> PrimArray Word32
rampShades ramp@(Ramp _ _ _ stops) pts =
generatePrimArray (sizeofPrimArray pts `div` 2) $ \i ->
let (x, y) = pointAt pts i
Color w = rampColor stops (rampAt ramp x y)
in w
-- | The colour at a gradient value, given stops in non-decreasing order.
rampColor :: [(Float, Color)] -> Float -> Color
rampColor stops v = case stops of
(o0, c0) : _ | v <= o0 -> c0
_ -> go stops
where
go ((o0, c0) : rest@((o1, c1) : _))
| v < o1 = lerpColor c0 c1 ((v - o0) / (o1 - o0))
| otherwise = go rest
go [(_, c)] = c
go [] = Color 0
-- | A polyline's points with a point inserted wherever an edge crosses a
-- value in @vs@ of @g@, in order along the edge. With @closed@, the closing
-- edge is split too.
splitEdges :: (Float -> Float -> Float) -> [Float] -> Bool -> PrimArray Float -> PrimArray Float
splitEdges g vs closed pts = primArrayFromList (concat [x : y : cuts i | i <- [0 .. m - 1], let (x, y) = pointAt pts i])
where
m = sizeofPrimArray pts `div` 2
cuts i
| i == m - 1 && not closed = []
| otherwise =
let (ax, ay) = pointAt pts i
(bx, by) = pointAt pts ((i + 1) `mod` m)
ga = g ax ay
gb = g bx by
us = sort [(v - ga) / (gb - ga) | v <- vs, min ga gb < v, v < max ga gb]
in concat [[ax + u * (bx - ax), ay + u * (by - ay)] | u <- us]
-- | Cut triangles along the lines where @g@ equals each value in @vs@
-- (ascending), so no piece straddles one. Returns the points with the new
-- corners appended, and the pieces' index triples. A cut point is computed
-- from its edge's lower-indexed end, so both triangles sharing the edge put
-- it in exactly the same place.
splitTriangles :: (Float -> Float -> Float) -> [Float] -> PrimArray Float -> PrimArray Int -> (PrimArray Float, PrimArray Int)
splitTriangles g vs pts tris = (pts <> primArrayFromList [c | (x, y) <- reverse added, c <- [x, y]], primArrayFromList (reverse out))
where
n0 = sizeofPrimArray pts `div` 2
corner i = let (x, y) = pointAt pts i in (i, x, y, g x y)
(_, added, out) = foldl' triangle (n0, [], []) [(indexPrimArray tris (3 * t), indexPrimArray tris (3 * t + 1), indexPrimArray tris (3 * t + 2)) | t <- [0 .. sizeofPrimArray tris `div` 3 - 1]]
triangle acc (i, j, k) =
let poly = map corner [i, j, k]
gs = [v | (_, _, _, v) <- poly]
cutsHere = [v | v <- vs, minimum gs < v, v < maximum gs]
(acc', rest) = foldl' cut (acc, poly) cutsHere
in fanOut acc' rest
-- Fan out the part below the value; the part above goes to the next cut.
cut ((next, adds, tris'), poly) v =
let edges = zip poly (drop 1 poly ++ take 1 poly)
step (nx, ads, lower, upper) (p@(_, _, _, gp), q@(_, _, _, gq))
| (gp < v && v < gq) || (gq < v && v < gp) =
let (a, b) = if first p q then (p, q) else (q, p)
(_, ax, ay, ga) = a
(_, bx, by, gb) = b
u = (v - ga) / (gb - ga)
cx = ax + u * (bx - ax)
cy = ay + u * (by - ay)
c = (nx, cx, cy, v)
in (nx + 1, (cx, cy) : ads, c : keepBelow p lower, c : keepAbove p upper)
| otherwise = (nx, ads, keepBelow p lower, keepAbove p upper)
keepBelow p@(_, _, _, gp) acc = if gp <= v then p : acc else acc
keepAbove p@(_, _, _, gp) acc = if gp >= v then p : acc else acc
(next', adds', belowR, aboveR) = foldl' step (next, adds, [], []) edges
-- The crossing goes after its edge's first end.
below = reverse belowR
above = reverse aboveR
(next'', adds'', tris'') = fanOut (next', adds', tris') below
in ((next'', adds'', tris''), above)
first (i, _, _, _) (j, _, _, _) = i <= j
fanOut acc@(nx, ads, ts) poly = case poly of
(a, _, _, _) : rest@(_ : _ : _) -> (nx, ads, foldl' (\acc' ((b, _, _, _), (c, _, _, _)) -> c : b : a : acc') ts (zip rest (drop 1 rest)))
_ -> acc
--------------------------------------------------------------------------------
-- Dashes
--------------------------------------------------------------------------------
-- | Split a polyline into dashes for a pattern and start offset. Each dash
-- is an open polyline. With @dots@, a zero-length dash gets a hair of length
-- so its caps have a direction; without, it is left out, as butt caps draw
-- nothing there. On a closed polyline, a dash through the start point is one
-- dash: the last one runs on into the first. 'Nothing' means draw solid: an
-- empty pattern, one with a negative or infinite length or all zeros, a
-- non-finite offset, or more than 'maxDashes' dashes.
--
-- NOINLINE: inlined, its bindings are allocated for every stroke, dashed or
-- not.
{-# NOINLINE dashes #-}
dashes :: Bool -> [Float] -> Float -> Bool -> PrimArray Float -> Maybe [PrimArray Float]
dashes dots pattern0 offset closed pts
| null pattern0 || any (\v -> not (v >= 0) || isInfinite v) pattern0 || not (period > 0) || isInfinite period = Nothing
| not (finite offset) || fromIntegral (length pattern `div` 2) * (total / period + 1) > (fromIntegral maxDashes :: Float) = Nothing
| otherwise = case path of
p0 : rest -> Just [primArrayFromList (concat [[x, y] | (x, y) <- d]) | d <- seam (filter (not . null) (walk k0 left0 [p0 | even k0] (0, 0) p0 rest))]
[] -> Nothing
where
pattern = if odd (length pattern0) then pattern0 ++ pattern0 else pattern0
plen = length pattern
entries = primArrayFromListN plen pattern
entry k = indexPrimArray entries (k `mod` plen)
period = sum pattern
widest = maximum pattern
m = sizeofPrimArray pts `div` 2
path = [pointAt pts i | i <- [0 .. m - 1]] ++ [pointAt pts 0 | closed]
total = sum (zipWith dist path (drop 1 path))
dist (ax, ay) (bx, by) = sqrt ((bx - ax) * (bx - ax) + (by - ay) * (by - ay))
-- The pattern entry the line starts in and how much of it remains. A
-- zero-length dash at the very start is kept as a dot. The offset is
-- taken modulo the period in double precision, and kept within it, so
-- a large offset cannot start past the entry it lands in.
(k0, left0) =
let o = realToFrac (realToFrac offset `mod'` (realToFrac period :: Double)) :: Float
in skip 0 (if o >= 0 && o < period then o else 0)
skip k o
| k < 2 * plen && o >= entry k && (entry k > 0 || o > 0) = skip (k + 1) (o - entry k)
| otherwise = (k, entry k - o)
-- In entry @k@ with @left@ remaining, at point @p@ heading along @dir@.
-- Inside a dash, @cur@ holds its points so far, reversed.
walk :: Int -> Float -> [(Float, Float)] -> (Float, Float) -> (Float, Float) -> [(Float, Float)] -> [[(Float, Float)]]
walk k left cur dir p qs = case qs of
[]
| even k -> [dash dir cur | not (null cur)]
-- A gap ending exactly at the line's end, followed by a zero-length
-- dash: a dot at the end.
| left <= 0 && entry (k + 1) == 0 -> [dash dir [p]]
| otherwise -> []
q : rest
| len <= left -> walk k (left - len) (if even k then q : cur else cur) dir' q rest
-- Not even the longest entry moves off @p@ at this precision, so
-- the pattern would repeat here forever: the rest of the segment is
-- solid.
| mid == p && along (widest / len) == p ->
if even k then walk k len cur dir' p qs else walk (k + 1) len [p] dir' p qs
| even k -> dash dir' (mid : cur) : walk (k + 1) (entry (k + 1)) [] dir' mid qs
| otherwise -> walk (k + 1) (entry (k + 1)) [mid] dir' mid qs
where
len = dist p q
along u = (fst p + u * (fst q - fst p), snd p + u * (snd q - snd p))
mid = along (left / len)
dir' = if len > 0 then ((fst q - fst p) / len, (snd q - snd p) / len) else dir
-- A dash's points in order without repeats. A lone point gets a second
-- one a hair further along the line, or with no @dots@ is dropped.
dash (dx, dy) ds = case dropRepeats (reverse ds) of
[(x, y)]
| dots -> [(x, y), (x + 1e-3 * dx, y + 1e-3 * dy)]
| otherwise -> []
kept -> kept
-- On a closed polyline, a last dash ending at the start runs on into a
-- first dash beginning there, rather than meeting it cap to cap.
seam ds = case ds of
first@(start : _) : more
| closed
, Just (middle, final) <- unsnoc more
, Just (_, end) <- unsnoc final
, dist start end < 1e-4 ->
middle ++ [final ++ drop 1 first]
_ -> ds
dropRepeats (a : b : rest)
| dist a b < 1e-4 = dropRepeats (a : rest)
| otherwise = a : dropRepeats (b : rest)
dropRepeats xs = xs
-- | The most dashes per subpath; past that it is drawn solid.
maxDashes :: Int
maxDashes = 4096
--------------------------------------------------------------------------------
-- Ops under a transform
--------------------------------------------------------------------------------
-- | An op drawn under transform @t@, flattening within @tol@ where needed.
--
-- Rects keep their op under transforms that keep sides axis-aligned (scale,
-- flip, quarter turn). Rounded rects also need a uniform scale, and circles
-- a transform that keeps them round. Otherwise they become polygons. Lines,
-- polygons and triangles transform their points, with widths scaled by the
-- square root of the transform's area scale.
--
-- A quad gradient under an axis-aligned transform fills the transformed
-- rect, each corner taking the colour of the nearest transformed corner,
-- when that keeps the diagonal it splits along or its colours blend the
-- same over either diagonal. Otherwise it becomes a polygon with per-corner
-- colours, triangulated as the untransformed quad is.
--
-- An unrotated image stays a rect under a transform without rotation or
-- skew, flipping its UVs for a flip or a negative size. Otherwise it is
-- rotated: its centre moves and it scales and turns with the transform. Text
-- moves its anchor and scales its font as widths scale; glyphs are not
-- rotated. A clip
-- becomes the bounding box of its transformed rect.
--
-- A transform with a NaN or infinite entry draws nothing, as does an empty
-- rounded rect, quad gradient or circle.
transformOp :: Float -> Transform -> DrawOp -> [DrawOp]
transformOp tol t@(Transform a b c d _ _) op
| not (transformFinite t) = []
| otherwise = case op of
FillRect r col
| keepsRects -> [FillRect (box r) col]
| otherwise -> fillPathOps tol t NonZero (rect r) (Solid col)
FillRoundedRect r rad col
| empty r -> []
| keepsRects && uniform -> [FillRoundedRect (box r) (rad * k) col]
| otherwise -> fillPathOps tol t NonZero (roundedRect r rad) (Solid col)
FillTriangle x0 y0 x1 y1 x2 y2 col ->
let (x0', y0') = applyTransform t x0 y0
(x1', y1') = applyTransform t x1 y1
(x2', y2') = applyTransform t x2 y2
in [FillTriangle x0' y0' x1' y1' x2' y2' col]
FillCircle cx cy rad col
| not (rad > 0) -> []
| conformal -> let (cx', cy') = applyTransform t cx cy in [FillCircle cx' cy' (rad * k) col]
| otherwise -> fillPathOps tol t NonZero (ellipse (V2 cx cy) (V2 rad rad)) (Solid col)
Stroke x0 y0 x1 y1 w col -> line Stroke x0 y0 x1 y1 w col
StrokeRoundedRect r rad w col
| empty r -> []
| keepsRects && uniform -> [StrokeRoundedRect (box r) (rad * k) (w * k) col]
| otherwise ->
-- The border lies inside the rect, so its centre line is the
-- rect inset by half the width.
let Rect x y rw rh = r
bw = min w (min rw rh / 2)
in strokePathOps tol t (stroke bw) (roundedRect (Rect (x + bw / 2) (y + bw / 2) (rw - bw) (rh - bw)) (rad - bw / 2)) (Solid col)
StrokeCircle cx cy rad w col
| not (rad > 0) -> []
| conformal -> let (cx', cy') = applyTransform t cx cy in [StrokeCircle cx' cy' (rad * k) (w * k) col]
| otherwise ->
let bw = min w rad
in strokePathOps tol t (stroke bw) (ellipse (V2 cx cy) (V2 (rad - bw / 2) (rad - bw / 2))) (Solid col)
StrokeLineAA x0 y0 x1 y1 w col -> line StrokeLineAA x0 y0 x1 y1 w col
FillPolygon pts rings tris sh -> [FillPolygon (points pts) rings tris sh]
StrokePolyline pts w closed cap join limit sh -> [StrokePolyline (points pts) (w * k) closed cap join limit sh]
FillQuadGradient r tl tr br bl
| empty r -> []
-- A quad blends over two triangles split from its top left to its
-- bottom right. When the old top left lands on another corner that
-- diagonal changes, which changes the blend unless the corner
-- colours lie on a plane.
| keepsRects && (even (fst (nearest (bx, by))) || planar) ->
[ FillQuadGradient
(Rect bx by bw bh)
(snd (nearest (bx, by)))
(snd (nearest (bx + bw, by)))
(snd (nearest (bx + bw, by + bh)))
(snd (nearest (bx, by + bh)))
]
| otherwise ->
-- The transformed corners, with the same order and two
-- triangles the untransformed quad uses.
let quad = primArrayFromList (concat [[x, y] | (x, y) <- cs])
in [ quadPolygon quad (Shaded (primArrayFromListN 4 [w | Color w <- [tl, tr, br, bl]]))
| abs (a * d - b * c) > 0
]
where
cs = corners r
Rect bx by bw bh = box r
-- The index and colour of the old corner, clockwise from top left,
-- nearest a point.
tagged = zip cs (zip [0 :: Int ..] [tl, tr, br, bl])
nearest (px, py) =
snd $ minimumBy (comparing (\((qx, qy), _) -> (qx - px) * (qx - px) + (qy - py) * (qy - py))) tagged
planar = all sameDiag [colorR, colorG, colorB, colorA]
sameDiag ch =
fromIntegral (ch tl) + fromIntegral (ch br) == (fromIntegral (ch tr) + fromIntegral (ch bl) :: Int)
DrawImage r angle tex u0 v0 u1 v1 col
| angle == 0 && levelAxes ->
-- The box runs left to right and top to bottom, so a flip, or a
-- negative width or height (drawn mirrored), flips the UVs.
let Rect _ _ rw rh = r
(u0', u1') = if (a < 0) /= (rw < 0) then (u1, u0) else (u0, u1)
(v0', v1') = if (d < 0) /= (rh < 0) then (v1, v0) else (v0, v1)
in [DrawImage (box r) 0 tex u0' v0' u1' v1' col]
| otherwise -> [turnedImage r angle tex u0 v0 u1 v1 col]
DrawText x y ax ay txt col
| scaled -> [DrawTextAligned x' y' ax ay k defaultTextFont txt col]
| otherwise -> [DrawText x' y' ax ay txt col]
where
(x', y') = applyTransform t x y
DrawTextStyled x y font txt col
| scaled -> [DrawTextAligned x' y' 0 1 k font txt col]
| otherwise -> [DrawTextStyled x' y' font txt col]
where
(x', y') = applyTransform t x y
DrawTextAligned x y ax ay s font txt col ->
let (x', y') = applyTransform t x y in [DrawTextAligned x' y' ax ay (if scaled then s * k else s) font txt col]
PushClip r -> [PushClip (box r)]
PopClip -> [PopClip]
where
k = averageStretch t
-- Ignore scale within rounding error (as from a rotation), so text
-- keeps its font.
scaled = abs (k - 1) > 1e-3
-- A zero-size rect, for which the rounded rect ops draw nothing.
empty (Rect _ _ w h) = not (w > 0 && h > 0)
-- Zero but for rounding: a half turn's sine is not quite 0.
rounding = 1e-6 * maximum (map abs [a, b, c, d])
small v = abs v <= rounding
-- No rotation or skew.
levelAxes = small b && small c
keepsRects = levelAxes || (small a && small d)
uniform = small (abs a + abs b - abs c - abs d)
-- Rotation and a uniform scale, perhaps with a flip.
conformal = (a == d && b == negate c) || (a == negate d && b == c)
line mk x0 y0 x1 y1 w col =
let (x0', y0') = applyTransform t x0 y0
(x1', y1') = applyTransform t x1 y1
in [mk x0' y0' x1' y1' (w * k) col]
points pts = runPrimArray $ do
let !n = sizeofPrimArray pts
out <- newPrimArray n
let go !i = when (i + 1 < n) $ do
let (x, y) = applyTransform t (indexPrimArray pts i) (indexPrimArray pts (i + 1))
writePrimArray out i x
writePrimArray out (i + 1) y
go (i + 2)
go 0
pure out
-- The rect's transformed corners, clockwise from the top left.
corners (Rect x y w h) = [applyTransform t px py | (px, py) <- [(x, y), (x + w, y), (x + w, y + h), (x, y + h)]]
-- The bounding box of the rect's transformed corners.
box r =
let cs = corners r
xs = map fst cs
ys = map snd cs
in Rect (minimum xs) (minimum ys) (maximum xs - minimum xs) (maximum ys - minimum ys)
-- An image rotated by @angle@ about its centre, under the transform.
-- The centre is transformed, each side scales by how much the transform
-- stretches the rotated image's axis along it, and the rotation follows
-- the image's x axis, flipping v when the transform flips. Exact for
-- rotations, uniform scales and flips; under a skew the image stays a
-- rect rather than a parallelogram.
turnedImage (Rect x y w h) angle tex u0 v0 u1 v1 col =
let (cx, cy) = applyTransform t (x + w / 2) (y + h / 2)
cs = cos angle
sn = sin angle
exX = a * cs + c * sn
exY = b * cs + d * sn
eyX = c * cs - a * sn
eyY = d * cs - b * sn
w' = w * sqrt (exX * exX + exY * exY)
h' = h * sqrt (eyX * eyX + eyY * eyY)
(v0', v1') = if a * d - b * c < 0 then (v1, v0) else (v0, v1)
in DrawImage (Rect (cx - w' / 2) (cy - h' / 2) w' h') (atan2 exY exX) tex u0 v0' u1 v1' col