-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSphere.cpp
More file actions
47 lines (38 loc) · 1.33 KB
/
Sphere.cpp
File metadata and controls
47 lines (38 loc) · 1.33 KB
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
//
// Created by remi on 10/01/25.
//
#include "Sphere.h"
#include <cmath>
#include "Ray.h"
Sphere::Sphere(const Vector& center, double radius, const Vector& albedo): Object(albedo), center(center), radius(radius) {}
Sphere::Sphere(const Vector& center, double radius, const AlbedoFunction& albedo): Object(albedo), center(center), radius(radius) {}
Object::IntersectResult Sphere::intersect(const Ray& ray) const {
double a = 1;
double b = 2 * ray.direction.dot(ray.origin - center);
double c = (ray.origin - center).norm2() - radius * radius;
double delta = b * b - 4 * a * c;
if (delta < 0) { return {}; }
double sqrt_delta = std::sqrt(delta);
double t1 = (-b - sqrt_delta) / 2;
double t2 = (-b + sqrt_delta) / 2;
if (t2 < 0) { return {}; }
double t = t1 > 0 ? t1 : t2;
Vector impact = ray.origin + t * ray.direction;
Vector normal = impact - center;
Vector albedo = hasVariableAlbedo ? albedoFunction(impact) : this->albedo;
return {.impact = impact, .normal = normal.normalized(), .distance = t, .albedo = albedo, .result = true};
}
Sphere& Sphere::mirror() {
this->mirrors = true;
return *this;
}
Sphere& Sphere::transparent(double opticalIndex) {
this->isTransparent = true;
this->opticalIndex = opticalIndex;
return *this;
}
Sphere& Sphere::light(double power) {
this->isLight = true;
this->lightPower = power;
return *this;
}