feat(draworder): cross-type draw order + context menu

DRAWORDER now affects rendering immediately (bump geometry epoch so the
sort cache rebuilds) and front/back anchor to the block's full effective
sort range instead of only existing table entries, so bring-to-front
actually lands on top. The render fallback sorts table-absent entities by
their own handle.

Draw order now applies across entity types, not just within a type. A
per-entity draw-order rank (SortEntitiesTable override or own handle,
ranked per block) is encoded as a small signed clip-z bias in the wire,
hatch, image, and 3DFACE pipelines. The shared LessEqual depth buffer then
orders fills, lines, rasters and 2D solids against each other regardless of
pass order — without touching model coordinates. 3D meshes keep real
geometric depth; wipeouts stay always-on-top.

Adds a Draw Order submenu to the viewport context menu (Bring to Front,
Send to Back, Bring Above/Send Under Object). The above/under items run an
interactive reference-object pick, then reorder the captured selection.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
Hakan SevenandClaude Opus 4.8 committed 2026-05-30 21:29:01 +03:00
1 parent 14a981dc87
commit 09e7e90aae
19 files changed
+469 -36

No files matched your search

+4
View File
@@ -78,6 +78,10 @@ pub struct HatchModel {
/// preventing viewport-projected content from bleeding past the
/// viewport frame. Mirrors `WireModel.vp_scissor`.
pub vp_scissor: Option<[f32; 4]>,
/// Normalized draw-order depth in (0,1); higher draws on top. Fed to the
/// hatch pipeline as a small clip-z bias so this fill orders correctly
/// against other entity types. 0.0 for transient/preview hatches.
pub draw_depth: f32,
}
impl HatchModel {
+5
View File
@@ -27,6 +27,10 @@ pub struct ImageModel {
/// viewport clipping. Mirrors `WireModel.vp_scissor` /
/// `HatchModel.vp_scissor`.
pub vp_scissor: Option<[f32; 4]>,
/// Normalized draw-order depth in (0,1); higher draws on top. Fed to the
/// image pipeline as a small clip-z bias so the raster orders correctly
/// against other entity types.
pub draw_depth: f32,
}
impl ImageModel {
@@ -61,6 +65,7 @@ impl ImageModel {
opacity,
corners,
vp_scissor: None,
draw_depth: 0.0,
})
}
}
+105 -2
View File
@@ -570,6 +570,14 @@ pub struct Scene {
/// Maps block_handle → (entity_handle.value() → sort_handle.value()).
/// Replaces the O(objects) linear scan inside `wires_for_block()` with an O(1) lookup.
sort_cache: RefCell<Option<(u64, HashMap<Handle, HashMap<u64, u64>>)>>,
/// Per-entity normalized draw-order depth in (0,1), keyed by
/// entity_handle.value(). Higher = drawn on top. Built once per
/// geometry epoch by ranking every entity within its owning block by
/// effective sort key (SortEntitiesTable override or own handle), then
/// fed to the 2D pipelines as a small clip-z bias so entities of
/// *different* types order correctly against each other. 3D meshes are
/// excluded (they keep real geometric depth).
draw_depth_cache: RefCell<Option<(u64, Arc<HashMap<u64, f32>>)>>,
/// Cached hatch fill models, keyed by geometry_epoch. View culling
/// is handled at draw time via `hatch_skip_flags` in the pipeline,
/// not at build time — that lets the GPU buffer stay stable across
@@ -683,6 +691,7 @@ impl Scene {
wire_cache: RefCell::new(None),
model_tile_wire_cache: RefCell::new(HashMap::new()),
sort_cache: RefCell::new(None),
draw_depth_cache: RefCell::new(None),
hatch_cache: RefCell::new(None),
wipeout_cache: RefCell::new(None),
image_cache: RefCell::new(None),
@@ -1328,6 +1337,79 @@ impl Scene {
(*self.entity_wires_arc()).clone()
}
/// Per-entity normalized draw-order depth, keyed by entity handle value.
/// Built (and cached per geometry epoch) by ranking every entity within
/// its owning block by effective sort key (SortEntitiesTable override or
/// own handle). The result feeds the 2D pipelines as a clip-z bias so
/// entities of different types order correctly against each other.
pub(super) fn draw_depth_map(&self) -> Arc<HashMap<u64, f32>> {
{
let cache = self.draw_depth_cache.borrow();
if let Some((epoch, ref arc)) = *cache {
if epoch == self.geometry_epoch {
return Arc::clone(arc);
}
}
}
use acadrust::objects::ObjectType;
// Per-block SortEntitiesTable overrides: block -> (entity_val -> sort_val).
let mut overrides: HashMap<Handle, HashMap<u64, u64>> = HashMap::new();
for obj in self.document.objects.values() {
if let ObjectType::SortEntitiesTable(t) = obj {
if !t.is_empty() {
overrides.insert(
t.block_owner_handle,
t.entries()
.map(|e| (e.entity_handle.value(), e.sort_handle.value()))
.collect(),
);
}
}
}
let ms = self.model_space_block_handle();
// Group entities by owning block, carrying each entity's effective key.
let mut by_block: HashMap<Handle, Vec<(u64, u64)>> = HashMap::new();
for e in self.document.entities() {
let c = e.common();
// 3D meshes keep real geometric depth — exclude them from
// draw-order biasing so 3D occlusion is never flattened.
if matches!(
e,
EntityType::Solid3D(_) | EntityType::Region(_) | EntityType::Body(_)
) {
continue;
}
let block = if c.owner_handle.is_null() {
ms
} else {
c.owner_handle
};
let hv = c.handle.value();
let eff = overrides
.get(&block)
.and_then(|m| m.get(&hv))
.copied()
.unwrap_or(hv);
by_block.entry(block).or_default().push((hv, eff));
}
let mut depth_map: HashMap<u64, f32> = HashMap::new();
for (_block, mut v) in by_block {
v.sort_by_key(|(_, eff)| *eff);
let denom = (v.len() as f32) + 1.0;
for (rank, (hv, _)) in v.into_iter().enumerate() {
// Signed (-1,1): back ranks → negative, front → positive,
// mid → ~0. The shader applies `z -= draw_depth * BIAS`, so a
// default/unranked 0.0 means "no bias" (neutral) — which keeps
// 3D mesh faces and transient wires at their real depth.
let norm = (rank as f32 + 1.0) / denom; // (0,1)
depth_map.insert(hv, (norm - 0.5) * 2.0);
}
}
let arc = Arc::new(depth_map);
*self.draw_depth_cache.borrow_mut() = Some((self.geometry_epoch, Arc::clone(&arc)));
arc
}
pub(super) fn hatch_models_arc(&self) -> Arc<Vec<HatchModel>> {
{
let cache = self.hatch_cache.borrow();
@@ -1365,7 +1447,17 @@ impl Scene {
}
}
}
let arc = Arc::new(self.images.values().cloned().collect());
let depth_map = self.draw_depth_map();
let arc = Arc::new(
self.images
.iter()
.map(|(handle, model)| {
let mut m = model.clone();
m.draw_depth = depth_map.get(&handle.value()).copied().unwrap_or(0.0);
m
})
.collect(),
);
*self.image_cache.borrow_mut() = Some((self.geometry_epoch, Arc::clone(&arc)));
arc
}
@@ -1688,7 +1780,11 @@ impl Scene {
let key = Self::handle_from_wire_name(&w.name)
.map(|h| h.value())
.unwrap_or(u64::MAX);
sort_map.get(&key).copied().unwrap_or(u64::MAX / 2)
// Entities absent from the table sort by their own
// handle — the same key space the table's sort handles
// live in — so reordered and untouched entities interleave
// correctly instead of all collapsing to one constant.
sort_map.get(&key).copied().unwrap_or(key)
});
}
}
@@ -2861,6 +2957,7 @@ impl Scene {
// paper), so projecting them through a camera built for the
// wrong block lands them outside the frustum and the per-vp
// scissor / LOD culls them out — no double-rendering.
let depth_map = self.draw_depth_map();
let mut models: Vec<HatchModel> = self
.hatches
.iter()
@@ -2909,6 +3006,7 @@ impl Scene {
if self.selected.contains(&handle) {
m.color = [0.15, 0.55, 1.00, m.color[3]];
}
m.draw_depth = depth_map.get(&handle.value()).copied().unwrap_or(0.0);
m
})
.collect();
@@ -2992,6 +3090,7 @@ impl Scene {
scale: 1.0,
world_origin: [0.0; 2],
vp_scissor: None,
draw_depth: depth_map.get(&common.handle.value()).copied().unwrap_or(0.0),
});
}
}
@@ -3055,6 +3154,7 @@ impl Scene {
scale: 1.0,
world_origin: [0.0; 2],
vp_scissor: None,
draw_depth: 0.0,
});
}
}
@@ -3453,6 +3553,7 @@ impl Scene {
scale: dxf.pattern_scale as f32,
world_origin,
vp_scissor: None,
draw_depth: 0.0,
})
}
@@ -3602,6 +3703,7 @@ impl Scene {
scale: 1.0,
world_origin: [0.0; 2],
vp_scissor: None,
draw_depth: 0.0,
}
}
@@ -5655,6 +5757,7 @@ impl Scene {
scale: 1.0,
world_origin: [0.0; 2],
vp_scissor: None,
draw_depth: 0.0,
});
}
Arc::new(models)
+24
View File
@@ -29,6 +29,10 @@ use iced::wgpu::util::DeviceExt;
pub struct Face3DVertex {
pub position: [f32; 3],
pub color: [f32; 4],
/// Normalized draw-order depth in (0,1) for 2D fills / 3DFACE quads;
/// applied as a small clip-z bias in the shader. 0.0 for true 3D mesh
/// faces (PolyfaceMesh / PolygonMesh) so their real depth is preserved.
pub draw_depth: f32,
}
impl Face3DVertex {
@@ -47,6 +51,11 @@ impl Face3DVertex {
shader_location: 1,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 28,
shader_location: 2,
format: wgpu::VertexFormat::Float32,
},
],
}
}
@@ -84,7 +93,15 @@ impl Face3DGpu {
face3d_wires: &[WireModel],
all_wires: &[WireModel],
keep_3d_mesh_fills: bool,
depth_map: &std::collections::HashMap<u64, f32>,
) -> Self {
let depth_of = |w: &WireModel| -> f32 {
w.name
.parse::<u64>()
.ok()
.and_then(|h| depth_map.get(&h).copied())
.unwrap_or(0.0)
};
let mut verts_3d: Vec<Face3DVertex> = Vec::with_capacity(face3d_wires.len() * 6);
let mut verts_2d: Vec<Face3DVertex> = Vec::new();
@@ -97,10 +114,12 @@ impl Face3DGpu {
}
let [r, g, b, a] = wire.color;
let fill_color = [r * 0.45, g * 0.45, b * 0.45, a];
let depth = depth_of(wire);
let p = &wire.key_vertices;
let v = |i: usize| Face3DVertex {
position: p[i],
color: fill_color,
draw_depth: depth,
};
verts_3d.push(v(0));
verts_3d.push(v(1));
@@ -132,18 +151,23 @@ impl Face3DGpu {
continue;
}
let fill_color = [r * 0.45, g * 0.45, b * 0.45, a];
// True 3D surface: keep real depth (no draw-order bias) so
// hidden-surface shading is preserved.
for &position in &wire.fill_tris {
verts_3d.push(Face3DVertex {
position,
color: fill_color,
draw_depth: 0.0,
});
}
} else {
let fill_color = [r, g, b, a];
let depth = depth_of(wire);
for &position in &wire.fill_tris {
verts_2d.push(Face3DVertex {
position,
color: fill_color,
draw_depth: depth,
});
}
}
+8 -3
View File
@@ -64,7 +64,10 @@ pub struct HatchInstance {
pub boundary_count: u32, // 92
pub family_offset: u32, // 96
pub family_count: u32, // 100
pub _pad0: [u32; 2], // 104 (pad to 112 = 16-byte stride)
/// Signed draw-order depth (-1,1); 0.0 = neutral. Applied as a clip-z
/// bias in the vertex shader so this fill orders against other types.
pub draw_depth: f32, // 104
pub _pad0: u32, // 108 (pad to 112 = 16-byte stride)
}
const _: () = assert!(std::mem::size_of::<HatchInstance>() == 112);
@@ -274,7 +277,8 @@ impl HatchBatchedGpu {
boundary_count,
family_offset,
family_count,
_pad0: [0; 2],
draw_depth: h.draw_depth,
_pad0: 0,
});
continue;
}
@@ -312,7 +316,8 @@ impl HatchBatchedGpu {
boundary_count,
family_offset,
family_count,
_pad0: [0; 2],
draw_depth: h.draw_depth,
_pad0: 0,
});
}
+6 -2
View File
@@ -45,7 +45,10 @@ impl ImageVertex {
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct ImageParams {
opacity: f32,
_pad: [f32; 3],
/// Signed draw-order depth (-1,1); applied as a clip-z bias in the shader
/// so the raster orders against other entity types. 0.0 = neutral.
draw_depth: f32,
_pad: [f32; 2],
} // 16 bytes
// ── Per-image GPU handle ──────────────────────────────────────────────────
@@ -118,7 +121,8 @@ impl ImageGpu {
// ── Opacity uniform ───────────────────────────────────────────────
let params = ImageParams {
opacity: model.opacity.clamp(0.0, 1.0),
_pad: [0.0; 3],
draw_depth: model.draw_depth,
_pad: [0.0; 2],
};
let _params_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("image.params"),
+24 -6
View File
@@ -646,10 +646,11 @@ impl Pipeline {
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
// binding 2: ImageParams uniform
// binding 2: ImageParams uniform (read in vertex for the
// draw-order z bias and in fragment for opacity).
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
@@ -886,15 +887,30 @@ impl Pipeline {
}
}
pub fn upload_wires(&mut self, device: &wgpu::Device, wires: &[WireModel]) {
self.gpu_wires = wires.iter().map(|w| WireGpu::new(device, w)).collect();
pub fn upload_wires(
&mut self,
device: &wgpu::Device,
wires: &[WireModel],
depth_map: &std::collections::HashMap<u64, f32>,
) {
let depth_of = |w: &WireModel| -> f32 {
w.name
.parse::<u64>()
.ok()
.and_then(|h| depth_map.get(&h).copied())
.unwrap_or(0.0)
};
self.gpu_wires = wires
.iter()
.map(|w| WireGpu::new(device, w, depth_of(w)))
.collect();
// Full-brightness copies of selected wires, drawn on top of everything
// in the selection overlay pass so they're always visible.
self.gpu_selected_wires = wires
.iter()
.filter(|w| w.selected)
.map(|w| WireGpu::new(device, w))
.map(|w| WireGpu::new(device, w, depth_of(w)))
.collect();
}
@@ -971,10 +987,11 @@ impl Pipeline {
face3d_wires: &[WireModel],
all_wires: &[WireModel],
wireframe_only: bool,
depth_map: &std::collections::HashMap<u64, f32>,
) {
// Edge buffer is always built from `face3d_wires`, so 3DFACE
// outlines stay on the screen regardless of mode.
self.gpu_face3d_edges = WireGpu::from_batch(device, face3d_wires);
self.gpu_face3d_edges = WireGpu::from_batch(device, face3d_wires, depth_map);
// Fill buffer split: 3D quads + PolyfaceMesh / PolygonMesh face
// tris go to `vertex_buffer_3d` (gated by `keep_3d_mesh_fills`);
// 2D fills (text-LOD greek, MultiLeader background) go to
@@ -996,6 +1013,7 @@ impl Pipeline {
face3d_wires,
all_wires,
keep_3d_mesh_fills,
depth_map,
));
}
}
+32 -7
View File
@@ -71,6 +71,9 @@ pub struct WireInstance {
pub pattern_length: f32,
pub pat0: [f32; 4],
pub pat1: [f32; 4],
/// Normalized draw-order depth in (0,1); applied as a small clip-z bias
/// in the shader so this wire orders against other entity types.
pub draw_depth: f32,
}
impl WireInstance {
@@ -124,6 +127,11 @@ impl WireInstance {
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
}, // pat1
wgpu::VertexAttribute {
offset: 76,
shader_location: 9,
format: wgpu::VertexFormat::Float32,
}, // draw_depth
],
}
}
@@ -158,7 +166,7 @@ fn pack_color(color: [f32; 4]) -> [u8; 4] {
]
}
fn emit_wire_instances(wire: &WireModel, color: [f32; 4]) -> Vec<WireInstance> {
fn emit_wire_instances(wire: &WireModel, color: [f32; 4], draw_depth: f32) -> Vec<WireInstance> {
let color_u8 = pack_color(color);
let pat0 = [
wire.pattern[0],
@@ -222,14 +230,27 @@ fn emit_wire_instances(wire: &WireModel, color: [f32; 4]) -> Vec<WireInstance> {
pattern_length: wire.pattern_length,
pat0,
pat1,
draw_depth,
});
}
instances
}
/// Looks up a wire's draw-order depth from the per-entity map using the
/// handle encoded in its `name`. Falls back to 0.0 (transient / preview
/// wires that carry no document handle).
fn wire_draw_depth(wire: &WireModel, depth_map: &std::collections::HashMap<u64, f32>) -> f32 {
wire
.name
.parse::<u64>()
.ok()
.and_then(|h| depth_map.get(&h).copied())
.unwrap_or(0.0)
}
impl WireGpu {
pub fn new(device: &wgpu::Device, wire: &WireModel) -> Self {
let mut g = Self::build(device, wire, wire.color);
pub fn new(device: &wgpu::Device, wire: &WireModel, draw_depth: f32) -> Self {
let mut g = Self::build(device, wire, wire.color, draw_depth);
g.vp_scissor = wire.vp_scissor;
g.is_3d_mesh_edge = !wire.fill_tris.is_empty();
g
@@ -238,7 +259,11 @@ impl WireGpu {
/// Merge multiple WireModels into GPU instance buffers, chunked to fit the
/// 256 MB GPU limit. Each wire keeps its own color and pattern — they live
/// per-instance.
pub fn from_batch(device: &wgpu::Device, wires: &[WireModel]) -> Vec<Self> {
pub fn from_batch(
device: &wgpu::Device,
wires: &[WireModel],
depth_map: &std::collections::HashMap<u64, f32>,
) -> Vec<Self> {
let total_segs: usize = wires.iter().map(|w| w.points.len().saturating_sub(1)).sum();
if total_segs == 0 {
return vec![];
@@ -251,7 +276,7 @@ impl WireGpu {
// across cores.
let instances: Vec<WireInstance> = wires
.par_iter()
.map(|wire| emit_wire_instances(wire, wire.color))
.map(|wire| emit_wire_instances(wire, wire.color, wire_draw_depth(wire, depth_map)))
.reduce(Vec::new, |mut acc, mut chunk| {
if acc.is_empty() {
chunk
@@ -286,8 +311,8 @@ impl WireGpu {
.collect()
}
fn build(device: &wgpu::Device, wire: &WireModel, color: [f32; 4]) -> Self {
let instances = emit_wire_instances(wire, color);
fn build(device: &wgpu::Device, wire: &WireModel, color: [f32; 4], draw_depth: f32) -> Self {
let instances = emit_wire_instances(wire, color, draw_depth);
let label = format!("wire.ibuf.{}", wire.name);
let instance_buffer = instance_buffer_mapped(device, &label, &instances);
+8 -1
View File
@@ -35,6 +35,11 @@ pub struct ViewportData {
/// 3DFACE entity wires — separated so they are uploaded to the dedicated
/// face3d pipeline (fill + batched edges) instead of N individual WireGpu.
pub(super) face3d_wires: Arc<Vec<WireModel>>,
/// Per-entity normalized draw-order depth (handle.value() → (0,1)), used
/// by the wire / face3d pipelines as a clip-z bias. WireModels carry no
/// depth field (84 construction sites); the bias is looked up by handle
/// at GPU-upload time from this map instead.
pub(super) draw_depths: Arc<std::collections::HashMap<u64, f32>>,
pub(super) hatches: Arc<Vec<HatchModel>>,
/// Wipeout fills — rendered in a separate pass AFTER wires.
pub(super) wipeout_hatches: Arc<Vec<HatchModel>>,
@@ -224,12 +229,13 @@ impl shader::Primitive for Primitive {
}
// Wires re-upload on every camera change because the visible
// subset shifts under frustum culling.
inner.upload_wires(device, &vp.wires[..]);
inner.upload_wires(device, &vp.wires[..], &vp.draw_depths);
inner.upload_face3d(
device,
&vp.face3d_wires[..],
&vp.wires[..],
!face3d_fill_active,
&vp.draw_depths,
);
inner.cached_epoch = cur_key;
}
@@ -645,6 +651,7 @@ impl Scene {
Some(ViewportData {
wires: all_wires,
face3d_wires: Arc::new(face3d_wires),
draw_depths: self.draw_depth_map(),
hatches: self.hatch_models_arc(),
wipeout_hatches: self.wipeout_models_arc(),
images: self.images_arc(),
+2
View File
@@ -15,6 +15,8 @@ pub struct SelectionState {
pub poly_crossing: bool,
pub poly_last_crossing: bool,
pub context_menu: Option<Point>,
/// True while the context menu's Draw Order sub-items are expanded.
pub draworder_submenu: bool,
pub last_move_pos: Option<Point>,
pub left_down: bool,
pub left_press_pos: Option<Point>,