5

基于这篇文章,我试图弄清楚如何在 Haskell 中使用 VBO。我试图填写那里没有涵盖的位:

data Sprite = Sprite { spriteImage :: Image
                     , spritePosition :: Position
                     } deriving (Show, Eq)

spriteBatch :: [Sprite] -> [(TextureObject, [Sprite])]
spriteBatch = (map f) . toList . (groupedBy (imageTexture . spriteImage))
    where f (t, s) = (t, s)

offset = plusPtr nullPtr

renderSprites :: [Sprite] -> IO ()
renderSprites l = (flip mapM_) (spriteBatch l) $ \(t, sps) -> do
        textureBinding Texture2D $= Just t
        let l = concat $ map sprToList sps
        vbo <- vboOfList ((length l)*4) l
        displayVbo vbo $ fromIntegral $ length sps
    where
        sprToList :: Sprite -> [GLfloat]
        sprToList (Sprite (Image _ (TexCoord2 u0 v0) (TexCoord2 u1 v1) (Size w h) _) (Position x y)) = 
            [fromIntegral x, fromIntegral y, u0, v0
            ,fromIntegral (x+w), fromIntegral y, u1, v0
            ,fromIntegral (x+w), fromIntegral (y+h), u1, v1
            ,fromIntegral x, fromIntegral (y+h), u0, v1
            ]

vboOfList :: Int -> [GLfloat] -> IO BufferObject
vboOfList size elems = do
    let ptrsize = toEnum $ size * 4
        arrayType = ElementArrayBuffer
    (array:_) <- genObjectNames 1
    bindBuffer arrayType $= Just array
    arr <- newListArray (0, size - 1) elems
    withStorableArray arr $ \ptr -> bufferData arrayType $= (ptrsize, ptr, StaticDraw)
    bindBuffer ArrayBuffer $= Nothing
    return array

displayVbo buff size = do
    let stride = 2*(2*4)
        vxDesc = VertexArrayDescriptor 2 Float stride $ offset 0
        texCoo = VertexArrayDescriptor 2 Float stride $ offset 8
    bindBuffer ArrayBuffer $= Just buff

    arrayPointer VertexArray $= vxDesc
    arrayPointer TextureCoordArray $= texCoo

    clientState VertexArray $= Enabled
    clientState TextureCoordArray $= Enabled

    drawArrays Quads 0 size
    bindBuffer ArrayBuffer $= Nothing

你可以在这里找到完整的代码,以备不时之需。

master 分支上,相同的函数使用普通vertex调用来绘制,Sprites并且它工作得很好。但是使用 VBO,精灵就不存在了。我得到一个空白屏幕。

谁能向我解释我在这里做错了什么?

4

1 回答 1

1

您正在为顶点和 uv 使用一个缓冲区。使用两个缓冲区,一个用于顶点,一个用于 uvs。

于 2013-10-28T08:19:45.717 回答