@driftengine/texture 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.md +106 -0
  4. package/dist/decodeCpu.d.ts +59 -0
  5. package/dist/decodeCpu.js +234 -0
  6. package/dist/decodeGraph.d.ts +105 -0
  7. package/dist/decodeGraph.js +180 -0
  8. package/dist/half.d.ts +24 -0
  9. package/dist/half.js +86 -0
  10. package/dist/index.d.ts +66 -0
  11. package/dist/index.js +55 -0
  12. package/dist/inference.d.ts +53 -0
  13. package/dist/inference.js +243 -0
  14. package/dist/materialArray.d.ts +38 -0
  15. package/dist/materialArray.js +40 -0
  16. package/dist/mipNdf.d.ts +29 -0
  17. package/dist/mipNdf.js +53 -0
  18. package/dist/overlay/journal.d.ts +78 -0
  19. package/dist/overlay/journal.js +171 -0
  20. package/dist/overlay/sparse.d.ts +68 -0
  21. package/dist/overlay/sparse.js +212 -0
  22. package/dist/progressive.d.ts +30 -0
  23. package/dist/progressive.js +56 -0
  24. package/dist/residency/pageCache.d.ts +103 -0
  25. package/dist/residency/pageCache.js +184 -0
  26. package/dist/residency/predict.d.ts +55 -0
  27. package/dist/residency/predict.js +51 -0
  28. package/dist/residency/predictor.d.ts +16 -0
  29. package/dist/residency/predictor.js +44 -0
  30. package/dist/residency/queue.d.ts +26 -0
  31. package/dist/residency/queue.js +52 -0
  32. package/dist/residency/stream.d.ts +66 -0
  33. package/dist/residency/stream.js +142 -0
  34. package/dist/residency/table.d.ts +36 -0
  35. package/dist/residency/table.js +72 -0
  36. package/dist/residency/viewTiles.d.ts +108 -0
  37. package/dist/residency/viewTiles.js +419 -0
  38. package/dist/semantics.d.ts +52 -0
  39. package/dist/semantics.js +76 -0
  40. package/dist/tensor/architecture.d.ts +53 -0
  41. package/dist/tensor/architecture.js +96 -0
  42. package/dist/tensor/attention.d.ts +5 -0
  43. package/dist/tensor/attention.js +62 -0
  44. package/dist/tensor/denseOperators.d.ts +2 -0
  45. package/dist/tensor/denseOperators.js +136 -0
  46. package/dist/tensor/graph.d.ts +83 -0
  47. package/dist/tensor/graph.js +175 -0
  48. package/dist/tensor/linear.d.ts +49 -0
  49. package/dist/tensor/linear.js +136 -0
  50. package/dist/tensor/operatorKit.d.ts +27 -0
  51. package/dist/tensor/operatorKit.js +45 -0
  52. package/dist/tensor/operators.d.ts +3 -0
  53. package/dist/tensor/operators.js +24 -0
  54. package/dist/tensor/resize.d.ts +6 -0
  55. package/dist/tensor/resize.js +107 -0
  56. package/dist/tensor/reuse.d.ts +33 -0
  57. package/dist/tensor/reuse.js +59 -0
  58. package/dist/tensor/shapeOperators.d.ts +3 -0
  59. package/dist/tensor/shapeOperators.js +173 -0
  60. package/dist/tensor/spatial.d.ts +34 -0
  61. package/dist/tensor/spatial.js +131 -0
  62. package/dist/tensor/spatialOperators.d.ts +2 -0
  63. package/dist/tensor/spatialOperators.js +138 -0
  64. package/dist/tileHash.d.ts +29 -0
  65. package/dist/tileHash.js +50 -0
  66. package/dist/timeNodes.d.ts +26 -0
  67. package/dist/timeNodes.js +48 -0
  68. package/package.json +59 -0
  69. package/src/decodeCpu.ts +308 -0
  70. package/src/decodeGraph.ts +214 -0
  71. package/src/half.ts +86 -0
  72. package/src/index.ts +175 -0
  73. package/src/inference.ts +278 -0
  74. package/src/materialArray.ts +67 -0
  75. package/src/mipNdf.ts +63 -0
  76. package/src/overlay/journal.ts +218 -0
  77. package/src/overlay/sparse.ts +275 -0
  78. package/src/progressive.ts +60 -0
  79. package/src/residency/pageCache.ts +233 -0
  80. package/src/residency/predict.ts +74 -0
  81. package/src/residency/predictor.ts +62 -0
  82. package/src/residency/queue.ts +78 -0
  83. package/src/residency/stream.ts +194 -0
  84. package/src/residency/table.ts +89 -0
  85. package/src/residency/viewTiles.ts +553 -0
  86. package/src/semantics.ts +114 -0
  87. package/src/tensor/architecture.ts +140 -0
  88. package/src/tensor/attention.ts +75 -0
  89. package/src/tensor/denseOperators.ts +153 -0
  90. package/src/tensor/graph.ts +244 -0
  91. package/src/tensor/linear.ts +153 -0
  92. package/src/tensor/operatorKit.ts +76 -0
  93. package/src/tensor/operators.ts +28 -0
  94. package/src/tensor/resize.ts +140 -0
  95. package/src/tensor/shapeOperators.ts +173 -0
  96. package/src/tensor/spatial.ts +178 -0
  97. package/src/tensor/spatialOperators.ts +182 -0
  98. package/src/tileHash.ts +60 -0
  99. package/src/timeNodes.ts +60 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Drift Technologies
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,29 @@
1
+ DriftEngine
2
+ Copyright 2026 Drift Technologies
3
+
4
+ This product includes software developed at Drift Technologies
5
+ (https://github.com/drftrun/driftengine).
6
+
7
+ Licensed under the Apache License, Version 2.0. Section 4(d) of that licence
8
+ requires this NOTICE to be reproduced in any derivative work you distribute,
9
+ in the source, the documentation, or a display generated by the work.
10
+
11
+ Models run by DriftCapture
12
+ --------------------------
13
+ DriftCapture runs the models below. Their weights are not in this repository
14
+ and are not distributed with it: tools/capture-weights/ fetches each at the
15
+ revision its manifest pins, verifies it, and converts it, and a game that
16
+ ships one ships it under that model's own licence. Each model's definition in
17
+ this engine is written from its project's published code.
18
+
19
+ - Depth Anything 3 Small and Depth Anything 3 Base. Apache License 2.0.
20
+ Copyright (c) 2025 ByteDance Ltd. and/or its affiliates.
21
+ - Depth Anything V2 Small. Apache License 2.0. The University of Hong Kong
22
+ and TikTok; converted to the Transformers layout by The HuggingFace Team.
23
+ - MobileSAM. Apache License 2.0. Its image encoder is TinyViT, Copyright (c)
24
+ 2022 Microsoft; its prompt encoder and mask decoder are Segment Anything's,
25
+ Copyright (c) Meta Platforms, Inc. and affiliates.
26
+ - SAM 2.1 tiny. Apache License 2.0. Copyright (c) Meta Platforms, Inc. and
27
+ affiliates.
28
+ - OWLv2 base patch16. Apache License 2.0. Copyright 2023 Google AI and The
29
+ HuggingFace Team.
package/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # `@driftengine/texture`
2
+
3
+ A texture as a compiled, sampled field rather than an image.
4
+
5
+ **Cost: 2,305 bytes gzipped, standalone** — 2,226 of code and 79 for the licence banner every
6
+ package carries. Measured by `scripts/size-gate.test.mjs`, which fails if
7
+ it drifts more than 3%. The package imports no renderer, so this is the whole of what a consumer
8
+ pays — there is no core in the number.
9
+
10
+ **The interpreter that runs a decode graph on the device is not in this package.** It lives in
11
+ `@driftengine/core`'s GPU-driven pass as `DECODE_WGSL`, and `scripts/gpu-parity.mjs` checks it
12
+ against `decodeCpu` on a real texture array and real samplers, over all nine operations and all four
13
+ address modes.
14
+
15
+ ```ts
16
+ import { createDecodeGraph, addDecodeNode, DECODE_OP, decodeCpu } from '@driftengine/texture';
17
+
18
+ const graph = createDecodeGraph(4);
19
+ addDecodeNode(graph, DECODE_OP.SAMPLE_LATENT, 0, 0, 0);
20
+ addDecodeNode(graph, DECODE_OP.REMAP_CHANNEL, 0, (0 << 4) | 0, 1); // albedo-srgb, component 0
21
+ graph.result = 1;
22
+
23
+ decodeCpu(graph, resources, u, v, simulationTime, out, registers);
24
+ ```
25
+
26
+ ## What makes it different from an image
27
+
28
+ **One object per material, not per channel.** Albedo, normal, roughness and the rest are strongly
29
+ correlated, and every engine in the world compresses them apart — which throws that correlation
30
+ away before it can pay for anything.
31
+
32
+ **Time is an argument, not a clock.** `decodeCpu` takes `t` from the caller, which is the
33
+ simulation's clock. So an animated texture is byte-exact under replay. Every other engine's
34
+ animated texture reads a wall clock, which means replaying one simulation twice shows different
35
+ texels — invisible in a game, fatal in a rollback session, a deterministic capture, or an
36
+ automated visual comparison.
37
+
38
+ **The decoder is data, not a shader permutation.** A decode graph is four words per node in a
39
+ uniform buffer, walked by one shader. `docs/ARCHITECTURE.md` records what the other choice costs
40
+ with the number: a fifth permutation flag took the generated WGSL corpus from 914 KB to 1,906 KB
41
+ and cost 196,910 gzipped bytes on every consumer, including those who never enabled the feature.
42
+ Per material rather than per feature, that does not survive contact with a real project.
43
+
44
+ **Conventions are declared, so nothing downstream guesses.** A channel says it is a Y-down
45
+ tangent-space normal, or an sRGB albedo, or gloss — and comes back Y-up, linear, and as roughness.
46
+ The exact sRGB curve, not the 2.2 approximation: the midpoint linearises to 0.2140, and the
47
+ approximation's 0.2176 is a colour shift nobody attributes to the right cause for weeks.
48
+
49
+ **Normal mips get rougher instead of sparkling.** Averaging four normals and renormalising discards
50
+ how much they disagreed, and that disagreement _is_ roughness at the smaller scale. Preserving it
51
+ needs the mip chain to write roughness as well as normals, which needs both in one object.
52
+
53
+ **Materials bind as array slices.** WebGPU has no bindless access, so a thousand materials as six
54
+ thousand textures is unreachable; a thousand latent slices in a handful of arrays, indexed from a
55
+ storage buffer, is ordinary. Identical content shares a layer.
56
+
57
+ **Two address conventions, because two kinds of data need them.** A lattice puts `u = 0` on the
58
+ first texel's centre, which is what a height field sampled at its own vertices wants; a centre mode
59
+ puts it on the first texel's edge, which is what every GPU sampler does and what a surface tiled
60
+ across a mesh wants. `ADDRESS_MODE` names all four, and `decodeCpu` takes a mip level as well, so
61
+ the device's trilinear sample has a reference at every level.
62
+
63
+ ## What a predicted view needs
64
+
65
+ **Prediction knows where the camera will be; `tilesForView` says what it will sample there.** For
66
+ each instance whose bounds are inside the predicted view, the level comes from its nearest point —
67
+ where the surface is finest on screen — and the tiles from its texture coordinates' span at that
68
+ level. It names the finer level too within an eighth of a level of a boundary, and every coarser
69
+ level, because a sampler with a fine tile missing falls back to a coarse one. An estimate is
70
+ enough: a tile it names that the frame does not sample is a wasted fetch.
71
+
72
+ ```ts
73
+ import {
74
+ TILE_RESIDENT,
75
+ enqueue,
76
+ latentTileGrid,
77
+ runPrediction,
78
+ tileState,
79
+ tilesForView,
80
+ } from '@driftengine/texture';
81
+
82
+ const grid = latentTileGrid(latent, 16, graph.addressMode); // content-addressed, level by level
83
+ runPrediction(
84
+ simulation,
85
+ {
86
+ needs: (view, out, budget) => tilesForView(view, projection, scene, out, budget),
87
+ resident: (hash) => tileState(table, hash) === TILE_RESIDENT,
88
+ request: (hash, priority) => enqueue(queue, hash, priority),
89
+ },
90
+ 6,
91
+ step,
92
+ 512,
93
+ );
94
+ ```
95
+
96
+ The answer is ordered by the screen each tile covers, and at any budget it is a prefix of the answer
97
+ with none; `runPrediction` keeps that order inside each predicted frame when it hands tiles to the
98
+ queue. `popIn.test.ts` flies a corridor of real latents through it: nothing is late after the three
99
+ frames no fetch could have reached.
100
+
101
+ ## What is not here
102
+
103
+ **The offline joint encoder is not in this package, by design**: it is a baker, and it lives in
104
+ `@driftengine/assets` as `encodeMaterial`, so a game that only decodes never carries it. The `NNET`
105
+ weights chunk is `@driftengine/drft`'s, and the half-precision network reference is here beside the
106
+ single-precision one, as `evalNetworkHalf`.
@@ -0,0 +1,59 @@
1
+ import type { DecodeGraph } from './decodeGraph.ts';
2
+ import type { NetworkShape } from './inference.ts';
3
+ import type { ChannelSemantic } from './semantics.ts';
4
+ /** One level of a latent's chain. Components are the image's own. */
5
+ export interface LatentLevel {
6
+ data: Float32Array;
7
+ width: number;
8
+ height: number;
9
+ }
10
+ export interface LatentImage {
11
+ data: Float32Array;
12
+ width: number;
13
+ height: number;
14
+ /** Components per texel, up to four. */
15
+ channels: number;
16
+ /**
17
+ * Levels 1 onward, each half the one before. `mips[k]` is level `k + 1`.
18
+ *
19
+ * Absent is a single level, which is every image written before 2026-09-17 — and at `lod` 0 the
20
+ * chain is never read, so those callers decode exactly what they did.
21
+ */
22
+ mips?: readonly LatentLevel[];
23
+ }
24
+ export interface DecodeResources {
25
+ latents: readonly LatentImage[];
26
+ blocks: readonly LatentImage[];
27
+ networks: readonly {
28
+ shape: NetworkShape;
29
+ weights: Float32Array;
30
+ }[];
31
+ /**
32
+ * Four floats per slot, for `CONSTANT`.
33
+ *
34
+ * Optional, so every caller written before Wave 4C still type-checks and still runs — a graph
35
+ * with no constant in it never reads this.
36
+ */
37
+ constants?: Float32Array;
38
+ }
39
+ /**
40
+ * The order `REMAP_CHANNEL` packs a semantic in, which is `CHANNEL_SEMANTICS` and not a copy of it.
41
+ *
42
+ * **It was a copy until 2026-09-20**, written out again here — the same eleven names in the same
43
+ * order in two files, with nothing holding them together. That is a list a file's channels are
44
+ * *numbered* by: the two drifting apart means every material written by one and read by the other
45
+ * decodes its channels as something else, and a normal map read as roughness inverts every
46
+ * highlight in a scene. The name is kept because `terrainTexture.ts`, the WGSL interpreter's test
47
+ * and this file all say `REMAP_SEMANTICS` when they mean the packing.
48
+ */
49
+ export declare const REMAP_SEMANTICS: readonly ChannelSemantic[];
50
+ /**
51
+ * Run the graph at one texture coordinate and one time, writing four components into `out`.
52
+ *
53
+ * `registers` is the caller's, `MAX_REGISTERS * 4` floats, reused so this allocates nothing.
54
+ * `lod` picks the level a latent is sampled at; 0, and anything that is not a positive number, is
55
+ * level 0.
56
+ */
57
+ export declare function decodeCpu(graph: DecodeGraph, resources: DecodeResources, u: number, v: number, t: number, out: Float32Array, registers: Float32Array, lod?: number): void;
58
+ /** A registers array of the right size, for a caller that holds one across calls. */
59
+ export declare function createDecodeRegisters(): Float32Array;
@@ -0,0 +1,234 @@
1
+ /**
2
+ * The reference decoder: what the shader has to agree with.
3
+ *
4
+ * **A second implementation is not duplication here, it is the specification.** A shader cannot be
5
+ * unit-tested at speed, and a decoder that is subtly wrong is a picture that is subtly wrong
6
+ * everywhere — the hardest defect in this whole design to notice and the easiest to ship. So the
7
+ * arithmetic is written once in TypeScript, where it can be asserted in milliseconds, and the
8
+ * device copy is checked against it over generated input.
9
+ *
10
+ * The repository already takes this position: `splats` authors its shader once and generates the
11
+ * second backend from it. This is the same discipline where the second copy cannot be generated.
12
+ *
13
+ * **Deterministic by construction.** No clock, no random, and `t` is the caller's. Decoding the
14
+ * same inputs twice is bit-identical, which is what the fingerprint test rests on.
15
+ */
16
+ import { ADDRESS_MODE, DECODE_OP, MAX_REGISTERS, nodeA, nodeB, nodeOp, nodeOut, } from './decodeGraph.js';
17
+ import { evalNetwork } from './inference.js';
18
+ import { CHANNEL_SEMANTICS, normaliseSample } from './semantics.js';
19
+ import { flipbookFrame } from './timeNodes.js';
20
+ /**
21
+ * The order `REMAP_CHANNEL` packs a semantic in, which is `CHANNEL_SEMANTICS` and not a copy of it.
22
+ *
23
+ * **It was a copy until 2026-09-20**, written out again here — the same eleven names in the same
24
+ * order in two files, with nothing holding them together. That is a list a file's channels are
25
+ * *numbered* by: the two drifting apart means every material written by one and read by the other
26
+ * decodes its channels as something else, and a normal map read as roughness inverts every
27
+ * highlight in a scene. The name is kept because `terrainTexture.ts`, the WGSL interpreter's test
28
+ * and this file all say `REMAP_SEMANTICS` when they mean the packing.
29
+ */
30
+ export const REMAP_SEMANTICS = CHANNEL_SEMANTICS;
31
+ /** Lattice addressing only: where a coordinate lands before it is scaled across the lattice. */
32
+ function address(value, mode) {
33
+ if (mode === ADDRESS_MODE.LATTICE_WRAP)
34
+ return value - Math.floor(value);
35
+ return Math.min(1, Math.max(0, value));
36
+ }
37
+ /** A texel index inside the image: wrapped for centre wrap, clamped for everything else. */
38
+ function texelIndex(value, size, mode) {
39
+ if (mode === ADDRESS_MODE.CENTRE_WRAP)
40
+ return ((value % size) + size) % size;
41
+ return Math.min(size - 1, Math.max(0, value));
42
+ }
43
+ /**
44
+ * Bilinear on one level, with the graph's address mode applied first.
45
+ *
46
+ * **For the lattice modes this is byte-identical to what it replaced**: `su` is inside
47
+ * `[0, width - 1]`, so clamping `floor(su)` and `floor(su) + 1` is exactly the `min` it was.
48
+ */
49
+ function sampleLevel(level, channels, u, v, mode, out) {
50
+ const centre = mode === ADDRESS_MODE.CENTRE_CLAMP || mode === ADDRESS_MODE.CENTRE_WRAP;
51
+ const su = centre ? u * level.width - 0.5 : address(u, mode) * (level.width - 1);
52
+ const sv = centre ? v * level.height - 0.5 : address(v, mode) * (level.height - 1);
53
+ const baseX = Math.floor(su);
54
+ const baseY = Math.floor(sv);
55
+ const fx = su - baseX;
56
+ const fy = sv - baseY;
57
+ const x0 = texelIndex(baseX, level.width, mode);
58
+ const x1 = texelIndex(baseX + 1, level.width, mode);
59
+ const y0 = texelIndex(baseY, level.height, mode);
60
+ const y1 = texelIndex(baseY + 1, level.height, mode);
61
+ for (let c = 0; c < 4; c += 1) {
62
+ if (c >= channels) {
63
+ out[c] = c === 3 ? 1 : 0;
64
+ continue;
65
+ }
66
+ const at = (x, y) => level.data[(y * level.width + x) * channels + c];
67
+ const top = at(x0, y0) * (1 - fx) + at(x1, y0) * fx;
68
+ const bottom = at(x0, y1) * (1 - fx) + at(x1, y1) * fx;
69
+ out[c] = top * (1 - fy) + bottom * fy;
70
+ }
71
+ }
72
+ const SECOND = new Float32Array(4);
73
+ /**
74
+ * Trilinear: bilinear on the two levels either side of `lod`, mixed by its fraction.
75
+ *
76
+ * **At a whole level only that level is read**, so an integer `lod` — and 0 above all — costs and
77
+ * returns exactly one bilinear sample.
78
+ */
79
+ function sampleImage(image, u, v, mode, lod, out) {
80
+ const top = image.mips?.length ?? 0;
81
+ const level = lod > 0 ? Math.min(lod, top) : 0;
82
+ const lower = Math.floor(level);
83
+ const blend = level - lower;
84
+ const levelOf = (k) => k === 0 ? image : image.mips?.[k - 1];
85
+ sampleLevel(levelOf(lower), image.channels, u, v, mode, out);
86
+ if (blend === 0)
87
+ return;
88
+ sampleLevel(levelOf(Math.min(lower + 1, top)), image.channels, u, v, mode, SECOND);
89
+ for (let c = 0; c < 4; c += 1) {
90
+ out[c] = out[c] * (1 - blend) + SECOND[c] * blend;
91
+ }
92
+ }
93
+ /** A deterministic integer hash, so the procedural node reproduces across runs and platforms. */
94
+ function hash2(x, y, seed) {
95
+ let h = Math.imul(x | 0, 0x27d4eb2d) ^ Math.imul(y | 0, 0x165667b1) ^ Math.imul(seed | 0, 0x9e3779b1);
96
+ h = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d);
97
+ h = Math.imul(h ^ (h >>> 12), 0x297a2d39);
98
+ return ((h ^ (h >>> 15)) >>> 0) / 0xffffffff;
99
+ }
100
+ function valueNoise(u, v, seed) {
101
+ const x0 = Math.floor(u);
102
+ const y0 = Math.floor(v);
103
+ const fx = u - x0;
104
+ const fy = v - y0;
105
+ const sx = fx * fx * (3 - 2 * fx);
106
+ const sy = fy * fy * (3 - 2 * fy);
107
+ const a = hash2(x0, y0, seed);
108
+ const b = hash2(x0 + 1, y0, seed);
109
+ const c = hash2(x0, y0 + 1, seed);
110
+ const d = hash2(x0 + 1, y0 + 1, seed);
111
+ return (a * (1 - sx) + b * sx) * (1 - sy) + (c * (1 - sx) + d * sx) * sy;
112
+ }
113
+ const SCRATCH = new Float32Array(256);
114
+ const SAMPLE = new Float32Array(4);
115
+ const NET_IN = new Float32Array(64);
116
+ const NET_OUT = new Float32Array(64);
117
+ /**
118
+ * Run the graph at one texture coordinate and one time, writing four components into `out`.
119
+ *
120
+ * `registers` is the caller's, `MAX_REGISTERS * 4` floats, reused so this allocates nothing.
121
+ * `lod` picks the level a latent is sampled at; 0, and anything that is not a positive number, is
122
+ * level 0.
123
+ */
124
+ export function decodeCpu(graph, resources, u, v, t, out, registers, lod = 0) {
125
+ for (let i = 0; i < graph.count; i += 1) {
126
+ const op = nodeOp(graph, i);
127
+ const a = nodeA(graph, i);
128
+ const b = nodeB(graph, i);
129
+ const dst = nodeOut(graph, i) * 4;
130
+ switch (op) {
131
+ case DECODE_OP.CONSTANT: {
132
+ const constants = resources.constants;
133
+ const base = a * 4;
134
+ for (let c = 0; c < 4; c += 1)
135
+ registers[dst + c] = constants?.[base + c] ?? 0;
136
+ break;
137
+ }
138
+ case DECODE_OP.SAMPLE_LATENT: {
139
+ const image = resources.latents[a];
140
+ if (image === undefined)
141
+ break;
142
+ sampleImage(image, u, v, graph.addressMode, lod, SAMPLE);
143
+ registers.set(SAMPLE, dst);
144
+ break;
145
+ }
146
+ case DECODE_OP.SAMPLE_BLOCK: {
147
+ const image = resources.blocks[a];
148
+ if (image === undefined)
149
+ break;
150
+ sampleImage(image, u, v, graph.addressMode, lod, SAMPLE);
151
+ registers.set(SAMPLE, dst);
152
+ break;
153
+ }
154
+ case DECODE_OP.PROCEDURAL_FBM: {
155
+ let sum = 0;
156
+ let amplitude = 0.5;
157
+ let frequency = 1;
158
+ const octaves = Math.max(1, b);
159
+ for (let o = 0; o < octaves; o += 1) {
160
+ sum += valueNoise(u * frequency * 8, v * frequency * 8, a) * amplitude;
161
+ amplitude *= 0.5;
162
+ frequency *= 2;
163
+ }
164
+ registers[dst] = sum;
165
+ registers[dst + 1] = sum;
166
+ registers[dst + 2] = sum;
167
+ registers[dst + 3] = 1;
168
+ break;
169
+ }
170
+ case DECODE_OP.FLIPBOOK_INDEX: {
171
+ registers[dst] = flipbookFrame(t, a, b, true);
172
+ registers[dst + 1] = 0;
173
+ registers[dst + 2] = 0;
174
+ registers[dst + 3] = 1;
175
+ break;
176
+ }
177
+ case DECODE_OP.LATENT_LERP: {
178
+ const mix = t - Math.floor(t);
179
+ const src0 = a * 4;
180
+ const src1 = b * 4;
181
+ for (let c = 0; c < 4; c += 1) {
182
+ registers[dst + c] =
183
+ registers[src0 + c] * (1 - mix) + registers[src1 + c] * mix;
184
+ }
185
+ break;
186
+ }
187
+ case DECODE_OP.REMAP_CHANNEL: {
188
+ const src = a * 4;
189
+ for (let c = 0; c < 4; c += 1)
190
+ registers[dst + c] = registers[src + c];
191
+ const semantic = REMAP_SEMANTICS[b >>> 4] ?? 'mask-linear';
192
+ const component = b & 0xf;
193
+ SAMPLE.set(registers.subarray(dst, dst + 4));
194
+ normaliseSample(SAMPLE, { semantic, component }, registers[src + component]);
195
+ registers.set(SAMPLE, dst);
196
+ break;
197
+ }
198
+ case DECODE_OP.COMPOSITE: {
199
+ const src0 = a * 4;
200
+ const src1 = b * 4;
201
+ const alpha = registers[src0 + 3];
202
+ for (let c = 0; c < 3; c += 1) {
203
+ registers[dst + c] =
204
+ registers[src0 + c] * alpha + registers[src1 + c] * (1 - alpha);
205
+ }
206
+ registers[dst + 3] = alpha + registers[src1 + 3] * (1 - alpha);
207
+ break;
208
+ }
209
+ case DECODE_OP.EVAL_NETWORK: {
210
+ const net = resources.networks[b];
211
+ if (net === undefined)
212
+ break;
213
+ const src = a * 4;
214
+ for (let c = 0; c < net.shape.inputs; c += 1) {
215
+ NET_IN[c] = c < 4 ? registers[src + c] : 0;
216
+ }
217
+ evalNetwork(net.shape, net.weights, NET_IN, NET_OUT, SCRATCH);
218
+ for (let c = 0; c < 4; c += 1) {
219
+ registers[dst + c] = c < net.shape.outputs ? NET_OUT[c] : 0;
220
+ }
221
+ break;
222
+ }
223
+ default:
224
+ break;
225
+ }
226
+ }
227
+ const result = graph.result * 4;
228
+ for (let c = 0; c < 4; c += 1)
229
+ out[c] = registers[result + c];
230
+ }
231
+ /** A registers array of the right size, for a caller that holds one across calls. */
232
+ export function createDecodeRegisters() {
233
+ return new Float32Array(MAX_REGISTERS * 4);
234
+ }