packages feed

keid-core-0.2.0.0: src/Render/Code.hs

{-# OPTIONS_GHC -fno-prof-auto #-}

module Render.Code
  ( Code(..)
  , glsl
  , trimming
  , compileVert
  , compileFrag
  , compileComp
  , compileStages
  , targetEnv
  ) where

import RIO

import Language.Haskell.TH (Exp, Q)
import Language.Haskell.TH.Syntax (Lift)
import Language.Haskell.TH.Syntax qualified as TH
import NeatInterpolation (trimming)
import RIO.List qualified as List
import RIO.Text qualified as Text
import Vulkan.Utils.ShaderQQ.GLSL.Glslang (compileShaderQ, glsl)
import Vulkan.Utils.ShaderQQ.GLSL.Glslang qualified as Glslang

import Engine.SpirV.Reflect qualified as Reflect
import Engine.Vulkan.Pipeline.Stages (StageInfo)
import Engine.Vulkan.Pipeline.Stages qualified as Stages

-- | A wrapper to `show` code into `compileShaderQ` vars.
newtype Code = Code { unCode :: Text }
  deriving (Eq, Ord, IsString)

instance Show Code where
  show = Text.unpack . unCode

compileVert :: Code -> Q Exp
compileVert = compileShaderQ (Just targetEnv) "vert" Nothing . Text.unpack . unCode

compileFrag :: Code -> Q Exp
compileFrag = compileShaderQ (Just targetEnv) "frag" Nothing . Text.unpack . unCode

compileComp :: Code -> Q Exp
compileComp = compileShaderQ (Just targetEnv) "comp" Nothing . Text.unpack . unCode

compileStages
  :: ( StageInfo stages
     , Lift (stages (Maybe ByteString))
     )
  => stages (Maybe Code)
  -> Q Exp
compileStages stages = do
  location <- TH.location
  compiled <- for (Stages.withLabels stages) \(stage, code) ->
    for code \(Code source) -> do
      (warnings, result) <-
        Glslang.compileShader (Just location) (Just targetEnv) stage Nothing (Text.unpack source)
      unless (null warnings) $
        TH.reportWarning $ glslangMessages warnings
      either (fail . glslangMessages) pure result
  modules <- Reflect.reflect compiled
  either fail pure . Reflect.check $
    Reflect.stageProblems modules
  TH.lift compiled
  where
    glslangMessages = \case
      [] ->
        "glslangValidator failed with no errors"
      [single] ->
        single
      multiple ->
        List.intercalate "\n" $
          "glslangValidator:" : map ("        " <>) multiple

targetEnv :: IsString a => a
targetEnv = "vulkan1.3"