-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathchapter_11_worker.js
136 lines (122 loc) · 2.88 KB
/
chapter_11_worker.js
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
onmessage = ({ data }) => {
const scene = new Scene(data.width, data.height)
let { startX, endX } = data
function sendBatch() {
const x = startX
const width = Math.min(x + 10, endX) - x
startX += width
const colors = scene.getColorData(x, width).buffer
postMessage({ x, width, colors }, [ colors ])
if (startX < endX) {
sendBatch()
} else {
postMessage({}) // Done
}
}
sendBatch()
}
class Scene {
constructor(width, height) {
this.width = width
this.height = height
}
*getColors(x, width) {
for (const pixel of this.camera.pixelsForWorld(this.world, x, x + width)) {
yield pixel.color
}
}
getColorData(x, width) {
const { data } = new ImageData(width, this.height)
let index = 0
for (const color of this.getColors(x, width)) {
for (const value of color.rgba) {
data[index++] = value
}
}
return data
}
get camera() {
return Camera.create({
hsize: this.width,
vsize: this.height,
view: Math.PI / 3,
transform: Matrix.viewTransform(
Point(-2.6, 1.5, -3.9),
Point(-0.6, 1, -0.8),
Vector(0, 1, 0)
)
})
}
get world() {
const world = World.of(this.floor, ...this.redSpheres, this.blueGlassSphere, this.greenGlassSphere)
world.light = new PointLight(Point(-4.9, 4.9, -1), Color.WHITE)
return world
}
get floor() {
const pattern = Checkers.of(Color.of(0.35, 0.35, 0.35), Color.of(0.65, 0.65, 0.65))
pattern.transform = Matrix.transform({
rotate: { y: 45 }
})
return Plane.create({
pattern,
reflective: 0.4,
specular: 0
})
}
get redSpheres() {
const material = {
color: Color.of(1, 0.3, 0.2),
specular: 0.4,
shininess: 5,
}
return [
Sphere.create({ ...material,
transform: Matrix.transform({
move: { x: 6, y: 1, z: 4 },
})
}),
Sphere.create({ ...material,
transform: Matrix.transform({
move: { x: 2, y: 1, z: 3 },
})
}),
Sphere.create({ ...material,
transform: Matrix.transform({
move: { x: -1, y: 1, z: 2 },
})
}),
]
}
get blueGlassSphere() {
return Sphere.create({
color: Color.of(0, 0, 0.2),
ambient: 0,
diffuse: 0.4,
specular: 0.9,
shininess: 300,
reflective: 0.9,
transparency: 0.9,
refractive: 1.5,
transform: Matrix.transform({
scale: 0.7,
move: { x: 0.6, y: 0.7, z: -0.6 },
})
})
}
get greenGlassSphere() {
return Sphere.create({
color: Color.of(0, 0.2, 0),
ambient: 0,
diffuse: 0.4,
specular: 0.9,
shininess: 300,
reflective: 0.9,
transparency: 0.9,
refractive: 1.5,
transform: Matrix.transform({
scale: 0.5,
move: { x: -0.7, y: 0.5, z: -0.8 },
})
})
}
}