clray

view rt.cl @ 4:3c95d568d3c7

wow a ball
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 15 Jul 2010 07:37:05 +0300
parents 88ac4eb2d18a
children 9f0ddb701882
line source
1 struct RendInfo {
2 int xsz, ysz;
3 int num_sph, num_lights;
4 int max_iter;
5 };
7 struct Sphere {
8 float4 pos;
9 float radius;
10 float4 kd, ks;
11 float spow, kr, kt;
12 };
14 struct Light {
15 float4 pos, color;
16 };
18 struct Ray {
19 float4 origin, dir;
20 };
22 struct SurfPoint {
23 float t;
24 float3 pos, norm;
25 global const struct Sphere *obj;
26 };
28 #define EPSILON 1e-6
30 float4 shade(struct Ray ray, struct SurfPoint sp);
31 bool intersect(struct Ray ray, global const struct Sphere *sph, struct SurfPoint *sp);
34 kernel void render(global float4 *fb,
35 global const struct RendInfo *rinf,
36 global const struct Sphere *sphlist,
37 global const struct Light *lights,
38 global const struct Ray *primrays)
39 {
40 int idx = get_global_id(0);
42 struct Ray ray = primrays[idx];
43 struct SurfPoint sp, sp0;
45 sp0.t = FLT_MAX;
47 for(int i=0; i<rinf->num_sph; i++) {
48 if(intersect(ray, sphlist, &sp) && sp.t < sp0.t) {
49 sp0 = sp;
50 }
51 }
53 fb[idx] = shade(ray, sp0);
54 }
56 float4 shade(struct Ray ray, struct SurfPoint sp)
57 {
58 return sp.obj->kd;
59 }
61 bool intersect(struct Ray ray,
62 global const struct Sphere *sph,
63 struct SurfPoint *sp)
64 {
65 float3 dir = ray.dir.xyz;
66 float3 orig = ray.origin.xyz;
67 float3 spos = sph->pos.xyz;
69 float a = dot(dir, dir);
70 float b = 2.0 * dir.x * (orig.x - spos.x) +
71 2.0 * dir.y * (orig.y - spos.y) +
72 2.0 * dir.z * (orig.z - spos.z);
73 float c = dot(spos, spos) + dot(orig, orig) +
74 2.0 * dot(-spos, orig) - sph->radius * sph->radius;
76 float d = b * b - 4.0 * a * c;
77 if(d < 0.0) return false;
79 float sqrt_d = sqrt(d);
80 float t1 = (-b + sqrt_d) / (2.0 * a);
81 float t2 = (-b - sqrt_d) / (2.0 * a);
83 if(t1 < EPSILON) t1 = t2;
84 if(t2 < EPSILON) t2 = t1;
85 float t = t1 < t2 ? t1 : t2;
87 if(t < EPSILON || t > 1.0) {
88 return false;
89 }
91 sp->t = t;
92 sp->pos = orig + dir * sp->t;
93 sp->norm = (sp->pos - spos) / sph->radius;
94 return true;
95 }