aboutsummaryrefslogtreecommitdiffstats
path: root/src/PFM.hs
blob: f16400fdc8a1f11f2fff8eb6dc7cf4b4279e5575 (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
{-|
Module      : PFM
Description : Debevec PFM reader
Copyright   : (c) 2019, Yann Herklotz Grave
License     : GPL-3
Maintainer  : ymherklotz [at] gmail [dot] com
Stability   : experimental
Portability : POSIX

Debevec PFM reader
-}

module PFM where

import           Control.Applicative        ((<|>))
import           Control.Monad              (void)
import           Data.Attoparsec.ByteString (Parser)
import qualified Data.Attoparsec.ByteString as P
import           Data.Binary.Get            (runGet)
import           Data.Binary.IEEE754        (getFloat32be, getFloat32le)
import           Data.ByteString            (ByteString)
import qualified Data.ByteString            as B
import           Data.ByteString.Lazy       (fromStrict)
import           Data.Text                  (Text)
import qualified Data.Text                  as T
import qualified Data.Text.Encoding         as T
import           Data.Word                  (Word8)

data Image = Image { width  :: Int
                   , height :: Int
                   , colour :: [Colour]
                   } deriving (Show)

data Colour = Colour { r :: Float
                     , g :: Float
                     , b :: Float
                     }
            | Mono Float
            deriving (Show)

matchText :: Text -> Parser ByteString
matchText = P.string . T.encodeUtf8

magicNumMono :: Parser ()
magicNumMono = void $ matchText "Pf"

magicNumRGB :: Parser ()
magicNumRGB = void $ matchText "PF"

skipNewline :: Parser ()
skipNewline = P.skip isNewline
  where
    isNewline w = w == 13 || w == 10

skipSpace :: Parser ()
skipSpace = P.skip (== 32)

decode :: (Read a) => [Word8] -> a
decode = read . T.unpack . T.decodeUtf8 . B.pack

matchMult :: String -> Parser [Word8]
matchMult = P.many1 . P.satisfy . P.inClass

num :: Parser Int
num = decode <$> matchMult "0-9"

endianness :: Parser Float
endianness = decode <$> matchMult "0-9.-"

float :: Parser Float
float = runGet getFloat32le . fromStrict <$> P.take 4

header :: Parser (Int, Int, Float)
header = do
  magicNumRGB
  skipNewline
  n1 <- num
  skipSpace
  n2 <- num
  skipNewline
  s <- endianness
  skipNewline
  return (n1, n2, s)

parseColour :: Parser Colour
parseColour = do
  ri <- float
  gi <- float
  bi <- float
  return $ Colour ri gi bi

parseMono :: Parser Colour
parseMono = Mono <$> float

parser :: Parser Image
parser = do
  (w, h, f) <- header
  c <- P.many1 parseColour
  return $ Image w h c

parse :: ByteString -> IO ()
parse s = case P.parseOnly parser s of
  Left str -> putStrLn str
  Right i  -> print i