knotflow Lessons PDF ↓ Deutsch Handbook Modeller ↗ Source

Lesson 4.1 · IV Tools

In the browser: WebAssembly, a worker and three.js

What it's about: The modeller also runs in the browser, with nothing to install. It is the same Rust code as in kf, just compiled to WebAssembly. The text is on the left, the model on the right. Every param line becomes a slider, and errors are marked right in the text. Browser and command line also write the same STL and 3MF files, byte for byte. That is harder than it sounds, and it is the most interesting numerical part of this lesson.

What you should know first: To use it, nothing – section 1 is enough, and the public version runs at https://fliegendreck.codefloe.page/knotflow/. For the sections after that it helps to know Lesson 1.3 (tessellation), 1.4 (floating-point numbers) and 2.1 (the interpreter), and to be able to read a little JavaScript.

The modeller in the browser: text on the left, model on the right, sliders from the param lines

1. Starting and using it

On the web: https://fliegendreck.codefloe.page/knotflow/. Or locally from the source (needs Rust, wasm-pack and Node.js):

cd web
npm install    # once: Vite, CodeMirror, three.js
npm run dev    # builds the WASM module, starts the server: localhost:5173

An error: marked, with help for the function and the message as on the command line

Projects and libraries

How libraries work in the language is explained in Lesson 2.4. The browser has no file system, but it has projects. Above the editor is a bar with the files:

Each file has its own state in the editor, with its own undo history. An error in a library is marked in its tab (red, with a dot in the bar), and in the model the call that led there is marked as well. The banner above the view names the file: "Error in shapes.kf, line 3". Clicking it opens the spot.

A slider always writes its value into the model, even while a library is open.

Projects as real files. Under "Project", "Open folder …" opens a folder on your computer (in Chrome and Edge, via the File System Access API). Every .kf file there with param or export is a model; the others are its libraries. The browser reads and writes exactly the files that kf uses too, and checks every second whether another program has changed them. So you can write in your favourite editor (with the language server from Lesson 4.4) and watch in the browser. After a reload the folder comes back if the browser allows it; otherwise a button offers to open it again. "Save to a folder …" turns an example into such a project, and "Download as ZIP" works in any browser.

Even a model with an error keeps its sliders: the param lines are then evaluated on their own. And the editor helps with libraries: after knots. it suggests the pub names, with signature and comment (the same evaluation as kf help, from the parser).

Data. From a folder the page reads exactly the files whose paths the model names in read("…"), from subfolders too (Lesson 2.5). Everything else in the folder stays unread, even hundreds of megabytes of it. When another program changes a file that is read, the page notices within a second and computes again, as with the .kf files. The examples get the files lying next to them in examples/, just as kf on the command line does. A project as a ZIP holds the files its model reads.

The files a model reads are in the file bar under "Data". A text file in UTF-8 can be edited there, and the model is computed again at once: change an edge in hex_tiles.json from "forest" to "village", and little houses stand there instead of trees. For an example the change stays in the browser until the example is reset; for a folder it is written into the file. A file that is no UTF-8 (a font, a picture, a Latin-1 text) is shown only by its size: edited as UTF-8, a Latin-1 text would break silently.

2. The path of a model

Editor ──text, slider values──▶ Worker ──▶ WebAssembly: lang::run → scene → with_normals
   ▲                                                         │
   └──parameters, messages◀── Worker ◀──Float32Array, Uint32Array
                                  │
                                  └──▶ three.js: BufferGeometry → graphics card

WebAssembly (WASM for short) is machine code for an imagined, simple machine. When the page loads, the browser translates it into real machine code for your processor. Rust can compile straight to WASM (--target wasm32-unknown-unknown). A WASM module has a single large memory, a byte array called linear memory. All Rust data lives there: vectors, meshes, the syntax tree. JavaScript sees only numbers and this byte array. wasm-bindgen generates the glue code in between. In Rust you write

#[wasm_bindgen]
pub fn evaluate(src: &str, overrides: &JsValue, tol: f64, files: &JsValue, draft: bool) -> JsValue

and get a JavaScript function evaluate(text, {twist: 150}, 0.01, files, false) (files are the project's data files, draft asks for a preview, Lesson 4.3). The text is copied from JavaScript into linear memory, and the result is rebuilt as a JavaScript object. The whole module is about 2 MB (just under 900 KB compressed).

A worker is a second thread in the browser. The page itself has only one: it draws, reacts to keys and runs JavaScript. If that thread spends five seconds on the Voronoi sphere, everything freezes, typing included. That is why the modeller runs in a worker (web/src/worker.ts), and the two talk to each other through messages. The triangle data is not copied but transferred: the block of memory changes owner, and the worker can no longer use it afterwards. You know this from Rust as a move.

Who computes when? web/src/runner.ts follows three rules:

  1. Only one computation runs at a time. Whatever arrives in the meantime waits, and only the newest waiting request counts. If you drag a slider quickly, the values in between are skipped.
  2. Anything that runs longer than a second is cancelled as soon as you type. A WASM function cannot be interrupted from outside, so the whole worker is terminated and a fresh one started. That costs a few milliseconds, because the compiled module (WebAssembly.Module) is reused. This way a slow model never blocks typing. Sliders and saving a file never cancel; Lesson 4.3 explains why.
  3. The same text with the same values is never computed twice.
Model native (kf) WebAssembly triangles
Vase 0.02 s 0.05 s 73,436
Romanesco 1.7 s 2.2 s 4,719,904
Voronoi nets 5.8 s 9.4 s 990,124
Bone (30 steps) 7.5 s 9.7 s 9,136

(Exact runs without cache; WebAssembly measured in Node, native including writing the STL.) For the large models WASM is 1.3 to 1.6 times slower than native. That is typical: the browser compiles faster and more cautiously than LLVM, and every memory access is bounds-checked.

3. What a graphics card needs

three.js is a library on top of WebGL, the browser's graphics interface. Only a small part of it is needed (web/src/viewer.ts):

One point needs some thought: a graphics card knows exactly one normal per vertex. Our mesh shares vertices across edges, which matters for being watertight (Lesson 1.3). But at the rim of a cylinder the same vertex belongs to the side, whose normal points sideways, and to the lid, whose normal points up. If you average the two, the edge looks soft and smeared. Mesh::with_normals therefore does what the PNG renderer does: where a surface bends by more than 35°, the vertex is duplicated for display, one copy per side. The mesh for the STL file stays unchanged.

Two more small things:

4. The text stays the model

When you let go of a slider, its value has to go to the right place in the text. Guessing with a regular expression would be unreliable, for example with param inside a comment. So while reading, the parser remembers where the default value is (Param::literal), but only if it is a plain number or true/false. With param n = 2 * 3 there is nothing sensible to write back. The slider still works then; its value just stays outside the text.

A detail that is easy to miss: positions in the text are counted differently. Rust stores text as UTF-8 and counts in bytes; ä or ° is 2 bytes long there. JavaScript counts in UTF-16 units, where ä or ° is one unit long. Labels and comments in the examples contain such characters (umlauts, the degree sign in "[°]"), so without converting, every mark after them would be off by a few characters. utf16() in crates/wasm/src/lib.rs does the conversion.

One more detail: after you let go, the text is different, but the result is the same. To avoid computing it again (six seconds for the Voronoi sphere), the page tells the runner: "treat the request for the old text as the request for the new one" (Runner.rename). The positions in the result are shifted by the change in length.

5. Limits

6. A deeper look: two stacks and tail recursion

Recursion needs stack (Lesson 2.1). That is why the command line evaluates in a thread with 64 MB of stack. The browser offers no such option, and here there are even two stacks:

A Chrome worker fits about 290 levels of a plain recursion like 1 + f(n - 1), about 135 if each level goes through map, about 100 with a long expression on the way. The command line allows 1000 nested calls. When it gets too deep, the engine stops with a RangeError, and the module is left in an unknown state: the page has to start a fresh worker, and the error has no place in the model.

So the browser stops a model earlier itself, with the usual message at its place: after 250 nested calls (a built-in that calls back, like map, counts as one) or 1000 expressions evaluated inside each other (lang::interp::MaxDepth, set in crates/wasm on the cache). A recursion through long expressions can still run out of the engine's stack first; then the worker reports the RangeError as an understandable error, and the page starts a fresh worker.

How deep do models really recurse?

Three patterns appear in the examples:

Pattern Example Depth
Loop as recursion threshold in the bone (bisection) 60
Tree recursion floret (Romanesco), crown_at (tree roof) 3–5
List recursion x + total(rest) length of the list

Tree recursion is shallow. Every level multiplies the work (buds to the power of levels). Long before the stack runs short, the model would be too big. Only loop-like recursion gets deep, and it can almost always be written so that the recursive call is the last thing a function does:

fn threshold(d, s, lo, hi, k) =
  if mean(…) > volume then threshold(d, s, mid, hi, k - 1)
                      else threshold(d, s, lo, mid, k - 1)

After the call to threshold there is nothing left to do; its result is directly the result. This is called a tail call. A tail call needs no new space on the stack: the calling function is finished, so its space can be reused.

Not so with fn count(n) = 1 + count(n - 1): after the call, 1 still has to be added, so every level has to remember where it was. With an accumulator, a parameter that carries the intermediate result along, it becomes a tail call:

fn count(0, acc) = acc
fn count(n, acc) = count(n - 1, acc + 1)

Haskell, Scheme and Erlang do exactly the same. For lists there are fold, sum and comprehensions anyway; they run in Rust and need none of the language's stack at all.

The trampoline

The interpreter performs tail call elimination. If a call is in tail position, that is, as the body of an equation, as a branch of an if, as an arm of a match or as the expression before where, it is not executed. Instead, eval_tail returns it as "call f with these arguments next" (Next::Call). call runs such calls one after another in a loop. Because control bounces back to the loop after every call and from there on to the next call, the technique is called a trampoline. Not in tail position are the right-hand side of and and or and a composition f >> g: there call calls both functions itself, one after the other. x |> f, on the other hand, is an ordinary call f(x) and may come last.

# sum.kf: fn sum_to(n, acc) = sum_to(n - 1, acc + n) … let a = sum_to(1000000, 0)
$ kf render sum.kf
values:
  a          = 500000500000
the model exports nothing (export …)

A million calls, in the browser too, in 0.5 s. The test tail_calls_need_no_stack computes 100,000 levels on a 512 KB stack, also for mutual recursion (even calls odd calls even).

Two consequences have to be accepted deliberately:

The trampoline has a price that has to be measured: every extra function on the way from one level of recursion to the next costs the engine stack. If every call went through eval_tail, the depth for normal, non-tail-recursive calls in Node would drop from 846 to 529. That is why eval handles calls itself, and eval_tail only comes into play for bodies that can end in a call. That gives 712. For deep, non-tail recursion the only option left would be an interpreter that uses no Rust stack at all. None of the example models needs one.

7. A deeper look: the same file, bit for bit

The STL from the browser is byte-identical to the one from kf. That is not a matter of course: if each of them computes with its platform's maths library, the comparison looks like this:

Model triangles different largest deviation
Pot 2,048 0 –
Vase 73,628 6 1.4·10⁻¹⁵ mm
Facade 10,528 12 1.18 mm

(Measured before both got the same library.) For the vase the difference is tiny, the last bit. For the facade, twelve triangles are up to a millimetre off, even though the same code ran. The reason:

IEEE 754 requires correct rounding only for + − × ÷ and √ (and for mul_add). Lesson 1.4 relied on this, and it is why every processor computes these operations the same way. For sin, cos, pow, exp and log there is no such requirement. Every maths library may round a little differently. x.sin() in Rust calls the operating system's library: on macOS Apple's, in WebAssembly a bundled one (a port of the C library musl). Both are very accurate, but not identical, and now and then they differ in the last bit.

Mostly that does not matter: a wrong last bit is 10⁻¹⁶ relative, no printer can see that. But there are decisions. Lesson 1.4 showed how to get the sign of an orientation test exactly (orient2d). But if the inputs already differ in the last bit, because an angle was computed via cos, then the test is exact, but for different inputs. If a decision is right on the edge (which point comes first, is this cell split once more, which ear is cut off), it tips one way on one platform and the other way on another. One bit turns into a differently divided piece of surface. Both results are valid, just not the same.

The fix is simple: the same library everywhere. crates/geom/src/math.rs forwards sin, cos, atan2, pow and friends to the libm crate, on every platform. glam too, which computes rotations via sine and cosine, gets the libm feature. With that:

$ node tools/same-stl.mjs
…
bone             identical  (STL 456.884 bytes, 3MF 85.814 bytes)
facade           identical  (STL 526.484 bytes, 3MF 103.088 bytes)
pot              identical  (STL 102.484 bytes, 3MF 19.607 bytes)
star             identical  (STL 1.884 bytes, 3MF 1.398 bytes)
vase             identical  (STL 3.671.884 bytes, 3MF 764.950 bytes)
…

The tool computes every example once with the WASM module (in Node, no browser needed) and once with kf, and compares the STL and the 3MF: all are identical, the bone included. There, many remodelling steps with finite elements and powers run one after the other, and any difference in the last bit would build up. That is the hardest test. To keep it that way, the whole project follows one rule: transcendental functions only through geom::math.

Why the effort? Byte equality makes results comparable. A test can check whether a file has changed, a cache can reuse results, and if someone sends you an STL, you can rebuild it exactly from the model. It is the same attitude as "same description, same bone" in Lesson 3.13, now across platforms.

Try it yourself

cd web && npm install && npm run dev       # → http://localhost:5173
cargo build --release -p kf                # then browser and command line
node tools/same-stl.mjs                    # compare byte for byte

Exercises:

  1. Open the vase, drag twist and watch line 5 while you do. Then change the text yourself, say to in 0..720. The slider adapts.
  2. Write fn count(0) = 0, fn count(n) = 1 + count(n - 1), let a = count(400) and find the limit in your browser (Safari and Firefox have different stacks from Chrome). Then write count with an accumulator and try count(1000000, 0).
  3. Set the tolerance to 0.2 mm, switch on Triangles and switch between vase and pot. Where does the tessellation place many triangles, where few (Lesson 1.3)?
  4. Something to think about: sqrt needed no special treatment, sin did. Why is correct rounding easy to guarantee for √ but hard for sin? (Keyword: the "table maker's dilemma". To round a number close to the midpoint between two f64 correctly, you may need a great many digits.)