Google Groups Home
Help | Sign in
Message from discussion Port my ray tracer
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
Jon Harrop  
View profile
 More options 2 Jun 2005, 09:02
Newsgroups: comp.lang.functional
From: Jon Harrop <use...@jdh30.plus.com>
Date: Thu, 02 Jun 2005 09:02:22 +0100
Local: Thurs 2 Jun 2005 09:02
Subject: Re: Port my ray tracer

alex goldman wrote:
> Jon Harrop wrote:

>> C++      1.605s  g++-3.4 -O3 -funroll-all-loops -ffast-math ray.cpp -o
>> ray
>> C        5.971s  gcc-3.4 -lm -std=c99 -O3 -ffast-math ray.c -o ray

> What explains such big difference here?

C does a lot better on AMD64 but I believe the difference is due to the
efficiency of inlined const reference passing of vectors in C++ compared to
the naive approach used by the C code.

Also, the C++ code includes some optimisations not in the C code because it
already exceeded the 100 LOC limit of the shootout. Specifically,
specialised calls for shadow rays. This shaves off another 30% or so.

> Where is the code actually used for benchmarking, BTW?

Here's the OCaml:

(* The Great Computer Language Shootout
   http://shootout.alioth.debian.org/
   Contributed by Jon Harrop, 2005
   Compile: ocamlopt -inline 100 ray.ml -o ray *)

(* This implementation differs from the original in several ways:

   Uses an implicit scene, generated as a ray is traced rather than being
   precalculated and stored explicitly in a tree.

   Specialized shadow-ray intersection functions. *)

let delta = sqrt epsilon_float and pi = 4. *. atan 1.

(* 3D vector and associated functions *)
type vec = {x:float; y:float; z:float}
let ( *| ) s r = {x = s *. r.x; y = s *. r.y; z = s *. r.z}
let ( +| ) a b = {x = a.x +. b.x; y = a.y +. b.y; z = a.z +. b.z}
let ( -| ) a b = {x = a.x -. b.x; y = a.y -. b.y; z = a.z -. b.z}
let dot a b = a.x *. b.x +. a.y *. b.y +. a.z *. b.z
let unitise r = (1. /. sqrt (dot r r)) *| r

(* A semi-infinite ray starting at "orig" and with direction "dir". *)
type ray = { orig: vec; dir: vec }

(* Calculate the parametric intersection of the given ray with the given
sphere. *)
let ray_sphere orig dir center radius =
  let v = center -| orig in
  let b = dot v dir in
  let disc = b *. b -. dot v v +. radius *. radius in
  if disc < 0. then infinity else
    let disc = sqrt disc in
    (fun t2 -> if t2 < 0. then infinity else
       ((fun t1 -> if t1 > 0. then t1 else t2) (b -. disc))) (b +. disc)

(* Calculate whether or not the given ray intersects the given sphere. *)
let ray_sphere' orig dir center radius =
  let v = center -| orig in
  let b = dot v dir in
  let disc = b *. b -. dot v v +. radius *. radius in
  if disc < 0. then false else b +. sqrt disc >= 0.

(* Ratio of the radii of one level of spheres to the next. *)
let s = 6. /. sqrt 12.

(* Find the first intersection point of the given ray with the scene. *)
let intersect level orig dir =
  let rec of_scene center radius lambda normal level =
    if level = 1 then
      let lambda' = ray_sphere orig dir center radius in
      if lambda' >= lambda then lambda, normal else
        lambda', unitise (orig +| lambda' *| dir -| center)
    else
      if ray_sphere orig dir center (3. *. radius) >= lambda
      then lambda, normal else
        let accu = of_scene center radius lambda normal 1 in
        let r = 0.5 *. radius and l = level - 1 in let r' = s *. r in
        let aux dx dz (lambda, normal) =
          of_scene (center +| {x=dx; y=r'; z=dz}) r lambda normal l in
        let mr' = -.r' in
        aux r' mr' (aux r' r' (aux mr' r' (aux mr' mr' accu))) in
  of_scene {x=0.; y= -1.; z=0.} 1. infinity {x=0.; y=0.; z=0.} level

(* Find if the given ray intersects the scene. *)
let intersect' level orig dir =
  let rec of_scene center radius level =
    if level = 1 then ray_sphere' orig dir center radius else
      (* Exploit short-circuit evaluation of boolean comparisons to
terminate
         this function early. *)
      ray_sphere' orig dir center (3. *. radius) &&
        (of_scene center radius 1 ||
           let r = 0.5 *. radius and l = level - 1 in let r' = s *. r in
           of_scene (center +| {x= -.r'; y=r'; z= -.r'}) r l ||
             of_scene (center +| {x= r'; y=r'; z= -.r'}) r l ||
             of_scene (center +| {x= -.r'; y=r'; z= r'}) r l ||
             of_scene (center +| {x= r'; y=r'; z= r'}) r l) in
  of_scene {x=0.; y= -1.; z=0.} 1. level

(* Trace a single ray by casting it into the scene and, if it intersects
   anything, casting a second ray toward the light to determine occlusion.
*)
let rec ray_trace l light orig dir =
  let lambda, n = intersect l orig dir in
  if lambda = infinity then 0. else
    let g = -. dot n light in
    (* If we are on the shadowed side of a sphere then don't bother casting
a
       shadow ray as we know it will intersect the same sphere. *)
    if g <= 0. then 0. else
      let p = orig +| lambda *| dir +| delta *| n in
      if intersect' l p ({x=0.; y=0.; z=0.} -| light) then 0. else g

(* Ray trace the scene at the given resolution. *)
let () =
  (* Resolution *)
  let n = match Sys.argv with [| _; l |] -> int_of_string l | _ -> 256 in
  (* Light direction *)
  let light = unitise {x= -1.; y= -3.; z=2.} in
  (* Number of levels of spheres, and oversampling. *)
  let level = 6 and ss = 4 in

  Printf.printf "P5\n%d %d\n255\n" n n;
  for y = n - 1 downto 0 do
    for x = 0 to n - 1 do
      (* Average each pixel over ss*ss separate rays. *)
      let g = ref 0. in
      for dx = 0 to ss - 1 do
        for dy = 0 to ss - 1 do
          (* Calculate the origin and direction of this ray. *)
          let orig = {x=0.; y=0.; z= -4.} in
          let dir = unitise {x = float (x - n / 2) +. float dx /. float ss;
                             y = float (y - n / 2) +. float dy /. float ss;
                             z = float n} in
          g := !g +. ray_trace level light orig dir
        done
      done;
      let g = int_of_float (0.5 +. 255. *. !g /. float (ss*ss)) in
      Printf.printf "%c" (char_of_int g)
    done
  done

Here's the C++:

// The Great Computer Language Shootout
// http://shootout.alioth.debian.org/
// Contributed by Jon Harrop, 2005
// Compile: g++ -Wall -O3 -ffast-math ray.cpp -o ray

#include <vector>
#include <iostream>
#include <limits>
#include <cmath>

using namespace std;

numeric_limits<double> real;
double delta = sqrt(real.epsilon()), infinity = real.infinity(), pi = M_PI;

// 3D vector
struct Vec {
  double x, y, z;
  Vec(double x2, double y2, double z2) : x(x2), y(y2), z(z2) {}

};

Vec operator+(const Vec &a, const Vec &b)
{ return Vec(a.x + b.x, a.y + b.y, a.z + b.z); }
Vec operator-(const Vec &a, const Vec &b)
{ return Vec(a.x - b.x, a.y - b.y, a.z - b.z); }
Vec operator*(double a, const Vec &b) { return Vec(a * b.x, a * b.y, a *
b.z); }
double dot(const Vec &a, const Vec &b) { return a.x*b.x + a.y*b.y +
a.z*b.z; }
Vec unitise(const Vec &a) { return (1 / sqrt(dot(a, a))) * a; }

// Semi-infinite ray
struct Ray { Vec orig, dir; Ray(Vec o, Vec d) : orig(o), dir(d) {} };

// Scene tree
// In this implementation, a node in the scene tree is represented by a
single
// struct which is either a group of scene trees with a spherical bound or,
// implicitly, a single sphere if the group has no children.
// This is not equivalent to the variant type used to represent a node in
the
// original OCaml implementation because this representation cannot
associate
// data with only leaf nodes (such as color, reflectivity etc.) but requires
// significantly less C++ code and gives room to implement a specialized
// shadow-ray intersection algorithm.
struct Scene {
  vector<Scene> child; // Child nodes in the scene tree
  Vec center; // Center of the sphere or spherical bound
  double radius; // Radius of the sphere or spherical bound

  Scene(Vec c, double r) : child(), center(c), radius(r) {}

};

// Find the first intersection of the given ray with this sphere
double ray_sphere(const Ray &ray, const Scene &s) {
  Vec v = s.center - ray.orig;
  double b = dot(v, ray.dir), disc = b*b - dot(v, v) + s.radius*s.radius;
  if (disc < 0) return infinity;
  double d = sqrt(disc), t2 = b + d;
  if (t2 < 0) return infinity;
  double t1 = b - d;
  return (t1 > 0 ? t1 : t2);

}

// Accumulate the first intersection of the given ray with the given scene
// The accumulated parameter (lambda) and normal vector (normal) are passed
by
// reference to avoid having to define a struct to represent the real return
// type of this function.
void intersect(double &lambda, Vec &normal, const Ray &ray, const Scene &s)
{
  double l = ray_sphere(ray, s);
  // If there is no intersection with this node or if the intersection point
is
  // farther than the current intersection then return as no closer
  // intersection is to be found here.
  if (l >= lambda) return;
  if (s.child.size() == 0) {
    // Intersect with a single sphere
    lambda = l;
    normal = unitise(ray.orig + l * ray.dir - s.center);
  } else
    // Intersect with a group
    for (std::vector<Scene>::const_iterator it=s.child.begin();
         it!=s.child.end(); ++it)
      intersect(lambda, normal, ray, *it);

}

// Find any intersection of the given ray with the given scene
// This function is significantly faster than the above function because it
can
// terminate as soon as any intersection is found.
// This function is distinguished from the above function by its arguments
// (function overloading).
bool intersect(const Ray &ray, const Scene &s) {
  if (ray_sphere(ray, s) == infinity) return false;
  if (s.child.size() == 0) return true; else
    for (std::vector<Scene>::const_iterator it=s.child.begin();
         it != s.child.end(); ++it)
      if (intersect(ray, *it)) return true;
  return false;

}

// Trace a single ray into the scene
double ray_trace(const double weight, const Vec light, const Ray ray,
                 const Scene &s) {
  // As the accumulator is passed to the "intersect" function by reference,
  // they cannot be given inline so they are declared as local variables
here.
  double lambda = infinity;
  Vec normal(0, 0, 0);
  intersect(lambda, normal, ray, s);
  if (lambda == infinity) return 0;
  Vec o = ray.orig + lambda * ray.dir + delta * normal;
  double g = -dot(normal, light);
  // If we are on the shadowed side of a sphere then don't bother casting a
  // shadow ray as we know it will intersect the same sphere.
  if (g <= 0) return 0.;
  return (intersect(Ray(o, Vec(0, 0, 0) - light), s) ? 0 : g);

}

// Recursively build the scene tree
Scene create(int level, double r, double x, double y, double z) {
  if (level == 1) return Scene(Vec(x, y, z), r);
  Scene group = Scene(Vec(x, y, z), 3*r);
  group.child.push_back(Scene(Vec(x, y, z), r));
  double rn = 3*r/sqrt(12.);
  for (int dz=-1; dz<=1; dz+=2)
    for (int dx=-1; dx<=1; dx+=2)
      group.child.push_back(create(level-1, r/2, x-dx*rn, y+rn, z-dz*rn));
  return group;

}

// Build a scene and trace many rays into it, outputting a PGM image
int main(int argc, char *argv[]) {
  // Number of levels of spheres, resolution and oversampling
  int level = 6, n = (argc==2 ? atoi(argv[1]) : 256), ss = 4;
  // Direction of the light
  Vec light = unitise(Vec(-1, -3, 2));
  // Build the scene
  Scene s = create(level, 1, 0, -1, 0);

  std::cout << "P5\n" << n << " " << n << "\n255\n";
  for (int y=n-1; y>=0; --y) {
    for (int x=0; x<n; ++x) {
      double g=0;
      for (int dx=0; dx<ss; ++dx)
        for (int dy=0; dy<ss; ++dy) {
          // We use "dx*1." instead of "double(dx)" to save space
          Vec d(x+dx*1./ss-n/2., y+dy*1./ss-n/2., n);
          g += ray_trace(1, light, Ray(Vec(0, 0, -4), unitise(d)), s);
        }
      std::cout << char(.5 + 255. * g / (ss*ss));
    }
  }

  // In this implementation the Scene destructor recursively deallocates the
  // entire scene for us, obviating the need for manually-defined
destructors.

  return 0;

}

--
Dr Jon D Harrop, Flying Frog Consultancy
http://www.ffconsultancy.com

    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message, you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.

Create a group - Google Groups - Google Home - Terms of Service - Privacy Policy
©2008 Google