-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSphere.java
More file actions
40 lines (35 loc) · 1.16 KB
/
Sphere.java
File metadata and controls
40 lines (35 loc) · 1.16 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
public class Sphere implements Hittable {
private final Point3 center;
private final double radius;
private final Material mat;
public Sphere(Point3 center, double radius, Material mat) {
this.center = center;
this.radius = Math.max(0, radius);
this.mat = mat;
}
@Override
public boolean hit(Ray r, Interval rayT, HitRecord rec) {
Vec3 oc = Vec3.subtract(center, r.origin());
double a = r.direction().lengthSquared();
double h = Vec3.dot(r.direction(), oc);
double c = oc.lengthSquared() - radius * radius;
double discriminant = h * h - a * c;
if (discriminant < 0) {
return false;
}
double sqrtd = Math.sqrt(discriminant);
double root = (h - sqrtd) / a;
if (!rayT.surrounds(root)) {
root = (h + sqrtd) / a;
if (!rayT.surrounds(root)) {
return false;
}
}
rec.t = root;
rec.p = r.at(rec.t);
Vec3 outwardNormal = Vec3.divide(Vec3.subtract(rec.p, center), radius);
rec.setFaceNormal(r, outwardNormal);
rec.mat = mat;
return true;
}
}