Adding documentation for agents
This commit is contained in:
@@ -0,0 +1,418 @@
|
||||
# Pipeline and producers
|
||||
|
||||
This document follows data from a GPU-emitted request to a resident cache page,
|
||||
and describes the producer interface. It also marks which producer code is
|
||||
durable and which is throwaway.
|
||||
|
||||
> **Temporary code:** `src/main.rs` and `src/producers.rs` are a playground/test
|
||||
> harness built alongside the cache. They contain hardcoded parameters and
|
||||
> blocking workarounds. Do not treat them as stable architecture, public API, or
|
||||
> examples of intended concurrency. The `ChunkedProducer` shape and the
|
||||
> insertion/data-flow contract are the durable parts; the concrete generators
|
||||
> (including `SdfGenerator` and `TerrainGenerator`) are throwaway fixtures and
|
||||
> should be replaced.
|
||||
|
||||
---
|
||||
|
||||
## 1. End-to-end sequence
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant R as Render pass (GPU)
|
||||
participant C as Voxel cache (GPU)
|
||||
participant T as Structure table (GPU)
|
||||
participant H as Host (main.rs)
|
||||
participant I as Insertion passes (GPU)
|
||||
|
||||
R->>C: descend pages, mark usage, increment missing-child counters
|
||||
R->>T: trace chunk cells, increment missing-root counters
|
||||
Note over C,T: end of draw
|
||||
C->>C: top-K + gather + descending radix sort
|
||||
T->>T: top-K + gather + descending radix sort
|
||||
C-->>H: request buffer (structure_id, node_id, child)
|
||||
T-->>H: table request buffer (slot, 0, 0)
|
||||
H->>H: produce one node per request (parallel)
|
||||
H->>I: upload CacheInsertionData (info, locations, attributes, count)
|
||||
I->>C: recycle pages, write pages, invalidate stale pointers
|
||||
I->>C: write new child pointers
|
||||
I->>T: point table slots at new root pages
|
||||
Note over R: next frame sees the new pages
|
||||
```
|
||||
|
||||
Timing detail: in the current driver the render pass runs **before** request
|
||||
gathering and insertion in the same `render()` call. Therefore pages produced in
|
||||
response to frame N are first visible in frame N+1.
|
||||
|
||||
---
|
||||
|
||||
## 2. The request/response contract
|
||||
|
||||
### 2.1 Request
|
||||
|
||||
```rust
|
||||
struct RequestInformation {
|
||||
structure_id: u32, // which structure (chunk/table slot)
|
||||
node_id: u32, // locator of the *parent* node
|
||||
children_index: u32, // which child is missing
|
||||
}
|
||||
|
||||
struct RequestMeta {
|
||||
page_index: u32, // parent page (internal) or sentinel (external)
|
||||
children_index: u32,
|
||||
depth: u32,
|
||||
}
|
||||
```
|
||||
|
||||
- The producer only sees `RequestInformation`. `RequestMeta` stays on the GPU
|
||||
and is used by `write_pointers` / table insertion.
|
||||
- For external requests from a structure table: `node_id = 0`,
|
||||
`children_index = 0`, and `structure_id` is the table slot.
|
||||
- Requests are sorted by demand (highest counter first) and capped at
|
||||
`max_requests`.
|
||||
|
||||
### 2.2 Response
|
||||
|
||||
One `CacheInsertionData` entry per request, in the **same order**:
|
||||
|
||||
```rust
|
||||
struct InsertionInformation<N> {
|
||||
children: [ChildInformation; 64], // bit 31 subdividable, bit 30 occupied
|
||||
}
|
||||
|
||||
struct LocationPage {
|
||||
structure_id: u32,
|
||||
node_id: u32,
|
||||
}
|
||||
```
|
||||
|
||||
Plus one attribute payload per page (color and normal in the demo).
|
||||
|
||||
The cache fills `destination_indices[i]` with the page that received slot `i`,
|
||||
or `0xFFFFFFFF` if it could not insert. The producer does not need to read it in
|
||||
the current demo, but a real implementation should, because the cache can silently
|
||||
drop pages when it is full or when candidate pages were used in the previous
|
||||
frame.
|
||||
|
||||
### 2.3 Why order matters
|
||||
|
||||
`write_pointers.wgsl` and `fixed_table/insertion.wgsl` assume:
|
||||
|
||||
```text
|
||||
request_informations[i] <-> insertion_data[i] <-> destination_indices[i]
|
||||
```
|
||||
|
||||
If a producer reorders, filters, or duplicates requests, pages will be linked to
|
||||
the wrong parents. There is no validation.
|
||||
|
||||
---
|
||||
|
||||
## 3. The durable producer shape
|
||||
|
||||
`src/producers.rs` defines:
|
||||
|
||||
```rust
|
||||
pub trait ChunkedProducer<const N: usize>
|
||||
where [(); N * N * N]:,
|
||||
{
|
||||
fn produce_node(
|
||||
&self,
|
||||
depth: usize,
|
||||
nx: usize,
|
||||
ny: usize,
|
||||
nz: usize,
|
||||
chunk_pos: (usize, usize, usize),
|
||||
) -> ProducedChunk<N>;
|
||||
}
|
||||
|
||||
pub struct ProducedChunk<const N: usize> {
|
||||
pub children: [ChildInformation; N * N * N],
|
||||
pub colors: [u32; N * N * N], // packed RGBA
|
||||
pub normals: [[f32; 3]; N * N * N],
|
||||
}
|
||||
```
|
||||
|
||||
Interpretation:
|
||||
|
||||
- `depth` is the node depth inside a chunk (root = 0).
|
||||
- `(nx, ny, nz)` is the node's position in the depth-specific coordinate space
|
||||
(`0 .. N^depth`), i.e. the node's grid coordinate at that depth, not a voxel
|
||||
coordinate.
|
||||
- `chunk_pos` is the chunk's grid position in the world.
|
||||
- The producer must fill one entry per child. Each child says whether it can be
|
||||
subdivided further and whether it is occupied, and supplies its attribute
|
||||
words.
|
||||
- A leaf is `subdividable = false`. A node that should be refined later is
|
||||
`subdividable = true`. Occupancy controls hit testing and coarse skipping.
|
||||
|
||||
This shape is independent of the cache layout only up to the attribute buffers:
|
||||
the demo's `colors` / `normals` arrays correspond exactly to the two configured
|
||||
attributes. A general design should produce `word_count` words per attribute per
|
||||
child instead of hardcoding color/normal.
|
||||
|
||||
### 3.1 Fulfilling a request
|
||||
|
||||
The demo's `fullfill_request` (`src/main.rs`) does:
|
||||
|
||||
1. Map `structure_id` to an absolute chunk coordinate using
|
||||
`ToroidalStructureTable::get_request_position`.
|
||||
2. Add the playground offset `+5000` to x and z and take `abs()` of y.
|
||||
3. If `node_id == 0`, produce the chunk root at depth 0 and emit the root
|
||||
locator.
|
||||
4. Otherwise:
|
||||
- decode the parent `NTreeNodeLocator<4>` from `node_id`;
|
||||
- decode `children_index` into `(child_x, child_y, child_z)` with x fastest;
|
||||
- compute the child locator;
|
||||
- produce the child node at `parent_depth + 1` with the child's node
|
||||
coordinates;
|
||||
- emit the child locator as the new `LocationPage.node_id`.
|
||||
|
||||
The `+5000` offset and the hardcoded `<4>` are playground artifacts. They assume
|
||||
chunk dimensions of 20×20×20 and a 4-ary tree.
|
||||
|
||||
### 3.2 Locators
|
||||
|
||||
Two locator implementations exist:
|
||||
|
||||
- **`NTreeNodeLocator<N>`** (`src/sparse_tree.rs`) — used by the demo. A packed
|
||||
`usize`; supports `root`, `from_usize`, `depth`, `child`, `node_location`,
|
||||
`as_usize`, `parent`, `children`.
|
||||
- **`TreeLocator<N>`** (`src/production/tree_locator.rs`) — the unwired
|
||||
production subsystem's version. Three base-N accumulators (`x`, `y`, `z`) with
|
||||
a leading `1` digit; root is `(1,1,1)`; `depth = ilog_N(x)`; `parent` divides
|
||||
each coordinate by `N`; `child` multiplies by `N` and adds the child digit.
|
||||
`StructureLocator` is a flat interleaved form.
|
||||
|
||||
Both encode "path from root" and can be converted to/from application-level
|
||||
coordinates. Whichever is used, it must round-trip through the 32-bit
|
||||
`node_id`.
|
||||
|
||||
---
|
||||
|
||||
## 4. The current driver, step by step
|
||||
|
||||
Relevant code: `State::render` and `fullfill_request` in `src/main.rs`.
|
||||
|
||||
1. **Render** writes G-buffers and request counters.
|
||||
2. **Gather** encodes both request pipelines (cache + table) into the same
|
||||
command buffer, then submits and presents.
|
||||
3. **Download** starts two asynchronous reads per request buffer (count and
|
||||
informations).
|
||||
4. **Busy-wait**:
|
||||
|
||||
```rust
|
||||
loop {
|
||||
if finished.load(Relaxed) >= 2 { break; }
|
||||
let _ = self.device.poll(wgpu::wgt::PollType::Poll);
|
||||
}
|
||||
```
|
||||
|
||||
`finished` counts completed callbacks (one cache, one table), so completion
|
||||
does not require all four reads to land independently.
|
||||
5. **Produce** on the CPU with rayon: one `fullfill_request` per request. The
|
||||
results are copied into dense vectors, then uploaded with
|
||||
`queue.write_buffer` into:
|
||||
- `insertion_information_buffer()`
|
||||
- `location_pages_buffer()`
|
||||
- `attributes_buffers()[0]` (color)
|
||||
- `attributes_buffers()[1]` (normal)
|
||||
- `page_count_buffer()`
|
||||
6. **Insert** encodes:
|
||||
|
||||
```rust
|
||||
cache.insert(&device, &mut encoder, &mut [
|
||||
&mut VoxelCacheInsertion::ExternalRequest(
|
||||
&structure_table_cache_insertion, &mut *structure_table),
|
||||
&mut VoxelCacheInsertion::InternalRequest(
|
||||
&cache_insertion, &request_buffer),
|
||||
]);
|
||||
structure_table.insert(&device, &mut encoder,
|
||||
&structure_table_cache_insertion, &structure_table_request_buffer);
|
||||
```
|
||||
|
||||
One eviction preparation is shared by both batches. It orders pages by
|
||||
timestamp first (least recently used first) and depth second (deepest first
|
||||
among equal timestamps).
|
||||
7. **Submit** and read back the insertion profile.
|
||||
|
||||
Because the external insertion is processed first, newly produced chunk roots
|
||||
are resident before the internal child insertion links them. The table insertion
|
||||
then points the slot at the root page.
|
||||
|
||||
### 4.1 Problems this creates
|
||||
|
||||
- The render thread blocks on the CPU producer; there is no overlap between
|
||||
production and rendering.
|
||||
- Request buffers are read back every frame even when empty.
|
||||
- `finished >= 2` is a coarse synchronization; it assumes exactly two buffers
|
||||
and no retries.
|
||||
- The producer runs on the same thread that owns the event loop, so a slow
|
||||
producer directly reduces frame rate.
|
||||
- No backpressure or prioritisation beyond the top-K request cap.
|
||||
|
||||
These are acceptable for a playground and are the first things to redesign for a
|
||||
real engine.
|
||||
|
||||
---
|
||||
|
||||
## 5. Generators in `src/producers.rs`
|
||||
|
||||
All are fixtures. They exist to exercise the cache and should not be treated as
|
||||
stable.
|
||||
|
||||
| Generator | Status | What it does |
|
||||
|---|---|---|
|
||||
| `SdfGenerator<N>` | Used by the demo | Signed-distance field from FBM simplex noise plus procedural "trees"; derives normal by finite differences; packs color from normal. |
|
||||
| `TerrainGenerator<N>` | Supported but commented out | Loads a TIFF heightmap and a JPEG/PNG colormap; builds low-resolution mips; produces nodes from min/max height spans. |
|
||||
| `BallGenerator<N>` | Unused | Implements the older `Producer<N>` trait (not `ChunkedProducer`), draws a sphere; useful as a minimal example. |
|
||||
|
||||
`TerrainGenerator` is the closest thing to a realistic producer, but it is
|
||||
single-threaded at load time and uses hardcoded mip factors (8×). It also has
|
||||
branching logic based on `depth <= 2`.
|
||||
|
||||
`SdfGenerator` demonstrates the attribute math:
|
||||
|
||||
- `alpha = 0` above the surface, `1` below;
|
||||
- `subdivided = depth < chunk_power - 1` near the surface;
|
||||
- normal from four SDF samples;
|
||||
- color derived from the normal with a small random tint.
|
||||
|
||||
---
|
||||
|
||||
## 6. The unwired production subsystem
|
||||
|
||||
These files are **not declared as modules in `main.rs`**, so they are not part of
|
||||
the running binary. They represent earlier or planned designs. Treat them as
|
||||
reference material, not current architecture.
|
||||
|
||||
### 6.1 `src/production.rs`
|
||||
|
||||
Defines a more ambitious interface:
|
||||
|
||||
```rust
|
||||
pub struct ProducerId(pub u32);
|
||||
pub struct StructureId(pub u32);
|
||||
pub struct StructureLocator(pub u32);
|
||||
|
||||
pub trait VoxelAttributes<const N: usize> {
|
||||
fn attribute_count() -> usize;
|
||||
fn attribute(&self, attribute_index: usize) -> &[u32];
|
||||
}
|
||||
|
||||
pub trait VoxelProducer<const N: usize> {
|
||||
type Output: VoxelAttributes<N>;
|
||||
fn produce(
|
||||
&self,
|
||||
producer_id: ProducerId,
|
||||
id: StructureId,
|
||||
locator: StructureLocator,
|
||||
) -> (InsertionInformation<N>, [Self::Output; N * N * N]);
|
||||
}
|
||||
```
|
||||
|
||||
Differences from the demo interface:
|
||||
|
||||
- A node carries a `producer_id`, so one cache can mix multiple producers.
|
||||
- Attributes are abstracted behind `VoxelAttributes`, avoiding hardcoded
|
||||
color/normal buffers.
|
||||
- The producer receives a `StructureLocator` rather than depth + coordinates,
|
||||
pushing locator arithmetic into the producer.
|
||||
|
||||
### 6.2 `src/production/host_production.rs`
|
||||
|
||||
`HostRequestHandler<N, P: VoxelProducer<N>>` owns a rayon `ThreadPool` and a
|
||||
producer, and is intended to fulfil requests on the CPU. Note that its
|
||||
`fullfill` method is a stub: it downloads the request buffer with an empty
|
||||
callback. `produce_requests` does the real parallel mapping.
|
||||
|
||||
### 6.3 `src/production/tree_locator.rs`
|
||||
|
||||
`TreeLocator<N>` (described in §3.2) plus `From<StructureLocator>` /
|
||||
`Into<StructureLocator>` conversions.
|
||||
|
||||
### 6.4 `src/production/request_queue.rs`
|
||||
|
||||
Untracked WIP. Do not depend on it.
|
||||
|
||||
### 6.5 `src/host_production.rs`
|
||||
|
||||
An older, simpler trait:
|
||||
|
||||
```rust
|
||||
pub trait ChunkVoxelProducer {
|
||||
fn produce_voxel(&mut self, depth, chunk_position, voxel_position);
|
||||
}
|
||||
```
|
||||
|
||||
It has no return value and no cache insertion types; it predates the current
|
||||
request/response pipeline.
|
||||
|
||||
### 6.6 `src/tree.rs`
|
||||
|
||||
A CPU `NTree<N>` prototype backed by a `HashMap<NTreeLocator<N>, NTreeNode<N>>`,
|
||||
with `constant`, `get`, `set`, array conversion, and explicit-structure export.
|
||||
Useful for understanding the tree, not used by the renderer.
|
||||
|
||||
### 6.7 `src/gi_pipeline.rs` + `sparse_set.rs`
|
||||
|
||||
Compiles (declared in `main.rs`) but `VoxelGiPipeline` is never instantiated. It
|
||||
adds `DontTouch` attributes for a leaf list and radiance, and a `GpuSparseSet`
|
||||
for resident leaves. It is a sketch of a future GI integration, not working
|
||||
code.
|
||||
|
||||
---
|
||||
|
||||
## 7. Adding a producer
|
||||
|
||||
Minimum viable path with the current demo interface:
|
||||
|
||||
1. Implement `ChunkedProducer<N>`:
|
||||
|
||||
```rust
|
||||
impl ChunkedProducer<4> for MyProducer {
|
||||
fn produce_node(&self, depth, nx, ny, nz, chunk_pos) -> ProducedChunk<4> { ... }
|
||||
}
|
||||
```
|
||||
|
||||
2. For each child, compute:
|
||||
- `subdividable`: can this child be refined?
|
||||
- `occupied`: can it produce a hit?
|
||||
- attribute words in the cache layout order.
|
||||
3. Wire the producer into `fullfill_request` (or replace that function).
|
||||
Request → coordinates:
|
||||
- external: `node_id == 0`, produce chunk root;
|
||||
- internal: decode `node_id`, decode `children_index`, produce child at
|
||||
`depth + 1`.
|
||||
4. Emit a `LocationPage` matching the produced node. For internal requests,
|
||||
it must be `parent.child(child_x, child_y, child_z)`.
|
||||
5. Ensure the output order matches the request order and the batch size matches
|
||||
`page_count_buffer`.
|
||||
6. Update the size passed to `CacheInsertionData::new` if the maximum batch can
|
||||
exceed `max_requests`.
|
||||
|
||||
A production-ready producer should additionally:
|
||||
|
||||
- use the unwired `VoxelProducer`/`VoxelAttributes` abstraction (or an
|
||||
equivalent) so attributes are not hardcoded;
|
||||
- run on a worker thread and stream results without blocking the render loop;
|
||||
- handle `destination_indices == 0xFFFFFFFF` by retrying the request;
|
||||
- implement filtering/mip generation for coarser levels so LOD stops do not
|
||||
alias;
|
||||
- support multiple structures/producers per cache via IDs.
|
||||
|
||||
---
|
||||
|
||||
## 8. Known issues
|
||||
|
||||
| Symptom | Location | Impact | Confidence |
|
||||
|---|---|---|---|
|
||||
| The host request path busy-waits on `device.poll`; production blocks the render thread. | `src/main.rs` (`loop { ... poll ... }` in `render`) | No overlap, frame stalls, no streaming. | High |
|
||||
| `fullfill_request` hardcodes `NTreeNodeLocator<4>`, x/y/z child unpacking with `4` and `16`, and a `+5000` chunk offset. | `src/main.rs:1762-1838` | Not generic; offsets only make sense for the demo terrain. | High |
|
||||
| `page_count_buffer` is set to `request_informations.len()`, which may exceed `CacheInsertionData`'s `max_page_count` (1024) if `max_requests` is raised without resizing. | `src/main.rs` (write of `page_count_buffer`), `CacheInsertionData::new` | Buffer overrun / truncated production. | High |
|
||||
| If `destination_indices[i] == 0xFFFFFFFF`, the producer is not told; the cache will re-request the node later. | `insertion.wgsl`, host callback | Wasted work and repeated requests; no metric for dropped pages. | High |
|
||||
| The external table insertion consumes the same eviction list as the cache insertion; if it inserts fewer roots than requested, the table has missing entries with no host-visible signal. | `VoxelCache::insert`, `fixed_table/insertion.wgsl` | Silent holes in the world. | Medium |
|
||||
| `TerrainGenerator` uses hardcoded mip factor 8 and `depth <= 2` special cases. | `src/producers.rs:207-263,330` | Not robust to different chunk resolutions. | High |
|
||||
| `BallGenerator` implements the old `Producer` trait, not `ChunkedProducer`. | `src/producers.rs:31-116` | Copying it as a template will not work with the current driver. | High |
|
||||
| The `production/` subsystem is not compiled into the binary but looks authoritative. | `src/production.rs`, `src/production/*` | Agents may "fix" dead code or assume it is live. | High |
|
||||
| `src/production/request_queue.rs` is untracked WIP. | same | Brittle; may change or disappear. | High |
|
||||
| The demo uploads all attribute payloads with `bytemuck::cast_slice` of Rust arrays, so layout mismatches (padding, alignment) are not checked. | `src/main.rs` upload section | Silent corruption if the Rust struct layout diverges from the WGSL/Slang layout. | Medium |
|
||||
| The `+5000` offset plus `chunk_y.abs()` means negative chunk coordinates fold onto positive ones. | `src/main.rs:1785-1789` | Duplicate chunks / visual artifacts at negative y. | Medium |
|
||||
Reference in New Issue
Block a user