-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsphere.go
52 lines (39 loc) · 878 Bytes
/
sphere.go
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
package raytracer
import (
"math"
)
type SphereOptions struct {
Center Point3
Radius float64
Material Material
}
type Sphere struct {
SphereOptions
}
func NewSphere(options SphereOptions) Sphere {
return Sphere{SphereOptions: options}
}
func (s Sphere) Hit(r Ray, rt Interval) (Hit, bool) {
oc := r.Origin.Subtract(s.Center)
a := r.Direction.LengthSquared()
halfB := oc.Dot(r.Direction)
c := oc.LengthSquared() - s.Radius*s.Radius
discriminant := halfB*halfB - a*c
if discriminant < 0 {
return Hit{}, false
}
sqrtd := math.Sqrt(discriminant)
root := (-halfB - sqrtd) / a
if !rt.Surrounds(root) {
root = (-halfB + sqrtd) / a
if !rt.Surrounds(root) {
return Hit{}, false
}
}
var hit Hit
hit.T = root
hit.P = r.At(hit.T)
hit.Material = s.Material
hit.SetFaceNormal(r, hit.P.Subtract(s.Center).Divide(s.Radius))
return hit, true
}