f1dbc3cad42f2c6cf9f64e1f8f85fd812f7f6dc2
[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_dist = 50
15 local bg_col = {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(location, ray_dir, sdf, count)
25    local p = sdf(location)
26    if p.dist < eps then
27       return p.texture(location, ray_dir, calculate_normal(sdf, location-(ray_dir*eps)), count)
28    elseif p.dist > max_dist then
29       return bg_col
30    else
31       return march(location + ray_dir*p.dist,
32                    ray_dir, sdf, count+1)
33    end
34 end
35
36 local function render(scene, width, height, filename) 
37    print("Rendering to file " .. filename .. "...")
38    
39    local f = io.open(filename, "w")
40    f:write("P3 ", width, " ", height, " 255\n")
41
42    local c = scene.camera
43    local cam_dir = V.normalize(c.point_at - c.location)
44    local right = V.normalize(c.right)
45    local up = V.cross(right,cam_dir)
46    local aspect = height/width;
47    
48    for y=1,height do
49
50       if y % math.floor(height/10) == 0 then
51          print(y/math.floor(height/10) * 10 .. "%")
52       end
53
54       local rayy = cam_dir + up*((y/height - 0.5)*c.fov*aspect)
55
56       for x=1,width do
57          local ray_dir = V.normalize(rayy + right*((x/width - 0.5)*c.fov))
58          local col = march(c.location, ray_dir, scene.sdf, 0)
59          col = {math.min(col[1]*255, 255),
60                 math.min(col[2]*255, 255),
61                 math.min(col[3]*255, 255)}
62
63          f:write(math.floor(col[1]), " ", math.floor(col[2]), " ", math.floor(col[3]), " ")
64       end
65       f:write("\n")
66    end
67    f:write("\n")
68
69    f:close()
70
71    print("done")
72 end
73
74
75
76 local scene = {
77    sdf = O.union(P.make_sphere(V.new{0,0,0}, 1,
78                        -- T.make_count_texture()),
79                                T.make_phong({V.new{2,-1,2}}, {0,1,0},
80                                   1.0, 0.5, 100)),
81                  P.make_sphere(V.new{1.5,0,1.0}, 0.5,
82                                T.make_phong({V.new{2,-1,2}}, {0,0,1},
83                                   1.0, 0.5, 100))),
84                                
85    camera = {location = V.new{0,-5,0},
86              point_at = V.new{0,0,0},
87              right = V.new{1,0,0},
88              fov = 1}}
89
90 render(scene, 640, 480, "test.ppm")