1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
/* Copyright (C) 2024 Aiden Gall
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
struct ray {
float3 orig;
float3 dir;
};
static float3
at(const struct ray ray, const float t)
{
return ray.orig + ray.dir * t;
}
static float
length_squared(const float3 v)
{
return v.x * v.x + v.y * v.y + v.z * v.z;
}
__kernel void
gen_rays(__global float3 *const rays, const float3 camera_centre,
const float3 pixel_delta_u, const float3 pixel_delta_v,
const float3 corner00)
{
size_t idx, w, i, j;
w = get_global_size(0);
i = get_global_id(0);
j = get_global_id(1);
idx = (w * j + i) * 2;
rays[idx] = camera_centre;
rays[idx + 1] = corner00 + ((i * pixel_delta_u) + (j * pixel_delta_v)) -
camera_centre;
}
static float
hit_sphere(const float3 center, const float radius, const struct ray ray)
{
float3 oc;
float a, half_b, c, disc;
oc = ray.orig - center;
a = length_squared(ray.dir);
half_b = dot(oc, ray.dir);
c = length_squared(oc) - radius * radius;
disc = half_b * half_b - a * c;
if (disc < 0.0f)
return -1.0f;
return (-half_b - sqrt(disc)) / a;
}
__kernel void
ray_colour(__global uchar *const canvas, __global const float3 *const rays)
{
struct ray ray;
size_t canvas_idx, ray_idx, w, i, j;
float3 colour;
float t;
w = get_global_size(0);
i = get_global_id(0);
j = get_global_id(1);
canvas_idx = (w * j + i) * 4;
ray_idx = (w * j + i) * 2;
ray.orig = rays[ray_idx];
ray.dir = rays[ray_idx + 1];
t = hit_sphere((float3)(0.0f, 0.0f, -1.0f), 0.5f, ray);
if (t > 0.0) {
colour = 0.5f *
(normalize(at(ray, t) - (float3)(0.0f, 0.0f, -1.0f)) +
1.0f);
} else {
float3 unit_direction;
float a;
unit_direction = normalize(ray.dir);
a = 0.5f * (unit_direction.y + 1.0f);
colour = (1.0f - a) * 1.0f + a * (float3)(0.5f, 0.7f, 1.0f);
}
colour = 256.0f * clamp(sqrt(colour), 0.0f, 0.999f);
canvas[canvas_idx] = colour.x;
canvas[canvas_idx + 1] = colour.y;
canvas[canvas_idx + 2] = colour.z;
canvas[canvas_idx + 3] = 255;
}
|