diff --git a/src/ray.ml b/src/ray.ml new file mode 100644 index 00000000..8a392d1d --- /dev/null +++ b/src/ray.ml @@ -0,0 +1,5 @@ +type ray = { origin: Vec3.vec3; + dir: Vec3.vec3 } + +let point_at_parameter r t = + Vec3.add r.origin (Vec3.mul t r.dir) diff --git a/src/raytracer.ml b/src/raytracer.ml index d30f8f0e..8990ad01 100644 --- a/src/raytracer.ml +++ b/src/raytracer.ml @@ -1,14 +1,10 @@ open Core.Std open Printf open Vec3 - +open Ray + type sphere = { center: Vec3.vec3; radius: float } -type ray = { origin: Vec3.vec3; - dir: Vec3.vec3 } - -let point_at_parameter r t = - add r.origin (mul t r.dir) let hit_sphere sphere ray = let oc = sub ray.origin sphere.center in @@ -26,12 +22,46 @@ let get_color ray = radius = 0.5 } in let t = (hit_sphere sphere ray) in if (t > 0.0) - then let n = unit_vector (sub (point_at_parameter ray t) sphere.center) in + then let n = unit_vector (sub (Ray.point_at_parameter ray t) sphere.center) in mul 0.5 (Vec3.of_floats (n.x +. 1., n.y +. 1., n.z +. 1.)) else let unit_direction = unit_vector ray.dir in let t = 0.5 *. (unit_direction.y +. 1.0) in add (mul (1.0 -. t) {x= 1.0; y=1.0; z= 1.0}) (mul t {x= 0.5; y= 0.7; z= 1.0}) - + +let write_to_file filename = + let nx = 200 in + let ny = 100 in + let oc = Out_channel.create filename in + fprintf oc "P3\n"; + fprintf oc "%d\n" nx; + fprintf oc "%d\n" ny; + fprintf oc "\n255\n"; + let lower_left_corner = Vec3.of_floats (-2., -1., -1.) in + let horizontal = Vec3.of_floats (4., 0., 0.) in + let vertical = Vec3.of_floats (0., 2., 0.) in + let origin = Vec3.of_floats (0., 0., 0.) in + let color = ref {x=0.; y=0.; z=0.} in + for j = ny downto 1 do + for i = 0 to nx-1 do + let u = (Float.of_int i) /. (Float.of_int nx) in + let v = (Float.of_int j) /. (Float.of_int ny) in + + let r = { origin = origin; + dir = Vec3.add lower_left_corner (Vec3.add (Vec3.mul u horizontal) (Vec3.mul v vertical)) } in + color := get_color r; + + let {x=r; y=g; z=b} = !color in + let (ir, ig, ib) = (Int.of_float (r*.255.99), + Int.of_float (g*.255.99), + Int.of_float (b*.255.99)) in + fprintf oc "%d " ir; + fprintf oc "%d " ig; + fprintf oc "%d \n" ib; + done + done; + Out_channel.close oc; +;; + let main() = let nx = 200 in @@ -67,4 +97,4 @@ let main() = done ;; -main() +(* main() *)