Menger Sponge
A box cut into 27 smaller boxes with seven taken out, then every box that is left cut the same way, and theirs. Four rounds are 160,000 boxes, and the shader makes none of them. It folds space so that every point lands in one small cell, cuts one cross-shaped hole there, and lets a loop repeat the cut at a third of the size. A fire in the middle lights the tunnels, and the sound cuts a bar of time by the same rule.
Teaches Folding space into a fractal, a box cut again and again
Builds on Floating 3D Scene (3D box distance), Kaleidoscope, Molten Metaballs, Ember Tunnel, Mandelbulb
Watch
The idea
Cut a box into 27 smaller boxes, three each way. Take out the one in the middle and the six in the middle of each face. Twenty are left, and what was removed is a cross of three square tunnels running straight through. Now do the same to each of the twenty, and to each of theirs. That is the Menger sponge. Every round leaves 20/27 of what was there, about 74%, so after four rounds 30% of the box remains, and if you never stopped there would be nothing left to weigh, with a surface that has no end.
Four rounds are 20 × 20 × 20 × 20 boxes, 160,000 of them. A shader that listed them would be far too slow, and this one doesn't list one. It asks a different question: for this point, which hole would it be in? Every small box is cut the same way, so the point is moved into one cell that stands for all of them, the cut is made once there, and a loop does it again at a third of the size. Each turn of the loop multiplies the boxes by twenty and costs the same few lines. That is folding space, the trick behind the mirrored wedges of Kaleidoscope and the rings repeated down Ember Tunnel, here used on itself.
The ray is marched as in Floating 3D Scene, and unlike Mandelbulb nothing has to be estimated: a box has an exact distance, and so does a tunnel. It is built in five steps.
Stage 1 · A box
sdBox is the box from Floating 3D Scene, and sponge is, for now, only that: a box 2 wide round the middle of the scene. The camera is 4.6 away, circles the box and rises and falls. Each pixel's ray steps forward by the distance sponge gives, up to 140 times, until it is within half a pixel of the surface: pixel is how wide one pixel is a unit from the camera, so pixel * dist is its width out where the ray is.
The surface's direction comes from four more distances at the corners of a small tetrahedron, and the box is lit like clay, as bright as it faces a light above and to the left of the camera. Everything after this stage changes sponge and leaves the marching alone.
stage-1-a-box.metal
// Stage 1 · A box
// A ray is marched to a box by its distance function, as in Floating 3D Scene, and the box is lit from above the
// camera, which circles it. Everything after this is done to the distance function alone.
// @param speed 0.5 0.0 2.0 How fast the camera circles
// @param heat 0.5 0.0 1.0 Slides the palette from deep ember to white-hot
constant float TAU = 6.2831853;
// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
float3 c0 = float3(0.020, 0.012, 0.020);
float3 c1 = float3(0.280, 0.040, 0.030);
float3 c2 = float3(0.880, 0.260, 0.050);
float3 c3 = float3(1.000, 0.680, 0.200);
float3 c4 = float3(1.000, 0.970, 0.840);
t = clamp(t, 0.0, 1.0);
float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
c = mix(c, c2, smoothstep(0.22, 0.50, t));
c = mix(c, c3, smoothstep(0.50, 0.76, t));
return mix(c, c4, smoothstep(0.76, 1.00, t));
}
// The box from Floating 3D Scene.
float sdBox(float3 p, float3 b) {
float3 d = abs(p) - b;
return length(max(d, 0.0)) + min(max(d.x, max(d.y, d.z)), 0.0);
}
// The sponge will be cut from this: a box 2 wide, for now whole.
float sponge(float3 p) {
return sdBox(p, float3(1.0));
}
// The surface's direction from four samples at a tetrahedron's corners.
float3 spongeNormal(float3 p, float e) {
const float2 k = float2(1.0, -1.0);
return normalize(k.xyy * sponge(p + k.xyy * e)
+ k.yyx * sponge(p + k.yyx * e)
+ k.yxy * sponge(p + k.yxy * e)
+ k.xxx * sponge(p + k.xxx * e));
}
float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
float t = u.time * p.speed;
// The camera circles the box and rises and falls. The pointer's offset
// from the middle (zero in every video) turns it further and tips it.
float2 steer = u.mouse / u.resolution - 0.5;
float yaw = 0.6 + t * 0.26 + steer.x * TAU * 0.5;
float pitch = 0.42 + 0.22 * sin(t * 0.17) + steer.y * 2.0;
pitch = clamp(pitch, -1.4, 1.4);
float3 ro = 4.6 * float3(cos(pitch) * sin(yaw), sin(pitch),
cos(pitch) * cos(yaw));
float3 fw = normalize(-ro);
float3 rt = normalize(cross(fw, float3(0.0, 1.0, 0.0)));
float3 up = cross(rt, fw);
float lens = 2.1;
float side = min(u.resolution.x, u.resolution.y);
float2 q = (uv - 0.5) * u.resolution / side * 2.0;
float3 rd = normalize(q.x * rt + q.y * up + lens * fw);
// How wide one pixel is a unit away from the camera.
float pixel = 2.0 / (side * lens);
float shift = (p.heat - 0.5) * 0.4;
// The kiln's dark behind it, warmer toward the middle of the picture.
float back = 0.05 + 0.09 * exp(-dot(q, q) * 0.7);
// March: step by the distance until the ray is within half a pixel.
float dist = 0.0;
bool hit = false;
for (int i = 0; i < 140; i++) {
float d = sponge(ro + rd * dist);
if (d < pixel * dist * 0.5) { hit = true; break; }
dist += d;
if (dist > 8.0) break;
}
if (!hit) return float4(kiln(back + shift), 1.0);
// Lit like clay: as bright as the surface faces the light, which is
// above and to the left of the camera and goes round with it.
float3 pos = ro + rd * dist;
float3 n = spongeNormal(pos, pixel * dist * 0.5);
float3 l = normalize(up * 0.8 - rt * 0.55 - fw * 0.35);
float lit = max(dot(n, l), 0.0);
return float4(kiln(0.09 + 0.55 * lit + shift), 1.0);
}Stage 2 · One cut
One round. A point is inside a tunnel when at least two of its three coordinates are in the middle third of the box: in the middle of x and y it is in the tunnel that runs along z, whatever its z.
a = 1 − |p| is how far inside the walls the point is on each axis, 0 on a wall and 1 in the middle. r = |1 − 3a| turns that into thirds: under 1 in the outer thirds, over 1 in the middle third. For each pair of axes the code takes the larger r, and bars is the smallest of the three pairs. If bars is under 1, some pair of coordinates is clear of the middle third, and the point is solid. (bars − 1) / 3 is a distance to the tunnels' walls, negative in what stays and positive in the tunnels, and max(d, …) with the box's own distance keeps only what is inside both: the box with the cross cut out.
stage-2-one-cut.metal5 new lines since stage 1
// Stage 2 · One cut
// Cut the box into 27 and take out the middle one and the middle of each face: a cross of three square tunnels. A
// point is in a tunnel when two of its three coordinates are in the middle third. Taking the tunnels away is a max.
// @param speed 0.5 0.0 2.0 How fast the camera circles
// @param heat 0.5 0.0 1.0 Slides the palette from deep ember to white-hot
constant float TAU = 6.2831853;
// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
float3 c0 = float3(0.020, 0.012, 0.020);
float3 c1 = float3(0.280, 0.040, 0.030);
float3 c2 = float3(0.880, 0.260, 0.050);
float3 c3 = float3(1.000, 0.680, 0.200);
float3 c4 = float3(1.000, 0.970, 0.840);
t = clamp(t, 0.0, 1.0);
float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
c = mix(c, c2, smoothstep(0.22, 0.50, t));
c = mix(c, c3, smoothstep(0.50, 0.76, t));
return mix(c, c4, smoothstep(0.76, 1.00, t));
}
// The box from Floating 3D Scene.
float sdBox(float3 p, float3 b) {
float3 d = abs(p) - b;
return length(max(d, 0.0)) + min(max(d.x, max(d.y, d.z)), 0.0);
}
// One cut: a cross of three square tunnels through the box.
float sponge(float3 p) {
float d = sdBox(p, float3(1.0));
// How far inside the walls p is on each axis: 0 at a wall, 1 mid-box.
float3 a = 1.0 - abs(p);
// Under 1 in the outer thirds, over 1 in the middle third.
float3 r = abs(1.0 - 3.0 * abs(a));
// Under 1 where two axes are clear of the middle third: solid.
float bars = min(max(r.x, r.y), min(max(r.y, r.z), max(r.z, r.x)));
// A third of that is a distance; max() cuts the tunnels away.
return max(d, (bars - 1.0) / 3.0);
}
// The surface's direction from four samples at a tetrahedron's corners.
float3 spongeNormal(float3 p, float e) {
const float2 k = float2(1.0, -1.0);
return normalize(k.xyy * sponge(p + k.xyy * e)
+ k.yyx * sponge(p + k.yyx * e)
+ k.yxy * sponge(p + k.yxy * e)
+ k.xxx * sponge(p + k.xxx * e));
}
float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
float t = u.time * p.speed;
// The camera circles the box and rises and falls. The pointer's offset
// from the middle (zero in every video) turns it further and tips it.
float2 steer = u.mouse / u.resolution - 0.5;
float yaw = 0.6 + t * 0.26 + steer.x * TAU * 0.5;
float pitch = 0.42 + 0.22 * sin(t * 0.17) + steer.y * 2.0;
pitch = clamp(pitch, -1.4, 1.4);
float3 ro = 4.6 * float3(cos(pitch) * sin(yaw), sin(pitch),
cos(pitch) * cos(yaw));
float3 fw = normalize(-ro);
float3 rt = normalize(cross(fw, float3(0.0, 1.0, 0.0)));
float3 up = cross(rt, fw);
float lens = 2.1;
float side = min(u.resolution.x, u.resolution.y);
float2 q = (uv - 0.5) * u.resolution / side * 2.0;
float3 rd = normalize(q.x * rt + q.y * up + lens * fw);
// How wide one pixel is a unit away from the camera.
float pixel = 2.0 / (side * lens);
float shift = (p.heat - 0.5) * 0.4;
// The kiln's dark behind it, warmer toward the middle of the picture.
float back = 0.05 + 0.09 * exp(-dot(q, q) * 0.7);
// March: step by the distance until the ray is within half a pixel.
float dist = 0.0;
bool hit = false;
for (int i = 0; i < 140; i++) {
float d = sponge(ro + rd * dist);
if (d < pixel * dist * 0.5) { hit = true; break; }
dist += d;
if (dist > 8.0) break;
}
if (!hit) return float4(kiln(back + shift), 1.0);
// Lit like clay: as bright as the surface faces the light, which is
// above and to the left of the camera and goes round with it.
float3 pos = ro + rd * dist;
float3 n = spongeNormal(pos, pixel * dist * 0.5);
float3 l = normalize(up * 0.8 - rt * 0.55 - fw * 0.35);
float lit = max(dot(n, l), 0.0);
return float4(kiln(0.09 + 0.55 * lit + shift), 1.0);
}1 line from stage 1 that are gone
return sdBox(p, float3(1.0));Stage 3 · The fold
The line that makes it a fractal is a = p * s − 2 * floor(p * s * 0.5) − 1. It cuts space into cells 2/s wide and gives every point its place inside its own cell, the same numbers whichever cell it is in. With s at 1 the cell is the whole box and a measures what stage 2's did. Then s is multiplied by 3: the cells are a third the size, 27 of them in the box, and the same two lines cut a cross in every one. Again, and there are 729.
Tunnels made in a cell are s times smaller out in the picture, so the distance is divided by s before the max. depth says how many turns the loop takes, rounded to a whole number here, and the loop itself can take up to 8. With depth at 4 the picture holds 160,000 boxes and sponge has run four turns of a loop for each step of the ray. The small holes on the far faces shimmer, because they are smaller than a pixel. The last stage deals with that.
stage-3-the-fold.metal17 new lines since stage 2
// Stage 3 · The fold
// The same cut in every smaller box, without visiting one of them. Folding space puts every point into one cell, the
// cut is made there, and a loop repeats it at a third of the size. Four turns of the loop are 160,000 boxes.
// @param speed 0.5 0.0 2.0 How fast the camera circles
// @param depth 4.0 1.0 5.0 How many times the box is cut: 1 is one cross of holes, each one more cuts every piece again
// @param heat 0.5 0.0 1.0 Slides the palette from deep ember to white-hot
constant float TAU = 6.2831853;
// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
float3 c0 = float3(0.020, 0.012, 0.020);
float3 c1 = float3(0.280, 0.040, 0.030);
float3 c2 = float3(0.880, 0.260, 0.050);
float3 c3 = float3(1.000, 0.680, 0.200);
float3 c4 = float3(1.000, 0.970, 0.840);
t = clamp(t, 0.0, 1.0);
float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
c = mix(c, c2, smoothstep(0.22, 0.50, t));
c = mix(c, c3, smoothstep(0.50, 0.76, t));
return mix(c, c4, smoothstep(0.76, 1.00, t));
}
// The box from Floating 3D Scene.
float sdBox(float3 p, float3 b) {
float3 d = abs(p) - b;
return length(max(d, 0.0)) + min(max(d.x, max(d.y, d.z)), 0.0);
}
// The fold: the same cut in every smaller box. Each turn of the loop
// cuts every piece the last one left: 1 cell, then 27, then 729.
float sponge(float3 p, int cuts) {
float d = sdBox(p, float3(1.0));
float s = 1.0;
for (int m = 0; m < 8; m++) {
if (m >= cuts) break;
// Cells 2/s wide; `a` is p's place in its own cell, alike in all.
float3 a = p * s - 2.0 * floor(p * s * 0.5) - 1.0;
s *= 3.0;
// Under 1 in the outer thirds, over 1 in the middle third.
float3 r = abs(1.0 - 3.0 * abs(a));
// Under 1 where two axes are clear of the middle third: solid.
float bars = min(max(r.x, r.y), min(max(r.y, r.z), max(r.z, r.x)));
// Distances in a cell are s times smaller out in the picture.
d = max(d, (bars - 1.0) / s);
}
return d;
}
float3 spongeNormal(float3 p, int cuts, float e) {
const float2 k = float2(1.0, -1.0);
return normalize(k.xyy * sponge(p + k.xyy * e, cuts)
+ k.yyx * sponge(p + k.yyx * e, cuts)
+ k.yxy * sponge(p + k.yxy * e, cuts)
+ k.xxx * sponge(p + k.xxx * e, cuts));
}
float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
float t = u.time * p.speed;
// The camera circles the box and rises and falls. The pointer's offset
// from the middle (zero in every video) turns it further and tips it.
float2 steer = u.mouse / u.resolution - 0.5;
float yaw = 0.6 + t * 0.26 + steer.x * TAU * 0.5;
float pitch = 0.42 + 0.22 * sin(t * 0.17) + steer.y * 2.0;
pitch = clamp(pitch, -1.4, 1.4);
float3 ro = 4.6 * float3(cos(pitch) * sin(yaw), sin(pitch),
cos(pitch) * cos(yaw));
float3 fw = normalize(-ro);
float3 rt = normalize(cross(fw, float3(0.0, 1.0, 0.0)));
float3 up = cross(rt, fw);
float lens = 2.1;
float side = min(u.resolution.x, u.resolution.y);
float2 q = (uv - 0.5) * u.resolution / side * 2.0;
float3 rd = normalize(q.x * rt + q.y * up + lens * fw);
// How wide one pixel is a unit away from the camera.
float pixel = 2.0 / (side * lens);
float shift = (p.heat - 0.5) * 0.4;
// The kiln's dark behind it, warmer toward the middle of the picture.
float back = 0.05 + 0.09 * exp(-dot(q, q) * 0.7);
// The slider is a number with decimals; the loop wants a whole one.
int cuts = int(p.depth + 0.5);
// March: step by the distance until the ray is within half a pixel.
float dist = 0.0;
bool hit = false;
for (int i = 0; i < 140; i++) {
float d = sponge(ro + rd * dist, cuts);
if (d < pixel * dist * 0.5) { hit = true; break; }
dist += d;
if (dist > 8.0) break;
}
if (!hit) return float4(kiln(back + shift), 1.0);
// Lit like clay: as bright as the surface faces the light, which is
// above and to the left of the camera and goes round with it.
float3 pos = ro + rd * dist;
float3 n = spongeNormal(pos, cuts, pixel * dist * 0.5);
float3 l = normalize(up * 0.8 - rt * 0.55 - fw * 0.35);
float lit = max(dot(n, l), 0.0);
return float4(kiln(0.09 + 0.55 * lit + shift), 1.0);
}10 lines from stage 2 that are gone
float sponge(float3 p) {
⋯
float3 a = 1.0 - abs(p);
⋯
return max(d, (bars - 1.0) / 3.0);
⋯
float3 spongeNormal(float3 p, float e) {
⋯
return normalize(k.xyy * sponge(p + k.xyy * e)
+ k.yyx * sponge(p + k.yyx * e)
+ k.yxy * sponge(p + k.yxy * e)
+ k.xxx * sponge(p + k.xxx * e));
⋯
float d = sponge(ro + rd * dist);
⋯
float3 n = spongeNormal(pos, pixel * dist * 0.5);Stage 4 · A fire inside
Light from one side leaves the tunnels flat. spongeShut is ambient occlusion, the idea Molten Metaballs used: five steps out along the surface's direction, from 0.047 to 0.187, each asking how near the sponge is. In a tunnel the far wall is nearer than the step, and the place darkens.
Then a fire is put in the middle. under is how far beneath the sponge's outer faces a point is: 0 on a face, 1 at the center. A wall glows by under to the power 0.6, so the mouths of the tunnels are dull and their depths run to gold, with a flicker of a tenth. A ray that misses the sponge glows by how near it passed, exp(−8 · nearest), which is the haze of heat round it. Rays are now marched only inside a ball of radius 2.6 round the sponge, room for its corners and for that glow to fade out.
stage-4-a-fire-inside.metal36 new lines since stage 3
// Stage 4 · A fire inside
// Light alone leaves the tunnels flat, so ambient occlusion darkens the places that are shut in. Then a fire is put in
// the middle: a wall glows by how far under the sponge's outer faces it is, and the air round the sponge glows too.
// @param speed 0.5 0.0 2.0 How fast the camera circles
// @param depth 4.0 1.0 5.0 How many times the box is cut: 1 is one cross of holes, each one more cuts every piece again
// @param glow 0.6 0.0 1.0 How brightly the fire inside lights the tunnels and the air round the sponge
// @param heat 0.5 0.0 1.0 Slides the palette from deep ember to white-hot
constant float TAU = 6.2831853;
// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
float3 c0 = float3(0.020, 0.012, 0.020);
float3 c1 = float3(0.280, 0.040, 0.030);
float3 c2 = float3(0.880, 0.260, 0.050);
float3 c3 = float3(1.000, 0.680, 0.200);
float3 c4 = float3(1.000, 0.970, 0.840);
t = clamp(t, 0.0, 1.0);
float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
c = mix(c, c2, smoothstep(0.22, 0.50, t));
c = mix(c, c3, smoothstep(0.50, 0.76, t));
return mix(c, c4, smoothstep(0.76, 1.00, t));
}
// The box from Floating 3D Scene.
float sdBox(float3 p, float3 b) {
float3 d = abs(p) - b;
return length(max(d, 0.0)) + min(max(d.x, max(d.y, d.z)), 0.0);
}
// The fold: the same cut in every smaller box. Each turn of the loop
// cuts every piece the last one left: 1 cell, then 27, then 729.
float sponge(float3 p, int cuts) {
float d = sdBox(p, float3(1.0));
float s = 1.0;
for (int m = 0; m < 8; m++) {
if (m >= cuts) break;
// Cells 2/s wide; `a` is p's place in its own cell, alike in all.
float3 a = p * s - 2.0 * floor(p * s * 0.5) - 1.0;
s *= 3.0;
// Under 1 in the outer thirds, over 1 in the middle third.
float3 r = abs(1.0 - 3.0 * abs(a));
// Under 1 where two axes are clear of the middle third: solid.
float bars = min(max(r.x, r.y), min(max(r.y, r.z), max(r.z, r.x)));
// Distances in a cell are s times smaller out in the picture.
d = max(d, (bars - 1.0) / s);
}
return d;
}
float3 spongeNormal(float3 p, int cuts, float e) {
const float2 k = float2(1.0, -1.0);
return normalize(k.xyy * sponge(p + k.xyy * e, cuts)
+ k.yyx * sponge(p + k.yyx * e, cuts)
+ k.yxy * sponge(p + k.yxy * e, cuts)
+ k.xxx * sponge(p + k.xxx * e, cuts));
}
// Ambient occlusion: step out from the surface; where the sponge is
// nearer than the step, the place is shut in and darkens.
float spongeShut(float3 p, float3 n, int cuts) {
float shut = 0.0;
float weight = 1.0;
for (int i = 1; i <= 5; i++) {
float h = 0.012 + 0.035 * float(i);
shut += (h - sponge(p + n * h, cuts)) * weight;
weight *= 0.7;
}
return clamp(1.0 - 2.4 * shut, 0.0, 1.0);
}
// Where the ray crosses a ball of radius 2.6 round the sponge, with room
// for the glow to fade out. Nothing outside the ball is marched.
float2 spongeBall(float3 ro, float3 rd) {
float b = dot(ro, rd);
float c = dot(ro, ro) - 2.6 * 2.6;
float h = b * b - c;
if (h < 0.0) return float2(1.0, -1.0);
h = sqrt(h);
return float2(max(-b - h, 0.0), -b + h);
}
float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
float t = u.time * p.speed;
// The camera circles the box and rises and falls. The pointer's offset
// from the middle (zero in every video) turns it further and tips it.
float2 steer = u.mouse / u.resolution - 0.5;
float yaw = 0.6 + t * 0.26 + steer.x * TAU * 0.5;
float pitch = 0.42 + 0.22 * sin(t * 0.17) + steer.y * 2.0;
pitch = clamp(pitch, -1.4, 1.4);
float3 ro = 4.6 * float3(cos(pitch) * sin(yaw), sin(pitch),
cos(pitch) * cos(yaw));
float3 fw = normalize(-ro);
float3 rt = normalize(cross(fw, float3(0.0, 1.0, 0.0)));
float3 up = cross(rt, fw);
float lens = 2.1;
float side = min(u.resolution.x, u.resolution.y);
float2 q = (uv - 0.5) * u.resolution / side * 2.0;
float3 rd = normalize(q.x * rt + q.y * up + lens * fw);
// How wide one pixel is a unit away from the camera.
float pixel = 2.0 / (side * lens);
float shift = (p.heat - 0.5) * 0.4;
// The kiln's dark behind it, warmer toward the middle of the picture.
float back = 0.05 + 0.09 * exp(-dot(q, q) * 0.7);
int cuts = int(p.depth + 0.5);
float2 span = spongeBall(ro, rd);
if (span.y < span.x) return float4(kiln(back + shift), 1.0);
float dist = span.x;
float nearest = 1e3;
bool hit = false;
for (int i = 0; i < 140; i++) {
float d = sponge(ro + rd * dist, cuts);
nearest = min(nearest, d);
if (d < pixel * dist * 0.5) { hit = true; break; }
dist += d;
if (dist > span.y) break;
}
if (!hit) {
// A ray that missed glows by how near it passed the sponge.
float halo = exp(-nearest * 8.0) * p.glow * 0.3;
return float4(kiln(back + halo + shift), 1.0);
}
float3 pos = ro + rd * dist;
float3 n = spongeNormal(pos, cuts, pixel * dist * 0.5);
// The light is above and to the left of the camera, and goes round with it.
float3 l = normalize(up * 0.8 - rt * 0.55 - fw * 0.35);
float lit = max(dot(n, l), 0.0);
float ao = spongeShut(pos, n, cuts);
// The fire: how far under the sponge's outer faces this point is, 0 on a
// face and 1 in the middle. Tunnel walls glow hotter the deeper they are.
float3 w = abs(pos);
float under = clamp(1.0 - max(w.x, max(w.y, w.z)), 0.0, 1.0);
float fire = pow(under, 0.6) * (0.9 + 0.1 * sin(t * 2.3 + under * 9.0));
// Edges facing away from the camera catch a little of it too.
float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0);
float level = 0.09 + 0.40 * lit * (0.3 + 0.7 * ao)
+ p.glow * (1.05 * fire * (0.45 + 0.55 * ao) + 0.12 * rim);
return float4(kiln(level + shift), 1.0);
}4 lines from stage 3 that are gone
float dist = 0.0;
⋯
if (dist > 8.0) break;
⋯
if (!hit) return float4(kiln(back + shift), 1.0);
⋯
return float4(kiln(0.09 + 0.55 * lit + shift), 1.0);Stage 5 · Menger Sponge
Three things finish it. A cut can be part way open: depth is no longer rounded, and a cut's threshold runs from 2, where nothing is taken away (no bars is larger), to walls, where it is fully open. So depth at 3.5 is three cuts and a fourth with its tunnels at half width, and dragging the slider grows the holes instead of popping them in. walls is 1 for the true sponge. Under 1 the tunnels are wider than a third and the cuts of different sizes run into each other, until the sponge is a lattice. Over 1 the walls are thicker and the tunnels narrower: at 1.3 each tunnel is about 70% as wide.
A cut whose holes would be smaller than a pixel is closed again. width is how wide this cut's tunnels are, 2/3 over the scale so far, and fine is a pixel's width where the ray is. The cut is fully open when its tunnels are three pixels wide and closed when they are one. That is level of detail: the picture never holds holes it can't draw, so nothing shimmers, and a larger picture or a closer look gets more of the sponge. At 1920 × 1080 the fourth cut is fully drawn and a fifth is most of the way open; a small picture shows less.
zoom looks closer by a longer lens, never by moving the camera in, so the camera can't end up inside a wall. The lens also leans in and out by 18% as time goes on.
the kiln palette and shade(), from the finished shader
// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
float3 c0 = float3(0.020, 0.012, 0.020);
float3 c1 = float3(0.280, 0.040, 0.030);
float3 c2 = float3(0.880, 0.260, 0.050);
float3 c3 = float3(1.000, 0.680, 0.200);
float3 c4 = float3(1.000, 0.970, 0.840);
t = clamp(t, 0.0, 1.0);
float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
c = mix(c, c2, smoothstep(0.22, 0.50, t));
c = mix(c, c3, smoothstep(0.50, 0.76, t));
return mix(c, c4, smoothstep(0.76, 1.00, t));
}
float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
float t = u.time * p.speed;
// The camera circles the sponge and rises and falls. The pointer's offset
// from the middle (zero in every video) turns it further and tips it.
float2 steer = u.mouse / u.resolution - 0.5;
float yaw = 0.6 + t * 0.26 + steer.x * TAU * 0.5;
float pitch = 0.42 + 0.22 * sin(t * 0.17) + steer.y * 2.0;
pitch = clamp(pitch, -1.4, 1.4);
float3 ro = 4.6 * float3(cos(pitch) * sin(yaw), sin(pitch),
cos(pitch) * cos(yaw));
float3 fw = normalize(-ro);
float3 rt = normalize(cross(fw, float3(0.0, 1.0, 0.0)));
float3 up = cross(rt, fw);
// It leans in and out by a longer lens, never by going nearer, so it
// can't end up inside a wall. `zoom` multiplies that.
float lens = 2.1 * p.zoom * (1.0 + 0.18 * sin(t * 0.31 - 0.6));
float side = min(u.resolution.x, u.resolution.y);
float2 q = (uv - 0.5) * u.resolution / side * 2.0;
float3 rd = normalize(q.x * rt + q.y * up + lens * fw);
// How wide one pixel is a unit away from the camera.
float pixel = 2.0 / (side * lens);
float shift = (p.heat - 0.5) * 0.4;
// The kiln's dark behind it, warmer toward the middle of the picture.
float back = 0.05 + 0.09 * exp(-dot(q, q) * 0.7);
float2 span = spongeBall(ro, rd);
if (span.y < span.x) return float4(kiln(back + shift), 1.0);
float dist = span.x;
float nearest = 1e3;
bool hit = false;
for (int i = 0; i < 140; i++) {
float3 pos = ro + rd * dist;
float fine = pixel * dist;
float d = sponge(pos, p.depth, p.walls, fine);
nearest = min(nearest, d);
if (d < fine * 0.5) { hit = true; break; }
dist += d;
if (dist > span.y) break;
}
if (!hit) {
// A ray that missed glows by how near it passed the sponge.
float halo = exp(-nearest * 8.0) * p.glow * 0.3;
return float4(kiln(back + halo + shift), 1.0);
}
float3 pos = ro + rd * dist;
float fine = pixel * dist;
float3 n = spongeNormal(pos, p.depth, p.walls, fine);
// The light is above and to the left of the camera, and goes round with it.
float3 l = normalize(up * 0.8 - rt * 0.55 - fw * 0.35);
float lit = max(dot(n, l), 0.0);
float ao = spongeShut(pos, n, p.depth, p.walls, fine);
// The fire: how far under the sponge's outer faces this point is, 0 on a
// face and 1 in the middle. Tunnel walls glow hotter the deeper they are.
float3 w = abs(pos);
float under = clamp(1.0 - max(w.x, max(w.y, w.z)), 0.0, 1.0);
float fire = pow(under, 0.6) * (0.9 + 0.1 * sin(t * 2.3 + under * 9.0));
// Edges facing away from the camera catch a little of it too.
float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0);
float level = 0.09 + 0.40 * lit * (0.3 + 0.7 * ao)
+ p.glow * (1.05 * fire * (0.45 + 0.55 * ao) + 0.12 * rim);
return float4(kiln(level + shift), 1.0);
}menger-sponge.metal, the whole file61 new lines since stage 4
// Ray Kiln · Menger Sponge
//
// @episode Menger Sponge
// @length 60
// @variation 30
// @variations 1,3,4,5,6,7,9,12
// @sweeps depth, walls, zoom
// @still 14.0
// @teaches Folding space into a fractal, a box cut again and again
// @category Fragment
// @tags menger sponge, fractals, folding space, signed distance fields, raymarching, ambient occlusion, level of detail, procedural sound
// @final Menger Sponge | The sponge with a fire inside it: cut four times, its tunnels glowing hotter the deeper they go, the camera circling and leaning in.
//
// Take a box, cut it into 27 smaller boxes, and take out the one in the middle and the six in the middle of each face.
// Twenty are left. Do the same to each of them, and to each of theirs. That is the Menger sponge, and writing it down
// box by box would take 20, 400, 8,000, 160,000 boxes. This shader never makes one of them. It folds space instead:
// every point is moved into one small cell, the same cell for all of them, and one cross-shaped hole is cut there. A
// loop does it again at a third of the size, so each turn of the loop multiplies the holes by twenty and costs the same.
// Each @param line below becomes a slider in the host app and a row in the page's parameters table:
// // @param name default min max description
// @param speed 0.5 0.0 2.0 How fast the camera circles and leans in
// @param depth 4.0 1.0 5.0 How many times the box is cut: 1 is one cross of holes, each one more cuts every piece again; a part of a cut opens it part way
// @param walls 1.0 0.8 1.3 How thick the walls are left: at 1 each cut takes a third of its box, the true sponge; less is thinner walls and wider holes, more is thicker
// @param zoom 1.0 1.0 6.0 How many times closer the picture looks
// @param glow 0.6 0.0 1.0 How brightly the fire inside lights the tunnels and the air round the sponge
// @param heat 0.5 0.0 1.0 Slides the palette from deep ember to white-hot
// @param volume 0.8 0.0 1.0 Loudness of the sound
constant float TAU = 6.2831853;
// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
float3 c0 = float3(0.020, 0.012, 0.020);
float3 c1 = float3(0.280, 0.040, 0.030);
float3 c2 = float3(0.880, 0.260, 0.050);
float3 c3 = float3(1.000, 0.680, 0.200);
float3 c4 = float3(1.000, 0.970, 0.840);
t = clamp(t, 0.0, 1.0);
float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
c = mix(c, c2, smoothstep(0.22, 0.50, t));
c = mix(c, c3, smoothstep(0.50, 0.76, t));
return mix(c, c4, smoothstep(0.76, 1.00, t));
}
// The box from Floating 3D Scene.
float sdBox(float3 p, float3 b) {
float3 d = abs(p) - b;
return length(max(d, 0.0)) + min(max(d.x, max(d.y, d.z)), 0.0);
}
// A cut can now be part way open (`depth` 3.5 is half of a fourth), and
// one whose holes are smaller than `fine`, a pixel out there, is closed.
float sponge(float3 p, float depth, float walls, float fine) {
float d = sdBox(p, float3(1.0));
float s = 1.0;
for (int m = 0; m < 8; m++) {
float open = clamp(depth - float(m), 0.0, 1.0);
// This cut's holes are 2/3 wide, over the scale so far.
float width = 0.6667 / s;
open *= smoothstep(1.0, 3.0, width / fine);
if (open <= 0.0) break;
// Cells 2/s wide; `a` is p's place in its own cell, alike in all.
float3 a = p * s - 2.0 * floor(p * s * 0.5) - 1.0;
s *= 3.0;
// Under 1 in the outer thirds, over 1 in the middle third.
float3 r = abs(1.0 - 3.0 * abs(a));
// Under 1 where two axes are clear of the middle third: solid.
float bars = min(max(r.x, r.y), min(max(r.y, r.z), max(r.z, r.x)));
// At 2 the cut takes nothing away; at `walls` it is fully open.
d = max(d, (bars - mix(2.0, walls, open)) / s);
}
return d;
}
float3 spongeNormal(float3 p, float depth, float walls, float fine) {
const float2 k = float2(1.0, -1.0);
float e = fine * 0.5;
return normalize(k.xyy * sponge(p + k.xyy * e, depth, walls, fine)
+ k.yyx * sponge(p + k.yyx * e, depth, walls, fine)
+ k.yxy * sponge(p + k.yxy * e, depth, walls, fine)
+ k.xxx * sponge(p + k.xxx * e, depth, walls, fine));
}
// Ambient occlusion: step out from the surface; where the sponge is
// nearer than the step, the place is shut in and darkens.
float spongeShut(float3 p, float3 n, float depth, float walls, float fine) {
float shut = 0.0;
float weight = 1.0;
for (int i = 1; i <= 5; i++) {
float h = 0.012 + 0.035 * float(i);
shut += (h - sponge(p + n * h, depth, walls, fine)) * weight;
weight *= 0.7;
}
return clamp(1.0 - 2.4 * shut, 0.0, 1.0);
}
// Where the ray crosses a ball of radius 2.6 round the sponge, with room
// for the glow to fade out. Nothing outside the ball is marched.
float2 spongeBall(float3 ro, float3 rd) {
float b = dot(ro, rd);
float c = dot(ro, ro) - 2.6 * 2.6;
float h = b * b - c;
if (h < 0.0) return float2(1.0, -1.0);
h = sqrt(h);
return float2(max(-b - h, 0.0), -b + h);
}
float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
float t = u.time * p.speed;
// The camera circles the sponge and rises and falls. The pointer's offset
// from the middle (zero in every video) turns it further and tips it.
float2 steer = u.mouse / u.resolution - 0.5;
float yaw = 0.6 + t * 0.26 + steer.x * TAU * 0.5;
float pitch = 0.42 + 0.22 * sin(t * 0.17) + steer.y * 2.0;
pitch = clamp(pitch, -1.4, 1.4);
float3 ro = 4.6 * float3(cos(pitch) * sin(yaw), sin(pitch),
cos(pitch) * cos(yaw));
float3 fw = normalize(-ro);
float3 rt = normalize(cross(fw, float3(0.0, 1.0, 0.0)));
float3 up = cross(rt, fw);
// It leans in and out by a longer lens, never by going nearer, so it
// can't end up inside a wall. `zoom` multiplies that.
float lens = 2.1 * p.zoom * (1.0 + 0.18 * sin(t * 0.31 - 0.6));
float side = min(u.resolution.x, u.resolution.y);
float2 q = (uv - 0.5) * u.resolution / side * 2.0;
float3 rd = normalize(q.x * rt + q.y * up + lens * fw);
// How wide one pixel is a unit away from the camera.
float pixel = 2.0 / (side * lens);
float shift = (p.heat - 0.5) * 0.4;
// The kiln's dark behind it, warmer toward the middle of the picture.
float back = 0.05 + 0.09 * exp(-dot(q, q) * 0.7);
float2 span = spongeBall(ro, rd);
if (span.y < span.x) return float4(kiln(back + shift), 1.0);
float dist = span.x;
float nearest = 1e3;
bool hit = false;
for (int i = 0; i < 140; i++) {
float3 pos = ro + rd * dist;
float fine = pixel * dist;
float d = sponge(pos, p.depth, p.walls, fine);
nearest = min(nearest, d);
if (d < fine * 0.5) { hit = true; break; }
dist += d;
if (dist > span.y) break;
}
if (!hit) {
// A ray that missed glows by how near it passed the sponge.
float halo = exp(-nearest * 8.0) * p.glow * 0.3;
return float4(kiln(back + halo + shift), 1.0);
}
float3 pos = ro + rd * dist;
float fine = pixel * dist;
float3 n = spongeNormal(pos, p.depth, p.walls, fine);
// The light is above and to the left of the camera, and goes round with it.
float3 l = normalize(up * 0.8 - rt * 0.55 - fw * 0.35);
float lit = max(dot(n, l), 0.0);
float ao = spongeShut(pos, n, p.depth, p.walls, fine);
// The fire: how far under the sponge's outer faces this point is, 0 on a
// face and 1 in the middle. Tunnel walls glow hotter the deeper they are.
float3 w = abs(pos);
float under = clamp(1.0 - max(w.x, max(w.y, w.z)), 0.0, 1.0);
float fire = pow(under, 0.6) * (0.9 + 0.1 * sin(t * 2.3 + under * 9.0));
// Edges facing away from the camera catch a little of it too.
float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0);
float level = 0.09 + 0.40 * lit * (0.3 + 0.7 * ao)
+ p.glow * (1.05 * fire * (0.45 + 0.55 * ao) + 0.12 * rim);
return float4(kiln(level + shift), 1.0);
}
// ---- Sound -------------------------------------------------------------------------------------------------------
// The sponge's rule, heard. A bar of 7.5 s is cut into three and its middle third left silent; each third that is left
// is cut the same way, and so on (in one dimension this is the Cantor set). Each cut is a voice: the first strikes at
// the start of the thirds it keeps, the second at its ninths, down to 243rds. A cut three times smaller sounds three
// times higher, an octave and a fifth, so the voices climb 55, 165, 495, 1,485 and 4,455 Hz. `depth` says how many of
// them play, as it says how many cuts the box gets. Under them a low hum swells and dies once a bar.
// One cut's voice: `slots` equal parts of the bar, struck where no base-3 digit
// of the part's number is 1, at `freq`, a little to one side by its last digit.
float2 cantorVoice(float bar, int digits, float slots, float freq, float ring) {
float at = bar * slots;
float index = floor(at);
float local = (at - index) / slots * 7.5;
int n = int(index);
float pan = 0.0;
for (int k = 0; k < 5; k++) {
if (k >= digits) break;
int digit = n % 3;
if (digit == 1) return float2(0.0);
if (k == 0) pan = float(digit) - 1.0;
n /= 3;
}
// A strike: 4 ms to come in, then it rings down.
float env = smoothstep(0.0, 0.004, local) * exp(-local / ring);
// It is faded out before its part ends, so the next strike starts clean.
env *= smoothstep(0.0, 0.006, 7.5 / slots - local);
float tone = sin(TAU * freq * local) + 0.3 * sin(TAU * freq * 2.0 * local);
return tone * env * float2(0.75 - 0.25 * pan, 0.75 + 0.25 * pan);
}
float2 sound(float t, constant Params& p) {
float bar = fract(t / 7.5);
// Thinner walls ring longer.
float ring = 0.5 + 0.9 * (1.3 - p.walls);
float2 a = float2(0.0);
float slots = 3.0;
float freq = 55.0;
for (int m = 0; m < 5; m++) {
float open = clamp(p.depth - float(m), 0.0, 1.0);
if (open > 0.0) {
float level = open / (1.0 + 1.2 * float(m));
// Higher voices ring shorter, as smaller things do.
a += cantorVoice(bar, m + 1, slots, freq,
ring / (1.0 + float(m))) * level;
}
slots *= 3.0;
freq *= 3.0;
}
// The fire's hum: 55 Hz and the fifth above, silent where the bar turns.
float swell = sin(3.14159265 * bar);
float hum = sin(TAU * 55.0 * bar * 7.5) + 0.5 * sin(TAU * 82.5 * bar * 7.5);
a += float2(hum) * swell * swell * 0.22 * p.glow;
return tanh(a * 0.55) * 0.92 * p.volume;
}16 lines from stage 4 that are gone
float sponge(float3 p, int cuts) {
⋯
if (m >= cuts) break;
⋯
d = max(d, (bars - 1.0) / s);
⋯
float3 spongeNormal(float3 p, int cuts, float e) {
⋯
return normalize(k.xyy * sponge(p + k.xyy * e, cuts)
+ k.yyx * sponge(p + k.yyx * e, cuts)
+ k.yxy * sponge(p + k.yxy * e, cuts)
+ k.xxx * sponge(p + k.xxx * e, cuts));
⋯
float spongeShut(float3 p, float3 n, int cuts) {
⋯
shut += (h - sponge(p + n * h, cuts)) * weight;
⋯
float lens = 2.1;
⋯
int cuts = int(p.depth + 0.5);
⋯
float d = sponge(ro + rd * dist, cuts);
⋯
if (d < pixel * dist * 0.5) { hit = true; break; }
⋯
float3 n = spongeNormal(pos, cuts, pixel * dist * 0.5);
⋯
float ao = spongeShut(pos, n, cuts);The sound
The sponge's rule, heard. A bar of 7.5 s is cut into three and its middle third left silent. Each third that is left is cut the same way, and so on: in one dimension the sponge is the Cantor set. Each cut is a voice. The first has 3 parts to the bar and strikes at the start of the 2 it keeps; the next has 9 parts and keeps 4, then 8 of 27, 16 of 81 and 32 of 243. A part is kept when its number, written in base 3, has no digit 1.
A cut three times smaller sounds three times higher, an octave and a fifth: 55, 165, 495, 1,485 and 4,455 Hz, each a sine with a little of its octave, each quieter and shorter than the one below, panned left or right by its last digit. depth says how many voices play, as it says how many cuts the box gets, and a part-open cut is a part-loud voice; past 5 there are no more voices to add. Thinner walls ring longer. Under the voices the fire hums at 55 and 82.5 Hz, swelling and dying once a bar and louder with glow. Sixty seconds are eight bars, and each bar ends in silence.
At the defaults the peak is −5.7 dBFS and the average (RMS) −20.7 dBFS over the minute. With volume, glow and depth at their highest and walls at its lowest it reaches a peak of −3.4 dBFS and an RMS of −17.2 dBFS.
New in Ray Kiln
Slider ranges and exact values. A slider gets you near a number, and only as far as the range its shader shipped with. Now a click on the number beside a slider lets you type it: Enter sets it, Escape puts it back. You can also reach it with Tab and press Enter. It works in the playground and in Run it live under every stage on an episode page.
In the playground each slider also shows its two ends under it, and a click on an end lets you type a new one. The range is part of the shader, so the playground writes it there: the slider's line in the code, // @param name default min max, gets the new min or max, and a default the range no longer holds moves to the nearer end. A Share link, a save to the gallery and an export all carry it, and the Mac app reads the same line. A value typed past an end moves that end out to it. An end isn't taken when the lower one wouldn't be under the upper one. In Run it live there is no code to write to, so a value typed past an end stops at the end.
This episode needs it twice. depth ships from 1 to 5, since a fifth cut is the smallest a 1080p picture can show from where the camera stands. But the loop in sponge can take 8 turns. Open the finished shader, click the number beside zoom and type 30: the slider's upper end becomes 30 and the line in the code says so. Then type 8 for depth. Close up there are pixels enough for the sixth and seventh cuts, and they open. Or type 3.5 for depth to see a cut exactly half open, which is hard to hit by dragging.
Try this
- Drag
depthslowly from 1 to 4 and watch each round of tunnels open in every piece the last one left. - Set
wallsto 0.8: the cuts run into each other and the sponge turns into a lattice of small frames. At 1.3 the walls are thicker and every tunnel about 70% as wide. - Set
glowto 0 for the sponge as plain clay under one light, then to 1. - In the playground, type 8 for
depthand leavezoomat 1: nothing more appears than at 5, because those holes are smaller than a pixel and the shader closes them. Now raisezoom. - Set
depthto 1 and press Sound: one voice is left, striking twice a bar at 55 Hz over the hum. Raisedeptha step at a time and each cut adds its voice, an octave and a fifth higher. - In
sponge, changes *= 3.0;tos *= 2.0;: the cells no longer line up with the cuts before them, and the sponge is something else, still made of one cut repeated. - In
sound, changefreq *= 3.0;tofreq *= 2.0;: every voice is an octave above the last, and the chord is one note.
Parameters
Pick a parameter and drag the slider. Each frame is the same moment of the shader, with only that one setting changed.
| Parameter | Default | Range | What it does |
|---|---|---|---|
speed | 0.5 | 0.0 to 2.0 | How fast the camera circles and leans in |
depth | 4.0 | 1.0 to 5.0 | How many times the box is cut: 1 is one cross of holes, each one more cuts every piece again; a part of a cut opens it part way |
walls | 1.0 | 0.8 to 1.3 | How thick the walls are left: at 1 each cut takes a third of its box, the true sponge; less is thinner walls and wider holes, more is thicker |
zoom | 1.0 | 1.0 to 6.0 | How many times closer the picture looks |
glow | 0.6 | 0.0 to 1.0 | How brightly the fire inside lights the tunnels and the air round the sponge |
heat | 0.5 | 0.0 to 1.0 | Slides the palette from deep ember to white-hot |
volume | 0.8 | 0.0 to 1.0 | Loudness of the sound |
More from this shader
The same shader 8 more ways: each from a different moment, with different settings, one after another. Each chapter below says which settings moved most, then lists them all.
Wallpapers
A still from the shader, rendered at full size for a desktop or a phone screen. Free to use as your wallpaper.
Clips to post
Fifteen seconds of the shader with its sound, sized for posting: square for feeds, vertical for stories and short videos. Free to post, ideally with a link to this page.
Made from this episode
The full source
This is the whole episode: the picture, the parameters and the sound.
menger-sponge.metal
// Ray Kiln · Menger Sponge
//
// @episode Menger Sponge
// @length 60
// @variation 30
// @variations 1,3,4,5,6,7,9,12
// @sweeps depth, walls, zoom
// @still 14.0
// @teaches Folding space into a fractal, a box cut again and again
// @category Fragment
// @tags menger sponge, fractals, folding space, signed distance fields, raymarching, ambient occlusion, level of detail, procedural sound
// @final Menger Sponge | The sponge with a fire inside it: cut four times, its tunnels glowing hotter the deeper they go, the camera circling and leaning in.
//
// Take a box, cut it into 27 smaller boxes, and take out the one in the middle and the six in the middle of each face.
// Twenty are left. Do the same to each of them, and to each of theirs. That is the Menger sponge, and writing it down
// box by box would take 20, 400, 8,000, 160,000 boxes. This shader never makes one of them. It folds space instead:
// every point is moved into one small cell, the same cell for all of them, and one cross-shaped hole is cut there. A
// loop does it again at a third of the size, so each turn of the loop multiplies the holes by twenty and costs the same.
// Each @param line below becomes a slider in the host app and a row in the page's parameters table:
// // @param name default min max description
// @param speed 0.5 0.0 2.0 How fast the camera circles and leans in
// @param depth 4.0 1.0 5.0 How many times the box is cut: 1 is one cross of holes, each one more cuts every piece again; a part of a cut opens it part way
// @param walls 1.0 0.8 1.3 How thick the walls are left: at 1 each cut takes a third of its box, the true sponge; less is thinner walls and wider holes, more is thicker
// @param zoom 1.0 1.0 6.0 How many times closer the picture looks
// @param glow 0.6 0.0 1.0 How brightly the fire inside lights the tunnels and the air round the sponge
// @param heat 0.5 0.0 1.0 Slides the palette from deep ember to white-hot
// @param volume 0.8 0.0 1.0 Loudness of the sound
constant float TAU = 6.2831853;
// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
float3 c0 = float3(0.020, 0.012, 0.020);
float3 c1 = float3(0.280, 0.040, 0.030);
float3 c2 = float3(0.880, 0.260, 0.050);
float3 c3 = float3(1.000, 0.680, 0.200);
float3 c4 = float3(1.000, 0.970, 0.840);
t = clamp(t, 0.0, 1.0);
float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
c = mix(c, c2, smoothstep(0.22, 0.50, t));
c = mix(c, c3, smoothstep(0.50, 0.76, t));
return mix(c, c4, smoothstep(0.76, 1.00, t));
}
// The box from Floating 3D Scene.
float sdBox(float3 p, float3 b) {
float3 d = abs(p) - b;
return length(max(d, 0.0)) + min(max(d.x, max(d.y, d.z)), 0.0);
}
// A cut can now be part way open (`depth` 3.5 is half of a fourth), and
// one whose holes are smaller than `fine`, a pixel out there, is closed.
float sponge(float3 p, float depth, float walls, float fine) {
float d = sdBox(p, float3(1.0));
float s = 1.0;
for (int m = 0; m < 8; m++) {
float open = clamp(depth - float(m), 0.0, 1.0);
// This cut's holes are 2/3 wide, over the scale so far.
float width = 0.6667 / s;
open *= smoothstep(1.0, 3.0, width / fine);
if (open <= 0.0) break;
// Cells 2/s wide; `a` is p's place in its own cell, alike in all.
float3 a = p * s - 2.0 * floor(p * s * 0.5) - 1.0;
s *= 3.0;
// Under 1 in the outer thirds, over 1 in the middle third.
float3 r = abs(1.0 - 3.0 * abs(a));
// Under 1 where two axes are clear of the middle third: solid.
float bars = min(max(r.x, r.y), min(max(r.y, r.z), max(r.z, r.x)));
// At 2 the cut takes nothing away; at `walls` it is fully open.
d = max(d, (bars - mix(2.0, walls, open)) / s);
}
return d;
}
float3 spongeNormal(float3 p, float depth, float walls, float fine) {
const float2 k = float2(1.0, -1.0);
float e = fine * 0.5;
return normalize(k.xyy * sponge(p + k.xyy * e, depth, walls, fine)
+ k.yyx * sponge(p + k.yyx * e, depth, walls, fine)
+ k.yxy * sponge(p + k.yxy * e, depth, walls, fine)
+ k.xxx * sponge(p + k.xxx * e, depth, walls, fine));
}
// Ambient occlusion: step out from the surface; where the sponge is
// nearer than the step, the place is shut in and darkens.
float spongeShut(float3 p, float3 n, float depth, float walls, float fine) {
float shut = 0.0;
float weight = 1.0;
for (int i = 1; i <= 5; i++) {
float h = 0.012 + 0.035 * float(i);
shut += (h - sponge(p + n * h, depth, walls, fine)) * weight;
weight *= 0.7;
}
return clamp(1.0 - 2.4 * shut, 0.0, 1.0);
}
// Where the ray crosses a ball of radius 2.6 round the sponge, with room
// for the glow to fade out. Nothing outside the ball is marched.
float2 spongeBall(float3 ro, float3 rd) {
float b = dot(ro, rd);
float c = dot(ro, ro) - 2.6 * 2.6;
float h = b * b - c;
if (h < 0.0) return float2(1.0, -1.0);
h = sqrt(h);
return float2(max(-b - h, 0.0), -b + h);
}
float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
float t = u.time * p.speed;
// The camera circles the sponge and rises and falls. The pointer's offset
// from the middle (zero in every video) turns it further and tips it.
float2 steer = u.mouse / u.resolution - 0.5;
float yaw = 0.6 + t * 0.26 + steer.x * TAU * 0.5;
float pitch = 0.42 + 0.22 * sin(t * 0.17) + steer.y * 2.0;
pitch = clamp(pitch, -1.4, 1.4);
float3 ro = 4.6 * float3(cos(pitch) * sin(yaw), sin(pitch),
cos(pitch) * cos(yaw));
float3 fw = normalize(-ro);
float3 rt = normalize(cross(fw, float3(0.0, 1.0, 0.0)));
float3 up = cross(rt, fw);
// It leans in and out by a longer lens, never by going nearer, so it
// can't end up inside a wall. `zoom` multiplies that.
float lens = 2.1 * p.zoom * (1.0 + 0.18 * sin(t * 0.31 - 0.6));
float side = min(u.resolution.x, u.resolution.y);
float2 q = (uv - 0.5) * u.resolution / side * 2.0;
float3 rd = normalize(q.x * rt + q.y * up + lens * fw);
// How wide one pixel is a unit away from the camera.
float pixel = 2.0 / (side * lens);
float shift = (p.heat - 0.5) * 0.4;
// The kiln's dark behind it, warmer toward the middle of the picture.
float back = 0.05 + 0.09 * exp(-dot(q, q) * 0.7);
float2 span = spongeBall(ro, rd);
if (span.y < span.x) return float4(kiln(back + shift), 1.0);
float dist = span.x;
float nearest = 1e3;
bool hit = false;
for (int i = 0; i < 140; i++) {
float3 pos = ro + rd * dist;
float fine = pixel * dist;
float d = sponge(pos, p.depth, p.walls, fine);
nearest = min(nearest, d);
if (d < fine * 0.5) { hit = true; break; }
dist += d;
if (dist > span.y) break;
}
if (!hit) {
// A ray that missed glows by how near it passed the sponge.
float halo = exp(-nearest * 8.0) * p.glow * 0.3;
return float4(kiln(back + halo + shift), 1.0);
}
float3 pos = ro + rd * dist;
float fine = pixel * dist;
float3 n = spongeNormal(pos, p.depth, p.walls, fine);
// The light is above and to the left of the camera, and goes round with it.
float3 l = normalize(up * 0.8 - rt * 0.55 - fw * 0.35);
float lit = max(dot(n, l), 0.0);
float ao = spongeShut(pos, n, p.depth, p.walls, fine);
// The fire: how far under the sponge's outer faces this point is, 0 on a
// face and 1 in the middle. Tunnel walls glow hotter the deeper they are.
float3 w = abs(pos);
float under = clamp(1.0 - max(w.x, max(w.y, w.z)), 0.0, 1.0);
float fire = pow(under, 0.6) * (0.9 + 0.1 * sin(t * 2.3 + under * 9.0));
// Edges facing away from the camera catch a little of it too.
float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0);
float level = 0.09 + 0.40 * lit * (0.3 + 0.7 * ao)
+ p.glow * (1.05 * fire * (0.45 + 0.55 * ao) + 0.12 * rim);
return float4(kiln(level + shift), 1.0);
}
// ---- Sound -------------------------------------------------------------------------------------------------------
// The sponge's rule, heard. A bar of 7.5 s is cut into three and its middle third left silent; each third that is left
// is cut the same way, and so on (in one dimension this is the Cantor set). Each cut is a voice: the first strikes at
// the start of the thirds it keeps, the second at its ninths, down to 243rds. A cut three times smaller sounds three
// times higher, an octave and a fifth, so the voices climb 55, 165, 495, 1,485 and 4,455 Hz. `depth` says how many of
// them play, as it says how many cuts the box gets. Under them a low hum swells and dies once a bar.
// One cut's voice: `slots` equal parts of the bar, struck where no base-3 digit
// of the part's number is 1, at `freq`, a little to one side by its last digit.
float2 cantorVoice(float bar, int digits, float slots, float freq, float ring) {
float at = bar * slots;
float index = floor(at);
float local = (at - index) / slots * 7.5;
int n = int(index);
float pan = 0.0;
for (int k = 0; k < 5; k++) {
if (k >= digits) break;
int digit = n % 3;
if (digit == 1) return float2(0.0);
if (k == 0) pan = float(digit) - 1.0;
n /= 3;
}
// A strike: 4 ms to come in, then it rings down.
float env = smoothstep(0.0, 0.004, local) * exp(-local / ring);
// It is faded out before its part ends, so the next strike starts clean.
env *= smoothstep(0.0, 0.006, 7.5 / slots - local);
float tone = sin(TAU * freq * local) + 0.3 * sin(TAU * freq * 2.0 * local);
return tone * env * float2(0.75 - 0.25 * pan, 0.75 + 0.25 * pan);
}
float2 sound(float t, constant Params& p) {
float bar = fract(t / 7.5);
// Thinner walls ring longer.
float ring = 0.5 + 0.9 * (1.3 - p.walls);
float2 a = float2(0.0);
float slots = 3.0;
float freq = 55.0;
for (int m = 0; m < 5; m++) {
float open = clamp(p.depth - float(m), 0.0, 1.0);
if (open > 0.0) {
float level = open / (1.0 + 1.2 * float(m));
// Higher voices ring shorter, as smaller things do.
a += cantorVoice(bar, m + 1, slots, freq,
ring / (1.0 + float(m))) * level;
}
slots *= 3.0;
freq *= 3.0;
}
// The fire's hum: 55 Hz and the fifth above, silent where the bar turns.
float swell = sin(3.14159265 * bar);
float hum = sin(TAU * 55.0 * bar * 7.5) + 0.5 * sin(TAU * 82.5 * bar * 7.5);
a += float2(hum) * swell * swell * 0.22 * p.glow;
return tanh(a * 0.55) * 0.92 * p.volume;
}Running it in your own project
Every Ray Kiln shader is the same shape. The standalone download above is the shader with the small wrapper around it that the Ray Kiln host adds, so it compiles with the ordinary Metal compiler and runs in your own app. It defines three entry points: rk_vertex (a full-screen triangle), rk_fragment (calls the shader's shade) and, for shaders with sound, the compute kernel rk_sound.
To draw it, pass the uniforms at fragment buffer 0 and the parameter values at buffer 1, in the order they are declared:
Drawing it, in Swift
struct Uniforms {
var resolution: SIMD2<Float>
var time: Float
var timeDelta: Float
var mouse: SIMD2<Float>
var frame: UInt32
var pad: UInt32 = 0
}
let library = try device.makeLibrary(source: standaloneSource, options: nil)
let descriptor = MTLRenderPipelineDescriptor()
descriptor.vertexFunction = library.makeFunction(name: "rk_vertex")
descriptor.fragmentFunction = library.makeFunction(name: "rk_fragment")
descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
let pipeline = try device.makeRenderPipelineState(descriptor: descriptor)
// Each frame, inside a render pass:
var uniforms = Uniforms(resolution: size, time: time, timeDelta: dt, mouse: mouse, frame: frame)
var params: [Float] = [0.5, 4.0, 1.0, 1.0, 0.6, 0.5, 0.8] // the @param defaults, in the order they are declared
encoder.setRenderPipelineState(pipeline)
encoder.setFragmentBytes(&uniforms, length: MemoryLayout<Uniforms>.stride, index: 0)
encoder.setFragmentBytes(¶ms, length: params.count * MemoryLayout<Float>.stride, index: 1)
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)Time is in seconds, mouse is in pixels from the bottom left, and uv in the shader runs 0 to 1 with (0, 0) at the bottom left. Write the output as sRGB: the shader's numbers go to the screen as they are.
More in Fractals
Press ? for keyboard shortcuts.


