aboutsummaryrefslogtreecommitdiff
path: root/hitable.go
blob: bc9f9bc4c8af4b15f51e3d21601304f9cbf3cb81 (plain) (blame)
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

package main

import "math"

type HitRecord struct {
	time   float64
	point  Vec3D
	normal Vec3D
}

type Hitable interface {
	Hit(ray Ray, t_min float64, t_max float64) HitRecord
	Normal(point Vec3D, ray Ray) Vec3D
}

type HitableList []Hitable

func (hitable_list HitableList) Hit(ray Ray, t_min float64, t_max float64) HitRecord {
	closest_hit := HitRecord{T_MAX, Vec3D{}, Vec3D{}}
	for _, hitable := range hitable_list {
		hit := hitable.Hit(ray, t_min, closest_hit.time)
		if hit.time > 0 {
			closest_hit = hit
		}
	}
	if closest_hit.time < T_MAX {
		return closest_hit
	} else {
		return HitRecord{}
	}
}

type Sphere struct {
	center Vec3D
	radius float64
}

func (sphere Sphere) Normal(point Vec3D, ray Ray) Vec3D {
	out_normal := SubVec3D(point, sphere.center).Unit()
	if DotProduct(ray.direction, out_normal) < 0.0 {
		return out_normal
	} else {
		return out_normal.Invert()
	}
}

func (sphere Sphere) Hit(ray Ray, t_min float64, t_max float64) HitRecord {
	oc := SubVec3D(ray.origin, sphere.center)
	a := DotProduct(ray.direction, ray.direction)
	b := 2.0 * DotProduct(oc, ray.direction)
	c := DotProduct(oc, oc) - sphere.radius*sphere.radius
	discriminant := b*b - 4*a*c
	if discriminant > 0 {
		root := math.Sqrt(discriminant)
		time := (-b - root) / (2.0 * a)
		if t_min < time && time < t_max {
			point := ray.PointAt(time)
			return HitRecord{time, point, sphere.Normal(point, ray)}
		}
		time = (-b + root) / (2.0 * a)
		if t_min < time && time < t_max {
			point := ray.PointAt(time)
			return HitRecord{time, point, sphere.Normal(point, ray)}
		}
	}
	return HitRecord{}
}