clray

view src/rt.cc @ 3:88ac4eb2d18a

added OpenGL display of the framebuffer
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 13 Jul 2010 03:38:29 +0300
parents src/clray.cc@41d6253492ad
children 3c95d568d3c7
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_float radius;
16 cl_float4 color;
17 } __attribute__((packed));
19 struct Ray {
20 cl_float4 origin, dir;
21 } __attribute__((packed));
23 struct Light {
24 cl_float4 pos, color;
25 } __attribute__((packed));
28 static Ray get_primary_ray(int x, int y, int w, int h, float vfov_deg);
30 static Ray *prim_rays;
31 static CLProgram *prog;
32 static int global_size;
34 bool init_renderer(int xsz, int ysz, float *fb)
35 {
36 Sphere sphlist[] = {
37 {{0, 0, 10, 1}, 1.0, {1, 0, 0, 1}}
38 };
39 Light lightlist[] = {
40 {{-10, 10, -20, 1}, {1, 1, 1, 1}}
41 };
42 RendInfo rinf = {
43 xsz, ysz,
44 sizeof sphlist / sizeof *sphlist,
45 sizeof lightlist / sizeof *lightlist,
46 6
47 };
49 /* calculate primary rays */
50 prim_rays = new Ray[xsz * ysz];
52 for(int i=0; i<ysz; i++) {
53 for(int j=0; j<xsz; j++) {
54 prim_rays[i * xsz + j] = get_primary_ray(j, i, xsz, ysz, 45.0);
55 }
56 }
58 /* setup opencl */
59 prog = new CLProgram("render");
60 if(!prog->load("rt.cl")) {
61 return 1;
62 }
64 /* setup argument buffers */
65 prog->set_arg_buffer(0, ARG_WR, xsz * ysz * 4 * sizeof(float), fb);
66 prog->set_arg_buffer(1, ARG_RD, sizeof rinf, &rinf);
67 prog->set_arg_buffer(2, ARG_RD, sizeof sphlist, sphlist);
68 prog->set_arg_buffer(3, ARG_RD, sizeof lightlist, lightlist);
69 prog->set_arg_buffer(4, ARG_RD, xsz * ysz * sizeof *prim_rays, prim_rays);
71 global_size = xsz * ysz;
72 return true;
73 }
75 void destroy_renderer()
76 {
77 delete [] prim_rays;
78 delete prog;
79 }
81 bool render()
82 {
83 if(!prog->run(1, global_size)) {
84 return false;
85 }
87 CLMemBuffer *mbuf = prog->get_arg_buffer(0);
88 map_mem_buffer(mbuf, MAP_RD);
89 /*if(!write_ppm("out.ppm", fb, xsz, ysz)) {
90 return 1;
91 }*/
92 unmap_mem_buffer(mbuf);
93 return true;
94 }
96 static Ray get_primary_ray(int x, int y, int w, int h, float vfov_deg)
97 {
98 float vfov = M_PI * vfov_deg / 180.0;
99 float aspect = (float)w / (float)h;
101 float ysz = 2.0;
102 float xsz = aspect * ysz;
104 float px = ((float)x / (float)w) * xsz - xsz / 2.0;
105 float py = 1.0 - ((float)y / (float)h) * ysz;
106 float pz = 1.0 / tan(0.5 * vfov);
108 pz *= 1000.0;
110 Ray ray = {{0, 0, 0, 1}, {px, py, pz, 1}};
111 return ray;
112 }