packages feed

keid-ui-dearimgui-0.2.0.0: src/Render/ImGui.hs

module Render.ImGui
  ( allocate

  , allocateWithFonts
  , allocateWith

  , renderWith

  , allocateLoop
  , beforeLoop
  , afterLoop

  , capturingKeyboard
  , capturingMouse

  , mkDrawData
  , draw

  , rootLayout
  , layout
  , askWindowBox
  ) where

import RIO

import Control.Monad.Trans.Resource (ReleaseKey, ResourceT, MonadResource)
import Control.Monad.Trans.Resource qualified as Resource
import Data.Vector qualified as Vector
import DearImGui qualified as ImGui
import DearImGui.FontAtlas qualified as FontAtlas
import DearImGui.Impl.GLFW qualified as ImplGLFW
import DearImGui.Raw.Impl.GLFW qualified as RawGLFW
import DearImGui.Raw.Impl.Vulkan qualified as ImplVulkan
import Engine.Setup.Window qualified as Window
import Engine.Stage.Component qualified as Stage
import Engine.Types (GlobalHandles(..), StageFrameRIO, StageRIO, askWindowSize)
import Engine.Vulkan.Types (HasSwapchain(..), Queue(..), getDevice, getQueues, MonadVulkan, waitDeviceIdle, withQueue)
import Engine.Worker qualified as Worker
import Foreign (FunPtr, castPtr, freeHaskellFunPtr, fromBool, poke, toBool)
import Geomancy.Layout.Box as Box
import Geomancy.Layout.View as View
import RIO.App (appEnv)
import Render.Target (HasRendering(..), RenderingFormats(..), pipelineRendering)
import Resource.Region qualified as Region
import Resource.Vulkan.Named qualified as Named
import Vulkan.Core10 qualified as Vk
import Vulkan.Core13 (pattern API_VERSION_1_3)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Utils.QueueAssignment (QueueFamilyIndex(..))
import Vulkan.Utils.Queues (Queues(..))
import Vulkan.Zero (zero)

allocate
  :: ( HasSwapchain swapchain
     , HasRendering target
     )
  => swapchain
  -> target
  -> ResourceT (StageRIO st) ReleaseKey
allocate swapchain target =
  fmap fst $
    allocateWith swapchain target 0 $
      pure ()

allocateWithFonts
  :: ( HasSwapchain swapchain
     , HasRendering target
     , Traversable t
     )
  => swapchain
  -> target
  -> Word32
  -> t FontAtlas.FontSource
  -> ResourceT (StageRIO st) (ReleaseKey, t ImGui.Font)
allocateWithFonts swapchain target extraTextures fonts =
  allocateWith swapchain target extraTextures do
    loaded <- FontAtlas.rebuild fonts
    _atlasKey <- Resource.register FontAtlas.clear
    pure loaded

allocateWith
  :: ( HasSwapchain swapchain
     , HasRendering target
     )
  => swapchain
  -> target
  -> Word32
  -> ResourceT (StageRIO st) a
  -> ResourceT (StageRIO st) (ReleaseKey, a)
allocateWith swapchain target extraTextures action = do
  logDebug "Initializing DearImGui"
  debugReleaseFinished <- toIO (logDebug "Released DearImGui")
  void $! Resource.register debugReleaseFinished

  (_poolKey, pool) <- allocateDescPool extraTextures

  ctx <- ImGui.createContext
  Region.register_ $ ImGui.destroyContext ctx

  GlobalHandles{..} <- asks appEnv

  let Queue{family = QueueFamilyIndex queueFamily, queue} = qGraphics ghQueues
  let formats = getRenderingFormats target

  runInIO <- askRunInIO
  checkResult <- liftIO $ wrapCheckResult \result ->
    unless (result == Vk.SUCCESS) $
      runInIO $ logBackendResult result
  Region.register_ $ freeHaskellFunPtr checkResult

  initOk <- liftIO $ ImplVulkan.withDefaultImGui_ImplVulkan_InitInfo \info -> do
    poke info.apiVersion API_VERSION_1_3
    poke info.instance_ $ Vk.instanceHandle ghInstance
    poke info.physicalDevice $ Vk.physicalDeviceHandle ghPhysicalDevice
    poke info.device $ Vk.deviceHandle ghDevice
    poke info.queueFamily queueFamily
    poke info.queue $ Vk.queueHandle queue
    poke info.descriptorPool pool
    poke info.minImageCount $ getMinImageCount swapchain
    poke info.imageCount $ getImageCount swapchain
    poke info.useDynamicRendering $ fromBool True
    poke info.checkVkResultFn checkResult
    let mainPipeline = info.pipelineInfoMain
    poke mainPipeline.mSAASamples $ rfSamples formats
    pokeCStruct
      (castPtr mainPipeline.pipelineRenderingCreateInfo)
      (pipelineRendering formats)
      (toBool <$> ImplVulkan.init info)
  unless initOk do
    logError "DearImGui vulkan initialization failed"
    exitFailure
  key <- Resource.register ImplVulkan.shutdown

  actionRes <- action

  debugReleaseStart <- toIO (logDebug "Releasing DearImGui")
  void $! Resource.register debugReleaseStart

  pure (key, actionRes)

allocateDescPool
  :: ( MonadVulkan env m
    , MonadResource m
    )
  => Word32
  -> m  (ReleaseKey, Vk.DescriptorPool)
allocateDescPool extraTextures = do
  device <- asks getDevice
  res <- Vk.withDescriptorPool
    device
    poolCI
    Nothing
    Resource.allocate

  Named.object (snd res) "ImGui"
  pure res
  where
    sampledImages =
      ImplVulkan.IMGUI_IMPL_VULKAN_MINIMUM_SAMPLED_IMAGE_POOL_SIZE + extraTextures
    samplers =
      ImplVulkan.IMGUI_IMPL_VULKAN_MINIMUM_SAMPLER_POOL_SIZE
    poolCI = zero
      { Vk.flags =
          Vk.DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT
      , Vk.maxSets =
          sampledImages + samplers
      , Vk.poolSizes =
          Vector.fromList
            [ Vk.DescriptorPoolSize Vk.DESCRIPTOR_TYPE_SAMPLED_IMAGE sampledImages
            , Vk.DescriptorPoolSize Vk.DESCRIPTOR_TYPE_SAMPLER samplers
            ]
      }

foreign import ccall "wrapper"
  wrapCheckResult :: (Vk.Result -> IO ()) -> IO (FunPtr (Vk.Result -> IO ()))

logBackendResult :: (MonadReader env m, MonadIO m, HasLogFunc env) => Vk.Result -> m ()
logBackendResult result
  | result < Vk.SUCCESS = logError message
  | otherwise = logWarn message
  where
    message = "DearImGui Vulkan backend: " <> displayShow result

allocateLoop :: Bool -> ResourceT (StageRIO st) ()
allocateLoop installCallbacks = do
  lift $ beforeLoop installCallbacks
  shutdownImGui <- lift $ toIO afterLoop
  void $! Resource.register shutdownImGui

{- | Initialize context to serve the draws in the current render loop.

You will need to trigger callbacks from DearImGui.Impl.GLFW if you're opting out of them here.

DearImgui will run your previously installed GLFW callbacks.
-}
beforeLoop :: Bool -> StageRIO st ()
beforeLoop installCallbacks = do
  logDebug "glfwInitForVulkan"
  window <- asks $ ghWindow . appEnv
  success <- liftIO $ ImplGLFW.initForVulkan window installCallbacks
  unless success do
    logWarn "glfwInitForVulkan failed"

afterLoop :: StageRIO st ()
afterLoop = do
  logDebug "glfwShutdown"
  waitDeviceIdle
  logDebug "glfwShutdown: Device idle"
  liftIO RawGLFW.shutdown
  logDebug "glfwShutdown finished"

mkDrawData :: MonadIO m => m a -> m (a, ImGui.DrawData)
mkDrawData action = do
  liftIO do
    ImplVulkan.newFrame
    RawGLFW.newFrame
  ImGui.newFrame
  result <- action
  ImGui.render
  drawData <- ImGui.getDrawData
  pure (result, drawData)

draw :: MonadVulkan env m => ImGui.DrawData -> Vk.CommandBuffer -> m ()
draw drawData commandBuffer = do
  graphics <- asks $ qGraphics . getQueues
  withQueue graphics \_queue ->
    liftIO $ ImplVulkan.renderDrawData drawData (Vk.commandBufferHandle commandBuffer) Vk.NULL_HANDLE

capturingKeyboard :: MonadIO m => m () -> m ()
capturingKeyboard action =
  ImGui.wantCaptureKeyboard >>= (`unless` action)

capturingMouse :: MonadIO m => m () -> m ()
capturingMouse action =
  ImGui.wantCaptureMouse >>= (`unless` action)

renderWith
  :: HasRendering target
  => (t -> target)
  -> Stage.Rendering t p st
  -> Stage.Rendering t p st
renderWith getTarget Stage.Rendering{..} = Stage.Rendering
  { rAllocateTargets
  , rAllocateP = \swapchain rts -> do
      void $! allocate swapchain (getTarget rts)
      rAllocateP swapchain rts
  }

-- | Run a full-screen layout using ImGui coordinates (origin at top-left)
{-# INLINE rootLayout #-}
rootLayout
  :: (LayoutView stuff, Placed stuff ~ StageFrameRIO rt p rr st ())
  => View () stuff
  -> StageFrameRIO rt p rr st ()
rootLayout viewTree = do
  root <- askWindowBox
  View.foldWith id root viewTree

-- | Get a window box using ImGui coordinates (origin at top-left)
{-# INLINE askWindowBox #-}
askWindowBox :: StageFrameRIO rt p rr st Box
askWindowBox = do
  Window.Size{window} <- mapRIO fst askWindowSize >>= Worker.getOutputData
  pure Box{size=window, position=window/2}