packages feed

ktx-font-0.4.0.0: src/Codec/Ktx2/Font/Slug.hs

module Codec.Ktx2.Font.Slug
  ( pack
  , Packed(..)
  , Tables(..)
  , Glyph(..)
  , bandTransform
  , encodeCurves
  , encodeBands
  , decodeBands
  , Shape(..)
  , scaleShape
  , FillRule(..)
  , Contour
  , Curve(..)
  , Point(..)
  , line
  , dataWidth
  , dataWidthLog2
  ) where

import Data.Aeson (FromJSON, ToJSON)
import Data.Bifunctor (bimap)
import Data.ByteString (ByteString)
import Data.ByteString qualified as ByteString
import Data.ByteString.Builder qualified as Builder
import Data.ByteString.Lazy qualified as Lazy
import Data.Bits (shiftL, (.|.))
import Data.List qualified as List
import Data.Map.Strict qualified as Map
import Data.Ord (Down(..), comparing)
import Data.Vector (Vector)
import Data.Vector qualified as Vector
import Data.Vector.Storable qualified as Storable
import Foreign.C.Types (CUShort(..))
import GHC.Float (castWord32ToFloat)
import GHC.Generics (Generic)
import Graphics.MSDF.Atlas.Compact (Box(..))
import Numeric.Half (Half)
import Numeric.Half qualified as Half

pack :: [Shape] -> Packed
pack shapes = Packed
  { curves = padRows 4 . Storable.fromList $ concat curveChunks
  , tables = Tables
      { bands = padRows 1 . Storable.fromList $ concat bandChunks
      , glyphs = Vector.fromList glyphs
      }
  }
  where
    (curveChunks, bandChunks, glyphs) =
      List.unzip3 . snd $ List.mapAccumL packShape (0, 0) shapes

data Packed = Packed
  { curves :: Storable.Vector Half
  , tables :: Tables
  }
  deriving (Eq, Show)

data Tables = Tables
  { bands :: Storable.Vector Float
  , glyphs :: Vector (Maybe Glyph)
  }
  deriving (Eq, Show)

data Glyph = Glyph
  { plane :: Box
  , bandsOffset :: Int
  , horizontalBands :: Int
  , verticalBands :: Int
  , fillRule :: FillRule
  }
  deriving (Eq, Show, Generic)

instance ToJSON Glyph
instance FromJSON Glyph

bandTransform :: Glyph -> (Float, Float, Float, Float)
bandTransform glyph = (scaleX, scaleY, negate left * scaleX, negate bottom * scaleY)
  where
    Box{x, y, w, h} = glyph.plane
    left = x - w / 2
    bottom = y - h / 2
    scaleX = bandScale glyph.verticalBands w
    scaleY = bandScale glyph.horizontalBands h

data Shape = Shape
  { fillRule :: FillRule
  , contours :: [Contour]
  }
  deriving (Eq, Show)

data FillRule
  = NonZero
  | EvenOdd
  deriving (Eq, Ord, Show, Enum, Bounded, Generic)

instance ToJSON FillRule
instance FromJSON FillRule

scaleShape :: Float -> Shape -> Shape
scaleShape factor shape = shape {contours = map (map scaleCurve) shape.contours}
  where
    scaleCurve (Curve a b c) = Curve (scalePoint a) (scalePoint b) (scalePoint c)

    scalePoint :: Point -> Point
    scalePoint p = Point (p.x * factor) (p.y * factor)

encodeCurves :: Storable.Vector Half -> ByteString
encodeCurves =
  Lazy.toStrict . Builder.toLazyByteString . Storable.foldMap (\(Half.Half (CUShort bits)) -> Builder.word16LE bits)

encodeBands :: Storable.Vector Float -> ByteString
encodeBands =
  Lazy.toStrict . Builder.toLazyByteString . Storable.foldMap Builder.floatLE

decodeBands :: ByteString -> Either String (Storable.Vector Float)
decodeBands bytes =
  if ByteString.length bytes `mod` 4 == 0 then
    Right $ Storable.generate (ByteString.length bytes `div` 4) valueAt
  else
    Left "Band data is not a whole number of float32 values"
  where
    valueAt i = castWord32ToFloat $ List.foldl' (.|.) 0
      [ fromIntegral (ByteString.index bytes (4 * i + k)) `shiftL` (8 * k)
      | k <- [0 .. 3]
      ]

type Contour = [Curve]

data Curve = Curve
  { p1 :: Point
  , p2 :: Point
  , p3 :: Point
  }
  deriving (Eq, Show)

data Point = Point
  { x :: Float
  , y :: Float
  }
  deriving (Eq, Ord, Show)

line :: Point -> Point -> Curve
line start end = Curve start end end

dataWidth :: Int
dataWidth = 2 ^ dataWidthLog2

dataWidthLog2 :: Int
dataWidthLog2 = 12

packShape :: (Int, Int) -> Shape -> ((Int, Int), ([Half], [Float], Maybe Glyph))
packShape (curveBase, bandBase) shape =
  case indexed of
    [] ->
      ((curveBase, bandBase), ([], [], Nothing))
    _ ->
      ( (curveBase + length texels, bandBase + length bandValues)
      , (concatMap texelHalves texels, bandValues, Just glyph)
      )
  where
    (texels, indexed) = layoutRuns curveBase $ concatMap (runs . map quantize) shape.contours

    Bounds{minX, minY, maxX, maxY} = foldMap (curveBounds . snd) indexed

    horizontal = chooseBands (minY, maxY) $ bandsAlong
      (minY, maxY)
      (filter (not . flatY . snd) indexed)
      (\c -> extent3 c.p1.y c.p2.y c.p3.y)
      (\c -> max3 c.p1.x c.p2.x c.p3.x)

    vertical = chooseBands (minX, maxX) $ bandsAlong
      (minX, maxX)
      (filter (not . flatX . snd) indexed)
      (\c -> extent3 c.p1.x c.p2.x c.p3.x)
      (\c -> max3 c.p1.y c.p2.y c.p3.y)

    (headers, listValues) =
      layoutLists (2 * (length horizontal + length vertical)) (horizontal <> vertical)

    bandValues =
      map fromIntegral $
        concatMap (\(count, offset) -> [count, offset]) headers <> listValues

    glyph = Glyph
      { plane = Box
          { x = (minX + maxX) / 2
          , y = (minY + maxY) / 2
          , w = maxX - minX
          , h = maxY - minY
          }
      , bandsOffset = bandBase
      , horizontalBands = length horizontal
      , verticalBands = length vertical
      , fillRule = shape.fillRule
      }

runs :: Contour -> [[Curve]]
runs = \case
  [] -> []
  begin : rest -> go [begin] rest
  where
    go acc = \case
      [] ->
        [reverse acc]
      next : rest
        | connected acc next -> go (next : acc) rest
        | otherwise -> reverse acc : go [next] rest

    connected :: [Curve] -> Curve -> Bool
    connected acc next =
      case acc of
        prev : _ -> prev.p3 == next.p1
        [] -> False

layoutRuns :: Int -> [[Curve]] -> ([(Point, Point)], [(Int, Curve)])
layoutRuns base =
  bimap concat concat . List.unzip . snd . List.mapAccumL place base
  where
    place :: Int -> [Curve] -> (Int, ([(Point, Point)], [(Int, Curve)]))
    place offset run =
      ( offset + length texels
      , (texels, zip [offset ..] run)
      )
      where
        texels = map (\c -> (c.p1, c.p2)) run <> lastPoint
        lastPoint = take 1 [(c.p3, Point 0 0) | c <- reverse run]

texelHalves :: (Point, Point) -> [Half]
texelHalves (a, b) = map Half.toHalf [a.x, a.y, b.x, b.y]

quantize :: Curve -> Curve
quantize Curve{p1, p2, p3} = Curve (quantizePoint p1) (quantizePoint p2) (quantizePoint p3)
  where
    quantizePoint :: Point -> Point
    quantizePoint p = Point (roundHalf p.x) (roundHalf p.y)

    roundHalf :: Float -> Float
    roundHalf = Half.fromHalf . Half.toHalf

data Bounds = Bounds
  { minX :: Float
  , minY :: Float
  , maxX :: Float
  , maxY :: Float
  }

instance Semigroup Bounds where
  a <> b = Bounds
    { minX = min a.minX b.minX
    , minY = min a.minY b.minY
    , maxX = max a.maxX b.maxX
    , maxY = max a.maxY b.maxY
    }

instance Monoid Bounds where
  mempty = Bounds
    { minX = 1 / 0
    , minY = 1 / 0
    , maxX = -1 / 0
    , maxY = -1 / 0
    }

curveBounds :: Curve -> Bounds
curveBounds c = Bounds
  { minX = min3 c.p1.x c.p2.x c.p3.x
  , minY = min3 c.p1.y c.p2.y c.p3.y
  , maxX = max3 c.p1.x c.p2.x c.p3.x
  , maxY = max3 c.p1.y c.p2.y c.p3.y
  }

flatX :: Curve -> Bool
flatX c = c.p1.x == c.p2.x && c.p2.x == c.p3.x

flatY :: Curve -> Bool
flatY c = c.p1.y == c.p2.y && c.p2.y == c.p3.y

extent3 :: Float -> Float -> Float -> (Float, Float)
extent3 a b c = (min3 a b c, max3 a b c)

min3 :: Float -> Float -> Float -> Float
min3 a b c = min a (min b c)

max3 :: Float -> Float -> Float -> Float
max3 a b c = max a (max b c)

bandsAlong
  :: (Float, Float)
  -> [(Int, Curve)]
  -> (Curve -> (Float, Float))
  -> (Curve -> Float)
  -> Int
  -> [[Int]]
bandsAlong (lo, hi) eligible extent sortKey count =
  map curvesIn [0 .. count - 1]
  where
    step = (hi - lo) / fromIntegral count

    curvesIn band =
      map fst . List.sortOn (Down . sortKey . snd) $
        filter (overlaps . extent . snd) eligible
      where
        bandLo = lo + fromIntegral band * step
        bandHi = bandLo + step
        overlaps (curveLo, curveHi) =
          curveLo <= bandHi + bandOverlap && curveHi >= bandLo - bandOverlap

bandOverlap :: Float
bandOverlap = 1 / 1024

chooseBands :: (Float, Float) -> (Int -> [[Int]]) -> [[Int]]
chooseBands (lo, hi) bandsFor =
  snd $ List.minimumBy (comparing fst)
    [ (List.foldl' max 0 (map length bands), bands)
    | count <- candidates
    , let bands = bandsFor count
    ]
  where
    candidates =
      if hi > lo then
        [1 .. maxBands]
      else
        [1]

maxBands :: Int
maxBands = 16

bandScale :: Int -> Float -> Float
bandScale count size =
  if size > 0 then
    fromIntegral count / size
  else
    0

layoutLists :: Int -> [[Int]] -> ([(Int, Int)], [Int])
layoutLists start =
  finish . List.foldl' place (start, Map.empty, [], [])
  where
    place (next, seen, headers, chunks) list =
      case Map.lookup list seen of
        Just offset ->
          (next, seen, (length list, offset) : headers, chunks)
        Nothing ->
          ( next + length list
          , Map.insert list next seen
          , (length list, next) : headers
          , list : chunks
          )

    finish (_next, _seen, headers, chunks) =
      (reverse headers, concat $ reverse chunks)

padRows :: (Storable.Storable a, Num a) => Int -> Storable.Vector a -> Storable.Vector a
padRows components items =
  items <> Storable.replicate padding 0
  where
    rowSize = components * dataWidth
    rows = max 1 $ (Storable.length items + rowSize - 1) `div` rowSize
    padding = rows * rowSize - Storable.length items