Let’s continue working on our ray tracer and pick up where we left off last week. Now that we know how to generate spheres of different materials and know how to look at them from different angles, let’s see how we can generate way more than just 3 spheres.
In pixel.swift let’s create a new random_scene() method:
This method generates roughly 25 smaller spheres and assigns a material to each of them based on a random number that determines whether the sphere material will be lambertian, metal or glass. Then we add each sphere to a list that the function needs to return. We also add the big sphere and the 3 initial smaller spheres we used to have.
Then inside the imageFromPixels() method we replace the code block where we used to add the spheres:
with a single line that creates the random world instead:
I would normally tell you to try rendering the scene now, but there is a great speed up hint I learned from hyperjeff and which allows us to get images of greater quality, much faster. Still inside the imageFromPixels() method, replace the outer loop first line:
with this block of code:
By using Grand Central Dispatch threading, the rendering finishes 3 times faster! In the main playground page, see the generated new image:
This image was generated using a value of ns = 50, a sphere generator range from -7..<7 and an image resolution of 800 x 400. The rendering took 752 seconds to run so if you want a quick, 5-second rendering I suggest using a value of ns = 10, a sphere generator range from -2..<3 and an image resolution of 400 x 200. The source code is posted on Github as usual.