{
  "url": "https://www.mattkeeter.com/blog/2026-11-23-snowflake/",
  "title": "An O(N) implicit representation for the Koch Snowflake",
  "leadImage": "https://www.mattkeeter.com/blog/2026-11-23-snowflake/sponge.png",
  "wordCount": 1334,
  "readingTimeMinutes": 6,
  "cacheStatus": "HIT",
  "markdown": "# An O(N) implicit representation for the Koch Snowflake\n\nThis blog post was supposed to be about the [Menger Sponge](https://en.wikipedia.org/wiki/Menger_sponge).\n\nI 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](https://www.mattkeeter.com/projects/halfspace).\n\nHere's an example, so you know what you missed:\n\n[![Picture of a sponge](https://www.mattkeeter.com/blog/2026-11-23-snowflake/sponge.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/sponge.html)\n\nYou 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.\n\nAnyways, the blog post was almost done, and I went to link to Inigo Quilez's [writeup on domain repetition](https://iquilezles.org/articles/sdfrepetition/). Down near the bottom of his writeup, he linked to another article titled [\"menger fractal - 2011\"](https://iquilezles.org/articles/menger/). As luck would have it, this was exactly the same trick that I was writing up, some 15 years earlier.\n\nWith 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!\n\n* * *\n\nThat fractal is, of course, the seasonally-appropriate [Koch Snowflake](https://en.wikipedia.org/wiki/Koch_snowflake):\n\n[![Picture of four snowflakes](https://www.mattkeeter.com/blog/2026-11-23-snowflake/snowstorm.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/snowstorm.html)\n\nLet's spell out the rules of the game.\n\nOur 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.\n\nThe 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.\n\nWe 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.\n\n(All of these conditions come from the design of the [Fidget implicit kernel](https://www.mattkeeter.com/projects/fidget))\n\nMost 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)`.\n\nIf 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):\n\n[![Picture of a snowflake built from many triangles](https://www.mattkeeter.com/blog/2026-11-23-snowflake/bad_recursion.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/bad_recursion.html)\n\nNone of this is particularly well documented (the scripting language is [Rhai](https://rhai.rs/)!), 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.\n\n* * *\n\n### Hexagons are the bestagons\n\nNot 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.\n\nButt 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](https://www.mattkeeter.com/blog/2017-05-13-implicit-zeros/), but it's nicer to just not do that in the first place.\n\nFor our first fix, we'll instead note that we can replace pairs of little triangles with a single larger triangle:\n\n[![Picture of a snowflake built with hexagonally-arranged triangles](https://www.mattkeeter.com/blog/2026-11-23-snowflake/hexagons.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/hexagons.html)\n\nNotice that each green and blue triangle has two ears poking out, and each one replaces two smaller triangles in the original model.\n\nThe core transform here is `hexify`, which scales and copies its input six times:\n\n```rust\nfn hexify(s) {\n    union([\n        s.remap(x * 3, -y * 3 + 2, z),\n        s.remap(x * 3,  y * 3 + 2, z),\n        s.remap(x * 3 + sqrt(3), -y * 3 - 1, z),\n        s.remap(x * 3 - sqrt(3), -y * 3 - 1, z),\n        s.remap(x * 3 - sqrt(3),  y * 3 - 1, z),\n        s.remap(x * 3 + sqrt(3),  y * 3 - 1, z),\n    ]) / 3\n}\n```\n\nThis eliminates the butt joints, although the distance field is far from perfect:\n\n[![Picture of a snowflake distance field, with no zero-thickness cracks](https://www.mattkeeter.com/blog/2026-11-23-snowflake/nobutt.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/nobutt.html)\n\nWe've still got an obvious exponential complexity: each call to `hexify` multiples the element count by 6. What else can we do?\n\n### Time for repetition\n\nIt'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:\n\n[![Picture of triangles repeating forever, which coincide with the level-two triangles in the snowflake](https://www.mattkeeter.com/blog/2026-11-23-snowflake/tiled.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/tiled.html)\n\nThe 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:\n\n```rust\nlet ycut = (((y + 0.5) % 1) - 0.5).abs() - 1/6.;\nlet cut = union(ycut, rotate(ycut, 120), rotate(ycut, 240));\n```\n\n[![Repeated cyan-magenta-yellow bars, with triangles in their negative space](https://www.mattkeeter.com/blog/2026-11-23-snowflake/cmyk.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/cmyk.html)\n\nThe triangles are in the negative space between bars.\n\nUsing 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:\n\n[![More repeated triangles](https://www.mattkeeter.com/blog/2026-11-23-snowflake/many.png)](https://www.mattkeeter.com/projects/halfspace/demo/#model=ZmxhaAEAAACxmDwA4CyMHR81-xTHCARLeFVW6qxqb_ZJTmR-4hqoDJ45JGfkc8KqTkR0tJLlu0mcZhrCRfCpw9IXSRa_X7v4P029FELWqJXU3sy-PU2IWvRFtVlIJELmGmI2pOkbNSUJXCFW3TbsIVwCcDH5AIIR-iDeZU1MGLyeC8MeojsgEyQA4m2A2Ambcp43nrwJDOhAQqBLjqBTMmFENvcChIiuBvREEzkR3BAH4J6RPoXQBL2HeS6U0RMF9Nc3nLDY5qotdSlz2CF_EYaeDv2QT-EosE_sZK0_pe4NHlPjRF8Kfetvns0XvFQb6lBaN4qdx6Uto7CZmEHQZsEcdjXmxUvCWZfOuHTWpZRLwC8Zq0_1cae_Dw15wfmg4U7YKXa8eAYQ2urFyXxiyq0-aBFdIHYCZWKRsW3aCrUrZUFYdX7RGYXQcX_e46RRNBX-mjaURN2tMR6kuHM6IiJbC0uuuHDAhSssOyoDo8jkGxfBzpMxaHvzwp1lWAQJQcAMiJ2YS6WMa3K3yePruMGWiQopPCreUGgJV_sh9GraooCv3BBHM2U0SkYFXRpSt9J2CazaOd5jHH_CIz6P07V1R_6vp0idvcfBg75P_6uMRJwgNrSlecVUNgOQxyMn1kU2Cmcztm6XS45mNBWMjWcCJPIe_AkFwd_a5IBWeRoptcqAEoxG0KQn9eiPx5yrrMfE7piu58YgN77QEG6LAkEznlu4GOEupC9yW55rVJWUzLKF2p7eQAXvdgPvE6k33RpNolRf_6YqY78qww2onFeRJy6UTJ6nC-k69iRQu2-BKHqARsrF6W9J_4WB2kf-s0IjOkCz0U6sZjN3nKVGVp9u9bitcGdiHM_qdLb1Dcq6Bnp7fJQUAWj2ZVP1kXMxYfNUgEkkVOBrz1DA9t52UX-NBW-Cp0LvoL5bFznSfsOhBDX2qgaFE2i-EQkCsZSWlp4R3uCQFl_EF2gkFyECmsV-CCBoq9yVoUMDIIujhO2oxfZBiaMc83dDOkZG_kECLHdxNM-56GQ9hODo3cIg)\n\nEach level of the pattern is `O(1)`, so this meets our `O(N)` specification.\n\nAnd voila! We have constructed our snowflake!\n\n### Sweeping up the snowstorm\n\nUnfortunately, we have also constructed a veritable Cantor duststorm of miscellaneous triangles, which is obvious in the black-and-white rendering:\n\n[![A black-and-white image of the above, with many triangles outside the snowflake](https://www.mattkeeter.com/blog/2026-11-23-snowflake/dust.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/dust.html)\n\nHow can we preserve only the central snowflake?  \nThis is where things start to get _sneaky_.\n\nRemember, 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:\n\n[![A six-pointed star with two offsets](https://www.mattkeeter.com/blog/2026-11-23-snowflake/dilated.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/dilated.html)\n\nThis 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:\n\n[![A six-pointed star with an offset in darker red, mostly clipping the smaller green triangles](https://www.mattkeeter.com/blog/2026-11-23-snowflake/clipped.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/clipped.html)\n\nIf 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.\n\nHere's what it looks like after a few rounds of recursion:\n\n[![Very nearly a correct snowflake](https://www.mattkeeter.com/blog/2026-11-23-snowflake/almost.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/almost.html)\n\nIt looks _interesting_, but not quite what we want!\n\nThe 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:\n\n[![Triangles showing different fields](https://www.mattkeeter.com/blog/2026-11-23-snowflake/circle.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/circle.html)\n\nThe dilation of this shape doesn't hit the green triangles:\n\n[![Triangle with dilation not hitting other triangles](https://www.mattkeeter.com/blog/2026-11-23-snowflake/good_dilation.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/good_dilation.html)\n\nUsing this as the basis for recursing, at last, our snowflake is correct!\n\n[![A correct snowflake](https://www.mattkeeter.com/blog/2026-11-23-snowflake/final.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/final.html)\n\n### Thinking with portals\n\nThis achieves our initial goal, but is still slightly unsatisfying: the underlying distance field is very wonky (technical term).\n\n[![The distance field of the snowflake, which has widely varying gradients](https://www.mattkeeter.com/blog/2026-11-23-snowflake/wonky.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/wonky.html)\n\nThe inner field is correct, but the outer field has widely varying gradients (shown by the spacing between the lines).\n\nAfter posting on social media, [Alexa Schor](https://alexaschor.com/) came up with an [elegant alternate design](https://bsky.app/profile/bsky.alexaschor.com/post/3n2i4u6nr4s2l) based on [Into the Portal: Directable Fractal Self-Similarity](https://alexaschor.com/into-the-portal/).\n\nThe 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.\n\nRemember, `hexify` is used to construct six copies of the model at different points in space:\n\n```rust\nfn hexify(s) {\n    union([\n        s.remap(x * 3, -y * 3 + 2, z),\n        s.remap(x * 3,  y * 3 + 2, z),\n        s.remap(x * 3 + sqrt(3), -y * 3 - 1, z),\n        s.remap(x * 3 - sqrt(3), -y * 3 - 1, z),\n        s.remap(x * 3 - sqrt(3),  y * 3 - 1, z),\n        s.remap(x * 3 + sqrt(3),  y * 3 - 1, z),\n    ]) / 3\n}\n```\n\nWe can instead write `hexify` in terms of a `fold` operation, which performs a combined reflection + union across a particular axis:\n\n```\nfn fold(x, y, angle) {\n    let nx = -sin(angle);\n    let ny =  cos(angle);\n    let dist = x * nx + y * ny; // dot product\n    let offset = max(dist, 0);\n    [x - 2 * offset * nx, y - 2 * offset * ny]\n}\n\nfn hexify(shape) {\n    let f0 = fold(x,         y,  120 * PI/180);\n    let f1 = fold(f0[0], f0[1], -120 * PI/180);\n    let f2 = fold(f1[0], f1[1],  120 * PI/180);\n    shape.remap(x * 3, y * 3 - 2, z) // scale and transform\n         .remap(f2[0], f2[1])        // six-fold reflection\n         / 3                         // normalize distance field\n}\n```\n\nThe 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.\n\nWith a little more tweaking, this produces the Best Possible Snowflake:\n\n[![Picture of a snowflake with both black-and-white and distance field views.  The distance field is perfectly Euclidean](https://www.mattkeeter.com/blog/2026-11-23-snowflake/best.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/best.html)\n\nPlease admire the fact that the field is an [Exact SDF](https://bsky.app/profile/mattkeeter.com/post/3loqglbjuak2n): 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!\n\n* * *\n\nThat's all I've got for now; as always, feel free to [say hi](https://www.mattkeeter.com/about#contact) if you've got your own improvements on the design!",
  "html": "<h1>An O(N) implicit representation for the Koch Snowflake</h1>\n<p>This blog post was supposed to be about the <a href=\"https://en.wikipedia.org/wiki/Menger_sponge\">Menger Sponge</a>.</p>\n<p>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 <a href=\"https://www.mattkeeter.com/projects/halfspace\">Halfspace</a>.</p>\n<p>Here's an example, so you know what you missed:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/sponge.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/sponge.png\" alt=\"Picture of a sponge\" /></a></p>\n<p>You can <strong>click this image</strong> (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.</p>\n<p>Anyways, the blog post was almost done, and I went to link to Inigo Quilez's <a href=\"https://iquilezles.org/articles/sdfrepetition/\">writeup on domain repetition</a>. Down near the bottom of his writeup, he linked to another article titled <a href=\"https://iquilezles.org/articles/menger/\">\"menger fractal - 2011\"</a>. As luck would have it, this was exactly the same trick that I was writing up, some 15 years earlier.</p>\n<p>With the original post scooped, I took it upon myself to use the same tricks on a different fractal – one which I had <em>planned</em> to leave as an exercise for the reader, because I didn't know how to do it!</p>\n<hr />\n<p>That fractal is, of course, the seasonally-appropriate <a href=\"https://en.wikipedia.org/wiki/Koch_snowflake\">Koch Snowflake</a>:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/snowstorm.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/snowstorm.png\" alt=\"Picture of four snowflakes\" /></a></p>\n<p>Let's spell out the rules of the game.</p>\n<p>Our goal is to come up with a function which takes a position <code>(x, y)</code> and returns a signed value: negative for points inside the snowflake, and positive for points outside the snowflake.</p>\n<p>The function should be <strong>closed-form</strong>: 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.</p>\n<p>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.</p>\n<p>(All of these conditions come from the design of the <a href=\"https://www.mattkeeter.com/projects/fidget\">Fidget implicit kernel</a>)</p>\n<p>Most importantly, the function should be <strong>linear in complexity</strong> 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 <code>O(4^N)</code> complexity, which is (to use a technical term) Very Bad; our target is <code>O(N)</code>.</p>\n<p>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):</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/bad_recursion.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/bad_recursion.png\" alt=\"Picture of a snowflake built from many triangles\" /></a></p>\n<p>None of this is particularly well documented (the scripting language is <a href=\"https://rhai.rs/\">Rhai</a>!), 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.</p>\n<hr />\n<h3>Hexagons are the bestagons</h3>\n<p>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.</p>\n<p>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 <a href=\"https://www.mattkeeter.com/blog/2017-05-13-implicit-zeros/\">strategies</a>, but it's nicer to just not do that in the first place.</p>\n<p>For our first fix, we'll instead note that we can replace pairs of little triangles with a single larger triangle:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/hexagons.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/hexagons.png\" alt=\"Picture of a snowflake built with hexagonally-arranged triangles\" /></a></p>\n<p>Notice that each green and blue triangle has two ears poking out, and each one replaces two smaller triangles in the original model.</p>\n<p>The core transform here is <code>hexify</code>, which scales and copies its input six times:</p>\n<pre><code class=\"language-rust\">fn hexify(s) {\n    union([\n        s.remap(x * 3, -y * 3 + 2, z),\n        s.remap(x * 3,  y * 3 + 2, z),\n        s.remap(x * 3 + sqrt(3), -y * 3 - 1, z),\n        s.remap(x * 3 - sqrt(3), -y * 3 - 1, z),\n        s.remap(x * 3 - sqrt(3),  y * 3 - 1, z),\n        s.remap(x * 3 + sqrt(3),  y * 3 - 1, z),\n    ]) / 3\n}\n</code></pre>\n<p>This eliminates the butt joints, although the distance field is far from perfect:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/nobutt.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/nobutt.png\" alt=\"Picture of a snowflake distance field, with no zero-thickness cracks\" /></a></p>\n<p>We've still got an obvious exponential complexity: each call to <code>hexify</code> multiples the element count by 6. What else can we do?</p>\n<h3>Time for repetition</h3>\n<p>It's at this point that I made an interesting observation: if we include the center in the <code>hexify</code> transform, those triangles form a subset of an infinite tiling:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/tiled.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/tiled.png\" alt=\"Picture of triangles repeating forever, which coincide with the level-two triangles in the snowflake\" /></a></p>\n<p>The light blue level-2 triangles in our snowflake are a subset of an infinitely-repeating pattern of darker blue tiles. This is <em>great news</em>! 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:</p>\n<pre><code class=\"language-rust\">let ycut = (((y + 0.5) % 1) - 0.5).abs() - 1/6.;\nlet cut = union(ycut, rotate(ycut, 120), rotate(ycut, 240));\n</code></pre>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/cmyk.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/cmyk.png\" alt=\"Repeated cyan-magenta-yellow bars, with triangles in their negative space\" /></a></p>\n<p>The triangles are in the negative space between bars.</p>\n<p>Using modulo gives us an infinitely field of triangles in <code>O(1)</code> expression terms. We can then build our level-N triangles by simply scaling the triangle pattern:</p>\n<p><a href=\"https://www.mattkeeter.com/projects/halfspace/demo/#model=ZmxhaAEAAACxmDwA4CyMHR81-xTHCARLeFVW6qxqb_ZJTmR-4hqoDJ45JGfkc8KqTkR0tJLlu0mcZhrCRfCpw9IXSRa_X7v4P029FELWqJXU3sy-PU2IWvRFtVlIJELmGmI2pOkbNSUJXCFW3TbsIVwCcDH5AIIR-iDeZU1MGLyeC8MeojsgEyQA4m2A2Ambcp43nrwJDOhAQqBLjqBTMmFENvcChIiuBvREEzkR3BAH4J6RPoXQBL2HeS6U0RMF9Nc3nLDY5qotdSlz2CF_EYaeDv2QT-EosE_sZK0_pe4NHlPjRF8Kfetvns0XvFQb6lBaN4qdx6Uto7CZmEHQZsEcdjXmxUvCWZfOuHTWpZRLwC8Zq0_1cae_Dw15wfmg4U7YKXa8eAYQ2urFyXxiyq0-aBFdIHYCZWKRsW3aCrUrZUFYdX7RGYXQcX_e46RRNBX-mjaURN2tMR6kuHM6IiJbC0uuuHDAhSssOyoDo8jkGxfBzpMxaHvzwp1lWAQJQcAMiJ2YS6WMa3K3yePruMGWiQopPCreUGgJV_sh9GraooCv3BBHM2U0SkYFXRpSt9J2CazaOd5jHH_CIz6P07V1R_6vp0idvcfBg75P_6uMRJwgNrSlecVUNgOQxyMn1kU2Cmcztm6XS45mNBWMjWcCJPIe_AkFwd_a5IBWeRoptcqAEoxG0KQn9eiPx5yrrMfE7piu58YgN77QEG6LAkEznlu4GOEupC9yW55rVJWUzLKF2p7eQAXvdgPvE6k33RpNolRf_6YqY78qww2onFeRJy6UTJ6nC-k69iRQu2-BKHqARsrF6W9J_4WB2kf-s0IjOkCz0U6sZjN3nKVGVp9u9bitcGdiHM_qdLb1Dcq6Bnp7fJQUAWj2ZVP1kXMxYfNUgEkkVOBrz1DA9t52UX-NBW-Cp0LvoL5bFznSfsOhBDX2qgaFE2i-EQkCsZSWlp4R3uCQFl_EF2gkFyECmsV-CCBoq9yVoUMDIIujhO2oxfZBiaMc83dDOkZG_kECLHdxNM-56GQ9hODo3cIg\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/many.png\" alt=\"More repeated triangles\" /></a></p>\n<p>Each level of the pattern is <code>O(1)</code>, so this meets our <code>O(N)</code> specification.</p>\n<p>And voila! We have constructed our snowflake!</p>\n<h3>Sweeping up the snowstorm</h3>\n<p>Unfortunately, we have also constructed a veritable Cantor duststorm of miscellaneous triangles, which is obvious in the black-and-white rendering:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/dust.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/dust.png\" alt=\"A black-and-white image of the above, with many triangles outside the snowflake\" /></a></p>\n<p>How can we preserve only the central snowflake?<br />This is where things start to get <em>sneaky</em>.</p>\n<p>Remember, each of these triangles is a <strong>distance field</strong>. We can dilate the distance field by subtracting an offset. Here's what that looks like on our original star, showing two offsets:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/dilated.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/dilated.png\" alt=\"A six-pointed star with two offsets\" /></a></p>\n<p>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:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/clipped.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/clipped.png\" alt=\"A six-pointed star with an offset in darker red, mostly clipping the smaller green triangles\" /></a></p>\n<p>If you look carefully, you can see that this <strong>almost works</strong>: 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.</p>\n<p>Here's what it looks like after a few rounds of recursion:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/almost.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/almost.png\" alt=\"Very nearly a correct snowflake\" /></a></p>\n<p>It looks <em>interesting</em>, but not quite what we want!</p>\n<p>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:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/circle.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/circle.png\" alt=\"Triangles showing different fields\" /></a></p>\n<p>The dilation of this shape doesn't hit the green triangles:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/good_dilation.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/good_dilation.png\" alt=\"Triangle with dilation not hitting other triangles\" /></a></p>\n<p>Using this as the basis for recursing, at last, our snowflake is correct!</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/final.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/final.png\" alt=\"A correct snowflake\" /></a></p>\n<h3>Thinking with portals</h3>\n<p>This achieves our initial goal, but is still slightly unsatisfying: the underlying distance field is very wonky (technical term).</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/wonky.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/wonky.png\" alt=\"The distance field of the snowflake, which has widely varying gradients\" /></a></p>\n<p>The inner field is correct, but the outer field has widely varying gradients (shown by the spacing between the lines).</p>\n<p>After posting on social media, <a href=\"https://alexaschor.com/\">Alexa Schor</a> came up with an <a href=\"https://bsky.app/profile/bsky.alexaschor.com/post/3n2i4u6nr4s2l\">elegant alternate design</a> based on <a href=\"https://alexaschor.com/into-the-portal/\">Into the Portal: Directable Fractal Self-Similarity</a>.</p>\n<p>The core idea here (adapted from her design) is using <strong>reflections</strong>, which construct the union of a shape and its reflection without <em>fully copying the shape</em>. We can use reflections to revisit our earlier <code>hexify</code> function.</p>\n<p>Remember, <code>hexify</code> is used to construct six copies of the model at different points in space:</p>\n<pre><code class=\"language-rust\">fn hexify(s) {\n    union([\n        s.remap(x * 3, -y * 3 + 2, z),\n        s.remap(x * 3,  y * 3 + 2, z),\n        s.remap(x * 3 + sqrt(3), -y * 3 - 1, z),\n        s.remap(x * 3 - sqrt(3), -y * 3 - 1, z),\n        s.remap(x * 3 - sqrt(3),  y * 3 - 1, z),\n        s.remap(x * 3 + sqrt(3),  y * 3 - 1, z),\n    ]) / 3\n}\n</code></pre>\n<p>We can instead write <code>hexify</code> in terms of a <code>fold</code> operation, which performs a combined reflection + union across a particular axis:</p>\n<pre><code>fn fold(x, y, angle) {\n    let nx = -sin(angle);\n    let ny =  cos(angle);\n    let dist = x * nx + y * ny; // dot product\n    let offset = max(dist, 0);\n    [x - 2 * offset * nx, y - 2 * offset * ny]\n}\n\nfn hexify(shape) {\n    let f0 = fold(x,         y,  120 * PI/180);\n    let f1 = fold(f0[0], f0[1], -120 * PI/180);\n    let f2 = fold(f1[0], f1[1],  120 * PI/180);\n    shape.remap(x * 3, y * 3 - 2, z) // scale and transform\n         .remap(f2[0], f2[1])        // six-fold reflection\n         / 3                         // normalize distance field\n}\n</code></pre>\n<p>The core thing to observe here is that we are only creating a single modified shape, instead of six transformed copies. Repeated applications of <code>hexify</code> are each <code>O(1)</code> in additional terms, thanks to common subexpression elimination.</p>\n<p>With a little more tweaking, this produces the Best Possible Snowflake:</p>\n<p><a href=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/best.html\"><img src=\"https://www.mattkeeter.com/blog/2026-11-23-snowflake/best.png\" alt=\"Picture of a snowflake with both black-and-white and distance field views.  The distance field is perfectly Euclidean\" /></a></p>\n<p>Please admire the fact that the field is an <a href=\"https://bsky.app/profile/mattkeeter.com/post/3loqglbjuak2n\">Exact SDF</a>: 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!</p>\n<hr />\n<p>That's all I've got for now; as always, feel free to <a href=\"https://www.mattkeeter.com/about#contact\">say hi</a> if you've got your own improvements on the design!</p>\n"
}