packages feed

nano-ui-sdl-0.2.0.0: lib/NanoUI/Sdl/Internal/Render.hs

{-# OPTIONS_HADDOCK not-home #-}

-- | Submit nano-ui draw batches to SDL with texture binding, clip
-- deduplication, range coalescing, and damage clipping.
module NanoUI.Sdl.Internal.Render
  ( RenderBatch
  , newRenderBatch
  , destroyRenderBatch
  , flushRenderBatch
  , discardRenderBatch
  , renderDrawDataPass
  , presentGpuRetain
  , glyphPageTexture
  , snapDamage
  )
where

import Control.Exception (onException)
import Control.Monad (unless, void, when)
import Control.Monad.Primitive (RealWorld)
import Data.ByteString.Unsafe qualified as BSU
import Data.Maybe (isJust)
import Data.Primitive.ByteArray (ByteArray, copyByteArrayToAddr, sizeofByteArray)
import Data.Primitive.PrimArray (MutablePrimArray, newPrimArray, readPrimArray, setPrimArray, writePrimArray)
import Data.Primitive.SmallArray (SmallArray, indexSmallArray, newSmallArray, sizeofSmallArray, smallArrayFromList, unsafeFreezeSmallArray, writeSmallArray)
import Data.Text.Encoding qualified as TE
import Data.Vector.Unboxed qualified as U
import Data.Word (Word64, Word8)
import Foreign.C.Types (CFloat (..), CInt (..))
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Array (allocaArray)
import Foreign.Ptr (Ptr, castPtr, nullPtr, ptrToWordPtr, wordPtrToPtr)
import Foreign.Storable (pokeElemOff)
import NanoUI (Color, Rect (..), colorA, colorB, colorG, colorR)
import NanoUI.Backend
import NanoUI.Sdl.Internal.Gpu
  ( GpuState
  , destroyGpuState
  , gpuBindShader
  , gpuEnsureWhiteTex
  , gpuHasDevice
  , newGpuState
  , presentGpuRetainImpl
  )
import NanoUI.Sdl.Internal.Image (ImageAtlas, lookupImage)
import NanoUI.Sdl.Internal.TargetPool
  ( TargetPool
  , acquireTarget
  , bindTarget
  , destroyTargetPool
  , lookupTarget
  , newTargetPool
  , releaseTarget
  )
import SDL3.Sys.Bindgen.Pixels (SDL_FColor (..))
import SDL3.Sys.Bindgen.Rect (SDL_FPoint (..))
import SDL3.Sys.Bindgen.Render (SDL_Renderer, SDL_Texture, SDL_Vertex (..))
import SDL3.Sys.Bindgen.Render qualified as RenderBind
import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst
import SDL3.Sys.Bindgen.Video (SDL_Window)
import SDL3.Sys.Blendmode qualified as Blend
import SDL3.Sys.Render
  ( getRenderTarget
  , renderClearSafe
  , renderGeometry
  , setGPURenderState
  , setRenderDrawColorSafe
  , setRenderTextureAddressMode
  , setTextureBlendMode
  )
import SDL3.Sys.Version (getVersion)

-- Unboxed slot indices inside 'rbState' so per-command clip deduplication and
-- range coalescing perform zero heap allocations.
sHasClip, sClipX, sClipY, sClipW, sClipH :: Int
sHasClip = 0
sClipX = 1
sClipY = 2
sClipW = 3
sClipH = 4

sPendingN, sPendingStart, sPendingVertCount, sPendingVerts, sPendingIndices, sPendingTex :: Int
sPendingN = 5
sPendingStart = 6
sPendingVertCount = 7
sPendingVerts = 8
sPendingIndices = 9
sPendingTex = 10

stateSlots :: Int
stateSlots = 11

{-# INLINE intToWord #-}
intToWord :: Int -> Word
intToWord = fromIntegral

{-# INLINE wordToInt #-}
wordToInt :: Word -> Int
wordToInt = fromIntegral

{-# INLINE ptrToWord #-}
ptrToWord :: Ptr a -> Word
ptrToWord = fromIntegral . ptrToWordPtr

{-# INLINE wordToPtr #-}
wordToPtr :: Word -> Ptr a
wordToPtr = wordPtrToPtr . fromIntegral

-- | Session-owned coalescing state, clip deduplication, GPU shader cache,
-- Tier 2 target pool, and OpenGL 3.2 direct batch handle.
data RenderBatch = RenderBatch
  { rbRenderer :: {-# UNPACK #-} !(Ptr SDL_Renderer)
  , rbGl :: {-# UNPACK #-} !(Ptr ())
  , rbGpu :: !GpuState
  , rbTargets :: !TargetPool
  , rbState :: {-# UNPACK #-} !(MutablePrimArray RealWorld Word)
  }

-- | Create a persistent render batch. Reusing one batch across frames avoids
-- per-frame C/GPU state allocation; flush after each render pass.
newRenderBatch :: Ptr SDL_Renderer -> IO RenderBatch
newRenderBatch ren = do
  gl <- c_glCreate ren
  if gl == nullPtr
    then fail "nano_ui_gl_create failed"
    else do
      -- Every UV the batches submit lies in [0, 1]. Left on AUTO, SDL 3.4 scans
      -- all vertices on every textured call to pick clamp vs wrap.
      ver <- getVersion
      when (ver >= 3004000) $
        void $ setRenderTextureAddressMode ren RenderBind.SDL_TEXTURE_ADDRESS_CLAMP RenderBind.SDL_TEXTURE_ADDRESS_CLAMP
      gpu <- newGpuState ren
      targets <- newTargetPool
      st <- newPrimArray stateSlots
      setPrimArray st 0 stateSlots 0
      pure (RenderBatch ren gl gpu targets st)

-- | Free a render batch and its pooled targets, GPU shaders, and GL buffers.
destroyRenderBatch :: RenderBatch -> IO ()
destroyRenderBatch batch = do
  flushAndLeaveGl batch
  destroyTargetPool (rbTargets batch)
  destroyGpuState (rbGpu batch)
  c_glDestroy (rbGl batch)

{-# INLINE flushAndLeaveGl #-}
flushAndLeaveGl :: RenderBatch -> IO ()
flushAndLeaveGl batch = do
  flushRenderBatch batch
  c_glLeavePass (rbGl batch)

{-# INLINE resetBatchClip #-}
resetBatchClip :: RenderBatch -> IO ()
resetBatchClip batch = do
  writePrimArray (rbState batch) sHasClip 0
  c_glSetClip (rbGl batch) 0 0 0 0 0

{-# INLINE setBatchClip #-}
setBatchClip :: RenderBatch -> Float -> Maybe Rect -> IO ()
setBatchClip batch _ Nothing = do
  let !st = rbState batch
  !was <- readPrimArray st sHasClip
  when (was /= 0) $ do
    flushRenderBatch batch
    writePrimArray st sHasClip 0
    c_glSetClip (rbGl batch) 0 0 0 0 0
setBatchClip batch scale (Just r) = do
  let !(x0, y0, x1, y1) = clipPixelEdges scale r
      !cw = max 1 (x1 - x0)
      !ch = max 1 (y1 - y0)
      !xW = intToWord x0
      !yW = intToWord y0
      !wW = intToWord cw
      !hW = intToWord ch
      !st = rbState batch
  !was <- readPrimArray st sHasClip
  !ox <- readPrimArray st sClipX
  !oy <- readPrimArray st sClipY
  !ow <- readPrimArray st sClipW
  !oh <- readPrimArray st sClipH
  unless (was /= 0 && ox == xW && oy == yW && ow == wW && oh == hW) $ do
    flushRenderBatch batch
    writePrimArray st sHasClip 1
    writePrimArray st sClipX xW
    writePrimArray st sClipY yW
    writePrimArray st sClipW wW
    writePrimArray st sClipH hW
    c_glSetClip (rbGl batch) 1 (fromIntegral x0) (fromIntegral y0) (fromIntegral cw) (fromIntegral ch)

-- | Draw what the batch has queued.
{-# INLINE flushRenderBatch #-}
flushRenderBatch :: RenderBatch -> IO ()
flushRenderBatch batch = do
  let !st = rbState batch
  !n <- wordToInt <$> readPrimArray st sPendingN
  when (n > 0) (flushNonEmpty batch n)

{-# NOINLINE flushNonEmpty #-}
flushNonEmpty :: RenderBatch -> Int -> IO ()
flushNonEmpty batch !n = do
  let !st = rbState batch
  !start <- wordToInt <$> readPrimArray st sPendingStart
  !vc <- wordToInt <$> readPrimArray st sPendingVertCount
  !vpW <- readPrimArray st sPendingVerts
  !ipW <- readPrimArray st sPendingIndices
  !texW <- readPrimArray st sPendingTex
  writePrimArray st sPendingN 0
  writePrimArray st sPendingStart 0
  writePrimArray st sPendingTex 0
  when (n >= 3) $
    c_glDrawPlain
      (rbGl batch)
      (wordToPtr vpW)
      (fromIntegral vc)
      (wordToPtr ipW)
      (fromIntegral start)
      (fromIntegral n)
      (wordToPtr texW)

-- | Drop what the batch has queued without drawing it.
discardRenderBatch :: RenderBatch -> IO ()
discardRenderBatch batch = do
  let !st = rbState batch
  writePrimArray st sPendingN 0
  writePrimArray st sPendingStart 0
  writePrimArray st sPendingTex 0
  c_glLeavePass (rbGl batch)

{-# INLINE rangeIsVisible #-}
rangeIsVisible :: Ptr Word8 -> Int -> Ptr Word8 -> Int -> Int -> Maybe Rect -> IO Bool
rangeIsVisible _ _ _ _ _ Nothing = pure True
rangeIsVisible vp vertCount ip start idxN (Just (Rect dx dy dw dh))
  | dw <= 0 || dh <= 0 = pure True
  | otherwise =
      (/= 0)
        <$> c_rangeVisible
          vp
          (fromIntegral vertCount)
          ip
          (fromIntegral start)
          (fromIntegral idxN)
          (realToFrac dx)
          (realToFrac dy)
          (realToFrac dw)
          (realToFrac dh)

{-# INLINE queueRange #-}
queueRange ::
  RenderBatch ->
  Ptr Word8 -> Int ->
  Ptr Word8 -> Int -> Int ->
  Ptr SDL_Texture ->
  Maybe Rect ->
  IO ()
queueRange batch vp vertCount ip idxStart idxN tex mDmg =
  when (vertCount > 0 && idxN >= 3 && vp /= nullPtr && ip /= nullPtr) $ do
    let !start = max 0 idxStart
    vis <- rangeIsVisible vp vertCount ip start idxN mDmg
    when vis $ do
      let !st = rbState batch
          !vpW = ptrToWord vp
          !ipW = ptrToWord ip
          !texW = ptrToWord tex
      !pendN <- wordToInt <$> readPrimArray st sPendingN
      !pendStart <- wordToInt <$> readPrimArray st sPendingStart
      !pendVp <- readPrimArray st sPendingVerts
      !pendIp <- readPrimArray st sPendingIndices
      !pendTex <- readPrimArray st sPendingTex
      if pendN > 0 && pendVp == vpW && pendIp == ipW && pendTex == texW && pendStart + pendN == start
        then do
          writePrimArray st sPendingN (intToWord (pendN + idxN))
          !pendVc <- wordToInt <$> readPrimArray st sPendingVertCount
          when (vertCount > pendVc) $
            writePrimArray st sPendingVertCount (intToWord vertCount)
        else do
          flushRenderBatch batch
          writePrimArray st sPendingVerts vpW
          writePrimArray st sPendingIndices ipW
          writePrimArray st sPendingTex texW
          writePrimArray st sPendingStart (intToWord start)
          writePrimArray st sPendingN (intToWord idxN)
          writePrimArray st sPendingVertCount (intToWord vertCount)

-- | Shared null-filled page table for passes without a glyph atlas.
emptyGlyphPages :: SmallArray (Ptr SDL_Texture)
emptyGlyphPages = smallArrayFromList (replicate glyphAtlasPages nullPtr)

-- | Flush any dirty glyph atlas pages and snapshot their textures once before
-- a draw pass begins so SDL_UpdateTexture never mutates OpenGL state mid-pass.
resolveGlyphPages :: Ptr () -> IO (SmallArray (Ptr SDL_Texture))
resolveGlyphPages glyphs
  | glyphs == nullPtr = pure emptyGlyphPages
  | otherwise = do
      arr <- newSmallArray glyphAtlasPages nullPtr
      let go !p
            | p >= glyphAtlasPages = unsafeFreezeSmallArray arr
            | otherwise = do
                tex <- glyphPageTexture glyphs p
                writeSmallArray arr p tex
                go (p + 1)
      go 0

-- | Draw every command in layer order, clipped to its own rect and to
-- the damage. A full repaint clears the target to 'drawClear' first.
--
-- The renderer must be at render scale 1: positions are multiplied by the
-- scale here, and clips are whole device pixels. The pass submits
-- everything it queued before it returns, while the draw data's buffers
-- are held; a pass that throws drops what it had queued instead.
renderDrawDataPass ::
  RenderBatch
  -> Ptr SDL_Renderer
  -> Float
  -- ^ Device pixels per layout unit.
  -> DrawData
  -> ImageAtlas
  -> Ptr ()
  -- ^ The glyph atlas, whose pages text draws from ('glyphPageTexture').
  -> Damage
  -> IO ()
renderDrawDataPass batch ren scale drawData images glyphs damage =
  unless (damageIsEmpty damage) $ do
    let !vertCount = drawVertexCount drawData
        !indexCount = fromIntegral (drawIndexCount drawData)
        !st = rbState batch
    !imgTex <- lookupImage images atlasTextureId
    !glyphPages <- resolveGlyphPages glyphs
    writePrimArray st sHasClip 0
    writePrimArray st sPendingN 0
    c_glBeginPass (rbGl batch) (realToFrac scale) indexCount
    mDamage <- case damage of
      DamageFull -> do
        let clear = drawClear drawData
        void $ setRenderDrawColorSafe ren (colorR clear) (colorG clear) (colorB clear) (colorA clear)
        void $ renderClearSafe ren
        pure Nothing
      -- The draw list starts a clip frame with its own page backdrop, so a
      -- clip needs no clear here.
      DamageClip r -> Just r <$ setBatchClip batch scale (Just r)
    let !calls = drawShaderCalls drawData
        !uBytes = drawUniformBytes drawData
        !spans = drawEffectSpans drawData
        !cmds = drawCommands drawData
        !nCmds = U.length cmds
    -- The batch keeps the vertex and index pointers until it flushes, so
    -- the last flush is inside the buffers' scope.
    ( withForeignPtr (drawVertices drawData) $ \vp ->
        withForeignPtr (drawIndices drawData) $ \ip -> do
          if sizeofSmallArray spans == 0
            then
              let go !i = when (i < nCmds) $ do
                    let !cmd = U.unsafeIndex cmds i
                        !count = fromIntegral (cmdIndexCount cmd)
                        !shIdx = fromIntegral (cmdShader cmd) :: Int
                    when (count >= 3) $ case cmdEffectiveClip mDamage cmd of
                      Nothing -> pure ()
                      Just mClip -> do
                        setBatchClip batch scale mClip
                        let !texId = cmdTextureId cmd
                            !page = textureGlyphPage texId
                            !tex
                              | page >= 0 = indexSmallArray glyphPages page
                              | texId == atlasTextureId = imgTex
                              | otherwise = nullPtr
                            !idxOff = fromIntegral (cmdIndexOffset cmd)
                        if shIdx > 0 && shIdx <= sizeofSmallArray calls
                          then
                            drawShaderCmd
                              batch vp vertCount ip idxOff count tex mDamage
                              (indexSmallArray calls (shIdx - 1)) uBytes
                          else
                            queueRange batch vp vertCount ip idxOff count tex mDamage
                    go (i + 1)
               in go 0
            else
              renderEffectSpansPass batch ren scale vertCount vp ip imgTex glyphPages calls uBytes spans cmds mDamage
          flushRenderBatch batch
          writePrimArray st sHasClip 0
          c_glEndPass (rbGl batch)
      )
      `onException` discardRenderBatch batch

{-# NOINLINE renderEffectSpansPass #-}
renderEffectSpansPass ::
  RenderBatch ->
  Ptr SDL_Renderer ->
  Float ->
  Int ->
  Ptr Word8 ->
  Ptr Word8 ->
  Ptr SDL_Texture ->
  SmallArray (Ptr SDL_Texture) ->
  SmallArray ShaderCall ->
  ByteArray ->
  SmallArray EffectSpan ->
  U.Vector DrawCmd ->
  Maybe Rect ->
  IO ()
renderEffectSpansPass batch ren scale vertCount vp ip imgTex glyphPages calls uBytes spans cmds mDamage = do
  rootTarget <- getRenderTarget ren
  let drawCmd curDmg !ox !oy cmd = do
        let !count = fromIntegral (cmdIndexCount cmd)
            !shIdx = fromIntegral (cmdShader cmd) :: Int
        when (count >= 3) $ case cmdEffectiveClip curDmg cmd of
          Nothing -> pure ()
          Just mClip -> do
            setBatchClip batch scale (shiftClip (-ox) (-oy) mClip)
            let !texId = cmdTextureId cmd
                !page = textureGlyphPage texId
                !tex
                  | page >= 0 = indexSmallArray glyphPages page
                  | texId == atlasTextureId = imgTex
                  | otherwise = nullPtr
                !idxOff = fromIntegral (cmdIndexOffset cmd)
            if shIdx > 0 && shIdx <= sizeofSmallArray calls
              then
                drawShaderCmd
                  batch vp vertCount ip idxOff count tex curDmg
                  (indexSmallArray calls (shIdx - 1)) uBytes
              else
                queueRange batch vp vertCount ip idxOff count tex curDmg
      drv =
        EffectDriver
          { edScale = scale
          , edFlipY = False
          , edPreparePasses = \passes ->
              pure $
                if all (\sc -> let p = scProgram sc in isJust (spSpirv p) || isJust (spMsl p) || isJust (spGlsl150 p)) passes
                  then Just passes
                  else Nothing
          , edAcquireTarget = acquireTarget ren (rbTargets batch) (flushAndLeaveGl batch)
          , edReleaseTarget = releaseTarget (rbTargets batch)
          , edBindTarget = \slot clr ox oy -> do
              ok <- bindTarget ren (rbTargets batch) (flushAndLeaveGl batch) (resetBatchClip batch) slot rootTarget clr
              if not ok
                then pure False
                else do
                  c_glSetOrigin (rbGl batch) (realToFrac ox) (realToFrac oy)
                  pure True
          , edFlush = flushRenderBatch batch
          , edEmitPlain = \_ _ _ ox oy curDmg from to ->
              let loop !i = when (i < to) (drawCmd curDmg ox oy (U.unsafeIndex cmds i) >> loop (i + 1))
               in loop from
          , edAfterSpanContent = \_ -> pure ()
          , edCompositePass = \_ sc pd _ _ -> do
              unless (epdIntermediate pd) $
                setBatchClip batch scale (epdClip pd)
              compositeEffectPass batch sc uBytes pd
          }
  execEffectSpans drv spans 0 (-1) (0, 0) 0 0 mDamage 0 (U.length cmds)

-- | The texture of a glyph atlas page: null for a page never opened, one past
-- the last, or a null atlas.
glyphPageTexture :: Ptr () -> Int -> IO (Ptr SDL_Texture)
glyphPageTexture atlas = textAtlasTexture atlas . fromIntegral

-- | Present an opaque retained texture directly to the SDL 3.4 GPU swapchain
-- at 1:1 pixels while live-resizing away from SDL 3.4's internal GPU
-- backbuffer size. Returns 'False' when the standard copy-and-present path
-- should run instead (steady frames, SDL 3.5+, or non-GPU renderers).
presentGpuRetain :: RenderBatch -> Ptr SDL_Window -> Ptr SDL_Texture -> Int -> Int -> Bool -> Color -> IO Bool
presentGpuRetain batch =
  presentGpuRetainImpl (rbRenderer batch) (rbGpu batch) (flushAndLeaveGl batch) (resetBatchClip batch)

{-# NOINLINE drawShaderCmd #-}
drawShaderCmd ::
  RenderBatch ->
  Ptr Word8 -> Int ->
  Ptr Word8 -> Int -> Int ->
  Ptr SDL_Texture ->
  Maybe Rect ->
  ShaderCall ->
  ByteArray ->
  IO ()
drawShaderCmd batch vp vertCount ip idxStart idxCount tex mDmg sc uniformBytes =
  when (vertCount > 0 && idxCount >= 3 && vp /= nullPtr && ip /= nullPtr) $ do
    let !start = max 0 idxStart
    vis <- rangeIsVisible vp vertCount ip start idxCount mDmg
    when vis $ do
      flushRenderBatch batch
      let prog = scProgram sc
          !uOff = scUniformOffset sc
          !uLen = min (scUniformLength sc) (max 0 (sizeofByteArray uniformBytes - uOff))
          runWithUniforms uPtr len
            | gpuHasDevice (rbGpu batch) = do
                let ren = rbRenderer batch
                tex' <- if tex /= nullPtr then pure tex else gpuEnsureWhiteTex ren (rbGpu batch)
                if tex' == nullPtr
                  then pure False
                  else do
                    bound <- gpuBindShader ren (rbGpu batch) prog (scHash sc) (spNeedsTex prog) uPtr len
                    if not bound
                      then pure False
                      else do
                        ok <-
                          c_sdlDrawRaw
                            (rbGl batch) tex' vp (fromIntegral vertCount)
                            ip (fromIntegral start) (fromIntegral idxCount)
                        void $ setGPURenderState ren nullPtr
                        pure (ok /= 0)
            | Just glslText <- spGlsl150 prog =
                BSU.unsafeUseAsCStringLen (TE.encodeUtf8 glslText) $ \(glslPtr, glslLen) ->
                  (/= 0)
                    <$> c_glDrawShader
                      (rbGl batch) vp (fromIntegral vertCount)
                      ip (fromIntegral start) (fromIntegral idxCount)
                      tex (scHash sc)
                      (castPtr glslPtr) (fromIntegral glslLen)
                      uPtr (fromIntegral len)
            | otherwise = pure False
      drawn <-
        if uLen > 0
          then allocaBytes uLen $ \uPtr -> copyByteArrayToAddr uPtr uniformBytes uOff uLen >> runWithUniforms uPtr uLen
          else runWithUniforms nullPtr 0
      unless drawn $
        queueRange batch vp vertCount ip start idxCount nullPtr Nothing

{-# NOINLINE compositeEffectPass #-}
compositeEffectPass :: RenderBatch -> ShaderCall -> ByteArray -> EffectPassDraw -> IO ()
compositeEffectPass batch sc uniformBytes pd = do
  flushRenderBatch batch
  mSrc <- lookupTarget (rbTargets batch) (epdSrcSlot pd)
  case mSrc of
    Nothing -> pure ()
    Just srcTex ->
      withEffectUniforms sc uniformBytes pd $ \uPtr uLen -> do
        let ren = rbRenderer batch
            prog = scProgram sc
        done <-
          if gpuHasDevice (rbGpu batch)
            then do
              bound <- gpuBindShader ren (rbGpu batch) prog (scHash sc) True uPtr uLen
              if not bound
                then pure False
                else do
                  void $ setTextureBlendMode srcTex Blend.SDL_BLENDMODE_BLEND
                  void $ renderQuad ren srcTex pd
                  void $ setGPURenderState ren nullPtr
                  pure True
            else case spGlsl150 prog of
              Just glslText ->
                BSU.unsafeUseAsCStringLen (TE.encodeUtf8 glslText) $ \(glslPtr, glslLen) ->
                  (/= 0)
                    <$> c_glCompositeEffect
                      (rbGl batch) srcTex
                      (realToFrac (epdDstX pd)) (realToFrac (epdDstY pd))
                      (realToFrac (epdDstW pd)) (realToFrac (epdDstH pd))
                      (realToFrac (epdU0 pd)) (realToFrac (epdV0 pd))
                      (realToFrac (epdU1 pd)) (realToFrac (epdV1 pd))
                      (scHash sc) (castPtr glslPtr) (fromIntegral glslLen)
                      uPtr (fromIntegral uLen)
              Nothing -> pure False
        -- Fallback: blit the offscreen premultiplied target unshaded so the
        -- wrapped subtree never disappears on shader compile failure.
        unless done $ do
          c_glLeavePass (rbGl batch)
          void $ setTextureBlendMode srcTex Blend.SDL_BLENDMODE_BLEND_PREMULTIPLIED
          void $ renderQuad ren srcTex pd
          void $ setTextureBlendMode srcTex Blend.SDL_BLENDMODE_BLEND

renderQuad :: Ptr SDL_Renderer -> Ptr SDL_Texture -> EffectPassDraw -> IO Bool
renderQuad ren srcTex pd = do
  let !px = realToFrac (epdDstX pd)
      !py = realToFrac (epdDstY pd)
      !pw = realToFrac (epdDstW pd)
      !ph = realToFrac (epdDstH pd)
      !u0 = realToFrac (epdU0 pd)
      !v0 = realToFrac (epdV0 pd)
      !u1 = realToFrac (epdU1 pd)
      !v1 = realToFrac (epdV1 pd)
      !white = SDL_FColor 1 1 1 1
  allocaArray 4 $ \qPtr -> do
    pokeElemOff qPtr 0 (SDL_Vertex (SDL_FPoint px py) white (SDL_FPoint u0 v0))
    pokeElemOff qPtr 1 (SDL_Vertex (SDL_FPoint (px + pw) py) white (SDL_FPoint u1 v0))
    pokeElemOff qPtr 2 (SDL_Vertex (SDL_FPoint (px + pw) (py + ph)) white (SDL_FPoint u1 v1))
    pokeElemOff qPtr 3 (SDL_Vertex (SDL_FPoint px (py + ph)) white (SDL_FPoint u0 v1))
    allocaArray 6 $ \iPtr -> do
      pokeElemOff iPtr 0 (0 :: CInt)
      pokeElemOff iPtr 1 1
      pokeElemOff iPtr 2 2
      pokeElemOff iPtr 3 0
      pokeElemOff iPtr 4 2
      pokeElemOff iPtr 5 3
      renderGeometry ren srcTex (PtrConst.unsafeFromPtr qPtr) 4 (PtrConst.unsafeFromPtr iPtr) 6

foreign import ccall unsafe "nano_ui_text_atlas_texture"
  textAtlasTexture :: Ptr () -> CInt -> IO (Ptr SDL_Texture)

foreign import ccall unsafe "nano_ui_gl_create"
  c_glCreate :: Ptr SDL_Renderer -> IO (Ptr ())

foreign import ccall unsafe "nano_ui_gl_destroy"
  c_glDestroy :: Ptr () -> IO ()

foreign import ccall unsafe "nano_ui_gl_begin_pass"
  c_glBeginPass :: Ptr () -> CFloat -> CInt -> IO ()

foreign import ccall unsafe "nano_ui_gl_end_pass"
  c_glEndPass :: Ptr () -> IO ()

foreign import ccall unsafe "nano_ui_gl_leave_pass"
  c_glLeavePass :: Ptr () -> IO ()

foreign import ccall unsafe "nano_ui_gl_set_clip"
  c_glSetClip :: Ptr () -> CInt -> CInt -> CInt -> CInt -> CInt -> IO ()

foreign import ccall unsafe "nano_ui_gl_set_origin"
  c_glSetOrigin :: Ptr () -> CFloat -> CFloat -> IO ()

foreign import ccall unsafe "nano_ui_range_visible"
  c_rangeVisible ::
    Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> CInt
    -> CFloat -> CFloat -> CFloat -> CFloat -> IO CInt

foreign import ccall unsafe "nano_ui_sdl_draw_raw"
  c_sdlDrawRaw ::
    Ptr () -> Ptr SDL_Texture -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> CInt -> IO CInt

foreign import ccall unsafe "nano_ui_gl_draw_plain"
  c_glDrawPlain ::
    Ptr () -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> CInt -> Ptr SDL_Texture -> IO ()

foreign import ccall unsafe "nano_ui_gl_draw_shader"
  c_glDrawShader ::
    Ptr () -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> CInt -> Ptr SDL_Texture
    -> Word64 -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> IO CInt

foreign import ccall unsafe "nano_ui_gl_composite_effect"
  c_glCompositeEffect ::
    Ptr () -> Ptr SDL_Texture
    -> CFloat -> CFloat -> CFloat -> CFloat
    -> CFloat -> CFloat -> CFloat -> CFloat
    -> Word64 -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> IO CInt