packages feed

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

{-# LANGUAGE CPP #-}

module Codec.Ktx2.Font
  ( -- * KTX font bundles
    Bundle(..)
  , loadBundle
  , loadBundleBytes
  , loadBundleFile
  , freeBundle
  , bundleFont
  , SlugBundle(..)
  , packSlugFont
  , bundleSlug
    -- * Shaping context
  , StackContext(..)
  , createStackContext
  , pushBundleFont
  , destroyStackContext
    -- ** Associated data utilities
  , lookupAtlas
  , lookupBundled
  , mapWithBundle
  , mapBundled
    -- * Format internals
  , pattern KTX_KEY_atlas
  , pattern KTX_KEY_kbts
  , pattern KTX_KEY_kbts_version
  , kbtsVersion
  , pattern KTX_KEY_slug_glyphs
  , pattern KTX_KEY_slug_bands
  , pattern KTX_KEY_slug_version
  , slugVersion
  ) where

import Codec.Compression.Zstd qualified as Zstd
import Codec.Ktx.KeyValue qualified as KVD
import Codec.Ktx2 qualified as Ktx2
import Codec.Ktx2.Font.Slug qualified as Slug
import Codec.Ktx2.Header (Header(..))
import Codec.Ktx2.Read qualified as Ktx2
import Codec.Ktx2.Write qualified as Ktx2
import Control.Concurrent (MVar, newMVar, takeMVar)
import Control.Exception (bracket)
import Control.Monad
import Data.Aeson (encode, eitherDecodeFileStrict, eitherDecodeStrict)
import Data.ByteString (ByteString)
import Data.ByteString qualified as ByteString
import Data.Foldable (toList)
import Data.IntMap (IntMap)
import Data.IntMap qualified as IntMap
import Data.Map qualified as Map
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Traversable (for)
import Data.Vector (Vector)
import Data.Vector.Generic qualified as Vector
import Data.Vector.Storable qualified as Storable
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
import GHC.Generics (Generic, Generic1)
import Graphics.MSDF.Atlas.Compact (Box(..), Compact, compact)
import Graphics.MSDF.Atlas.Compact qualified as Compact
import Graphics.MSDF.Atlas.Layout qualified as Layout
import KB.Text.Layout.Measure qualified as Measure
import KB.Text.Shape qualified as TextShape
import KB.Text.Shape.FFI.Enums qualified as KBTS
import KB.Text.Shape.FFI.Handles (Font(..), intHandle)
import KB.Text.Shape.Font (FontData(..), createFont, destroyFont, withFontData)
import KB.Text.Shape.Font qualified as Font

pattern KTX_KEY_atlas :: Text
pattern KTX_KEY_atlas = "msdf-atlas"

pattern KTX_KEY_kbts :: Text
pattern KTX_KEY_kbts = "kbts-blob"

pattern KTX_KEY_kbts_version :: Text
pattern KTX_KEY_kbts_version = "kbts-version"

kbtsVersion :: Text
kbtsVersion = Text.pack $ show KBTS.VERSION_CURRENT <> "," <> show KBTS.BLOB_VERSION_CURRENT

pattern KTX_KEY_slug_glyphs :: Text
pattern KTX_KEY_slug_glyphs = "slug-glyphs"

pattern KTX_KEY_slug_bands :: Text
pattern KTX_KEY_slug_bands = "slug-bands"

pattern KTX_KEY_slug_version :: Text
pattern KTX_KEY_slug_version = "slug-version"

slugVersion :: Text
slugVersion = Text.pack $ "1," <> show Slug.dataWidthLog2

bundleFont
  :: FilePath -- ^ Source font (ttf etc)
  -> FilePath -- ^ Atlas JSON
  -> FilePath -- ^ KTX2 texture
  -> FilePath -- ^ Output
  -> IO ()
bundleFont pathTtf pathJson pathKtx2 pathKtxf = do
  layout <- eitherDecodeFileStrict pathJson >>= either fail pure

  ttfData <- ByteString.readFile pathTtf

  font <- createFont ttfData 0
  kbtsData <- loadedBlob pathTtf font
  rescale <-
    case layout.atlas.sizeUnit of
      Just Layout.CapsHeight -> pure id
      Nothing -> fmap scalePlanes . withFontData font $ emToCapsOf pathTtf
  destroyFont font

  sourceKtx <- Ktx2.fromFile pathKtx2
  let
    atlas = rescale $ compact layout
    atlasData = ByteString.toStrict $ encode atlas
    kvd =
      KVD.insertBytes KTX_KEY_atlas (Zstd.compress 19 atlasData) $
      KVD.insertBytes KTX_KEY_kbts (Zstd.compress 19 kbtsData) $
      KVD.insertText KTX_KEY_kbts_version kbtsVersion $
      KVD.setWriterWith (writerTag <>) sourceKtx.kvd
  Ktx2.toFile pathKtxf sourceKtx{Ktx2.kvd}

packSlugFont :: FilePath -> [Slug.Shape] -> IO Slug.Packed
packSlugFont pathTtf shapes = do
  scale <- withSourceFont pathTtf \font ->
    withFontData font $ capsScaleOf pathTtf
  pure . Slug.pack $ map (Slug.scaleShape scale) shapes

bundleSlug :: FilePath -> Slug.Tables -> FilePath -> FilePath -> IO ()
bundleSlug pathTtf tables pathKtx2 pathKtxf = do
  kbtsData <- withSourceFont pathTtf $ loadedBlob pathTtf

  sourceKtx <- Ktx2.fromFile pathKtx2
  let
    glyphsData = ByteString.toStrict . encode $ Vector.toList tables.glyphs
    kvd =
      KVD.insertBytes KTX_KEY_slug_glyphs (Zstd.compress 19 glyphsData) $
      KVD.insertBytes KTX_KEY_slug_bands (Zstd.compress 19 $ Slug.encodeBands tables.bands) $
      KVD.insertText KTX_KEY_slug_version slugVersion $
      KVD.insertBytes KTX_KEY_kbts (Zstd.compress 19 kbtsData) $
      KVD.insertText KTX_KEY_kbts_version kbtsVersion $
      KVD.setWriterWith (writerTag <>) sourceKtx.kvd
  Ktx2.toFile pathKtxf sourceKtx{Ktx2.kvd}

withSourceFont :: FilePath -> (FontData -> IO a) -> IO a
withSourceFont pathTtf =
  bracket (ByteString.readFile pathTtf >>= flip createFont 0) destroyFont

capsScaleOf :: FilePath -> Font -> IO Float
capsScaleOf pathTtf font = do
  info <- Font.getFontInfo font
  if info.capitalHeight <= 0
    then fail $ "No cap height in " <> pathTtf <> " (missing or truncated OS/2 table)"
    else pure $ 1 / fromIntegral info.capitalHeight

{- | The kbts blob that loading the source produced as a side effect.

A source that was a blob already is kept as is.
-}
loadedBlob :: FilePath -> FontData -> IO ByteString
loadedBlob pathTtf font =
  case font.fontResources of
    [_source, blob] -> pure blob
    [blob] -> pure blob
    huh -> fail $ "Unexpected font resources in " <> pathTtf <> ": " <> show (length huh)

{- | The em to cap-height factor of a font that declares a cap height.

An em-sized layout can only be normalized to the cap height if the font
has one, so bail out here instead of writing infinities into the planes
and failing much later, at shaping time.
-}
emToCapsOf :: FilePath -> Font -> IO Float
emToCapsOf pathTtf font = do
  info <- Font.getFontInfo font
  if info.capitalHeight <= 0
    then fail $ "No cap height in " <> pathTtf <> " (missing or truncated OS/2 table)"
    else pure $ Font.emToCaps info

writerTag :: Text
writerTag = "ktx-font " <> CURRENT_PACKAGE_VERSION <> " / "

-- | Rescale planes to caps height instead of ems.
--
-- With 1.4 factor, 1em targeting 10px would become 14px.
-- That means you need smaller font sizes in caps that in ems.
scalePlanes :: Float -> Compact -> Compact
scalePlanes s a = a
  { Compact._size = a._size * s
  , Compact.planes = Vector.map (Compact.scaleBox s) a.planes
  }

{- | Put already-loaded font to context.

The context will NOT keep a fontData reference.
-}
pushBundleFont :: TextShape.Context -> Bundle -> IO Int
pushBundleFont ctx Bundle{fontData} =
  withFontData fontData $ TextShape.pushFont ctx

data Bundle = Bundle
  { fontData :: FontData -- ^ The bundle holds the font memory too.
  , atlas :: Compact -- ^ Glyph atlas data for the texture.
  , slug :: Maybe SlugBundle
  }
  deriving (Eq)

data SlugBundle = SlugBundle
  { glyphs :: Vector (Maybe Slug.Glyph)
  , bandsZstd :: ByteString
  }
  deriving (Eq, Show)

loadBundleFile :: FilePath -> IO Bundle
loadBundleFile fontFile =
  bracket (Ktx2.open fontFile) Ktx2.close loadBundle

loadBundleBytes :: ByteString -> IO Bundle
loadBundleBytes bytes =
  Ktx2.bytes bytes >>= loadBundle

-- | Load bundle data from already opened KTX2 reader context
loadBundle :: Ktx2.ReadChunk a => Ktx2.Context a -> IO Bundle
loadBundle ktx = do
  kvd <- Ktx2.keyValueData ktx
  let
    lookupValue key = Map.lookup key kvd >>= KVD.fromValue
    fontKeys = (,)
      <$> lookupValue KTX_KEY_kbts
      <*> lookupValue KTX_KEY_kbts_version
    slugKeys = (,,)
      <$> lookupValue KTX_KEY_slug_version
      <*> lookupValue KTX_KEY_slug_glyphs
      <*> lookupValue KTX_KEY_slug_bands

  (kbtsZstd, kbtsVer) <-
    case fontKeys of
      Nothing ->
        error "Missing KTXF metadata"
      Just compressed ->
        pure compressed

  unless (kbtsVer == kbtsVersion) $
    error $ "KBTS blob version mismatch: " <> show kbtsVer <> ", expected " <> show kbtsVersion

  (atlas, slug) <-
    case (lookupValue KTX_KEY_atlas, slugKeys) of
      (Just mtsdfZstd, _) -> do
        atlas <- either error pure $ decompressed "Atlas" mtsdfZstd >>= eitherDecodeStrict
        pure (atlas, Nothing)
      (Nothing, Just (slugVer, glyphsZstd, bandsZstd)) -> do
        unless (slugVer == slugVersion) $
          error $ "Slug layout version mismatch: " <> show slugVer <> ", expected " <> show (slugVersion :: Text)
        glyphs <- either error pure $ decompressed "Slug glyph" glyphsZstd >>= eitherDecodeStrict
        let slugBundle = SlugBundle{glyphs = Vector.fromList glyphs, bandsZstd}
        pure (planeAtlas ktx.header slugBundle.glyphs, Just slugBundle)
      (Nothing, Nothing) ->
        error "Missing KTXF metadata"

  fontData <-
    case Zstd.decompress kbtsZstd of
      Zstd.Decompress fontData ->
        createFont fontData 0
      Zstd.Skip ->
        error $ "Empty font data"
      Zstd.Error err ->
        error $ "Font decompression error: " <> err

  pure Bundle{..}

decompressed :: String -> ByteString -> Either String ByteString
decompressed what compressed =
  case Zstd.decompress compressed of
    Zstd.Decompress bytes -> Right bytes
    Zstd.Skip -> Left $ "Empty " <> what <> " data"
    Zstd.Error err -> Left $ what <> " decompression error: " <> err

planeAtlas :: Header -> Vector (Maybe Slug.Glyph) -> Compact
planeAtlas header glyphs = Compact.Compact
  { Compact._atlasSize = (fromIntegral header.pixelWidth, fromIntegral header.pixelHeight)
  , Compact._size = 1
  , Compact._type = Layout.Softmask
  , Compact._yOrigin = Layout.Bottom
  , Compact._distanceLower = 0
  , Compact._distanceRange = 0
  , Compact.glyphs = Storable.replicate (Vector.length glyphs) emptyBox
  , Compact.planes = Storable.fromList [maybe emptyBox (.plane) glyph | glyph <- Vector.toList glyphs]
  }
  where
    emptyBox = Box 0 0 0 0

freeBundle :: Bundle -> IO ()
freeBundle Bundle{fontData} = destroyFont fontData

-- * Shaping contexts

data StackContext a = StackContext
  { shapeContext :: MVar TextShape.Context
  , layout :: Measure.LayoutContext -- ^ Measurement caches over the same context. Aliases the locked context, so use it only while holding 'shapeContext'.
  , bundled :: IntMap a
  , atlases :: IntMap Compact -- XXX: Font.Handle ~ Ptr Font.Handle ~ Int
  }
  deriving stock (Functor, Foldable, Traversable, Generic, Generic1)

{- | Create shaping context and push fonts from all the bundles.
-}
createStackContext :: Foldable t => t Bundle -> IO (StackContext ())
createStackContext bundles = do
  ctx <- TextShape.createContext
  layout <- Measure.createLayoutContext ctx
  locals <- for (toList bundles) \Bundle{..} ->
    withFontData fontData \font -> do
      _refs <- TextShape.pushFont ctx font
      pure (intHandle font, atlas)
  let atlases = IntMap.fromList locals
  let bundled = IntMap.map (const ()) atlases
  shapeContext <- newMVar ctx
  pure StackContext{..}

{- | Update font annotations with the bundle collection annotated with update functions.

This may be used to attach more information, e.g. after all fonts were assigned texture slots.

The update collection should be a superset of what was initially bundled.
Otherwise you may see missing things downstream.
-}
mapWithBundle :: Foldable t => t (Bundle, Maybe a -> b) -> StackContext a -> StackContext b
mapWithBundle bundles StackContext{bundled = old, ..} = StackContext{bundled = new, ..}
  where
    new = IntMap.fromList do
      (Bundle{fontData=Font.FontData{fontData}}, f) <- toList bundles
      let key = intHandle $ unsafeForeignPtrToPtr fontData
      pure (key, f $ IntMap.lookup key old)

{- | Destroy shaping context.

NB: Does NOT free the fonts as they may be shared with other stacks. Use `freeBundle` for that.
-}
destroyStackContext :: StackContext a -> IO ()
destroyStackContext StackContext{shapeContext} = takeMVar shapeContext >>= TextShape.destroyContext

{-# INLINE lookupBundled #-}
lookupBundled :: Font -> StackContext a -> Maybe a
lookupBundled font StackContext{..} = IntMap.lookup (intHandle font) bundled

{-# INLINE lookupAtlas #-}
lookupAtlas :: Font -> StackContext a -> Maybe Compact
lookupAtlas font StackContext{atlases} = IntMap.lookup (intHandle font) atlases

mapBundled :: (a -> b) -> StackContext a -> StackContext b
mapBundled f ctx@StackContext{bundled} = ctx
  { bundled = IntMap.map f bundled
  }