summaryrefslogtreecommitdiffstats
path: root/raytracer.hs
blob: 618c7089c41d12ba8e89996b74ec1ad61f3f3a8b (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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import System.IO
import Data.Char
import Debug.Trace
-- ppm image file
-- P3 width height maxcolorval r g b r g b r g b ...
-- max line length: 70


type Angle = Double
type ScreenCoord = (Angle, Angle)
type Color = (Int, Int, Int)
type Coord = (Double, Double, Double)
data Sphere = Sphere Coord Double Color deriving (Show, Eq)

degrees = pi / 180

eye :: Coord
eye = (0, -20, 20)

x_of (x, _, _) = x
y_of (_, y, _) = y
z_of (_, _, z) = z

sphere1 = Sphere (0, 80, 5) 10 (55,255,0)
sphere2 = Sphere (80, 0, 5) 20 (255,60,0)
--sphere3 = Sphere (0, -80, 5) 20 (5,60,200)
--sphere4 = Sphere (-80, 0, 5) 20 (0,255,255)
--spheres = [sphere1, sphere2, sphere3, sphere4]


filename num = "foo/foo" ++ show num ++ ".ppm"

--spherepos = take 1 [0,20..]
spherepos = take 10 [0,36..]

spheres num = [ trace ("Sphere at " ++
                    show (round (80 * sin(num * degrees))) ++ "," ++
                    show (round (80 * cos(num * degrees))) ++ ",5" )
            Sphere (80 * sin(num * degrees), 80 * cos(num * degrees), 5) 10 (255,60,0),
            sphere1, sphere2]

writenum :: Double -> IO ()
writenum num = trace ("Rendering " ++ show (filename $ round num))
               writeFile (filename num) (image $ spheres num)

main = mapM writenum spherepos


alpha1 = 0 * degrees
alpha2 = 360 * degrees

beta1 = 70 * degrees
beta2 = 180 * degrees

floorscale = 4

w = 500
h = 200

oversampling = 1 -- each pixel is 2x2 rays

black :: Color
black = (0,0,0)

ov_alphaoffset = ((alpha2 - alpha1) / (w-1)) / oversampling
ov_betaoffset  = ((beta2 - beta1) / (h-1)) / oversampling

ov_alphaoffsets = take (round oversampling) [0,ov_alphaoffset..]
ov_betaoffsets  = take (round oversampling) [0,ov_betaoffset..]

imgheader = "P3 " ++ (show $ round w) ++ " " ++ (show $ round h) ++ " 255\n"

alphas = take (round w) [alpha1,(alpha1 + ((alpha2 - alpha1) / (w-1)))..]
betas  = take (round h) [beta1,(beta1 + ((beta2 - beta1) / (h-1)))..]


-- spherical projection,
-- return coordinates from a given coordinate, extended by given
-- angles to some distance
spherical_proj :: Coord -> Angle -> Angle -> Double -> Coord
spherical_proj (x,y,z) alpha beta dist = (x + dist*(sin beta * cos alpha),
                                          y + dist*(sin beta * sin alpha),
                                          z + dist*cos beta)


-- intersect sphere

-- discr = 4(( A u + B v + C w )^2 - (A^2 + B^2 + C^2)(u^2 + v^2 + w^2))
discr :: Coord -> ScreenCoord -> Sphere -> Double
discr source (alpha, beta) (Sphere centre radius _) = 4*(( aa * u + bb * v + cc * w )^2 -
                                        (aa*aa + bb*bb + cc*cc)*(u*u + v*v + w*w - radius^2))
      where u = (x_of source) - (x_of centre)
            v = (y_of source) - (y_of centre)
            w = (z_of source) - (z_of centre)
            aa = sin beta * cos alpha
            bb = sin beta * sin alpha
            cc = cos beta

-- the intersect functions return (Coord, Distance, Color)
-- distance = 0 means no intersection
intersect_sphere :: Coord -> ScreenCoord -> Sphere -> (Coord, Double, Color)
intersect_sphere source (alpha, beta) (Sphere centre radius color)
        | delta > 0 = (spherical_proj source alpha beta t, t, color)
        | otherwise = ((0,0,0), 0, black)
            where   t = min ((-b - sqrt(delta)) / (2*a)) ((-b + sqrt(delta)) / (2*a))
                    delta = discr source (alpha, beta) (Sphere centre radius color)
                    a = aa^2 + bb^2 + cc^2
                    b = 2 * (aa*u + bb*v + cc*w)
                    u = (x_of source) - (x_of centre)
                    v = (y_of source) - (y_of centre)
                    w = (z_of source) - (z_of centre)
                    aa = sin beta * cos alpha
                    bb = sin beta * sin alpha
                    cc = cos beta


intersect_point_floor :: Coord -> ScreenCoord -> (Coord, Double)
intersect_point_floor (x, y, z) (alpha, beta) =
                      (  (x - z * sin beta * cos alpha / cos beta,
                          y - z * sin beta * sin alpha / cos beta,
                          0),
                      -z / (cos beta) )

direction_color :: Double -> Double -> Int -> Color
direction_color x y attn
        | x > 0 && y > 0  = (attn, 0, 0) -- red
        | x <= 0 && y > 0 = (0, attn, 0) -- green
        | x > 0 && y <= 0 = (attn, attn, 0) -- yellow
        | otherwise       = (0, 0, attn) -- blue

checkerboard_pattern :: Double -> Double -> Int -> Color
checkerboard_pattern x y attn
        | (round (x/floorscale) `mod` 2) == (round (y/floorscale) `mod` 2) = direction_color x y attn
        | otherwise              = (attn, attn, attn)

intersect_floor :: Coord -> ScreenCoord -> (Coord, Double, Color)
intersect_floor source (alpha, beta)
        | x > (-0.5) && x < 0.5  = ((x, y, z), t, (0, attn, attn)) -- x near 0 : cyan
        | y > (-0.5) && y < 0.5  = ((x, y, z), t, (attn, attn, 0)) -- y near 0 : yellow
        | beta <= 90*degrees     = ((x, y, z), 0, checkerboard_pattern x y 128)
        | otherwise              = ((x, y, z), t, checkerboard_pattern x y attn)
        where   attn = max 0 (round (255 - 8*(sqrt $ abs t)))
                ((x, y, z), t) = intersect_point_floor source (alpha, beta)

-- blue is beautiful, but a green tint is nice too
skycolor :: Coord -> ScreenCoord -> Color
skycolor source (alpha, beta) = (60,
            round ((sqrt (alpha/6)) / (sqrt (90 * degrees)) * 128),
            round ((sqrt (-beta+90*degrees)) / (sqrt (90 * degrees)) * 255) )

data SphereIntersect = SphereIntersect Double Color deriving (Eq, Show) -- distance color
instance Ord SphereIntersect where
  (SphereIntersect d1 _) `compare` (SphereIntersect d2 _)
                        | d2 <= 0 = LT
                        | d1 <= 0 = GT
                        | otherwise = d1 `compare` d2

nearest_sphere :: Coord -> ScreenCoord -> [Sphere] -> SphereIntersect
nearest_sphere source scoord spheres =
                        minimum [(SphereIntersect distance color) | (_, distance, color) <- intersections]
                        where intersections = map (intersect_sphere source scoord) spheres

-- also include floor in objects
nearest_obj :: Coord -> ScreenCoord -> [Sphere] -> (Double, Color)
nearest_obj source scoord spheres
            | floordist == 0 && spheredist > 0           = (spheredist, spherecolor)
            | floordist > spheredist && spheredist > 0   = (spheredist, spherecolor)
            | otherwise                                  = (floordist, floorcolor)
            where   (SphereIntersect spheredist spherecolor)  = nearest_sphere source scoord spheres
                    (_, floordist, floorcolor) = intersect_floor source scoord

-- First iteration
pixel_color :: Coord -> [Sphere] -> ScreenCoord -> Color
pixel_color_only_floor source spheres scoord =  floorcolor
                    where   ((x,y,z), floordist, floorcolor) = intersect_floor source scoord
                            (alpha, beta) = scoord

pixel_color source spheres scoord
            | nearest_object_dist > 0 = objcolor
            | beta == 90 * degrees    = (0, 255, 0)
            | otherwise               = skycolor source scoord
            where   (_, beta) = scoord
                    (nearest_object_dist, objcolor) = nearest_obj source scoord spheres


cartProdTranspose xs ys = [(y,x) | x <- xs, y <- ys]
cartProd xs ys = [(x,y) | x <- xs, y <- ys]

pixel_to_ppm (r,g,b) = show r ++ " " ++ show g ++ " " ++ show b ++ "\n"

tuple2sum x y = (a1 + b1, a2 + b2)
               where (a1, a2) = x
                     (b1, b2) = y

-- from one pixel (alpha, beta), get a list of oversampled pixels
oversample :: ScreenCoord -> [ScreenCoord]
oversample (a,b) = map (tuple2sum (a,b)) (cartProd ov_alphaoffsets ov_betaoffsets)

tuple3sum x y = (a1 + b1, a2 + b2, a3 + b3)
               where (a1, a2, a3) = x
                     (b1, b2, b3) = y

coloraverage :: [Color] -> Color
coloraverage xs = ( round (fromIntegral s1/l),
                    round (fromIntegral s2/l),
                    round (fromIntegral s3/l) )
                    where (s1, s2, s3) = foldr tuple3sum (0,0,0) xs
                          l = fromIntegral (length xs)

-- calculate color of oversampled pixels
ov_color :: [Sphere] -> [ScreenCoord] -> Color
ov_color spheres coords  = coloraverage (map (pixel_color eye spheres) coords)

-- list of list of (alpha, beta)-tuples
ov_pixels = map oversample (cartProdTranspose betas alphas)

allpixels spheres = map (ov_color spheres) ov_pixels

image spheres = imgheader ++ (foldr (++) "" (map pixel_to_ppm (allpixels spheres)))