Add Ray as a module

This commit is contained in:
Samrat Man Singh 2016-03-11 10:04:09 +05:45
parent 3e0afa04c4
commit ea62b75010
2 changed files with 44 additions and 9 deletions

5
src/ray.ml Normal file
View file

@ -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)

View file

@ -1,14 +1,10 @@
open Core.Std open Core.Std
open Printf open Printf
open Vec3 open Vec3
open Ray
type sphere = { center: Vec3.vec3; type sphere = { center: Vec3.vec3;
radius: float } 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 hit_sphere sphere ray =
let oc = sub ray.origin sphere.center in let oc = sub ray.origin sphere.center in
@ -26,12 +22,46 @@ let get_color ray =
radius = 0.5 } in radius = 0.5 } in
let t = (hit_sphere sphere ray) in let t = (hit_sphere sphere ray) in
if (t > 0.0) 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.)) mul 0.5 (Vec3.of_floats (n.x +. 1., n.y +. 1., n.z +. 1.))
else let unit_direction = unit_vector ray.dir in else let unit_direction = unit_vector ray.dir in
let t = 0.5 *. (unit_direction.y +. 1.0) 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}) 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 main() =
let nx = 200 in let nx = 200 in
@ -67,4 +97,4 @@ let main() =
done done
;; ;;
main() (* main() *)