BLOG

Notes from the KAYAC hyper-casual team

I Tried CPU-Based Ray Tracing with WebGL2

Takumi Fukasawa

Hello! I'm Fukasawa from the hyper-casual team.

This article is about something I tried as a personal research project, unrelated to my actual work.

A few months ago iOS 15 and macOS Monterey came out, and WebGL2 finally became available by default in Safari on both iOS and macOS. For the web front-end world, this was very welcome news.

Remembering that, I decided to build something with WebGL2 for my Advent Calendar article, and took on something I'd long wanted to try: "ray tracing on the CPU in the browser to display a 3D model".

"CPU-based" here means "doing the ray tracing's pixel calculations on the JavaScript side".

Introduction

In this article I'll focus on how I structured things to implement CPU-based ray tracing in the browser.

So please note up front that there won't be much about ray tracing itself or about its code-level details.

Also, ray tracing in the browser doesn't actually require WebGL2, and in the end there isn't much about WebGL2 in the article either.

For the ray-tracing-related programs I wrote, I mainly referred to Ray Tracing in One Weekend — The Book Series.

What I made

Here it is. The gem-shaped object in the middle is the OBJ data.

The rendered scene with a gem-shaped OBJ model in the middle

This time I also had a secondary goal of "writing everything in a single HTML file", so the only asset is one HTML file. I embedded the OBJ data as text too.

Also, since it runs in the browser, I wanted the picture to respond to interaction, so the camera position follows the mouse position on the Canvas and the picture updates accordingly.

The camera moving with the mouse

I also wanted to aim for a nice-looking picture, so once every pixel has been drawn with the initial number of samples, it raises the sample count and redraws each pixel, again and again. If you leave it alone, the picture gradually becomes cleaner.


Here are the demo and the repository.

Demo

https://takumifukasawa.github.io/js-raytracing-sandbox/for-article.html

Repository

GitHub - takumifukasawa/js-raytracing-sandbox: js-raytracing-sandbox

Approaches to drawing a picture

Graphics APIs

Before getting into ray tracing, let's review how you display something with a graphics API. Graphics APIs generally display things using rasterization. Roughly, the flow is as follows.

Prepare data on where the vertices are
↓
Send it to the GPU via the graphics API
↓
Set the shape to draw it as (points, lines, faces)
↓
Determine the pixel positions on screen via the vertex shader
↓
Determine the colours in the pixel shader

Repeating this outputs a picture to the screen.

(Illustration)

Illustration of rasterization

Ray tracing

Ray tracing, on the other hand, calculates colors using the concept of a ray. A ray has two pieces of information: "from where" and "in which direction". Roughly, the flow is as follows.

Cast a ray from the viewpoint through each pixel towards the scene (what manages what is where)
↓
If it hits something, find where it reflects to
↓
If it hits something again, find where it reflects to
↓
... repeat ...
↓
Stop tracing at some point and determine the colour from the reflection information

(Illustration)

Illustration of ray tracing

Pseudocode would look like this, for example. The loops keep nesting, and you can sense that the amount of computation is going to be very large.

for(let i = 0; i < height; i++) {
  for(let j = 0; j < width; j++) {
    // processing for each pixel
    ...
    // number of samples per pixel. Supersampling
    for(let k = 0; k < sampleCount; k++) {
      // maximum number of bounces to trace
      for(let l = 0; l < maxIterationCount; l++) {
        // trace the ray
      }
    }
  }
}

To sum it up roughly once more, ray tracing is a method of calculation that traces a ray for each pixel and repeats reflections. It comes close to simulating the repeated reflections that happen with real light, so things like the way light falls tend to look more natural. A technique called path tracing gets even closer to a natural look.

This method doesn't actually require a graphics API. This time I used WebGL2, but you can do the same with a Canvas context2d.

As touched on in the pseudocode, the problem with ray tracing is "computation time". The cleaner the picture you want, the more the number of calculations balloons, with more bounces to trace, aliasing to reduce, and so on.

How the ray tracer I built is structured

If you do ray tracing purely in shaders, one way is to prepare a single flat polygon and ray trace each pixel in the shader. The so-called raymarching shader art works this way. This time, the per-pixel calculations are done on the JavaScript side, and WebGL takes care of drawing.

Accumulating the results with off-screen rendering

After calculating the colors on the JavaScript side, the data has to be passed through WebGL somehow and drawn. So I take the approach of drawing the results into a texture with off-screen rendering, and displaying that texture on screen.

For off-screen rendering, you prepare a Framebuffer and a Texture. It's what Three.js and UE4 call a RenderTarget and Unity calls a RenderTexture. Here, following Three.js, I'll call the destination of off-screen rendering a RenderTarget.

1. Generate vertices with position and colour information, one per pixel calculated at once
2. Choose the pixels to update, as many as are calculated at once, and calculate their colours
3. Convert the chosen pixels' positions to clip coordinates, and update the positions and colour information of the vertices generated in 1
4. Draw to the RenderTarget. Don't clear, so the pixels' colours are painted over
5. Choose the next pixels that need updating, as many as are calculated at once
6. ... repeat choosing pixels and drawing

Below is a diagram of the case where 8 pixels are updated at a time. z is always 0, so passing only xy through WebGL would probably have been fine too.

Diagram of updating 8 pixels at a time

In this way, the pixels' colors accumulate.

Pixel colors accumulating in the render target

As in the diagram, I used a VertexArrayObject (VAO) to manage the vertex information. It became standard in WebGL2 and is a handy feature that manages vertex buffers and index buffers together. Since this project was WebGL2-based, I gave VAOs a try.

WebGLVertexArrayObject - Web APIs | MDN

The shaders that draw the vertices representing the calculated pixels just output the vertex position and color they're given as is, so they're very simple.

Vertex shader

#version 300 es
layout(location = 0) in vec3 aPosition;
layout(location = 1) in vec3 aColor;
out vec3 vColor;
void main() {
  vColor = aColor;
  gl_Position = vec4(aPosition, 1);
  gl_PointSize = 1.0;
}

Pixel shader

#version 300 es
precision mediump float;
in vec3 vColor;
out vec4 outColor;
void main() {
  outColor = vec4(vColor, 1);
}

Displaying it on screen

The results can now be stored in the RenderTarget. But since this is off-screen rendering, nothing is on screen yet. All that's left is to display the RenderTarget on screen, though, so this part is simple too.

You prepare a flat polygon covering the whole canvas, pass the RenderTarget's texture as a uniform, and write a shader that displays that texture.

Moving the pixel color calculation to Web Workers

Now for "the amount of computation," the big problem in ray tracing. Since this runs in the browser, with interaction that's as close to real time as possible, it's fine if the picture gets somewhat rough; what I want is a setup where the computation is unlikely to interfere with the controls.

Using Web Workers

JavaScript in the browser basically runs on a single thread (the main thread), so the more heavy computation you do on the CPU, the more the main thread clogs up and blocks, and UI elements become very unresponsive.

So I decided to offload the ray tracing's color calculation to Web Workers. Concretely, the flow is as follows.

1. Send the information needed for ray tracing (number of pixels to update, etc.) with WebWorker.postMessage
2. Calculate in the WebWorker
3. Receive the vertex positions and colour information to update with WebWorker.onmessage
4. Draw to the RenderTarget
5. Back to 1

Using Web Workers - Web APIs | MDN

Here's an excerpt of the Web Worker-related flow. In the implementation, I create several workers.

  ...

  // send to the worker
  const tryExecWorker = async (i) => {
    ...
    /*
     * args: data sent to the worker
     * {
     *   scene, // scene information
     *   camera, // camera information
     *   width, // width
     *   height,  // height
     *   sampleCountPerPixel, // number of supersamples per pixel
     *   maxRayIterationCount, // maximum number of bounces to trace
     *   updatePixelIndexes // array of indices of the pixels to update
     * };
     */
    this.#workers[i].worker.postMessage([args]);
    ...
  }

  // receive from the worker
  worker.onmessage = async (e) => {
    const [args] = e.data;          
    // update the RenderTarget
    this.updatePixels(args);
    tryExecWorker(i)
  };

  updatePixels({ positions, colors }) {
    // per-vertex data comes as nested arrays, so apply flat
    // updateAttribute updates the data with bufferSubData
    this.#pointGeometry.updateAttribute('position', positions.flat());
    this.#pointGeometry.updateAttribute('color', colors.flat());
    this.updateRenderTarget();
    ...
  }
...

// the worker's script
self.onmessage = (e) => {
  const [args] = e.data;
  // calcPixelsColor is the method that calculates colours
  const result = RaytraceRenderer.calcPixelsColor(args);
  postMessage([result]);
}

A caution about the data structures passed to Web Workers

This strays a little from ray tracing.

Web Workers help avoid the problems that heavy computation on the main thread can cause, but they come with caveats and pitfalls.

Namely, some data can be passed and some can't. For example, you can't pass functions to a Web Worker.

Below is an excerpt of MDN's note on the data passed to Web Workers.

Data passed between the main page and workers is copied, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning.

Function objects are one example: if you pass an instance of a class with postMessage, its methods aren't passed (the instance itself is converted into an Object).

Using Web Workers - Web APIs | MDN

The structured clone algorithm - Web APIs | MDN

Running the following in Chrome outputs { hoge: "hogehoge" } as an Object. You can see it's no longer an instance of the class. It seems private fields, like functions, aren't copied either.

class Hoge {
  hoge;
  #fuga;
  constructor(hoge, fuga) {
    this.hoge = hoge;
    this.#fuga = fuga;
  }
  echo() {
    console.log(this.hoge);
    console.log(this.#fuga);
  }
}

const hoge = new Hoge("hogehoge", "fugafuga");

const worker = new Worker(URL.createObjectURL(new Blob([`
self.onmessage = (e) => {
  console.log(e.data[0]); // Object { hoge: "hogehoge" }
}
`])));

worker.postMessage([hoge]);

So you need to be careful with the data structures you pass, and design with that in mind. This time I used lots of private class fields, got bitten by this problem as a result, and ended up making all the related parts public.

What's next

I didn't add search optimization using a BVH or kd-tree this time, so that's what I want to try next. I got partway through implementing a BVH, but I couldn't quite work out how to do a BVH that takes mesh subdivision into account, so I dropped it this time.

I'm also curious how heavy it would be to try path tracing in the browser. Given the computational load I may not be able to hope for much in the way of interaction, but even if it took a while, it would be great fun to get a path-traced picture out of the browser.

References

I've collected them here.

js-raytracing-sandbox/README.md at main · takumifukasawa/js-raytracing-sandbox

Finally

Ray tracing was fun! Thank you for reading this far!

Tomorrow's article is by koluku!