code wiki / (root) / nx_skullsdf_verified_r3_t333.nx

nx_skullsdf_verified_r3_t333.nx source

↩ module page · 2872 lines · 152575 B

1// nx_skullsdf.nx -- the skull as a FUSED SHELL WITH OPENINGS, built in the implicit path. 2// 3// ★WHY THIS EXISTS, from two render cycles of evidence rather than preference. nx_skullgen emits the 4// skull as seven LOFTED TUBES. Rendered, that is seven separate objects sharing a bounding box: the 5// nasal bones float clear of the face, the zygomatic arch is a rod passing through nothing, and the 6// braincase is a balloon with a jaw hanging near it. Moving the tubes closer helps a little and cannot 7// fix the class of problem, because A SKULL IS NOT A SET OF TUBES -- it is one continuous fused shell 8// with holes cut in it. Tubes cannot fuse and cannot have holes. 9// 10// ★THE IMPLICIT PATH DOES EXACTLY THOSE TWO THINGS AND WE ALREADY OWN IT: smooth-union joins bones into 11// one surface, subtraction cuts the orbits and the nasal aperture as real openings, and nx_isosurf's 12// surface_nets polygonizes the result into nx_trimesh. The plan reserved SDF for viscera on the grounds 13// that it cannot resolve an eyelash -- true, and irrelevant to bone, whose features are centimetres. 14// ⚠So this does NOT replace the loft path for skin. It claims the skull only. 15// 16// nx_skullsdf <out.nxmesh> [sex 0-1000] [robust 0-1000] [grid] 17// license_tier: ORIGINAL expect_exit: 0 No hw writes (Rule 26). 18import "nx_isosurf.nx" 19import "nx_itoa_lib.nx" // shared MSB-first emitter (zero-alloc) 20import "nx_memfloor.nx" // mf_admit: refuse an O(G^3) grid that would eat the host (2026-07-30 incident) 21import "nx_sdfprim_lib.nx" // the implicit primitives (ellipsoid, capsule, arch, plate, walled cylinder, ring): ONE family for every anatomy field 22import "nx_fieldfit_verified_r2_t333.nx" 23import "nx_sha256.nx" // the fit machinery (two-sided region-balanced objective, coordinate descent, prefix fit file): ONE optimiser for every field 24const SS_MAGIC_2026: i64 = 2026 25const SS_MAGIC_1024: i64 = 1024 26const SS_MAGIC_8388608: i64 = 8388608 27const SS_MAGIC_8388607: i64 = 8388607 28const SS_MAGIC_40000: i64 = 40000 29 30const SS_G: i64 = 160 // grid cells per axis 31const SS_EXT: i64 = 120 // world half-extent in MILLIMETRES. A male skull is ~185mm long and 32 // ~145mm broad, so 260mm of grid covers it with no wasted resolution 33 // (the first version sampled 600mm and spent most of the grid on air) 34// ★THE PRIMITIVES ARE AUTHORED IN AN ARBITRARY ~90-UNIT SPACE, NOT MILLIMETRES. Assuming otherwise 35// produced a skull measuring 84x75x93mm against the reference's 151x209x215 -- roughly half scale and 36// wrongly proportioned. This factor maps the authored space onto real millimetres, and the three 37// reference dimensions are named so the gate can check the result against them instead of my eye. 38// Derived from the measurement, not guessed: at 1850 the emitted skull stood 348mm against a 209mm 39// reference, so the factor is 1850 x 209/348. Each correction here is now driven by the bbox the organ 40// prints, which is the whole reason that check exists. 41// ★IDENTITY. The field below is now authored in REAL MILLIMETRES against the reference's measured box, 42// so there is no unit-space to get wrong. The previous arbitrary ~90-unit space needed a fudge factor 43// that could correct overall size but never proportion -- the skull came out 176x256x210 where the 44// reference is 151x209x215: too tall AND too shallow, which no single multiplier can fix. 45const SS_SCALE: i64 = 1000 46const SS_REF_W: i64 = 151 // reference bounding box, mm, measured off BodyParts3D: x lateral 47const SS_REF_H: i64 = 215 // HEIGHT = the file's z extent (BodyParts3D is a floor-origin z-UP body frame) 48const SS_REF_D: i64 = 209 // DEPTH = the file's y extent (antero-posterior, face at -y). Until 2026-09-18 the two 49 // were swapped, because every reader below took the file as y-up: see ss_ref_map 50const SS_TOL: i64 = 25 // mm each dimension may differ before the build is called wrong 51const SS_Q: i64 = SP_Q // fixed point for the distance functions 52const SS_NQ: i64 = 4096 // the scale surface_nets emits gradient normals in (nx_isosurf.nx:68) 53const SS_ISO: i64 = 0 54const SS_BONE: i64 = 0xe8e0d8 55// ***REDISTANCE (argv[8]) -- REBUILD |grad f| = 1 ON THE SAMPLED GRID, the fix this file's own tissue 56// diagnosis names (see the DISABLED gradient-normalisation block): chained ss_smin leaves the field up 57// to 40 percent off a true SDF near the surface, so an iso-offset of depth d moves the skin by 58// d/|grad| instead of d (measured 3-6mm scatter), and dividing by |grad| downstream AMPLIFIES flat 59// cells (measured 62mm chins). The standard remedy is an eikonal pass over the grid we already build: 60// SEED every node adjacent to a zero crossing with its exact sub-cell distance to that crossing (so 61// the bone surface CANNOT move -- linear interpolation between two seeds reproduces the crossing at 62// exactly the raw field's own position), then FAST-SWEEP the upwind eikonal update in all 8 diagonal 63// orders until distances are true everywhere. The redistanced field is carried at SS_RDQ fixed point 64// so sub-cell seeds survive integer storage; surface_nets only ever interpolates zero crossings and 65// normalises gradients, so a uniformly scaled field polygonizes identically. 66// ADDITIVE: argv[8] absent or 0 leaves the old path byte-identical. 67const SS_RDQ: i64 = 256 // fixed-point units per millimetre in the redistanced field 68const SS_RD_INF: i64 = 76800 // 300mm x SS_RDQ -- farther than any point in the sampled box 69// ---- M2 SUB-MM RAW FIELD (debt 1786406737, 2026-08-12): the raw grid stored INTEGER-MILLIMETRE 70// distances, so every iso-crossing snapped to coarse fractions of a cell and the redistance seeds 71// inherited those mm crossings -- the onion-ring terraces that SURVIVE redistancing (proven 08-10: 72// "redistance seeds inherit the RAW field's integer-mm zero crossings; the only cure is fixed-point 73// evaluation of the primitive field itself"). The _q lanes below evaluate the SAME authored-mm 74// geometry but carry the RESULT at SS_FQ units per millimetre. SS_FQ == SS_RDQ so the raw and 75// redistanced grids share ONE fixed point and every ratio-based consumer (seed crossing t=af/(af+ag), 76// sign restore, surface_nets at SS_ISO=0) is scale-invariant by construction -- no downstream change. 77// The mm lane (ss_field/ss_field_p/ss_field_world) stays for the tuner/bench/grad verbs unchanged. 78const SS_FQ: i64 = SP_FQ 79const SS_RD_NEAR: i64 = 3 // near-band half-width, cells, for the printed |grad| A/B 80const SS_RD_LO: i64 = 800 // |grad| per-mille below this counts under (same bar as ss_grad) 81const SS_RD_HI: i64 = 1200 // |grad| per-mille above this counts over (same bar as ss_grad) 82static SS_REDIST: i64 83// ★★SMOOTH-UNION RADIUS -- AND WHY IT IS NOW ZERO. ss_smin subtracts h^2/(4k) from the result, so every 84// chained call pushes the field further negative. Chaining eleven of them means the value at a point 85// depends on how many bones are near it, and the result is NOT a distance field -- gradient magnitude 86// drifts far from 1. surface_nets places each vertex by LINEAR INTERPOLATION along a cell edge, which 87// assumes the field is locally linear in distance; feed it a distorted field and vertices land in 88// inconsistent places, giving a jagged self-intersecting shell that renders as speckle. 89// ★Plain min() is the exact union of two SDFs and cannot distort anything. It is also anatomically 90// right: bones meet at SUTURES, which are sharp, not blended. 91// Restored to a real millimetre blend. At 0 (plain union) the mandible and face floated as separate 92// lumps with visible seams; bones do meet at sutures, but a 6mm blend at 2mm sampling is what makes 93// adjacent masses read as ONE bone rather than a pile of touching balls. 94// ★2026-08-10: default 6 -> 3, the value every measured run shipped with today (redistancing repairs 95// the field distortion smin causes, so the old reason to hold 6 is gone; 3 keeps fusion w/ sharper form) 96const SS_K: i64 = 3 97// ***SS_K IS NOW RUNTIME-SETTABLE (argv[7]) SO THE SMOOTH-UNION/DISTANCE-FIDELITY TRADE CAN BE A/B'd 98// WITHOUT A REBUILD. This file already records setting K to ZERO once, for exactly the reason that 99// matters here -- plain min() is the EXACT union of two SDFs and cannot distort anything, whereas every 100// chained ss_smin subtracts h*h/(4k) and pushes the field away from a true distance function. K=0 gives 101// honest distances with visible sutures; K=6 gives one fused shell with a distorted field. Until now that 102// trade was a recompile, so nobody measured it. Default is unchanged, so every existing caller is 103// byte-identical. 104static SS_KSET: i64 105static SS_KVAL: i64 106func ss_k() -> i64 { if SS_KSET == 1 { return SS_KVAL } return SS_K } 107 108func ss_puts(s: *u8) -> i64 { var n: i64=0; while s[n]!=(0 as u8){n=n+1} sys_write(1,s,n); return 0 } 109// MIGRATED to nxi_out (debt 1785563586). The old body mmapped 32 bytes per call and never freed it, 110// across 33 call sites. THIS ORGAN ALREADY IMPORTS nx_memfloor mf_admit after the 2026-07-30 111// incident where it took 27.7GB of 36GB and froze every seat -- the GUARD was added, the CAUSE 112// was not. nxi_out is MSB-first, allocates NOTHING, and emits identical bytes including the sign. 113func ss_pn(v: i64) -> i64 { nxi_out(v); return 0 } 114func ss_atoi(s: *u8) -> i64 { 115 var i: i64=0; var n: i64=0; var sg: i64=1 116 if s[0]==(45 as u8) { sg=0-1; i=1 } 117 while s[i]!=(0 as u8) { let c: i64=s[i] as i64; if c>=48 { if c<=57 { n=n*10+(c-48) } } i=i+1 } 118 return n*sg 119} 120func ss_streq(a: *u8, b: *u8) -> i64 { 121 var i: i64=0; var go: i64=1; var eq: i64=1 122 while go==1 { if a[i]!=b[i] { eq=0; go=0 } else { if a[i]==(0 as u8) { go=0 } else { i=i+1 } } } 123 return eq 124} 125func ss_isqrt(v: i64) -> i64 { return sp_isqrt(v) } 126func ss_abs(v: i64) -> i64 { if v<0 { return 0-v } return v } 127func ss_min(a: i64, b: i64) -> i64 { if a<b { return a } return b } 128func ss_max(a: i64, b: i64) -> i64 { if a>b { return a } return b } 129 130// ---- primitives. All return a signed distance in world units: negative inside. 131// An ellipsoid's exact SDF has no closed form; the standard cheap bound (scaled radial distance times 132// the smallest semi-axis) is used, which is what every SDF modeller uses and is accurate near the 133// surface -- the only place the polygonizer looks. 134// ★★TRUE ELLIPSOID DISTANCE, not a radial bound. The previous version returned 135// (radial-1) x smallest-semi-axis, which is only correct on a sphere and drifts badly off-axis. Alone 136// that is invisible; SMOOTH-UNIONED a dozen times it produced grid-scale ripples in the field, and 137// surface nets faithfully polygonized the ripples into a lumpy self-intersecting shell that z-fought 138// against itself. ★The error was in the PRIMITIVE and only became visible under COMPOSITION. 139// This is the standard first-order approximation d = k0(k0-1)/k1, exact on a sphere and accurate near 140// the surface of an ellipsoid -- which is the only region the polygonizer samples. 141// integer Bhaskara sine: degrees in, per-mille out; exact at 0/90/180, <2 permil error between. 142// The estate's emitter already carries one for the body; the field needs its own because a 143// STRUCTURED primitive places instances around an arc and a table lookup cannot be tuned smoothly. 144// ---- rule-11 named constants: each is a DOMAIN FACT, not a dial (2026-08-14) ---- 145// Bhaskara I's 7th-century sine approximation: sin(x) ~ 4x(180-x) / (40500 - x(180-x)). 146// The numerator's 4 is scaled by 1000 so the result is PER-MILLE, matching ss_isin's contract 147// above; 40500 = 5 * 90^2 belongs to the closed form itself and is not tunable. 148const SS_BHASKARA_NUM_PERMILLE: i64 = 4000 149const SS_BHASKARA_DEN: i64 = 40500 150// Trilinear interpolation carries fractions as 0..SS_LERP_ONE (Q10 fixed point). 151const SS_LERP_ONE: i64 = 1024 152// Per-mille denominator. A UNIT, not a dial: sexf/robust arrive as 0..1000 and the policy is the 153// NUMERATOR (`3*sexf/SS_PERMILLE` says three per-mille per unit of sex). Hoisted ONLY at the 23 154// sites proven by enumeration to be divisors -- 47 of the 70 occurrences of 1000 are NOT (spans, 155// coordinates, argv), and folding those in would move the skull, not rename a unit. 156const SS_PERMILLE: i64 = 1000 157// Min/max accumulators start at +/- this and are replaced by the first real sample. A 158// SENTINEL, not a limit -- no value is ever clamped to it. 159const SS_EXTENT_SENTINEL: i64 = 999999 160// |grad SDF| must be ~1000 per-mille (unit) for a true signed-distance field; the probe counts 161// samples outside a +/-20% band around unit. LO and HI are ONE fact in two halves -- nx_magic's 162// 1024 threshold flags only HI, so naming HI alone would leave the pair half-told. 163const SS_GRAD_BAND_LO: i64 = 800 164const SS_GRAD_BAND_HI: i64 = 1200 165// Marching-cubes cell budget: the argv[7] default and the floor it is clamped up to. 166const SS_MARCH_CELLS_DEFAULT: i64 = 2000 167const SS_MARCH_CELLS_MIN: i64 = 1000 168// ---- THE SKULL FIELD. Every dimension is a function of the sex/robusticity knobs, as in nx_skullgen; 169// the difference is purely that these compose by union and subtraction instead of standing apart. 170// ★AUTHORED IN MILLIMETRES, in a frame centred on the cranium: +y up, +z forward (toward the face), 171// x lateral. Every figure is a real skull dimension, so the emitted bounding box can be compared 172// directly against the reference's 151 x 209 x 215 instead of through a fudge factor. 173// ★★THE SKULL AS A PARAMETER VECTOR. Hand-placing coordinates got the bounding box to 5mm and left the 174// SHAPE at 8mm mean error, because a person adjusting numbers by eye cannot search twenty dimensions. 175// Exposing the dimensions as data lets the fit metric DRIVE them instead: `tune` runs coordinate 176// descent against the real scanned reference and keeps only changes that lower the measured error. 177const SP_N: i64 = 87 178const SS_FIT_MIN: i64 = 58 // the v1 vector length: a fit file carrying at least this many ints 179 // applies as a PREFIX (structured params added later keep their 180 // defaults until the next tune saves the full vector) -- growing the 181 // parametrization must never discard banked convergence 182const P_VW: i64 = 0 // vault half-width 183const P_VH: i64 = 1 // vault half-height 184const P_VD: i64 = 2 // vault half-depth 185const P_VY: i64 = 3 // vault centre y 186const P_VZ: i64 = 4 // vault centre z 187const P_FY: i64 = 5 // frontal centre y 188const P_FZ: i64 = 6 // frontal centre z 189const P_FH: i64 = 7 // frontal half-height 190const P_FD: i64 = 8 // frontal half-depth 191const P_MY: i64 = 9 // maxilla centre y 192const P_MZ: i64 = 10 // maxilla centre z 193const P_MW: i64 = 11 // maxilla half-width 194const P_MH: i64 = 12 // maxilla half-height 195const P_MD: i64 = 13 // maxilla half-depth 196const P_JY: i64 = 14 // mandible chin y 197const P_JZ: i64 = 15 // mandible chin z 198const P_RX: i64 = 16 // ramus x offset 199const P_RY: i64 = 17 // ramus centre y 200const P_OR: i64 = 18 // orbit radius 201const P_OX: i64 = 19 // orbit centre x 202// ***THE REST OF THE SKULL'S STATIONS, PARAMETERISED (2026-08-09, operator: "the tooling should be 203// able to see pixel by pixel why our emitter is emitting shit compared to the benchmark and get us 204// to pixel to pixel emission -- not manual"). Coordinate descent can only move what is a parameter; 205// everything below was a frozen literal, which is why the measured-wrong stations (orbit depth, 206// nasal position, arch endpoints) could never converge no matter how good the objective was. 207const P_BX: i64 = 20 // brow bar half-span 208const P_BY: i64 = 21 // brow bar y 209const P_BZ: i64 = 22 // brow bar z 210const P_ZAX: i64 = 23 // zygomatic arch face-end x 211const P_ZAY: i64 = 24 // zygomatic arch face-end y 212const P_ZAZ: i64 = 25 // zygomatic arch face-end z 213const P_ZBX: i64 = 26 // zygomatic arch ear-end x 214const P_ZBY: i64 = 27 // zygomatic arch ear-end y 215const P_ZBZ: i64 = 28 // zygomatic arch ear-end z 216const P_ZR: i64 = 29 // zygomatic arch radius 217const P_NY: i64 = 30 // nasal bones centre y 218const P_NZ: i64 = 31 // nasal bones centre z 219const P_NRX: i64 = 32 // nasal radius x 220const P_NRY: i64 = 33 // nasal radius y 221const P_NRZ: i64 = 34 // nasal radius z 222const P_JAX: i64 = 35 // jaw body chin-end x 223const P_JAZ: i64 = 36 // jaw body chin-end z offset from P_JZ 224const P_JBX: i64 = 37 // jaw body angle-end x 225const P_JBY: i64 = 38 // jaw body angle-end y offset from P_JY 226const P_JBZ: i64 = 39 // jaw body angle-end z 227const P_JR: i64 = 40 // jaw body radius 228const P_RZ: i64 = 41 // ramus centre z 229const P_RRX: i64 = 42 // ramus radius x 230const P_RRY: i64 = 43 // ramus radius y 231const P_RRZ: i64 = 44 // ramus radius z 232const P_OAY: i64 = 45 // orbit opening y 233const P_OAZ: i64 = 46 // orbit opening z 234const P_OBX: i64 = 47 // orbit apex x 235const P_OBY: i64 = 48 // orbit apex y 236const P_OBZ: i64 = 49 // orbit apex z 237const P_PAY: i64 = 50 // nasal aperture opening y 238const P_PAZ: i64 = 51 // nasal aperture opening z 239const P_PBY: i64 = 52 // nasal aperture back y 240const P_PBZ: i64 = 53 // nasal aperture back z 241const P_PR: i64 = 54 // nasal aperture radius 242const P_CRX: i64 = 55 // chin ellipsoid radius x 243const P_CRY: i64 = 56 // chin ellipsoid radius y 244const P_CRZ: i64 = 57 // chin ellipsoid radius z 245// ***THE FIRST STRUCTURED PRIMITIVE: A REPEATED ELEMENT ALONG A CURVE (operator 2026-08-09: "you 246// cant even make teeth in a jaw... how are you going to emit a tree"). A flat list of blobs cannot 247// express teeth; ~9 knobs per ARCH drive N instances of one tooth rule along an elliptical arc. 248// This construct IS the seed of tree emission: a tree is elements-along-a-curve RECURSED. 249const P_UY: i64 = 58 // upper arch: occlusal centre y 250const P_UZ: i64 = 59 // upper arch: arc centre z 251const P_UAX: i64 = 60 // upper arch: lateral semi-axis 252const P_UAZ: i64 = 61 // upper arch: anterior semi-axis 253const P_UTH: i64 = 62 // upper arch: half arc span, degrees 254const P_UN: i64 = 63 // upper arch: tooth count 255const P_UTW: i64 = 64 // upper arch: tooth width 256const P_UTHT: i64 = 65 // upper arch: tooth height 257const P_UPR: i64 = 66 // upper arch: molar widening, permil at the arc ends 258const P_LY: i64 = 67 // lower arch: occlusal centre y 259const P_LZ: i64 = 68 // lower arch: arc centre z 260const P_LAX: i64 = 69 // lower arch: lateral semi-axis 261const P_LAZ: i64 = 70 // lower arch: anterior semi-axis 262const P_LTH: i64 = 71 // lower arch: half arc span, degrees 263const P_LN: i64 = 72 // lower arch: tooth count 264const P_LTW: i64 = 73 // lower arch: tooth width 265const P_LTHT: i64 = 74 // lower arch: tooth height 266const P_LPR: i64 = 75 // lower arch: molar widening, permil at the arc ends 267// ---- AN17 primitive rungs (2026-09-19): the openings as SHAPES the ruler can read, appended so a 76-int fit file still 268// loads as a prefix. RETIRED stations (kept in the vector for file compatibility, skipped by the tuner, unread by the 269// field): P_OR P_OBX P_OBY P_OBZ (the orbit was a drilled capsule to an apex), P_PBY P_PBZ P_PR (the aperture was a 270// capsule tunnel), P_NRZ (the nasal bones are a plate with P_NTH), P_JAX (the body is one arc through the chin), 271// P_RX P_RY P_RZ P_RRY (the ramus stands between the body's angle and the arch's ear end, derived, never placed). 272const P_OSW: i64 = 76 // orbit socket semi-width x (the rim's lateral half-span) 273const P_OSH: i64 = 77 // orbit socket semi-height y 274const P_OSD: i64 = 78 // orbit socket semi-depth z (the back wall sits at P_OCZ - P_OSD, inside the bone) 275const P_OCZ: i64 = 79 // orbit socket centre z; the front pokes through the face at P_OCZ + P_OSD 276const P_PAW: i64 = 80 // piriform aperture width (rim to rim) 277const P_PAH: i64 = 81 // piriform aperture height (rhinion to nasospinale) 278const P_PAD: i64 = 82 // piriform aperture depth: the nasal floor wall sits P_PAD behind the rim at P_PAZ 279const P_NTILT: i64 = 83 // nasal plate pitch, degrees: the rhinion end forward of the nasion end 280const P_NTH: i64 = 84 // nasal plate half-thickness 281const P_AAR: i64 = 85 // alveolar process radius: the U-arch of bone the upper teeth stand in 282const P_FPR: i64 = 86 // maxillary frontal process radius (the bone either side of the aperture, up to the orbits) 283// also RETIRED: P_PAY P_PAZ -- the aperture hangs from the nasal plate's lower edge (the rhinion), derived in the field 284// the tuner's population: 1 for a station the field reads, 0 for a retired one (an evaluation spent on a dead 285// parameter is a pass that cannot move anything) 286func ss_param_live(k: i64) -> i64 { 287 if k == P_PAY { return 0 } 288 if k == P_PAZ { return 0 } 289 if k == P_OR { return 0 } 290 if k == P_OBX { return 0 } 291 if k == P_OBY { return 0 } 292 if k == P_OBZ { return 0 } 293 if k == P_PBY { return 0 } 294 if k == P_PBZ { return 0 } 295 if k == P_PR { return 0 } 296 if k == P_NRZ { return 0 } 297 if k == P_JAX { return 0 } 298 if k == P_RX { return 0 } 299 if k == P_RY { return 0 } 300 if k == P_RZ { return 0 } 301 if k == P_RRY { return 0 } 302 return 1 303} 304// ★FITTED, NOT TYPED. These are the output of `tune` -- coordinate descent against the 171k-triangle 305// scanned reference, which took the mean surface error from 8.37mm to 5.06mm in one run. Every value 306// here was accepted only because it LOWERED a measured number, which is the opposite of how the 307// previous eight rounds of hand-placed coordinates were chosen. 308func ss_defaults(P: *i64) -> i64 { 309 P[P_VW]=81; P[P_VH]=71; P[P_VD]=75; P[P_VY]=24; P[P_VZ]=0-33 310 P[P_FY]=46; P[P_FZ]=15; P[P_FH]=34; P[P_FD]=33 311 P[P_MY]=0-45; P[P_MZ]=58; P[P_MW]=30; P[P_MH]=13; P[P_MD]=53 312 P[P_JY]=0-78; P[P_JZ]=60; P[P_RX]=57; P[P_RY]=0-46 313 P[P_OR]=8; P[P_OX]=30 314 // every remaining primitive station, extracted verbatim from the field's former literals so the 315 // TUNER can reach them -- the orbit stations, nasal position and arch endpoints were frozen 316 // literals no optimizer could move, which is why the gamed 8mm orbit could never recover 317 P[P_BX]=52; P[P_BY]=22; P[P_BZ]=62 318 P[P_ZAX]=52; P[P_ZAY]=6; P[P_ZAZ]=52; P[P_ZBX]=62; P[P_ZBY]=8; P[P_ZBZ]=0-30; P[P_ZR]=7 319 P[P_NY]=8; P[P_NZ]=76; P[P_NRX]=9; P[P_NRY]=18; P[P_NRZ]=12 320 P[P_JAX]=22; P[P_JAZ]=0-4; P[P_JBX]=46; P[P_JBY]=10; P[P_JBZ]=10; P[P_JR]=17 321 P[P_RZ]=0-6; P[P_RRX]=9; P[P_RRY]=34; P[P_RRZ]=26 322 P[P_OAY]=18; P[P_OAZ]=80; P[P_OBX]=20; P[P_OBY]=12; P[P_OBZ]=18 323 P[P_PAY]=0-8; P[P_PAZ]=92; P[P_PBY]=0-2; P[P_PBZ]=40; P[P_PR]=13 324 P[P_CRX]=26; P[P_CRY]=18; P[P_CRZ]=22 325 // DENTAL ARCHES: placement DERIVES from the parent bones (never type a placement the parent 326 // already knows -- the maxilla and jaw rows above are the parents); the structural dims (arch 327 // radii, tooth size/count, published human dental anatomy) are STARTING values the tuner owns. 328 P[P_UY]=P[P_MY]-24; P[P_UZ]=P[P_MZ]-10; P[P_UAX]=26; P[P_UAZ]=30 329 P[P_UTH]=75; P[P_UN]=14; P[P_UTW]=9; P[P_UTHT]=11; P[P_UPR]=400 330 P[P_LY]=P[P_JY]+16; P[P_LZ]=P[P_JZ]-12; P[P_LAX]=25; P[P_LAZ]=28 331 P[P_LTH]=75; P[P_LN]=14; P[P_LTW]=9; P[P_LTHT]=11; P[P_LPR]=400 332 // AN17 primitive rungs: the openings START at the oracle's own ruler readings (nx_skull_canon_gate, 2026-09-18, mm: 333 // aperture 23.1 wide, 22.4 high, 10.7 deep; orbit width 28.3) and the tuner owns them from there 334 P[P_OSW]=16; P[P_OSH]=14; P[P_OSD]=22; P[P_OCZ]=P[P_OAZ]-8 335 P[P_PAW]=23; P[P_PAH]=22; P[P_PAD]=11 336 P[P_NTILT]=25; P[P_NTH]=3; P[P_AAR]=8; P[P_FPR]=6 337 return 0 338} 339 340// the millimetre lane is the SS_FQ lane divided down: ONE definition of the skull's geometry (until 2026-09-19 the two 341// lanes carried the same twenty-two primitives twice, and a primitive changed in one and not the other is half a skull) 342func ss_field_p(px: i64, py: i64, pz: i64, sexf: i64, robust: i64, P: *i64) -> i64 { 343 return ss_field_p_q(px, py, pz, sexf, robust, P)/SS_FQ 344} 345// ss_field_p at SS_FQ output: same geometry, same composition order, sub-mm result. ss_smin/ss_sub 346// are scale-invariant so only the primitive outputs and the smoothing radius change units. 347func ss_field_p_q(px: i64, py: i64, pz: i64, sexf: i64, robust: i64, P: *i64) -> i64 { 348 let vw: i64 = P[P_VW] - 3*sexf/SS_PERMILLE 349 let vh: i64 = P[P_VH] - 2*sexf/SS_PERMILLE 350 let vd: i64 = P[P_VD] - 2*sexf/SS_PERMILLE 351 let brow: i64 = 10 - 3*sexf/SS_PERMILLE + 5*robust/SS_PERMILLE 352 let kq: i64 = ss_k()*SS_FQ 353 var d: i64 = sp_ellipsoid_q(px,py,pz, 0, P[P_VY], P[P_VZ], vw, vh, vd) 354 d = sp_smin(d, sp_ellipsoid_q(px,py,pz, 0, P[P_FY], P[P_FZ], vw*78/100, P[P_FH], P[P_FD]), kq) 355 d = sp_smin(d, sp_capsule_q(px,py,pz, 0-P[P_BX],P[P_BY],P[P_BZ], P[P_BX],P[P_BY],P[P_BZ], brow), kq) 356 d = sp_smin(d, sp_ellipsoid_q(px,py,pz, 0, P[P_MY], P[P_MZ], P[P_MW], P[P_MH], P[P_MD]), kq) 357 // (d) the alveolar process: a U-arch of bone standing on the upper dental arc; its front at the midline is the prosthion 358 d = sp_smin(d, sp_arch_q(px,py,pz, P[P_UY]+P[P_UTHT]/2+P[P_AAR]*2/3, P[P_UZ], P[P_UAX], P[P_UAZ], P[P_UTH], 0, P[P_AAR]), kq) 359 d = sp_smin(d, sp_ring_q(px,py,pz, P[P_UY], P[P_UZ], P[P_UAX], P[P_UAZ], P[P_UTH], P[P_UN], P[P_UTW], P[P_UTHT], P[P_UPR]), kq) 360 d = sp_smin(d, sp_ring_q(px,py,pz, P[P_LY], P[P_LZ], P[P_LAX], P[P_LAZ], P[P_LTH], P[P_LN], P[P_LTW], P[P_LTHT], P[P_LPR]), kq) 361 d = sp_smin(d, sp_capsule_q(px,py,pz, 0-P[P_ZAX],P[P_ZAY],P[P_ZAZ], 0-P[P_ZBX],P[P_ZBY],P[P_ZBZ], P[P_ZR]), kq) 362 d = sp_smin(d, sp_capsule_q(px,py,pz, P[P_ZAX],P[P_ZAY],P[P_ZAZ], P[P_ZBX],P[P_ZBY],P[P_ZBZ], P[P_ZR]), kq) 363 // (c) the nasal bones as a pitched PLATE from the nasion down and forward to the rhinion, never a peg 364 d = sp_smin(d, sp_ellipsoid_tiltx_q(px,py,pz, 0, P[P_NY], P[P_NZ], P[P_NRX], P[P_NRY], P[P_NTH], P[P_NTILT]), kq) 365 d = sp_smin(d, sp_ellipsoid_q(px,py,pz, 0, P[P_JY], P[P_JZ], P[P_CRX], P[P_CRY], P[P_CRZ]), kq) 366 // (e) the mandibular body as ONE arc from angle to angle through the chin, rising P_JBY toward the angles 367 d = sp_smin(d, sp_arch_q(px,py,pz, P[P_JY], P[P_JBZ], P[P_JBX], P[P_JZ]+P[P_JAZ]-P[P_JBZ], 90, P[P_JBY], P[P_JR]), kq) 368 // the ramus stands between the body's angle end and the arch's ear end (the condyle under the arch root): DERIVED 369 // from the two structures it joins, so the angle and the condyle cannot drift apart 370 let cdy: i64 = P[P_ZBY] - 2*P[P_ZR] 371 let rcy: i64 = (P[P_JY]+P[P_JBY] + cdy)/2 372 let rcz: i64 = (P[P_JBZ] + P[P_ZBZ])/2 373 let rcx: i64 = (P[P_JBX] + P[P_ZBX])/2 374 var rhy: i64 = (cdy - (P[P_JY]+P[P_JBY]))/2 + P[P_RRX] 375 if rhy < P[P_RRX] { rhy = P[P_RRX] } 376 d = sp_smin(d, sp_ellipsoid_q(px,py,pz, 0-rcx, rcy, rcz, P[P_RRX], rhy, P[P_RRZ]), kq) 377 d = sp_smin(d, sp_ellipsoid_q(px,py,pz, rcx, rcy, rcz, P[P_RRX], rhy, P[P_RRZ]), kq) 378 // the rhinion: the nasal plate's lower edge, where the aperture's top rim is by definition. The aperture is placed 379 // FROM it (a typed aperture station drifted 20 mm in front of the bone the moment the peg became a plate: an 380 // opening carved into air is not an opening) 381 let nts: i64 = sp_isin(P[P_NTILT]) 382 let ntc: i64 = sp_icos(P[P_NTILT]) 383 let yrh: i64 = P[P_NY] - P[P_NRY]*ntc/SS_PERMILLE 384 let zrh: i64 = P[P_NZ] + P[P_NRY]*nts/SS_PERMILLE 385 // the maxilla's FRONTAL PROCESSES: the bone either side of the aperture, rising from its lateral rims to the medial 386 // orbital rims, so the opening has rims to be walked and the maxilla joins the brow instead of floating under it 387 let fpx: i64 = P[P_PAW]/2 + P[P_FPR] 388 let fpy: i64 = yrh - P[P_PAH]/2 389 let fpz: i64 = zrh - P[P_FPR] 390 let fqx: i64 = P[P_OX] - P[P_OSW] - P[P_FPR]/2 391 let fqy: i64 = P[P_OAY] - P[P_OSH]/2 392 d = sp_smin(d, sp_capsule_q(px,py,pz, 0-fpx,fpy,fpz, 0-fqx,fqy,P[P_OCZ], P[P_FPR]), kq) 393 d = sp_smin(d, sp_capsule_q(px,py,pz, fpx,fpy,fpz, fqx,fqy,P[P_OCZ], P[P_FPR]), kq) 394 // (b) the orbits as SOCKETS: an ellipsoid carved with its back wall inside the bone and its front through the face 395 d = sp_sub(d, sp_ellipsoid_q(px,py,pz, 0-P[P_OX], P[P_OAY], P[P_OCZ], P[P_OSW], P[P_OSH], P[P_OSD])) 396 d = sp_sub(d, sp_ellipsoid_q(px,py,pz, P[P_OX], P[P_OAY], P[P_OCZ], P[P_OSW], P[P_OSH], P[P_OSD])) 397 // (c) the piriform aperture as an OPENING hanging from the rhinion, its nasal floor P_PAD behind the rim 398 d = sp_sub(d, sp_cylz_q(px,py,pz, 0, yrh - P[P_PAH]/2, P[P_PAW]/2, P[P_PAH]/2, zrh - P[P_PAD])) 399 return d 400} 401 402// THE DEFAULT PARAMETER VECTOR IS MAPPED ONCE, NOT ONCE PER SAMPLE -- the organ's single largest 403// defect, not a tuning matter. ss_field is the hot path of the whole program: the polygonizer 404// evaluates it at every one of (G+1)^3 grid corners. It used to sys_mmap(SP_N*8) on EVERY call, and 405// sys_mmap is PAGE-GRANULAR -- a 160-byte request costs a whole 4096-byte page, nothing here frees, 406// so THE FIELD LEAKED ONE PAGE PER SAMPLE. 407// MEASURED, and it reproduces the 2026-07-30 incident to the digit: G=224 is 225^3 = 11,390,625 408// samples x 4096 B = 46.6 GB of anonymous pages; the box OOM-killed it at total-vm 33.8 GB / 409// anon-rss 28.0 GB partway through. The grid array at that size is only 91 MB and cv another 90 MB, 410// so 2,966 bytes per cell was never the grid -- it was this line. It is also why G=1500 mapped 27 GB 411// and froze every other seat's builds. 412// THE BANKED DIAGNOSIS -- 'the knob allocates on the RAW argument while computing on a CAPPED one' -- 413// WAS WRONG, and the memory arithmetic refutes it: the raw-argument allocation is O(G^3)x8 = 91 MB at 414// G=224, three orders of magnitude short of the observed kill. The cost was per-EVALUATION, not 415// per-cell-of-storage. 416// A static POINTER lazily mapped once is the sanctioned shape here (a static ARRAY in BSS is the 417// banked crash-on-startup hazard, and this is the idiom nx_fluid/nx_genome/nx_ghash already use). The 418// vector is immutable after ss_defaults, so ONE copy is correct for every caller and ss_field stays a 419// pure function of its arguments -- the property the tuner and the polygonizer both rely on. 420// ---- THE FIT FILE: the tuner's output is DATA the emitter loads, never a source edit. If 421// knowledge/skull_fit.dat exists and carries a COMPLETE SP_N integer vector it overrides the 422// builtin defaults; short or absent files change nothing (parsed into a temp, applied only when 423// complete, so a truncated write cannot half-poison the skull). `tune ... <savepath>` writes it, 424// every emit reports fit_src, and the optimize->emit->measure loop closes with no hand in the numbers. 425static SS_FITSRC: i64 426static SS_FITN: i64 427// the fit file through the ONE loader (nx_fieldfit_lib.ff_load_prefix): a prefix of at least SS_FIT_MIN ints applies, 428// anything shorter changes nothing; SS_FITN carries how many stations the file governed for the emit receipt 429func ss_load_fit(P: *i64) -> i64 { 430 let got: i64 = ff_load_prefix("knowledge/skull_fit.dat" as *u8, P, SP_N, SS_FIT_MIN) 431 if got >= SS_FIT_MIN { SS_FITN = got; return 1 } 432 return 0 433} 434static SS_PDEF: i64 435func ss_pdef() -> *i64 { 436 if SS_PDEF == 0 { 437 SS_PDEF = sys_mmap(SP_N*8) as i64 438 ss_defaults(SS_PDEF as *i64) 439 SS_FITSRC = ss_load_fit(SS_PDEF as *i64) 440 } 441 return SS_PDEF as *i64 442} 443func ss_field(px: i64, py: i64, pz: i64, sexf: i64, robust: i64) -> i64 { 444 // delegates to the parameterised field with the default vector, so every existing caller is 445 // unchanged and there is exactly ONE definition of the skull's geometry 446 return ss_field_p(px, py, pz, sexf, robust, ss_pdef()) 447} 448 449// Evaluate the authored field at a WORLD millimetre point: map the point back into authored space, 450// then scale the returned distance forward again so the field stays a true SDF in world units. 451func ss_field_world(px: i64, py: i64, pz: i64, sexf: i64, robust: i64) -> i64 { 452 let d: i64 = ss_field(px*1000/SS_SCALE, py*1000/SS_SCALE, pz*1000/SS_SCALE, sexf, robust) 453 return d * SS_SCALE / 1000 454} 455// world-space field at SS_FQ units per world-unit -- the sub-mm raw lane (see the SS_FQ block) 456func ss_field_world_q(px: i64, py: i64, pz: i64, sexf: i64, robust: i64) -> i64 { 457 let d: i64 = ss_field_p_q(px*1000/SS_SCALE, py*1000/SS_SCALE, pz*1000/SS_SCALE, sexf, robust, ss_pdef()) 458 return d * SS_SCALE / 1000 459} 460 461// ★★★SKIN AS A TRUE ENVELOPE -- THE ANSWER THE OFFSET FAILURE HANDED US. nx_skinwrap displaced every 462// bone vertex outward along its own normal by the forensic tissue depth, and it LOWERED the binding judge 463// 99 -> 88 against the cadaver skin. The reason was structural, not tuning: AN OFFSET ALONG A NORMAL 464// CANNOT BRIDGE A CAVITY, and a face is largely defined by the cavities its skin bridges -- the orbits, 465// the nasal aperture, the temporal fossa. A per-vertex offset reproduces every opening and pushes its rim 466// outward, so a socket becomes a bulging crater. That is the exact inverse of this lane's banked law that 467// relief modulates a radius and cannot CUT a hole: a normal offset cannot FILL one. 468// ★THE IMPLICIT PATH DOES IT FOR FREE, and that is why this belongs here and not in a new organ. The skull 469// is already a distance FIELD. Subtracting a depth from the distance before polygonizing moves the zero 470// level OUTWARD by that depth, and AN ISO-SURFACE AT DISTANCE d NATURALLY BRIDGES ANY OPENING NARROWER 471// THAN 2d -- which is precisely the eyelid-over-orbit and skin-over-aperture behaviour we want, arising 472// from the representation rather than from a special case. 473// ★DEPTH IS KEYED ON THE FIELD'S OWN AUTHORED STATIONS, not on a per-mille of some bounding box, because 474// the field already places every landmark in millimetres in a frame centred on the cranium. These are the 475// published forensic depths (Rhine/De Greef class) this codebase carries in knowledge/face_tissue.dat. 476// ⚠HONEST v1 LIMIT, declared here rather than discovered later: this varies with HEIGHT only. The temple 477// is 3mm while the cheekbone at nearly the same height is 7, so a height-keyed table cannot express a 478// lateral difference. The nasion dip at 3mm between brow 7 and nasal 6 IS expressible, and it is the one 479// that makes a nose read as a nose. 480static SS_TISSUE: i64 481// ★★★DENSE-ER TISSUE MAP: DEPTH IS A FUNCTION OF (HEIGHT, LATERAL DISTANCE), NOT HEIGHT ALONE. 482// ★WHY, from the 2026 literature rather than from taste: the state of the art in anatomy-guided face 483// generation (Skull-to-Face, arXiv 2403.16207; SCULPTOR skeleton-consistent parametric generator; and the 484// PLOS One automatic forensic reconstruction from DENSE STATISTICS OF SOFT TISSUE THICKNESS) does not use 485// a sparse landmark list -- it fits a DENSE MAP of tissue thickness over the skull surface. Our v1 was a 486// 9-band table keyed on height only, and I declared its limit when I shipped it: the temple is ~3mm while 487// the zygion sits at ~7mm at nearly the SAME HEIGHT, so a 1-D table structurally cannot express either 488// without corrupting the other. Adding the lateral axis is the smallest honest step toward a dense map, 489// and it is the axis that carries the largest published disagreement. 490// ★THE LATERAL STRUCTURE IS REAL ANATOMY, NOT SMOOTHING. Two rows invert with distance from the midline 491// and they are the reason this matters: at the BROW LINE the midline glabella is thick (7) while the 492// TEMPLE is the thinnest soft tissue on the whole head (3); at the JAW the midline chin is 11 but the 493// GONION is thicker still going outward (11) because the MASSETER inserts there. A height-only table gets 494// the temple and the gonion wrong in OPPOSITE directions, which is exactly the kind of error that shows up 495// as a wrong silhouette rather than a wrong number. 496// ⚠STILL NOT A DENSE MAP: this is 9 height bands x 3 lateral bands = 27 cells, against a literature 497// standard of a per-vertex statistical field. It is a strict superset of v1's information, not parity. 498const SS_LAT_MID: i64 = 25 // |x| under this is the midline column 499const SS_LAT_FAR: i64 = 55 // |x| over this is the far-lateral column (temple / zygomatic arch / gonion) 500func ss_tdepth2(y: i64, ax: i64) -> i64 { 501 var col: i64 = 0 502 if ax >= SS_LAT_MID { col = 1 } 503 if ax >= SS_LAT_FAR { col = 2 } 504 if y < 0-78 { if col==0 { return 11 } if col==1 { return 10 } return 8 } // chin / mental 505 if y < 0-60 { if col==0 { return 9 } if col==1 { return 10 } return 11 } // jaw -- THICKENS outward (masseter) 506 if y < 0-38 { if col==0 { return 11 } if col==1 { return 9 } return 8 } // lower lip 507 if y < 0-30 { if col==0 { return 10 } if col==1 { return 8 } return 7 } // upper lip 508 if y < 0 { if col==0 { return 7 } if col==1 { return 7 } return 6 } // maxilla / zygion 509 if y < 8 { if col==0 { return 6 } if col==1 { return 7 } return 6 } // nasal 510 if y < 22 { if col==0 { return 3 } if col==1 { return 6 } return 5 } // nasion DIP on the midline only 511 if y < 30 { if col==0 { return 7 } if col==1 { return 6 } return 4 } // brow: glabella thick, temple thin 512 if col==0 { return 5 } 513 if col==1 { return 4 } 514 return 3 // temple -- thinnest on the head 515} 516// v1 kept as the midline column so the 1-D behaviour is still reachable and comparable 517func ss_tdepth(y: i64) -> i64 { return ss_tdepth2(y, 0) } 518// ***TABLE VALUES ARE LANDMARK MEASUREMENTS, NOT STEP FUNCTIONS. On the distorted field the band 519// steps were accidentally BLURRED by the field error; the redistanced field reproduces them 520// faithfully, as visible horizontal shelves at every band boundary (rendered proof: 521// /world/mh_skin_env_redist.png). The honest reading of a forensic depth table is depth AT a 522// landmark station, interpolated BETWEEN stations. Only the REDIST path consumes this, so the 523// shipped band behaviour is byte-identical. 524const SS_TD_N: i64 = 9 525static SS_TD_Y: i64 526static SS_TD_D: i64 527func ss_td_tab() -> i64 { 528 if SS_TD_Y == 0 { 529 SS_TD_Y = sys_mmap(SS_TD_N*8) as i64 530 SS_TD_D = sys_mmap(SS_TD_N*8) as i64 531 let Y: *i64 = SS_TD_Y as *i64 532 let D: *i64 = SS_TD_D as *i64 533 Y[0]=0-88; D[0]=11 534 Y[1]=0-69; D[1]=9 535 Y[2]=0-49; D[2]=11 536 Y[3]=0-34; D[3]=10 537 Y[4]=0-15; D[4]=7 538 Y[5]=4; D[5]=6 539 Y[6]=15; D[6]=3 540 Y[7]=26; D[7]=7 541 Y[8]=45; D[8]=5 542 } 543 return 0 544} 545// depth at height y in mm x SS_RDQ, piecewise-linear between the landmark stations (band centres of 546// ss_tdepth, same forensic values), clamped at both ends 547func ss_tdepth_q(y: i64) -> i64 { 548 ss_td_tab() 549 let Y: *i64 = SS_TD_Y as *i64 550 let D: *i64 = SS_TD_D as *i64 551 if y <= Y[0] { return D[0]*SS_RDQ } 552 if y >= Y[SS_TD_N-1] { return D[SS_TD_N-1]*SS_RDQ } 553 var i: i64 = 0 554 while i < SS_TD_N-1 { 555 if y <= Y[i+1] { 556 let c0: i64 = Y[i] 557 let c1: i64 = Y[i+1] 558 return (D[i]*(c1-y) + D[i+1]*(y-c0))*SS_RDQ/(c1-c0) 559 } 560 i = i + 1 561 } 562 return D[SS_TD_N-1]*SS_RDQ 563} 564func ss_f32(v: i64, scale: i64) -> i64 { 565 // integer -> IEEE-754 single bits, value = v/scale 566 if v == 0 { return 0 } 567 var neg: i64 = 0 568 var m: i64 = v 569 if m < 0 { neg = 1; m = 0 - m } 570 var e: i64 = 127 571 // normalise m/scale into [1,2) 572 var num: i64 = m 573 var den: i64 = scale 574 while num >= den*2 { den = den*2; e = e + 1 } 575 while num < den { num = num*2; e = e - 1 } 576 // mantissa = (num/den - 1) * 2^23 577 let frac: i64 = ((num - den) * SS_MAGIC_8388608) / den 578 var bits: i64 = (e << 23) | (frac & SS_MAGIC_8388607) 579 if neg == 1 { bits = bits | (1 << 31) } 580 return bits 581} 582func ss_wr32(b: *u8, o: i64, v: i64) -> i64 { 583 b[o] = (v & 255) as u8 584 b[o+1] = ((v >> 8) & 255) as u8 585 b[o+2] = ((v >> 16) & 255) as u8 586 b[o+3] = ((v >> 24) & 255) as u8 587 return 0 588} 589 590// ***REALISED THICKNESS -- THE OBJECTIVE THE DENSE-MAP LITERATURE ACTUALLY NEEDS, AND IT IS FREE HERE. 591// The 2-D table failed because writing depths into a FIELD is not the same as getting them on the 592// SURFACE: surface_nets redistributes them. So the thing to build is not a better table, it is a 593// MEASUREMENT OF WHAT THE SURFACE ACTUALLY REALISED. Our skull IS a distance function, so |field| at an 594// envelope vertex IS that vertex's realised tissue thickness over the bone -- no ray cast, no nearest- 595// triangle search. Same trick ss_fit already uses against the scanned reference. 596// Simultaneously the diagnostic (how much does the field-to-surface step redistribute a requested 597// depth) and the objective a coordinate descent would minimise. 598func ss_bandix(y: i64) -> i64 { 599 if y < 0-78 { return 0 } 600 if y < 0-60 { return 1 } 601 if y < 0-38 { return 2 } 602 if y < 0-30 { return 3 } 603 if y < 0 { return 4 } 604 if y < 8 { return 5 } 605 if y < 22 { return 6 } 606 if y < 30 { return 7 } 607 return 8 608} 609func ss_band_req(ix: i64) -> i64 { 610 if ix == 0 { return 11 } 611 if ix == 1 { return 9 } 612 if ix == 2 { return 11 } 613 if ix == 3 { return 10 } 614 if ix == 4 { return 7 } 615 if ix == 5 { return 6 } 616 if ix == 6 { return 3 } 617 if ix == 7 { return 7 } 618 return 5 619} 620func ss_rd32(b: *u8, o: i64) -> i64 { 621 return (b[o] as i64) | ((b[o+1] as i64)<<8) | ((b[o+2] as i64)<<16) | ((b[o+3] as i64)<<24) 622} 623func ss_r_f32(bits: i64, scale: i64) -> i64 { 624 let s: i64 = (bits >> 31) & 1 625 let e: i64 = (bits >> 23) & 255 626 let m: i64 = bits & SS_MAGIC_8388607 627 if e == 0 { return 0 } 628 if e == 255 { return 0 } 629 let mant: i64 = SS_MAGIC_8388608 | m 630 let sh: i64 = e - 127 - 23 631 var v: i64 = 0 632 if sh >= 0 { if sh > 30 { return 0 } v = (mant*scale) << sh } 633 else { let rs: i64 = 0 - sh; if rs > 62 { return 0 } v = (mant*scale) >> rs } 634 if s == 1 { return 0 - v } 635 return v 636} 637// ★SCORE AGAINST THE REAL SCANNED REFERENCE, IN MILLIMETRES -- and the metric is FREE because our skull 638// IS a distance function: |field| at a reference vertex is the error there. No registration search, no 639// closest-triangle hunt. Eight rounds of hand-placing primitives matched the bounding box to 5mm while 640// the SHAPE stayed a cluster of lumps; a bounding box cannot see shape and an eyeball cannot be 641// optimized against. This can. 642// ⚠FRAME: the reference faces -z in a full-body frame, ours faces +z centred on the cranium. The 643// transform is DERIVED from the reference's own bbox, and z is negated -- without that we would be 644// scoring our face against the back of its skull. 645// THE ORACLE'S FRAME, READ ONCE, CORRECTLY (anatomy AN17, 2026-09-18). knowledge/skull.nxmesh is BodyParts3D, and 646// BodyParts3D is a FLOOR-ORIGIN, z-UP body frame: the head sits at z 1.42..1.64 m, y runs antero-posterior with the 647// face at -y, x lateral (first triangle: x 18.7, y -156.9, z 1457.4 mm; bbox x 151, y 209, z 215 mm). Every reader in 648// this file took it as y-up and merely negated z, so the tuner fitted an upright field to a skull LYING ON ITS BACK 649// since the first tune: the trend's "vault 4 mm" was measured against that pose and knowledge/skull_fit.dat converged 650// to the egg that best matches a supine skull (vault half-height 92, a negative nasal radius). Measured by the AN17 651// canon ruler's midline profile dump: read as x, z, -y the profile from the front IS a skull (forehead receding 110 mm 652// over 126 mm to a glabella, an aperture floor 26 mm behind it, a chin 53 mm below the prosthion); read as y-up it is 653// the skull base seen from below, its 36 mm see-through the foramen magnum. 654// x_a = x - cx ; y_a = z - cz ; z_a = -(y - cy) -- a proper rotation of a quarter turn about x, applied to positions 655// (out3, integer mm at scale units) and to normals (ss_ref_map_normal). ONE mapper for every reader below. 656func ss_ref_map(buf: *u8, o: i64, cx: i64, cy: i64, cz: i64, scale: i64, out3: *i64) -> i64 { 657 out3[0] = ss_r_f32(ss_rd32(buf, o), scale) - cx 658 out3[1] = ss_r_f32(ss_rd32(buf, o+8), scale) - cz 659 out3[2] = 0 - (ss_r_f32(ss_rd32(buf, o+4), scale) - cy) 660 return 0 661} 662func ss_ref_map_normal(buf: *u8, o: i64, scale: i64, out3: *i64) -> i64 { 663 out3[0] = ss_r_f32(ss_rd32(buf, o), scale) 664 out3[1] = ss_r_f32(ss_rd32(buf, o+8), scale) 665 out3[2] = 0 - ss_r_f32(ss_rd32(buf, o+4), scale) 666 return 0 667} 668func ss_fit(path: *u8, sexf: i64, robust: i64, stride: i64) -> i64 { 669 let ln: *i64 = sys_mmap(16) as *i64 670 let buf: *u8 = sys_read_file(path, ln) 671 if (buf as i64) == 0 { ss_puts("{\x22error\x22:\x22cannot read reference\x22}\n" as *u8); return 3 } 672 let nlayer: i64 = ss_rd32(buf, 8) 673 let nt: i64 = ss_rd32(buf, 12) 674 let hdr: i64 = 16 + nlayer*24 675 if nt <= 0 { ss_puts("{\x22error\x22:\x22no triangles\x22}\n" as *u8); return 4 } 676 var lox: i64 = 0; var hix: i64 = 0 677 var loy: i64 = 0; var hiy: i64 = 0 678 var loz: i64 = 0; var hiz: i64 = 0 679 var first: i64 = 1 680 var t: i64 = 0 681 while t < nt { 682 let o: i64 = hdr + t*84 683 var j: i64 = 0 684 while j < 3 { 685 let x: i64 = ss_r_f32(ss_rd32(buf,o+j*12), 1) 686 let y: i64 = ss_r_f32(ss_rd32(buf,o+j*12+4), 1) 687 let z: i64 = ss_r_f32(ss_rd32(buf,o+j*12+8), 1) 688 if first == 1 { lox=x; hix=x; loy=y; hiy=y; loz=z; hiz=z; first=0 } else { 689 if x<lox {lox=x} 690 if x>hix {hix=x} 691 if y<loy {loy=y} 692 if y>hiy {hiy=y} 693 if z<loz {loz=z} 694 if z>hiz {hiz=z} 695 } 696 j = j + 1 697 } 698 t = t + 1 699 } 700 let cx: i64 = (lox+hix)/2 701 let cy: i64 = (loy+hiy)/2 702 let cz: i64 = (loz+hiz)/2 703 var sum: i64 = 0 704 var n: i64 = 0 705 var worst: i64 = 0 706 var over: i64 = 0 707 t = 0 708 while t < nt { 709 if t % stride == 0 { 710 let o: i64 = hdr + t*84 711 let m3: *i64 = sys_mmap(24) as *i64 712 ss_ref_map(buf, o, cx, cy, cz, 1, m3) 713 let x: i64 = m3[0] 714 let y: i64 = m3[1] 715 let z: i64 = m3[2] 716 var d: i64 = ss_field(x, y, z, sexf, robust) 717 if d < 0 { d = 0 - d } 718 sum = sum + d 719 n = n + 1 720 if d > worst { worst = d } 721 if d > 10 { over = over + 1 } 722 } 723 t = t + 1 724 } 725 if n == 0 { ss_puts("{\x22error\x22:\x22no samples\x22}\n" as *u8); return 5 } 726 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22fit\x22,\x22mean_err_mm\x22:" as *u8); ss_pn(sum/n) 727 ss_puts(",\x22worst_err_mm\x22:" as *u8); ss_pn(worst) 728 ss_puts(",\x22over_10mm_permil\x22:" as *u8); ss_pn(over*1000/n) 729 ss_puts(",\x22samples\x22:" as *u8); ss_pn(n) 730 ss_puts(",\x22ref_bbox_mm\x22:[" as *u8); ss_pn(hix-lox) 731 ss_puts("," as *u8); ss_pn(hiy-loy); ss_puts("," as *u8); ss_pn(hiz-loz) 732 ss_puts("]}\n" as *u8) 733 return 0 734} 735 736// load reference vertices once into flat arrays, already transformed into our frame 737func ss_load_ref(path: *u8, RX: *i64, RY: *i64, RZ: *i64, cap: i64, stride: i64) -> i64 { 738 let ln: *i64 = sys_mmap(16) as *i64 739 let buf: *u8 = sys_read_file(path, ln) 740 if (buf as i64) == 0 { return 0-1 } 741 let digest: *u8 = sys_mmap(SHA256_DIGEST_BYTES) 742 if sha256_digest_checked_native(buf, ln[0], digest) != 0 { return 0 - 2 } 743 if digest[0] != (0 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 744 if digest[1] != (34 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 745 if digest[2] != (219 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 746 if digest[3] != (65 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 747 if digest[4] != (170 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 748 if digest[5] != (93 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 749 if digest[6] != (31 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 750 if digest[7] != (116 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 751 if digest[8] != (30 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 752 if digest[9] != (117 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 753 if digest[10] != (244 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 754 if digest[11] != (161 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 755 if digest[12] != (156 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 756 if digest[13] != (1 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 757 if digest[14] != (99 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 758 if digest[15] != (197 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 759 if digest[16] != (254 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 760 if digest[17] != (187 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 761 if digest[18] != (192 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 762 if digest[19] != (37 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 763 if digest[20] != (241 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 764 if digest[21] != (111 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 765 if digest[22] != (238 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 766 if digest[23] != (234 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 767 if digest[24] != (6 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 768 if digest[25] != (134 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 769 if digest[26] != (22 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 770 if digest[27] != (209 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 771 if digest[28] != (166 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 772 if digest[29] != (185 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 773 if digest[30] != (19 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 774 if digest[31] != (194 as u8) { ss_puts("REFERENCE-CONTRACT-MISMATCH\n" as *u8); return 0 - 3 } 775 let nlayer: i64 = ss_rd32(buf, 8) 776 let nt: i64 = ss_rd32(buf, 12) 777 let hdr: i64 = 16 + nlayer*24 778 var lox: i64 = 0; var hix: i64 = 0 779 var loy: i64 = 0; var hiy: i64 = 0 780 var loz: i64 = 0; var hiz: i64 = 0 781 var first: i64 = 1 782 var t: i64 = 0 783 while t < nt { 784 let o: i64 = hdr + t*84 785 // all three vertices: the gapmap and voxref centre by the same bbox, and a centre read off vertex 0 alone 786 // (as this loop did until 2026-09-18) registered the two readers a fraction of a cell apart 787 var vj: i64 = 0 788 while vj < 3 { 789 let x: i64 = ss_r_f32(ss_rd32(buf,o+vj*12), 1) 790 let y: i64 = ss_r_f32(ss_rd32(buf,o+vj*12+4), 1) 791 let z: i64 = ss_r_f32(ss_rd32(buf,o+vj*12+8), 1) 792 if first == 1 { lox=x; hix=x; loy=y; hiy=y; loz=z; hiz=z; first=0 } else { 793 if x<lox {lox=x} 794 if x>hix {hix=x} 795 if y<loy {loy=y} 796 if y>hiy {hiy=y} 797 if z<loz {loz=z} 798 if z>hiz {hiz=z} 799 } 800 vj = vj + 1 801 } 802 t = t + 1 803 } 804 let cx: i64 = (lox+hix)/2 805 let cy: i64 = (loy+hiy)/2 806 let cz: i64 = (loz+hiz)/2 807 var n: i64 = 0 808 let m3: *i64 = sys_mmap(24) as *i64 809 t = 0 810 while t < nt { 811 if t % stride == 0 { 812 if n < cap { 813 let o: i64 = hdr + t*84 814 ss_ref_map(buf, o, cx, cy, cz, 1, m3) 815 RX[n] = m3[0] 816 RY[n] = m3[1] 817 RZ[n] = m3[2] 818 n = n + 1 819 } 820 } 821 t = t + 1 822 } 823 return n 824} 825// ★★THE OBJECTIVE IS SYMMETRIC, AND IT HAS TO BE. A one-directional score -- "how far is each REFERENCE 826// point from my surface" -- is trivially gamed by DELETING GEOMETRY: the first tuning run shrank the 827// orbits from 22mm to 8mm and flattened the maxilla from 30mm to 13mm, improving the number 40% by 828// filling in the eye sockets, because surface that does not exist cannot be wrong. 829// The reverse term fixes that by construction: sample points on OUR surface and measure how far they 830// are from the REFERENCE. A filled orbit puts our surface where the reference has a hole, and the 831// reverse term charges for it. Together they are a two-sided (Hausdorff-style) distance. 832// ⚠We have no distance function for the reference MESH, so the reverse term uses the nearest reference 833// VERTEX from a spatial grid. That is an upper bound on the true point-to-surface distance -- it can 834// overstate, never understate, which is the safe direction for a penalty. 835// the oracle box the reverse term's spatial hash covers: the scanned skull's own extent, in the field's frame 836const SG_DIM: i64 = 24 // spatial hash grid, cells per axis 837const SG_EXT: i64 = 140 // half-extent covered, mm 838const SS_TUNE_LAT: i64 = 6 // reverse-term lattice spacing, mm (the objective's sampling of OUR surface) 839const SS_GR_N: i64 = 7 // the named regions of ss_gap_region (vault, base, brow-orbits, nasal, zygomatic, mandible, maxilla) 840// ★THE LANDMARK TERM (AN17, 2026-09-19). MEASURED FIRST: with the two surface terms alone, region-balanced, the descent 841// closed the orbit sockets to 2 mm slits and deepened the aperture to a 35 mm tunnel while the objective fell 445 -> 413, 842// because a surface objective cannot see an opening. This term is the third error mean the fit library folds in: where 843// the field PLACES its features (from its own stations, closed-form) against where the ruler FOUND the oracle's 844// landmarks (knowledge/status/skull_oracle_q.dat, written by nx_skull_canon_gate from its own measurement, never typed 845// here). It is a SURROGATE of the ruler on our mesh -- the beat still runs the real ruler on the emitted mesh and gates 846// the pass on its in-band count -- and its predicted quantities are printed so the surrogate's error is readable beside 847// the ruler's reading. Quantities the ruler seeds from its own conf (orbit depth at the eye seed, the vault chord pitch) 848// are not predicted. Absent file = term OFF, announced. 849const SS_LMQ_N: i64 = 18 // the ruler's quantity count, in skc_qname order (15 + the three of 2026-09-19) 850const SS_LMQ_PRED: i64 = 16 // the quantities this field can place from its stations 851const SS_LMQ_BYTES: i64 = 4096 852const SS_LMQ_NONE: i64 = 0 - 999999999 // "this quantity is not predicted from the stations" -- a value no landmark can reach 853static SS_LMQ: i64 // *i64: oracle_u10 per quantity, or 0 when the file is absent 854static SS_LM_SEXF: i64 855static SS_LM_ROBUST: i64 856func ss_lm_load() -> i64 { 857 if SS_LMQ != 0 { return 1 } 858 let ln: *i64 = sys_mmap(16) as *i64 859 let buf: *u8 = sys_read_file("knowledge/status/skull_oracle_q.dat" as *u8, ln) 860 if (buf as i64) == 0 { return 0 } 861 let n: i64 = ln[0] 862 let T: *i64 = sys_mmap(SS_LMQ_N*8) as *i64 863 // each row: <name> <oracle_u10> <band_u10>; the second field of each line is the target. Flag-exited scans: a loop 864 // that clobbers its cursor to break cannot report where it stopped (the estate's cursor-sentinel law) 865 var i: i64 = 0 866 var row: i64 = 0 867 while i < n { 868 var go: i64 = 1 869 while go == 1 { if i >= n { go = 0 } else { if buf[i] == (32 as u8) { go = 0 } else { i = i + 1 } } } 870 if i < n { i = i + 1 } 871 var neg: i64 = 0 872 if i < n { if buf[i] == (45 as u8) { neg = 1; i = i + 1 } } 873 var v: i64 = 0 874 var any: i64 = 0 875 go = 1 876 while go == 1 { 877 if i >= n { go = 0 } else { 878 let c: i64 = buf[i] as i64 879 if c >= 48 { if c <= 57 { v = v*10 + (c-48); any = 1; i = i + 1 } else { go = 0 } } else { go = 0 } 880 } 881 } 882 if any == 1 { if row < SS_LMQ_N { if neg == 1 { v = 0 - v } T[row] = v; row = row + 1 } } 883 go = 1 884 while go == 1 { if i >= n { go = 0 } else { if buf[i] == (10 as u8) { go = 0 } else { i = i + 1 } } } 885 if i < n { i = i + 1 } 886 } 887 if row < SS_LMQ_N { return 0 } 888 SS_LMQ = T as i64 889 return 1 890} 891// the field's own placement of the ruler's quantities, u10, from the stations (index = skc_qname order; -1 = not predicted) 892func ss_lm_predict(P: *i64, Q: *i64) -> i64 { 893 let brow: i64 = 10 - 3*SS_LM_SEXF/SS_PERMILLE + 5*SS_LM_ROBUST/SS_PERMILLE 894 // the ruler's glabella is the MOST ANTERIOR midline point above the aperture floor: the brow bar's front or the 895 // frontal ellipsoid's front, whichever leads (measured 2026-09-19: the surrogate read the bar, the ruler the bulge) 896 var glab_z: i64 = P[P_BZ] + brow 897 if P[P_FZ] + P[P_FD] > glab_z { glab_z = P[P_FZ] + P[P_FD] } 898 let glab_y: i64 = P[P_BY] 899 let nts: i64 = sp_isin(P[P_NTILT]) 900 let ntc: i64 = sp_icos(P[P_NTILT]) 901 let nasion_y: i64 = P[P_NY] + P[P_NRY]*ntc/SS_PERMILLE 902 let yrh: i64 = P[P_NY] - P[P_NRY]*ntc/SS_PERMILLE 903 let nasosp_y: i64 = yrh - P[P_PAH] 904 let pog_z: i64 = P[P_JZ] + P[P_CRZ] 905 let gnath_y: i64 = P[P_JY] - P[P_CRY] 906 let pros_z: i64 = P[P_UZ] + P[P_UAZ] + P[P_AAR] 907 let pros_y: i64 = P[P_UY] + P[P_UTHT]/2 + P[P_AAR]*2/3 908 let k: i64 = ss_k() 909 Q[0] = (pog_z - glab_z)*10 910 Q[1] = (nasion_y - nasosp_y)*10 911 Q[2] = P[P_PAH]*10 912 Q[3] = P[P_PAW]*10 // the ruler's crest walk stops at the cylinder's own rim, not the process crest (measured) 913 Q[4] = 2*P[P_OX]*10 914 Q[5] = (glab_y - P[P_OAY])*10 915 Q[6] = 2*(P[P_OSW] + k)*10 916 Q[7] = 2*(P[P_ZBX] + P[P_ZR])*10 917 Q[8] = 2*(P[P_JBX] + P[P_JR])*10 918 Q[9] = (pros_z - glab_z)*10 919 Q[10] = (nasion_y - pros_y)*10 920 Q[11] = ((glab_y - nasosp_y) - (nasosp_y - gnath_y))*10 921 Q[12] = P[P_PAD]*10 922 Q[13] = SS_LMQ_NONE 923 Q[14] = SS_LMQ_NONE 924 // the three the ruler grew for the tuner's blind spots: the socket's rim height, the dip at the nasion (the plate's 925 // front face at its top end against the glabella), the nasal bones' projection (the plate's slope times its length) 926 let nasion_z: i64 = P[P_NZ] - P[P_NRY]*nts/SS_PERMILLE + P[P_NTH] 927 let rhinion_z: i64 = P[P_NZ] + P[P_NRY]*nts/SS_PERMILLE + P[P_NTH] 928 Q[15] = 2*(P[P_OSH] + k)*10 929 Q[16] = (glab_z - nasion_z)*10 930 Q[17] = (rhinion_z - nasion_z)*10 931 return SS_LMQ_PRED 932} 933// the third error mean, centi-mm: mean |predicted - oracle| over the predicted quantities. The scratch vector is mapped 934// ONCE (this runs per descent move; a page per call is the leak this file measured in ss_field) 935static SS_LMSCR: i64 936func ss_lm_term(P: *i64) -> i64 { 937 if SS_LMQ == 0 { return 0 } 938 let O: *i64 = SS_LMQ as *i64 939 if SS_LMSCR == 0 { SS_LMSCR = sys_mmap(SS_LMQ_N*8) as i64 } 940 let Q: *i64 = SS_LMSCR as *i64 941 ss_lm_predict(P, Q) 942 var sum: i64 = 0 943 var cnt: i64 = 0 944 var q: i64 = 0 945 while q < SS_LMQ_N { 946 if Q[q] != SS_LMQ_NONE { 947 var d: i64 = Q[q] - O[q] 948 if d < 0 { d = 0 - d } 949 sum = sum + d 950 cnt = cnt + 1 951 } 952 q = q + 1 953 } 954 if cnt == 0 { return 0 } 955 return sum*10/cnt 956} 957// ★THE TUNE COMPOSES nx_fieldfit_lib (AN17, 2026-09-19): the two-sided region-balanced objective, the coordinate descent 958// and the fit file are the library's; this organ supplies its field, its region classifier and its live-station mask 959// as function values, and keeps only what is the skull's -- the oracle reader, the parameter vector, the receipt. 960func ss_params_valid(P: *i64, np: i64) -> i64 { 961 if np != SP_N { return 0 } 962 if P[P_VW] <= 0 { return 0 } 963 if P[P_VH] <= 0 { return 0 } 964 if P[P_VD] <= 0 { return 0 } 965 if P[P_FH] <= 0 { return 0 } 966 if P[P_FD] <= 0 { return 0 } 967 if P[P_MW] <= 0 { return 0 } 968 if P[P_MH] <= 0 { return 0 } 969 if P[P_MD] <= 0 { return 0 } 970 if P[P_OX] <= 0 { return 0 } 971 if P[P_BX] <= 0 { return 0 } 972 if P[P_ZR] <= 0 { return 0 } 973 if P[P_NRX] <= 0 { return 0 } 974 if P[P_NRY] <= 0 { return 0 } 975 if P[P_JBX] <= 0 { return 0 } 976 if P[P_JR] <= 0 { return 0 } 977 if P[P_RRX] <= 0 { return 0 } 978 if P[P_RRZ] <= 0 { return 0 } 979 if P[P_CRX] <= 0 { return 0 } 980 if P[P_CRY] <= 0 { return 0 } 981 if P[P_CRZ] <= 0 { return 0 } 982 if P[P_UAX] <= 0 { return 0 } 983 if P[P_UAZ] <= 0 { return 0 } 984 if P[P_UTW] <= 0 { return 0 } 985 if P[P_UTHT] <= 0 { return 0 } 986 if P[P_LAX] <= 0 { return 0 } 987 if P[P_LAZ] <= 0 { return 0 } 988 if P[P_LTW] <= 0 { return 0 } 989 if P[P_LTHT] <= 0 { return 0 } 990 if P[P_OSW] <= 0 { return 0 } 991 if P[P_OSH] <= 0 { return 0 } 992 if P[P_OSD] <= 0 { return 0 } 993 if P[P_PAW] <= 0 { return 0 } 994 if P[P_PAH] <= 0 { return 0 } 995 if P[P_PAD] <= 0 { return 0 } 996 if P[P_NTH] <= 0 { return 0 } 997 if P[P_AAR] <= 0 { return 0 } 998 if P[P_FPR] <= 0 { return 0 } 999 if P[P_UN] < SP_RING_N_MIN { return 0 } if P[P_UN] > SP_RING_N_MAX { return 0 } 1000 if P[P_LN] < SP_RING_N_MIN { return 0 } if P[P_LN] > SP_RING_N_MAX { return 0 } 1001 if P[P_UTH] < SP_RING_TH_MIN { return 0 } if P[P_UTH] > SP_RING_TH_MAX { return 0 } 1002 if P[P_LTH] < SP_RING_TH_MIN { return 0 } if P[P_LTH] > SP_RING_TH_MAX { return 0 } 1003 return 1 1004} 1005func ss_contract_cat(b: *u8, o: i64, s: *u8) -> i64 { var i: i64=0; while s[i] != 0 { b[o+i]=s[i]; i=i+1 } return o+i } 1006func ss_fit_contract(sexf: i64, robust: i64, stride: i64) -> *FfFitContract { 1007 let C: *FfFitContract=sys_mmap(32) as *FfFitContract 1008 let b: *u8=sys_mmap(486) 1009 var o: i64=ss_contract_cat(b,0,"NXFFIT2 schema=4bef6d72830e61efa67c0ca4f0a1887fb596f8ae1d7c93b25b7f2d30275fd7f4 frame=bodyparts3d-x-z-negative-y-mm-v1 producer=11613c2b4757d27c32efc54fa3e3fe43693d7631399e93d5646fb913b627b83c reference=0022db41aa5d1f741e75f4a19c0163c5febbc025f16feeea068616d1a6b913c2 objective=region-balanced-two-sided-no-extra residual=none" as *u8) 1010 o=ss_contract_cat(b,o," sex=" as *u8); o=ff_wint(b,o,sexf) 1011 o=ss_contract_cat(b,o," robust=" as *u8); o=ff_wint(b,o,robust) 1012 o=ss_contract_cat(b,o," stride=" as *u8); o=ff_wint(b,o,stride) 1013 b[o]=10 as u8; o=o+1 1014 C.header=b; C.header_bytes=o; C.np=SP_N; C.valid=ss_params_valid 1015 return C 1016} 1017 1018func ss_tune(path: *u8, sexf: i64, robust: i64, stride: i64, passes: i64, step0: i64, save: *u8) -> i64 { 1019 let cap: i64 = SS_MAGIC_40000 1020 let C: *FfCtx = ff_ctx_new(SP_N, SS_GR_N, cap, SG_EXT, SG_DIM, SS_TUNE_LAT, SS_FQ) 1021 C.field = ss_field_p_q 1022 C.region = ss_gap_region 1023 C.live = ss_param_live 1024 C.a = sexf 1025 C.b = robust 1026 SS_LM_SEXF = sexf 1027 SS_LM_ROBUST = robust 1028 C.extra = ss_lm_term 1029 C.has_extra = 0 // explicit two-sided objective; no optional unbound landmark file 1030 let n: i64 = ss_load_ref(path, C.RX, C.RY, C.RZ, cap, stride) 1031 if n <= 0 { ss_puts("{\x22error\x22:\x22cannot load reference\x22}\n" as *u8); return 3 } 1032 C.n = n 1033 ff_bin(C) 1034 ff_regions(C) 1035 let P: *i64 = sys_mmap(SP_N*8) as *i64 1036 ss_defaults(P) 1037 // iterate FROM the current fit so successive tune runs converge instead of restarting 1038 let seeded: i64 = 0 1039 ss_puts("FIT-MODE explicit-new-from-named-source-defaults legacy-not-applied residual-none\n" as *u8) 1040 if ss_params_valid(P, SP_N) != 1 { ss_puts("FIT-REFUSED invalid named defaults\n" as *u8); return 6 } 1041 let start: i64 = ff_score2(C, P) 1042 let best: i64 = ff_descend_checked(C, P, passes, step0, 1, ss_params_valid) 1043 // persist the fit as DATA (the emitter loads it; no source edit carries these numbers) 1044 if best < 0 { return 6 } 1045 if (save as i64) != 0 { if ff_save_verified(save, P, ss_fit_contract(sexf, robust, stride)) < 0 { return 6 } } 1046 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22tune\x22,\x22samples\x22:" as *u8); ss_pn(n) 1047 ss_puts(",\x22start_err_mm\x22:" as *u8); ss_pn(start/100) 1048 ss_puts(",\x22final_err_mm\x22:" as *u8); ss_pn(best/100) 1049 ss_puts(",\x22start_centi\x22:" as *u8); ss_pn(start) 1050 ss_puts(",\x22final_centi\x22:" as *u8); ss_pn(best) 1051 ss_puts(",\x22objective\x22:\x22region-balanced\x22,\x22regions\x22:" as *u8); ss_pn(SS_GR_N) 1052 ss_puts(",\x22live_params\x22:" as *u8); ss_pn(ff_live_count(C)) 1053 ss_puts(",\x22seeded\x22:" as *u8); ss_pn(seeded) 1054 ss_puts(",\x22landmark_term\x22:" as *u8); ss_pn(C.has_extra) 1055 if C.has_extra == 1 { 1056 // the surrogate's own prediction, u10, in the ruler's quantity order (-1 = not predicted): read it beside the 1057 // canon gate's `q ... ours=` line to know the surrogate's error 1058 let LQ: *i64 = sys_mmap(SS_LMQ_N*8) as *i64 1059 ss_lm_predict(P, LQ) 1060 ss_puts(",\x22landmark_term_centi\x22:" as *u8); ss_pn(ss_lm_term(P)) 1061 ss_puts(",\x22predicted_u10\x22:[" as *u8) 1062 var lq: i64 = 0 1063 while lq < SS_LMQ_N { 1064 if lq > 0 { ss_puts("," as *u8) } 1065 ss_pn(LQ[lq]) 1066 lq = lq + 1 1067 } 1068 ss_puts("]" as *u8) 1069 } 1070 ss_puts(",\x22params\x22:[" as *u8) 1071 var q: i64 = 0 1072 while q < SP_N { 1073 if q > 0 { ss_puts("," as *u8) } 1074 ss_pn(P[q]) 1075 q = q + 1 1076 } 1077 ss_puts("]}\n" as *u8) 1078 return 0 1079} 1080 1081// THE `thick` VERB: report, per height band, the depth we REQUESTED versus the thickness the emitted 1082// envelope ACTUALLY realised over the bone. A gap between them is the field-to-surface redistribution 1083// made visible, and its mean absolute error is the number a fit would drive to zero. 1084func ss_thick(path: *u8, sexf: i64, robust: i64, stride: i64) -> i64 { 1085 let ln: *i64 = sys_mmap(16) as *i64 1086 let buf: *u8 = sys_read_file(path, ln) 1087 if (buf as i64) == 0 { ss_puts("{\x22error\x22:\x22cannot read envelope mesh\x22}\n" as *u8); return 3 } 1088 let nlayer: i64 = ss_rd32(buf, 8) 1089 let nt: i64 = ss_rd32(buf, 12) 1090 if nt <= 0 { ss_puts("{\x22error\x22:\x22no triangles\x22}\n" as *u8); return 4 } 1091 let hdr: i64 = 16 + nlayer*24 1092 let cnt: *i64 = sys_mmap(9*8) as *i64 1093 let sm: *i64 = sys_mmap(9*8) as *i64 1094 let mn: *i64 = sys_mmap(9*8) as *i64 1095 let mx: *i64 = sys_mmap(9*8) as *i64 1096 var b: i64 = 0 1097 while b < 9 { cnt[b]=0; sm[b]=0; mn[b]=SS_EXTENT_SENTINEL; mx[b]=0-SS_EXTENT_SENTINEL; b=b+1 } 1098 var abserr: i64 = 0 1099 var n: i64 = 0 1100 var t: i64 = 0 1101 while t < nt { 1102 if t % stride == 0 { 1103 var j: i64 = 0 1104 while j < 3 { 1105 let o: i64 = hdr + t*84 + j*12 1106 let px: i64 = ss_r_f32(ss_rd32(buf,o), 1) 1107 let py: i64 = ss_r_f32(ss_rd32(buf,o+4), 1) 1108 let pz: i64 = ss_r_f32(ss_rd32(buf,o+8), 1) 1109 let d: i64 = ss_field(px, py, pz, sexf, robust) 1110 let ix: i64 = ss_bandix(py) 1111 cnt[ix] = cnt[ix] + 1 1112 sm[ix] = sm[ix] + d 1113 if d < mn[ix] { mn[ix] = d } 1114 if d > mx[ix] { mx[ix] = d } 1115 var e: i64 = d - ss_band_req(ix) 1116 if e < 0 { e = 0 - e } 1117 abserr = abserr + e 1118 n = n + 1 1119 j = j + 1 1120 } 1121 } 1122 t = t + 1 1123 } 1124 if n == 0 { ss_puts("{\x22error\x22:\x22no samples\x22}\n" as *u8); return 5 } 1125 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22thick\x22,\x22samples\x22:" as *u8); ss_pn(n) 1126 ss_puts(",\x22mean_abs_err_mm\x22:" as *u8); ss_pn(abserr/n) 1127 ss_puts(",\x22bands\x22:[" as *u8) 1128 b = 0 1129 while b < 9 { 1130 if b > 0 { ss_puts("," as *u8) } 1131 ss_puts("{\x22band\x22:" as *u8); ss_pn(b) 1132 ss_puts(",\x22req\x22:" as *u8); ss_pn(ss_band_req(b)) 1133 ss_puts(",\x22mean\x22:" as *u8) 1134 if cnt[b] > 0 { ss_pn(sm[b]/cnt[b]) } else { ss_pn(0-1) } 1135 ss_puts(",\x22min\x22:" as *u8) 1136 if cnt[b] > 0 { ss_pn(mn[b]) } else { ss_pn(0-1) } 1137 ss_puts(",\x22max\x22:" as *u8) 1138 if cnt[b] > 0 { ss_pn(mx[b]) } else { ss_pn(0-1) } 1139 ss_puts(",\x22n\x22:" as *u8); ss_pn(cnt[b]) 1140 ss_puts("}" as *u8) 1141 b = b + 1 1142 } 1143 ss_puts("]}\n" as *u8) 1144 return 0 1145} 1146 1147// ***THE `grad` VERB -- MEASURE |grad f| DIRECTLY INSTEAD OF INFERRING IT FROM SCATTER. 1148// Every remaining hypothesis about the tissue-thickness scatter is a claim about how far this field is 1149// from a TRUE distance function, where |grad f| = 1 everywhere. Rather than argue, sample it: walk a 1150// coarse lattice, keep the points NEAR THE SURFACE (the only region that matters for an offset), and 1151// report the distribution of |grad f| in per-mille. A true SDF reads 1000. 1152// ***READ IT LIKE THIS: spread around 1000 is the offset error budget. If a requested 7mm offset lands 1153// where |grad| is 700, the surface moves 10mm; at 1400 it moves 5mm. That IS the 3-6mm scatter, and this 1154// verb says so directly instead of by inference. It also discriminates the two surviving suspects -- 1155// ss_smin composition (already exonerated by K=0) versus ss_ellipsoid's first-order approximation -- 1156// because you can re-run it with argv[5]=0 for a plain union and compare the SAME distribution. 1157func ss_grad(sexf: i64, robust: i64, step: i64, near: i64) -> i64 { 1158 var lo: i64 = SS_EXTENT_SENTINEL 1159 var hi: i64 = 0-SS_EXTENT_SENTINEL 1160 var sum: i64 = 0 1161 var n: i64 = 0 1162 var under: i64 = 0 1163 var over: i64 = 0 1164 var x: i64 = 0 - SS_EXT 1165 while x <= SS_EXT { 1166 var y: i64 = 0 - SS_EXT 1167 while y <= SS_EXT { 1168 var z: i64 = 0 - SS_EXT 1169 while z <= SS_EXT { 1170 let f: i64 = ss_field(x, y, z, sexf, robust) 1171 var af: i64 = f 1172 if af < 0 { af = 0 - af } 1173 if af <= near { 1174 let gx: i64 = (ss_field(x+1,y,z,sexf,robust) - ss_field(x-1,y,z,sexf,robust)) * 1000 / 2 1175 let gy: i64 = (ss_field(x,y+1,z,sexf,robust) - ss_field(x,y-1,z,sexf,robust)) * 1000 / 2 1176 let gz: i64 = (ss_field(x,y,z+1,sexf,robust) - ss_field(x,y,z-1,sexf,robust)) * 1000 / 2 1177 let g: i64 = ss_isqrt(gx*gx + gy*gy + gz*gz) 1178 if g < lo { lo = g } 1179 if g > hi { hi = g } 1180 sum = sum + g 1181 n = n + 1 1182 if g < SS_GRAD_BAND_LO { under = under + 1 } 1183 if g > SS_GRAD_BAND_HI { over = over + 1 } 1184 } 1185 z = z + step 1186 } 1187 y = y + step 1188 } 1189 x = x + step 1190 } 1191 if n == 0 { ss_puts("{\x22error\x22:\x22no near-surface samples\x22}\n" as *u8); return 5 } 1192 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22grad\x22,\x22samples\x22:" as *u8); ss_pn(n) 1193 ss_puts(",\x22true_sdf_is\x22:1000,\x22mean\x22:" as *u8); ss_pn(sum/n) 1194 ss_puts(",\x22min\x22:" as *u8); ss_pn(lo) 1195 ss_puts(",\x22max\x22:" as *u8); ss_pn(hi) 1196 ss_puts(",\x22under_800_permil\x22:" as *u8); ss_pn(under*1000/n) 1197 ss_puts(",\x22over_1200_permil\x22:" as *u8); ss_pn(over*1000/n) 1198 ss_puts(",\x22smooth_union_k\x22:" as *u8); ss_pn(ss_k()) 1199 ss_puts("}\n" as *u8) 1200 return 0 1201} 1202 1203// ---- GAP MAP (the `gapmap` verb): WHERE and HOW MUCH we deviate from the scanned oracle ---- 1204// The redistance pass makes OUR field a true SDF; the same sweep machinery run over the ORACLE'S 1205// VERTICES gives the ORACLE'S distance field on the SAME grid. Comparing the two turns "ours is 1206// wrong" into a RANKED PER-REGION WORKLIST (which primitive to fix first, by measured millimetres) 1207// and TWO HEAT MESHES the eye can read: our surface coloured by distance-to-oracle (where our 1208// geometry is wrong) and the oracle's surface coloured by distance-to-ours (what real anatomy we 1209// are MISSING -- sockets, teeth, arches glow). The oracle stays a RULER: nothing here feeds oracle 1210// geometry back into the generator. 1211// ⚠DECLARED BOUND: the oracle field is seeded from VERTICES, not triangles, so it OVERSTATES 1212// distance by at most half the oracle's vertex spacing (~1mm on the 171k-tri skull) -- safe 1213// direction for a gap report, and printed in the JSON. 1214// ***THE RESIDUAL LAYER (operator 2026-08-09: "not until you actually can emit the benchmark skull 1215// can you claim any of this"). The parametric base B is the CONTROLLABLE layer and converges near 1216// ~4.5mm -- blobs cannot carry identity. The industry decomposition is base + DISPLACEMENT: gapmap 1217// already builds B and the ingested input's own SDF O on the same grid, so the ideal correction is 1218// their pointwise difference, downsampled to a lattice and stored as DATA. Emission = B + trilinear(R) 1219// -- the input-derived residual carries identity, the base stays controllable, and a scale knob 1220// slides between the generic parametric skull (0) and the ingested benchmark (1000). R is DERIVED 1221// FROM THE INGESTED INPUT by construction: that IS the match half of the ingest->match->exceed 1222// circle, and it involves no hand-typed number anywhere. 1223const SS_RES_MAGIC: i64 = 0x4e585253 // 'NXRS' 1224const SS_RES_MAXN: i64 = 256 // lattice nodes per axis, upper bound (256^3 x 8 = 134MB; 1225 // raised 128->256 2026-08-10: a 2mm-lattice residual over a 1226 // 1mm grid blurs sub-2mm bone walls into speckle -- MEASURED 1227 // as the ghost-shell emission; identity needs lattice = grid) 1228static SS_RESP: i64 // loaded residual values (Q units) 1229static SS_RESN: i64 // lattice nodes per axis 1230static SS_RESORG: i64 // lattice origin, mm 1231static SS_RESSP: i64 // lattice spacing, mm 1232static SS_RESSC: i64 // application scale, permil 1233// load a residual file: [magic n org sp q] then n^3 i64 values; complete-or-nothing 1234func ss_res_load(path: *u8) -> i64 { 1235 let ln: *i64 = sys_mmap(16) as *i64 1236 let buf: *u8 = sys_read_file(path, ln) 1237 if (buf as i64) == 0 { return 0 } 1238 let hdr: *i64 = buf as *i64 1239 if hdr[0] != SS_RES_MAGIC { return 0 } 1240 let n: i64 = hdr[1] 1241 if n < 2 { return 0 } 1242 if n > SS_RES_MAXN { return 0 } 1243 if ln[0] < 40 + n*n*n*8 { return 0 } 1244 SS_RESN = n 1245 SS_RESORG = hdr[2] 1246 SS_RESSP = hdr[3] 1247 SS_RESP = (buf as i64) + 40 1248 return 1 1249} 1250// trilinear sample of the residual at a world-mm point, in Q units; zero outside the lattice 1251func ss_res_at(x: i64, y: i64, z: i64) -> i64 { 1252 if SS_RESP == 0 { return 0 } 1253 let R: *i64 = SS_RESP as *i64 1254 let n: i64 = SS_RESN 1255 let sp: i64 = SS_RESSP 1256 var ux: i64 = x - SS_RESORG 1257 var uy: i64 = y - SS_RESORG 1258 var uz: i64 = z - SS_RESORG 1259 if ux < 0 { return 0 } 1260 if uy < 0 { return 0 } 1261 if uz < 0 { return 0 } 1262 var i0: i64 = ux/sp 1263 var j0: i64 = uy/sp 1264 var k0: i64 = uz/sp 1265 if i0 >= n-1 { return 0 } 1266 if j0 >= n-1 { return 0 } 1267 if k0 >= n-1 { return 0 } 1268 let fx: i64 = (ux - i0*sp)*SS_LERP_ONE/sp 1269 let fy: i64 = (uy - j0*sp)*SS_LERP_ONE/sp 1270 let fz: i64 = (uz - k0*sp)*SS_LERP_ONE/sp 1271 let c000: i64 = R[(i0*n+j0)*n+k0] 1272 let c100: i64 = R[((i0+1)*n+j0)*n+k0] 1273 let c010: i64 = R[(i0*n+(j0+1))*n+k0] 1274 let c110: i64 = R[((i0+1)*n+(j0+1))*n+k0] 1275 let c001: i64 = R[(i0*n+j0)*n+(k0+1)] 1276 let c101: i64 = R[((i0+1)*n+j0)*n+(k0+1)] 1277 let c011: i64 = R[(i0*n+(j0+1))*n+(k0+1)] 1278 let c111: i64 = R[((i0+1)*n+(j0+1))*n+(k0+1)] 1279 let x00: i64 = c000 + (c100-c000)*fx/SS_LERP_ONE 1280 let x10: i64 = c010 + (c110-c010)*fx/SS_LERP_ONE 1281 let x01: i64 = c001 + (c101-c001)*fx/SS_LERP_ONE 1282 let x11: i64 = c011 + (c111-c011)*fx/SS_LERP_ONE 1283 let y0: i64 = x00 + (x10-x00)*fy/SS_LERP_ONE 1284 let y1: i64 = x01 + (x11-x01)*fy/SS_LERP_ONE 1285 return y0 + (y1-y0)*fz/SS_LERP_ONE 1286} 1287// ***THE ORACLE FIELD, DONE RIGHT (2026-08-10, operator: "nothing still looks close to a skull do 1288// you actually know what you are doing"). Honest answer: the vertex-cloud + flood + normal-heuristic 1289// construction of O was improvised through every classic mesh-to-SDF pitfall in sequence (beads, 1290// leaks, dead signs). The robust textbook construction, which the redistance pass ALREADY uses for 1291// OUR field, is: exact SURFACE CROSSINGS + PARITY. Intersect each grid column (x-ray at fixed y,z) 1292// with the actual TRIANGLES: a 2D point-in-triangle test in (y,z) selects hits, barycentric 1293// interpolation gives the exact crossing x in Q units, the two flanking nodes seed with exact 1294// distances, and CROSSING PARITY gives inside/outside -- no normals, no flood, no beads possible. 1295// The control verb `voxref` emits surface_nets(O) ALONE so the render answers one question first: 1296// is O the skull? 1297// ***NO CAPACITY CONSTANTS (rule 11, operator 2026-08-10: "stop doing these magic number bullshit 1298// things"). Bucket granularity = the GRID CELL (derived, not chosen); insertion storage is sized by a 1299// COUNTING pass, so there is no cap to hit and nothing to silently drop; the per-column hit buffer is 1300// sized by the longest measured bucket. Every bound is the population's own, computed per run. 1301// counting pass: how many (triangle, bucket-cell) insertions will the build make? 1302func ss_vb_count(rbuf: *u8, rhdr: i64, rnt: i64, cy: i64, cz: i64, ocy: i64, ocz: i64, 1303 org: i64, nb: i64, bcell: i64) -> i64 { 1304 var ins: i64 = 0 1305 var t: i64 = 0 1306 while t < rnt { 1307 let o: i64 = rhdr + t*84 1308 var loy: i64 = 0 1309 var hiy: i64 = 0 1310 var loz: i64 = 0 1311 var hiz: i64 = 0 1312 var vj: i64 = 0 1313 while vj < 3 { 1314 let wy: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+8), 1) - cz + ocy 1315 let wz: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+vj*12+4), 1) - cy) + ocz 1316 if vj == 0 { loy=wy; hiy=wy; loz=wz; hiz=wz } else { 1317 if wy<loy {loy=wy} 1318 if wy>hiy {hiy=wy} 1319 if wz<loz {loz=wz} 1320 if wz>hiz {hiz=wz} 1321 } 1322 vj = vj + 1 1323 } 1324 var bj: i64 = (loy - org)/bcell 1325 let bj1: i64 = (hiy - org)/bcell 1326 while bj <= bj1 { 1327 if bj >= 0 { if bj < nb { 1328 var bk: i64 = (loz - org)/bcell 1329 let bk1: i64 = (hiz - org)/bcell 1330 while bk <= bk1 { 1331 if bk >= 0 { if bk < nb { ins = ins + 1 } } 1332 bk = bk + 1 1333 } 1334 } } 1335 bj = bj + 1 1336 } 1337 t = t + 1 1338 } 1339 return ins 1340} 1341// fill pass: identical walk; capacity is the counting pass's own number, so overflow is impossible 1342func ss_vb_build(rbuf: *u8, rhdr: i64, rnt: i64, cx: i64, cy: i64, cz: i64, ocx: i64, ocy: i64, ocz: i64, 1343 org: i64, nb: i64, bcell: i64, head: *i64, nxt: *i64, tref: *i64, cap: i64) -> i64 { 1344 var c: i64 = 0 1345 while c < nb*nb { head[c] = 0-1; c = c + 1 } 1346 var ins: i64 = 0 1347 var t: i64 = 0 1348 while t < rnt { 1349 let o: i64 = rhdr + t*84 1350 var loy: i64 = 0 1351 var hiy: i64 = 0 1352 var loz: i64 = 0 1353 var hiz: i64 = 0 1354 var vj: i64 = 0 1355 while vj < 3 { 1356 let wy: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+8), 1) - cz + ocy 1357 let wz: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+vj*12+4), 1) - cy) + ocz 1358 if vj == 0 { loy=wy; hiy=wy; loz=wz; hiz=wz } else { 1359 if wy<loy {loy=wy} 1360 if wy>hiy {hiy=wy} 1361 if wz<loz {loz=wz} 1362 if wz>hiz {hiz=wz} 1363 } 1364 vj = vj + 1 1365 } 1366 var bj: i64 = (loy - org)/bcell 1367 let bj1: i64 = (hiy - org)/bcell 1368 while bj <= bj1 { 1369 if bj >= 0 { if bj < nb { 1370 var bk: i64 = (loz - org)/bcell 1371 let bk1: i64 = (hiz - org)/bcell 1372 while bk <= bk1 { 1373 if bk >= 0 { if bk < nb { 1374 if ins < cap { 1375 tref[ins] = t 1376 nxt[ins] = head[bj*nb+bk] 1377 head[bj*nb+bk] = ins 1378 ins = ins + 1 1379 } 1380 } } 1381 bk = bk + 1 1382 } 1383 } } 1384 bj = bj + 1 1385 } 1386 t = t + 1 1387 } 1388 return ins 1389} 1390func ss_gap_region(x: i64, y: i64, z: i64) -> i64 { 1391 // coarse NAMED boxes in the field's own authored frame (mm, +y up, +z face); priority order. 1392 // THE NASAL BOX IS DERIVED FROM THE FIELD'S OWN NASAL PRIMITIVES (AN17, 2026-09-18): the typed box below (|x|<20, 1393 // z>=55, -15<=y<30) read n_ours=0 n_oracle=0 on every trend row since 2026-08-14 -- it was authored for the default 1394 // nasal station (y 8, z 76) while the tuned station had drifted (y -28, z 34), and the oracle's nose, read supine, 1395 // was never where any box expected it. The region is now wherever the nasal-bone ellipsoid and the piriform capsule 1396 // stand in the CURRENT vector: y from the aperture's lowest rim to the top of the nasal bones, |x| within the wider 1397 // of the two radii, z no further back than the nasal ellipsoid's back face. It moves with the tune. 1398 let P: *i64 = ss_pdef() 1399 var ax: i64 = x 1400 if ax < 0 { ax = 0-ax } 1401 if y < 0-55 { return 5 } 1402 var nxr: i64 = P[P_NRX] 1403 if P[P_PAW]/2 > nxr { nxr = P[P_PAW]/2 } 1404 // the aperture hangs from the rhinion (the plate's lower edge), so its lowest rim is one aperture height below it 1405 let nylo: i64 = P[P_NY] - P[P_NRY]*sp_icos(P[P_NTILT])/SS_PERMILLE - P[P_PAH] 1406 let nyhi: i64 = P[P_NY] + P[P_NRY] 1407 let nzlo: i64 = P[P_NZ] - P[P_NRY] 1408 if ax <= nxr { if z >= nzlo { if y >= nylo { if y <= nyhi { return 3 } } } } 1409 if ax < 20 { if z >= 55 { if y >= 0-15 { if y < 30 { return 3 } } } } 1410 if ax < 45 { if z >= 25 { if y >= 5 { if y < 40 { return 2 } } } } 1411 if ax >= 42 { if y >= 0-10 { if y < 25 { if z >= 0-35 { return 4 } } } } 1412 if y >= 0-55 { if y < 0-20 { if z >= 25 { return 6 } } } 1413 if y >= 18 { return 0 } 1414 return 1 1415} 1416func ss_gap_regname(i: i64) -> i64 { 1417 if i == 0 { ss_puts("vault" as *u8); return 0 } 1418 if i == 1 { ss_puts("base_other" as *u8); return 0 } 1419 if i == 2 { ss_puts("brow_orbits" as *u8); return 0 } 1420 if i == 3 { ss_puts("nasal" as *u8); return 0 } 1421 if i == 4 { ss_puts("zygomatic" as *u8); return 0 } 1422 if i == 5 { ss_puts("mandible" as *u8); return 0 } 1423 ss_puts("maxilla" as *u8) 1424 return 0 1425} 1426// heat ramp: green 0mm -> yellow 3mm -> red 8mm+, written as the tri's 3 colour floats 1427func ss_gap_wrcol(b: *u8, o: i64, gq: i64) -> i64 { 1428 let g3: i64 = 3*SS_RDQ 1429 let g8: i64 = 8*SS_RDQ 1430 var r: i64 = 0 1431 var g: i64 = 750 1432 var bl: i64 = 250 1433 if gq <= g3 { 1434 r = 200 + 650*gq/g3 1435 } else { 1436 var t: i64 = (gq-g3)*1000/(g8-g3) 1437 if t > 1000 { t = 1000 } 1438 r = 850 + 50*t/SS_PERMILLE 1439 g = 750 - 500*t/SS_PERMILLE 1440 bl = 250 - 50*t/SS_PERMILLE 1441 } 1442 ss_wr32(b, o, ss_f32(r,1000)) 1443 ss_wr32(b, o+4, ss_f32(g,1000)) 1444 ss_wr32(b, o+8, ss_f32(bl,1000)) 1445 return 0 1446} 1447// nearest grid node index for a world-mm point; wx-org >= 0 always (org is the negative bound) 1448func ss_gap_node(w: i64, org: i64, cell: i64, n1: i64) -> i64 { 1449 var i: i64 = (w - org + cell/2)/cell 1450 if i < 0 { i = 0 } 1451 if i > n1-1 { i = n1-1 } 1452 return i 1453} 1454// write one NXMSH2 header + layer table (single "bone" layer covering nt tris) 1455func ss_gap_wrhdr(buf: *u8, nt: i64) -> i64 { 1456 buf[0]=78 as u8; buf[1]=88 as u8; buf[2]=77 as u8; buf[3]=83 as u8 1457 buf[4]=72 as u8; buf[5]=50 as u8; buf[6]=0 as u8; buf[7]=0 as u8 1458 ss_wr32(buf, 8, 3) 1459 ss_wr32(buf, 12, nt) 1460 var L: i64 = 0 1461 while L < 3 { 1462 let lb: i64 = 16 + L*24 1463 var q: i64 = 0 1464 while q < 16 { buf[lb+q]=0 as u8; q=q+1 } 1465 if L==2 { buf[lb]=98 as u8; buf[lb+1]=111 as u8; buf[lb+2]=110 as u8; buf[lb+3]=101 as u8 } 1466 if L==2 { ss_wr32(buf, lb+16, 0); ss_wr32(buf, lb+20, nt) } else { ss_wr32(buf, lb+16, 0); ss_wr32(buf, lb+20, 0) } 1467 L = L + 1 1468 } 1469 return 0 1470} 1471func ss_gapmap(ref: *u8, oursout: *u8, oraout: *u8, sexf: i64, robust: i64, cum: i64, resout: *u8, latmm: i64) -> i64 { 1472 var G: i64 = (SS_EXT*2*1000 + cum - 1)/cum 1473 if G > SS_EXT*2 { G = SS_EXT*2 } 1474 let cell: i64 = (SS_EXT*2 + G - 1)/G 1475 let org: i64 = 0 - (G*cell)/2 1476 let n1: i64 = G+1 1477 if mf_admit("nx_skullsdf gapmap grids" as *u8, n1*n1*n1*8*3) == 0 { return 8 } 1478 let grid: *i64 = sys_mmap(n1*n1*n1*8) as *i64 1479 let dist: *i64 = sys_mmap(n1*n1*n1*8) as *i64 1480 let odist: *i64 = sys_mmap(n1*n1*n1*8) as *i64 1481 let hq: i64 = cell*SS_RDQ 1482 // ---- OUR true SDF (fill raw, seed, sweep, sign -- the proven redistance recipe) ---- 1483 var i: i64 = 0 1484 while i < n1 { 1485 let x: i64 = org + i*cell 1486 var j: i64 = 0 1487 while j < n1 { 1488 let y: i64 = org + j*cell 1489 var k: i64 = 0 1490 while k < n1 { 1491 let z: i64 = org + k*cell 1492 grid[(i*n1+j)*n1+k] = ss_field_world(x, y, z, sexf, robust) 1493 k = k + 1 1494 } 1495 j = j + 1 1496 } 1497 i = i + 1 1498 } 1499 var si: i64 = 0 1500 while si < n1 { 1501 var sj: i64 = 0 1502 while sj < n1 { 1503 var sk: i64 = 0 1504 while sk < n1 { 1505 let ix: i64 = (si*n1+sj)*n1+sk 1506 let f: i64 = grid[ix] 1507 var best: i64 = SS_RD_INF 1508 if si > 0 { best = ss_rd_try(f, grid[((si-1)*n1+sj)*n1+sk], cell, best) } 1509 if si < n1-1 { best = ss_rd_try(f, grid[((si+1)*n1+sj)*n1+sk], cell, best) } 1510 if sj > 0 { best = ss_rd_try(f, grid[(si*n1+(sj-1))*n1+sk], cell, best) } 1511 if sj < n1-1 { best = ss_rd_try(f, grid[(si*n1+(sj+1))*n1+sk], cell, best) } 1512 if sk > 0 { best = ss_rd_try(f, grid[(si*n1+sj)*n1+(sk-1)], cell, best) } 1513 if sk < n1-1 { best = ss_rd_try(f, grid[(si*n1+sj)*n1+(sk+1)], cell, best) } 1514 dist[ix] = best 1515 sk = sk + 1 1516 } 1517 sj = sj + 1 1518 } 1519 si = si + 1 1520 } 1521 var it: i64 = 0 1522 while it < 2 { 1523 var sw: i64 = 0 1524 while sw < 8 { 1525 var di: i64 = 1 1526 if (sw & 1) == 1 { di = 0-1 } 1527 var dj: i64 = 1 1528 if ((sw>>1) & 1) == 1 { dj = 0-1 } 1529 var dk: i64 = 1 1530 if ((sw>>2) & 1) == 1 { dk = 0-1 } 1531 let sd0: i64 = ss_rd_sweep(dist, n1, hq, di, dj, dk) 1532 sw = sw + 1 1533 } 1534 it = it + 1 1535 } 1536 // ---- OUR surface's own bbox centre, then sign restore ---- 1537 // The oracle below is centred by ITS bbox; without centring OURS the same way, the authored 1538 // frame's off-centre z biases every gap (first run: nasal read 25mm with n_oracle=0 from 1539 // exactly this). And surface_nets needs the SIGNED field -- polygonizing the unsigned one 1540 // emits a doubled shell (first run: 177,120 tris where the skull has 97,660). 1541 var obx0: i64 = 0; var obx1: i64 = 0 1542 var oby0: i64 = 0; var oby1: i64 = 0 1543 var obz0: i64 = 0; var obz1: i64 = 0 1544 var obfirst: i64 = 1 1545 var bi2: i64 = 0 1546 while bi2 < n1 { 1547 var bj2: i64 = 0 1548 while bj2 < n1 { 1549 var bk2: i64 = 0 1550 while bk2 < n1 { 1551 var ad2: i64 = dist[(bi2*n1+bj2)*n1+bk2] 1552 if ad2 < 0 { ad2 = 0-ad2 } 1553 if ad2 <= hq { 1554 let wx2: i64 = org + bi2*cell 1555 let wy2: i64 = org + bj2*cell 1556 let wz2: i64 = org + bk2*cell 1557 if obfirst == 1 { obx0=wx2; obx1=wx2; oby0=wy2; oby1=wy2; obz0=wz2; obz1=wz2; obfirst=0 } else { 1558 if wx2<obx0 {obx0=wx2} 1559 if wx2>obx1 {obx1=wx2} 1560 if wy2<oby0 {oby0=wy2} 1561 if wy2>oby1 {oby1=wy2} 1562 if wz2<obz0 {obz0=wz2} 1563 if wz2>obz1 {obz1=wz2} 1564 } 1565 } 1566 bk2 = bk2 + 1 1567 } 1568 bj2 = bj2 + 1 1569 } 1570 bi2 = bi2 + 1 1571 } 1572 let ocx: i64 = (obx0+obx1)/2 1573 let ocy: i64 = (oby0+oby1)/2 1574 let ocz: i64 = (obz0+obz1)/2 1575 var sgi: i64 = 0 1576 while sgi < n1*n1*n1 { 1577 if grid[sgi] <= 0 { dist[sgi] = 0 - dist[sgi] } 1578 sgi = sgi + 1 1579 } 1580 // ---- ORACLE distance field on the SAME grid, seeded from its vertices ---- 1581 let ln: *i64 = sys_mmap(16) as *i64 1582 let rbuf: *u8 = sys_read_file(ref, ln) 1583 if (rbuf as i64) == 0 { ss_puts("{\x22error\x22:\x22cannot read reference\x22}\n" as *u8); return 3 } 1584 let rlayer: i64 = ss_rd32(rbuf, 8) 1585 let rnt: i64 = ss_rd32(rbuf, 12) 1586 let rhdr: i64 = 16 + rlayer*24 1587 if rnt <= 0 { ss_puts("{\x22error\x22:\x22no reference triangles\x22}\n" as *u8); return 4 } 1588 var lox: i64 = 0; var hix: i64 = 0 1589 var loy: i64 = 0; var hiy: i64 = 0 1590 var loz: i64 = 0; var hiz: i64 = 0 1591 var first: i64 = 1 1592 var t: i64 = 0 1593 while t < rnt { 1594 let o: i64 = rhdr + t*84 1595 var vj: i64 = 0 1596 while vj < 3 { 1597 let x: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12), 1) 1598 let y: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+4), 1) 1599 let z: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+8), 1) 1600 if first == 1 { lox=x; hix=x; loy=y; hiy=y; loz=z; hiz=z; first=0 } else { 1601 if x<lox {lox=x} 1602 if x>hix {hix=x} 1603 if y<loy {loy=y} 1604 if y>hiy {hiy=y} 1605 if z<loz {loz=z} 1606 if z>hiz {hiz=z} 1607 } 1608 vj = vj + 1 1609 } 1610 t = t + 1 1611 } 1612 let cx: i64 = (lox+hix)/2 1613 let cy: i64 = (loy+hiy)/2 1614 let cz: i64 = (loz+hiz)/2 1615 // ***SEEDS CARRY THE SIGN OF THE ORACLE'S OWN VERTEX NORMALS. The first version signed the whole 1616 // near-band negative (flood barrier), and a point-cloud distance field touches zero AT every seed 1617 // -- surface_nets then emitted ONE BEAD PER ORACLE VERTEX (measured: ~380K verts ~ the 171K-vertex 1618 // benchmark, rendered as skull-shaped filigree). A node signed by the side of the surface its 1619 // seeding vertex's normal says it is on crosses zero ONCE. 1620 if mf_admit("nx_skullsdf gapmap seed-signs" as *u8, n1*n1*n1) == 0 { return 8 } 1621 let osgn: *u8 = sys_mmap(n1*n1*n1) 1622 var oi: i64 = 0 1623 while oi < n1*n1*n1 { odist[oi] = SS_RD_INF; osgn[oi] = 0 as u8; oi = oi + 1 } 1624 t = 0 1625 while t < rnt { 1626 let o: i64 = rhdr + t*84 1627 var vj: i64 = 0 1628 while vj < 3 { 1629 let wx: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12), 1) - cx + ocx 1630 let wy: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+8), 1) - cz + ocy 1631 let wz: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+vj*12+4), 1) - cy) + ocz 1632 let nvx: i64 = ss_r_f32(ss_rd32(rbuf,o+36+vj*12), 1000) 1633 let nvy: i64 = ss_r_f32(ss_rd32(rbuf,o+36+vj*12+8), 1000) 1634 let nvz: i64 = 0 - ss_r_f32(ss_rd32(rbuf,o+36+vj*12+4), 1000) 1635 let ni: i64 = ss_gap_node(wx, org, cell, n1) 1636 let nj: i64 = ss_gap_node(wy, org, cell, n1) 1637 let nk: i64 = ss_gap_node(wz, org, cell, n1) 1638 let dxq: i64 = (wx - (org + ni*cell))*SS_RDQ 1639 let dyq: i64 = (wy - (org + nj*cell))*SS_RDQ 1640 let dzq: i64 = (wz - (org + nk*cell))*SS_RDQ 1641 let dq: i64 = ss_isqrt(dxq*dxq + dyq*dyq + dzq*dzq) 1642 let nix: i64 = (ni*n1+nj)*n1+nk 1643 if dq < odist[nix] { 1644 odist[nix] = dq 1645 // node minus vertex, dotted with the outward normal: positive = outside 1646 let dt: i64 = (0-dxq)*nvx + (0-dyq)*nvy + (0-dzq)*nvz 1647 if dt >= 0 { osgn[nix] = 1 as u8 } else { osgn[nix] = 2 as u8 } 1648 } 1649 // ***SEED THE SIX NEIGHBOURS TOO, SIGNED. MEASURED MOTIVE: the benchmark's vertices are 1650 // INTEGER MILLIMETRES, so at cell=1 they land EXACTLY on nodes -- offset zero, sign moot 1651 // (+-0 is 0: the counters read 47,529 outside / 0 inside and both residuals hashed 1652 // identical), and an isolated zero-node beads by construction. A signed +-cell seed on 1653 // each neighbour puts the crossing THROUGH the vertex node instead of islanding it. 1654 var nbi: i64 = 0 1655 while nbi < 6 { 1656 var oi2: i64 = 0 1657 var oj2: i64 = 0 1658 var ok2: i64 = 0 1659 if nbi == 0 { oi2 = 1 } 1660 if nbi == 1 { oi2 = 0-1 } 1661 if nbi == 2 { oj2 = 1 } 1662 if nbi == 3 { oj2 = 0-1 } 1663 if nbi == 4 { ok2 = 1 } 1664 if nbi == 5 { ok2 = 0-1 } 1665 let mi: i64 = ni + oi2 1666 let mj: i64 = nj + oj2 1667 let mk3: i64 = nk + ok2 1668 var inr: i64 = 1 1669 if mi < 0 { inr = 0 } 1670 if mi > n1-1 { inr = 0 } 1671 if mj < 0 { inr = 0 } 1672 if mj > n1-1 { inr = 0 } 1673 if mk3 < 0 { inr = 0 } 1674 if mk3 > n1-1 { inr = 0 } 1675 if inr == 1 { 1676 let vxq: i64 = (org + mi*cell - wx)*SS_RDQ 1677 let vyq: i64 = (org + mj*cell - wy)*SS_RDQ 1678 let vzq: i64 = (org + mk3*cell - wz)*SS_RDQ 1679 let nd2: i64 = ss_isqrt(vxq*vxq + vyq*vyq + vzq*vzq) 1680 let mix: i64 = (mi*n1+mj)*n1+mk3 1681 if nd2 < odist[mix] { 1682 odist[mix] = nd2 1683 let dt2: i64 = vxq*nvx + vyq*nvy + vzq*nvz 1684 if dt2 >= 0 { osgn[mix] = 1 as u8 } else { osgn[mix] = 2 as u8 } 1685 } 1686 } 1687 nbi = nbi + 1 1688 } 1689 vj = vj + 1 1690 } 1691 t = t + 1 1692 } 1693 // instrument the sign seeding itself: a fix whose counters read zero is dead code, not a fix 1694 var sgn_out: i64 = 0 1695 var sgn_in: i64 = 0 1696 var sgi2: i64 = 0 1697 while sgi2 < n1*n1*n1 { 1698 if osgn[sgi2] == (1 as u8) { sgn_out = sgn_out + 1 } 1699 if osgn[sgi2] == (2 as u8) { sgn_in = sgn_in + 1 } 1700 sgi2 = sgi2 + 1 1701 } 1702 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22seedsign\x22,\x22outside\x22:" as *u8); ss_pn(sgn_out) 1703 ss_puts(",\x22inside\x22:" as *u8); ss_pn(sgn_in) 1704 ss_puts("}\n" as *u8) 1705 it = 0 1706 while it < 2 { 1707 var sw2: i64 = 0 1708 while sw2 < 8 { 1709 var di2: i64 = 1 1710 if (sw2 & 1) == 1 { di2 = 0-1 } 1711 var dj2: i64 = 1 1712 if ((sw2>>1) & 1) == 1 { dj2 = 0-1 } 1713 var dk2: i64 = 1 1714 if ((sw2>>2) & 1) == 1 { dk2 = 0-1 } 1715 let sd1: i64 = ss_rd_sweep(odist, n1, hq, di2, dj2, dk2) 1716 sw2 = sw2 + 1 1717 } 1718 it = it + 1 1719 } 1720 // ---- per-region two-sided tallies over both near-bands ---- 1721 let fsum: *i64 = sys_mmap(SS_GR_N*8) as *i64 1722 let fmax: *i64 = sys_mmap(SS_GR_N*8) as *i64 1723 let fn: *i64 = sys_mmap(SS_GR_N*8) as *i64 1724 let rsum: *i64 = sys_mmap(SS_GR_N*8) as *i64 1725 let rmax: *i64 = sys_mmap(SS_GR_N*8) as *i64 1726 let rn: *i64 = sys_mmap(SS_GR_N*8) as *i64 1727 var gi: i64 = 0 1728 while gi < SS_GR_N { fsum[gi]=0; fmax[gi]=0; fn[gi]=0; rsum[gi]=0; rmax[gi]=0; rn[gi]=0; gi=gi+1 } 1729 var pi: i64 = 0 1730 while pi < n1 { 1731 let px: i64 = org + pi*cell 1732 var pj: i64 = 0 1733 while pj < n1 { 1734 let py: i64 = org + pj*cell 1735 var pk: i64 = 0 1736 while pk < n1 { 1737 let pz: i64 = org + pk*cell 1738 let ix2: i64 = (pi*n1+pj)*n1+pk 1739 var ao: i64 = dist[ix2] 1740 if ao < 0 { ao = 0-ao } 1741 let r: i64 = ss_gap_region(px, py, pz) 1742 if ao <= hq { 1743 let gv: i64 = odist[ix2] 1744 fsum[r] = fsum[r] + gv 1745 if gv > fmax[r] { fmax[r] = gv } 1746 fn[r] = fn[r] + 1 1747 } 1748 if odist[ix2] <= hq { 1749 rsum[r] = rsum[r] + ao 1750 if ao > rmax[r] { rmax[r] = ao } 1751 rn[r] = rn[r] + 1 1752 } 1753 pk = pk + 1 1754 } 1755 pj = pj + 1 1756 } 1757 pi = pi + 1 1758 } 1759 // ---- heat mesh 1: OUR surface coloured by distance-to-oracle ---- 1760 tm_reset() 1761 surface_nets(dist, G, G, G, org, org, org, cell, SS_ISO, SS_BONE) 1762 let nt1: i64 = tm_nt() 1763 if nt1 > 0 { 1764 let h1: i64 = 16 + 3*24 1765 let by1: i64 = h1 + nt1*84 + nt1*4 1766 let b1: *u8 = sys_mmap(by1 + 64) 1767 ss_gap_wrhdr(b1, nt1) 1768 var t1: i64 = 0 1769 while t1 < nt1 { 1770 let o: i64 = h1 + t1*84 1771 let ia: i64 = tm_ta(t1); let ib: i64 = tm_tb(t1); let ic: i64 = tm_tc(t1) 1772 ss_wr32(b1, o, ss_f32(tm_vx(ia),1)); ss_wr32(b1, o+4, ss_f32(tm_vy(ia),1)); ss_wr32(b1, o+8, ss_f32(tm_vz(ia),1)) 1773 ss_wr32(b1, o+12, ss_f32(tm_vx(ib),1)); ss_wr32(b1, o+16, ss_f32(tm_vy(ib),1)); ss_wr32(b1, o+20, ss_f32(tm_vz(ib),1)) 1774 ss_wr32(b1, o+24, ss_f32(tm_vx(ic),1)); ss_wr32(b1, o+28, ss_f32(tm_vy(ic),1)); ss_wr32(b1, o+32, ss_f32(tm_vz(ic),1)) 1775 ss_wr32(b1, o+36, ss_f32(tm_vnx(ia),SS_NQ)); ss_wr32(b1, o+40, ss_f32(tm_vny(ia),SS_NQ)); ss_wr32(b1, o+44, ss_f32(tm_vnz(ia),SS_NQ)) 1776 ss_wr32(b1, o+48, ss_f32(tm_vnx(ib),SS_NQ)); ss_wr32(b1, o+52, ss_f32(tm_vny(ib),SS_NQ)); ss_wr32(b1, o+56, ss_f32(tm_vnz(ib),SS_NQ)) 1777 ss_wr32(b1, o+60, ss_f32(tm_vnx(ic),SS_NQ)); ss_wr32(b1, o+64, ss_f32(tm_vny(ic),SS_NQ)); ss_wr32(b1, o+68, ss_f32(tm_vnz(ic),SS_NQ)) 1778 let mx: i64 = (tm_vx(ia)+tm_vx(ib)+tm_vx(ic))/3 1779 let my: i64 = (tm_vy(ia)+tm_vy(ib)+tm_vy(ic))/3 1780 let mz: i64 = (tm_vz(ia)+tm_vz(ib)+tm_vz(ic))/3 1781 let hi1: i64 = ss_gap_node(mx, org, cell, n1) 1782 let hj1: i64 = ss_gap_node(my, org, cell, n1) 1783 let hk1: i64 = ss_gap_node(mz, org, cell, n1) 1784 ss_gap_wrcol(b1, o+72, odist[(hi1*n1+hj1)*n1+hk1]) 1785 ss_wr32(b1, h1 + nt1*84 + t1*4, 2) 1786 t1 = t1 + 1 1787 } 1788 let fd1: i64 = sys_openat_wr(oursout, 420) 1789 sys_write(fd1, b1, by1) 1790 sys_close(fd1) 1791 } 1792 // ---- heat mesh 2: ORACLE surface coloured by distance-to-ours (what we are MISSING) ---- 1793 let h2: i64 = 16 + 3*24 1794 let by2: i64 = h2 + rnt*84 + rnt*4 1795 let b2: *u8 = sys_mmap(by2 + 64) 1796 ss_gap_wrhdr(b2, rnt) 1797 t = 0 1798 while t < rnt { 1799 let so: i64 = rhdr + t*84 1800 let dsto: i64 = h2 + t*84 1801 var vj: i64 = 0 1802 var mx2: i64 = 0 1803 var my2: i64 = 0 1804 var mz2: i64 = 0 1805 while vj < 3 { 1806 let wx: i64 = ss_r_f32(ss_rd32(rbuf,so+vj*12), 1) - cx + ocx 1807 let wy: i64 = ss_r_f32(ss_rd32(rbuf,so+vj*12+8), 1) - cz + ocy 1808 let wz: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,so+vj*12+4), 1) - cy) + ocz 1809 ss_wr32(b2, dsto+vj*12, ss_f32(wx,1)) 1810 ss_wr32(b2, dsto+vj*12+4, ss_f32(wy,1)) 1811 ss_wr32(b2, dsto+vj*12+8, ss_f32(wz,1)) 1812 // normals: copy with z negated (decode at mille scale, re-encode negated -- no new 1813 // bit-twiddling operator, and a unit normal loses nothing at 1/SS_PERMILLE resolution) 1814 // normals through the same quarter turn: authored ny = file nz, authored nz = -file ny 1815 ss_wr32(b2, dsto+36+vj*12, ss_rd32(rbuf, so+36+vj*12)) 1816 ss_wr32(b2, dsto+36+vj*12+4, ss_rd32(rbuf, so+36+vj*12+8)) 1817 let nzv: i64 = ss_r_f32(ss_rd32(rbuf, so+36+vj*12+4), 1000) 1818 ss_wr32(b2, dsto+36+vj*12+8, ss_f32(0-nzv, 1000)) 1819 mx2 = mx2 + wx 1820 my2 = my2 + wy 1821 mz2 = mz2 + wz 1822 vj = vj + 1 1823 } 1824 mx2 = mx2/3 1825 my2 = my2/3 1826 mz2 = mz2/3 1827 let hi2: i64 = ss_gap_node(mx2, org, cell, n1) 1828 let hj2: i64 = ss_gap_node(my2, org, cell, n1) 1829 let hk2: i64 = ss_gap_node(mz2, org, cell, n1) 1830 var av: i64 = dist[(hi2*n1+hj2)*n1+hk2] 1831 if av < 0 { av = 0-av } 1832 ss_gap_wrcol(b2, dsto+72, av) 1833 ss_wr32(b2, h2 + rnt*84 + t*4, 2) 1834 t = t + 1 1835 } 1836 let fd2: i64 = sys_openat_wr(oraout, 420) 1837 sys_write(fd2, b2, by2) 1838 sys_close(fd2) 1839 // ---- optional RESIDUAL LAYER: R = O_signed - B at lattice nodes, written as DATA ---- 1840 if (resout as i64) != 0 { 1841 // sign the oracle field by flooding OUTSIDE-ness from the box boundary; the near-surface 1842 // band is the barrier. Enclosed cavities (sinuses) stay INSIDE, which is correct anatomy. 1843 if mf_admit("nx_skullsdf gapmap oracle-sign" as *u8, n1*n1*n1*8) == 0 { return 8 } 1844 let mk: *i64 = sys_mmap(n1*n1*n1*8) as *i64 1845 let thr: i64 = hq 1846 var fi: i64 = 0 1847 while fi < n1 { 1848 var fj: i64 = 0 1849 while fj < n1 { 1850 var fk: i64 = 0 1851 while fk < n1 { 1852 let ixf: i64 = (fi*n1+fj)*n1+fk 1853 mk[ixf] = 0 1854 var onb: i64 = 0 1855 if fi == 0 { onb = 1 } 1856 if fi == n1-1 { onb = 1 } 1857 if fj == 0 { onb = 1 } 1858 if fj == n1-1 { onb = 1 } 1859 if fk == 0 { onb = 1 } 1860 if fk == n1-1 { onb = 1 } 1861 if onb == 1 { if odist[ixf] > thr { mk[ixf] = 1 } } 1862 fk = fk + 1 1863 } 1864 fj = fj + 1 1865 } 1866 fi = fi + 1 1867 } 1868 var chg: i64 = 1 1869 var itc: i64 = 0 1870 while chg == 1 { 1871 if itc >= 8 { chg = 0 } else { 1872 chg = 0 1873 var pi2: i64 = 0 1874 while pi2 < n1 { 1875 var pj2: i64 = 0 1876 while pj2 < n1 { 1877 var pk2: i64 = 0 1878 while pk2 < n1 { 1879 let ixp: i64 = (pi2*n1+pj2)*n1+pk2 1880 if mk[ixp] == 0 { if odist[ixp] > thr { 1881 var nb: i64 = 0 1882 if pi2 > 0 { if mk[((pi2-1)*n1+pj2)*n1+pk2] == 1 { nb = 1 } } 1883 if pi2 < n1-1 { if mk[((pi2+1)*n1+pj2)*n1+pk2] == 1 { nb = 1 } } 1884 if pj2 > 0 { if mk[(pi2*n1+(pj2-1))*n1+pk2] == 1 { nb = 1 } } 1885 if pj2 < n1-1 { if mk[(pi2*n1+(pj2+1))*n1+pk2] == 1 { nb = 1 } } 1886 if pk2 > 0 { if mk[(pi2*n1+pj2)*n1+(pk2-1)] == 1 { nb = 1 } } 1887 if pk2 < n1-1 { if mk[(pi2*n1+pj2)*n1+(pk2+1)] == 1 { nb = 1 } } 1888 if nb == 1 { mk[ixp] = 1; chg = 1 } 1889 } } 1890 pk2 = pk2 + 1 1891 } 1892 pj2 = pj2 + 1 1893 } 1894 pi2 = pi2 + 1 1895 } 1896 var qi2: i64 = n1-1 1897 while qi2 >= 0 { 1898 var qj2: i64 = n1-1 1899 while qj2 >= 0 { 1900 var qk2: i64 = n1-1 1901 while qk2 >= 0 { 1902 let ixq: i64 = (qi2*n1+qj2)*n1+qk2 1903 if mk[ixq] == 0 { if odist[ixq] > thr { 1904 var nb2: i64 = 0 1905 if qi2 > 0 { if mk[((qi2-1)*n1+qj2)*n1+qk2] == 1 { nb2 = 1 } } 1906 if qi2 < n1-1 { if mk[((qi2+1)*n1+qj2)*n1+qk2] == 1 { nb2 = 1 } } 1907 if qj2 > 0 { if mk[(qi2*n1+(qj2-1))*n1+qk2] == 1 { nb2 = 1 } } 1908 if qj2 < n1-1 { if mk[(qi2*n1+(qj2+1))*n1+qk2] == 1 { nb2 = 1 } } 1909 if qk2 > 0 { if mk[(qi2*n1+qj2)*n1+(qk2-1)] == 1 { nb2 = 1 } } 1910 if qk2 < n1-1 { if mk[(qi2*n1+qj2)*n1+(qk2+1)] == 1 { nb2 = 1 } } 1911 if nb2 == 1 { mk[ixq] = 1; chg = 1 } 1912 } } 1913 qk2 = qk2 - 1 1914 } 1915 qj2 = qj2 - 1 1916 } 1917 qi2 = qi2 - 1 1918 } 1919 itc = itc + 1 1920 } 1921 } 1922 var lat: i64 = latmm 1923 if lat < cell { lat = cell } 1924 var n2: i64 = (G*cell)/lat + 1 1925 // REFUSE, never clamp: a clamped lattice would silently cover part of the box and be read 1926 // as the whole -- the exact silent-cap class this organ refuses one layer down (grid finer 1927 // than the field). Caught in my own first version, 2026-08-09. 1928 if n2 > SS_RES_MAXN { 1929 ss_puts("{\x22error\x22:\x22residual lattice finer than the bound allows\x22,\x22requested_n\x22:" as *u8); ss_pn(n2) 1930 ss_puts(",\x22max_n\x22:" as *u8); ss_pn(SS_RES_MAXN) 1931 ss_puts(",\x22finest_allowed_lat_mm\x22:" as *u8); ss_pn((G*cell)/(SS_RES_MAXN-1) + 1) 1932 ss_puts("}\n" as *u8) 1933 return 9 1934 } 1935 let rby: i64 = 40 + n2*n2*n2*8 1936 let rb: *u8 = sys_mmap(rby + 64) 1937 let rh: *i64 = rb as *i64 1938 rh[0] = SS_RES_MAGIC 1939 rh[1] = n2 1940 rh[2] = org 1941 rh[3] = lat 1942 rh[4] = SS_RDQ 1943 let rv: *i64 = ((rb as i64) + 40) as *i64 1944 var li: i64 = 0 1945 while li < n2 { 1946 var gi2: i64 = li*lat/cell 1947 if gi2 > n1-1 { gi2 = n1-1 } 1948 var lj: i64 = 0 1949 while lj < n2 { 1950 var gj2: i64 = lj*lat/cell 1951 if gj2 > n1-1 { gj2 = n1-1 } 1952 var lk: i64 = 0 1953 while lk < n2 { 1954 var gk2: i64 = lk*lat/cell 1955 if gk2 > n1-1 { gk2 = n1-1 } 1956 let ixr: i64 = (gi2*n1+gj2)*n1+gk2 1957 var osg: i64 = odist[ixr] 1958 // a normal-signed seed overrides the flood; unseeded nodes fall back to it 1959 var oneg: i64 = 0 1960 if osgn[ixr] == (2 as u8) { oneg = 1 } 1961 if osgn[ixr] == (0 as u8) { if mk[ixr] == 0 { oneg = 1 } } 1962 if oneg == 1 { osg = 0 - osg } 1963 rv[(li*n2+lj)*n2+lk] = osg - dist[ixr] 1964 lk = lk + 1 1965 } 1966 lj = lj + 1 1967 } 1968 li = li + 1 1969 } 1970 let rfd: i64 = sys_openat_wr(resout, 420) 1971 sys_write(rfd, rb, rby) 1972 sys_close(rfd) 1973 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22fitres\x22,\x22lattice_n\x22:" as *u8); ss_pn(n2) 1974 ss_puts(",\x22spacing_mm\x22:" as *u8); ss_pn(lat) 1975 ss_puts(",\x22flood_iters\x22:" as *u8); ss_pn(itc) 1976 ss_puts(",\x22bytes\x22:" as *u8); ss_pn(rby) 1977 ss_puts(",\x22derived_from\x22:\x22the ingested reference -- this file IS the match half of the circle, benchmark evidence, not a product asset\x22}\n" as *u8) 1978 } 1979 // ---- the ranked worklist ---- 1980 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22gapmap\x22,\x22cell_mm\x22:" as *u8); ss_pn(cell) 1981 ss_puts(",\x22ours_centre_mm\x22:[" as *u8); ss_pn(ocx) 1982 ss_puts("," as *u8); ss_pn(ocy) 1983 ss_puts("," as *u8); ss_pn(ocz) 1984 ss_puts("]" as *u8) 1985 ss_puts(",\x22bound\x22:\x22vertex-seeded oracle field OVERSTATES gaps by at most half the oracle vertex spacing (~1mm); ours near-band = our surface, oracle near-band = its surface\x22" as *u8) 1986 ss_puts(",\x22regions\x22:[" as *u8) 1987 gi = 0 1988 while gi < SS_GR_N { 1989 if gi > 0 { ss_puts("," as *u8) } 1990 ss_puts("{\x22region\x22:\x22" as *u8) 1991 ss_gap_regname(gi) 1992 ss_puts("\x22,\x22ours_to_oracle_mean_mm\x22:" as *u8) 1993 if fn[gi] > 0 { ss_pn(fsum[gi]/fn[gi]/SS_RDQ) } else { ss_pn(0-1) } 1994 ss_puts(",\x22ours_to_oracle_worst_mm\x22:" as *u8); ss_pn(fmax[gi]/SS_RDQ) 1995 ss_puts(",\x22missing_anatomy_mean_mm\x22:" as *u8) 1996 if rn[gi] > 0 { ss_pn(rsum[gi]/rn[gi]/SS_RDQ) } else { ss_pn(0-1) } 1997 ss_puts(",\x22missing_anatomy_worst_mm\x22:" as *u8); ss_pn(rmax[gi]/SS_RDQ) 1998 ss_puts(",\x22n_ours\x22:" as *u8); ss_pn(fn[gi]) 1999 ss_puts(",\x22n_oracle\x22:" as *u8); ss_pn(rn[gi]) 2000 ss_puts("}" as *u8) 2001 gi = gi + 1 2002 } 2003 ss_puts("]}\n" as *u8) 2004 return 0 2005} 2006 2007// ---- VOXREF: the oracle voxelized by exact triangle crossings + parity (derived bounds, no caps) ---- 2008func ss_voxref(ref: *u8, outp: *u8, cum: i64) -> i64 { 2009 var G: i64 = (SS_EXT*2*1000 + cum - 1)/cum 2010 if G > SS_EXT*2 { G = SS_EXT*2 } 2011 let cell: i64 = (SS_EXT*2 + G - 1)/G 2012 let org: i64 = 0 - (G*cell)/2 2013 let n1: i64 = G+1 2014 let ln: *i64 = sys_mmap(16) as *i64 2015 let rbuf: *u8 = sys_read_file(ref, ln) 2016 if (rbuf as i64) == 0 { ss_puts("{\x22error\x22:\x22cannot read reference\x22}\n" as *u8); return 3 } 2017 let rlayer: i64 = ss_rd32(rbuf, 8) 2018 let rnt: i64 = ss_rd32(rbuf, 12) 2019 let rhdr: i64 = 16 + rlayer*24 2020 if rnt <= 0 { ss_puts("{\x22error\x22:\x22no reference triangles\x22}\n" as *u8); return 4 } 2021 // bbox centre (mm) 2022 var lox: i64 = 0; var hix: i64 = 0 2023 var loy: i64 = 0; var hiy: i64 = 0 2024 var loz: i64 = 0; var hiz: i64 = 0 2025 var first: i64 = 1 2026 var t: i64 = 0 2027 while t < rnt { 2028 let o: i64 = rhdr + t*84 2029 var vj: i64 = 0 2030 while vj < 3 { 2031 let x: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12), 1) 2032 let y: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+4), 1) 2033 let z: i64 = ss_r_f32(ss_rd32(rbuf,o+vj*12+8), 1) 2034 if first == 1 { lox=x; hix=x; loy=y; hiy=y; loz=z; hiz=z; first=0 } else { 2035 if x<lox {lox=x} 2036 if x>hix {hix=x} 2037 if y<loy {loy=y} 2038 if y>hiy {hiy=y} 2039 if z<loz {loz=z} 2040 if z>hiz {hiz=z} 2041 } 2042 vj = vj + 1 2043 } 2044 t = t + 1 2045 } 2046 let cx: i64 = (lox+hix)/2 2047 let cy: i64 = (loy+hiy)/2 2048 let cz: i64 = (loz+hiz)/2 2049 // buckets over (y,z) AT GRID RESOLUTION -- granularity derived from the grid, storage sized by 2050 // the counting pass: no capacity constant exists to hit 2051 let nb: i64 = G + 2 2052 let nins: i64 = ss_vb_count(rbuf, rhdr, rnt, cy, cz, 0, 0, org, nb, cell) 2053 if nins <= 0 { ss_puts("{\x22error\x22:\x22no triangles land in the grid\x22}\n" as *u8); return 4 } 2054 if mf_admit("nx_skullsdf voxref" as *u8, n1*n1*n1*8 + nb*nb*8 + nins*16) == 0 { return 8 } 2055 let head: *i64 = sys_mmap(nb*nb*8) as *i64 2056 let nxt: *i64 = sys_mmap(nins*8) as *i64 2057 let tref: *i64 = sys_mmap(nins*8) as *i64 2058 let ins: i64 = ss_vb_build(rbuf, rhdr, rnt, cx, cy, cz, 0, 0, 0, org, nb, cell, head, nxt, tref, nins) 2059 if ins != nins { 2060 // the two passes walk identical loops; disagreement is an internal defect, never tolerable 2061 ss_puts("{\x22error\x22:\x22count/fill mismatch\x22,\x22counted\x22:" as *u8); ss_pn(nins) 2062 ss_puts(",\x22filled\x22:" as *u8); ss_pn(ins) 2063 ss_puts("}\n" as *u8) 2064 return 9 2065 } 2066 // per-column hit buffer sized by the longest measured bucket (the exact upper bound) 2067 var maxlist: i64 = 0 2068 var bc2: i64 = 0 2069 while bc2 < nb*nb { 2070 var ll: i64 = 0 2071 var p2: i64 = head[bc2] 2072 while p2 >= 0 { ll = ll + 1; p2 = nxt[p2] } 2073 if ll > maxlist { maxlist = ll } 2074 bc2 = bc2 + 1 2075 } 2076 // signed field, Q units; parity signs every node, crossings seed exact flank distances 2077 let fld: *i64 = sys_mmap(n1*n1*n1*8) as *i64 2078 let hits: *i64 = sys_mmap((maxlist+1)*8) as *i64 2079 let orgq: i64 = org*SS_RDQ 2080 let cellq: i64 = cell*SS_RDQ 2081 var totalhits: i64 = 0 2082 var repaired: i64 = 0 2083 var maxnd: i64 = 0 2084 var j: i64 = 0 2085 while j < n1 { 2086 let y0q: i64 = (org + j*cell)*SS_RDQ 2087 var k: i64 = 0 2088 while k < n1 { 2089 let z0q: i64 = (org + k*cell)*SS_RDQ 2090 let bj: i64 = j 2091 let bk: i64 = k 2092 var nh: i64 = 0 2093 if bj >= 0 { if bj < nb { if bk >= 0 { if bk < nb { 2094 var p: i64 = head[bj*nb+bk] 2095 while p >= 0 { 2096 let tt: i64 = tref[p] 2097 let o: i64 = rhdr + tt*84 2098 let xa: i64 = ss_r_f32(ss_rd32(rbuf,o), SS_RDQ) - cx*SS_RDQ 2099 let ya: i64 = ss_r_f32(ss_rd32(rbuf,o+8), SS_RDQ) - cz*SS_RDQ 2100 let za: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+4), SS_RDQ) - cy*SS_RDQ) 2101 let xb: i64 = ss_r_f32(ss_rd32(rbuf,o+12), SS_RDQ) - cx*SS_RDQ 2102 let yb: i64 = ss_r_f32(ss_rd32(rbuf,o+20), SS_RDQ) - cz*SS_RDQ 2103 let zb: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+16), SS_RDQ) - cy*SS_RDQ) 2104 let xc: i64 = ss_r_f32(ss_rd32(rbuf,o+24), SS_RDQ) - cx*SS_RDQ 2105 let yc: i64 = ss_r_f32(ss_rd32(rbuf,o+32), SS_RDQ) - cz*SS_RDQ 2106 let zc: i64 = 0 - (ss_r_f32(ss_rd32(rbuf,o+28), SS_RDQ) - cy*SS_RDQ) 2107 // edge functions in the (y,z) plane at (y0q,z0q) 2108 let e0: i64 = (yb-ya)*(z0q-za) - (zb-za)*(y0q-ya) 2109 let e1: i64 = (yc-yb)*(z0q-zb) - (zc-zb)*(y0q-yb) 2110 let e2: i64 = (ya-yc)*(z0q-zc) - (za-zc)*(y0q-yc) 2111 var hit: i64 = 0 2112 if e0 >= 0 { if e1 >= 0 { if e2 >= 0 { hit = 1 } } } 2113 if e0 <= 0 { if e1 <= 0 { if e2 <= 0 { hit = 1 } } } 2114 if hit == 1 { 2115 let den: i64 = e0 + e1 + e2 2116 if den != 0 { 2117 // barycentric: e1 weights vertex a, e2 weights b, e0 weights c 2118 // nh is bounded by this bucket's own length <= maxlist: no cap exists 2119 let xq: i64 = (e1*xa + e2*xb + e0*xc)/den 2120 hits[nh] = xq 2121 nh = nh + 1 2122 } 2123 } 2124 p = nxt[p] 2125 } 2126 } } } } 2127 // insertion sort + dedup within 2 Q (shared-edge doubles) 2128 var s1: i64 = 1 2129 while s1 < nh { 2130 let v: i64 = hits[s1] 2131 var s2: i64 = s1 2132 var go2: i64 = 1 2133 while go2 == 1 { 2134 if s2 <= 0 { go2 = 0 } else { 2135 if hits[s2-1] > v { hits[s2] = hits[s2-1]; s2 = s2 - 1 } else { go2 = 0 } 2136 } 2137 } 2138 hits[s2] = v 2139 s1 = s1 + 1 2140 } 2141 var nd: i64 = 0 2142 var s3: i64 = 0 2143 while s3 < nh { 2144 var keep: i64 = 1 2145 // shared-edge duplicates coincide geometrically; each crossing rounds ONCE in the 2146 // barycentric integer division, so duplicates differ by at most 2 quanta -- the 2147 // tolerance is the arithmetic's own bound, not a tuned number 2148 if nd > 0 { if hits[s3] - hits[nd-1] <= 2 { keep = 0 } } 2149 if keep == 1 { hits[nd] = hits[s3]; nd = nd + 1 } 2150 s3 = s3 + 1 2151 } 2152 // parity repair: an ODD count means this ray passed through a hole in the scan; the 2153 // unpaired crossing would flip parity for the rest of the column and extrude a streak to 2154 // the box edge (rendered, measured). Drop the deepest crossing so parity closes; COUNT it. 2155 if (nd & 1) == 1 { nd = nd - 1; repaired = repaired + 1 } 2156 if nd > maxnd { maxnd = nd } 2157 totalhits = totalhits + nd 2158 // walk nodes: parity sign everywhere, exact seeds at crossing flanks 2159 var hi2: i64 = 0 2160 var i: i64 = 0 2161 while i < n1 { 2162 let nxq: i64 = orgq + i*cellq 2163 var go3: i64 = 1 2164 while go3 == 1 { 2165 if hi2 >= nd { go3 = 0 } else { 2166 if hits[hi2] <= nxq { hi2 = hi2 + 1 } else { go3 = 0 } 2167 } 2168 } 2169 var fv: i64 = SS_RD_INF 2170 // distance to nearest crossing on this column (exact near the surface) 2171 if hi2 > 0 { 2172 let dl: i64 = nxq - hits[hi2-1] 2173 if dl < fv { fv = dl } 2174 } 2175 if hi2 < nd { 2176 let dr: i64 = hits[hi2] - nxq 2177 if dr < fv { fv = dr } 2178 } 2179 // parity: odd crossings passed = inside 2180 if (hi2 & 1) == 1 { fv = 0 - fv } 2181 fld[(i*n1+j)*n1+k] = fv 2182 i = i + 1 2183 } 2184 k = k + 1 2185 } 2186 j = j + 1 2187 } 2188 // polygonize O alone -- the control: is O the skull? 2189 tm_reset() 2190 surface_nets(fld, G, G, G, org, org, org, cell, SS_ISO, SS_BONE) 2191 let nv: i64 = tm_nv() 2192 let nt2: i64 = tm_nt() 2193 if nt2 <= 0 { ss_puts("{\x22error\x22:\x22no surface\x22}\n" as *u8); return 5 } 2194 let h1: i64 = 16 + 3*24 2195 let by1: i64 = h1 + nt2*84 + nt2*4 2196 let b1: *u8 = sys_mmap(by1 + 64) 2197 ss_gap_wrhdr(b1, nt2) 2198 var t2: i64 = 0 2199 while t2 < nt2 { 2200 let o: i64 = h1 + t2*84 2201 let ia: i64 = tm_ta(t2); let ib: i64 = tm_tb(t2); let ic: i64 = tm_tc(t2) 2202 ss_wr32(b1, o, ss_f32(tm_vx(ia),1)); ss_wr32(b1, o+4, ss_f32(tm_vy(ia),1)); ss_wr32(b1, o+8, ss_f32(tm_vz(ia),1)) 2203 ss_wr32(b1, o+12, ss_f32(tm_vx(ib),1)); ss_wr32(b1, o+16, ss_f32(tm_vy(ib),1)); ss_wr32(b1, o+20, ss_f32(tm_vz(ib),1)) 2204 ss_wr32(b1, o+24, ss_f32(tm_vx(ic),1)); ss_wr32(b1, o+28, ss_f32(tm_vy(ic),1)); ss_wr32(b1, o+32, ss_f32(tm_vz(ic),1)) 2205 ss_wr32(b1, o+36, ss_f32(tm_vnx(ia),SS_NQ)); ss_wr32(b1, o+40, ss_f32(tm_vny(ia),SS_NQ)); ss_wr32(b1, o+44, ss_f32(tm_vnz(ia),SS_NQ)) 2206 ss_wr32(b1, o+48, ss_f32(tm_vnx(ib),SS_NQ)); ss_wr32(b1, o+52, ss_f32(tm_vny(ib),SS_NQ)); ss_wr32(b1, o+56, ss_f32(tm_vnz(ib),SS_NQ)) 2207 ss_wr32(b1, o+60, ss_f32(tm_vnx(ic),SS_NQ)); ss_wr32(b1, o+64, ss_f32(tm_vny(ic),SS_NQ)); ss_wr32(b1, o+68, ss_f32(tm_vnz(ic),SS_NQ)) 2208 ss_wr32(b1, o+72, ss_f32(910,1000)); ss_wr32(b1, o+76, ss_f32(890,1000)); ss_wr32(b1, o+80, ss_f32(845,1000)) 2209 ss_wr32(b1, h1 + nt2*84 + t2*4, 2) 2210 t2 = t2 + 1 2211 } 2212 let fd1: i64 = sys_openat_wr(outp, MODE_0644) 2213 sys_write(fd1, b1, by1) 2214 sys_close(fd1) 2215 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22voxref\x22,\x22cell_mm\x22:" as *u8); ss_pn(cell) 2216 ss_puts(",\x22crossings\x22:" as *u8); ss_pn(totalhits) 2217 ss_puts(",\x22parity_repaired_columns\x22:" as *u8); ss_pn(repaired) 2218 ss_puts(",\x22max_crossings_per_column\x22:" as *u8); ss_pn(maxnd) 2219 ss_puts(",\x22max_bucket_len\x22:" as *u8); ss_pn(maxlist) 2220 ss_puts(",\x22bucket_insertions\x22:" as *u8); ss_pn(ins) 2221 ss_puts(",\x22verts\x22:" as *u8); ss_pn(nv) 2222 ss_puts(",\x22tris\x22:" as *u8); ss_pn(nt2) 2223 ss_puts(",\x22overflow\x22:" as *u8); ss_pn(tm_ovf()) 2224 ss_puts(",\x22method\x22:\x22exact triangle crossings per grid column + parity sign -- the control: this is O alone, no base, no residual\x22}\n" as *u8) 2225 return 0 2226} 2227 2228// ---- REDISTANCE HELPERS (argv[8]; see the SS_RDQ const block for why this pass exists) ---- 2229// one seed candidate: if f and g straddle the iso level, the crossing sits |f|/(|f|+|g|) along the 2230// edge; the distance from this node to it, in SS_RDQ units, competes for the seed minimum 2231func ss_rd_try(f: i64, g: i64, cell: i64, best: i64) -> i64 { 2232 var fin: i64 = 0 2233 if f <= 0 { fin = 1 } 2234 var gin: i64 = 0 2235 if g <= 0 { gin = 1 } 2236 if fin == gin { return best } 2237 var af: i64 = f 2238 if af < 0 { af = 0-af } 2239 var ag: i64 = g 2240 if ag < 0 { ag = 0-ag } 2241 var den: i64 = af+ag 2242 if den < 1 { den = 1 } 2243 let t: i64 = af*cell*SS_RDQ/den 2244 if t < best { return t } 2245 return best 2246} 2247// upwind eikonal update from the per-axis neighbour minima with grid spacing h (all SS_RDQ units). 2248// Sequential form: try 1D, then 2D, then 3D. Each discriminant is positive when its case is reached 2249// (reaching 2D means a+h > b so (a-b)^2 < h^2 < 2h^2), but both are still guarded. 2250func ss_rd_solve(a0: i64, b0: i64, c0: i64, h: i64) -> i64 { 2251 var a: i64 = a0 2252 var b: i64 = b0 2253 var c: i64 = c0 2254 var tv: i64 = 0 2255 if a > b { tv=a; a=b; b=tv } 2256 if b > c { tv=b; b=c; c=tv } 2257 if a > b { tv=a; a=b; b=tv } 2258 if a >= SS_RD_INF { return SS_RD_INF } 2259 var d: i64 = a + h 2260 if d <= b { return d } 2261 let s2: i64 = 2*h*h - (a-b)*(a-b) 2262 if s2 > 0 { d = (a + b + ss_isqrt(s2))/2 } 2263 if d <= c { return d } 2264 let s: i64 = a+b+c 2265 let s3: i64 = s*s - 3*(a*a + b*b + c*c - h*h) 2266 if s3 > 0 { return (s + ss_isqrt(s3))/3 } 2267 return d 2268} 2269// one directional sweep; returns the largest single-node improvement so convergence is a PRINTED 2270// number rather than an assumption. Min-update only ever lowers a value, and an eikonal update from 2271// true-distance neighbours can never undercut the true distance (triangle inequality), so the exact 2272// sub-cell seeds survive every sweep without a freeze flag. 2273func ss_rd_sweep(dist: *i64, n1: i64, h: i64, di: i64, dj: i64, dk: i64) -> i64 { 2274 var maxd: i64 = 0 2275 var sa: i64 = 0 2276 while sa < n1 { 2277 var i: i64 = sa 2278 if di < 0 { i = n1-1-sa } 2279 var sb: i64 = 0 2280 while sb < n1 { 2281 var j: i64 = sb 2282 if dj < 0 { j = n1-1-sb } 2283 var sc: i64 = 0 2284 while sc < n1 { 2285 var k: i64 = sc 2286 if dk < 0 { k = n1-1-sc } 2287 let ix: i64 = (i*n1+j)*n1+k 2288 let cur: i64 = dist[ix] 2289 if cur > 0 { 2290 var ax: i64 = SS_RD_INF 2291 if i > 0 { ax = dist[((i-1)*n1+j)*n1+k] } 2292 if i < n1-1 { 2293 let wx: i64 = dist[((i+1)*n1+j)*n1+k] 2294 if wx < ax { ax = wx } 2295 } 2296 var ay: i64 = SS_RD_INF 2297 if j > 0 { ay = dist[(i*n1+(j-1))*n1+k] } 2298 if j < n1-1 { 2299 let wy: i64 = dist[(i*n1+(j+1))*n1+k] 2300 if wy < ay { ay = wy } 2301 } 2302 var az: i64 = SS_RD_INF 2303 if k > 0 { az = dist[(i*n1+j)*n1+(k-1)] } 2304 if k < n1-1 { 2305 let wz: i64 = dist[(i*n1+j)*n1+(k+1)] 2306 if wz < az { az = wz } 2307 } 2308 let nd: i64 = ss_rd_solve(ax, ay, az, h) 2309 if nd < cur { 2310 dist[ix] = nd 2311 let dl: i64 = cur - nd 2312 if dl > maxd { maxd = dl } 2313 } 2314 } 2315 sc = sc + 1 2316 } 2317 sb = sb + 1 2318 } 2319 sa = sa + 1 2320 } 2321 return maxd 2322} 2323// near-band |grad| distribution of a SAMPLED field, per-mille of a true SDF -- the same statistic 2324// ss_grad reports for the analytic field, taken here on the grid so the pass can be A/B'd in-run. 2325// q = field units per millimetre (1 for the raw grid, SS_RDQ for the redistanced one). 2326func ss_rd_gradstat(F: *i64, n1: i64, cell: i64, q: i64, tag: *u8) -> i64 { 2327 var lo: i64 = SS_EXTENT_SENTINEL 2328 var hi: i64 = 0-SS_EXTENT_SENTINEL 2329 var sum: i64 = 0 2330 var n: i64 = 0 2331 var under: i64 = 0 2332 var over: i64 = 0 2333 let band: i64 = SS_RD_NEAR*cell*q 2334 var i: i64 = 1 2335 while i < n1-1 { 2336 var j: i64 = 1 2337 while j < n1-1 { 2338 var k: i64 = 1 2339 while k < n1-1 { 2340 let f: i64 = F[(i*n1+j)*n1+k] 2341 var af: i64 = f 2342 if af < 0 { af = 0-af } 2343 if af <= band { 2344 let gx: i64 = F[((i+1)*n1+j)*n1+k] - F[((i-1)*n1+j)*n1+k] 2345 let gy: i64 = F[(i*n1+(j+1))*n1+k] - F[(i*n1+(j-1))*n1+k] 2346 let gz: i64 = F[(i*n1+j)*n1+(k+1)] - F[(i*n1+j)*n1+(k-1)] 2347 let g: i64 = ss_isqrt(gx*gx + gy*gy + gz*gz)*1000/(2*cell*q) 2348 if g < lo { lo = g } 2349 if g > hi { hi = g } 2350 sum = sum + g 2351 n = n + 1 2352 if g < SS_RD_LO { under = under + 1 } 2353 if g > SS_RD_HI { over = over + 1 } 2354 } 2355 k = k + 1 2356 } 2357 j = j + 1 2358 } 2359 i = i + 1 2360 } 2361 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22redist_gradstat\x22,\x22field\x22:\x22" as *u8) 2362 ss_puts(tag) 2363 ss_puts("\x22,\x22true_sdf_is\x22:1000,\x22samples\x22:" as *u8); ss_pn(n) 2364 if n > 0 { 2365 ss_puts(",\x22mean\x22:" as *u8); ss_pn(sum/n) 2366 ss_puts(",\x22min\x22:" as *u8); ss_pn(lo) 2367 ss_puts(",\x22max\x22:" as *u8); ss_pn(hi) 2368 ss_puts(",\x22under_800_permil\x22:" as *u8); ss_pn(under*1000/n) 2369 ss_puts(",\x22over_1200_permil\x22:" as *u8); ss_pn(over*1000/n) 2370 } 2371 ss_puts("}\n" as *u8) 2372 return 0 2373} 2374 2375func main(argc: i64, argv: *i64) -> i64 { 2376 if argc < 2 { return 2 } 2377 if ss_streq(argv[1] as *u8, "tune" as *u8) != 1 { ss_puts("CANDIDATE: explicit new fit only; emission not installed\n" as *u8); return 2 } 2378 if argc < 2 { ss_puts("usage: nx_skullsdf <out.nxmesh> [sex] [robust] [grid] [cell_um] [tissue_permil] [k_mm] [redist] | fit <ref> | tune <ref> | gapmap <ref> <heat_ours> <heat_oracle>\n" as *u8); return 2 } 2379 if ss_streq(argv[1] as *u8, "tune" as *u8) == 1 { 2380 if argc < 3 { ss_puts("usage: nx_skullsdf tune <ref.nxmesh> [sex] [robust] [stride] [passes] [step0] [save_dat]\n" as *u8); return 2 } 2381 var ts: i64 = 0 2382 if argc > 3 { ts = ss_atoi(argv[3] as *u8) } 2383 var tr: i64 = 500 2384 if argc > 4 { tr = ss_atoi(argv[4] as *u8) } 2385 var tst: i64 = 31 2386 if argc > 5 { tst = ss_atoi(argv[5] as *u8) } 2387 if tst < 1 { tst = 1 } 2388 var tp: i64 = 5 2389 if argc > 6 { tp = ss_atoi(argv[6] as *u8) } 2390 var tstep: i64 = 8 2391 if argc > 7 { tstep = ss_atoi(argv[7] as *u8) } 2392 var tsv: i64 = 0 2393 if argc > 8 { tsv = argv[8] } 2394 return ss_tune(argv[2] as *u8, ts, tr, tst, tp, tstep, tsv as *u8) 2395 } 2396 if ss_streq(argv[1] as *u8, "grad" as *u8) == 1 { 2397 var gs: i64 = 0 2398 if argc > 2 { gs = ss_atoi(argv[2] as *u8) } 2399 var gr: i64 = 500 2400 if argc > 3 { gr = ss_atoi(argv[3] as *u8) } 2401 var gp: i64 = 4 2402 if argc > 4 { gp = ss_atoi(argv[4] as *u8) } 2403 if gp < 1 { gp = 1 } 2404 if argc > 5 { 2405 SS_KVAL = ss_atoi(argv[5] as *u8) 2406 if SS_KVAL >= 0 { SS_KSET = 1 } 2407 } 2408 return ss_grad(gs, gr, gp, 3) 2409 } 2410 if ss_streq(argv[1] as *u8, "thick" as *u8) == 1 { 2411 if argc < 3 { ss_puts("usage: nx_skullsdf thick <envelope.nxmesh> [sex] [robust] [stride]\n" as *u8); return 2 } 2412 var ks: i64 = 0 2413 if argc > 3 { ks = ss_atoi(argv[3] as *u8) } 2414 var kr: i64 = 500 2415 if argc > 4 { kr = ss_atoi(argv[4] as *u8) } 2416 var kt: i64 = 7 2417 if argc > 5 { kt = ss_atoi(argv[5] as *u8) } 2418 if kt < 1 { kt = 1 } 2419 return ss_thick(argv[2] as *u8, ks, kr, kt) 2420 } 2421 if ss_streq(argv[1] as *u8, "voxref" as *u8) == 1 { 2422 if argc < 4 { ss_puts("usage: nx_skullsdf voxref <ref.nxmesh> <out.nxmesh> [cell_um]\n" as *u8); return 2 } 2423 var vc: i64 = 1000 2424 if argc > 4 { vc = ss_atoi(argv[4] as *u8) } 2425 if vc < 1000 { vc = 1000 } 2426 return ss_voxref(argv[2] as *u8, argv[3] as *u8, vc) 2427 } 2428 if ss_streq(argv[1] as *u8, "gapmap" as *u8) == 1 { 2429 if argc < 5 { ss_puts("usage: nx_skullsdf gapmap <ref.nxmesh> <heat_ours.nxmesh> <heat_oracle.nxmesh> [sex] [robust] [cell_um]\n" as *u8); return 2 } 2430 var ms: i64 = 0 2431 if argc > 5 { ms = ss_atoi(argv[5] as *u8) } 2432 var mr: i64 = 500 2433 if argc > 6 { mr = ss_atoi(argv[6] as *u8) } 2434 var mc: i64 = SS_MARCH_CELLS_DEFAULT 2435 if argc > 7 { mc = ss_atoi(argv[7] as *u8) } 2436 if mc < SS_MARCH_CELLS_MIN { mc = SS_MARCH_CELLS_MIN } 2437 var mres: i64 = 0 2438 if argc > 8 { mres = argv[8] } 2439 var mlat: i64 = 4 2440 if argc > 9 { mlat = ss_atoi(argv[9] as *u8) } 2441 return ss_gapmap(argv[2] as *u8, argv[3] as *u8, argv[4] as *u8, ms, mr, mc, mres as *u8, mlat) 2442 } 2443 if ss_streq(argv[1] as *u8, "fit" as *u8) == 1 { 2444 if argc < 3 { ss_puts("usage: nx_skullsdf fit <ref.nxmesh> [sex] [robust] [stride]\n" as *u8); return 2 } 2445 var fs: i64 = 0 2446 if argc > 3 { fs = ss_atoi(argv[3] as *u8) } 2447 var fr: i64 = 500 2448 if argc > 4 { fr = ss_atoi(argv[4] as *u8) } 2449 var st: i64 = 7 2450 if argc > 5 { st = ss_atoi(argv[5] as *u8) } 2451 if st < 1 { st = 1 } 2452 return ss_fit(argv[2] as *u8, fs, fr, st) 2453 } 2454 var sexf: i64 = 0 2455 if argc > 2 { sexf = ss_atoi(argv[2] as *u8) } 2456 var robust: i64 = 500 2457 if argc > 3 { robust = ss_atoi(argv[3] as *u8) } 2458 var G: i64 = SS_G 2459 if argc > 4 { G = ss_atoi(argv[4] as *u8) } 2460 // ★★CELL-SIZE-DRIVEN RESOLUTION (argv[5], MICROMETRES) -- the honest dial, additive so argv[4] still 2461 // means G for every existing caller. 2462 // WHY: `cell` below is INTEGER MILLIMETRES, so with a 320mm extent EVERY G from 161 to 319 yields 2463 // cell=2. Raising G in that range buys ZERO resolution while GROWING THE BOX (G=224 covers 448mm at 2464 // the SAME 2mm) and the allocation with it -- the dial is actively harmful in its dead zone. 2465 // MEASURED: G=160, 176 and 192 emit BYTE-IDENTICAL geometry (cell 2, verts 48814, tris 97660). 2466 // Asking for a CELL SIZE makes resolution monotonic and the box exactly the extent, with no waste. 2467 if argc > 5 { 2468 let cum: i64 = ss_atoi(argv[5] as *u8) 2469 if cum > 0 { G = (SS_EXT*2*1000 + cum - 1)/cum } 2470 } 2471 2472 // ★TISSUE ENVELOPE (argv[6], per-mille of the published depths). ADDITIVE by construction: absent or 0 2473 // means SS_TISSUE stays 0 and the bone surface is emitted exactly as before. 2474 if argc > 6 { 2475 let tp: i64 = ss_atoi(argv[6] as *u8) 2476 if tp > 0 { SS_TISSUE = tp } 2477 } 2478 // SMOOTH-UNION RADIUS (argv[7], mm). Set 0 for a TRUE distance field with visible sutures. 2479 if argc > 7 { 2480 SS_KVAL = ss_atoi(argv[7] as *u8) 2481 if SS_KVAL >= 0 { SS_KSET = 1 } 2482 } 2483 // REDISTANCE (argv[8]). ★DEFAULT NOW 1 (2026-08-10, shipped winners: a plain call gets the true 2484 // SDF; pass 0 explicitly for the legacy raw field). 2485 SS_REDIST = 1 2486 if argc > 8 { 2487 SS_REDIST = ss_atoi(argv[8] as *u8) 2488 } 2489 // RESIDUAL (argv[9] scale permil, argv[10] path): the input-derived identity layer on top of the 2490 // parametric base. ★DEFAULT NOW 250 PERMIL (2026-08-10, operator: a bug to not ship): measured ladder 2491 // 0->73, 250->125 with silhouettes held and the onion-ring class dead by eye, 1000->bead cloud. 2492 // Explicit argv[9] overrides (0 disables). A missing/invalid residual file FAILS OPEN to the 2493 // parametric base on the DEFAULT path -- only an EXPLICIT request errors loudly. 2494 if argc <= 9 { SS_RESSC = 250 } 2495 if argc > 9 { SS_RESSC = ss_atoi(argv[9] as *u8) } 2496 if SS_RESSC > 0 { 2497 var rp: *u8 = "knowledge/skull_res.dat" as *u8 2498 if argc > 10 { rp = argv[10] as *u8 } 2499 if ss_res_load(rp) == 0 { 2500 if argc > 9 { 2501 ss_puts("{\x22error\x22:\x22residual requested but the file did not load (magic/size/bounds)\x22}\n" as *u8) 2502 return 6 2503 } 2504 SS_RESSC = 0 2505 } 2506 if SS_RESSC > 0 { if SS_REDIST != 1 { 2507 if argc > 9 { 2508 ss_puts("{\x22error\x22:\x22residual requires redist=1 (argv[8]): the base must be a true SDF\x22}\n" as *u8) 2509 return 6 2510 } 2511 SS_RESSC = 0 2512 }} 2513 } 2514 2515 // ⚠CEILING, not truncation. SS_EXT*2/G with 260mm over 144 cells gives cell=1, so the grid covered 2516 // only 144mm and CLIPPED the skull at its own boundary -- which is why width and depth both came 2517 // back as 142: they were not measurements of the skull, they were measurements of the box. 2518 let cell: i64 = (SS_EXT*2 + G - 1)/G 2519 if cell*G < SS_EXT*2 { ss_puts("{\x22error\x22:\x22grid does not cover the extent\x22}\n" as *u8); return 7 } 2520 // THE DIAL'S OTHER DEAD ZONE, AND IT IS THE SAME DEFECT ONE LEVEL DOWN. `cell` is an INTEGER 2521 // NUMBER OF MILLIMETRES, so the finest resolution this field can be sampled at is 1mm, reached at 2522 // G = SS_EXT*2. Every G ABOVE that still yields cell=1 -- but G*cell then EXCEEDS the extent, so the 2523 // grid silently covers a LARGER BOX at the SAME resolution: G=480 sampled 480mm instead of 240mm, 2524 // costing 8x the memory and 8x the time for ZERO extra detail, while still printing a `grid` field 2525 // that implies the caller got what they asked for. 2526 // That is exactly the failure the micrometre dial above was added to cure, so silently tolerating 2527 // it here would leave the cure with the disease inside it. REFUSE, and NAME the finest cell that is 2528 // actually expressible -- an honest non-answer beats a wrong mesh (the nx_memfloor law, applied to 2529 // over-resolution rather than over-allocation). 2530 if G > SS_EXT*2 { 2531 ss_puts("{\x22error\x22:\x22grid finer than the field can be sampled\x22,\x22requested_grid\x22:" as *u8); ss_pn(G) 2532 ss_puts(",\x22max_grid\x22:" as *u8); ss_pn(SS_EXT*2) 2533 ss_puts(",\x22finest_cell_mm\x22:1,\x22why\x22:\x22cell size is integer millimetres, so G above 2*SS_EXT grows the sampled box without adding resolution\x22}\n" as *u8) 2534 return 9 2535 } 2536 // ⚠CENTRE THE GRID ON THE SPAN IT ACTUALLY HAS. Ceiling division makes G*cell LARGER than 2*EXT, so 2537 // an origin of -EXT put the extra span entirely on the positive side and clipped the mandible off 2538 // the bottom -- which made the measured height depend on the grid rather than on the skull. 2539 let org: i64 = 0 - (G*cell)/2 2540 let n1: i64 = G+1 2541 // UPPER BOUND. The check above guards G being too SMALL; nothing guarded it being too LARGE, and 2542 // this allocation is O(G^3). On 2026-07-30 a G of ~1500 mapped 1501^3*8 = 27.06 GB on a 36 GB host 2543 // in under three minutes: swap hit 98%, load hit 41, and the mgmt API began refusing builds for 2544 // every other seat. seq1547 was the same shape in nx_ssdf and took mgmt, tools and sshd down. 2545 // Ask BEFORE mapping, and REFUSE rather than silently shrinking -- a caller who asked for 1500 and 2546 // quietly got 160 would get a wrong mesh, which is worse than an honest non-answer. 2547 if mf_admit("nx_skullsdf sdf grid" as *u8, n1*n1*n1*8) == 0 { return 8 } 2548 let grid: *i64 = sys_mmap(n1*n1*n1*8) as *i64 2549 var i: i64 = 0 2550 while i < n1 { 2551 let x: i64 = org + i*cell 2552 var j: i64 = 0 2553 while j < n1 { 2554 let y: i64 = org + j*cell 2555 var k: i64 = 0 2556 while k < n1 { 2557 let z: i64 = org + k*cell 2558 // M2: the raw grid now carries SS_FQ units/mm -- seeds, signs and surface_nets are 2559 // ratio/sign-based so nothing downstream changes; the tissue subtract below becomes 2560 // unit-CONSISTENT (ss_tdepth is already mm x SS_RDQ and SS_FQ == SS_RDQ). 2561 var fv: i64 = ss_field_world_q(x, y, z, sexf, robust) 2562 // SS_TISSUE = 0 leaves the bone iso-surface EXACTLY as it was, so every existing caller 2563 // is byte-identical; > 0 moves the zero level outward by the forensic depth at this height. 2564 // depth now varies with BOTH height and lateral distance (|x|), per the dense-map 2565 // literature; ss_tdepth2 at ax=0 reproduces the old midline column exactly. 2566 // ★★★MEASURED AND REVERTED TO THE MIDLINE COLUMN. The 2-D (height x lateral) table above is 2567 // RETAINED UNUSED, the GX-34 emitLimbTube precedent, because it MADE THE FACE WORSE on the 2568 // judge built to catch exactly this. A/B at grid 80 vs the cadaver skin oracle: 2569 // variance headline 128 -> 129 (noise), but PLACEMENT 135 -> 123 with recall 306 -> 278 and 2570 // precision unchanged at 444. For positional work this lane trusts PLACEMENT over variance. 2571 // ★★AND THE REASON IS STRUCTURAL, worth more than the revert: the midline depths in ss_tdepth2 2572 // are IDENTICAL to v1 by construction, yet the MIDLINE PROFILE STILL CHANGED. In an 2573 // ISO-SURFACE formulation the depths are NOT independent per-vertex knobs -- subtracting a 2574 // different depth off-midline moves the field in a neighbourhood, and surface_nets 2575 // interpolates that across cells, so a LATERAL edit propagates onto the MIDLINE SURFACE. 2576 // ★That is the difference from the offset formulation, where every vertex moved alone, and it 2577 // means the literature's DENSE TISSUE MAP cannot be transplanted cell-by-cell onto an SDF 2578 // envelope: the map must be fitted AGAINST THE RESULTING SURFACE, not applied to the field. 2579 // ***THE PER-POINT SUBTRACTION IS THE ONE THAT MEASURES BEST. I moved this into a 2580 // gradient-normalised second pass and it was WORSE BY A LOT -- see the disabled pass below. 2581 // under REDIST the offset moves to a separate pass AFTER redistancing, so the raw 2582 // bone field survives for seeding; without it this line is the exact old behaviour 2583 if SS_TISSUE > 0 { if SS_REDIST == 0 { fv = fv - ss_tdepth(y)*SS_TISSUE/SS_PERMILLE } } 2584 grid[(i*n1+j)*n1+k] = fv 2585 k = k + 1 2586 } 2587 j = j + 1 2588 } 2589 i = i + 1 2590 } 2591 // ***GRADIENT-NORMALISED TISSUE OFFSET -- THE FIX THE MEASUREMENT DEMANDED, NOT THE ONE I EXPECTED. 2592 // MEASURED: requesting a depth d realised 3-6mm of SCATTER around it, and that scatter barely moved 2593 // when the cell went 3mm -> 2mm (total spread 37 -> 34, 8 percent for 2.25x the cells). So it is NOT a 2594 // sampling artifact. THE CAUSE IS IN THIS FILE'S OWN HEADER: ss_smin subtracts h*h/(4k) on every 2595 // chained call, and 'the result is NOT a distance field -- gradient magnitude drifts far from 1'. 2596 // SUBTRACTING d FROM A FIELD WHOSE GRADIENT MAGNITUDE IS NOT 1 MOVES THE SURFACE BY d/|grad f|, NOT d. 2597 // With ~16 chained unions the drift is worst exactly where primitives overlap, which is why the nasal 2598 // and upper-lip bands scattered most and why everything came out systematically THIN (chained smin 2599 // pushes the field negative, so |grad| > 1 and d/|grad| lands short). 2600 // ***THE REMEDY IS THE STANDARD SDF ONE: divide the requested depth by the LOCAL GRADIENT MAGNITUDE, 2601 // estimated by central differences on the grid we have already built. It costs one extra pass and no 2602 // extra field evaluations. This also subsumes the -1mm bias, which was the same cause, not a second. 2603 // Gradient is carried in PER-MILLE so a true distance field reads 1000 and integer division stays exact. 2604 // ***DISABLED AND RETAINED (GX-34 precedent). MEASURED AT 3mm, normalised vs per-point: 2605 // chin req 11 realised 14 with range 8..62 (was 10, range 9..13); cheek 7 -> 8 range 4..24 (was 6, 2606 // range 5..8); mean_abs_err 0 -> 2. DIVIDING BY |grad f| MADE IT MUCH WORSE. 2607 // ***WHY, and it sharpens the diagnosis rather than excusing it: the gradient does not merely drift 2608 // ABOVE 1, it drifts BOTH WAYS, and where it drifts LOW the division AMPLIFIES -- a 62mm chin came 2609 // from a near-flat cell. My guard only caught g < 0.1; a g of 0.2 still multiplies the requested 2610 // depth by five. So the field is not slightly distorted, it is distorted enough that neither naive 2611 // remedy works: IGNORING |grad| scatters by 3-6mm, DIVIDING BY IT scatters by 50. 2612 // ***THE REAL FIX IS TO MAKE THE FIELD A TRUE SDF, not to compensate downstream: either drop SS_K to 0 2613 // (this file records having done exactly that once, for exactly this reason, before restoring 6mm for 2614 // appearance) and accept sutured seams, or REDISTANCE the grid -- an eikonal/fast-sweeping pass that 2615 // rebuilds |grad| = 1 everywhere before any offset is taken. Redistancing is the standard answer and 2616 // it operates on the grid we already build. 2617 if SS_TISSUE < 0 { 2618 let gm: *i64 = sys_mmap(n1*n1*n1*8) as *i64 2619 var gi: i64 = 0 2620 while gi < n1 { 2621 var gj: i64 = 0 2622 while gj < n1 { 2623 var gk: i64 = 0 2624 while gk < n1 { 2625 var ai: i64 = gi+1 2626 if ai > n1-1 { ai = n1-1 } 2627 var bi: i64 = gi-1 2628 if bi < 0 { bi = 0 } 2629 var aj: i64 = gj+1 2630 if aj > n1-1 { aj = n1-1 } 2631 var bj: i64 = gj-1 2632 if bj < 0 { bj = 0 } 2633 var ak: i64 = gk+1 2634 if ak > n1-1 { ak = n1-1 } 2635 var bk: i64 = gk-1 2636 if bk < 0 { bk = 0 } 2637 let dx: i64 = (grid[(ai*n1+gj)*n1+gk] - grid[(bi*n1+gj)*n1+gk]) * 1000 / ((ai-bi)*cell*SS_FQ) 2638 let dy: i64 = (grid[(gi*n1+aj)*n1+gk] - grid[(gi*n1+bj)*n1+gk]) * 1000 / ((aj-bj)*cell*SS_FQ) 2639 let dz: i64 = (grid[(gi*n1+gj)*n1+ak] - grid[(gi*n1+gj)*n1+bk]) * 1000 / ((ak-bk)*cell*SS_FQ) 2640 var g: i64 = ss_isqrt(dx*dx + dy*dy + dz*dz) 2641 // a degenerate gradient (flat field, e.g. deep inside a solid) carries no direction 2642 // information; fall back to the unnormalised depth rather than dividing by ~0 2643 if g < 100 { g = 1000 } 2644 gm[(gi*n1+gj)*n1+gk] = g 2645 gk = gk + 1 2646 } 2647 gj = gj + 1 2648 } 2649 gi = gi + 1 2650 } 2651 gi = 0 2652 while gi < n1 { 2653 let gx: i64 = org + gi*cell 2654 var gj: i64 = 0 2655 while gj < n1 { 2656 let gy: i64 = org + gj*cell 2657 var gk: i64 = 0 2658 while gk < n1 { 2659 let ix: i64 = (gi*n1+gj)*n1+gk 2660 let d: i64 = ss_tdepth(gy)*SS_TISSUE/SS_PERMILLE 2661 grid[ix] = grid[ix] - d*1000/gm[ix] 2662 gk = gk + 1 2663 } 2664 gj = gj + 1 2665 } 2666 gi = gi + 1 2667 } 2668 } 2669 // ---- REDISTANCE PASS (argv[8]; mechanism at the SS_RDQ const block) ---- 2670 var FLD: *i64 = grid 2671 if SS_REDIST == 1 { 2672 // its own array: grid keeps the raw signed field (for seeds, signs and the printed A/B), 2673 // dist receives true unsigned distances at SS_RDQ fixed point. Ask before mapping (memfloor law). 2674 if mf_admit("nx_skullsdf redistance grid" as *u8, n1*n1*n1*8) == 0 { return 8 } 2675 let dist: *i64 = sys_mmap(n1*n1*n1*8) as *i64 2676 let hq: i64 = cell*SS_RDQ 2677 var seeded: i64 = 0 2678 var si: i64 = 0 2679 while si < n1 { 2680 var sj: i64 = 0 2681 while sj < n1 { 2682 var sk: i64 = 0 2683 while sk < n1 { 2684 let ix: i64 = (si*n1+sj)*n1+sk 2685 let f: i64 = grid[ix] 2686 var best: i64 = SS_RD_INF 2687 if si > 0 { best = ss_rd_try(f, grid[((si-1)*n1+sj)*n1+sk], cell, best) } 2688 if si < n1-1 { best = ss_rd_try(f, grid[((si+1)*n1+sj)*n1+sk], cell, best) } 2689 if sj > 0 { best = ss_rd_try(f, grid[(si*n1+(sj-1))*n1+sk], cell, best) } 2690 if sj < n1-1 { best = ss_rd_try(f, grid[(si*n1+(sj+1))*n1+sk], cell, best) } 2691 if sk > 0 { best = ss_rd_try(f, grid[(si*n1+sj)*n1+(sk-1)], cell, best) } 2692 if sk < n1-1 { best = ss_rd_try(f, grid[(si*n1+sj)*n1+(sk+1)], cell, best) } 2693 dist[ix] = best 2694 if best < SS_RD_INF { seeded = seeded + 1 } 2695 sk = sk + 1 2696 } 2697 sj = sj + 1 2698 } 2699 si = si + 1 2700 } 2701 // 8 diagonal sweep orders, run twice; the second set's largest improvement is printed as the 2702 // convergence evidence (0 = fully converged after the first set) 2703 var lastd: i64 = 0 2704 var it: i64 = 0 2705 while it < 2 { 2706 var setd: i64 = 0 2707 var sw: i64 = 0 2708 while sw < 8 { 2709 var di: i64 = 1 2710 if (sw & 1) == 1 { di = 0-1 } 2711 var dj: i64 = 1 2712 if ((sw>>1) & 1) == 1 { dj = 0-1 } 2713 var dk: i64 = 1 2714 if ((sw>>2) & 1) == 1 { dk = 0-1 } 2715 let sd: i64 = ss_rd_sweep(dist, n1, hq, di, dj, dk) 2716 if sd > setd { setd = sd } 2717 sw = sw + 1 2718 } 2719 lastd = setd 2720 it = it + 1 2721 } 2722 // restore the sign from the raw field BEFORE measuring: on an unsigned field a central 2723 // difference straddling the surface reads ~0 and the statistic would convict its own input 2724 var pi: i64 = 0 2725 while pi < n1 { 2726 var pj: i64 = 0 2727 while pj < n1 { 2728 var pk: i64 = 0 2729 while pk < n1 { 2730 let ix2: i64 = (pi*n1+pj)*n1+pk 2731 if grid[ix2] <= 0 { dist[ix2] = 0 - dist[ix2] } 2732 pk = pk + 1 2733 } 2734 pj = pj + 1 2735 } 2736 pi = pi + 1 2737 } 2738 // the in-run A/B: same statistic, same band, raw grid versus redistanced grid 2739 ss_rd_gradstat(grid, n1, cell, SS_FQ, "raw" as *u8) 2740 ss_rd_gradstat(dist, n1, cell, SS_RDQ, "redistanced" as *u8) 2741 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22verb\x22:\x22redist\x22,\x22seeded\x22:" as *u8); ss_pn(seeded) 2742 ss_puts(",\x22last_sweep_delta_q\x22:" as *u8); ss_pn(lastd) 2743 ss_puts(",\x22q_per_mm\x22:" as *u8); ss_pn(SS_RDQ) 2744 ss_puts("}\n" as *u8) 2745 // the identity layer rides ON TOP of the honest base: F = B + trilinear(R) x scale 2746 if SS_RESSC > 0 { 2747 var ri: i64 = 0 2748 while ri < n1 { 2749 let rx: i64 = org + ri*cell 2750 var rj: i64 = 0 2751 while rj < n1 { 2752 let ry: i64 = org + rj*cell 2753 var rk: i64 = 0 2754 while rk < n1 { 2755 let rix: i64 = (ri*n1+rj)*n1+rk 2756 dist[rix] = dist[rix] + ss_res_at(rx, ry, org + rk*cell)*SS_RESSC/SS_PERMILLE 2757 rk = rk + 1 2758 } 2759 rj = rj + 1 2760 } 2761 ri = ri + 1 2762 } 2763 } 2764 // tissue offset on the TRUE distance field: an iso-offset of depth d now moves the surface by 2765 // exactly d, which is the whole point of the pass 2766 if SS_TISSUE > 0 { 2767 var ti: i64 = 0 2768 while ti < n1 { 2769 var tj: i64 = 0 2770 while tj < n1 { 2771 let ty: i64 = org + tj*cell 2772 // interpolated landmark depths (ss_tdepth_q) rather than the band steps: on an 2773 // honest field the steps render as literal shelves; see the function's comment 2774 let toff: i64 = ss_tdepth_q(ty)*SS_TISSUE/SS_PERMILLE 2775 var tk: i64 = 0 2776 while tk < n1 { 2777 let ix3: i64 = (ti*n1+tj)*n1+tk 2778 dist[ix3] = dist[ix3] - toff 2779 tk = tk + 1 2780 } 2781 tj = tj + 1 2782 } 2783 ti = ti + 1 2784 } 2785 } 2786 FLD = dist 2787 } 2788 tm_reset() 2789 surface_nets(FLD, G, G, G, org, org, org, cell, SS_ISO, SS_BONE) 2790 let nv: i64 = tm_nv() 2791 let nt: i64 = tm_nt() 2792 if nt <= 0 { ss_puts("{\x22error\x22:\x22no surface -- field never crosses the iso level\x22}\n" as *u8); return 5 } 2793 2794 // ---- write NXMSH2, one layer ("bone"), so the existing viewer and benches read it unchanged 2795 let hdr: i64 = 16 + 3*24 2796 let bytes: i64 = hdr + nt*84 + nt*4 2797 let buf: *u8 = sys_mmap(bytes + 64) 2798 buf[0]=78 as u8; buf[1]=88 as u8; buf[2]=77 as u8; buf[3]=83 as u8 2799 buf[4]=72 as u8; buf[5]=50 as u8; buf[6]=0 as u8; buf[7]=0 as u8 2800 ss_wr32(buf, 8, 3); ss_wr32(buf, 12, nt) 2801 var L: i64 = 0 2802 while L < 3 { 2803 let lb: i64 = 16 + L*24 2804 var q: i64 = 0 2805 while q < 16 { buf[lb+q]=0 as u8; q=q+1 } 2806 if L==2 { buf[lb]=98 as u8; buf[lb+1]=111 as u8; buf[lb+2]=110 as u8; buf[lb+3]=101 as u8 } 2807 if L==2 { ss_wr32(buf, lb+16, 0); ss_wr32(buf, lb+20, nt) } else { ss_wr32(buf, lb+16, 0); ss_wr32(buf, lb+20, 0) } 2808 L = L + 1 2809 } 2810 var t: i64 = 0 2811 while t < nt { 2812 let o: i64 = hdr + t*84 2813 let ia: i64 = tm_ta(t); let ib: i64 = tm_tb(t); let ic: i64 = tm_tc(t) 2814 ss_wr32(buf, o, ss_f32(tm_vx(ia),1)); ss_wr32(buf, o+4, ss_f32(tm_vy(ia),1)); ss_wr32(buf, o+8, ss_f32(tm_vz(ia),1)) 2815 ss_wr32(buf, o+12, ss_f32(tm_vx(ib),1)); ss_wr32(buf, o+16, ss_f32(tm_vy(ib),1)); ss_wr32(buf, o+20, ss_f32(tm_vz(ib),1)) 2816 ss_wr32(buf, o+24, ss_f32(tm_vx(ic),1)); ss_wr32(buf, o+28, ss_f32(tm_vy(ic),1)); ss_wr32(buf, o+32, ss_f32(tm_vz(ic),1)) 2817 // ⚠surface_nets writes gradient normals at 4096 scale (nx_isosurf.nx:68), NOT the Q14 16384 the 2818 // mesh format uses elsewhere. Reading them as Q14 made every normal a QUARTER length, so the 2819 // lambert term collapsed and the whole surface rendered dark and mottled -- which I spent three 2820 // passes blaming on the ellipsoid, the rasterizer and the z-buffer in turn. 2821 ss_wr32(buf, o+36, ss_f32(tm_vnx(ia),SS_NQ)); ss_wr32(buf, o+40, ss_f32(tm_vny(ia),SS_NQ)); ss_wr32(buf, o+44, ss_f32(tm_vnz(ia),SS_NQ)) 2822 ss_wr32(buf, o+48, ss_f32(tm_vnx(ib),SS_NQ)); ss_wr32(buf, o+52, ss_f32(tm_vny(ib),SS_NQ)); ss_wr32(buf, o+56, ss_f32(tm_vnz(ib),SS_NQ)) 2823 ss_wr32(buf, o+60, ss_f32(tm_vnx(ic),SS_NQ)); ss_wr32(buf, o+64, ss_f32(tm_vny(ic),SS_NQ)); ss_wr32(buf, o+68, ss_f32(tm_vnz(ic),SS_NQ)) 2824 ss_wr32(buf, o+72, ss_f32(910,1000)); ss_wr32(buf, o+76, ss_f32(890,1000)); ss_wr32(buf, o+80, ss_f32(845,1000)) 2825 ss_wr32(buf, hdr + nt*84 + t*4, 2) 2826 t = t + 1 2827 } 2828 let fd: i64 = sys_openat_wr(argv[1] as *u8, 420) 2829 sys_write(fd, buf, bytes) 2830 sys_close(fd) 2831 2832 // ★MEASURE THE RESULT AGAINST THE REFERENCE, in the organ, every run. The scale defect shipped to a 2833 // published page because nothing compared the emitted skull to the 151x209x215mm it is meant to be. 2834 var lox: i64 = 0; var hix: i64 = 0 2835 var loy: i64 = 0; var hiy: i64 = 0 2836 var loz: i64 = 0; var hiz: i64 = 0 2837 var vi: i64 = 0 2838 while vi < nv { 2839 let X: i64 = tm_vx(vi); let Y: i64 = tm_vy(vi); let Z: i64 = tm_vz(vi) 2840 if vi == 0 { lox=X; hix=X; loy=Y; hiy=Y; loz=Z; hiz=Z } else { 2841 if X < lox { lox = X } 2842 if X > hix { hix = X } 2843 if Y < loy { loy = Y } 2844 if Y > hiy { hiy = Y } 2845 if Z < loz { loz = Z } 2846 if Z > hiz { hiz = Z } 2847 } 2848 vi = vi + 1 2849 } 2850 let bw: i64 = hix-lox 2851 let bh: i64 = hiy-loy 2852 let bd: i64 = hiz-loz 2853 var fit: i64 = 1 2854 if ss_abs(bw - SS_REF_W) > SS_TOL { fit = 0 } 2855 if ss_abs(bh - SS_REF_H) > SS_TOL { fit = 0 } 2856 if ss_abs(bd - SS_REF_D) > SS_TOL { fit = 0 } 2857 ss_puts("{\x22organ\x22:\x22nx_skullsdf\x22,\x22bbox_mm\x22:[" as *u8); ss_pn(bw) 2858 ss_puts("," as *u8); ss_pn(bh); ss_puts("," as *u8); ss_pn(bd) 2859 ss_puts("],\x22reference_mm\x22:[" as *u8); ss_pn(SS_REF_W) 2860 ss_puts("," as *u8); ss_pn(SS_REF_H); ss_puts("," as *u8); ss_pn(SS_REF_D) 2861 ss_puts("],\x22dims_within_tolerance\x22:" as *u8); ss_pn(fit) 2862 ss_puts(",\x22grid\x22:" as *u8); ss_pn(G) 2863 ss_puts(",\x22cell\x22:" as *u8); ss_pn(cell) 2864 ss_puts(",\x22verts\x22:" as *u8); ss_pn(nv) 2865 ss_puts(",\x22tris\x22:" as *u8); ss_pn(nt) 2866 ss_puts(",\x22overflow\x22:" as *u8); ss_pn(tm_ovf()) 2867 ss_puts(",\x22fit_src\x22:" as *u8); ss_pn(SS_FITSRC) 2868 ss_puts(",\x22fit_n\x22:" as *u8); ss_pn(SS_FITN) 2869 ss_puts(",\x22res_scale\x22:" as *u8); ss_pn(SS_RESSC) 2870 ss_puts(",\x22method\x22:\x22smooth-union of bone primitives, orbits and nasal aperture SUBTRACTED as real openings, polygonized by surface_nets\x22}\n" as *u8) 2871 return 0 2872}