5bace409102cc965b0cd42db6d4b4a63bec6690c
[raymarcher.git] / raymarch.lua
1 require "Vector"
2 local V = Vector
3
4 require "Primitives"
5 local P = Primitives
6
7 require "Operations"
8 local O = Operations
9
10 require "Textures"
11 local T = Textures
12
13 local eps = 0.01
14 local max_dist2 = 20^2
15 local bg_col = {0.1,0.1,0.1}
16
17 local function calculate_normal(sdf, l)
18    local delta = 1e-3;
19    return V.new{sdf(l+V.x*delta).dist-sdf(l-V.x*delta).dist,
20                 sdf(l+V.y*delta).dist-sdf(l-V.y*delta).dist,
21                 sdf(l+V.z*delta).dist-sdf(l-V.z*delta).dist}/(2*delta)
22 end
23
24 local function march(start, location, ray_dir, sdf, count)
25    if V.norm2(location-start) > max_dist2 then
26       return bg_col
27    end
28    
29    local p = sdf(location)
30    if p.dist < eps then
31       return p.texture(location, ray_dir, calculate_normal(sdf, location-(ray_dir*eps)), count)
32    else
33       return march(start, location + ray_dir*p.dist,
34                    ray_dir, sdf, count+1)
35    end
36 end
37
38 local function render(scene, width, height, filename) 
39    print("Rendering to file " .. filename .. "...")
40    
41    local f = io.open(filename, "w")
42    f:write("P3 ", width, " ", height, " 255\n")
43
44    local c = scene.camera
45    local cam_dir = V.normalize(c.point_at - c.location)
46    local right = V.normalize(c.right)
47    local up = V.cross(right,cam_dir)
48    local aspect = height/width;
49
50    local normalize = V.normalize -- optimization
51    
52    for y=1,height do
53
54       if y % math.floor(height/10) == 0 then
55          print(y/math.floor(height/10) * 10 .. "%")
56       end
57
58       local rayy = cam_dir + up*((0.5 - y/height)*c.fov*aspect)
59
60       for x=1,width do
61          local ray_dir = normalize(rayy + right*((x/width - 0.5)*c.fov))
62          local col = march(c.location, c.location, ray_dir, scene.sdf, 0)
63          col = {math.min(col[1]*255, 255),
64                 math.min(col[2]*255, 255),
65                 math.min(col[3]*255, 255)}
66
67          f:write(math.floor(col[1]), " ", math.floor(col[2]), " ", math.floor(col[3]), " ")
68       end
69       f:write("\n")
70    end
71    f:write("\n")
72
73    f:close()
74
75    print("done")
76 end
77
78
79
80 local scene = {
81    sdf =
82       O.union(
83          P.make_sphere(V.new{0,0,0}, 1,
84                        T.make_phong_texture({V.new{2,-3,1}},
85                           T.make_solid_pigment({0,1,0}),
86                           0.2, 0.7, 1.0, 100)),
87          P.make_plane(V.new{0,0,-3.0}, V.new{0,0,1},
88                       T.make_flat_texture(T.make_checkered_pigment({0,0,1}, {1,1,1})))),
89                                
90    camera = {location = V.new{0,-5,0},
91              point_at = V.new{0,0,0},
92              right = V.new{1,0,0},
93              fov = 1}}
94
95 render(scene, 640, 480, "test.ppm")