module Graphics.FreeGame.Data.Bitmap (
Bitmap
,bitmapData
,bitmapHash
,bitmapSize
,loadBitmapFromFile
,toBitmap
,toStableBitmap
,makeStableBitmap
,onBitmap
,onBitmapWithHashable
,cropBitmap
) where
import Control.Applicative
import Codec.Picture.Repa
import Data.Array.Repa as R
import qualified Data.Array.Repa.Repr.ForeignPtr as RF
import Data.Word
import System.Random
import Data.Hashable
data Bitmap = Bitmap {
bitmapData :: R.Array RF.F DIM3 Word8
,bitmapHash :: Maybe Int
}
toBitmap :: R.Array RF.F DIM3 Word8 -> Bitmap
toBitmap ar = Bitmap ar Nothing
toStableBitmap :: R.Array RF.F DIM3 Word8 -> Bitmap
toStableBitmap ar = Bitmap ar $ Just $ head $ foldAllP combine 0 $ R.map fromIntegral ar where
combine p q = hash (p, q)
makeStableBitmap :: R.Array RF.F DIM3 Word8 -> IO Bitmap
makeStableBitmap ar = Bitmap ar <$> Just <$> randomIO
bitmapSize :: Bitmap -> (Int, Int)
bitmapSize bmp = let (Z :. h :. w :. _) = R.extent (bitmapData bmp) in (w, h)
loadBitmapFromFile :: FilePath -> IO Bitmap
loadBitmapFromFile path = readImageRGBA path >>= either fail return >>= makeStableBitmap . imgData
onBitmap :: (R.Array RF.F DIM3 Word8 -> R.Array RF.F DIM3 Word8) -> Bitmap -> Bitmap
onBitmap f = toStableBitmap . f . bitmapData
onBitmapWithHashable :: Hashable h => h -> (R.Array RF.F DIM3 Word8 -> R.Array RF.F DIM3 Word8) -> Bitmap -> Bitmap
onBitmapWithHashable v f (Bitmap ar h) = Bitmap (f ar) (hash <$> (,) v <$> h)
cropBitmap :: Bitmap
-> (Int, Int)
-> (Int, Int)
-> Bitmap
cropBitmap bmp (w, h) (x, y) = onBitmapWithHashable (w,h,x,y) (head . computeP . extract (Z :. y :. x :. 0) (Z :. h :. w :. 4)) bmp