From 1c689008fe1286cfbfda5b30e13ccca1c19094c9 Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Tue, 7 Jul 2026 18:22:32 +0900 Subject: [PATCH 01/15] fix(volume): premultiply alpha to kill the dark-fringe artifact MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 3D texture stored straight-alpha RGBA and the linear sampler interpolated colour and alpha independently, so at a colour/transparent boundary a transparent voxel's rgb=0 bled into the neighbouring colour and darkened it — a black fringe around every opaque region. Premultiply on upload (rgb *= a/255) so a transparent voxel is (0,0,0,0) and the filter interpolates premultiplied colour, which keeps the hue. The shader now composites in premultiplied space: it scales coverage by the opacity knob and rescales the premultiplied colour to match (gain = sa/s.a) rather than re-multiplying straight rgb by alpha. premultiply_rgba is unit-tested; the render tests stay green. --- src/render/shaders/volume_raycaster.wgsl | 19 ++++++--- src/render/volume_raycaster.rs | 53 +++++++++++++++++++++++- 2 files changed, 64 insertions(+), 8 deletions(-) diff --git a/src/render/shaders/volume_raycaster.wgsl b/src/render/shaders/volume_raycaster.wgsl index 17f9a82..d494029 100644 --- a/src/render/shaders/volume_raycaster.wgsl +++ b/src/render/shaders/volume_raycaster.wgsl @@ -2,8 +2,11 @@ // // 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 { @@ -80,11 +83,15 @@ 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 rescale the + // premultiplied colour to that coverage (gain = sa/s.a). Compositing + // stays in premultiplied space, so no dark fringe at boundaries. + let sa = clamp(s.a * alpha_scale, 0.0, 1.0); + let gain = sa / max(s.a, 1e-6); + let w = 1.0 - acc.a; + acc = vec4(acc.rgb + s.rgb * gain * w, acc.a + sa * w); } if acc.a >= 0.995 { break; diff --git a/src/render/volume_raycaster.rs b/src/render/volume_raycaster.rs index e7dce7d..87a7687 100644 --- a/src/render/volume_raycaster.rs +++ b/src/render/volume_raycaster.rs @@ -58,6 +58,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, @@ -181,7 +200,9 @@ impl VolumeGpu { } /// 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 and bind group. 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, @@ -192,6 +213,7 @@ impl VolumeGpu { ) { 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 +236,7 @@ impl VolumeGpu { origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All, }, - rgba, + &premul, wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), @@ -364,3 +386,30 @@ pub fn paint_volume_raycaster(ui: &mut egui::Ui, rect: egui::Rect, frame: Volume VolumeCallback { frame }, )); } + +#[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); + } +} From 4da9ddca618b1c604bdb82a1d67bbd53d8a05330 Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Tue, 7 Jul 2026 18:23:08 +0900 Subject: [PATCH 02/15] fix(volume): make opacity independent of the ray step count MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per-sample coverage was composited as-is, so raising `set_steps` sampled each voxel more often and made the whole volume more opaque — the step knob doubled as a brightness knob. Correct each sample's coverage by REF_STEPS/steps (Beer-Lambert) so transmittance (1-sa)^steps is held to a 256-step baseline. Opacity now depends only on the data and alpha_scale, not the sample count. The baseline equals the widget's default steps, so the default view is unchanged. --- src/render/shaders/volume_raycaster.wgsl | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/render/shaders/volume_raycaster.wgsl b/src/render/shaders/volume_raycaster.wgsl index d494029..a888fa8 100644 --- a/src/render/shaders/volume_raycaster.wgsl +++ b/src/render/shaders/volume_raycaster.wgsl @@ -23,6 +23,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, @@ -85,13 +91,17 @@ fn fs_main(in: VsOut) -> @location(0) vec4 { let uvw = (p - u.vol_min.xyz) / extent; let s = textureSampleLevel(vol_tex, vol_samp, uvw, 0.0); // premultiplied rgb, coverage a if s.a > cull_floor { - // Scale coverage by the user opacity knob, then rescale the - // premultiplied colour to that coverage (gain = sa/s.a). Compositing - // stays in premultiplied space, so no dark fringe at boundaries. + // 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 gain = sa / max(s.a, 1e-6); + 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 * w); + acc = vec4(acc.rgb + s.rgb * gain * w, acc.a + sa_c * w); } if acc.a >= 0.995 { break; From a6354aa930e3551d9c5259e99815cb7c9ebd52fd Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Tue, 7 Jul 2026 18:24:08 +0900 Subject: [PATCH 03/15] fix(volume): add a remove API so raycaster VRAM can be freed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Shared resources kept one VolumeGpu (3D texture + bind group + uniform buffer) per id forever — a view that came and went, or a caller cycling ids, leaked that VRAM for the app's lifetime with no way to release it. Add remove_volume_raycaster(id) and VolumeRaycaster::remove to drop the entry and its GPU handles; both are no-ops if nothing was uploaded. --- src/render/volume_raycaster.rs | 14 ++++++++++++++ src/widget/volume_raycaster.rs | 13 +++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/render/volume_raycaster.rs b/src/render/volume_raycaster.rs index 87a7687..db2fce3 100644 --- a/src/render/volume_raycaster.rs +++ b/src/render/volume_raycaster.rs @@ -338,6 +338,20 @@ pub fn set_volume_raycaster( ); } +/// Drop view `id`'s GPU resources (texture, bind group, uniform buffer), +/// freeing their 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: write this frame's uniforms in `prepare`, ray-march in /// `paint`. struct VolumeCallback { diff --git a/src/widget/volume_raycaster.rs b/src/widget/volume_raycaster.rs index 3566b26..ec2599e 100644 --- a/src/widget/volume_raycaster.rs +++ b/src/widget/volume_raycaster.rs @@ -19,8 +19,8 @@ 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, }; /// Interactive GPU direct-volume-rendering widget. See the module docs. @@ -109,6 +109,15 @@ impl VolumeRaycaster { self.camera.reset_camera(self.bounds); } + /// Free this view's uploaded GPU volume (texture, bind group, uniforms). 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 { From e6ac75ce41ffedb90dd1bffc195aa7d8a8da7613 Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Tue, 7 Jul 2026 18:24:37 +0900 Subject: [PATCH 04/15] fix(volume): anchor Ctrl-pan on the volume centre, not the far plane MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PanDrag began on the far plane (ndc_z = 1.0), so a Ctrl/Cmd-drag pan moved the volume faster than the cursor — the pan plane sat far behind the geometry. Anchor the pan at the box-centre depth, the same NDC-z the wheel zoom already uses, so the volume tracks the pointer one-to-one. --- src/widget/volume_raycaster.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/widget/volume_raycaster.rs b/src/widget/volume_raycaster.rs index ec2599e..164cf53 100644 --- a/src/widget/volume_raycaster.rs +++ b/src/widget/volume_raycaster.rs @@ -135,14 +135,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)); } From 2165af02005da848d3f82948d228b9d8b43161d7 Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Tue, 7 Jul 2026 18:25:24 +0900 Subject: [PATCH 05/15] fix(volume): validate volume dims/length before upload set_volume_raycaster fed its arguments straight to wgpu, so a zero extent or an rgba slice that did not match depth*height*width*4 surfaced as a wgpu validation error (a hard panic deep in the render backend). Check the texture invariants up front: an invalid call is a no-op that keeps any prior upload, and a debug_assert flags the caller bug in dev builds. --- src/render/volume_raycaster.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/render/volume_raycaster.rs b/src/render/volume_raycaster.rs index db2fce3..926a2b7 100644 --- a/src/render/volume_raycaster.rs +++ b/src/render/volume_raycaster.rs @@ -320,6 +320,19 @@ 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 From 1869e3619ea50dbea099d1a825bed4e10722372c Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Tue, 7 Jul 2026 18:26:03 +0900 Subject: [PATCH 06/15] fix(volume): clamp ray step count to a safe maximum set_steps only enforced a floor of 1, so a large value marched every ray that many times in one frame and could outrun the OS GPU-timeout watchdog, resetting the device. Clamp to [1, 4096]; the default 256 and any reasonable quality setting are unaffected. --- src/widget/volume_raycaster.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/widget/volume_raycaster.rs b/src/widget/volume_raycaster.rs index 164cf53..90e1b5a 100644 --- a/src/widget/volume_raycaster.rs +++ b/src/widget/volume_raycaster.rs @@ -23,6 +23,10 @@ use crate::render::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, @@ -89,9 +93,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. From 72aa5f452e63fdc876ebf3b05b98d599b61aa016 Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Tue, 7 Jul 2026 18:27:07 +0900 Subject: [PATCH 07/15] refactor(volume): drop the unused cam_pos uniform MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shader builds each ray by un-projecting near/far NDC through inv_mvp, so cam_pos was written to the uniform buffer every frame and never read. Remove it from the WGSL and Rust uniform structs, VolumeFrame, and the widget that filled it — shrinking the uniform buffer and dropping a dead per-frame camera-position computation. --- src/render/shaders/volume_raycaster.wgsl | 1 - src/render/volume_raycaster.rs | 3 --- src/widget/volume_raycaster.rs | 2 -- 3 files changed, 6 deletions(-) diff --git a/src/render/shaders/volume_raycaster.wgsl b/src/render/shaders/volume_raycaster.wgsl index a888fa8..87b5e3a 100644 --- a/src/render/shaders/volume_raycaster.wgsl +++ b/src/render/shaders/volume_raycaster.wgsl @@ -12,7 +12,6 @@ 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. diff --git a/src/render/volume_raycaster.rs b/src/render/volume_raycaster.rs index 926a2b7..6d5792e 100644 --- a/src/render/volume_raycaster.rs +++ b/src/render/volume_raycaster.rs @@ -24,7 +24,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 +36,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], } @@ -272,7 +270,6 @@ impl VolumeGpu { 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], diff --git a/src/widget/volume_raycaster.rs b/src/widget/volume_raycaster.rs index 90e1b5a..876b073 100644 --- a/src/widget/volume_raycaster.rs +++ b/src/widget/volume_raycaster.rs @@ -192,11 +192,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); From ecc413b359eea2c17a6179a7cd5f4af5ed275f63 Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Tue, 7 Jul 2026 18:28:15 +0900 Subject: [PATCH 08/15] docs(volume): require one paint per VolumeId per frame MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The per-id uniform buffer is shared between prepare and paint, so two callbacks with the same id in one frame both read the last-prepared camera. A full fix needs per-callback GPU buffers (disproportionate — the widget already binds one id per instance and never triggers this). Document the invariant on paint_volume_raycaster and VolumeRaycaster::new so callers assigning ids by hand keep them distinct. --- src/render/volume_raycaster.rs | 7 +++++++ src/widget/volume_raycaster.rs | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/src/render/volume_raycaster.rs b/src/render/volume_raycaster.rs index 6d5792e..3332e0e 100644 --- a/src/render/volume_raycaster.rs +++ b/src/render/volume_raycaster.rs @@ -404,6 +404,13 @@ 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`. +/// +/// **Invariant: paint each [`VolumeId`] at most once per frame.** The per-id +/// uniform buffer is shared between `prepare` and `paint`, so if two callbacks +/// with the same id run in one frame, `prepare` writes that buffer twice and +/// both `paint`s read the value from whichever prepared last — both views render +/// with the last one's camera. Give every on-screen view its own id (the +/// [`crate::VolumeRaycaster`] widget already binds one id per instance). pub fn paint_volume_raycaster(ui: &mut egui::Ui, rect: egui::Rect, frame: VolumeFrame) { ui.painter().add(egui_wgpu::Callback::new_paint_callback( rect, diff --git a/src/widget/volume_raycaster.rs b/src/widget/volume_raycaster.rs index 876b073..2f248d4 100644 --- a/src/widget/volume_raycaster.rs +++ b/src/widget/volume_raycaster.rs @@ -49,6 +49,10 @@ 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. + /// + /// Each on-screen view must use a distinct `id`: the id keys shared GPU state + /// including a uniform buffer that is written once per frame, so two views + /// sharing an id would both render with the last one's camera. pub fn new(render_state: &RenderState, id: VolumeId) -> Self { install_volume_raycaster(render_state); let camera = Camera::new( From fe45cc8f1e02d292692604d4f96b9f85dd29dac7 Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Tue, 7 Jul 2026 18:45:25 +0900 Subject: [PATCH 09/15] fix(volume): per-callback uniforms so same-id repaint keeps its own camera MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F13 root-cause fix (was documented-only). VolumeGpu held one uniform buffer + bind group per VolumeId, written in prepare and read in paint. egui_wgpu runs prepare for ALL callbacks, then paint for ALL, so two callbacks sharing a VolumeId in one frame both wrote that single buffer and both painted whichever prepared last — same volume in two panels would render both from one camera. Move the dynamic state out of the shared per-id slot: VolumeGpu now holds only the 3D texture + world box; each VolumeCallback builds its own uniform buffer + bind group in prepare (VolumeGpu::frame_bind_group) and stashes it in a Mutex, which paint reads. The Mutex only satisfies CallbackTrait: Send + Sync — prepare/paint run in sequence on the render thread. The bind group holds strong refs to the fresh uniform buffer and texture view, so both live for the frame; the guard is held through the draw. Illegal state (two views, one camera) is now unrepresentable by construction, not avoided by a "paint each id once per frame" invariant. Drops the now-moot invariant docs on paint_volume_raycaster and the widget's new(). GPU render tests + 1619 lib tests pass; clippy clean. --- src/render/volume_raycaster.rs | 129 +++++++++++++++++++-------------- src/widget/volume_raycaster.rs | 13 ++-- 2 files changed, 83 insertions(+), 59 deletions(-) diff --git a/src/render/volume_raycaster.rs b/src/render/volume_raycaster.rs index 3332e0e..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}; @@ -172,40 +173,34 @@ 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. The straight alpha is - /// premultiplied before upload so the linear sampler interpolates - /// premultiplied colour (no dark fringe at colour/transparent boundaries). + /// 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), ) { @@ -242,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, @@ -263,18 +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, - 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)); + })) } } @@ -335,23 +351,19 @@ pub fn set_volume_raycaster( .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), ); } -/// Drop view `id`'s GPU resources (texture, bind group, uniform buffer), -/// freeing their 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. +/// 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 @@ -362,16 +374,23 @@ pub fn remove_volume_raycaster(render_state: &RenderState, id: VolumeId) { } } -/// egui paint callback: write this frame's uniforms in `prepare`, ray-march in -/// `paint`. +/// 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, @@ -380,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() } @@ -391,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, &[]); @@ -405,16 +427,17 @@ 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`. /// -/// **Invariant: paint each [`VolumeId`] at most once per frame.** The per-id -/// uniform buffer is shared between `prepare` and `paint`, so if two callbacks -/// with the same id run in one frame, `prepare` writes that buffer twice and -/// both `paint`s read the value from whichever prepared last — both views render -/// with the last one's camera. Give every on-screen view its own id (the -/// [`crate::VolumeRaycaster`] widget already binds one id per instance). +/// 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), + }, )); } diff --git a/src/widget/volume_raycaster.rs b/src/widget/volume_raycaster.rs index 2f248d4..fb3b999 100644 --- a/src/widget/volume_raycaster.rs +++ b/src/widget/volume_raycaster.rs @@ -50,9 +50,10 @@ impl VolumeRaycaster { /// into `render_state` (idempotent). The camera looks down `-z`; the first /// [`set_volume`](Self::set_volume) frames it to the volume. /// - /// Each on-screen view must use a distinct `id`: the id keys shared GPU state - /// including a uniform buffer that is written once per frame, so two views - /// sharing an id would both render with the last one's camera. + /// 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( @@ -119,9 +120,9 @@ impl VolumeRaycaster { self.camera.reset_camera(self.bounds); } - /// Free this view's uploaded GPU volume (texture, bind group, uniforms). 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 + /// 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); From 7972b02acd913f454a5638616374e0c4731a2515 Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Tue, 7 Jul 2026 18:57:59 +0900 Subject: [PATCH 10/15] release: 0.5.2 Bump rsplot, rsdm, adl2rsdm to 0.5.2 in lockstep and cut the CHANGELOG [0.5.2] section: a post-release correctness/robustness pass over VolumeRaycaster (premultiplied-alpha dark-fringe fix, step-independent opacity, step clamp, input validation, pointer-tracking pan, per-callback camera, remove API, dropped cam_pos uniform). rsplot only; rsdm/adl2rsdm lockstep no-op. --- CHANGELOG.md | 41 +++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 2 +- adl2rsdm/Cargo.toml | 2 +- rsdm/Cargo.toml | 4 ++-- 4 files changed, 45 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d771acd..3ae61a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,47 @@ 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-07 + +A correctness and robustness pass over the `VolumeRaycaster` shipped in 0.5.1, +from a post-release review. `rsplot` only; `rsdm` and `adl2rsdm` are 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. + ## [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. From 15c7656bb150aef0f1101cc160dec311ee78df52 Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Tue, 7 Jul 2026 19:08:58 +0900 Subject: [PATCH 11/15] test(rsdm): raise calc_derived poll deadline to stop macOS CI flake calc_update_list_restricts_which_child_triggers_recompute intermittently timed out on the macOS CI runner (3 of 5 runs): the calc:// pipeline (child connect -> value poll -> expr eval -> republish) occasionally took longer than the 2 s wait_for deadline under load. wait_for returns as soon as the condition holds, so a larger deadline only bounds the failure path and never slows a passing run. Centralize the file's deadline into one WAIT constant (30 s) instead of scattered 2 s literals. The negative-assertion settle sleep is unchanged. --- rsdm/tests/calc_derived.rs | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/rsdm/tests/calc_derived.rs b/rsdm/tests/calc_derived.rs index b23b8aa..926b4be 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,7 +120,7 @@ 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()) @@ -128,7 +135,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 +210,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" ); From 6ba4a4e4a4276bbc29a3b18f8cc6882e98855bf0 Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Wed, 8 Jul 2026 09:26:55 +0900 Subject: [PATCH 12/15] fix(ca): gate the connect-time value emit so a re-entered on_connect can't leak a duplicate sample MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `on_connect` posted the connect-time value unconditionally. It can run more than once per connection (a native-type-change / reconnect event re-enters it, and it races the value monitor), so the second post re-emitted a value already delivered on this connection. When a value subscriber (`subscribe_values`, used by the strip chart / event plot) was created between the two posts, the duplicate leaked to it as a spurious sample. Invariant: a value event is emitted only when the decoded value differs from `last_value`, at every value-arrival site. The monitor branch already enforced it; `on_connect` was the one unconditional emitter. Gate its post on the same `last_value` check — emit on an actual change, else refresh the CTRL metadata via `update` with no sample. Reconnect still re-emits because the Disconnected arm clears `last_value` (PyDM clear_cache parity). Reproduced ca_ioc::ca_property_event_refreshes_metadata_live at 3/100 (unfixed, under CPU load) with an instrumented trace showing a second on_connect post delivered to the live subscription; 0/350 after the fix. pva_plugin does not share the family: its initial value arrives exactly once via the first monitor Data event (marked=None), with no separate connect-time value post. --- .../data_plugins/epics_plugins/ca_plugin.rs | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) 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 From c020401d2eadb18e7fb1acb4ecba20f59ac729fa Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Wed, 8 Jul 2026 09:53:13 +0900 Subject: [PATCH 13/15] fix(calc): don't consume a child's recompute trigger before all children connect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The poll loop advanced `prev_stamps[i]` for every changed child stamp unconditionally, then gated the recompute on `all_connected && trigger` in the same tick. A child's initial value routinely lands a tick or more before the last child connects, so that change was folded into `prev_stamps` while `!all_connected` and its trigger was dropped. If the child that finally completes the connection is not itself a triggering variable (an `update` list that excludes it), the first all-connected tick saw no change and never ran the initial evaluation: the calc stayed connected but valueless until the next child write. This is child-connect-order dependent, so it flaked on CI: with `update=a`, whether the initial value published depended on whether `a` connected before or after `b`. Fix: fold stamp changes into `prev_stamps` only while `all_connected`. `prev_stamps` stays at `u64::MAX` until the first all-connected tick, which therefore always observes every child as changed and runs the initial evaluation — with no dependence on the child-connect vs poll-tick interleaving. This also makes the default-update case's initial eval hold by construction, not by the last-connecting child happening to be a trigger. Adds calc_publishes_initial_value_when_update_var_connects_before_others: connects the update variable first, lets the poll loop observe it while the other child is still disconnected, then connects the other (non-update) child. Times out on the pre-fix code (30 s), passes after. --- rsdm/src/data_plugins/calc_plugin.rs | 37 +++++++++++++++++-------- rsdm/tests/calc_derived.rs | 41 ++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 11 deletions(-) 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/tests/calc_derived.rs b/rsdm/tests/calc_derived.rs index 926b4be..6302246 100644 --- a/rsdm/tests/calc_derived.rs +++ b/rsdm/tests/calc_derived.rs @@ -127,6 +127,47 @@ fn calc_update_list_restricts_which_child_triggers_recompute() { ); } +/// 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. // --------------------------------------------------------------------------- From 5596c2f8b504a20f9238aabfa9540fa5ad66918f Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Wed, 8 Jul 2026 12:08:44 +0900 Subject: [PATCH 14/15] docs(changelog): record the ca:// and calc:// race fixes under 0.5.2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 0.5.2 section covered only the VolumeRaycaster hardening; the two rsdm data-engine race fixes (ca:// duplicate initial sample, calc:// lost initial evaluation) landed on the release branch after it. Add them under a Fixed — rsdm subsection and correct the release date to 2026-07-08. --- CHANGELOG.md | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ae61a4..c3dceec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,11 +9,12 @@ 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-07 +## [0.5.2] - 2026-07-08 A correctness and robustness pass over the `VolumeRaycaster` shipped in 0.5.1, -from a post-release review. `rsplot` only; `rsdm` and `adl2rsdm` are re-released -in lockstep (no functional change). +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` @@ -50,6 +51,24 @@ in lockstep (no functional change). - 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 From 576e0772a04e9b557dfbcfc8f5b7064e52b39de7 Mon Sep 17 00:00:00 2001 From: Sang Woo Kim Date: Wed, 8 Jul 2026 12:21:12 +0900 Subject: [PATCH 15/15] test(volume): serialize the two GPU render tests to avoid a Windows WARP crash MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two tests each create and tear down their own wgpu device; `cargo test` runs them on parallel threads, so on the Windows CI runner's DX12 software adapter (WARP) the concurrent device create/destroy faulted with STATUS_ACCESS_VIOLATION (0xc0000005) — a native crash in the adapter, not in rsplot, and intermittent (the same code passed the full matrix on the prior run). Serialize them through a process-wide lock so exactly one device is alive at a time; poison is recovered so a failed assertion in one test cannot wedge the other. This removes the concurrency that triggers the crash; the underlying WARP-adapter fault under concurrent device lifecycle is environmental and outside rsplot. --- tests/volume_raycaster_render.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) 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,