packages feed

keid-core-0.2.0.0: src/Render/Target/Offscreen.hs

{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedRecordDot #-}

module Render.Target.Offscreen
  ( Settings(..)
  , allocate
  , Offscreen(..)
  , color
  , render
  , renderReading
  , settingsTexture
  , colorTexture
  , settingsCubemap
  , colorCube
  ) where

import RIO

import Control.Arrow (arr)
import Control.Monad.Trans.Resource (ResourceT)
import Control.Monad.Trans.Resource qualified as Resource
import Data.Bits ((.|.))
import Geomancy.UVec2 (UVec2, pattern WithUVec2)
import Vulkan.Core10 qualified as Vk
import Vulkan.Core13 qualified as Vk13
import Vulkan.NamedType ((:::))
import Vulkan.Utils.RefCounted (RefCounted)
import Vulkan.Utils.RefCounted qualified as RefCounted
import Vulkan.Zero (zero)

import Engine.Types.RefCounted qualified as RefCounted
import Engine.Vulkan.Types (MonadVulkan)
import Render.Graph (Graph, HasSliceRegistry, Image, Reads, Tracked)
import Render.Graph qualified as Graph
import Render.Target (HasRendering(..), RenderTarget(..), RenderingFormats(..))
import Render.Target qualified as Target
import Resource.Image (AllocatedImage)
import Resource.Image qualified as Image
import Resource.Region qualified as Region
import Resource.Texture (CubeMap, Flat, Texture(..))

{- XXX: Consider spec wrt. parameters and intended use!

https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/vkCmdBlitImage.html

For depth-only rendering consider "Render.ShadowMap.Target".
-}
data Settings = Settings
  { sLabel       :: Text
  , sExtent      :: Vk.Extent2D
  , sFormat      :: Vk.Format
  , sDepthFormat :: Vk.Format
  , sLayers      :: Word32
  , sMultiView   :: Bool -- ^ Makes sense only for multiple layers.
  , sSamples     :: Vk.SampleCountFlagBits -- ^ Multisample prevents cubes.
  }
  deriving (Eq, Show)

{- | Base settings for rendering to textures.

Single-layer, no multisampling, only the color layer is exported.
-}
settingsTexture
  :: "label" ::: Text
  -> "size"  ::: UVec2
  -> "color" ::: Vk.Format
  -> "depth" ::: Vk.Format
  -> Settings
settingsTexture label (WithUVec2 w h) colorFmt depthFmt = Settings
  { sLabel       = label
  , sLayers      = 1
  , sMultiView   = False
  , sSamples     = Vk.SAMPLE_COUNT_1_BIT
  , sExtent      = Vk.Extent2D w h
  , sFormat      = colorFmt
  , sDepthFormat = depthFmt
  }

{- | Settings for multiview cubemap rendering

6 layers, multiview.
-}
settingsCubemap
  :: "label" ::: Text
  -> "size"  ::: UVec2
  -> "color" ::: Vk.Format
  -> "depth" ::: Vk.Format
  -> Settings
settingsCubemap label size colorFmt depthFmt =
  (settingsTexture label size colorFmt depthFmt)
    { sLayers    = 6
    , sMultiView = True
    }

data Offscreen (tag :: k) = Offscreen
  { oLabel         :: Text
  , oExtent        :: Vk.Extent2D
  , oColor         :: AllocatedImage
  , oDepth         :: AllocatedImage
  , oColorTracked  :: Tracked tag
  , oDepthTracked  :: Tracked Depth
  , oLayers        :: Word32
  , oFormats       :: RenderingFormats
  , oRenderingInfo :: Vk13.RenderingInfo '[]
  , oRenderArea    :: Vk.Rect2D
  , oRelease       :: RefCounted
  }

data Depth

instance HasRendering (Offscreen tag) where
  getRenderingFormats = oFormats
  getRenderingInfo    = const . oRenderingInfo
  getRenderArea       = oRenderArea

instance RenderTarget (Offscreen tag) where
  refcountTarget = RefCounted.resourceTRefCount . oRelease

color :: Offscreen tag -> Tracked tag
color = oColorTracked

render
  :: Offscreen tag
  -> (Vk.CommandBuffer -> RIO env ())
  -> Graph env (Image tag) (Image tag)
render offscreen draw =
  arr (, mempty) >>> renderReading offscreen draw

renderReading
  :: Offscreen tag
  -> (Vk.CommandBuffer -> RIO env ())
  -> Graph env (Image tag, Reads) (Image tag)
renderReading offscreen draw =
  Graph.withPrivate offscreen.oDepthTracked $
    Target.render offscreen.oLabel offscreen declare draw
  where
    declare ((target, reads), depth) = do
      Graph.reading reads
      target' <- Graph.colorAttachment target
      depth' <- Graph.depthAttachment depth
      pure (target', depth')

colorTexture :: Offscreen tag -> Texture Flat
colorTexture Offscreen{..} = Texture
  { tFormat         = oColor.aiFormat
  , tMipLevels      = 1
  , tLayers         = oLayers
  , tAllocatedImage = oColor
  }

colorCube :: Offscreen tag -> Texture CubeMap
colorCube Offscreen{..} = Texture
  { tFormat         = oColor.aiFormat
  , tMipLevels      = 1
  , tLayers         = oLayers -- TODO: get from type param
  , tAllocatedImage = oColor
  }

allocate
  :: ( Resource.MonadResource m
     , MonadVulkan env m
     , HasLogFunc env
     , HasSliceRegistry env
     )
  => Settings
  -> m (Offscreen tag)
allocate settings@Settings{..} = do
  (release, (colorImage, depthImage, colorTracked, depthTracked)) <- RefCounted.wrapped $ Region.run do
    Region.logDebug
      ("Allocating Offscreen resources for " <> display sLabel)
      ("Releasing Offscreen resources for " <> display sLabel)
    (colorImage, depthImage) <- allocateImages settings
    colorTracked <- Graph.track (sLabel <> ".color") colorImage
    depthTracked <- Graph.track (sLabel <> ".depth") depthImage
    pure (colorImage, depthImage, colorTracked, depthTracked)

  pure Offscreen
    { oLabel         = sLabel
    , oRenderArea    = fullSurface
    , oExtent        = sExtent
    , oLayers        = sLayers
    , oFormats       = formats
    , oRenderingInfo = renderingInfo colorImage depthImage
    , oColor         = colorImage
    , oDepth         = depthImage
    , oColorTracked  = colorTracked
    , oDepthTracked  = depthTracked
    , oRelease       = release
    }
  where
    fullSurface = Vk.Rect2D
      { Vk.offset = zero
      , Vk.extent = sExtent
      }

    formats = RenderingFormats
      { rfColor    = [sFormat]
      , rfDepth    = sDepthFormat
      , rfStencil  = Vk.FORMAT_UNDEFINED
      , rfSamples  = sSamples
      , rfViewMask = viewMask
      }

    viewMask =
      if sMultiView then
        Target.viewMaskFor sLayers
      else
        0

    renderingInfo colorImage depthImage = Vk13.RenderingInfo
      { next              = ()
      , flags             = zero
      , renderArea        = fullSurface
      , layerCount        = if sMultiView then 1 else sLayers
      , viewMask          = viewMask
      , colorAttachments  =
          [ Target.colorAttachment
              colorImage.aiImageView
              Vk.ATTACHMENT_LOAD_OP_CLEAR
              Vk.ATTACHMENT_STORE_OP_STORE
              (Vk.Color $ Vk.Float32 0 0 0 1)
          ]
      , depthAttachment   =
          Just $ Target.depthAttachment
            depthImage.aiImageView
            Vk.ATTACHMENT_STORE_OP_DONT_CARE
            0.0
      , stencilAttachment = Nothing
      }

allocateImages
  :: ( Resource.MonadResource m
     , MonadVulkan env m
     )
  => Settings
  -> ResourceT m (AllocatedImage, AllocatedImage)
allocateImages Settings{..} = do
  colorImage <- Image.allocate
    (Just $ sLabel <> ".color")
    Vk.IMAGE_ASPECT_COLOR_BIT
    (Image.inflateExtent sExtent 1)
    1
    sLayers
    sSamples
    sFormat
    ( Vk.IMAGE_USAGE_COLOR_ATTACHMENT_BIT .|.
      Vk.IMAGE_USAGE_SAMPLED_BIT .|.
      Vk.IMAGE_USAGE_TRANSFER_SRC_BIT
    )

  depthImage <- Image.allocate
    (Just $ sLabel <> ".depth")
    Vk.IMAGE_ASPECT_DEPTH_BIT
    (Image.inflateExtent sExtent 1)
    1
    sLayers
    sSamples
    sDepthFormat
    ( Vk.IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT .|.
      Vk.IMAGE_USAGE_SAMPLED_BIT
    )

  pure (colorImage, depthImage)