An O(N) implicit representation for the Koch Snowflake
This blog post was supposed to be about the Menger Sponge.
I had come up with a clever strategy to use domain repetition – which is essentially free in implicit surfaces – to generate the fractal without an exponential blowup in element count. There were a bunch of cool pictures, and each one linked to an interactive demo in Halfspace.
Here's an example, so you know what you missed:
You can click this image (and indeed every image in this blog post) to load the model in Halfspace. I'd recommend doing so on a desktop; the Halfspace UI is un-suitable for phone screens and not optimized for touch interactions.
Anyways, the blog post was almost done, and I went to link to Inigo Quilez's writeup on domain repetition. Down near the bottom of his writeup, he linked to another article titled "menger fractal - 2011". As luck would have it, this was exactly the same trick that I was writing up, some 15 years earlier.
With the original post scooped, I took it upon myself to use the same tricks on a different fractal – one which I had planned to leave as an exercise for the reader, because I didn't know how to do it!
That fractal is, of course, the seasonally-appropriate Koch Snowflake:
Let's spell out the rules of the game.
Our goal is to come up with a function which takes a position (x, y) and
returns a signed value: negative for points inside the snowflake, and positive
for points outside the snowflake.
The function should be closed-form: there should be no recursion, looping, or reliance on short-circuiting conditionals. The function can be built from a reasonable set of arithmetic operations: addition, subtraction, multiplication, modulo, minimum, maximum, etc.
We will assume that the function is being evaluated with common subexpression elimination, i.e. once you've computed a subexpression once, you can use it again for free elsewhere in the function.
(All of these conditions come from the design of the Fidget implicit kernel)
Most importantly, the function should be linear in complexity with the
number of levels in the snowflake. It's a CS 101 exercise to write a recursive
fractal generator, where the function calls itself four times to produce the
division into four line segments. Such an construction has O(4^N) complexity,
which is (to use a technical term) Very Bad; our target is O(N).
If this sounds like fun, I would strongly encourage you to try it yourself – it's a surprisingly interesting exercise! To get you started, here's a baseline implementation, which implements the Very Bad recursive strategy (click to edit it in Halfspace):
None of this is particularly well documented (the scripting language is Rhai!), but you should be able to poke around and figure out how things work; I have great faith in the intelligent and attractive readers of my blog.
Hexagons are the bestagons
Not being sure where to start, I did notice one deficiency in the existing distance field: there are cracks between the triangles. The visualization shows inside/outside based on color: blue is inside, orange is outside, and the boundary ("isosurface") is shown in white. We are just sticking triangles together, so there are a bunch of zero-area cracks.
Butt joints are a common antipattern in modeling with distance fields: they have a distance value of zero, so it's ambiguous whether the crack should be treated as inside or outside the model. There are strategies, but it's nicer to just not do that in the first place.
For our first fix, we'll instead note that we can replace pairs of little triangles with a single larger triangle:
Notice that each green and blue triangle has two ears poking out, and each one replaces two smaller triangles in the original model.
The core transform here is hexify, which scales and copies its input six times:
fn hexify(s) {
union([
s.remap(x * 3, -y * 3 + 2, z),
s.remap(x * 3, y * 3 + 2, z),
s.remap(x * 3 + sqrt(3), -y * 3 - 1, z),
s.remap(x * 3 - sqrt(3), -y * 3 - 1, z),
s.remap(x * 3 - sqrt(3), y * 3 - 1, z),
s.remap(x * 3 + sqrt(3), y * 3 - 1, z),
]) / 3
}
This eliminates the butt joints, although the distance field is far from perfect:
We've still got an obvious exponential complexity: each call to hexify
multiples the element count by 6. What else can we do?
Time for repetition
It's at this point that I made an interesting observation: if we include the
center in the hexify transform, those triangles form a subset of an infinite
tiling:
The light blue level-2 triangles in our snowflake are a subset of an infinitely-repeating pattern of darker blue tiles. This is great news! Infinite repetitions are easy to construct using implicit surfaces using the modulo operator: in this case, we build the triangles from a repeating horizontal bar cutout:
let ycut = (((y + 0.5) % 1) - 0.5).abs() - 1/6.;
let cut = union(ycut, rotate(ycut, 120), rotate(ycut, 240));
The triangles are in the negative space between bars.
Using modulo gives us an infinitely field of triangles in O(1) expression
terms. We can then build our level-N triangles by simply scaling the triangle
pattern:
Each level of the pattern is O(1), so this meets our O(N) specification.
And voila! We have constructed our snowflake!
Sweeping up the snowstorm
Unfortunately, we have also constructed a veritable Cantor duststorm of miscellaneous triangles, which is obvious in the black-and-white rendering:
How can we preserve only the central snowflake?
This is where things start to get sneaky.
Remember, each of these triangles is a distance field. We can dilate the distance field by subtracting an offset. Here's what that looks like on our original star, showing two offsets:
This suggests a strategy: at each level, construct a "safe zone" by offsetting the previous level, then clip the infinitely-repeating triangles against that zone. Here's an example showing the safe zone (in dark red) for the level-1 triangles:
If you look carefully, you can see that this almost works: it exactly preserves the next-level green triangles in the snowflake. Unfortunately, the dilation also catches a fraction of next-level triangles elsewhere in the tiling.
Here's what it looks like after a few rounds of recursion:
It looks interesting, but not quite what we want!
The final fix relies on the distance field itself: we want the dilation of the field from triangle corners to be slower than from the sides. We can construct such a field by taking the intersection of the triangle with a high-gradient circle:
The dilation of this shape doesn't hit the green triangles:
Using this as the basis for recursing, at last, our snowflake is correct!
Thinking with portals
This achieves our initial goal, but is still slightly unsatisfying: the underlying distance field is very wonky (technical term).
The inner field is correct, but the outer field has widely varying gradients (shown by the spacing between the lines).
After posting on social media, Alexa Schor came up with an elegant alternate design based on Into the Portal: Directable Fractal Self-Similarity.
The core idea here (adapted from her design) is using reflections, which
construct the union of a shape and its reflection without fully copying
the shape. We can use reflections to revisit our earlier hexify function.
Remember, hexify is used to construct six copies of the model at different
points in space:
fn hexify(s) {
union([
s.remap(x * 3, -y * 3 + 2, z),
s.remap(x * 3, y * 3 + 2, z),
s.remap(x * 3 + sqrt(3), -y * 3 - 1, z),
s.remap(x * 3 - sqrt(3), -y * 3 - 1, z),
s.remap(x * 3 - sqrt(3), y * 3 - 1, z),
s.remap(x * 3 + sqrt(3), y * 3 - 1, z),
]) / 3
}
We can instead write hexify in terms of a fold operation, which performs a
combined reflection + union across a particular axis:
fn fold(x, y, angle) {
let nx = -sin(angle);
let ny = cos(angle);
let dist = x * nx + y * ny; // dot product
let offset = max(dist, 0);
[x - 2 * offset * nx, y - 2 * offset * ny]
}
fn hexify(shape) {
let f0 = fold(x, y, 120 * PI/180);
let f1 = fold(f0[0], f0[1], -120 * PI/180);
let f2 = fold(f1[0], f1[1], 120 * PI/180);
shape.remap(x * 3, y * 3 - 2, z) // scale and transform
.remap(f2[0], f2[1]) // six-fold reflection
/ 3 // normalize distance field
}
The core thing to observe here is that we are only creating a single modified
shape, instead of six transformed copies. Repeated applications of hexify
are each O(1) in additional terms, thanks to common subexpression elimination.
With a little more tweaking, this produces the Best Possible Snowflake:
Please admire the fact that the field is an Exact SDF: it has the same gradient everywhere, and that gradient always points directly to the nearest point on the surface, both inside and outside the shape. What a lovely construction; thank you to Alexa for the suggestion!
That's all I've got for now; as always, feel free to say hi if you've got your own improvements on the design!
















