Skip to main content

isomesh_gpu/
lib.rs

1//! GPU isosurface extraction for [`isomesh`], on raw `wgpu`.
2//!
3//! ```no_run
4//! use isomesh_gpu::{MarchingCubesGpu, headless};
5//!
6//! // Any wgpu device will do -- Bevy's via `RenderDevice::wgpu_device()`, a CAD
7//! // tool's own, or this one. The API never names an engine type.
8//! let gpu = headless::Gpu::new()?;
9//! let mut mc = MarchingCubesGpu::new(gpu.device(), gpu.queue())?;
10//! # let _ = &mut mc;
11//! # Ok::<(), isomesh_gpu::Error>(())
12//! ```
13//!
14//! # The one rule this crate exists to keep
15//!
16//! **Every public entry point takes `&wgpu::Device`, `&wgpu::Queue` or
17//! `&mut wgpu::CommandEncoder`, and never an engine type.** A Bevy consumer
18//! reaches the raw device through `RenderDevice::wgpu_device()` and hands it in;
19//! a CAD tool passes its own; a test passes one from [`headless`]. There is no
20//! second entry point that takes a `RenderDevice`, because that would make the
21//! engine a dependency of the algorithm rather than a caller of it.
22//!
23//! That is also why [`headless`] exists in the library and not only in tests: a
24//! CAD tool with no renderer at all still needs a device, and a GPU path that
25//! can only be reached through a game engine has already leaked.
26//!
27//! # The wgpu version is a hard pin, and getting it wrong does not fail loudly
28//!
29//! `wgpu 29.0.3` exactly, matching Bevy 0.19. Cargo resolves two wgpu majors
30//! **side by side with no resolution error** — verified in
31//! `docs/research/2026-08-11-meshing-crate-architecture.md` §6, where adding
32//! `wgpu 30` alongside `bevy 0.19` locks 317 packages containing both. The
33//! failure arrives much later and reads as a type error about `TextureFormat`
34//! not matching itself.
35//!
36//! | `isomesh-gpu` | `wgpu` | `bevy` |
37//! |---|---|---|
38//! | 0.0.x | 29.0.3 | 0.19 |
39//!
40//! # What is here
41//!
42//! A whole extraction pipeline, not a substrate waiting for one.
43//!
44//! | | |
45//! |---|---|
46//! | **Extraction** | [`MarchingCubesGpu`] — the case table is uploaded rather than transcribed, so there is one table in the repository and the GPU reads the same bytes the CPU does ([`case_table_bytes`]) |
47//! | **Fields on the GPU** | [`GpuField`], [`GpuShape`], [`GpuOp`], [`GpuBrush`], [`FieldSampler`] — brushes folded device-side, so an edit does not cross the bus |
48//! | **The plumbing extraction needs** | [`PrefixScan`] and [`DeferredScan`] for compaction, [`GridParams`] for std140 packing, [`FieldBuffer`], [`read_buffer`] |
49//! | **Drawing without a readback** | [`MeshShaderRenderer`], [`IndirectGeometry`], and [`probe_mesh_shaders`] to ask first |
50//! | **Distance transforms** | [`JumpFlood`] |
51//! | **Shader sources** | [`MARCHING_CUBES_WGSL`], [`FIELD_WGSL`], [`GRID_WGSL`], [`SCAN_WGSL`], [`JUMP_FLOOD_WGSL`], [`MESH_RENDER_WGSL`], composed by [`Composer`] |
52//! | **No device of your own** | [`headless`] |
53//!
54//! # Is it faster than the CPU? Above about 33³, yes — by 37× at 129³
55//!
56//! Sphere, warmed, median of three, RTX 3090 over Vulkan, against a
57//! single-threaded CPU extraction. `docs/measurements/gpu_vs_cpu.csv`.
58//!
59//! | samples/axis | CPU | GPU, field evaluated on the GPU | |
60//! |---|---|---|---|
61//! | 17³ | **0.06 ms** | 0.22 ms | CPU ahead 3.7× |
62//! | 33³ | 0.34 ms | **0.23 ms** | GPU ahead 1.5× |
63//! | 65³ | 2.44 ms | **0.27 ms** | GPU ahead 9× |
64//! | 129³ | 20.14 ms | **0.54 ms** | GPU ahead **37×** |
65//!
66//! **The shape is the finding.** That GPU column is nearly flat across a 420×
67//! rise in cell count, because extraction was never the cost: `count + emit` is
68//! **0.045 ms at 129³** and does not move with resolution. Below ~33³ a fixed
69//! ~0.22 ms of setup is larger than the whole job, and the CPU wins.
70//!
71//! # Where you evaluate the field decides the rest
72//!
73//! Sample on the CPU and hand over a [`FieldBuffer`] and the **upload is 87% of
74//! the path** — 8.37 ms at 129³, so 2.4× ahead instead of 37×. Worse, that
75//! design does not take field evaluation off the CPU's budget; it adds a copy to
76//! it, and field evaluation is 65–74% of the whole job on a noise field.
77//!
78//! Evaluate it in the shader instead — [`GpuField`], [`GpuShape`], [`GpuOp`],
79//! [`GpuBrush`] — and the upload stops existing, because the samples are
80//! produced where they are read.
81//!
82//! A base the shader has no name for — an arbitrary analytic SDF, which is half
83//! this crate's audience — takes the third option:
84//! [`FieldSampler::fold_into`] reads that base from a buffer the caller filled
85//! and folds the edit log over it on the device. **One upload per grid instead
86//! of none, and none per edit**, which is what makes it the right shape for an
87//! editor: `bevy_isomesh`'s `game_dig` samples its terrain once per chunk and
88//! thereafter moves 64 bytes per surviving brush and no samples at all.
89//!
90//! Three tickets took this path from 15.01 ms to 0.54 ms at 129³ and **none of
91//! them made the extractor faster.** Every gain was data movement removed: a GPU
92//! prefix scan so 8.4 MB of per-cell counts never come home (M-150), then
93//! device-side field evaluation (M-155). What is left after that is the geometry
94//! read-back, and [`MeshShaderRenderer`] removes even that by drawing straight
95//! out of the compute output.
96//!
97//! ```no_run
98//! use isomesh::fields::Sphere;
99//! use isomesh_gpu::{FieldBuffer, GridParams, headless};
100//!
101//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
102//! let gpu = headless::Gpu::new()?;
103//! let grid = GridParams::new([33; 3], [-2.0; 3], 0.125)?;
104//!
105//! // Takes &Device and &Queue -- never an engine type.
106//! let field = FieldBuffer::sampled(
107//!     gpu.device(),
108//!     gpu.queue(),
109//!     grid,
110//!     &Sphere::<f32>::canonical(),
111//! )?;
112//! assert_eq!(field.params().sample_count(), 33 * 33 * 33);
113//! # Ok(())
114//! # }
115//! ```
116
117mod block_on;
118mod buffers;
119mod error;
120mod field_sampler;
121mod grid;
122mod marching_cubes;
123mod mesh_render;
124mod mesh_shader;
125mod scan;
126mod shader;
127mod timestamps;
128
129pub mod headless;
130pub mod jump_flood;
131
132pub use buffers::{
133    DeferredGeometry, FieldBuffer, Readback, read_buffer, read_buffer_u32, read_bytes,
134    read_bytes_many, read_bytes_many_deferred,
135};
136pub use error::{Error, Result};
137pub use field_sampler::{FieldSampler, GpuBrush, GpuField, GpuOp, GpuShape};
138pub use grid::GridParams;
139pub use jump_flood::JumpFlood;
140pub use marching_cubes::{
141    ExtractTimings, GpuGeometry, GpuMesh, IndirectGeometry, MarchingCubesGpu, case_table_bytes,
142};
143pub use mesh_render::MeshShaderRenderer;
144pub use mesh_shader::{MeshShaderReport, probe_mesh_shaders};
145pub use scan::{DeferredScan, PrefixScan, ScanOutput, cpu_prefix_sum};
146pub use shader::{
147    Composer, FEATURES, FIELD_WGSL, GRID_WGSL, JUMP_FLOOD_WGSL, MARCHING_CUBES_WGSL,
148    MESH_RENDER_WGSL, SCAN_WGSL,
149};
150pub use timestamps::{MAX_PASSES, Span, Spans, StageTimestamps};
151
152/// The `wgpu` this crate was built against.
153///
154/// Every public entry point here takes `wgpu` types -- `extract(&self, device:
155/// &wgpu::Device, queue: &wgpu::Queue, ...)` -- so a consumer already needs the
156/// crate and already needs the **same version**. Re-exporting it turns a silent
157/// version-mismatch type error into `isomesh_gpu::wgpu`, which cannot mismatch.
158/// Not a new dependency: it is the one this crate's signatures already require.
159pub use wgpu;
160
161/// Compiles the README's example as a doctest, without putting the README into
162/// these docs — the same pattern `isomesh` uses. The README's fence is
163/// `rust,no_run`: it must compile everywhere, including a CI runner with no
164/// adapter, and execute nowhere, because [`headless::Gpu::new`] refuses to fall
165/// back to a software device.
166#[cfg(doctest)]
167#[doc = include_str!("../README.md")]
168pub struct ReadmeExample;