mischief-render-0.1.1.0: src/Mischief/Render/Camera.hs
module Mischief.Render.Camera where
import Control.Monad
import Control.Monad.IO.Class
import Data.Bits
import Data.Foldable
import Data.Primitive.Ptr (nullPtr)
import Data.Text qualified as T
import Foreign.C.ConstPtr
import Linear (M44, V2 (..), V3 (V3), V4 (V4), inv44, (!*), (!*!), (^*), (^/))
import Mischief.ECS
import Mischief.Math.Transform
import Mischief.Math.Vec.Orphans.FieldAccessors
import Mischief.Render.Buffer
import Mischief.Render.Core
import Mischief.Render.Layers (RenderLayers)
import Mischief.Render.Texture
import Mischief.Render.Texture qualified as Texture
import Mischief.SDL.Window
import Mischief.Shader (Bufferable, Field)
import Mischief.Shader.Internal.State (CPU)
import Mischief.Shader.Types qualified as ST
import Mischief.WGPU (wgpuTextureRelease)
import Mischief.WGPU.Types.Enums
import Mischief.WGPU.Types.General
data Camera = Camera
instance Component Camera where
required = require @(Transform, RenderLayers, CameraZoom, CameraBackground)
-- | Add this as a relationship between a camera and a window to have the
-- camera's output texture be rendered to that window.
--
-- Exclusive.
data OutputTo = OutputTo
instance Component OutputTo where
type IsExclusiveRel OutputTo = True
newtype CameraBackground = CameraBackground (V3 Float) deriving anyclass (Component)
instance Default CameraBackground where
def = CameraBackground $ V3 0.184313725 0.211764706 0.250980392
newtype CameraTexture = CameraTexture SwappableTexture
instance Component CameraTexture where
onRemove =
[ hook $ \(HookContext entity) -> do
Just (CameraTexture (SwappableTexture {currentTexture, otherTexture})) <- single [q|entity. CameraTexture|]
liftIO $ wgpuTextureRelease currentTexture
liftIO $ wgpuTextureRelease otherTexture
]
newtype ViewMatrix = ViewMatrix (M44 Float) deriving anyclass (Component)
newtype ProjectionMatrix = ProjectionMatrix (M44 Float) deriving anyclass (Component)
newtype CameraMatrices = CameraMatrices (Buffer Matrices) deriving anyclass (Component)
data CameraPlugin
instance Plugin CameraPlugin where
init = do
void $ spawn $ Observer onAddCameraOutputTo
void $ spawn $ Observer onUpdateWindowSize
systems updateCameraMatrices
& schedule @Update
updateCameraMatrices :: System ()
updateCameraMatrices = query_ $ do
device <- qres @RenderDevice
queue <- qres @RenderQueue
(camera, buffer, transform, zoom, From _ (WindowSize w h)) <-
[q|Entity, Maybe CameraMatrices, Transform, CameraZoom, OutputTo -> (WindowSize) / With Camera|]
buffer <- case buffer of
Just (CameraMatrices b) -> pure b
Nothing -> qlift $ do
buffer <- createBuffer @Matrices device
insert (CameraMatrices buffer) camera
pure buffer
let matrices = getCameraProjection w h transform zoom
qlift $ do
insert (ViewMatrix matrices.view, ProjectionMatrix matrices.projection) camera
uploadBuffer queue buffer matrices
onAddCameraOutputTo :: OnAddRel OutputTo -> System ()
onAddCameraOutputTo (OnAddRel entity target) = updateCameraTexture entity target
onUpdateWindowSize :: OnSet WindowSize -> System ()
onUpdateWindowSize (OnSet window) = do
cameras <- query [q|Entity / With OutputTo -> window|]
for_ cameras $ \camera -> updateCameraTexture camera window
-- | Creates a new CameraTexture component that fits the targeted window.
updateCameraTexture :: Entity -> Entity -> System ()
updateCameraTexture camera window = do
Just device <- res @RenderDevice
window <- single [q|window. WindowSize|]
case window of
Nothing -> warn "Camera output window not found."
Just (WindowSize width height) -> do
texture <- liftIO $ createSwappableTexture device (textureDescriptor {Texture.width, height})
insert (CameraTexture texture) camera
newTextureDescriptor :: Int -> Int -> WGPUStringView -> WGPUTextureDescriptor
newTextureDescriptor w h label =
WGPUTextureDescriptor
{ size = WGPUExtent3D (fromIntegral w) (fromIntegral h) 1,
label,
mipLevelCount = 1,
sampleCount = 1,
dimension = wGPUTextureDimension_2D,
format = wGPUTextureFormat_RGBA8UnormSrgb,
usage = wGPUTextureUsage_TextureBinding .|. wGPUTextureUsage_CopyDst,
nextInChain = nullPtr,
viewFormatCount = 0,
viewFormats = ConstPtr nullPtr
}
data Matrices f = Matrices
{ projection :: Field f (ST.Mat 4 4),
view :: Field f (ST.Mat 4 4)
}
deriving stock (Generic)
deriving anyclass (Bufferable)
newtype CameraZoom = CameraZoom Float deriving anyclass (Component)
instance Default CameraZoom where
def = CameraZoom 1
getCameraProjection :: Int -> Int -> Transform -> CameraZoom -> Matrices CPU
getCameraProjection w h Transform {translation = pos} (CameraZoom zoom) = do
let hw = fromIntegral w / (2 * zoom)
let hh = fromIntegral h / (2 * zoom)
let l = pos.x - hw
let r = pos.x + hw
let t = pos.y + hh
let b = pos.y - hh
let n = 0
let f = 100
let forward = V3 0 0 1
let right = V3 1 0 0
let up = V3 0 1 0
let rotation =
V4
(V4 right.x right.y right.z 0)
(V4 up.x up.y up.z 0)
(V4 forward.x forward.y forward.z 0)
(V4 0 0 0 1)
let translation' =
V4
(V4 1 0 0 0)
(V4 0 1 0 0)
(V4 0 0 1 0)
(V4 (-pos.x) (-pos.y) (-pos.z) 1)
let translation :: V4 (V4 Float) = rotation !*! translation'
-- let V4 v1 v2 v3 v4 = translation
Matrices
-- projection matrix
( V4
(V4 (2 / (r - l)) 0 0 (-((r + l) / (r - l))))
(V4 0 (2 / (t - b)) 0 (-((t + b) / (t - b))))
(V4 0 0 (-(2 / (f - n))) (-((f + n) / (f - n))))
(V4 0 0 0 1)
)
-- view matrix
translation
cameraView :: Entity -> Query System TextureView
cameraView camera = do
CameraTexture (SwappableTexture {currentTexture = texture, desc}) <- qget camera [qd|CameraTexture|]
qlift $ createView $ Texture texture desc
cameraSwapView :: Entity -> Query System TextureView
cameraSwapView camera = do
CameraTexture (SwappableTexture {currentTexture = texture, desc, otherTexture}) <- qget camera [qd|CameraTexture|]
qlift $ do
insert (CameraTexture $ SwappableTexture {currentTexture = otherTexture, otherTexture = texture, desc}) camera
createView $ Texture texture desc
-- | Expects a Camera entity and a screen-space position. Outputs that position in world coordinates.
windowToWorldPos :: Entity -> (Float, Float) -> System (Maybe (V2 Float))
windowToWorldPos camera (x, y) = single $ do
(Rel _ window, ProjectionMatrix proj, ViewMatrix view) <- qget camera [qd|OutputTo -> *, ProjectionMatrix, ViewMatrix|]
let proj' = inv44 proj
let view' = inv44 view
WindowSize {width, height} <- qget window [qd|WindowSize|]
let ndc = (V4 @Float (x / fromIntegral width) (y / fromIntegral height) 0 1 ^* 2) - 1
let cameraPos = proj' !* ndc
let worldPos = view' !* cameraPos
pure $ V2 worldPos.x (-worldPos.y)