nx_cast_lit_surface_expanded_t181.nx source
↩ module page · 3776 lines · 262144 B
1// nx_shader_ir.nx -- THE SHADER IR: ONE source of truth, N dialect backends.
2//
3// WHY THIS EXISTS (measured 2026-08-23). The estate's shaders are hand-written GLSL string
4// literals inside nx_game_page_emit. Drawing characters on the WebGPU tier therefore demanded a
5// SECOND HAND COPY in WGSL -- ~600 lines (dual-quaternion skinning off a joint texture, instance
6// uniform arrays, the voxel occlusion march, the procedural anatomy/eye/hair/skin paint) of the
7// most actively-edited shader in the estate: three separate feature edits landed in it on the day
8// this was written. Two artifacts that must agree, kept in agreement by discipline, is the exact
9// shape the banked law forbids. This module is the construction that makes disagreement
10// IMPOSSIBLE: neither dialect is authored, both are EMITTED from this representation.
11//
12// HOUSE SHAPE. This mirrors the NishiLang compiler itself -- lex_source -> parse_module ->
13// opt_run -> {nx_compile_x86, nx_compile_wat}: one front-end representation, many backends.
14// nx_glsl.nx and nx_wgsl.nx are backends over this IR, not transpilers bolted to a call site.
15//
16// THE SOURCE OF TRUTH IS NISHILANG (operator, 2026-08-23: "we dont want python or glsl or
17// javascript or all that it should be nishi lang and nishi ecosystem from the first byte up each
18// rung gaining all these capabilities"). GLSL IS A TARGET, NOT AN INPUT. This is NOT a GLSL->WGSL
19// transpiler: translating would enshrine GLSL as the canonical language and make a foreign dialect
20// the artifact we maintain. A shader is authored ONCE in NishiLang; GLSL and WGSL are both OUTPUTS,
21// exactly as x86_64 and WAT are outputs of the same NishiLang front-end. The ~600 lines of GLSL in
22// MVS/MFS are therefore a MIGRATION TARGET, not the source: each rung expresses more of them in
23// NishiLang and PROVES the emitted GLSL equivalent to the hand-written GLSL that ships today.
24//
25// LADDER (each rung widens the covered subset; rung 1 is what this lane ships):
26// rung 1 the fullscreen-triangle vertex stage -- authored in NishiLang, emitting BOTH the GLSL
27// VSH and the WGSL vs that are hand-written and SHIPPING today, proven against them.
28// rung 2 lower the real NishiLang AST (nx_tokenizer/nx_parse) into this IR, so a shader is an
29// ordinary NishiLang function rather than builder calls -- the full 'target, not
30// translator' shape, sharing the front-end with nx_compile_x86 and the WAT lane.
31// rung 3 widen the subset to the MFS paint set; rung 4 the MVS skinning set; then the character
32// pass becomes a compile target and the WebGPU abstention flips from owed to shipped.
33//
34// THE SOURCE OF TRUTH IS NISHILANG (operator, 2026-08-23: "we dont want python or glsl or
35// javascript or all that it should be nishi lang and nishi ecosystem from the first byte up each
36// rung gaining all these capabilities"). GLSL IS A TARGET, NOT AN INPUT. This is NOT a GLSL->WGSL
37// transpiler: translating would enshrine GLSL as the canonical language and make a foreign dialect
38// the artifact we maintain. A shader is authored ONCE in NishiLang; GLSL and WGSL are both OUTPUTS,
39// exactly as x86_64 and WAT are outputs of the same NishiLang front-end. The ~600 lines of GLSL in
40// MVS/MFS are therefore a MIGRATION TARGET, not the source: each rung expresses more of them in
41// NishiLang and PROVES the emitted GLSL equivalent to the hand-written GLSL that ships today.
42//
43// LADDER (each rung widens the covered subset; rung 1 is what this lane ships):
44// rung 1 the fullscreen-triangle vertex stage -- authored in NishiLang, emitting BOTH the GLSL
45// VSH and the WGSL vs that are hand-written and SHIPPING today, proven against them.
46// rung 2 lower the real NishiLang AST (nx_tokenizer/nx_parse) into this IR, so a shader is an
47// ordinary NishiLang function rather than builder calls -- the full "target, not
48// translator" shape, sharing the front-end with nx_compile_x86 and the WAT lane.
49// rung 3 widen the subset to the MFS paint set; rung 4 the MVS skinning set; then the pass
50// itself becomes a compile target and the WebGPU character abstention flips to shipped.
51//
52// SCOPE IS DECLARED AND ENFORCED, NEVER SILENT. The node kinds below cover what MVS/MFS actually
53// use. A backend meeting anything outside the subset must call sir_refuse and return -1.
54// A NAMED REFUSAL IS A CONTRACT; A SILENT MISTRANSLATION IS THE WORST POSSIBLE FAILURE IN A
55// SHADER BACKEND -- it compiles, it runs, and it draws the wrong thing.
56//
57// NO FLOATING POINT IS USED OR NEEDED: the NishiLang toolchain carries no f32, and a shader
58// emitter never computes with literals -- it TRANSCRIBES them. Numeric literals live in the
59// string pool in canonical form ("0.0", never "0."), which is also what WGSL requires.
60
61// syscalls.nx -- thin __syscall wrappers used across modules.
62//
63// Sovereign path: no libc. Every memory allocation, file op, and
64// clock read in the rest of the runtime routes through one of these
65// helpers. Numbers match Linux RV64; NishiOS uses the same set.
66//
67// Extracted from runtime.nx and ir.nx's copy-pasted helpers so the
68// module-import build doesn't produce duplicate symbols.
69
70// Tier aliases (nx_size / nx_idx / nx_fd / ...) ride along with the
71// syscall shelf: 141 runtime files use `as nx_size` etc. and only
72// compiled historically because the old parser silently void-cast
73// unknown type names (T#nx-int-alias-size-0 closed that hole LOUDLY,
74// which exposed the missing import). nx_tier.nx is pure type
75// aliases (0 funcs); prepass_register_aliases skips duplicates, so
76// modules that also import it directly stay fine.
77// nx_tier.nx -- substrate-wide tier configuration.
78//
79// Single point of edit for scale-agnostic substrate. Per user
80// directive 2026-05-13: "with the i64 it looks hardcoded everywhere
81// if we really want this dynamic dont we want that to be a changeable
82// value everywhere so it can switch to i128 and i256 etc."
83//
84// Per cardinals:
85// - feedback-numeric-tier-ladder.md (N0..N9 swap)
86// - feedback-scale-agnostic-substrate.md (MCU..HPC swap)
87// - feedback-substrate-additive-not-restrictive.md (declare cost)
88//
89// SEMANTIC ALIASES (not all should swap simultaneously):
90//
91// nx_int -- DEFAULT ARITHMETIC integer. Swappable across the
92// numeric tier ladder. Swap this to i128 to make the
93// entire substrate compute in 128-bit integers.
94//
95// nx_size -- MEMORY-SIZE integer. Always platform-pointer-width.
96// Used for buffer sizes, mmap byte counts, struct
97// sizes. Does NOT swap with nx_int -- changing this
98// would break pointer arithmetic. Stays i64 on RV64.
99//
100// nx_idx -- ARRAY-INDEX integer. Same width as nx_size on
101// flat-memory targets. Distinct alias so future
102// GPU/distributed targets can change indexing without
103// touching arithmetic.
104//
105// nx_byte -- The byte type. Stays u8. Distinct alias so MCU
106// targets that emulate u16-byte memory could rebind.
107//
108// HARDWARE-TIER BUFFER SIZES (declare cost, don't restrict):
109//
110// NX_BUF_TINY -- 64 B (MCU-friendly; stack-safe)
111// NX_BUF_SMALL -- 256 B (MCU heap-friendly)
112// NX_BUF_MEDIUM -- 4096 B (page-size; workstation default)
113// NX_BUF_LARGE -- 64 KiB (server-friendly)
114// NX_BUF_HUGE -- 1 MiB (HPC; assumes virtual memory)
115//
116// Use these instead of `sys_mmap(4096)` etc. so the substrate
117// announces its memory footprint and tier-incompatible code can
118// be flagged by audit.
119//
120// HARDWARE TIER (informational; downstream code may branch):
121//
122// NX_TIER_MCU = 0 -- microcontroller, kilobytes RAM
123// NX_TIER_SOVEREIGN_CHIP = 1 -- custom silicon, ~MB RAM
124// NX_TIER_FAMILY_DEVICE = 2 -- phone/router, ~GB RAM
125// NX_TIER_WORKSTATION = 3 -- laptop/desktop, ~10-100 GB RAM
126// NX_TIER_SERVER = 4 -- server-class, ~TB RAM
127// NX_TIER_HPC = 5 -- cluster, distributed
128//
129// COMPILE-TIME SWAP for nx_int (uncomment exactly one line):
130
131// THIS FILE IS THE SINGLE DEFINITION SITE for substrate-wide types.
132// Per user directive 2026-05-13: only this file (and platform-ABI
133// definition files like nx_syscalls.nx) should declare bare i64.
134// Every other substrate module uses the aliases below.
135
136// ===== arithmetic-tier aliases (swappable per nx_int tier ladder) =====
137
138type nx_int = i64 // N1 -- default; 9 quintillion, fits all physical scales
139// type nx_int = i32 // N0 -- MCU / embedded
140// type nx_int = i128 // N2 -- queued; needs nx_i128 backend ops
141// type nx_int = i256 // N3 -- shipped (nx_i256.nx); cosmology / crypto
142
143// ===== platform-width aliases (stay at pointer width) =================
144
145type nx_size = i64 // memory-size / byte-count
146type nx_idx = i64 // array-index
147type nx_byte = u8 // single-byte unit
148
149// ===== POSIX/Linux platform-ABI aliases (mandated 64-bit on RV64) ====
150//
151// Each is a 64-bit integer by Linux RV64 ABI. Renamed here so substrate
152// code never writes bare `i64` for these semantic types.
153
154type nx_fd = i64 // file descriptor (kernel-mandated width)
155type nx_exit = i64 // exit / status code (main() return)
156type nx_pid = i64 // process id
157type nx_uid = i64 // user id
158type nx_gid = i64 // group id
159type nx_syscall_num = i64 // Linux syscall number
160type nx_off = i64 // file offset (off_t)
161type nx_errno = i64 // errno (negative on syscall failure)
162
163// ===== SEMANTIC TYPE GENEALOGY (added 2026-05-20) ======================
164//
165// Per cardinal [[feedback-type-genealogy-math-cardinal-not-script]]
166// AND its immediate refinement (same session): every alias collapsing
167// to i64 is "y2k incestuous" -- relabeling, not genealogy. Real
168// semantic types pick the APPROPRIATE underlying width based on
169// the physics of the values they represent:
170//
171// - Small sealed enums (15 outcomes, 18 probe kinds) -> u8
172// - Display pixel coords (~32M max realistic) -> i32
173// - Q10 / Q14 fixed-point (values * 1024 / 16384) -> i32
174// - 32-bit color packs (RGBA8888) -> u32
175// - Q20 fixed-point (values * 1048576) -> i64
176// - Wide color packs (RGBA16161616, PRESERVE_ALL) -> u64
177// - Timestamps (ns / us / ms / cycles) -> i64 (2038 Y2K38)
178// - 64-bit hash digests -> u64
179// - Cryptographic hashes (SHA-256, SHA-512) -> STRUCT (multi-word; queued)
180// - Virtual addresses on 64-bit ISA -> u64
181//
182// Each type is a child of its PHYSICALLY-APPROPRIATE parent
183// (i8/u8/i32/u32/i64/u64), not blanket-i64. This breaks the
184// y2k-incestuous trap where renaming i64 N ways pretends to be
185// type discipline while every value silently shares one width.
186
187// ----- TIME family (all i64; ns/us/ms/cycles legitimately need it) -----
188// 2038 Y2K38 lurks for 32-bit time_t; i64 is the substrate-honest
189// choice. ms/us/ns + cycles all i64. s_q14 needs only i32 range
190// (val*16384 fits comfortably in i32 for typical second scales) but
191// we stay at i64 to compose cleanly with the i64 time arithmetic
192// across the substrate.
193type nx_ns = i64 // nanoseconds (since boot, monotonic)
194type nx_us = i64 // microseconds (since boot, monotonic)
195type nx_ms = i64 // milliseconds (since epoch, wall)
196type nx_s_q14 = i64 // seconds in Q14 fixed-point
197type nx_cycles = i64 // CPU cycle count
198
199// ----- HASH family (non-cryptographic 64-bit; crypto = STRUCT) -----
200// FNV-1a / xxhash digest is u64 by spec. SHA-256 / SHA-512 / BLAKE
201// hashes are MULTI-WORD; they're declared as structs in
202// nx_sha256.nx / nx_sha512.nx / nx_blake2b.nx (each carries its own
203// fixed-size byte array; NOT i64).
204type nx_hash64 = u64 // FNV-1a / xxhash / truncated SHA -- 64-bit digest
205
206// ----- ETG family (sealed enums; small value space -> u8) -----
207// nx_outcome_id sealed enum has 11 values; u8 fits 256
208// nx_probe_kind sealed enum has 18 values; u8 fits 256
209// nx_claim_source sealed enum has 13 values; u8 fits 256
210// nx_silicon_serial is a content-addressed identity HASH; u64.
211type nx_outcome_id = u8 // NX_ETG_OUTCOME_* (11 values; u8 fits)
212type nx_probe_kind = u8 // NX_ETG_PROBE_* (18 values; u8 fits)
213type nx_claim_source = u8 // NX_ETG_CLAIM_* (13 values; u8 fits)
214type nx_silicon_serial = u64 // per-die identity hash (cryptographic-strength width)
215
216// ----- PERF family (sealed enums) -----
217type nx_pathology_id = u8 // NX_PERF_PATH_* (15 values; u8 fits)
218type nx_flow_state_id = u8 // NX_FLOW_STATE_* (6 values; u8 fits)
219
220// ----- FIXED-POINT family (width chosen by precision*range) -----
221// Q10: value * 1024. Typical seed values are 0..255 so q10 max is
222// ~261K; i32 holds up to ~2.1B -> plenty of headroom.
223// Q14: value * 16384. Typical max around 16K of seed -> q14 ~ 2.6e8;
224// i32 holds up to 2.1e9 -> headroom for a few decimal seconds.
225// Q20: value * 1048576. Wider precision; needs i64 to avoid wrap.
226type nx_q10 = i32 // val * 1024; ~0.001 precision
227type nx_q14 = i32 // val * 16384; ~6e-5 precision
228type nx_q20 = i64 // val * 1048576; ~1e-6 precision
229
230// ----- GRAPHICS family (display coords + color packs at real widths) -----
231// Modern displays are well within 32-bit pixel addressing.
232// 8K display = 7680x4320 pixels. i32 holds 2.1B -> plenty.
233// nx_color_rgba8 = 32-bit packed RGBA (the common case)
234// nx_color_rgba16 = 64-bit packed RGBA16161616 (HDR / wide gamut)
235type nx_pixel_x = i32 // screen X in pixels
236type nx_pixel_y = i32 // screen Y in pixels
237type nx_color_rgba8 = u32 // RGBA8888 packed
238type nx_color_rgba16 = u64 // RGBA16161616 packed (HDR / preserve-all)
239
240// ----- PERCEPTUAL family (sealed enum; small value space) -----
241// nx_perceptual_profile has ~40 declared values up through
242// NX_PERCEPT_PRESERVE_ALL = 9999. Sentinel value 9999 needs i16,
243// not u8. i16 fits -32768..32767 with room for sentinels.
244type nx_perceptual_profile = i16 // NX_PERCEPT_* (~40 values + 9999 sentinel)
245
246// ----- ADDRESS family (virtual addresses on 64-bit ISA) -----
247// Pointer-width is u64 on all our supported 64-bit targets
248// (RV64 / x86_64 / AArch64 / ppc64le / loongarch64 / mips64 /
249// s390x / RV32 uses u32 -- TODO: tier-conditional).
250type nx_addr = u64 // raw virtual address (caller casts to *u8)
251
252// nx_capability_manifest:
253// variant_class: tier_config
254// variant_id: tier_config_v1_global
255// requires_isa: [rv32i, rv32imac, rv64imac, rv64imacv, x86_64, aarch64, armv7a, cortex_m, avr, xtensa, wasm32]
256// requires_syscalls: []
257// requires_ram_min_b: 0 // pure-const + typedef module, no runtime cost
258// tier_floor: NX_TIER_MCU
259// tier_ceiling: NX_TIER_HPC
260// cost_model:
261// flops_per_n: 0.0
262// bytes_per_n: 0.0
263// syscalls_per_n: 0.0
264// adversary_class: THREAT_OPPORTUNISTIC
265//
266// Note: This file is the substrate's TIER ENUM SOURCE OF TRUTH. It
267// has no variants by design (it IS the variant_class taxonomy that
268// other primitives' tier_floor / tier_ceiling reference). Manifest
269// declared for hygiene completeness; selector will skip it.
270
271// ---- buffer-size constants (use instead of bare numbers) -------
272
273const NX_BUF_TINY: nx_size = 64
274const NX_BUF_SMALL: nx_size = 256
275const NX_BUF_MEDIUM: nx_size = 4096
276const NX_BUF_LARGE: nx_size = 65536
277const NX_BUF_HUGE: nx_size = 1048576
278
279// ---- hardware tier sentinels -----------------------------------
280
281const NX_TIER_MCU: nx_int = 0
282const NX_TIER_SOVEREIGN_CHIP: nx_int = 1
283const NX_TIER_FAMILY_DEVICE: nx_int = 2
284const NX_TIER_WORKSTATION: nx_int = 3
285const NX_TIER_SERVER: nx_int = 4
286const NX_TIER_HPC: nx_int = 5
287
288// ---- numeric tier sentinels (informational) --------------------
289
290const NX_NUM_N0_I32: nx_int = 0
291const NX_NUM_N1_I64: nx_int = 1
292const NX_NUM_N2_I128: nx_int = 2
293const NX_NUM_N3_I256: nx_int = 3
294const NX_NUM_N4_I512: nx_int = 4
295const NX_NUM_N5_BIGINT: nx_int = 5
296
297// ---- byte-width of substrate types (replace bare `8` / `4`) ----
298//
299// Use these wherever you need the byte count of a substrate type --
300// e.g., sys_mmap(N * NX_SIZEOF_NX_SIZE) to allocate N nx_size slots.
301// Swap nx_int's underlying type and ONLY this constant changes.
302
303const NX_SIZEOF_NX_INT: nx_size = 8 // nx_int currently i64 -> 8 bytes
304const NX_SIZEOF_NX_SIZE: nx_size = 8 // nx_size always pointer-width
305const NX_SIZEOF_NX_IDX: nx_size = 8 // nx_idx alias of nx_size
306
307// ---- POSIX stdio file descriptors (replace bare 0/1/2) ---------
308
309const NX_FD_STDIN: nx_fd = 0
310const NX_FD_STDOUT: nx_fd = 1
311const NX_FD_STDERR: nx_fd = 2
312
313const SYS_MAGIC_1024: i64 = 1024
314const SYS_MAGIC_1000000: i64 = 1000000
315const SYS_MAGIC_4294967296: i64 = 4294967296
316// first read window for a size-UNKNOWABLE file (lseek END <= 0); doubles while it fills -- see sys_read_file
317const SYS_READ_GROW_INIT: i64 = 65536
318const SYS_MAGIC_100000: i64 = 100000
319
320// ---- syscall numbers (per-target) ----
321//
322// Cross-target via the macro processor (cardinal landed 2026-05-20:
323// feedback-hardware-agnostic-is-robustness -- the substrate must
324// compile + run on every silicon we point it at). Default path
325// (TARGET_X86_64 not defined) carries Linux RV64 numbers used by
326// qemu-RV64 + NishiOS. When nxc2 is invoked with --target x86_64
327// main.c pre-defines @macro TARGET_X86_64 1 so this file resolves
328// to x86_64 Linux ABI numbers.
329//
330// nx_syscalls_x86_64.nx remains the dedicated x86_64-only mirror
331// for files that want explicit single-target imports (e.g., bench
332// smokes built only for x86_64). This block makes nx_syscalls.nx
333// itself dual-target so substrate primitives compile portably.
334
335@ifdef TARGET_X86_64
336const SYS_READ: i64 = 0
337const SYS_WRITE: i64 = 1
338const SYS_CLOSE: i64 = 3
339const SYS_LSEEK: i64 = 8
340const SYS_OPENAT: i64 = 257
341const SYS_EXIT: i64 = 60
342const SYS_MMAP: i64 = 9
343const SYS_CLOCK_GETTIME: i64 = 228
344const SYS_IOCTL: i64 = 16
345const SYS_CLOCK_NANOSLEEP: i64 = 230
346// Namespace/container family, x86 branch (debt 1785528831). Moved here from
347// nx_syscalls_x86_64.nx so ONE module owns the wrapper set -- a TU reaching both
348// modules used to hold every wrapper TWICE, resolved silently by definition ORDER.
349const SYS_CHROOT: i64 = 161
350const SYS_MOUNT: i64 = 165
351const SYS_UNSHARE: i64 = 272
352const SYS_GETUID: i64 = 102
353const SYS_GETGID: i64 = 104
354const SYS_POLL: i64 = 7
355@endif
356
357@ifndef TARGET_X86_64
358const SYS_READ: i64 = 63
359const SYS_WRITE: i64 = 64
360const SYS_CLOSE: i64 = 57
361const SYS_LSEEK: i64 = 62
362const SYS_OPENAT: i64 = 56
363const SYS_EXIT: i64 = 93
364const SYS_MMAP: i64 = 222
365const SYS_CLOCK_GETTIME: i64 = 113
366const SYS_IOCTL: i64 = 29
367const SYS_CLOCK_NANOSLEEP: i64 = 115
368// Namespace/container family, RV64 branch (debt 1785528831). This is the branch actually
369// KEPT (TARGET_X86_64 is hard-pinned undefined), so these are the numbers the x86 backend
370// translates at emit: 51->161 chroot, 40->165 mount, 97->272 unshare, 174->102 getuid,
371// 176->104 getgid. The 40 and 51 rows were added to x86ctx_rv64_to_x86_64_syscall and
372// shipped FIRST -- without them both would pass through to the WRONG x86 syscall
373// (sendfile / getsockname), silently, because that translator's default is `return num`.
374const SYS_CHROOT: i64 = 51
375const SYS_MOUNT: i64 = 40
376const SYS_UNSHARE: i64 = 97
377const SYS_GETUID: i64 = 174
378const SYS_GETGID: i64 = 176
379const SYS_POLL: i64 = 73
380@endif
381
382func sys_ioctl(fd: i64, request: i64, arg: i64) -> i64 {
383 return __syscall(SYS_IOCTL, fd, request, arg, 0, 0, 0)
384}
385
386// poll(2): wait for events on fds. fds points to an array of `nfds`
387// struct pollfd { i32 fd; i16 events; i16 revents } (8 bytes each).
388// timeout_ms < 0 = block forever, 0 = return immediately. Returns the
389// count of ready fds (>0), 0 on timeout, or -errno. Used by the
390// substrate's own network diagnostics (bounded non-blocking connect)
391// instead of reaching for external tools. (rv64 const = ppoll; this
392// wrapper only runs on the x86_64 target.)
393func sys_poll(fds: *u8, nfds: i64, timeout_ms: i64) -> i64 {
394 return __syscall(SYS_POLL, fds, nfds, timeout_ms, 0, 0, 0)
395}
396
397// ---- core wrappers ----
398
399func sys_write(fd: i64, buf: *u8, count: i64) -> i64 {
400 return __syscall(SYS_WRITE, fd, buf, count, 0, 0, 0)
401}
402
403func sys_read(fd: i64, buf: *u8, count: i64) -> i64 {
404 return __syscall(SYS_READ, fd, buf, count, 0, 0, 0)
405}
406
407func sys_close(fd: i64) -> i64 {
408 return __syscall(SYS_CLOSE, fd, 0, 0, 0, 0, 0)
409}
410
411// chdir. The compiler only rv64->x86 translates CONSTANT syscall numbers (x86ctx_emit_syscall:
412// VK_CONST_INT); chdir is absent from that table, so a constant 49 falls through to x86_64 bind and a
413// constant 80 is mapped to fstat -- BOTH gave EBADF (PROBE-PROVEN by test_chdir). The documented escape
414// (nx_x86_64_ctx.nx:1004 "Runtime-computed syscall number -- load as-is") is to make op0 RUNTIME: a memory
415// load can't be folded to VK_CONST_INT, so the raw x86_64 number 80 passes through untranslated = real
416// chdir. Used by the supervisor to set a spawned daemon's CWD before execve. 0 on success, -errno on fail.
417func sys_chdir(path: *u8) -> i64 {
418 let nbox: *i64 = sys_mmap(16) as *i64
419 nbox[0] = 80 // x86_64 chdir, forced runtime so the rv64->x86 xlate is skipped
420 return __syscall(nbox[0], path as i64, 0, 0, 0, 0, 0)
421}
422
423// getcwd -- SAME runtime-number escape as sys_chdir directly above, for the same documented reason: the
424// rv64->x86 translator only rewrites CONSTANT syscall numbers, and getcwd is absent from that table, so a
425// constant would be mangled exactly as chdir's was. A memory load cannot be folded to VK_CONST_INT, so the
426// raw x86_64 number passes through untranslated.
427// WHY THIS EXISTS (2026-08-14): the shim had sys_chdir but NOTHING to ask where we are. Every organ that
428// resolves a path against the CWD could therefore only print a RELATIVE path -- a claim whose truth depends
429// on invisible state. Three separate working-directory faults in one session stayed invisible until they
430// bit, and in each the reader could not tell "the file is missing" from "I am standing somewhere else".
431// ★★★AN ORGAN THAT CANNOT REPORT WHERE IT IS CANNOT WRITE AN HONEST PATH.
432// Returns the byte length written INCLUDING the terminator, or -errno (notably -ERANGE if cap is short).
433// SYS_PATH_MAX is exported so a caller never hand-writes the size: the FIRST consumer of sys_getcwd (this
434// author, minutes after adding it) wrote `sys_mmap(4096)` and `sys_getcwd(buf, 4096)` on consecutive
435// lines -- a bare literal AND a duplicate-authored pair, the exact shape being removed elsewhere the same
436// day. ★★A NEW PRIMITIVE THAT DOES NOT EXPORT ITS OWN SIZE INVITES EVERY CALLER TO INVENT ONE.
437const SYS_PATH_MAX: i64 = 4096 // Linux PATH_MAX; getcwd returns -ERANGE below it
438// The DIRECTORY sibling of MODE_0644, added on the same evidence: `0x1ed` appears at 569 sites in
439// buildroot/runtime (nx_shelltool, corpus_complete=1), i.e. the estate scatters TWO file-mode constants,
440// not one. Named here so the pair lives together and a reader meets both at the same place.
441const MODE_0755: i64 = 0x1ed // rwxr-xr-x : default mode for a created directory
442func sys_getcwd(buf: *u8, cap: i64) -> i64 {
443 let nbox: *i64 = sys_mmap(16) as *i64
444 nbox[0] = 79 // x86_64 getcwd, forced runtime so the rv64->x86 xlate is skipped
445 return __syscall(nbox[0], buf as i64, cap, 0, 0, 0, 0)
446}
447
448// ⚠AT_FDCWD MOVED UP 2026-07-20 -- IT WAS A LIVE MISCOMPILE. This const was declared ~60 lines BELOW
449// (in the openat block) while sys_unlinkat and sys_fchmodat immediately below REFERENCE it. A module
450// const referenced ABOVE its declaration does not resolve, and nx_cc silently substituted CONSTANT 0
451// -- so both wrappers passed dirfd=0 (stdin) instead of -100. Absolute paths survive that (openat
452// ignores dirfd when the path is absolute), RELATIVE paths do not, which is exactly why unlinkat was
453// long recorded as flaky and "passing only by luck". Surfaced by the new unknown-identifier
454// diagnostic, which turned a silent 0 into a compile error. LAW (already banked, now enforced):
455// module-wide consts/statics go ABOVE every possible reader.
456const AT_FDCWD: i64 = -100
457
458// unlinkat(AT_FDCWD, path, 0) -- delete a file. x86_64 263 is a PROVEN pass-through (not an rv64 key),
459// but this is THE canonical home: 5+ organs hand-rolled `__syscall(263,...)` before this landed (DRY,
460// 2026-07-20). 0 on success, -errno on fail.
461func sys_unlinkat(path: *u8) -> i64 {
462 return __syscall(263, AT_FDCWD, path as i64, 0, 0, 0, 0)
463}
464
465// fchmodat(AT_FDCWD, path, mode) -- chmod by path. ⚠a CONSTANT 268 gets rv64->x86 TRANSLATED to the
466// wrong syscall (silent no-op chmod -- cost a vacuous-permission-test debug cycle, 2026-07-20), so the
467// number is forced RUNTIME via the sys_chdir nbox pattern. 0 on success, -errno on fail.
468func sys_fchmodat(path: *u8, mode: i64) -> i64 {
469 let nbox: *i64 = sys_mmap(16) as *i64
470 nbox[0] = 268 // x86_64 fchmodat, forced runtime so the xlate is skipped
471 return __syscall(nbox[0], AT_FDCWD, path as i64, mode, 0, 0, 0)
472}
473
474// exit_group(2) -- terminate ALL tasks in the thread group. Raw x86_64 231
475// (231 is NOT an rv64 key in the compiler's swap table, so it passes through
476// untranslated -- the munmap-11 precedent). THE explicit program-exit call
477// once a process holds live nx_thread_pool workers: CLONE_VM tasks are
478// separate PIDs, so plain sys_exit (93 -> x86 60, single task) leaves them
479// running, holding stdout open and wedging any pipeline that waits for EOF
480// (found 2026-07-07: the shared-pool matmul dispatcher hung the build lane
481// this way). Return-from-main already exit_groups via the _start trampoline;
482// use THIS for explicit early program exit. Per-THREAD exit stays sys_exit
483// (see nx_thread_exit).
484func sys_exit_group(code: i64) -> i64 {
485 return __syscall(231, code, 0, 0, 0, 0, 0)
486}
487
488// setpriority(PRIO_PROCESS=0, who=0 -> SELF, prio) -- x86_64 syscall 141.
489// Lower priority = larger nice value; 19 is the maximum yield.
490// WHY A WRAPPER AND NOT AN OPERATOR STEP (measured 2026-07-30): a bulk media
491// migration walk saturated the NAS; every forked organ queued behind its I/O so
492// EVERY agent MCP call 503'd for minutes -- the control plane went blind while a
493// background job did exactly what it was told. `renice 19` on the running pid
494// restored interactive service at once.
495// LAW: a long-running BULK job must yield to the interactive control plane BY
496// CONSTRUCTION at its own launch, not when an operator notices. Bind it to the
497// one act every bulk job performs (its startup) and nothing has to remember it.
498// WARN: `ionice` does NOT exist on the Synology busybox, so the I/O-class lever
499// is unavailable; CPU nice sufficed because the walk is SHA-256-bound over
500// cached reads (state R, not D, once niced).
501func sys_setpriority(prio: i64) -> i64 {
502 return __syscall(141, 0, 0, prio, 0, 0, 0)
503}
504
505// ADDITIVE TWIN 2026-08-04 (nx_resgov): re-nice ANOTHER process by pid. The incumbent above pins
506// who=0 = "me", so it cannot deprioritise a runaway -- and a governor that can only slow ITSELF has
507// no graceful rung between "observe" and "kill". PRIO_PROCESS=0, who=pid. Existing callers untouched
508// (rule 19: add the new entry point, never re-shape the one in service).
509func sys_setpriority_of(pid: i64, prio: i64) -> i64 {
510 return __syscall(141, 0, pid, prio, 0, 0, 0)
511}
512
513// munmap -- free a region from sys_mmap. x86_64 munmap = 11; 11 is NOT an rv64 number in the compiler's
514// swap table, so the literal passes through untranslated = real munmap (unlike chdir, where rv64 80=fstat
515// intercepted it). CRITICAL for long-running loops: the supervisor's per-poll proc_* scans mmap 64KB+ each;
516// unfreed, the leak hits DSM's RLIMIT_AS -> mmap returns -12 -> the code writes through it -> SEGFAULT
517// (dmesg-proven: nx_hostctl segfault at 0xfffffffffffffff4). Free scan buffers to keep the supervisor alive.
518// ===== SMALL-ALLOCATION BUMP ARENA (2026-08-06, debt 1785516350 / 1786055008) =====================
519// MEASURED FIRST, THEN BUILT. nx_arena_probe: 20,000 x sys_mmap(32) -> VmSize 80,172 kB,
520// VmRSS 80,024 kB. 640 KB of requested data cost 78 MB of RESIDENT memory -- 4096 bytes per 32-byte
521// request, exactly one page and one kernel VMA each. Across the corpus nx_mmapbal deep counts 17,157
522// functions / 43,498 sites that allocate and never return, so this multiplier is the actual shape of
523// the leak: the call sites are not individually wrong so much as individually EXPENSIVE.
524//
525// One VMA per call is also a HARD CORRECTNESS CEILING, not just a memory cost: vm.max_map_count
526// defaults to 65530, after which mmap returns -ENOMEM and callers write through the failed pointer.
527// That is precisely the dmesg-proven nx_hostctl SEGFAULT at 0xfffffffffffffff4 described below.
528//
529// SO: requests <= NXA_SMALL_MAX are bump-allocated out of a 256 KiB chunk (one VMA per ~5,400 small
530// allocations instead of one per allocation). Larger requests take the ORIGINAL path untouched --
531// they are the ones plausibly relying on page alignment, and they are not where the leak lives.
532//
533// THE ZEROING CONTRACT IS LOAD-BEARING AND IS PRESERVED BY NEVER RECYCLING. Callers rely on mmap
534// returning zeroed memory (nx_mmapbal: "mmap zeroes, so an untouched slot reads empty with no init
535// loop"). Bytes handed out here come from a freshly mmapped chunk and are NEVER handed out twice, so
536// every region is zero-filled exactly as before. LIFO give-back on munmap was deliberately REJECTED:
537// it would recover memory but hand back dirty bytes, silently breaking every caller that trusts the
538// zero -- a correctness regression traded for a memory win, which is the wrong trade.
539//
540// KNOWN TRADE-OFF, stated rather than hidden: small allocations are now ADJACENT within a chunk
541// instead of isolated in their own pages. An overrun that today walks off the end of a page and
542// SIGSEGVs loudly may instead corrupt a neighbouring allocation quietly. NXA_GAP puts slack between
543// allocations and NXA_SMALL_MAX is kept deliberately low to bound the exposure, but the risk is real
544// and is the reason this starts at 256 rather than a page.
545// ---- MEMORY ORDERING, THE ONE DEFINITION -------------------------------------------------------
546// Moved here from nx_atom.nx on 2026-08-25 and DELETED from its two other copies
547// (nx_atomic_intrinsic_test, nx_simd_i32x8_test). Measured before the move, corpus_complete=1:
548// THREE files each declared NX_MO_SEQ_CST = 5 independently. A constant written in three places is
549// three rulers that agree until one of them does not.
550//
551// They live at THIS layer because the arena allocator below needs an ordering value for its own
552// lock, and this file cannot import nx_atom.nx -- nx_atom imports THIS file, so that direction is a
553// cycle. Everything that had these constants still has them: nx_atom.nx imports this file, and so
554// does every consumer of nx_atom.
555//
556// The __atomic_* forms these feed are COMPILER INTRINSICS, not library calls, so this file can use
557// them with no import at all. Verified in nx_x86_64_ctx rather than assumed: __atomic_cas_i64 emits
558// `lock cmpxchgq`, __atomic_faa_i64 emits `lock xaddq`, __atomic_fence emits `mfence`. On x86-64 the
559// ordering operand is not consulted by the emitter because those instructions are full barriers
560// regardless; it is carried for the RV64A backend, where it selects the aq/rl bits.
561const NX_MO_RELAXED: i64 = 0
562const NX_MO_CONSUME: i64 = 1
563const NX_MO_ACQUIRE: i64 = 2
564const NX_MO_RELEASE: i64 = 3
565const NX_MO_ACQ_REL: i64 = 4
566const NX_MO_SEQ_CST: i64 = 5
567
568const NXA_SMALL_MAX: i64 = 256
569const NXA_CHUNK: i64 = 262144
570const NXA_ALIGN: i64 = 16
571const NXA_GAP: i64 = 16
572const NXA_STATE: i64 = 4096
573// RING CANARY (temporary diagnostic): the single-slot canary checked only the immediately
574// previous allocation and reported ZERO overruns -- but the bisection proved the write is
575// DELAYED, landing after later allocations have been served. Track the last NXA_RING
576// allocations and re-verify every one of them on each call. Lives at i64 slot NXA_RBASE in
577// the state page; the reporter borrows bytes 64/128, so 512 is clear of it.
578const NXA_RING: i64 = 128
579const NXA_RBASE: i64 = 64
580// ---- ARENA MARK/RESET (2026-08-12, additive; the durable fix for bump-without-reset). The arena
581// abandons a full chunk on rollover, so a long-running accept loop accumulates chunks into one giant
582// coalesced VMA (hub_gw MEASURED 3.4GB over 64k requests). A daemon marks the arena AFTER startup and
583// resets at its accept-loop's quiescent point; reset munmaps every chunk allocated since the mark and
584// zeroes the marked chunk's reclaimed tail, so per-request small allocations reuse a bounded slab.
585// State slots (state page is 512 i64): [3]=chunk_count [4]=mark_valid [5]=mark_bump [6]=mark_chunk_end
586// [7]=mark_chunk_count; the chunk-base list lives at slots NXA_CHUNKBASE..+NXA_CHUNKMAX (clear of the
587// ring at 64..320 and the reporter scratch below 64). CONTRACT: the caller guarantees NO arena
588// allocation made after the mark is still referenced at reset (the accept-loop top, where the previous
589// request's frames have all returned -- the same quiescent point ss_cache_reap already uses). LARGE
590// (>NXA_SMALL_MAX) allocations take their own VMA and are NOT tracked here; a per-request large mmap
591// still needs its own munmap. Untracked-overflow (>NXA_CHUNKMAX chunks between resets) degrades to the
592// old leak for the excess, never corrupts.
593// ---- ARENA MUTUAL EXCLUSION (2026-08-25) -------------------------------------------------------
594// THE DEFECT: the bump-pointer advance below was a plain read-modify-write --
595// let p: i64 = nxa_st[0]
596// nxa_st[0] = p + need
597// -- so two threads that read nxa_st[0] before either wrote it BOTH RECEIVE THE SAME POINTER and
598// then write over each other. The chunk refill, the ring-canary scan and the nxa_st[2] counter have
599// the same shape. MEASURED while shipping structured concurrency: eight pool workers calling a
600// helper that allocates a 16-byte timespec raced this cursor and produced ARENA-OVERRUN
601// prev_alloc_size=16 followed by SIGSEGV. It generalises to EVERY small allocation from more than
602// one thread, which is why the scoped-spawn child body was written to allocate nothing at all.
603//
604// WHY A LOCK AND NOT A LOCK-FREE BUMP. A fetch-and-add on the cursor fixes only the fast path; two
605// threads can still both observe the chunk exhausted and both refill, and the canary ring and the
606// counter would still race. One lock over the whole mutable region is correct by inspection, which
607// on the allocator that every organ in the estate calls is worth more than a clever fast path.
608// THE COST IS NOT THE DOMINANT COST HERE: this function ALREADY walks all NXA_RING canary slots on
609// every allocation, so one uncontended `lock cmpxchgq` is far below the noise of work already done.
610//
611// SLOT 4 IS FREE BY THE LAYOUT ABOVE: [0] cursor, [1] limit, [2] ring counter, [3] chunk count, and
612// the ring starts at NXA_RBASE=64. It is also clear of the byte-64 and byte-128 scratch that
613// nxa_report_overrun formats digits into (slots 8 and 16), which slot 4 (bytes 32-39) does not touch.
614const NXA_LOCK: i64 = 4
615// A BOUND ON AN UNKNOWABLE WAIT, DERIVED RATHER THAN PICKED, AND ITS EXHAUSTION ANNOUNCES. The
616// longest thing the critical section can do is the NXA_RING canary scan plus one mmap, so a spin far
617// beyond that is not contention -- it is a holder that is never coming back. Eight times the ring
618// gives an order of magnitude of headroom over the longest legitimate hold; on reaching it the
619// allocator SAYS SO on stderr once and keeps waiting, because hanging visibly is recoverable and
620// corrupting silently is not, and dying inside the allocator would take down a process that may be
621// merely slow.
622const NXA_LOCK_WARN: i64 = NXA_RING * 8
623// Slot 5: "the contention hint has already been printed by this process". Also free by the layout
624// above and clear of every scratch region. It is a FLAG, not a counter, and it is set through a CAS
625// so the once-ness is itself race-free rather than depending on the lock it reports about.
626const NXA_LOCK_WARNED: i64 = 5
627
628const NXA_CHUNKBASE: i64 = 320
629const NXA_CHUNKMAX: i64 = 192
630
631// [0] = next free byte, [1] = one past the end of the current chunk. A static POINTER to a real
632// mmapped page rather than scalar statics, matching the idiom the corpus already proves; the state
633// page is taken through __syscall directly so this can never recurse into itself.
634static nxa_st: *i64
635
636// munmap -- free a region from sys_mmap. x86_64 munmap = 11; 11 is NOT an rv64 number in the compiler's
637// swap table, so the literal passes through untranslated = real munmap (unlike chdir, where rv64 80=fstat
638// intercepted it). CRITICAL for long-running loops: the supervisor's per-poll proc_* scans mmap 64KB+ each;
639// unfreed, the leak hits DSM's RLIMIT_AS -> mmap returns -12 -> the code writes through it -> SEGFAULT
640// (dmesg-proven: nx_hostctl segfault at 0xfffffffffffffff4). Free scan buffers to keep the supervisor alive.
641//
642// A small len means the region came from the bump arena above, because sys_mmap routes by the SAME
643// threshold. Unmapping an interior pointer would tear a hole in a chunk still holding other callers'
644// live allocations, so it is a no-op here. Balanced small callers therefore no longer return memory --
645// but they now cost ~48 bytes instead of 4096, so the arena wins by two orders of magnitude even
646// against code that was already correct.
647// Matching release for sys_mmap_try and other whole kernel mappings.
648// Never pass an arena allocation from sys_mmap: its small pointers may be interior.
649// Preserve the requested mapping length; the kernel applies its page rounding.
650const NXA_MAP_INVALID:i64=0-22 // Linux EINVAL, a protocol value rather than a resource budget.
651func sys_munmap_direct(addr:*u8,len:i64)->i64{
652 if (addr as i64)<=0||len<=0{return NXA_MAP_INVALID}
653 return __syscall(11,addr as i64,len,0,0,0,0)
654}
655
656func sys_munmap(addr: *u8, len: i64) -> i64 {
657 if len <= NXA_SMALL_MAX { return 0 }
658 return __syscall(11, addr as i64, len, 0, 0, 0, 0)
659}
660
661// Seek within a file. whence: 0=SEEK_SET, 1=SEEK_CUR, 2=SEEK_END.
662// Returns new file offset on success, -errno on failure.
663func sys_lseek(fd: i64, offset: i64, whence: i64) -> i64 {
664 return __syscall(SYS_LSEEK, fd, offset, whence, 0, 0, 0)
665}
666
667// ---- FILESYSTEM SPACE: THE AXIS THE ESTATE DID NOT HAVE (2026-08-28) -----------------------------
668// WHY THIS IS HERE AND NOT LEFT WHERE IT WAS. On 2026-08-28 a 100%-FULL DISK truncated a sibling seat's
669// MEMORY.md to 0 bytes -- open(path,"w") truncates before it writes, so a full volume does not refuse a
670// write, it DESTROYS the file. Nothing in the estate saw it coming: nx_resmon is "the resource axis
671// nx_health lacks" for MEMORY and SWAP, and a search for the disk primitive returned matches=0 for BOTH
672// sys_statfs and statvfs with corpus_complete=1. nx_res_census records the same absence in its own header.
673// The capability was not missing, it was DARK: nx_system_triage.tr_free_gb has read filesystem space since
674// 2026-06-10, in an _hdl_build organ that is NOT REGISTERED (nx_job_run refuses it as "not an unpinned
675// GREEN tool"), so the one instrument that could have warned was unreachable by any caller.
676// A CAPABILITY THAT EXISTS IN ONE UNREACHABLE ORGAN IS INDISTINGUISHABLE FROM ONE NOBODY BUILT.
677//
678// WHY THE RAW 137 AND NOT A SYS_ CONST. This file's dual-arch blocks are gated on TARGET_X86_64, which is
679// HARD-PINNED UNDEFINED, so the RV64 branch is what compiles and the x86 backend translates each number at
680// emit through x86ctx_rv64_to_x86_64_syscall -- whose default is `return num`. There is NO row for RV64 43
681// (statfs), so a SYS_STATFS=43 const would pass through unmapped to x86_64 43 = ACCEPT: a different
682// syscall, silently, on a path pointer. That is not a hypothesis -- nx_system_triage PROBE-PROVED it on
683// 2026-06-10: "rv64 43 returns -9 through the translation table; 137 raw matches df exactly." So 137 is
684// the MEASURED-CORRECT number for the target we actually emit, and it is named here ONCE instead of
685// sitting as a bare literal at each call site.
686// ⚠NAMED FOLLOW-UP, conflict-checked and deliberately NOT taken here: adding `if num == 43 { return 137 }`
687// to x86ctx_rv64_to_x86_64_syscall would make the arch-correct const work too. Nothing passes 43 as an x86
688// number (43 appears only as a translation TARGET, from RV64 202 accept), so the row is safe -- but it is a
689// COMPILER change that activates only on the next nx_cc self-host rebuild, and the working path needs none.
690//
691// struct statfs (x86_64) as i64 slots: 0 f_type, 1 f_bsize, 2 f_blocks, 3 f_bfree, 4 f_bavail, 5 f_files.
692// f_bavail (not f_bfree) is the honest number for "will my write succeed": it excludes the root reserve, so
693// it reports FULLER than root would see. Wrong in the safe direction, and said out loud rather than implied.
694// ⚠THE IMPRECISION, MEASURED AND NAMED SO NOBODY LATER "FIXES" IT INTO AGREEING WITH df: this permil is
695// NOT df's Use%. df computes Used/(Used+Available), which EXCLUDES the root-reserved blocks from its
696// denominator; this computes (blocks-bavail)/blocks, which counts the reserve as used. VERIFIED against df
697// on 2026-08-28: avail_bytes came back 958449582080, which is EXACTLY df's Available of 935985920 KiB, while
698// the same volume read 113 permil here and 7% there -- both correct, measuring different things. Both reach
699// their maximum at the SAME event (bavail = 0), so a threshold calibrated against THIS metric alarms at the
700// same moment a writer actually hits the wall; it simply sits higher below that. Calibrate thresholds to
701// this definition, and do not import a df-derived number as if it were the same quantity.
702const SYS_STATFS_X86_MEASURED: i64 = 137
703const STATFS_BUF_BYTES: i64 = 144
704const STATFS_I_BSIZE: i64 = 1
705const STATFS_I_BLOCKS: i64 = 2
706const STATFS_I_BAVAIL: i64 = 4
707const STATFS_PERMIL: i64 = 1000
708const STATFS_ERR: i64 = 0 - 1
709
710// raw statfs into a caller-supplied 144-byte buffer. 0 = ok, non-zero = the kernel's negative errno.
711func sys_statfs(path: *u8, buf: *i64) -> i64 {
712 return __syscall(SYS_STATFS_X86_MEASURED, path, buf, 0, 0, 0, 0)
713}
714
715// bytes available to a non-root writer on the filesystem holding `path`; STATFS_ERR if statfs failed.
716func sys_fs_avail_bytes(path: *u8) -> i64 {
717 let buf: *i64 = sys_mmap(STATFS_BUF_BYTES) as *i64
718 if sys_statfs(path, buf) != 0 { return STATFS_ERR }
719 return buf[STATFS_I_BSIZE] * buf[STATFS_I_BAVAIL]
720}
721
722// USED per-mille of the filesystem holding `path`, counted against what a non-root writer can reach:
723// (blocks - bavail) * 1000 / blocks. STATFS_ERR if statfs failed or the volume reports zero blocks --
724// an UNMEASURABLE volume must never read as 0 permil used, which is the most flattering possible lie.
725func sys_fs_used_permil(path: *u8) -> i64 {
726 let buf: *i64 = sys_mmap(STATFS_BUF_BYTES) as *i64
727 if sys_statfs(path, buf) != 0 { return STATFS_ERR }
728 let blocks: i64 = buf[STATFS_I_BLOCKS]
729 if blocks <= 0 { return STATFS_ERR }
730 let avail: i64 = buf[STATFS_I_BAVAIL]
731 return ((blocks - avail) * STATFS_PERMIL) / blocks
732}
733
734func sys_exit(code: i64) -> i64 {
735 return __syscall(SYS_EXIT, code, 0, 0, 0, 0, 0)
736}
737
738// mmap anonymous R/W memory; returns raw bytes. Fixed flags:
739// PROT_READ|PROT_WRITE = 3, MAP_PRIVATE|MAP_ANONYMOUS = 0x22, fd=-1.
740// FAIL-CLOSED ON A REFUSED MAPPING (2026-08-07). MEASURED: the corpus has 90,817 sys_mmap call sites
741// and SIX of them check the result -- all six in test probes whose response is sys_exit anyway. So
742// 90,811 sites take whatever this returns and write through it. When the kernel refuses, that value is
743// -errno, and the write lands at 0xfffffffffffffff4 (-12, ENOMEM). That is not a hypothetical: dmesg
744// on this host recorded it hourly in nx_web_shard_compact, and 18 times in nx_web_crawl_step.
745// Returning a poisoned pointer to 90,811 unguarded callers is the defect. Dying here is strictly safer
746// than dying there: the process ends either way, but this way there is no memory corruption first and
747// the failure is NAMED instead of arriving as a bare segfault address an operator has to decode.
748// This is the never-brick shape -- fail-safe BY CONSTRUCTION, not by every caller remembering.
749// KNOWN COST, stated: nx_mmap_probe / test_munmap deliberately provoke a refusal to observe it. They
750// now exit here with code 12 rather than printing their own verdict. Six probes lose a diagnostic;
751// 90,811 sites stop corrupting memory.
752// ===== TEMPORARY DIAGNOSTIC -- ARENA OVERRUN CANARY (2026-08-07) =====================================
753// ⛔DO NOT BLESS A COMPILER BUILT WITH THIS. The canary writes 0xC7 into the NXA_GAP slack that a
754// caller could otherwise legitimately read as zeros, so it changes observable behaviour for any code
755// that reads past its declared size -- which is precisely the code being hunted.
756// PURPOSE: at NXA_SMALL_MAX=256 the compiler produces 14 SPURIOUS type diagnostics (it reports
757// `arg 2 is an INTEGER but the parameter is a POINTER` against a parameter DECLARED `j: *u8`), i.e.
758// something writes past its allocation and corrupts the parser's type table. At threshold 64 the same
759// requests each get a 4096-byte page whose slack absorbs it. Reading the source found nothing: the
760// two obvious suspects (nx_ir.nx:70 sys_mmap(104), nx_parse.nx:868 sys_mmap(256)) are both correctly
761// sized and bounded. So stop reading and MEASURE: stamp each small allocation's gap, verify the
762// PREVIOUS one on the next call, and print the size of whichever allocation was overrun.
763// Writes to fd 2 without allocating -- it borrows scratch inside the arena state page, because a
764// reporter that called sys_mmap would recurse into the thing it is instrumenting.
765// Dump n bytes at src to fd 2, unprintables as '.', using scratch at state+256 (the ring starts at
766// state+512 and the decimal scratch sits at +64/+128, so this cannot collide with either). n is
767// capped by callers at 48 so the buffer stays clear of the ring.
768func nxa_dump_printable(src: i64, n: i64) -> i64 {
769 let o: *u8 = ((nxa_st as i64) + 256) as *u8
770 var i: i64 = 0
771 while i < n {
772 let sp: *u8 = (src + i) as *u8
773 var c: i64 = sp[0] as i64
774 if c < 32 { c = 46 }
775 if c > 126 { c = 46 }
776 o[i] = c as u8
777 i = i + 1
778 }
779 o[n] = 10 as u8
780 sys_write(2, o, n + 1)
781 return 0
782}
783
784// FINGERPRINT (2026-08-12): the size alone + all-zeros byte dump never named the site. The ring already
785// records each allocation's REQUESTED size in counter order, so the recent size SEQUENCE fingerprints the
786// code path that was running when the overrun landed (a distinctive run of sizes is near-unique to a
787// function). Writes to fd 2 borrowing state-page scratch at bytes 320/340 (clear of the ring at byte 512,
788// the reporter decimals at 64/128, and the byte-dump at 256). No allocation -- must not recurse into sys_mmap.
789func nxa_dump_sizes() -> i64 {
790 sys_write(2, " ring_sizes(old->recent): " as *u8, 27)
791 let scr: *u8 = ((nxa_st as i64) + 320) as *u8
792 let out2: *u8 = ((nxa_st as i64) + 340) as *u8
793 let cnt: i64 = nxa_st[2]
794 var start: i64 = cnt - 32
795 if start < 0 { start = 0 }
796 var idx: i64 = start
797 while idx < cnt {
798 let slot: i64 = idx % NXA_RING
799 let szv: i64 = nxa_st[NXA_RBASE + slot * 2 + 1]
800 var m: i64 = szv
801 var k: i64 = 0
802 if m == 0 { scr[0] = 48 as u8; k = 1 }
803 while m > 0 { scr[k] = (48 + (m % 10)) as u8; m = m / 10; k = k + 1 }
804 var j: i64 = 0
805 while j < k { out2[j] = scr[k - 1 - j]; j = j + 1 }
806 out2[k] = 44 as u8
807 sys_write(2, out2, k + 1)
808 idx = idx + 1
809 }
810 sys_write(2, "\n" as *u8, 1)
811 return 0
812}
813
814func nxa_report_overrun(sz: i64, gs: i64) -> i64 {
815 let msg: *u8 = "ARENA-OVERRUN prev_alloc_size=" as *u8
816 var n: i64 = 0
817 while msg[n] != (0 as u8) { n = n + 1 }
818 sys_write(2, msg, n)
819 let b: *u8 = ((nxa_st as i64) + 64) as *u8
820 let o: *u8 = ((nxa_st as i64) + 128) as *u8
821 var m: i64 = sz
822 var k: i64 = 0
823 if m == 0 { b[0] = 48 as u8; k = 1 }
824 while m > 0 { b[k] = (48 + (m % 10)) as u8; m = m / 10; k = k + 1 }
825 var i: i64 = 0
826 while i < k { o[i] = b[k - 1 - i]; i = i + 1 }
827 o[k] = 10 as u8
828 sys_write(2, o, k + 1)
829 // The SIZE alone did not name the site (four 80-byte victims, and the two unbounded 80-byte
830 // buffers in nx_parse.nx were sized from their inputs with no effect). So show the DATA: the
831 // victim's own bytes identify the buffer, and the bytes written past its end identify the WRITER.
832 let algn: i64 = (sz + NXA_ALIGN - 1) / NXA_ALIGN * NXA_ALIGN
833 let base: i64 = gs - algn
834 var dn: i64 = sz
835 if dn > 48 { dn = 48 }
836 sys_write(2, " own : " as *u8, 8)
837 nxa_dump_printable(base, dn)
838 sys_write(2, " over: " as *u8, 8)
839 nxa_dump_printable(gs, 16)
840 nxa_dump_sizes()
841 return 0
842}
843
844func nxa_die(msg: *u8) -> i64 {
845 var n: i64 = 0
846 while msg[n] != (0 as u8) { n = n + 1 }
847 sys_write(2, msg, n)
848 sys_exit(12)
849 return 0
850}
851
852// Address of the arena lock word. Valid only once nxa_st exists; every caller below has already
853// ensured that, and the state-page creation itself is discussed at the take site.
854func nxa_lock_addr() -> *i64 {
855 return ((nxa_st as i64) + NXA_LOCK * 8) as *i64
856}
857
858// __atomic_cas_i64 returns 1 when it wrote and 0 when it did not, so the spin condition is == 0.
859// It is a COMPILER INTRINSIC, not a call into nx_atom -- that module imports THIS file, so importing
860// it back would be a cycle. Verified in nx_x86_64_ctx rather than assumed: it lowers to a genuine
861// `lock cmpxchgq` followed by sete, which is a full barrier on x86-64 whatever ordering is passed.
862func nxa_lock_take() -> i64 {
863 var spins: i64 = 0
864 while __atomic_cas_i64(nxa_lock_addr(), 0, 1, NX_MO_ACQUIRE) == 0 {
865 spins = spins + 1
866 // Fires EXACTLY ONCE, on equality rather than on exceeding, so a genuinely long wait reports
867 // itself without turning the allocator into a log generator.
868 if spins == NXA_LOCK_WARN {
869 // ONCE PER PROCESS, not once per acquisition. MEASURED 2026-08-25 and this is a
870 // correction to the first cut of this very function: it fired on equality per CALL, and
871 // eight workers contending LEGITIMATELY produced hundreds of identical lines in a single
872 // gate run. A DIAGNOSTIC THAT FIRES CONSTANTLY IS ONE EVERY READER LEARNS TO IGNORE, and
873 // this one writes to the stderr of every organ in the estate.
874 // The threshold was derived from the longest the critical section can run, which bounds
875 // ONE hold and says nothing about QUEUE DEPTH: with N threads waiting, a legitimate wait
876 // is N holds and can exceed any per-section derivation. So this is a NOISE FLOOR for a
877 // hint, never a correctness bound -- it never fails, never delays, and never repeats.
878 // The flag is set through a CAS so the once-ness cannot itself race.
879 let wflag: *i64 = ((nxa_st as i64) + NXA_LOCK_WARNED * 8) as *i64
880 if __atomic_cas_i64(wflag, 0, 1, NX_MO_ACQ_REL) == 1 {
881 let m: *u8 = "ARENA-LOCK: sustained allocator contention seen (reported once per process; a hint, not an error -- allocation proceeds normally).\n" as *u8
882 var mn: i64 = 0
883 while m[mn] != (0 as u8) { mn = mn + 1 }
884 sys_write(2, m, mn)
885 }
886 }
887 }
888 return 0
889}
890
891func nxa_lock_give() -> i64 {
892 // nx_cc refuses a bare intrinsic statement ("computes a value and never uses it") and an atomic
893 // store has no result worth using, so it is bound and discarded -- the same shape nx_atom uses
894 // for exactly this reason. The contract is unchanged: this returns 0 either way.
895 let discarded: i64 = __atomic_store_i64(nxa_lock_addr(), 0, NX_MO_RELEASE)
896 if discarded != 0 { return 0 }
897 return 0
898}
899
900// Optional mapping for request boundaries that must report allocation refusal.
901// Unlike sys_mmap, this never aborts the process and never consumes arena storage.
902// Release successful mappings with sys_munmap_direct, not the arena-aware sys_munmap.
903// A successful reservation can still fail on later physical-memory pressure; callers
904// must not describe virtual address admission as guaranteed resident RAM.
905func sys_mmap_try(size:i64)->*u8 {
906 if size<=0 { return 0 as *u8 }
907 let mapped:i64=__syscall(SYS_MMAP,0,size,3,0x22,-1,0)
908 if mapped<=0 { return 0 as *u8 }
909 return mapped as *u8
910}
911
912func sys_mmap(size: i64) -> *u8 {
913 // Large requests keep the EXACT original behaviour, byte for byte: page-aligned, own VMA. Any
914 // caller that depends on page alignment is allocating at least a page, so the arena cannot reach
915 // it. Every failure path below also falls back to this same call, so an exhausted arena degrades
916 // to the old allocator rather than returning a bad pointer.
917 if size > NXA_SMALL_MAX {
918 let big: i64 = __syscall(SYS_MMAP, 0, size, 3, 0x22, -1, 0)
919 if big <= 0 { nxa_die("FATAL sys_mmap: kernel refused a large mapping (ENOMEM). Refusing to return a poisoned pointer -- a write through it would corrupt memory.\n" as *u8) }
920 return big as *u8
921 }
922 if (nxa_st as i64) == 0 {
923 let s: i64 = __syscall(SYS_MMAP, 0, NXA_STATE, 3, 0x22, -1, 0)
924 if s <= 0 {
925 // arena state page refused -- degrade to the plain allocator, and only die if THAT fails too
926 let f1: i64 = __syscall(SYS_MMAP, 0, size, 3, 0x22, -1, 0)
927 if f1 <= 0 { nxa_die("FATAL sys_mmap: kernel refused the arena state page AND the fallback mapping (ENOMEM).\n" as *u8) }
928 return f1 as *u8
929 }
930 nxa_st = s as *i64
931 }
932 // EVERYTHING FROM HERE TO THE RETURN TOUCHES SHARED STATE: the cursor, the limit, the chunk
933 // table, the canary ring and the ring counter. It is ONE critical section because the refill
934 // decision and the bump that depends on it cannot be separated without reintroducing the race.
935 // The state page itself is created ABOVE this point, unlocked: two threads arriving there
936 // together would each map a page and one would win the static, leaking the other's 4 KiB but
937 // corrupting nothing, and in practice the arena is warm long before any thread is spawned
938 // because spawning one allocates. That residual is NAMED here rather than papered over.
939 nxa_lock_take()
940 var need: i64 = size
941 if need <= 0 { need = 1 }
942 need = (need + NXA_ALIGN - 1) / NXA_ALIGN * NXA_ALIGN + NXA_GAP
943 if nxa_st[0] + need > nxa_st[1] {
944 let c: i64 = __syscall(SYS_MMAP, 0, NXA_CHUNK, 3, 0x22, -1, 0)
945 if c <= 0 {
946 // chunk refused -- degrade to the plain allocator, and only die if THAT fails too.
947 // RELEASE FIRST: this is the one path that leaves the critical section early, and a lock
948 // held across a degraded return would wedge every other allocator in the process.
949 nxa_lock_give()
950 let f2: i64 = __syscall(SYS_MMAP, 0, size, 3, 0x22, -1, 0)
951 if f2 <= 0 { nxa_die("FATAL sys_mmap: kernel refused an arena chunk AND the fallback mapping (ENOMEM).\n" as *u8) }
952 return f2 as *u8
953 }
954 nxa_st[0] = c
955 nxa_st[1] = c + NXA_CHUNK
956 // track the chunk base so arena_reset can munmap post-mark chunks (additive; guarded at cap).
957 if nxa_st[3] < NXA_CHUNKMAX { nxa_st[NXA_CHUNKBASE + nxa_st[3]] = c; nxa_st[3] = nxa_st[3] + 1 }
958 }
959 // ---- RING CANARY (temporary diagnostic) ----
960 var rk: i64 = 0
961 while rk < NXA_RING {
962 let gs0: i64 = nxa_st[NXA_RBASE + rk * 2]
963 if gs0 != 0 {
964 var bi: i64 = 0
965 var bad: i64 = 0
966 while bi < 8 {
967 let bp: *u8 = (gs0 + bi) as *u8
968 if bp[0] != (199 as u8) { bad = 1; bi = 8 } else { bi = bi + 1 }
969 }
970 if bad == 1 {
971 nxa_report_overrun(nxa_st[NXA_RBASE + rk * 2 + 1], gs0)
972 nxa_st[NXA_RBASE + rk * 2] = 0
973 }
974 }
975 rk = rk + 1
976 }
977 let p: i64 = nxa_st[0]
978 nxa_st[0] = p + need
979 let gs: i64 = p + need - NXA_GAP
980 var gj: i64 = 0
981 while gj < NXA_GAP { let q: *u8 = (gs + gj) as *u8; q[0] = 199 as u8; gj = gj + 1 }
982 let slot: i64 = nxa_st[2] % NXA_RING
983 nxa_st[NXA_RBASE + slot * 2] = gs
984 nxa_st[NXA_RBASE + slot * 2 + 1] = size
985 nxa_st[2] = nxa_st[2] + 1
986 // The ONLY other exit from the critical section is the degraded chunk-refill path above, which
987 // releases before it returns. Every shared write is now behind this pair.
988 nxa_lock_give()
989 return p as *u8
990}
991
992// arena_mark: force the arena warm (so a first chunk + state page exist), then record the current
993// position as the reset barrier. Returns 1. A daemon calls this ONCE after startup, before its loop.
994func sys_arena_mark() -> i64 {
995 let warm: *u8 = sys_mmap(1) // ensures nxa_st + chunk[0] exist; the 1 byte is itself arena scratch
996 if (warm as i64) == 0 { return 0 }
997 nxa_st[4] = 1
998 nxa_st[5] = nxa_st[0]
999 nxa_st[6] = nxa_st[1]
1000 nxa_st[7] = nxa_st[3]
1001 return 1
1002}
1003
1004// arena_reset: reclaim everything allocated since the mark. munmap post-mark chunks, restore the bump
1005// to the mark, ZERO the marked chunk's reclaimed tail (preserves the mmap-returns-zeroed contract for
1006// recycled bytes), and CLEAR the ring canary (its stamps may point into a just-munmap'd chunk, and a
1007// stale deref on the next alloc would SEGV). Returns 1 on reset, 0 if no mark was set.
1008func sys_arena_reset() -> i64 {
1009 if (nxa_st as i64) == 0 { return 0 }
1010 if nxa_st[4] != 1 { return 0 }
1011 var i: i64 = nxa_st[7]
1012 while i < nxa_st[3] {
1013 let cb: i64 = nxa_st[NXA_CHUNKBASE + i]
1014 if cb != 0 { __syscall(11, cb, NXA_CHUNK, 0, 0, 0, 0); nxa_st[NXA_CHUNKBASE + i] = 0 }
1015 i = i + 1
1016 }
1017 nxa_st[3] = nxa_st[7]
1018 nxa_st[0] = nxa_st[5]
1019 nxa_st[1] = nxa_st[6]
1020 var z: i64 = nxa_st[0]
1021 while z < nxa_st[1] { let q: *u8 = z as *u8; q[0] = 0 as u8; z = z + 1 }
1022 var r: i64 = 0
1023 while r < NXA_RING * 2 { nxa_st[NXA_RBASE + r] = 0; r = r + 1 }
1024 nxa_st[2] = 0
1025 return 1
1026}
1027
1028// mmap anonymous SHARED R/W memory -- ONE region that survives fork() so all
1029// children see each other's writes (MAP_SHARED|MAP_ANONYMOUS = 0x21). Allocate
1030// in the PARENT before fork. Foundation for the fork-per-connection video relay
1031// (peers in separate children share the per-room frame table).
1032func sys_mmap_shared(size: i64) -> *u8 {
1033 let r: i64 = __syscall(SYS_MMAP, 0, size, 3, 0x21, -1, 0)
1034 return r as *u8
1035}
1036
1037// madvise(2) -- prefetch/advice hints for mapped ranges. MADV_WILLNEED=3 batches page-ins so a
1038// serial fault loop over a cold file-backed mmap becomes parallel disk readahead (the dp-web-pub
1039// stage-2 p95 fix, 2026-08-12). RAW x86_64 NUMBER 28 ON PURPOSE (sys_exit_group's raw-231 pattern):
1040// the portable rv64/asm-generic number is 233 and x86ctx_rv64_to_x86_64_syscall has no 233 row in
1041// the DEPLOYED compiler, so a portable const would emit x86_64 233 = epoll_ctl (the wrong-syscall-
1042// not-an-error class; see the setpgid/flock rows). The 233->28 row is staged in nx_x86_64_ctx.nx and
1043// activates on the next nx_cc self-host rebuild; flip this to the portable const AFTER that lands.
1044// Signature bite-proven by nx_madvise_probe (0 / -12 ENOMEM / -22 EINVAL). Advisory contract: callers
1045// may ignore the return value -- a failed hint costs nothing but the cold-read behaviour it hints away.
1046func sys_madvise(addr: *u8, len: i64, advice: i64) -> i64 {
1047 return __syscall(28, addr, len, advice, 0, 0, 0)
1048}
1049
1050// openat flavors used by the compiler driver. AT_FDCWD = -100 (declared ABOVE, next to its first
1051// reader -- see the miscompile note there; do NOT move it back down).
1052// O_RDONLY = 0; O_CREAT|O_WRONLY|O_TRUNC = 0x241 on Linux RV64.
1053const O_RDONLY: i64 = 0
1054const O_WRONLY_CT: i64 = 0x241 // O_CREAT | O_WRONLY | O_TRUNC
1055const O_WRONLY_CA: i64 = 0x441 // O_CREAT | O_WRONLY | O_APPEND
1056
1057func sys_openat_rd(path: *u8) -> i64 {
1058 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_RDONLY, 0, 0, 0)
1059}
1060
1061// O_RDWR|O_CREAT (NO truncate) -- for offset-addressed persistent files like the metrics ring TSDB
1062// (create if missing, then lseek+read/write records in place, never truncating existing history).
1063const O_RDWR_CREATE: i64 = 0x42
1064func sys_openat_rdwr(path: *u8, mode: i64) -> i64 {
1065 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_RDWR_CREATE, mode, 0, 0)
1066}
1067
1068// ★★★THE FILE MODE IS THE HALF OF THIS INTERFACE THAT WAS NEVER NAMED. The O_ flags above are named
1069// consts in hex WITH a decoding comment; the mode passed beside them is a bare literal at every call
1070// site. MEASURED 2026-08-14 (coverage_complete=1 corpus_complete=1 over 23,053 files):
1071// - 29 organs passed the mode as a bare DECIMAL literal, which no reader decodes as rw-r--r--
1072// without stopping to convert it. ⚠THE FIRST COUNT PUBLISHED HERE WAS 26: the scan was scoped to
1073// runtime/_hdl_build/ and the SUBDIRECTORY's count was published as the estate figure -- three
1074// more (nx_forge_rag, nx_gpu_export, nx_bvhfk) sat one level up in runtime/.
1075// ★A COUNT INHERITS THE SCOPE OF ITS SCAN, AND THE SCOPE IS THE PART NOBODY PRINTS BESIDE IT.
1076// ⚠The offending call is deliberately NOT spelled out literally in this comment: prose is source
1077// bytes, so writing the pattern here would make every future grep for it match this note;
1078// - 10 MORE each define their OWN private 0644 const (IP_ VR_ VP_ LIVE_ FD_ FP_ WL_ PUB_ REG_ HFF_),
1079// nine written 0x1a4 and one written 420 -- THE SAME CONSTANT IN TWO DIFFERENT BASES.
1080// Ten seats each solved this privately and none put the answer where the next one would look. That is
1081// the duplicate-ruler defect precisely: changing the estate's default artifact mode today means finding
1082// 39 sites in two notations and hoping none was missed. One name, in the shim every organ already
1083// imports, is the entire fix -- and it belongs HERE, beside the flags, not in a 40th private copy.
1084const MODE_0644: i64 = 0x1a4 // rw-r--r-- : default mode for a generated artifact
1085// rwxr-xr-x : default mode for a created DIRECTORY. A directory without the execute bit cannot be
1086// traversed, so MODE_0644 is not merely stricter here -- it is wrong, and the failure surfaces later
1087// as an unopenable path rather than as a refused mkdir. Named beside its sibling so the choice is a
1088// lookup rather than a recollection; the estate otherwise spells this as a raw 0x1ed at every site.
1089const MODE_0755: i64 = 0x1ed
1090// Seconds of ZERO PROGRESS on one socket operation before an accepted connection is abandoned.
1091// A single-threaded accept-loop daemon that loop-reads to Content-Length can be starved FOREVER by one
1092// peer that declares a body it never finishes sending -- a one-request DoS, hostile OR merely buggy.
1093// nx_dos_timeout_scan supervises the class and named 16 daemons carrying no timeout at all; the cure is
1094// sys_set_socket_timeout(cfd, ACCEPT_TMO_S) folded in right after accept.
1095// WHY 30 AND NOT THE 5 THE LOGIN DAEMONS USE: this bound must be wrong in the direction of SERVING, not
1096// of dropping. The attack is an UNBOUNDED wait, so ANY finite bound closes it; a short one additionally
1097// risks aborting a legitimate slow client. 30s of zero progress on a single recv/send is pathological
1098// for every daemon in the class -- including the streaming ones, where data is flowing and the timer
1099// never approaches its bound -- while still converting an infinite starvation into a bounded one.
1100// It is the calibration nx_galx_bridge already uses for an accepted cfd; named here rather than copied
1101// into a 16th private literal, exactly as MODE_0644 above.
1102const ACCEPT_TMO_S: i64 = 30
1103func sys_openat_wr(path: *u8, mode: i64) -> i64 {
1104 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_WRONLY_CT, mode, 0, 0)
1105}
1106
1107// Linux O_WRONLY | O_CREAT | O_EXCL. An existing final component, including
1108// a symlink, is a conflict; callers acquire ownership only on success.
1109const O_WRONLY_CREATE_EXCLUSIVE: i64 = 0x1 | 0x40 | 0x80
1110func sys_openat_exclusive(path: *u8, mode: i64) -> i64 {
1111 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_WRONLY_CREATE_EXCLUSIVE, mode, 0, 0)
1112}
1113
1114// Linux O_DIRECTORY: require a directory, rather than merely an openable node.
1115const O_DIRECTORY: i64 = 0x10000
1116func sys_openat_directory(path: *u8) -> i64 {
1117 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_RDONLY | O_DIRECTORY, 0, 0, 0)
1118}
1119
1120// Open path for append (create if missing). Used by append-only
1121// journals such as .race_telemetry.tsv. RV64 syscall numbers; the
1122// x86_64 mirror lives in nx_syscalls_x86_64.nx.
1123func sys_openat_append(path: *u8, mode: i64) -> i64 {
1124 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_WRONLY_CA, mode, 0, 0)
1125}
1126
1127// Linux open ABI flags: acquire close-on-exec atomically and refuse a final
1128// symlink. Nonblocking also prevents an unexpected FIFO from stalling admission.
1129const O_CLOEXEC: i64 = 0x80000
1130const O_NOFOLLOW: i64 = 0x20000
1131const O_NONBLOCK: i64 = 0x800
1132const MODE_0600: i64 = 0x180
1133func sys_openat_lock(path: *u8) -> i64 {
1134 return __syscall(SYS_OPENAT, AT_FDCWD, path, O_WRONLY_CA | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, MODE_0600, 0, 0)
1135}
1136
1137// symlinkat(target, AT_FDCWD, linkpath) -- raw x86_64 266 forced RUNTIME (the chdir escape, same as
1138// readlinkat below). THE atomic-repoint primitive for release management: create releases/current.new ->
1139// sys_renameat over releases/current = an atomic symlink swap (golive/rollback are instant + crash-safe).
1140// 0 on success, -errno (notably -EEXIST=-17 if linkpath exists -- create the .new name, then rename).
1141func sys_symlinkat(target: *u8, linkpath: *u8) -> i64 {
1142 let nbox: *i64 = sys_mmap(16) as *i64
1143 nbox[0] = 266
1144 let r: i64 = __syscall(nbox[0], target as i64, AT_FDCWD, linkpath as i64, 0, 0, 0)
1145 sys_munmap(nbox as *u8, 16)
1146 return r
1147}
1148
1149// readlinkat(AT_FDCWD, path, buf, cap) -- raw x86_64 267 forced RUNTIME (the chdir escape: keep the
1150// number out of the rv64->x86 constant-translate path). Returns link length (NO NUL appended), -errno
1151// on fail. nbox is munmap'd before return: the daemon supervisor calls this hundreds of times PER CYCLE
1152// (exe-identity sweeps), and a leaked page per call is exactly the VSZ-balloon class that broke fork.
1153func sys_readlinkat(path: *u8, buf: *u8, cap: i64) -> i64 {
1154 let nbox: *i64 = sys_mmap(16) as *i64
1155 nbox[0] = 267
1156 let r: i64 = __syscall(nbox[0], AT_FDCWD, path as i64, buf as i64, cap, 0, 0)
1157 sys_munmap(nbox as *u8, 16)
1158 return r
1159}
1160
1161// Atomically replace newpath with oldpath (rename(2) on one filesystem: a concurrent reader sees the
1162// whole old file or the whole new file, never a torn read). The S-class content-publish primitive:
1163// write the new page to a temp file, then sys_renameat(tmp, live) -> hot-swap, NO rm+ln race.
1164// renameat2: rv64=276, x86_64=316, flags=0. The known-good compiler translates most rv64 syscall
1165// numbers to the x86_64 target but its table MISSES 276 -- verified 2026-06-14 via nx_rename_probe:
1166// raw 276 -> -EINVAL (lands on x86_64 `tee`), raw 316 -> renames OK. That silently broke every
1167// cst_write_atomic publish (page.html.new written, never swapped in). Try the x86_64 number first
1168// (works on every x86_64 build incl. known-good); fall back to the rv64 number for native-rv64 or
1169// translating compilers that do map it. flags=0 so renameat2 == renameat semantics.
1170func sys_renameat(oldpath: *u8, newpath: *u8) -> i64 {
1171 let r: i64 = __syscall(316, AT_FDCWD, oldpath, AT_FDCWD, newpath, 0, 0)
1172 if r == 0 { return 0 }
1173 return __syscall(276, AT_FDCWD, oldpath, AT_FDCWD, newpath, 0, 0)
1174}
1175
1176// fsync(2): flush file (or directory) data+metadata to stable storage.
1177// PROBE-PROVEN 2026-06-10 (_fsync_probe): rv64 82 is NOT in the compiler's
1178// translation table (lands on x86 rename -> -EFAULT both ways); direct
1179// x86_64 74 passes through raw (the unlinkat-263 precedent) and behaves as
1180// fsync (0 on a valid fd, -9 EBADF on a bad one). Storage commit points
1181// fsync the data files AND their directory around rename(2) so a committed
1182// segment survives power loss, not just process death.
1183func sys_fsync(fd: i64) -> i64 {
1184 return __syscall(74, fd, 0, 0, 0, 0, 0)
1185}
1186
1187// flock(2): BSD-style whole-file ADVISORY lock. rv64 32 -> x86_64 73 via the compiler's
1188// x86ctx_rv64_to_x86_64_syscall table (nx_x86_64_ctx.nx:961, PROVEN LIVE in flock_deploy.log).
1189// op: SYS_LOCK_SH=1 / SYS_LOCK_EX=2 / SYS_LOCK_NB=4 (OR) / SYS_LOCK_UN=8. Returns 0 on success,
1190// -errno on failure. Used by the framed-append durability floor to serialize the write-until-
1191// complete loop so a partial/short write under contention can NEVER misalign a concurrent appender
1192// (O_APPEND single-write atomicity is necessary but not sufficient on every fs -- the lock makes
1193// the whole framed record write atomic against other lockers). Additive: no existing caller in
1194// this file changes. NOTE: nx_flock.nx is a separate organ importing the LEGACY "syscalls.nx"
1195// name; this wrapper lives HERE so organs already on nx_syscalls.nx (e.g. nx_framed_append) get
1196// flock without a second import (double-import rc=6 trap).
1197const SYS_LOCK_SH: i64 = 1
1198const SYS_LOCK_EX: i64 = 2
1199const SYS_LOCK_NB: i64 = 4
1200const SYS_LOCK_UN: i64 = 8
1201func sys_flock(fd: i64, op: i64) -> i64 {
1202 return __syscall(32, fd, op, 0, 0, 0, 0)
1203}
1204
1205// newfstatat(2): stat `path` into a 144-byte x86-64 struct stat at `statbuf`. x86_64 nr 262 is passed
1206// DIRECTLY (the unlinkat-263 / fsync-74 precedent: stat-family rv64 numbers aren't in the compiler's
1207// translation table, so a raw x86_64 number passes through untranslated). Returns 0 on success, <0
1208// (e.g. -2 ENOENT) on error. st_mtim.tv_sec @ offset 88, st_mtim.tv_nsec @ 96 (the freshness channel).
1209func sys_fstatat(path: *u8, statbuf: *u8) -> i64 {
1210 return __syscall(262, AT_FDCWD, path, statbuf, 0, 0, 0)
1211}
1212
1213// utimensat(2): set `path` atime+mtime from `times` (a struct timespec[2] = [atime.sec,atime.nsec,
1214// mtime.sec,mtime.nsec]). x86_64 nr 280 passed DIRECTLY. A sovereign `touch`; also makes freshness
1215// tests deterministic. Returns 0 on success, <0 on error.
1216func sys_utimensat(path: *u8, times: *i64) -> i64 {
1217 return __syscall(280, AT_FDCWD, path, times as i64, 0, 0, 0)
1218}
1219
1220// ---- sovereign host control-plane syscalls (x86_64; single unconditional consts,
1221// per the known-good-compiler @ifdef finding). The Nishi supervisor uses these to
1222// manage the daemon lifecycle WITHOUT any shell (no pkill / mkdir / chmod glue). ----
1223
1224// COMPILER NOTE: the known-good compiler BAKES whole function bodies by NAME for some syscalls
1225// (proven via emitted .s: a function literally named sys_kill emits number 8, sys_chmod emits 155
1226// -- both wrong, regardless of the const referenced). So these wrappers use NON-baked names
1227// (nx_kill / nx_chmod). sys_mkdir / sys_renameat are not baked, so those keep the sys_ name.
1228
1229// DESIGN: __syscall takes the RV64/generic number; the compiler's x86ctx_rv64_to_x86_64_syscall table
1230// (nx_x86_64_ctx.nx) translates it to the build target. So pass the RV64 number. These four were added
1231// to that sovereign table 2026-06-06 (kill 129->62, mkdirat 34->258, fchmodat 53->268, renameat2
1232// 276->316); x86 kill(62) had collided with rv64 lseek(62), x86 fchmodat(268) with rv64 pivot_root(268).
1233
1234// kill(pid, sig) -- rv64 129 -> x86_64 62. SIGTERM=15 / SIGKILL=9. Host control plane.
1235func nx_kill(pid: i64, sig: i64) -> i64 { return __syscall(129, pid, sig, 0, 0, 0, 0) }
1236
1237// setpgid(pid, pgid) -- put a process in its own PROCESS GROUP so a killer can reach its whole
1238// subtree. nx_kill(0 - pgid, sig) signals every member, not just the one process you forked.
1239// A BOUND THAT ONLY REACHES THE PROCESS YOU FORKED IS NOT A BOUND ON THE WORK IT STARTED.
1240// Per-target const, NOT a bare generic number: x86ctx_rv64_to_x86_64_syscall translates only the
1241// numbers it knows and FALLS THROUGH for the rest. MEASURED on the laptop lane 2026-08-10: a bare
1242// generic 154 reached x86_64 as 154 and returned -38 (ENOSYS), silently -- and a fix built on it
1243// reproduced the original bug exactly. Callers must treat setpgid as BEST-EFFORT.
1244@ifdef TARGET_X86_64
1245const SYS_SETPGID: i64 = 109
1246@endif
1247@ifndef TARGET_X86_64
1248const SYS_SETPGID: i64 = 154
1249@endif
1250func sys_setpgid(pid: i64, pgid: i64) -> i64 { return __syscall(SYS_SETPGID, pid, pgid, 0, 0, 0, 0) }
1251
1252// prlimit64(pid, resource, new_limit, old_limit) -- the Linux RESOURCE-LIMIT primitive =
1253// the Job-Object ActiveProcessLimit / memory-limit analog for the sovereign supervisor (M5).
1254// x86_64 prlimit64 = 302 (PASSED DIRECTLY, the unlinkat-263 / fsync-74 / fstatat-262
1255// precedent: a raw x86_64 number not in the compiler's rv64->x86 swap table passes through
1256// untranslated). NOTE: rv64 prlimit64 IS 261 but x86_64 261 = futimesat -- so the naive
1257// "261 is the same on both" is WRONG (PROBE-PROVEN: 261 returned EFAULT/EINVAL because it
1258// hit futimesat); the build target here is x86_64, so we emit 302 directly. pid=0 => the
1259// calling process (a forked child caps ITSELF before running its payload). new_limit /
1260// old_limit each point at a struct rlimit64 { rlim_cur: i64, rlim_max: i64 } (16 bytes);
1261// pass 0 for old_limit to skip read-back. Returns 0 on success, -errno (e.g. -1 EPERM if
1262// raising a hard limit unprivileged) on failure. NON-baked name (the compiler bakes some
1263// sys_* bodies by name; the nx_ prefix avoids that trap).
1264func nx_prlimit(pid: i64, resource: i64, new_limit: *u8, old_limit: *u8) -> i64 {
1265 return __syscall(302, pid, resource, new_limit as i64, old_limit as i64, 0, 0)
1266}
1267
1268// RLIMIT resource ids (Linux generic; identical rv64/x86_64). RLIMIT_AS = address-space
1269// (virtual memory) cap -- the cleanest userspace-settable "memory budget" for a supervised
1270// job. RLIMIT_CPU = CPU-seconds cap. WNOHANG=1 = wait4 non-blocking liveness poll option.
1271const RLIMIT_CPU: i64 = 0
1272const RLIMIT_AS: i64 = 9
1273const WNOHANG: i64 = 1
1274
1275// mkdirat -- rv64 34 -> x86_64 258. Create a doc-root directory. mode e.g. 0x1ed (0755).
1276func sys_mkdir(path: *u8, mode: i64) -> i64 { return __syscall(34, AT_FDCWD, path, mode, 0, 0, 0) }
1277
1278// fchmodat -- rv64 53 -> x86_64 268. +x a freshly-deployed daemon binary (mode 0x1ed). flags=0.
1279func nx_chmod(path: *u8, mode: i64) -> i64 { return __syscall(53, AT_FDCWD, path, mode, 0, 0, 0) }
1280
1281// setsid -- x86_64 = 112 (not in the rv64->x86 table, so the literal passes through). Detach a forked
1282// process into a NEW session so it survives the SSH/parent close -- sovereign daemonization (no shell setsid).
1283func nx_setsid() -> i64 { return __syscall(112, 0, 0, 0, 0, 0, 0) }
1284
1285// CLOCK_MONOTONIC = 1. ts is 16 bytes {sec: i64, nsec: i64}.
1286// Returns 0 / -errno.
1287func sys_clock_gettime_mono(ts: *i64) -> i64 {
1288 return __syscall(SYS_CLOCK_GETTIME, 1, ts, 0, 0, 0, 0)
1289}
1290
1291// CLOCK_REALTIME = 0 -- wall-clock seconds since the Unix epoch. Use
1292// this (NOT monotonic) for anything that must match calendar time:
1293// X.509 notBefore/notAfter, logs, TLS timestamps. Monotonic returns
1294// time-since-boot, which encodes as ~1970 when (mis)used as an epoch.
1295func sys_clock_gettime_real(ts: *i64) -> i64 {
1296 return __syscall(SYS_CLOCK_GETTIME, 0, ts, 0, 0, 0, 0)
1297}
1298
1299// Wall-clock seconds since the Unix epoch.
1300func sys_now_realtime_sec() -> i64 {
1301 let ts: *i64 = sys_mmap(16) as *i64
1302 sys_clock_gettime_real(ts)
1303 return ts[0]
1304}
1305
1306// Wall-clock milliseconds since the Unix epoch.
1307func sys_now_realtime_ms() -> i64 {
1308 let ts: *i64 = sys_mmap(16) as *i64
1309 sys_clock_gettime_real(ts)
1310 return ts[0] * 1000 + ts[1] / SYS_MAGIC_1000000
1311}
1312
1313// Wall-clock MICROSECONDS since the Unix epoch -- the CROSS-MACHINE stamp.
1314// ★ Use this, never sys_now_us(), for any value one machine writes and ANOTHER machine judges
1315// (fleet beats, lease expiry, telemetry rows). Monotonic counts from each machine's OWN boot, so
1316// subtracting one node's monotonic stamp from another's monotonic now yields the difference of two
1317// unrelated boot epochs -- the remote row then reads as ancient (or future-forged) and a freshness
1318// guard rejects every honest remote node while looking like it is working.
1319func sys_now_realtime_us() -> i64 {
1320 let ts: *i64 = sys_mmap(16) as *i64
1321 sys_clock_gettime_real(ts)
1322 return ts[0] * SYS_MAGIC_1000000 + ts[1] / 1000
1323}
1324
1325// Convenience: monotonic time in milliseconds. Caller does not own
1326// the timespec buffer -- it is mmap'd once per call (cheap; the
1327// underlying syscall already costs more than the page fault).
1328func sys_now_ms() -> i64 {
1329 let ts: *i64 = sys_mmap(16) as *i64
1330 sys_clock_gettime_mono(ts)
1331 let sec_part: i64 = ts[0] * 1000
1332 let nsec_part: i64 = ts[1] / SYS_MAGIC_1000000
1333 return sec_part + nsec_part
1334}
1335
1336// Convenience: monotonic time in microseconds. Used by per-request
1337// elapsed-time tracking in search engines + benches where ms is too
1338// coarse. Same caller-ownership rules as sys_now_ms.
1339func sys_now_us() -> i64 {
1340 let ts: *i64 = sys_mmap(16) as *i64
1341 sys_clock_gettime_mono(ts)
1342 let sec_part: i64 = ts[0] * SYS_MAGIC_1000000
1343 let nsec_part: i64 = ts[1] / 1000
1344 return sec_part + nsec_part
1345}
1346
1347// Alias used by nx_search_onsite_engine etc. Matches `_us` naming
1348// convention. Substrate-canonical name is sys_now_us; this alias
1349// preserves existing call sites without churn.
1350func sys_clock_now_us() -> i64 {
1351 return sys_now_us()
1352}
1353
1354// Read the entire file at `path` into a fresh mmap'd buffer. Returns
1355// a null-terminated *u8 plus writes the byte count to *out_len. On
1356// error (open failure, oversize) returns null and leaves out_len = 0.
1357// Uses a fixed 1 MiB buffer for the first pass; larger sources need a
1358// growth loop.
1359// ---- process control (Linux RV64) ----------------------------
1360//
1361// Lets NishiLang programs spawn other processes -- prerequisite
1362// for replacing shell scripts (f6_gate.sh) with .nx equivalents.
1363// NishiOS will expose a different process model (capability-based);
1364// these wrappers are the Linux-host compatibility layer.
1365
1366@ifdef TARGET_X86_64
1367const SYS_CLONE: i64 = 56
1368const SYS_EXECVE: i64 = 59
1369const SYS_WAIT4: i64 = 61
1370const SYS_PIPE2: i64 = 293
1371const SYS_DUP3: i64 = 292
1372@endif
1373
1374@ifndef TARGET_X86_64
1375const SYS_CLONE: i64 = 220
1376const SYS_EXECVE: i64 = 221
1377const SYS_WAIT4: i64 = 260
1378const SYS_PIPE2: i64 = 59
1379const SYS_DUP3: i64 = 24
1380@endif
1381
1382// Clone flags (subset). CLONE_VFORK blocks parent until child
1383// exec's or exits, matching fork() semantics closely enough for
1384// our spawn-then-wait patterns.
1385const CLONE_VM: i64 = 0x00000100
1386const CLONE_VFORK: i64 = 0x00004000
1387const SIGCHLD: i64 = 17
1388
1389// Create a child process via Linux clone(). Returns:
1390// > 0 in the parent: child PID
1391// == 0 in the child: child should exec or exit
1392// < 0 on error: -errno
1393// Uses SIGCHLD as the signal that parent receives on child exit
1394// (the libc fork() default); no shared memory or thread flags.
1395// ---- namespace / container family (debt 1785528831) ----------------
1396// Moved here from nx_syscalls_x86_64.nx so ONE module owns the wrapper set. Their
1397// absence here is why nx_container.nx had to import that module as a SECOND syscall
1398// layer, which put every wrapper in the TU twice and let definition ORDER pick the
1399// winner, silently, until the duplicate-definition guard made it fail closed.
1400func sys_unshare(flags: i64) -> i64 {
1401 return __syscall(SYS_UNSHARE, flags, 0, 0, 0, 0, 0)
1402}
1403func sys_mount(source: *u8, target: *u8, fs_type: *u8, mountflags: i64, data: *u8) -> i64 {
1404 return __syscall(SYS_MOUNT, source, target, fs_type, mountflags, data, 0)
1405}
1406func sys_chroot(path: *u8) -> i64 {
1407 return __syscall(SYS_CHROOT, path, 0, 0, 0, 0, 0)
1408}
1409func sys_getuid() -> i64 {
1410 return __syscall(SYS_GETUID, 0, 0, 0, 0, 0, 0)
1411}
1412func sys_getgid() -> i64 {
1413 return __syscall(SYS_GETGID, 0, 0, 0, 0, 0, 0)
1414}
1415
1416func sys_fork() -> i64 {
1417 return __syscall(SYS_CLONE, SIGCHLD, 0, 0, 0, 0, 0)
1418}
1419
1420// Replace the current process image. `path` is the executable
1421// (absolute or in $PATH if the child first does a fresh clone).
1422// `argv` is a null-terminated array of *u8 (already-marshalled).
1423// `envp` same shape, or null for "inherit parent's env".
1424// Only returns on failure (-errno).
1425// EXEC WITH A CLEAN FD TABLE (seq1785451144). A child inherits every fd its parent held, INCLUDING
1426// listen sockets, across fork AND execve. That is how nx_opaque_login came to hold mgmt s :18098
1427// alongside mgmt itself -- two listeners on one port, connections split between them, a VALID route
1428// answering 404 on some requests. There is no error anywhere in that state, which is why it was
1429// filed as a transport flake for months.
1430// ADDITIVE ON PURPOSE: sys_execve is left byte-identical (910 call sites across 719 files -- a
1431// global change there is unverifiable in one session). Spawners opt in by calling THIS instead.
1432// AUDIT THAT MAKES IT SAFE: zero call sites in the tree dup3 to a target fd above 2, so no exec d
1433// child is deliberately handed a high fd; 0/1/2 are preserved untouched.
1434// Linux child lifetime binding: call in the freshly forked child, before exec.
1435// The expected parent PID is captured before fork, closing the pre-arm death race.
1436// Kernel semantics bind to the creating thread; privileged exec can clear this.
1437const NX_SYS_PRCTL: i64 = 167
1438const NX_PR_SET_PDEATHSIG: i64 = 1
1439const NX_PR_SET_CHILD_SUBREAPER: i64 = 36
1440func sys_prctl(option: i64, arg: i64) -> i64 {
1441 return __syscall(NX_SYS_PRCTL,option,arg,0,0,0,0)
1442}
1443func sys_bind_parent_lifetime(expected_parent: i64, signal: i64) -> i64 {
1444 if expected_parent <= 0 || signal <= 0 { return 0-22 }
1445 let armed: i64=sys_prctl(NX_PR_SET_PDEATHSIG,signal)
1446 if armed < 0 { return armed }
1447 let parent: i64=__syscall(173,0,0,0,0,0,0)
1448 if parent != expected_parent { return 0-10 }
1449 return 0
1450}
1451
1452// Linux waitid observes termination without releasing the child's PID when WNOWAIT is set.
1453// Portable syscall 95 requires the matching x86 backend translation to 247.
1454const SYS_WAITID_PORTABLE: i64 = 95
1455const NX_WAIT_P_PID: i64 = 1
1456const NX_WAIT_EXITED: i64 = 4
1457const NX_WAIT_NOWAIT: i64 = 0x01000000
1458const NX_WAIT_SIGINFO_BYTES: i64 = 128
1459func sys_waitid(idtype: i64, id: i64, info: *u8, options: i64) -> i64 {
1460 return __syscall(SYS_WAITID_PORTABLE,idtype,id,info as i64,options,0,0)
1461}
1462
1463// Post-fork only: the child owns its descriptor table. The buffer bounds a
1464// getdents batch, never the descriptor numbers or number of open handles.
1465const NX_FD_DENT_BUFFER: i64 = 4096
1466const NX_SYS_CLOSE_RANGE: i64 = 436 // Linux x86_64 and asm-generic ABI
1467const NX_FD_UINT_MAX: i64 = 4294967295
1468func sys_close_inherited_proc(first: i64) -> i64 {
1469 let directory: i64=sys_openat_rd("/proc/self/fd")
1470 if directory < 0 { return directory }
1471 let buf: *u8=sys_mmap(NX_FD_DENT_BUFFER)
1472 var result: i64=0
1473 var running: i64=1
1474 while running == 1 {
1475 let n: i64=sys_getdents64(directory,buf,NX_FD_DENT_BUFFER)
1476 if n == (0-4) { continue }
1477 if n <= 0 { result=n; break }
1478 var off: i64=0
1479 while off < n {
1480 if n-off < 20 { result=0-5; running=0; break }
1481 let rec: *u8=buf+off
1482 let size: i64=dirent_reclen(rec)
1483 if size < 20 || size > n-off { result=0-5; running=0; break }
1484 var i: i64=19
1485 var fd: i64=0
1486 var valid: i64=1
1487 while i < size {
1488 let c: i64=rec[i] as i64
1489 if c == 0 { break }
1490 if c < 48 || c > 57 { valid=0; break }
1491 if fd > (2147483647-(c-48))/10 { valid=0; break }
1492 fd=fd*10+c-48; i=i+1
1493 }
1494 if i == 19 || i == size { valid=0 }
1495 if valid == 1 && fd >= first && fd != directory {
1496 // Linux releases the descriptor even when close reports a late
1497 // I/O error; never retry close and risk a reused descriptor.
1498 let closed: i64=sys_close(fd)
1499 if closed < 0 && closed != (0-9) { result=closed; running=0; break }
1500 }
1501 off=off+size
1502 }
1503 }
1504 let closedir: i64=sys_close(directory)
1505 sys_munmap(buf,NX_FD_DENT_BUFFER)
1506 if result == 0 && closedir < 0 { result=closedir }
1507 return result
1508}
1509func sys_close_inherited(first: i64) -> i64 {
1510 if first < 0 { return 0-22 }
1511 let rc: i64=__syscall(NX_SYS_CLOSE_RANGE,first,NX_FD_UINT_MAX,0,0,0,0)
1512 if rc == (0-38) { return sys_close_inherited_proc(first) }
1513 return rc
1514}
1515func sys_execve_clean(path: *u8, argv: *i64, envp: *i64) -> i64 {
1516 let rc: i64=sys_close_inherited(3)
1517 if rc < 0 { return rc }
1518 return sys_execve(path,argv,envp)
1519}
1520
1521func sys_execve(path: *u8, argv: *i64, envp: *i64) -> i64 {
1522 return __syscall(SYS_EXECVE, path, argv, envp, 0, 0, 0)
1523}
1524
1525// Wait for a child to exit. `pid` = -1 waits for ANY child,
1526// otherwise waits for that specific PID. `status` is a caller-
1527// mmapped i64 slot: on exit the low 16 bits carry Linux's w* status
1528// flags (WIFEXITED / WEXITSTATUS). Returns the reaped child's PID
1529// or -errno.
1530func sys_wait4(pid: i64, status: *i64, options: i64) -> i64 {
1531 return __syscall(SYS_WAIT4, pid, status, options, 0, 0, 0)
1532}
1533
1534// Extract exit code from a wait4 status word. Matches the glibc
1535// WEXITSTATUS macro: bits 8-15 of the low 16.
1536func wait_exit_code(status: i64) -> i64 {
1537 return (status >> 8) & 0xFF
1538}
1539
1540// Terminating signal from a wait4 status (0 when the child exited normally). Sibling of
1541// wait_exit_code; RESTORED 2026-07-30 after a stale whole-tree push erased both it and
1542// sys_ignore_sigpipe below, while three files still CALLED them (nx_http_server, nx_sigpipe_gate,
1543// nx_tools_api_serve) -- so the tree could not build until they came back.
1544func wait_term_signal(status: i64) -> i64 {
1545 return status & 0x7f
1546}
1547
1548// THE ONE RULER for "what result code did this process actually produce". Use this, not
1549// wait_exit_code, anywhere the answer becomes a VERDICT.
1550//
1551// WHY IT EXISTS, MEASURED 2026-08-25. wait_exit_code is WEXITSTATUS and is correctly named:
1552// bits 8-15 of the status word. But a child KILLED BY A SIGNAL has no exit status at all, and
1553// those bits are ZERO -- so a SEGFAULTING process is indistinguishable from a clean exit 0 to
1554// every caller that reads only wait_exit_code. Measured live: a gate that SIGSEGV'd mid-run was
1555// served by /api/gate_run as exit_code 0, verdict GREEN. A CRASHED GATE WORE A PASS.
1556//
1557// This is not a new discovery in this estate -- and that is the point. nx_gatekit_lib's
1558// gk_wait_code already carried exactly this rule, with its own measurement recorded (two gates
1559// the 60 s watchdog KILLED journaled `GREEN exit=0 ms=60443`). It was fixed THERE in August and
1560// left unfixed in nx_tool_run, which is the shared exec primitive sitting behind /api/gate_run,
1561// /api/build and 51 other consumers. A LAW APPLIED IN ONE ORGAN AND NOT ITS SIBLING IS HALF A
1562// LAW, AND THE HALF LEFT UNDONE IS THE ONE ON THE PRODUCTION PATH. So the rule now lives HERE,
1563// beside the two accessors it is composed of, and gk_wait_code delegates to it: one ruler.
1564//
1565// Shell convention 128+signal (137 SIGKILL, 139 SIGSEGV) is deliberate: it makes the death both
1566// VISIBLE and NON-ZERO, so every existing caller that branches on rc != 0 sees it with no change.
1567// wait_exit_code is left EXACTLY as it was -- 85 call sites across the corpus (corpus_complete=1)
1568// read it, and silently redefining WEXITSTATUS under them would be the cure being worse.
1569func wait_status_rc(status: i64) -> i64 {
1570 let sig: i64 = wait_term_signal(status)
1571 if sig != 0 { return 128 + sig }
1572 return wait_exit_code(status)
1573}
1574
1575// Ignore SIGPIPE process-wide, so writing to a socket the peer already closed returns -EPIPE
1576// instead of KILLING the process. SIGPIPE default action is TERMINATE, which for a daemon means
1577// every client that walks away mid-response is an outage -- this one call at the listen primitive
1578// is inherited by all 52 consumers of nx_http_server_listen.
1579// rt_sigaction(SIGPIPE, {handler=SIG_IGN}, NULL, 8): syscall 13 on x86-64, which happens to equal
1580// the signal number. SA_RESTORER is deliberately NOT set -- the kernel consults it only when it
1581// DELIVERS a handler frame, and SIG_IGN never delivers one.
1582// PROVEN, not asserted: nx_sigpipe_gate forks a child that writes to a closed pipe and demands
1583// death-by-signal-13 WITHOUT this call and a clean -EPIPE WITH it.
1584// Restore a signal to its DEFAULT disposition. THE INVERSE OF sys_ignore_sigpipe, and it exists
1585// because SIG_IGN is inherited across BOTH fork and execve: a daemon that ignores SIGPIPE hands
1586// that ignore to every child it spawns, FOREVER. That silently corrupted verification -- the
1587// sigpipe gate reported 4/5 RED under /api/gate_run and 5/5 GREEN under a shell, same binary,
1588// same minute, because its DISEASE control (writing to a closed peer must KILL) could not be
1589// observed inside an environment where the kill was already disabled (seq1463). A harness must
1590// not change the state it is verifying; where it must, it has to hand back a clean slate.
1591// ⚠the same inheritance can also produce a FALSE GREEN, which is the far more dangerous half.
1592func sys_default_signal(sig: i64) -> i64 {
1593 let act: *i64 = sys_mmap(64) as *i64
1594 act[0] = 0
1595 act[1] = 0
1596 act[2] = 0
1597 act[3] = 0
1598 return __syscall(13, sig, act as i64, 0, 8, 0, 0)
1599}
1600
1601func sys_ignore_sigpipe() -> i64 {
1602 let act: *i64 = sys_mmap(64) as *i64
1603 act[0] = 1
1604 act[1] = 0
1605 act[2] = 0
1606 act[3] = 0
1607 return __syscall(13, 13, act as i64, 0, 8, 0, 0)
1608}
1609
1610// Create a pipe. `fds` must point at 8+ writable bytes; the kernel
1611// packs BOTH int32 fds into fds[0]: read end = low 32 bits, write end
1612// = HIGH 32 bits (fds[1] is never written -- the old comment claiming
1613// fds[1]=write-end caused a false-pass KAT + a hung gate, 2026-07-16).
1614// Extract: rfd = fds[0] & 0xffffffff; wfd = (fds[0] / 4294967296) &
1615// 0xffffffff. Returns 0 on success, -errno on failure.
1616func sys_pipe2(fds: *i64, flags: i64) -> i64 {
1617 return __syscall(SYS_PIPE2, fds, flags, 0, 0, 0, 0)
1618}
1619
1620// Duplicate `oldfd` onto `newfd`, closing `newfd` first if open.
1621// Used to wire child stdout to a pipe: dup3(pipe_write_end, 1).
1622func sys_dup3(oldfd: i64, newfd: i64, flags: i64) -> i64 {
1623 return __syscall(SYS_DUP3, oldfd, newfd, flags, 0, 0, 0)
1624}
1625
1626// ---- directory listing (Linux RV64 getdents64) ---------------
1627//
1628// Foundation for ls / glob / dir-walk helpers. Linux returns
1629// linux_dirent64 records:
1630// u64 d_ino (inode, ignored here)
1631// s64 d_off (next-record offset)
1632// u16 d_reclen (this record's byte length)
1633// u8 d_type (file type; DT_DIR=4, DT_REG=8, DT_LNK=10)
1634// char d_name[] (null-terminated name, padded so d_reclen
1635// carries us to the next record boundary)
1636// Total struct header: 19 bytes, then name up to d_reclen - 19.
1637
1638@ifdef TARGET_X86_64
1639const SYS_GETDENTS64: i64 = 217
1640@endif
1641@ifndef TARGET_X86_64
1642const SYS_GETDENTS64: i64 = 61
1643@endif
1644
1645const DT_UNKNOWN: i64 = 0
1646const DT_FIFO: i64 = 1
1647const DT_CHR: i64 = 2
1648const DT_DIR: i64 = 4
1649const DT_BLK: i64 = 6
1650const DT_REG: i64 = 8
1651const DT_LNK: i64 = 10
1652const DT_SOCK: i64 = 12
1653
1654// Raw syscall. Returns bytes written on success (0 = end-of-dir),
1655// or -errno on failure.
1656func sys_getdents64(fd: i64, buf: *u8, buf_len: i64) -> i64 {
1657 return __syscall(SYS_GETDENTS64, fd, buf, buf_len, 0, 0, 0)
1658}
1659
1660// Extract fields from a linux_dirent64 record. `rec` points at
1661// the start of the record; fields are at fixed offsets.
1662func dirent_reclen(rec: *u8) -> i64 {
1663 // d_reclen is u16 at offset 16. Read as two bytes little-endian.
1664 let lo: i64 = rec[16]
1665 let hi: i64 = rec[17]
1666 return lo | (hi << 8)
1667}
1668
1669func dirent_type(rec: *u8) -> i64 {
1670 return rec[18]
1671}
1672
1673// Pointer to the null-terminated name inside the record.
1674func dirent_name(rec: *u8) -> *u8 {
1675 let base: i64 = rec as i64
1676 return (base + 19) as *u8
1677}
1678
1679// ---- content-addressed file reader ---------------------------
1680
1681func sys_read_file(path: *u8, out_len: *i64) -> *u8 {
1682 let fd: i64 = sys_openat_rd(path)
1683 if fd < 0 {
1684 *out_len = 0
1685 return 0 as *u8
1686 }
1687 // DEBT-EATEN 2026-07-15: the old fixed 4 GiB cap SILENTLY TRUNCATED bigger files (a 9 GB gguf would
1688 // short-read into plausible-garbage tensors -- the worst failure class). Now the buffer is sized from
1689 // the file itself (lseek END), so ANY size reads fully. Physical pages still allocate on-demand. For
1690 // zero-copy any-size READ-ONLY access prefer sys_map_file (below).
1691 // DEBT-EATEN 2026-08-19 (1787076780): when the size is UNKNOWABLE (lseek END <= 0: /proc files, pipes
1692 // -- AND every empty regular file, which reports 0 just the same) this used to reserve
1693 // SYS_MAGIC_4294967296 of address space per call. Untouched pages were never resident, but the
1694 // mapping WAS: a daemon that read an empty registry every sweep ballooned its VmSize by 4 GiB per
1695 // read (measured: smoke instances at a 4.2 GB base), the leak screens flagged it, and sys_free_file
1696 // could only release what was read. The size-unknowable path now GROWS: start at SYS_READ_GROW_INIT,
1697 // double while the window fills, and hand back an EXACT mapping (total + 16) so sys_free_file
1698 // releases all of it. An empty file costs one small read and a 16-byte arena cell; /proc/stat fits
1699 // the first window; a pipe of any length still reads whole. The known-size path is unchanged.
1700 let fsz: i64 = sys_lseek(fd, 0, 2)
1701 sys_lseek(fd, 0, 0)
1702 var cap: i64 = SYS_READ_GROW_INIT
1703 var grow: i64 = 1
1704 if fsz > 0 { cap = fsz; grow = 0 }
1705 var buf: *u8 = sys_mmap(cap + 16)
1706 var total: i64 = 0
1707 var go: i64 = 1
1708 while go == 1 {
1709 let base: i64 = buf as i64
1710 let tail: *u8 = (base + total) as *u8
1711 let n: i64 = sys_read(fd, tail, cap - total)
1712 if n <= 0 { go = 0 }
1713 if n > 0 { total = total + n }
1714 if total >= cap {
1715 if grow == 0 { go = 0 } else {
1716 // the window filled and the size is unknown: double it, copy, release the old mapping
1717 let ncap: i64 = cap * 2
1718 let nb: *u8 = sys_mmap(ncap + 16)
1719 var ci: i64 = 0
1720 let obase: i64 = buf as i64
1721 let nbase: i64 = nb as i64
1722 while ci < total { let src: *u8 = (obase + ci) as *u8; let dst: *u8 = (nbase + ci) as *u8; dst[0] = src[0]; ci = ci + 1 }
1723 sys_munmap(buf, cap + 16)
1724 buf = nb
1725 cap = ncap
1726 }
1727 }
1728 }
1729 sys_close(fd)
1730 if grow == 1 {
1731 // hand back an EXACT mapping so the paired free releases everything (the doubled window would
1732 // otherwise leave its slack mapped forever -- the address-space leak this change exists to end)
1733 let xb: *u8 = sys_mmap(total + 16)
1734 var xi: i64 = 0
1735 let gbase: i64 = buf as i64
1736 let xbase: i64 = xb as i64
1737 while xi < total { let gsrc: *u8 = (gbase + xi) as *u8; let xdst: *u8 = (xbase + xi) as *u8; xdst[0] = gsrc[0]; xi = xi + 1 }
1738 sys_munmap(buf, cap + 16)
1739 buf = xb
1740 }
1741 // Null-terminate for the lexer.
1742 let bbase: i64 = buf as i64
1743 let term: *u8 = (bbase + total) as *u8
1744 term[0] = 0
1745 *out_len = total
1746 return buf
1747}
1748
1749// PAIRED FREE FOR sys_read_file (2026-08-17). sys_read_file mmaps `cap + 16` where cap is the FILE SIZE
1750// and returns only the pointer -- so any caller that frees it must know the padding, and a caller that
1751// unmaps `len` alone leaks the tail page whenever the file size sits just under a page boundary.
1752// ★A CALLER FORCED TO KNOW ITS ALLOCATOR'S PADDING IS A COUPLING THAT WILL DRIFT -- so the +16 lives
1753// HERE, beside the +16 it mirrors, instead of being retyped at every call site.
1754// Pass the length sys_read_file reported through out_len; this re-derives the mapping from it.
1755// Null-safe by construction: sys_read_file returns 0 on failure, so callers need no extra guard --
1756// ★A FREE THAT REFUSES NULL IS A FREE NOBODY HAS TO WRAP IN AN IF.
1757// EXACT for every path since 2026-08-19: the size-unknowable fallback (lseek <= 0: /proc, pipes, empty
1758// regular files) now returns a mapping of exactly total + 16, so this releases ALL of it. (It used to
1759// map SYS_MAGIC_4294967296 of address space and release only what was read -- stated then, ended now.)
1760// WHY IT EXISTS: nx_sites_daemon serves /wiki/roadmap by calling sys_read_file PER REQUEST inside a loop
1761// that runs up to NX_SD_MAX_REQ_PER_CONN (64) times per connection and never released it -- an 8,408 B
1762// file became 3 fresh pages and a fresh kernel VMA on every hit, held until the child exited.
1763func sys_free_file(buf: *u8, len: i64) -> i64 {
1764 if (buf as i64) == 0 { return 0 }
1765 if len < 0 { return 0 }
1766 return sys_munmap(buf, len + 16)
1767}
1768
1769// Read-only FILE-BACKED map of the whole file (PROT_READ=1, MAP_PRIVATE=2): any size, zero-copy -- only
1770// touched pages become resident (the lazy-MoE shape: a 9 GB model serves in ~active-set RSS, and load
1771// time is ~0 because nothing is copied). NO NUL pad (a file mapping cannot be extended) -- BINARY
1772// consumers only; text/lexer callers keep sys_read_file. Returns 0 on failure; *out_len = file size.
1773// Read-only by construction (PROT_READ; writes fault -- Rule 26-friendly).
1774func sys_map_file(path: *u8, out_len: *i64) -> *u8 {
1775 *out_len = 0
1776 let fd: i64 = sys_openat_rd(path)
1777 if fd < 0 { return 0 as *u8 }
1778 let fsz: i64 = sys_lseek(fd, 0, 2)
1779 if fsz <= 0 { sys_close(fd); return 0 as *u8 }
1780 let r: i64 = __syscall(SYS_MMAP, 0, fsz, 1, 2, fd, 0)
1781 sys_close(fd)
1782 if r <= 0 { return 0 as *u8 }
1783 *out_len = fsz
1784 return r as *u8
1785}
1786
1787// Sleep for `ms` milliseconds against CLOCK_MONOTONIC (relative).
1788// Returns 0 on success, negative errno on failure. Caller-supplied
1789// budget: ms <= 0 is a no-op; very large values are accepted as-is
1790// (the kernel will saturate to its own clamp). Defined at the bottom
1791// of this file so sys_mmap is in scope (single-pass parser).
1792func sys_sleep_ms(ms: i64) -> i64 {
1793 if ms <= 0 { return 0 }
1794 // struct timespec { sec: i64, nsec: i64 } -- 16 bytes RV64.
1795 let req: *u8 = sys_mmap(16)
1796 let rem: *u8 = sys_mmap(16)
1797 let secs: i64 = ms / 1000
1798 let nsec: i64 = (ms - secs * 1000) * SYS_MAGIC_1000000 // remainder ms -> ns
1799 let req_sec: *i64 = req as *i64
1800 let req_nsec: *i64 = ((req as i64) + 8) as *i64
1801 req_sec[0] = secs
1802 req_nsec[0] = nsec
1803 // clock_nanosleep(CLOCK_MONOTONIC=1, flags=0, req, rem). On EINTR (-4) a signal (e.g. SIGCHLD from a
1804 // reaped child) cut the sleep short and wrote the leftover into rem -- RESUME it, otherwise a caller
1805 // that uses the sleep as a timer (the torrent pool's 2s tick) gets spun into a busy loop by child
1806 // deaths and any tick-based budget collapses to milliseconds. A sleep must sleep its full duration.
1807 var r: i64 = __syscall(SYS_CLOCK_NANOSLEEP, 1, 0, req as i64, rem as i64, 0, 0)
1808 var guard: i64 = 0
1809 while r == (0 - 4) {
1810 if guard > SYS_MAGIC_100000 { r = 0 } else {
1811 let rs: *i64 = rem as *i64
1812 let rn: *i64 = ((rem as i64) + 8) as *i64
1813 req_sec[0] = rs[0]
1814 req_nsec[0] = rn[0]
1815 r = __syscall(SYS_CLOCK_NANOSLEEP, 1, 0, req as i64, rem as i64, 0, 0)
1816 guard = guard + 1
1817 }
1818 }
1819 sys_munmap(req, 16); sys_munmap(rem, 16) // FREE the timespec pages -- every call mmap'd 2 pages; in a
1820 // long-running poll loop (the supervisor's 15s tick) that leaked ~8KB/iter until mmap -> -12 -> SEGFAULT.
1821 return r
1822}
1823
1824// ---- sockets (RV64 generic syscall numbers) ----------------------
1825//
1826// Source uses RV64 numbers; the x86_64 backend's
1827// x86ctx_rv64_to_x86_64_syscall table translates at codegen time.
1828// Numbers from arch/arm64/include/asm/unistd.h (RV64 inherits the
1829// generic ABI).
1830
1831// Socket-family syscall numbers via @ifdef macro -- mirrors the
1832// pattern already used for SYS_READ/WRITE/MMAP/etc. above. Without
1833// this gate, --target x86_64 compiled the RV64 numbers as literals
1834// into the `syscall` instruction (e.g. 198 = sched_setaffinity on
1835// x86_64, not socket) and any daemon using sys_socket() died with
1836// ENOSYS before printing its banner -- caught by the nx_signaling
1837// stone S2 deploy on 2026-05-20 (see [[project-cross-isa-syscall-
1838// unification-gap-2026-05-20]]).
1839@ifdef TARGET_X86_64
1840const SYS_SOCKET: i64 = 41
1841const SYS_BIND: i64 = 49
1842const SYS_LISTEN: i64 = 50
1843const SYS_ACCEPT: i64 = 43
1844const SYS_CONNECT: i64 = 42
1845const SYS_SETSOCKOPT: i64 = 54
1846const SYS_SENDTO: i64 = 44
1847const SYS_RECVFROM: i64 = 45
1848const SYS_SHUTDOWN: i64 = 48
1849@endif
1850
1851@ifndef TARGET_X86_64
1852const SYS_SOCKET: i64 = 198
1853const SYS_BIND: i64 = 200
1854const SYS_LISTEN: i64 = 201
1855const SYS_ACCEPT: i64 = 202
1856const SYS_CONNECT: i64 = 203
1857const SYS_SETSOCKOPT: i64 = 208
1858const SYS_SENDTO: i64 = 206
1859const SYS_RECVFROM: i64 = 207
1860const SYS_SHUTDOWN: i64 = 210
1861@endif
1862
1863// Socket-option constants used by nx_http_server / nx_https_server.
1864const SOL_SOCKET: i64 = 1
1865const SO_REUSEADDR: i64 = 2
1866// Receive/send timeouts (Linux x86_64). optval is a struct timeval
1867// {tv_sec: i64, tv_usec: i64} (16 bytes). Essential on PUBLIC sockets:
1868// without them, a single silent/slow client hangs a blocking read
1869// forever -> trivial DoS on a single-threaded accept loop.
1870const SO_SNDTIMEO: i64 = 21
1871const SO_RCVTIMEO: i64 = 20
1872
1873// setsockopt(2) -- set a socket option. Defined BEFORE its first caller
1874// (sys_set_socket_timeout, below): NishiLang forbids forward references,
1875// so the definition must precede every use.
1876func sys_setsockopt(fd: i64, level: i64, optname: i64,
1877 optval: *u8, optlen: i64) -> i64 {
1878 return __syscall(SYS_SETSOCKOPT, fd, level, optname, optval, optlen, 0)
1879}
1880
1881// Set a receive+send timeout (in whole seconds) on a socket fd.
1882// tv is munmap'd before return (LEAK FIXED 2026-07-16): this is called once per PROBE by the daemon
1883// supervisor (35/cycle forever -> ~800MB VSZ/day) and once per CONNECTION by fork-per-connection daemons.
1884// The unfreed page-per-call ballooned VSZ until heuristic overcommit made fork() return -ENOMEM (the
1885// proven pid=-12 failure class) -- likely the historical VSZ pressure behind the vsz_watchdog.
1886func sys_set_socket_timeout(fd: i64, secs: i64) -> i64 {
1887 let tv: *i64 = (sys_mmap(16)) as *i64
1888 tv[0] = secs // tv_sec
1889 tv[1] = 0 // tv_usec
1890 sys_setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, tv as *u8, 16)
1891 sys_setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, tv as *u8, 16)
1892 sys_munmap(tv as *u8, 16)
1893 return 0
1894}
1895
1896// alarm(2): deliver SIGALRM after `secs` seconds (0 cancels a pending alarm). No SIGALRM handler is installed, so
1897// the default action TERMINATES the process. Used as a per-request watchdog inside a forked request-child: a
1898// pathologically-slow page can then never hang the child forever (which would leak its buffers + pile up procs).
1899const SYS_ALARM: i64 = 37
1900func sys_alarm(secs: i64) -> i64 { return __syscall(SYS_ALARM, secs, 0, 0, 0, 0, 0) }
1901
1902const AF_INET: i64 = 2
1903const SOCK_STREAM: i64 = 1
1904const SOCK_DGRAM: i64 = 2
1905
1906func sys_socket(domain: i64, sock_type: i64, protocol: i64) -> i64 {
1907 return __syscall(SYS_SOCKET, domain, sock_type, protocol, 0, 0, 0)
1908}
1909// Pack an AF_INET any-address sockaddr_in (16 bytes) for `port` at `addr`.
1910// RESTORED INTO THE OWNER 2026-08-19: this lived in the old full nx_syscalls_x86_64.nx and was the
1911// one wrapper WITH LIVE CALLERS (nx_nishipages_serve, nx_udp) that the 2026-07-31 alias-stub
1912// consolidation dropped -- both lanes sat NAS-unbuildable ("I do not know the name") until the
1913// rebuild-drain surfaced them. Body verbatim from the old file, including its documented
1914// workaround: NO `as u8` casts on the byte stores -- the array-element-store already truncates
1915// when the lvalue is *u8, and casts on this path once tripped a codegen defect.
1916// (The old file's other two uncalled orphans, sys_pivot_root/sys_umount2, were left dead on a
1917// zero-caller full-tree grep -- restoring an uncalled wrapper is inventory, not capability.)
1918func sockaddr_in_init(addr: *u8, port: i64) -> i64 {
1919 addr[0] = 2 // AF_INET low byte
1920 addr[1] = 0
1921 // Port in network byte order (big-endian).
1922 let hi: i64 = (port >> 8) & 0xFF
1923 let lo: i64 = port & 0xFF
1924 addr[2] = hi
1925 addr[3] = lo
1926 addr[4] = 0
1927 addr[5] = 0
1928 addr[6] = 0
1929 addr[7] = 0
1930 addr[8] = 0
1931 addr[9] = 0
1932 addr[10] = 0
1933 addr[11] = 0
1934 addr[12] = 0
1935 addr[13] = 0
1936 addr[14] = 0
1937 addr[15] = 0
1938 return 0
1939}
1940
1941func sys_bind(fd: i64, addr: *u8, addr_len: i64) -> i64 {
1942 return __syscall(SYS_BIND, fd, addr, addr_len, 0, 0, 0)
1943}
1944func sys_listen(fd: i64, backlog: i64) -> i64 {
1945 return __syscall(SYS_LISTEN, fd, backlog, 0, 0, 0, 0)
1946}
1947// accept(2) -- accept the next pending connection on a listening socket.
1948// Single-arg form (kernel ignores NULL addr/addr_len writes). Existing
1949// nx_http_server callers use this signature; the 3-arg form is provided
1950// as sys_accept_with_addr for outliers needing peer address.
1951func sys_accept(fd: i64) -> i64 {
1952 return __syscall(SYS_ACCEPT, fd, 0, 0, 0, 0, 0)
1953}
1954func sys_accept_with_addr(fd: i64, addr: *u8, addr_len: *i64) -> i64 {
1955 return __syscall(SYS_ACCEPT, fd, addr, addr_len, 0, 0, 0)
1956}
1957// shutdown(2) -- half-close a socket. how: 0=RD, 1=WR, 2=RDWR.
1958func sys_shutdown(fd: i64, how: i64) -> i64 {
1959 return __syscall(SYS_SHUTDOWN, fd, how, 0, 0, 0, 0)
1960}
1961func sys_connect(fd: i64, addr: *u8, addr_len: i64) -> i64 {
1962 return __syscall(SYS_CONNECT, fd, addr, addr_len, 0, 0, 0)
1963}
1964func sys_sendto(fd: i64, buf: *u8, n: i64, flags: i64,
1965 dest_addr: *u8, addr_len: i64) -> i64 {
1966 return __syscall(SYS_SENDTO, fd, buf, n, flags, dest_addr, addr_len)
1967}
1968func sys_recvfrom(fd: i64, buf: *u8, n: i64, flags: i64,
1969 src_addr: *u8, addr_len: *i64) -> i64 {
1970 return __syscall(SYS_RECVFROM, fd, buf, n, flags, src_addr, addr_len)
1971}
1972
1973// ---- SCM_RIGHTS DESCRIPTOR PASSING (sendmsg/recvmsg over AF_UNIX) -----------------------------
1974// ADDED 2026-08-21 for /compare/trafficsafety TS1. Until now sys_sendmsg was ABSENT-PROVEN from the
1975// whole tree (corpus_complete=1), so the mechanism nginx, HAProxy and Envoy all use for hitless
1976// replacement -- MOVING the listening descriptor rather than re-binding it -- could not be written
1977// at all. SO_REUSEPORT co-binding is an ACCEPT-DISTRIBUTION primitive, NOT a handoff primitive:
1978// LWN documents that changing the set of listening sockets on a port drops connections during the
1979// three-way handshake, so co-binding proves two binders and can never prove zero drops.
1980//
1981// EVERY OFFSET BELOW IS MEASURED, NOT RECALLED. They were read out of the platform's own headers
1982// with offsetof/sizeof/CMSG_LEN compiled for x86_64:
1983// msghdr 56 = name 0 | namelen 8 (u32) | iov 16 | iovlen 24 | control 32 | controllen 40 | flags 48 (u32)
1984// iovec 16 = base 0 | len 8
1985// cmsghdr 16 = len 0 (u64) | level 8 (u32) | type 12 (u32), data at 16
1986// CMSG_LEN(4)=20 CMSG_SPACE(4)=24 sendmsg=46 recvmsg=47 socketpair=53
1987// AF_UNIX=1 SOL_SOCKET=1 SCM_RIGHTS=1 MSG_CMSG_CLOEXEC=1073741824
1988// A WRONG LAYOUT HERE DOES NOT FAIL LOUD. The syscall still returns a positive byte count and
1989// simply transfers no descriptor, which is why the gate for this proves the property by passing a
1990// REAL descriptor between two REAL processes and then USING it, never by reading a return code.
1991// x86_64 Linux numbers, DELIBERATELY UNGUARDED, and the reason is a measurement rather than a
1992// preference. The first draft of this block wrapped these three in the same
1993// @ifdef TARGET_X86_64 / @ifndef pair every other syscall number in this file uses. On an x86 build
1994// that made every call ENOSYS, and the probe that caught it printed why:
1995// CONSTS SYS_SENDMSG=211 SYS_RECVMSG=212 SYS_SOCKETPAIR=199 SYS_WRITE=64
1996// N sendmsg PLAIN via the CONST rc=-38 (211 is unassigned on x86_64)
1997// N2 sendmsg PLAIN via the LITERAL rc=1
1998// SYS_WRITE reading 64 is the tell and it is NOT MINE: the file's own original guarded block
1999// resolves to its RV64 branch when the constant is referenced, on a build whose sys_write plainly
2000// works. So a constant inside these guards is not reliably the value the guard appears to select.
2001// !! A GUARD THAT SILENTLY SELECTS THE OTHER TARGET'S NUMBER IS WORSE THAN NO GUARD: the call still
2002// compiles, still returns, and dispatches a DIFFERENT SYSCALL. Syscall 199 on x86_64 is
2003// fremovexattr, which is why socketpair appeared to answer EFAULT for every input including a NULL
2004// vector and an unsupported domain -- varying the ARGUMENTS can never reveal that the NUMBER is
2005// wrong, because every variant was equally wrong.
2006// => RV64 support for these three is an OPEN, NAMED requirement, blocked on that toolchain
2007// behaviour. It is left undone and stated rather than papered over with a guard measured not to
2008// work. The estate already keeps nx_syscalls_x86_64.nx as the explicit single-target mirror for
2009// exactly this class of problem.
2010const SYS_SENDMSG: i64 = 46
2011const SYS_RECVMSG: i64 = 47
2012const SYS_SOCKETPAIR: i64 = 53
2013const SCM_AF_UNIX: i64 = 1
2014const SCM_SOL_SOCKET: i64 = 1
2015const SCM_RIGHTS_TYPE: i64 = 1
2016const SCM_MSG_CMSG_CLOEXEC: i64 = 1073741824
2017const SCM_MSGHDR_BYTES: i64 = 56
2018const SCM_MSGHDR_OFF_IOV: i64 = 16
2019const SCM_MSGHDR_OFF_IOVLEN: i64 = 24
2020const SCM_MSGHDR_OFF_CTRL: i64 = 32
2021const SCM_MSGHDR_OFF_CTRLLEN: i64 = 40
2022const SCM_IOVEC_BYTES: i64 = 16
2023const SCM_IOVEC_OFF_BASE: i64 = 0
2024const SCM_IOVEC_OFF_LEN: i64 = 8
2025const SCM_CMSG_OFF_LEN: i64 = 0
2026const SCM_CMSG_OFF_LEVEL: i64 = 8
2027const SCM_CMSG_OFF_TYPE: i64 = 12
2028const SCM_CMSG_OFF_DATA: i64 = 16
2029const SCM_CMSG_LEN_1FD: i64 = 20
2030const SCM_CMSG_SPACE_1FD: i64 = 24
2031const SCM_IOV_COUNT_ONE: i64 = 1
2032const SCM_U32_BYTES: i64 = 4
2033const SCM_BYTE_RADIX: i64 = 256
2034const SCM_FDPAIR_BYTES: i64 = 8
2035// One real data byte travels with the ancillary data ON PURPOSE: a sendmsg carrying SCM_RIGHTS and
2036// NO ordinary payload is the classic silent no-transfer, and it returns 0 rather than an error.
2037const SCM_PAYLOAD_BYTES: i64 = 1
2038const SCM_PAYLOAD_BYTE: i64 = 70
2039// Distinguishable refusals, each naming WHICH conjunct failed -- a compound assertion that will not
2040// name its failing conjunct is a false-alarm generator. All are negative and all sit far outside the
2041// errno range, so no caller can confuse one with a kernel error or with a valid descriptor.
2042const SCM_ERR_NO_CMSG: i64 = 0 - 901
2043const SCM_ERR_CMSG_LEN: i64 = 0 - 902
2044const SCM_ERR_CMSG_LEVEL: i64 = 0 - 903
2045const SCM_ERR_CMSG_TYPE: i64 = 0 - 904
2046
2047func scm_zero(base: *u8, n: i64) -> i64 { var i: i64 = 0; while i < n { base[i] = 0; i = i + 1 } return 0 }
2048func scm_put_i64(base: *u8, off: i64, v: i64) -> i64 {
2049 let p: *i64 = ((base as i64) + off) as *i64
2050 p[0] = v
2051 return 0
2052}
2053func scm_get_i64(base: *u8, off: i64) -> i64 {
2054 let p: *i64 = ((base as i64) + off) as *i64
2055 return p[0]
2056}
2057// The two cmsg header fields and the descriptor slot itself are 4-byte ints, so they are packed and
2058// unpacked byte by byte in little-endian order. Radix arithmetic rather than bit shifts, matching
2059// sockaddr_in_init's documented style on this exact path.
2060func scm_put_u32(base: *u8, off: i64, v: i64) -> i64 {
2061 var i: i64 = 0
2062 var m: i64 = v
2063 while i < SCM_U32_BYTES {
2064 base[off + i] = m % SCM_BYTE_RADIX
2065 m = m / SCM_BYTE_RADIX
2066 i = i + 1
2067 }
2068 return 0
2069}
2070func scm_get_u32(base: *u8, off: i64) -> i64 {
2071 var v: i64 = 0
2072 var mult: i64 = 1
2073 var i: i64 = 0
2074 while i < SCM_U32_BYTES {
2075 v = v + (base[off + i] as i64) * mult
2076 mult = mult * SCM_BYTE_RADIX
2077 i = i + 1
2078 }
2079 return v
2080}
2081
2082func sys_sendmsg(fd: i64, msg: *u8, flags: i64) -> i64 {
2083 return __syscall(SYS_SENDMSG, fd, msg, flags, 0, 0, 0)
2084}
2085func sys_recvmsg(fd: i64, msg: *u8, flags: i64) -> i64 {
2086 return __syscall(SYS_RECVMSG, fd, msg, flags, 0, 0, 0)
2087}
2088// socketpair(2). sv receives TWO 4-byte descriptors, so it is a *u8 read with scm_get_u32 -- a
2089// single *i64 read would splice both descriptors into one number and the second would vanish.
2090// !! THIS NUMBER IS NOT REACHING socketpair, AND THE FIRST DIAGNOSIS OF THAT WAS WRONG.
2091// Measured 2026-08-21: every call returns -14 (EFAULT) -- with a valid pointer, with a NULL vector,
2092// and with an UNSUPPORTED DOMAIN alike. The first reading of that evidence was "the host refuses
2093// this call for every input", and it was REFUTED by measuring the emitted constants instead of the
2094// arguments. TARGET_X86_64 is hard-pinned UNDEFINED in this toolchain (see nx_syscalls_x86_64.nx
2095// and nx_tokenizer.nx), so the @ifndef branch is what compiles and the x86 backend TRANSLATES RV64
2096// syscall numbers at emit time. Under that translation 53 is RV64 fchmodat, whose SECOND argument
2097// is a path pointer -- and SOCK_STREAM==1 as a path pointer is exactly EFAULT, every time,
2098// regardless of the other arguments.
2099// * VARYING THE ARGUMENTS CAN NEVER REVEAL THAT THE SYSCALL NUMBER IS WRONG: every variant is
2100// equally wrong, so a set of controls that all agree reads as a confident finding about the host.
2101// The control that actually discriminated was PRINTING THE CONSTANT the binary emits.
2102// => The likely correct value here is the RV64 number 199, exactly as sendmsg/recvmsg above needed
2103// their own numbers rather than the guarded pair. That is NOT asserted: it is UNTESTED, and this
2104// comment says so rather than shipping a plausible number with a confident sentence.
2105// => NOTHING DEPENDS ON IT. The descriptor-passing lane uses a NAMED AF_UNIX rendezvous
2106// (sys_unix_listen + sys_unix_connect_fd below), which is proven end to end by nx_scm_rights_gate
2107// and is also what nginx, HAProxy and systemd actually use to move a listener between processes.
2108// socketpair was only ever the convenience.
2109func sys_socketpair(domain: i64, sock_type: i64, protocol: i64, sv: *u8) -> i64 {
2110 return __syscall(SYS_SOCKETPAIR, domain, sock_type, protocol, sv, 0, 0)
2111}
2112
2113// Bind+listen a NAMED AF_UNIX stream socket -- the accepting half of the rendezvous whose
2114// connecting half is nx_unix_connect. Returns the listening fd, or a negative errno.
2115// The caller owns the path: unlink it first (a stale node makes bind return EADDRINUSE) and unlink
2116// it after, because an AF_UNIX bind leaves a filesystem entry that outlives the process.
2117const SCM_SUN_PATH_OFF: i64 = 2 // sockaddr_un = [sa_family: u16][sun_path: 108]
2118const SCM_SUN_BYTES: i64 = 110
2119const SCM_SUN_PATH_MAX: i64 = 107
2120func sys_unix_listen(path: *u8, backlog: i64) -> i64 {
2121 let fd: i64 = sys_socket(SCM_AF_UNIX, SOCK_STREAM, 0)
2122 if fd < 0 { return fd }
2123 let sa: *u8 = sys_mmap(SCM_SUN_BYTES)
2124 var i: i64 = 0
2125 while i < SCM_SUN_BYTES { sa[i] = 0; i = i + 1 }
2126 sa[0] = SCM_AF_UNIX
2127 sa[1] = 0
2128 var p: i64 = 0
2129 while path[p] != (0 as u8) {
2130 if p >= SCM_SUN_PATH_MAX { sys_close(fd); return 0 - 36 }
2131 sa[SCM_SUN_PATH_OFF + p] = path[p]
2132 p = p + 1
2133 }
2134 let br: i64 = sys_bind(fd, sa, SCM_SUN_PATH_OFF + p + 1)
2135 if br < 0 { sys_close(fd); return br }
2136 let lr: i64 = sys_listen(fd, backlog)
2137 if lr < 0 { sys_close(fd); return lr }
2138 return fd
2139}
2140
2141// The CONNECTING half of the same rendezvous. Returns the connected fd or a negative errno.
2142// RESIDUAL NAMED RATHER THAN LEFT SILENT: nx_unix_socket.nx already carries an nx_unix_connect with
2143// this exact body. It is not composed here because that file also defines a main(), so importing it
2144// would inject a second main into every one of the 52 daemons that reach nx_http_server -- a
2145// resolution-by-definition-order hazard this tree has already been bitten by. The primitive belongs
2146// in the shim; the older standalone file should be reduced to a caller of this one, and that is a
2147// separate change to a file with its own consumers rather than something to fold in silently here.
2148func sys_unix_connect_fd(path: *u8) -> i64 {
2149 let fd: i64 = sys_socket(SCM_AF_UNIX, SOCK_STREAM, 0)
2150 if fd < 0 { return fd }
2151 let sa: *u8 = sys_mmap(SCM_SUN_BYTES)
2152 var i: i64 = 0
2153 while i < SCM_SUN_BYTES { sa[i] = 0; i = i + 1 }
2154 sa[0] = SCM_AF_UNIX
2155 sa[1] = 0
2156 var p: i64 = 0
2157 while path[p] != (0 as u8) {
2158 if p >= SCM_SUN_PATH_MAX { sys_close(fd); return 0 - 36 }
2159 sa[SCM_SUN_PATH_OFF + p] = path[p]
2160 p = p + 1
2161 }
2162 let cr: i64 = sys_connect(fd, sa, SCM_SUN_PATH_OFF + p + 1)
2163 if cr < 0 { sys_close(fd); return cr }
2164 return fd
2165}
2166
2167// Send ONE open descriptor over a connected AF_UNIX socket. Returns the sendmsg result: the number
2168// of ordinary data bytes sent (SCM_PAYLOAD_BYTES on success) or a negative errno. The descriptor
2169// itself is NOT closed here -- both ends legitimately hold it until the sender chooses to let go,
2170// and that overlap is the entire point: there must be no instant at which zero processes hold the
2171// listening socket.
2172func sys_send_fd(sock: i64, fd: i64) -> i64 {
2173 let msg: *u8 = sys_mmap(SCM_MSGHDR_BYTES)
2174 let iov: *u8 = sys_mmap(SCM_IOVEC_BYTES)
2175 let cbuf: *u8 = sys_mmap(SCM_CMSG_SPACE_1FD)
2176 let data: *u8 = sys_mmap(SCM_PAYLOAD_BYTES)
2177 scm_zero(msg, SCM_MSGHDR_BYTES)
2178 scm_zero(cbuf, SCM_CMSG_SPACE_1FD)
2179 data[0] = SCM_PAYLOAD_BYTE
2180 scm_put_i64(iov, SCM_IOVEC_OFF_BASE, data as i64)
2181 scm_put_i64(iov, SCM_IOVEC_OFF_LEN, SCM_PAYLOAD_BYTES)
2182 scm_put_i64(msg, SCM_MSGHDR_OFF_IOV, iov as i64)
2183 scm_put_i64(msg, SCM_MSGHDR_OFF_IOVLEN, SCM_IOV_COUNT_ONE)
2184 scm_put_i64(msg, SCM_MSGHDR_OFF_CTRL, cbuf as i64)
2185 scm_put_i64(msg, SCM_MSGHDR_OFF_CTRLLEN, SCM_CMSG_SPACE_1FD)
2186 scm_put_i64(cbuf, SCM_CMSG_OFF_LEN, SCM_CMSG_LEN_1FD)
2187 scm_put_u32(cbuf, SCM_CMSG_OFF_LEVEL, SCM_SOL_SOCKET)
2188 scm_put_u32(cbuf, SCM_CMSG_OFF_TYPE, SCM_RIGHTS_TYPE)
2189 scm_put_u32(cbuf, SCM_CMSG_OFF_DATA, fd)
2190 let r: i64 = sys_sendmsg(sock, msg, 0)
2191 sys_munmap(msg, SCM_MSGHDR_BYTES)
2192 sys_munmap(iov, SCM_IOVEC_BYTES)
2193 sys_munmap(cbuf, SCM_CMSG_SPACE_1FD)
2194 sys_munmap(data, SCM_PAYLOAD_BYTES)
2195 return r
2196}
2197
2198// Receive ONE descriptor from a connected AF_UNIX socket. Returns the NEW descriptor number in this
2199// process (>= 0), a negative errno from recvmsg, or one of the SCM_ERR_* codes above.
2200// flags: 0, or SCM_MSG_CMSG_CLOEXEC so the arriving descriptor is not leaked into grandchildren --
2201// the estate has already lost a port for six days to exactly that inheritance (nx_cloexec_gate).
2202// THE VALIDATION IS THE WHOLE POINT. recvmsg happily returns a positive byte count having delivered
2203// no ancillary data at all, so the kernel's REWRITTEN msg_controllen is read back rather than the
2204// value we asked for, and each of the three cmsg header fields is checked separately so a failure
2205// says which one.
2206func sys_recv_fd(sock: i64, flags: i64) -> i64 {
2207 let msg: *u8 = sys_mmap(SCM_MSGHDR_BYTES)
2208 let iov: *u8 = sys_mmap(SCM_IOVEC_BYTES)
2209 let cbuf: *u8 = sys_mmap(SCM_CMSG_SPACE_1FD)
2210 let data: *u8 = sys_mmap(SCM_PAYLOAD_BYTES)
2211 scm_zero(msg, SCM_MSGHDR_BYTES)
2212 scm_zero(cbuf, SCM_CMSG_SPACE_1FD)
2213 scm_put_i64(iov, SCM_IOVEC_OFF_BASE, data as i64)
2214 scm_put_i64(iov, SCM_IOVEC_OFF_LEN, SCM_PAYLOAD_BYTES)
2215 scm_put_i64(msg, SCM_MSGHDR_OFF_IOV, iov as i64)
2216 scm_put_i64(msg, SCM_MSGHDR_OFF_IOVLEN, SCM_IOV_COUNT_ONE)
2217 scm_put_i64(msg, SCM_MSGHDR_OFF_CTRL, cbuf as i64)
2218 scm_put_i64(msg, SCM_MSGHDR_OFF_CTRLLEN, SCM_CMSG_SPACE_1FD)
2219 let r: i64 = sys_recvmsg(sock, msg, flags)
2220 var out: i64 = r
2221 if r >= 0 {
2222 out = SCM_ERR_NO_CMSG
2223 if scm_get_i64(msg, SCM_MSGHDR_OFF_CTRLLEN) >= SCM_CMSG_LEN_1FD {
2224 out = SCM_ERR_CMSG_LEN
2225 if scm_get_i64(cbuf, SCM_CMSG_OFF_LEN) == SCM_CMSG_LEN_1FD {
2226 out = SCM_ERR_CMSG_LEVEL
2227 if scm_get_u32(cbuf, SCM_CMSG_OFF_LEVEL) == SCM_SOL_SOCKET {
2228 out = SCM_ERR_CMSG_TYPE
2229 if scm_get_u32(cbuf, SCM_CMSG_OFF_TYPE) == SCM_RIGHTS_TYPE {
2230 out = scm_get_u32(cbuf, SCM_CMSG_OFF_DATA)
2231 }
2232 }
2233 }
2234 }
2235 }
2236 sys_munmap(msg, SCM_MSGHDR_BYTES)
2237 sys_munmap(iov, SCM_IOVEC_BYTES)
2238 sys_munmap(cbuf, SCM_CMSG_SPACE_1FD)
2239 sys_munmap(data, SCM_PAYLOAD_BYTES)
2240 return out
2241}
2242
2243// Ordinary permission bits only. Special privilege bits are never copied by staging.
2244const NX_FILE_PERMISSION_MASK:i64=511
2245const NX_FILE_DESCRIPTOR_INVALID:i64=0-22
2246func sys_fchmod_fd(fd:i64,mode:i64)->i64{
2247 if fd<0 || mode<0 || mode>NX_FILE_PERMISSION_MASK {return NX_FILE_DESCRIPTOR_INVALID}
2248 return __syscall(52,fd,mode,0,0,0,0)
2249}
2250// Portable descriptor syscall; consumers below use the x86-64 stat ABI layout.
2251const NX_STAT_X64_BYTES:i64=144
2252const NX_STAT_X64_MODE_OFFSET:i64=24
2253const NX_STAT_X64_BLOCK_OFFSET:i64=56
2254const NX_STAT_X64_SIZE_OFFSET:i64=48
2255const NX_STAT_X64_DEVICE_OFFSET:i64=0
2256const NX_STAT_X64_INODE_OFFSET:i64=8
2257const NX_STAT_TYPE_MASK:i64=61440
2258const NX_STAT_REGULAR_FILE:i64=32768
2259func sys_fstat_fd(fd:i64,stat:*u8)->i64{
2260 if fd<0 || (stat as i64)==0{return NX_FILE_DESCRIPTOR_INVALID}
2261 return __syscall(80,fd,stat,0,0,0,0)
2262}
2263func sys_stat_permissions(stat:*u8)->i64{
2264 let mode:i64=(stat[NX_STAT_X64_MODE_OFFSET] as i64)+((stat[NX_STAT_X64_MODE_OFFSET+1] as i64)<<8)
2265 return mode & NX_FILE_PERMISSION_MASK
2266}
2267
2268
2269// ---- fixed-width node arena -------------------------------------------------------------
2270// Flat i64 slots rather than structs: the walker stays trivial and the encoding is auditable
2271// by eye. Slot 7 is the intrusive NEXT link, so every list is a chain of node ids.
2272const SIR_SLOTS: i64 = 8
2273// S12c-6 (2026-09-05): the node ARENA. Measured need: the cast vertex stage is 1,394 nodes and its fragment stage is 2.35x
2274// its canonical-token count, i.e. ~3,300 nodes -- under 4,096 by a margin no future slice could keep. sir_node OVERFLOW IS
2275// SILENT (returns 0, sets M_OVER, and every builder ignores a 0 child), so the arena is sized at 4x the measured vertex+fragment
2276// sum and every verb that builds a real module PRINTS M_OVER beside its node count; the flag, not the size, is the guard.
2277const SIR_MAXNODE: i64 = 16384
2278const SIR_POOLCAP: i64 = 65536
2279
2280const SIR_KIND: i64 = 0
2281const SIR_TY: i64 = 1
2282const SIR_A: i64 = 2
2283const SIR_B: i64 = 3
2284const SIR_C: i64 = 4
2285const SIR_NAME: i64 = 5
2286const SIR_D: i64 = 6
2287const SIR_NEXT: i64 = 7
2288
2289// module header words
2290const M_NODES: i64 = 0
2291const M_NCOUNT: i64 = 1
2292const M_POOL: i64 = 2
2293const M_POOLUSED: i64 = 3
2294const M_DECLH: i64 = 4
2295const M_DECLT: i64 = 5
2296const M_FUNCH: i64 = 6
2297const M_FUNCT: i64 = 7
2298const M_REFUSE: i64 = 8
2299const M_OVER: i64 = 9
2300// S2 (2026-09-04): THE EMISSION CONTEXT. The K_FUNC whose body a backend is emitting right now (0 between
2301// functions). An E_IDENT carries only a name, and what that name resolves to -- a parameter or local of
2302// THIS function, or a module-scope declaration -- decides how a dialect spells it (WGSL reads a uniform as
2303// `u.<name>`). Both backends set it; the resolver reads it. Word 10 of the 16-word header sir_new maps.
2304const M_CURFN: i64 = 10
2305// S5 (2026-09-04): THE FRAGMENT OUTPUT BEING EMITTED. The K_FRAGOUT declaration whose value the entry
2306// point currently returns (0 everywhere else -- between functions, inside a helper, outside a fragment
2307// stage). GLSL has no value-returning fragment entry: `void main()` ASSIGNS a declared `out` variable,
2308// while WGSL RETURNS one. Both backends walk ONE S_RETURN node, so the shape that differs has to be
2309// readable from somewhere; this word is that somewhere, and it is set ONLY around the entry body so a
2310// plain helper in the same module still emits an ordinary `return`. Word 11 of the 16 sir_new maps.
2311const M_FRAGOUT: i64 = 11
2312// S7 (2026-09-05): THE INTERSTAGE-STRUCT MODE. 0 = no varyings in play; 1 = inside the vertex entry that
2313// RETURNS struct VIO (varying writes and the position assignment land in vo.<name>); 2 = inside the fragment
2314// entry that TAKES vin:VIO (varying and position reads come from vin.<name>). Set and cleared by the WGSL
2315// entry emitter; wg_expr / wg_stmts read it. GLSL never sets it. Word 12 of the 16 sir_new maps.
2316const M_VIOMODE: i64 = 12
2317// S12a (2026-09-05): DOES THIS MODULE READ THE INSTANCE INDEX? Set by sir_builtin the moment an instance_index node is
2318// built, read by the WGSL vertex-entry emitter, which binds @builtin(instance_index) ii:u32 ONLY then -- so every module
2319// that never asks for it (the fullscreen triangle, every S0..S9 fixture) keeps a byte-identical signature. GLSL never
2320// reads it: gl_InstanceID needs no declaration. Word 13 of the 16 sir_new maps.
2321const M_USESII: i64 = 13
2322// S12c-5 (2026-09-05): THE WGSL FRAGMENT OUTPUT VARIABLE. The hand cast fragment ASSIGNS its output (`fc=...;`) and exits
2323// early with a void `return;` -- valid GLSL (fc is an `out` variable) and the shape the token ruler must see. WGSL RETURNS
2324// its output, so the WGSL backend opens such an entry with `var fc:vec4f;`, lowers every void return inside it to
2325// `return fc;` and appends one after the body when the last statement is not a return. This word holds the K_FRAGOUT
2326// declaration ONLY while the WGSL backend is inside a fragment entry whose body assigns it (0 everywhere else) -- the
2327// WGSL twin of M_FRAGOUT, which the GLSL backend uses for the opposite lowering (value return -> assignment). Word 14.
2328const M_WGFRAGOUT: i64 = 14
2329// S12 step 2 (2026-09-06): THE BIND GROUP a module's WGSL resources are spelled in (@group(N)). 0 for every module until
2330// now; the cast FRAGMENT module is emitted at 1, because its struct U and its textures differ from the vertex module's and
2331// WebGPU binds ONE resource per (group,binding) across both stages of a pipeline -- two structs named U at group 0 binding 0
2332// would read one buffer through two layouts, and vertex uJT (2d f32) against fragment uVm (3d u32) at binding 1 is a
2333// validation refusal. GLSL never reads this word. Word 15 of the 16 sir_new maps (the last free slot).
2334const M_BINDGROUP: i64 = 15
2335// Source clip depth is explicit: backends translate it to their device convention.
2336// Existing modules retain their native convention until they declare otherwise.
2337const M_CLIP_DEPTH: i64 = 16
2338const SIR_MODULE_WORDS: i64 = 17
2339const SIR_CLIP_NATIVE: i64 = 0
2340const SIR_CLIP_NEGATIVE_ONE_TO_ONE: i64 = 1
2341// S12c-5: an E_LIT flag (SIR_A) -- the unsigned literal keeps its `u` suffix in GLSL too (see sir_lit_u).
2342const SIR_LIT_USUFFIX: i64 = 1
2343
2344// ---- node kinds (the DECLARED SUBSET) ----------------------------------------------------
2345const K_UNIFORM: i64 = 1
2346const K_ATTRIB: i64 = 2
2347const K_VARY: i64 = 3
2348const K_FUNC: i64 = 4
2349const K_PARAM: i64 = 5
2350// RUNG GE43 -- COMPUTE (gameengine board, 2026-09-02). A storage buffer is the one declaration a
2351// rasterizer KERNEL cannot do without: the depth buffer, the tile bins and the framebuffer all live
2352// in read_write storage and are resolved with atomics. GLSL ES 3.00 (WebGL2) has NEITHER storage
2353// buffers nor atomics nor a compute stage, so the GLSL backend REFUSES this kind BY NAME and the
2354// WGSL door is the only third-party-browser path for it -- exactly the split GE42-GE45 declare:
2355// ONE kernel authored here, one door per host (WebGPU as a submission pipe; dxg on NishiOS).
2356// SIR_TY = element type SIR_A = binding index SIR_B = 1 read_write / 0 read SIR_C = 1 atomic<>
2357const K_STORAGE: i64 = 6
2358// S3 (2026-09-04): a TEXTURE is its own declaration kind. It is a BOUND RESOURCE in both dialects -- a
2359// sampler uniform (`uniform highp usampler3D`) in GLSL, a `@group/@binding var` OUTSIDE struct U in WGSL --
2360// and it was never a uniform: a texture-typed K_UNIFORM passed the WGSL type check and landed INSIDE
2361// struct U (WGSL that does not compile, no refusal) until S1 made that a named refusal in both backends.
2362// SIR_TY = the texture type (T_TEX3U is the covered one; every other texture type refuses BY NAME)
2363// No binding slot is stored: GLSL has no bindings and the WGSL backend DERIVES one from declaration order.
2364const K_TEXTURE: i64 = 7
2365// S5 (2026-09-04): THE FRAGMENT OUTPUT is its own declaration kind, for the same reason K_TEXTURE is.
2366// It was not modelled at all, and the cost was silent: a fragment stage emitted `void main(){ return
2367// vec4(...); }` -- a value returned from a void function, against no declared output -- which is invalid
2368// GLSL ES 3.00 on BOTH counts and which no gate could see, because nothing pinned the GLSL fragment
2369// bytes. The WGSL side had the mirror defect wearing the opposite face: it spelled the whole signature
2370// tail as the LITERAL ")->@location(0) vec4f{", so the location and the type were unreadable constants
2371// rather than data -- exactly the defect S4 removed from the parameter half of the same line.
2372// ONE declaration now feeds both: GLSL emits `out <ty> <name>;` and lowers the entry's return to
2373// `<name>=<expr>;`, WGSL emits no declaration and DERIVES `->@location(<loc>) <ty>`.
2374// SIR_TY = the output type SIR_A = the @location index
2375const K_FRAGOUT: i64 = 8
2376// R-D (2026-09-04, GE44, B1 of the hand-shader diff): A STRUCT is a module-scope declaration whose members are
2377// K_PARAM nodes chained under it EXACTLY as a function's parameters are (sir_member IS sir_param), so member
2378// spelling shares the parameter machinery and cannot drift from it. A struct TYPE is named by its declaration:
2379// sir_struct_ty(st) = SIR_MAXNODE + st, unique by construction and above every T_ scalar, so a type speller that
2380// meets one looks the declaration up (sir_struct_of) instead of refusing. Member ACCESS needs no new expression
2381// kind -- both dialects spell it base.member, the bytes E_SWZ already emits -- and CONSTRUCTION is an E_CALL
2382// named after the struct (both dialects spell Hit(a,b)). SIR_A = member chain head, SIR_C = member tail.
2383const K_STRUCT: i64 = 9
2384const S_RETURN: i64 = 10
2385const S_ASSIGN: i64 = 11
2386const S_VAR: i64 = 12
2387const S_IF: i64 = 13
2388const S_DISCARD: i64 = 14
2389// RUNG 2b-GENERAL: structured LOOP + BREAK. A back edge cannot be emitted as a goto -- neither
2390// GLSL ES 3.00 nor WGSL has one -- so the recovered form is an infinite loop whose exit is an
2391// explicit break. That is exactly the Relooper's Loop block, whose Inner block "will appear
2392// inside the loop, i.e., when execution reaches the end of that block, flow will return to the
2393// beginning" and which "will contain a conditional break defining where it is exited"
2394// (Zakai, Emscripten, OOPSLA 2011 -- READ from the mirrored PDF banked as graphics.refs
2395// key relooper-zakai11, not recalled from memory).
2396const S_LOOP: i64 = 15
2397const S_BREAK: i64 = 16
2398// GE43: an EXPRESSION STATEMENT -- an atomic read-modify-write whose old value is discarded is a
2399// statement in both dialects (`atomicMin(&d[i],z);`), and neither S_ASSIGN nor S_VAR can carry it
2400// without inventing a dead local. SIR_A = the expression.
2401const S_EXPR: i64 = 17
2402const E_LIT: i64 = 20
2403const E_IDENT: i64 = 21
2404const E_BIN: i64 = 22
2405const E_CALL: i64 = 23
2406const E_SWZ: i64 = 24
2407const E_INDEX: i64 = 25
2408const E_TEXLOAD: i64 = 26
2409const E_TEXSAMPLE: i64 = 27
2410const E_CTOR: i64 = 28
2411// rung-1 additions: a numeric CAST (GLSL float(x) / WGSL f32(x)) and a stage BUILTIN
2412// (GLSL gl_VertexID / WGSL @builtin(vertex_index)). Both are pure dialect-SPELLING differences
2413// over one IR node -- the thesis of this module in miniature.
2414const E_CAST: i64 = 29
2415const E_BUILTIN: i64 = 30
2416// GE43: an ATOMIC read-modify-write. SIR_NAME = the op spelling (atomicMin / atomicMax / atomicAdd,
2417// identical in WGSL and in the dxg-lane HLSL family so the IR carries the WGSL spelling), SIR_A =
2418// the TARGET lvalue (an E_INDEX into a K_STORAGE), SIR_B = the value. WGSL takes the ADDRESS of the
2419// target (`&d[i]`); that `&` is dialect knowledge the backend owns, the author never writes it.
2420const E_ATOMIC: i64 = 31
2421// R-A (2026-09-04, the GE44 world-shader contract): a SELECT. SIR_A = the condition, SIR_B = the value when
2422// true, SIR_C = the value when false. GLSL spells it as the ternary (cond?then:else), WGSL as select(f,t,cond)
2423// -- note WGSL's argument order puts the FALSE value first; that ordering is dialect knowledge the backend
2424// owns. The condition is a scalar bool by construction of this IR (there is no vector-bool type), so the
2425// ternary's scalar-condition rule holds wherever this node appears.
2426const E_SELECT: i64 = 32
2427// R-G0 (2026-09-04): unary negation. SIR_A = the operand; both dialects spell (-x). The world shader writes
2428// -vec3f(...), -u.yp.x and -1.0 as expressions; an E_BIN(0 - x) would be semantically equal but would spell a
2429// subtraction the hand shader never wrote, so negation is its own node with one arm per dialect.
2430const E_NEG: i64 = 33
2431// K_PRIVATE (GE55, 2026-09-05): MODULE-SCOPE PRIVATE STATE -- `var<private> name:T;` in WGSL, a bare global `T name;`
2432// in GLSL. Written by one function and read bare by another, never qualified as u.<name>, invisible to the uniform
2433// layout. It exists so a shader can derive every float it needs from RAW uniform words in ONE function (upk) while
2434// every other function body stays byte-identical: the sim hands the GPU integers, the kernel does the math. Numbered
2435// after the last expression kind because node kinds share one space and nothing range-tests them (measured).
2436const K_PRIVATE: i64 = 34
2437// S12c-4 (2026-09-05): LOGICAL NOT. SIR_A = the operand (a bool); both dialects spell (!x). The cast vertex stage gates a
2438// garment instance on `!(gbm==4||gbm==5||gbm==8||gbm==9)` and `!wr9`; the world shader never needed it (its exits are
2439// spelled as the inverted comparison, see sir_for_until), so it lands here as its own node kind rather than a rewrite the
2440// hand text does not contain -- the token ruler would name that rewrite as a divergence. Numbered after K_PRIVATE for the
2441// same reason K_PRIVATE is numbered after E_NEG: one kind space, nothing range-tests it.
2442const E_NOT: i64 = 35
2443
2444// ---- types -------------------------------------------------------------------------------
2445const T_VOID: i64 = 0
2446const T_F32: i64 = 1
2447const T_I32: i64 = 2
2448const T_U32: i64 = 3
2449const T_BOOL: i64 = 4
2450const T_V2F: i64 = 5
2451const T_V3F: i64 = 6
2452const T_V4F: i64 = 7
2453const T_V3I: i64 = 8
2454const T_TEX3U: i64 = 9
2455const T_TEX2F: i64 = 10
2456// GE43: vec3<u32> -- the type of @builtin(global_invocation_id); GLSL ES 3.10 would spell it uvec3.
2457const T_V3U: i64 = 11
2458// S8 (2026-09-05): vec2<i32> -- the INTEGER texel coordinate of a 2D fetch (the cast reads its joint table and
2459// garment table with texelFetch(uJT, ivec2(...), 0)); WGSL spells it vec2i, GLSL ivec2.
2460const T_V2I: i64 = 12
2461// S9 (2026-09-05): mat3x3<f32> -- the cast's TBN / joint-rotation matrix. WGSL spells it mat3x3f, GLSL mat3; the
2462// constructor takes three column vectors and mat*vec is plain E_BIN '*' in both dialects, so the type NAME is the only
2463// dialect fact and it lives in wg_ty/gl_ty like every other type.
2464const T_M3F: i64 = 13
2465const T_MAX: i64 = 13
2466
2467func sir_slen(s: *u8) -> i64 { var n: i64 = 0; while s[n] != (0 as u8) { n = n + 1 } return n }
2468
2469func sir_new() -> *i64 {
2470 let m: *i64 = sys_mmap(SIR_MODULE_WORDS*8) as *i64
2471 m[M_NODES] = sys_mmap(SIR_MAXNODE*SIR_SLOTS*8) as i64
2472 m[M_NCOUNT] = 1
2473 m[M_POOL] = sys_mmap(SIR_POOLCAP) as i64
2474 m[M_POOLUSED] = 1
2475 m[M_DECLH] = 0
2476 m[M_DECLT] = 0
2477 m[M_FUNCH] = 0
2478 m[M_FUNCT] = 0
2479 m[M_REFUSE] = 0
2480 m[M_OVER] = 0
2481 m[M_CURFN] = 0
2482 m[M_FRAGOUT] = 0
2483 return m
2484}
2485
2486func sir_get(m: *i64, id: i64, k: i64) -> i64 {
2487 let base: *i64 = m[M_NODES] as *i64
2488 return base[id*SIR_SLOTS + k]
2489}
2490
2491func sir_set(m: *i64, id: i64, k: i64, v: i64) -> i64 {
2492 let base: *i64 = m[M_NODES] as *i64
2493 base[id*SIR_SLOTS + k] = v
2494 return 0
2495}
2496
2497// intern a string; returns its pool offset (0 means none). Offsets start at 1 so 0 is a
2498// usable NULL for every name slot.
2499func sir_str(m: *i64, s: *u8) -> i64 {
2500 let pool: *u8 = m[M_POOL] as *u8
2501 let n: i64 = sir_slen(s)
2502 var u: i64 = m[M_POOLUSED]
2503 if u + n + 1 >= SIR_POOLCAP { m[M_OVER] = 1; return 0 }
2504 let at: i64 = u
2505 var i: i64 = 0
2506 while i < n { pool[u] = s[i]; u = u + 1; i = i + 1 }
2507 pool[u] = 0 as u8
2508 u = u + 1
2509 m[M_POOLUSED] = u
2510 return at
2511}
2512
2513func sir_cstr(m: *i64, off: i64) -> *u8 {
2514 return ((m[M_POOL] + off) as *u8)
2515}
2516
2517func sir_node(m: *i64, kind: i64, ty: i64, a: i64, b: i64, c: i64, nameoff: i64) -> i64 {
2518 var id: i64 = m[M_NCOUNT]
2519 if id >= SIR_MAXNODE { m[M_OVER] = 1; return 0 }
2520 m[M_NCOUNT] = id + 1
2521 sir_set(m, id, SIR_KIND, kind)
2522 sir_set(m, id, SIR_TY, ty)
2523 sir_set(m, id, SIR_A, a)
2524 sir_set(m, id, SIR_B, b)
2525 sir_set(m, id, SIR_C, c)
2526 sir_set(m, id, SIR_NAME, nameoff)
2527 sir_set(m, id, SIR_D, 0)
2528 sir_set(m, id, SIR_NEXT, 0)
2529 return id
2530}
2531
2532// append onto an intrusive chain whose head/tail live in two module words
2533func sir_chain(m: *i64, hw: i64, tw: i64, id: i64) -> i64 {
2534 if id == 0 { return 0 }
2535 if m[hw] == 0 { m[hw] = id; m[tw] = id; return id }
2536 sir_set(m, m[tw], SIR_NEXT, id)
2537 m[tw] = id
2538 return id
2539}
2540
2541// ---- declaration builders ----------------------------------------------------------------
2542// arraylen 0 = scalar. location -1 = unlocated. flat 1 = no interpolation.
2543func sir_uniform(m: *i64, name: *u8, ty: i64, arraylen: i64) -> i64 {
2544 let id: i64 = sir_node(m, K_UNIFORM, ty, arraylen, 0, 0, sir_str(m, name))
2545 return sir_chain(m, M_DECLH, M_DECLT, id)
2546}
2547
2548// module-scope private state (K_PRIVATE): arraylen 0 = scalar, N = array<ty,N> / ty name[N]
2549func sir_private(m: *i64, name: *u8, ty: i64, arraylen: i64) -> i64 {
2550 let id: i64 = sir_node(m, K_PRIVATE, ty, arraylen, 0, 0, sir_str(m, name))
2551 return sir_chain(m, M_DECLH, M_DECLT, id)
2552}
2553
2554func sir_attrib(m: *i64, name: *u8, ty: i64, location: i64) -> i64 {
2555 let id: i64 = sir_node(m, K_ATTRIB, ty, location, 0, 0, sir_str(m, name))
2556 return sir_chain(m, M_DECLH, M_DECLT, id)
2557}
2558
2559func sir_vary(m: *i64, name: *u8, ty: i64, location: i64, flat: i64) -> i64 {
2560 let id: i64 = sir_node(m, K_VARY, ty, location, flat, 0, sir_str(m, name))
2561 return sir_chain(m, M_DECLH, M_DECLT, id)
2562}
2563
2564// GE43: a storage buffer `name: array<elemty>` at @group(0)@binding(binding). readwrite 1 = var<storage,read_write>,
2565// 0 = var<storage,read>. atomic 1 wraps the element as atomic<elemty> so E_ATOMIC may target it.
2566func sir_storage(m: *i64, name: *u8, elemty: i64, binding: i64, readwrite: i64, atomic: i64) -> i64 {
2567 let id: i64 = sir_node(m, K_STORAGE, elemty, binding, readwrite, atomic, sir_str(m, name))
2568 return sir_chain(m, M_DECLH, M_DECLT, id)
2569}
2570
2571// S3: a texture declaration `name: <ty>` (see K_TEXTURE). Read with sir_texload / sir_texsample.
2572func sir_texture(m: *i64, name: *u8, ty: i64) -> i64 {
2573 let id: i64 = sir_node(m, K_TEXTURE, ty, 0, 0, 0, sir_str(m, name))
2574 return sir_chain(m, M_DECLH, M_DECLT, id)
2575}
2576
2577// S5: the fragment stage's colour output (see K_FRAGOUT). Declared ONCE; each backend owns how its
2578// dialect carries it. A shader that only discards declares none, and neither backend requires one.
2579func sir_fragout(m: *i64, name: *u8, ty: i64, location: i64) -> i64 {
2580 let id: i64 = sir_node(m, K_FRAGOUT, ty, location, 0, 0, sir_str(m, name))
2581 return sir_chain(m, M_DECLH, M_DECLT, id)
2582}
2583
2584// R-D (2026-09-04): struct builders. sir_member IS sir_param -- the same K_PARAM node under the same A/C chain
2585// -- so there is exactly one member/parameter shape in the IR. sir_struct_ty derives the type id from the
2586// declaration (never picked, never colliding with a T_ scalar); sir_struct_of is the ONE inverse both backends
2587// spell a struct type through. sir_member_of delegates to E_SWZ because no dialect distinguishes a member
2588// read from a swizzle in its bytes -- a second kind would be two arms that could disagree about `.`.
2589func sir_struct(m: *i64, name: *u8) -> i64 {
2590 let id: i64 = sir_node(m, K_STRUCT, T_VOID, 0, 0, 0, sir_str(m, name))
2591 return sir_chain(m, M_DECLH, M_DECLT, id)
2592}
2593func sir_member(m: *i64, st: i64, name: *u8, ty: i64) -> i64 { return sir_param(m, st, name, ty) }
2594func sir_struct_ty(st: i64) -> i64 { return SIR_MAXNODE + st }
2595// the K_STRUCT declaration a type id names, or 0 for every scalar, vector and resource type
2596func sir_struct_of(m: *i64, ty: i64) -> i64 {
2597 if ty <= SIR_MAXNODE { return 0 }
2598 let st: i64 = ty - SIR_MAXNODE
2599 if st >= SIR_MAXNODE { return 0 }
2600 if sir_get(m, st, SIR_KIND) != K_STRUCT { return 0 }
2601 return st
2602}
2603func sir_member_of(m: *i64, base: i64, name: *u8, ty: i64) -> i64 { return sir_swz(m, base, name, ty) }
2604
2605// a function: A = param chain head, B = body chain head, C = param tail (build scratch)
2606func sir_func(m: *i64, name: *u8, rettype: i64) -> i64 {
2607 let id: i64 = sir_node(m, K_FUNC, rettype, 0, 0, 0, sir_str(m, name))
2608 return sir_chain(m, M_FUNCH, M_FUNCT, id)
2609}
2610
2611// S4 (2026-09-04): HOW A PARAMETER IS BOUND. SIR_A of a K_PARAM names its binding: P_PLAIN (an ordinary
2612// function parameter -- the only kind before S4, and sir_node's zero default) or P_BUILTIN_POSITION (the
2613// fragment stage's position input: `@builtin(position) name:vec4f` in WGSL, `gl_FragCoord` in GLSL). The IR
2614// says WHAT the input is; each backend owns how its dialect spells it, and an entry-point parameter with a
2615// binding a backend cannot derive REFUSES by name rather than being dropped from the signature.
2616const P_PLAIN: i64 = 0
2617const P_BUILTIN_POSITION: i64 = 1
2618const P_BUILTIN_FRONT_FACING: i64 = 2
2619
2620// Rasterizer orientation is a fragment boolean input, never a view-normal estimate.
2621func sir_param_front_facing(m:*i64,fn:i64,name:*u8)->i64{
2622 let id:i64=sir_param(m,fn,name,T_BOOL)
2623 sir_set(m,id,SIR_A,P_BUILTIN_FRONT_FACING)
2624 return id
2625}
2626
2627func sir_param(m: *i64, fn: i64, name: *u8, ty: i64) -> i64 {
2628 let id: i64 = sir_node(m, K_PARAM, ty, P_PLAIN, 0, 0, sir_str(m, name))
2629 if sir_get(m, fn, SIR_A) == 0 { sir_set(m, fn, SIR_A, id); sir_set(m, fn, SIR_C, id); return id }
2630 sir_set(m, sir_get(m, fn, SIR_C), SIR_NEXT, id)
2631 sir_set(m, fn, SIR_C, id)
2632 return id
2633}
2634
2635// S4: a parameter bound to the fragment stage's @builtin(position). Typed vec4f by the builtin itself.
2636func sir_param_position(m: *i64, fn: i64, name: *u8) -> i64 {
2637 let id: i64 = sir_param(m, fn, name, T_V4F)
2638 sir_set(m, id, SIR_A, P_BUILTIN_POSITION)
2639 return id
2640}
2641
2642// append a statement to a function body (D holds the body tail while building)
2643func sir_stmt(m: *i64, fn: i64, st: i64) -> i64 {
2644 if st == 0 { return 0 }
2645 if sir_get(m, fn, SIR_B) == 0 { sir_set(m, fn, SIR_B, st); sir_set(m, fn, SIR_D, st); return st }
2646 sir_set(m, sir_get(m, fn, SIR_D), SIR_NEXT, st)
2647 sir_set(m, fn, SIR_D, st)
2648 return st
2649}
2650
2651// ---- statement builders ------------------------------------------------------------------
2652func sir_return(m: *i64, e: i64) -> i64 { return sir_node(m, S_RETURN, T_VOID, e, 0, 0, 0) }
2653// Fragment depth is window depth [0,1] in both emitted dialects. S_RETURN.B
2654// carries it alongside the color expression; ordinary returns leave B zero.
2655func sir_return_depth(m: *i64, color: i64, depth: i64) -> i64 {
2656 return sir_node(m, S_RETURN, T_VOID, color, depth, 0, 0)
2657}
2658
2659func sir_assign(m: *i64, lhs: i64, rhs: i64) -> i64 { return sir_node(m, S_ASSIGN, T_VOID, lhs, rhs, 0, 0) }
2660func sir_var(m: *i64, name: *u8, ty: i64, init: i64) -> i64 { return sir_node(m, S_VAR, ty, init, 0, 0, sir_str(m, name)) }
2661func sir_if(m: *i64, cond: i64, thenh: i64, elseh: i64) -> i64 { return sir_node(m, S_IF, T_VOID, cond, thenh, elseh, 0) }
2662func sir_discard(m: *i64) -> i64 { return sir_node(m, S_DISCARD, T_VOID, 0, 0, 0, 0) }
2663// SIR_A of an S_LOOP is the body chain. The loop is UNCONDITIONAL by construction; every exit is
2664// an explicit S_BREAK inside the body, so no dialect needs a loop-condition slot and the two
2665// backends cannot disagree about where the test lives.
2666func sir_loop(m: *i64, body: i64) -> i64 { return sir_node(m, S_LOOP, T_VOID, body, 0, 0, 0) }
2667func sir_break(m: *i64) -> i64 { return sir_node(m, S_BREAK, T_VOID, 0, 0, 0, 0) }
2668// GE43: an expression evaluated for its effect (an atomic whose old value is not kept)
2669func sir_expr(m: *i64, e: i64) -> i64 { return sir_node(m, S_EXPR, T_VOID, e, 0, 0, 0) }
2670// R-B (2026-09-04, GE44): A COUNTED LOOP IS BUILDER SUGAR, NOT A NODE KIND. The whole-population diff of the
2671// two hand world shaders named the counted for-loop as a missing IR kind; it lands as a composition of the
2672// incumbent S_LOOP/S_BREAK shape -- init; loop { if until { break } body; step } -- appended to fn in that
2673// order. Both dialects therefore lower it through arms they already share, so they cannot disagree about
2674// where the test lives (the argument sir_loop makes for itself) and the node trace is dialect-independent by
2675// construction -- no second visitation order to get wrong. `until` is the EXIT test, spelled by the caller:
2676// the IR carries no unary not, and inverting a comparison on the author's behalf would silently change its
2677// NaN semantics. Returns the S_LOOP node; init and the loop are already appended to fn.
2678func sir_for_until(m: *i64, fn: i64, init: i64, until: i64, step: i64, body: i64) -> i64 {
2679 sir_stmt(m, fn, init)
2680 let ex: i64 = sir_if(m, until, sir_break(m), 0)
2681 let lp: i64 = sir_loop(m, sir_seq(m, sir_seq(m, ex, body), step))
2682 sir_stmt(m, fn, lp)
2683 return lp
2684}
2685
2686// chain two statements (for if-branch bodies)
2687func sir_seq(m: *i64, a: i64, b: i64) -> i64 {
2688 if a == 0 { return b }
2689 var t: i64 = a
2690 while sir_get(m, t, SIR_NEXT) != 0 { t = sir_get(m, t, SIR_NEXT) }
2691 sir_set(m, t, SIR_NEXT, b)
2692 return a
2693}
2694
2695// ---- expression builders -----------------------------------------------------------------
2696func sir_lit(m: *i64, text: *u8, ty: i64) -> i64 { return sir_node(m, E_LIT, ty, 0, 0, 0, sir_str(m, text)) }
2697// S12c-5: an UNSIGNED literal spelled with its u suffix in BOTH dialects (`0u`). A plain sir_lit(.., T_U32) keeps GLSL bare
2698// (the fullscreen triangle's shift amount ships that way); a uint COMPARE in GLSL ES 3.00 needs the suffix, so the cast
2699// fragment builds its block ids with this.
2700func sir_lit_u(m: *i64, text: *u8) -> i64 {
2701 let id: i64 = sir_lit(m, text, T_U32)
2702 sir_set(m, id, SIR_A, SIR_LIT_USUFFIX)
2703 return id
2704}
2705// S12c-5: a CONSTANT local (`const float K=1.2;` in GLSL, `const K:f32=1.2;` in WGSL) -- SIR_D = SIR_VAR_CONST on a plain
2706// sir_var node, one flavour beside sir_let, so both backends spell it from the same word.
2707const SIR_VAR_CONST: i64 = 2
2708func sir_const(m: *i64, name: *u8, ty: i64, init: i64) -> i64 {
2709 let id: i64 = sir_var(m, name, ty, init)
2710 sir_set(m, id, SIR_D, SIR_VAR_CONST)
2711 return id
2712}
2713func sir_ident(m: *i64, name: *u8, ty: i64) -> i64 { return sir_node(m, E_IDENT, ty, 0, 0, 0, sir_str(m, name)) }
2714func sir_bin(m: *i64, op: *u8, l: i64, r: i64, ty: i64) -> i64 { return sir_node(m, E_BIN, ty, l, r, 0, sir_str(m, op)) }
2715func sir_swz(m: *i64, base: i64, sel: *u8, ty: i64) -> i64 { return sir_node(m, E_SWZ, ty, base, 0, 0, sir_str(m, sel)) }
2716func sir_index(m: *i64, base: i64, idx: i64, ty: i64) -> i64 { return sir_node(m, E_INDEX, ty, base, idx, 0, 0) }
2717// S8 (2026-09-05): the load's result type FOLLOWS THE TEXTURE -- texture_2d<f32> returns vec4f (the cast uses the
2718// fetched joint-table row WHOLE); texture_3d<u32> keeps the T_U32 the vox fixture swizzles .x from, so every
2719// existing 3D read is byte-identical. `tex` is the texture's E_IDENT and its SIR_TY names the texture type.
2720func sir_texload(m: *i64, tex: i64, coord: i64, lod: i64) -> i64 {
2721 var rt: i64 = T_U32
2722 if sir_get(m, tex, SIR_TY) == T_TEX2F { rt = T_V4F }
2723 return sir_node(m, E_TEXLOAD, rt, tex, coord, lod, 0)
2724}
2725func sir_texsample(m: *i64, tex: i64, coord: i64) -> i64 { return sir_node(m, E_TEXSAMPLE, T_V4F, tex, coord, 0, 0) }
2726
2727// call/ctor argument chains are built with sir_arg
2728func sir_call(m: *i64, name: *u8, ty: i64) -> i64 { return sir_node(m, E_CALL, ty, 0, 0, 0, sir_str(m, name)) }
2729func sir_ctor(m: *i64, ty: i64) -> i64 { return sir_node(m, E_CTOR, ty, 0, 0, 0, 0) }
2730func sir_cast(m: *i64, e: i64, ty: i64) -> i64 { return sir_node(m, E_CAST, ty, e, 0, 0, 0) }
2731func sir_builtin(m: *i64, which: *u8, ty: i64) -> i64 {
2732 // S12a: an instance_index read marks the module so the WGSL vertex entry binds the builtin (M_USESII).
2733 if which[0] == (105 as u8) { m[M_USESII] = 1 }
2734 return sir_node(m, E_BUILTIN, ty, 0, 0, 0, sir_str(m, which))
2735}
2736// GE43: op is the WGSL spelling (atomicMin/atomicMax/atomicAdd); target is an E_INDEX into a storage buffer
2737func sir_atomic(m: *i64, op: *u8, target: i64, val: i64, ty: i64) -> i64 { return sir_node(m, E_ATOMIC, ty, target, val, 0, sir_str(m, op)) }
2738// R-A: select -- (cond, then, else) in IR order; each backend spells its own argument order.
2739func sir_select(m: *i64, cond: i64, tval: i64, fval: i64, ty: i64) -> i64 { return sir_node(m, E_SELECT, ty, cond, tval, fval, 0) }
2740// R-G0: unary negation of e, typed ty.
2741func sir_neg(m: *i64, e: i64, ty: i64) -> i64 { return sir_node(m, E_NEG, ty, e, 0, 0, 0) }
2742// S12c-4: logical not of a bool e (see E_NOT).
2743func sir_not(m: *i64, e: i64) -> i64 { return sir_node(m, E_NOT, T_BOOL, e, 0, 0, 0) }
2744// R-C: an IMMUTABLE local. Same node as sir_var with SIR_D = 1; WGSL spells it `let`, GLSL has no such
2745// spelling for a non-constant initialiser and emits the plain local -- one IR node, two shapes.
2746const SIR_VAR_LET: i64 = 1
2747func sir_let(m: *i64, name: *u8, ty: i64, init: i64) -> i64 {
2748 let id: i64 = sir_var(m, name, ty, init)
2749 sir_set(m, id, SIR_D, SIR_VAR_LET)
2750 return id
2751}
2752
2753func sir_arg(m: *i64, callid: i64, e: i64) -> i64 {
2754 if e == 0 { return 0 }
2755 // List linkage belongs to an argument occurrence, never to its reusable expression.
2756 // Child expressions remain shared; only the intrusive sibling link needs ownership.
2757 let arg:i64=sir_node(m,sir_get(m,e,SIR_KIND),sir_get(m,e,SIR_TY),
2758 sir_get(m,e,SIR_A),sir_get(m,e,SIR_B),sir_get(m,e,SIR_C),sir_get(m,e,SIR_NAME))
2759 if arg==0 { return 0 }
2760 sir_set(m,arg,SIR_D,sir_get(m,e,SIR_D))
2761 if sir_get(m, callid, SIR_A) == 0 { sir_set(m, callid, SIR_A, arg); sir_set(m, callid, SIR_C, arg); return e }
2762 sir_set(m, sir_get(m, callid, SIR_C), SIR_NEXT, arg)
2763 sir_set(m, callid, SIR_C, arg)
2764 return e
2765}
2766
2767// ---- refusal -----------------------------------------------------------------------------
2768// A backend that meets a construct outside its declared subset records the construct BY NAME
2769// and returns -1. Never emit a guess.
2770func sir_refuse(m: *i64, what: *u8) -> i64 {
2771 if m[M_REFUSE] == 0 { m[M_REFUSE] = sir_str(m, what) }
2772 return 0 - 1
2773}
2774func sir_refused(m: *i64) -> i64 { return m[M_REFUSE] }
2775
2776// ---- shared emit buffer ------------------------------------------------------------------
2777func eb_put(out: *u8, pos: i64, cap: i64, s: *u8) -> i64 {
2778 var p: i64 = pos
2779 var i: i64 = 0
2780 let n: i64 = sir_slen(s)
2781 while i < n { if p + 1 < cap { out[p] = s[i]; p = p + 1 } i = i + 1 }
2782 return p
2783}
2784
2785func eb_num(out: *u8, pos: i64, cap: i64, v: i64) -> i64 {
2786 var p: i64 = pos
2787 var x: i64 = v
2788 if x < 0 { p = eb_put(out, p, cap, "-" as *u8); x = 0 - x }
2789 let tmp: *u8 = sys_mmap(32)
2790 var k: i64 = 0
2791 if x == 0 { tmp[0] = 48 as u8; k = 1 }
2792 while x > 0 { tmp[k] = ((48 + x - (x/10)*10) as u8); x = x/10; k = k + 1 }
2793 while k > 0 { k = k - 1; if p + 1 < cap { out[p] = tmp[k]; p = p + 1 } }
2794 return p
2795}
2796
2797// ---- backend trace ------------------------------------------------------------------------
2798// EVERY backend appends each node id as it emits it. Two backends that consumed the SAME ir
2799// COMPLETELY produce IDENTICAL traces -- that identity is the equivalence oracle available on a
2800// box with no GPU, and it is not vacuous: a backend that silently skips a statement produces a
2801// SHORTER trace, and one that visits in a different order produces a DIFFERENT one.
2802func tr_add(trace: *i64, tcap: i64, tn: *i64, id: i64) -> i64 {
2803 if tn[0] < tcap { trace[tn[0]] = id; tn[0] = tn[0] + 1 }
2804 return 0
2805}
2806// nx_cast_shader_src.nx -- THE CHARACTER CAST VERTEX STAGE, WRITTEN ONCE (gameengine S12c, 2026-09-05).
2807// The cast vertex shader that nx_game_page_emit ships as the hand-written GLSL literal MVS (extracted to the board as
2808// buildroot/knowledge/compare/cast_mvs_hand.glsl, 2,485 raw / 2,521 expanded / 3,097 canonical tokens) is transcribed here
2809// SLICE BY SLICE as shader-IR builder calls, so that BOTH dialects are emitted from one source: GLSL for the WebGL2 door
2810// (proven against the hand text by nx_glsl_tokdiff -- an emitted slice is accepted when its canonical token stream is a PREFIX
2811// of the hand's up to main's closing brace, slice_prefix=1, and the whole stage when the verdict reads IDENTICAL) and WGSL for
2812// the WebGPU door (the S12 cast pipeline). The vocabulary is nx_world_shader_src's ws_* shorthands over nx_shader_ir; nothing
2813// here re-implements a builder. RULES THAT KEEP THE CANONICAL FORM REACHABLE: a negative literal is sir_neg over the positive
2814// literal ((-999.0), never a "-999.0" literal); every literal is spelled with the hand's own digits, canonically (0.5 not .5,
2815// 0.930 not 0.93 -- the ruler canonicalises spelling, never value); a compound assignment is x=(x op (y)); left-associative
2816// chains are built left-nested exactly as the grammar parses them; the hand's grouping parentheses are simply the tree's shape.
2817// The f32 uniform arrays the hand declares (uOF uGB uGT uGN, float[12]) are declared EXACTLY as the hand does -- the
2818// uniform-space stride rule is a WGSL-dialect fact and belongs in the WGSL backend's lowering (S12c-2b), never in this source.
2819// SLICES (each measured, journaled on gameengine.plan under GE59):
2820// 1 declarations + hsh + the instance/lock prologue (through vII=ii;) -- MEASURED 602/3097 canonical, slice_prefix
2821// 2 dual-quaternion skinning off the joint table, garment displacement, the PASS-1 face cut, the y-up rotation and world
2822// placement (through vec3 wp=...;)
2823// 3 soft-body fields (hb2, sbo over the DYNA anchors, hair wind, dress inheritance, the body branch), wp+=sbo
2824// 4 garment degeneration, the cast-shadow projection, vW, the clip transform (gl_Position)
2825// license_tier: ORIGINAL No hw writes (Rule 26).
2826// nx_world_shader_src.nx -- THE WORLD SHADER, WRITTEN ONCE (gameengine GE44 R-G, 2026-09-04).
2827// The voxel world pass that nx_game_page_emit ships hand-written twice (a GLSL FSH for the WebGL2 door and a WGSL
2828// module for the WebGPU door) is authored here ONCE as shader-IR builder calls and emitted to BOTH dialects by
2829// nx_wgsl. Every function below is the hand WGSL, statement for statement (vx, h21, h31, pal9, sky, struct Hit,
2830// march, shade, the fragment entry); the vertex entry is the backend's own fullscreen triangle (shsrc_fullscreen_tri).
2831// Deliberate deltas from the hand text, all semantic no-ops: compound assignments are spelled x=(x+y); unsigned
2832// constants are casts (u32(0) / uint(0)) because the GLSL backend spells a u32 literal without its suffix and a bare 0
2833// beside a uint is a GLSL type error; the WebGPU top-left fragment origin is carried as the uniform `yflip` (1 on the
2834// WebGPU door, 0 on WebGL2) instead of a per-dialect edit, so ONE source serves both doors. The uniform block is
2835// declared ONCE here (ws_world_uniforms) and `nx_wgsl layout` derives its memory layout from it.
2836// GE55 (2026-09-05): the world module now takes the sim's RAW state words as its uniform block (ws_world_uniforms_raw,
2837// the same 40-word table as nx_wasm_craft UR_*) and derives every float in upk() into module-scope private state, so
2838// the page packs nothing and computes nothing; ws_world_uniforms (the f32 block) stays as the R-F layout ruler fixture.
2839// license_tier: ORIGINAL
2840
2841
2842// ---- builder shorthands (one IR node per call; a node is never reused as two children) ----------------------
2843func ws_f(m: *i64, s: *u8) -> i64 { return sir_lit(m, s, T_F32) }
2844func ws_i(m: *i64, s: *u8) -> i64 { return sir_lit(m, s, T_I32) }
2845// an unsigned constant as a cast of an int literal: `u32(0)` / `uint(0)`, the one spelling valid in both dialects
2846func ws_u(m: *i64, s: *u8) -> i64 { return sir_cast(m, sir_lit(m, s, T_I32), T_U32) }
2847func ws_id(m: *i64, n: *u8, ty: i64) -> i64 { return sir_ident(m, n, ty) }
2848func ws_bin(m: *i64, op: *u8, a: i64, b: i64, ty: i64) -> i64 { return sir_bin(m, op, a, b, ty) }
2849func ws_cmp(m: *i64, op: *u8, a: i64, b: i64) -> i64 { return sir_bin(m, op, a, b, T_BOOL) }
2850func ws_and(m: *i64, a: i64, b: i64) -> i64 { return sir_bin(m, "&&" as *u8, a, b, T_BOOL) }
2851func ws_or(m: *i64, a: i64, b: i64) -> i64 { return sir_bin(m, "||" as *u8, a, b, T_BOOL) }
2852func ws_sw(m: *i64, a: i64, sel: *u8, ty: i64) -> i64 { return sir_swz(m, a, sel, ty) }
2853// swizzle of a FRESH identifier (the common `name.x` read)
2854func ws_sx(m: *i64, n: *u8, nty: i64, sel: *u8, ty: i64) -> i64 { return sir_swz(m, sir_ident(m, n, nty), sel, ty) }
2855func ws_mem(m: *i64, a: i64, name: *u8, ty: i64) -> i64 { return sir_member_of(m, a, name, ty) }
2856func ws_c1(m: *i64, name: *u8, a: i64, ty: i64) -> i64 { let c: i64 = sir_call(m, name, ty); sir_arg(m, c, a); return c }
2857func ws_c2(m: *i64, name: *u8, a: i64, b: i64, ty: i64) -> i64 { let c: i64 = sir_call(m, name, ty); sir_arg(m, c, a); sir_arg(m, c, b); return c }
2858func ws_c3(m: *i64, name: *u8, a: i64, b: i64, c3: i64, ty: i64) -> i64 { let c: i64 = sir_call(m, name, ty); sir_arg(m, c, a); sir_arg(m, c, b); sir_arg(m, c, c3); return c }
2859func ws_c4(m: *i64, name: *u8, a: i64, b: i64, c3: i64, d: i64, ty: i64) -> i64 { let c: i64 = sir_call(m, name, ty); sir_arg(m, c, a); sir_arg(m, c, b); sir_arg(m, c, c3); sir_arg(m, c, d); return c }
2860func ws_c5(m: *i64, name: *u8, a: i64, b: i64, c3: i64, d: i64, e: i64, ty: i64) -> i64 { let c: i64 = sir_call(m, name, ty); sir_arg(m, c, a); sir_arg(m, c, b); sir_arg(m, c, c3); sir_arg(m, c, d); sir_arg(m, c, e); return c }
2861func ws_c6(m: *i64, name: *u8, a: i64, b: i64, c3: i64, d: i64, e: i64, g: i64, ty: i64) -> i64 { let c: i64 = sir_call(m, name, ty); sir_arg(m, c, a); sir_arg(m, c, b); sir_arg(m, c, c3); sir_arg(m, c, d); sir_arg(m, c, e); sir_arg(m, c, g); return c }
2862func ws_v1(m: *i64, ty: i64, a: i64) -> i64 { let c: i64 = sir_ctor(m, ty); sir_arg(m, c, a); return c }
2863func ws_vt2(m: *i64, ty: i64, a: i64, b: i64) -> i64 { let c: i64 = sir_ctor(m, ty); sir_arg(m, c, a); sir_arg(m, c, b); return c }
2864func ws_vt3(m: *i64, ty: i64, a: i64, b: i64, c3: i64) -> i64 { let c: i64 = sir_ctor(m, ty); sir_arg(m, c, a); sir_arg(m, c, b); sir_arg(m, c, c3); return c }
2865func ws_v2(m: *i64, a: i64, b: i64) -> i64 { return ws_vt2(m, T_V2F, a, b) }
2866func ws_v3(m: *i64, a: i64, b: i64, c3: i64) -> i64 { return ws_vt3(m, T_V3F, a, b, c3) }
2867func ws_v3i(m: *i64, a: i64, b: i64, c3: i64) -> i64 { return ws_vt3(m, T_V3I, a, b, c3) }
2868func ws_v4(m: *i64, a: i64, b: i64, c3: i64, d: i64) -> i64 { let c: i64 = sir_ctor(m, T_V4F); sir_arg(m, c, a); sir_arg(m, c, b); sir_arg(m, c, c3); sir_arg(m, c, d); return c }
2869// vec2f(x,y) / vec3f(x,y,z) of three f32 literals
2870func ws_v2f(m: *i64, a: *u8, b: *u8) -> i64 { return ws_v2(m, ws_f(m, a), ws_f(m, b)) }
2871func ws_v3f(m: *i64, a: *u8, b: *u8, c3: *u8) -> i64 { return ws_v3(m, ws_f(m, a), ws_f(m, b), ws_f(m, c3)) }
2872func ws_q2(m: *i64, a: i64, b: i64) -> i64 { return sir_seq(m, a, b) }
2873func ws_q3(m: *i64, a: i64, b: i64, c: i64) -> i64 { return sir_seq(m, sir_seq(m, a, b), c) }
2874func ws_q4(m: *i64, a: i64, b: i64, c: i64, d: i64) -> i64 { return sir_seq(m, ws_q3(m, a, b, c), d) }
2875func ws_q5(m: *i64, a: i64, b: i64, c: i64, d: i64, e: i64) -> i64 { return sir_seq(m, ws_q4(m, a, b, c, d), e) }
2876func ws_set(m: *i64, lhs: i64, rhs: i64) -> i64 { return sir_assign(m, lhs, rhs) }
2877// x = (x op y) -- the spelling of every compound assignment in the hand text
2878func ws_op(m: *i64, name: *u8, ty: i64, op: *u8, rhs: i64) -> i64 { return sir_assign(m, sir_ident(m, name, ty), sir_bin(m, op, sir_ident(m, name, ty), rhs, ty)) }
2879// name.sel = (name.sel op y)
2880func ws_opx(m: *i64, name: *u8, nty: i64, sel: *u8, ty: i64, op: *u8, rhs: i64) -> i64 { return sir_assign(m, ws_sx(m, name, nty, sel, ty), sir_bin(m, op, ws_sx(m, name, nty, sel, ty), rhs, ty)) }
2881func ws_if(m: *i64, c: i64, t: i64, e: i64) -> i64 { return sir_if(m, c, t, e) }
2882func ws_ret(m: *i64, e: i64) -> i64 { return sir_return(m, e) }
2883func ws_st(m: *i64, f: i64, s: i64) -> i64 { return sir_stmt(m, f, s) }
2884
2885// ---- the uniform block, declared ONCE (its layout is derived by `nx_wgsl layout`) ------------------------------
2886// p0 of the hand packer is `yflip` here: the WebGPU door packs 1 (top-left origin), the WebGL2 door 0 (see fs).
2887func ws_world_uniforms(m: *i64) -> i64 {
2888 sir_uniform(m, "cam" as *u8, T_V3F, 0)
2889 sir_uniform(m, "t" as *u8, T_F32, 0)
2890 sir_uniform(m, "yp" as *u8, T_V4F, 0)
2891 sir_uniform(m, "sund" as *u8, T_V3F, 0)
2892 sir_uniform(m, "rain" as *u8, T_F32, 0)
2893 sir_uniform(m, "skt" as *u8, T_V3F, 0)
2894 sir_uniform(m, "sun" as *u8, T_F32, 0)
2895 sir_uniform(m, "skh" as *u8, T_V3F, 0)
2896 sir_uniform(m, "cld" as *u8, T_F32, 0)
2897 sir_uniform(m, "res" as *u8, T_V2F, 0)
2898 sir_uniform(m, "wmax" as *u8, T_F32, 0)
2899 sir_uniform(m, "selb" as *u8, T_F32, 0)
2900 sir_uniform(m, "hok" as *u8, T_F32, 0)
2901 sir_uniform(m, "npct" as *u8, T_F32, 0)
2902 sir_uniform(m, "yflip" as *u8, T_F32, 0)
2903 sir_uniform(m, "p1" as *u8, T_F32, 0)
2904 sir_uniform(m, "pal" as *u8, T_V4F, 12)
2905 sir_uniform(m, "palf" as *u8, T_V4F, 5)
2906 return 0
2907}
2908
2909// ---- GE55 (2026-09-05): THE RAW UNIFORM BLOCK -- the sim's own state words, verbatim (nx_wasm_craft pack_uniforms) ----
2910// 40 little-endian 32-bit words, 160 B; word index = byte offset / 4, the SAME table as UR_* in nx_wasm_craft.nx, and
2911// `nx_wgsl layout` on this module is the one ruler both sides are pinned to. Signed state is i32, packed RGB words and
2912// flags are u32. NOTHING here is a float: the wasm lane carries no f32 lowering, so every float the world pass needs is
2913// derived in upk() below from these words -- the page packs no uniform and computes no arithmetic (the bridge is one
2914// writeBuffer from the sim's memory). The derived values live in MODULE-SCOPE PRIVATE STATE (K_PRIVATE) under the
2915// names every function body already reads (cam, t, yp, sund, rain, skt, sun, skh, cld, res, wmax, selb, hok, npct,
2916// yflip, pal[12], palf[5]), so every function below stays byte-identical to the hand text it was proven against.
2917func ws_ru(m: *i64, n: *u8, ty: i64) -> i64 { return sir_uniform(m, n, ty, 0) }
2918func ws_world_uniforms_raw(m: *i64) -> i64 {
2919 ws_ru(m, "r_camx" as *u8, T_I32); ws_ru(m, "r_camy" as *u8, T_I32); ws_ru(m, "r_camz" as *u8, T_I32); ws_ru(m, "r_tnow" as *u8, T_I32)
2920 ws_ru(m, "r_yaw" as *u8, T_I32); ws_ru(m, "r_pitch" as *u8, T_I32); ws_ru(m, "r_sunel" as *u8, T_I32); ws_ru(m, "r_dayt" as *u8, T_I32)
2921 ws_ru(m, "r_dlen" as *u8, T_I32); ws_ru(m, "r_rain" as *u8, T_I32); ws_ru(m, "r_skt" as *u8, T_U32); ws_ru(m, "r_skh" as *u8, T_U32)
2922 ws_ru(m, "r_sun" as *u8, T_I32); ws_ru(m, "r_cld" as *u8, T_I32); ws_ru(m, "r_wmax" as *u8, T_I32); ws_ru(m, "r_selb" as *u8, T_I32)
2923 ws_ru(m, "r_hok" as *u8, T_I32); ws_ru(m, "r_npct" as *u8, T_I32); ws_ru(m, "r_broken" as *u8, T_I32); ws_ru(m, "r_placed" as *u8, T_I32)
2924 ws_ru(m, "r_pal0" as *u8, T_U32); ws_ru(m, "r_pal1" as *u8, T_U32); ws_ru(m, "r_pal2" as *u8, T_U32); ws_ru(m, "r_pal3" as *u8, T_U32)
2925 ws_ru(m, "r_pal4" as *u8, T_U32); ws_ru(m, "r_pal5" as *u8, T_U32); ws_ru(m, "r_pal6" as *u8, T_U32); ws_ru(m, "r_pal7" as *u8, T_U32)
2926 ws_ru(m, "r_pal8" as *u8, T_U32); ws_ru(m, "r_pal9" as *u8, T_U32); ws_ru(m, "r_pal10" as *u8, T_U32); ws_ru(m, "r_pal11" as *u8, T_U32)
2927 ws_ru(m, "r_palf0" as *u8, T_U32); ws_ru(m, "r_palf1" as *u8, T_U32); ws_ru(m, "r_palf2" as *u8, T_U32); ws_ru(m, "r_palf3" as *u8, T_U32)
2928 ws_ru(m, "r_palf4" as *u8, T_U32); ws_ru(m, "r_resw" as *u8, T_I32); ws_ru(m, "r_resh" as *u8, T_I32); ws_ru(m, "r_yflip" as *u8, T_I32)
2929 ws_ru(m, "r_surf" as *u8, T_I32) // Continuous terrain and water; vegetation/objects still need separate geometry.
2930 ws_ru(m, "r_water_q8" as *u8, T_I32) // Native UR_WATER_Q8, previously padding; block size is unchanged.
2931 return 0
2932}
2933// the derived values, module-scope private state: `var<private>` in WGSL, a bare global in GLSL
2934func ws_world_privates(m: *i64) -> i64 {
2935 sir_private(m, "cam" as *u8, T_V3F, 0); sir_private(m, "t" as *u8, T_F32, 0); sir_private(m, "yp" as *u8, T_V4F, 0)
2936 sir_private(m, "sund" as *u8, T_V3F, 0); sir_private(m, "rain" as *u8, T_F32, 0); sir_private(m, "skt" as *u8, T_V3F, 0)
2937 sir_private(m, "sun" as *u8, T_F32, 0); sir_private(m, "skh" as *u8, T_V3F, 0); sir_private(m, "cld" as *u8, T_F32, 0)
2938 sir_private(m, "res" as *u8, T_V2F, 0); sir_private(m, "wmax" as *u8, T_F32, 0); sir_private(m, "selb" as *u8, T_F32, 0)
2939 sir_private(m, "hok" as *u8, T_F32, 0); sir_private(m, "npct" as *u8, T_F32, 0); sir_private(m, "yflip" as *u8, T_F32, 0)
2940 sir_private(m, "pal" as *u8, T_V4F, 12); sir_private(m, "palf" as *u8, T_V4F, 5)
2941 return 0
2942}
2943// f32(<raw i32 word>)
2944func ws_fi(m: *i64, n: *u8) -> i64 { return sir_cast(m, sir_ident(m, n, T_I32), T_F32) }
2945// fn rgb9(w:u32)->vec3f{return vec3f(f32(w&255u),f32((w>>8u)&255u),f32((w>>16u)&255u))/255.0;} -- the packed RGB word
2946func ws_fn_rgb9(m: *i64) -> i64 {
2947 let f: i64 = sir_func(m, "rgb9" as *u8, T_V3F)
2948 sir_param(m, f, "w" as *u8, T_U32)
2949 let r: i64 = sir_cast(m, ws_bin(m, "&" as *u8, ws_id(m, "w" as *u8, T_U32), ws_u(m, "255" as *u8), T_U32), T_F32)
2950 let g: i64 = sir_cast(m, ws_bin(m, "&" as *u8, ws_bin(m, ">>" as *u8, ws_id(m, "w" as *u8, T_U32), ws_u(m, "8" as *u8), T_U32), ws_u(m, "255" as *u8), T_U32), T_F32)
2951 let b: i64 = sir_cast(m, ws_bin(m, "&" as *u8, ws_bin(m, ">>" as *u8, ws_id(m, "w" as *u8, T_U32), ws_u(m, "16" as *u8), T_U32), ws_u(m, "255" as *u8), T_U32), T_F32)
2952 ws_st(m, f, ws_ret(m, ws_bin(m, "/" as *u8, ws_v3(m, r, g, b), ws_f(m, "255.0" as *u8), T_V3F)))
2953 return f
2954}
2955// <arr>[<k>]=vec4f(rgb9(<rn>)*dl2,0.0);
2956func ws_pal(m: *i64, f: i64, arr: *u8, k: *u8, rn: *u8) -> i64 {
2957 let c: i64 = ws_vt2(m, T_V4F, ws_bin(m, "*" as *u8, ws_c1(m, "rgb9" as *u8, ws_id(m, rn, T_U32), T_V3F), ws_id(m, "dl2" as *u8, T_F32), T_V3F), ws_f(m, "0.0" as *u8))
2958 return ws_st(m, f, ws_set(m, sir_index(m, ws_id(m, arr, T_V4F), ws_i(m, k), T_V4F), c))
2959}
2960// fn upk(){ ... } -- every float the world pass reads, derived ONCE per fragment from the raw words. The arithmetic is
2961// the retired JS packer's, line for line: cam/256, yaw and pitch Q12, df=max(0,sunel/4096), dl2=.22+.78*pow(df,.6),
2962// nn=1-dl2, the sky words unpacked times dl2 plus nn*k, the sun disc only when the sim says sun AND df>.04, the sun
2963// direction from the day fraction (az) and the elevation (el), and the 17 palette words times dl2.
2964func ws_fn_upk(m: *i64) -> i64 {
2965 let f: i64 = sir_func(m, "upk" as *u8, T_VOID)
2966 ws_st(m, f, ws_set(m, ws_id(m, "cam" as *u8, T_V3F), ws_bin(m, "/" as *u8, ws_v3(m, ws_fi(m, "r_camx" as *u8), ws_fi(m, "r_camy" as *u8), ws_fi(m, "r_camz" as *u8)), ws_f(m, "256.0" as *u8), T_V3F)))
2967 ws_st(m, f, ws_set(m, ws_id(m, "t" as *u8, T_F32), ws_fi(m, "r_tnow" as *u8)))
2968 ws_st(m, f, sir_let(m, "ya" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_fi(m, "r_yaw" as *u8), ws_f(m, "4096.0" as *u8), T_F32)))
2969 ws_st(m, f, sir_let(m, "pa" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_fi(m, "r_pitch" as *u8), ws_f(m, "4096.0" as *u8), T_F32)))
2970 ws_st(m, f, ws_set(m, ws_id(m, "yp" as *u8, T_V4F), ws_v4(m, ws_c1(m, "sin" as *u8, ws_id(m, "ya" as *u8, T_F32), T_F32), ws_c1(m, "cos" as *u8, ws_id(m, "ya" as *u8, T_F32), T_F32), ws_c1(m, "sin" as *u8, ws_id(m, "pa" as *u8, T_F32), T_F32), ws_c1(m, "cos" as *u8, ws_id(m, "pa" as *u8, T_F32), T_F32))))
2971 ws_st(m, f, sir_let(m, "sel" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_fi(m, "r_sunel" as *u8), ws_f(m, "4096.0" as *u8), T_F32)))
2972 ws_st(m, f, sir_let(m, "df" as *u8, T_F32, ws_c2(m, "max" as *u8, ws_f(m, "0.0" as *u8), ws_id(m, "sel" as *u8, T_F32), T_F32)))
2973 ws_st(m, f, sir_let(m, "dl2" as *u8, T_F32, ws_bin(m, "+" as *u8, ws_f(m, "0.22" as *u8), ws_bin(m, "*" as *u8, ws_f(m, "0.78" as *u8), ws_c2(m, "pow" as *u8, ws_id(m, "df" as *u8, T_F32), ws_f(m, "0.6" as *u8), T_F32), T_F32), T_F32)))
2974 ws_st(m, f, sir_let(m, "nn" as *u8, T_F32, ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_id(m, "dl2" as *u8, T_F32), T_F32)))
2975 ws_st(m, f, sir_let(m, "dfr" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_fi(m, "r_dayt" as *u8), ws_c2(m, "max" as *u8, ws_f(m, "1.0" as *u8), ws_fi(m, "r_dlen" as *u8), T_F32), T_F32)))
2976 ws_st(m, f, sir_let(m, "az" as *u8, T_F32, ws_bin(m, "*" as *u8, ws_f(m, "3.14159265" as *u8), ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_bin(m, "*" as *u8, ws_id(m, "dfr" as *u8, T_F32), ws_f(m, "1.6" as *u8), T_F32), T_F32), T_F32)))
2977 ws_st(m, f, sir_let(m, "el" as *u8, T_F32, ws_c1(m, "asin" as *u8, ws_c3(m, "clamp" as *u8, ws_id(m, "sel" as *u8, T_F32), ws_f(m, "-0.99" as *u8), ws_f(m, "0.99" as *u8), T_F32), T_F32)))
2978 ws_st(m, f, sir_let(m, "sd" as *u8, T_V3F, ws_v3(m, ws_bin(m, "*" as *u8, ws_c1(m, "cos" as *u8, ws_id(m, "el" as *u8, T_F32), T_F32), ws_c1(m, "cos" as *u8, ws_id(m, "az" as *u8, T_F32), T_F32), T_F32), ws_c1(m, "sin" as *u8, ws_id(m, "el" as *u8, T_F32), T_F32), ws_bin(m, "*" as *u8, ws_c1(m, "cos" as *u8, ws_id(m, "el" as *u8, T_F32), T_F32), ws_f(m, "0.45" as *u8), T_F32))))
2979 ws_st(m, f, sir_let(m, "sdl" as *u8, T_F32, ws_c1(m, "length" as *u8, ws_id(m, "sd" as *u8, T_V3F), T_F32)))
2980 ws_st(m, f, ws_set(m, ws_id(m, "sund" as *u8, T_V3F), ws_bin(m, "/" as *u8, ws_id(m, "sd" as *u8, T_V3F), sir_select(m, ws_cmp(m, "==" as *u8, ws_id(m, "sdl" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_f(m, "1.0" as *u8), ws_id(m, "sdl" as *u8, T_F32), T_F32), T_V3F)))
2981 ws_st(m, f, ws_set(m, ws_id(m, "rain" as *u8, T_F32), ws_fi(m, "r_rain" as *u8)))
2982 ws_st(m, f, ws_set(m, ws_id(m, "skt" as *u8, T_V3F), ws_bin(m, "+" as *u8, ws_bin(m, "*" as *u8, ws_c1(m, "rgb9" as *u8, ws_id(m, "r_skt" as *u8, T_U32), T_V3F), ws_id(m, "dl2" as *u8, T_F32), T_V3F), ws_bin(m, "*" as *u8, ws_v3f(m, "0.02" as *u8, "0.03" as *u8, "0.10" as *u8), ws_id(m, "nn" as *u8, T_F32), T_V3F), T_V3F)))
2983 ws_st(m, f, ws_set(m, ws_id(m, "skh" as *u8, T_V3F), ws_bin(m, "+" as *u8, ws_bin(m, "*" as *u8, ws_c1(m, "rgb9" as *u8, ws_id(m, "r_skh" as *u8, T_U32), T_V3F), ws_id(m, "dl2" as *u8, T_F32), T_V3F), ws_bin(m, "*" as *u8, ws_v3f(m, "0.04" as *u8, "0.05" as *u8, "0.12" as *u8), ws_id(m, "nn" as *u8, T_F32), T_V3F), T_V3F)))
2984 ws_st(m, f, ws_set(m, ws_id(m, "sun" as *u8, T_F32), sir_select(m, ws_and(m, ws_cmp(m, "==" as *u8, ws_id(m, "r_sun" as *u8, T_I32), ws_i(m, "1" as *u8)), ws_cmp(m, ">" as *u8, ws_id(m, "df" as *u8, T_F32), ws_f(m, "0.04" as *u8))), ws_f(m, "1.0" as *u8), ws_f(m, "0.0" as *u8), T_F32)))
2985 ws_st(m, f, ws_set(m, ws_id(m, "cld" as *u8, T_F32), ws_fi(m, "r_cld" as *u8)))
2986 ws_st(m, f, ws_set(m, ws_id(m, "res" as *u8, T_V2F), ws_v2(m, ws_fi(m, "r_resw" as *u8), ws_fi(m, "r_resh" as *u8))))
2987 ws_st(m, f, ws_set(m, ws_id(m, "wmax" as *u8, T_F32), ws_fi(m, "r_wmax" as *u8)))
2988 ws_st(m, f, ws_set(m, ws_id(m, "selb" as *u8, T_F32), ws_fi(m, "r_selb" as *u8)))
2989 ws_st(m, f, ws_set(m, ws_id(m, "hok" as *u8, T_F32), ws_fi(m, "r_hok" as *u8)))
2990 ws_st(m, f, ws_set(m, ws_id(m, "npct" as *u8, T_F32), ws_fi(m, "r_npct" as *u8)))
2991 ws_st(m, f, ws_set(m, ws_id(m, "yflip" as *u8, T_F32), ws_fi(m, "r_yflip" as *u8)))
2992 ws_pal(m, f, "pal" as *u8, "0" as *u8, "r_pal0" as *u8); ws_pal(m, f, "pal" as *u8, "1" as *u8, "r_pal1" as *u8); ws_pal(m, f, "pal" as *u8, "2" as *u8, "r_pal2" as *u8)
2993 ws_pal(m, f, "pal" as *u8, "3" as *u8, "r_pal3" as *u8); ws_pal(m, f, "pal" as *u8, "4" as *u8, "r_pal4" as *u8); ws_pal(m, f, "pal" as *u8, "5" as *u8, "r_pal5" as *u8)
2994 ws_pal(m, f, "pal" as *u8, "6" as *u8, "r_pal6" as *u8); ws_pal(m, f, "pal" as *u8, "7" as *u8, "r_pal7" as *u8); ws_pal(m, f, "pal" as *u8, "8" as *u8, "r_pal8" as *u8)
2995 ws_pal(m, f, "pal" as *u8, "9" as *u8, "r_pal9" as *u8); ws_pal(m, f, "pal" as *u8, "10" as *u8, "r_pal10" as *u8); ws_pal(m, f, "pal" as *u8, "11" as *u8, "r_pal11" as *u8)
2996 ws_pal(m, f, "palf" as *u8, "0" as *u8, "r_palf0" as *u8); ws_pal(m, f, "palf" as *u8, "1" as *u8, "r_palf1" as *u8); ws_pal(m, f, "palf" as *u8, "2" as *u8, "r_palf2" as *u8)
2997 ws_pal(m, f, "palf" as *u8, "3" as *u8, "r_palf3" as *u8); ws_pal(m, f, "palf" as *u8, "4" as *u8, "r_palf4" as *u8)
2998 return f
2999}
3000
3001// fn vx(c:vec3i)->u32{if(c.x<0||c.y<0||c.z<0||c.x>127||c.y>47||c.z>127){return 0u;}return textureLoad(tV,vec3i(c.x,c.z,c.y),0).r;}
3002func ws_fn_vx(m: *i64) -> i64 {
3003 let f: i64 = sir_func(m, "vx" as *u8, T_U32)
3004 sir_param(m, f, "c" as *u8, T_V3I)
3005 let c0: i64 = ws_or(m, ws_or(m, ws_or(m, ws_or(m, ws_or(m,
3006 ws_cmp(m, "<" as *u8, ws_sx(m, "c" as *u8, T_V3I, "x" as *u8, T_I32), ws_i(m, "0" as *u8)),
3007 ws_cmp(m, "<" as *u8, ws_sx(m, "c" as *u8, T_V3I, "y" as *u8, T_I32), ws_i(m, "0" as *u8))),
3008 ws_cmp(m, "<" as *u8, ws_sx(m, "c" as *u8, T_V3I, "z" as *u8, T_I32), ws_i(m, "0" as *u8))),
3009 ws_cmp(m, ">" as *u8, ws_sx(m, "c" as *u8, T_V3I, "x" as *u8, T_I32), ws_i(m, "127" as *u8))),
3010 ws_cmp(m, ">" as *u8, ws_sx(m, "c" as *u8, T_V3I, "y" as *u8, T_I32), ws_i(m, "47" as *u8))),
3011 ws_cmp(m, ">" as *u8, ws_sx(m, "c" as *u8, T_V3I, "z" as *u8, T_I32), ws_i(m, "127" as *u8)))
3012 ws_st(m, f, ws_if(m, c0, ws_ret(m, ws_u(m, "0" as *u8)), 0))
3013 let co: i64 = ws_v3i(m, ws_sx(m, "c" as *u8, T_V3I, "x" as *u8, T_I32), ws_sx(m, "c" as *u8, T_V3I, "z" as *u8, T_I32), ws_sx(m, "c" as *u8, T_V3I, "y" as *u8, T_I32))
3014 let tl: i64 = sir_texload(m, ws_id(m, "tV" as *u8, T_TEX3U), co, ws_i(m, "0" as *u8))
3015 ws_st(m, f, ws_ret(m, ws_sw(m, tl, "r" as *u8, T_U32)))
3016 return f
3017}
3018
3019// fn h21(p:vec2f)->f32{return fract(sin(dot(p,vec2f(127.1,311.7)))*43758.5453);}
3020func ws_fn_h21(m: *i64) -> i64 {
3021 let f: i64 = sir_func(m, "h21" as *u8, T_F32)
3022 sir_param(m, f, "p" as *u8, T_V2F)
3023 let d: i64 = ws_c2(m, "dot" as *u8, ws_id(m, "p" as *u8, T_V2F), ws_v2f(m, "127.1" as *u8, "311.7" as *u8), T_F32)
3024 ws_st(m, f, ws_ret(m, ws_c1(m, "fract" as *u8, ws_bin(m, "*" as *u8, ws_c1(m, "sin" as *u8, d, T_F32), ws_f(m, "43758.5453" as *u8), T_F32), T_F32)))
3025 return f
3026}
3027
3028// fn h31(p:vec3f)->f32{return fract(sin(dot(p,vec3f(127.1,311.7,74.7)))*43758.5453);}
3029func ws_fn_h31(m: *i64) -> i64 {
3030 let f: i64 = sir_func(m, "h31" as *u8, T_F32)
3031 sir_param(m, f, "p" as *u8, T_V3F)
3032 let d: i64 = ws_c2(m, "dot" as *u8, ws_id(m, "p" as *u8, T_V3F), ws_v3f(m, "127.1" as *u8, "311.7" as *u8, "74.7" as *u8), T_F32)
3033 ws_st(m, f, ws_ret(m, ws_c1(m, "fract" as *u8, ws_bin(m, "*" as *u8, ws_c1(m, "sin" as *u8, d, T_F32), ws_f(m, "43758.5453" as *u8), T_F32), T_F32)))
3034 return f
3035}
3036
3037// fn pal9(b:u32)->vec3f{var i:i32=i32(b);if(i<0){i=0;}if(i>16){i=16;}if(i<12){return u.pal[i].xyz;}return u.palf[i-12].xyz;}
3038func ws_fn_pal9(m: *i64) -> i64 {
3039 let f: i64 = sir_func(m, "pal9" as *u8, T_V3F)
3040 sir_param(m, f, "b" as *u8, T_U32)
3041 ws_st(m, f, sir_var(m, "i" as *u8, T_I32, sir_cast(m, ws_id(m, "b" as *u8, T_U32), T_I32)))
3042 ws_st(m, f, ws_if(m, ws_cmp(m, "<" as *u8, ws_id(m, "i" as *u8, T_I32), ws_i(m, "0" as *u8)), ws_set(m, ws_id(m, "i" as *u8, T_I32), ws_i(m, "0" as *u8)), 0))
3043 ws_st(m, f, ws_if(m, ws_cmp(m, ">" as *u8, ws_id(m, "i" as *u8, T_I32), ws_i(m, "16" as *u8)), ws_set(m, ws_id(m, "i" as *u8, T_I32), ws_i(m, "16" as *u8)), 0))
3044 let pal: i64 = ws_sw(m, sir_index(m, ws_id(m, "pal" as *u8, T_V4F), ws_id(m, "i" as *u8, T_I32), T_V4F), "xyz" as *u8, T_V3F)
3045 ws_st(m, f, ws_if(m, ws_cmp(m, "<" as *u8, ws_id(m, "i" as *u8, T_I32), ws_i(m, "12" as *u8)), ws_ret(m, pal), 0))
3046 let palf: i64 = ws_sw(m, sir_index(m, ws_id(m, "palf" as *u8, T_V4F), ws_bin(m, "-" as *u8, ws_id(m, "i" as *u8, T_I32), ws_i(m, "12" as *u8), T_I32), T_V4F), "xyz" as *u8, T_V3F)
3047 ws_st(m, f, ws_ret(m, palf))
3048 return f
3049}
3050
3051// the 2-octave hash noise used by sky: mix(mix(h21(i),h21(i+(1,0)),f.x),mix(h21(i+(0,1)),h21(i+(1,1)),f.x),f.y)
3052func ws_noise2(m: *i64, iname: *u8, fname: *u8) -> i64 {
3053 let a: i64 = ws_c1(m, "h21" as *u8, ws_id(m, iname, T_V2F), T_F32)
3054 let b: i64 = ws_c1(m, "h21" as *u8, ws_bin(m, "+" as *u8, ws_id(m, iname, T_V2F), ws_v2f(m, "1.0" as *u8, "0.0" as *u8), T_V2F), T_F32)
3055 let c: i64 = ws_c1(m, "h21" as *u8, ws_bin(m, "+" as *u8, ws_id(m, iname, T_V2F), ws_v2f(m, "0.0" as *u8, "1.0" as *u8), T_V2F), T_F32)
3056 let d: i64 = ws_c1(m, "h21" as *u8, ws_bin(m, "+" as *u8, ws_id(m, iname, T_V2F), ws_v2f(m, "1.0" as *u8, "1.0" as *u8), T_V2F), T_F32)
3057 let m1: i64 = ws_c3(m, "mix" as *u8, a, b, ws_sx(m, fname, T_V2F, "x" as *u8, T_F32), T_F32)
3058 let m2: i64 = ws_c3(m, "mix" as *u8, c, d, ws_sx(m, fname, T_V2F, "x" as *u8, T_F32), T_F32)
3059 return ws_c3(m, "mix" as *u8, m1, m2, ws_sx(m, fname, T_V2F, "y" as *u8, T_F32), T_F32)
3060}
3061
3062// ---- PG22 (2026-09-06): THE VOLUMETRIC WEATHER FIELD ON THE GPU DOOR -- the sky's cloud is a 3D density RAYMARCHED,
3063// never a sheet. This is nx_worldgen.wg_cloud_volume's law spoken in the shader dialect: 3D value noise on h31 (three
3064// octaves), a vertical envelope between CB_BASE and CB_TOP, and a coverage threshold driven by the weather's cloud
3065// param (cld); the CPU tier keeps drawing the sheet (nx_worldgen.wg_cloud_sheet) and nx_cloud_volume_gate proves the
3066// volume follows the weather field. The march is one slab, entry to exit in CB_STEPS steps, front-to-back transmittance,
3067// lit by a base-to-top gradient plus a silver term toward the sun. Every number is a named string const (a data hook
3068// until the weather table carries it). The hand text, statement for statement:
3069// fn vn3(q:vec3f)->f32{let i=floor(q);let f0=fract(q);let f=f0*f0*(3.0-f0*2.0);let a=h31(i);let b=h31(i+vec3f(1,0,0));...;let k=h31(i+vec3f(1,1,1));return mix(mix(mix(a,b,f.x),mix(c,d,f.x),f.y),mix(mix(e,g,f.x),mix(h,k,f.x),f.y),f.z);}
3070// fn cvol(p:vec3f)->f32{let q=vec3f(p.x/CELL+t/DX,p.y/CELLY,p.z/CELL+t/DZ);let n=vn3(q)*0.5+vn3(q*2.0)*0.3+vn3(q*4.0)*0.2;let env=min((p.y-BASE)/RLO,1.0)*min((TOP-p.y)/RHI,1.0);let thr=THR0-THRK*clamp(cld,0.0,1.0);return clamp((n-thr)*GAIN,0.0,1.0)*max(env,0.0);}
3071// fn cld3(rd:vec3f,s0:vec3f)->vec3f{if(cld<=0.5||rd.y<=0.04){return s0;}let t0=(BASE-cam.y)/rd.y;if(t0<=0.0){return s0;}let dt=((TOP-cam.y)/rd.y-t0)/STEPS;var tr=1.0;var acc=vec3f(0.0);for(var i=0;i<STEPS;i++){let p=cam+rd*(t0+(f32(i)+0.5)*dt);let dn=1.0-exp(0.0-cvol(p)*dt*SIGMA);let lit=LIT0+LIT1*(p.y-BASE)/(TOP-BASE)+SUNK*max(dot(rd,sund),0.0)*sun;acc=acc+vec3f(0.98,0.99,1.0)*(lit*dn*tr);tr=tr*(1.0-dn);}return s0*tr+acc;}
3072const CB_BASE: *u8 = "180.0" // the incumbent sheet's height in blocks, now the slab base
3073const CB_TOP: *u8 = "300.0"
3074const CB_RLO: *u8 = "24.0" // density ramps in over this many blocks above the base
3075const CB_RHI: *u8 = "48.0" // and out over this many below the top
3076const CB_CELL: *u8 = "180.0" // one noise cell in blocks, horizontal
3077const CB_CELLY: *u8 = "120.0" // and vertical (flatter cells read as stratus)
3078const CB_DRIFT_X: *u8 = "240.0" // the incumbent sheet's drift divisors, kept so the motion does not change
3079const CB_DRIFT_Z: *u8 = "540.0"
3080const CB_THR0: *u8 = "0.78" // coverage threshold at cld=0
3081const CB_THRK: *u8 = "0.30" // and how far cld=1 lowers it
3082const CB_GAIN: *u8 = "1.4"
3083const CB_STEPS: *u8 = "48"
3084const CB_STEPS_F: *u8 = "48.0"
3085const CB_SIGMA: *u8 = "0.04" // extinction per block of unit density
3086const CB_LIT0: *u8 = "0.70" // ambient at the base
3087const CB_LIT1: *u8 = "0.30" // brighter toward the top
3088const CB_SUNK: *u8 = "0.15" // silver toward the sun
3089
3090// PRIVATE cloud profile: world-unit artistic defaults, not measured weather.
3091// Six sun-ray samples follow the existing banked cloud contract; view/light budgets require device qualification.
3092const CB_EROSION: *u8 = "0.22"
3093const CB_SUN_Y_MIN: *u8 = "0.01"
3094const CB_LIGHT_DISTANCE: *u8 = "480.0"
3095const CB_LIGHT_STEPS: *u8 = "6"
3096const CB_LIGHT_STEPS_F: *u8 = "6.0"
3097const CB_VIEW_DISTANCE: *u8 = "1400.0"
3098const CB_PHASE_G: *u8 = "0.35"
3099const CB_AMBIENT: *u8 = "0.85"
3100const CB_DIRECT: *u8 = "0.72"
3101func ws_h31o(m: *i64, a: *u8, b: *u8, c: *u8) -> i64 {
3102 return ws_c1(m, "h31" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "i" as *u8, T_V3F), ws_v3f(m, a, b, c), T_V3F), T_F32)
3103}
3104func ws_fx(m: *i64, sel: *u8) -> i64 { return ws_sx(m, "f" as *u8, T_V3F, sel, T_F32) }
3105func ws_py(m: *i64) -> i64 { return ws_sx(m, "p" as *u8, T_V3F, "y" as *u8, T_F32) }
3106// fn vn3(q:vec3f)->f32 -- 3D value noise on h31, trilinear with a smoothstep fade (the shape of noise2 lifted one axis)
3107func ws_fn_vn3(m: *i64) -> i64 {
3108 let f: i64 = sir_func(m, "vn3" as *u8, T_F32)
3109 sir_param(m, f, "q" as *u8, T_V3F)
3110 ws_st(m, f, sir_let(m, "i" as *u8, T_V3F, ws_c1(m, "floor" as *u8, ws_id(m, "q" as *u8, T_V3F), T_V3F)))
3111 ws_st(m, f, sir_let(m, "f0" as *u8, T_V3F, ws_c1(m, "fract" as *u8, ws_id(m, "q" as *u8, T_V3F), T_V3F)))
3112 ws_st(m, f, sir_let(m, "f" as *u8, T_V3F, ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "f0" as *u8, T_V3F), ws_id(m, "f0" as *u8, T_V3F), T_V3F), ws_bin(m, "-" as *u8, ws_v1(m, T_V3F, ws_f(m, "3.0" as *u8)), ws_bin(m, "*" as *u8, ws_id(m, "f0" as *u8, T_V3F), ws_f(m, "2.0" as *u8), T_V3F), T_V3F), T_V3F)))
3113 ws_st(m, f, sir_let(m, "a" as *u8, T_F32, ws_c1(m, "h31" as *u8, ws_id(m, "i" as *u8, T_V3F), T_F32)))
3114 ws_st(m, f, sir_let(m, "b" as *u8, T_F32, ws_h31o(m, "1.0" as *u8, "0.0" as *u8, "0.0" as *u8)))
3115 ws_st(m, f, sir_let(m, "c" as *u8, T_F32, ws_h31o(m, "0.0" as *u8, "1.0" as *u8, "0.0" as *u8)))
3116 ws_st(m, f, sir_let(m, "d" as *u8, T_F32, ws_h31o(m, "1.0" as *u8, "1.0" as *u8, "0.0" as *u8)))
3117 ws_st(m, f, sir_let(m, "e" as *u8, T_F32, ws_h31o(m, "0.0" as *u8, "0.0" as *u8, "1.0" as *u8)))
3118 ws_st(m, f, sir_let(m, "g" as *u8, T_F32, ws_h31o(m, "1.0" as *u8, "0.0" as *u8, "1.0" as *u8)))
3119 ws_st(m, f, sir_let(m, "h" as *u8, T_F32, ws_h31o(m, "0.0" as *u8, "1.0" as *u8, "1.0" as *u8)))
3120 ws_st(m, f, sir_let(m, "k" as *u8, T_F32, ws_h31o(m, "1.0" as *u8, "1.0" as *u8, "1.0" as *u8)))
3121 let x0: i64 = ws_c3(m, "mix" as *u8, ws_c3(m, "mix" as *u8, ws_id(m, "a" as *u8, T_F32), ws_id(m, "b" as *u8, T_F32), ws_fx(m, "x" as *u8), T_F32), ws_c3(m, "mix" as *u8, ws_id(m, "c" as *u8, T_F32), ws_id(m, "d" as *u8, T_F32), ws_fx(m, "x" as *u8), T_F32), ws_fx(m, "y" as *u8), T_F32)
3122 let x1: i64 = ws_c3(m, "mix" as *u8, ws_c3(m, "mix" as *u8, ws_id(m, "e" as *u8, T_F32), ws_id(m, "g" as *u8, T_F32), ws_fx(m, "x" as *u8), T_F32), ws_c3(m, "mix" as *u8, ws_id(m, "h" as *u8, T_F32), ws_id(m, "k" as *u8, T_F32), ws_fx(m, "x" as *u8), T_F32), ws_fx(m, "y" as *u8), T_F32)
3123 ws_st(m, f, ws_ret(m, ws_c3(m, "mix" as *u8, x0, x1, ws_fx(m, "z" as *u8), T_F32)))
3124 return f
3125}
3126// fn cvol(p:vec3f)->f32 -- the cloud density at a world point: three octaves, the envelope, the coverage threshold
3127func ws_fn_cvol(m: *i64) -> i64 {
3128 let f: i64 = sir_func(m, "cvol" as *u8, T_F32)
3129 sir_param(m, f, "p" as *u8, T_V3F)
3130 ws_st(m, f, sir_let(m, "hf" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_sx(m, "p" as *u8, T_V3F, "y" as *u8, T_F32), ws_f(m, CB_BASE), T_F32), ws_bin(m, "-" as *u8, ws_f(m, CB_TOP), ws_f(m, CB_BASE), T_F32), T_F32)))
3131 ws_st(m, f, sir_let(m, "adv" as *u8, T_V3F, ws_v3(m, ws_bin(m, "/" as *u8, ws_id(m, "t" as *u8, T_F32), ws_f(m, CB_DRIFT_X), T_F32), ws_f(m, "0.0" as *u8), ws_bin(m, "/" as *u8, ws_id(m, "t" as *u8, T_F32), ws_f(m, CB_DRIFT_Z), T_F32))))
3132 ws_st(m, f, sir_let(m, "q" as *u8, T_V3F, ws_bin(m, "+" as *u8, ws_bin(m, "/" as *u8, ws_id(m, "p" as *u8, T_V3F), ws_v3(m, ws_f(m, CB_CELL), ws_f(m, CB_CELLY), ws_f(m, CB_CELL)), T_V3F), ws_id(m, "adv" as *u8, T_V3F), T_V3F)))
3133 ws_st(m, f, sir_let(m, "shape" as *u8, T_F32, ws_c1(m, "vn3" as *u8, ws_id(m, "q" as *u8, T_V3F), T_F32)))
3134 ws_st(m, f, sir_let(m, "detail" as *u8, T_F32, ws_c1(m, "vn3" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "q" as *u8, T_V3F), ws_f(m, "4.0" as *u8), T_V3F), T_F32)))
3135 ws_st(m, f, sir_let(m, "env" as *u8, T_F32, ws_bin(m, "*" as *u8, ws_c3(m, "smoothstep" as *u8, ws_f(m, "0.0" as *u8), ws_bin(m, "/" as *u8, ws_f(m, CB_RLO), ws_bin(m, "-" as *u8, ws_f(m, CB_TOP), ws_f(m, CB_BASE), T_F32), T_F32), ws_id(m, "hf" as *u8, T_F32), T_F32), ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_c3(m, "smoothstep" as *u8, ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_bin(m, "/" as *u8, ws_f(m, CB_RHI), ws_bin(m, "-" as *u8, ws_f(m, CB_TOP), ws_f(m, CB_BASE), T_F32), T_F32), T_F32), ws_f(m, "1.0" as *u8), ws_id(m, "hf" as *u8, T_F32), T_F32), T_F32), T_F32)))
3136 ws_st(m, f, sir_let(m, "thr" as *u8, T_F32, ws_bin(m, "-" as *u8, ws_f(m, CB_THR0), ws_bin(m, "*" as *u8, ws_f(m, CB_THRK), ws_c3(m, "clamp" as *u8, ws_id(m, "cld" as *u8, T_F32), ws_f(m, "0.0" as *u8), ws_f(m, "1.0" as *u8), T_F32), T_F32), T_F32)))
3137 ws_st(m, f, sir_let(m, "body" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_id(m, "shape" as *u8, T_F32), ws_id(m, "thr" as *u8, T_F32), T_F32), ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_id(m, "thr" as *u8, T_F32), T_F32), T_F32)))
3138 ws_st(m, f, sir_let(m, "eroded" as *u8, T_F32, ws_bin(m, "-" as *u8, ws_id(m, "body" as *u8, T_F32), ws_bin(m, "*" as *u8, ws_id(m, "detail" as *u8, T_F32), ws_f(m, CB_EROSION), T_F32), T_F32)))
3139 ws_st(m, f, ws_ret(m, ws_bin(m, "*" as *u8, ws_c3(m, "clamp" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "eroded" as *u8, T_F32), ws_f(m, CB_GAIN), T_F32), ws_f(m, "0.0" as *u8), ws_f(m, "1.0" as *u8), T_F32), ws_id(m, "env" as *u8, T_F32), T_F32)))
3140 return f
3141}
3142
3143func ws_fn_csun(m: *i64) -> i64 {
3144 let f: i64 = sir_func(m, "csun" as *u8, T_F32)
3145 sir_param(m, f, "p" as *u8, T_V3F)
3146 ws_st(m, f, sir_let(m, "dy" as *u8, T_F32, ws_c2(m, "max" as *u8, ws_sx(m, "sund" as *u8, T_V3F, "y" as *u8, T_F32), ws_f(m, CB_SUN_Y_MIN), T_F32)))
3147 ws_st(m, f, sir_let(m, "ds" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_c2(m, "min" as *u8, ws_bin(m, "/" as *u8, ws_c2(m, "max" as *u8, ws_bin(m, "-" as *u8, ws_f(m, CB_TOP), ws_sx(m, "p" as *u8, T_V3F, "y" as *u8, T_F32), T_F32), ws_f(m, "0.0" as *u8), T_F32), ws_id(m, "dy" as *u8, T_F32), T_F32), ws_f(m, CB_LIGHT_DISTANCE), T_F32), ws_f(m, CB_LIGHT_STEPS_F), T_F32)))
3148 ws_st(m, f, sir_var(m, "tau" as *u8, T_F32, ws_f(m, "0.0" as *u8)))
3149 let lp: i64 = sir_let(m, "lp" as *u8, T_V3F, ws_bin(m, "+" as *u8, ws_id(m, "p" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "sund" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_bin(m, "+" as *u8, ws_fi(m, "j" as *u8), ws_f(m, "0.5" as *u8), T_F32), ws_id(m, "ds" as *u8, T_F32), T_F32), T_V3F), T_V3F))
3150 let lt: i64 = ws_op(m, "tau" as *u8, T_F32, "+" as *u8, ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_c1(m, "cvol" as *u8, ws_id(m, "lp" as *u8, T_V3F), T_F32), ws_id(m, "ds" as *u8, T_F32), T_F32), ws_f(m, CB_SIGMA), T_F32))
3151 sir_for_until(m, f, sir_var(m, "j" as *u8, T_I32, ws_i(m, "0" as *u8)), ws_cmp(m, ">=" as *u8, ws_id(m, "j" as *u8, T_I32), ws_i(m, CB_LIGHT_STEPS)), ws_op(m, "j" as *u8, T_I32, "+" as *u8, ws_i(m, "1" as *u8)), ws_q2(m, lp, lt))
3152 ws_st(m, f, ws_ret(m, ws_c1(m, "exp" as *u8, ws_bin(m, "-" as *u8, ws_f(m, "0.0" as *u8), ws_id(m, "tau" as *u8, T_F32), T_F32), T_F32)))
3153 return f
3154}
3155// fn cld3(rd:vec3f,s0:vec3f)->vec3f -- the march: the sky colour s0 seen through the slab, front to back
3156func ws_fn_cld3(m: *i64) -> i64 {
3157 let f: i64 = sir_func(m, "cld3" as *u8, T_V3F)
3158 sir_param(m, f, "rd" as *u8, T_V3F)
3159 sir_param(m, f, "s0" as *u8, T_V3F)
3160 ws_st(m, f, ws_if(m, ws_cmp(m, "<=" as *u8, ws_id(m, "cld" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_ret(m, ws_id(m, "s0" as *u8, T_V3F)), 0))
3161 ws_st(m, f, sir_let(m, "dy" as *u8, T_F32, ws_sx(m, "rd" as *u8, T_V3F, "y" as *u8, T_F32)))
3162 ws_st(m, f, ws_if(m, ws_cmp(m, "==" as *u8, ws_id(m, "dy" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_ret(m, ws_id(m, "s0" as *u8, T_V3F)), 0))
3163 ws_st(m, f, sir_let(m, "a" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_f(m, CB_BASE), ws_sx(m, "cam" as *u8, T_V3F, "y" as *u8, T_F32), T_F32), ws_id(m, "dy" as *u8, T_F32), T_F32)))
3164 ws_st(m, f, sir_let(m, "b" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_f(m, CB_TOP), ws_sx(m, "cam" as *u8, T_V3F, "y" as *u8, T_F32), T_F32), ws_id(m, "dy" as *u8, T_F32), T_F32)))
3165 ws_st(m, f, sir_let(m, "t0" as *u8, T_F32, ws_c2(m, "max" as *u8, ws_c2(m, "min" as *u8, ws_id(m, "a" as *u8, T_F32), ws_id(m, "b" as *u8, T_F32), T_F32), ws_f(m, "0.0" as *u8), T_F32)))
3166 ws_st(m, f, sir_let(m, "t1" as *u8, T_F32, ws_c2(m, "min" as *u8, ws_c2(m, "max" as *u8, ws_id(m, "a" as *u8, T_F32), ws_id(m, "b" as *u8, T_F32), T_F32), ws_f(m, CB_VIEW_DISTANCE), T_F32)))
3167 ws_st(m, f, ws_if(m, ws_cmp(m, "<=" as *u8, ws_id(m, "t1" as *u8, T_F32), ws_id(m, "t0" as *u8, T_F32)), ws_ret(m, ws_id(m, "s0" as *u8, T_V3F)), 0))
3168 ws_st(m, f, sir_let(m, "dt" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_id(m, "t1" as *u8, T_F32), ws_id(m, "t0" as *u8, T_F32), T_F32), ws_f(m, CB_STEPS_F), T_F32)))
3169 ws_st(m, f, sir_var(m, "tr" as *u8, T_F32, ws_f(m, "1.0" as *u8)))
3170 ws_st(m, f, sir_var(m, "acc" as *u8, T_V3F, ws_v1(m, T_V3F, ws_f(m, "0.0" as *u8))))
3171 ws_st(m, f, sir_let(m, "phase" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_bin(m, "*" as *u8, ws_f(m, CB_PHASE_G), ws_f(m, CB_PHASE_G), T_F32), T_F32), ws_c2(m, "pow" as *u8, ws_bin(m, "-" as *u8, ws_bin(m, "+" as *u8, ws_f(m, "1.0" as *u8), ws_bin(m, "*" as *u8, ws_f(m, CB_PHASE_G), ws_f(m, CB_PHASE_G), T_F32), T_F32), ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_f(m, "2.0" as *u8), ws_f(m, CB_PHASE_G), T_F32), ws_c2(m, "dot" as *u8, ws_id(m, "rd" as *u8, T_V3F), ws_id(m, "sund" as *u8, T_V3F), T_F32), T_F32), T_F32), ws_f(m, "1.5" as *u8), T_F32), T_F32)))
3172 ws_st(m, f, sir_let(m, "ambient" as *u8, T_V3F, ws_bin(m, "*" as *u8, ws_id(m, "s0" as *u8, T_V3F), ws_f(m, CB_AMBIENT), T_V3F)))
3173 let p0: i64 = sir_let(m, "p" as *u8, T_V3F, ws_bin(m, "+" as *u8, ws_id(m, "cam" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "rd" as *u8, T_V3F), ws_bin(m, "+" as *u8, ws_id(m, "t0" as *u8, T_F32), ws_bin(m, "*" as *u8, ws_bin(m, "+" as *u8, ws_fi(m, "i" as *u8), ws_f(m, "0.5" as *u8), T_F32), ws_id(m, "dt" as *u8, T_F32), T_F32), T_F32), T_V3F), T_V3F))
3174 let d0: i64 = sir_let(m, "density" as *u8, T_F32, ws_c1(m, "cvol" as *u8, ws_id(m, "p" as *u8, T_V3F), T_F32))
3175 let a0: i64 = sir_let(m, "alpha" as *u8, T_F32, ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_c1(m, "exp" as *u8, ws_bin(m, "-" as *u8, ws_f(m, "0.0" as *u8), ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "density" as *u8, T_F32), ws_id(m, "dt" as *u8, T_F32), T_F32), ws_f(m, CB_SIGMA), T_F32), T_F32), T_F32), T_F32))
3176 let l0: i64 = sir_let(m, "light" as *u8, T_V3F, ws_bin(m, "+" as *u8, ws_id(m, "ambient" as *u8, T_V3F), ws_v1(m, T_V3F, ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_c1(m, "csun" as *u8, ws_id(m, "p" as *u8, T_V3F), T_F32), ws_id(m, "phase" as *u8, T_F32), T_F32), ws_f(m, CB_DIRECT), T_F32), ws_id(m, "sun" as *u8, T_F32), T_F32)), T_V3F))
3177 let c0: i64 = ws_op(m, "acc" as *u8, T_V3F, "+" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "light" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "tr" as *u8, T_F32), ws_id(m, "alpha" as *u8, T_F32), T_F32), T_V3F))
3178 let t0s: i64 = ws_op(m, "tr" as *u8, T_F32, "*" as *u8, ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_id(m, "alpha" as *u8, T_F32), T_F32))
3179 let body: i64 = ws_q2(m, ws_q3(m, p0, d0, a0), ws_if(m, ws_cmp(m, ">" as *u8, ws_id(m, "density" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_q3(m, l0, c0, t0s), 0))
3180 sir_for_until(m, f, sir_var(m, "i" as *u8, T_I32, ws_i(m, "0" as *u8)), ws_cmp(m, ">=" as *u8, ws_id(m, "i" as *u8, T_I32), ws_i(m, CB_STEPS)), ws_op(m, "i" as *u8, T_I32, "+" as *u8, ws_i(m, "1" as *u8)), body)
3181 let fog: i64 = ws_c3(m, "smoothstep" as *u8, ws_f(m, "0.0" as *u8), ws_f(m, CB_VIEW_DISTANCE), ws_id(m, "t0" as *u8, T_F32), T_F32)
3182 let composite: i64 = ws_bin(m, "+" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "s0" as *u8, T_V3F), ws_id(m, "tr" as *u8, T_F32), T_V3F), ws_id(m, "acc" as *u8, T_V3F), T_V3F)
3183 ws_st(m, f, ws_ret(m, ws_c3(m, "mix" as *u8, composite, ws_id(m, "s0" as *u8, T_V3F), fog, T_V3F)))
3184 return f
3185}
3186
3187// fn sky(rd:vec3f)->vec3f{ ... } -- the hand text, statement for statement
3188func ws_fn_sky(m: *i64) -> i64 {
3189 let f: i64 = sir_func(m, "sky" as *u8, T_V3F)
3190 sir_param(m, f, "rd" as *u8, T_V3F)
3191 // var s:vec3f=mix(u.skh,u.skt,clamp(rd.y*1.6+0.35,0.0,1.0));
3192 let cl: i64 = ws_c3(m, "clamp" as *u8, ws_bin(m, "+" as *u8, ws_bin(m, "*" as *u8, ws_sx(m, "rd" as *u8, T_V3F, "y" as *u8, T_F32), ws_f(m, "1.6" as *u8), T_F32), ws_f(m, "0.35" as *u8), T_F32), ws_f(m, "0.0" as *u8), ws_f(m, "1.0" as *u8), T_F32)
3193 ws_st(m, f, sir_var(m, "s" as *u8, T_V3F, ws_c3(m, "mix" as *u8, ws_id(m, "skh" as *u8, T_V3F), ws_id(m, "skt" as *u8, T_V3F), cl, T_V3F)))
3194 // if(u.sun>0.5){let d=dot(rd,u.sund);if(d>0.9993){s=vec3f(1.0,0.98,0.88);}else if(d>0.985){s=mix(s,vec3f(1.0,0.98,0.88),(d-0.985)/0.015*0.6);}}
3195 let dlet: i64 = sir_let(m, "d" as *u8, T_F32, ws_c2(m, "dot" as *u8, ws_id(m, "rd" as *u8, T_V3F), ws_id(m, "sund" as *u8, T_V3F), T_F32))
3196 let sunc: i64 = ws_set(m, ws_id(m, "s" as *u8, T_V3F), ws_v3f(m, "1.0" as *u8, "0.98" as *u8, "0.88" as *u8))
3197 let glow: i64 = ws_set(m, ws_id(m, "s" as *u8, T_V3F), ws_c3(m, "mix" as *u8, ws_id(m, "s" as *u8, T_V3F), ws_v3f(m, "1.0" as *u8, "0.98" as *u8, "0.88" as *u8), ws_bin(m, "*" as *u8, ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_id(m, "d" as *u8, T_F32), ws_f(m, "0.985" as *u8), T_F32), ws_f(m, "0.015" as *u8), T_F32), ws_f(m, "0.6" as *u8), T_F32), T_V3F))
3198 let inner: i64 = ws_if(m, ws_cmp(m, ">" as *u8, ws_id(m, "d" as *u8, T_F32), ws_f(m, "0.9993" as *u8)), sunc, ws_if(m, ws_cmp(m, ">" as *u8, ws_id(m, "d" as *u8, T_F32), ws_f(m, "0.985" as *u8)), glow, 0))
3199 ws_st(m, f, ws_if(m, ws_cmp(m, ">" as *u8, ws_id(m, "sun" as *u8, T_F32), ws_f(m, "0.5" as *u8)), ws_q2(m, dlet, inner), 0))
3200 // PG22: s = cld3(rd, s) -- the cloud is a raymarched 3D density (vn3 / cvol / cld3 above), never the projected
3201 // sheet this block used to draw; the cld>0.5 && rd.y>0.04 gate lives inside cld3 as its early return.
3202 ws_st(m, f, ws_set(m, ws_id(m, "s" as *u8, T_V3F), ws_c2(m, "cld3" as *u8, ws_id(m, "rd" as *u8, T_V3F), ws_id(m, "s" as *u8, T_V3F), T_V3F)))
3203 ws_st(m, f, ws_ret(m, ws_id(m, "s" as *u8, T_V3F)))
3204 return f
3205}
3206
3207// struct Hit{t:f32,c:vec3i,fce:i32,b:u32}
3208func ws_struct_hit(m: *i64) -> i64 {
3209 let st: i64 = sir_struct(m, "Hit" as *u8)
3210 sir_member(m, st, "t" as *u8, T_F32)
3211 sir_member(m, st, "c" as *u8, T_V3I)
3212 sir_member(m, st, "fce" as *u8, T_I32)
3213 sir_member(m, st, "b" as *u8, T_U32)
3214 return st
3215}
3216
3217// one DDA step: c.<a>=(c.<a>+st.<a>);t=tm.<a>;tm.<a>=(tm.<a>+dd.<a>);fce=select(<f>,<t>,st.<a>>0);
3218func ws_dda_step(m: *i64, ax: *u8, fneg: *u8, fpos: *u8) -> i64 {
3219 let s1: i64 = ws_opx(m, "c" as *u8, T_V3I, ax, T_I32, "+" as *u8, ws_sx(m, "st" as *u8, T_V3I, ax, T_I32))
3220 let s2: i64 = ws_set(m, ws_id(m, "t" as *u8, T_F32), ws_sx(m, "tm" as *u8, T_V3F, ax, T_F32))
3221 let s3: i64 = ws_opx(m, "tm" as *u8, T_V3F, ax, T_F32, "+" as *u8, ws_sx(m, "dd" as *u8, T_V3F, ax, T_F32))
3222 let s4: i64 = ws_set(m, ws_id(m, "fce" as *u8, T_I32), sir_select(m, ws_cmp(m, ">" as *u8, ws_sx(m, "st" as *u8, T_V3I, ax, T_I32), ws_i(m, "0" as *u8)), ws_i(m, fpos), ws_i(m, fneg), T_I32))
3223 return ws_q4(m, s1, s2, s3, s4)
3224}
3225
3226// ---- GE53 THE SURFACE FIELD (WebGPU, emitted from this one source) ---------------------------------------
3227// fn hq(x:i32,z:i32)->f32{ if(x<0||z<0||x>127||z>127){return -1.0;} return textureLoad(tH,vec2i(x,z),0).r; }
3228// the column's Q height in blocks (the base of its top block), -1 off the window
3229func ws_fn_hq(m: *i64) -> i64 {
3230 let f: i64 = sir_func(m, "hq" as *u8, T_F32)
3231 sir_param(m, f, "x" as *u8, T_I32)
3232 sir_param(m, f, "z" as *u8, T_I32)
3233 let oob: i64 = ws_or(m, ws_or(m, ws_or(m,
3234 ws_cmp(m, "<" as *u8, ws_id(m, "x" as *u8, T_I32), ws_i(m, "0" as *u8)),
3235 ws_cmp(m, "<" as *u8, ws_id(m, "z" as *u8, T_I32), ws_i(m, "0" as *u8))),
3236 ws_cmp(m, ">" as *u8, ws_id(m, "x" as *u8, T_I32), ws_i(m, "127" as *u8))),
3237 ws_cmp(m, ">" as *u8, ws_id(m, "z" as *u8, T_I32), ws_i(m, "127" as *u8)))
3238 ws_st(m, f, ws_if(m, oob, ws_ret(m, ws_f(m, "-1.0" as *u8)), 0))
3239 let tl: i64 = sir_texload(m, ws_id(m, "tH" as *u8, T_TEX2F), ws_vt2(m, T_V2I, ws_id(m, "x" as *u8, T_I32), ws_id(m, "z" as *u8, T_I32)), ws_i(m, "0" as *u8))
3240 ws_st(m, f, ws_ret(m, ws_sw(m, tl, "r" as *u8, T_F32)))
3241 return f
3242}
3243// fn surf(p:vec2f)->f32 -- the terrain SURFACE height at a world xz: bilinear between the four columns,
3244// one block above the column base (the top of the ground). -1 when any corner is off the field.
3245func ws_fn_surf(m: *i64) -> i64 {
3246 let f: i64 = sir_func(m, "surf" as *u8, T_F32)
3247 sir_param(m, f, "p" as *u8, T_V2F)
3248 ws_st(m, f, sir_let(m, "ix" as *u8, T_I32, sir_cast(m, ws_c1(m, "floor" as *u8, ws_sx(m, "p" as *u8, T_V2F, "x" as *u8, T_F32), T_F32), T_I32)))
3249 ws_st(m, f, sir_let(m, "iz" as *u8, T_I32, sir_cast(m, ws_c1(m, "floor" as *u8, ws_sx(m, "p" as *u8, T_V2F, "y" as *u8, T_F32), T_F32), T_I32)))
3250 ws_st(m, f, sir_let(m, "fr" as *u8, T_V2F, ws_c1(m, "fract" as *u8, ws_id(m, "p" as *u8, T_V2F), T_V2F)))
3251 ws_st(m, f, sir_let(m, "h00" as *u8, T_F32, ws_c2(m, "hq" as *u8, ws_id(m, "ix" as *u8, T_I32), ws_id(m, "iz" as *u8, T_I32), T_F32)))
3252 ws_st(m, f, sir_let(m, "h10" as *u8, T_F32, ws_c2(m, "hq" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "ix" as *u8, T_I32), ws_i(m, "1" as *u8), T_I32), ws_id(m, "iz" as *u8, T_I32), T_F32)))
3253 ws_st(m, f, sir_let(m, "h01" as *u8, T_F32, ws_c2(m, "hq" as *u8, ws_id(m, "ix" as *u8, T_I32), ws_bin(m, "+" as *u8, ws_id(m, "iz" as *u8, T_I32), ws_i(m, "1" as *u8), T_I32), T_F32)))
3254 ws_st(m, f, sir_let(m, "h11" as *u8, T_F32, ws_c2(m, "hq" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "ix" as *u8, T_I32), ws_i(m, "1" as *u8), T_I32), ws_bin(m, "+" as *u8, ws_id(m, "iz" as *u8, T_I32), ws_i(m, "1" as *u8), T_I32), T_F32)))
3255 let miss: i64 = ws_or(m, ws_or(m, ws_or(m,
3256 ws_cmp(m, "<" as *u8, ws_id(m, "h00" as *u8, T_F32), ws_f(m, "0.0" as *u8)),
3257 ws_cmp(m, "<" as *u8, ws_id(m, "h10" as *u8, T_F32), ws_f(m, "0.0" as *u8))),
3258 ws_cmp(m, "<" as *u8, ws_id(m, "h01" as *u8, T_F32), ws_f(m, "0.0" as *u8))),
3259 ws_cmp(m, "<" as *u8, ws_id(m, "h11" as *u8, T_F32), ws_f(m, "0.0" as *u8)))
3260 ws_st(m, f, ws_if(m, miss, ws_ret(m, ws_f(m, "-1.0" as *u8)), 0))
3261 let mx0: i64 = ws_c3(m, "mix" as *u8, ws_id(m, "h00" as *u8, T_F32), ws_id(m, "h10" as *u8, T_F32), ws_sx(m, "fr" as *u8, T_V2F, "x" as *u8, T_F32), T_F32)
3262 let mx1: i64 = ws_c3(m, "mix" as *u8, ws_id(m, "h01" as *u8, T_F32), ws_id(m, "h11" as *u8, T_F32), ws_sx(m, "fr" as *u8, T_V2F, "x" as *u8, T_F32), T_F32)
3263 ws_st(m, f, ws_ret(m, ws_bin(m, "+" as *u8, ws_c3(m, "mix" as *u8, mx0, mx1, ws_sx(m, "fr" as *u8, T_V2F, "y" as *u8, T_F32), T_F32), ws_f(m, "1.0" as *u8), T_F32)))
3264 return f
3265}
3266// fn terrain(b:u32)->i32 -- the ground classes the field replaces; structures (wood, leaves, crops, water) stay cells
3267func ws_fn_terrain(m: *i64) -> i64 {
3268 let f: i64 = sir_func(m, "terrain" as *u8, T_I32)
3269 sir_param(m, f, "b" as *u8, T_U32)
3270 let tb: i64 = ws_or(m, ws_or(m, ws_or(m, ws_or(m, ws_or(m, ws_or(m, ws_or(m,
3271 ws_beq(m, "1" as *u8), ws_beq(m, "2" as *u8)), ws_beq(m, "3" as *u8)), ws_beq(m, "5" as *u8)), ws_beq(m, "8" as *u8)), ws_beq(m, "9" as *u8)), ws_beq(m, "10" as *u8)), ws_beq(m, "11" as *u8))
3272 ws_st(m, f, ws_if(m, tb, ws_ret(m, ws_i(m, "1" as *u8)), 0))
3273 ws_st(m, f, ws_ret(m, ws_i(m, "0" as *u8)))
3274 return f
3275}
3276// fn smarch(ro:vec3f,rd:vec3f,mx:i32)->f32 -- march the continuous surface: quarter-block steps (the field is
3277// bilinear between columns, so a quarter block can never skip one), exit above the tallest column when climbing,
3278// six bisections at the crossing. Returns t, or -1 for sky. The GPU twin of the sim's wray_surf.
3279func ws_fn_smarch(m: *i64) -> i64 {
3280 let f: i64 = sir_func(m, "smarch" as *u8, T_F32)
3281 sir_param(m, f, "ro" as *u8, T_V3F)
3282 sir_param(m, f, "rd" as *u8, T_V3F)
3283 sir_param(m, f, "mx" as *u8, T_I32)
3284 ws_st(m, f, sir_var(m, "t" as *u8, T_F32, ws_f(m, "0.0" as *u8)))
3285 ws_st(m, f, sir_var(m, "tp" as *u8, T_F32, ws_f(m, "0.0" as *u8)))
3286 ws_st(m, f, sir_var(m, "hit" as *u8, T_I32, ws_i(m, "0" as *u8)))
3287 let s1: i64 = ws_op(m, "t" as *u8, T_F32, "+" as *u8, ws_f(m, "0.25" as *u8))
3288 let s2: i64 = sir_let(m, "p" as *u8, T_V3F, ws_bin(m, "+" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "rd" as *u8, T_V3F), ws_id(m, "t" as *u8, T_F32), T_V3F), T_V3F))
3289 let s3: i64 = ws_if(m, ws_and(m, ws_cmp(m, ">" as *u8, ws_sx(m, "p" as *u8, T_V3F, "y" as *u8, T_F32), ws_bin(m, "+" as *u8, ws_id(m, "wmax" as *u8, T_F32), ws_f(m, "2.0" as *u8), T_F32)), ws_cmp(m, ">=" as *u8, ws_sx(m, "rd" as *u8, T_V3F, "y" as *u8, T_F32), ws_f(m, "0.0" as *u8))), ws_ret(m, ws_f(m, "-1.0" as *u8)), 0)
3290 let oob: i64 = ws_or(m, ws_or(m, ws_or(m,
3291 ws_cmp(m, "<" as *u8, ws_sx(m, "p" as *u8, T_V3F, "x" as *u8, T_F32), ws_f(m, "-8.0" as *u8)),
3292 ws_cmp(m, ">" as *u8, ws_sx(m, "p" as *u8, T_V3F, "x" as *u8, T_F32), ws_f(m, "136.0" as *u8))),
3293 ws_cmp(m, "<" as *u8, ws_sx(m, "p" as *u8, T_V3F, "z" as *u8, T_F32), ws_f(m, "-8.0" as *u8))),
3294 ws_cmp(m, ">" as *u8, ws_sx(m, "p" as *u8, T_V3F, "z" as *u8, T_F32), ws_f(m, "136.0" as *u8)))
3295 let s4: i64 = ws_if(m, oob, ws_ret(m, ws_f(m, "-1.0" as *u8)), 0)
3296 let s5: i64 = sir_let(m, "hs" as *u8, T_F32, ws_c1(m, "surf" as *u8, ws_sx(m, "p" as *u8, T_V3F, "xz" as *u8, T_V2F), T_F32))
3297 let s6: i64 = ws_if(m, ws_and(m, ws_cmp(m, ">=" as *u8, ws_id(m, "hs" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_cmp(m, "<=" as *u8, ws_sx(m, "p" as *u8, T_V3F, "y" as *u8, T_F32), ws_id(m, "hs" as *u8, T_F32))), ws_q2(m, ws_set(m, ws_id(m, "hit" as *u8, T_I32), ws_i(m, "1" as *u8)), sir_break(m)), 0)
3298 let s7: i64 = ws_set(m, ws_id(m, "tp" as *u8, T_F32), ws_id(m, "t" as *u8, T_F32))
3299 let body: i64 = ws_q4(m, ws_q3(m, s1, s2, s3), s4, s5, ws_q2(m, s6, s7))
3300 sir_for_until(m, f, sir_var(m, "i" as *u8, T_I32, ws_i(m, "0" as *u8)), ws_cmp(m, ">=" as *u8, ws_id(m, "i" as *u8, T_I32), ws_bin(m, "*" as *u8, ws_id(m, "mx" as *u8, T_I32), ws_i(m, "4" as *u8), T_I32)), ws_op(m, "i" as *u8, T_I32, "+" as *u8, ws_i(m, "1" as *u8)), body)
3301 ws_st(m, f, ws_if(m, ws_cmp(m, "==" as *u8, ws_id(m, "hit" as *u8, T_I32), ws_i(m, "0" as *u8)), ws_ret(m, ws_f(m, "-1.0" as *u8)), 0))
3302 ws_st(m, f, sir_var(m, "lo" as *u8, T_F32, ws_id(m, "tp" as *u8, T_F32)))
3303 ws_st(m, f, sir_var(m, "hi" as *u8, T_F32, ws_id(m, "t" as *u8, T_F32)))
3304 let k1: i64 = sir_let(m, "md" as *u8, T_F32, ws_bin(m, "*" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "lo" as *u8, T_F32), ws_id(m, "hi" as *u8, T_F32), T_F32), ws_f(m, "0.5" as *u8), T_F32))
3305 let k2: i64 = sir_let(m, "q" as *u8, T_V3F, ws_bin(m, "+" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "rd" as *u8, T_V3F), ws_id(m, "md" as *u8, T_F32), T_V3F), T_V3F))
3306 let k3: i64 = sir_let(m, "h2" as *u8, T_F32, ws_c1(m, "surf" as *u8, ws_sx(m, "q" as *u8, T_V3F, "xz" as *u8, T_V2F), T_F32))
3307 let k4: i64 = ws_if(m, ws_and(m, ws_cmp(m, ">=" as *u8, ws_id(m, "h2" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_cmp(m, "<=" as *u8, ws_sx(m, "q" as *u8, T_V3F, "y" as *u8, T_F32), ws_id(m, "h2" as *u8, T_F32))), ws_set(m, ws_id(m, "hi" as *u8, T_F32), ws_id(m, "md" as *u8, T_F32)), ws_set(m, ws_id(m, "lo" as *u8, T_F32), ws_id(m, "md" as *u8, T_F32)))
3308 sir_for_until(m, f, sir_var(m, "k" as *u8, T_I32, ws_i(m, "0" as *u8)), ws_cmp(m, ">=" as *u8, ws_id(m, "k" as *u8, T_I32), ws_i(m, "6" as *u8)), ws_op(m, "k" as *u8, T_I32, "+" as *u8, ws_i(m, "1" as *u8)), ws_q4(m, k1, k2, k3, k4))
3309 ws_st(m, f, ws_ret(m, ws_id(m, "hi" as *u8, T_F32)))
3310 return f
3311}
3312// fn gnd(p:vec2f)->f32 -- the ground light from the field's own gradient (central differences a quarter block
3313// apart), Lambert against the sun and NORMALISED TO LEVEL GROUND: level lights exactly as the shipped flat top
3314// face (1.0), the lee side floors at the shipped darkest face (0.42) -- the same two values shade's six-way
3315// face table carries, so a flat field is byte-identical in brightness to a flat block top.
3316func ws_fn_gnd(m: *i64) -> i64 {
3317 let f: i64 = sir_func(m, "gnd" as *u8, T_F32)
3318 sir_param(m, f, "p" as *u8, T_V2F)
3319 ws_st(m, f, sir_let(m, "hl" as *u8, T_F32, ws_c1(m, "surf" as *u8, ws_bin(m, "-" as *u8, ws_id(m, "p" as *u8, T_V2F), ws_v2f(m, "0.25" as *u8, "0.0" as *u8), T_V2F), T_F32)))
3320 ws_st(m, f, sir_let(m, "hr" as *u8, T_F32, ws_c1(m, "surf" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "p" as *u8, T_V2F), ws_v2f(m, "0.25" as *u8, "0.0" as *u8), T_V2F), T_F32)))
3321 ws_st(m, f, sir_let(m, "hd" as *u8, T_F32, ws_c1(m, "surf" as *u8, ws_bin(m, "-" as *u8, ws_id(m, "p" as *u8, T_V2F), ws_v2f(m, "0.0" as *u8, "0.25" as *u8), T_V2F), T_F32)))
3322 ws_st(m, f, sir_let(m, "hu" as *u8, T_F32, ws_c1(m, "surf" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "p" as *u8, T_V2F), ws_v2f(m, "0.0" as *u8, "0.25" as *u8), T_V2F), T_F32)))
3323 let miss: i64 = ws_or(m, ws_or(m, ws_or(m,
3324 ws_cmp(m, "<" as *u8, ws_id(m, "hl" as *u8, T_F32), ws_f(m, "0.0" as *u8)),
3325 ws_cmp(m, "<" as *u8, ws_id(m, "hr" as *u8, T_F32), ws_f(m, "0.0" as *u8))),
3326 ws_cmp(m, "<" as *u8, ws_id(m, "hd" as *u8, T_F32), ws_f(m, "0.0" as *u8))),
3327 ws_cmp(m, "<" as *u8, ws_id(m, "hu" as *u8, T_F32), ws_f(m, "0.0" as *u8)))
3328 ws_st(m, f, ws_if(m, miss, ws_ret(m, ws_f(m, "1.0" as *u8)), 0))
3329 let nx: i64 = ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_id(m, "hl" as *u8, T_F32), ws_id(m, "hr" as *u8, T_F32), T_F32), ws_f(m, "0.5" as *u8), T_F32)
3330 let nz: i64 = ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_id(m, "hd" as *u8, T_F32), ws_id(m, "hu" as *u8, T_F32), T_F32), ws_f(m, "0.5" as *u8), T_F32)
3331 ws_st(m, f, sir_let(m, "n9" as *u8, T_V3F, ws_c1(m, "normalize" as *u8, ws_v3(m, nx, ws_f(m, "1.0" as *u8), nz), T_V3F)))
3332 ws_st(m, f, sir_let(m, "cp" as *u8, T_F32, ws_c2(m, "max" as *u8, ws_c2(m, "dot" as *u8, ws_id(m, "n9" as *u8, T_V3F), ws_id(m, "sund" as *u8, T_V3F), T_F32), ws_f(m, "0.0" as *u8), T_F32)))
3333 ws_st(m, f, sir_let(m, "cf" as *u8, T_F32, ws_c2(m, "max" as *u8, ws_sx(m, "sund" as *u8, T_V3F, "y" as *u8, T_F32), ws_f(m, "0.001" as *u8), T_F32)))
3334 let span: i64 = ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_f(m, "0.42" as *u8), T_F32)
3335 ws_st(m, f, ws_ret(m, ws_c2(m, "min" as *u8, ws_bin(m, "+" as *u8, ws_f(m, "0.42" as *u8), ws_bin(m, "*" as *u8, span, ws_bin(m, "/" as *u8, ws_id(m, "cp" as *u8, T_F32), ws_id(m, "cf" as *u8, T_F32), T_F32), T_F32), T_F32), ws_f(m, "1.0" as *u8), T_F32)))
3336 return f
3337}
3338
3339// fn march(ro:vec3f,rd:vec3f,skipw:i32,mx:i32)->Hit{ ... }
3340func ws_fn_march(m: *i64, hty: i64) -> i64 {
3341 let f: i64 = sir_func(m, "march" as *u8, hty)
3342 sir_param(m, f, "ro" as *u8, T_V3F)
3343 sir_param(m, f, "rd" as *u8, T_V3F)
3344 sir_param(m, f, "skipw" as *u8, T_I32)
3345 sir_param(m, f, "mx" as *u8, T_I32)
3346 sir_param(m, f, "skipt" as *u8, T_I32) // GE53: 1 = terrain cells are air (the field is the ground); callers pass u.r_surf
3347 // var h:Hit;h.t=-1.0;h.fce=0;h.b=0u;h.c=vec3i(0);
3348 ws_st(m, f, sir_var(m, "h" as *u8, hty, 0))
3349 ws_st(m, f, ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "t" as *u8, T_F32), ws_f(m, "-1.0" as *u8)))
3350 ws_st(m, f, ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "fce" as *u8, T_I32), ws_i(m, "0" as *u8)))
3351 ws_st(m, f, ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "b" as *u8, T_U32), ws_u(m, "0" as *u8)))
3352 ws_st(m, f, ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "c" as *u8, T_V3I), ws_v1(m, T_V3I, ws_i(m, "0" as *u8))))
3353 // var c:vec3i=vec3i(floor(ro));let st=vec3i(sign(rd));
3354 ws_st(m, f, sir_var(m, "c" as *u8, T_V3I, ws_v1(m, T_V3I, ws_c1(m, "floor" as *u8, ws_id(m, "ro" as *u8, T_V3F), T_V3F))))
3355 ws_st(m, f, sir_let(m, "st" as *u8, T_V3I, ws_v1(m, T_V3I, ws_c1(m, "sign" as *u8, ws_id(m, "rd" as *u8, T_V3F), T_V3F))))
3356 // let dd=abs(vec3f(1.0)/max(abs(rd),vec3f(1e-6)));
3357 ws_st(m, f, sir_let(m, "dd" as *u8, T_V3F, ws_c1(m, "abs" as *u8, ws_bin(m, "/" as *u8, ws_v1(m, T_V3F, ws_f(m, "1.0" as *u8)), ws_c2(m, "max" as *u8, ws_c1(m, "abs" as *u8, ws_id(m, "rd" as *u8, T_V3F), T_V3F), ws_v1(m, T_V3F, ws_f(m, "1e-6" as *u8)), T_V3F), T_V3F), T_V3F)))
3358 // var tm=(vec3f(st)*(vec3f(c)-ro)+vec3f(st)*0.5+vec3f(0.5))*dd;
3359 let tm0: i64 = ws_bin(m, "*" as *u8, ws_v1(m, T_V3F, ws_id(m, "st" as *u8, T_V3I)), ws_bin(m, "-" as *u8, ws_v1(m, T_V3F, ws_id(m, "c" as *u8, T_V3I)), ws_id(m, "ro" as *u8, T_V3F), T_V3F), T_V3F)
3360 let tm1: i64 = ws_bin(m, "+" as *u8, tm0, ws_bin(m, "*" as *u8, ws_v1(m, T_V3F, ws_id(m, "st" as *u8, T_V3I)), ws_f(m, "0.5" as *u8), T_V3F), T_V3F)
3361 let tm2: i64 = ws_bin(m, "+" as *u8, tm1, ws_v1(m, T_V3F, ws_f(m, "0.5" as *u8)), T_V3F)
3362 ws_st(m, f, sir_var(m, "tm" as *u8, T_V3F, ws_bin(m, "*" as *u8, tm2, ws_id(m, "dd" as *u8, T_V3F), T_V3F)))
3363 ws_st(m, f, sir_var(m, "t" as *u8, T_F32, ws_f(m, "0.0" as *u8)))
3364 ws_st(m, f, sir_var(m, "fce" as *u8, T_I32, ws_i(m, "0" as *u8)))
3365 // for(var i:i32=0;i<200;i++){ ... }
3366 let b1: i64 = ws_if(m, ws_cmp(m, ">=" as *u8, ws_id(m, "i" as *u8, T_I32), ws_id(m, "mx" as *u8, T_I32)), sir_break(m), 0)
3367 let cx: i64 = ws_and(m, ws_cmp(m, "<" as *u8, ws_sx(m, "tm" as *u8, T_V3F, "x" as *u8, T_F32), ws_sx(m, "tm" as *u8, T_V3F, "y" as *u8, T_F32)), ws_cmp(m, "<" as *u8, ws_sx(m, "tm" as *u8, T_V3F, "x" as *u8, T_F32), ws_sx(m, "tm" as *u8, T_V3F, "z" as *u8, T_F32)))
3368 let cy: i64 = ws_cmp(m, "<" as *u8, ws_sx(m, "tm" as *u8, T_V3F, "y" as *u8, T_F32), ws_sx(m, "tm" as *u8, T_V3F, "z" as *u8, T_F32))
3369 let b2: i64 = ws_if(m, cx, ws_dda_step(m, "x" as *u8, "1" as *u8, "2" as *u8), ws_if(m, cy, ws_dda_step(m, "y" as *u8, "3" as *u8, "4" as *u8), ws_dda_step(m, "z" as *u8, "5" as *u8, "6" as *u8)))
3370 // if(f32(c.y)>u.wmax&&rd.y>=0.0){return h;}if(c.y<0){return h;}
3371 let b3: i64 = ws_if(m, ws_and(m, ws_cmp(m, ">" as *u8, sir_cast(m, ws_sx(m, "c" as *u8, T_V3I, "y" as *u8, T_I32), T_F32), ws_id(m, "wmax" as *u8, T_F32)), ws_cmp(m, ">=" as *u8, ws_sx(m, "rd" as *u8, T_V3F, "y" as *u8, T_F32), ws_f(m, "0.0" as *u8))), ws_ret(m, ws_id(m, "h" as *u8, hty)), 0)
3372 let b4: i64 = ws_if(m, ws_cmp(m, "<" as *u8, ws_sx(m, "c" as *u8, T_V3I, "y" as *u8, T_I32), ws_i(m, "0" as *u8)), ws_ret(m, ws_id(m, "h" as *u8, hty)), 0)
3373 // if(c.x< -8||c.x>135||c.z< -8||c.z>135){return h;}
3374 let oob: i64 = ws_or(m, ws_or(m, ws_or(m, ws_cmp(m, "<" as *u8, ws_sx(m, "c" as *u8, T_V3I, "x" as *u8, T_I32), ws_i(m, "-8" as *u8)), ws_cmp(m, ">" as *u8, ws_sx(m, "c" as *u8, T_V3I, "x" as *u8, T_I32), ws_i(m, "135" as *u8))), ws_cmp(m, "<" as *u8, ws_sx(m, "c" as *u8, T_V3I, "z" as *u8, T_I32), ws_i(m, "-8" as *u8))), ws_cmp(m, ">" as *u8, ws_sx(m, "c" as *u8, T_V3I, "z" as *u8, T_I32), ws_i(m, "135" as *u8)))
3375 let b5: i64 = ws_if(m, oob, ws_ret(m, ws_id(m, "h" as *u8, hty)), 0)
3376 // var b=vx(c);if(skipw==1&&b==4u){b=0u;}
3377 let b6: i64 = sir_var(m, "b" as *u8, T_U32, ws_c1(m, "vx" as *u8, ws_id(m, "c" as *u8, T_V3I), T_U32))
3378 // GE53: under skipt the terrain classes are air too -- the field is the ground, only structures stay cells
3379 let b7: i64 = ws_q2(m,
3380 ws_if(m, ws_and(m, ws_cmp(m, "==" as *u8, ws_id(m, "skipw" as *u8, T_I32), ws_i(m, "1" as *u8)), ws_cmp(m, "==" as *u8, ws_id(m, "b" as *u8, T_U32), ws_u(m, "4" as *u8))), ws_set(m, ws_id(m, "b" as *u8, T_U32), ws_u(m, "0" as *u8)), 0),
3381 ws_if(m, ws_and(m, ws_cmp(m, "==" as *u8, ws_id(m, "skipt" as *u8, T_I32), ws_i(m, "1" as *u8)), ws_cmp(m, "==" as *u8, ws_c1(m, "terrain" as *u8, ws_id(m, "b" as *u8, T_U32), T_I32), ws_i(m, "1" as *u8))), ws_set(m, ws_id(m, "b" as *u8, T_U32), ws_u(m, "0" as *u8)), 0))
3382 // if(b!=0u){h.t=t;h.c=c;h.fce=fce;h.b=b;return h;}
3383 let hit: i64 = ws_q5(m,
3384 ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "t" as *u8, T_F32), ws_id(m, "t" as *u8, T_F32)),
3385 ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "c" as *u8, T_V3I), ws_id(m, "c" as *u8, T_V3I)),
3386 ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "fce" as *u8, T_I32), ws_id(m, "fce" as *u8, T_I32)),
3387 ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "b" as *u8, T_U32), ws_id(m, "b" as *u8, T_U32)),
3388 ws_ret(m, ws_id(m, "h" as *u8, hty)))
3389 let b8: i64 = ws_if(m, ws_cmp(m, "!=" as *u8, ws_id(m, "b" as *u8, T_U32), ws_u(m, "0" as *u8)), hit, 0)
3390 let body: i64 = ws_q4(m, ws_q4(m, b1, b2, b3, b4), b5, b6, ws_q2(m, b7, b8))
3391 sir_for_until(m, f, sir_var(m, "i" as *u8, T_I32, ws_i(m, "0" as *u8)), ws_cmp(m, ">=" as *u8, ws_id(m, "i" as *u8, T_I32), ws_i(m, "200" as *u8)), ws_op(m, "i" as *u8, T_I32, "+" as *u8, ws_i(m, "1" as *u8)), body)
3392 ws_st(m, f, ws_ret(m, ws_id(m, "h" as *u8, hty)))
3393 return f
3394}
3395
3396// one face arm of shade: uv=hp.<sw>;oc.<ax>=(oc.<ax><op>1);n=vec3f(<nx>,<ny>,<nz>);
3397func ws_face(m: *i64, sw: *u8, ax: *u8, op: *u8, nx: *u8, ny: *u8, nz: *u8) -> i64 {
3398 return ws_q3(m,
3399 ws_set(m, ws_id(m, "uv" as *u8, T_V2F), ws_sx(m, "hp" as *u8, T_V3F, sw, T_V2F)),
3400 ws_opx(m, "oc" as *u8, T_V3I, ax, T_I32, op, ws_i(m, "1" as *u8)),
3401 ws_set(m, ws_id(m, "n" as *u8, T_V3F), ws_v3f(m, nx, ny, nz)))
3402}
3403// li=(li*<k>)
3404func ws_li(m: *i64, k: *u8) -> i64 { return ws_op(m, "li" as *u8, T_F32, "*" as *u8, ws_f(m, k)) }
3405// fce==<k>
3406func ws_fce(m: *i64, k: *u8) -> i64 { return ws_cmp(m, "==" as *u8, ws_id(m, "fce" as *u8, T_I32), ws_i(m, k)) }
3407// b==<k>u
3408func ws_beq(m: *i64, k: *u8) -> i64 { return ws_cmp(m, "==" as *u8, ws_id(m, "b" as *u8, T_U32), ws_u(m, k)) }
3409// one AO probe: if(f.<fa> <cmp> <edge>){var nb=oc; <nudge>; if(vx(nb)!=0u&&vx(nb)!=4u){ao=(ao+(<gain>)*2.0);}}
3410func ws_ao(m: *i64, fa: *u8, cmp: *u8, edge: *u8, nudge: i64, gain: i64) -> i64 {
3411 let nbv: i64 = sir_var(m, "nb" as *u8, T_V3I, ws_id(m, "oc" as *u8, T_V3I))
3412 let solid: i64 = ws_and(m, ws_cmp(m, "!=" as *u8, ws_c1(m, "vx" as *u8, ws_id(m, "nb" as *u8, T_V3I), T_U32), ws_u(m, "0" as *u8)), ws_cmp(m, "!=" as *u8, ws_c1(m, "vx" as *u8, ws_id(m, "nb" as *u8, T_V3I), T_U32), ws_u(m, "4" as *u8)))
3413 let add: i64 = ws_op(m, "ao" as *u8, T_F32, "+" as *u8, ws_bin(m, "*" as *u8, gain, ws_f(m, "2.0" as *u8), T_F32))
3414 return ws_if(m, ws_cmp(m, cmp, ws_sx(m, "f" as *u8, T_V2F, fa, T_F32), ws_f(m, edge)), ws_q3(m, nbv, nudge, ws_if(m, solid, add, 0)), 0)
3415}
3416// nb.<ax>=(nb.<ax><op>1)
3417func ws_nb(m: *i64, ax: *u8, op: *u8) -> i64 { return ws_opx(m, "nb" as *u8, T_V3I, ax, T_I32, op, ws_i(m, "1" as *u8)) }
3418// fce==3||fce==4
3419func ws_topbot(m: *i64) -> i64 { return ws_or(m, ws_fce(m, "3" as *u8), ws_fce(m, "4" as *u8)) }
3420
3421// fn shade(ro:vec3f,rd:vec3f,t:f32,c:vec3i,fce:i32,b:u32)->vec3f{ ... }
3422// GE53 helpers -- each call builds a FRESH node tree (a node is never two children).
3423// Terrain lighting belongs only to a field hit, never to water or an object top face.
3424func ws_smooth(m: *i64) -> i64 {
3425 let field: i64 = ws_and(m, ws_cmp(m, "==" as *u8, sir_ident(m, "r_surf" as *u8, T_I32), ws_i(m, "1" as *u8)), ws_fce(m, "3" as *u8))
3426 return ws_and(m, field, ws_cmp(m, "==" as *u8, ws_c1(m, "terrain" as *u8, ws_id(m, "b" as *u8, T_U32), T_I32), ws_i(m, "1" as *u8)))
3427}
3428// The analytic plane has two sides; neither inherits the voxel material's cell decoration.
3429func ws_cont_water(m: *i64) -> i64 {
3430 return ws_and(m, ws_and(m, ws_cmp(m, "==" as *u8, sir_ident(m, "r_surf" as *u8, T_I32), ws_i(m, "1" as *u8)), ws_beq(m, "4" as *u8)), ws_topbot(m))
3431}
3432func ws_cont_surface(m: *i64) -> i64 { return ws_or(m, ws_smooth(m), ws_cont_water(m)) }
3433// one step of the scan-down to the column's top solid cell: if(cy9>0&&vx(vec3i(cx9,cy9,cz9))==0u){cy9=cy9-1;}
3434func ws_step_down(m: *i64) -> i64 {
3435 return ws_if(m, ws_and(m, ws_cmp(m, ">" as *u8, ws_id(m, "cy9" as *u8, T_I32), ws_i(m, "0" as *u8)), ws_cmp(m, "==" as *u8, ws_c1(m, "vx" as *u8, ws_vt3(m, T_V3I, ws_id(m, "cx9" as *u8, T_I32), ws_id(m, "cy9" as *u8, T_I32), ws_id(m, "cz9" as *u8, T_I32)), T_U32), ws_u(m, "0" as *u8))), ws_op(m, "cy9" as *u8, T_I32, "-" as *u8, ws_i(m, "1" as *u8)), 0)
3436}
3437// ---- GR27 (2026-09-06): THE GROUND IS A MATERIAL, NOT A PAINT -----------------------------------------------
3438// fn sand(hp:vec3f,c:vec3i,rd:vec3f,t:f32)->vec2f -- the field's ground material, all arithmetic on the surface
3439// field and the voxel volume, no texture. x = the light multiplier: the gnd() Lambert (level 1.0, lee floor 0.42)
3440// taken on the field normal TILTED by grain facets and wind ripples, then wet-darkened; y = the specular: a thin
3441// water film inside the wet band (a Blinn lobe plus a Fresnel sky sheen) and dry quartz glints.
3442// FOOTPRINT: one pixel spans 2/res.x world units per unit distance (sc = px/(res.x*0.5)), stretched by 1/|n.rd|
3443// at grazing angles. A hash cannot be mip-averaged, so every detail whose period falls under TWO footprints
3444// (the Nyquist bound) fades to zero instead of aliasing -- grains and ripples survive a grazing view by
3445// fading, never by sparkling; beyond that range sand reads as its albedo, which is what sand does.
3446// WET BAND: the volume is probed for water (class 4) on a ring of SD_RING_DIRS directions x SD_WET_R radii at
3447// the column's top solid cell and one below it; the nearest water radius sets the wetness (adjacent 1, three
3448// cells 1/3, beyond 0) and a water cell ABOVE the column means submerged (1). Wet sand darkens because pore
3449// water index-matches the grains (albedo x SD_WET_DARK) and gains a film sheen; the swash erases ripples.
3450// Every constant below is a data hook: the ripple heading is the wind row's heading and the grain scale the
3451// recipe's sand grade; both become raw words when the material table lands, and are NAMED here until then.
3452const SD_GRAIN_PER_BLOCK: *u8 = "32.0" // facets per block edge: 3 cm at a 1 m block, coarse beach sand
3453const SD_GRAIN_SLOPE: *u8 = "1.2" // facet steepness as a normal slope
3454const SD_RIPPLE_PER_BLOCK: *u8 = "9.0" // wind ripples per block: an 11 cm wavelength at a 1 m block
3455const SD_RIPPLE_SLOPE: *u8 = "0.45" // crest slope
3456const SD_RIPPLE_DX: *u8 = "0.8" // ripple normal heading (unit): the wind heading, a data hook
3457const SD_RIPPLE_DZ: *u8 = "0.6"
3458const SD_PATCH: *u8 = "0.25" // ripple phase jitter per 4-block patch so the field is not one sine
3459const SD_TAU: *u8 = "6.2831853"
3460const SD_QUARTER_TURN: *u8 = "1.5707963"
3461const SD_EIGHTH_TURN: *u8 = "0.7853982"
3462const SD_RING_DIRS: *u8 = "8"
3463const SD_RING_STEPS: *u8 = "24" // SD_RING_DIRS x SD_WET_R
3464const SD_WET_R: *u8 = "3.0" // wet band reach in cells
3465const SD_WET_DRY: *u8 = "4.0" // SD_WET_R + 1: no water within reach
3466const SD_WET_DARK: *u8 = "0.55" // wet albedo multiplier
3467const SD_FILM_POW: *u8 = "48.0"
3468const SD_FILM_GAIN: *u8 = "0.55"
3469const SD_SHEEN_GAIN: *u8 = "0.10"
3470const SD_GLINT_POW: *u8 = "96.0"
3471const SD_GLINT_GAIN: *u8 = "0.35"
3472const SD_GLINT_FRAC: *u8 = "0.9" // facets whose hash exceeds this are quartz glints
3473const SD_NDV_FLOOR: *u8 = "0.15" // the footprint stretch floor at grazing angles
3474const SD_SHADOW_SPEC: *u8 = "0.2" // in a block shadow the film keeps its sky sheen and loses the sun
3475const SD_TWO: *u8 = "2.0"
3476const SD_HALF: *u8 = "0.5"
3477// helpers -- every call builds a FRESH node tree (a node is never two children)
3478func ws_sd_pxz(m: *i64) -> i64 { return ws_sx(m, "hp" as *u8, T_V3F, "xz" as *u8, T_V2F) }
3479func ws_sd_f(m: *i64, n: *u8) -> i64 { return ws_id(m, n, T_F32) }
3480func ws_sd_v3(m: *i64, n: *u8) -> i64 { return ws_id(m, n, T_V3F) }
3481// surf(hp.xz <op> (dx,dz))
3482func ws_sd_surf(m: *i64, op: *u8, dx: *u8, dz: *u8) -> i64 { return ws_c1(m, "surf" as *u8, ws_bin(m, op, ws_sd_pxz(m), ws_v2f(m, dx, dz), T_V2F), T_F32) }
3483// h21(gc + (dx,dz))
3484func ws_sd_g(m: *i64, dx: *u8, dz: *u8) -> i64 { return ws_c1(m, "h21" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "gc" as *u8, T_V2F), ws_v2f(m, dx, dz), T_V2F), T_F32) }
3485func ws_sd_lt0(m: *i64, n: *u8) -> i64 { return ws_cmp(m, "<" as *u8, ws_id(m, n, T_F32), ws_f(m, "0.0" as *u8)) }
3486func ws_sd_dk(m: *i64, n: *u8) -> i64 { return ws_bin(m, "*" as *u8, ws_id(m, n, T_I32), ws_id(m, "k" as *u8, T_I32), T_I32) }
3487// vx(c + vec3i(dx*k, <y>, dz*k)) == 4u
3488func ws_sd_wat(m: *i64, y: *u8) -> i64 { return ws_cmp(m, "==" as *u8, ws_c1(m, "vx" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "c" as *u8, T_V3I), ws_vt3(m, T_V3I, ws_sd_dk(m, "dx" as *u8), ws_i(m, y), ws_sd_dk(m, "dz" as *u8)), T_V3I), T_U32), ws_u(m, "4" as *u8)) }
3489// i32(floor(sin(a + <shift>) + 0.5)) -- the ring direction from the angle, sin only (the covered subset)
3490func ws_sd_dir(m: *i64, shift: *u8) -> i64 { return sir_cast(m, ws_c1(m, "floor" as *u8, ws_bin(m, "+" as *u8, ws_c1(m, "sin" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "a" as *u8, T_F32), ws_f(m, shift), T_F32), T_F32), ws_f(m, SD_HALF), T_F32), T_F32), T_I32) }
3491// clamp(1 - 2*fp*<freq>, 0, 1) -- the Nyquist fade of a detail with <freq> periods per block
3492func ws_sd_fade(m: *i64, freq: *u8) -> i64 { return ws_c3(m, "clamp" as *u8, ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_f(m, SD_TWO), ws_sd_f(m, "fp" as *u8), T_F32), ws_f(m, freq), T_F32), T_F32), ws_f(m, "0.0" as *u8), ws_f(m, "1.0" as *u8), T_F32) }
3493// (a - b) * <k>
3494func ws_sd_dslope(m: *i64, a: *u8, b: *u8, k: *u8) -> i64 { return ws_bin(m, "*" as *u8, ws_bin(m, "-" as *u8, ws_sd_f(m, a), ws_sd_f(m, b), T_F32), ws_f(m, k), T_F32) }
3495// <s> + gam*<g> - dry*rs*<rdk> -- one axis of the tilted normal
3496func ws_sd_tilt(m: *i64, s: *u8, g: *u8, rdk: *u8) -> i64 {
3497 let a: i64 = ws_bin(m, "+" as *u8, ws_sd_f(m, s), ws_bin(m, "*" as *u8, ws_sd_f(m, "gam" as *u8), ws_sd_f(m, g), T_F32), T_F32)
3498 return ws_bin(m, "-" as *u8, a, ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_sd_f(m, "dry" as *u8), ws_sd_f(m, "rs" as *u8), T_F32), ws_f(m, rdk), T_F32), T_F32)
3499}
3500// the sand classes: 1 the shore slot (SHORE repaints the grass slot as shore sand), 2 packed sand, 5 sand at and
3501// below the waterline (nx_wasm_craft gencol) -- and ONLY under the field (ws_smooth), which today is the shore
3502// world's ground; a per-class material word is the data hook owed before another world's field lands
3503func ws_sandcls(m: *i64) -> i64 { return ws_or(m, ws_or(m, ws_beq(m, "1" as *u8), ws_beq(m, "2" as *u8)), ws_beq(m, "5" as *u8)) }
3504func ws_sandy(m: *i64) -> i64 { return ws_and(m, ws_smooth(m), ws_sandcls(m)) }
3505// the block-shadow arm: li*=0.55 as shipped, and the film specular loses the sun (keeps its sky sheen)
3506func ws_shd(m: *i64) -> i64 { return ws_q2(m, ws_li(m, "0.55" as *u8), ws_op(m, "sp" as *u8, T_F32, "*" as *u8, ws_f(m, SD_SHADOW_SPEC))) }
3507func ws_fn_sand(m: *i64) -> i64 {
3508 let f: i64 = sir_func(m, "sand" as *u8, T_V2F)
3509 sir_param(m, f, "hp" as *u8, T_V3F)
3510 sir_param(m, f, "c" as *u8, T_V3I)
3511 sir_param(m, f, "rd" as *u8, T_V3F)
3512 sir_param(m, f, "t" as *u8, T_F32)
3513 // the field normal from the same quarter-block central differences gnd uses; off the field = the flat answer
3514 ws_st(m, f, sir_let(m, "hl" as *u8, T_F32, ws_sd_surf(m, "-" as *u8, "0.25" as *u8, "0.0" as *u8)))
3515 ws_st(m, f, sir_let(m, "hr" as *u8, T_F32, ws_sd_surf(m, "+" as *u8, "0.25" as *u8, "0.0" as *u8)))
3516 ws_st(m, f, sir_let(m, "hd" as *u8, T_F32, ws_sd_surf(m, "-" as *u8, "0.0" as *u8, "0.25" as *u8)))
3517 ws_st(m, f, sir_let(m, "hu" as *u8, T_F32, ws_sd_surf(m, "+" as *u8, "0.0" as *u8, "0.25" as *u8)))
3518 let miss: i64 = ws_or(m, ws_or(m, ws_or(m, ws_sd_lt0(m, "hl" as *u8), ws_sd_lt0(m, "hr" as *u8)), ws_sd_lt0(m, "hd" as *u8)), ws_sd_lt0(m, "hu" as *u8))
3519 ws_st(m, f, ws_if(m, miss, ws_ret(m, ws_v2f(m, "1.0" as *u8, "0.0" as *u8)), 0))
3520 ws_st(m, f, sir_let(m, "sx" as *u8, T_F32, ws_sd_dslope(m, "hl" as *u8, "hr" as *u8, SD_TWO)))
3521 ws_st(m, f, sir_let(m, "sz" as *u8, T_F32, ws_sd_dslope(m, "hd" as *u8, "hu" as *u8, SD_TWO)))
3522 ws_st(m, f, sir_let(m, "nrm" as *u8, T_V3F, ws_c1(m, "normalize" as *u8, ws_v3(m, ws_sd_f(m, "sx" as *u8), ws_f(m, "1.0" as *u8), ws_sd_f(m, "sz" as *u8)), T_V3F)))
3523 // the pixel footprint at this hit, stretched by the grazing angle
3524 ws_st(m, f, sir_let(m, "ndv" as *u8, T_F32, ws_c2(m, "max" as *u8, ws_c1(m, "abs" as *u8, ws_c2(m, "dot" as *u8, ws_sd_v3(m, "nrm" as *u8), ws_sd_v3(m, "rd" as *u8), T_F32), T_F32), ws_f(m, SD_NDV_FLOOR), T_F32)))
3525 ws_st(m, f, sir_let(m, "fp" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_bin(m, "*" as *u8, ws_sd_f(m, "t" as *u8), ws_bin(m, "/" as *u8, ws_f(m, SD_TWO), ws_sx(m, "res" as *u8, T_V2F, "x" as *u8, T_F32), T_F32), T_F32), ws_sd_f(m, "ndv" as *u8), T_F32)))
3526 // grain facets: three hash taps a facet apart give the facet's two slopes; the amplitude fades at the Nyquist bound
3527 ws_st(m, f, sir_let(m, "gc" as *u8, T_V2F, ws_c1(m, "floor" as *u8, ws_bin(m, "*" as *u8, ws_sd_pxz(m), ws_f(m, SD_GRAIN_PER_BLOCK), T_V2F), T_V2F)))
3528 ws_st(m, f, sir_let(m, "g0" as *u8, T_F32, ws_sd_g(m, "0.0" as *u8, "0.0" as *u8)))
3529 ws_st(m, f, sir_let(m, "g1" as *u8, T_F32, ws_sd_g(m, "1.0" as *u8, "0.0" as *u8)))
3530 ws_st(m, f, sir_let(m, "g2" as *u8, T_F32, ws_sd_g(m, "0.0" as *u8, "1.0" as *u8)))
3531 ws_st(m, f, sir_let(m, "gam" as *u8, T_F32, ws_sd_fade(m, SD_GRAIN_PER_BLOCK)))
3532 ws_st(m, f, sir_let(m, "gx" as *u8, T_F32, ws_sd_dslope(m, "g0" as *u8, "g1" as *u8, SD_GRAIN_SLOPE)))
3533 ws_st(m, f, sir_let(m, "gz" as *u8, T_F32, ws_sd_dslope(m, "g0" as *u8, "g2" as *u8, SD_GRAIN_SLOPE)))
3534 // wind ripples: a crest slope along the wind heading, phase-jittered per patch, fading at its own Nyquist bound
3535 let ph0: i64 = ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_c2(m, "dot" as *u8, ws_sd_pxz(m), ws_v2f(m, SD_RIPPLE_DX, SD_RIPPLE_DZ), T_F32), ws_f(m, SD_RIPPLE_PER_BLOCK), T_F32), ws_f(m, SD_TAU), T_F32)
3536 let ph1: i64 = ws_bin(m, "*" as *u8, ws_c1(m, "h21" as *u8, ws_c1(m, "floor" as *u8, ws_bin(m, "*" as *u8, ws_sd_pxz(m), ws_f(m, SD_PATCH), T_V2F), T_V2F), T_F32), ws_f(m, SD_TAU), T_F32)
3537 ws_st(m, f, sir_let(m, "ph" as *u8, T_F32, ws_bin(m, "+" as *u8, ph0, ph1, T_F32)))
3538 ws_st(m, f, sir_let(m, "ram" as *u8, T_F32, ws_sd_fade(m, SD_RIPPLE_PER_BLOCK)))
3539 ws_st(m, f, sir_let(m, "rs" as *u8, T_F32, ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_c1(m, "sin" as *u8, ws_bin(m, "+" as *u8, ws_sd_f(m, "ph" as *u8), ws_f(m, SD_QUARTER_TURN), T_F32), T_F32), ws_f(m, SD_RIPPLE_SLOPE), T_F32), ws_sd_f(m, "ram" as *u8), T_F32)))
3540 // the wet band: the nearest water on the ring, at this cell's height and one below
3541 ws_st(m, f, sir_var(m, "wd" as *u8, T_F32, ws_f(m, SD_WET_DRY)))
3542 let kk: i64 = sir_let(m, "k" as *u8, T_I32, ws_bin(m, "+" as *u8, ws_bin(m, "/" as *u8, ws_id(m, "j" as *u8, T_I32), ws_i(m, SD_RING_DIRS), T_I32), ws_i(m, "1" as *u8), T_I32))
3543 let dd: i64 = sir_let(m, "d" as *u8, T_I32, ws_bin(m, "-" as *u8, ws_id(m, "j" as *u8, T_I32), ws_bin(m, "*" as *u8, ws_bin(m, "/" as *u8, ws_id(m, "j" as *u8, T_I32), ws_i(m, SD_RING_DIRS), T_I32), ws_i(m, SD_RING_DIRS), T_I32), T_I32))
3544 let aa: i64 = sir_let(m, "a" as *u8, T_F32, ws_bin(m, "*" as *u8, sir_cast(m, ws_id(m, "d" as *u8, T_I32), T_F32), ws_f(m, SD_EIGHTH_TURN), T_F32))
3545 let dx: i64 = sir_let(m, "dx" as *u8, T_I32, ws_sd_dir(m, SD_QUARTER_TURN))
3546 let dz: i64 = sir_let(m, "dz" as *u8, T_I32, ws_sd_dir(m, "0.0" as *u8))
3547 let near: i64 = ws_if(m, ws_or(m, ws_sd_wat(m, "0" as *u8), ws_sd_wat(m, "-1" as *u8)), ws_set(m, ws_id(m, "wd" as *u8, T_F32), ws_c2(m, "min" as *u8, ws_id(m, "wd" as *u8, T_F32), sir_cast(m, ws_id(m, "k" as *u8, T_I32), T_F32), T_F32)), 0)
3548 sir_for_until(m, f, sir_var(m, "j" as *u8, T_I32, ws_i(m, "0" as *u8)), ws_cmp(m, ">=" as *u8, ws_id(m, "j" as *u8, T_I32), ws_i(m, SD_RING_STEPS)), ws_op(m, "j" as *u8, T_I32, "+" as *u8, ws_i(m, "1" as *u8)), ws_q5(m, kk, dd, aa, ws_q2(m, dx, dz), near))
3549 let sub: i64 = ws_cmp(m, "==" as *u8, ws_c1(m, "vx" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "c" as *u8, T_V3I), ws_vt3(m, T_V3I, ws_i(m, "0" as *u8), ws_i(m, "1" as *u8), ws_i(m, "0" as *u8)), T_V3I), T_U32), ws_u(m, "4" as *u8))
3550 ws_st(m, f, ws_if(m, sub, ws_set(m, ws_id(m, "wd" as *u8, T_F32), ws_f(m, "0.0" as *u8)), 0))
3551 ws_st(m, f, sir_let(m, "wet" as *u8, T_F32, ws_c3(m, "clamp" as *u8, ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_f(m, SD_WET_DRY), ws_sd_f(m, "wd" as *u8), T_F32), ws_f(m, SD_WET_R), T_F32), ws_f(m, "0.0" as *u8), ws_f(m, "1.0" as *u8), T_F32)))
3552 ws_st(m, f, sir_let(m, "dry" as *u8, T_F32, ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_sd_f(m, "wet" as *u8), T_F32)))
3553 // the tilted normal: field slope + faded facets + the ripples the swash has not erased
3554 ws_st(m, f, sir_let(m, "pn" as *u8, T_V3F, ws_c1(m, "normalize" as *u8, ws_v3(m, ws_sd_tilt(m, "sx" as *u8, "gx" as *u8, SD_RIPPLE_DX), ws_f(m, "1.0" as *u8), ws_sd_tilt(m, "sz" as *u8, "gz" as *u8, SD_RIPPLE_DZ)), T_V3F)))
3555 // light: the gnd() Lambert on the tilted normal (level 1.0, lee floor 0.42), then wet darkening
3556 ws_st(m, f, sir_let(m, "cp" as *u8, T_F32, ws_c2(m, "max" as *u8, ws_c2(m, "dot" as *u8, ws_sd_v3(m, "pn" as *u8), ws_sd_v3(m, "sund" as *u8), T_F32), ws_f(m, "0.0" as *u8), T_F32)))
3557 ws_st(m, f, sir_let(m, "cf" as *u8, T_F32, ws_c2(m, "max" as *u8, ws_sx(m, "sund" as *u8, T_V3F, "y" as *u8, T_F32), ws_f(m, "0.001" as *u8), T_F32)))
3558 let span: i64 = ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_f(m, "0.42" as *u8), T_F32)
3559 ws_st(m, f, sir_let(m, "lp" as *u8, T_F32, ws_c2(m, "min" as *u8, ws_bin(m, "+" as *u8, ws_f(m, "0.42" as *u8), ws_bin(m, "*" as *u8, span, ws_bin(m, "/" as *u8, ws_sd_f(m, "cp" as *u8), ws_sd_f(m, "cf" as *u8), T_F32), T_F32), T_F32), ws_f(m, "1.0" as *u8), T_F32)))
3560 ws_st(m, f, sir_let(m, "lw" as *u8, T_F32, ws_bin(m, "*" as *u8, ws_sd_f(m, "lp" as *u8), ws_c3(m, "mix" as *u8, ws_f(m, "1.0" as *u8), ws_f(m, SD_WET_DARK), ws_sd_f(m, "wet" as *u8), T_F32), T_F32)))
3561 // specular: the film's Blinn lobe and Fresnel sky sheen inside the band, quartz glints on dry facets
3562 ws_st(m, f, sir_let(m, "hv" as *u8, T_V3F, ws_c1(m, "normalize" as *u8, ws_bin(m, "-" as *u8, ws_sd_v3(m, "sund" as *u8), ws_sd_v3(m, "rd" as *u8), T_V3F), T_V3F)))
3563 ws_st(m, f, sir_let(m, "fr" as *u8, T_F32, ws_c2(m, "pow" as *u8, ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_sd_f(m, "ndv" as *u8), T_F32), ws_f(m, "5.0" as *u8), T_F32)))
3564 ws_st(m, f, sir_let(m, "film" as *u8, T_F32, ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_sd_f(m, "wet" as *u8), ws_c2(m, "pow" as *u8, ws_c2(m, "max" as *u8, ws_c2(m, "dot" as *u8, ws_sd_v3(m, "pn" as *u8), ws_sd_v3(m, "hv" as *u8), T_F32), ws_f(m, "0.0" as *u8), T_F32), ws_f(m, SD_FILM_POW), T_F32), T_F32), ws_f(m, SD_FILM_GAIN), T_F32)))
3565 ws_st(m, f, sir_let(m, "sheen" as *u8, T_F32, ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_sd_f(m, "wet" as *u8), ws_sd_f(m, "fr" as *u8), T_F32), ws_f(m, SD_SHEEN_GAIN), T_F32)))
3566 ws_st(m, f, sir_let(m, "gn" as *u8, T_V3F, ws_c1(m, "normalize" as *u8, ws_v3(m, ws_sd_f(m, "gx" as *u8), ws_f(m, "1.0" as *u8), ws_sd_f(m, "gz" as *u8)), T_V3F)))
3567 ws_st(m, f, sir_var(m, "glint" as *u8, T_F32, ws_f(m, "0.0" as *u8)))
3568 let gl: i64 = ws_set(m, ws_id(m, "glint" as *u8, T_F32), ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_sd_f(m, "gam" as *u8), ws_c2(m, "pow" as *u8, ws_c2(m, "max" as *u8, ws_c2(m, "dot" as *u8, ws_sd_v3(m, "gn" as *u8), ws_sd_v3(m, "hv" as *u8), T_F32), ws_f(m, "0.0" as *u8), T_F32), ws_f(m, SD_GLINT_POW), T_F32), T_F32), ws_f(m, SD_GLINT_GAIN), T_F32))
3569 ws_st(m, f, ws_if(m, ws_cmp(m, ">" as *u8, ws_sd_f(m, "g0" as *u8), ws_f(m, SD_GLINT_FRAC)), gl, 0))
3570 // x = light, y = specular: the sun terms scaled by the sun flag, the sheen is the sky's and stays
3571 let sunspec: i64 = ws_bin(m, "*" as *u8, ws_sd_f(m, "sun" as *u8), ws_bin(m, "+" as *u8, ws_sd_f(m, "film" as *u8), ws_sd_f(m, "glint" as *u8), T_F32), T_F32)
3572 ws_st(m, f, ws_ret(m, ws_v2(m, ws_sd_f(m, "lw" as *u8), ws_bin(m, "+" as *u8, ws_sd_f(m, "sheen" as *u8), sunspec, T_F32))))
3573 return f
3574}
3575func ws_fn_shade(m: *i64, hty: i64) -> i64 {
3576 let f: i64 = sir_func(m, "shade" as *u8, T_V3F)
3577 sir_param(m, f, "ro" as *u8, T_V3F)
3578 sir_param(m, f, "rd" as *u8, T_V3F)
3579 sir_param(m, f, "t" as *u8, T_F32)
3580 sir_param(m, f, "c" as *u8, T_V3I)
3581 sir_param(m, f, "fce" as *u8, T_I32)
3582 sir_param(m, f, "b" as *u8, T_U32)
3583 // let hp=ro+rd*t; var uv:vec2f; var oc:vec3i=c; var n:vec3f=vec3f(0.0);
3584 ws_st(m, f, sir_let(m, "hp" as *u8, T_V3F, ws_bin(m, "+" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "rd" as *u8, T_V3F), ws_id(m, "t" as *u8, T_F32), T_V3F), T_V3F)))
3585 ws_st(m, f, sir_var(m, "uv" as *u8, T_V2F, 0))
3586 ws_st(m, f, sir_var(m, "oc" as *u8, T_V3I, ws_id(m, "c" as *u8, T_V3I)))
3587 ws_st(m, f, sir_var(m, "n" as *u8, T_V3F, ws_v1(m, T_V3F, ws_f(m, "0.0" as *u8))))
3588 // the six faces
3589 let f6: i64 = ws_face(m, "xy" as *u8, "z" as *u8, "-" as *u8, "0.0" as *u8, "0.0" as *u8, "-1.0" as *u8)
3590 let f5: i64 = ws_if(m, ws_fce(m, "5" as *u8), ws_face(m, "xy" as *u8, "z" as *u8, "+" as *u8, "0.0" as *u8, "0.0" as *u8, "1.0" as *u8), f6)
3591 let f4: i64 = ws_if(m, ws_fce(m, "4" as *u8), ws_face(m, "xz" as *u8, "y" as *u8, "-" as *u8, "0.0" as *u8, "-1.0" as *u8, "0.0" as *u8), f5)
3592 let f3: i64 = ws_if(m, ws_fce(m, "3" as *u8), ws_face(m, "xz" as *u8, "y" as *u8, "+" as *u8, "0.0" as *u8, "1.0" as *u8, "0.0" as *u8), f4)
3593 let f2: i64 = ws_if(m, ws_fce(m, "2" as *u8), ws_face(m, "zy" as *u8, "x" as *u8, "-" as *u8, "-1.0" as *u8, "0.0" as *u8, "0.0" as *u8), f3)
3594 ws_st(m, f, ws_if(m, ws_fce(m, "1" as *u8), ws_face(m, "zy" as *u8, "x" as *u8, "+" as *u8, "1.0" as *u8, "0.0" as *u8, "0.0" as *u8), f2))
3595 // let f=fract(uv); var bb:u32=b; if(b==1u&&fce!=3&&fce!=4){bb=2u;if(f.y>0.8){bb=1u;}}
3596 ws_st(m, f, sir_let(m, "f" as *u8, T_V2F, ws_c1(m, "fract" as *u8, ws_id(m, "uv" as *u8, T_V2F), T_V2F)))
3597 ws_st(m, f, sir_var(m, "bb" as *u8, T_U32, ws_id(m, "b" as *u8, T_U32)))
3598 let grass: i64 = ws_q2(m, ws_set(m, ws_id(m, "bb" as *u8, T_U32), ws_u(m, "2" as *u8)), ws_if(m, ws_cmp(m, ">" as *u8, ws_sx(m, "f" as *u8, T_V2F, "y" as *u8, T_F32), ws_f(m, "0.8" as *u8)), ws_set(m, ws_id(m, "bb" as *u8, T_U32), ws_u(m, "1" as *u8)), 0))
3599 ws_st(m, f, ws_if(m, ws_and(m, ws_and(m, ws_beq(m, "1" as *u8), ws_cmp(m, "!=" as *u8, ws_id(m, "fce" as *u8, T_I32), ws_i(m, "3" as *u8))), ws_cmp(m, "!=" as *u8, ws_id(m, "fce" as *u8, T_I32), ws_i(m, "4" as *u8))), grass, 0))
3600 // var li:f32; the six-way face light
3601 ws_st(m, f, sir_var(m, "li" as *u8, T_F32, 0))
3602 let l6: i64 = ws_set(m, ws_id(m, "li" as *u8, T_F32), ws_f(m, "0.56" as *u8))
3603 let l5: i64 = ws_if(m, ws_fce(m, "5" as *u8), ws_set(m, ws_id(m, "li" as *u8, T_F32), ws_f(m, "0.62" as *u8)), l6)
3604 let l2: i64 = ws_if(m, ws_fce(m, "2" as *u8), ws_set(m, ws_id(m, "li" as *u8, T_F32), ws_f(m, "0.7" as *u8)), l5)
3605 let l1: i64 = ws_if(m, ws_fce(m, "1" as *u8), ws_set(m, ws_id(m, "li" as *u8, T_F32), ws_f(m, "0.76" as *u8)), l2)
3606 let l4: i64 = ws_if(m, ws_fce(m, "4" as *u8), ws_set(m, ws_id(m, "li" as *u8, T_F32), ws_f(m, "0.42" as *u8)), l1)
3607 ws_st(m, f, ws_if(m, ws_fce(m, "3" as *u8), ws_set(m, ws_id(m, "li" as *u8, T_F32), ws_f(m, "1.0" as *u8)), l4))
3608 // GE53: on the field the ground's own gradient lights the top face (level = the same 1.0, lee = the same 0.42 floor)
3609 // GR27: on the field the sand classes are a MATERIAL -- sand() lights the tilted normal and returns the film specular
3610 // in sp; every other class on the field keeps the bare gradient light
3611 ws_st(m, f, sir_var(m, "sp" as *u8, T_F32, ws_f(m, "0.0" as *u8)))
3612 let sm: i64 = ws_q3(m, sir_let(m, "sm" as *u8, T_V2F, ws_c4(m, "sand" as *u8, ws_id(m, "hp" as *u8, T_V3F), ws_id(m, "c" as *u8, T_V3I), ws_id(m, "rd" as *u8, T_V3F), ws_id(m, "t" as *u8, T_F32), T_V2F)), ws_set(m, ws_id(m, "li" as *u8, T_F32), ws_sx(m, "sm" as *u8, T_V2F, "x" as *u8, T_F32)), ws_set(m, ws_id(m, "sp" as *u8, T_F32), ws_sx(m, "sm" as *u8, T_V2F, "y" as *u8, T_F32)))
3613 ws_st(m, f, ws_if(m, ws_smooth(m), ws_if(m, ws_sandcls(m), sm, ws_set(m, ws_id(m, "li" as *u8, T_F32), ws_c1(m, "gnd" as *u8, ws_sx(m, "hp" as *u8, T_V3F, "xz" as *u8, T_V2F), T_F32))), 0))
3614 // if(u.sun>0.5){if(fce==1){li*=1.12;}if(fce==2){li*=0.92;}if(fce==5){li*=1.04;}}
3615 ws_st(m, f, ws_if(m, ws_cmp(m, ">" as *u8, ws_id(m, "sun" as *u8, T_F32), ws_f(m, "0.5" as *u8)), ws_q3(m, ws_if(m, ws_fce(m, "1" as *u8), ws_li(m, "1.12" as *u8), 0), ws_if(m, ws_fce(m, "2" as *u8), ws_li(m, "0.92" as *u8), 0), ws_if(m, ws_fce(m, "5" as *u8), ws_li(m, "1.04" as *u8), 0)), 0))
3616 // let sd3=floor(hp)*0.13; let bs=f32(b)*7.0;
3617 ws_st(m, f, sir_let(m, "sd3" as *u8, T_V3F, ws_bin(m, "*" as *u8, ws_c1(m, "floor" as *u8, ws_id(m, "hp" as *u8, T_V3F), T_V3F), ws_f(m, "0.13" as *u8), T_V3F)))
3618 ws_st(m, f, sir_let(m, "bs" as *u8, T_F32, ws_bin(m, "*" as *u8, sir_cast(m, ws_id(m, "b" as *u8, T_U32), T_F32), ws_f(m, "7.0" as *u8), T_F32)))
3619 // t00 / t10 / t01 = h31(vec3f(floor(f*24.0 [+ offset]),bs)+sd3)
3620 let f24a: i64 = ws_bin(m, "*" as *u8, ws_id(m, "f" as *u8, T_V2F), ws_f(m, "24.0" as *u8), T_V2F)
3621 ws_st(m, f, sir_let(m, "t00" as *u8, T_F32, ws_c1(m, "h31" as *u8, ws_bin(m, "+" as *u8, ws_vt2(m, T_V3F, ws_c1(m, "floor" as *u8, f24a, T_V2F), ws_id(m, "bs" as *u8, T_F32)), ws_id(m, "sd3" as *u8, T_V3F), T_V3F), T_F32)))
3622 let f24b: i64 = ws_bin(m, "+" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "f" as *u8, T_V2F), ws_f(m, "24.0" as *u8), T_V2F), ws_v2f(m, "1.0" as *u8, "0.0" as *u8), T_V2F)
3623 ws_st(m, f, sir_let(m, "t10" as *u8, T_F32, ws_c1(m, "h31" as *u8, ws_bin(m, "+" as *u8, ws_vt2(m, T_V3F, ws_c1(m, "floor" as *u8, f24b, T_V2F), ws_id(m, "bs" as *u8, T_F32)), ws_id(m, "sd3" as *u8, T_V3F), T_V3F), T_F32)))
3624 let f24c: i64 = ws_bin(m, "+" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "f" as *u8, T_V2F), ws_f(m, "24.0" as *u8), T_V2F), ws_v2f(m, "0.0" as *u8, "1.0" as *u8), T_V2F)
3625 ws_st(m, f, sir_let(m, "t01" as *u8, T_F32, ws_c1(m, "h31" as *u8, ws_bin(m, "+" as *u8, ws_vt2(m, T_V3F, ws_c1(m, "floor" as *u8, f24c, T_V2F), ws_id(m, "bs" as *u8, T_F32)), ws_id(m, "sd3" as *u8, T_V3F), T_V3F), T_F32)))
3626 // let bmp=(t10-t00)*0.6+(t01-t00)*0.45;
3627 ws_st(m, f, sir_let(m, "bmp" as *u8, T_F32, ws_bin(m, "+" as *u8, ws_bin(m, "*" as *u8, ws_bin(m, "-" as *u8, ws_id(m, "t10" as *u8, T_F32), ws_id(m, "t00" as *u8, T_F32), T_F32), ws_f(m, "0.6" as *u8), T_F32), ws_bin(m, "*" as *u8, ws_bin(m, "-" as *u8, ws_id(m, "t01" as *u8, T_F32), ws_id(m, "t00" as *u8, T_F32), T_F32), ws_f(m, "0.45" as *u8), T_F32), T_F32)))
3628 // var bamp:f32; the block-class relief amplitude
3629 ws_st(m, f, sir_var(m, "bamp" as *u8, T_F32, 0))
3630 let a4: i64 = ws_if(m, ws_beq(m, "4" as *u8), ws_set(m, ws_id(m, "bamp" as *u8, T_F32), ws_f(m, "0.25" as *u8)), ws_set(m, ws_id(m, "bamp" as *u8, T_F32), ws_f(m, "0.7" as *u8)))
3631 let a7: i64 = ws_if(m, ws_beq(m, "7" as *u8), ws_set(m, ws_id(m, "bamp" as *u8, T_F32), ws_f(m, "1.3" as *u8)), a4)
3632 let rough: i64 = ws_or(m, ws_or(m, ws_or(m, ws_or(m, ws_beq(m, "3" as *u8), ws_beq(m, "2" as *u8)), ws_beq(m, "9" as *u8)), ws_beq(m, "10" as *u8)), ws_beq(m, "11" as *u8))
3633 ws_st(m, f, ws_if(m, rough, ws_set(m, ws_id(m, "bamp" as *u8, T_F32), ws_f(m, "1.0" as *u8)), a7))
3634 ws_st(m, f, ws_if(m, ws_or(m, ws_sandy(m), ws_cont_water(m)), ws_set(m, ws_id(m, "bamp" as *u8, T_F32), ws_f(m, "0.0" as *u8)), 0)) // GR27: the per-cell hash relief IS the paint the material replaces
3635 // let dfade=clamp(1.0-t/24.0,0.0,1.0); li*=clamp(1.0+bmp*bamp*dfade,0.55,1.45); li*=0.9+t00*0.2*dfade;
3636 ws_st(m, f, sir_let(m, "dfade" as *u8, T_F32, ws_c3(m, "clamp" as *u8, ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_bin(m, "/" as *u8, ws_id(m, "t" as *u8, T_F32), ws_f(m, "24.0" as *u8), T_F32), T_F32), ws_f(m, "0.0" as *u8), ws_f(m, "1.0" as *u8), T_F32)))
3637 ws_st(m, f, ws_op(m, "li" as *u8, T_F32, "*" as *u8, ws_c3(m, "clamp" as *u8, ws_bin(m, "+" as *u8, ws_f(m, "1.0" as *u8), ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "bmp" as *u8, T_F32), ws_id(m, "bamp" as *u8, T_F32), T_F32), ws_id(m, "dfade" as *u8, T_F32), T_F32), T_F32), ws_f(m, "0.55" as *u8), ws_f(m, "1.45" as *u8), T_F32)))
3638 // The sand material owns its detail response; legacy voxel paint belongs to other surfaces.
3639 ws_st(m, f, ws_if(m, sir_not(m, ws_or(m, ws_sandy(m), ws_cont_water(m))), ws_op(m, "li" as *u8, T_F32, "*" as *u8, ws_bin(m, "+" as *u8, ws_f(m, "0.9" as *u8), ws_bin(m, "*" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "t00" as *u8, T_F32), ws_f(m, "0.2" as *u8), T_F32), ws_id(m, "dfade" as *u8, T_F32), T_F32), T_F32)), 0))
3640 // if(bb==1u&&fce==3&&t<24.0){let tf=h21(floor(f*38.0)+floor(hp.xz)*3.7);if(tf>0.82){li*=1.28;}else if(tf<0.14){li*=0.78;}}
3641 let tf: i64 = sir_let(m, "tf" as *u8, T_F32, ws_c1(m, "h21" as *u8, ws_bin(m, "+" as *u8, ws_c1(m, "floor" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "f" as *u8, T_V2F), ws_f(m, "38.0" as *u8), T_V2F), T_V2F), ws_bin(m, "*" as *u8, ws_c1(m, "floor" as *u8, ws_sx(m, "hp" as *u8, T_V3F, "xz" as *u8, T_V2F), T_V2F), ws_f(m, "3.7" as *u8), T_V2F), T_V2F), T_F32))
3642 let tfi: i64 = ws_if(m, ws_cmp(m, ">" as *u8, ws_id(m, "tf" as *u8, T_F32), ws_f(m, "0.82" as *u8)), ws_li(m, "1.28" as *u8), ws_if(m, ws_cmp(m, "<" as *u8, ws_id(m, "tf" as *u8, T_F32), ws_f(m, "0.14" as *u8)), ws_li(m, "0.78" as *u8), 0))
3643 ws_st(m, f, ws_if(m, ws_and(m, sir_not(m, ws_sandy(m)), ws_and(m, ws_and(m, ws_cmp(m, "==" as *u8, ws_id(m, "bb" as *u8, T_U32), ws_u(m, "1" as *u8)), ws_fce(m, "3" as *u8)), ws_cmp(m, "<" as *u8, ws_id(m, "t" as *u8, T_F32), ws_f(m, "24.0" as *u8)))), ws_q2(m, tf, tfi), 0))
3644 // if(f.x<0.055||f.x>0.945||f.y<0.055||f.y>0.945){li*=0.82;}
3645 let edge: i64 = ws_or(m, ws_or(m, ws_or(m, ws_cmp(m, "<" as *u8, ws_sx(m, "f" as *u8, T_V2F, "x" as *u8, T_F32), ws_f(m, "0.055" as *u8)), ws_cmp(m, ">" as *u8, ws_sx(m, "f" as *u8, T_V2F, "x" as *u8, T_F32), ws_f(m, "0.945" as *u8))), ws_cmp(m, "<" as *u8, ws_sx(m, "f" as *u8, T_V2F, "y" as *u8, T_F32), ws_f(m, "0.055" as *u8))), ws_cmp(m, ">" as *u8, ws_sx(m, "f" as *u8, T_V2F, "y" as *u8, T_F32), ws_f(m, "0.945" as *u8)))
3646 ws_st(m, f, ws_if(m, ws_and(m, edge, sir_not(m, ws_cont_surface(m))), ws_li(m, "0.82" as *u8), 0)) // GE53: no cell-edge grid on the field
3647 // var ao:f32=0.0; the four edge-AO probes
3648 ws_st(m, f, sir_var(m, "ao" as *u8, T_F32, ws_f(m, "0.0" as *u8)))
3649 let n1: i64 = ws_if(m, ws_topbot(m), ws_nb(m, "x" as *u8, "-" as *u8), ws_if(m, ws_cmp(m, "<" as *u8, ws_id(m, "fce" as *u8, T_I32), ws_i(m, "3" as *u8)), ws_nb(m, "z" as *u8, "-" as *u8), ws_nb(m, "x" as *u8, "-" as *u8)))
3650 ws_st(m, f, ws_ao(m, "x" as *u8, "<" as *u8, "0.17" as *u8, n1, ws_bin(m, "-" as *u8, ws_f(m, "0.17" as *u8), ws_sx(m, "f" as *u8, T_V2F, "x" as *u8, T_F32), T_F32)))
3651 let n2: i64 = ws_if(m, ws_topbot(m), ws_nb(m, "x" as *u8, "+" as *u8), ws_if(m, ws_cmp(m, "<" as *u8, ws_id(m, "fce" as *u8, T_I32), ws_i(m, "3" as *u8)), ws_nb(m, "z" as *u8, "+" as *u8), ws_nb(m, "x" as *u8, "+" as *u8)))
3652 ws_st(m, f, ws_ao(m, "x" as *u8, ">" as *u8, "0.83" as *u8, n2, ws_bin(m, "-" as *u8, ws_sx(m, "f" as *u8, T_V2F, "x" as *u8, T_F32), ws_f(m, "0.83" as *u8), T_F32)))
3653 let n3: i64 = ws_if(m, ws_topbot(m), ws_nb(m, "z" as *u8, "-" as *u8), ws_nb(m, "y" as *u8, "-" as *u8))
3654 ws_st(m, f, ws_ao(m, "y" as *u8, "<" as *u8, "0.17" as *u8, n3, ws_bin(m, "-" as *u8, ws_f(m, "0.17" as *u8), ws_sx(m, "f" as *u8, T_V2F, "y" as *u8, T_F32), T_F32)))
3655 let n4: i64 = ws_if(m, ws_topbot(m), ws_nb(m, "z" as *u8, "+" as *u8), ws_nb(m, "y" as *u8, "+" as *u8))
3656 ws_st(m, f, ws_ao(m, "y" as *u8, ">" as *u8, "0.83" as *u8, n4, ws_bin(m, "-" as *u8, ws_sx(m, "f" as *u8, T_V2F, "y" as *u8, T_F32), ws_f(m, "0.83" as *u8), T_F32)))
3657 // li*=1.0-min(ao,0.45);
3658 ws_st(m, f, ws_if(m, sir_not(m, ws_cont_surface(m)), ws_op(m, "li" as *u8, T_F32, "*" as *u8, ws_bin(m, "-" as *u8, ws_f(m, "1.0" as *u8), ws_c2(m, "min" as *u8, ws_id(m, "ao" as *u8, T_F32), ws_f(m, "0.45" as *u8), T_F32), T_F32)), 0)) // GE53: no cell-corner AO on the field
3659 // if(u.sun>0.5){let sh=march(hp+n*0.02,u.sund,1,60);if(sh.t>0.0){li*=0.55;}}
3660 let sh: i64 = sir_let(m, "sh" as *u8, hty, ws_c5(m, "march" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "hp" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "n" as *u8, T_V3F), ws_f(m, "0.02" as *u8), T_V3F), T_V3F), ws_id(m, "sund" as *u8, T_V3F), ws_i(m, "1" as *u8), ws_i(m, "60" as *u8), sir_ident(m, "r_surf" as *u8, T_I32), hty))
3661 // GE53: on the field a cell march cannot shadow the ground (terrain cells are air to it), so the surface march does
3662 let shs: i64 = ws_if(m, ws_and(m, ws_and(m, ws_cmp(m, "==" as *u8, sir_ident(m, "r_surf" as *u8, T_I32), ws_i(m, "1" as *u8)), ws_cmp(m, "<=" as *u8, ws_mem(m, ws_id(m, "sh" as *u8, hty), "t" as *u8, T_F32), ws_f(m, "0.0" as *u8))), ws_cmp(m, ">" as *u8, ws_c3(m, "smarch" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "hp" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "n" as *u8, T_V3F), ws_f(m, "0.02" as *u8), T_V3F), T_V3F), ws_id(m, "sund" as *u8, T_V3F), ws_i(m, "60" as *u8), T_F32), ws_f(m, "0.0" as *u8))), ws_shd(m), 0)
3663 ws_st(m, f, ws_if(m, ws_cmp(m, ">" as *u8, ws_id(m, "sun" as *u8, T_F32), ws_f(m, "0.5" as *u8)), ws_q3(m, sh, ws_if(m, ws_cmp(m, ">" as *u8, ws_mem(m, ws_id(m, "sh" as *u8, hty), "t" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_shd(m), 0), shs), 0))
3664 // let col=pal9(bb)*li; let fw9=vec3f(1.0)-exp(-vec3f(0.123,0.287,0.700)*t/168.0); return mix(col,sky(rd),fw9);
3665 ws_st(m, f, sir_let(m, "col" as *u8, T_V3F, ws_bin(m, "+" as *u8, ws_bin(m, "*" as *u8, ws_c1(m, "pal9" as *u8, ws_id(m, "bb" as *u8, T_U32), T_V3F), ws_id(m, "li" as *u8, T_F32), T_V3F), ws_v1(m, T_V3F, ws_id(m, "sp" as *u8, T_F32)), T_V3F))) // GR27: + the film specular
3666 let tau: i64 = ws_bin(m, "/" as *u8, ws_bin(m, "*" as *u8, sir_neg(m, ws_v3f(m, "0.123" as *u8, "0.287" as *u8, "0.700" as *u8), T_V3F), ws_id(m, "t" as *u8, T_F32), T_V3F), ws_f(m, "168.0" as *u8), T_V3F)
3667 ws_st(m, f, sir_let(m, "fw9" as *u8, T_V3F, ws_bin(m, "-" as *u8, ws_v1(m, T_V3F, ws_f(m, "1.0" as *u8)), ws_c1(m, "exp" as *u8, tau, T_V3F), T_V3F)))
3668 ws_st(m, f, ws_ret(m, ws_c3(m, "mix" as *u8, ws_id(m, "col" as *u8, T_V3F), ws_c1(m, "sky" as *u8, ws_id(m, "rd" as *u8, T_V3F), T_V3F), ws_id(m, "fw9" as *u8, T_V3F), T_V3F)))
3669 return f
3670}
3671
3672// the hotbar slot's block id: if(s2==0){bt=3;}else if(s2==1){bt=2;}...else{bt=13;}
3673func ws_bt(m: *i64, k: *u8, v: *u8, els: i64) -> i64 {
3674 return ws_if(m, ws_cmp(m, "==" as *u8, ws_id(m, "s2" as *u8, T_I32), ws_i(m, k)), ws_set(m, ws_id(m, "bt" as *u8, T_I32), ws_i(m, v)), els)
3675}
3676// px.<a> <op> (o.<a> + <e>) / px.<a> <op> (o.<a> + hbS - <e>)
3677func ws_pxo(m: *i64, a: *u8, op: *u8, e: i64) -> i64 { return ws_cmp(m, op, ws_sx(m, "px" as *u8, T_V2F, a, T_F32), ws_bin(m, "+" as *u8, ws_sx(m, "o" as *u8, T_V2F, a, T_F32), e, T_F32)) }
3678
3679// the fragment entry: fs -- the world pass per pixel, the hand text statement for statement (yflip carries the
3680// WebGPU top-left origin as a uniform so ONE source serves both doors)
3681// One hit policy for visible geometry and geometry seen through water.
3682// Continuous still-water intersection. Level is simulation data; no water voxel supplies geometry.
3683func ws_fn_water_hit(m: *i64, hty: i64) -> i64 {
3684 let f: i64 = sir_func(m, "water_hit" as *u8, hty)
3685 sir_param(m, f, "ro" as *u8, T_V3F); sir_param(m, f, "rd" as *u8, T_V3F)
3686 sir_param(m, f, "prior" as *u8, hty); sir_param(m, f, "mx" as *u8, T_I32)
3687 ws_st(m, f, ws_if(m, ws_cmp(m, "==" as *u8, ws_sx(m, "rd" as *u8, T_V3F, "y" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_ret(m, ws_id(m, "prior" as *u8, hty)), 0))
3688 ws_st(m, f, sir_let(m, "level" as *u8, T_F32, ws_bin(m, "/" as *u8, sir_cast(m, ws_id(m, "r_water_q8" as *u8, T_I32), T_F32), ws_f(m, "256.0" as *u8), T_F32)))
3689 ws_st(m, f, sir_let(m, "wt" as *u8, T_F32, ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_id(m, "level" as *u8, T_F32), ws_sx(m, "ro" as *u8, T_V3F, "y" as *u8, T_F32), T_F32), ws_sx(m, "rd" as *u8, T_V3F, "y" as *u8, T_F32), T_F32)))
3690 let outside: i64 = ws_or(m, ws_cmp(m, "<" as *u8, ws_id(m, "wt" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_cmp(m, ">" as *u8, ws_id(m, "wt" as *u8, T_F32), sir_cast(m, ws_id(m, "mx" as *u8, T_I32), T_F32)))
3691 ws_st(m, f, ws_if(m, outside, ws_ret(m, ws_id(m, "prior" as *u8, hty)), 0))
3692 let occluded: i64 = ws_and(m, ws_cmp(m, ">=" as *u8, ws_mem(m, ws_id(m, "prior" as *u8, hty), "t" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_cmp(m, ">=" as *u8, ws_id(m, "wt" as *u8, T_F32), ws_mem(m, ws_id(m, "prior" as *u8, hty), "t" as *u8, T_F32)))
3693 ws_st(m, f, ws_if(m, occluded, ws_ret(m, ws_id(m, "prior" as *u8, hty)), 0))
3694 ws_st(m, f, sir_let(m, "wp" as *u8, T_V3F, ws_bin(m, "+" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "rd" as *u8, T_V3F), ws_id(m, "wt" as *u8, T_F32), T_V3F), T_V3F)))
3695 ws_st(m, f, sir_let(m, "bed" as *u8, T_F32, ws_c1(m, "surf" as *u8, ws_sx(m, "wp" as *u8, T_V3F, "xz" as *u8, T_V2F), T_F32)))
3696 let dry: i64 = ws_or(m, ws_cmp(m, "<" as *u8, ws_id(m, "bed" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_cmp(m, ">=" as *u8, ws_id(m, "bed" as *u8, T_F32), ws_id(m, "level" as *u8, T_F32)))
3697 ws_st(m, f, ws_if(m, dry, ws_ret(m, ws_id(m, "prior" as *u8, hty)), 0))
3698 ws_st(m, f, sir_var(m, "result" as *u8, hty, ws_id(m, "prior" as *u8, hty)))
3699 ws_st(m, f, ws_set(m, ws_mem(m, ws_id(m, "result" as *u8, hty), "t" as *u8, T_F32), ws_id(m, "wt" as *u8, T_F32)))
3700 ws_st(m, f, ws_set(m, ws_mem(m, ws_id(m, "result" as *u8, hty), "b" as *u8, T_U32), ws_u(m, "4" as *u8)))
3701 ws_st(m, f, ws_set(m, ws_mem(m, ws_id(m, "result" as *u8, hty), "c" as *u8, T_V3I), ws_v1(m, T_V3I, ws_c1(m, "floor" as *u8, ws_id(m, "wp" as *u8, T_V3F), T_V3F))))
3702 ws_st(m, f, ws_set(m, ws_mem(m, ws_id(m, "result" as *u8, hty), "fce" as *u8, T_I32), ws_i(m, "3" as *u8)))
3703 ws_st(m, f, ws_if(m, ws_cmp(m, ">" as *u8, ws_sx(m, "rd" as *u8, T_V3F, "y" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_set(m, ws_mem(m, ws_id(m, "result" as *u8, hty), "fce" as *u8, T_I32), ws_i(m, "4" as *u8)), 0))
3704 ws_st(m, f, ws_ret(m, ws_id(m, "result" as *u8, hty)))
3705 return f
3706}
3707
3708func ws_fn_scene_hit(m: *i64, hty: i64) -> i64 {
3709 ws_fn_water_hit(m, hty)
3710 let f: i64 = sir_func(m, "scene_hit" as *u8, hty)
3711 sir_param(m, f, "ro" as *u8, T_V3F)
3712 sir_param(m, f, "rd" as *u8, T_V3F)
3713 sir_param(m, f, "skipw" as *u8, T_I32)
3714 sir_param(m, f, "mx" as *u8, T_I32)
3715 sir_param(m, f, "ts" as *u8, T_F32)
3716 ws_st(m, f, sir_var(m, "h" as *u8, hty, ws_c5(m, "march" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_id(m, "rd" as *u8, T_V3F), ws_c2(m, "max" as *u8, ws_id(m, "skipw" as *u8, T_I32), ws_id(m, "r_surf" as *u8, T_I32), T_I32), ws_id(m, "mx" as *u8, T_I32), sir_ident(m, "r_surf" as *u8, T_I32), hty)))
3717 // Both camera and transmitted-water rays resolve the same continuous ground.
3718 let hp9: i64 = sir_let(m, "hp9" as *u8, T_V3F, ws_bin(m, "+" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "rd" as *u8, T_V3F), ws_id(m, "ts" as *u8, T_F32), T_V3F), T_V3F))
3719 let cx9: i64 = sir_let(m, "cx9" as *u8, T_I32, sir_cast(m, ws_c1(m, "floor" as *u8, ws_sx(m, "hp9" as *u8, T_V3F, "x" as *u8, T_F32), T_F32), T_I32))
3720 let cz9: i64 = sir_let(m, "cz9" as *u8, T_I32, sir_cast(m, ws_c1(m, "floor" as *u8, ws_sx(m, "hp9" as *u8, T_V3F, "z" as *u8, T_F32), T_F32), T_I32))
3721 let cy9: i64 = sir_var(m, "cy9" as *u8, T_I32, ws_c2(m, "min" as *u8, sir_cast(m, ws_c1(m, "floor" as *u8, ws_sx(m, "hp9" as *u8, T_V3F, "y" as *u8, T_F32), T_F32), T_I32), ws_i(m, "47" as *u8), T_I32))
3722 // Search the actual column extent: water and air cannot supply the seabed material.
3723 let ground_class: i64 = ws_c1(m, "terrain" as *u8, ws_c1(m, "vx" as *u8, ws_vt3(m, T_V3I, ws_id(m, "cx9" as *u8, T_I32), ws_id(m, "cy9" as *u8, T_I32), ws_id(m, "cz9" as *u8, T_I32)), T_U32), T_I32)
3724 let stop_scan: i64 = ws_or(m, ws_cmp(m, "<=" as *u8, ws_id(m, "cy9" as *u8, T_I32), ws_i(m, "0" as *u8)), ws_cmp(m, "==" as *u8, ground_class, ws_i(m, "1" as *u8)))
3725 let scan: i64 = sir_loop(m, ws_q2(m, ws_if(m, stop_scan, sir_break(m), 0), ws_op(m, "cy9" as *u8, T_I32, "-" as *u8, ws_i(m, "1" as *u8))))
3726 let sett: i64 = ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "t" as *u8, T_F32), ws_id(m, "ts" as *u8, T_F32))
3727 let setf: i64 = ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "fce" as *u8, T_I32), ws_i(m, "3" as *u8))
3728 let setc: i64 = ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "c" as *u8, T_V3I), ws_vt3(m, T_V3I, ws_id(m, "cx9" as *u8, T_I32), ws_id(m, "cy9" as *u8, T_I32), ws_id(m, "cz9" as *u8, T_I32)))
3729 let setb: i64 = ws_set(m, ws_mem(m, ws_id(m, "h" as *u8, hty), "b" as *u8, T_U32), ws_c1(m, "vx" as *u8, ws_mem(m, ws_id(m, "h" as *u8, hty), "c" as *u8, T_V3I), T_U32))
3730 let nearer: i64 = ws_and(m, ws_cmp(m, ">" as *u8, ws_id(m, "ts" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_or(m, ws_cmp(m, "<" as *u8, ws_mem(m, ws_id(m, "h" as *u8, hty), "t" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_cmp(m, "<" as *u8, ws_id(m, "ts" as *u8, T_F32), ws_mem(m, ws_id(m, "h" as *u8, hty), "t" as *u8, T_F32))))
3731 let inner: i64 = ws_if(m, nearer, ws_q5(m, hp9, ws_q4(m, cx9, cz9, cy9, scan), sett, setf, ws_q2(m, setc, setb)), 0)
3732 ws_st(m, f, ws_if(m, ws_cmp(m, "==" as *u8, sir_ident(m, "r_surf" as *u8, T_I32), ws_i(m, "1" as *u8)), inner, 0))
3733 // Resolve water against the same field after ground/objects, preserving nearest-hit ordering.
3734 let water_call: i64 = ws_c4(m, "water_hit" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_id(m, "rd" as *u8, T_V3F), ws_id(m, "h" as *u8, hty), ws_id(m, "mx" as *u8, T_I32), hty)
3735 ws_st(m, f, ws_if(m, ws_and(m, ws_cmp(m, "==" as *u8, ws_id(m, "r_surf" as *u8, T_I32), ws_i(m, "1" as *u8)), ws_cmp(m, "==" as *u8, ws_id(m, "skipw" as *u8, T_I32), ws_i(m, "0" as *u8))), ws_set(m, ws_id(m, "h" as *u8, hty), water_call), 0))
3736 ws_st(m, f, ws_ret(m, ws_id(m, "h" as *u8, hty)))
3737 return f
3738}
3739
3740func ws_fn_fs(m: *i64, hty: i64) -> i64 {
3741 sir_fragout(m, "fc" as *u8, T_V4F, 0)
3742 let f: i64 = sir_func(m, "main" as *u8, T_VOID)
3743 sir_param_position(m, f, "pos" as *u8)
3744 // upk(); -- GE55: derive every float from the raw words FIRST; every statement below reads the private state
3745 ws_st(m, f, sir_expr(m, sir_call(m, "upk" as *u8, T_VOID)))
3746 // let px=vec2f(pos.x,mix(pos.y,u.res.y-pos.y,u.yflip));
3747 let flipped: i64 = ws_bin(m, "-" as *u8, ws_sx(m, "res" as *u8, T_V2F, "y" as *u8, T_F32), ws_sx(m, "pos" as *u8, T_V4F, "y" as *u8, T_F32), T_F32)
3748 ws_st(m, f, sir_let(m, "px" as *u8, T_V2F, ws_v2(m, ws_sx(m, "pos" as *u8, T_V4F, "x" as *u8, T_F32), ws_c3(m, "mix" as *u8, ws_sx(m, "pos" as *u8, T_V4F, "y" as *u8, T_F32), flipped, ws_id(m, "yflip" as *u8, T_F32), T_F32))))
3749 // let sc=(px-u.res*0.5)/(u.res.x*0.5);
3750 ws_st(m, f, sir_let(m, "sc" as *u8, T_V2F, ws_bin(m, "/" as *u8, ws_bin(m, "-" as *u8, ws_id(m, "px" as *u8, T_V2F), ws_bin(m, "*" as *u8, ws_id(m, "res" as *u8, T_V2F), ws_f(m, "0.5" as *u8), T_V2F), T_V2F), ws_bin(m, "*" as *u8, ws_sx(m, "res" as *u8, T_V2F, "x" as *u8, T_F32), ws_f(m, "0.5" as *u8), T_F32), T_V2F)))
3751 // let fw=vec3f(u.yp.x*u.yp.w,u.yp.z,u.yp.y*u.yp.w); let rt=vec3f(u.yp.y,0.0,-u.yp.x); let up=vec3f(-u.yp.x*u.yp.z,u.yp.w,-u.yp.y*u.yp.z);
3752 ws_st(m, f, sir_let(m, "fw" as *u8, T_V3F, ws_v3(m, ws_bin(m, "*" as *u8, ws_sx(m, "yp" as *u8, T_V4F, "x" as *u8, T_F32), ws_sx(m, "yp" as *u8, T_V4F, "w" as *u8, T_F32), T_F32), ws_sx(m, "yp" as *u8, T_V4F, "z" as *u8, T_F32), ws_bin(m, "*" as *u8, ws_sx(m, "yp" as *u8, T_V4F, "y" as *u8, T_F32), ws_sx(m, "yp" as *u8, T_V4F, "w" as *u8, T_F32), T_F32))))
3753 ws_st(m, f, sir_let(m, "rt" as *u8, T_V3F, ws_v3(m, ws_sx(m, "yp" as *u8, T_V4F, "y" as *u8, T_F32), ws_f(m, "0.0" as *u8), sir_neg(m, ws_sx(m, "yp" as *u8, T_V4F, "x" as *u8, T_F32), T_F32))))
3754 ws_st(m, f, sir_let(m, "up" as *u8, T_V3F, ws_v3(m, ws_bin(m, "*" as *u8, sir_neg(m, ws_sx(m, "yp" as *u8, T_V4F, "x" as *u8, T_F32), T_F32), ws_sx(m, "yp" as *u8, T_V4F, "z" as *u8, T_F32), T_F32), ws_sx(m, "yp" as *u8, T_V4F, "w" as *u8, T_F32), ws_bin(m, "*" as *u8, sir_neg(m, ws_sx(m, "yp" as *u8, T_V4F, "y" as *u8, T_F32), T_F32), ws_sx(m, "yp" as *u8, T_V4F, "z" as *u8, T_F32), T_F32))))
3755 // let rd=normalize(fw+rt*sc.x+up*sc.y); let ro=u.cam; let h=march(ro,rd,0,200);
3756 ws_st(m, f, sir_let(m, "rd" as *u8, T_V3F, ws_c1(m, "normalize" as *u8, ws_bin(m, "+" as *u8, ws_bin(m, "+" as *u8, ws_id(m, "fw" as *u8, T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "rt" as *u8, T_V3F), ws_sx(m, "sc" as *u8, T_V2F, "x" as *u8, T_F32), T_V3F), T_V3F), ws_bin(m, "*" as *u8, ws_id(m, "up" as *u8, T_V3F), ws_sx(m, "sc" as *u8, T_V2F, "y" as *u8, T_F32), T_V3F), T_V3F), T_V3F)))
3757 ws_st(m, f, sir_let(m, "ro" as *u8, T_V3F, ws_id(m, "cam" as *u8, T_V3F)))
3758 // Water and camera use this identical ray against the same immutable per-frame field.
3759 ws_st(m, f, sir_var(m, "ground_t" as *u8, T_F32, ws_f(m, "-1.0" as *u8)))
3760 ws_st(m, f, ws_if(m, ws_cmp(m, "==" as *u8, sir_ident(m, "r_surf" as *u8, T_I32), ws_i(m, "1" as *u8)), ws_set(m, ws_id(m, "ground_t" as *u8, T_F32), ws_c3(m, "smarch" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_id(m, "rd" as *u8, T_V3F), ws_i(m, "200" as *u8), T_F32)), 0))
3761 ws_st(m, f, sir_let(m, "h" as *u8, hty, ws_c5(m, "scene_hit" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_id(m, "rd" as *u8, T_V3F), ws_i(m, "0" as *u8), ws_i(m, "200" as *u8), ws_id(m, "ground_t" as *u8, T_F32), hty)))
3762 // var col:vec3f; if(h.t<0.0){col=sky(rd);}else{col=shade(...);if(h.b==4u){let h2=march(ro,rd,1,200);if(h2.t>0.0){col=col*0.58+shade(...h2...)*0.42;}}}
3763 ws_st(m, f, sir_var(m, "col" as *u8, T_V3F, 0))
3764 let sh1: i64 = ws_c6(m, "shade" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_id(m, "rd" as *u8, T_V3F), ws_mem(m, ws_id(m, "h" as *u8, hty), "t" as *u8, T_F32), ws_mem(m, ws_id(m, "h" as *u8, hty), "c" as *u8, T_V3I), ws_mem(m, ws_id(m, "h" as *u8, hty), "fce" as *u8, T_I32), ws_mem(m, ws_id(m, "h" as *u8, hty), "b" as *u8, T_U32), T_V3F)
3765 let sh2: i64 = ws_c6(m, "shade" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_id(m, "rd" as *u8, T_V3F), ws_mem(m, ws_id(m, "h2" as *u8, hty), "t" as *u8, T_F32), ws_mem(m, ws_id(m, "h2" as *u8, hty), "c" as *u8, T_V3I), ws_mem(m, ws_id(m, "h2" as *u8, hty), "fce" as *u8, T_I32), ws_mem(m, ws_id(m, "h2" as *u8, hty), "b" as *u8, T_U32), T_V3F)
3766 let blend: i64 = ws_set(m, ws_id(m, "col" as *u8, T_V3F), ws_bin(m, "+" as *u8, ws_bin(m, "*" as *u8, ws_id(m, "col" as *u8, T_V3F), ws_f(m, "0.58" as *u8), T_V3F), ws_bin(m, "*" as *u8, sh2, ws_f(m, "0.42" as *u8), T_V3F), T_V3F))
3767 let h2: i64 = sir_let(m, "h2" as *u8, hty, ws_c5(m, "scene_hit" as *u8, ws_id(m, "ro" as *u8, T_V3F), ws_id(m, "rd" as *u8, T_V3F), ws_i(m, "1" as *u8), ws_i(m, "200" as *u8), ws_id(m, "ground_t" as *u8, T_F32), hty))
3768 let water: i64 = ws_if(m, ws_cmp(m, "==" as *u8, ws_mem(m, ws_id(m, "h" as *u8, hty), "b" as *u8, T_U32), ws_u(m, "4" as *u8)), ws_q2(m, h2, ws_if(m, ws_cmp(m, ">" as *u8, ws_mem(m, ws_id(m, "h2" as *u8, hty), "t" as *u8, T_F32), ws_f(m, "0.0" as *u8)), blend, 0)), 0)
3769 ws_st(m, f, ws_if(m, ws_cmp(m, "<" as *u8, ws_mem(m, ws_id(m, "h" as *u8, hty), "t" as *u8, T_F32), ws_f(m, "0.0" as *u8)), ws_set(m, ws_id(m, "col" as *u8, T_V3F), ws_c1(m, "sky" as *u8, ws_id(m, "rd" as *u8, T_V3F), T_V3F)), ws_q2(m, ws_set(m, ws_id(m, "col" as *u8, T_V3F), sh1), water)))
3770 // let ctr=u.res*0.5;
3771 ws_st(m, f, sir_let(m, "ctr" as *u8, T_V2F, ws_bin(m, "*" as *u8, ws_id(m, "res" as *u8, T_V2F), ws_f(m, "0.5" as *u8), T_V2F)))
3772 // if(u.rain>0.5){let rr=h21(vec2f(floor((px.x+px.y*0.35)/2.0),floor((px.y+u.t*13.0)/26.0)));if(rr>0.945){col=mix(col,vec3f(0.75,0.8,0.92),0.45);}col*=0.93;}
3773 let rrx: i64 = ws_c1(m, "floor" as *u8, ws_bin(m, "/" as *u8, ws_bin(m, "+" as *u8, ws_sx(m, "px" as *u8, T_V2F, "x" as *u8, T_F32), ws_bin(m, "*" as *u8, ws_sx(m, "px" as *u8, T_V2F, "y" as *u8, T_F32), ws_f(m, "0.35" as *u8), T_F32), T_F32), ws_f(m, "2.0" as *u8), T_F32), T_F32)
3774 let rry: i64 = ws_c1(m, "floor" as *u8, ws_bin(m, "/" as *u8, ws_bin(m, "+" as *u8, ws_sx(m, "px" as *u8, T_V2F, "y" as *u8, T_F32), ws_bin(m, "*" as *u8, ws_id(m, "t" as *u8, T_F32), ws_f(m, "13.0" as *u8), T_F32), T_F32), ws_f(m, "26.0" as *u8), T_F32), T_F32)
3775 let rr: i64 = sir_let(m, "rr" as *u8, T_F32, ws_c1(m, "h21" as *u8, ws_v2(m, rrx, rry), T_F32))
3776 let drops: i64 = ws_if(m, ws_cmp(m, ">" as *u8, ws_id(m, "rr" as *u8, T_F32), ws_f(m, "0.945" as *u8)), ws_set(m, ws_id(m, "col" as *u8, T_V3F), ws_c3(m, "mix" as *u8, ws_id(m, "col" as *u8, T_V3F), ws_v3f(m, "0.75" as *u8, "0.8" as *u8, "0.92" as *u8), ws_f(m, "0.45" as *u8), T_V3F)), 0)
3777 ws_st(m, f, ws_if(m, ws_cmp(m, ">" as *u8, ws_id(m, "rain" as *u8, T_F32), ws_f(m, "0.5" as *u8)), ws_q3(m, rr, drops, ws_op(m, "col" as *u8, T_V3F, "*" as *u8, ws_f(m, "0.93" as *