packages feed

nano-ui-rgfw-0.2.0.0: lib/NanoUI/Rgfw/Internal/Gl.hs

{-# OPTIONS_HADDOCK not-home #-}

-- | OpenGL presentation for the RGFW host.
--
-- Geometry goes to the GPU straight from the core's shared 'DrawData'
-- buffers, one scissored draw per command; image-atlas commands sample the
-- texture 'syncImagesGl' maintains. Text comes from the collected
-- spans: every glyph is a quad sampled from an atlas that the Cozette
-- software blitter bakes at the current scale, so glyph pixels match what the
-- blitter stamps.
--
-- Frames draw into a retained framebuffer and a present copies it to the
-- window, so a frame whose damage is a clip draws only inside it.
--
-- The frame must come from a context built by
-- 'NanoUI.Rgfw.Internal.Context.newRgfwContext' (external text: the buffer holds no
-- text quads). Draw order is 'NanoUI.Rgfw.Internal.Context.paintInLayerOrder'.
module NanoUI.Rgfw.Internal.Gl
  ( GlRenderer
  , newGlRenderer
  , freeGlRenderer
  , renderArenaGl
  , syncImagesGl
  , readRetainedPixels
  , readWindowPixels
  , retainedPixels
  , GlyphAtlas (..)
  , glyphAtlasFor
  , atlasCell
  , bakeGlyphAtlas
  , writeSpanQuads
  , toPhysRect
  , physClip
  , glBufferStrides
  ) where

import Control.Exception (bracket)
import Control.Monad (foldM, forM_, void, when)
import Data.Bits (shiftR, (.&.))
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.Int (Int32)
import qualified Data.IntMap.Strict as IM
import Data.Maybe (fromMaybe, isJust)
import Data.Primitive.ByteArray (ByteArray, copyByteArrayToAddr, sizeofByteArray)
import Data.Primitive.PrimArray (indexPrimArray)
import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BSI
import qualified Data.ByteString.Unsafe as BSU
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Foreign as TF
import qualified Data.Vector.Unboxed as U
import Data.Word (Word32, Word64, Word8)
import Foreign.C.Types (CChar)
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Marshal.Alloc (alloca, allocaBytes, callocBytes, free, reallocBytes)
import Foreign.Marshal.Utils (copyBytes)
import Foreign.Ptr (Ptr, nullPtr, plusPtr)
import Foreign.Storable (peek, pokeByteOff)
import NanoUI (Color (..), Rect (..), RgbaPixels, rectInflate, rgbaPixels)
import NanoUI.Backend (Damage (..), roundHalfUp)
import NanoUI.Rgfw.Internal.Context (TextSpan, paintInLayerOrder)
import NanoUI.Rgfw.Internal.Font.Cozette
  ( CozetteFont (..)
  , cozetteGlyphFootprint
  , cozetteLineHeight
  , foldPenPositions
  , renderGlyphScaledToBuffer
  )
import NanoUI.Backend
  ( AtlasUpload (..)
  , Context
  , DrawCmd (..)
  , DrawData (..)
  , EffectDriver (..)
  , EffectPassDraw (..)
  , EffectSpan (..)
  , Layer (..)
  , ShaderCall (..)
  , ShaderProgram (..)
  , atlasChanges
  , atlasTextureId
  , execEffectSpans
  , forDrawCmdsInLayer_
  , vertexSize
  , withEffectUniforms
  )

-- | Opaque C renderer state (cbits/nano_ui_gl.c).
data NanoUiGl

foreign import ccall unsafe "nano_ui_gl_create"
  c_create :: IO (Ptr NanoUiGl)

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

foreign import ccall unsafe "nano_ui_gl_upload_atlas"
  c_uploadAtlas :: Ptr NanoUiGl -> Ptr Word32 -> Int32 -> Int32 -> IO Int32

foreign import ccall unsafe "nano_ui_gl_upload_images"
  c_uploadImages :: Ptr NanoUiGl -> Ptr Word8 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO Int32

foreign import ccall unsafe "nano_ui_gl_begin"
  c_begin :: Ptr NanoUiGl -> Int32 -> Int32 -> Float -> Float -> Float -> Float -> Int32 -> IO Int32

foreign import ccall unsafe "nano_ui_gl_present"
  c_present :: Ptr NanoUiGl -> IO ()

foreign import ccall unsafe "nano_ui_gl_read_retained"
  c_readRetained :: Ptr NanoUiGl -> Int32 -> Int32 -> Ptr Word8 -> IO ()

foreign import ccall unsafe "nano_ui_gl_read_window"
  c_readWindow :: Ptr NanoUiGl -> Int32 -> Int32 -> Ptr Word8 -> IO ()

foreign import ccall unsafe "nano_ui_gl_upload_geometry"
  c_uploadGeometry :: Ptr NanoUiGl -> Ptr Word8 -> Int32 -> Ptr Word8 -> Int32 -> IO ()

foreign import ccall unsafe "nano_ui_gl_upload_text"
  c_uploadText :: Ptr NanoUiGl -> Ptr Word8 -> Int32 -> IO ()

foreign import ccall unsafe "nano_ui_gl_draw_geometry"
  c_drawGeometry :: Ptr NanoUiGl -> Int32 -> Int32 -> Int32 -> Int32 -> Word32 -> Word32 -> Int32 -> IO ()

foreign import ccall unsafe "nano_ui_gl_draw_shader"
  c_drawShader ::
    Ptr NanoUiGl ->
    Int32 -> Int32 -> Int32 -> Int32 ->
    Word32 -> Word32 ->
    Word64 -> Ptr CChar -> Int32 ->
    Ptr Word8 -> Int32 ->
    IO Int32

foreign import ccall unsafe "nano_ui_gl_draw_text"
  c_drawText :: Ptr NanoUiGl -> Int32 -> Int32 -> IO ()

foreign import ccall unsafe "nano_ui_gl_acquire_target"
  c_acquireTarget :: Ptr NanoUiGl -> Int32 -> Int32 -> Ptr Int32 -> Ptr Int32 -> IO Int32

foreign import ccall unsafe "nano_ui_gl_release_target"
  c_releaseTarget :: Ptr NanoUiGl -> Int32 -> IO ()

foreign import ccall unsafe "nano_ui_gl_bind_target"
  c_bindTarget :: Ptr NanoUiGl -> Int32 -> Int32 -> Float -> Float -> IO Int32

foreign import ccall unsafe "nano_ui_gl_composite_effect"
  c_compositeEffect ::
    Ptr NanoUiGl -> Int32 ->
    Float -> Float -> Float -> Float ->
    Float -> Float -> Float -> Float ->
    Int32 -> Int32 -> Int32 -> Int32 -> Int32 ->
    Int32 ->
    Word64 -> Ptr CChar -> Int32 ->
    Ptr Word8 -> Int32 ->
    IO Int32

foreign import ccall unsafe "nano_ui_gl_vertex_bytes"
  c_vertexBytes :: IO Int32

foreign import ccall unsafe "nano_ui_gl_index_bytes"
  c_indexBytes :: IO Int32

-- | The vertex and index strides in bytes nano_ui_gl.c reads the draw
-- buffers with. They must equal the core's 'vertexSize' and
-- 'NanoUI.Testing.indexSize'; nano-ui-rgfw-test checks.
glBufferStrides :: IO (Int, Int)
glBufferStrides = (,) <$> (fromIntegral <$> c_vertexBytes) <*> (fromIntegral <$> c_indexBytes)

-- | GPU resources and glyph scratch storage owned by one OpenGL context.
-- Release with 'freeGlRenderer' while that context is still current.
data GlRenderer = GlRenderer
  { glHandle :: !(Ptr NanoUiGl)
  , glAtlas  :: !(IORef (Maybe GlyphAtlas))
  , glText   :: !(IORef (Ptr Word8, Int)) -- ^ glyph vertex scratch, capacity in vertices
  , glImages :: !(IORef Int) -- ^ image atlas generation uploaded, 0 for none
  }

-- | Build the renderer on the calling thread's current OpenGL context.
newGlRenderer :: IO GlRenderer
newGlRenderer = do
  h <- c_create
  when (h == nullPtr) $
    fail "nano-ui-rgfw: OpenGL renderer setup failed (needs an OpenGL 3.2 core context)"
  GlRenderer h <$> newIORef Nothing <*> newIORef (nullPtr, 0) <*> newIORef 0

-- | Release the GPU objects (the context must still be current) and the
-- glyph vertex scratch.
freeGlRenderer :: GlRenderer -> IO ()
freeGlRenderer r = do
  c_destroy (glHandle r)
  (p, _) <- readIORef (glText r)
  free p

-- | Draw a frame into the retained framebuffer and copy it to the current
-- context's default framebuffer. The caller swaps buffers.
--
-- A 'DamageClip' frame redraws only its damage and keeps the other pixels
-- from the frames before, so its 'DrawData' may leave out what lies outside.
-- Its damage pieces ('NanoUI.Testing.takeDamagePieces'), when it has some,
-- are all it redraws: text is cut to each, as draw commands already are.
-- A frame at a new size has no such pixels and must be a 'DamageFull' one.
renderArenaGl ::
  GlRenderer ->
  CozetteFont ->
  Float -> -- logical (layout) -> physical (pixel) scale
  Int -> -- framebuffer width (physical pixels)
  Int -> -- framebuffer height
  Damage -> -- what to redraw, in logical pixels
  [Rect] -> -- the damage's pieces, if any
  DrawData -> -- the frame, and the colour a full frame clears to
  [TextSpan] -> -- base spans
  [TextSpan] -> -- overlay spans
  IO ()
renderArenaGl r font !scale !fbW !fbH damage pieces drawData baseSpans overlaySpans = do
  let !h = glHandle r
      (!full, mDamage, textBoxes) = case damage of
        DamageFull -> (1, Nothing, [(0, 0, fbW, fbH)])
        DamageClip rect -> (0, Just rect, map (damageBox scale fbW fbH) (if null pieces then [rect] else pieces))
      (!bgR, !bgG, !bgB, _) = colorFloats (drawClear drawData)
  began <- c_begin h (fromIntegral fbW) (fromIntegral fbH) scale bgR bgG bgB full
  when (began == 0) $ fail "nano-ui-rgfw: retained framebuffer setup failed"
  atlas <- ensureAtlas r font scale
  let effectSpans = drawEffectSpans drawData
  withForeignPtr (drawVertices drawData) $ \vp ->
    withForeignPtr (drawIndices drawData) $ \ip ->
      c_uploadGeometry h vp (fromIntegral (drawVertexCount drawData)) ip (fromIntegral (drawIndexCount drawData))
  if sizeofSmallArray effectSpans == 0
    then do
      buf <- ensureTextCapacity r ((spanChars baseSpans + spanChars overlaySpans) * 6 * length textBoxes)
      let spansIn spans n0 = foldM (\n tb -> foldM (writeSpanQuads atlas font tb buf) n spans) n0 textBoxes
      nBase <- spansIn baseSpans 0
      nAll <- spansIn overlaySpans nBase
      c_uploadText h buf (fromIntegral nAll)
      paintInLayerOrder
        (\layer -> forDrawCmdsInLayer_ layer drawData (drawCmd h scale fbW fbH 0 0 (drawShaderCalls drawData) (drawUniformBytes drawData)))
        (c_drawText h 0 (fromIntegral nBase))
        (c_drawText h (fromIntegral nBase) (fromIntegral (nAll - nBase)))
    else
      renderArenaGlWithEffects r h atlas font scale fbW fbH mDamage textBoxes drawData effectSpans baseSpans overlaySpans
  c_present h

-- | Render a frame containing Tier 2 subtree effects into pooled offscreen
-- OpenGL 3.2 framebuffers. Cozette text spans falling inside an effect span
-- are drawn into that span's offscreen target before its shader passes run.
{-# NOINLINE renderArenaGlWithEffects #-}
renderArenaGlWithEffects ::
  GlRenderer ->
  Ptr NanoUiGl ->
  GlyphAtlas ->
  CozetteFont ->
  Float ->
  Int ->
  Int ->
  Maybe Rect ->
  [(Int, Int, Int, Int)] ->
  DrawData ->
  SmallArray EffectSpan ->
  [TextSpan] ->
  [TextSpan] ->
  IO ()
renderArenaGlWithEffects r h atlas font !scale !fbW !fbH mDamage textBoxes drawData effectSpans baseSpans overlaySpans = do
  let nSpans = sizeofSmallArray effectSpans
      allSpans = [indexSmallArray effectSpans i | i <- [0 .. nSpans - 1]]
      isBaseLayer l = l == LayerBackground || l == LayerContent
      ownerOf isBase (Rect tx ty tw th, _, _, _, _) =
        let !cx = tx + tw * 0.5
            !cy = ty + th * 0.5
            inBounds (Rect bx by bw bh) = cx >= bx && cx <= bx + bw && cy >= by && cy <= by + bh
            matches =
              [ esId sp
              | sp <- allSpans
              , isBaseLayer (esLayer sp) == isBase
              , inBounds (esBounds sp)
              ]
         in case matches of
              [] -> 0
              xs -> maximum xs
      -- Partition spans into root vs. per-effect buckets in one linear pass.
      partitionSpans isBase =
        foldr
          (\s (roots, byId) ->
            let !eid = ownerOf isBase s
             in if eid == 0
                  then (s : roots, byId)
                  else (roots, IM.insertWith (++) eid [s] byId))
          ([], IM.empty)
      (rootBase, baseById) = partitionSpans True baseSpans
      (rootOver, overById) = partitionSpans False overlaySpans
      spansById = IM.unionWith (++) baseById overById
      effectIds = [esId sp | sp <- allSpans]
      totalVerts =
        ((spanChars rootBase + spanChars rootOver) * length textBoxes
          + IM.foldl' (\acc ss -> acc + spanChars ss) 0 spansById)
          * 6
  buf <- ensureTextCapacity r totalVerts
  let writeBoxes boxes spans n0 = foldM (\n tb -> foldM (writeSpanQuads atlas font tb buf) n spans) n0 boxes
  nRootBase <- writeBoxes textBoxes rootBase 0
  nRootOver <- writeBoxes textBoxes rootOver nRootBase
  (spanRanges, nFinal) <-
    foldM
      (\(acc, n0) eid ->
        case IM.lookup eid spansById of
          Nothing -> pure (acc, n0)
          Just ss -> do
            n1 <- writeBoxes [(0, 0, fbW, fbH)] ss n0
            pure (IM.insert eid (n0, n1 - n0) acc, n1))
      (IM.empty, nRootOver)
      effectIds
  c_uploadText h buf (fromIntegral nFinal)
  let rawCmds = drawCommands drawData
      offsets = drawLayerOffsets drawData
      shaderCalls = drawShaderCalls drawData
      uBytes = drawUniformBytes drawData
      drawSpanText eid =
        case IM.lookup eid spanRanges of
          Just (startV, cntV) | cntV > 0 -> c_drawText h (fromIntegral startV) (fromIntegral cntV)
          _ -> pure ()
      drv =
        EffectDriver
          { edScale = scale
          , edFlipY = True
          , edPreparePasses = \passes ->
              pure $
                if all (\i -> isJust (spGlsl150 (scProgram (indexSmallArray passes i)))) [0 .. sizeofSmallArray passes - 1]
                  then Just passes
                  else Nothing
          , edAcquireTarget = acquireGlTarget h
          , edReleaseTarget = c_releaseTarget h . fromIntegral
          , edBindTarget = \slot clr ox oy ->
              (/= 0) <$> c_bindTarget h (fromIntegral slot) (if clr then 1 else 0) ox oy
          , edFlush = pure ()
          , edEmitPlain = \_ cw ch ox oy _ from to ->
              let loop !i = when (i < to) (drawCmd h scale cw ch ox oy shaderCalls uBytes (U.unsafeIndex rawCmds i) >> loop (i + 1))
               in loop from
          , edAfterSpanContent = drawSpanText
          , edCompositePass = \_ sc pd dstW dstH ->
              case epdClip pd of
                Nothing -> compositeGlPass h sc uBytes pd (0, 0, 0, 0, 0)
                Just clipR ->
                  forM_ (physClip scale dstW dstH clipR) $ \(sx0, sy0, sx1, sy1) ->
                    compositeGlPass h sc uBytes pd (1, sx0, sy0, sx1, sy1)
          }
      renderLayer layer =
        let !lo = indexPrimArray offsets (fromEnum layer)
            !hi = indexPrimArray offsets (fromEnum layer + 1)
         in execEffectSpans drv effectSpans 0 (-1) (fbW, fbH) 0 0 mDamage lo hi
  paintInLayerOrder
    renderLayer
    (c_drawText h 0 (fromIntegral nRootBase))
    (c_drawText h (fromIntegral nRootBase) (fromIntegral (nRootOver - nRootBase)))

acquireGlTarget :: Ptr NanoUiGl -> Int -> Int -> IO (Int, Int, Int)
acquireGlTarget h minW minH =
  alloca $ \pW ->
    alloca $ \pH -> do
      slot <- c_acquireTarget h (fromIntegral minW) (fromIntegral minH) pW pH
      if slot < 0
        then pure (-1, 0, 0)
        else do
          cw <- peek pW
          ch <- peek pH
          pure (fromIntegral slot, fromIntegral cw, fromIntegral ch)

{-# NOINLINE compositeGlPass #-}
compositeGlPass ::
  Ptr NanoUiGl ->
  ShaderCall ->
  ByteArray ->
  EffectPassDraw ->
  (Int32, Int, Int, Int, Int) ->
  IO ()
compositeGlPass h sc uniformBytes pd (hasSc, sx0, sy0, sx1, sy1) =
  case spGlsl150 (scProgram sc) of
    Nothing -> pure ()
    Just src -> do
      let srcUtf8 = TE.encodeUtf8 src
          blendCopy = if epdIntermediate pd then 1 else 0 :: Int32
      BSU.unsafeUseAsCStringLen srcUtf8 $ \(srcPtr, srcLen) ->
        withEffectUniforms sc uniformBytes pd $ \uPtr uLen ->
          void $
            c_compositeEffect
              h (fromIntegral (epdSrcSlot pd))
              (epdDstX pd) (epdDstY pd) (epdDstW pd) (epdDstH pd)
              (epdU0 pd) (epdV0 pd) (epdU1 pd) (epdV1 pd)
              hasSc (fromIntegral sx0) (fromIntegral sy0) (fromIntegral sx1) (fromIntegral sy1)
              blendCopy (scHash sc) srcPtr (fromIntegral srcLen)
              uPtr (fromIntegral uLen)

-- | Upload image atlas changes since the last sync: dirty rects, or the
-- whole atlas after a resize or on first use. Call before 'renderArenaGl'
-- with the GL context current.
syncImagesGl :: GlRenderer -> Context -> IO ()
syncImagesGl r ctx = do
  since <- readIORef (glImages r)
  changes <- atlasChanges ctx since
  forM_ changes $ \(w, h, pixels, gen, upload) -> do
    let put whole (x, y, rw, rh) =
          (/= 0) <$> withForeignPtr pixels (\p ->
            c_uploadImages (glHandle r) p (fromIntegral w) (fromIntegral h)
              (fromIntegral x) (fromIntegral y) (fromIntegral rw) (fromIntegral rh) whole)
    ok <- case upload of
      AtlasWhole -> put 1 (0, 0, w, h)
      AtlasRegions rects -> and <$> mapM (put 0) rects
    -- A failed rect upload (no texture yet) forces a full upload next frame.
    writeIORef (glImages r) (if ok then gen else 0)

-- | The retained frame's pixels, for checking what frames drew: RGBA rows,
-- bottom row first, of its bottom-left w x h. Pixels past the last frame's
-- size are undefined.
readRetainedPixels :: GlRenderer -> Int -> Int -> IO BS.ByteString
readRetainedPixels r w h =
  BSI.create (w * h * 4) (c_readRetained (glHandle r) (fromIntegral w) (fromIntegral h))

-- | The window back buffer after the last present, in the same layout as
-- 'readRetainedPixels'. For tests; read before the swap, after which the
-- back buffer is undefined.
readWindowPixels :: GlRenderer -> Int -> Int -> IO BS.ByteString
readWindowPixels r w h =
  BSI.create (w * h * 4) (c_readWindow (glHandle r) (fromIntegral w) (fromIntegral h))

-- | The retained frame as a top-down screenshot. @w@ x @h@ must be the last
-- frame's size; each is clamped to at least 1.
retainedPixels :: GlRenderer -> Int -> Int -> IO (Maybe RgbaPixels)
retainedPixels r w0 h0 = do
  let w = max 1 w0
      h = max 1 h0
      row = w * 4
  bottomUp <- readRetainedPixels r w h
  pixels <- BSI.create (h * row) $ \dst ->
    BSU.unsafeUseAsCString bottomUp $ \src ->
      mapM_ (\y -> copyBytes (dst `plusPtr` (y * row)) (src `plusPtr` ((h - 1 - y) * row)) row) [0 .. h - 1]
  pure (rgbaPixels w h pixels)

-- | The physical pixels a damage rect repaints, as @(x0, y0, x1, y1)@ within
-- a w x h framebuffer. The core paints a clip frame's backdrop one logical
-- pixel past the damage, and the box is the scissor a command clipped to that
-- backdrop gets, so text never lands on a pixel the backdrop left.
damageBox :: Float -> Int -> Int -> Rect -> (Int, Int, Int, Int)
damageBox !scale !w !h = fromMaybe (0, 0, 0, 0) . physClip scale w h . rectInflate 1

drawCmd :: Ptr NanoUiGl -> Float -> Int -> Int -> Float -> Float -> SmallArray ShaderCall -> ByteArray -> DrawCmd -> IO ()
drawCmd h !scale !curW !curH !ox !oy shaderCalls uniformBytes cmd
  | cmdIndexCount cmd < 3 = pure ()
  | otherwise =
      case physClip scale curW curH (Rect (cmdClipX cmd - ox) (cmdClipY cmd - oy) (cmdClipW cmd) (cmdClipH cmd)) of
        Nothing -> pure ()
        Just (x0, y0, x1, y1) ->
          let !shIdx = fromIntegral (cmdShader cmd) :: Int
           in if shIdx > 0 && shIdx <= sizeofSmallArray shaderCalls
                then drawShaderCmd h x0 y0 x1 y1 cmd (indexSmallArray shaderCalls (shIdx - 1)) uniformBytes
                else
                  c_drawGeometry h (fromIntegral x0) (fromIntegral y0) (fromIntegral x1) (fromIntegral y1)
                    (cmdIndexOffset cmd) (cmdIndexCount cmd) (if cmdTextureId cmd == atlasTextureId then 1 else 0)

{-# NOINLINE drawShaderCmd #-}
drawShaderCmd :: Ptr NanoUiGl -> Int -> Int -> Int -> Int -> DrawCmd -> ShaderCall -> ByteArray -> IO ()
drawShaderCmd h x0 y0 x1 y1 cmd sc uniformBytes =
  case spGlsl150 (scProgram sc) of
    Nothing -> pure ()
    Just src -> do
      let srcUtf8 = TE.encodeUtf8 src
          !uOff = scUniformOffset sc
          !uLen = min (scUniformLength sc) (max 0 (sizeofByteArray uniformBytes - uOff))
      BSU.unsafeUseAsCStringLen srcUtf8 $ \(srcPtr, srcLen) ->
        if uLen > 0
          then allocaBytes uLen $ \uPtr -> do
            copyByteArrayToAddr uPtr uniformBytes uOff uLen
            void $
              c_drawShader h (fromIntegral x0) (fromIntegral y0) (fromIntegral x1) (fromIntegral y1)
                (cmdIndexOffset cmd) (cmdIndexCount cmd) (scHash sc) srcPtr (fromIntegral srcLen)
                uPtr (fromIntegral uLen)
          else
            void $
              c_drawShader h (fromIntegral x0) (fromIntegral y0) (fromIntegral x1) (fromIntegral y1)
                (cmdIndexOffset cmd) (cmdIndexCount cmd) (scHash sc) srcPtr (fromIntegral srcLen)
                nullPtr 0

-- | Scale logical x/y/width/height to physical pixels, snapping both edges
-- with half-up rounding. Returns x/y/width/height with non-negative extents.
--
-- The SDL and web backends round a clip outwards instead
-- ('NanoUI.Testing.clipPixelEdges'), to cover the pixels of damage they
-- snapped outwards ('NanoUI.Backend.snapDamage'). This backend snaps no
-- damage: it repaints a logical pixel past it ('damageBox'), and rounds
-- each scissor edge to the pixel 'roundHalfUp' snaps geometry and Cozette
-- glyph pens to, so a scissor edge falls where the shapes it cuts end, and
-- two clips that meet share an edge with no pixel between or under both.
{-# INLINE toPhysRect #-}
toPhysRect :: Float -> Float -> Float -> Float -> Float -> (Int, Int, Int, Int)
toPhysRect !scale !rx !ry !rw !rh =
  let !x0 = roundHalfUp (rx * scale)
      !y0 = roundHalfUp (ry * scale)
      !x1 = roundHalfUp ((rx + rw) * scale)
      !y1 = roundHalfUp ((ry + rh) * scale)
   in (x0, y0, max 0 (x1 - x0), max 0 (y1 - y0))

-- | A logical clip rect scaled to physical pixels and intersected with a
-- w x h target, as @(x0, y0, x1, y1)@ with exclusive ends; 'Nothing' if empty.
{-# INLINE physClip #-}
physClip :: Float -> Int -> Int -> Rect -> Maybe (Int, Int, Int, Int)
physClip !scale !w !h = physClipIn scale (0, 0, w, h)

-- | 'physClip' intersected with a box of physical pixels instead of a target.
{-# INLINE physClipIn #-}
physClipIn :: Float -> (Int, Int, Int, Int) -> Rect -> Maybe (Int, Int, Int, Int)
physClipIn !scale (!bx0, !by0, !bx1, !by1) (Rect x y rw rh) =
  let (!px, !py, !pw, !ph) = toPhysRect scale x y rw rh
      !x0 = max bx0 px
      !y0 = max by0 py
      !x1 = min bx1 (px + pw)
      !y1 = min by1 (py + ph)
   in if x0 >= x1 || y0 >= y1 then Nothing else Just (x0, y0, x1, y1)

-- | Cell grid of one glyph bake. Every glyph owns a 'gaCellW' x 'gaCellH'
-- cell: the footprint 'renderGlyphScaledToBuffer' stamps at 'gaScale'.
data GlyphAtlas = GlyphAtlas
  { gaScale  :: !Float
  , gaCellW  :: !Int
  , gaCellH  :: !Int
  , gaCols   :: !Int
  , gaWidth  :: !Int
  , gaHeight :: !Int
  }
  deriving (Eq, Show)

-- | A roughly square atlas holding every glyph of the font at a scale.
glyphAtlasFor :: CozetteFont -> Float -> GlyphAtlas
glyphAtlasFor font !scale =
  let (!cw, !ch) = cozetteGlyphFootprint scale
      !n = max 1 (cfNumGlyphs font)
      !cols = max 1 (ceiling (sqrt (fromIntegral (n * ch) / fromIntegral cw :: Double)))
      !rows = (n + cols - 1) `quot` cols
   in GlyphAtlas scale cw ch cols (cols * cw) (rows * ch)

-- | Top-left texel of a glyph's cell.
atlasCell :: GlyphAtlas -> Int -> (Int, Int)
atlasCell ga gid =
  let (!row, !col) = gid `quotRem` gaCols ga
   in (col * gaCellW ga, row * gaCellH ga)

-- | Stamp every glyph into its cell with the software blitter, opaque white
-- over transparent black, and hand the pixels to the continuation: each
-- pixel's low byte is its coverage. The pixels are freed afterwards.
bakeGlyphAtlas :: CozetteFont -> GlyphAtlas -> (Ptr Word32 -> IO a) -> IO a
bakeGlyphAtlas font ga k =
  bracket (callocBytes (gaWidth ga * gaHeight ga * 4)) free $ \px -> do
    let go !gid = when (gid < cfNumGlyphs font) $ do
          let (!cx, !cy) = atlasCell ga gid
          renderGlyphScaledToBuffer px (gaWidth ga) cx cy (cx + gaCellW ga) (cy + gaCellH ga)
            (gaScale ga) cx cy 0xFFFFFFFF font (fromIntegral gid)
          go (gid + 1)
    go 0
    k px

ensureAtlas :: GlRenderer -> CozetteFont -> Float -> IO GlyphAtlas
ensureAtlas r font !scale = do
  cur <- readIORef (glAtlas r)
  case cur of
    Just ga | gaScale ga == scale -> pure ga
    _ -> do
      let !ga = glyphAtlasFor font scale
      ok <- bakeGlyphAtlas font ga $ \px ->
        c_uploadAtlas (glHandle r) px (fromIntegral (gaWidth ga)) (fromIntegral (gaHeight ga))
      when (ok == 0) $ fail "nano-ui-rgfw: glyph atlas upload failed"
      writeIORef (glAtlas r) (Just ga)
      pure ga

ensureTextCapacity :: GlRenderer -> Int -> IO (Ptr Word8)
ensureTextCapacity r !needVerts = do
  (p, cap) <- readIORef (glText r)
  if needVerts <= cap
    then pure p
    else do
      let !cap' = maximum [needVerts, cap * 2, 4096]
      p' <- reallocBytes p (cap' * vertexSize)
      writeIORef (glText r) (p', cap')
      pure p'

-- | Upper bound on a span list's glyph count: the UTF-8 byte length, which is
-- O(1) per span.
spanChars :: [TextSpan] -> Int
spanChars = foldl' (\acc (_, t, _, _, _) -> acc + TF.lengthWord8 t) 0

-- | Append a span's glyph quads to a vertex buffer, 6 vertices per glyph in
-- the core's vertex layout: physical-pixel position, span colour, atlas UV.
-- Pen positions are 'foldPenPositions' at the atlas scale. Quads are clipped
-- to the span clip and a box of physical pixels, @(x0, y0, x1, y1)@, with UVs
-- cut to match, so text draws need no scissor. A span whose glyphs all lie
-- outside is skipped without visiting them. The buffer must have room for 6
-- vertices per character; returns the new vertex count.
writeSpanQuads :: GlyphAtlas -> CozetteFont -> (Int, Int, Int, Int) -> Ptr Word8 -> Int -> TextSpan -> IO Int
writeSpanQuads ga font box buf !n0 (Rect rx ry _ _, txt, fg, _, clip) =
  case physClipIn scale box clip of
    Nothing -> pure n0
    Just (cx0, cy0, cx1, cy1)
      -- No pen lies left of or above the span origin, and each line's pen
      -- lies at most 'lineStep' (plus a pixel of rounding) below the last.
      -- Counting lines is left for spans that begin above the box.
      | penX0 >= cx1 || penY0 >= cy1 -> pure n0
      | penY0 + gaCellH ga <= cy0 && penY0 + newlines * lineStep + gaCellH ga + 1 <= cy0 -> pure n0
      | otherwise ->
      let quad !n !penX !penY !glyph =
            let !gid = if fromIntegral glyph < cfNumGlyphs font then fromIntegral glyph else 0
                (!ax, !ay) = atlasCell ga gid
                !x0 = max cx0 penX
                !y0 = max cy0 penY
                !x1 = min cx1 (penX + gaCellW ga)
                !y1 = min cy1 (penY + gaCellH ga)
                u x = fromIntegral (ax + x - penX) / aw
                v y = fromIntegral (ay + y - penY) / ah
             in if x0 >= x1 || y0 >= y1
                  then pure n
                  else do
                    vertex n x0 y0 (u x0) (v y0)
                    vertex (n + 1) x1 y0 (u x1) (v y0)
                    vertex (n + 2) x1 y1 (u x1) (v y1)
                    vertex (n + 3) x0 y0 (u x0) (v y0)
                    vertex (n + 4) x1 y1 (u x1) (v y1)
                    vertex (n + 5) x0 y1 (u x0) (v y1)
                    pure (n + 6)
       in foldPenPositions font scale rx ry n0 quad txt
  where
    !scale = gaScale ga
    !penX0 = roundHalfUp (rx * scale)
    !penY0 = roundHalfUp (ry * scale)
    newlines = T.count "\n" txt
    !lineStep = ceiling (cozetteLineHeight * scale) :: Int
    !aw = fromIntegral (gaWidth ga) :: Float
    !ah = fromIntegral (gaHeight ga) :: Float
    (!fr, !fgG, !fb, !fa) = colorFloats fg
    vertex :: Int -> Int -> Int -> Float -> Float -> IO ()
    vertex !i !x !y !u !v = do
      let !off = i * vertexSize
      pokeByteOff buf off (fromIntegral x :: Float)
      pokeByteOff buf (off + 4) (fromIntegral y :: Float)
      pokeByteOff buf (off + 8) fr
      pokeByteOff buf (off + 12) fgG
      pokeByteOff buf (off + 16) fb
      pokeByteOff buf (off + 20) fa
      pokeByteOff buf (off + 24) u
      pokeByteOff buf (off + 28) v

colorFloats :: Color -> (Float, Float, Float, Float)
colorFloats (Color w) = (chan 24, chan 16, chan 8, chan 0)
  where
    chan s = fromIntegral ((w `shiftR` s) .&. 0xFF) / 255