JSFiddle - React, Tailwind, and code Playground

by blparker

HTML

<canvas id="c"></canvas>

JavaScript

// Originally submitted to a JS1K competition (975 bytes).
// Non-minified source in 35 lines for HN, because it's the latest fad :)
// www.gabrielgambetta.com/tiny_raytracer.html
var w = 500;
var spheres = [w, [ 0, -w, 0],  9, 9, 0,  w,  2,  1, [ 0,  0, 3],  9, 0, 0,  w,  3,  1, [-2,  1, 4],  0, 9, 0,  9,  4,  1, [ 2,  1, 4],  0, 0, 9,  w,  5];
var ambient_light = 2, lights = [8, [2, 2, 0]];
var math = Math, sqrt = math.sqrt, max = math.max, out_idx = 0, canvas = document.getElementById("c"), context2d = canvas.getContext("2d"), image_data = context2d.getImageData(0, 0, w, w), raw_data = image_data.data;
canvas.width = canvas.height = w;
function dot(A, B) { return A[0]*B[0] + A[1]*B[1] + A[2]*B[2]; }
function A_minus_Bk (A, B, k) { return [A[0] - B[0]*k, A[1] - B[1]*k, A[2] - B[2]*k]; }
function closest_intersection(B, D, t_min, t_max) {
  for (t = w, v = q = 0; r = spheres[q++]; q += 6) {  
    a = 2*dot(D, D); b = 2*(dot( C = spheres[q], D) - dot(B, D));
    if ( d = sqrt( b*b - 2*a*(dot(B, B) + dot(C, C) - r*r - 2*dot(B, C)) ) ) {
      for (e = 2; e--; d = -d) {
        f = (b - d)/a; if (t_min < f && f < t_max && f < t) { v = q; t = f; }
      }
    }
  }
  return v;
}
function trace_ray(B, D, t_min, t_max, depth) {
  if (!(s = closest_intersection(B, D, t_min, t_max))) return 0;
  N = A_minus_Bk(X = A_minus_Bk(B, D, -t), spheres[s], 1); n = dot(N, N); i = ambient_light;
  for (l = 0; u = lights[l++]; ) {
    k = dot(N, L = A_minus_Bk(lights[l++], X, 1));
    i += u * !closest_intersection(X, L, 1/w, 1) * (max(0, k / sqrt(dot(L, L)*n)) + max(0, math.pow( dot(M = A_minus_Bk(L, N, 2*k/n), D) / sqrt(dot(M, M)*dot(D, D)), spheres[s+4])));
  }
  var local_color = spheres[s+c]*i*2.8, ref = spheres[s+5]/9;
  return depth-- ? trace_ray(X, A_minus_Bk(D, N, 2*dot(N, D)/n), 1/w, w, depth)*ref + local_color*(1 - ref) : local_color;
}
for (y = h=w/2; y-- > -h;) {
  for (x = -h; x++ < h;) {
    for (c = 0; ++c < 4;) { raw_data[out_idx++] = trace_ray([0, 1, 0], [x/w,...