Lesson 4.3 · IV Tools
Preview and exact computation
What it's about: The view has to be quick enough, the print has to be exact. If the exact model takes too long, the browser shows a coarser preview that is ready five to ten times sooner, and computes exactly afterwards. STL and 3MF are always exact. What is put off is not the computation, only its accuracy. Why knotflow does not take the other, better-known way of computing everything only when it is needed (lazy evaluation) is in the deeper look at the end.
What you should know first: Lesson 4.1 (the modeller in the browser) and 4.2 (the cache).

1. Putting off what is worth it: accuracy
What you really don't need while dragging is full accuracy. Some of the built-in functions do not decide what is created, only how finely it is approximated. These are exactly the expensive ones:
| in a preview | instead of | saved |
|---|---|---|
isosurface with twice the voxel size |
voxel as given |
only one eighth of the cells left |
simplify is skipped |
collapsing edges | the whole simplification |
| triangles with a deviation of at least 0.1 mm | 0.01 mm | many triangles |
On the command line, kf render … --draft shows the same
preview:
| Model | exact | preview |
|---|---|---|
| Voronoi nets | 7.1 s | 1.4 s |
| Tree roof | 6.6 s | 1.0 s |
| Romanesco | 1.6 s | 0.24 s |
Isn't this magic, that is, something where the language secretly does
something other than what is written? The line is drawn in the same
place as for the tolerance: the tolerance was never part of the model
but is chosen when displaying and saving. Voxel size and
simplify are its relatives. The preview does not change
what the model describes, only how accurately it is shown. Both
functions say so in their help, too.
2. Quick enough, and no coarser than necessary
When does the browser show the preview? The obvious answer would be: only while a slider is moving, and always exactly when you let go. For the Voronoi nets that would mean waiting 13 seconds after every release. The better question is: does the view have to be as exact as the print at all? No, it has to be quick enough. It may of course still be exact if that costs nothing. Three rules follow from this:
- Exact if it is quick enough. While a slider is moving, that means at most 150 ms; otherwise (after letting go, after a pause in typing) at most 2 seconds.
- How is that known? From the latest measurement of this model. If it was an exact run, its time counts; if it was a preview, it is estimated: about six times as long. So a model you open for the first time appears as a preview first and becomes exact right after, if the estimate fits the budget. You always see something quickly.
- The print is always exact. "save STL" and "save
3MF" compute the exact model if the view is only a preview, at that
moment if need be. Byte for byte, it is the same file as from
kf.
If the status line says "preview", a click on it computes the exact model for the view as well. Measured in Chrome:
| Voronoi nets | Vase | |
|---|---|---|
| open | 1.9 s (preview) instead of 13.6 s | 0.01 s, exact |
| drag a slider | 1.5–1.9 s per step (preview) | 0.02–0.03 s, exact |
| let go | nothing to compute | nothing to compute |
| click on "preview" | 11.9 s, exact afterwards | – |
| save STL afterwards | 0.2 s (from the cache) | 0.2 s |
| save STL without an exact view | 11.8 s | – |
So for the Voronoi nets a preview is not a compromise while dragging but the normal case in the view. The 12 seconds for the exact run are only spent when you really need it.
3. Preview and cache
A preview has to live alongside the cache without spoiling it. The rule is quickly stated:
- Every entry remembers whether it is approximate.
- A draft run gladly takes exact entries. If you change the thickness of the tree roof, the parts that do not depend on it stay in full quality, provided they were computed exactly before.
- An exact run never takes an approximate entry. It recomputes and replaces it.
The interesting question is what counts as approximate. It
would seem natural to keep track of when a coarser function ran, and to
mark only the statements in which that happened. That goes wrong:
export a only reads the name a and calls
nothing coarser itself. Its result would be stored as exact, even though
a came from a preview. A value does not carry around how it
came about. The other extreme, treating every statement of a
draft run as approximate, would be correct but wasteful. The rule lies
in between: as soon as anything in a draft run was approximate,
every statement after it counts as approximate. Before that,
there was nothing approximate it could have read. A model without any
coarser functions, such as an L-system made of tubes, is therefore
computed exactly even in a preview, and the exact run afterwards takes
everything from the cache. A test checks that nothing approximate ever
reaches an exact run.
Expensive calls such as the finite element analysis of the bone still stay exact. They are stored under the values of their arguments (Lesson 4.2). An approximate value as an argument gives a different key anyway. Only if the function itself computed more coarsely is its result approximate. That is why the structural analysis does not run a second time when you let go. A test pins this down as well.
The same goes for triangles: a surface that has already been broken into triangles at 0.01 mm keeps those triangles in the preview instead of getting coarser ones.
4. When a run is cancelled
Lesson 4.1 named a rule: if a run takes longer than a second and something new comes in, the page throws the worker away and starts a fresh one. But the cache goes with the worker, and with it everything that would have made the next run fast. So the rule only applies to typing: a slow model should not block writing, and after a change to the text much has to be computed anew anyway. Typing may also cancel a long preview after a second.
Nothing else ever cancels:
- A slider waits until the running computation is finished and then takes the latest value. If it cancelled, every step would lose the cache, and no preview would ever arrive.
- Letting go does not either. Otherwise the tree roof, for example, would recompute all 8 statements instead of 3.
- An STL or 3MF file being made is never cancelled either.
On top of that comes the bookkeeping around it, which is easy to overlook:
- If the module crashes (recursion too deep), also while a file is being made, the worker is replaced, and the message is the same as in the view. A waiting button ("exact STL …") then gets an answer instead of waiting for ever.
- Another model starts without an estimate: the time of the previous one says nothing about it.
- The latest measurement always counts, preview or exact. So the view becomes exact again on its own when a model has become quicker.
5. Limits
- Two levels: there are only preview and exact. With intermediate steps (say, one and a half times the voxel size) the budget could be met better: as exact as is possible in 2 seconds.
- Computing in parallel. Because all functions are pure, independent statements and the elements of a list could run at the same time on several cores. On the command line that is easy. In the browser, threads need special HTTP headers (cross-origin isolation) that not every web server can set.
- A preview the model itself can see, for example as
a value
preview. Then the bone could compute fewer remodelling steps while dragging. That would be explicit in the model and not magic, but it would be a new way for a value to depend on something outside. It would have to go into the fingerprint.
6. A deeper look: why not lazy?
The language has no mutable values (Lesson 2.2). That would make lazy evaluation possible: computing each expression only when its value is needed. Would that make it faster? The measurements say: hardly. The expensive work is not in the language but in a few geometry functions.
What lazy means
Strict (eager) means: let a = f(x) computes
f(x) right away. Lazy means: at first, a is
only a promise, a thunk, that is, "here is f(x)
still to do, work it out when someone asks". If nobody asks, it is never
computed. If someone asks twice, the result is remembered (call by
need). Haskell works like this, and so does Nix, whose modules
knotflow's follow (Lesson 2.4).
That no value ever changes in knotflow is the precondition: only then does it not matter when something is computed. So the question is not whether it would be possible, but whether it is worth it.
Measure first
Where does the time go? For each example separately: evaluating the
language (run) and breaking the surfaces into triangles
(scene, tolerance 0.01 mm), on the command line:
| Model | Evaluation | Triangles | where the time goes |
|---|---|---|---|
| Bone | 7,985 ms | 0 ms | finite elements, smoothing the field |
| Voronoi nets | 6,252 ms | 2 ms | isosurface, simplify |
| Tree roof | 5,882 ms | 3 ms | isosurface, simplify |
| Tour 4 (recursion) | 443 ms | 14 ms | the interpreter |
| Romanesco | 24 ms | 590 ms | 4.7 million triangles |
| Vase, pot, knot, chain … | 0.1–3 ms | 1–47 ms | – |
Where evaluation takes long, a profiler (on macOS,
sample) almost always shows the same functions:
Implicit::mesh (the isosurface),
decimate::simplify and fem2d::analyze_plane.
These are built-in functions written in Rust. The interpreter itself
only matters for the deep recursion of Tour 4.
Lazy evaluation saves work whose result nobody needs. But in a model
almost everything flows into an export. A line that
contributes nothing is usually a mistake, not a case worth making
fast.
What laziness would cost
- Errors in the wrong place. An error would only show up where a value is needed, not where it is written. The messages with a call chain and a mark in the editor (Lesson 2.2) assume that a value is computed where it is written. And an error in an unused line would stay completely silent.
- The stack. Lazily,
fold(xs, 0, (a, x) => a + x)first builds a chain of a million thunks,((0 + x₁) + x₂) + …, and evaluates it recursively at the end. In the browser the stack is enough for about 290 nested calls (Lesson 4.1). In Haskell such chains are called space leaks: they are the best-known problem there, and people fight them with annotations that force strict evaluation in specific places. - Predictability. With strict evaluation it is obvious when what gets computed. The limits (at most 10 million calls, Lesson 2.3) and the cache depend on that as well.
Laziness suits Nix well: the package collection has tens of thousands of entries, and a single machine needs only a few of them. In knotflow, libraries define almost nothing but functions, and those cost nothing until you call them.
What laziness already gives
The useful parts of laziness are already there, in other places:
- The cache is call by need per statement (Lesson 4.2): whatever has not changed is not recomputed but taken from memory.
- The geometry stays exact until the very end. NURBS surfaces are only broken into triangles at the last moment, once it is clear what is needed and at which tolerance (Lesson 1.1).
- Instances only become separate shapes when the STL is downloaded, and in the 3MF not at all (Lessons 3.1 and 4.6).
And the NURBS themselves? Creating them later would gain nothing: building a surface takes microseconds, and moving, rotating and scaling only touch its control points. What is expensive is what comes afterwards.
Try it yourself
cargo run --release -p kf -- render examples/voronoi_sphere.kf --draft -o out/preview.png
cargo run --release -p kf -- render examples/voronoi_sphere.kf -o out/exact.png
- Compare the two pictures. Where can you see the difference, and why exactly there? (Hint: how thick are the thinnest strands compared with the voxel size?)
- Open the tree roof in the browser and drag
thick. How many statements are recomputed per step? Then click on "preview": which statements does the exact view take from the cache, and which does it compute again, even some that do not depend onthickat all? Why? - Write
fold([1 .. 100000], 0, (a, x) => a + x)into a model. How deep would the chain of thunks be if the language were lazy? And how deep is the stack now? - Something to think about: which other built-in functions only decide
how finely something comes out, and not what? Where
does the line run for
blur, or for the cell size of agrid?