calib-corpora / pipeline /reasoning_extra.py
worthant's picture
Rebuild calibration corpus for DeepSeek-V4-Flash-0731 imatrix
bf3d2af verified
Raw
History Blame Contribute Delete
30.1 kB
"""Additional reasoning generators (same contract as reasoning.GENERATORS).
Split out purely to keep each file readable. Same rules apply: every number is
computed at build time, and no problem is sourced from an evaluation set.
"""
from __future__ import annotations
import math
import random
import numpy as np
from reasoning import _f
def rodrigues(rng):
axis = np.array([rng.uniform(-1, 1) for _ in range(3)])
axis /= np.linalg.norm(axis)
ang = round(rng.uniform(0.3, 2.6), 3)
v = np.array([round(rng.uniform(-4, 4), 2) for _ in range(3)])
c, s = math.cos(ang), math.sin(ang)
rot = v * c + np.cross(axis, v) * s + axis * float(np.dot(axis, v)) * (1 - c)
K = np.array([[0, -axis[2], axis[1]], [axis[2], 0, -axis[0]], [-axis[1], axis[0], 0]])
R = np.eye(3) + s * K + (1 - c) * (K @ K)
q = (f"Rotate the vector v = {_f(v)} by {ang} rad about the unit axis k = {_f(axis)} "
f"using Rodrigues' formula. Also give the equivalent 3x3 matrix and verify the two agree.")
th = (f"Rodrigues: v_rot = v cos θ + (k × v) sin θ + k (k·v)(1 - cos θ)\n\n"
f"cos θ = {_f(c)}, sin θ = {_f(s)}\n"
f"k × v = {_f(np.cross(axis, v))}\n"
f"k·v = {_f(float(np.dot(axis, v)))}\n\n"
f"term 1: v·cos θ = {_f(v*c)}\n"
f"term 2: (k×v)·sin θ = {_f(np.cross(axis,v)*s)}\n"
f"term 3: k(k·v)(1-cos θ) = {_f(axis*float(np.dot(axis,v))*(1-c))}\n"
f"sum = {_f(rot)}\n\n"
f"Matrix form R = I + sin θ·K + (1-cos θ)·K², with K the cross-product matrix of k:\n"
f"{np.array2string(R, precision=5, suppress_small=True)}\n\n"
f"R·v = {_f(R @ v)} — matches to floating point.\n\n"
f"Length check: |v| = {_f(float(np.linalg.norm(v)))}, |v_rot| = {_f(float(np.linalg.norm(rot)))}. "
f"Rotation is an isometry so these must agree, and they do. "
f"det R = {_f(float(np.linalg.det(R)))} (must be +1 — a value of -1 would mean a reflection crept in).")
a = (f"v_rot = {_f(rot)}\n\nMatrix form:\n{np.array2string(R, precision=5, suppress_small=True)}\n\n"
f"Both routes agree. |v| is preserved ({_f(float(np.linalg.norm(v)))} → "
f"{_f(float(np.linalg.norm(rot)))}) and det R = {_f(float(np.linalg.det(R)))}, confirming a proper "
f"rotation rather than a reflection.\n\n"
f"Use the vector form for a one-off rotation (three cross/dot products, no matrix build); build the "
f"matrix when you will reuse the same rotation across many vertices.")
return q, th, a, "rodrigues-rotation"
def look_at(rng):
eye = np.array([round(rng.uniform(-10, 10), 2) for _ in range(3)])
target = np.array([round(rng.uniform(-4, 4), 2) for _ in range(3)])
up = np.array([0.0, 1.0, 0.0])
fwd = target - eye
if np.linalg.norm(fwd) < 1e-6:
fwd = np.array([0.0, 0.0, -1.0])
z = -fwd / np.linalg.norm(fwd) # camera looks down -Z
x = np.cross(up, z)
degenerate = np.linalg.norm(x) < 1e-6
if degenerate:
x = np.array([1.0, 0.0, 0.0])
x = x / np.linalg.norm(x)
y = np.cross(z, x)
q = (f"Build the camera basis for a look-at from eye {_f(eye)} to target {_f(target)} with world up "
f"(0,1,0), in the OpenGL convention where the camera looks down -Z. Show the orthonormalisation and "
f"say when this construction breaks.")
th = (f"Forward direction: t - e = {_f(fwd)}, length {_f(float(np.linalg.norm(fwd)))}.\n\n"
f"The camera's +Z axis points *backwards* in the OpenGL convention, so\n"
f" z = -normalize(t - e) = {_f(z)}\n\n"
f"Right axis from the world up:\n"
f" x = normalize(up × z) = {_f(x)}\n"
f" |up × z| = {_f(float(np.linalg.norm(np.cross(up, -fwd/np.linalg.norm(fwd)))))}\n\n"
f"True up, recovered so the basis is exactly orthonormal rather than inheriting any skew from the "
f"world up vector:\n y = z × x = {_f(y)}\n\n"
f"Orthogonality check: x·y = {_f(float(np.dot(x,y)))}, x·z = {_f(float(np.dot(x,z)))}, "
f"y·z = {_f(float(np.dot(y,z)))} — all zero to floating point.\n\n"
f"Degenerate case: when the view direction is parallel to the world up, up × z is the zero vector and "
f"normalising it produces NaN. That is the classic 'camera flips out when you look straight down' bug. "
+ ("This case *is* nearly degenerate here.\n" if degenerate else "Not the case here.\n"))
a = (f"Camera basis:\n x (right) = {_f(x)}\n y (up) = {_f(y)}\n z (backward)= {_f(z)}\n\n"
f"The rotation part of the view matrix is the transpose of [x y z], since a view matrix is the inverse "
f"of the camera's world transform and the inverse of an orthonormal matrix is its transpose. The "
f"translation column is -[x·e, y·e, z·e] = {_f(np.array([-float(np.dot(x,eye)), -float(np.dot(y,eye)), -float(np.dot(z,eye))]))}.\n\n"
f"Breaks when the view direction is parallel to the world up: `up × z` collapses to zero and you get "
f"NaN. Guard it by falling back to a different up vector when |up · forward| exceeds about 0.9999 — "
f"this is exactly why orbit controls clamp polar angle short of the poles.")
return q, th, a, "look-at-basis"
def moller_trumbore(rng):
v0 = np.array([round(rng.uniform(-3, 3), 2) for _ in range(3)])
v1 = np.array([round(rng.uniform(-3, 3), 2) for _ in range(3)])
v2 = np.array([round(rng.uniform(-3, 3), 2) for _ in range(3)])
o = np.array([round(rng.uniform(-6, 6), 2) for _ in range(3)])
centroid = (v0 + v1 + v2) / 3
d = centroid - o + np.array([rng.uniform(-.6, .6) for _ in range(3)])
d = d / np.linalg.norm(d)
e1, e2 = v1 - v0, v2 - v0
p = np.cross(d, e2)
det = float(np.dot(e1, p))
q = (f"Ray-triangle test with Möller-Trumbore. Triangle v0={_f(v0)}, v1={_f(v1)}, v2={_f(v2)}. "
f"Ray origin {_f(o)}, direction {_f(d)}. Hit or miss, and where?")
if abs(det) < 1e-8:
th = (f"e1 = {_f(e1)}, e2 = {_f(e2)}\np = d × e2 = {_f(p)}\ndet = e1·p = {_f(det)}\n\n"
f"|det| is below epsilon: the ray is parallel to the triangle's plane, so there is no unique "
f"intersection point. Reject.")
a = f"**Miss** — determinant {_f(det)} is degenerate, the ray runs parallel to the triangle plane."
else:
inv = 1.0 / det
t_vec = o - v0
u = float(np.dot(t_vec, p)) * inv
qv = np.cross(t_vec, e1)
v = float(np.dot(d, qv)) * inv
t = float(np.dot(e2, qv)) * inv
hit = (u >= 0) and (v >= 0) and (u + v <= 1) and t > 0
th = (f"Möller-Trumbore solves o + t·d = v0 + u·e1 + v·e2 by Cramer's rule, which avoids ever building "
f"the plane equation.\n\n"
f"e1 = v1 - v0 = {_f(e1)}\ne2 = v2 - v0 = {_f(e2)}\n"
f"p = d × e2 = {_f(p)}\ndet = e1·p = {_f(det)} (non-degenerate, so the ray is not parallel)\n"
f"inv_det = {_f(inv)}\n\n"
f"T = o - v0 = {_f(t_vec)}\n"
f"u = (T·p)·inv_det = {_f(u)} {'✓ in [0,1]' if 0 <= u <= 1 else '✗ outside [0,1]'}\n"
f"q = T × e1 = {_f(qv)}\n"
f"v = (d·q)·inv_det = {_f(v)} {'✓' if v >= 0 else '✗ negative'}\n"
f"u + v = {_f(u+v)} {'✓ ≤ 1' if u+v <= 1 else '✗ > 1, outside the triangle'}\n"
f"t = (e2·q)·inv_det = {_f(t)} {'✓ in front of the origin' if t > 0 else '✗ behind the origin'}\n\n"
f"{'All barycentric conditions hold and t > 0, so it is a genuine forward hit.' if hit else 'At least one condition fails, so the ray misses the triangle.'}")
if hit:
a = (f"**Hit** at t = {_f(t)}, point {_f(o + t*d)}.\n\n"
f"Barycentrics: u = {_f(u)}, v = {_f(v)}, w = 1-u-v = {_f(1-u-v)} — all non-negative and summing "
f"to 1, so the point is inside the triangle. Those same weights interpolate vertex normals, UVs "
f"and colours at the hit point.")
else:
reasons = []
if not (u >= 0): reasons.append(f"u = {_f(u)} < 0")
if not (v >= 0): reasons.append(f"v = {_f(v)} < 0")
if u + v > 1: reasons.append(f"u+v = {_f(u+v)} > 1")
if t <= 0: reasons.append(f"t = {_f(t)} ≤ 0 (behind the ray origin)")
a = (f"**Miss** — {', '.join(reasons)}.\n\nThe ray crosses the triangle's plane at t = {_f(t)}, but "
f"the barycentric test places that point outside the triangle itself.")
return q, th, a, "moller-trumbore"
def catmull_rom(rng):
P = [np.array([round(rng.uniform(-6, 6), 2), round(rng.uniform(-6, 6), 2)]) for _ in range(4)]
t = round(rng.uniform(0.15, 0.85), 2)
p0, p1, p2, p3 = P
tau = rng.choice([0.5, 0.5, 1.0])
m1 = tau * (p2 - p0)
m2 = tau * (p3 - p1)
t2, t3 = t * t, t * t * t
h00 = 2 * t3 - 3 * t2 + 1
h10 = t3 - 2 * t2 + t
h01 = -2 * t3 + 3 * t2
h11 = t3 - t2
pt = h00 * p1 + h10 * m1 + h01 * p2 + h11 * m2
q = (f"Evaluate a Catmull-Rom spline at t={t} on the segment between P1 and P2, with control points "
f"P0={_f(p0)}, P1={_f(p1)}, P2={_f(p2)}, P3={_f(p3)} and tension τ={tau}. "
f"Why does this curve pass through its control points when a B-spline does not?")
th = (f"Catmull-Rom is a cubic Hermite spline whose tangents are estimated from the neighbouring points:\n"
f" m1 = τ(P2 - P0) = {tau}·{_f(p2-p0)} = {_f(m1)}\n"
f" m2 = τ(P3 - P1) = {tau}·{_f(p3-p1)} = {_f(m2)}\n\n"
f"Hermite basis at t={t} (t²={_f(t2)}, t³={_f(t3)}):\n"
f" h00 = 2t³-3t²+1 = {_f(h00)}\n h10 = t³-2t²+t = {_f(h10)}\n"
f" h01 = -2t³+3t² = {_f(h01)}\n h11 = t³-t² = {_f(h11)}\n"
f" (they sum on the position terms: h00 + h01 = {_f(h00+h01)})\n\n"
f"P(t) = h00·P1 + h10·m1 + h01·P2 + h11·m2\n"
f" = {_f(h00)}·{_f(p1)} + {_f(h10)}·{_f(m1)} + {_f(h01)}·{_f(p2)} + {_f(h11)}·{_f(m2)}\n"
f" = {_f(pt)}\n\n"
f"Interpolation vs approximation: at t=0 the basis reduces to h00=1 and everything else 0, giving "
f"exactly P1; at t=1, h01=1 giving exactly P2. So the curve is *interpolating* by construction. A "
f"uniform cubic B-spline instead weights each control point by 1/6, 4/6, 1/6 at the knots, so it "
f"passes near but not through them — it trades interpolation for C² continuity, whereas Catmull-Rom "
f"is only C¹.")
a = (f"P({t}) = {_f(pt)}\n\nTangents m1 = {_f(m1)}, m2 = {_f(m2)}; Hermite weights h00={_f(h00)}, "
f"h10={_f(h10)}, h01={_f(h01)}, h11={_f(h11)}.\n\n"
f"Catmull-Rom interpolates because its Hermite basis collapses to exactly P1 at t=0 and exactly P2 at "
f"t=1. A uniform B-spline weights the knots 1/6, 4/6, 1/6 and so only approximates them — buying C² "
f"continuity in exchange, where Catmull-Rom gives you only C¹. That is the trade: pass through the "
f"points, or have continuous curvature. three.js `CatmullRomCurve3` is the former.")
return q, th, a, "catmull-rom"
def easing_inverse(rng):
x1, y1 = round(rng.uniform(0.05, 0.9), 2), round(rng.uniform(-0.3, 1.4), 2)
x2, y2 = round(rng.uniform(0.1, 0.95), 2), round(rng.uniform(-0.3, 1.4), 2)
target_x = round(rng.uniform(0.15, 0.85), 2)
def bx(t):
return 3 * (1 - t) ** 2 * t * x1 + 3 * (1 - t) * t * t * x2 + t ** 3
def bx_prime(t):
return 3 * (1 - t) ** 2 * x1 + 6 * (1 - t) * t * (x2 - x1) + 3 * t * t * (1 - x2)
def by(t):
return 3 * (1 - t) ** 2 * t * y1 + 3 * (1 - t) * t * t * y2 + t ** 3
t = target_x
steps = []
for i in range(5):
f = bx(t) - target_x
d = bx_prime(t)
steps.append((i, t, f, d))
if abs(f) < 1e-9 or abs(d) < 1e-9:
break
t = t - f / d
y = by(t)
q = (f"CSS `cubic-bezier({x1}, {y1}, {x2}, {y2})`. The browser needs the eased value at progress "
f"x = {target_x}. Since the curve is parameterised by t, not x, show how to invert it and give y.")
th = (f"The subtlety: `cubic-bezier(x1,y1,x2,y2)` defines a 2D curve with P0=(0,0) and P3=(1,1). Animation "
f"progress is the *x* coordinate, but the curve is parameterised by t, and x ≠ t unless the curve is "
f"linear. So you must solve B_x(t) = {target_x} for t first, then evaluate B_y(t).\n\n"
f"B_x(t) = 3(1-t)²t·{x1} + 3(1-t)t²·{x2} + t³\n\n"
f"Newton-Raphson, seeded with t = x = {target_x} (a good seed because x is monotone in t and close to "
f"it for well-behaved easings):\n"
+ "".join(f" iter {i}: t={_f(tt)} f(t)=B_x(t)-x={_f(ff)} f'(t)={_f(dd)}\n" for i, tt, ff, dd in steps)
+ f" converged t = {_f(t)}\n\n"
f"Now the y coordinate:\n"
f" B_y(t) = 3(1-t)²t·{y1} + 3(1-t)t²·{y2} + t³ = {_f(y)}\n\n"
f"Newton is what real engines use, falling back to bisection when the derivative gets small — which "
f"happens when x1 or x2 sit near 0 or 1 and the curve has a near-vertical segment. Note also that y "
f"is allowed outside [0,1] (that is how overshoot/anticipation easings work) while x is clamped to "
f"[0,1] to keep the curve a function of progress."
+ (f" Here y = {_f(y)} is outside [0,1], so this easing overshoots." if not (0 <= y <= 1) else ""))
a = (f"y = **{_f(y)}** at x = {target_x} (solved t = {_f(t)}).\n\n"
f"The step people miss is that the cubic-bezier parameter t is *not* the animation progress x. You have "
f"to invert B_x(t) = x numerically — Newton-Raphson seeded at t = x converges in "
f"{len(steps)} iterations here — and only then evaluate B_y(t).\n\n"
+ (f"Note y = {_f(y)} lies outside [0,1]: this easing overshoots, which is exactly what control point "
f"y-values beyond the unit range are for." if not (0 <= y <= 1) else
f"y stays within [0,1], so this easing does not overshoot."))
return q, th, a, "cubic-bezier-easing"
def float_precision_world(rng):
dist = rng.choice([100_000.0, 1_000_000.0, 6_371_000.0, 20_000_000.0])
eps = 2.0 ** math.floor(math.log2(dist)) * 2 ** -23
q = (f"My scene is georeferenced and objects sit around {dist:,.0f} units from the origin. Vertices jitter "
f"and shadows crawl when the camera moves slowly. What is going on and how do I fix it?")
th = (f"float32 has a 24-bit significand (23 stored + 1 implicit). The spacing between representable values "
f"at magnitude m is 2^floor(log2 m) · 2⁻²³.\n\n"
f"At {dist:,.0f}: 2^{int(math.floor(math.log2(dist)))} · 2⁻²³ ≈ {_f(eps)} units.\n\n"
f"So positions near that distance snap to a lattice roughly {_f(eps)} units apart. If the scene unit "
f"is a metre, that is {_f(eps*1000)} mm of quantisation — visible as jitter the moment the camera or "
f"object moves by less than one lattice step, because the rounded result stops changing and then "
f"jumps.\n\n"
f"It gets worse in the shader: the model-view product is computed in float32, and subtracting two "
f"large nearly-equal numbers (object position minus camera position) is catastrophic cancellation — "
f"you lose most of your remaining significant digits precisely where you need them.\n\n"
f"Shadows crawl for the same reason one level down: the light-space depth comparison is differencing "
f"two quantised large values.\n\n"
f"The fix is not more precision, it is smaller numbers. Standard approach is floating origin: keep the "
f"camera at or near (0,0,0) and translate the world around it, so all the arithmetic that reaches the "
f"GPU happens at small magnitudes. Doubles on the CPU for authoritative positions, rebased to float32 "
f"relative coordinates before upload.")
a = (f"This is float32 quantisation. At {dist:,.0f} units the gap between representable floats is about "
f"**{_f(eps)} units** — your vertices are snapping to a lattice that coarse, and slow motion makes it "
f"visible as jitter.\n\n"
f"Fixes, in order of effectiveness:\n\n"
f"1. **Floating origin.** Keep the camera near (0,0,0) and shift the world instead. This is the real "
f"fix — it makes every number the GPU sees small.\n"
f"2. **Camera-relative vertices.** Upload positions already relative to the camera (or to a nearby "
f"tile origin), so the shader never differences two huge values. Avoids the catastrophic cancellation "
f"in the model-view multiply.\n"
f"3. **Doubles on the CPU only.** Keep authoritative positions in float64 in JS, rebase to float32 "
f"before upload. WebGL has no float64 attributes, so precision must be spent before it reaches the GPU.\n"
f"4. **Tile the world** into local coordinate frames if it spans more than about 10⁵ units.\n\n"
f"Raising the depth-buffer precision or the near plane will not help here — the error is in the "
f"position pipeline, not in depth.")
return q, th, a, "float32-world-precision"
def transparency_sorting(rng):
n = rng.choice([3, 12, 40, 200])
q = (f"I have {n} overlapping transparent quads (smoke sprites). Depending on camera angle some of them "
f"vanish behind others or pop as I orbit. `transparent: true` is set on all of them. What is happening?")
th = (f"Two distinct mechanisms get conflated here, and the fix differs.\n\n"
f"**Depth write.** With `transparent: true` three.js still writes depth by default. A near sprite drawn "
f"first writes its depth, and a farther sprite drawn later fails the depth test and is discarded "
f"entirely — so it 'vanishes'. That is not a sorting problem, it is a depth-write problem.\n\n"
f"**Sort order.** Alpha blending is not commutative: over(a, over(b, c)) ≠ over(b, over(a, c)). So "
f"transparent geometry must be drawn back-to-front. three.js does sort transparent objects by distance, "
f"but per *object*, using the object's origin — not per triangle. {n} overlapping quads whose origins "
f"are close together, or that interpenetrate, will sort inconsistently and pop as the camera orbits and "
f"the origin ordering flips.\n\n"
f"So: 'vanishes' → depthWrite. 'pops as I orbit' → per-object sort granularity.\n\n"
f"For {n} quads, "
+ ("the practical answer is to turn off depth writing and accept unsorted blending with a commutative "
"blend mode." if n > 50 else
"turning off depth writing plus the built-in sort is usually enough.")
+ "\n\nIf the sprites are opaque-ish with hard edges, alpha *testing* sidesteps the whole problem, "
f"because cutout geometry can go in the opaque pass and be depth-sorted by the hardware for free.")
a = (f"Two separate bugs, and they need different fixes.\n\n"
f"**Sprites vanishing → depth writes.** `transparent: true` does not stop depth writing. A near quad "
f"writes depth, then a farther one fails the test and is culled. Set `depthWrite: false` on the "
f"transparent material (keep `depthTest: true` so opaque geometry still occludes them).\n\n"
f"**Popping as you orbit → sort granularity.** three.js sorts transparent objects back-to-front by "
f"object origin, not per triangle. With {n} overlapping quads the origin ordering flips as you move and "
f"the blend order changes visibly.\n\n"
f"Options:\n"
f"- `depthWrite: false` — fixes the vanishing immediately, do this first.\n"
f"- Use `renderOrder` to pin an explicit order when you know the layering.\n"
+ (f"- At {n} sprites, prefer an order-independent approach: premultiplied additive blending is "
f"commutative, so sort order stops mattering. Weighted blended OIT if you need proper alpha.\n"
if n > 50 else
f"- At only {n} sprites the built-in sort is fine once depthWrite is off.\n")
+ f"- If the alpha is mostly hard-edged, use `alphaTest` instead of transparency and let them render in "
f"the opaque pass — the depth buffer then sorts them for free.")
return q, th, a, "transparency-sorting"
def raycaster_matrixworld(rng):
q = ("My raycaster stops hitting an object right after I move it in the same frame. If I wait a frame it "
"works. The object is a child of a Group that I translate. Why?")
th = ("The symptom — works next frame, fails same frame — is the signature of a stale cached transform.\n\n"
"Three.js keeps two things per object: the local transform (`position`, `quaternion`, `scale`, "
"composed into `matrix`) and the resolved world transform (`matrixWorld`). Setting `.position` marks "
"the local matrix dirty but does *not* recompute `matrixWorld`. That recomputation happens in "
"`updateMatrixWorld()`, which the renderer calls once per frame inside `render()`.\n\n"
"`Raycaster.intersectObject` works in world space: it transforms the ray into the object's local space "
"using the *inverse of matrixWorld*. If you move the object and immediately raycast, matrixWorld still "
"holds last frame's value, so the ray is tested against where the object used to be. Next frame the "
"renderer has updated it and the hit succeeds — exactly the reported behaviour.\n\n"
"The Group matters because the child's matrixWorld is the product of the parent chain. Moving the "
"parent invalidates every descendant's world matrix, and only a traversal from the moved node down "
"fixes them.")
a = ("`matrixWorld` is stale. Setting `.position` only dirties the *local* matrix; the world matrix is "
"recomputed in `updateMatrixWorld()`, which the renderer calls once per frame inside `render()`. "
"`Raycaster` works in world space and uses the inverse of `matrixWorld`, so a same-frame raycast tests "
"against the object's previous location.\n\n"
"Fix — force the update after moving, before raycasting:\n\n"
"```js\n"
"group.position.copy(newPos);\n"
"group.updateMatrixWorld(true); // true = force, and recurse to children\n"
"raycaster.setFromCamera(pointer, camera);\n"
"const hits = raycaster.intersectObject(group, true);\n"
"```\n\n"
"Call it on the highest node you moved — the child's world matrix is the product of the whole parent "
"chain, so updating only the child is not enough.\n\n"
"Two related traps: `Object3D.matrixAutoUpdate = false` means even the renderer will not refresh it, "
"and `Raycaster` against a `SkinnedMesh` or instanced mesh needs the bone/instance matrices current too, "
"not just the object transform.")
return q, th, a, "raycaster-stale-matrix"
def dispose_leak(rng):
n = rng.choice([500, 2000, 10000])
q = (f"My app creates and removes about {n:,} meshes over a session and GPU memory climbs until the tab "
f"crashes. I do call `scene.remove(mesh)`. What am I missing?")
th = (f"`scene.remove()` only detaches the object from the scene graph. It has no effect on GPU-side "
f"resources, because those live in WebGL objects that JavaScript garbage collection cannot see or "
f"reclaim: buffers for geometry, textures for materials, and compiled programs.\n\n"
f"three.js allocates GPU resources lazily on first render and tracks them in `WebGLRenderer.info`. "
f"Dropping the last JS reference to a Geometry does *not* free its VBO — the renderer's internal "
f"`WebGLGeometries` map still holds it, keyed by geometry id, until `.dispose()` fires the event that "
f"removes it.\n\n"
f"So the leak is three separate resource classes:\n"
f"- geometry → `geometry.dispose()` frees the attribute buffers\n"
f"- material → `material.dispose()` frees the program (if no longer shared)\n"
f"- textures → `texture.dispose()`, per texture slot, and materials can hold many (map, normalMap, "
f"roughnessMap, envMap...)\n\n"
f"At {n:,} meshes, even modest per-mesh geometry adds up fast.\n\n"
f"The diagnostic is `renderer.info.memory` — `geometries` and `textures` counts should return to "
f"baseline after teardown. If they climb monotonically, disposal is being missed.")
a = (f"`scene.remove()` detaches from the graph but frees no GPU memory — those buffers, textures and "
f"programs live in WebGL objects that JS GC cannot reclaim. You have to dispose explicitly.\n\n"
f"```js\n"
f"function disposeMesh(mesh) {{\n"
f" mesh.geometry?.dispose();\n"
f" const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];\n"
f" for (const m of mats) {{\n"
f" if (!m) continue;\n"
f" for (const k of Object.keys(m)) {{\n"
f" const v = m[k];\n"
f" if (v && v.isTexture) v.dispose();\n"
f" }}\n"
f" m.dispose();\n"
f" }}\n"
f"}}\n"
f"scene.remove(mesh);\n"
f"disposeMesh(mesh);\n"
f"```\n\n"
f"Watch `renderer.info.memory.geometries` and `.textures` — they should return to baseline after "
f"teardown. A monotonic climb over your {n:,} meshes is the leak.\n\n"
f"Two caveats: do **not** dispose a material or texture that other live meshes still share, and "
f"`renderer.dispose()` plus `forceContextLoss()` is the only way to reclaim everything if you tear down "
f"the whole renderer.")
return q, th, a, "gpu-resource-disposal"
def instancing_drawcalls(rng):
n = rng.choice([1000, 20000, 200000])
tri = rng.choice([12, 500, 5000])
q = (f"I need to render {n:,} copies of a {tri:,}-triangle model. Compare separate Meshes, merged geometry, "
f"and InstancedMesh — which should I use and why?")
total_tri = n * tri
th = (f"Total triangle load is {n:,} × {tri:,} = {total_tri:,} triangles either way, so the geometry cost is "
f"fixed. What differs is CPU overhead and flexibility.\n\n"
f"**{n:,} separate Meshes.** One draw call each. Browsers manage roughly 1,000-5,000 draw calls per "
f"frame at 60fps before the CPU becomes the bottleneck, and each also costs a matrix update and a "
f"frustum-cull test in the three.js render loop. At {n:,} this is "
f"{'catastrophic' if n > 10000 else 'already too many' if n > 2000 else 'borderline but survivable'}.\n\n"
f"**Merged geometry.** One draw call, {total_tri:,} triangles in one buffer. Cheapest possible CPU "
f"cost, but the copies lose independent transforms — moving one means rewriting the vertex buffer — "
f"and you lose per-object frustum culling, so all {total_tri:,} triangles are submitted even when most "
f"are off screen.\n\n"
f"**InstancedMesh.** One draw call, one copy of the geometry, plus a per-instance matrix buffer "
f"({n:,} × 16 floats = {n*16*4/1048576:.1f} MB). Per-instance transforms stay independent and cheap to "
f"update. The tradeoff is that culling is all-or-nothing per InstancedMesh unless you sort and manage "
f"`count` yourself.\n\n"
f"At {tri:,} triangles per copy the geometry is "
f"{'heavy enough that GPU throughput, not draw calls, becomes the limit' if total_tri > 5_000_000 else 'light enough that draw-call overhead dominates'}.")
a = (f"**Use InstancedMesh.**\n\n"
f"All three submit the same {total_tri:,} triangles, so the difference is CPU overhead:\n\n"
f"| approach | draw calls | per-copy transform | culling |\n"
f"|---|---|---|---|\n"
f"| {n:,} Meshes | {n:,} | yes | per object |\n"
f"| merged | 1 | no | none |\n"
f"| InstancedMesh | 1 | yes | per batch |\n\n"
f"{n:,} separate meshes means {n:,} draw calls; the practical browser budget is roughly 1,000-5,000 per "
f"frame, so that is {'far past' if n > 5000 else 'at the edge of'} the limit. Merging gets you to one "
f"call but freezes the copies into a single buffer.\n\n"
f"InstancedMesh gives you the single draw call *and* keeps per-instance matrices "
f"({n*16*4/1048576:.1f} MB for {n:,} instances). Update with `setMatrixAt(i, m)` and set "
f"`instanceMatrix.needsUpdate = true`.\n\n"
+ (f"At {total_tri:,} triangles total you will be GPU-bound rather than draw-call-bound, so also add an "
f"LOD or reduce {tri:,} triangles per copy — instancing alone will not save you.\n"
if total_tri > 5_000_000 else
f"At {total_tri:,} triangles total the GPU has plenty of headroom; draw-call overhead was the whole "
f"problem and instancing removes it.\n")
+ f"\nCaveat: frustum culling becomes per-InstancedMesh, not per instance. If the copies are spread over "
f"a large area, split them into several InstancedMeshes by region so off-screen groups can be culled.")
return q, th, a, "instancing-vs-merging"
EXTRA_GENERATORS = [
(rodrigues, 4), (look_at, 4), (moller_trumbore, 6), (catmull_rom, 4),
(easing_inverse, 5), (float_precision_world, 4), (transparency_sorting, 4),
(raycaster_matrixworld, 1), (dispose_leak, 3), (instancing_drawcalls, 3),
]