Render a diffuse sphere

This commit is contained in:
Jean-Michel Gorius 2022-11-11 09:39:51 +01:00
parent d2a6aec56c
commit 0f5b6a756c
5 changed files with 46 additions and 4 deletions

View File

@ -7,6 +7,10 @@ Color color_add(Color c1, Color c2) {
return (Color){c1.r + c2.r, c1.g + c2.g, c1.b + c2.b};
}
Color color_mul(double t, Color c) {
return (Color){t * c.r, t * c.g, t * c.b};
}
Color color_lerp(Color c1, Color c2, double t) {
return (Color){
(1.0 - t) * c1.r + t * c2.r,

View File

@ -8,6 +8,7 @@ typedef struct Color {
} Color;
Color color_add(Color c1, Color c2);
Color color_mul(double t, Color c);
Color color_lerp(Color c1, Color c2, double t);

15
main.c
View File

@ -11,11 +11,17 @@
#include "utils.h"
#include "vec3.h"
Color ray_color(Ray r, Hittable world) {
Color ray_color(Ray r, Hittable world, int depth) {
if (depth <= 0)
return (Color){0, 0, 0};
HitRecord record;
if (hittable_hit(&world, r, 0, DBL_MAX, &record)) {
return (Color){0.5 * (record.normal.x + 1), 0.5 * (record.normal.y + 1),
0.5 * (record.normal.z + 1)};
Point3 target = point3_add(
record.p, vec3_add(record.normal, vec3_random_in_unit_sphere()));
return color_mul(0.5,
ray_color((Ray){record.p, point3_sub(target, record.p)},
world, depth - 1));
}
Vec3 unit_direction = vec3_normalize(r.direction);
double t = 0.5 * (unit_direction.y + 1.0);
@ -30,6 +36,7 @@ int main(void) {
const int image_width = 256;
const int image_height = (int)(image_width / aspect_ratio);
const int samples_per_pixel = 100;
const int max_depth = 50;
/* World */
HittableList object_list = {0};
@ -57,7 +64,7 @@ int main(void) {
double u = (i + random_double()) / (image_width - 1);
double v = (j + random_double()) / (image_height - 1);
Ray r = camera_get_ray(&camera, u, v);
pixel_color = color_add(pixel_color, ray_color(r, world));
pixel_color = color_add(pixel_color, ray_color(r, world, max_depth));
}
color_write(stdout, pixel_color, samples_per_pixel);
}

26
vec3.c
View File

@ -1,4 +1,5 @@
#include "vec3.h"
#include "utils.h"
#include <math.h>
@ -33,3 +34,28 @@ Vec3 vec3_cross(Vec3 v1, Vec3 v2) {
v1.x * v2.y - v1.y * v2.x,
};
}
Vec3 vec3_random(void) {
return (Vec3){
random_double(),
random_double(),
random_double(),
};
}
Vec3 vec3_random_in_range(double min, double max) {
return (Vec3){
random_double_in_range(min, max),
random_double_in_range(min, max),
random_double_in_range(min, max),
};
}
Vec3 vec3_random_in_unit_sphere(void) {
while (1) {
Vec3 result = vec3_random_in_range(-1, 1);
if (vec3_length2(result) >= 1)
continue;
return result;
}
}

4
vec3.h
View File

@ -19,4 +19,8 @@ Vec3 vec3_normalize(Vec3 v);
double vec3_dot(Vec3 v1, Vec3 v2);
Vec3 vec3_cross(Vec3 v1, Vec3 v2);
Vec3 vec3_random(void);
Vec3 vec3_random_in_range(double min, double max);
Vec3 vec3_random_in_unit_sphere(void);
#endif /* INCLUDED_VEC3_H */