gpuray_glsl

annotate src/sphere.cc @ 2:6e3a4daf3159

adding cones
author John Tsiombikas <nuclear@mutantstargoat.com>
date Sun, 09 Nov 2014 14:39:01 +0200
parents
children 297dbc5080c4
rev   line source
nuclear@0 1 #include <stdio.h>
nuclear@0 2 #include "sphere.h"
nuclear@0 3
nuclear@0 4 Sphere::Sphere()
nuclear@0 5 {
nuclear@0 6 radius = 1.0;
nuclear@0 7 }
nuclear@0 8
nuclear@0 9 Sphere::Sphere(const Vector3 &pos, float rad)
nuclear@0 10 {
nuclear@0 11 radius = rad;
nuclear@0 12 this->pos = pos;
nuclear@0 13 }
nuclear@0 14
nuclear@0 15 bool Sphere::intersect(const Ray &inray, HitPoint *pt) const
nuclear@0 16 {
nuclear@0 17 Ray ray = inray.transformed(inv_xform);
nuclear@0 18
nuclear@0 19 float a = dot_product(ray.dir, ray.dir);
nuclear@0 20 float b = 2.0 * ray.dir.x * (ray.origin.x - pos.x) +
nuclear@0 21 2.0 * ray.dir.y * (ray.origin.y - pos.y) +
nuclear@0 22 2.0 * ray.dir.z * (ray.origin.z - pos.z);
nuclear@0 23 float c = dot_product(ray.origin, ray.origin) + dot_product(pos, pos) -
nuclear@0 24 2.0 * dot_product(ray.origin, pos) - radius * radius;
nuclear@0 25
nuclear@0 26 float discr = b * b - 4.0 * a * c;
nuclear@0 27 if(discr < 1e-4)
nuclear@0 28 return false;
nuclear@0 29
nuclear@0 30 float sqrt_discr = sqrt(discr);
nuclear@0 31 float t0 = (-b + sqrt_discr) / (2.0 * a);
nuclear@0 32 float t1 = (-b - sqrt_discr) / (2.0 * a);
nuclear@0 33
nuclear@0 34 if(t0 < 1e-4)
nuclear@0 35 t0 = t1;
nuclear@0 36 if(t1 < 1e-4)
nuclear@0 37 t1 = t0;
nuclear@0 38
nuclear@0 39 float t = t0 < t1 ? t0 : t1;
nuclear@0 40 if(t < 1e-4)
nuclear@0 41 return false;
nuclear@0 42
nuclear@0 43 // fill the HitPoint structure
nuclear@0 44 pt->obj = this;
nuclear@0 45 pt->dist = t;
nuclear@0 46 pt->pos = ray.origin + ray.dir * t;
nuclear@0 47 pt->normal = (pt->pos - pos) / radius;
nuclear@0 48
nuclear@0 49 pt->pos.transform(xform);
nuclear@0 50 pt->normal.transform(dir_xform);
nuclear@0 51 return true;
nuclear@0 52 }