clray

view src/rt.cc @ 6:b06518bb16e9

adding polygon meshes and obj loading
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 20 Jul 2010 20:02:41 +0100
parents 3c95d568d3c7
children 575383f3a239
line source
1 #include <stdio.h>
2 #include <math.h>
3 #include <assert.h>
4 #include "ocl.h"
6 struct RendInfo {
7 int xsz, ysz;
8 int num_sph, num_lights;
9 int max_iter;
10 } __attribute__((packed));
12 struct Sphere {
13 cl_float4 pos;
14 cl_float4 kd, ks;
15 cl_float radius;
16 cl_float spow;
17 cl_float kr, kt;
18 } __attribute__((packed));
20 struct Ray {
21 cl_float4 origin, dir;
22 } __attribute__((packed));
24 struct Light {
25 cl_float4 pos, color;
26 } __attribute__((packed));
29 static Ray get_primary_ray(int x, int y, int w, int h, float vfov_deg);
31 static Ray *prim_rays;
32 static CLProgram *prog;
33 static int global_size;
35 static Sphere sphlist[] = {
36 {{0, 0, 8, 1}, {0.7, 0.2, 0.15, 1}, {1, 1, 1, 1}, 1.0, 60, 0, 0},
37 {{-0.2, 0.4, 5, 1}, {0.2, 0.9, 0.3, 1}, {1, 1, 1, 1}, 0.25, 40, 0, 0}
38 };
40 static Light lightlist[] = {
41 {{-10, 10, -20, 1}, {1, 1, 1, 1}}
42 };
44 static RendInfo rinf;
47 bool init_renderer(int xsz, int ysz, float *fb)
48 {
49 // render info
50 rinf.xsz = xsz;
51 rinf.ysz = ysz;
52 rinf.num_sph = sizeof sphlist / sizeof *sphlist;
53 rinf.num_lights = sizeof lightlist / sizeof *lightlist;
54 rinf.max_iter = 6;
56 /* calculate primary rays */
57 prim_rays = new Ray[xsz * ysz];
59 for(int i=0; i<ysz; i++) {
60 for(int j=0; j<xsz; j++) {
61 prim_rays[i * xsz + j] = get_primary_ray(j, i, xsz, ysz, 45.0);
62 }
63 }
65 /* setup opencl */
66 prog = new CLProgram("render");
67 if(!prog->load("rt.cl")) {
68 return 1;
69 }
71 /* setup argument buffers */
72 prog->set_arg_buffer(0, ARG_WR, xsz * ysz * 4 * sizeof(float), fb);
73 prog->set_arg_buffer(1, ARG_RD, sizeof rinf, &rinf);
74 prog->set_arg_buffer(2, ARG_RD, sizeof sphlist, sphlist);
75 prog->set_arg_buffer(3, ARG_RD, sizeof lightlist, lightlist);
76 prog->set_arg_buffer(4, ARG_RD, xsz * ysz * sizeof *prim_rays, prim_rays);
78 global_size = xsz * ysz;
79 return true;
80 }
82 void destroy_renderer()
83 {
84 delete [] prim_rays;
85 delete prog;
86 }
88 bool render()
89 {
90 if(!prog->run(1, global_size)) {
91 return false;
92 }
94 CLMemBuffer *mbuf = prog->get_arg_buffer(0);
95 map_mem_buffer(mbuf, MAP_RD);
96 /*if(!write_ppm("out.ppm", fb, xsz, ysz)) {
97 return 1;
98 }*/
99 unmap_mem_buffer(mbuf);
100 return true;
101 }
103 static Ray get_primary_ray(int x, int y, int w, int h, float vfov_deg)
104 {
105 float vfov = M_PI * vfov_deg / 180.0;
106 float aspect = (float)w / (float)h;
108 float ysz = 2.0;
109 float xsz = aspect * ysz;
111 float px = ((float)x / (float)w) * xsz - xsz / 2.0;
112 float py = 1.0 - ((float)y / (float)h) * ysz;
113 float pz = 1.0 / tan(0.5 * vfov);
115 px *= 100.0;
116 py *= 100.0;
117 pz *= 100.0;
119 Ray ray = {{0, 0, 0, 1}, {px, py, pz, 1}};
120 return ray;
121 }