forked from RayTracing/raytracing.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RayTracingInOneWeekend.html
4501 lines (3413 loc) · 199 KB
/
RayTracingInOneWeekend.html
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<meta charset="utf-8">
<link rel="icon" type="image/png" href="../favicon.png">
<!-- Markdeep: https://casual-effects.com/markdeep/ -->
**Ray Tracing in One Weekend**
[Peter Shirley][], [Trevor David Black][], [Steve Hollasch][]
<br>
Version 4.0.0-alpha.2, 2024-04-07
<br>
Copyright 2018-2024 Peter Shirley. All rights reserved.
Overview
====================================================================================================
I’ve taught many graphics classes over the years. Often I do them in ray tracing, because you are
forced to write all the code, but you can still get cool images with no API. I decided to adapt my
course notes into a how-to, to get you to a cool program as quickly as possible. It will not be a
full-featured ray tracer, but it does have the indirect lighting which has made ray tracing a staple
in movies. Follow these steps, and the architecture of the ray tracer you produce will be good for
extending to a more extensive ray tracer if you get excited and want to pursue that.
When somebody says “ray tracing” it could mean many things. What I am going to describe is
technically a path tracer, and a fairly general one. While the code will be pretty simple (let the
computer do the work!) I think you’ll be very happy with the images you can make.
I’ll take you through writing a ray tracer in the order I do it, along with some debugging tips. By
the end, you will have a ray tracer that produces some great images. You should be able to do this
in a weekend. If you take longer, don’t worry about it. I use C++ as the driving language, but you
don’t need to. However, I suggest you do, because it’s fast, portable, and most production movie and
video game renderers are written in C++. Note that I avoid most “modern features” of C++, but
inheritance and operator overloading are too useful for ray tracers to pass on.
> I do not provide the code online, but the code is real and I show all of it except for a few
> straightforward operators in the `vec3` class. I am a big believer in typing in code to learn it,
> but when code is available I use it, so I only practice what I preach when the code is not
> available. So don’t ask!
I have left that last part in because it is funny what a 180 I have done. Several readers ended up
with subtle errors that were helped when we compared code. So please do type in the code, but you
can find the finished source for each book in the [RayTracing project on GitHub][repo].
A note on the implementing code for these books -- our philosophy for the included code prioritizes
the following goals:
- The code should implement the concepts covered in the books.
- We use C++, but as simple as possible. Our programming style is very C-like, but we take
advantage of modern features where it makes the code easier to use or understand.
- Our coding style continues the style established from the original books as much as possible,
for continuity.
- Line length is kept to 96 characters per line, to keep lines consistent between the codebase and
code listings in the books.
The code thus provides a baseline implementation, with tons of improvements left for the reader to
enjoy. There are endless ways one can optimize and modernize the code; we prioritize the simple
solution.
We assume a little bit of familiarity with vectors (like dot product and vector addition). If you
don’t know that, do a little review. If you need that review, or to learn it for the first time,
check out the online [_Graphics Codex_][gfx-codex] by Morgan McGuire, _Fundamentals of Computer
Graphics_ by Steve Marschner and Peter Shirley, or _Computer Graphics: Principles and Practice_
by J.D. Foley and Andy Van Dam.
See the [project README][readme] file for information about this project, the repository on GitHub,
directory structure, building & running, and how to make or reference corrections and contributions.
See [our Further Reading wiki page][wiki-further] for additional project related resources.
These books have been formatted to print well directly from your browser. We also include PDFs of
each book [with each release][releases], in the "Assets" section.
If you want to communicate with us, feel free to send us an email at:
- Peter Shirley, [email protected]
- Steve Hollasch, [email protected]
- Trevor David Black, [email protected]
Finally, if you run into problems with your implementation, have general questions, or would like to
share your own ideas or work, see [the GitHub Discussions forum][discussions] on the GitHub project.
Thanks to everyone who lent a hand on this project. You can find them in the acknowledgments section
at the end of this book.
Let’s get on with it!
Output an Image
====================================================================================================
The PPM Image Format
---------------------
Whenever you start a renderer, you need a way to see an image. The most straightforward way is to
write it to a file. The catch is, there are so many formats. Many of those are complex. I always
start with a plain text ppm file. Here’s a nice description from Wikipedia:
![Figure [ppm]: PPM Example](../images/fig-1.01-ppm.jpg)
<div class='together'>
Let’s make some C++ code to output such a thing:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
#include <iostream>
int main() {
// Image
int image_width = 256;
int image_height = 256;
// Render
std::cout << "P3\n" << image_width << ' ' << image_height << "\n255\n";
for (int j = 0; j < image_height; j++) {
for (int i = 0; i < image_width; i++) {
auto r = double(i) / (image_width-1);
auto g = double(j) / (image_height-1);
auto b = 0.0;
int ir = int(255.999 * r);
int ig = int(255.999 * g);
int ib = int(255.999 * b);
std::cout << ir << ' ' << ig << ' ' << ib << '\n';
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [main-initial]: <kbd>[main.cc]</kbd> Creating your first image]
</div>
There are some things to note in this code:
1. The pixels are written out in rows.
2. Every row of pixels is written out left to right.
3. These rows are written out from top to bottom.
4. By convention, each of the red/green/blue components are represented internally by real-valued
variables that range from 0.0 to 1.0. These must be scaled to integer values between 0 and 255
before we print them out.
5. Red goes from fully off (black) to fully on (bright red) from left to right, and green goes
from fully off at the top (black) to fully on at the bottom (bright green). Adding red and
green light together make yellow so we should expect the bottom right corner to be yellow.
Creating an Image File
-----------------------
Because the file is written to the standard output stream, you'll need to redirect it to an image
file. Typically this is done from the command-line by using the `>` redirection operator.
On Windows, you'd get the debug build from CMake running this command:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cmake -B build
cmake --build build
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Then run your newly-built program like so:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
build\Debug\inOneWeekend.exe > image.ppm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Later, it will be better to run optimized builds for speed. In that case, you would build like this:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cmake --build build --config release
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
and would run the optimized program like this:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
build\Release\inOneWeekend.exe > image.ppm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The examples above assume that you are building with CMake, using the same approach as the
`CMakeLists.txt` file in the included source. Use whatever build environment (and language) you're
most comfortable with.
On Mac or Linux, release build, you would launch the program like this:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
build/inOneWeekend > image.ppm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Complete building and running instructions can be found in the [project README][readme].
Opening the output file (in `ToyViewer` on my Mac, but try it in your favorite image viewer and
Google “ppm viewer” if your viewer doesn’t support it) shows this result:
![<span class='num'>Image 1:</span> First PPM image
](../images/img-1.01-first-ppm-image.png class='pixel')
Hooray! This is the graphics “hello world”. If your image doesn’t look like that, open the output
file in a text editor and see what it looks like. It should start something like this:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
P3
256 256
255
0 0 0
1 0 0
2 0 0
3 0 0
4 0 0
5 0 0
6 0 0
7 0 0
8 0 0
9 0 0
10 0 0
11 0 0
12 0 0
...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [first-img]: First image output]
If your PPM file doesn't look like this, then double-check your formatting code. If it _does_ look
like this but fails to render, then you may have line-ending differences or something similar that
is confusing your image viewer. To help debug this, you can find a file `test.ppm` in the `images`
directory of the Github project. This should help to ensure that your viewer can handle the PPM
format and to use as a comparison against your generated PPM file.
Some readers have reported problems viewing their generated files on Windows. In this case, the
problem is often that the PPM is written out as UTF-16, often from PowerShell. If you run into this
problem, see [Discussion 1114](https://github.com/RayTracing/raytracing.github.io/discussions/1114)
for help with this issue.
If everything displays correctly, then you're pretty much done with system and IDE issues --
everything in the remainder of this series uses this same simple mechanism for generated rendered
images.
If you want to produce other image formats, I am a fan of `stb_image.h`, a header-only image library
available on GitHub at <https://github.com/nothings/stb>.
Adding a Progress Indicator
----------------------------
Before we continue, let's add a progress indicator to our output. This is a handy way to track the
progress of a long render, and also to possibly identify a run that's stalled out due to an infinite
loop or other problem.
<div class='together'>
Our program outputs the image to the standard output stream (`std::cout`), so leave that alone and
instead write to the logging output stream (`std::clog`):
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
for (int j = 0; j < image_height; ++j) {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
std::clog << "\rScanlines remaining: " << (image_height - j) << ' ' << std::flush;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
for (int i = 0; i < image_width; i++) {
auto r = double(i) / (image_width-1);
auto g = double(j) / (image_height-1);
auto b = 0.0;
int ir = int(255.999 * r);
int ig = int(255.999 * g);
int ib = int(255.999 * b);
std::cout << ir << ' ' << ig << ' ' << ib << '\n';
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
std::clog << "\rDone. \n";
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [main-progress]: <kbd>[main.cc]</kbd> Main render loop with progress reporting]
</div>
Now when running, you'll see a running count of the number of scanlines remaining. Hopefully this
runs so fast that you don't even see it! Don't worry -- you'll have lots of time in the future to
watch a slowly updating progress line as we expand our ray tracer.
The vec3 Class
====================================================================================================
Almost all graphics programs have some class(es) for storing geometric vectors and colors. In many
systems these vectors are 4D (3D position plus a homogeneous coordinate for geometry, or RGB plus an
alpha transparency component for colors). For our purposes, three coordinates suffice. We’ll use the
same class `vec3` for colors, locations, directions, offsets, whatever. Some people don’t like this
because it doesn’t prevent you from doing something silly, like subtracting a position from a color.
They have a good point, but we’re going to always take the “less code” route when not obviously
wrong. In spite of this, we do declare two aliases for `vec3`: `point3` and `color`. Since these two
types are just aliases for `vec3`, you won't get warnings if you pass a `color` to a function
expecting a `point3`, and nothing is stopping you from adding a `point3` to a `color`, but it makes
the code a little bit easier to read and to understand.
We define the `vec3` class in the top half of a new `vec3.h` header file, and define a set of useful
vector utility functions in the bottom half:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
#ifndef VEC3_H
#define VEC3_H
#include <cmath>
#include <iostream>
using std::sqrt;
class vec3 {
public:
double e[3];
vec3() : e{0,0,0} {}
vec3(double e0, double e1, double e2) : e{e0, e1, e2} {}
double x() const { return e[0]; }
double y() const { return e[1]; }
double z() const { return e[2]; }
vec3 operator-() const { return vec3(-e[0], -e[1], -e[2]); }
double operator[](int i) const { return e[i]; }
double& operator[](int i) { return e[i]; }
vec3& operator+=(const vec3& v) {
e[0] += v.e[0];
e[1] += v.e[1];
e[2] += v.e[2];
return *this;
}
vec3& operator*=(double t) {
e[0] *= t;
e[1] *= t;
e[2] *= t;
return *this;
}
vec3& operator/=(double t) {
return *this *= 1/t;
}
double length() const {
return sqrt(length_squared());
}
double length_squared() const {
return e[0]*e[0] + e[1]*e[1] + e[2]*e[2];
}
};
// point3 is just an alias for vec3, but useful for geometric clarity in the code.
using point3 = vec3;
// Vector Utility Functions
inline std::ostream& operator<<(std::ostream& out, const vec3& v) {
return out << v.e[0] << ' ' << v.e[1] << ' ' << v.e[2];
}
inline vec3 operator+(const vec3& u, const vec3& v) {
return vec3(u.e[0] + v.e[0], u.e[1] + v.e[1], u.e[2] + v.e[2]);
}
inline vec3 operator-(const vec3& u, const vec3& v) {
return vec3(u.e[0] - v.e[0], u.e[1] - v.e[1], u.e[2] - v.e[2]);
}
inline vec3 operator*(const vec3& u, const vec3& v) {
return vec3(u.e[0] * v.e[0], u.e[1] * v.e[1], u.e[2] * v.e[2]);
}
inline vec3 operator*(double t, const vec3& v) {
return vec3(t*v.e[0], t*v.e[1], t*v.e[2]);
}
inline vec3 operator*(const vec3& v, double t) {
return t * v;
}
inline vec3 operator/(const vec3& v, double t) {
return (1/t) * v;
}
inline double dot(const vec3& u, const vec3& v) {
return u.e[0] * v.e[0]
+ u.e[1] * v.e[1]
+ u.e[2] * v.e[2];
}
inline vec3 cross(const vec3& u, const vec3& v) {
return vec3(u.e[1] * v.e[2] - u.e[2] * v.e[1],
u.e[2] * v.e[0] - u.e[0] * v.e[2],
u.e[0] * v.e[1] - u.e[1] * v.e[0]);
}
inline vec3 unit_vector(const vec3& v) {
return v / v.length();
}
#endif
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [vec3-class]: <kbd>[vec3.h]</kbd> vec3 definitions and helper functions]
We use `double` here, but some ray tracers use `float`. `double` has greater precision and range,
but is twice the size compared to `float`. This increase in size may be important if you're
programming in limited memory conditions (such as hardware shaders). Either one is fine -- follow
your own tastes.
Color Utility Functions
------------------------
Using our new `vec3` class, we'll create a new `color.h` header file and define a utility function
that writes a single pixel's color out to the standard output stream.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
#ifndef COLOR_H
#define COLOR_H
#include "vec3.h"
#include <iostream>
using color = vec3;
void write_color(std::ostream& out, const color& pixel_color) {
auto r = pixel_color.x();
auto g = pixel_color.y();
auto b = pixel_color.z();
// Translate the [0,1] component values to the byte range [0,255].
int rbyte = int(255.999 * r);
int gbyte = int(255.999 * g);
int bbyte = int(255.999 * b);
// Write out the pixel color components.
out << rbyte << ' ' << gbyte << ' ' << bbyte << '\n';
}
#endif
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [color]: <kbd>[color.h]</kbd> color utility functions]
<div class='together'>
Now we can change our main to use both of these:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
#include "color.h"
#include "vec3.h"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
#include <iostream>
int main() {
// Image
int image_width = 256;
int image_height = 256;
// Render
std::cout << "P3\n" << image_width << ' ' << image_height << "\n255\n";
for (int j = 0; j < image_height; j++) {
std::clog << "\rScanlines remaining: " << (image_height - j) << ' ' << std::flush;
for (int i = 0; i < image_width; i++) {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
auto pixel_color = color(double(i)/(image_width-1), double(j)/(image_height-1), 0);
write_color(std::cout, pixel_color);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
}
}
std::clog << "\rDone. \n";
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [ppm-2]: <kbd>[main.cc]</kbd> Final code for the first PPM image]
</div>
And you should get the exact same picture as before.
Rays, a Simple Camera, and Background
====================================================================================================
The ray Class
--------------
The one thing that all ray tracers have is a ray class and a computation of what color is seen along
a ray. Let’s think of a ray as a function $\mathbf{P}(t) = \mathbf{A} + t \mathbf{b}$. Here
$\mathbf{P}$ is a 3D position along a line in 3D. $\mathbf{A}$ is the ray origin and $\mathbf{b}$ is
the ray direction. The ray parameter $t$ is a real number (`double` in the code). Plug in a
different $t$ and $\mathbf{P}(t)$ moves the point along the ray. Add in negative $t$ values and you
can go anywhere on the 3D line. For positive $t$, you get only the parts in front of $\mathbf{A}$,
and this is what is often called a half-line or a ray.
![Figure [lerp]: Linear interpolation](../images/fig-1.02-lerp.jpg)
<div class='together'>
We can represent the idea of a ray as a class, and represent the function $\mathbf{P}(t)$ as a
function that we'll call `ray::at(t)`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
#ifndef RAY_H
#define RAY_H
#include "vec3.h"
class ray {
public:
ray() {}
ray(const point3& origin, const vec3& direction) : orig(origin), dir(direction) {}
const point3& origin() const { return orig; }
const vec3& direction() const { return dir; }
point3 at(double t) const {
return orig + t*dir;
}
private:
point3 orig;
vec3 dir;
};
#endif
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [ray-initial]: <kbd>[ray.h]</kbd> The ray class]
</div>
(For those unfamiliar with C++, the functions `ray::origin()` and `ray::direction()` both return an
immutable reference to their members. Callers can either just use the reference directly, or make a
mutable copy depending on their needs.)
Sending Rays Into the Scene
----------------------------
Now we are ready to turn the corner and make a ray tracer. At its core, a ray tracer sends rays
through pixels and computes the color seen in the direction of those rays. The involved steps are
1. Calculate the ray from the “eye” through the pixel,
2. Determine which objects the ray intersects, and
3. Compute a color for the closest intersection point.
When first developing a ray tracer, I always do a simple camera for getting the code up and running.
I’ve often gotten into trouble using square images for debugging because I transpose $x$ and $y$ too
often, so we’ll use a non-square image. A square image has a 1∶1 aspect ratio, because its
width is the same as its height. Since we want a non-square image, we'll choose 16∶9 because
it's so common. A 16∶9 aspect ratio means that the ratio of image width to image height is
16∶9. Put another way, given an image with a 16∶9 aspect ratio,
$$\text{width} / \text{height} = 16 / 9 = 1.7778$$
For a practical example, an image 800 pixels wide by 400 pixels high has a 2∶1 aspect ratio.
The image's aspect ratio can be determined from the ratio of its height to its width. However, since
we have a given aspect ratio in mind, it's easier to set the image's width and the aspect ratio, and
then using this to calculate for its height. This way, we can scale up or down the image by changing
the image width, and it won't throw off our desired aspect ratio. We do have to make sure that when
we solve for the image height the resulting height is at least 1.
In addition to setting up the pixel dimensions for the rendered image, we also need to set up a
virtual _viewport_ through which to pass our scene rays. The viewport is a virtual rectangle in the
3D world that contains the grid of image pixel locations. If pixels are spaced the same distance
horizontally as they are vertically, the viewport that bounds them will have the same aspect ratio
as the rendered image. The distance between two adjacent pixels is called the pixel spacing, and
square pixels is the standard.
To start things off, we'll choose an arbitrary viewport height of 2.0, and scale the viewport width
to give us the desired aspect ratio. Here's a snippet of what this code will look like:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
auto aspect_ratio = 16.0 / 9.0;
int image_width = 400;
// Calculate the image height, and ensure that it's at least 1.
int image_height = int(image_width / aspect_ratio);
image_height = (image_height < 1) ? 1 : image_height;
// Viewport widths less than one are ok since they are real valued.
auto viewport_height = 2.0;
auto viewport_width = viewport_height * (double(image_width)/image_height);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [image-setup]: Rendered image setup]
If you're wondering why we don't just use `aspect_ratio` when computing `viewport_width`, it's
because the value set to `aspect_ratio` is the ideal ratio, it may not be the _actual_ ratio between
`image_width` and `image_height`. If `image_height` was allowed to be real valued--rather than just
an integer--then it would be fine to use `aspect_ratio`. But the _actual_ ratio between
`image_width` and `image_height` can vary based on two parts of the code. First, `image_height` is
rounded down to the nearest integer, which can increase the ratio. Second, we don't allow
`image_height` to be less than one, which can also change the actual aspect ratio.
Note that `aspect_ratio` is an ideal ratio, which we approximate as best as possible with the
integer-based ratio of image width over image height. In order for our viewport proportions to
exactly match our image proportions, we use the calculated image aspect ratio to determine our final
viewport width.
Next we will define the camera center: a point in 3D space from which all scene rays will originate
(this is also commonly referred to as the _eye point_). The vector from the camera center to the
viewport center will be orthogonal to the viewport. We'll initially set the distance between the
viewport and the camera center point to be one unit. This distance is often referred to as the
_focal length_.
For simplicity we'll start with the camera center at $(0,0,0)$. We'll also have the y-axis go up,
the x-axis to the right, and the negative z-axis pointing in the viewing direction. (This is
commonly referred to as _right-handed coordinates_.)
![Figure [camera-geom]: Camera geometry](../images/fig-1.03-cam-geom.jpg)
Now the inevitable tricky part. While our 3D space has the conventions above, this conflicts with
our image coordinates, where we want to have the zeroth pixel in the top-left and work our way down
to the last pixel at the bottom right. This means that our image coordinate Y-axis is inverted: Y
increases going down the image.
As we scan our image, we will start at the upper left pixel (pixel $0,0$), scan left-to-right across
each row, and then scan row-by-row, top-to-bottom. To help navigate the pixel grid, we'll use a
vector from the left edge to the right edge ($\mathbf{V_u}$), and a vector from the upper edge to
the lower edge ($\mathbf{V_v}$).
Our pixel grid will be inset from the viewport edges by half the pixel-to-pixel distance. This way,
our viewport area is evenly divided into width × height identical regions. Here's what our
viewport and pixel grid look like:
![Figure [pixel-grid]: Viewport and pixel grid](../images/fig-1.04-pixel-grid.jpg)
In this figure, we have the viewport, the pixel grid for a 7×5 resolution image, the viewport
upper left corner $\mathbf{Q}$, the pixel $\mathbf{P_{0,0}}$ location, the viewport vector
$\mathbf{V_u}$ (`viewport_u`), the viewport vector $\mathbf{V_v}$ (`viewport_v`), and the pixel
delta vectors $\mathbf{\Delta u}$ and $\mathbf{\Delta v}$.
<div class='together'>
Drawing from all of this, here's the code that implements the camera. We'll stub in a function
`ray_color(const ray& r)` that returns the color for a given scene ray -- which we'll set to always
return black for now.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
#include "color.h"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
#include "ray.h"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
#include "vec3.h"
#include <iostream>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
color ray_color(const ray& r) {
return color(0,0,0);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
int main() {
// Image
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
auto aspect_ratio = 16.0 / 9.0;
int image_width = 400;
// Calculate the image height, and ensure that it's at least 1.
int image_height = int(image_width / aspect_ratio);
image_height = (image_height < 1) ? 1 : image_height;
// Camera
auto focal_length = 1.0;
auto viewport_height = 2.0;
auto viewport_width = viewport_height * (double(image_width)/image_height);
auto camera_center = point3(0, 0, 0);
// Calculate the vectors across the horizontal and down the vertical viewport edges.
auto viewport_u = vec3(viewport_width, 0, 0);
auto viewport_v = vec3(0, -viewport_height, 0);
// Calculate the horizontal and vertical delta vectors from pixel to pixel.
auto pixel_delta_u = viewport_u / image_width;
auto pixel_delta_v = viewport_v / image_height;
// Calculate the location of the upper left pixel.
auto viewport_upper_left = camera_center
- vec3(0, 0, focal_length) - viewport_u/2 - viewport_v/2;
auto pixel00_loc = viewport_upper_left + 0.5 * (pixel_delta_u + pixel_delta_v);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
// Render
std::cout << "P3\n" << image_width << " " << image_height << "\n255\n";
for (int j = 0; j < image_height; j++) {
std::clog << "\rScanlines remaining: " << (image_height - j) << ' ' << std::flush;
for (int i = 0; i < image_width; i++) {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
auto pixel_center = pixel00_loc + (i * pixel_delta_u) + (j * pixel_delta_v);
auto ray_direction = pixel_center - camera_center;
ray r(camera_center, ray_direction);
color pixel_color = ray_color(r);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
write_color(std::cout, pixel_color);
}
}
std::clog << "\rDone. \n";
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [creating-rays]: <kbd>[main.cc]</kbd> Creating scene rays]
</div>
Notice that in the code above, I didn't make `ray_direction` a unit vector, because I think not
doing that makes for simpler and slightly faster code.
Now we'll fill in the `ray_color(ray)` function to implement a simple gradient. This function will
linearly blend white and blue depending on the height of the $y$ coordinate _after_ scaling the ray
direction to unit length (so $-1.0 < y < 1.0$). Because we're looking at the $y$ height after
normalizing the vector, you'll notice a horizontal gradient to the color in addition to the vertical
gradient.
I'll use a standard graphics trick to linearly scale $0.0 ≤ a ≤ 1.0$. When $a = 1.0$, I want blue.
When $a = 0.0$, I want white. In between, I want a blend. This forms a “linear blend”, or “linear
interpolation”. This is commonly referred to as a _lerp_ between two values. A lerp is always of the
form
$$ \mathit{blendedValue} = (1-a)\cdot\mathit{startValue} + a\cdot\mathit{endValue}, $$
with $a$ going from zero to one.
<div class='together'>
Putting all this together, here's what we get:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
#include "color.h"
#include "ray.h"
#include "vec3.h"
#include <iostream>
color ray_color(const ray& r) {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
vec3 unit_direction = unit_vector(r.direction());
auto a = 0.5*(unit_direction.y() + 1.0);
return (1.0-a)*color(1.0, 1.0, 1.0) + a*color(0.5, 0.7, 1.0);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
}
...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [main-blue-white-blend]: <kbd>[main.cc]</kbd> Rendering a blue-to-white gradient]
</div>
<div class='together'>
In our case this produces:
![<span class='num'>Image 2:</span> A blue-to-white gradient depending on ray Y coordinate
](../images/img-1.02-blue-to-white.png class='pixel')
</div>
Adding a Sphere
====================================================================================================
Let’s add a single object to our ray tracer. People often use spheres in ray tracers because
calculating whether a ray hits a sphere is relatively simple.
Ray-Sphere Intersection
------------------------
The equation for a sphere of radius $r$ that is centered at the origin is an important mathematical
equation:
$$ x^2 + y^2 + z^2 = r^2 $$
You can also think of this as saying that if a given point $(x,y,z)$ is on the surface of the
sphere, then $x^2 + y^2 + z^2 = r^2$. If a given point $(x,y,z)$ is _inside_ the sphere, then
$x^2 + y^2 + z^2 < r^2$, and if a given point $(x,y,z)$ is _outside_ the sphere, then
$x^2 + y^2 + z^2 > r^2$.
If we want to allow the sphere center to be at an arbitrary point $(C_x, C_y, C_z)$, then the
equation becomes a lot less nice:
$$ (C_x - x)^2 + (C_y - y)^2 + (C_z - z)^2 = r^2 $$
In graphics, you almost always want your formulas to be in terms of vectors so that all the
$x$/$y$/$z$ stuff can be simply represented using a `vec3` class. You might note that the vector
from point $\mathbf{P} = (x,y,z)$ to center $\mathbf{C} = (C_x, C_y, C_z)$ is
$(\mathbf{C} - \mathbf{P})$.
If we use the definition of the dot product:
$$ (\mathbf{C} - \mathbf{P}) \cdot (\mathbf{C} - \mathbf{P})
= (C_x - x)^2 + (C_y - y)^2 + (C_z - z)^2
$$
Then we can rewrite the equation of the sphere in vector form as:
$$ (\mathbf{C} - \mathbf{P}) \cdot (\mathbf{C} - \mathbf{P}) = r^2 $$
We can read this as “any point $\mathbf{P}$ that satisfies this equation is on the sphere”. We want
to know if our ray $\mathbf{P}(t) = \mathbf{Q} + t\mathbf{d}$ ever hits the sphere anywhere. If it
does hit the sphere, there is some $t$ for which $\mathbf{P}(t)$ satisfies the sphere equation. So
we are looking for any $t$ where this is true:
$$ (\mathbf{C} - \mathbf{P}(t)) \cdot (\mathbf{C} - \mathbf{P}(t)) = r^2 $$
which can be found by replacing $\mathbf{P}(t)$ with its expanded form:
$$ (\mathbf{C} - (\mathbf{Q} + t \mathbf{d}))
\cdot (\mathbf{C} - (\mathbf{Q} + t \mathbf{d})) = r^2 $$
We have three vectors on the left dotted by three vectors on the right. If we solved for the full
dot product we would get nine vectors. You can definitely go through and write everything out, but
we don't need to work that hard. If you remember, we want to solve for $t$, so we'll separate the
terms based on whether there is a $t$ or not:
$$ (-t \mathbf{d} + (\mathbf{C} - \mathbf{Q})) \cdot (-t \mathbf{d} + (\mathbf{C} - \mathbf{Q}))
= r^2
$$
And now we follow the rules of vector algebra to distribute the dot product:
$$ t^2 \mathbf{d} \cdot \mathbf{d}
- 2t \mathbf{d} \cdot (\mathbf{C} - \mathbf{Q})
+ (\mathbf{C} - \mathbf{Q}) \cdot (\mathbf{C} - \mathbf{Q}) = r^2
$$
Move the square of the radius over to the left hand side:
$$ t^2 \mathbf{d} \cdot \mathbf{d}
- 2t \mathbf{d} \cdot (\mathbf{C} - \mathbf{Q})
+ (\mathbf{C} - \mathbf{Q}) \cdot (\mathbf{C} - \mathbf{Q}) - r^2 = 0
$$
It's hard to make out what exactly this equation is, but the vectors and $r$ in that equation are
all constant and known. Furthermore, the only vectors that we have are reduced to scalars by dot
product. The only unknown is $t$, and we have a $t^2$, which means that this equation is quadratic.
You can solve for a quadratic equation $ax^2 + bx + c = 0$ by using the quadratic formula:
$$ \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$
So solving for $t$ in the ray-sphere intersection equation gives us these values for $a$, $b$, and
$c$:
$$ a = \mathbf{d} \cdot \mathbf{d} $$
$$ b = -2 \mathbf{d} \cdot (\mathbf{C} - \mathbf{Q}) $$
$$ c = (\mathbf{C} - \mathbf{Q}) \cdot (\mathbf{C} - \mathbf{Q}) - r^2 $$
Using all of the above you can solve for $t$, but there is a square root part that can be either
positive (meaning two real solutions), negative (meaning no real solutions), or zero (meaning one
real solution). In graphics, the algebra almost always relates very directly to the geometry. What
we have is:
![Figure [ray-sphere]: Ray-sphere intersection results](../images/fig-1.05-ray-sphere.jpg)
Creating Our First Raytraced Image
-----------------------------------
If we take that math and hard-code it into our program, we can test our code by placing a small
sphere at -1 on the z-axis and then coloring red any pixel that intersects it.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
bool hit_sphere(const point3& center, double radius, const ray& r) {
vec3 oc = center - r.origin();
auto a = dot(r.direction(), r.direction());
auto b = -2.0 * dot(r.direction(), oc);
auto c = dot(oc, oc) - radius*radius;
auto discriminant = b*b - 4*a*c;
return (discriminant >= 0);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
color ray_color(const ray& r) {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
if (hit_sphere(point3(0,0,-1), 0.5, r))
return color(1, 0, 0);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
vec3 unit_direction = unit_vector(r.direction());
auto a = 0.5*(unit_direction.y() + 1.0);
return (1.0-a)*color(1.0, 1.0, 1.0) + a*color(0.5, 0.7, 1.0);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [main-red-sphere]: <kbd>[main.cc]</kbd> Rendering a red sphere]
<div class='together'>
What we get is this:
![<span class='num'>Image 3:</span> A simple red sphere
](../images/img-1.03-red-sphere.png class='pixel')
</div>
Now this lacks all sorts of things -- like shading, reflection rays, and more than one object -- but
we are closer to halfway done than we are to our start! One thing to be aware of is that we are
testing to see if a ray intersects with the sphere by solving the quadratic equation and seeing if a
solution exists, but solutions with negative values of $t$ work just fine. If you change your sphere
center to $z = +1$ you will get exactly the same picture because this solution doesn't distinguish
between objects _in front of the camera_ and objects _behind the camera_. This is not a feature!
We’ll fix those issues next.
Surface Normals and Multiple Objects
====================================================================================================
Shading with Surface Normals
-----------------------------
First, let’s get ourselves a surface normal so we can shade. This is a vector that is perpendicular
to the surface at the point of intersection.
We have a key design decision to make for normal vectors in our code: whether normal vectors will
have an arbitrary length, or will be normalized to unit length.
It is tempting to skip the expensive square root operation involved in normalizing the vector, in
case it's not needed. In practice, however, there are three important observations. First, if a
unit-length normal vector is _ever_ required, then you might as well do it up front once, instead of
over and over again "just in case" for every location where unit-length is required. Second, we _do_
require unit-length normal vectors in several places. Third, if you require normal vectors to be
unit length, then you can often efficiently generate that vector with an understanding of the
specific geometry class, in its constructor, or in the `hit()` function. For example, sphere normals
can be made unit length simply by dividing by the sphere radius, avoiding the square root entirely.
Given all of this, we will adopt the policy that all normal vectors will be of unit length.
For a sphere, the outward normal is in the direction of the hit point minus the center:
![Figure [sphere-normal]: Sphere surface-normal geometry](../images/fig-1.06-sphere-normal.jpg)
On the earth, this means that the vector from the earth’s center to you points straight up. Let’s
throw that into the code now, and shade it. We don’t have any lights or anything yet, so let’s just
visualize the normals with a color map. A common trick used for visualizing normals (because it’s
easy and somewhat intuitive to assume $\mathbf{n}$ is a unit length vector -- so each component is
between -1 and 1) is to map each component to the interval from 0 to 1, and then map $(x, y, z)$ to
$(\mathit{red}, \mathit{green}, \mathit{blue})$. For the normal, we need the hit point, not just
whether we hit or not (which is all we're calculating at the moment). We only have one sphere in the
scene, and it's directly in front of the camera, so we won't worry about negative values of $t$ yet.
We'll just assume the closest hit point (smallest $t$) is the one that we want. These changes in the
code let us compute and visualize $\mathbf{n}$:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
double hit_sphere(const point3& center, double radius, const ray& r) {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
vec3 oc = center - r.origin();
auto a = dot(r.direction(), r.direction());
auto b = -2.0 * dot(r.direction(), oc);
auto c = dot(oc, oc) - radius*radius;
auto discriminant = b*b - 4*a*c;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
if (discriminant < 0) {
return -1.0;
} else {
return (-b - sqrt(discriminant) ) / (2.0*a);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
}
color ray_color(const ray& r) {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++ highlight
auto t = hit_sphere(point3(0,0,-1), 0.5, r);
if (t > 0.0) {
vec3 N = unit_vector(r.at(t) - vec3(0,0,-1));
return 0.5*color(N.x()+1, N.y()+1, N.z()+1);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ C++
vec3 unit_direction = unit_vector(r.direction());
auto a = 0.5*(unit_direction.y() + 1.0);
return (1.0-a)*color(1.0, 1.0, 1.0) + a*color(0.5, 0.7, 1.0);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Listing [render-surface-normal]: <kbd>[main.cc]</kbd> Rendering surface normals on a sphere]
<div class='together'>
And that yields this picture:
![<span class='num'>Image 4:</span> A sphere colored according to its normal vectors
](../images/img-1.04-normals-sphere.png class='pixel')
</div>