packages feed

ktx-build-0.1.0.0: app/Build/Job.hs

{-# OPTIONS_GHC -Wno-orphans #-}

module Build.Job
 ( Job(..)
 , JobType(..)
 , parseJobsFile
 ) where

import Data.Aeson

import Control.DeepSeq (NFData(..))
import Control.Monad (unless, when)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KM
import Data.Aeson.Types (Parser)
import Data.Binary (Binary(..))
import Data.Foldable (foldl')
import Data.Hashable (Hashable(..))
import Data.List qualified as L
import Data.Maybe (fromMaybe)
import Data.String (IsString)
import Data.Text qualified as T
import Data.Yaml qualified as Y
import GHC.Generics (Generic)
import System.FilePath (takeBaseName, takeExtension)

import Build.Atlas (AtlasJob (..))
import Build.CapHeight (CapHeight(..))
import Graphics.MSDF.Atlas.Layout (AtlasType(..))

data JobType
  = Atlas AtlasJob
  | Slug
  | Texture
  deriving (Show, Eq, Generic)

instance Hashable JobType
instance Binary JobType
instance NFData JobType

data Job = Job
  { jobSource :: FilePath
  , jobId :: String
  , jobOutput :: FilePath
  , jobType :: JobType
  , jobFormat :: String -- ^ ktx create --format R8_UNORM
  , jobTarget :: String -- ^ ktx transcode --target bc7
  , jobCapHeight :: CapHeight
  } deriving (Show, Eq, Generic)

instance Hashable Job
instance Binary Job
instance NFData Job

parseJobsFile :: (MonadFail m, MonadIO m) => FilePath -> m [Job]
parseJobsFile source = do
  config <- liftIO $ Y.decodeFileThrow source
  case Y.parseEither flattenJobs config of
    Left err -> fail $ "YAML Config Error: " ++ err
    Right jobs -> pure jobs

extend :: Object -> [Object] -> Object
extend kv = foldl' (flip KM.union) kv

flattenJobs :: Value -> Parser [Job]
flattenJobs root = do
  (globalCtx, global) <- withObject "Root" (pure . collect) root

  flatten global "Collection" \globalOpts (collectionId, collection) -> do
    let collectionCtx = extend globalOpts ["collection" .= collectionId]
    flatten collection "Source" \collectionOpts (sourcePath, source') -> do
      let
        sourceCtx = extend collectionOpts
          [ "source" .= sourcePath
          , "basename" .= takeBaseName (Key.toString sourcePath)
          ]

      source <-
        case source' of
          Object o | KM.null o ->
            pure $ Object $ KM.singleton "default" (Object mempty)
          Object _ ->
            pure source'
          huh ->
            fail $ "Unexpected source type: " <> takeWhile (/= ' ') (show huh)

      flatten source "Target" \sourceOpts (targetId, target) -> do
        let targetCtx = extend sourceOpts [ "id" .= targetId]
        let scopes = [targetCtx, sourceCtx, collectionCtx, globalCtx]
        job <- parseJob scopes target
        pure [job]

-- | Pick up all the ttf sources into the default collection
collect :: Object -> (Object, Value)
collect root = (rootOptions, Object $ inject (KM.fromList collections))
  where
    (rootOptions, children) = splitOptions root
    (sources, collections) = L.partition isSource children
    inject = case sources of
      [] -> id -- Do not inject empty "default" collection
      defaultCollection -> KM.insert "default" (Object $ KM.fromList defaultCollection)
    isSource (k, _) = any (`T.isSuffixOf` Key.toText k) (".ttf" : imageExtensions)

parseJob :: [Object] -> Value -> Parser Job
parseJob scopes = withObject "Job" \jobOpts -> do
  let job = mconcat $ jobOpts : scopes
  jobSource <- job .: "source"
  jobId <- job .: "id"
  jobOutput <- T.unpack . applyTemplate job <$> job .: "output"
  when ("{{" `L.isInfixOf` jobOutput) $
    fail $ "Unfilled template in output: " <> jobOutput

  (jobType, jobCapHeight) <- case takeExtension jobSource of
    ext | ext `elem` imageExtensions ->
      pure (Texture, Declared)
    ".ttf" -> do
      kind <- job .:? "type"
      fontType <-
        if kind == Just ("slug" :: T.Text)
          then pure Slug
          else Atlas <$> parseJSON (Object job)
      capHeight <- job .:? "capHeight" >>= traverse parseCapHeight
      pure (fontType, fromMaybe Declared capHeight)
    ext ->
      fail $ "Unsupported source extension: " <> ext

  (jobFormat, jobTarget) <- case jobType of
    Slug ->
      pure (slugFormat, "none")
    _ -> do
      let
        (defaultFormat, defaultTarget) = case jobType of
          Atlas AtlasJob{atlasType = MTSDF} -> ("R8G8B8A8_UNORM", "bc7")
          Atlas AtlasJob{atlasType = MSDF} -> ("R8G8B8_UNORM", "bc7")
          _ -> ("R8_UNORM", "bc4")

      format <- job .:? "format" .!= (if jobType == Texture then "R8G8B8A8_SRGB" else defaultFormat)
      unless (elem format validFormats) $
        fail $ "Bad format: " <> show format <> ". Must be one of:\n" <> L.intercalate "\n" validFormats

      target <- job .:? "target" .!= (if jobType == Texture then "bc7" else defaultTarget)
      unless (elem target validTargets) $
        fail $ "Bad target: " <> show target <> ". Must be one of: " <> L.intercalate " | " validTargets

      pure (format, target)

  pure Job{..}

parseCapHeight :: Value -> Parser CapHeight
parseCapHeight = \case
  String "declared" -> pure Declared
  String "measure" -> pure Measured
  Number units
    | units > 0 && units == fromInteger (round units) -> pure . Units $ round units
  huh ->
    fail $ "capHeight must be declared, measure or a positive whole number of font units, not " <> show huh

imageExtensions :: IsString s => [s]
imageExtensions = [".png", ".jpg", ".jpeg"]

slugFormat :: String
slugFormat = "R16G16B16A16_SFLOAT"

flatten :: Value -> String -> (Object -> (Key, Value) -> Parser [a]) -> Parser [a]
flatten parentVal childLabel next = withObject childLabel step parentVal
  where
    step parent = do
      let (parentOptions, children) = splitOptions parent
      fmap concat $ traverse (next parentOptions) children

applyTemplate :: Object -> T.Text -> T.Text
applyTemplate context templ = foldl' go templ (KM.toList context)
  where
    go acc (k, v) = case v of
      String t -> replace k t acc
      Number n -> replace k (T.pack vs) acc
        where
          ni = floor n
          vs =
            if fromInteger ni == n then
              show ni
            else
              show n
      _ -> acc
    replace k = T.replace ("{{" <> Key.toText k <> "}}")

splitOptions :: KM.KeyMap a -> (KM.KeyMap a, [(Key, a)])
splitOptions obj = (KM.fromList $ map stripOption opts, rest)
  where
    (opts, rest) = L.partition isOption $ KM.toList obj
    isOption (k, _) = "_" `T.isPrefixOf` Key.toText k
    stripOption (k, v) =
      case T.uncons (Key.toText k) of
        Just ('_', k') -> (Key.fromText k', v)
        _ -> (k, v)

validFormats :: [String]
validFormats =
  [ "R8_UNORM"
  , "R8_SRGB"
  , "R8G8_UNORM"
  , "R8G8_SRGB"
  , "R8G8B8_UNORM"
  , "R8G8B8_SRGB"
  , "R8G8B8A8_UNORM"
  , "R8G8B8A8_SRGB"
  ]

-- From `ktx transcode --help`
validTargets :: [String]
validTargets =
  [ "etc-rgb"
  , "etc-rgba"
  , "eac-r11"
  , "eac-rg11"
  , "bc1"
  , "bc3"
  , "bc4"
  , "bc5"
  , "bc7"
  , "astc"
  , "r8"
  , "rg8"
  , "rgb8"
  , "rgba8"
  ]