keid-core 0.1.11.1 → 0.2.0.0
raw patch · 40 files changed
+2726/−2231 lines, 40 filesdep +fragrdep +vulkan-utils-framegraphdep +vulkan-utils-spirvdep −spirv-enumdep −spirv-reflect-ffidep ~spirv-reflect-typesdep ~vulkandep ~vulkan-utils
Dependencies added: fragr, vulkan-utils-framegraph, vulkan-utils-spirv
Dependencies removed: spirv-enum, spirv-reflect-ffi
Dependency ranges changed: spirv-reflect-types, vulkan, vulkan-utils
Files
- ChangeLog.md +48/−0
- keid-core.cabal +12/−9
- src/Engine/App.hs +1/−2
- src/Engine/Frame.hs +82/−105
- src/Engine/Render.hs +38/−25
- src/Engine/Run.hs +191/−113
- src/Engine/Setup.hs +75/−115
- src/Engine/Setup/Device.hs +299/−56
- src/Engine/SpirV/Compile.hs +27/−19
- src/Engine/SpirV/Reflect.hs +220/−296
- src/Engine/Stage/Bootstrap/Setup.hs +1/−33
- src/Engine/Stage/Component.hs +37/−71
- src/Engine/Types.hs +39/−41
- src/Engine/Types/RefCounted.hs +4/−46
- src/Engine/Vulkan/Capabilities.hs +342/−0
- src/Engine/Vulkan/DescSets.hs +4/−3
- src/Engine/Vulkan/Format.hs +29/−0
- src/Engine/Vulkan/Pipeline/Compute.hs +18/−11
- src/Engine/Vulkan/Pipeline/External.hs +61/−91
- src/Engine/Vulkan/Pipeline/Graphics.hs +42/−30
- src/Engine/Vulkan/Pipeline/Raytrace.hs +4/−4
- src/Engine/Vulkan/Shader.hs +0/−155
- src/Engine/Vulkan/Swapchain.hs +97/−271
- src/Engine/Vulkan/Types.hs +49/−40
- src/Render/Code.hs +39/−1
- src/Render/Graph.hs +353/−0
- src/Render/Pass.hs +0/−58
- src/Render/Pass/Offscreen.hs +0/−392
- src/Render/Target.hs +172/−0
- src/Render/Target/Offscreen.hs +263/−0
- src/Resource/Buffer.hs +2/−1
- src/Resource/CommandBuffer.hs +10/−6
- src/Resource/Compressed/Zstd.hs +30/−1
- src/Resource/Image.hs +2/−1
- src/Resource/Image/Downsample.hs +120/−227
- src/Resource/Mesh/Codec.hs +5/−3
- src/Resource/Model.hs +2/−1
- src/Resource/Texture.hs +2/−1
- src/Resource/Texture/Ktx1.hs +2/−1
- src/Resource/Texture/Ktx2.hs +4/−2
ChangeLog.md view
@@ -1,5 +1,53 @@ # Changelog for keid-core +## 0.2.0.0++### Vulkan 1.3 adaptations++- Required device features are the ones guaranteed by Vulkan 1.3, except robust buffer and image access. `descriptorIndexing` is required too.+- Common optional features and extensions are enabled when available. Check `pdiCapabilities` (`Engine.Vulkan.Capabilities`) before relying on one. Device properties moved there from `pdiProperties`.+- Devices that miss a requirement are skipped and the unmet requirements are logged.+- Shaders target SPIR-V 1.6. `discard` demotes the invocation to a helper instead of terminating it. Use `terminateInvocation` for the old behavior.+- Render passes are replaced with dynamic rendering.+- `Render.Target` describes render targets (`HasRendering`) and keeps their resources current across swapchain updates (`RenderTarget`). Stages allocate them with `sAllocateTargets`.+- Graphics pipelines take the sample count and attachment formats from the target. `Graphics.allocate`, `Graphics.create` and the `External` observers lost their sample count argument.+- `Render.Target.Offscreen` replaces `Render.Pass.Offscreen`.++### Frame graph recording++- Stages provide `sRenderGraph` instead of `sRecordCommands`.+- `Stage.assemble` takes the graph in place of the `Scene` component. The `Scene` hooks moved to `Resources` (`rBeforeLoop`, `rUpdateBuffers`).+- `Render.Graph.record` runs a graph in a one-shot command buffer and can read results back to the host.++### Shader validation++Shader interfaces are checked with SPIR-V reflection from `vulkan-utils-spirv`.++- `Render.Code.compileStages` fails the build when pipeline stages disagree on their inputs, outputs, descriptors or push constants.+- Pipeline creation checks the shaders against the descriptor set layouts, push constant ranges and vertex attributes.+- Pipelines reloaded with `External.spawnReflect` keep the previous version when the new one fails the checks.++### Stage handover++Stages prepare their successor on a bound thread while the current one keeps rendering.++- `sInitialRS` of every stage after the first runs off the main thread. It must not call GLFW window functions, touch Dear ImGui or `link` threads to itself.+- Removed `bootstrapStage`. `Engine.Stage.Bootstrap.Setup.stackStage` gives a `StackStageSetup` instead.++### Upstreamed utilities++- `RefCounted`, `Specialization`, `Queues` and `RecycledResources` moved to `vulkan-utils`.+- `SwapchainResources` wraps the `vulkan-utils` swapchain in `srSwapchain`.++### Fixes++- Fixed loader threads and the render loop using the same `VkQueue` at once.+- Fixed races at exit, stage switches and interrupts that released resources the GPU still used.+- Fixed the frame loop stalling while loader threads decompress zstd data or wait for the GPU.+- Fixed `SUBOPTIMAL_KHR` from image acquisition leaving the image-available semaphore signalled.+- Fixed `SpirV.Compile.glsl` reusing stale output.+- Fixed `Engine.Vulkan.Pipeline.Raytrace` shader stage flags.+ ## 0.1.11.1 - Added `Texture.fromAllocatedImage`
keid-core.cabal view
@@ -1,11 +1,11 @@ cabal-version: 1.12 --- This file has been generated from package.yaml by hpack version 0.36.1.+-- This file has been generated from package.yaml by hpack version 0.39.6. -- -- see: https://github.com/sol/hpack name: keid-core-version: 0.1.11.1+version: 0.2.0.0 synopsis: Core parts of Keid engine. category: Game Engine homepage: https://keid.haskell-game.dev@@ -49,6 +49,7 @@ Engine.Types Engine.Types.Options Engine.Types.RefCounted+ Engine.Vulkan.Capabilities Engine.Vulkan.DescSets Engine.Vulkan.Format Engine.Vulkan.Pipeline@@ -69,9 +70,10 @@ Render.Code Render.Code.Noise Render.Draw- Render.Pass- Render.Pass.Offscreen+ Render.Graph Render.Samplers+ Render.Target+ Render.Target.Offscreen Resource.Buffer Resource.Collection Resource.Combined.Textures@@ -139,6 +141,7 @@ , derive-storable-plugin , file-embed , foldl+ , fragr >=0.1 , geomancy >=0.3.0.0 , geomancy-layout , ktx-codec >=0.0.2.0@@ -149,9 +152,7 @@ , rio >=0.1.24.0 , rio-app , serialise- , spirv-enum ==0.1.*- , spirv-reflect-ffi ==0.3.*- , spirv-reflect-types ==0.3.*+ , spirv-reflect-types ==0.4.* , tagged , template-haskell , text@@ -159,7 +160,9 @@ , unagi-chan , unliftio , vector- , vulkan >=3.17- , vulkan-utils+ , vulkan >=3.27+ , vulkan-utils >=0.5.11+ , vulkan-utils-framegraph >=0.1+ , vulkan-utils-spirv >=0.1 , zstd default-language: GHC2021
src/Engine/App.hs view
@@ -25,8 +25,7 @@ engineMainWith :: (a -> Engine.StackStage) -> Engine.StageSetupRIO a -> IO () engineMainWith handoff action = appMain getOptions optionsVerbose setup $ runStack- [ -- XXX: run swapchain bootstrap and replace with next stage- Bootstrap.stackStage handoff action+ [ Bootstrap.stackStage handoff action ] withDataDir :: IO FilePath -> FilePath -> IO a -> IO a
src/Engine/Frame.hs view
@@ -3,9 +3,9 @@ , initial , run , advance+ , drain , queueSubmit - , RecycledResources(..) , initialRecycledResources , timeoutError ) where@@ -22,23 +22,27 @@ import Vulkan.Core10 qualified as Vk import Vulkan.Core12.Promoted_From_VK_KHR_timeline_semaphore qualified as Vk12 import Vulkan.CStruct.Extends (SomeStruct(..), pattern (:&), pattern (::&))-import Vulkan.NamedType ((:::))+import Vulkan.Utils.Frame (allocateCommandPool, allocateTimelineSemaphore, waitTwice) import Vulkan.Utils.QueueAssignment (QueueFamilyIndex(..))+import Vulkan.Utils.Queues (Queues(..))+import Vulkan.Utils.RefCounted (newRefCounted)+import Vulkan.Utils.VulkanContext (RecycledResources(..)) import Vulkan.Zero (zero) import Engine.DataRecycler (DumpResource, WaitResource) import Engine.Setup.Window qualified as Window-import Engine.Types (GlobalHandles(..), StageRIO, Stage(..), Frame(..), GPUWork, RecycledResources(..))+import Engine.Types (GlobalHandles(..), StageRIO, Stage(..), Frame(..), GPUWork) import Engine.Types.Options (optionsPresent, optionsMsaa)-import Engine.Types.RefCounted (newRefCounted)-import Engine.Vulkan.Swapchain (SwapchainResources(..), SwapchainInfo(..), allocSwapchainResources, recreateSwapchainResources)-import Engine.Vulkan.Types (HasVulkan(..), MonadVulkan, RenderPass(..), Queues)+import Engine.Vulkan.Swapchain (SwapchainResources, allocSwapchainResources, recreateSwapchainResources)+import Engine.Vulkan.Types (HasSwapchain(..), HasVulkan(..), MonadVulkan, Queue(..), withQueue)+import Render.Graph (HasSliceRegistry)+import Render.Target (RenderTarget(..)) initial :: Maybe SwapchainResources -> DumpResource (RecycledResources rr)- -> Stage rp p rr st- -> StageRIO st (Frame rp p rr)+ -> Stage rt p rr st+ -> StageRIO st (Frame rt p rr) initial oldSR dumpResource Stage{..} = do logDebug "Making initial frame" @@ -78,22 +82,18 @@ debugRelease <- toIO . logDebug $ "Releasing inside stage " <> display sTitle void $! ResourceT.allocate_ debugAlloc debugRelease - -- For each render pass:- sfRenderpass <- sAllocateRP sfSwapchainResources+ -- For each render target:+ sfTargets <- sAllocateTargets sfSwapchainResources -- TODO: Recreate this if the swapchain format changes- sfPipelines <- sAllocateP sfSwapchainResources sfRenderpass+ sfPipelines <- sAllocateP sfSwapchainResources sfTargets - (_, sfRenderFinishedHostSemaphore) <- Vk.withSemaphore- device- (zero ::& Vk12.SemaphoreTypeCreateInfo Vk12.SEMAPHORE_TYPE_TIMELINE 0 :& ())- Nothing- allocate+ (_, sfRenderFinishedHostSemaphore) <- allocateTimelineSemaphore device 0 logDebug $ "Creating initial recycled resources for stage " <> display sTitle- sfRecycledResources <- initialRecycledResources sInitialRR sfRenderpass sfPipelines+ sfRecycledResources <- initialRecycledResources sInitialRR sfTargets sfPipelines replicateM_ (INFLIGHT_FRAMES - 1) do- resources <- initialRecycledResources sInitialRR sfRenderpass sfPipelines+ resources <- initialRecycledResources sInitialRR sfTargets sfPipelines liftIO $ dumpResource resources releaseDataDebug <- toIO . logDebug $ "Releasing recycled resources for stage " <> display sTitle@@ -101,14 +101,14 @@ pure ( sfSwapchainResources- , sfRenderpass+ , sfTargets , sfPipelines , sfRenderFinishedHostSemaphore , sfRecycledResources ) let- (fSwapchainResources, fRenderpass, fPipelines, fRenderFinishedHostSemaphore, fRecycledResources) = semiFrame+ (fSwapchainResources, fTargets, fPipelines, fRenderFinishedHostSemaphore, fRecycledResources) = semiFrame {- XXX: Create this resource object at the global level so it's closed correctly on exception.@@ -133,35 +133,19 @@ advance :: ( HasLogFunc env , HasVulkan env+ , HasSliceRegistry env , MonadResource (RIO env)- , RenderPass rp+ , RenderTarget rt ) => WaitResource (RecycledResources rr)- -> Frame rp p rr+ -> Frame rt p rr -> Bool- -> RIO env (Frame rp p rr)+ -> RIO env (Frame rt p rr) advance waitDumped f needsNewSwapchain = do -- Wait for a prior frame to finish, then we can steal it's resources!-- -- Handle mvar indefinite timeout exception here:- -- https://github.com/expipiplus1/vulkan/issues/236- fRecycledResources <-- liftIO waitDumped >>= \case- Left block ->- timeout 15e6 (liftIO block) >>= \case- Nothing -> do- logError . display $ Text.unwords- [ "Timed out waiting for recycled resources."- , "A recycler thread is stuck on timeline semaphore or something."- , "Try running with --recycler-wait 15000 or a similar value."- ]- exitFailure- Just rr ->- pure rr- Right rs ->- pure rs+ fRecycledResources <- takeRecycled waitDumped - (fSwapchainResources, fRenderpass) <- getNext f+ (fSwapchainResources, fTargets) <- getNext f -- The per-frame resource helpers need to be created fresh fGPUWork <- liftIO $ newIORef mempty@@ -177,7 +161,7 @@ , fPresent = fPresent f , fMSAA = fMSAA f , fSwapchainResources- , fRenderpass+ , fTargets , fGPUWork , fResources , fRecycledResources@@ -185,29 +169,63 @@ where getNext Frame{..} = do if needsNewSwapchain then do+ graphics <- asks (qGraphics . getQueues)+ withQueue graphics Vk.queueWaitIdleSafe framebufferExtent <- liftIO $ Window.getExtent2D fWindow- newResources <- recreateSwapchainResources fPresent fMSAA framebufferExtent fSwapchainResources+ newResources <- recreateSwapchainResources fMSAA framebufferExtent fSwapchainResources let formatMatch =- siSurfaceFormat (srInfo newResources) ==- siSurfaceFormat (srInfo fSwapchainResources)+ getSurfaceFormat newResources ==+ getSurfaceFormat fSwapchainResources unless formatMatch do logWarn "Swapchain changed format" throwString "TODO: Handle swapchain changing formats" - newRenderpass <- updateRenderpass newResources fRenderpass+ newTargets <- updateTarget newResources fTargets pure ( newResources- , newRenderpass+ , newTargets ) else pure ( fSwapchainResources- , fRenderpass+ , fTargets ) +drain+ :: HasLogFunc env+ => WaitResource (RecycledResources rr)+ -> Frame rt p rr+ -> RIO env ()+drain waitDumped Frame{fResources} = do+ release (fst fResources)+ replicateM_ (INFLIGHT_FRAMES - 1) . void $+ takeRecycled waitDumped++takeRecycled+ :: HasLogFunc env+ => WaitResource a+ -> RIO env a+takeRecycled waitDumped =+ -- Handle mvar indefinite timeout exception here:+ -- https://github.com/expipiplus1/vulkan/issues/236+ liftIO waitDumped >>= \case+ Left block ->+ timeout 15e6 (liftIO block) >>= \case+ Nothing -> do+ logError . display $ Text.unwords+ [ "Timed out waiting for recycled resources."+ , "A recycler thread is stuck on timeline semaphore or something."+ , "Try running with --recycler-wait 15000 or a similar value."+ ]+ exitFailure+ Just resources ->+ pure resources+ Right resources ->+ pure resources+ run :: ( HasLogFunc env , HasVulkan env@@ -215,8 +233,8 @@ ) => (RecycledResources rr -> IO ()) -> Maybe Int- -> RIO (env, Frame rp p rr) a- -> Frame rp p rr+ -> RIO (env, Frame rt p rr) a+ -> Frame rt p rr -> RIO env a run recycle recyclerWait render frame@Frame{..} = do env <- ask@@ -235,7 +253,7 @@ { Vk12.semaphores = Vector.fromList (map fst waits) , Vk12.values = Vector.fromList (map snd waits) }- waitTwice waitInfo tenSecondsKhr >>= \case+ liftIO (waitTwice device waitInfo tenSecondsKhr) >>= \case Vk.TIMEOUT -> do logError "Time out (10s) waiting for frame to finish on Device" timeoutError "Time out (10s) waiting for frame to finish on Device"@@ -251,30 +269,26 @@ -- logDebug $ "Flushing Frame " <> displayShow fIndex -- Free resources wanted elsewhere now, all those in RecycledResources- for_ (rrQueues fRecycledResources) \commandPool ->+ for_ (rrCommandPools fRecycledResources) \commandPool -> Vk.resetCommandPool device commandPool Vk.COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT - -- Signal we're done by making the recycled resources available- liftIO $ recycle fRecycledResources-- -- Destroy frame-specific resources at our leisure- release (fst fResources)+ release (fst fResources) `finally` liftIO (recycle fRecycledResources) -- | 'queueSubmit' and add wait for the timeline 'Semaphore' before retiring the frame. queueSubmit :: MonadVulkan env m- => Vk.Queue+ => Queue -> Vector (SomeStruct Vk.SubmitInfo) -> IORef [GPUWork] -> Vk.Semaphore -> Word64 -> m ()-queueSubmit q submits gpuWork hostSemaphore frameIndex = do+queueSubmit queue submits gpuWork hostSemaphore frameIndex = do {- Make sure we don't get interrupted between submitting the work and recording the wait. -}- mask \_ -> do+ mask \_ -> withQueue queue \q -> do Vk.queueSubmit q submits Vk.NULL_HANDLE atomicModifyIORef' gpuWork \waits -> ( (hostSemaphore, frameIndex) : waits@@ -286,65 +300,28 @@ , HasVulkan env , HasLogFunc env )- => (Queues Vk.CommandPool -> rp -> p -> ResourceT (RIO env) rr)- -> rp+ => (Queues Vk.CommandPool -> rt -> p -> ResourceT (RIO env) rr)+ -> rt -> p -> ResourceT (RIO env) (RecycledResources rr)-initialRecycledResources initialRecycledData rps pipes = do+initialRecycledResources initialRecycledData rts pipes = do device <- asks getDevice - (_iaKey, rrImageAvailableSemaphore) <- Vk.withSemaphore- device- (zero ::& Vk12.SemaphoreTypeCreateInfo Vk12.SEMAPHORE_TYPE_BINARY 0 :& ())- Nothing- allocate-- (_rfKey, rrRenderFinishedSemaphore) <- Vk.withSemaphore+ (_iaKey, rrImageAvailable) <- Vk.withSemaphore device (zero ::& Vk12.SemaphoreTypeCreateInfo Vk12.SEMAPHORE_TYPE_BINARY 0 :& ()) Nothing allocate queues <- asks getQueues- rrQueues <- for queues \(QueueFamilyIndex ix, _queue) -> do- let- commandPoolCI = Vk.CommandPoolCreateInfo- { flags = zero- , queueFamilyIndex = ix- }+ rrCommandPools <- for queues \Queue{family = QueueFamilyIndex ix} -> do cpDebug <- toIO . logDebug $ "Release time for command pool for queue " <> display ix void $! ResourceT.register cpDebug- fmap snd $! Vk.withCommandPool device commandPoolCI Nothing ResourceT.allocate+ allocateCommandPool device ix - rrData <- initialRecycledData rrQueues rps pipes+ rrData <- initialRecycledData rrCommandPools rts pipes pure RecycledResources{..}--{- |- Wait for some semaphores, if the wait times out give the frame one last- chance to complete with a zero timeout.-- It could be that the program was suspended during the preceding- wait causing it to timeout, this will check if it actually- finished.--}-waitTwice- :: (MonadVulkan env m, HasLogFunc env)- => Vk12.SemaphoreWaitInfo- -> "timeout" ::: Word64- -> m Vk.Result-waitTwice waitInfo t = do- device <- asks getDevice- Vk12.waitSemaphoresSafe device waitInfo t >>= \case- Vk.TIMEOUT -> do- r <- Vk12.waitSemaphoresSafe device waitInfo 1e3- logWarn $ mconcat- [ "waiting a second time on " <> displayShow waitInfo- , " got " <> displayShow r- ]- pure r- r ->- pure r timeoutError :: MonadThrow m => String -> m a timeoutError message =
src/Engine/Render.hs view
@@ -6,26 +6,31 @@ import Vulkan.Exception (VulkanException(..)) import Control.Monad.Trans.Resource qualified as Resource+import RIO.Vector.Partial ((!)) import Vulkan.Core10 qualified as Vk import Vulkan.Core10.CommandBuffer qualified as CommandBuffer import Vulkan.Core12.Promoted_From_VK_KHR_timeline_semaphore qualified as Vk12 import Vulkan.CStruct.Extends (SomeStruct(..), pattern (:&), pattern (::&)) import Vulkan.Extensions.VK_KHR_swapchain qualified as Khr-import Vulkan.NamedType ((:::))+import Vulkan.Utils.Queues (Queues(..))+import Vulkan.Utils.RefCounted (resourceTRefCount)+import Vulkan.Utils.Swapchain (Swapchain(..))+import Vulkan.Utils.VulkanContext (RecycledResources(..)) import Vulkan.Zero (zero) import Engine.Frame qualified as Frame-import Engine.Types (Frame(..), RecycledResources(..), StageFrameRIO)-import Engine.Types.RefCounted (resourceTRefCount)-import Engine.Vulkan.Swapchain (SwapchainInfo(..), SwapchainResources(..))-import Engine.Vulkan.Types (HasVulkan(..), RenderPass(..), Queues(..))+import Engine.Types (Frame(..), RenderGraph, StageFrameRIO)+import Engine.Vulkan.Swapchain (SwapchainResources(..))+import Engine.Vulkan.Types (HasVulkan(..), withQueue)+import Render.Graph qualified as Graph+import Render.Target (RenderTarget(..)) renderFrame- :: RenderPass rp- => (rr -> StageFrameRIO rp p rr st ())- -> (Vk.CommandBuffer -> rr -> "image index" ::: Word32 -> StageFrameRIO rp p rr st ())- -> StageFrameRIO rp p rr st ()-renderFrame updateBuffers recordCommandBuffer = do+ :: RenderTarget rt+ => (rr -> StageFrameRIO rt p rr st ())+ -> (rt -> p -> rr -> RenderGraph rt p rr st)+ -> StageFrameRIO rt p rr st ()+renderFrame updateBuffers renderGraph = do Frame{..} <- asks snd let stageRecycled = rrData fRecycledResources device <- asks getDevice@@ -34,27 +39,29 @@ let RecycledResources{..} = fRecycledResources SwapchainResources{..} = fSwapchainResources- SwapchainInfo{..} = srInfo+ Swapchain{..} = srSwapchain - resourceTRefCount srRelease+ resourceTRefCount sRelease resourceTRefCount (fst fStageResources)- refcountRenderpass fRenderpass+ refcountTarget fTargets updateBuffers stageRecycled (res, imageIndex) <- Khr.acquireNextImageKHRSafe device- siSwapchain+ sSwapchain oneSecondKhr- rrImageAvailableSemaphore+ rrImageAvailable Vk.NULL_HANDLE let proceed = do -- Allocate a command buffer and populate it let+ renderFinished = sRenderFinished ! fromIntegral imageIndex+ swapchainImage = srTrackedImages ! fromIntegral imageIndex commandBufferAI = zero- { Vk.commandPool = qGraphics rrQueues+ { Vk.commandPool = qGraphics rrCommandPools , Vk.level = Vk.COMMAND_BUFFER_LEVEL_PRIMARY , Vk.commandBufferCount = 1 }@@ -64,18 +71,22 @@ _ -> throwString "assert: 1 buffer allocated as requested" + env <- ask+ execute <- Graph.prepare env commandBuffer imageIndex swapchainImage $+ renderGraph fTargets fPipelines stageRecycled+ let commandBufferBI = zero { CommandBuffer.flags = Vk.COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT } Vk.useCommandBuffer commandBuffer commandBufferBI $- recordCommandBuffer commandBuffer stageRecycled imageIndex+ liftIO execute let submitInfo = zero { Vk.waitSemaphores =- [ rrImageAvailableSemaphore+ [ rrImageAvailable ] , Vk.waitDstStageMask = [ Vk.PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT@@ -84,7 +95,7 @@ [ Vk.commandBufferHandle commandBuffer ] , Vk.signalSemaphores =- [ rrRenderFinishedSemaphore+ [ renderFinished , fRenderFinishedHostSemaphore ] }@@ -95,7 +106,7 @@ :& () -- traceM $ "Submitting frame " <> textDisplay fIndex <> " to image " <> textDisplay imageIndex- Queues{qGraphics=(_family, graphicsPresentQueue)} <- asks getQueues+ Queues{qGraphics=graphicsPresentQueue} <- asks getQueues Frame.queueSubmit graphicsPresentQueue [SomeStruct submitInfo]@@ -104,11 +115,12 @@ fIndex -- traceM $ "Presenting image " <> textDisplay imageIndex <> " from frame " <> textDisplay fIndex- presentRes <- Khr.queuePresentKHR graphicsPresentQueue zero- { Khr.waitSemaphores = [rrRenderFinishedSemaphore]- , Khr.swapchains = [siSwapchain]- , Khr.imageIndices = [imageIndex]- }+ presentRes <- withQueue graphicsPresentQueue \queue ->+ Khr.queuePresentKHR queue zero+ { Khr.waitSemaphores = [renderFinished]+ , Khr.swapchains = [sSwapchain]+ , Khr.imageIndices = [imageIndex]+ } case presentRes of Vk.SUCCESS -> pure ()@@ -136,6 +148,7 @@ throwM $ VulkanException res Vk.SUBOPTIMAL_KHR -> do+ proceed {- XXX: Converting 'Vk.SUBOPTIMAL_KHR' error to OOD to trigger swapchain update. -}
src/Engine/Run.hs view
@@ -1,7 +1,5 @@ module Engine.Run ( runStack- , run- , step ) where import RIO@@ -10,8 +8,10 @@ import Graphics.UI.GLFW qualified as GLFW import RIO.App (App(..), appEnv) import RIO.State (get, put)-import UnliftIO.Resource (ReleaseKey, release)-import Vulkan.Core10 qualified as Vk+import UnliftIO.Resource (ReleaseKey, register, release)+import Vulkan.Utils.RefCounted (releaseRefCounted)+import Vulkan.Utils.Swapchain (Swapchain(sRelease))+import Vulkan.Utils.VulkanContext (RecycledResources) import Engine.DataRecycler (DataRecycler(..)) import Engine.DataRecycler qualified as DataRecycler@@ -19,38 +19,71 @@ import Engine.Render (renderFrame) import Engine.Setup.Window qualified as Window import Engine.StageSwitch (getNextStage)-import Engine.Types (Frame, NextStage(..), RecycledResources, StageStack, StackStage(..), Stage(..), StageRIO)+import Engine.Types (Frame, GlobalHandles, NextStage(..), StageStack, StackStage(..), Stage(..), StageRIO) import Engine.Types qualified as Engine import Engine.Types.Options (optionsRecyclerWait, optionsMaxFPS)-import Engine.Types.RefCounted (releaseRefCounted)-import Engine.Vulkan.Swapchain (SwapchainResources(srRelease), threwSwapchainError)-import Engine.Vulkan.Types (RenderPass, getDevice)+import Engine.Vulkan.Swapchain (SwapchainResources(srSwapchain), threwSwapchainError)+import Engine.Vulkan.Types (waitDeviceIdle) import Engine.Worker qualified as Worker+import Render.Target (RenderTarget) runStack :: StageStack -> StageRIO (Maybe SwapchainResources) () runStack = \case [] -> do logInfo "Stage stack finished"+ waitDeviceIdle get >>= \case Nothing -> pure () Just oldSR ->- releaseRefCounted (srRelease oldSR)- asks getDevice >>= Vk.deviceWaitIdle- threadDelay 0.5e6 -- XXX: this is arbitrary and may not always satisfy the validator+ releaseRefCounted (sRelease (srSwapchain oldSR)) - StackStage stage : rest -> do+ next : rest ->+ prepare next >>= runPrepared rest++data Prepared where+ Prepared+ :: RenderTarget rt+ => ReleaseKey+ -> App GlobalHandles st+ -> Stage rt p rr st+ -> Prepared++prepare :: StackStage -> StageRIO (Maybe SwapchainResources) Prepared+prepare = \case+ StackStage stage -> do logInfo $ "Setting up stage " <> display (sTitle stage)- (stageRelease, runner) <- prepareStage (sInitialRS stage)- oldSR <- get- runner (run oldSR stageRelease stage) >>= proceed stageRelease rest+ sInitialRS stage >>= enterStage stage - StackStageContinue stKey state stage : rest -> do+ StackStageContinue stKey state stage -> do logInfo $ "Resuming stage " <> display (sTitle stage)- (stageRelease, runner) <- prepareStage (pure (stKey, state))- oldSR <- get- runner (run oldSR stageRelease stage) >>= proceed stageRelease rest+ enterStage stage (stKey, state) + StackStageSetup setup ->+ setup >>= prepare++enterStage+ :: RenderTarget rt+ => Stage rt p rr st+ -> (ReleaseKey, st)+ -> StageRIO (Maybe SwapchainResources) Prepared+enterStage stage (key, rs) = do+ freshStateVar <- newSomeRef rs+ App{..} <- ask+ let+ stageApp = App+ { appState = freshStateVar+ , ..+ }+ pure $ Prepared key stageApp stage++runPrepared :: StageStack -> Prepared -> StageRIO (Maybe SwapchainResources) ()+runPrepared rest (Prepared stageRelease stageApp stage) = do+ setupApp <- ask+ oldSR <- get+ runRIO stageApp (run setupApp oldSR stageRelease rest stage) >>=+ proceed stageRelease rest+ type StageResult = (SwapchainResources, StageAction) proceed :: ReleaseKey -> StageStack -> StageResult -> StageRIO (Maybe SwapchainResources) ()@@ -60,73 +93,61 @@ StageDone -> do releaseStage "Stage done" runStack rest+ StagePop below -> do+ releaseStage "Stage done"+ runPrepared (drop 1 rest) below StageReplace nextStage -> do releaseStage "Stage replaced"- runStack (nextStage : rest)- StagePush frozenStage nextStage -> do- case frozenStage of- StackStage{} ->- logDebug "Restarting stage pushed"- StackStageContinue{} ->- logDebug "Frozen stage pushed"- runStack (nextStage : frozenStage : rest)+ runPrepared rest nextStage+ StagePush frozenStage nextStage ->+ runPrepared (frozenStage : rest) nextStage where releaseStage label = do logDebug label- void $! async do- {-- XXX: wait for the current render job to finish.-- Since the new frames wouldn't be submitted until the control flow- gets back to the render loop, this should be enough of a signal that- the stage resources aren't used anymore.-- The call is costly, but its effects aren't seen.- -}- asks getDevice >>= Vk.deviceWaitIdle+ releasing <- asyncBound do release stageRelease logDebug $ label <> ", released"--prepareStage- :: StageRIO env (ReleaseKey, st)- -> StageRIO env (ReleaseKey, StageRIO st a -> StageRIO env a)-prepareStage initialRS = do- (key, rs) <- initialRS- freshStateVar <- newSomeRef rs- App{..} <- ask- let- stageApp = App- { appState = freshStateVar- , ..- }- pure (key, runRIO stageApp)+ void $! register (void $ waitCatch releasing) run- :: RenderPass rp- => Maybe SwapchainResources+ :: RenderTarget rt+ => App GlobalHandles (Maybe SwapchainResources)+ -> Maybe SwapchainResources -> ReleaseKey- -> Stage rp p rr st+ -> StageStack+ -> Stage rt p rr st -> StageRIO st StageResult-run oldSR stKey stage@Stage{..} = do+run setupApp oldSR stKey rest stage@Stage{..} = do logInfo $ "Starting stage: " <> display sTitle recycler <- DataRecycler.new startFrame <- Frame.initial oldSR (drDump recycler) stage - Engine.GlobalHandles{ghWindow, ghOptions} <- asks appEnv+ Engine.GlobalHandles{ghWindow, ghOptions, ghStageSwitch} <- asks appEnv quit <- liftIO $ GLFW.windowShouldClose ghWindow if quit then do logDebug $ "Forcing stage unwind for " <> display sTitle+ Frame.drain (drWait recycler) startFrame pure ( Frame.fSwapchainResources startFrame , StageDone ) else do+ atomically . void $ tryTakeTMVar ghStageSwitch logInfo $ "Entering stage loop: " <> display sTitle startTime <- liftIO getMonotonicTimeNSec- (finalFrame, stageAction) <- bracket sBeforeLoop sAfterLoop \_stagePrivates ->- stageLoop (step stKey stage recycler (optionsMaxFPS ghOptions)) startFrame+ let+ loop preparer =+ stageLoop+ (step preparer stKey rest stage recycler (optionsMaxFPS ghOptions))+ (startFrame, Nothing)+ (finalFrame, stageAction) <- bracket sBeforeLoop sAfterLoop \_stagePrivates -> do+ result@(lastFrame, _action) <-+ withPreparer setupApp loop+ `onException` idleBeforeUnwind sTitle+ Frame.drain (drWait recycler) lastFrame+ pure result endTime <- liftIO getMonotonicTimeNSec let frames = Frame.fIndex finalFrame@@ -141,79 +162,136 @@ , stageAction ) +idleBeforeUnwind :: Text -> StageRIO st ()+idleBeforeUnwind title = do+ logDebug $ "Waiting for the device before unwinding " <> display title+ waitDeviceIdle `catchAny` \err ->+ logError $ "Device wait failed while unwinding " <> display title <> ": " <> displayShow err++data Preparer = Preparer+ { setup :: App GlobalHandles (Maybe SwapchainResources)+ , requests :: TMVar StackStage+ , prepared :: Async Prepared+ }++withPreparer+ :: App GlobalHandles (Maybe SwapchainResources)+ -> (Preparer -> StageRIO st a)+ -> StageRIO st a+withPreparer setup action = do+ requests <- newEmptyTMVarIO+ withAsyncBound (runRIO setup $ atomically (takeTMVar requests) >>= prepare) \prepared ->+ action Preparer{..}++data Switch+ = SwitchReplace+ | SwitchPushRestart+ | SwitchPushFreeze+ | SwitchPop+ step- :: RenderPass rp- => ReleaseKey- -> Stage rp p rr st+ :: RenderTarget rt+ => Preparer+ -> ReleaseKey+ -> StageStack+ -> Stage rt p rr st -> DataRecycler (RecycledResources rr) -> Maybe Int- -> Frame rp p rr- -> StageRIO st (LoopAction (Frame rp p rr))-step stKey stage@Stage{..} DataRecycler{..} maxFPS_ frame = do+ -> (Frame rt p rr, Maybe Switch)+ -> StageRIO st (LoopAction (Frame rt p rr, Maybe Switch))+step preparer stKey rest stage@Stage{..} DataRecycler{..} maxFPS_ (frame, switching) = do startTime <- liftIO getMonotonicTimeNSec liftIO GLFW.pollEvents -- XXX: runs callback processing on a frame budget -- XXX: hard unwind all the stages, rendering nothing quit <- liftIO $ GLFW.windowShouldClose (Frame.fWindow frame) if quit then- pure LoopQuit+ pure $ LoopExit StageDone else- getNextStage >>= \case- Nothing -> do- Engine.GlobalHandles{ghOptions, ghScreenVar, ghWindow, ghWindowSize} <- asks appEnv- needsNewSwapchain <- threwSwapchainError do- let recyclerWait = optionsRecyclerWait ghOptions- rs <- get- Frame.run drDump recyclerWait (renderFrame (sUpdateBuffers rs) sRecordCommands) frame- nextFrame <- Frame.advance drWait frame needsNewSwapchain- when needsNewSwapchain do- newSize <- liftIO (Window.getSize ghWindow)- Worker.pushInput ghScreenVar $ const newSize.framebufferExtent- Worker.pushInput ghWindowSize $ const newSize- for_ maxFPS_ \maxFPS -> do- -- Wait until the end of allocated time.- endTime <- liftIO getMonotonicTimeNSec- let- elapsedUS = fromIntegral (endTime - startTime) `div` 1e3- fpsCapUS = 1e6 `div` maxFPS- threadDelay $ fpsCapUS - min fpsCapUS elapsedUS- pure $ LoopNextFrame nextFrame- Just Finish ->- -- XXX: finish the stage and proceed with the remaining stack- pure LoopQuit- Just (Replace nextStage) ->- pure $ LoopReplaceStage frame nextStage- Just (PushRestart nextStage) ->- pure $ LoopPushStage frame (StackStage stage) nextStage- Just (PushFreeze nextStage) -> do+ case switching of+ Nothing ->+ getNextStage >>= \case+ Nothing ->+ render startTime Nothing+ Just Finish ->+ case rest of+ [] ->+ pure $ LoopExit StageDone+ below : _rest ->+ beginSwitch startTime SwitchPop below+ Just (Replace nextStage) ->+ beginSwitch startTime SwitchReplace nextStage+ Just (PushRestart nextStage) ->+ beginSwitch startTime SwitchPushRestart nextStage+ Just (PushFreeze nextStage) ->+ beginSwitch startTime SwitchPushFreeze nextStage+ Just switch ->+ poll preparer.prepared >>= \case+ Nothing ->+ render startTime switching+ Just (Left failure) ->+ throwIO failure+ Just (Right nextStage) ->+ LoopExit <$> finishSwitch switch nextStage+ where+ beginSwitch startTime switch nextStage = do+ writeSomeRef preparer.setup.appState . Just $ Frame.fSwapchainResources frame+ atomically $ putTMVar preparer.requests nextStage+ render startTime $ Just switch++ finishSwitch switch nextStage = case switch of+ SwitchReplace ->+ pure $ StageReplace nextStage+ SwitchPop ->+ pure $ StagePop nextStage+ SwitchPushRestart -> do+ logDebug "Restarting stage pushed"+ pure $ StagePush (StackStage stage) nextStage+ SwitchPushFreeze -> do+ logDebug "Frozen stage pushed" frozen <- freeze stKey stage- pure $ LoopPushStage frame frozen nextStage+ pure $ StagePush frozen nextStage -freeze :: RenderPass rp => ReleaseKey -> Stage rp p rr st -> StageRIO st StackStage+ render startTime switching' = do+ Engine.GlobalHandles{ghOptions, ghScreenVar, ghWindow, ghWindowSize} <- asks appEnv+ needsNewSwapchain <- threwSwapchainError do+ let recyclerWait = optionsRecyclerWait ghOptions+ rs <- get+ Frame.run drDump recyclerWait (renderFrame (sUpdateBuffers rs) \targets pipelines -> sRenderGraph targets pipelines rs) frame+ nextFrame <- Frame.advance drWait frame needsNewSwapchain+ when needsNewSwapchain do+ newSize <- liftIO (Window.getSize ghWindow)+ Worker.pushInput ghScreenVar $ const newSize.framebufferExtent+ Worker.pushInput ghWindowSize $ const newSize+ for_ maxFPS_ \maxFPS -> do+ -- Wait until the end of allocated time.+ endTime <- liftIO getMonotonicTimeNSec+ let+ elapsedUS = fromIntegral (endTime - startTime) `div` 1e3+ fpsCapUS = 1e6 `div` maxFPS+ threadDelay $ fpsCapUS - min fpsCapUS elapsedUS+ pure $ LoopNextFrame (nextFrame, switching')++freeze :: RenderTarget rt => ReleaseKey -> Stage rt p rr st -> StageRIO st StackStage freeze stKey stage = do st <- get pure $ StackStageContinue stKey st stage data StageAction- = StageReplace StackStage- | StagePush StackStage StackStage+ = StageReplace Prepared+ | StagePush StackStage Prepared+ | StagePop Prepared | StageDone -data LoopAction f- = LoopNextFrame f- | LoopReplaceStage f StackStage- | LoopPushStage f StackStage StackStage- | LoopQuit+data LoopAction s+ = LoopNextFrame s+ | LoopExit StageAction {-# INLINE stageLoop #-}-stageLoop :: (f -> StageRIO st (LoopAction f)) -> f -> StageRIO st (f, StageAction)-stageLoop action current =+stageLoop :: ((f, s) -> StageRIO st (LoopAction (f, s))) -> (f, s) -> StageRIO st (f, StageAction)+stageLoop action current@(frame, _state) = action current >>= \case- LoopNextFrame nextFrame ->- stageLoop action nextFrame- LoopQuit ->- pure (current, StageDone)- LoopReplaceStage lastFrame nextStage ->- pure (lastFrame, StageReplace nextStage)- LoopPushStage lastFrame frozenStage nextStage ->- pure (lastFrame, StagePush frozenStage nextStage)+ LoopNextFrame next ->+ stageLoop action next+ LoopExit stageAction ->+ pure (frame, stageAction)
src/Engine/Setup.hs view
@@ -1,24 +1,24 @@-{-# LANGUAGE CPP #-}- module Engine.Setup where import RIO +import Data.Bits ((.|.)) import Foreign.Ptr (castFunPtr) import GHC.Clock (getMonotonicTimeNSec) import UnliftIO.Resource (MonadResource) import UnliftIO.Resource qualified as Resource import Vulkan.Core10 qualified as Vk-import Vulkan.Core12 (pattern API_VERSION_1_2)+import Vulkan.Core13 (pattern API_VERSION_1_3) import Vulkan.Dynamic qualified as VkDynamic import Vulkan.Extensions.VK_EXT_debug_utils qualified as Ext-import Vulkan.Extensions.VK_KHR_get_physical_device_properties2 qualified as Khr-import Vulkan.Extensions.VK_KHR_portability_enumeration qualified as Khr+import Vulkan.Extensions.VK_EXT_memory_budget (pattern EXT_MEMORY_BUDGET_EXTENSION_NAME) import Vulkan.Extensions.VK_KHR_surface qualified as Khr import Vulkan.Requirement (InstanceRequirement(..))-import Vulkan.Utils.Initialization (createInstanceFromRequirements)+import Vulkan.Utils.FrameGraph.Image (SliceRegistry, newSliceRegistry)+import Vulkan.Utils.Init.Headless qualified as Headless+import Vulkan.Utils.Initialization (allocateVulkanInstance) import Vulkan.Utils.QueueAssignment (QueueFamilyIndex(..))-import Vulkan.Utils.Requirements (checkInstanceRequirements, requirementReport)+import Vulkan.Utils.Queues (Queues) import Vulkan.Zero (zero) import VulkanMemoryAllocator qualified as VMA @@ -27,10 +27,12 @@ import Engine.StageSwitch (newStageSwitchVar) import Engine.Types (GlobalHandles(..)) import Engine.Types.Options (Options(..))+import Engine.Vulkan.Capabilities qualified as Capabilities import Engine.Vulkan.Swapchain (SwapchainResources) import Engine.Vulkan.Types (PhysicalDeviceInfo(..)) import Engine.Vulkan.Types qualified as Vulkan import Engine.Worker qualified as Worker+import Render.Graph (HasSliceRegistry(..)) setup :: ( HasLogFunc env@@ -48,39 +50,11 @@ Window.pickLargest "Keid Engine" - let- iReqs =-#ifdef darwin_HOST_OS- portabilityEnum :-#endif- deviceProps : debugUtils : windowReqs- oReqs = []- appInfo = Vk.ApplicationInfo- { apiVersion = API_VERSION_1_2- , applicationName = Nothing- , applicationVersion = 0- , engineName = Nothing- , engineVersion = 0- }- instanceCI = zero- { Vk.applicationInfo = Just appInfo- , Vk.flags =-#ifdef darwin_HOST_OS- Vk.INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR-#else- zero-#endif- }- (instanceCI', reqResult, optResult) <- checkInstanceRequirements iReqs oReqs instanceCI- let report = fmap fromString $ requirementReport reqResult optResult- ghInstance <- case instanceCI' of- Nothing -> do- logWarn "Instance check failed"- traverse_ logWarn report- createInstanceFromRequirements iReqs oReqs instanceCI- Just ci -> do- traverse_ logDebug report- createInstanceFromRequirements iReqs oReqs ci+ ghInstance <- allocateVulkanInstance+ mempty+ (Just applicationInfo)+ (debugUtils : windowReqs)+ [] setupWith ghOptions ghWindow ghInstance @@ -105,20 +79,10 @@ logDebug "Creating logical device" ghDevice <- allocateLogical ghPhysicalDeviceInfo ghPhysicalDevice - logDebug "Creating VMA"- let- allocatorCI :: VMA.AllocatorCreateInfo- allocatorCI = zero- { VMA.physicalDevice = Vk.physicalDeviceHandle ghPhysicalDevice- , VMA.device = Vk.deviceHandle ghDevice- , VMA.instance' = Vk.instanceHandle ghInstance- , VMA.vulkanFunctions = Just $ vmaVulkanFunctions ghDevice ghInstance- }- (_vmaKey, ghAllocator) <- VMA.withAllocator allocatorCI Resource.allocate- toIO (logDebug "Releasing VMA") >>= Resource.register+ ghAllocator <- allocateVma ghInstance ghPhysicalDeviceInfo ghPhysicalDevice ghDevice - ghQueues <- liftIO $ pdiGetQueues ghPhysicalDeviceInfo ghDevice- logDebug $ "Got command queues: " <> displayShow (fmap (unQueueFamilyIndex . fst) ghQueues)+ ghQueues <- liftIO (pdiGetQueues ghPhysicalDeviceInfo ghDevice) >>= Vulkan.lockQueues+ logDebug $ "Got command queues: " <> displayShow (fmap (unQueueFamilyIndex . (.family)) ghQueues) screen <- liftIO $ Window.getExtent2D ghWindow ghScreenVar <- Worker.newVar screen@@ -129,13 +93,49 @@ ghMonotonicStart <- liftIO getMonotonicTimeNSec + ghSliceRegistry <- newSliceRegistry+ pure (GlobalHandles{..}, Nothing) +allocateVma+ :: ( HasLogFunc env+ , MonadResource (RIO env)+ )+ => Vk.Instance+ -> PhysicalDeviceInfo+ -> Vk.PhysicalDevice+ -> Vk.Device+ -> RIO env VMA.Allocator+allocateVma vkInstance pdi physicalDevice device = do+ logDebug $ "Creating VMA with " <> displayShow (vmaFlags pdi)+ let+ allocatorCI :: VMA.AllocatorCreateInfo+ allocatorCI = zero+ { VMA.physicalDevice = Vk.physicalDeviceHandle physicalDevice+ , VMA.device = Vk.deviceHandle device+ , VMA.instance' = Vk.instanceHandle vkInstance+ , VMA.vulkanApiVersion = API_VERSION_1_3+ , VMA.flags = vmaFlags pdi+ , VMA.vulkanFunctions = Just $ vmaVulkanFunctions device vkInstance+ }+ (_vmaKey, allocator) <- VMA.withAllocator allocatorCI Resource.allocate+ toIO (logDebug "Releasing VMA") >>= Resource.register+ pure allocator++vmaFlags :: PhysicalDeviceInfo -> VMA.AllocatorCreateFlags+vmaFlags pdi =+ VMA.ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT .|. memoryBudget+ where+ memoryBudget =+ if Capabilities.hasExtension EXT_MEMORY_BUDGET_EXTENSION_NAME (pdiCapabilities pdi) then+ VMA.ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT+ else+ zero+ vmaVulkanFunctions :: Vk.Device -> Vk.Instance -> VMA.VulkanFunctions-#if MIN_VERSION_vulkan(3,15,0) vmaVulkanFunctions Vk.Device{deviceCmds} Vk.Instance{instanceCmds} = zero { VMA.vkGetInstanceProcAddr =@@ -143,9 +143,6 @@ , VMA.vkGetDeviceProcAddr = castFunPtr $ VkDynamic.pVkGetDeviceProcAddr deviceCmds }-#else-vmaVulkanFunctions _device _instance = zero-#endif setupHeadless :: ( HasLogFunc env@@ -156,40 +153,10 @@ setupHeadless opts = do logDebug $ displayShow opts - let- iReqs =-#ifdef darwin_HOST_OS- portabilityEnum :-#endif- deviceProps : debugUtils : headlessReqs- oReqs = []- appInfo = Vk.ApplicationInfo- { apiVersion = API_VERSION_1_2- , applicationName = Nothing- , applicationVersion = 0- , engineName = Nothing- , engineVersion = 0- }- instanceCI = zero- { Vk.applicationInfo = Just appInfo- , Vk.flags =-#ifdef darwin_HOST_OS- Vk.INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR-#else- zero-#endif- }-- (instanceCI', reqResult, optResult) <- checkInstanceRequirements iReqs oReqs instanceCI- let report = fmap fromString $ requirementReport reqResult optResult- hInstance <- case instanceCI' of- Nothing -> do- logWarn "Instance check failed"- traverse_ logWarn report- createInstanceFromRequirements iReqs oReqs instanceCI- Just ci -> do- traverse_ logDebug report- createInstanceFromRequirements iReqs oReqs ci+ hInstance <- Headless.allocateInstance+ (Just applicationInfo)+ (debugUtils : headlessReqs)+ [] logDebug "Creating physical device" (hPhysicalDeviceInfo, hPhysicalDevice) <- allocatePhysical@@ -200,21 +167,13 @@ logDebug "Creating logical device" hDevice <- allocateLogical hPhysicalDeviceInfo hPhysicalDevice - logDebug "Creating VMA"- let- allocatorCI :: VMA.AllocatorCreateInfo- allocatorCI = zero- { VMA.physicalDevice = Vk.physicalDeviceHandle hPhysicalDevice- , VMA.device = Vk.deviceHandle hDevice- , VMA.instance' = Vk.instanceHandle hInstance- , VMA.vulkanFunctions = Just $ vmaVulkanFunctions hDevice hInstance- }- (_vmaKey, hAllocator) <- VMA.withAllocator allocatorCI Resource.allocate- toIO (logDebug "Releasing VMA") >>= Resource.register+ hAllocator <- allocateVma hInstance hPhysicalDeviceInfo hPhysicalDevice hDevice - hQueues <- liftIO $ pdiGetQueues hPhysicalDeviceInfo hDevice- logDebug $ "Got command queues: " <> displayShow (fmap (unQueueFamilyIndex . fst) hQueues)+ hQueues <- liftIO (pdiGetQueues hPhysicalDeviceInfo hDevice) >>= Vulkan.lockQueues+ logDebug $ "Got command queues: " <> displayShow (fmap (unQueueFamilyIndex . (.family)) hQueues) + hSliceRegistry <- newSliceRegistry+ pure Headless{..} data Headless = Headless@@ -223,7 +182,8 @@ , hPhysicalDevice :: Vk.PhysicalDevice , hDevice :: Vk.Device , hAllocator :: VMA.Allocator- , hQueues :: Vulkan.Queues (QueueFamilyIndex, Vk.Queue)+ , hQueues :: Queues Vulkan.Queue+ , hSliceRegistry :: SliceRegistry } instance Vulkan.HasVulkan Headless where@@ -234,17 +194,17 @@ getDevice = hDevice getAllocator = hAllocator -portabilityEnum :: InstanceRequirement-portabilityEnum = RequireInstanceExtension- Nothing- Khr.KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME- minBound+instance HasSliceRegistry Headless where+ getSliceRegistry = hSliceRegistry -deviceProps :: InstanceRequirement-deviceProps = RequireInstanceExtension- Nothing- Khr.KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME- minBound+applicationInfo :: Vk.ApplicationInfo+applicationInfo = Vk.ApplicationInfo+ { apiVersion = API_VERSION_1_3+ , applicationName = Nothing+ , applicationVersion = 0+ , engineName = Nothing+ , engineVersion = 0+ } debugUtils :: InstanceRequirement debugUtils = RequireInstanceExtension
src/Engine/Setup/Device.hs view
@@ -14,23 +14,44 @@ import UnliftIO.Resource (MonadResource) import UnliftIO.Resource qualified as Resource import Vulkan.Core10 qualified as Vk-import Vulkan.Core11.Promoted_From_VK_KHR_multiview (PhysicalDeviceMultiviewFeatures(..))-import Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing (PhysicalDeviceDescriptorIndexingFeatures(..))-import Vulkan.Core12.Promoted_From_VK_KHR_timeline_semaphore (PhysicalDeviceTimelineSemaphoreFeatures(..))-import Vulkan.CStruct.Extends ( SomeStruct(SomeStruct), pattern (:&), pattern (::&))-import Vulkan.Extensions.VK_KHR_get_physical_device_properties2 (getPhysicalDeviceFeatures2KHR)+import Vulkan.Core12 (PhysicalDeviceVulkan11Features(..), PhysicalDeviceVulkan12Features(..))+import Vulkan.Core13 (PhysicalDeviceVulkan13Features(..), pattern API_VERSION_1_3)+import Vulkan.Core14.Promoted_From_VK_KHR_global_priority (PhysicalDeviceGlobalPriorityQueryFeatures(..))+import Vulkan.Core14.Promoted_From_VK_KHR_index_type_uint8 (PhysicalDeviceIndexTypeUint8Features(..))+import Vulkan.Core14.Promoted_From_VK_KHR_line_rasterization (PhysicalDeviceLineRasterizationFeatures(..))+import Vulkan.Core14.Promoted_From_VK_KHR_maintenance5 (PhysicalDeviceMaintenance5Features(..))+import Vulkan.Core14.Promoted_From_VK_KHR_vertex_attribute_divisor (PhysicalDeviceVertexAttributeDivisorFeatures(..))+import Vulkan.CStruct.Extends (SomeStruct(SomeStruct))+import Vulkan.Extensions.VK_EXT_attachment_feedback_loop_layout (PhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_conditional_rendering (PhysicalDeviceConditionalRenderingFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_custom_border_color (PhysicalDeviceCustomBorderColorFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_depth_clip_control (PhysicalDeviceDepthClipControlFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_depth_clip_enable (PhysicalDeviceDepthClipEnableFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_dynamic_rendering_unused_attachments (PhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_extended_dynamic_state3 (PhysicalDeviceExtendedDynamicState3FeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_fragment_shader_interlock (PhysicalDeviceFragmentShaderInterlockFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_graphics_pipeline_library (PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_image_view_min_lod (PhysicalDeviceImageViewMinLodFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_mutable_descriptor_type (PhysicalDeviceMutableDescriptorTypeFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_non_seamless_cube_map (PhysicalDeviceNonSeamlessCubeMapFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_primitive_topology_list_restart (PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_shader_atomic_float (PhysicalDeviceShaderAtomicFloatFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_transform_feedback (PhysicalDeviceTransformFeedbackFeaturesEXT(..))+import Vulkan.Extensions.VK_EXT_vertex_input_dynamic_state (PhysicalDeviceVertexInputDynamicStateFeaturesEXT(..))+import Vulkan.Extensions.VK_KHR_robustness2 (PhysicalDeviceRobustness2FeaturesKHR(..)) import Vulkan.Extensions.VK_KHR_surface qualified as Khr import Vulkan.Extensions.VK_KHR_swapchain (pattern KHR_SWAPCHAIN_EXTENSION_NAME)-import Vulkan.Extensions.VK_KHR_timeline_semaphore (pattern KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME) import Vulkan.Requirement (DeviceRequirement)-import Vulkan.Utils.Initialization (createDeviceFromRequirements, physicalDeviceName, pickPhysicalDevice)+import Vulkan.Utils.Initialization (pickPhysicalDevice) import Vulkan.Utils.QueueAssignment (QueueSpec(..)) import Vulkan.Utils.QueueAssignment qualified as Utils+import Vulkan.Utils.Queues (Queues(..)) import Vulkan.Utils.Requirements.TH qualified as Utils import Vulkan.Core10 (PhysicalDeviceFeatures(..)) import Vulkan.Zero (zero) -import Engine.Vulkan.Types (PhysicalDeviceInfo(..), Queues(..))+import Engine.Vulkan.Capabilities (Capabilities(..), logCapabilities, probe)+import Engine.Vulkan.Types (PhysicalDeviceInfo(..)) allocatePhysical :: ( MonadUnliftIO m, MonadThrow m@@ -56,6 +77,7 @@ [ "Using physical device: " , displayShow (pdiName pdi) ]+ logCapabilities (pdiCapabilities pdi) pure res destroy _res = unliftIO $@@ -72,9 +94,11 @@ -> Vk.PhysicalDevice -> m (Maybe PhysicalDeviceInfo) physicalDeviceInfo presentSurface phys = runMaybeT do- pdiName <- physicalDeviceName phys+ properties <- Vk.getPhysicalDeviceProperties phys let+ pdiName = decodeUtf8Lenient properties.deviceName+ ignoreDevice = "llvmpipe" `Text.isPrefixOf` pdiName @@ -84,12 +108,11 @@ else logDebug $ "Considering " <> displayShow pdiName - hasTimelineSemaphores <- deviceHasTimelineSemaphores phys- unless hasTimelineSemaphores do+ when (properties.apiVersion < API_VERSION_1_3) do logWarn $ mconcat [ "Not using physical device " , displayShow pdiName- , " because it doesn't support timeline semaphores"+ , " because it doesn't support Vulkan 1.3" ] mzero @@ -123,13 +146,34 @@ Just queues -> pure queues - pdiTotalMemory <- do- props <- Vk.getPhysicalDeviceMemoryProperties phys- pure . sum $- fmap (.size) (Vk.memoryHeaps props)+ let+ baseCreateInfo = zero+ { Vk.queueCreateInfos = fmap SomeStruct pdiQueueCreateInfos+ } - pdiProperties <- Vk.getPhysicalDeviceProperties phys+ (pdiCapabilities, pdiDeviceCreateInfo) <- probe reqs opts phys baseCreateInfo >>= \case+ Left unmet -> do+ logWarn $ mconcat+ [ "Not using physical device "+ , displayShow pdiName+ , " because it doesn't meet requirements"+ ]+ for_ unmet \requirement ->+ logWarn $ " " <> display requirement+ mzero+ Right probed@(caps, _createInfo) -> do+ logDebug $ mconcat+ [ displayShow pdiName+ , " denies "+ , display (length caps.capsDenied)+ , " optional requirements"+ ]+ pure probed + let+ pdiTotalMemory =+ sum $ fmap (.size) pdiCapabilities.capsMemory.memoryHeaps+ pure PhysicalDeviceInfo{..} where isFallbackQ _queueFamilyIndex queueFamilyProperties =@@ -176,20 +220,6 @@ ((KHR_SWAPCHAIN_EXTENSION_NAME ==) . Vk.extensionName) extensions -deviceHasTimelineSemaphores :: MonadIO m => Vk.PhysicalDevice -> m Bool-deviceHasTimelineSemaphores phys = do- (_, extensions) <- Vk.enumerateDeviceExtensionProperties phys Nothing- let- hasExt = V.any- ((KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME ==) . Vk.extensionName)- extensions-- hasFeat <- getPhysicalDeviceFeatures2KHR phys >>= \case- _ ::& (PhysicalDeviceTimelineSemaphoreFeatures hasTimelineSemaphores :& ()) ->- pure hasTimelineSemaphores-- pure $ hasExt && hasFeat- allocateLogical :: ( MonadUnliftIO m , MonadReader env m, HasLogFunc env@@ -199,51 +229,264 @@ allocateLogical pdi pd = do logDebug "Creating logical device" - ld <- createDeviceFromRequirements reqs opts pd deviceCI+ ld <- case pdiDeviceCreateInfo pdi of+ SomeStruct createInfo ->+ snd <$> Vk.withDevice pd createInfo Nothing Resource.allocate toIO (logDebug "Destroying logical device") >>= Resource.register pure ld - where- deviceCI = zero- { Vk.queueCreateInfos = fmap SomeStruct (pdiQueueCreateInfos pdi)- }- reqs :: [DeviceRequirement] reqs =-#ifdef darwin_HOST_OS- [Utils.req| VK_KHR_portability_subset |] :-#endif [Utils.reqs|- 1.2+ 1.3 - VK_KHR_maintenance3 VK_KHR_swapchain -- PhysicalDeviceFeatures.robustBufferAccess PhysicalDeviceFeatures.textureCompressionBC+ PhysicalDeviceFeatures.shaderSampledImageArrayDynamicIndexing+ PhysicalDeviceFeatures.shaderStorageBufferArrayDynamicIndexing - VK_KHR_multiview- PhysicalDeviceMultiviewFeatures.multiview+ PhysicalDeviceVulkan11Features.multiview - VK_EXT_descriptor_indexing- PhysicalDeviceDescriptorIndexingFeatures.descriptorBindingPartiallyBound- PhysicalDeviceDescriptorIndexingFeatures.descriptorBindingVariableDescriptorCount- PhysicalDeviceDescriptorIndexingFeatures.runtimeDescriptorArray- PhysicalDeviceDescriptorIndexingFeatures.shaderSampledImageArrayNonUniformIndexing+ PhysicalDeviceVulkan12Features.descriptorIndexing+ PhysicalDeviceVulkan12Features.descriptorBindingPartiallyBound+ PhysicalDeviceVulkan12Features.descriptorBindingVariableDescriptorCount+ PhysicalDeviceVulkan12Features.runtimeDescriptorArray+ PhysicalDeviceVulkan12Features.shaderSampledImageArrayNonUniformIndexing+ PhysicalDeviceVulkan12Features.shaderStorageBufferArrayNonUniformIndexing+ PhysicalDeviceVulkan12Features.shaderUniformTexelBufferArrayDynamicIndexing+ PhysicalDeviceVulkan12Features.shaderStorageTexelBufferArrayDynamicIndexing+ PhysicalDeviceVulkan12Features.shaderUniformTexelBufferArrayNonUniformIndexing+ PhysicalDeviceVulkan12Features.descriptorBindingSampledImageUpdateAfterBind+ PhysicalDeviceVulkan12Features.descriptorBindingStorageImageUpdateAfterBind+ PhysicalDeviceVulkan12Features.descriptorBindingStorageBufferUpdateAfterBind+ PhysicalDeviceVulkan12Features.descriptorBindingUniformTexelBufferUpdateAfterBind+ PhysicalDeviceVulkan12Features.descriptorBindingStorageTexelBufferUpdateAfterBind+ PhysicalDeviceVulkan12Features.descriptorBindingUpdateUnusedWhilePending - VK_KHR_timeline_semaphore- PhysicalDeviceTimelineSemaphoreFeatures.timelineSemaphore+ PhysicalDeviceVulkan12Features.timelineSemaphore+ PhysicalDeviceVulkan12Features.hostQueryReset+ PhysicalDeviceVulkan12Features.imagelessFramebuffer+ PhysicalDeviceVulkan12Features.separateDepthStencilLayouts+ PhysicalDeviceVulkan12Features.uniformBufferStandardLayout+ PhysicalDeviceVulkan12Features.shaderSubgroupExtendedTypes+ PhysicalDeviceVulkan12Features.subgroupBroadcastDynamicId+ PhysicalDeviceVulkan12Features.bufferDeviceAddress+ PhysicalDeviceVulkan12Features.vulkanMemoryModel+ PhysicalDeviceVulkan12Features.vulkanMemoryModelDeviceScope++ PhysicalDeviceVulkan13Features.descriptorBindingInlineUniformBlockUpdateAfterBind+ PhysicalDeviceVulkan13Features.dynamicRendering+ PhysicalDeviceVulkan13Features.synchronization2+ PhysicalDeviceVulkan13Features.maintenance4+ PhysicalDeviceVulkan13Features.inlineUniformBlock+ PhysicalDeviceVulkan13Features.pipelineCreationCacheControl+ PhysicalDeviceVulkan13Features.privateData+ PhysicalDeviceVulkan13Features.shaderDemoteToHelperInvocation+ PhysicalDeviceVulkan13Features.shaderTerminateInvocation+ PhysicalDeviceVulkan13Features.subgroupSizeControl+ PhysicalDeviceVulkan13Features.computeFullSubgroups+ PhysicalDeviceVulkan13Features.shaderZeroInitializeWorkgroupMemory+ PhysicalDeviceVulkan13Features.shaderIntegerDotProduct |] -opts :: [DeviceRequirement]+opts :: [[DeviceRequirement]] opts =- [Utils.reqs|- PhysicalDeviceFeatures.samplerAnisotropy- PhysicalDeviceFeatures.sampleRateShading- |]+#ifdef darwin_HOST_OS+ [Utils.reqs| VK_KHR_portability_subset |] :+#endif+ [ [Utils.reqs|+ PhysicalDeviceFeatures.samplerAnisotropy+ PhysicalDeviceFeatures.sampleRateShading+ PhysicalDeviceFeatures.multiDrawIndirect+ PhysicalDeviceFeatures.drawIndirectFirstInstance+ PhysicalDeviceFeatures.fullDrawIndexUint32+ PhysicalDeviceFeatures.depthClamp+ PhysicalDeviceFeatures.depthBiasClamp+ PhysicalDeviceFeatures.depthBounds+ PhysicalDeviceFeatures.independentBlend+ PhysicalDeviceFeatures.dualSrcBlend+ PhysicalDeviceFeatures.logicOp+ PhysicalDeviceFeatures.alphaToOne+ PhysicalDeviceFeatures.imageCubeArray+ PhysicalDeviceFeatures.fillModeNonSolid+ PhysicalDeviceFeatures.wideLines+ PhysicalDeviceFeatures.largePoints+ PhysicalDeviceFeatures.multiViewport+ PhysicalDeviceFeatures.variableMultisampleRate+ PhysicalDeviceFeatures.geometryShader+ PhysicalDeviceFeatures.tessellationShader+ PhysicalDeviceFeatures.shaderTessellationAndGeometryPointSize+ PhysicalDeviceFeatures.occlusionQueryPrecise+ PhysicalDeviceFeatures.pipelineStatisticsQuery+ PhysicalDeviceFeatures.inheritedQueries+ PhysicalDeviceFeatures.shaderClipDistance+ PhysicalDeviceFeatures.shaderCullDistance+ PhysicalDeviceFeatures.shaderImageGatherExtended+ PhysicalDeviceFeatures.shaderResourceMinLod+ PhysicalDeviceFeatures.shaderInt16+ PhysicalDeviceFeatures.shaderInt64+ PhysicalDeviceFeatures.fragmentStoresAndAtomics+ PhysicalDeviceFeatures.vertexPipelineStoresAndAtomics+ PhysicalDeviceFeatures.shaderStorageImageExtendedFormats+ PhysicalDeviceFeatures.shaderStorageImageReadWithoutFormat+ PhysicalDeviceFeatures.shaderStorageImageWriteWithoutFormat+ PhysicalDeviceFeatures.shaderUniformBufferArrayDynamicIndexing+ PhysicalDeviceFeatures.shaderStorageImageArrayDynamicIndexing++ PhysicalDeviceVulkan11Features.shaderDrawParameters+ PhysicalDeviceVulkan11Features.storageBuffer16BitAccess+ PhysicalDeviceVulkan11Features.uniformAndStorageBuffer16BitAccess+ PhysicalDeviceVulkan11Features.storagePushConstant16+ PhysicalDeviceVulkan11Features.multiviewGeometryShader+ PhysicalDeviceVulkan11Features.multiviewTessellationShader+ PhysicalDeviceVulkan11Features.samplerYcbcrConversion++ PhysicalDeviceVulkan12Features.scalarBlockLayout+ PhysicalDeviceVulkan12Features.samplerMirrorClampToEdge+ PhysicalDeviceVulkan12Features.samplerFilterMinmax+ PhysicalDeviceVulkan12Features.drawIndirectCount+ PhysicalDeviceVulkan12Features.shaderOutputLayer+ PhysicalDeviceVulkan12Features.shaderOutputViewportIndex+ PhysicalDeviceVulkan12Features.shaderFloat16+ PhysicalDeviceVulkan12Features.shaderInt8+ PhysicalDeviceVulkan12Features.storageBuffer8BitAccess+ PhysicalDeviceVulkan12Features.uniformAndStorageBuffer8BitAccess+ PhysicalDeviceVulkan12Features.storagePushConstant8+ PhysicalDeviceVulkan12Features.shaderUniformBufferArrayNonUniformIndexing+ PhysicalDeviceVulkan12Features.shaderStorageImageArrayNonUniformIndexing+ PhysicalDeviceVulkan12Features.shaderStorageTexelBufferArrayNonUniformIndexing+ PhysicalDeviceVulkan12Features.shaderInputAttachmentArrayDynamicIndexing+ PhysicalDeviceVulkan12Features.descriptorBindingUniformBufferUpdateAfterBind+ |]+ , [Utils.reqs|+ VK_KHR_push_descriptor+ VK_KHR_swapchain_mutable_format+ VK_KHR_calibrated_timestamps+ VK_EXT_load_store_op_none+ VK_EXT_memory_budget+ VK_EXT_external_memory_host+ VK_EXT_hdr_metadata+ VK_EXT_sample_locations+ VK_EXT_post_depth_coverage+ VK_EXT_shader_stencil_export+ |]+ , [Utils.reqs|+ VK_KHR_maintenance5+ PhysicalDeviceMaintenance5Features.maintenance5+ |]+ , [Utils.reqs|+ VK_KHR_global_priority+ PhysicalDeviceGlobalPriorityQueryFeatures.globalPriorityQuery+ |]+ , [Utils.reqs|+ VK_KHR_vertex_attribute_divisor+ PhysicalDeviceVertexAttributeDivisorFeatures.vertexAttributeInstanceRateDivisor+ PhysicalDeviceVertexAttributeDivisorFeatures.vertexAttributeInstanceRateZeroDivisor+ |]+ , [Utils.reqs|+ VK_EXT_index_type_uint8+ PhysicalDeviceIndexTypeUint8Features.indexTypeUint8+ |]+ , [Utils.reqs|+ VK_EXT_line_rasterization+ PhysicalDeviceLineRasterizationFeatures.bresenhamLines+ PhysicalDeviceLineRasterizationFeatures.stippledBresenhamLines+ |]+ , [Utils.reqs|+ VK_EXT_robustness2+ PhysicalDeviceRobustness2FeaturesKHR.nullDescriptor+ |]+ , [Utils.reqs|+ VK_EXT_shader_atomic_float+ PhysicalDeviceShaderAtomicFloatFeaturesEXT.shaderBufferFloat32Atomics+ PhysicalDeviceShaderAtomicFloatFeaturesEXT.shaderSharedFloat32Atomics+ PhysicalDeviceShaderAtomicFloatFeaturesEXT.shaderImageFloat32Atomics+ |]+ , [Utils.reqs|+ VK_EXT_mutable_descriptor_type+ PhysicalDeviceMutableDescriptorTypeFeaturesEXT.mutableDescriptorType+ |]+ , [Utils.reqs|+ VK_EXT_depth_clip_control+ PhysicalDeviceDepthClipControlFeaturesEXT.depthClipControl+ |]+ , [Utils.reqs|+ VK_EXT_depth_clip_enable+ PhysicalDeviceDepthClipEnableFeaturesEXT.depthClipEnable+ |]+ , [Utils.reqs|+ VK_EXT_custom_border_color+ PhysicalDeviceCustomBorderColorFeaturesEXT.customBorderColors+ PhysicalDeviceCustomBorderColorFeaturesEXT.customBorderColorWithoutFormat+ |]+ , [Utils.reqs|+ VK_EXT_image_view_min_lod+ PhysicalDeviceImageViewMinLodFeaturesEXT.minLod+ |]+ , [Utils.reqs|+ VK_EXT_non_seamless_cube_map+ PhysicalDeviceNonSeamlessCubeMapFeaturesEXT.nonSeamlessCubeMap+ |]+ , [Utils.reqs|+ VK_EXT_primitive_topology_list_restart+ PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT.primitiveTopologyListRestart+ |]+ , [Utils.reqs|+ VK_EXT_fragment_shader_interlock+ PhysicalDeviceFragmentShaderInterlockFeaturesEXT.fragmentShaderPixelInterlock+ PhysicalDeviceFragmentShaderInterlockFeaturesEXT.fragmentShaderSampleInterlock+ |]+ , [Utils.reqs|+ VK_EXT_conditional_rendering+ PhysicalDeviceConditionalRenderingFeaturesEXT.conditionalRendering+ |]+ , [Utils.reqs|+ VK_EXT_transform_feedback+ PhysicalDeviceTransformFeedbackFeaturesEXT.transformFeedback+ PhysicalDeviceTransformFeedbackFeaturesEXT.geometryStreams+ |]+ , [Utils.reqs|+ VK_EXT_attachment_feedback_loop_layout+ PhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT.attachmentFeedbackLoopLayout+ |]+ , [Utils.reqs|+ VK_EXT_dynamic_rendering_unused_attachments+ PhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT.dynamicRenderingUnusedAttachments+ |]+ , [Utils.reqs|+ VK_EXT_vertex_input_dynamic_state+ PhysicalDeviceVertexInputDynamicStateFeaturesEXT.vertexInputDynamicState+ |]+ , [Utils.reqs|+ VK_KHR_pipeline_library+ VK_EXT_graphics_pipeline_library+ PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT.graphicsPipelineLibrary+ |]+ , [Utils.reqs|+ VK_EXT_extended_dynamic_state3+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3PolygonMode+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3DepthClampEnable+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3DepthClipEnable+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3DepthClipNegativeOneToOne+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3LineRasterizationMode+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3LineStippleEnable+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3SampleLocationsEnable+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3RasterizationSamples+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3SampleMask+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3AlphaToCoverageEnable+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3LogicOpEnable+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3ColorBlendEnable+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3ColorBlendEquation+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3ColorWriteMask+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3ProvokingVertexMode+ PhysicalDeviceExtendedDynamicState3FeaturesEXT.extendedDynamicState3TessellationDomainOrigin+ |]+ ] noSuchThing :: MonadThrow m => String -> m a noSuchThing message =
src/Engine/SpirV/Compile.hs view
@@ -7,7 +7,7 @@ import RIO import RIO.ByteString qualified as ByteString-import RIO.Directory (createDirectoryIfMissing, doesFileExist)+import RIO.Directory (createDirectoryIfMissing, doesFileExist, removeFile) import RIO.FilePath ((<.>), (</>)) import RIO.Map qualified as Map import RIO.Process (HasProcessContext, proc, readProcess_)@@ -28,29 +28,29 @@ glsl outdir basename stage (Code source) = do withDir \dir -> do let- shaderFile = dir </> Text.unpack basename <.> Text.unpack stage- outFile = shaderFile <.> "spv"- outBytes = encodeUtf8 source-- exists <- doesFileExist shaderFile- same <-- if exists then do- oldBytes <- ByteString.readFile shaderFile- pure $ oldBytes == outBytes- else- pure False-- unless same do- ByteString.writeFile shaderFile outBytes- (_out, _err) <- proc- "glslangValidator"+ shaderFile = dir </> Text.unpack basename <.> Text.unpack stage+ outFile = shaderFile <.> "spv"+ argsFile = shaderFile <.> "args"+ sourceBytes = encodeUtf8 source+ args = [ "--target-env", targetEnv , "-S", Text.unpack stage , "-V", shaderFile , "-o", outFile ]- readProcess_- logDebug $ displayShow (_out, _err)+ argsBytes = encodeUtf8 $ tshow args++ sameSource <- hasContents shaderFile sourceBytes+ sameArgs <- hasContents argsFile argsBytes+ compiled <- doesFileExist outFile++ unless (sameSource && sameArgs && compiled) do+ when sameArgs $+ removeFile argsFile+ ByteString.writeFile shaderFile sourceBytes+ (out, err) <- proc "glslangValidator" args readProcess_+ logDebug $ displayShow (out, err)+ ByteString.writeFile argsFile argsBytes where withDir action = case outdir of@@ -59,6 +59,14 @@ Just dir -> do createDirectoryIfMissing True dir action dir++hasContents :: MonadIO m => FilePath -> ByteString -> m Bool+hasContents path expected = do+ exists <- doesFileExist path+ if exists then+ (== expected) <$> ByteString.readFile path+ else+ pure False glslStages :: ( Stages.StageInfo stages
src/Engine/SpirV/Reflect.hs view
@@ -1,334 +1,258 @@-{-# LANGUAGE UndecidableInstances #-}+module Engine.SpirV.Reflect+ ( reflect+ , check -module Engine.SpirV.Reflect where+ , stageProblems+ , layoutProblems+ , vertexInputProblems+ ) where import RIO -import Data.IntMap qualified as IntMap-import Data.List qualified as List-import Data.SpirV.Enum qualified as SpirV-import Data.SpirV.Enum.StorageClass qualified as StorageClass-import Data.SpirV.Reflect.BlockVariable qualified as BlockVariable+import Data.Bits ((.&.))+import Data.SpirV.Reflect.DescriptorBinding (DescriptorBinding) import Data.SpirV.Reflect.DescriptorBinding qualified as DescriptorBinding-import Data.SpirV.Reflect.DescriptorSet qualified as DescriptorSet-import Data.SpirV.Reflect.Enums qualified as Reflect-import Data.SpirV.Reflect.FFI qualified as Reflect+import Data.SpirV.Reflect.Enums.DescriptorType (DescriptorType(..))+import Data.SpirV.Reflect.Enums.Format (Format(..)) import Data.SpirV.Reflect.InterfaceVariable (InterfaceVariable) import Data.SpirV.Reflect.InterfaceVariable qualified as InterfaceVariable import Data.SpirV.Reflect.Module (Module) import Data.SpirV.Reflect.Module qualified as Module import Data.SpirV.Reflect.Traits qualified as Traits-import Data.SpirV.Reflect.TypeDescription qualified as TypeDescription-import Data.Tree (Tree(..))-import Engine.Vulkan.Pipeline.Stages (StageInfo(..), withLabels)-import RIO.ByteString (readFile)+import Data.Vector qualified as Vector+import Data.Vector.Storable qualified as VectorS+import RIO.List qualified as List import RIO.Text qualified as Text-import Vulkan.Core10.Enums.Format qualified as VkFormat+import Vulkan.Core10 qualified as Vk+import Vulkan.Utils.SpirV.Descriptors qualified as Descriptors+import Vulkan.Utils.SpirV.Reflect qualified as Reflect+import Vulkan.Utils.SpirV.Stage qualified as Stage -invoke- :: MonadIO m- => FilePath- -> m Module-invoke file =- readFile file >>= Reflect.loadBytes+import Engine.Vulkan.Format qualified as Format+import Engine.Vulkan.Pipeline.Stages (StageInfo(..))+import Engine.Vulkan.Pipeline.Stages qualified as Stages+import Engine.Vulkan.Types (DsLayoutBindings) -data Reflect stages = Reflect- { bindMap :: BindMap BlockBinding- , interfaces :: StageInterface stages- , inputStage :: Text- , inputs :: InterfaceBinds- }+reflect+ :: ( Traversable stages+ , MonadIO io+ )+ => stages (Maybe ByteString)+ -> io (stages (Maybe Module))+reflect = traverse $ traverse Reflect.reflectBytes --- | @layout(set=X, binding=Y) ...@-type BindMap a = IntMap (IntMap a)+check :: [Text] -> Either String ()+check = \case+ [] ->+ Right ()+ problems ->+ Left . Text.unpack . Text.intercalate "\n" $+ "Shaders do not match:" : map (" " <>) problems -type StageInterface stages = stages (Maybe (InterfaceBinds, InterfaceBinds))+stageProblems+ :: StageInfo stages+ => stages (Maybe Module)+ -> [Text]+stageProblems stages = linkProblems <> sharedProblems+ where+ active = do+ (label, Just module_) <- toList $ Stages.withLabels stages+ pure (label, module_) --- | @layout(location=N)-type InterfaceBinds = IntMap InterfaceBinding+ linkProblems = do+ (producer, consumer) <- zip active (drop 1 active)+ interfaceProblems producer consumer -deriving instance (Eq (StageInterface stages)) => Eq (Reflect stages)-deriving instance (Show (StageInterface stages)) => Show (Reflect stages)+ sharedProblems =+ map fromString $ lefts+ [ void $ Descriptors.mergedDescriptorSetLayoutInfos modules+ , void $ Descriptors.mergedPushConstantRanges modules+ ] --- * Block variables+ modules = map snd active --- | @uniform Foo { ... } foo;@-type BlockBinding =- ( Text- , Reflect.DescriptorType- , Maybe (Tree ([Maybe Text], BlockSignature))- )+interfaceProblems :: (Text, Module) -> (Text, Module) -> [Text]+interfaceProblems (outputStage, producer) (inputStage, consumer) = do+ (location, expected) <- consumerInfo.inputs+ let+ input =+ inputStage <> " input" <> variableAt consumer.input_variables location+ case List.lookup location producerInfo.outputs of+ Nothing ->+ pure $ input <> " has no matching " <> outputStage <> " output"+ Just provided -> do+ guard $ provided /= expected+ pure $ mconcat+ [ input+ , " does not match "+ , outputStage+ , " output"+ , variableAt producer.output_variables location+ ]+ where+ consumerInfo = Stage.stageInfoOf consumer+ producerInfo = Stage.stageInfoOf producer -data BlockSignature = BlockSignature- { offset :: Word32- , size :: Word32- , flags :: Reflect.TypeFlags- , scalar :: Maybe Traits.Scalar- }- deriving (Eq, Ord, Show)+variableAt :: Vector InterfaceVariable -> Word32 -> Text+variableAt variables location =+ foldMap (" " <>) name <> " at location " <> tshow location+ where+ name = Vector.find ((== location) . (.location)) variables >>= (.name) -stagesBindMap- :: ( MonadIO m- , MonadReader env m- , HasLogFunc env- , StageInfo stages- )+layoutProblems+ :: StageInfo stages => stages (Maybe Module)- -> m (BindMap BlockBinding)-stagesBindMap = fmap snd . foldM collect ([] :: [Text], mempty) . annotate+ -> [DsLayoutBindings]+ -> Vector Vk.PushConstantRange+ -> [Text]+layoutProblems stages setLayouts pushRanges = do+ (label, stage, Just module_) <- toList $ (,,) <$> stageNames <*> stageFlagBits <*> stages+ descriptorProblems label stage module_ <> pushProblems label stage module_ where- annotate modules = (,)- <$> stageNames- <*> modules-- collect acc@(visited, old) (source, stageModule) =- case stageModule of- Nothing ->- pure acc- Just new ->- case unionDS old (moduleBindMap new) of- Left (six, bix, inAcc, inNew) -> do- logError $ mconcat- [ "incompatible data at "- , "layout("- , "set=", display six- , ", "- , "binding=", display bix- , ")"- ]- logError $ "old: " <> displayDS inAcc- logError $ " from " <> displayShow visited- logError $ "new: " <> displayDS inNew- logError $ " from " <> displayShow source- throwString "catch this"- Right matching ->- pure (visited <> [source], matching)+ descriptorProblems label stage module_ = do+ binding <- toList module_.descriptor_bindings+ guard $ binding.accessed /= 0+ bindingProblems setLayouts label stage binding - unionDS =- bindMapUnionWith \(_, adt, asig) (_, bdt, bsig) ->- adt == bdt &&- fmap (fmap snd) asig == fmap (fmap snd) bsig+ pushProblems label stage module_ = do+ range <- Descriptors.pushConstantRanges module_+ guard . not $ any (covers stage range) pushRanges+ pure $ mconcat+ [ label+ , " push constants at offset "+ , tshow range.offset+ , " with size "+ , tshow range.size+ , " are outside the push constant ranges"+ ] - displayDS (name, dt, sigs) = mconcat- [ display name- , " :: "- , maybe (displayShow dt) display $- Reflect.descriptorTypeName @Text dt- , maybe- mempty- ( \sigs' ->- mappend " -- " $- displayShow . toList $- sigs' <&> \(path, BlockSignature{..}) ->- ( Text.intercalate "|" (catMaybes path)- , (size, offset, Reflect.typeFlagsNames @Text flags)- , scalar- )- )- sigs+bindingProblems+ :: [DsLayoutBindings]+ -> Text+ -> Vk.ShaderStageFlagBits+ -> DescriptorBinding+ -> [Text]+bindingProblems setLayouts label stage binding =+ case declared of+ Nothing ->+ pure $ subject <> " is missing from the descriptor set layouts"+ Just layoutBinding -> catMaybes+ [ do+ guard . not $ compatibleDescriptor shaderType layoutBinding.descriptorType+ pure $ mconcat+ [ subject+ , " is "+ , tshow shaderType+ , " but the layout has "+ , tshow layoutBinding.descriptorType+ ]+ , do+ guard $ layoutBinding.stageFlags .&. stage /= stage+ pure $ subject <> " is not visible to the " <> label <> " stage"+ , do+ count <- binding.count+ guard $ count > layoutBinding.descriptorCount+ pure $ mconcat+ [ subject+ , " has "+ , tshow count+ , " descriptors but the layout has "+ , tshow layoutBinding.descriptorCount+ ] ]--moduleBindMap :: Module -> BindMap BlockBinding-moduleBindMap refl = IntMap.fromList do- ds <- toList $ Module.descriptor_sets refl- pure- ( fromIntegral $ DescriptorSet.set ds- , IntMap.fromList do- db <- toList $ DescriptorSet.bindings ds- let- DescriptorBinding.DescriptorBinding- {binding, name, descriptor_type, block} = db- pure- ( fromIntegral binding- , ( name- , descriptor_type- , fmap (blockTree []) block- )- )- )--blockTree- :: [Maybe Text]- -> BlockVariable.BlockVariable- -> Tree ([Maybe Text], BlockSignature)-blockTree ancestors bv = Node (path, here) $ map (blockTree path) there where- here = BlockSignature- { offset = bv.offset- , size = bv.size- , ..- }- where- (flags, scalar) =- case BlockVariable.type_description bv of- Nothing ->- (Reflect.TYPE_FLAG_UNDEFINED, Nothing)- Just td ->- ( TypeDescription.type_flags td- , do- TypeDescription.Traits{numeric} <- TypeDescription.traits td- let st@Traits.Scalar{width} = Traits.scalar numeric- guard $ width > 0- pure st- )+ subject = mconcat+ [ label+ , " "+ , binding.name+ , " at set "+ , tshow binding.set+ , " binding "+ , tshow binding.binding+ ] - path =- ancestors ++ [BlockVariable.name bv]+ declared = do+ layoutBindings <- listToMaybe $ drop (fromIntegral binding.set) setLayouts+ fst <$> List.find ((== binding.binding) . (.binding) . fst) layoutBindings - there =- toList $ BlockVariable.members bv+ shaderType =+ case binding.descriptor_type of+ DescriptorType value ->+ Vk.DescriptorType $ fromIntegral value -{-# INLINE bindMapUnionWith #-}-bindMapUnionWith- :: (a -> a -> Bool)- -> BindMap a- -> BindMap a- -> Either (Int, Int, a, a) (BindMap a)-bindMapUnionWith compatible as bs = traverse sequence validated+compatibleDescriptor :: Vk.DescriptorType -> Vk.DescriptorType -> Bool+compatibleDescriptor shaderType layoutType =+ shaderType == layoutType || (shaderType, layoutType) `elem` alternatives where- validated =- IntMap.unionWithKey- (IntMap.unionWithKey . check)- (wrap as)- (wrap bs)-- wrap = fmap (fmap pure)-- check six bix a' b' = do- a <- a'- b <- b'- if compatible a b then- Right a- else- Left (six, bix, a, b)---- * Interface variables--type InterfaceBinding =- ( Maybe Text- , [Text]- , InterfaceSignature- )+ alternatives =+ [ (Vk.DESCRIPTOR_TYPE_UNIFORM_BUFFER, Vk.DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC)+ , (Vk.DESCRIPTOR_TYPE_STORAGE_BUFFER, Vk.DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)+ , (Vk.DESCRIPTOR_TYPE_SAMPLED_IMAGE, Vk.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)+ , (Vk.DESCRIPTOR_TYPE_SAMPLER, Vk.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)+ ] -data InterfaceSignature = InterfaceSignature- { format :: VkFormat.Format- , flags :: Reflect.TypeFlags- , matrix :: Maybe Traits.Matrix- }- deriving (Eq, Ord, Show)+covers :: Vk.ShaderStageFlagBits -> Vk.PushConstantRange -> Vk.PushConstantRange -> Bool+covers stage range declared =+ declared.stageFlags .&. stage == stage &&+ declared.offset <= range.offset &&+ range.offset + range.size <= declared.offset + declared.size -stagesInterfaceMap- :: ( Traversable stages- )+vertexInputProblems+ :: StageInfo stages => stages (Maybe Module)- -> StageInterface stages-stagesInterfaceMap = fmap (fmap moduleInterfaceBinds)--moduleInterfaceBinds :: Module -> (InterfaceBinds, InterfaceBinds)-moduleInterfaceBinds refl =- ( interfaceBinds StorageClass.Input (Module.input_variables refl)- , interfaceBinds StorageClass.Output (Module.output_variables refl)- )--interfaceBinds :: SpirV.StorageClass -> Vector InterfaceVariable -> InterfaceBinds-interfaceBinds cls vars = IntMap.fromList do- var@InterfaceVariable.InterfaceVariable{location} <- toList vars- guard $ InterfaceVariable.storage_class var == cls-- -- XXX: Remove vars like @gl_FragCoord@/@SV_Position@ from potential signatures.- guard $ InterfaceVariable.built_in var == Nothing-- let- td = InterfaceVariable.type_description var- Reflect.Format format = InterfaceVariable.format var- flags = maybe Reflect.TYPE_FLAG_UNDEFINED TypeDescription.type_flags td-- stuff = do- TypeDescription.TypeDescription{traits} <- td- TypeDescription.Traits{numeric} <- traits- let- mt@Traits.Matrix{column_count, row_count} = Traits.matrix numeric- guard $ column_count > 0 && row_count > 0- pure mt-- signature = InterfaceSignature- { format = VkFormat.Format $ fromIntegral format- , flags = flags- , matrix = stuff- }-- pure- ( fromIntegral location- , ( InterfaceVariable.name var- , Reflect.typeFlagsNames @Text flags- , signature- )- )--type IncompatibleInterfaces label = (label, label, Int, Maybe (InterfaceSignature, InterfaceSignature))-type CompatibleInterfaces label = (label, label, IntMap ([Text], Matching (Maybe Text)))-type Matching a = Either (a, a) a--interfaceCompatible- :: ( StageInfo stages- , IsString label- )- => StageInterface stages- -> Either (IncompatibleInterfaces label) [CompatibleInterfaces label]-interfaceCompatible staged =- for chained \((inputLabel, input), (outputLabel, output)) -> do- checked <- for (IntMap.assocs input) \(location, requested) ->- case IntMap.lookup location output of- Just provided -> do- let- (rName, rFlags, rSignature) = requested- (pName, _pFlags, pSignature) = provided- if rSignature == pSignature then- let- names =- if rName == pName then- Right rName- else- Left (rName, pName)- in- Right (location, (rFlags, names))- else- Left- ( inputLabel- , outputLabel- , location- , Just (rSignature, pSignature)- )- Nothing ->- Left- ( inputLabel- , outputLabel- , location- , Nothing- )- Right- ( outputLabel- , inputLabel- , IntMap.fromList checked- )-+ -> Vector Vk.VertexInputAttributeDescription+ -> [Text]+vertexInputProblems stages attributes =+ case active of+ (label, Vk.SHADER_STAGE_VERTEX_BIT, module_) : _rest -> do+ variable <- toList module_.input_variables+ guard $ isNothing variable.built_in+ location <- take (locations variable) [variable.location ..]+ inputProblems attributes label variable location+ _noVertexStage ->+ [] where- chained = zip (drop 1 ins) outs+ active = do+ (label, stage, Just module_) <- toList $ (,,) <$> stageNames <*> stageFlagBits <*> stages+ pure (label, stage, module_) - (ins, outs) =- List.unzip do- (label, Just binds) <- toList $ withLabels staged- pure- ( (label, fst binds)- , (label, snd binds)- )+ locations variable =+ fromIntegral $+ max 1 variable.numeric.matrix.column_count *+ product (VectorS.toList variable.array.dims) -inputStageInterface- :: (StageInfo stages, IsString label)- => StageInterface stages- -> Maybe (label, InterfaceBinds)-inputStageInterface staged = listToMaybe active+inputProblems+ :: Vector Vk.VertexInputAttributeDescription+ -> Text+ -> InterfaceVariable+ -> Word32+ -> [Text]+inputProblems attributes label variable location =+ case Vector.find ((== location) . (.location)) attributes of+ Nothing ->+ pure $ subject <> " has no vertex attribute"+ Just attribute -> do+ shaderNumeric <- toList $ Format.numericFormat shaderFormat+ attributeNumeric <- toList $ Format.numericFormat attribute.format+ guard $ shaderNumeric /= attributeNumeric+ pure $ mconcat+ [ subject+ , " reads "+ , tshow shaderFormat+ , " from a "+ , tshow attribute.format+ , " attribute"+ ] where- active = do- (label, Just binds) <- toList $ withLabels staged- pure (label, fst binds)+ subject = mconcat+ [ label+ , " input"+ , foldMap (" " <>) variable.name+ , " at location "+ , tshow location+ ]++ shaderFormat =+ case variable.format of+ Format value ->+ Vk.Format $ fromIntegral value
src/Engine/Stage/Bootstrap/Setup.hs view
@@ -1,46 +1,14 @@ module Engine.Stage.Bootstrap.Setup ( stackStage- , bootstrapStage ) where import RIO -import UnliftIO.Resource qualified as Resource--import Engine.Stage.Component qualified as Stage import Engine.Types (StackStage(..)) import Engine.Types qualified as Engine-import Engine.StageSwitch (trySwitchStage) stackStage :: (a -> StackStage) -> Engine.StageSetupRIO a -> StackStage-stackStage handoff action = StackStage $ bootstrapStage handoff action--bootstrapStage- :: (a -> StackStage)- -> Engine.StageSetupRIO a- -> Engine.Stage Stage.NoRenderPass Stage.NoPipelines Stage.NoFrameResources Stage.NoRunState-bootstrapStage handoff action = Stage.assemble "Bootstrap" Stage.noRendering resources Nothing- where- resources = Stage.noResources- { Stage.rInitialRS =- transitState handoff action- }--transitState- :: (a -> StackStage)- -> Engine.StageSetupRIO a- -> Engine.StageSetupRIO (Resource.ReleaseKey, Stage.NoRunState)-transitState handoff action = do- res <- action-- switched <- trySwitchStage . Engine.Replace $- handoff res-- unless switched $- logError "Bootstrap switch failed"-- key <- Resource.register $ pure ()- pure (key, Stage.NoRunState)+stackStage handoff action = StackStageSetup $ handoff <$> action
src/Engine/Stage/Component.hs view
@@ -3,71 +3,71 @@ import RIO import Control.Monad.Trans.Resource (ResourceT)-import Data.Semigroup (Semigroup(..)) import UnliftIO.Resource (ReleaseKey, allocate) import Vulkan.Core10 qualified as Vk-import Vulkan.NamedType ((:::))+import Vulkan.Utils.Queues (Queues) -import Engine.Types (Stage(..), StageFrameRIO, StageRIO)+import Engine.Types (RenderGraph, Stage(..), StageFrameRIO, StageRIO) import Engine.Vulkan.Swapchain (SwapchainResources(..))-import Engine.Vulkan.Types qualified as Vulkan+import Render.Target (RenderTarget(..)) import Resource.Region qualified as Region assemble- :: Foldable t- => Text- -> Rendering rp p st- -> Resources rp p st rr- -> t (Scene rp p st rr)- -> Stage rp p rr st-assemble title Rendering{..} Resources{..} (fold -> Scene{..}) = Stage+ :: Text+ -> Rendering rt p st+ -> Resources rt p st rr+ -> (rt -> p -> st -> rr -> RenderGraph rt p rr st)+ -> Stage rt p rr st+assemble title Rendering{..} Resources{..} renderGraph = Stage { sTitle = title - , sAllocateRP = rAllocateRP- , sAllocateP = rAllocateP+ , sAllocateTargets = rAllocateTargets+ , sAllocateP = rAllocateP - , sInitialRS = rInitialRS- , sInitialRR = rInitialRR+ , sInitialRS = rInitialRS+ , sInitialRR = rInitialRR - , sBeforeLoop = Region.exec scBeforeLoop- , sUpdateBuffers = scUpdateBuffers- , sRecordCommands = scRecordCommands+ , sBeforeLoop = Region.exec rBeforeLoop+ , sUpdateBuffers = rUpdateBuffers+ , sRenderGraph = renderGraph , sAfterLoop = Region.release } -data Rendering rp p st = Rendering- { rAllocateRP :: SwapchainResources -> ResourceT (StageRIO st) rp- , rAllocateP :: SwapchainResources -> rp -> ResourceT (StageRIO st) p+data Rendering rt p st = Rendering+ { rAllocateTargets :: SwapchainResources -> ResourceT (StageRIO st) rt+ , rAllocateP :: SwapchainResources -> rt -> ResourceT (StageRIO st) p } -data NoRenderPass = NoRenderPass+data NoRenderTarget = NoRenderTarget -instance Vulkan.RenderPass NoRenderPass where- updateRenderpass _context = pure- refcountRenderpass _rp = pure ()+instance RenderTarget NoRenderTarget where+ updateTarget _context = pure+ refcountTarget _rp = pure () data NoPipelines = NoPipelines-type NoRendering = Rendering NoRenderPass NoPipelines+type NoRendering = Rendering NoRenderTarget NoPipelines noRendering :: NoRendering st noRendering = Rendering- { rAllocateRP = \_swapchain ->- pure NoRenderPass- , rAllocateP = \_swapchain NoRenderPass ->+ { rAllocateTargets = \_swapchain ->+ pure NoRenderTarget+ , rAllocateP = \_swapchain NoRenderTarget -> pure NoPipelines } -data Resources rp p st rr = Resources- { rInitialRS :: StageRIO (Maybe SwapchainResources) (ReleaseKey, st)- , rInitialRR :: Vulkan.Queues Vk.CommandPool -> rp -> p -> ResourceT (StageRIO st) rr+data Resources rt p st rr = Resources+ { rInitialRS :: StageRIO (Maybe SwapchainResources) (ReleaseKey, st)+ , rInitialRR :: Queues Vk.CommandPool -> rt -> p -> ResourceT (StageRIO st) rr+ , rBeforeLoop :: ResourceT (StageRIO st) ()+ , rUpdateBuffers :: st -> rr -> StageFrameRIO rt p rr st () } -type NoResources rp p = Resources rp p NoRunState NoFrameResources+type NoResources rt p = Resources rt p NoRunState NoFrameResources data NoRunState = NoRunState data NoFrameResources = NoFrameResources -noResources :: NoResources rp p+noResources :: NoResources rt p noResources = Resources { rInitialRS = allocate@@ -75,41 +75,7 @@ (\NoRunState -> pure ()) , rInitialRR = \_pool _rp _p -> pure NoFrameResources- }--data Scene rp p st rr = Scene- { scBeforeLoop :: ResourceT (StageRIO st) ()- , scUpdateBuffers :: st -> rr -> StageFrameRIO rp p rr st ()- , scRecordCommands :: Vk.CommandBuffer -> rr -> "image index" ::: Word32 -> StageFrameRIO rp p rr st ()+ , rBeforeLoop = pure ()+ , rUpdateBuffers = \NoRunState NoFrameResources ->+ pure () }--instance Semigroup (Scene rp p st rr) where- a <> b = Scene- { scBeforeLoop = do- scBeforeLoop a- scBeforeLoop b- , scUpdateBuffers = \st rr -> do- scUpdateBuffers a st rr- scUpdateBuffers b st rr- , scRecordCommands = \cb rr ii -> do- scRecordCommands a cb rr ii- scRecordCommands b cb rr ii- }-- sconcat scenes = Scene- { scBeforeLoop = do- traverse_ scBeforeLoop scenes- , scUpdateBuffers = \st rr ->- for_ scenes \Scene{scUpdateBuffers} ->- scUpdateBuffers st rr- , scRecordCommands = \cb rr ii ->- for_ scenes \Scene{scRecordCommands} ->- scRecordCommands cb rr ii- }--instance Monoid (Scene rp p st rr) where- mempty = Scene- { scBeforeLoop = pure ()- , scUpdateBuffers = mempty- , scRecordCommands = mempty- }
src/Engine/Types.hs view
@@ -13,17 +13,21 @@ import Vulkan.Core10 qualified as Vk import Vulkan.Extensions.VK_KHR_surface qualified as Khr import Vulkan.NamedType ((:::))-import Vulkan.Utils.QueueAssignment (QueueFamilyIndex(..))+import Vulkan.Utils.FrameGraph.Image (SliceRegistry)+import Vulkan.Utils.Queues (Queues)+import Vulkan.Utils.RefCounted (RefCounted)+import Vulkan.Utils.VulkanContext (RecycledResources) import VulkanMemoryAllocator qualified as VMA import Engine.Setup.Window (Window) import Engine.Setup.Window qualified as Window import Engine.Types.Options (Options)-import Engine.Types.RefCounted (RefCounted) import Engine.Vulkan.Swapchain (SwapchainResources(..)) import Engine.Vulkan.Types (HasVulkan(..), HasSwapchain(..)) import Engine.Vulkan.Types qualified as Vulkan import Engine.Worker qualified as Worker+import Render.Graph (Graph, HasSliceRegistry(..), Image, Swapchain)+import Render.Target (RenderTarget) -- * App globals @@ -37,11 +41,12 @@ , ghPhysicalDeviceInfo :: Vulkan.PhysicalDeviceInfo , ghDevice :: Vk.Device , ghAllocator :: VMA.Allocator- , ghQueues :: Vulkan.Queues (QueueFamilyIndex, Vk.Queue)+ , ghQueues :: Queues Vulkan.Queue , ghScreenVar :: Worker.Var Vk.Extent2D , ghWindowSize :: Worker.Var Window.Size , ghStageSwitch :: StageSwitchVar , ghMonotonicStart :: Word64+ , ghSliceRegistry :: SliceRegistry } {-# INLINE askScreenVar #-}@@ -64,6 +69,9 @@ getDevice = ghDevice getAllocator = ghAllocator +instance HasSliceRegistry GlobalHandles where+ getSliceRegistry = ghSliceRegistry+ class HasMonotime env where getMonotonicTimeStart :: env -> Word64 @@ -75,7 +83,7 @@ {-# INLINE getMonotonicTimeStart #-} getMonotonicTimeStart = ghMonotonicStart . appEnv -instance HasMonotime (App GlobalHandles st, Frame rp p rr) where+instance HasMonotime (App GlobalHandles st, Frame rt p rr) where {-# INLINE getMonotonicTimeStart #-} getMonotonicTimeStart = ghMonotonicStart . appEnv . fst @@ -108,17 +116,20 @@ data StackStage where StackStage- :: forall rp p rr st- . Vulkan.RenderPass rp- => Stage rp p rr st+ :: forall rt p rr st+ . RenderTarget rt+ => Stage rt p rr st -> StackStage StackStageContinue- :: forall rp p rr st- . Vulkan.RenderPass rp+ :: forall rt p rr st+ . RenderTarget rt => ReleaseKey -> st- -> Stage rp p rr st+ -> Stage rt p rr st -> StackStage+ StackStageSetup+ :: StageSetupRIO StackStage+ -> StackStage type StageSwitchVar = TMVar StageSwitch @@ -132,9 +143,13 @@ type StageSetupRIO = RIO (App GlobalHandles (Maybe SwapchainResources)) -type StageFrameRIO rp p rr st = RIO (App GlobalHandles st, Frame rp p rr)+type StageFrameRIO rt p rr st = RIO (App GlobalHandles st, Frame rt p rr) -instance HasStateRef st (App GlobalHandles st, Frame rp p rr) where+type StageGraph rt p rr st = Graph (App GlobalHandles st, Frame rt p rr)++type RenderGraph rt p rr st = StageGraph rt p rr st (Image Swapchain) (Image Swapchain)++instance HasStateRef st (App GlobalHandles st, Frame rt p rr) where stateRefL = lens (appState . fst)@@ -146,24 +161,24 @@ ) ) -data Stage rp p rr st = forall a . Stage+data Stage rt p rr st = forall a . Stage { sTitle :: Text - , sAllocateRP :: SwapchainResources -> ResourceT (StageRIO st) rp- , sAllocateP :: SwapchainResources -> rp -> ResourceT (StageRIO st) p- , sInitialRS :: StageRIO (Maybe SwapchainResources) (ReleaseKey, st)- , sInitialRR :: Vulkan.Queues Vk.CommandPool -> rp -> p -> ResourceT (StageRIO st) rr+ , sAllocateTargets :: SwapchainResources -> ResourceT (StageRIO st) rt+ , sAllocateP :: SwapchainResources -> rt -> ResourceT (StageRIO st) p+ , sInitialRS :: StageRIO (Maybe SwapchainResources) (ReleaseKey, st)+ , sInitialRR :: Queues Vk.CommandPool -> rt -> p -> ResourceT (StageRIO st) rr , sBeforeLoop :: StageRIO st a- , sUpdateBuffers :: st -> rr -> StageFrameRIO rp p rr st ()- , sRecordCommands :: Vk.CommandBuffer -> rr -> "image index" ::: Word32 -> StageFrameRIO rp p rr st ()+ , sUpdateBuffers :: st -> rr -> StageFrameRIO rt p rr st ()+ , sRenderGraph :: rt -> p -> st -> rr -> RenderGraph rt p rr st , sAfterLoop :: a -> StageRIO st () } -- * Frame loop inside a stage -- | All the information required to render a single frame-data Frame renderpass pipelines resources = Frame+data Frame targets pipelines resources = Frame { fIndex :: Word64 -- ^ Which number frame is this , fWindow :: Window , fSurface :: Khr.SurfaceKHR@@ -172,7 +187,7 @@ , fMSAA :: Vk.SampleCountFlagBits , fSwapchainResources :: SwapchainResources- , fRenderpass :: renderpass+ , fTargets :: targets , fPipelines :: pipelines , fRenderFinishedHostSemaphore :: Vk.Semaphore {- ^@@ -203,7 +218,7 @@ -} } -instance HasSwapchain (Frame renderpass pipelines resources) where+instance HasSwapchain (Frame targets pipelines resources) where getSurfaceExtent = getSurfaceExtent . fSwapchainResources getSurfaceFormat = getSurfaceFormat . fSwapchainResources getDepthFormat = getDepthFormat . fSwapchainResources@@ -226,27 +241,10 @@ , "frame index" ::: Word64 ) --- | These are resources which are reused by a later frame when the current--- frame is retired-data RecycledResources a = RecycledResources- { rrImageAvailableSemaphore :: Vk.Semaphore- -- ^ A binary semaphore passed to 'acquireNextImageKHR'- , rrRenderFinishedSemaphore :: Vk.Semaphore- -- ^ A binary semaphore to synchronize rendering and presenting-- , rrQueues :: Vulkan.Queues Vk.CommandPool- {- ^- Pool for this frame's commands for each of the queue families.- (might want more than one of these for multithreaded recording)- -}-- , rrData :: a- }--instance HasLogFunc env => HasLogFunc (env, Frame rp p rr) where+instance HasLogFunc env => HasLogFunc (env, Frame rt p rr) where logFuncL = _1 . logFuncL -instance MonadResource (RIO (env, Frame rp p rr)) where+instance MonadResource (RIO (env, Frame rt p rr)) where {-# INLINE liftResourceT #-} liftResourceT rt = asks (snd . fResources . snd) >>=
src/Engine/Types/RefCounted.hs view
@@ -1,54 +1,12 @@-module Engine.Types.RefCounted where+module Engine.Types.RefCounted+ ( wrapped+ ) where import RIO -import Control.Monad.Trans.Resource (allocate_)-import GHC.IO.Exception (IOErrorType(UserError), IOException(IOError)) import UnliftIO.Resource (MonadResource, ReleaseKey) import UnliftIO.Resource qualified as Resource---- | A 'RefCounted' will perform the specified action when the count reaches 0-data RefCounted = RefCounted- { rcCount :: IORef Int- , rcAction :: IO ()- }---- | Create a counter with a value of 1-newRefCounted :: MonadIO m => IO () -> m RefCounted-newRefCounted rcAction = do- rcCount <- liftIO $ newIORef 1- pure RefCounted{..}---- | Decrement the value, the action will be run promptly and in--- this thread if the counter reached 0.-releaseRefCounted :: MonadIO m => RefCounted -> m ()-releaseRefCounted RefCounted{..} =- liftIO $ mask \_ ->- atomicModifyIORef' rcCount (\c -> (c - 1, c - 1)) >>= \case- n | n < 0 ->- throwM $ IOError- Nothing- UserError- ""- "Ref counted value decremented below 0"- Nothing- Nothing-- 0 ->- rcAction-- _stillReferenced ->- pure ()---- | Increment the counter by 1-takeRefCounted :: MonadIO m => RefCounted -> m ()-takeRefCounted RefCounted{..} =- liftIO $ atomicModifyIORef' rcCount \c -> (c + 1, ())---- | Hold a reference for the duration of the 'MonadResource' action-resourceTRefCount :: MonadResource f => RefCounted -> f ()-resourceTRefCount r =- void $ allocate_ (takeRefCounted r) (releaseRefCounted r)+import Vulkan.Utils.RefCounted (RefCounted, newRefCounted) wrapped :: MonadResource m => m (ReleaseKey, a) -> m (RefCounted, a) wrapped action = do
+ src/Engine/Vulkan/Capabilities.hs view
@@ -0,0 +1,342 @@+module Engine.Vulkan.Capabilities+ ( Capabilities(..)+ , probe+ , hasExtension+ , anisotropyLimit+ , sampleShading+ , logCapabilities+ ) where++import RIO++import Data.Typeable (cast)+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import RIO.Text qualified as Text+import RIO.Vector qualified as Vector+import Vulkan.Core10 qualified as Vk+import Vulkan.Core11 (PhysicalDeviceProperties2(..), getPhysicalDeviceProperties2)+import Vulkan.Core12 (PhysicalDeviceVulkan11Features, PhysicalDeviceVulkan11Properties, PhysicalDeviceVulkan12Features, PhysicalDeviceVulkan12Properties(..))+import Vulkan.Core13 (PhysicalDeviceVulkan13Features, PhysicalDeviceVulkan13Properties)+import Vulkan.CStruct.Extends (Extendss, PeekChain, PokeChain, SomeStruct)+import Vulkan.Extensions.VK_EXT_attachment_feedback_loop_layout (PhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT)+import Vulkan.Extensions.VK_EXT_conditional_rendering (PhysicalDeviceConditionalRenderingFeaturesEXT)+import Vulkan.Extensions.VK_EXT_custom_border_color (PhysicalDeviceCustomBorderColorFeaturesEXT, PhysicalDeviceCustomBorderColorPropertiesEXT, pattern EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME)+import Vulkan.Extensions.VK_EXT_depth_clip_control (PhysicalDeviceDepthClipControlFeaturesEXT)+import Vulkan.Extensions.VK_EXT_depth_clip_enable (PhysicalDeviceDepthClipEnableFeaturesEXT)+import Vulkan.Extensions.VK_EXT_dynamic_rendering_unused_attachments (PhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT)+import Vulkan.Extensions.VK_EXT_extended_dynamic_state3 (PhysicalDeviceExtendedDynamicState3FeaturesEXT, PhysicalDeviceExtendedDynamicState3PropertiesEXT, pattern EXT_EXTENDED_DYNAMIC_STATE_3_EXTENSION_NAME)+import Vulkan.Extensions.VK_EXT_external_memory_host (PhysicalDeviceExternalMemoryHostPropertiesEXT, pattern EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME)+import Vulkan.Extensions.VK_EXT_fragment_shader_interlock (PhysicalDeviceFragmentShaderInterlockFeaturesEXT)+import Vulkan.Extensions.VK_EXT_graphics_pipeline_library (PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT, PhysicalDeviceGraphicsPipelineLibraryPropertiesEXT, pattern EXT_GRAPHICS_PIPELINE_LIBRARY_EXTENSION_NAME)+import Vulkan.Extensions.VK_EXT_image_view_min_lod (PhysicalDeviceImageViewMinLodFeaturesEXT)+import Vulkan.Extensions.VK_EXT_line_rasterization (pattern EXT_LINE_RASTERIZATION_EXTENSION_NAME)+import Vulkan.Extensions.VK_EXT_mutable_descriptor_type (PhysicalDeviceMutableDescriptorTypeFeaturesEXT)+import Vulkan.Extensions.VK_EXT_non_seamless_cube_map (PhysicalDeviceNonSeamlessCubeMapFeaturesEXT)+import Vulkan.Extensions.VK_EXT_primitive_topology_list_restart (PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT)+import Vulkan.Extensions.VK_EXT_robustness2 (PhysicalDeviceRobustness2FeaturesEXT, PhysicalDeviceRobustness2PropertiesEXT, pattern EXT_ROBUSTNESS_2_EXTENSION_NAME)+import Vulkan.Extensions.VK_EXT_sample_locations (PhysicalDeviceSampleLocationsPropertiesEXT, pattern EXT_SAMPLE_LOCATIONS_EXTENSION_NAME)+import Vulkan.Extensions.VK_EXT_shader_atomic_float (PhysicalDeviceShaderAtomicFloatFeaturesEXT)+import Vulkan.Extensions.VK_EXT_transform_feedback (PhysicalDeviceTransformFeedbackFeaturesEXT, PhysicalDeviceTransformFeedbackPropertiesEXT, pattern EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME)+import Vulkan.Extensions.VK_EXT_vertex_input_dynamic_state (PhysicalDeviceVertexInputDynamicStateFeaturesEXT)+import Vulkan.Extensions.VK_KHR_global_priority (PhysicalDeviceGlobalPriorityQueryFeaturesKHR)+import Vulkan.Extensions.VK_KHR_index_type_uint8 (PhysicalDeviceIndexTypeUint8FeaturesKHR)+import Vulkan.Extensions.VK_KHR_line_rasterization (PhysicalDeviceLineRasterizationFeaturesKHR, PhysicalDeviceLineRasterizationPropertiesKHR)+import Vulkan.Extensions.VK_KHR_maintenance5 (PhysicalDeviceMaintenance5FeaturesKHR, PhysicalDeviceMaintenance5PropertiesKHR, pattern KHR_MAINTENANCE_5_EXTENSION_NAME)+import Vulkan.Extensions.VK_KHR_push_descriptor (PhysicalDevicePushDescriptorPropertiesKHR, pattern KHR_PUSH_DESCRIPTOR_EXTENSION_NAME)+import Vulkan.Extensions.VK_KHR_vertex_attribute_divisor (PhysicalDeviceVertexAttributeDivisorFeaturesKHR, PhysicalDeviceVertexAttributeDivisorPropertiesKHR, pattern KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME)+import Vulkan.Requirement (DeviceRequirement(..))+import Vulkan.Utils.Requirements (RequirementResult(..), checkDeviceRequirements, prettyRequirementResult)+import Vulkan.Version (_API_VERSION_MAJOR, _API_VERSION_MINOR, _API_VERSION_PATCH)+import Vulkan.Zero (Zero, zero)++data Capabilities = Capabilities+ { capsFeatures :: Vk.PhysicalDeviceFeatures+ , capsFeatures11 :: PhysicalDeviceVulkan11Features+ , capsFeatures12 :: PhysicalDeviceVulkan12Features+ , capsFeatures13 :: PhysicalDeviceVulkan13Features++ , capsExtensions :: Set ByteString++ , capsMaintenance5 :: PhysicalDeviceMaintenance5FeaturesKHR+ , capsGlobalPriorityQuery :: PhysicalDeviceGlobalPriorityQueryFeaturesKHR+ , capsVertexAttributeDivisor :: PhysicalDeviceVertexAttributeDivisorFeaturesKHR+ , capsIndexTypeUint8 :: PhysicalDeviceIndexTypeUint8FeaturesKHR+ , capsLineRasterization :: PhysicalDeviceLineRasterizationFeaturesKHR+ , capsRobustness2 :: PhysicalDeviceRobustness2FeaturesEXT+ , capsShaderAtomicFloat :: PhysicalDeviceShaderAtomicFloatFeaturesEXT+ , capsMutableDescriptorType :: PhysicalDeviceMutableDescriptorTypeFeaturesEXT+ , capsDepthClipControl :: PhysicalDeviceDepthClipControlFeaturesEXT+ , capsDepthClipEnable :: PhysicalDeviceDepthClipEnableFeaturesEXT+ , capsCustomBorderColor :: PhysicalDeviceCustomBorderColorFeaturesEXT+ , capsImageViewMinLod :: PhysicalDeviceImageViewMinLodFeaturesEXT+ , capsNonSeamlessCubeMap :: PhysicalDeviceNonSeamlessCubeMapFeaturesEXT+ , capsPrimitiveTopologyListRestart :: PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT+ , capsFragmentShaderInterlock :: PhysicalDeviceFragmentShaderInterlockFeaturesEXT+ , capsConditionalRendering :: PhysicalDeviceConditionalRenderingFeaturesEXT+ , capsTransformFeedback :: PhysicalDeviceTransformFeedbackFeaturesEXT+ , capsAttachmentFeedbackLoopLayout :: PhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT+ , capsDynamicRenderingUnusedAttachments :: PhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT+ , capsVertexInputDynamicState :: PhysicalDeviceVertexInputDynamicStateFeaturesEXT+ , capsGraphicsPipelineLibrary :: PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT+ , capsExtendedDynamicState3 :: PhysicalDeviceExtendedDynamicState3FeaturesEXT++ , capsProperties :: Vk.PhysicalDeviceProperties+ , capsProperties11 :: PhysicalDeviceVulkan11Properties+ , capsProperties12 :: PhysicalDeviceVulkan12Properties+ , capsProperties13 :: PhysicalDeviceVulkan13Properties++ , capsPushDescriptorProperties :: Maybe PhysicalDevicePushDescriptorPropertiesKHR+ , capsRobustness2Properties :: Maybe PhysicalDeviceRobustness2PropertiesEXT+ , capsLineRasterizationProperties :: Maybe PhysicalDeviceLineRasterizationPropertiesKHR+ , capsVertexAttributeDivisorProperties :: Maybe PhysicalDeviceVertexAttributeDivisorPropertiesKHR+ , capsExtendedDynamicState3Properties :: Maybe PhysicalDeviceExtendedDynamicState3PropertiesEXT+ , capsGraphicsPipelineLibraryProperties :: Maybe PhysicalDeviceGraphicsPipelineLibraryPropertiesEXT+ , capsTransformFeedbackProperties :: Maybe PhysicalDeviceTransformFeedbackPropertiesEXT+ , capsCustomBorderColorProperties :: Maybe PhysicalDeviceCustomBorderColorPropertiesEXT+ , capsSampleLocationsProperties :: Maybe PhysicalDeviceSampleLocationsPropertiesEXT+ , capsExternalMemoryHostProperties :: Maybe PhysicalDeviceExternalMemoryHostPropertiesEXT+ , capsMaintenance5Properties :: Maybe PhysicalDeviceMaintenance5PropertiesKHR++ , capsMemory :: Vk.PhysicalDeviceMemoryProperties+ , capsQueueFamilies :: Vector Vk.QueueFamilyProperties++ , capsDenied :: [Text]+ }+ deriving (Show)++probe+ :: MonadIO m+ => [DeviceRequirement]+ -> [[DeviceRequirement]]+ -> Vk.PhysicalDevice+ -> Vk.DeviceCreateInfo '[]+ -> m (Either [Text] (Capabilities, SomeStruct Vk.DeviceCreateInfo))+probe required optionalGroups phys baseCreateInfo = do+ (_, availableExtensions) <- Vk.enumerateDeviceExtensionProperties phys Nothing+ let+ extensionVersions = Map.fromList+ [ (extensionName, specVersion)+ | Vk.ExtensionProperties extensionName specVersion <- toList availableExtensions+ ]+ (optionals, skipped) = foldMap (gateGroup extensionVersions) optionalGroups+ (createInfo, requiredResults, optionalResults) <-+ checkDeviceRequirements required optionals phys baseCreateInfo+ case createInfo of+ Nothing ->+ pure . Left $ unmet requiredResults+ Just deviceCreateInfo -> do+ let+ granted =+ required <>+ [ requirement+ | (requirement, Satisfied) <- zip optionals optionalResults+ ]+ caps <- collect phys granted (unmet optionalResults <> skipped)+ pure $ Right (caps, deviceCreateInfo)+ where+ unmet results =+ [ fromString $ prettyRequirementResult result+ | result <- results+ , result /= Satisfied+ ]++gateGroup+ :: Map ByteString Word32+ -> [DeviceRequirement]+ -> ([DeviceRequirement], [Text])+gateGroup extensionVersions group+ | all extensionAvailable group =+ (group, [])+ | otherwise =+ ( filter (isNothing . extensionDependentName) group+ , [ "Skipped " <> decodeUtf8Lenient name <> " without its extension"+ | Just name <- map extensionDependentName group+ ]+ )+ where+ extensionAvailable = \case+ RequireDeviceExtension{deviceExtensionName, deviceExtensionMinVersion} ->+ maybe False (>= deviceExtensionMinVersion) $+ Map.lookup deviceExtensionName extensionVersions+ _ ->+ True++extensionDependentName :: DeviceRequirement -> Maybe ByteString+extensionDependentName = \case+ RequireDeviceFeature{featureName} ->+ Just featureName+ RequireDeviceProperty{propertyName} ->+ Just propertyName+ _ ->+ Nothing++collect+ :: MonadIO m+ => Vk.PhysicalDevice+ -> [DeviceRequirement]+ -> [Text]+ -> m Capabilities+collect phys granted denied = do+ PhysicalDeviceProperties2{properties = coreProperties, next = (properties11, (properties12, (properties13, ())))} <-+ getPhysicalDeviceProperties2+ @'[PhysicalDeviceVulkan11Properties, PhysicalDeviceVulkan12Properties, PhysicalDeviceVulkan13Properties]+ phys++ pushDescriptor <- grantedProperties @PhysicalDevicePushDescriptorPropertiesKHR extensions phys KHR_PUSH_DESCRIPTOR_EXTENSION_NAME+ robustness2 <- grantedProperties @PhysicalDeviceRobustness2PropertiesEXT extensions phys EXT_ROBUSTNESS_2_EXTENSION_NAME+ lineRasterization <- grantedProperties @PhysicalDeviceLineRasterizationPropertiesKHR extensions phys EXT_LINE_RASTERIZATION_EXTENSION_NAME+ vertexAttributeDivisor <- grantedProperties @PhysicalDeviceVertexAttributeDivisorPropertiesKHR extensions phys KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME+ extendedDynamicState3 <- grantedProperties @PhysicalDeviceExtendedDynamicState3PropertiesEXT extensions phys EXT_EXTENDED_DYNAMIC_STATE_3_EXTENSION_NAME+ graphicsPipelineLibrary <- grantedProperties @PhysicalDeviceGraphicsPipelineLibraryPropertiesEXT extensions phys EXT_GRAPHICS_PIPELINE_LIBRARY_EXTENSION_NAME+ transformFeedback <- grantedProperties @PhysicalDeviceTransformFeedbackPropertiesEXT extensions phys EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME+ customBorderColor <- grantedProperties @PhysicalDeviceCustomBorderColorPropertiesEXT extensions phys EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME+ sampleLocations <- grantedProperties @PhysicalDeviceSampleLocationsPropertiesEXT extensions phys EXT_SAMPLE_LOCATIONS_EXTENSION_NAME+ externalMemoryHost <- grantedProperties @PhysicalDeviceExternalMemoryHostPropertiesEXT extensions phys EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME+ maintenance5 <- grantedProperties @PhysicalDeviceMaintenance5PropertiesKHR extensions phys KHR_MAINTENANCE_5_EXTENSION_NAME++ memory <- trimMemory <$> Vk.getPhysicalDeviceMemoryProperties phys+ queueFamilies <- Vk.getPhysicalDeviceQueueFamilyProperties phys++ pure Capabilities+ { capsFeatures = grantedStruct granted+ , capsFeatures11 = grantedStruct granted+ , capsFeatures12 = grantedStruct granted+ , capsFeatures13 = grantedStruct granted++ , capsExtensions = extensions++ , capsMaintenance5 = grantedStruct granted+ , capsGlobalPriorityQuery = grantedStruct granted+ , capsVertexAttributeDivisor = grantedStruct granted+ , capsIndexTypeUint8 = grantedStruct granted+ , capsLineRasterization = grantedStruct granted+ , capsRobustness2 = grantedStruct granted+ , capsShaderAtomicFloat = grantedStruct granted+ , capsMutableDescriptorType = grantedStruct granted+ , capsDepthClipControl = grantedStruct granted+ , capsDepthClipEnable = grantedStruct granted+ , capsCustomBorderColor = grantedStruct granted+ , capsImageViewMinLod = grantedStruct granted+ , capsNonSeamlessCubeMap = grantedStruct granted+ , capsPrimitiveTopologyListRestart = grantedStruct granted+ , capsFragmentShaderInterlock = grantedStruct granted+ , capsConditionalRendering = grantedStruct granted+ , capsTransformFeedback = grantedStruct granted+ , capsAttachmentFeedbackLoopLayout = grantedStruct granted+ , capsDynamicRenderingUnusedAttachments = grantedStruct granted+ , capsVertexInputDynamicState = grantedStruct granted+ , capsGraphicsPipelineLibrary = grantedStruct granted+ , capsExtendedDynamicState3 = grantedStruct granted++ , capsProperties = coreProperties+ , capsProperties11 = properties11+ , capsProperties12 = properties12+ , capsProperties13 = properties13++ , capsPushDescriptorProperties = pushDescriptor+ , capsRobustness2Properties = robustness2+ , capsLineRasterizationProperties = lineRasterization+ , capsVertexAttributeDivisorProperties = vertexAttributeDivisor+ , capsExtendedDynamicState3Properties = extendedDynamicState3+ , capsGraphicsPipelineLibraryProperties = graphicsPipelineLibrary+ , capsTransformFeedbackProperties = transformFeedback+ , capsCustomBorderColorProperties = customBorderColor+ , capsSampleLocationsProperties = sampleLocations+ , capsExternalMemoryHostProperties = externalMemoryHost+ , capsMaintenance5Properties = maintenance5++ , capsMemory = memory+ , capsQueueFamilies = queueFamilies++ , capsDenied = denied+ }+ where+ extensions = Set.fromList+ [ deviceExtensionName+ | RequireDeviceExtension{deviceExtensionName} <- granted+ ]++grantedStruct :: (Typeable struct, Zero struct) => [DeviceRequirement] -> struct+grantedStruct = foldl' enable zero+ where+ enable acc = \case+ RequireDeviceFeature{enableFeature} ->+ maybe acc ($ acc) (cast enableFeature)+ _ ->+ acc++grantedProperties+ :: forall struct m+ . ( MonadIO m+ , Extendss PhysicalDeviceProperties2 '[struct]+ , PokeChain '[struct]+ , PeekChain '[struct]+ )+ => Set ByteString+ -> Vk.PhysicalDevice+ -> ByteString+ -> m (Maybe struct)+grantedProperties extensions phys extensionName+ | Set.member extensionName extensions = do+ PhysicalDeviceProperties2{next = (extensionProperties, ())} <-+ getPhysicalDeviceProperties2 @'[struct] phys+ pure $ Just extensionProperties+ | otherwise =+ pure Nothing++trimMemory :: Vk.PhysicalDeviceMemoryProperties -> Vk.PhysicalDeviceMemoryProperties+trimMemory (Vk.PhysicalDeviceMemoryProperties typeCount types heapCount heaps) =+ Vk.PhysicalDeviceMemoryProperties+ typeCount+ (Vector.take (fromIntegral typeCount) types)+ heapCount+ (Vector.take (fromIntegral heapCount) heaps)++hasExtension :: ByteString -> Capabilities -> Bool+hasExtension extensionName caps =+ Set.member extensionName caps.capsExtensions++anisotropyLimit :: Capabilities -> Float+anisotropyLimit caps =+ if caps.capsFeatures.samplerAnisotropy then+ caps.capsProperties.limits.maxSamplerAnisotropy+ else+ 1++sampleShading :: Capabilities -> Bool+sampleShading caps =+ caps.capsFeatures.sampleRateShading++logCapabilities+ :: ( MonadIO m+ , MonadReader env m+ , HasLogFunc env+ )+ => Capabilities+ -> m ()+logCapabilities caps = do+ logInfo $ mconcat+ [ "Device API "+ , display (_API_VERSION_MAJOR apiVersion)+ , "."+ , display (_API_VERSION_MINOR apiVersion)+ , "."+ , display (_API_VERSION_PATCH apiVersion)+ , ", driver "+ , display (decodeUtf8Lenient caps.capsProperties12.driverName)+ , " "+ , display (decodeUtf8Lenient caps.capsProperties12.driverInfo)+ , ", "+ , display (Set.size caps.capsExtensions)+ , " extensions granted, "+ , display (length caps.capsDenied)+ , " optional requirements denied"+ ]+ logDebug $+ "Granted extensions: " <>+ display (Text.intercalate ", " . map decodeUtf8Lenient $ Set.toAscList caps.capsExtensions)+ for_ caps.capsDenied \denied ->+ logDebug $ "Denied: " <> display denied+ where+ apiVersion = caps.capsProperties.apiVersion
src/Engine/Vulkan/DescSets.hs view
@@ -24,8 +24,9 @@ import Data.Tagged (Tagged(..)) import GHC.TypeLits as Type import Vulkan.Core10 qualified as Vk+import Vulkan.Utils.VulkanContext (RecycledResources(rrData)) -import Engine.Types (Frame(fRecycledResources), RecycledResources(rrData))+import Engine.Types (Frame(fRecycledResources)) import Engine.Vulkan.Types (Bound(..)) class HasDescSet tag a where@@ -35,11 +36,11 @@ {-# INLINE getDescSet #-} getDescSet = getDescSet . rrData -instance HasDescSet tag rr => HasDescSet tag (Frame rp p rr) where+instance HasDescSet tag rr => HasDescSet tag (Frame rt p rr) where {-# INLINE getDescSet #-} getDescSet = getDescSet . fRecycledResources -instance HasDescSet tag rr => HasDescSet tag (env, Frame rp p rr) where+instance HasDescSet tag rr => HasDescSet tag (env, Frame rt p rr) where {-# INLINE getDescSet #-} getDescSet = getDescSet . snd
src/Engine/Vulkan/Format.hs view
@@ -5,6 +5,9 @@ , genericVkFormat , formatSize++ , NumericFormat(..)+ , numericFormat ) where import RIO@@ -128,3 +131,29 @@ format -> error $ "Format size unknown: " <> show format++data NumericFormat+ = NumericFloat+ | NumericSInt+ | NumericUInt+ deriving (Eq, Show)++numericFormat :: Vk.Format -> Maybe NumericFormat+numericFormat = \case+ Vk.FORMAT_R32G32B32A32_SFLOAT -> Just NumericFloat+ Vk.FORMAT_R32G32B32_SFLOAT -> Just NumericFloat+ Vk.FORMAT_R32G32_SFLOAT -> Just NumericFloat+ Vk.FORMAT_R32_SFLOAT -> Just NumericFloat++ Vk.FORMAT_R32G32B32A32_UINT -> Just NumericUInt+ Vk.FORMAT_R32G32B32_UINT -> Just NumericUInt+ Vk.FORMAT_R32G32_UINT -> Just NumericUInt+ Vk.FORMAT_R32_UINT -> Just NumericUInt++ Vk.FORMAT_R32G32B32A32_SINT -> Just NumericSInt+ Vk.FORMAT_R32G32B32_SINT -> Just NumericSInt+ Vk.FORMAT_R32G32_SINT -> Just NumericSInt+ Vk.FORMAT_R32_SINT -> Just NumericSInt++ _other ->+ Nothing
src/Engine/Vulkan/Pipeline/Compute.hs view
@@ -12,7 +12,6 @@ , stageFlagBits , StageCode , StageSpirv- , StageReflect , Pipeline(..) , allocate@@ -32,9 +31,11 @@ import UnliftIO.Resource (MonadResource, ReleaseKey) import Vulkan.Core10 qualified as Vk import Vulkan.CStruct.Extends (SomeStruct(..))+import Vulkan.Utils.Pipeline.Specialization (Specialization)+import Vulkan.Utils.Pipeline.Specialization qualified as PS import Vulkan.Zero (Zero(..)) -import Engine.SpirV.Reflect (Reflect)+import Engine.SpirV.Reflect qualified as Reflect import Engine.Vulkan.DescSets (Bound(..), Compatible) import Engine.Vulkan.Pipeline (Pipeline(..)) import Engine.Vulkan.Pipeline qualified as Pipeline@@ -75,13 +76,12 @@ type StageCode = Stages (Maybe Code) type StageSpirv = Stages (Maybe ByteString)-type StageReflect = Reflect Stages allocate :: ( MonadVulkan env m , MonadResource m , HasCallStack- , Shader.Specialization spec+ , Specialization spec ) => Config dsl spec -> m (ReleaseKey, Pipeline dsl Compute Compute)@@ -91,12 +91,17 @@ create :: ( MonadVulkan env io- , Shader.Specialization spec+ , Specialization spec , HasCallStack ) => Config dsl spec -> io (Pipeline dsl Compute Compute) create Config{..} = withFrozenCallStack do+ modules <- Reflect.reflect stages+ either throwString pure . Reflect.check $+ Reflect.stageProblems modules <>+ Reflect.layoutProblems modules (unTagged cDescLayouts) cPushConstantRanges+ -- TODO: get from outside ? dsLayouts <- Layout.create $ Vector.fromList (unTagged cDescLayouts) @@ -106,10 +111,8 @@ cPushConstantRanges Named.objectOrigin pipelineLayout - shader <- Shader.withSpecialization cSpecialization $- Shader.create Stages- { comp = Just cComputeCode- }+ shader <- PS.withSpecialization cSpecialization $+ Shader.create stages let cis = Vector.singleton . SomeStruct $@@ -135,13 +138,17 @@ where cache = getPipelineCache undefined - pipelineCI stages layout = zero+ stages = Stages+ { comp = Just cComputeCode+ }++ pipelineCI shaderStages layout = zero { Vk.layout = layout , Vk.stage = stage , Vk.basePipelineHandle = zero } where- stage = case stages of+ stage = case shaderStages of [one] -> one _assert -> error "compute code has one stage"
src/Engine/Vulkan/Pipeline/External.hs view
@@ -44,6 +44,7 @@ import UnliftIO.Resource (MonadResource, ReleaseKey) import UnliftIO.Resource qualified as Resource import Vulkan.Core10 qualified as Vk+import Vulkan.Utils.Pipeline.Specialization (Specialization) import Render.Code (Code(..)) import Engine.SpirV.Reflect qualified as Reflect@@ -53,9 +54,9 @@ import Engine.Vulkan.Pipeline.Compute qualified as Compute import Engine.Vulkan.Pipeline.Graphics qualified as Graphics import Engine.Vulkan.Pipeline.Stages (StageInfo(..))-import Engine.Vulkan.Shader qualified as Shader-import Engine.Vulkan.Types (Bound, DsLayoutBindings, HasRenderPass)+import Engine.Vulkan.Types (Bound, DsLayoutBindings) import Engine.Worker qualified as Worker+import Render.Target (HasRendering) type Process config = Worker.Timed () config @@ -111,7 +112,7 @@ ) => Text -> stages (Maybe FilePath)- -> ((stages (Maybe ByteString), Reflect.Reflect stages) -> config)+ -> (stages (Maybe ByteString) -> config) -> m (Process config) spawnReflect = spawn loadConfigReflect @@ -128,7 +129,7 @@ ) => Text -> stages (Maybe FilePath)- -> m (Process (stages (Maybe ByteString), Reflect.Reflect stages))+ -> m (Process (stages (Maybe ByteString))) spawnReflect_ name stages = spawn loadConfigReflect name stages id checkTime@@ -160,57 +161,15 @@ loadConfigReflect :: ( StageInfo stages , MonadIO io- , MonadReader env io- , HasLogFunc env ) => stages (Maybe FilePath)- -> io (stages (Maybe ByteString), Reflect.Reflect stages)+ -> io (stages (Maybe ByteString)) loadConfigReflect stageFiles = do stageCode <- loadConfig stageFiles-- -- TODO: use stageCode?- stageRefl <- for stageFiles $- traverse Reflect.invoke-- reflDS <- Reflect.stagesBindMap stageRefl-- let reflIS = Reflect.stagesInterfaceMap stageRefl- case Reflect.interfaceCompatible reflIS of- Right ok ->- logDebug $ displayShow ok- Left (inputStage, outputStage, location, err) -> do- let- between = "Between " <> outputStage <> " and " <> inputStage- locInfo = "(location=" <> show location <> ")"- case err of- Nothing ->- throwString $- unwords [ between, "missing output ", locInfo ]- Just (sigRequested, sigProvided) ->- throwString $ unlines- [ unwords [ between, locInfo <> ":", "incompatible signatures" ]- , " requested: " <> show sigRequested- , " provided: " <> show sigProvided- ]-- (inputStage, inputs) <-- case Reflect.inputStageInterface reflIS of- Nothing ->- throwString "No active stage"- Just found ->- pure found-- let- reflect = Reflect.Reflect- { bindMap = reflDS- , interfaces = reflIS- , inputStage = inputStage- , inputs = inputs- }- pure- ( stageCode- , reflect- )+ modules <- Reflect.reflect stageCode+ either throwString pure . Reflect.check $+ Reflect.stageProblems modules+ pure stageCode type Observer pipeline = Worker.ObserverIO (ReleaseKey, pipeline) @@ -218,55 +177,51 @@ :: ( HasCallStack , pipeline ~ Graphics.Pipeline dsl vertices instances , Worker.HasOutput worker- , Shader.Specialization (Graphics.Specialization pipeline)- , HasRenderPass renderpass+ , Specialization (Graphics.Specialization pipeline)+ , HasRendering target , Worker.GetOutput worker ~ Graphics.Configure pipeline )- => renderpass- -> Vk.SampleCountFlagBits+ => target -> worker -> ResourceT (StageRIO rs) (Observer pipeline)-newObserverGraphics rp msaa process = do+newObserverGraphics target process = do initialConfig <- Worker.getOutputData process initial <- withFrozenCallStack $ Graphics.allocate Nothing- msaa initialConfig- rp+ target Worker.newObserverIO initial observeGraphics- :: ( HasRenderPass renderpass+ :: ( HasRendering target , Worker.HasOutput output , Worker.GetOutput output ~ Graphics.Configure pipeline , pipeline ~ Graphics.Pipeline dsl vertices instances , spec ~ Graphics.Specialization pipeline- , Shader.Specialization spec+ , Specialization spec , HasCallStack )- => renderpass- -> Vk.SampleCountFlagBits+ => target -> Tagged dsl [DsLayoutBindings] -> output -> Worker.ObserverIO (ReleaseKey, pipeline)- -> StageFrameRIO rp p fr rs ()-observeGraphics rp msaa sceneBinds configP output =+ -> StageFrameRIO rt p fr rs ()+observeGraphics target sceneBinds configP output = withFrozenCallStack $ void $!- Worker.observeIO configP output \(oldKey, _old) config -> do+ Worker.observeIO configP output \old config -> do logDebug "Rebuilding pipeline"- Resource.release oldKey- mapRIO fst $ Graphics.allocate- Nothing- msaa- ( config- { Graphics.cDescLayouts = sceneBinds- }- )- rp+ replacePipeline old $+ mapRIO fst $ Graphics.allocate+ Nothing+ ( config+ { Graphics.cDescLayouts = sceneBinds+ }+ )+ target {-# INLINE bindGraphics #-} bindGraphics@@ -303,22 +258,39 @@ observeCompute :: ( Worker.HasOutput output , Worker.GetOutput output ~ config- , Shader.Specialization spec+ , Specialization spec , config ~ Compute.Configure pipeline spec , pipeline ~ Compute.Pipeline dsl Compute Compute ) => Tagged dsl [DsLayoutBindings] -> output -> Worker.ObserverIO (ReleaseKey, pipeline)- -> StageFrameRIO rp p fr rs ()+ -> StageFrameRIO rt p fr rs () observeCompute binds configP output =- void $! Worker.observeIO configP output \(oldKey, _old) config -> do+ void $! Worker.observeIO configP output \old config -> do logDebug "Rebuilding pipeline"- Resource.release oldKey- mapRIO fst $ Compute.allocate config- { Compute.cDescLayouts = binds- }+ replacePipeline old $+ mapRIO fst $ Compute.allocate config+ { Compute.cDescLayouts = binds+ } +replacePipeline+ :: ( MonadUnliftIO m+ , MonadReader env m+ , HasLogFunc env+ )+ => (ReleaseKey, pipeline)+ -> m (ReleaseKey, pipeline)+ -> m (ReleaseKey, pipeline)+replacePipeline old@(oldKey, _old) allocateNew =+ try allocateNew >>= \case+ Left (SomeException err) -> do+ logError $ "Keeping the previous pipeline: " <> displayShow err+ pure old+ Right new -> do+ Resource.release oldKey+ pure new+ -- * HKD wrappers data ConfigureGraphics p@@ -345,25 +317,23 @@ :: forall pf p- renderpass+ target dsl s vs is- rps ps fr rs+ rts ps fr rs . ( p ~ Graphics.Pipeline s vs is- , Shader.Specialization (Graphics.Specialization p)- , HasRenderPass renderpass+ , Specialization (Graphics.Specialization p)+ , HasRendering target )- => renderpass- -> Vk.SampleCountFlagBits+ => target -> Tagged dsl DsLayoutBindings -> pf ConfigureGraphics -> pf Observers -> (forall a . pf a -> a ^ p)- -> StageFrameRIO rps ps fr rs ()-observeField rp msaa binds workers observers field =+ -> StageFrameRIO rts ps fr rs ()+observeField target binds workers observers field = observeGraphics- rp- msaa+ target (Tagged [unTagged binds]) (field @ConfigureGraphics workers) (field @Observers observers)
src/Engine/Vulkan/Pipeline/Graphics.hs view
@@ -23,7 +23,6 @@ , vertexOnly , StageCode , StageSpirv- , StageReflect , Pipeline(..) , allocate@@ -46,21 +45,26 @@ import Data.Vector qualified as Vector import Geomancy (Transform) import GHC.Stack (withFrozenCallStack)+import Language.Haskell.TH.Syntax (Lift) import UnliftIO.Resource (MonadResource, ReleaseKey) import Vulkan.Core10 qualified as Vk-import Vulkan.CStruct.Extends (SomeStruct(..))+import Vulkan.CStruct.Extends (SomeStruct(..), pattern (:&), pattern (::&)) import Vulkan.NamedType ((:::))+import Vulkan.Utils.Pipeline.Specialization (Specialization)+import Vulkan.Utils.Pipeline.Specialization qualified as PS import Vulkan.Zero (Zero(..)) -import Engine.SpirV.Reflect (Reflect)+import Engine.SpirV.Reflect qualified as Reflect+import Engine.Vulkan.Capabilities qualified as Capabilities import Engine.Vulkan.DescSets (Bound(..), Compatible) import Engine.Vulkan.Format (HasVkFormat(..), formatSize) import Engine.Vulkan.Pipeline (Pipeline(..)) import Engine.Vulkan.Pipeline qualified as Pipeline import Engine.Vulkan.Pipeline.Stages (StageInfo(..)) import Engine.Vulkan.Shader qualified as Shader-import Engine.Vulkan.Types (HasVulkan(..), HasRenderPass(..), MonadVulkan, DsLayoutBindings, getPipelineCache)+import Engine.Vulkan.Types (HasVulkan(..), MonadVulkan, DsLayoutBindings, getPipelineCache, pdiCapabilities) import Render.Code (Code)+import Render.Target (HasRendering(..), RenderingFormats(..), pipelineRendering) import Resource.Vulkan.DescriptorLayout qualified as Layout import Resource.Vulkan.Named qualified as Named @@ -71,7 +75,7 @@ , geom :: a -- ^ geometry , frag :: a -- ^ fragment }- deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic1)+ deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic1, Lift) deriving Applicative via (Generically1 Stages) instance StageInfo Stages where@@ -109,7 +113,6 @@ type StageCode = Stages (Maybe Code) type StageSpirv = Stages (Maybe ByteString)-type StageReflect = Reflect Stages type family Configure pipeline where Configure (Pipeline dsl vertices instances) =@@ -121,7 +124,6 @@ data Config (dsl :: [Type]) vertices instances spec = Config { cStages :: StageSpirv- , cReflect :: Maybe StageReflect , cVertexInput :: SomeStruct Vk.PipelineVertexInputStateCreateInfo , cDescLayouts :: Tagged dsl [DsLayoutBindings] , cPushConstantRanges :: Vector Vk.PushConstantRange@@ -140,7 +142,6 @@ baseConfig = Config { cStages = pure Nothing , cVertexInput = zero- , cReflect = Nothing , cDescLayouts = Tagged [] , cPushConstantRanges = mempty , cBlend = False@@ -168,33 +169,37 @@ :: ( config ~ Configure pipeline , pipeline ~ Pipeline dsl vertices instances , spec ~ Pipeline.Specialization pipeline- , Shader.Specialization spec+ , Specialization spec , HasCallStack , MonadVulkan env m , MonadResource m- , HasRenderPass renderpass+ , HasRendering target ) => Maybe Vk.Extent2D- -> Vk.SampleCountFlagBits -> Config dsl vertices instances spec- -> renderpass+ -> target -> m (ReleaseKey, pipeline)-allocate extent_ msaa config renderpass =+allocate extent_ config target = withFrozenCallStack $- Pipeline.allocateWith $ create extent_ msaa renderpass config+ Pipeline.allocateWith $ create extent_ target config create :: ( MonadVulkan env io- , HasRenderPass renderpass- , Shader.Specialization spec+ , HasRendering target+ , Specialization spec , HasCallStack ) => Maybe Vk.Extent2D- -> Vk.SampleCountFlagBits- -> renderpass+ -> target -> Config dsl vertices instances spec -> io (Pipeline dsl vertices instances)-create extent_ msaa renderpass Config{..} = withFrozenCallStack do+create extent_ target Config{..} = withFrozenCallStack do+ modules <- Reflect.reflect cStages+ either throwString pure . Reflect.check $+ Reflect.stageProblems modules <>+ Reflect.layoutProblems modules (unTagged cDescLayouts) cPushConstantRanges <>+ Reflect.vertexInputProblems modules vertexAttributes+ -- TODO: get from outside dsLayouts <- Layout.create $ Vector.fromList (unTagged cDescLayouts) @@ -204,12 +209,16 @@ cPushConstantRanges Named.objectOrigin pipelineLayout - shader <- Shader.withSpecialization cSpecialization $+ shader <- PS.withSpecialization cSpecialization $ Shader.create cStages + shading <- asks $ Capabilities.sampleShading . pdiCapabilities . getPhysicalDeviceInfo+ let cis = Vector.singleton . SomeStruct $- pipelineCI (Shader.sPipelineStages shader) pipelineLayout+ pipelineCI shading (Shader.sPipelineStages shader) pipelineLayout+ ::& pipelineRendering formats+ :& () device <- asks getDevice Vk.createGraphicsPipelines device cache cis Nothing >>= \case@@ -230,7 +239,14 @@ where cache = getPipelineCache undefined - pipelineCI stages layout = zero+ formats = getRenderingFormats target++ vertexAttributes =+ case cVertexInput of+ SomeStruct inputState ->+ inputState.vertexAttributeDescriptions++ pipelineCI shading stages layout = zero { Vk.stages = stages , Vk.vertexInputState = Just cVertexInput , Vk.inputAssemblyState = Just inputAsembly@@ -241,8 +257,6 @@ , Vk.colorBlendState = Just $ SomeStruct colorBlendState , Vk.dynamicState = dynamicState , Vk.layout = layout- , Vk.renderPass = getRenderPass renderpass- , Vk.subpass = 0 , Vk.basePipelineHandle = zero } where@@ -311,13 +325,11 @@ } multisampleState = zero- { Vk.rasterizationSamples = msaa- , Vk.sampleShadingEnable = enable- , Vk.minSampleShading = if enable then 0.2 else 1.0+ { Vk.rasterizationSamples = rfSamples formats+ , Vk.sampleShadingEnable = shading+ , Vk.minSampleShading = if shading then 0.2 else 1.0 , Vk.sampleMask = Vector.singleton maxBound }- where- enable = True -- TODO: check and enable sample rate shading feature depthStencilState = zero { Vk.depthTestEnable = cDepthTest@@ -334,7 +346,7 @@ colorBlendState = zero { Vk.logicOpEnable = False- , Vk.attachments = Vector.singleton zero+ , Vk.attachments = Vector.replicate (Vector.length $ rfColor formats) zero { Vk.blendEnable = cBlend , Vk.srcColorBlendFactor = Vk.BLEND_FACTOR_ONE , Vk.dstColorBlendFactor = Vk.BLEND_FACTOR_ONE_MINUS_SRC_ALPHA
src/Engine/Vulkan/Pipeline/Raytrace.hs view
@@ -29,10 +29,10 @@ } stageFlagBits = Stages- { rgen = Vk.SHADER_STAGE_CALLABLE_BIT_KHR+ { rgen = Vk.SHADER_STAGE_RAYGEN_BIT_KHR , rint = Vk.SHADER_STAGE_INTERSECTION_BIT_KHR- , rahit = Vk.SHADER_STAGE_MISS_BIT_KHR+ , rahit = Vk.SHADER_STAGE_ANY_HIT_BIT_KHR , rchit = Vk.SHADER_STAGE_CLOSEST_HIT_BIT_KHR- , rmiss = Vk.SHADER_STAGE_ANY_HIT_BIT_KHR- , rcall = Vk.SHADER_STAGE_RAYGEN_BIT_KHR+ , rmiss = Vk.SHADER_STAGE_MISS_BIT_KHR+ , rcall = Vk.SHADER_STAGE_CALLABLE_BIT_KHR }
src/Engine/Vulkan/Shader.hs view
@@ -1,26 +1,13 @@-{-# OPTIONS_GHC -Wwarn=orphans #-}--{-# LANGUAGE OverloadedLists #-}- module Engine.Vulkan.Shader ( Shader(..) , create , destroy-- , withSpecialization- , Specialization(..)-- , SpecializationConst(..) ) where import RIO import Data.Vector qualified as Vector-import Data.Vector.Storable qualified as Storable-import Foreign qualified-import GHC.Float (castFloatToWord32) import GHC.Stack (withFrozenCallStack)-import Unsafe.Coerce (unsafeCoerce) import Vulkan.CStruct.Extends (SomeStruct(..)) import Vulkan.Core10 qualified as Vk import Vulkan.Zero (Zero(..))@@ -78,145 +65,3 @@ device <- asks getDevice Vector.forM_ sModules \module_ -> Vk.destroyShaderModule device module_ Nothing---- * Specialization constants--withSpecialization- :: ( Specialization spec- , MonadUnliftIO m- )- => spec- -> (Maybe Vk.SpecializationInfo -> m a)- -> m a-withSpecialization spec action =- case mapEntries of- [] ->- action Nothing- _some ->- withRunInIO \run ->- Storable.unsafeWith specData \specPtr ->- run . action $ Just Vk.SpecializationInfo- { mapEntries = mapEntries- , dataSize = fromIntegral $ Storable.length specData * 4- , data' = Foreign.castPtr @_ @() specPtr- }- where- specData = Storable.fromList $ specializationData spec-- mapEntries = Vector.imap- (\ix _data -> Vk.SpecializationMapEntry- { constantID = fromIntegral ix- , offset = fromIntegral $ ix * 4- , size = 4- }- )- (Vector.convert specData)--class Specialization a where- -- XXX: abusing the fact that most scalars (sans double) are 4-wide- specializationData :: a -> [Word32]--instance Specialization () where- specializationData = const []--instance Specialization [Word32] where- specializationData = id--{- |- The constant_id can only be applied to a scalar *int*, a scalar *float* or a scalar *bool*.- (https://github.com/KhronosGroup/GLSL/blob/master/extensions/khr/GL_KHR_vulkan_glsl.txt)-- XXX: Apparently it is possible to pass uints and doubles too.--}--instance Specialization Word32 where- specializationData x = [packConstData x]--instance Specialization Int32 where- specializationData x = [packConstData x]--instance Specialization Float where- specializationData x = [packConstData x]--instance Specialization Bool where- specializationData x = [packConstData x]--class SpecializationConst a where- packConstData :: a -> Word32--instance SpecializationConst Word32 where- packConstData = id--instance SpecializationConst Int32 where- packConstData = unsafeCoerce--instance SpecializationConst Float where- packConstData = castFloatToWord32--instance SpecializationConst Bool where- packConstData = bool 0 1--instance- ( SpecializationConst a- , SpecializationConst b- ) => Specialization (a, b) where- specializationData (a, b) =- [ packConstData a- , packConstData b- ]--instance- ( SpecializationConst a- , SpecializationConst b- , SpecializationConst c- ) => Specialization (a, b, c) where- specializationData (a, b, c) =- [ packConstData a- , packConstData b- , packConstData c- ]--instance- ( SpecializationConst a- , SpecializationConst b- , SpecializationConst c- , SpecializationConst d- ) => Specialization (a, b, c, d) where- specializationData (a, b, c, d) =- [ packConstData a- , packConstData b- , packConstData c- , packConstData d- ]--instance- ( SpecializationConst a- , SpecializationConst b- , SpecializationConst c- , SpecializationConst d- , SpecializationConst e- ) => Specialization (a, b, c, d, e) where- specializationData (a, b, c, d, e) =- [ packConstData a- , packConstData b- , packConstData c- , packConstData d- , packConstData e- ]--instance- ( SpecializationConst a- , SpecializationConst b- , SpecializationConst c- , SpecializationConst d- , SpecializationConst e- , SpecializationConst f- ) => Specialization (a, b, c, d, e, f) where- specializationData (a, b, c, d, e, f) =- [ packConstData a- , packConstData b- , packConstData c- , packConstData d- , packConstData e- , packConstData f- ]
src/Engine/Vulkan/Swapchain.hs view
@@ -3,70 +3,57 @@ module Engine.Vulkan.Swapchain ( SwapchainResources(..)- , SwapchainInfo(..) , allocSwapchainResources , recreateSwapchainResources- , createSwapchain , threwSwapchainError - , HasSwapchain(..)- , setDynamic , setDynamicFullscreen ) where import RIO -import Data.Bits (zeroBits, (.&.), (.|.))+import Data.Bits (zeroBits, (.&.)) import RIO.Vector qualified as V-import UnliftIO.Resource (MonadResource, allocate, release)-import UnliftIO.Resource qualified as Resource+import UnliftIO.Resource (MonadResource) import Vulkan.Core10 qualified as Vk-import Vulkan.Exception (VulkanException(..)) import Vulkan.Extensions.VK_KHR_surface qualified as Khr import Vulkan.Extensions.VK_KHR_swapchain qualified as Khr+import Vulkan.Utils.FrameGraph.Image (ManagedImage)+import Vulkan.Utils.FrameGraph.Swapchain (forgetSwapchainImages, newSwapchainImages) import Vulkan.Utils.Misc ((.&&.))+import Vulkan.Utils.Swapchain (Swapchain(..))+import Vulkan.Utils.Swapchain qualified as Utils import Vulkan.NamedType ((:::)) import Vulkan.Zero (zero) -import Engine.Types.RefCounted (RefCounted, newRefCounted, releaseRefCounted)-import Engine.Vulkan.Types (MonadVulkan, HasVulkan(..), HasSwapchain(..), pdiProperties)+import Engine.Vulkan.Capabilities qualified as Capabilities+import Engine.Vulkan.Types (HasVulkan(..), HasSwapchain(..), pdiCapabilities)+import Render.Graph (HasSliceRegistry(..)) data SwapchainResources = SwapchainResources- { srInfo :: SwapchainInfo- , srImageViews :: Vector Vk.ImageView- , srImages :: Vector Vk.Image- , srRelease :: RefCounted- }--data SwapchainInfo = SwapchainInfo- { siSwapchain :: Khr.SwapchainKHR- , siSwapchainReleaseKey :: Resource.ReleaseKey- , siPresentMode :: Khr.PresentModeKHR- , siMinImageCount :: Word32- , siSurfaceFormat :: Vk.Format- , siSurfaceColorspace :: Khr.ColorSpaceKHR- , siDepthFormat :: Vk.Format- , siMultisample :: Vk.SampleCountFlagBits- , siAnisotropy :: Float- , siImageExtent :: Vk.Extent2D- , siSurface :: Khr.SurfaceKHR+ { srSwapchain :: Swapchain+ , srTrackedImages :: Vector ManagedImage+ , srMinImageCount :: Word32+ , srDepthFormat :: Vk.Format+ , srMultisample :: Vk.SampleCountFlagBits+ , srAnisotropy :: Float } instance HasSwapchain SwapchainResources where- getSurfaceExtent = siImageExtent . srInfo- getSurfaceFormat = siSurfaceFormat . srInfo- getDepthFormat = siDepthFormat . srInfo- getMultisample = siMultisample . srInfo- getAnisotropy = siAnisotropy . srInfo- getSwapchainViews = srImageViews- getMinImageCount = siMinImageCount . srInfo- getImageCount = fromIntegral . V.length . srImages+ getSurfaceExtent = sExtent . srSwapchain+ getSurfaceFormat = Khr.format . sFormat . srSwapchain+ getDepthFormat = srDepthFormat+ getMultisample = srMultisample+ getAnisotropy = srAnisotropy+ getSwapchainViews = sImageViews . srSwapchain+ getMinImageCount = srMinImageCount+ getImageCount = fromIntegral . V.length . sImages . srSwapchain --- | Allocate everything which depends on the swapchain allocSwapchainResources :: ( MonadResource (RIO env) , HasVulkan env+ , HasSliceRegistry env , HasLogFunc env ) => Maybe Khr.PresentModeKHR@@ -79,209 +66,94 @@ -> RIO env SwapchainResources allocSwapchainResources present msaa oldSwapchain windowSize surface = do logDebug "Allocating swapchain resources"-+ physical <- asks getPhysicalDevice device <- asks getDevice- info@SwapchainInfo{..} <- createSwapchain present msaa oldSwapchain windowSize surface-- -- XXX: Get all the swapchain images, and create views for them- (_, swapchainImages) <- Khr.getSwapchainImagesKHR device siSwapchain- res <- for swapchainImages $- createImageView siSurfaceFormat- let (imageViewKeys, imageViews) = V.unzip res-- -- XXX: This refcount is released in 'recreateSwapchainResources'- releaseDebug <- toIO $ logDebug "Releasing swapchain resources"- releaseResources <- newRefCounted $ do- releaseDebug- traverse_ release imageViewKeys- release siSwapchainReleaseKey-- pure SwapchainResources- { srInfo = info- , srImageViews = imageViews- , srImages = swapchainImages- , srRelease = releaseResources- }+ swapchain <- Utils.allocateSwapchain+ physical+ device+ (swapchainConfig present)+ oldSwapchain+ windowSize+ surface+ resourcesFor msaa swapchain recreateSwapchainResources :: ( MonadResource (RIO env) , HasVulkan env+ , HasSliceRegistry env , HasLogFunc env )- => Maybe Khr.PresentModeKHR- -> Vk.SampleCountFlagBits+ => Vk.SampleCountFlagBits -> Vk.Extent2D -> SwapchainResources -- ^ The reference to these resources will be dropped -> RIO env SwapchainResources-recreateSwapchainResources present msaa windowSize oldResources = do- sr <- allocSwapchainResources- present- msaa- (siSwapchain $ srInfo oldResources)- windowSize- (siSurface $ srInfo oldResources)- releaseRefCounted (srRelease oldResources)- pure sr---- | Create a swapchain from a 'SurfaceKHR'-createSwapchain- :: ( MonadResource m- , MonadVulkan env m- , HasLogFunc env- )- => Maybe Khr.PresentModeKHR- -> Vk.SampleCountFlagBits- -> Khr.SwapchainKHR- -- ^ Old swapchain, can be NULL_HANDLE- -> Vk.Extent2D- -- ^ If the swapchain size determines the surface size, use this size- -> Khr.SurfaceKHR- -> m SwapchainInfo-createSwapchain present msaa oldSwapchain explicitSize surf = do+recreateSwapchainResources msaa windowSize old = do+ logDebug "Allocating swapchain resources" physical <- asks getPhysicalDevice device <- asks getDevice- props <- asks $ pdiProperties . getPhysicalDeviceInfo- surfaceCaps <- Khr.getPhysicalDeviceSurfaceCapabilitiesKHR physical surf-- logDebug $ displayShow surfaceCaps-- -- Check flags- for_ requiredUsageFlags \flag ->- unless (Khr.supportedUsageFlags surfaceCaps .&&. flag) do- logError $ "Surface images do not support " <> displayShow flag- throwString $ "Surface images do not support " <> show flag+ registry <- asks getSliceRegistry+ forgetSwapchainImages registry old.srSwapchain+ swapchain <- Utils.recreateSwapchain physical device windowSize old.srSwapchain+ resourcesFor msaa swapchain - -- Select a present mode- desiredPresentModes <- case present of- Nothing -> do- logDebug $ "Using default present modes: " <> displayShow defaultPresentModes- pure defaultPresentModes- Just selected -> do- logDebug $ "Forcing selected present mode: " <> displayShow selected- pure [selected]- (_, availablePresentModes) <- Khr.getPhysicalDeviceSurfacePresentModesKHR physical surf- presentMode <-- case filter (`V.elem` availablePresentModes) desiredPresentModes of- [] -> do- logError "Unable to find a suitable present mode for swapchain"- throwString "Unable to find a suitable present mode for swapchain"- x : _rest ->- pure x+swapchainConfig :: Maybe Khr.PresentModeKHR -> Utils.SwapchainConfig+swapchainConfig present = Utils.defaultSwapchainConfig+ { Utils.scDesiredPresentModes =+ maybe (Utils.scDesiredPresentModes Utils.defaultSwapchainConfig) pure present+ , Utils.scSurfaceFormatPreferences =+ [Utils.srgbEncoding]+ } - -- Select a surface format- -- getPhysicalDeviceSurfaceFormatsKHR doesn't return an empty list- -- (_, availableFormats) <- Khr.getPhysicalDeviceSurfaceFormatsKHR physical surf- surfaceFormatKhr <- getSurfaceFormatKhr physical surf preferSrgb+resourcesFor+ :: ( HasVulkan env+ , HasSliceRegistry env+ , HasLogFunc env+ )+ => Vk.SampleCountFlagBits+ -> Swapchain+ -> RIO env SwapchainResources+resourcesFor msaa swapchain = do+ physical <- asks getPhysicalDevice+ caps <- asks $ pdiCapabilities . getPhysicalDeviceInfo+ surfaceCaps <- Khr.getPhysicalDeviceSurfaceCapabilitiesKHR physical swapchain.sSurface+ registry <- asks getSliceRegistry+ trackedImages <- newSwapchainImages registry swapchain - depthFormat <- getDepthFormats physical preferStenciledDepth >>= \case+ depthFormat <- getDepthFormats physical preferDepth >>= \case fmt : _rest -> pure fmt _none -> throwString "Unable to find a suitable depth format" - -- Calculate the extent- let- imageExtent =- case Khr.currentExtent (surfaceCaps :: Khr.SurfaceCapabilitiesKHR) of- Vk.Extent2D w h | w == maxBound, h == maxBound ->- explicitSize- extent ->- extent-- let- minImageCount =- let- limit = case surfaceCaps.maxImageCount of- 0 -> maxBound- n -> n- -- Request one additional image to prevent us having to wait for- -- the driver to finish- buffer = 1- desired =- buffer + surfaceCaps.minImageCount- in- min limit desired-- let compositeAlphaMode = Khr.COMPOSITE_ALPHA_OPAQUE_BIT_KHR- unless (compositeAlphaMode .&&. Khr.supportedCompositeAlpha surfaceCaps) $- throwString $ "Surface doesn't support " <> show compositeAlphaMode-- let- Khr.SurfaceFormatKHR{colorSpace=surfaceColorspace, format=surfaceFormat} = surfaceFormatKhr- swapchainCreateInfo = Khr.SwapchainCreateInfoKHR- { surface = surf- , next = ()- , flags = zero- , queueFamilyIndices = mempty -- No need to specify when not using concurrent access- , minImageCount = minImageCount- , imageFormat = surfaceFormat- , imageColorSpace = surfaceColorspace- , imageExtent = imageExtent- , imageArrayLayers = 1- , imageUsage = foldr (.|.) zero requiredUsageFlags- , imageSharingMode = Vk.SHARING_MODE_EXCLUSIVE- , preTransform = Khr.currentTransform (surfaceCaps :: Khr.SurfaceCapabilitiesKHR)- , compositeAlpha = compositeAlphaMode- , presentMode = presentMode- , clipped = True- , oldSwapchain = oldSwapchain- }-- logDebug $ "Creating swapchain from " <> displayShow swapchainCreateInfo- (key, swapchain) <- Khr.withSwapchainKHR device swapchainCreateInfo Nothing allocate+ logDebug $ mconcat+ [ "Swapchain "+ , displayShow swapchain.sExtent+ , " "+ , displayShow swapchain.sFormat+ , " "+ , displayShow swapchain.sPresentMode+ , ", images: "+ , display (V.length swapchain.sImages)+ ] - pure SwapchainInfo- { siSwapchain = swapchain- , siSwapchainReleaseKey = key- , siPresentMode = presentMode- , siMinImageCount = minImageCount- , siSurface = surf- , siSurfaceFormat = surfaceFormat- , siSurfaceColorspace = surfaceColorspace- , siDepthFormat = depthFormat- , siMultisample = msaaSamples msaa props- , siAnisotropy = Vk.maxSamplerAnisotropy (Vk.limits props)- , siImageExtent = imageExtent+ pure SwapchainResources+ { srSwapchain = swapchain+ , srTrackedImages = trackedImages+ , srMinImageCount = requestedImageCount surfaceCaps+ , srDepthFormat = depthFormat+ , srMultisample = msaaSamples msaa (Capabilities.capsProperties caps)+ , srAnisotropy = Capabilities.anisotropyLimit caps } --- -- The vector passed will have at least one element--- selectSurfaceFormat :: Vector Khr.SurfaceFormatKHR -> Khr.SurfaceFormatKHR--- selectSurfaceFormat = V.maximumBy (comparing surfaceFormatScore)--- where--- -- An ordered list of formats to choose for the swapchain images, if none--- -- match then the first available format will be chosen.--- surfaceFormatScore :: Khr.SurfaceFormatKHR -> Int--- surfaceFormatScore = \case--- _ -> 0--getSurfaceFormatKhr- :: MonadIO io- => Vk.PhysicalDevice- -> Khr.SurfaceKHR- -> Khr.SurfaceFormatKHR- -> io Khr.SurfaceFormatKHR-getSurfaceFormatKhr device surface desiredFormat = do- (_res, formats) <- Khr.getPhysicalDeviceSurfaceFormatsKHR device surface- pure case toList formats of- [] ->- desiredFormat- [Khr.SurfaceFormatKHR Vk.FORMAT_UNDEFINED _colorSpace] ->- desiredFormat- candidates | any cond candidates ->- desiredFormat- whatever : _rest ->- whatever+requestedImageCount :: Khr.SurfaceCapabilitiesKHR -> Word32+requestedImageCount surfaceCaps =+ min limit (1 + surfaceCaps.minImageCount) where- cond f =- Khr.format f == Khr.format desiredFormat &&- Khr.colorSpace f == Khr.colorSpace desiredFormat--preferSrgb :: Khr.SurfaceFormatKHR-preferSrgb =- Khr.SurfaceFormatKHR- Vk.FORMAT_B8G8R8A8_SRGB- Khr.COLOR_SPACE_SRGB_NONLINEAR_KHR+ limit =+ case surfaceCaps.maxImageCount of+ 0 -> maxBound+ n -> n getDepthFormats :: MonadIO io@@ -294,13 +166,15 @@ (format, props) <- zip desiredDepthFormats properties guard $ Vk.optimalTilingFeatures props .&&. Vk.FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT+ guard $+ Vk.optimalTilingFeatures props .&&. Vk.FORMAT_FEATURE_SAMPLED_IMAGE_BIT pure format -preferStenciledDepth :: [Vk.Format]-preferStenciledDepth =- [ Vk.FORMAT_D32_SFLOAT_S8_UINT- , Vk.FORMAT_D24_UNORM_S8_UINT- , Vk.FORMAT_D32_SFLOAT+preferDepth :: [Vk.Format]+preferDepth =+ [ Vk.FORMAT_D32_SFLOAT+ , Vk.FORMAT_X8_D24_UNORM_PACK32+ , Vk.FORMAT_D16_UNORM ] msaaSamples@@ -336,59 +210,11 @@ , Vk.SAMPLE_COUNT_1_BIT -- XXX: i.e. "disable", always available ] --- | An ordered list of the present mode to be chosen for the swapchain.-defaultPresentModes :: [Khr.PresentModeKHR]-defaultPresentModes =- [ Khr.PRESENT_MODE_FIFO_RELAXED_KHR- , Khr.PRESENT_MODE_FIFO_KHR -- ^ This will always be present- ]---- | The images in the swapchain must support these flags.-requiredUsageFlags :: [Vk.ImageUsageFlagBits]-requiredUsageFlags =- [ Vk.IMAGE_USAGE_COLOR_ATTACHMENT_BIT- -- , Vk.IMAGE_USAGE_STORAGE_BIT- ]- -- | Catch an ERROR_OUT_OF_DATE_KHR exception and return 'True' if that happened threwSwapchainError :: MonadUnliftIO f => f () -> f Bool-threwSwapchainError = fmap isLeft . tryJust swapchainError- where- swapchainError = \case- VulkanException e@Vk.ERROR_OUT_OF_DATE_KHR ->- Just e-- VulkanException Vk.ERROR_SURFACE_LOST_KHR ->- error "TODO: handle ERROR_SURFACE_LOST_KHR"-- VulkanException _ ->- Nothing---- | Create a pretty vanilla ImageView covering the whole image-createImageView- :: ( MonadResource m- , MonadVulkan env m- )- => Vk.Format- -> Vk.Image- -> m (Resource.ReleaseKey, Vk.ImageView)-createImageView format image = do- device <- asks getDevice- Vk.withImageView device imageViewCI Nothing allocate- where- imageViewCI = zero- { Vk.image = image- , Vk.viewType = Vk.IMAGE_VIEW_TYPE_2D- , Vk.format = format- -- , Vk.components = zero- , Vk.subresourceRange = zero- { Vk.aspectMask = Vk.IMAGE_ASPECT_COLOR_BIT- , Vk.baseMipLevel = 0- , Vk.levelCount = 1- , Vk.baseArrayLayer = 0- , Vk.layerCount = 1- }- }+threwSwapchainError action =+ withRunInIO \run ->+ Utils.threwSwapchainError (run action) setDynamic :: MonadIO io
src/Engine/Vulkan/Types.hs view
@@ -4,11 +4,13 @@ , getPipelineCache , HasSwapchain(..)- , HasRenderPass(..)- , RenderPass(..) , PhysicalDeviceInfo(..)- , Queues(..)+ , Queue(..)+ , lockQueues+ , withQueue+ , withQueues+ , waitDeviceIdle , DsLayouts , DsLayoutBindings@@ -20,14 +22,18 @@ import Data.Kind (Type) import RIO.App (App(..))-import RIO.State (MonadState(..))-import UnliftIO.Resource (MonadResource)+import RIO.List qualified as List+import RIO.State (MonadState(..), evalStateT, gets, modify') import Vulkan.Core10 qualified as Vk import Vulkan.Core12.Promoted_From_VK_EXT_descriptor_indexing qualified as Vk12+import Vulkan.CStruct.Extends (SomeStruct) import Vulkan.NamedType ((:::)) import Vulkan.Utils.QueueAssignment (QueueFamilyIndex(..))+import Vulkan.Utils.Queues (Queues(..)) import VulkanMemoryAllocator qualified as VMA +import Engine.Vulkan.Capabilities (Capabilities)+ type MonadVulkan env m = ( MonadUnliftIO m , MonadReader env m@@ -37,7 +43,7 @@ -- | A class for Monads which can provide some Vulkan handles class HasVulkan a where getInstance :: a -> Vk.Instance- getQueues :: a -> Queues (QueueFamilyIndex, Vk.Queue)+ getQueues :: a -> Queues Queue getPhysicalDevice :: a -> Vk.PhysicalDevice getPhysicalDeviceInfo :: a -> PhysicalDeviceInfo getDevice :: a -> Vk.Device@@ -63,22 +69,49 @@ getPipelineCache :: {- HasVulkan ctx => -} ctx -> Vk.PipelineCache getPipelineCache _ctx = Vk.NULL_HANDLE -{- |- The shape of all the queues we use for our program, parameterized over the- queue type so we can use it with 'Vulkan.Utils.QueueAssignment.assignQueues'.--}-data Queues q = Queues- { qGraphics :: q- , qTransfer :: q- , qCompute :: q+data Queue = Queue+ { family :: QueueFamilyIndex+ , queue :: Vk.Queue+ , lock :: MVar () }- deriving (Show, Functor, Foldable, Traversable) +lockQueues :: MonadIO m => Queues (QueueFamilyIndex, Vk.Queue) -> m (Queues Queue)+lockQueues queues =+ evalStateT (traverse assign queues) []+ where+ assign (family, queue) = do+ known <- gets $ List.lookup (Vk.queueHandle queue)+ lock <- maybe (fresh queue) pure known+ pure Queue{..}++ fresh queue = do+ lock <- newMVar ()+ modify' ((Vk.queueHandle queue, lock) :)+ pure lock++withQueue :: MonadUnliftIO m => Queue -> (Vk.Queue -> m a) -> m a+withQueue Queue{queue, lock} action =+ withMVar lock \() ->+ action queue++withQueues :: MonadUnliftIO m => Queues Queue -> m a -> m a+withQueues queues action =+ foldr withLock action . List.nub $ map (.lock) (toList queues)+ where+ withLock lock inner = withMVar lock \() -> inner++waitDeviceIdle :: MonadVulkan env m => m ()+waitDeviceIdle = do+ context <- ask+ withQueues (getQueues context) $+ Vk.deviceWaitIdleSafe (getDevice context)+ data PhysicalDeviceInfo = PhysicalDeviceInfo { pdiTotalMemory :: Word64 , pdiQueueCreateInfos :: Vector (Vk.DeviceQueueCreateInfo '[]) , pdiName :: Text- , pdiProperties :: Vk.PhysicalDeviceProperties+ , pdiCapabilities :: Capabilities+ , pdiDeviceCreateInfo :: SomeStruct Vk.DeviceCreateInfo , pdiGetQueues :: Vk.Device -> IO (Queues (QueueFamilyIndex, Vk.Queue)) } @@ -91,30 +124,6 @@ getSwapchainViews :: a -> Vector Vk.ImageView getMinImageCount :: a -> Word32 getImageCount :: a -> Word32---- TODO: extract to a module-class HasRenderPass a where- getFramebuffers :: a -> Vector Vk.Framebuffer- getRenderPass :: a -> Vk.RenderPass- getClearValues :: a -> Vector Vk.ClearValue- getRenderArea :: a -> Vk.Rect2D--class RenderPass a where- updateRenderpass- :: ( HasLogFunc env- , HasSwapchain swapchain- , HasVulkan env- , MonadResource (RIO env)- )- => swapchain- -> a- -> RIO env a- updateRenderpass = const pure-- refcountRenderpass- :: MonadResource (RIO env)- => a- -> RIO env () type DsLayoutBindings = [(Vk.DescriptorSetLayoutBinding, Vk12.DescriptorBindingFlags)] type DsLayouts = Vector Vk.DescriptorSetLayout
src/Render/Code.hs view
@@ -7,16 +7,25 @@ , 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)@@ -33,5 +42,34 @@ 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.2"+targetEnv = "vulkan1.3"
+ src/Render/Graph.hs view
@@ -0,0 +1,353 @@+module Render.Graph+ ( Graph+ , Image+ , Tracked+ , Swapchain+ , GraphError(..)++ , importImage+ , pass+ , passIndexed+ , withPrivate+ , changed+ , readback+ , splitSlices+ , joinSlices++ , Setup+ , Reads+ , reading+ , sampled+ , sampledIn+ , storageRead+ , transferSrc+ , colorAttachment+ , depthAttachment+ , transferDst+ , storageWrite+ , sideEffect++ , HasSliceRegistry(..)+ , track+ , trackMips+ , trackImage++ , prepare+ , record+ ) where++import RIO++import Control.Arrow (ArrowChoice, Kleisli(..))+import Data.Semigroup (sconcat)+import Fragr qualified as FG+import RIO.App (App(..))+import RIO.Map qualified as Map+import RIO.NonEmpty qualified as NonEmpty+import RIO.Text qualified as Text+import UnliftIO.Resource (MonadResource)+import UnliftIO.Resource qualified as Resource+import Vulkan.Core10 qualified as Vk+import Vulkan.NamedType ((:::))+import Vulkan.Utils.FrameGraph.Image (ImageDesc(..), ImageState(..), ManagedImage(..), SliceRegistry, Usage(..), describedAs, forgetImage, imageInfo, newManagedImage, newManagedImageSlice)+import Vulkan.Utils.FrameGraph.Recorder (Recorder, flushBarriers, newRecorder)+import Vulkan.Zero (zero)++import Engine.Worker qualified as Worker+import Resource.Image (AllocatedImage(..))++newtype Graph env i o = Graph (i -> RIO (Env env) o)+ deriving (Category, Arrow, ArrowChoice) via Kleisli (RIO (Env env))++data Env env = Env+ { eGraph :: FG.FrameGraph Recorder ()+ , eCallbackEnv :: env+ , eCommandBuffer :: Vk.CommandBuffer+ , eImageIndex :: Word32+ , eImports :: IORef (Map (Vk.Image, Word32, Word32) Imported)+ }++data Imported = Imported+ { importedAs :: Text+ , private :: Maybe (FG.Handle ManagedImage)+ }++data Image (tag :: k) = Image+ { name :: Text+ , handles :: NonEmpty (FG.Handle ManagedImage)+ }++data Tracked (tag :: k) = Tracked+ { name :: Text+ , slices :: NonEmpty ManagedImage+ }++data Swapchain++data GraphError+ = StaleImage Text Text Text+ | DoubleImport Text Text+ | OwnOutput Text Text+ deriving stock (Show)++instance Exception GraphError where+ displayException = Text.unpack . \case+ StaleImage passName image access ->+ "Pass " <> passName <> " uses a superseded version of " <> image <> " as " <> access <> "."+ DoubleImport image previous ->+ "Image " <> image <> " is already in the graph as " <> previous <> "."+ OwnOutput passName image ->+ "Pass " <> passName <> " reads " <> image <> ", which it writes itself."++importImage :: Graph env (Tracked tag) (Image tag)+importImage = Graph \Tracked{name, slices} -> do+ Env{eGraph, eImports} <- ask+ handles <- for slices \managed -> do+ known <- readIORef eImports+ for_ (Map.lookup (sliceKey managed) known) \Imported{importedAs} ->+ throwIO $ DoubleImport name importedAs+ modifyIORef' eImports $+ Map.insert (sliceKey managed) Imported{importedAs = name, private = Nothing}+ FG.importResource eGraph name (ImageDesc managed.info) managed+ pure Image{name, handles}++withPrivate :: Tracked private -> Graph env (i, Image private) (o, Image private) -> Graph env i o+withPrivate Tracked{name, slices} (Graph inner) = Graph \input -> do+ Env{eGraph, eImports} <- ask+ handles <- for slices \managed -> do+ known <- readIORef eImports+ case Map.lookup (sliceKey managed) known of+ Just Imported{private = Just latest} ->+ pure latest+ Just Imported{importedAs} ->+ throwIO $ DoubleImport name importedAs+ Nothing ->+ FG.importScratch eGraph name (ImageDesc managed.info) managed+ (output, Image{handles = renamed}) <- inner (input, Image{name, handles})+ for_ (NonEmpty.zip slices renamed) \(managed, latest) ->+ modifyIORef' eImports $+ Map.insert (sliceKey managed) Imported{importedAs = name, private = Just latest}+ pure output++sliceKey :: ManagedImage -> (Vk.Image, Word32, Word32)+sliceKey managed =+ ( managed.image+ , managed.range.baseMipLevel+ , managed.range.baseArrayLayer+ )++pass+ :: Text+ -> (i -> Setup o)+ -> (Vk.CommandBuffer -> RIO env ())+ -> Graph env i o+pass name setup callback = passIndexed name setup (const callback)++passIndexed+ :: Text+ -> (i -> Setup o)+ -> ("image index" ::: Word32 -> Vk.CommandBuffer -> RIO env ())+ -> Graph env i o+passIndexed name setup callback = Graph \input -> do+ Env{eGraph, eCallbackEnv, eCommandBuffer, eImageIndex} <- ask+ let Setup declared = setup input+ FG.addPass eGraph name (runReaderT declared name) \_outputs ->+ liftIO . runRIO eCallbackEnv $ callback eImageIndex eCommandBuffer++changed :: Worker.HasOutput output => output -> Worker.ObserverIO () -> Graph env i Bool+changed output observer = Graph \_input -> do+ fired <- newIORef False+ Worker.observeIO_ output observer \() _new ->+ writeIORef fired True+ readIORef fired++readback :: Graph env (Image tag) ()+readback = Graph \Image{name, handles} -> do+ Env{eGraph} <- ask+ for_ handles \latest ->+ FG.finalize eGraph latest HostRead `catch` rethrowAs "readback" name "host read"++splitSlices :: Image tag -> NonEmpty (Image tag)+splitSlices Image{name, handles} =+ fmap (\latest -> Image{name, handles = latest :| []}) handles++joinSlices :: NonEmpty (Image tag) -> Image tag+joinSlices images@(Image{name} :| _rest) =+ Image{name, handles = sconcat $ fmap (\Image{handles} -> handles) images}++newtype Setup a = Setup (ReaderT Text (FG.Build Recorder ()) a)+ deriving newtype (Functor, Applicative, Monad)++newtype Reads = Reads (Setup ())++instance Semigroup Reads where+ Reads a <> Reads b = Reads (a *> b)++instance Monoid Reads where+ mempty = Reads (pure ())++reading :: Reads -> Setup ()+reading (Reads declared) = declared++declare+ :: Text+ -> Image tag+ -> (FG.Handle ManagedImage -> FG.Build Recorder () a)+ -> Setup (NonEmpty a)+declare accessName Image{name, handles} action = Setup do+ passName <- ask+ lift $ for handles \latest ->+ action latest `catch` rethrowAs passName name accessName++rethrowAs :: MonadIO m => Text -> Text -> Text -> FG.FragrError -> m a+rethrowAs passName image accessName = \case+ FG.StaleHandle _operation _handle ->+ throwIO $ StaleImage passName image accessName+ FG.ReadsOwnOutput _handle ->+ throwIO $ OwnOutput passName image+ other ->+ throwIO other++readAs :: Text -> Usage -> Image tag -> Reads+readAs accessName usage image = Reads . void $+ declare accessName image (`FG.readWith` usage)++writeAs :: Text -> Usage -> Image tag -> Setup (Image tag)+writeAs accessName usage image = do+ renamed <- declare accessName image (`FG.writeWith` usage)+ pure image{handles = renamed}++sampled :: Image tag -> Reads+sampled = sampledIn Vk.PIPELINE_STAGE_FRAGMENT_SHADER_BIT++sampledIn :: Vk.PipelineStageFlags -> Image tag -> Reads+sampledIn shaderStage = readAs "sampled" (Sampled shaderStage)++storageRead :: Vk.PipelineStageFlags -> Image tag -> Reads+storageRead shaderStage = readAs "storage read" (StorageRead shaderStage)++transferSrc :: Image tag -> Reads+transferSrc = readAs "transfer source" TransferSrc++colorAttachment :: Image tag -> Setup (Image tag)+colorAttachment = writeAs "color attachment" ColorAttachment++depthAttachment :: Image tag -> Setup (Image tag)+depthAttachment = writeAs "depth attachment" DepthAttachment++transferDst :: Image tag -> Setup (Image tag)+transferDst = writeAs "transfer destination" TransferDst++storageWrite :: Vk.PipelineStageFlags -> Image tag -> Setup (Image tag)+storageWrite shaderStage = writeAs "storage write" (StorageWrite shaderStage)++sideEffect :: Setup ()+sideEffect = Setup (lift FG.setSideEffect)++class HasSliceRegistry a where+ getSliceRegistry :: a -> SliceRegistry++instance HasSliceRegistry env => HasSliceRegistry (App env st) where+ getSliceRegistry = getSliceRegistry . appEnv++instance HasSliceRegistry env => HasSliceRegistry (env, a) where+ getSliceRegistry = getSliceRegistry . fst++track+ :: ( MonadResource m+ , MonadReader env m+ , HasSliceRegistry env+ )+ => Text+ -> AllocatedImage+ -> m (Tracked tag)+track name AllocatedImage{aiImage, aiFormat, aiExtent, aiImageRange} = do+ registry <- asks getSliceRegistry+ managed <- describedAs (describe aiFormat aiExtent) <$>+ newManagedImage registry aiImage aiImageRange.aspectMask+ forgetting registry aiImage+ pure Tracked{name, slices = managed :| []}++trackMips+ :: ( MonadResource m+ , MonadReader env m+ , HasSliceRegistry env+ )+ => Text+ -> AllocatedImage+ -> m (Tracked tag)+trackMips name AllocatedImage{aiImage, aiFormat, aiExtent, aiImageRange} = do+ registry <- asks getSliceRegistry+ slices <- for (0 :| [1 .. aiImageRange.levelCount - 1]) \mip ->+ describedAs (describe aiFormat aiExtent <> " mip " <> textDisplay mip) <$>+ newManagedImageSlice registry aiImage aiImageRange.aspectMask mip 1 0 aiImageRange.layerCount+ forgetting registry aiImage+ pure Tracked{name, slices}++trackImage+ :: ( MonadResource m+ , MonadReader env m+ , HasSliceRegistry env+ )+ => Text+ -> Vk.Format+ -> Vk.Extent2D+ -> Vk.ImageAspectFlags+ -> Vk.Image+ -> m (Tracked tag)+trackImage name format extent aspect image = do+ registry <- asks getSliceRegistry+ managed <- describedAs (imageInfo format extent) <$>+ newManagedImage registry image aspect+ forgetting registry image+ pure Tracked{name, slices = managed :| []}++describe :: Vk.Format -> Vk.Extent3D -> Text+describe format Vk.Extent3D{width, height} = imageInfo format Vk.Extent2D{width, height}++forgetting :: MonadResource m => SliceRegistry -> Vk.Image -> m ()+forgetting registry image =+ void . Resource.register $ forgetImage registry image++prepare+ :: MonadIO m+ => env+ -> Vk.CommandBuffer+ -> "image index" ::: Word32+ -> ManagedImage+ -> Graph env (Image Swapchain) (Image Swapchain)+ -> m (IO ())+prepare env cb imageIndex swapchain (Graph stageGraph) = liftIO do+ writeIORef swapchain.stateRef ImageState+ { layout = Vk.IMAGE_LAYOUT_UNDEFINED+ , stage = Vk.PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT+ , access = zero+ }+ (graph, recorder, frame) <- newFrame env cb imageIndex+ let Graph importer = importImage+ Image{name, handles} <- runRIO frame $+ importer Tracked{name = "swapchain", slices = swapchain :| []} >>= stageGraph+ for_ handles \latest ->+ FG.finalize graph latest Present `catch` rethrowAs "present" name "presented image"+ FG.compile graph+ pure $ FG.execute graph recorder ()++record :: MonadIO m => env -> Vk.CommandBuffer -> Graph env () o -> m o+record env cb (Graph build) = liftIO do+ (graph, recorder, frame) <- newFrame env cb 0+ output <- runRIO frame $ build ()+ FG.compile graph+ FG.execute graph recorder ()+ pure output++newFrame+ :: env+ -> Vk.CommandBuffer+ -> Word32+ -> IO (FG.FrameGraph Recorder (), Recorder, Env env)+newFrame eCallbackEnv eCommandBuffer eImageIndex = do+ eGraph <- FG.newFrameGraph+ recorder <- newRecorder eCommandBuffer+ FG.addPreExec eGraph flushBarriers+ eImports <- newIORef mempty+ pure (eGraph, recorder, Env{eGraph, eCallbackEnv, eCommandBuffer, eImageIndex, eImports})
− src/Render/Pass.hs
@@ -1,58 +0,0 @@-{-# LANGUAGE OverloadedLists #-}--module Render.Pass- ( usePass- , setViewportScissor-- , beginInfo- ) where--import RIO--import RIO.Vector.Partial ((!))-import Vulkan.Core10 qualified as Vk-import Vulkan.Zero (zero)--import Engine.Vulkan.Types (HasRenderPass(..))--usePass :: (MonadIO io, HasRenderPass a) => a -> Word32 -> Vk.CommandBuffer -> io r -> io r-usePass render imageIndex cb =- Vk.cmdUseRenderPass- cb- (beginInfo render imageIndex)- Vk.SUBPASS_CONTENTS_INLINE--beginInfo :: HasRenderPass a => a -> Word32 -> Vk.RenderPassBeginInfo '[]-beginInfo rp imageIndex = zero- { Vk.renderPass = getRenderPass rp- , Vk.framebuffer = getFramebuffers rp ! fromIntegral imageIndex- , Vk.renderArea = getRenderArea rp- , Vk.clearValues = getClearValues rp- }--setViewportScissor- :: ( HasRenderPass rp- , MonadIO io- )- => Vk.CommandBuffer- -> Vk.Extent2D- -> rp- -> io ()-setViewportScissor cb Vk.Extent2D{width, height} rp = do- Vk.cmdSetViewport- cb- 0- [ Vk.Viewport- { x = 0- , y = 0- , width = realToFrac width- , height = realToFrac height- , minDepth = 0- , maxDepth = 1- }- ]- Vk.cmdSetScissor- cb- 0- [ getRenderArea rp- ]
− src/Render/Pass/Offscreen.hs
@@ -1,392 +0,0 @@-{-# LANGUAGE OverloadedLists #-}-{-# LANGUAGE OverloadedRecordDot #-}--module Render.Pass.Offscreen- ( Settings(..)- , allocate- , Offscreen(..)- , settingsTexture- , colorTexture- , depthTexture- , settingsCubemap- , colorCube- , depthCube- ) where--import RIO--import Control.Monad.Trans.Resource (ResourceT)-import Control.Monad.Trans.Resource qualified as Resource-import Data.Bits ((.|.))-import Data.Vector qualified as Vector-import Geomancy.UVec2 (UVec2, pattern WithUVec2)-import Vulkan.CStruct.Extends (pattern (:&), pattern (::&))-import Vulkan.Core10 qualified as Vk-import Vulkan.Core11.Promoted_From_VK_KHR_multiview qualified as Khr-import Vulkan.NamedType ((:::))-import Vulkan.Utils.Debug qualified as Debug-import Vulkan.Zero (zero)--import Engine.Types.RefCounted (RefCounted)-import Engine.Types.RefCounted qualified as RefCounted-import Engine.Vulkan.Types (HasVulkan(..), HasRenderPass(..), RenderPass(..), MonadVulkan)-import Resource.Image (AllocatedImage)-import Resource.Image qualified as Image-import Resource.Region qualified as Region-import Resource.Texture (CubeMap, Flat, Texture(..))-import Resource.Vulkan.Named qualified as Named--{- XXX: Consider spec wrt. parameters and intended use!--https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/vkCmdBlitImage.html--For a depth-only pass consider "Render.ShadowMap.RenderPass".--}-data Settings = Settings- { sLabel :: Text- , sExtent :: Vk.Extent2D- , sFormat :: Vk.Format- , sColorLayout :: Maybe Vk.ImageLayout -- ^ Target color format when used for export.- , sDepthFormat :: Vk.Format- , sDepthLayout :: Maybe Vk.ImageLayout -- ^ Target depth format when used for export.- , sLayers :: Word32- , sMultiView :: Bool -- ^ Makes sense only for multiple layers.- , sSamples :: Vk.SampleCountFlagBits -- ^ Multisample prevents mipmapping and cubes.- , sMipMap :: Bool- }- deriving (Eq, Show)--{- | Base settings for rendering to textures.--Single-layer, no mips, 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- , sColorLayout = Just Vk.IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL- , sDepthFormat = depthFmt- , sDepthLayout = Nothing- , sMipMap = False- }--{- | Specialize pass for multiview cubemap rendering--6 layers, multiview, mips disabled.--}-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- , sMipMap = False -- incompatible with cubes- }--data Offscreen = Offscreen- { oRenderPass :: Vk.RenderPass- , oExtent :: Vk.Extent2D- , oColor :: AllocatedImage- , oDepth :: AllocatedImage- , oLayers :: Word32- , oMipLevels :: Word32-- , oFrameBuffer :: Vk.Framebuffer- , oRenderArea :: Vk.Rect2D- , oClear :: Vector Vk.ClearValue- , oRelease :: RefCounted- }--instance HasRenderPass Offscreen where- getRenderPass = oRenderPass- getFramebuffers = Vector.replicate 10 . oFrameBuffer- getClearValues = oClear- getRenderArea = oRenderArea--instance RenderPass Offscreen where- refcountRenderpass = RefCounted.resourceTRefCount . oRelease--colorTexture :: Offscreen -> Texture Flat-colorTexture Offscreen{..} = Texture- { tFormat = oColor.aiFormat- , tMipLevels = oMipLevels- , tLayers = oLayers- , tAllocatedImage = oColor- }--colorCube :: Offscreen -> Texture CubeMap-colorCube Offscreen{..} = Texture- { tFormat = oColor.aiFormat- , tMipLevels = oMipLevels- , tLayers = oLayers -- TODO: get from type param- , tAllocatedImage = oColor- }--depthTexture :: Offscreen -> Texture Flat-depthTexture Offscreen{..} = Texture- { tFormat = oDepth.aiFormat- , tMipLevels = oMipLevels- , tLayers = oLayers- , tAllocatedImage = oDepth- }--depthCube :: Offscreen -> Texture CubeMap-depthCube Offscreen{..} = Texture- { tFormat = oDepth.aiFormat- , tMipLevels = oMipLevels- , tLayers = oLayers -- TODO: get from type param- , tAllocatedImage = oDepth- }--allocate- :: ( Resource.MonadResource m- , MonadVulkan env m- , HasLogFunc env- )- => Settings- -> m Offscreen-allocate settings@Settings{..} = do- (_passKey, renderPass) <- allocateRenderPass settings-- (release, resources) <- RefCounted.wrapped $ Region.run do- Region.logDebug- ("Allocating Offscreen resources for " <> display sLabel)- ("Releasing Offscreen resources for " <> display sLabel)- allocateFramebuffer settings renderPass- let (color, depth, framebuffer) = resources-- pure Offscreen- { oRenderPass = renderPass- , oRenderArea = fullSurface- , oExtent = sExtent- , oMipLevels = 1- , oLayers = sLayers- , oClear = clear- , oColor = color- , oDepth = depth- , oFrameBuffer = framebuffer- , oRelease = release- }- where- fullSurface = Vk.Rect2D- { Vk.offset = zero- , Vk.extent = sExtent- }-- clear = Vector.fromList- [ Vk.Color $ Vk.Float32 0 0 0 1- , Vk.DepthStencil (Vk.ClearDepthStencilValue 0.0 0)- ]---- ** Render pass--allocateRenderPass- :: ( MonadVulkan env m- , Resource.MonadResource m- )- => Settings- -> m (Resource.ReleaseKey, Vk.RenderPass)-allocateRenderPass settings = do- device <- asks getDevice-- res <-- if sMultiView settings then- Vk.withRenderPass device createInfoMulti Nothing Resource.allocate- else- Vk.withRenderPass device createInfo Nothing Resource.allocate- Debug.nameObject device (snd res) $ "Offscreen:" <> encodeUtf8 (sLabel settings)- pure res- where- createInfo =- zero- { Vk.attachments = Vector.fromList [color, depth]- , Vk.subpasses = Vector.fromList [subpass]- , Vk.dependencies = deps- }-- createInfoMulti =- createInfo- ::& Khr.RenderPassMultiviewCreateInfo- { Khr.viewMasks = [2 ^ sLayers settings - 1]- , Khr.viewOffsets = []- , Khr.correlationMasks = [0]- }- :& ()-- color = zero- { Vk.format = sFormat settings- , Vk.samples = sSamples settings- , Vk.initialLayout = Vk.IMAGE_LAYOUT_UNDEFINED- , Vk.finalLayout = fromMaybe Vk.IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL (sColorLayout settings)- , Vk.loadOp = Vk.ATTACHMENT_LOAD_OP_CLEAR- , Vk.storeOp = Vk.ATTACHMENT_STORE_OP_STORE- , Vk.stencilLoadOp = Vk.ATTACHMENT_LOAD_OP_DONT_CARE- , Vk.stencilStoreOp = Vk.ATTACHMENT_STORE_OP_DONT_CARE- }-- depth = zero- { Vk.format = sDepthFormat settings- , Vk.samples = sSamples settings- , Vk.initialLayout = Vk.IMAGE_LAYOUT_UNDEFINED- , Vk.finalLayout = fromMaybe Vk.IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL (sDepthLayout settings)- , Vk.loadOp = Vk.ATTACHMENT_LOAD_OP_CLEAR- , Vk.storeOp = Vk.ATTACHMENT_STORE_OP_DONT_CARE- , Vk.stencilLoadOp = Vk.ATTACHMENT_LOAD_OP_DONT_CARE- , Vk.stencilStoreOp = Vk.ATTACHMENT_STORE_OP_DONT_CARE- }-- subpass = zero- { Vk.pipelineBindPoint = Vk.PIPELINE_BIND_POINT_GRAPHICS- , Vk.colorAttachments = Vector.singleton zero- { Vk.attachment = 0- , Vk.layout = Vk.IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL- }- , Vk.depthStencilAttachment = Just zero- { Vk.attachment = 1- , Vk.layout = Vk.IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL- }- }-- {- BUG: Validation Error: [ SYNC-HAZARD-READ_AFTER_WRITE ]-- vkCmdDraw: Hazard READ_AFTER_WRITE for VkImageView 0x2c0a7b0[],- in VkCommandBuffer 0x3297680[],- and VkPipeline 0x3203390[Global.Render.EnvCube.Pipeline],- VkDescriptorSet 0x3248050[],- type: VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE,- imageLayout: VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,- binding #3, index 5.- Access info (- usage: SYNC_FRAGMENT_SHADER_SHADER_STORAGE_READ,- prior_usage: SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,- write_barriers: 0,- command: vkCmdBeginRenderPass,- seq_no: 26,- reset_no: 1- ).- -}- deps =- [ zero- { Vk.dependencyFlags = Vk.DEPENDENCY_BY_REGION_BIT- , Vk.srcSubpass = Vk.SUBPASS_EXTERNAL- , Vk.dstSubpass = 0- , Vk.srcStageMask = Vk.PIPELINE_STAGE_FRAGMENT_SHADER_BIT- , Vk.dstStageMask = Vk.PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT .|. Vk.PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT .|. Vk.PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT- , Vk.srcAccessMask = Vk.ACCESS_SHADER_READ_BIT .|. Vk.ACCESS_SHADER_WRITE_BIT- , Vk.dstAccessMask = Vk.ACCESS_COLOR_ATTACHMENT_WRITE_BIT .|. Vk.ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT- }- , zero- { Vk.dependencyFlags = Vk.DEPENDENCY_BY_REGION_BIT- , Vk.srcSubpass = 0- , Vk.dstSubpass = Vk.SUBPASS_EXTERNAL- , Vk.srcStageMask = Vk.PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT .|. Vk.PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT .|. Vk.PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT- , Vk.dstStageMask = Vk.PIPELINE_STAGE_FRAGMENT_SHADER_BIT- , Vk.srcAccessMask = Vk.ACCESS_COLOR_ATTACHMENT_WRITE_BIT .|. Vk.ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT- , Vk.dstAccessMask = Vk.ACCESS_SHADER_READ_BIT- }- ]---- ** Framebuffer--type FramebufferOffscreen =- ( Image.AllocatedImage- , Image.AllocatedImage- , Vk.Framebuffer- )--allocateFramebuffer- :: ( Resource.MonadResource m- , MonadVulkan env m- , HasLogFunc env- )- => Settings- -> Vk.RenderPass- -> ResourceT m FramebufferOffscreen-allocateFramebuffer Settings{..} renderPass = do- Region.logDebug- ("Allocating Offscreen resources for " <> display sLabel)- ("Releasing Offscreen resources for " <> display sLabel)-- color <- Image.allocate- (Just $ sLabel <> ".color")- Vk.IMAGE_ASPECT_COLOR_BIT- (Image.inflateExtent sExtent 1)- (if sMipMap then mipLevels else 1)- sLayers- sSamples- sFormat- ( Vk.IMAGE_USAGE_COLOR_ATTACHMENT_BIT .|.- Vk.IMAGE_USAGE_SAMPLED_BIT .|.- Vk.IMAGE_USAGE_TRANSFER_SRC_BIT- )-- depth <- Image.allocate- (Just $ sLabel <> ".depth")- Vk.IMAGE_ASPECT_DEPTH_BIT- (Image.inflateExtent sExtent 1)- (if sMipMap then mipLevels else 1)- sLayers- sSamples- sDepthFormat- ( Vk.IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT .|.- Vk.IMAGE_USAGE_SAMPLED_BIT- )-- let- attachments = Vector.fromList- [ Image.aiImageView color- , Image.aiImageView depth- ]-- {- XXX:- If the render pass uses multiview, then layers must be one and each attachment- requires a number of layers that is greater than the maximum bit index set in- the view mask in the subpasses in which it is used.- -}- fbNumLayers =- if sMultiView then- 1- else- sLayers-- fbCI = zero- { Vk.renderPass = renderPass- , Vk.width = width- , Vk.height = height- , Vk.attachments = attachments- , Vk.layers = fbNumLayers- }-- device <- asks getDevice- framebuffer <- Vk.createFramebuffer device fbCI Nothing- void $! Resource.register $ Vk.destroyFramebuffer device framebuffer Nothing- Named.object framebuffer $ sLabel <> ".FB"-- pure (color, depth, framebuffer)- where- Vk.Extent2D{width, height} = sExtent- mipLevels = extentMips sExtent--extentMips :: Num t => Vk.Extent2D -> t-extentMips Vk.Extent2D{width, height} = go 1 (min width height)- where- go levels = \case- 0 ->- levels- 1 ->- levels- side ->- go (levels + 1) (side `div` 2)
+ src/Render/Target.hs view
@@ -0,0 +1,172 @@+{-# LANGUAGE OverloadedLists #-}++module Render.Target+ ( HasRendering(..)+ , RenderingFormats(..)+ , pipelineRendering+ , RenderTarget(..)++ , render+ , setViewportScissor++ , colorAttachment+ , resolvedColor+ , depthAttachment+ , viewMaskFor+ ) where++import RIO++import Data.Bits (shiftL)+import UnliftIO.Resource (MonadResource)+import Vulkan.Core10 qualified as Vk+import Vulkan.Core12 qualified as Vk12+import Vulkan.Core13 qualified as Vk13+import Vulkan.CStruct.Extends (SomeStruct(..))+import Vulkan.NamedType ((:::))++import Engine.Vulkan.Types (HasSwapchain, HasVulkan)+import Render.Graph (Graph, HasSliceRegistry, Setup)+import Render.Graph qualified as Graph++class HasRendering a where+ getRenderingFormats :: a -> RenderingFormats+ getRenderingInfo :: a -> "image index" ::: Word32 -> Vk13.RenderingInfo '[]+ getRenderArea :: a -> Vk.Rect2D++data RenderingFormats = RenderingFormats+ { rfColor :: Vector Vk.Format+ , rfDepth :: Vk.Format+ , rfStencil :: Vk.Format+ , rfSamples :: Vk.SampleCountFlagBits+ , rfViewMask :: Word32+ }+ deriving (Eq, Show)++pipelineRendering :: RenderingFormats -> Vk13.PipelineRenderingCreateInfo+pipelineRendering RenderingFormats{..} = Vk13.PipelineRenderingCreateInfo+ { viewMask = rfViewMask+ , colorAttachmentFormats = rfColor+ , depthAttachmentFormat = rfDepth+ , stencilAttachmentFormat = rfStencil+ }++class RenderTarget a where+ updateTarget+ :: ( HasLogFunc env+ , HasSliceRegistry env+ , HasSwapchain swapchain+ , HasVulkan env+ , MonadResource (RIO env)+ )+ => swapchain+ -> a+ -> RIO env a+ updateTarget = const pure++ refcountTarget+ :: MonadResource (RIO env)+ => a+ -> RIO env ()++render+ :: HasRendering target+ => Text+ -> target+ -> (i -> Setup o)+ -> (Vk.CommandBuffer -> RIO env ())+ -> Graph env i o+render name target setup draw =+ Graph.passIndexed name setup \imageIndex cb ->+ Vk13.cmdUseRendering cb (getRenderingInfo target imageIndex) do+ setViewportScissor cb (getRenderArea target).extent target+ draw cb++setViewportScissor+ :: ( HasRendering target+ , MonadIO io+ )+ => Vk.CommandBuffer+ -> Vk.Extent2D+ -> target+ -> io ()+setViewportScissor cb Vk.Extent2D{width, height} target = do+ Vk.cmdSetViewport+ cb+ 0+ [ Vk.Viewport+ { x = 0+ , y = 0+ , width = realToFrac width+ , height = realToFrac height+ , minDepth = 0+ , maxDepth = 1+ }+ ]+ Vk.cmdSetScissor+ cb+ 0+ [ getRenderArea target+ ]++colorAttachment+ :: Vk.ImageView+ -> Vk.AttachmentLoadOp+ -> Vk.AttachmentStoreOp+ -> Vk.ClearValue+ -> SomeStruct Vk13.RenderingAttachmentInfo+colorAttachment attachmentView loadOp storeOp clear =+ SomeStruct Vk13.RenderingAttachmentInfo+ { next = ()+ , imageView = attachmentView+ , imageLayout = Vk.IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL+ , resolveMode = Vk12.RESOLVE_MODE_NONE+ , resolveImageView = Vk.NULL_HANDLE+ , resolveImageLayout = Vk.IMAGE_LAYOUT_UNDEFINED+ , loadOp = loadOp+ , storeOp = storeOp+ , clearValue = clear+ }++resolvedColor+ :: "multisampled" ::: Vk.ImageView+ -> "resolved" ::: Vk.ImageView+ -> Vk.ClearValue+ -> SomeStruct Vk13.RenderingAttachmentInfo+resolvedColor multisampled resolved clear =+ SomeStruct Vk13.RenderingAttachmentInfo+ { next = ()+ , imageView = multisampled+ , imageLayout = Vk.IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL+ , resolveMode = Vk12.RESOLVE_MODE_AVERAGE_BIT+ , resolveImageView = resolved+ , resolveImageLayout = Vk.IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL+ , loadOp = Vk.ATTACHMENT_LOAD_OP_CLEAR+ , storeOp = Vk.ATTACHMENT_STORE_OP_DONT_CARE+ , clearValue = clear+ }++depthAttachment+ :: Vk.ImageView+ -> Vk.AttachmentStoreOp+ -> "clear depth" ::: Float+ -> SomeStruct Vk13.RenderingAttachmentInfo+depthAttachment attachmentView storeOp clearDepth =+ SomeStruct Vk13.RenderingAttachmentInfo+ { next = ()+ , imageView = attachmentView+ , imageLayout = Vk.IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL+ , resolveMode = Vk12.RESOLVE_MODE_NONE+ , resolveImageView = Vk.NULL_HANDLE+ , resolveImageLayout = Vk.IMAGE_LAYOUT_UNDEFINED+ , loadOp = Vk.ATTACHMENT_LOAD_OP_CLEAR+ , storeOp = storeOp+ , clearValue = Vk.DepthStencil (Vk.ClearDepthStencilValue clearDepth 0)+ }++viewMaskFor :: "views" ::: Word32 -> Word32+viewMaskFor views+ | views == 0 = 0+ | views > 32 = error $ "Too many views for a view mask: " <> show views+ | views == 32 = maxBound+ | otherwise = (1 `shiftL` fromIntegral views) - 1
+ src/Render/Target/Offscreen.hs view
@@ -0,0 +1,263 @@+{-# 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)
src/Resource/Buffer.hs view
@@ -10,10 +10,11 @@ import UnliftIO.Resource qualified as Resource import Vulkan.Core10 qualified as Vk import Vulkan.NamedType ((:::))+import Vulkan.Utils.Queues (Queues(qTransfer)) import Vulkan.Zero (zero) import VulkanMemoryAllocator qualified as VMA -import Engine.Vulkan.Types (HasVulkan(getAllocator), Queues(qTransfer), MonadVulkan)+import Engine.Vulkan.Types (HasVulkan(getAllocator), MonadVulkan) import Engine.Worker qualified as Worker import Resource.CommandBuffer (oneshot_) import Resource.Vulkan.Named qualified as Named
src/Resource/CommandBuffer.hs view
@@ -15,9 +15,10 @@ import Vulkan.Core10.CommandBuffer qualified as CommandBuffer import Vulkan.CStruct.Extends (SomeStruct(..)) import Vulkan.Utils.QueueAssignment (QueueFamilyIndex(..))+import Vulkan.Utils.Queues (Queues(..)) import Vulkan.Zero (zero) -import Engine.Vulkan.Types (HasVulkan(..), MonadVulkan, Queues(..))+import Engine.Vulkan.Types (HasVulkan(..), MonadVulkan, Queue(..), withQueue) allocatePools :: (HasVulkan context, Resource.MonadResource m)@@ -25,10 +26,12 @@ -> m (Resource.ReleaseKey, Queues Vk.CommandPool) allocatePools context = do -- context <- ask- bootstrapQueues <- for (getQueues context) \(QueueFamilyIndex ix, _queue) -> do+ bootstrapQueues <- for (getQueues context) \Queue{family = QueueFamilyIndex ix} -> do let+ commandPoolCI :: Vk.CommandPoolCreateInfo '[] commandPoolCI = Vk.CommandPoolCreateInfo- { flags = zero+ { next = ()+ , flags = zero , queueFamilyIndex = ix } Vk.withCommandPool (getDevice context) commandPoolCI Nothing Resource.allocate@@ -65,8 +68,9 @@ Vk.useCommandBuffer buf oneTime $ action buf Vk.withFence device zero Nothing bracket \fence -> do- Vk.queueSubmit queue (wrap buf) fence- Vk.waitForFences device (pure fence) True maxBound >>= \case+ withQueue queue \q ->+ Vk.queueSubmit q (wrap buf) fence+ Vk.waitForFencesSafe device (pure fence) True maxBound >>= \case Vk.SUCCESS -> -- traceM "oneshot_: queue finished" pure ()@@ -76,7 +80,7 @@ error "assert: exactly the requested buffer was given" where device = getDevice context- queue = snd . pickQueue $ getQueues context+ queue = pickQueue $ getQueues context commandBufferAllocateInfo :: Vk.CommandBufferAllocateInfo commandBufferAllocateInfo = zero
src/Resource/Compressed/Zstd.hs view
@@ -2,12 +2,41 @@ import RIO +import Data.ByteString.Internal qualified as ByteString.Internal+import Data.ByteString.Unsafe qualified as ByteString.Unsafe import Data.Typeable (typeOf)+import Foreign (Ptr)+import Foreign qualified+import Foreign.C.Types (CSize(..)) import RIO.ByteString qualified as ByteString import RIO.FilePath (takeExtension)+import System.IO.Unsafe (unsafePerformIO) +import Codec.Compression.Zstd (Decompress) import Codec.Compression.Zstd qualified as Zstd+import Codec.Compression.Zstd.FFI qualified as ZstdFFI +foreign import ccall safe "ZSTD_decompress"+ decompressInto :: Ptr dst -> CSize -> Ptr src -> CSize -> IO CSize++decompress :: ByteString -> Decompress+decompress bytes =+ unsafePerformIO $+ ByteString.Unsafe.unsafeUseAsCStringLen bytes \(src, srcSize) -> do+ expected <- ZstdFFI.getDecompressedSize src (fromIntegral srcSize)+ if expected == 0 then+ pure Zstd.Skip+ else if expected > fromIntegral (maxBound :: Int) then+ pure $ Zstd.Error "invalid compressed payload size"+ else do+ dst <- ByteString.Internal.mallocByteString (fromIntegral expected)+ Foreign.withForeignPtr dst \dstPtr ->+ ZstdFFI.checkError (decompressInto dstPtr (fromIntegral expected) src (fromIntegral srcSize)) <&> \case+ Left err ->+ Zstd.Error err+ Right size ->+ Zstd.Decompress $ ByteString.Internal.BS dst (fromIntegral size)+ -- * Compressed container newtype Compressed a = Compressed { getCompressed :: a }@@ -17,7 +46,7 @@ decompressBytes :: Compressed ByteString -> Either CompressedError ByteString decompressBytes (Compressed bytes) =- case Zstd.decompress bytes of+ case decompress bytes of Zstd.Decompress buf -> Right buf Zstd.Skip ->
src/Resource/Image.hs view
@@ -44,10 +44,11 @@ import Vulkan.Core10 qualified as Vk import Vulkan.CStruct.Extends (SomeStruct(..)) import Vulkan.NamedType ((:::))+import Vulkan.Utils.Queues (Queues(..)) import Vulkan.Zero (zero) import VulkanMemoryAllocator qualified as VMA -import Engine.Vulkan.Types (HasVulkan(..), MonadVulkan, Queues(..))+import Engine.Vulkan.Types (HasVulkan(..), MonadVulkan) import Resource.Buffer qualified as Buffer import Resource.CommandBuffer (oneshot_) import Resource.Vulkan.Named qualified as Named
src/Resource/Image/Downsample.hs view
@@ -2,254 +2,147 @@ {-# LANGUAGE OverloadedRecordDot #-} module Resource.Image.Downsample- ( mipPyramid- -- * Internals- ,+ ( Pyramid(..)+ , allocate+ , tracked+ , texture+ , generate ) where import RIO +import Control.Arrow (arr)+import Control.Monad.Trans.Resource qualified as Resource import Data.Bits (shiftR)-import Vulkan.CStruct.Extends (SomeStruct(..))-import Vulkan.Core10 qualified as ImageBlit (ImageBlit(..))-import Vulkan.Core10 qualified as ImageSubresourceRange (ImageSubresourceRange(..))+import RIO.Vector qualified as Vector+import RIO.Vector.Partial ((!), (//))+import RIO.Vector.Partial qualified as Partial import Vulkan.Core10 qualified as Vk 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 Resource.Image (AllocatedImage, DstImage(..))+import Render.Graph (Graph, HasSliceRegistry, Image, Tracked)+import Render.Graph qualified as Graph+import Render.Target (RenderTarget(..))+import Resource.Image (AllocatedImage(..), DstImage(..)) import Resource.Image qualified as Image+import Resource.Region qualified as Region+import Resource.Texture (Texture(..)) --- https://docs.vulkan.org/samples/latest/samples/api/texture_mipmap_generation/README.html-mipPyramid- :: MonadVulkan env m- => Vk.CommandBuffer -- XXX: tag to require qGraphics pool- -> AllocatedImage- -> Vk.ImageLayout- -> DstImage- -> m AllocatedImage-mipPyramid cmd src srcLayout dst = do- -- dst is undefined everywhere, src is srcLayout- copyImageBaseToDst cmd src srcLayout dst- -- src copied and reverted, dst[0] is dst-optimal, the rest are undefined- transferTransitions cmd dst Vk.IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL Vk.IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL 0- -- dst[0] is src-optimal, dst[1+] remain undefined- for_ @[] [1 .. dst.aiImageRange.levelCount - 1] \toMip -> do- -- dst[toMip-1] is src-optimal, dst[toMip] is undefined- transferTransitions cmd dst Vk.IMAGE_LAYOUT_UNDEFINED Vk.IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL toMip- -- dst[toMip] is dst-optimal- blitMipDown cmd dst (toMip - 1) toMip- transferTransitions cmd dst Vk.IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL Vk.IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL toMip- -- dst[toMip] is src-optimal, will become dst[toMip - 1]- -- dst[*] are all src-optimal- finalizeDst cmd dst srcLayout- -- dst[*] are all srcLayout+data Pyramid (tag :: k) = Pyramid+ { pyramidLabel :: Text+ , pyramidSource :: AllocatedImage+ , pyramidImage :: AllocatedImage+ , pyramidMips :: Tracked tag+ , pyramidRelease :: RefCounted+ } -{- | Transition src image to src-optimal, copy the data, and transition it back.+instance RenderTarget (Pyramid tag) where+ refcountTarget = RefCounted.resourceTRefCount . pyramidRelease -The dst image asssumed to be in the dst-optimal layout and not transitioned.--}-copyImageBaseToDst- :: MonadIO m- => Vk.CommandBuffer- -> "src image" ::: AllocatedImage- -> "src layout" ::: Vk.ImageLayout- -> "dst image" ::: DstImage- -> m ()-copyImageBaseToDst cmd src srcLayout (DstImage dst) = liftIO do- Vk.cmdPipelineBarrier- cmd- Vk.PIPELINE_STAGE_TOP_OF_PIPE_BIT- Vk.PIPELINE_STAGE_TRANSFER_BIT- zero mempty mempty- [prepareDst, prepareSrc]+allocate+ :: ( Resource.MonadResource m+ , MonadVulkan env m+ , HasLogFunc env+ , HasSliceRegistry env+ )+ => Text+ -> "max mips" ::: Word32+ -> "source" ::: AllocatedImage+ -> m (Pyramid tag)+allocate pyramidLabel maxMips pyramidSource = do+ (pyramidRelease, (pyramidImage, pyramidMips)) <- RefCounted.wrapped $ Region.run do+ Region.logDebug+ ("Allocating mip pyramid " <> display pyramidLabel)+ ("Releasing mip pyramid " <> display pyramidLabel)+ DstImage image <- Image.allocateDstMipFor (Just pyramidLabel) maxMips pyramidSource+ mips <- Graph.trackMips pyramidLabel image+ pure (image, mips)+ pure Pyramid{..} - {-- VUID-vkCmdCopyImage-srcImageLayout-01917- srcImageLayout must be VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, or VK_IMAGE_LAYOUT_GENERAL- -}- Vk.cmdCopyImage- cmd- src.aiImage- Vk.IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL- dst.aiImage- Vk.IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL- [copyBase]+tracked :: Pyramid tag -> Tracked tag+tracked = pyramidMips - Vk.cmdPipelineBarrier- cmd- Vk.PIPELINE_STAGE_TRANSFER_BIT- Vk.PIPELINE_STAGE_FRAGMENT_SHADER_BIT -- hm...- zero mempty mempty- [revertSrc]- where- prepareDst = SomeStruct zero- { Vk.srcAccessMask = zero- , Vk.dstAccessMask = Vk.ACCESS_TRANSFER_WRITE_BIT- , Vk.oldLayout = Vk.IMAGE_LAYOUT_UNDEFINED- , Vk.newLayout = Vk.IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL- , Vk.srcQueueFamilyIndex = Vk.QUEUE_FAMILY_IGNORED- , Vk.dstQueueFamilyIndex = Vk.QUEUE_FAMILY_IGNORED- , Vk.image = dst.aiImage- , Vk.subresourceRange = dst.aiImageRange- }+texture :: Pyramid tag -> Texture layers+texture Pyramid{pyramidImage} = Texture+ { tFormat = pyramidImage.aiFormat+ , tMipLevels = pyramidImage.aiImageRange.levelCount+ , tLayers = pyramidImage.aiImageRange.layerCount+ , tAllocatedImage = pyramidImage+ } - onlyBaseLevel = src.aiImageRange- { ImageSubresourceRange.levelCount = 1- }+generate :: Pyramid tag -> Graph env (Image source, Image tag) (Image tag)+generate Pyramid{pyramidLabel, pyramidSource, pyramidImage} =+ arr (second $ Vector.fromList . toList . Graph.splitSlices) >>>+ copy >>>+ foldr (\mip next -> blit mip >>> next) (arr id) ([1 .. levels - 1] :: [Word32]) >>>+ arr (Graph.joinSlices . fromVector)+ where+ levels = pyramidImage.aiImageRange.levelCount+ layers = pyramidImage.aiImageRange.layerCount+ aspect = pyramidImage.aiImageRange.aspectMask - prepareSrc = SomeStruct zero- { Vk.srcAccessMask = Vk.ACCESS_SHADER_WRITE_BIT- , Vk.dstAccessMask = Vk.ACCESS_TRANSFER_WRITE_BIT- , Vk.oldLayout = srcLayout- , Vk.newLayout = Vk.IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL- , Vk.srcQueueFamilyIndex = Vk.QUEUE_FAMILY_IGNORED- , Vk.dstQueueFamilyIndex = Vk.QUEUE_FAMILY_IGNORED- , Vk.image = src.aiImage- , Vk.subresourceRange = onlyBaseLevel- }+ fromVector :: Vector (Image t) -> NonEmpty (Image t)+ fromVector mips = Partial.head mips :| toList (Partial.tail mips) - copyBase = Vk.ImageCopy- { srcSubresource = baseISL- , srcOffset = zero- , dstSubresource = baseISL- , dstOffset = zero- , extent = src.aiExtent- }- where- baseISL = Vk.ImageSubresourceLayers- { aspectMask = Vk.IMAGE_ASPECT_COLOR_BIT- , mipLevel = 0- , baseArrayLayer = 0- , layerCount = Vk.REMAINING_ARRAY_LAYERS- }+ copy =+ Graph.pass (pyramidLabel <> ".copy")+ ( \(source, mips) -> do+ Graph.reading (Graph.transferSrc source)+ base <- Graph.transferDst (mips ! 0)+ pure $ mips // [(0, base)]+ )+ \cb ->+ Vk.cmdCopyImage+ cb+ pyramidSource.aiImage+ Vk.IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL+ pyramidImage.aiImage+ Vk.IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL+ [ Vk.ImageCopy+ { srcSubresource = mipLayers 0+ , srcOffset = zero+ , dstSubresource = mipLayers 0+ , dstOffset = zero+ , extent = pyramidSource.aiExtent+ }+ ] - revertSrc = SomeStruct zero- { Vk.srcAccessMask = Vk.ACCESS_TRANSFER_WRITE_BIT- , Vk.dstAccessMask = Vk.ACCESS_SHADER_READ_BIT- , Vk.oldLayout = Vk.IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL- , Vk.newLayout = srcLayout- , Vk.srcQueueFamilyIndex = Vk.QUEUE_FAMILY_IGNORED- , Vk.dstQueueFamilyIndex = Vk.QUEUE_FAMILY_IGNORED- , Vk.image = src.aiImage- , Vk.subresourceRange = onlyBaseLevel- }+ blit mip =+ Graph.pass (pyramidLabel <> ".mip" <> textDisplay mip)+ ( \mips -> do+ Graph.reading (Graph.transferSrc $ mips ! fromIntegral (mip - 1))+ next <- Graph.transferDst (mips ! fromIntegral mip)+ pure $ mips // [(fromIntegral mip, next)]+ )+ \cb ->+ Vk.cmdBlitImage+ cb+ pyramidImage.aiImage+ Vk.IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL+ pyramidImage.aiImage+ Vk.IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL+ [ Vk.ImageBlit+ { srcSubresource = mipLayers (mip - 1)+ , srcOffsets = (zero, mipCorner (mip - 1))+ , dstSubresource = mipLayers mip+ , dstOffsets = (zero, mipCorner mip)+ }+ ]+ Vk.FILTER_LINEAR -transferTransitions- :: MonadIO m- => Vk.CommandBuffer- -> DstImage- -> Vk.ImageLayout- -> Vk.ImageLayout- -> Word32- -> m ()-transferTransitions cmd (DstImage image) old new mip =- Vk.cmdPipelineBarrier cmd srcStage Vk.PIPELINE_STAGE_TRANSFER_BIT zero mempty mempty [barrier]- where- barrier = SomeStruct zero- { Vk.srcAccessMask = srcAccess- , Vk.dstAccessMask = dstAccess- , Vk.oldLayout = old- , Vk.newLayout = new- , Vk.srcQueueFamilyIndex = Vk.QUEUE_FAMILY_IGNORED- , Vk.dstQueueFamilyIndex = Vk.QUEUE_FAMILY_IGNORED- , Vk.image = image.aiImage- , Vk.subresourceRange = subr- }- srcAccess = case old of- Vk.IMAGE_LAYOUT_UNDEFINED -> zero- Vk.IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL -> Vk.ACCESS_TRANSFER_WRITE_BIT- Vk.IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL -> Vk.ACCESS_TRANSFER_READ_BIT- _ -> error $ "unexpected old layout: " <> show old- dstAccess = case new of- Vk.IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL -> Vk.ACCESS_TRANSFER_READ_BIT- Vk.IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL -> Vk.ACCESS_TRANSFER_WRITE_BIT- _ -> error $ "unexpected new layout: " <> show new- srcStage = case old of- Vk.IMAGE_LAYOUT_UNDEFINED -> Vk.PIPELINE_STAGE_TOP_OF_PIPE_BIT- _ -> Vk.PIPELINE_STAGE_TRANSFER_BIT- subr = Vk.ImageSubresourceRange- { aspectMask = image.aiImageRange.aspectMask- , baseMipLevel = mip- , levelCount = 1+ mipLayers mip = Vk.ImageSubresourceLayers+ { aspectMask = aspect+ , mipLevel = mip , baseArrayLayer = 0- , layerCount = Vk.REMAINING_ARRAY_LAYERS+ , layerCount = layers } -blitMipDown- :: MonadIO m- => Vk.CommandBuffer -- XXX: tag to require qGraphics pool- -> DstImage- -> Word32- -> Word32- -> m ()-blitMipDown cmd (DstImage image) fromMip toMip =- Vk.cmdBlitImage- cmd- image.aiImage- Vk.IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL- image.aiImage- Vk.IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL- [region]- Vk.FILTER_LINEAR- where- region = zero- { ImageBlit.srcSubresource = prevLayers- , ImageBlit.srcOffsets =- ( zero- , Vk.Offset3D- (max 1 $ fromIntegral image.aiExtent.width `shiftR` fromIntegral fromMip)- (max 1 $ fromIntegral image.aiExtent.height `shiftR` fromIntegral fromMip)- 1- )- , ImageBlit.dstSubresource = currLayers- , ImageBlit.dstOffsets =- ( zero- , Vk.Offset3D- (max 1 $ fromIntegral image.aiExtent.width `shiftR` fromIntegral toMip)- (max 1 $ fromIntegral image.aiExtent.height `shiftR` fromIntegral toMip)- 1- )- }- where- prevLayers = Vk.ImageSubresourceLayers- { aspectMask = image.aiImageRange.aspectMask- , mipLevel = fromMip- , baseArrayLayer = 0- , layerCount = Vk.REMAINING_ARRAY_LAYERS- }- currLayers = Vk.ImageSubresourceLayers- { aspectMask = image.aiImageRange.aspectMask- , mipLevel = toMip- , baseArrayLayer = 0- , layerCount = Vk.REMAINING_ARRAY_LAYERS- }--finalizeDst- :: MonadIO m- => Vk.CommandBuffer- -> DstImage- -> Vk.ImageLayout- -> m AllocatedImage-finalizeDst cmd (DstImage image) toLayout = do- Vk.cmdPipelineBarrier- cmd- Vk.PIPELINE_STAGE_TRANSFER_BIT- Vk.PIPELINE_STAGE_FRAGMENT_SHADER_BIT- zero- mempty- mempty- [barrier]- pure image- where- barrier = SomeStruct zero- { Vk.srcAccessMask = Vk.ACCESS_TRANSFER_READ_BIT- , Vk.dstAccessMask = Vk.ACCESS_SHADER_READ_BIT- , Vk.oldLayout = Vk.IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL- , Vk.newLayout = toLayout- , Vk.srcQueueFamilyIndex = Vk.QUEUE_FAMILY_IGNORED- , Vk.dstQueueFamilyIndex = Vk.QUEUE_FAMILY_IGNORED- , Vk.image = image.aiImage- , Vk.subresourceRange = image.aiImageRange- }+ mipCorner mip = Vk.Offset3D+ (max 1 $ fromIntegral pyramidImage.aiExtent.width `shiftR` fromIntegral mip)+ (max 1 $ fromIntegral pyramidImage.aiExtent.height `shiftR` fromIntegral mip)+ 1
src/Resource/Mesh/Codec.hs view
@@ -23,9 +23,11 @@ import UnliftIO.Resource (MonadResource) import UnliftIO.Resource qualified as Resource import Vulkan.Core10 qualified as Vk+import Vulkan.Utils.Queues (Queues) -import Engine.Vulkan.Types (MonadVulkan, Queues)+import Engine.Vulkan.Types (MonadVulkan) import Resource.Buffer qualified as Buffer+import Resource.Compressed.Zstd qualified as Compressed import Resource.Model qualified as Model import Resource.Region qualified as Region @@ -309,7 +311,7 @@ -> ByteString -> m (Storable.Vector item) decodeItems label digest expectedSize zBytes =- case Zstd.decompress zBytes of+ case Compressed.decompress zBytes of Zstd.Error err -> fail err Zstd.Skip -> do@@ -352,7 +354,7 @@ -> ByteString -> m a decodeCBOR label digest expectedSize zBytes =- case Zstd.decompress zBytes of+ case Compressed.decompress zBytes of Zstd.Error err -> fail $ label <> ": zstd error (" <> err <> ")" Zstd.Skip ->
src/Resource/Model.hs view
@@ -14,11 +14,12 @@ import Geomancy.Vec3 qualified as Vec3 import UnliftIO.Resource (MonadResource) import Vulkan.Core10 qualified as Vk+import Vulkan.Utils.Queues (Queues(..)) import Engine.Vulkan.Pipeline.Graphics (HasVertexInputBindings(..)) import Engine.Vulkan.Format (HasVkFormat(..)) import Engine.Vulkan.Pipeline.Graphics qualified as Graphics-import Engine.Vulkan.Types (MonadVulkan, Queues(..))+import Engine.Vulkan.Types (MonadVulkan) import Resource.Buffer qualified as Buffer data Indexed storage pos attrs = Indexed
src/Resource/Texture.hs view
@@ -37,10 +37,11 @@ import Vulkan.Core10 qualified as Vk import Vulkan.NamedType ((:::)) import Vulkan.Utils.Debug qualified as Debug+import Vulkan.Utils.Queues (Queues) import Vulkan.Zero (zero) import VulkanMemoryAllocator qualified as VMA -import Engine.Vulkan.Types (HasVulkan(getDevice), MonadVulkan, Queues)+import Engine.Vulkan.Types (HasVulkan(getDevice), MonadVulkan) import Resource.Collection qualified as Collection import Resource.Image (AllocatedImage(..)) import Resource.Image qualified as Image
src/Resource/Texture/Ktx1.hs view
@@ -16,9 +16,10 @@ import UnliftIO.Resource (MonadResource) import Vulkan.Core10 qualified as Vk import Vulkan.Utils.FromGL qualified as FromGL+import Vulkan.Utils.Queues (Queues) import VulkanMemoryAllocator qualified as VMA -import Engine.Vulkan.Types (HasVulkan(..), MonadVulkan, Queues)+import Engine.Vulkan.Types (HasVulkan(..), MonadVulkan) import Resource.Image qualified as Image import Resource.Source (Source(..)) import Resource.Source qualified as Source
src/Resource/Texture/Ktx2.hs view
@@ -20,9 +20,11 @@ import GHC.Stack (withFrozenCallStack) import UnliftIO.Resource (MonadResource) import Vulkan.Core10 qualified as Vk+import Vulkan.Utils.Queues (Queues) import VulkanMemoryAllocator qualified as VMA -import Engine.Vulkan.Types (HasVulkan(..), MonadVulkan, Queues)+import Engine.Vulkan.Types (HasVulkan(..), MonadVulkan)+import Resource.Compressed.Zstd qualified as Compressed import Resource.Image qualified as Image import Resource.Source (Source(..)) import Resource.Source qualified as Source@@ -141,7 +143,7 @@ res <- Zstd.checkError $- Zstd.decompress+ Compressed.decompressInto (Foreign.plusPtr (VMA.mappedData stageInfo) offset) expected src