fix(shader): keep absent BVH children out of sorted box hits #27

Closed
github-bot wants to merge 1 commit from github-bot/gh-27 into main AGit
Owner

@⁠mathcx on GitHub · 2026-11-25 15:48 UTC · original
fix/bvh-absent-child-sort → main · +36 −2 · 3 files · 1 commits · closed without merging

1. Problema / Contexto

Nas instruções de interseção de ray tracing do console (image_bvh_intersect_ray e image_bvh64_intersect_ray), cada nó interno de caixas delimitadoras (tipos 4 / box16 e 5 / box32) armazena até 4 ponteiros de filhos (children[0..4]) acompanhados de 4 AABBs. Quando um nó interno possui menos de 4 filhos ativos, os slots ausentes recebem a sentinela NONE (0xffff_ffff), mas os floats correspondentes da caixa nem sempre são preenchidos com NaN pelo construtor da estrutura — podendo conter zeros ([0.0; 6]) ou limites finitos residuais.

Anteriormente, tanto a referência em CPU (bvh::boxes) quanto a emissão inline em DXIL (Lower::bvh_boxes) descartavam apenas caixas com b[0].is_nan(). Se o raio interceptasse uma caixa finita associada a um slot children[n] == NONE, o identificador continuava sendo NONE, mas distances[n] recebia a distância finita enter em vez de permanecer em +inf (f32::INFINITY). Quando a ordenação por distância estava habilitada (sort = true), a rede de ordenação classificava esse NONE à frente de filhos válidos atingidos a distâncias maiores (enter_ausente < enter_valido), deslocando ponteiros válidos para depois de 0xffff_ffff. Como os loops de travessia de BVH nos shaders interrompem o empilhamento ao encontrar NONE (ou consomem os slots assumindo que todos os hits válidos precedem NONE), hits geométricos reais eram descartados prematuramente durante a travessia (relacionado à Issue #4).

2. Alterações Técnicas

  • crates/victory-shader/src/bvh.rs:
    • Atualizada bvh::boxes para exigir children[n] != NONE antes de registrar um hit e atribuir distances[n] = enter, mantendo distances[n] = f32::INFINITY em qualquer slot de filho ausente independentemente das coordenadas armazenadas na AABB.
    • Adicionado o teste unitário a_missing_child_with_a_finite_box_does_not_sort_ahead_of_hits cobrindo nós box32 (kind = 5) e box16 (kind = 4), com e sem ordenação (sort = true e sort = false), quando filhos NONE possuem caixas finitas ([0.0; 6] e UNIT) mais próximas da origem do raio do que filhos válidos.
  • crates/victory-shader/src/emit/intersect.rs:
    • Atualizado Lower::bvh_boxes para emitir icmp ne (pred::NE) entre children[n] e none (0xffff_ffff) e combinar o predicado present ao bit hit via Bin::And, garantindo que distances[n] selecione infinity para filhos ausentes antes da rede de ordenação em DXIL.
  • crates/victory-shader/src/emit/intersect_tests.rs:
    • Adicionados nós box32 e box16 com filhos NONE em caixas finitas posicionadas à frente de filhos válidos na cena de validação GPU/WARP (scene), exercitando os caminhos de 32 bits e 64 bits (com e sem BOX_SORT) no adaptador de hardware e no WARP contra a referência corrigida.

3. Validação e Testes

  • cargo clippy -p victory-shader --all-targets -- -D warnings: aprovado sem avisos.
  • cargo test -p victory-shader: todos os testes unitários e de integração em GPU/WARP aprovados (228 passed, 0 failed, 3 ignored).
  • cargo xtask policy: aprovado (asset policy e limites de tamanho de arquivo respeitados).
  • cargo run --release -p victory -- translate --validate --pipelines: 26.599 containers processados, 25.745 / 25.758 shaders DXIL emitidos, 25.674 validados via dxil.dll e 25.346 PSOs aceitos na GPU local sem regressões.

1. Problem / Context

In the console ray-tracing intersection instructions (image_bvh_intersect_ray and image_bvh64_intersect_ray), each internal bounding-box node (pointer kinds 4 / box16 and 5 / box32) holds up to 4 child pointers (children[0..4]) alongside 4 AABBs. When an internal node has fewer than 4 active children, unused child slots carry the NONE sentinel (0xffff_ffff), while their box coordinates are not guaranteed to be filled with NaN — they may hold zeroed ([0.0; 6]) or leftover finite bounds.

Previously, both the CPU reference (bvh::boxes) and the inline DXIL emitter (Lower::bvh_boxes) only rejected disabled boxes via b[0].is_nan(). Whenever a ray intersected the finite bounds of an absent child slot (children[n] == NONE), ids[n] stayed NONE, but distances[n] was overwritten with enter instead of remaining +inf (f32::INFINITY). With distance sorting enabled (sort = true), the 4-element sorting network ordered that NONE slot ahead of valid child hits at larger entry distances (enter_absent < enter_valid), pushing valid child pointers behind 0xffff_ffff. Because shader BVH traversal loops stop pushing children upon encountering NONE (or assume valid hits precede NONE slots), valid geometry intersections behind closer unused slots were silently dropped (related to Issue #4).

2. Technical Changes

  • crates/victory-shader/src/bvh.rs:
    • Updated bvh::boxes to require children[n] != NONE before recording a slab hit, keeping distances[n] = f32::INFINITY for absent child slots regardless of their box coordinates.
    • Added unit test a_missing_child_with_a_finite_box_does_not_sort_ahead_of_hits covering both box32 (kind = 5) and box16 (kind = 4), sorted and unsorted (sort = true and sort = false), when NONE slots have closer finite bounds ([0.0; 6] and UNIT) than valid children.
  • crates/victory-shader/src/emit/intersect.rs:
    • Updated Lower::bvh_boxes to emit icmp ne (pred::NE) comparing children[n] against none (0xffff_ffff) and combine present into hit via Bin::And, ensuring distances[n] selects infinity for absent children prior to the DXIL sorting network.
  • crates/victory-shader/src/emit/intersect_tests.rs:
    • Added box32 and box16 test nodes with closer finite-box NONE children ahead of valid children in scene(), exercising 32-bit and 64-bit pointer modes (both with and without BOX_SORT) on the hardware D3D12 adapter and WARP against the fixed reference.

3. Verification & Testing

  • cargo clippy -p victory-shader --all-targets -- -D warnings: passed with zero warnings.
  • cargo test -p victory-shader: all unit and GPU/WARP integration tests passed (228 passed, 0 failed, 3 ignored).
  • cargo xtask policy: passed (asset policy and file size checks clean).
  • cargo run --release -p victory -- translate --validate --pipelines: 26,599 containers processed, 25,745 / 25,758 DXIL shaders emitted, 25,674 validated through dxil.dll, and 25,346 host PSOs created with zero regressions.
**@⁠mathcx** on GitHub · 2026-11-25 15:48 UTC · [original](https://github.com/uiliannn/VItoriaBr/pull/27) `fix/bvh-absent-child-sort` → `main` · +36 −2 · 3 files · 1 commits · closed without merging ### 1. Problema / Contexto Nas instruções de interseção de ray tracing do console (`image_bvh_intersect_ray` e `image_bvh64_intersect_ray`), cada nó interno de caixas delimitadoras (tipos `4` / `box16` e `5` / `box32`) armazena até 4 ponteiros de filhos (`children[0..4]`) acompanhados de 4 AABBs. Quando um nó interno possui menos de 4 filhos ativos, os slots ausentes recebem a sentinela `NONE` (`0xffff_ffff`), mas os floats correspondentes da caixa nem sempre são preenchidos com `NaN` pelo construtor da estrutura — podendo conter zeros (`[0.0; 6]`) ou limites finitos residuais. Anteriormente, tanto a referência em CPU (`bvh::boxes`) quanto a emissão inline em DXIL (`Lower::bvh_boxes`) descartavam apenas caixas com `b[0].is_nan()`. Se o raio interceptasse uma caixa finita associada a um slot `children[n] == NONE`, o identificador continuava sendo `NONE`, mas `distances[n]` recebia a distância finita `enter` em vez de permanecer em `+inf` (`f32::INFINITY`). Quando a ordenação por distância estava habilitada (`sort = true`), a rede de ordenação classificava esse `NONE` à frente de filhos válidos atingidos a distâncias maiores (`enter_ausente < enter_valido`), deslocando ponteiros válidos para depois de `0xffff_ffff`. Como os loops de travessia de BVH nos shaders interrompem o empilhamento ao encontrar `NONE` (ou consomem os slots assumindo que todos os hits válidos precedem `NONE`), hits geométricos reais eram descartados prematuramente durante a travessia (relacionado à Issue #4). ### 2. Alterações Técnicas - **`crates/victory-shader/src/bvh.rs`**: - Atualizada `bvh::boxes` para exigir `children[n] != NONE` antes de registrar um hit e atribuir `distances[n] = enter`, mantendo `distances[n] = f32::INFINITY` em qualquer slot de filho ausente independentemente das coordenadas armazenadas na AABB. - Adicionado o teste unitário `a_missing_child_with_a_finite_box_does_not_sort_ahead_of_hits` cobrindo nós `box32` (`kind = 5`) e `box16` (`kind = 4`), com e sem ordenação (`sort = true` e `sort = false`), quando filhos `NONE` possuem caixas finitas (`[0.0; 6]` e `UNIT`) mais próximas da origem do raio do que filhos válidos. - **`crates/victory-shader/src/emit/intersect.rs`**: - Atualizado `Lower::bvh_boxes` para emitir `icmp ne` (`pred::NE`) entre `children[n]` e `none` (`0xffff_ffff`) e combinar o predicado `present` ao bit `hit` via `Bin::And`, garantindo que `distances[n]` selecione `infinity` para filhos ausentes antes da rede de ordenação em DXIL. - **`crates/victory-shader/src/emit/intersect_tests.rs`**: - Adicionados nós `box32` e `box16` com filhos `NONE` em caixas finitas posicionadas à frente de filhos válidos na cena de validação GPU/WARP (`scene`), exercitando os caminhos de 32 bits e 64 bits (com e sem `BOX_SORT`) no adaptador de hardware e no WARP contra a referência corrigida. ### 3. Validação e Testes - `cargo clippy -p victory-shader --all-targets -- -D warnings`: aprovado sem avisos. - `cargo test -p victory-shader`: todos os testes unitários e de integração em GPU/WARP aprovados (`228 passed, 0 failed, 3 ignored`). - `cargo xtask policy`: aprovado (`asset policy` e limites de tamanho de arquivo respeitados). - `cargo run --release -p victory -- translate --validate --pipelines`: `26.599` containers processados, `25.745 / 25.758` shaders DXIL emitidos, `25.674` validados via `dxil.dll` e `25.346` PSOs aceitos na GPU local sem regressões. --- ### 1. Problem / Context In the console ray-tracing intersection instructions (`image_bvh_intersect_ray` and `image_bvh64_intersect_ray`), each internal bounding-box node (pointer kinds `4` / `box16` and `5` / `box32`) holds up to 4 child pointers (`children[0..4]`) alongside 4 AABBs. When an internal node has fewer than 4 active children, unused child slots carry the `NONE` sentinel (`0xffff_ffff`), while their box coordinates are not guaranteed to be filled with `NaN` — they may hold zeroed (`[0.0; 6]`) or leftover finite bounds. Previously, both the CPU reference (`bvh::boxes`) and the inline DXIL emitter (`Lower::bvh_boxes`) only rejected disabled boxes via `b[0].is_nan()`. Whenever a ray intersected the finite bounds of an absent child slot (`children[n] == NONE`), `ids[n]` stayed `NONE`, but `distances[n]` was overwritten with `enter` instead of remaining `+inf` (`f32::INFINITY`). With distance sorting enabled (`sort = true`), the 4-element sorting network ordered that `NONE` slot ahead of valid child hits at larger entry distances (`enter_absent < enter_valid`), pushing valid child pointers behind `0xffff_ffff`. Because shader BVH traversal loops stop pushing children upon encountering `NONE` (or assume valid hits precede `NONE` slots), valid geometry intersections behind closer unused slots were silently dropped (related to Issue #4). ### 2. Technical Changes - **`crates/victory-shader/src/bvh.rs`**: - Updated `bvh::boxes` to require `children[n] != NONE` before recording a slab hit, keeping `distances[n] = f32::INFINITY` for absent child slots regardless of their box coordinates. - Added unit test `a_missing_child_with_a_finite_box_does_not_sort_ahead_of_hits` covering both `box32` (`kind = 5`) and `box16` (`kind = 4`), sorted and unsorted (`sort = true` and `sort = false`), when `NONE` slots have closer finite bounds (`[0.0; 6]` and `UNIT`) than valid children. - **`crates/victory-shader/src/emit/intersect.rs`**: - Updated `Lower::bvh_boxes` to emit `icmp ne` (`pred::NE`) comparing `children[n]` against `none` (`0xffff_ffff`) and combine `present` into `hit` via `Bin::And`, ensuring `distances[n]` selects `infinity` for absent children prior to the DXIL sorting network. - **`crates/victory-shader/src/emit/intersect_tests.rs`**: - Added `box32` and `box16` test nodes with closer finite-box `NONE` children ahead of valid children in `scene()`, exercising 32-bit and 64-bit pointer modes (both with and without `BOX_SORT`) on the hardware D3D12 adapter and WARP against the fixed reference. ### 3. Verification & Testing - `cargo clippy -p victory-shader --all-targets -- -D warnings`: passed with zero warnings. - `cargo test -p victory-shader`: all unit and GPU/WARP integration tests passed (`228 passed, 0 failed, 3 ignored`). - `cargo xtask policy`: passed (`asset policy` and file size checks clean). - `cargo run --release -p victory -- translate --validate --pipelines`: `26,599` containers processed, `25,745 / 25,758` DXIL shaders emitted, `25,674` validated through `dxil.dll`, and `25,346` host PSOs created with zero regressions.
Require child pointers in bvh::boxes and Lower::bvh_boxes to differ from NONE before recording slab entry distances, so unused child slots with finite or zeroed box coordinates keep infinite entry distance and never sort ahead of valid child hits.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 03:41:29 +00:00
github-bot closed this pull request 2026-11-27 01:05:42 +00:00

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.