aboutsummaryrefslogtreecommitdiff
path: root/Graphics/Glyph/Textures.hs
blob: 538c87a5e9c7815700793b5006b573053d088ff7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
module Graphics.Glyph.Textures where

import Control.Monad
import Data.Array.Storable
import Data.Word
import Graphics.GL.Compatibility30
import Graphics.Rendering.OpenGL

data Pixels
  = PixelsRGB (Int, Int) (StorableArray Int Word8)
  | PixelsRGBA (Int, Int) (StorableArray Int Word8)

pixelsArray :: Pixels -> StorableArray Int Word8
pixelsArray (PixelsRGB _ a) = a
pixelsArray (PixelsRGBA _ a) = a

-- construct a new 2d array of pixels
makePixelsRGB :: (Int, Int) -> IO Pixels
makePixelsRGB a@(w, h) = liftM (PixelsRGB a) (newArray_ (0, w * h -1))

-- convert a list of rgb values to an array
newPixelsFromListRGB :: (Int, Int) -> [(Word8, Word8, Word8)] -> IO Pixels
newPixelsFromListRGB a@(w, h) lst =
  liftM (PixelsRGB a) $
    ( newListArray (0, w * h * 3)
        . concatMap (\(x, y, z) -> [x, y, z])
    )
      lst

newPixelsFromListRGBA :: (Int, Int) -> [(Word8, Word8, Word8, Word8)] -> IO Pixels
newPixelsFromListRGBA a@(w, h) lst =
  liftM (PixelsRGBA a) $
    newListArray
      (0, w * h * 4)
      (concatMap (\(x, y, z, q) -> [x, y, z, q]) lst)

attachPixelsToTexture :: Pixels -> TextureObject -> IO ()
attachPixelsToTexture pixels tex =
  withStorableArray (pixelsArray pixels) $ \ptr -> do
    textureBinding Texture2D $= Just tex
    case pixels of
      PixelsRGB (w, h) _ -> glTexImage2D GL_TEXTURE_2D 0 3 (f w) (f h) 0 GL_RGB GL_UNSIGNED_BYTE ptr
      PixelsRGBA (w, h) _ -> glTexImage2D GL_TEXTURE_2D 0 4 (f w) (f h) 0 GL_RGBA GL_UNSIGNED_BYTE ptr
  where
    f = fromIntegral