diff --git a/CHANGELOG.md b/CHANGELOG.md index d771acd..c3dceec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,66 @@ This is a workspace of three crates released together: **rsplot** (the plotting library), **rsdm** (a PyDM-style EPICS display layer built on rsplot), and **adl2rsdm** (a MEDM `.adl` → RsDM-Rust-source converter). +## [0.5.2] - 2026-07-08 + +A correctness and robustness pass over the `VolumeRaycaster` shipped in 0.5.1, +from a post-release review, plus two `rsdm` data-engine race fixes surfaced by +the cross-platform CI. `adl2rsdm` is re-released in lockstep (no functional +change). + +### Fixed — `rsplot` + +- **Dark fringe around opaque regions is gone.** The 3-D volume texture stored + straight-alpha RGBA, so the linear sampler bled a transparent voxel's `rgb=0` + into neighbouring colour at a boundary, darkening it. The volume is now + premultiplied on upload and composited in premultiplied space, so the filter + interpolates colour that keeps its hue. (`premultiply_rgba` is unit-tested.) +- **Opacity no longer depends on the ray step count.** Per-sample coverage was + composited as-is, so raising `set_steps` also made the whole volume more + opaque. Each sample's coverage is now Beer-Lambert–corrected to a 256-step + baseline, so opacity depends only on the data and `set_alpha_scale`; the + default view is unchanged. +- **`set_steps` is clamped to `[1, 4096]`.** A very large value marched every ray + that many times in one frame and could trip the OS GPU-timeout watchdog and + reset the device. +- **Invalid volumes are rejected up front.** `set_volume` now validates the + extent and that the RGBA length matches `depth·height·width·4`, so a bad call + is a no-op (keeping any prior upload) instead of a wgpu validation panic deep + in the render backend. +- **Ctrl/Cmd-pan tracks the pointer one-to-one.** The pan was anchored on the far + plane, so the volume moved faster than the cursor; it is now anchored at the + box-centre depth (the same depth the wheel zoom uses). +- **Same `VolumeId` painted twice in one frame keeps each camera.** The per-id + uniform buffer was shared between `prepare` and `paint`, so two callbacks with + one id both rendered from whichever prepared last (e.g. the same volume in two + panels). Dynamic camera state moved to per-callback buffers. + +### Changed — `rsplot` + +- **`VolumeRaycaster::remove` / `remove_volume_raycaster(id)`** free a volume's + GPU resources (3-D texture, bind group, uniform buffer); previously an id's + VRAM was held for the app's lifetime with no way to release it. +- Dropped the unused `cam_pos` uniform (the shader un-projects rays through + `inv_mvp`), shrinking the per-frame uniform buffer. + +### Fixed — `rsdm` + +- **`ca://` no longer leaks a duplicate initial sample.** The connect-time + metadata fetch posted the initial value unconditionally, but the connection + task can run its connect handler more than once (the CA client emits a native + DBR-type "change" on the first connect, re-entering it). The second post + re-emitted a value the value monitor had already delivered, and a strip-chart / + event-plot `subscribe_values` created in between received it as a spurious + sample. The connect-time value is now gated on an actual change, like the + monitor path. +- **`calc://` always publishes its initial derived value.** The poll loop + consumed a child's recompute trigger even on ticks where not every child was + connected yet, so if the last child to connect was not itself a triggering + variable (an `update` list excluding it), the first all-connected tick saw no + change and never ran the initial evaluation — the calc stayed connected but + valueless. Child stamp changes are now folded in only once every child is + connected, so the initial evaluation is order-independent. + ## [0.5.1] - 2026-07-07 A feature-bearing patch over the `0.5.0` crate rename: a new volume-rendering diff --git a/Cargo.toml b/Cargo.toml index 507a574..2a7c7f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rsplot" -version = "0.5.1" +version = "0.5.2" edition = "2024" rust-version = "1.92" license = "MIT OR Apache-2.0" diff --git a/adl2rsdm/Cargo.toml b/adl2rsdm/Cargo.toml index 07bdf67..7a25b34 100644 --- a/adl2rsdm/Cargo.toml +++ b/adl2rsdm/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "adl2rsdm" -version = "0.5.1" +version = "0.5.2" edition = "2024" rust-version = "1.92" license = "MIT OR Apache-2.0" diff --git a/rsdm/Cargo.toml b/rsdm/Cargo.toml index 8f34144..ee046c4 100644 --- a/rsdm/Cargo.toml +++ b/rsdm/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rsdm" -version = "0.5.1" +version = "0.5.2" edition = "2024" rust-version = "1.92" license = "MIT OR Apache-2.0" @@ -53,7 +53,7 @@ calc = ["dep:evalexpr", "dep:epics-base-rs"] # `version` (alongside `path`) is required so `cargo publish` records a # crates.io dependency on the published rsplot; the path is used for local # workspace builds. Keep this in lockstep with rsplot's version. -rsplot = { path = "..", version = "0.5.1" } +rsplot = { path = "..", version = "0.5.2" } # Async runtime for the data engine. The connection tasks live on a tokio # runtime the `Engine` owns; widgets read shared state on the GUI thread. `net` # is enabled so `enable_all()` (and the EPICS backends, later) work. diff --git a/rsdm/src/data_plugins/calc_plugin.rs b/rsdm/src/data_plugins/calc_plugin.rs index 9ff0305..4e22eba 100644 --- a/rsdm/src/data_plugins/calc_plugin.rs +++ b/rsdm/src/data_plugins/calc_plugin.rs @@ -279,25 +279,40 @@ async fn run_channel( _ = ticker.tick() => { let all_connected = children.iter().all(|(_, ch)| ch.is_connected()); + if all_connected != connected { + connected = all_connected; + writer.update(move |s| s.connected = all_connected); + } + // Note every child whose value changed; a change to a variable // in the `update` list (or any variable when no list is given) // triggers a recompute. + // + // Fold stamp changes into `prev_stamps` ONLY while every child + // is connected — i.e. only while a recompute could actually + // run. A child's initial value often lands a tick or more + // before the last child connects; consuming that change here + // (advancing `prev_stamps` regardless of `all_connected`, the + // old behaviour) dropped its trigger, so the first + // all-connected tick saw no change and the initial value was + // never published — the calc stayed connected but valueless + // until the next child write. Leaving `prev_stamps` at + // `u64::MAX` until the first all-connected tick makes that tick + // observe every child as changed and run the initial eval, with + // no dependence on the child-connect vs poll-tick interleaving. let mut trigger = false; - for (i, (name, ch)) in children.iter().enumerate() { - let stamp = ch.stamp(); - if stamp != prev_stamps[i] { - prev_stamps[i] = stamp; - if update.as_ref().is_none_or(|u| u.iter().any(|n| n == name)) { - trigger = true; + if all_connected { + for (i, (name, ch)) in children.iter().enumerate() { + let stamp = ch.stamp(); + if stamp != prev_stamps[i] { + prev_stamps[i] = stamp; + if update.as_ref().is_none_or(|u| u.iter().any(|n| n == name)) { + trigger = true; + } } } } - if all_connected != connected { - connected = all_connected; - writer.update(move |s| s.connected = all_connected); - } - if all_connected && trigger && let Some(value) = evaluate( &id, diff --git a/rsdm/src/data_plugins/epics_plugins/ca_plugin.rs b/rsdm/src/data_plugins/epics_plugins/ca_plugin.rs index 5064a5c..22ecc04 100644 --- a/rsdm/src/data_plugins/epics_plugins/ca_plugin.rs +++ b/rsdm/src/data_plugins/epics_plugins/ca_plugin.rs @@ -365,14 +365,30 @@ async fn on_connect( .filter(|e| !e.strings.is_empty()) .map(|e| latin1_strings(&e.strings)); *enum_cache = strings.clone(); - // The connect-time snapshot carries the initial value, so post it as - // a value event (not a bare snapshot update) — the first strip-chart - // sample. Always a value event: PyDM clears its value cache on - // (re)connect, so the first callback after connect emits - // unconditionally (pyepics_plugin_component.py:192-199 → :102). + // The connect-time snapshot carries the initial value. Post it as a + // value event (the first strip-chart sample) — but gate it on the + // same `last_value` change check the monitor branch uses, not + // unconditionally. The value monitor and this metadata fetch both + // deliver the connect-time value, and the runtime fixes neither + // their order nor whether `on_connect` runs once or twice (a + // native-type-change / reconnect event re-enters it). Posting here + // unconditionally re-emits a value the monitor — or a prior + // `on_connect` — already delivered on this connection; if a value + // subscriber was created in between (the strip-chart / event-plot + // `subscribe_values` case) that duplicate leaks to it as a spurious + // sample. Emit only on an actual change; otherwise refresh the CTRL + // metadata (units/precision/enum strings the TIME-class monitor + // lacks) without a sample. PyDM clear_cache parity is preserved: a + // reconnect clears `last_value` (the Disconnected arm), so the first + // value after a reconnect still emits (pyepics_plugin_component.py: + // 192-199 → :102). let value = epics_to_pv(&snap.value, strings.as_deref()); - *last_value = Some(value.clone()); - writer.post_value(move |s| apply_metadata(s, &snap, value, strings)); + if last_value.as_ref() != Some(&value) { + *last_value = Some(value.clone()); + writer.post_value(move |s| apply_metadata(s, &snap, value, strings)); + } else { + writer.update(move |s| apply_metadata(s, &snap, value, strings)); + } } Err(_) => { // Connected, but the metadata read failed; reflect the connection so diff --git a/rsdm/tests/calc_derived.rs b/rsdm/tests/calc_derived.rs index b23b8aa..6302246 100644 --- a/rsdm/tests/calc_derived.rs +++ b/rsdm/tests/calc_derived.rs @@ -12,6 +12,13 @@ use std::time::{Duration, Instant}; use rsdm::{Engine, PvValue}; +/// Poll deadline for the async calc pipeline to settle. Generous on purpose: +/// `wait_for` returns as soon as the condition holds, so a large deadline only +/// bounds the failure path and never slows a passing run — but the `calc://` +/// chain (child connect → value poll → expr eval → republish) can take well +/// over a second on a loaded CI runner, and a 2 s deadline flaked on macOS. +const WAIT: Duration = Duration::from_secs(30); + /// Poll `cond` until it holds or `timeout` elapses; returns the final result. fn wait_for(mut cond: impl FnMut() -> bool, timeout: Duration) -> bool { let start = Instant::now(); @@ -44,7 +51,7 @@ fn calc_sums_two_local_children_and_recomputes_on_write() { // Both children configure via the direct handles → calc connects. assert!( - wait_for(|| calc.is_connected(), Duration::from_secs(2)), + wait_for(|| calc.is_connected(), WAIT), "calc channel never connected (children did not all connect)" ); @@ -52,7 +59,7 @@ fn calc_sums_two_local_children_and_recomputes_on_write() { assert!( wait_for( || matches!(calc.read(|s| s.value.clone()), Some(PvValue::Float(v)) if v.abs() < 1e-9), - Duration::from_secs(2) + WAIT ), "did not observe the initial derived value 0.0 (got {:?})", calc.read(|s| s.value.clone()) @@ -64,7 +71,7 @@ fn calc_sums_two_local_children_and_recomputes_on_write() { assert!( wait_for( || matches!(calc.read(|s| s.value.clone()), Some(PvValue::Float(v)) if (v - 5.0).abs() < 1e-9), - Duration::from_secs(2) + WAIT ), "did not observe the recomputed sum 5.0 (got {:?})", calc.read(|s| s.value.clone()) @@ -87,13 +94,13 @@ fn calc_update_list_restricts_which_child_triggers_recompute() { .expect("connect child b"); assert!( - wait_for(|| calc.is_connected(), Duration::from_secs(2)), + wait_for(|| calc.is_connected(), WAIT), "calc channel never connected" ); assert!( wait_for( || matches!(calc.read(|s| s.value.clone()), Some(PvValue::Float(v)) if v.abs() < 1e-9), - Duration::from_secs(2) + WAIT ), "did not observe the initial derived value 0.0" ); @@ -113,13 +120,54 @@ fn calc_update_list_restricts_which_child_triggers_recompute() { assert!( wait_for( || matches!(calc.read(|s| s.value.clone()), Some(PvValue::Float(v)) if (v - 6.0).abs() < 1e-9), - Duration::from_secs(2) + WAIT ), "a (in update list) did not trigger a recompute to 6.0 (got {:?})", calc.read(|s| s.value.clone()) ); } +/// Regression for the lost initial-evaluation edge: a child whose value lands +/// before *every* child is connected must not have its recompute trigger +/// silently consumed. With `update=a`, connect `a` first and let the 50 ms poll +/// loop observe it (over several ticks) while `b` is still a bare, disconnected +/// child; then connect `b`. `b` is not in the update list, so `b`'s own +/// connection cannot be the trigger — only the pending change to `a` can. The +/// initial evaluation must still run on the first all-connected tick. +/// +/// Before the fix the poll loop folded `a`'s change into `prev_stamps` on a +/// not-all-connected tick, so the first all-connected tick saw no triggering +/// change and never published — the calc stayed connected but valueless, and +/// this timed out. This is the deterministic form of the child-connect-order +/// flake that hit `calc://` on CI. +#[test] +fn calc_publishes_initial_value_when_update_var_connects_before_others() { + let engine = Engine::new(); + let calc = engine + .connect("calc://early?expr=a+b&a=loc://calc_early_a&b=loc://calc_early_b&update=a") + .expect("connect calc channel"); + // Connect the update variable `a` first, then let the poll loop run several + // 50 ms ticks with `a` connected but `b` still bare and disconnected. + let _a = engine + .connect("loc://calc_early_a?type=float&init=2") + .expect("connect child a"); + std::thread::sleep(Duration::from_millis(300)); + // Now connect `b` (not in the update list): only the pending change to `a` + // can trigger the initial evaluation. + let _b = engine + .connect("loc://calc_early_b?type=float&init=3") + .expect("connect child b"); + + assert!( + wait_for( + || matches!(calc.read(|s| s.value.clone()), Some(PvValue::Float(v)) if (v - 5.0).abs() < 1e-9), + WAIT + ), + "initial derived value a+b = 2+3 = 5.0 was never published (got {:?})", + calc.read(|s| s.value.clone()) + ); +} + // --------------------------------------------------------------------------- // MEDM CALC dialect (`?dialect=medm`) — the adl2rsdm visibility-gate language. // --------------------------------------------------------------------------- @@ -128,7 +176,7 @@ fn calc_update_list_restricts_which_child_triggers_recompute() { fn wait_for_float(calc: &rsdm::Channel, expected: f64) -> bool { wait_for( || matches!(calc.read(|s| s.value.clone()), Some(PvValue::Float(v)) if (v - expected).abs() < 1e-9), - Duration::from_secs(2), + WAIT, ) } @@ -203,7 +251,7 @@ fn medm_ternary_functions_and_encoded_and_evaluate() { .connect("loc://medm_t_b?type=float&init=0") .expect("connect child b"); assert!( - wait_for(|| calc.is_connected(), Duration::from_secs(2)), + wait_for(|| calc.is_connected(), WAIT), "medm ternary channel never connected" ); diff --git a/src/render/shaders/volume_raycaster.wgsl b/src/render/shaders/volume_raycaster.wgsl index 17f9a82..87b5e3a 100644 --- a/src/render/shaders/volume_raycaster.wgsl +++ b/src/render/shaders/volume_raycaster.wgsl @@ -2,14 +2,16 @@ // // A full-screen triangle generates one camera ray per pixel from the inverse // view-projection matrix. Each ray is clipped to the volume's axis-aligned box -// and marched in fixed steps, sampling straight-alpha RGBA and accumulating -// PREMULTIPLIED colour so the result blends with `PREMULTIPLIED_ALPHA_BLENDING` +// and marched in fixed steps. The 3D texture holds PREMULTIPLIED RGBA (the +// uploader premultiplies straight alpha) so the hardware linear filter +// interpolates premultiplied colour — a colour/transparent boundary stays the +// right hue instead of bleeding toward black. Samples accumulate front-to-back +// into premultiplied colour that blends with `PREMULTIPLIED_ALPHA_BLENDING` // straight into egui's render pass (no offscreen target, no depth). struct Uniforms { // Inverse of the camera clip matrix P·V (OpenGL clip, z in [-1, 1]). inv_mvp: mat4x4, - cam_pos: vec4, // world-space camera position (xyz; w unused) vol_min: vec4, // world-space AABB min (xyz) vol_max: vec4, // world-space AABB max (xyz) // x = step count, y = alpha scale, z = sample-alpha cull floor, w unused. @@ -20,6 +22,12 @@ struct Uniforms { @group(0) @binding(1) var vol_tex: texture_3d; @group(0) @binding(2) var vol_samp: sampler; +// Reference sample count for the opacity correction: at this many steps a +// sample's coverage is used as-is, and other step counts are corrected so the +// accumulated opacity stays the same. Matches the widget's default `steps`, so +// the default view is unchanged. +const REF_STEPS: f32 = 256.0; + struct VsOut { @builtin(position) clip: vec4, @location(0) ndc: vec2, @@ -80,11 +88,19 @@ fn fs_main(in: VsOut) -> @location(0) vec4 { for (var i = 0; i < steps; i = i + 1) { let p = ro + rd * t; let uvw = (p - u.vol_min.xyz) / extent; - let s = textureSampleLevel(vol_tex, vol_samp, uvw, 0.0); + let s = textureSampleLevel(vol_tex, vol_samp, uvw, 0.0); // premultiplied rgb, coverage a if s.a > cull_floor { - let a = clamp(s.a * alpha_scale, 0.0, 1.0); - let w = (1.0 - acc.a) * a; - acc = vec4(acc.rgb + s.rgb * w, acc.a + w); + // Scale coverage by the user opacity knob, then correct it for the + // step count so accumulated opacity is invariant to `steps` + // (transmittance (1-sa)^steps held to the REF_STEPS baseline). + let sa = clamp(s.a * alpha_scale, 0.0, 1.0); + let sa_c = 1.0 - pow(1.0 - sa, REF_STEPS / f32(steps)); + // Rescale the premultiplied colour to the corrected coverage + // (gain = sa_c/s.a). Compositing stays in premultiplied space, so no + // dark fringe at boundaries. + let gain = sa_c / max(s.a, 1e-6); + let w = 1.0 - acc.a; + acc = vec4(acc.rgb + s.rgb * gain * w, acc.a + sa_c * w); } if acc.a >= 0.995 { break; diff --git a/src/render/volume_raycaster.rs b/src/render/volume_raycaster.rs index e7dce7d..93a1fc5 100644 --- a/src/render/volume_raycaster.rs +++ b/src/render/volume_raycaster.rs @@ -12,6 +12,7 @@ //! [`paint_volume_raycaster`] registers the per-frame paint callback. use std::collections::HashMap; +use std::sync::Mutex; use egui_wgpu::{RenderState, wgpu}; @@ -24,7 +25,6 @@ pub type VolumeId = u64; #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] struct VolumeUniforms { inv_mvp: [[f32; 4]; 4], - cam_pos: [f32; 4], vol_min: [f32; 4], vol_max: [f32; 4], params: [f32; 4], @@ -37,7 +37,6 @@ pub struct VolumeFrame { pub id: VolumeId, /// Inverse of the camera clip matrix, column-major (`Mat4::to_gpu_cols`). pub inv_mvp: [[f32; 4]; 4], - pub cam_pos: [f32; 3], /// `[step_count, alpha_scale, cull_floor]`. pub params: [f32; 3], } @@ -58,6 +57,25 @@ pub fn volume_bounds(depth: usize, height: usize, width: usize) -> ([f32; 3], [f ([-half[0], -half[1], -half[2]], half) } +/// Premultiply a straight-alpha RGBA8 buffer (`rgb *= a/255`, rounded), so the +/// linear sampler interpolates premultiplied colour: a transparent voxel becomes +/// `(0,0,0,0)` and interpolating it against an opaque colour keeps the hue +/// instead of dragging it toward black. A trailing partial pixel (len not a +/// multiple of 4) is dropped. +fn premultiply_rgba(rgba: &[u8]) -> Vec { + rgba.chunks_exact(4) + .flat_map(|px| { + let a = px[3] as u16; + [ + ((px[0] as u16 * a + 127) / 255) as u8, + ((px[1] as u16 * a + 127) / 255) as u8, + ((px[2] as u16 * a + 127) / 255) as u8, + px[3], + ] + }) + .collect() +} + struct VolumePipeline { pipeline: wgpu::RenderPipeline, bgl: wgpu::BindGroupLayout, @@ -155,43 +173,40 @@ impl VolumePipeline { } } -/// Per-view GPU state: the uniform buffer, the uploaded 3D texture, its bind -/// group and the world-space box the texture occupies. +/// Per-view GPU state: the uploaded 3D texture and the world-space box it +/// occupies. Uniforms and the bind group are NOT stored here — each paint +/// callback builds its own in `prepare` (see [`VolumeCallback`]), so two +/// callbacks sharing a [`VolumeId`] in one frame no longer clobber a shared +/// uniform buffer. struct VolumeGpu { - uniform_buf: wgpu::Buffer, - bind_group: Option, + texture: Option, vol_min: [f32; 3], vol_max: [f32; 3], } impl VolumeGpu { - fn new(device: &wgpu::Device) -> Self { - let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("rsplot volume raycaster uniforms"), - size: std::mem::size_of::() as u64, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); + fn new() -> Self { Self { - uniform_buf, - bind_group: None, + texture: None, vol_min: [-0.5, -0.5, -0.5], vol_max: [0.5, 0.5, 0.5], } } /// Upload a `(depth, height, width)` RGBA8 volume (row-major, straight - /// alpha), (re)building the 3D texture and bind group. + /// alpha), (re)building the 3D texture. The straight alpha is premultiplied + /// before upload so the linear sampler interpolates premultiplied colour (no + /// dark fringe at colour/transparent boundaries). fn upload( &mut self, device: &wgpu::Device, queue: &wgpu::Queue, - pipeline: &VolumePipeline, rgba: &[u8], dims: (usize, usize, usize), ) { let (depth, height, width) = dims; let (w, h, d) = (width as u32, height as u32, depth as u32); + let premul = premultiply_rgba(rgba); let extent = wgpu::Extent3d { width: w, height: h, @@ -214,7 +229,7 @@ impl VolumeGpu { origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All, }, - rgba, + &premul, wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), @@ -222,17 +237,49 @@ impl VolumeGpu { }, extent, ); + self.texture = Some(texture); + (self.vol_min, self.vol_max) = volume_bounds(depth, height, width); + } + + /// Build a bind group for one frame: a fresh uniform buffer holding this + /// frame's camera and this view's box, plus the view's texture and the shared + /// sampler. `None` until a volume has been uploaded. Called once per paint in + /// `prepare`, so each callback owns its uniforms rather than sharing one + /// per-id buffer. + fn frame_bind_group( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + pipeline: &VolumePipeline, + frame: &VolumeFrame, + ) -> Option { + let texture = self.texture.as_ref()?; + let u = VolumeUniforms { + inv_mvp: frame.inv_mvp, + vol_min: [self.vol_min[0], self.vol_min[1], self.vol_min[2], 0.0], + vol_max: [self.vol_max[0], self.vol_max[1], self.vol_max[2], 0.0], + params: [frame.params[0], frame.params[1], frame.params[2], 0.0], + }; + let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("rsplot volume raycaster uniforms"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&uniform_buf, 0, bytemuck::bytes_of(&u)); let view = texture.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D3), ..Default::default() }); - self.bind_group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor { + // The bind group holds strong refs to the uniform buffer and view, so + // both live as long as the callback keeps the bind group. + Some(device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("rsplot volume raycaster bind group"), layout: &pipeline.bgl, entries: &[ wgpu::BindGroupEntry { binding: 0, - resource: self.uniform_buf.as_entire_binding(), + resource: uniform_buf.as_entire_binding(), }, wgpu::BindGroupEntry { binding: 1, @@ -243,19 +290,7 @@ impl VolumeGpu { resource: wgpu::BindingResource::Sampler(&pipeline.sampler), }, ], - })); - (self.vol_min, self.vol_max) = volume_bounds(depth, height, width); - } - - fn write_uniforms(&self, queue: &wgpu::Queue, frame: &VolumeFrame) { - let u = VolumeUniforms { - inv_mvp: frame.inv_mvp, - cam_pos: [frame.cam_pos[0], frame.cam_pos[1], frame.cam_pos[2], 1.0], - vol_min: [self.vol_min[0], self.vol_min[1], self.vol_min[2], 0.0], - vol_max: [self.vol_max[0], self.vol_max[1], self.vol_max[2], 0.0], - params: [frame.params[0], frame.params[1], frame.params[2], 0.0], - }; - queue.write_buffer(&self.uniform_buf, 0, bytemuck::bytes_of(&u)); + })) } } @@ -298,34 +333,64 @@ pub fn set_volume_raycaster( height: usize, width: usize, ) { + // Guard the wgpu texture invariants: non-empty extent and exactly one RGBA8 + // texel per voxel. An invalid call is a no-op (keeping any prior upload) + // rather than a wgpu validation panic; debug builds trip an assert so the + // caller bug is caught. + let expected = depth.saturating_mul(height).saturating_mul(width) * 4; + if depth == 0 || height == 0 || width == 0 || rgba.len() != expected { + debug_assert!( + false, + "set_volume_raycaster: bad volume ({depth}x{height}x{width}, {} bytes, expected {expected})", + rgba.len() + ); + return; + } let mut renderer = render_state.renderer.write(); let res: &mut VolumeRaycasterResources = renderer .callback_resources .get_mut() .expect("VolumeRaycasterResources not installed — call install_volume_raycaster() first"); - let VolumeRaycasterResources { pipeline, scenes } = res; - let scene = scenes - .entry(id) - .or_insert_with(|| VolumeGpu::new(&render_state.device)); + let scene = res.scenes.entry(id).or_insert_with(VolumeGpu::new); scene.upload( &render_state.device, &render_state.queue, - pipeline, rgba, (depth, height, width), ); } -/// egui paint callback: write this frame's uniforms in `prepare`, ray-march in -/// `paint`. +/// Drop view `id`'s GPU resources (the 3D texture), freeing its VRAM. A no-op if +/// `id` was never uploaded or the pipeline is not installed. Call when a +/// raycaster view goes away so its texture does not linger in +/// `callback_resources` for the app's lifetime. +pub fn remove_volume_raycaster(render_state: &RenderState, id: VolumeId) { + let mut renderer = render_state.renderer.write(); + if let Some(res) = renderer + .callback_resources + .get_mut::() + { + res.scenes.remove(&id); + } +} + +/// egui paint callback. `prepare` builds this frame's own bind group (fresh +/// uniform buffer for the camera + the view's texture) and stashes it in `ready`; +/// `paint` ray-marches with it. Because the bind group is per-callback rather +/// than a shared per-id buffer, two callbacks with the same [`VolumeId`] in one +/// frame each render with their own camera. struct VolumeCallback { frame: VolumeFrame, + /// Built in `prepare`, consumed in `paint`. `Mutex` only to satisfy the + /// `CallbackTrait: Send + Sync` bound — prepare and paint run in sequence on + /// the render thread, never concurrently. + ready: Mutex>, } impl egui_wgpu::CallbackTrait for VolumeCallback { fn prepare( &self, - _device: &wgpu::Device, + device: &wgpu::Device, queue: &wgpu::Queue, _screen: &egui_wgpu::ScreenDescriptor, _encoder: &mut wgpu::CommandEncoder, @@ -334,7 +399,8 @@ impl egui_wgpu::CallbackTrait for VolumeCallback { if let Some(res) = resources.get::() && let Some(scene) = res.scenes.get(&self.frame.id) { - scene.write_uniforms(queue, &self.frame); + let bg = scene.frame_bind_group(device, queue, &res.pipeline, &self.frame); + *self.ready.lock().unwrap() = bg; } Vec::new() } @@ -345,9 +411,11 @@ impl egui_wgpu::CallbackTrait for VolumeCallback { render_pass: &mut wgpu::RenderPass<'static>, resources: &egui_wgpu::CallbackResources, ) { + // Hold the guard through the draw so the bind group (and the uniform + // buffer it owns) stay alive while the pass records. + let ready = self.ready.lock().unwrap(); if let Some(res) = resources.get::() - && let Some(scene) = res.scenes.get(&self.frame.id) - && let Some(bind_group) = &scene.bind_group + && let Some(bind_group) = ready.as_ref() { render_pass.set_pipeline(&res.pipeline.pipeline); render_pass.set_bind_group(0, bind_group, &[]); @@ -358,9 +426,44 @@ impl egui_wgpu::CallbackTrait for VolumeCallback { /// Register the raycaster paint callback for `frame` over `rect`. A no-op on /// screen until [`set_volume_raycaster`] has uploaded a volume for `frame.id`. +/// +/// Each callback builds its own uniform buffer + bind group in `prepare` (keyed +/// off `frame`, not shared per id), so painting the same [`VolumeId`] twice in +/// one frame — two panels of the same volume from different cameras — renders +/// each with its own viewpoint. pub fn paint_volume_raycaster(ui: &mut egui::Ui, rect: egui::Rect, frame: VolumeFrame) { ui.painter().add(egui_wgpu::Callback::new_paint_callback( rect, - VolumeCallback { frame }, + VolumeCallback { + frame, + ready: Mutex::new(None), + }, )); } + +#[cfg(test)] +mod tests { + use super::premultiply_rgba; + + #[test] + fn premultiply_zeroes_transparent_and_keeps_opaque() { + // Opaque red is unchanged; fully transparent becomes (0,0,0,0) so the + // linear filter cannot bleed its colour; half-alpha halves rgb. + let src = [ + 255, 0, 0, 255, // opaque red + 200, 100, 50, 0, // transparent → all zero + 255, 255, 255, 128, // half coverage → ~half + ]; + let out = premultiply_rgba(&src); + assert_eq!(&out[0..4], &[255, 0, 0, 255]); + assert_eq!(&out[4..8], &[0, 0, 0, 0]); + assert_eq!(out[11], 128); // alpha preserved + assert_eq!(out[8], 128); // 255*128/255 rounded + } + + #[test] + fn premultiply_drops_trailing_partial_pixel() { + let src = [255, 0, 0, 255, 1, 2]; // 6 bytes: one pixel + 2 stragglers + assert_eq!(premultiply_rgba(&src).len(), 4); + } +} diff --git a/src/widget/volume_raycaster.rs b/src/widget/volume_raycaster.rs index 3566b26..fb3b999 100644 --- a/src/widget/volume_raycaster.rs +++ b/src/widget/volume_raycaster.rs @@ -19,10 +19,14 @@ use crate::core::scene3d::camera::Camera; use crate::core::scene3d::interaction::{OrbitDrag, PanDrag, window_to_ndc}; use crate::core::scene3d::mat4::{Mat4, Vec3}; use crate::render::volume_raycaster::{ - VolumeFrame, VolumeId, install_volume_raycaster, paint_volume_raycaster, set_volume_raycaster, - volume_bounds, + VolumeFrame, VolumeId, install_volume_raycaster, paint_volume_raycaster, + remove_volume_raycaster, set_volume_raycaster, volume_bounds, }; +/// Upper bound on samples per ray; beyond this a single frame can outrun the +/// OS GPU-timeout watchdog on modest hardware. +const MAX_STEPS: u32 = 4096; + /// Interactive GPU direct-volume-rendering widget. See the module docs. pub struct VolumeRaycaster { id: VolumeId, @@ -45,6 +49,11 @@ impl VolumeRaycaster { /// Create a raycaster bound to scene key `id`, installing the shared pipeline /// into `render_state` (idempotent). The camera looks down `-z`; the first /// [`set_volume`](Self::set_volume) frames it to the volume. + /// + /// The `id` keys the uploaded 3D texture, so distinct volumes need distinct + /// ids (two views sharing an id share the last-uploaded texture). Cameras are + /// not shared: each paint builds its own uniforms, so same-id views still + /// render with their own viewpoint. pub fn new(render_state: &RenderState, id: VolumeId) -> Self { install_volume_raycaster(render_state); let camera = Camera::new( @@ -89,9 +98,11 @@ impl VolumeRaycaster { } } - /// Number of samples per ray (higher = smoother, slower). Default 256. + /// Number of samples per ray (higher = smoother, slower). Default 256, + /// clamped to `[1, MAX_STEPS]` — an unbounded count can stall the GPU long + /// enough to trip the OS device-timeout reset. pub fn set_steps(&mut self, steps: u32) { - self.steps = steps.max(1); + self.steps = steps.clamp(1, MAX_STEPS); } /// Global opacity multiplier applied to each sample's alpha. Default 1.0. @@ -109,6 +120,15 @@ impl VolumeRaycaster { self.camera.reset_camera(self.bounds); } + /// Free this view's uploaded GPU volume (the 3D texture). Its VRAM is + /// otherwise held for the app's lifetime, since the shared resources keep one + /// entry per id. After this the view paints nothing until the next + /// [`set_volume`](Self::set_volume). + pub fn remove(&mut self, render_state: &RenderState) { + remove_volume_raycaster(render_state, self.id); + self.has_volume = false; + } + /// Lay the view over the available space, handle orbit/pan/zoom, and paint. /// Left drag orbits the volume centre; Ctrl/Cmd-drag pans; the wheel zooms. pub fn show(&mut self, ui: &mut Ui) -> Response { @@ -126,14 +146,17 @@ impl VolumeRaycaster { // Begin a gesture at the press origin (before egui's drag threshold moves // the pointer), mirroring `SceneWidget`. No geometry to pick against, so - // orbit pivots on the box centre and pan sits on the far plane. + // orbit pivots on the box centre and pan sits on the box-centre depth + // plane (the same NDC-z the wheel zoom anchors on) — anchoring on the far + // plane would make the pan drift faster than the cursor. if response.drag_started_by(PointerButton::Primary) && let Some(p) = press_origin { let ctrl = ui.ctx().input(|i| i.modifiers.command); let win = to_local(p); if ctrl { - self.pan = Some(PanDrag::begin(win, size_px, 1.0)); + let ndc_z = self.camera.matrix().transform_point(center, true).z; + self.pan = Some(PanDrag::begin(win, size_px, ndc_z)); } else { self.orbit = Some(OrbitDrag::begin(&self.camera, win, center)); } @@ -174,11 +197,9 @@ impl VolumeRaycaster { .matrix() .inverse() .map_or_else(|| Mat4::IDENTITY.to_gpu_cols(), |m| m.to_gpu_cols()); - let pos = self.camera.extrinsic.position(); let frame = VolumeFrame { id: self.id, inv_mvp, - cam_pos: [pos.x, pos.y, pos.z], params: [self.steps as f32, self.alpha_scale, self.cull_floor], }; paint_volume_raycaster(ui, rect, frame); diff --git a/tests/volume_raycaster_render.rs b/tests/volume_raycaster_render.rs index 34576b6..1b73fe5 100644 --- a/tests/volume_raycaster_render.rs +++ b/tests/volume_raycaster_render.rs @@ -9,9 +9,19 @@ use rsplot::egui; use rsplot::egui_wgpu::RenderState; use std::cell::RefCell; use std::rc::Rc; +use std::sync::Mutex; const WIN: f32 = 320.0; +/// Serializes the two GPU tests in this binary. `cargo test` runs them on +/// parallel threads, so each would create and tear down its own wgpu device at +/// the same time; on the Windows CI runner's DX12 software adapter (WARP) that +/// concurrent device create/destroy faults with STATUS_ACCESS_VIOLATION (a +/// native crash in the adapter, not in rsplot). Holding this lock across each +/// test's whole render keeps exactly one device alive at a time. Poison is +/// recovered (a failed assertion in one test must not wedge the other). +static GPU: Mutex<()> = Mutex::new(()); + /// An `n³` RGBA8 volume, every voxel `(r, g, b, a)`. fn solid(n: usize, rgba: [u8; 4]) -> Vec { let mut v = Vec::with_capacity(n * n * n * 4); @@ -66,6 +76,7 @@ fn red_pixels_for(rgba: [u8; 4]) -> usize { #[test] fn opaque_volume_ray_marches_to_colour() { + let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); let red = red_pixels_for([255, 0, 0, 255]); assert!( red > 500, @@ -75,6 +86,7 @@ fn opaque_volume_ray_marches_to_colour() { #[test] fn transparent_volume_renders_nothing() { + let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); let red = red_pixels_for([255, 0, 0, 0]); // alpha 0 everywhere assert!( red < 50,